ktx/packages/cli/test/context/wiki/sqlite-knowledge-index.test.ts
Andrey Avtomonov 56985b7e09
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

152 lines
5 KiB
TypeScript

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';
import { SqliteKnowledgeIndex, type SqliteKnowledgeIndexPage } from '../../../src/context/wiki/sqlite-knowledge-index.js';
describe('SqliteKnowledgeIndex', () => {
let tempDir: string;
let dbPath: string;
beforeEach(async () => {
tempDir = await mkdtemp(join(tmpdir(), 'ktx-sqlite-knowledge-index-'));
dbPath = join(tempDir, 'db.sqlite');
});
afterEach(async () => {
await rm(tempDir, { recursive: true, force: true });
});
function page(overrides: Partial<SqliteKnowledgeIndexPage> = {}): SqliteKnowledgeIndexPage {
return {
path: 'wiki/global/revenue.md',
key: 'revenue',
scope: 'GLOBAL',
summary: 'Revenue definition',
content: 'Revenue is the sum of paid order amounts.',
tags: ['finance'],
embedding: null,
...overrides,
};
}
it('creates a SQLite FTS5 index and returns lexical lane candidates', async () => {
const index = new SqliteKnowledgeIndex({ dbPath });
index.sync([
page(),
page({
path: 'wiki/global/support.md',
key: 'support',
summary: 'Support queue',
content: 'Tickets are grouped by priority.',
tags: ['operations'],
}),
]);
await expect(access(dbPath)).resolves.toBeUndefined();
expect(index.searchLexicalCandidates({ queryText: 'paid order', limit: 10 })).toEqual([
expect.objectContaining({
id: 'wiki/global/revenue.md',
path: 'wiki/global/revenue.md',
rank: 1,
rawScore: expect.any(Number),
}),
]);
});
it('removes stale rows when the Markdown source list changes', () => {
const index = new SqliteKnowledgeIndex({ dbPath });
index.rebuild([page(), page({ path: 'wiki/global/churn.md', key: 'churn', content: 'Churn risk.' })]);
expect(index.search('churn', 10)).toHaveLength(1);
index.rebuild([page()]);
expect(index.search('churn', 10)).toEqual([]);
});
it('clear removes one wiki scope and leaves other scopes intact', async () => {
const index = new SqliteKnowledgeIndex({ dbPath });
index.sync([
page({ path: 'wiki/global/revenue.md', key: 'revenue', scope: 'GLOBAL', scopeId: null }),
page({
path: 'wiki/user/local/revenue.md',
key: 'revenue',
scope: 'USER',
scopeId: 'local',
summary: 'Local revenue',
content: 'Local revenue notes.',
}),
page({
path: 'wiki/user/alex/revenue.md',
key: 'revenue',
scope: 'USER',
scopeId: 'alex',
summary: 'Alex revenue',
content: 'Alex revenue notes.',
}),
]);
expect(index.clear('USER', 'local')).toBe(1);
expect(index.search('Local', 10)).toEqual([]);
expect(index.search('Alex', 10)).toEqual([expect.objectContaining({ path: 'wiki/user/alex/revenue.md' })]);
expect(index.search('definition', 10)).toEqual([expect.objectContaining({ path: 'wiki/global/revenue.md' })]);
});
it('exposes existing search text and embedding state for incremental refresh', () => {
const index = new SqliteKnowledgeIndex({ dbPath });
index.sync([page({ path: 'wiki/global/revenue.md', key: 'revenue', embedding: [1, 0] })]);
expect(index.getExistingPages()).toEqual(
new Map([
[
'wiki/global/revenue.md',
expect.objectContaining({
searchText: expect.stringContaining('Revenue definition'),
embedding: [1, 0],
}),
],
]),
);
});
it('does not treat empty embeddings as indexed semantic vectors', () => {
const index = new SqliteKnowledgeIndex({ dbPath });
index.sync([page({ path: 'wiki/global/revenue.md', key: 'revenue', embedding: [] })]);
expect(index.getExistingPages().get('wiki/global/revenue.md')?.embedding).toBeNull();
expect(index.searchSemanticCandidates({ queryEmbedding: [1, 0], limit: 10 })).toEqual([]);
});
it('returns semantic lane candidates from stored page embeddings', () => {
const index = new SqliteKnowledgeIndex({ dbPath });
index.sync([
page({ path: 'wiki/global/revenue.md', key: 'revenue', embedding: [1, 0] }),
page({ path: 'wiki/global/support.md', key: 'support', summary: 'Support queue', embedding: [0, 1] }),
]);
expect(index.searchSemanticCandidates({ queryEmbedding: [1, 0], limit: 10 })).toEqual([
expect.objectContaining({
id: 'wiki/global/revenue.md',
path: 'wiki/global/revenue.md',
rank: 1,
rawScore: 1,
}),
expect.objectContaining({
id: 'wiki/global/support.md',
path: 'wiki/global/support.md',
rank: 2,
rawScore: 0,
}),
]);
});
it('returns an empty result for blank or punctuation-only queries', () => {
const index = new SqliteKnowledgeIndex({ dbPath });
index.rebuild([page()]);
expect(index.search(' ', 10)).toEqual([]);
expect(index.search('---', 10)).toEqual([]);
});
});