mirror of
https://github.com/Kaelio/ktx.git
synced 2026-06-10 08:05:14 +02:00
* 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
272 lines
11 KiB
TypeScript
272 lines
11 KiB
TypeScript
import { describe, expect, it, vi } from 'vitest';
|
|
import { KnowledgeWikiService, type WikiFrontmatter } from '../../../src/context/wiki/knowledge-wiki.service.js';
|
|
|
|
function makeService() {
|
|
const pagesRepository: Record<string, ReturnType<typeof vi.fn>> = {
|
|
upsertPage: vi.fn().mockResolvedValue(undefined),
|
|
deleteByKey: vi.fn().mockResolvedValue(0),
|
|
deleteByScope: vi.fn().mockResolvedValue(0),
|
|
deleteStale: vi.fn().mockResolvedValue(0),
|
|
getExistingSearchTexts: vi.fn().mockResolvedValue(new Map()),
|
|
applyDiffTransactional: vi.fn().mockResolvedValue(undefined),
|
|
};
|
|
const embeddingService = {
|
|
computeEmbedding: vi.fn().mockResolvedValue([0.1, 0.2, 0.3]),
|
|
computeEmbeddingsBulk: vi.fn().mockResolvedValue([]),
|
|
maxBatchSize: 16,
|
|
};
|
|
const configService = {
|
|
forWorktree: vi.fn().mockReturnValue({
|
|
writeFile: vi.fn(),
|
|
readFile: vi.fn(),
|
|
deleteFile: vi.fn(),
|
|
listFiles: vi.fn(),
|
|
getFileHistory: vi.fn(),
|
|
}),
|
|
writeFile: vi.fn(),
|
|
readFile: vi.fn(),
|
|
deleteFile: vi.fn(),
|
|
listFiles: vi.fn(),
|
|
getFileHistory: vi.fn(),
|
|
};
|
|
const gitService = {
|
|
diffNameStatus: vi.fn().mockResolvedValue([]),
|
|
getFileAtCommit: vi.fn().mockResolvedValue(''),
|
|
};
|
|
const logger = {
|
|
log: vi.fn(),
|
|
warn: vi.fn(),
|
|
error: vi.fn(),
|
|
};
|
|
const service = new KnowledgeWikiService(
|
|
configService as any,
|
|
embeddingService as any,
|
|
pagesRepository as any,
|
|
gitService as any,
|
|
logger as any,
|
|
);
|
|
return { service, pagesRepository, embeddingService, configService, gitService, logger };
|
|
}
|
|
|
|
const fm: WikiFrontmatter = { summary: 'sum', usage_mode: 'auto' };
|
|
|
|
describe('KnowledgeWikiService file reads', () => {
|
|
it('warns and returns null when an existing page cannot be parsed', async () => {
|
|
const { service, configService, logger } = makeService();
|
|
configService.readFile.mockResolvedValue({ content: '---\nsummary: [\n---\nBody' });
|
|
|
|
await expect(service.readPage('GLOBAL', null, 'revenue')).resolves.toBeNull();
|
|
|
|
expect(configService.readFile).toHaveBeenCalledWith('wiki/global/revenue.md');
|
|
expect(logger.warn).toHaveBeenCalledWith(expect.stringContaining('[readPage] wiki/global/revenue.md: parse failed:'));
|
|
});
|
|
|
|
it('warns and returns an empty page list when directory listing fails', async () => {
|
|
const { service, configService, logger } = makeService();
|
|
configService.listFiles.mockRejectedValue(new Error('filesystem unavailable'));
|
|
|
|
await expect(service.listPageKeys('GLOBAL', null)).resolves.toEqual([]);
|
|
|
|
expect(logger.warn).toHaveBeenCalledWith('[listPageKeys] wiki/global: filesystem unavailable');
|
|
});
|
|
});
|
|
|
|
describe('KnowledgeWikiService.syncIndex result stats', () => {
|
|
it('reports scanned, updated, deleted, and embedding counts', async () => {
|
|
const { service, pagesRepository, embeddingService, configService } = makeService();
|
|
configService.listFiles.mockResolvedValue({ files: ['wiki/global/revenue.md'] });
|
|
configService.readFile.mockResolvedValue({
|
|
content: '---\nsummary: Revenue\nusage_mode: auto\ntags:\n - finance\n---\n\nPaid orders.\n',
|
|
});
|
|
pagesRepository.getExistingSearchTexts.mockResolvedValue(
|
|
new Map([
|
|
['old-page', { searchText: 'old', hasEmbedding: true }],
|
|
]),
|
|
);
|
|
embeddingService.computeEmbeddingsBulk.mockResolvedValue([[0.1, 0.2, 0.3]]);
|
|
pagesRepository.deleteStale.mockResolvedValue(1);
|
|
|
|
await expect(service.syncIndex('GLOBAL', null)).resolves.toEqual({
|
|
scanned: 1,
|
|
updated: 1,
|
|
deleted: 1,
|
|
embeddingsRecomputed: 1,
|
|
embeddingsFailed: 0,
|
|
});
|
|
});
|
|
|
|
it('indexes lexical rows when embeddings are not configured', async () => {
|
|
const { pagesRepository, configService, gitService, logger } = makeService();
|
|
const service = new KnowledgeWikiService(
|
|
configService as any,
|
|
null,
|
|
pagesRepository as any,
|
|
gitService as any,
|
|
logger as any,
|
|
);
|
|
configService.listFiles.mockResolvedValue({ files: ['wiki/global/revenue.md'] });
|
|
configService.readFile.mockResolvedValue({
|
|
content: '---\nsummary: Revenue\nusage_mode: auto\n---\n\nPaid orders.\n',
|
|
});
|
|
pagesRepository.getExistingSearchTexts.mockResolvedValue(new Map());
|
|
pagesRepository.deleteStale.mockResolvedValue(0);
|
|
|
|
const result = await service.syncIndex('GLOBAL', null);
|
|
|
|
expect(result.embeddingsRecomputed).toBe(0);
|
|
expect(result.embeddingsFailed).toBe(0);
|
|
expect(pagesRepository.upsertPage).toHaveBeenCalledWith(
|
|
expect.objectContaining({ pageKey: 'revenue', embedding: null }),
|
|
);
|
|
});
|
|
|
|
it('does not update unchanged lexical-only wiki rows on repeated sync', async () => {
|
|
const { pagesRepository, configService, gitService, logger } = makeService();
|
|
const service = new KnowledgeWikiService(
|
|
configService as any,
|
|
null,
|
|
pagesRepository as any,
|
|
gitService as any,
|
|
logger as any,
|
|
);
|
|
configService.listFiles.mockResolvedValue({ files: ['wiki/global/revenue.md'] });
|
|
configService.readFile.mockResolvedValue({
|
|
content: '---\nsummary: Revenue\nusage_mode: auto\n---\n\nPaid orders.\n',
|
|
});
|
|
pagesRepository.getExistingSearchTexts.mockResolvedValue(
|
|
new Map([
|
|
['revenue', { searchText: 'revenue\nRevenue\nPaid orders.', hasEmbedding: false }],
|
|
]),
|
|
);
|
|
pagesRepository.deleteStale.mockResolvedValue(0);
|
|
|
|
await expect(service.syncIndex('GLOBAL', null)).resolves.toEqual({
|
|
scanned: 1,
|
|
updated: 0,
|
|
deleted: 0,
|
|
embeddingsRecomputed: 0,
|
|
embeddingsFailed: 0,
|
|
});
|
|
expect(pagesRepository.upsertPage).not.toHaveBeenCalled();
|
|
expect(pagesRepository.deleteStale).toHaveBeenCalledWith('GLOBAL', null, ['revenue']);
|
|
});
|
|
});
|
|
|
|
describe('KnowledgeWikiService.forWorktree isolation', () => {
|
|
it('syncSinglePage in worktree scope does not call pagesRepository.upsertPage', async () => {
|
|
const { service, pagesRepository, embeddingService } = makeService();
|
|
const scoped = service.forWorktree('/tmp/fake-worktree');
|
|
|
|
await scoped.syncSinglePage('GLOBAL', null, 'key', fm, 'body');
|
|
|
|
expect(pagesRepository.upsertPage).not.toHaveBeenCalled();
|
|
expect(embeddingService.computeEmbedding).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it('deleteFromIndex in worktree scope does not call pagesRepository.deleteByKey', async () => {
|
|
const { service, pagesRepository } = makeService();
|
|
const scoped = service.forWorktree('/tmp/fake-worktree');
|
|
|
|
await scoped.deleteFromIndex('GLOBAL', null, 'key');
|
|
|
|
expect(pagesRepository.deleteByKey).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it('syncSinglePage in main scope still calls pagesRepository.upsertPage', async () => {
|
|
const { service, pagesRepository } = makeService();
|
|
|
|
await service.syncSinglePage('GLOBAL', null, 'key', fm, 'body');
|
|
|
|
expect(pagesRepository.upsertPage).toHaveBeenCalledTimes(1);
|
|
});
|
|
});
|
|
|
|
describe('KnowledgeWikiService.syncFromCommit', () => {
|
|
it('applies upserts for added/modified files and deletes for removed files in a single transactional batch', async () => {
|
|
const { service, pagesRepository, gitService } = makeService();
|
|
|
|
gitService.diffNameStatus.mockResolvedValue([
|
|
{ status: 'A', path: 'wiki/global/new-page.md' },
|
|
{ status: 'M', path: 'wiki/global/changed-page.md' },
|
|
{ status: 'D', path: 'wiki/global/gone-page.md' },
|
|
]);
|
|
gitService.getFileAtCommit.mockImplementation((path: string) => {
|
|
if (path.endsWith('new-page.md')) {
|
|
return Promise.resolve('---\nsummary: new\nusage_mode: auto\n---\n\nbody-new\n');
|
|
}
|
|
if (path.endsWith('changed-page.md')) {
|
|
return Promise.resolve('---\nsummary: changed\nusage_mode: auto\n---\n\nbody-changed\n');
|
|
}
|
|
return Promise.reject(new Error(`unexpected getFileAtCommit path: ${path}`));
|
|
});
|
|
|
|
await service.syncFromCommit('sha-before', 'sha-after', 'run-uuid');
|
|
|
|
expect(pagesRepository.applyDiffTransactional).toHaveBeenCalledTimes(1);
|
|
const call = pagesRepository.applyDiffTransactional.mock.calls[0][0];
|
|
expect(call.runId).toBe('run-uuid');
|
|
expect(call.upserts).toHaveLength(2);
|
|
expect(call.upserts).toEqual(
|
|
expect.arrayContaining([
|
|
expect.objectContaining({ scope: 'GLOBAL', pageKey: 'new-page', summary: 'new' }),
|
|
expect.objectContaining({ scope: 'GLOBAL', pageKey: 'changed-page', summary: 'changed' }),
|
|
]),
|
|
);
|
|
expect(call.deletes).toEqual([{ scope: 'GLOBAL', scopeId: null, pageKey: 'gone-page' }]);
|
|
});
|
|
|
|
it('indexes only flat wiki pages and skips nested paths from commit sync', async () => {
|
|
const { service, pagesRepository, gitService, logger } = makeService();
|
|
|
|
gitService.diffNameStatus.mockResolvedValue([
|
|
{ status: 'A', path: 'wiki/global/revenue-policy.md' },
|
|
{ status: 'A', path: 'wiki/global/historic-sql-order-lifecycle.md' },
|
|
{ status: 'A', path: 'wiki/global/historic-sql/order-lifecycle.md' },
|
|
{ status: 'A', path: 'wiki/global/orbit/company-overview.md' },
|
|
]);
|
|
gitService.getFileAtCommit.mockImplementation((path: string) => {
|
|
if (path.endsWith('revenue-policy.md')) {
|
|
return Promise.resolve('---\nsummary: revenue\nusage_mode: auto\n---\n\nbody-revenue\n');
|
|
}
|
|
if (path.endsWith('order-lifecycle.md')) {
|
|
return Promise.resolve('---\nsummary: order lifecycle\nusage_mode: auto\n---\n\nbody-orders\n');
|
|
}
|
|
if (path.endsWith('retired-pattern.md')) {
|
|
return Promise.resolve('---\nsummary: retired\nusage_mode: never\n---\n\nbody-retired\n');
|
|
}
|
|
return Promise.reject(new Error(`unexpected getFileAtCommit path: ${path}`));
|
|
});
|
|
|
|
await service.syncFromCommit('sha-before', 'sha-after', 'run-uuid');
|
|
|
|
expect(gitService.getFileAtCommit).not.toHaveBeenCalledWith('wiki/global/orbit/company-overview.md', 'sha-after');
|
|
expect(gitService.getFileAtCommit).not.toHaveBeenCalledWith('wiki/global/historic-sql/order-lifecycle.md', 'sha-after');
|
|
expect(logger.warn).toHaveBeenCalledWith(
|
|
'[wiki.sync] skipping unparseable path: wiki/global/orbit/company-overview.md',
|
|
);
|
|
expect(logger.warn).toHaveBeenCalledWith(
|
|
'[wiki.sync] skipping unparseable path: wiki/global/historic-sql/order-lifecycle.md',
|
|
);
|
|
const call = pagesRepository.applyDiffTransactional.mock.calls[0][0];
|
|
expect(call.upserts).toEqual(
|
|
expect.arrayContaining([
|
|
expect.objectContaining({ scope: 'GLOBAL', pageKey: 'revenue-policy', summary: 'revenue' }),
|
|
expect.objectContaining({
|
|
scope: 'GLOBAL',
|
|
pageKey: 'historic-sql-order-lifecycle',
|
|
summary: 'order lifecycle',
|
|
}),
|
|
]),
|
|
);
|
|
expect(call.upserts).toHaveLength(2);
|
|
});
|
|
|
|
it('is a no-op when the diff between shas has no knowledge changes', async () => {
|
|
const { service, pagesRepository, gitService } = makeService();
|
|
gitService.diffNameStatus.mockResolvedValue([]);
|
|
|
|
await service.syncFromCommit('sha-before', 'sha-after', 'run-uuid');
|
|
|
|
expect(pagesRepository.applyDiffTransactional).not.toHaveBeenCalled();
|
|
});
|
|
});
|