ktx/packages/cli/test/context/wiki/local-knowledge.test.ts

324 lines
11 KiB
TypeScript
Raw Permalink Normal View History

2026-05-10 23:12:26 +02:00
import { access, mkdtemp, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
test: split cli tests from source tree (#216) * feat(cli): define full warehouse dialect contract * test(cli): keep dialect edge tests focused * fix(cli): stabilize dialect contract foundation * refactor(connectors): own read-only query preparation * refactor(connectors): resolve dialects through registry * refactor(connectors): keep concrete dialect classes internal * chore(workspace): enforce dialect import boundary * refactor(cli): resolve relationship dialect at scan boundary * refactor(cli): use dialect display parsing for entity details * refactor(cli): use dialect display parsing for warehouse catalog * refactor(cli): use dialect SQL in relationship workflows * test(cli): verify solid dialect scan workflow closure * test: split cli tests from source tree * refactor(cli): standardize BigQuery scope listing * feat(sqlite): implement connector scope listing * test(connectors): cover required table listing * feat(cli): add warehouse driver registry * refactor(setup): route scope discovery through driver registry * refactor(cli): route local query execution through driver registry * refactor(historic-sql): route dialect support through driver registry * refactor(cli): test warehouse connections through driver registry * fix(cli): close driver registry type export gaps * Improve setup daemon diagnostics * refactor(setup): centralize rail-prefixed diagnostics + query-history fallback Extract errorMessage, writePrefixedLines, and flushPrefixedBufferedCommandOutput into clack.ts so the setup wizard, managed daemons, and embedding/agent steps share one rail-formatted writer. setup-databases.ts also adds a "disable query history and retry" option when the schema-context build fails and query history is the likely culprit, surfaced via a new failed-query-history-unavailable status. * fix(cli): carry catalog through the picker so BigQuery/Snowflake/SQL Server scope filters match The setup picker's KtxTableListEntry was a 2-level { schema, name }, so qualifiedTableId always wrote db.name into enabled_tables. When BigQuery, Snowflake, or SQL Server later ran fast ingest, their introspect step filtered the scope set with scopedTableNames(scope, { catalog: projectId|database, db }) — catalog was non-null on the introspect side but null in the scope refs, so every entry was rejected, the live-database adapter staged zero table files, and detect() failed with 'Adapter "live-database" did not recognize fetched source output'. Align the picker boundary with the canonical 3-level KtxTableRef: - Add catalog: string | null to KtxTableListEntry. - BigQuery/Snowflake/SQL Server listTables populate catalog from the resolved projectId / database; Postgres/MySQL/ClickHouse/SQLite set null. - qualifiedTableId emits catalog.schema.name when catalog is non-null (resolveEnabledTables already accepts the 3-part shape) and schemasFromEnabledTables now goes through parseDottedTableEntry so it recovers the schema correctly from both 2-part and 3-part entries. - Export parseDottedTableEntry from enabled-tables.ts (@internal) for picker reuse. Update listTables expectations in all seven connector tests and the setup / picker test fixtures. Add a picker regression test that covers the catalog-bearing round-trip (save + refine). * fix(cli): allow debug telemetry under opt-out env
2026-05-26 08:49:05 +02:00
import { initKtxProject, type KtxLocalProject } from '../../../src/context/project/project.js';
2026-05-10 23:12:26 +02:00
import {
listLocalKnowledgePages,
readLocalKnowledgePage,
searchLocalKnowledgePages,
writeLocalKnowledgePage,
test: split cli tests from source tree (#216) * feat(cli): define full warehouse dialect contract * test(cli): keep dialect edge tests focused * fix(cli): stabilize dialect contract foundation * refactor(connectors): own read-only query preparation * refactor(connectors): resolve dialects through registry * refactor(connectors): keep concrete dialect classes internal * chore(workspace): enforce dialect import boundary * refactor(cli): resolve relationship dialect at scan boundary * refactor(cli): use dialect display parsing for entity details * refactor(cli): use dialect display parsing for warehouse catalog * refactor(cli): use dialect SQL in relationship workflows * test(cli): verify solid dialect scan workflow closure * test: split cli tests from source tree * refactor(cli): standardize BigQuery scope listing * feat(sqlite): implement connector scope listing * test(connectors): cover required table listing * feat(cli): add warehouse driver registry * refactor(setup): route scope discovery through driver registry * refactor(cli): route local query execution through driver registry * refactor(historic-sql): route dialect support through driver registry * refactor(cli): test warehouse connections through driver registry * fix(cli): close driver registry type export gaps * Improve setup daemon diagnostics * refactor(setup): centralize rail-prefixed diagnostics + query-history fallback Extract errorMessage, writePrefixedLines, and flushPrefixedBufferedCommandOutput into clack.ts so the setup wizard, managed daemons, and embedding/agent steps share one rail-formatted writer. setup-databases.ts also adds a "disable query history and retry" option when the schema-context build fails and query history is the likely culprit, surfaced via a new failed-query-history-unavailable status. * fix(cli): carry catalog through the picker so BigQuery/Snowflake/SQL Server scope filters match The setup picker's KtxTableListEntry was a 2-level { schema, name }, so qualifiedTableId always wrote db.name into enabled_tables. When BigQuery, Snowflake, or SQL Server later ran fast ingest, their introspect step filtered the scope set with scopedTableNames(scope, { catalog: projectId|database, db }) — catalog was non-null on the introspect side but null in the scope refs, so every entry was rejected, the live-database adapter staged zero table files, and detect() failed with 'Adapter "live-database" did not recognize fetched source output'. Align the picker boundary with the canonical 3-level KtxTableRef: - Add catalog: string | null to KtxTableListEntry. - BigQuery/Snowflake/SQL Server listTables populate catalog from the resolved projectId / database; Postgres/MySQL/ClickHouse/SQLite set null. - qualifiedTableId emits catalog.schema.name when catalog is non-null (resolveEnabledTables already accepts the 3-part shape) and schemasFromEnabledTables now goes through parseDottedTableEntry so it recovers the schema correctly from both 2-part and 3-part entries. - Export parseDottedTableEntry from enabled-tables.ts (@internal) for picker reuse. Update listTables expectations in all seven connector tests and the setup / picker test fixtures. Add a picker regression test that covers the catalog-bearing round-trip (save + refine). * fix(cli): allow debug telemetry under opt-out env
2026-05-26 08:49:05 +02:00
} from '../../../src/context/wiki/local-knowledge.js';
2026-05-10 23:12:26 +02:00
class FakeEmbeddingPort {
readonly maxBatchSize = 16;
async computeEmbedding(text: string): Promise<number[]> {
return text.toLowerCase().includes('semantic revenue') ? [1, 0] : [0, 1];
}
async computeEmbeddingsBulk(texts: string[]): Promise<number[][]> {
return Promise.all(texts.map((text) => this.computeEmbedding(text)));
}
}
class ArrSynonymEmbeddingPort {
readonly maxBatchSize = 16;
async computeEmbedding(text: string): Promise<number[]> {
const lower = text.toLowerCase();
if (lower.trim() === 'annual recurring revenue' || lower.includes('arr') || lower.includes('contract-first')) {
return [1, 0];
}
if (lower.includes('net revenue') || lower.includes('gross') || lower.includes('refund')) {
return [0, 1];
}
return [0.5, 0.5];
}
async computeEmbeddingsBulk(texts: string[]): Promise<number[][]> {
return Promise.all(texts.map((text) => this.computeEmbedding(text)));
}
}
2026-05-10 23:12:26 +02:00
describe('local knowledge helpers', () => {
let tempDir: string;
2026-05-10 23:51:24 +02:00
let project: KtxLocalProject;
2026-05-10 23:12:26 +02:00
beforeEach(async () => {
2026-05-10 23:51:24 +02:00
tempDir = await mkdtemp(join(tmpdir(), 'ktx-local-knowledge-'));
project = await initKtxProject({ projectDir: join(tempDir, 'project') });
2026-05-10 23:12:26 +02:00
});
afterEach(async () => {
await rm(tempDir, { recursive: true, force: true });
});
it('writes, reads, lists, and searches global wiki pages', async () => {
2026-05-10 23:12:26 +02:00
const write = await writeLocalKnowledgePage(project, {
key: 'metrics-revenue',
2026-05-10 23:12:26 +02:00
scope: 'GLOBAL',
summary: 'Revenue metric definition',
content: 'Revenue is recognized when an order is paid.',
tags: ['finance'],
refs: ['semantic-layer/warehouse/orders.yaml'],
slRefs: ['orders'],
});
expect(write.path).toBe('wiki/global/metrics-revenue.md');
2026-05-10 23:12:26 +02:00
expect(write.operation).toBe('write');
await expect(readLocalKnowledgePage(project, { key: 'metrics-revenue', userId: 'local' })).resolves.toMatchObject({
key: 'metrics-revenue',
2026-05-10 23:12:26 +02:00
scope: 'GLOBAL',
summary: 'Revenue metric definition',
content: 'Revenue is recognized when an order is paid.',
tags: ['finance'],
refs: ['semantic-layer/warehouse/orders.yaml'],
slRefs: ['orders'],
});
await expect(listLocalKnowledgePages(project, { userId: 'local' })).resolves.toEqual([
{
key: 'metrics-revenue',
path: 'wiki/global/metrics-revenue.md',
2026-05-10 23:12:26 +02:00
scope: 'GLOBAL',
summary: 'Revenue metric definition',
},
]);
const search = await searchLocalKnowledgePages(project, { query: 'paid order', userId: 'local' });
expect(search).toEqual([
expect.objectContaining({
key: 'metrics-revenue',
path: 'wiki/global/metrics-revenue.md',
2026-05-10 23:12:26 +02:00
scope: 'GLOBAL',
score: expect.any(Number),
matchReasons: expect.arrayContaining(['lexical']),
lanes: expect.arrayContaining([expect.objectContaining({ lane: 'lexical', status: 'available' })]),
}),
]);
expect(search[0]?.score).toBeGreaterThan(0);
2026-05-10 23:51:24 +02:00
await expect(access(join(project.projectDir, '.ktx', 'db.sqlite'))).resolves.toBeUndefined();
2026-05-10 23:12:26 +02:00
});
it('adds the token lane alongside lexical wiki matches', async () => {
await writeLocalKnowledgePage(project, {
key: 'metrics-revenue',
2026-05-10 23:12:26 +02:00
scope: 'GLOBAL',
summary: 'Revenue metric definition',
content: 'Revenue is recognized when an order is paid.',
tags: ['finance'],
});
const search = await searchLocalKnowledgePages(project, { query: 'paid---', userId: 'local', limit: 5 });
expect(search[0]).toMatchObject({
key: 'metrics-revenue',
2026-05-10 23:12:26 +02:00
matchReasons: expect.arrayContaining(['token']),
lanes: expect.arrayContaining([expect.objectContaining({ lane: 'token', status: 'available' })]),
});
});
it('uses stored page embeddings when a wiki embedding backend is configured', async () => {
await writeLocalKnowledgePage(project, {
key: 'metrics-revenue',
2026-05-10 23:12:26 +02:00
scope: 'GLOBAL',
summary: 'Semantic revenue definition',
content: 'Revenue search text.',
tags: ['finance'],
});
await writeLocalKnowledgePage(project, {
key: 'support-escalations',
2026-05-10 23:12:26 +02:00
scope: 'GLOBAL',
summary: 'Support escalation process',
content: 'Support search text.',
tags: ['operations'],
});
const search = await searchLocalKnowledgePages(project, {
query: 'semantic revenue',
userId: 'local',
limit: 5,
embeddingService: new FakeEmbeddingPort(),
});
expect(search[0]).toMatchObject({
key: 'metrics-revenue',
2026-05-10 23:12:26 +02:00
matchReasons: expect.arrayContaining(['semantic']),
lanes: expect.arrayContaining([expect.objectContaining({ lane: 'semantic', status: 'available' })]),
});
});
it('ranks ARR synonym queries by semantic page embeddings over stronger lexical revenue matches', async () => {
await writeLocalKnowledgePage(project, {
key: 'arr-definition',
scope: 'GLOBAL',
summary: 'ARR is calculated contract-first for active customer contracts.',
content: 'Contract-first active contract value takes precedence over subscription values.',
tags: ['arr', 'contracts', 'finance'],
});
await writeLocalKnowledgePage(project, {
key: 'net-revenue-definition',
scope: 'GLOBAL',
summary: 'Net revenue definition',
content: 'Annual revenue is gross invoice revenue minus credits and refunds.',
tags: ['revenue', 'finance'],
});
const search = await searchLocalKnowledgePages(project, {
query: 'annual recurring revenue',
userId: 'local',
limit: 2,
embeddingService: new ArrSynonymEmbeddingPort(),
});
expect(search.map((result) => result.key)).toEqual(['arr-definition', 'net-revenue-definition']);
expect(search[0]).toMatchObject({
key: 'arr-definition',
matchReasons: expect.arrayContaining(['semantic']),
2026-05-10 23:12:26 +02:00
lanes: expect.arrayContaining([expect.objectContaining({ lane: 'semantic', status: 'available' })]),
});
});
it('reports semantic lane as skipped when wiki embeddings are not configured', async () => {
await writeLocalKnowledgePage(project, {
key: 'metrics-revenue',
2026-05-10 23:12:26 +02:00
scope: 'GLOBAL',
summary: 'Revenue metric definition',
content: 'Revenue is recognized when an order is paid.',
tags: ['finance'],
});
const search = await searchLocalKnowledgePages(project, { query: 'revenue', userId: 'local', limit: 5 });
expect(search[0]?.lanes).toEqual(
expect.arrayContaining([
expect.objectContaining({ lane: 'semantic', status: 'skipped', reason: 'embedding_unconfigured' }),
]),
);
});
it('prefers user knowledge over global pages with the same key', async () => {
await writeLocalKnowledgePage(project, {
key: 'handoff',
scope: 'GLOBAL',
summary: 'Global handoff',
content: 'Global context.',
});
await writeLocalKnowledgePage(project, {
key: 'handoff',
scope: 'USER',
userId: 'agent-1',
summary: 'User handoff',
content: 'User context.',
});
await expect(readLocalKnowledgePage(project, { key: 'handoff', userId: 'agent-1' })).resolves.toMatchObject({
scope: 'USER',
summary: 'User handoff',
});
});
it('serializes historic-SQL frontmatter fields for global pages', async () => {
await writeLocalKnowledgePage(project, {
key: 'monthly-paid-orders',
2026-05-10 23:12:26 +02:00
scope: 'GLOBAL',
summary: 'Monthly paid orders',
content: '## Monthly paid order count',
tags: ['historic-sql', 'query-pattern'],
slRefs: ['analytics.orders'],
source: 'historic-sql',
intent: 'Monthly paid order count',
tables: ['analytics.orders'],
representativeSql: "SELECT count(*) FROM analytics.orders WHERE status = 'paid'",
usage: {
executions: 42,
distinct_users: 3,
first_seen: '2026-02-01',
last_seen: '2026-05-04',
p50_runtime_ms: 100,
p95_runtime_ms: 200,
error_rate: 0,
rows_produced: 42,
},
fingerprints: ['fp_paid_orders'],
});
const raw = await project.fileStore.readFile('wiki/global/monthly-paid-orders.md');
2026-05-10 23:12:26 +02:00
expect(raw.content).toContain('source: historic-sql');
expect(raw.content).toContain('intent: Monthly paid order count');
expect(raw.content).toContain(['tables:', ' - analytics.orders'].join('\n'));
expect(raw.content).toContain("representative_sql: SELECT count(*) FROM analytics.orders WHERE status = 'paid'");
expect(raw.content).toContain(['usage:', ' executions: 42', ' distinct_users: 3'].join('\n'));
expect(raw.content).toContain(['fingerprints:', ' - fp_paid_orders'].join('\n'));
});
it('falls back to Markdown scanning when the config does not select sqlite-fts5', async () => {
project.config.storage.search = 'postgres-hybrid';
await writeLocalKnowledgePage(project, {
key: 'metrics-revenue',
2026-05-10 23:12:26 +02:00
scope: 'GLOBAL',
summary: 'Revenue metric definition',
content: 'Revenue is recognized when an order is paid.',
tags: ['finance'],
});
await expect(searchLocalKnowledgePages(project, { query: 'paid order', userId: 'local' })).resolves.toEqual([
expect.objectContaining({
key: 'metrics-revenue',
2026-05-10 23:12:26 +02:00
score: 3,
matchReasons: ['token'],
}),
]);
});
it('rejects unsafe knowledge keys', async () => {
await expect(
writeLocalKnowledgePage(project, {
key: '../secret',
scope: 'GLOBAL',
summary: 'bad',
content: 'bad',
}),
).rejects.toThrow('Invalid wiki key "../secret". Wiki keys must be flat; use "secret".');
});
it('rejects slash-delimited knowledge keys with a flat-key suggestion', async () => {
await expect(
writeLocalKnowledgePage(project, {
key: 'orbit/company-overview',
scope: 'GLOBAL',
summary: 'bad',
content: 'bad',
}),
).rejects.toThrow('Invalid wiki key "orbit/company-overview". Wiki keys must be flat; use "orbit-company-overview".');
2026-05-10 23:12:26 +02:00
});
feat(context): add warehouse verification tools (#46) * feat(context): add warehouse dialect dispatch * feat(context): read warehouse scan catalog * feat(context): add entity details verification tool * feat(context): add ingest SQL verification tool * feat(context): add raw warehouse discovery tool * feat(context): expose warehouse verification tools to ingest * docs(context): add ingest identifier verification protocol * test(context): guard ingest identifier verification prompts * chore(context): verify warehouse verification tools * docs: add warehouse verification tools plan and spec * fix(context): expose target warehouses to Notion ingest * fix(context): update ingest prompts for warehouse verification tools * fix(context): scope raw schema discovery to allowed connections * fix(context): verify warehouse column display targets * docs: add notion warehouse verification gap closure plan * fix(context): include raw discovery connection names * fix(context): expose warehouse targets for LookML and MetricFlow * fix(context): pass connection config to ingest query executors * fix(cli): enable read-only SQL probes for local ingest * docs: add warehouse verification final v1 closure plan * fix(context): align warehouse sql probe prompt shape * docs: add warehouse verification prompt shape closure plan * test(context): catch connectionless sql execution prompt examples * fix(context): include connection name in sl capture sql example * docs: add warehouse verification sql example closure plan * fix(context): report structured entity detail misses * docs: add warehouse verification structured target miss closure plan * fix: report untracked squash merge conflicts * feat: require ingest verification ledger * fix: stabilize ingest wiki references
2026-05-13 13:43:23 +02:00
it('ignores nested historic-SQL legacy paths when listing local wiki pages', async () => {
await writeLocalKnowledgePage(project, {
key: 'historic-sql-paid-orders',
scope: 'GLOBAL',
summary: 'Flat historic SQL page',
content: 'Flat page body.',
tags: ['historic-sql'],
});
await project.fileStore.writeFile(
'wiki/global/historic-sql/paid-orders.md',
'---\nsummary: Nested historic SQL page\nusage_mode: auto\n---\n\nNested body\n',
'Test',
'test@example.com',
'Write nested legacy page',
);
await expect(listLocalKnowledgePages(project, { userId: 'local' })).resolves.toEqual([
{
key: 'historic-sql-paid-orders',
path: 'wiki/global/historic-sql-paid-orders.md',
scope: 'GLOBAL',
summary: 'Flat historic SQL page',
},
]);
});
2026-05-10 23:12:26 +02:00
});