ktx/packages/cli/src/context/scan/relationship-discovery.test.ts

679 lines
22 KiB
TypeScript
Raw Normal View History

2026-05-10 23:12:26 +02:00
import Database from 'better-sqlite3';
import { afterEach, describe, expect, it, vi } from 'vitest';
chore(workspace): gate dead-code with knip production mode (#196) * refactor(workspace): relocate @ktx/llm source into packages/cli/src/llm * refactor(workspace): rewrite @ktx/llm imports to relative paths * refactor(workspace): fold internal packages into cli * chore(workspace): gate dead-code with knip production mode Turn on production-mode knip plus an autofix run in pre-commit and the `pnpm dead-code` script, document the `/** @internal */` convention for test-only exports in AGENTS.md, annotate test-only exports across the CLI with that JSDoc, and drop dead exports/wrappers the new gate surfaced (e.g. `cli-project.ts`, `lookerRuntimeSourceToFileAdapterSource`, `createLocalScanEnrichmentProvidersFromConfig`, `PGLITE_OWNER_PROCESS_BACKEND_CAPABILITIES`, stale type re-exports). Replace the loose `ignoreIssues` allowlist in `knip.json` with explicit production entries so cross-package barrel leaks are caught. * refactor(cli): delete internal barrel index.ts files The 34 `index.ts` re-export barrels inside `packages/cli/src/` were holdovers from the pre-fold multi-workspace structure. Post-fold-in they served no production purpose: external consumers go through the single package main entry, and in-repo callers mostly imported through them only because the path was short. Internally, knip flagged most barrel re-exports as production-dead (only reached via tests). This change: - Deletes every internal barrel except `packages/cli/src/index.ts` (the published package entry). - Rewrites ~270 source/test files to import each name directly from the file that defines it. - Moves `tools/warehouse-verification/index.ts` to `create-warehouse-verification-tools.ts` (the function it defined locally) and updates its single consumer. - Renames `search/backend-conformance.ts` → `.test-utils.ts` to match the existing test-helper file convention. - Deletes 13 dead test-only chains (dbt-descriptions/*, live-database/extracted-schema, live-database/structural-sync, relationship-* feedback/review chain) plus their tests and a cascading orphan integration test. - Updates test mocks that pointed at deleted barrel paths (notion-client, connector barrels in scan/local-scan-connectors tests) to mock the source files instead. - Points the maintainer benchmark script (`scripts/relationship-benchmark-report.mjs`) at source files instead of `dist/context/scan/index.js`. - Drops the barrel `!` entries from `knip.json`; adds explicit production entries only for the benchmark code reached via dist by the maintainer script. Net: 413 files changed, ~1.2k insertions, ~9.4k deletions. `pnpm run dead-code` (Biome + knip default + knip production) and `pnpm run type-check` are clean; 2277 tests pass. * refactor(workspace): rename @ktx/cli to @kaelio/ktx and pack it directly Promote the CLI workspace package to the public name `@kaelio/ktx` and drop the separate `scripts/build-public-npm-package.mjs` wrapper. The CLI package is now publishable in place (`publishConfig.access: public`, `provenance: true`), so artifact packing uses `pnpm pack` against `packages/cli/` instead of assembling a parallel package tree. Updates all workspace filter invocations, docs, tests, and release readiness checks to reference the new package name, and folds the tarball-name helper into `scripts/public-npm-release-metadata.mjs`. * docs: align "agent clients" and "data agents" terminology Replace "client agents" with "agent clients" and "database agents" with "data agents" across AGENTS.md, README.md, the docs-site copy, and the matching setup-agents test description, matching the canonical vocabulary in docs/terminology.md. Also moves packages/cli/tsconfig.json's tsBuildInfoFile from node_modules/.cache/ to dist/.tsbuildinfo so incremental builds survive node_modules reinstalls. * refactor(release): single source of truth for package version Make packages/cli/package.json the single source of truth for the @kaelio/ktx version. publicNpmPackageVersion() now reads it directly, so artifact filenames, release-readiness checks, and the Python wheel version all derive from one field. The duplicate release-policy.json.publicNpmPackageVersion is removed. Previously the two fields could drift: tarballs were named kaelio-ktx-0.4.1.tgz while internally containing @kaelio/ktx@0.0.0-private. - update-public-release-version.mjs rewrites both Python pyproject.toml files (ktx-daemon, ktx-sl) alongside the npm package.jsons, normalizing the version for PEP 440 (e.g. 0.1.0-rc.2 -> 0.1.0rc2). - semantic-release-config.cjs adds the two pyproject.toml files to @semantic-release/git assets so the release commit back to main carries every version source in lockstep. - The six "?? '0.0.0-private'" fallback literals across the CLI are replaced with "?? getKtxCliPackageInfo().version", and createDefaultKtxMcpServer makes its version arg required. - docs/release.md describes the actual commit-back model: the dev tree always reflects the most recent release; no sentinel pin to maintain. Verified: pnpm run artifacts:build now produces kaelio-ktx-0.4.1.tgz and kaelio_ktx-0.4.1-py3-none-any.whl with @kaelio/ktx@0.4.1 inside. Full type-check, dead-code, and 2287 vitests + 173 script tests pass. * refactor(cli): inject embedding provider resolution and detect sentence-transformers runtime Make resolveProjectEmbeddingProvider and runtimeIo injectable in ingest and scan command entrypoints so tests can stub them, and teach resolvePublicIngestRuntimeRequirements to flag the local-embeddings runtime feature when ktx.yaml selects sentence-transformers. * chore(cli): mark buildLocalStatsStatus and LocalStatsStatus as @internal Both symbols are consumed only by status-project.test.ts. Annotating with /** @internal */ keeps knip's production-mode check clean without changing runtime behavior. * fix(cli): use real package metadata in print-command-tree The stubbed package name embedded a forbidden product identifier that tripped the boundary check in CI. Read the metadata from package.json instead — keeps the rendered tree unchanged and removes a duplicate source of truth. * feat(cli): show embedding coverage in `ktx status`, drop duplicate disk counts Inline `(N embedded)` next to the Wiki scope counts and Semantic-layer source counts, computed with `SUM(embedding_json IS NOT NULL)` over `knowledge_pages` and `local_sl_sources`. Rename the "Knowledge" label to "Wiki" (canonical per `docs/terminology.md`) and rename the matching `localStats.knowledgePages` field to `localStats.wikiPages`. Drop `wiki=N md` and `semantic-layer=N yaml` from the Disk row — those duplicated the per-surface rows above. Disk now reports only actual byte usage (db, cache, raw-sources). The unused `wikiGlobalMarkdownCount` / `semanticLayerYamlCount` fields, the `isMarkdownEntry` / `isYamlEntry` helpers, and the `filter` arg on `summarizeDir` are removed.
2026-05-21 15:28:58 +02:00
import type { KtxLlmRuntimePort } from '../../context/llm/runtime-port.js';
2026-05-10 23:51:24 +02:00
import { buildDefaultKtxProjectConfig } from '../project/config.js';
import { snapshotToKtxEnrichedSchema } from './local-enrichment.js';
2026-05-10 23:12:26 +02:00
import {
2026-05-10 23:51:24 +02:00
loadKtxRelationshipBenchmarkFixture,
maskKtxRelationshipBenchmarkSnapshot,
2026-05-10 23:12:26 +02:00
} from './relationship-benchmarks.js';
2026-05-10 23:51:24 +02:00
import { discoverKtxRelationships } from './relationship-discovery.js';
import { createKtxConnectorCapabilities } from './types.js';
import type { KtxQueryResult, KtxReadOnlyQueryInput, KtxScanConnector, KtxScanContext, KtxSchemaSnapshot } from './types.js';
2026-05-10 23:12:26 +02:00
class InMemorySqliteExecutor {
readonly db = new Database(':memory:');
queryCount = 0;
2026-05-10 23:51:24 +02:00
executeReadOnly(input: KtxReadOnlyQueryInput, _ctx: KtxScanContext): Promise<KtxQueryResult> {
2026-05-10 23:12:26 +02:00
this.queryCount += 1;
const rows = this.db.prepare(input.sql).all() as Record<string, unknown>[];
const headers = Object.keys(rows[0] ?? {});
return Promise.resolve({
headers,
rows: rows.map((row) => headers.map((header) => row[header])),
totalRows: rows.length,
rowCount: rows.length,
});
}
close(): void {
this.db.close();
}
}
2026-05-10 23:51:24 +02:00
function snapshot(): KtxSchemaSnapshot {
2026-05-10 23:12:26 +02:00
return {
connectionId: 'warehouse',
driver: 'sqlite',
extractedAt: '2026-05-07T00:00:00.000Z',
scope: {},
metadata: {},
tables: [
{
catalog: null,
db: null,
name: 'accounts',
kind: 'table',
comment: null,
estimatedRows: 2,
foreignKeys: [],
columns: [
{
name: 'id',
nativeType: 'INTEGER',
normalizedType: 'integer',
dimensionType: 'number',
nullable: false,
primaryKey: false,
comment: null,
},
{
name: 'name',
nativeType: 'TEXT',
normalizedType: 'text',
dimensionType: 'string',
nullable: false,
primaryKey: false,
comment: null,
},
],
},
{
catalog: null,
db: null,
name: 'orders',
kind: 'table',
comment: null,
estimatedRows: 3,
foreignKeys: [],
columns: [
{
name: 'id',
nativeType: 'INTEGER',
normalizedType: 'integer',
dimensionType: 'number',
nullable: false,
primaryKey: false,
comment: null,
},
{
name: 'account_id',
nativeType: 'INTEGER',
normalizedType: 'integer',
dimensionType: 'number',
nullable: false,
primaryKey: false,
comment: null,
},
],
},
],
};
}
2026-05-10 23:51:24 +02:00
function declaredForeignKeySnapshot(): KtxSchemaSnapshot {
2026-05-10 23:12:26 +02:00
const source = snapshot();
return {
...source,
tables: source.tables.map((table) =>
table.name === 'accounts'
? {
...table,
columns: table.columns.map((column) => (column.name === 'id' ? { ...column, primaryKey: true } : column)),
}
: table.name === 'orders'
? {
...table,
foreignKeys: [
{
fromColumn: 'account_id',
toCatalog: null,
toDb: null,
toTable: 'accounts',
toColumn: 'id',
constraintName: 'orders_account_id_fkey',
},
],
}
: table,
),
};
}
2026-05-10 23:51:24 +02:00
function naturalKeySnapshot(): KtxSchemaSnapshot {
2026-05-10 23:12:26 +02:00
return {
connectionId: 'warehouse',
driver: 'sqlite',
extractedAt: '2026-05-07T00:00:00.000Z',
scope: {},
metadata: {},
tables: [
{
catalog: null,
db: null,
name: 'dim_countries',
kind: 'table',
comment: null,
estimatedRows: 3,
foreignKeys: [],
columns: [
{
name: 'iso_code',
nativeType: 'TEXT',
normalizedType: 'text',
dimensionType: 'string',
nullable: false,
primaryKey: false,
comment: null,
},
{
name: 'name',
nativeType: 'TEXT',
normalizedType: 'text',
dimensionType: 'string',
nullable: false,
primaryKey: false,
comment: null,
},
],
},
{
catalog: null,
db: null,
name: 'fct_accounts',
kind: 'table',
comment: null,
estimatedRows: 4,
foreignKeys: [],
columns: [
{
name: 'id',
nativeType: 'INTEGER',
normalizedType: 'integer',
dimensionType: 'number',
nullable: false,
primaryKey: false,
comment: null,
},
{
name: 'country_code',
nativeType: 'TEXT',
normalizedType: 'text',
dimensionType: 'string',
nullable: false,
primaryKey: false,
comment: null,
},
],
},
],
};
}
2026-05-10 23:51:24 +02:00
function connector(executor: InMemorySqliteExecutor | null): KtxScanConnector {
2026-05-10 23:12:26 +02:00
return {
id: 'sqlite:test',
driver: 'sqlite',
2026-05-10 23:51:24 +02:00
capabilities: createKtxConnectorCapabilities({
2026-05-10 23:12:26 +02:00
readOnlySql: executor !== null,
columnStats: executor !== null,
tableSampling: false,
columnSampling: false,
}),
introspect: async () => snapshot(),
executeReadOnly: executor ? executor.executeReadOnly.bind(executor) : undefined,
};
}
feat: add claude-code llm backend with runtime port (#115) * docs: revise claude-code ingest backend spec * docs: keep claude-code spec focused on ingest * docs: expand claude-code spec to full llm parity * Refine claude-code backend spec after adversarial review iteration 1 * Refine claude-code backend spec after adversarial review iteration 2 * Refine claude-code backend spec after adversarial review iteration 3 * feat: recognize claude-code llm backend * feat: add ktx llm runtime port * feat: add claude-code llm runtime * feat: route non-agent llm calls through runtime * feat: run ingest agents through llm runtime * feat: support claude-code setup and status * test: verify claude-code backend runtime * docs: add claude-code backend v1 runtime plan * fix: close claude-code runtime isolation checks * fix: warn on claude-code prompt caching during setup * chore: verify claude-code v1 closure * docs: add claude-code backend v1 isolation closure plan * fix: update claude-code ingest setup guidance * docs: add claude-code backend v1 ingest guidance closure plan * docs: align claude-code isolation spec with sdk metadata * test: cover claude-code host discovery metadata * fix: tolerate claude-code host discovery metadata * docs: clarify claude-code host discovery metadata * docs: add claude-code auth-probe isolation fix plan * chore: prepare kaelio ktx rc1 release * chore: add semantic release workflow * fix: unblock ci checks * chore(release): 0.1.0-rc.1 * feat: add Claude Code model selection to setup * fix: keep git maintenance attached in local repos
2026-05-16 12:06:34 +02:00
function llmRuntime(output: unknown): KtxLlmRuntimePort {
2026-05-10 23:12:26 +02:00
return {
feat: add claude-code llm backend with runtime port (#115) * docs: revise claude-code ingest backend spec * docs: keep claude-code spec focused on ingest * docs: expand claude-code spec to full llm parity * Refine claude-code backend spec after adversarial review iteration 1 * Refine claude-code backend spec after adversarial review iteration 2 * Refine claude-code backend spec after adversarial review iteration 3 * feat: recognize claude-code llm backend * feat: add ktx llm runtime port * feat: add claude-code llm runtime * feat: route non-agent llm calls through runtime * feat: run ingest agents through llm runtime * feat: support claude-code setup and status * test: verify claude-code backend runtime * docs: add claude-code backend v1 runtime plan * fix: close claude-code runtime isolation checks * fix: warn on claude-code prompt caching during setup * chore: verify claude-code v1 closure * docs: add claude-code backend v1 isolation closure plan * fix: update claude-code ingest setup guidance * docs: add claude-code backend v1 ingest guidance closure plan * docs: align claude-code isolation spec with sdk metadata * test: cover claude-code host discovery metadata * fix: tolerate claude-code host discovery metadata * docs: clarify claude-code host discovery metadata * docs: add claude-code auth-probe isolation fix plan * chore: prepare kaelio ktx rc1 release * chore: add semantic release workflow * fix: unblock ci checks * chore(release): 0.1.0-rc.1 * feat: add Claude Code model selection to setup * fix: keep git maintenance attached in local repos
2026-05-16 12:06:34 +02:00
generateText: vi.fn(),
generateObject: vi.fn(async () => output) as KtxLlmRuntimePort['generateObject'],
runAgentLoop: vi.fn(),
2026-05-10 23:12:26 +02:00
};
}
function relationshipSettings() {
return buildDefaultKtxProjectConfig().scan.relationships;
2026-05-10 23:12:26 +02:00
}
2026-05-10 23:51:24 +02:00
function llmOnlyRelationshipSnapshot(): KtxSchemaSnapshot {
2026-05-10 23:12:26 +02:00
return {
connectionId: 'warehouse',
driver: 'sqlite',
extractedAt: '2026-05-07T00:00:00.000Z',
scope: {},
metadata: {},
tables: [
{
catalog: null,
db: null,
name: 'customers',
kind: 'table',
comment: null,
estimatedRows: 2,
foreignKeys: [],
columns: [
{
name: 'id',
nativeType: 'INTEGER',
normalizedType: 'integer',
dimensionType: 'number',
nullable: false,
primaryKey: false,
comment: null,
},
],
},
{
catalog: null,
db: null,
name: 'orders',
kind: 'table',
comment: null,
estimatedRows: 2,
foreignKeys: [],
columns: [
{
name: 'id',
nativeType: 'INTEGER',
normalizedType: 'integer',
dimensionType: 'number',
nullable: false,
primaryKey: false,
comment: null,
},
{
name: 'buyer_ref',
nativeType: 'INTEGER',
normalizedType: 'integer',
dimensionType: 'number',
nullable: false,
primaryKey: false,
comment: null,
},
],
},
],
};
}
describe('production relationship discovery', () => {
let executor: InMemorySqliteExecutor | null = null;
afterEach(() => {
executor?.close();
executor = null;
});
it('accepts a validated relationship without declared PK or FK metadata', async () => {
executor = new InMemorySqliteExecutor();
executor.db.exec(`
CREATE TABLE accounts (id INTEGER NOT NULL, name TEXT NOT NULL);
CREATE TABLE orders (id INTEGER NOT NULL, account_id INTEGER NOT NULL);
INSERT INTO accounts (id, name) VALUES (1, 'Acme'), (2, 'Globex');
INSERT INTO orders (id, account_id) VALUES (10, 1), (11, 1), (12, 2);
`);
2026-05-10 23:51:24 +02:00
const result = await discoverKtxRelationships({
2026-05-10 23:12:26 +02:00
connectionId: 'warehouse',
driver: 'sqlite',
connector: connector(executor),
2026-05-10 23:51:24 +02:00
schema: snapshotToKtxEnrichedSchema(snapshot()),
2026-05-10 23:12:26 +02:00
context: { runId: 'relationship-run-1' },
settings: relationshipSettings(),
});
expect(result.relationships).toEqual({ accepted: 1, review: 0, rejected: 0, skipped: 0 });
expect(result.statisticalValidation).toBe('completed');
expect(result.profile.sqlAvailable).toBe(true);
expect(result.profile.queryCount).toBeGreaterThan(0);
expect(result.relationshipUpdate.accepted).toEqual([
expect.objectContaining({
from: expect.objectContaining({ table: expect.objectContaining({ name: 'orders' }), columns: ['account_id'] }),
to: expect.objectContaining({ table: expect.objectContaining({ name: 'accounts' }), columns: ['id'] }),
relationshipType: 'many_to_one',
source: 'inferred',
isPrimaryKeyReference: true,
}),
]);
expect(result.resolvedRelationships[0]).toMatchObject({
status: 'accepted',
validation: expect.objectContaining({ reasons: expect.arrayContaining(['validation_passed']) }),
graph: expect.objectContaining({ reasons: expect.arrayContaining(['fk_score_passed']) }),
});
});
it('accepts a profile-driven natural-key relationship without declared metadata', async () => {
executor = new InMemorySqliteExecutor();
executor.db.exec(`
CREATE TABLE dim_countries (iso_code TEXT NOT NULL, name TEXT NOT NULL);
CREATE TABLE fct_accounts (id INTEGER NOT NULL, country_code TEXT NOT NULL);
INSERT INTO dim_countries (iso_code, name) VALUES ('US', 'United States'), ('FR', 'France'), ('DE', 'Germany');
INSERT INTO fct_accounts (id, country_code) VALUES (1, 'US'), (2, 'FR'), (3, 'US'), (4, 'DE');
`);
const schema = naturalKeySnapshot();
2026-05-10 23:51:24 +02:00
const result = await discoverKtxRelationships({
2026-05-10 23:12:26 +02:00
connectionId: 'warehouse',
driver: 'sqlite',
connector: {
...connector(executor),
introspect: async () => schema,
},
2026-05-10 23:51:24 +02:00
schema: snapshotToKtxEnrichedSchema(schema),
2026-05-10 23:12:26 +02:00
context: { runId: 'natural-key-relationship-run' },
settings: relationshipSettings(),
});
expect(result.relationships).toEqual({ accepted: 1, review: 0, rejected: 0, skipped: 0 });
expect(result.relationshipUpdate.accepted).toEqual([
expect.objectContaining({
from: expect.objectContaining({ table: expect.objectContaining({ name: 'fct_accounts' }), columns: ['country_code'] }),
to: expect.objectContaining({ table: expect.objectContaining({ name: 'dim_countries' }), columns: ['iso_code'] }),
relationshipType: 'many_to_one',
source: 'inferred',
isPrimaryKeyReference: true,
}),
]);
expect(result.resolvedRelationships[0]).toMatchObject({
source: 'profile_match',
status: 'accepted',
validation: expect.objectContaining({ reasons: expect.arrayContaining(['validation_passed']) }),
graph: expect.objectContaining({ reasons: expect.arrayContaining(['fk_score_passed']) }),
});
});
it('accepts an embedding-driven relationship without declared metadata or LLM proposals', async () => {
executor = new InMemorySqliteExecutor();
executor.db.exec(`
CREATE TABLE customers (id INTEGER NOT NULL, name TEXT NOT NULL);
CREATE TABLE orders (id INTEGER NOT NULL, buyer_ref INTEGER NOT NULL);
INSERT INTO customers (id, name) VALUES (1, 'Acme'), (2, 'Orbit'), (3, 'Globex');
INSERT INTO orders (id, buyer_ref) VALUES (10, 1), (11, 2), (12, 2), (13, 3);
`);
const sourceSnapshot = llmOnlyRelationshipSnapshot();
2026-05-10 23:51:24 +02:00
const schema = snapshotToKtxEnrichedSchema(
2026-05-10 23:12:26 +02:00
sourceSnapshot,
new Map([
['customers.id', [1, 0, 0]],
['customers.name', [0, 1, 0]],
['orders.id', [0, 0, 1]],
['orders.buyer_ref', [0.995, 0.005, 0]],
]),
);
2026-05-10 23:51:24 +02:00
const result = await discoverKtxRelationships({
2026-05-10 23:12:26 +02:00
connectionId: 'warehouse',
driver: 'sqlite',
connector: {
...connector(executor),
introspect: async () => sourceSnapshot,
},
schema,
context: { runId: 'embedding-relationship-run' },
settings: {
...relationshipSettings(),
llmProposals: false,
},
});
expect(result.llmRelationshipValidation).toBe('skipped');
expect(result.relationships).toEqual({ accepted: 1, review: 0, rejected: 0, skipped: 0 });
expect(result.relationshipUpdate.accepted[0]).toMatchObject({
from: { table: { name: 'orders' }, columns: ['buyer_ref'] },
to: { table: { name: 'customers' }, columns: ['id'] },
});
expect(result.resolvedRelationships[0]).toMatchObject({
source: 'embedding_similarity',
status: 'accepted',
validation: expect.objectContaining({ reasons: expect.arrayContaining(['validation_passed']) }),
evidence: expect.objectContaining({
reasons: expect.arrayContaining(['embedding_similarity', 'target_key_like']),
embeddingSimilarity: expect.any(Number),
}),
});
});
it('keeps candidates review-only when read-only SQL is unavailable', async () => {
2026-05-10 23:51:24 +02:00
const result = await discoverKtxRelationships({
2026-05-10 23:12:26 +02:00
connectionId: 'warehouse',
driver: 'sqlite',
connector: connector(null),
2026-05-10 23:51:24 +02:00
schema: snapshotToKtxEnrichedSchema(snapshot()),
2026-05-10 23:12:26 +02:00
context: { runId: 'relationship-run-no-sql' },
settings: relationshipSettings(),
});
expect(result.relationships).toEqual({ accepted: 0, review: 1, rejected: 0, skipped: 0 });
expect(result.statisticalValidation).toBe('skipped');
expect(result.relationshipUpdate.accepted).toEqual([]);
expect(result.resolvedRelationships[0]).toMatchObject({
status: 'review',
validation: expect.objectContaining({ reasons: expect.arrayContaining(['validation_unavailable']) }),
});
expect(result.warnings).toContainEqual({
code: 'connector_capability_missing',
2026-05-10 23:51:24 +02:00
message: 'KTX scan connector cannot run read-only SQL relationship validation',
2026-05-10 23:12:26 +02:00
recoverable: true,
metadata: { capability: 'readOnlySql' },
});
});
it('accepts formal metadata relationships when read-only SQL is unavailable', async () => {
const sourceSnapshot = declaredForeignKeySnapshot();
2026-05-10 23:51:24 +02:00
const result = await discoverKtxRelationships({
2026-05-10 23:12:26 +02:00
connectionId: 'warehouse',
driver: 'sqlite',
connector: connector(null),
2026-05-10 23:51:24 +02:00
schema: snapshotToKtxEnrichedSchema(sourceSnapshot),
2026-05-10 23:12:26 +02:00
context: { runId: 'formal-metadata-no-sql' },
settings: relationshipSettings(),
});
expect(result.statisticalValidation).toBe('skipped');
expect(result.relationships).toEqual({ accepted: 1, review: 0, rejected: 0, skipped: 0 });
expect(result.resolvedRelationships).toEqual([]);
expect(result.relationshipUpdate.accepted).toEqual([
expect.objectContaining({
id: 'orders:(orders.account_id)->accounts:(accounts.id)',
source: 'formal',
confidence: 1,
from: expect.objectContaining({ table: expect.objectContaining({ name: 'orders' }), columns: ['account_id'] }),
to: expect.objectContaining({ table: expect.objectContaining({ name: 'accounts' }), columns: ['id'] }),
}),
]);
expect(result.relationshipUpdate.rejected).toEqual([]);
expect(result.relationshipUpdate.skipped).toEqual([]);
});
it('accepts LLM-only relationship proposals only after SQL validation and graph resolution pass', async () => {
executor = new InMemorySqliteExecutor();
executor.db.exec(`
CREATE TABLE customers (id INTEGER);
CREATE TABLE orders (id INTEGER, buyer_ref INTEGER);
INSERT INTO customers (id) VALUES (1), (2);
INSERT INTO orders (id, buyer_ref) VALUES (10, 1), (11, 2);
`);
feat: add claude-code llm backend with runtime port (#115) * docs: revise claude-code ingest backend spec * docs: keep claude-code spec focused on ingest * docs: expand claude-code spec to full llm parity * Refine claude-code backend spec after adversarial review iteration 1 * Refine claude-code backend spec after adversarial review iteration 2 * Refine claude-code backend spec after adversarial review iteration 3 * feat: recognize claude-code llm backend * feat: add ktx llm runtime port * feat: add claude-code llm runtime * feat: route non-agent llm calls through runtime * feat: run ingest agents through llm runtime * feat: support claude-code setup and status * test: verify claude-code backend runtime * docs: add claude-code backend v1 runtime plan * fix: close claude-code runtime isolation checks * fix: warn on claude-code prompt caching during setup * chore: verify claude-code v1 closure * docs: add claude-code backend v1 isolation closure plan * fix: update claude-code ingest setup guidance * docs: add claude-code backend v1 ingest guidance closure plan * docs: align claude-code isolation spec with sdk metadata * test: cover claude-code host discovery metadata * fix: tolerate claude-code host discovery metadata * docs: clarify claude-code host discovery metadata * docs: add claude-code auth-probe isolation fix plan * chore: prepare kaelio ktx rc1 release * chore: add semantic release workflow * fix: unblock ci checks * chore(release): 0.1.0-rc.1 * feat: add Claude Code model selection to setup * fix: keep git maintenance attached in local repos
2026-05-16 12:06:34 +02:00
const llmOutput = {
pkCandidates: [{ table: 'customers', column: 'id', confidence: 0.91, rationale: 'Unique customer key.' }],
fkCandidates: [
{
fromTable: 'orders',
fromColumn: 'buyer_ref',
toTable: 'customers',
toColumn: 'id',
confidence: 0.89,
rationale: 'Buyer reference values align with customer identifiers.',
},
],
};
2026-05-10 23:12:26 +02:00
2026-05-10 23:51:24 +02:00
const result = await discoverKtxRelationships({
2026-05-10 23:12:26 +02:00
connectionId: 'warehouse',
driver: 'sqlite',
connector: connector(executor),
2026-05-10 23:51:24 +02:00
schema: snapshotToKtxEnrichedSchema(llmOnlyRelationshipSnapshot()),
2026-05-10 23:12:26 +02:00
context: { runId: 'llm-relationship-orchestrator' },
settings: relationshipSettings(),
feat: add claude-code llm backend with runtime port (#115) * docs: revise claude-code ingest backend spec * docs: keep claude-code spec focused on ingest * docs: expand claude-code spec to full llm parity * Refine claude-code backend spec after adversarial review iteration 1 * Refine claude-code backend spec after adversarial review iteration 2 * Refine claude-code backend spec after adversarial review iteration 3 * feat: recognize claude-code llm backend * feat: add ktx llm runtime port * feat: add claude-code llm runtime * feat: route non-agent llm calls through runtime * feat: run ingest agents through llm runtime * feat: support claude-code setup and status * test: verify claude-code backend runtime * docs: add claude-code backend v1 runtime plan * fix: close claude-code runtime isolation checks * fix: warn on claude-code prompt caching during setup * chore: verify claude-code v1 closure * docs: add claude-code backend v1 isolation closure plan * fix: update claude-code ingest setup guidance * docs: add claude-code backend v1 ingest guidance closure plan * docs: align claude-code isolation spec with sdk metadata * test: cover claude-code host discovery metadata * fix: tolerate claude-code host discovery metadata * docs: clarify claude-code host discovery metadata * docs: add claude-code auth-probe isolation fix plan * chore: prepare kaelio ktx rc1 release * chore: add semantic release workflow * fix: unblock ci checks * chore(release): 0.1.0-rc.1 * feat: add Claude Code model selection to setup * fix: keep git maintenance attached in local repos
2026-05-16 12:06:34 +02:00
llmRuntime: llmRuntime(llmOutput),
2026-05-10 23:12:26 +02:00
});
expect(result.llmRelationshipValidation).toBe('completed');
expect(result.relationships).toEqual({ accepted: 1, review: 0, rejected: 0, skipped: 0 });
expect(result.resolvedRelationships[0]).toMatchObject({
source: 'llm_proposal',
status: 'accepted',
evidence: {
llmRationale: 'Buyer reference values align with customer identifiers.',
},
});
expect(result.relationshipUpdate.accepted[0]).toMatchObject({
from: { table: { name: 'orders' }, columns: ['buyer_ref'] },
to: { table: { name: 'customers' }, columns: ['id'] },
});
});
it('uses configured acceptance thresholds when resolving graph relationships', async () => {
const executor = new InMemorySqliteExecutor();
executor.db.exec(`
CREATE TABLE accounts (id INTEGER NOT NULL, name TEXT NOT NULL);
CREATE TABLE orders (id INTEGER NOT NULL, account_id INTEGER NOT NULL);
INSERT INTO accounts VALUES (1, 'Acme'), (2, 'Orbit');
INSERT INTO orders VALUES (10, 1), (11, 1), (12, 2);
`);
const settings = {
...buildDefaultKtxProjectConfig().scan.relationships,
2026-05-10 23:12:26 +02:00
acceptThreshold: 0.99,
reviewThreshold: 0.55,
};
2026-05-10 23:51:24 +02:00
const result = await discoverKtxRelationships({
2026-05-10 23:12:26 +02:00
connectionId: 'warehouse',
driver: 'sqlite',
connector: connector(executor),
2026-05-10 23:51:24 +02:00
schema: snapshotToKtxEnrichedSchema(snapshot()),
2026-05-10 23:12:26 +02:00
context: { runId: 'configured-thresholds' },
settings,
});
expect(result.relationships).toEqual({ accepted: 0, review: 1, rejected: 0, skipped: 0 });
expect(result.relationshipUpdate.accepted).toEqual([]);
expect(result.resolvedRelationships[0]).toMatchObject({
status: 'review',
graph: { reasons: expect.arrayContaining(['fk_score_review']) },
});
executor.close();
});
it('passes maxCandidatesPerColumn into broad deterministic candidate generation', async () => {
const executor = new InMemorySqliteExecutor();
executor.db.exec(`
CREATE TABLE accounts (id INTEGER NOT NULL, name TEXT NOT NULL);
CREATE TABLE account_archive (id INTEGER NOT NULL, name TEXT NOT NULL);
CREATE TABLE orders (id INTEGER NOT NULL, account_id INTEGER NOT NULL);
INSERT INTO accounts VALUES (1, 'Acme'), (2, 'Orbit');
INSERT INTO account_archive VALUES (99, 'Archive');
INSERT INTO orders VALUES (10, 1), (11, 1), (12, 2);
`);
const richSnapshot = snapshot();
richSnapshot.tables.splice(1, 0, {
catalog: null,
db: null,
name: 'account_archive',
kind: 'table',
comment: null,
estimatedRows: 1,
foreignKeys: [],
columns: [
{
name: 'id',
nativeType: 'INTEGER',
normalizedType: 'integer',
dimensionType: 'number',
nullable: false,
primaryKey: false,
comment: null,
},
{
name: 'name',
nativeType: 'TEXT',
normalizedType: 'text',
dimensionType: 'string',
nullable: false,
primaryKey: false,
comment: null,
},
],
});
2026-05-10 23:51:24 +02:00
const result = await discoverKtxRelationships({
2026-05-10 23:12:26 +02:00
connectionId: 'warehouse',
driver: 'sqlite',
connector: {
...connector(executor),
introspect: async () => richSnapshot,
},
2026-05-10 23:51:24 +02:00
schema: snapshotToKtxEnrichedSchema(richSnapshot),
2026-05-10 23:12:26 +02:00
context: { runId: 'candidate-cap' },
settings: {
...buildDefaultKtxProjectConfig().scan.relationships,
2026-05-10 23:12:26 +02:00
maxCandidatesPerColumn: 1,
},
});
const sourceTargets = result.resolvedRelationships
.filter((relationship) => relationship.from.columns[0] === 'account_id')
.map((relationship) => `${relationship.to.table.name}.${relationship.to.columns[0]}`);
expect(sourceTargets).toHaveLength(1);
expect(sourceTargets).toEqual(['accounts.id']);
executor.close();
});
it('accepts SQL-validated composite relationships in production relationship-discovery detection', async () => {
const fixtureRoot = new URL(
'../../test/fixtures/relationship-benchmarks/composite_keys_no_declared_constraints',
import.meta.url,
);
2026-05-10 23:51:24 +02:00
const fixture = await loadKtxRelationshipBenchmarkFixture(fixtureRoot.pathname);
const maskedSnapshot = maskKtxRelationshipBenchmarkSnapshot(fixture.snapshot, 'declared_pks_and_declared_fks_removed');
2026-05-10 23:12:26 +02:00
const database = new Database(fixture.dataPath ?? '', { readonly: true, fileMustExist: true });
2026-05-10 23:51:24 +02:00
const testConnector: KtxScanConnector = {
2026-05-10 23:12:26 +02:00
id: 'sqlite:composite',
driver: 'sqlite',
2026-05-10 23:51:24 +02:00
capabilities: createKtxConnectorCapabilities({
2026-05-10 23:12:26 +02:00
readOnlySql: true,
columnStats: true,
tableSampling: false,
columnSampling: false,
}),
introspect: async () => maskedSnapshot,
executeReadOnly: async (input) => {
const rows = database.prepare(input.sql).all() as Record<string, unknown>[];
const headers = Object.keys(rows[0] ?? {});
return {
headers,
rows: rows.map((row) => headers.map((header) => row[header])),
totalRows: rows.length,
rowCount: rows.length,
};
},
};
2026-05-10 23:51:24 +02:00
const result = await discoverKtxRelationships({
2026-05-10 23:12:26 +02:00
connectionId: maskedSnapshot.connectionId,
driver: maskedSnapshot.driver,
connector: testConnector,
2026-05-10 23:51:24 +02:00
schema: snapshotToKtxEnrichedSchema(maskedSnapshot, new Map()),
2026-05-10 23:12:26 +02:00
context: { runId: 'test:production-composite' },
settings: relationshipSettings(),
});
database.close();
expect(
result.relationshipUpdate.accepted.map(
(relationship) =>
`${relationship.from.table.name}.(${relationship.from.columns.join(',')})->${relationship.to.table.name}.(${relationship.to.columns.join(',')})`,
),
).toContain('order_line_allocations.(order_id,line_number)->order_lines.(order_id,line_number)');
expect(result.relationships.accepted).toBeGreaterThanOrEqual(1);
expect(result.compositeRelationships.map((relationship) => relationship.status)).toContain('accepted');
});
});