ktx/packages/cli/src/context/scan/relationship-diagnostics.test.ts
Andrey Avtomonov 2366b00301
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

373 lines
13 KiB
TypeScript

import { describe, expect, it } from 'vitest';
import type { KtxEnrichedRelationship, KtxRelationshipEndpoint } from './enrichment-types.js';
import type { KtxResolvedRelationshipDiscoveryCandidate } from './relationship-graph-resolver.js';
import {
buildKtxRelationshipArtifacts,
buildKtxRelationshipDiagnostics,
emptyKtxRelationshipProfileArtifact,
} from './relationship-diagnostics.js';
function endpoint(table: string, column: string): KtxRelationshipEndpoint {
return {
tableId: table,
columnIds: [`${table}.${column}`],
table: { catalog: null, db: null, name: table },
columns: [column],
};
}
function enrichedRelationship(input: {
id: string;
fromTable: string;
fromColumn: string;
toTable: string;
toColumn: string;
confidence?: number;
}): KtxEnrichedRelationship {
return {
id: input.id,
source: 'inferred',
from: endpoint(input.fromTable, input.fromColumn),
to: endpoint(input.toTable, input.toColumn),
relationshipType: 'many_to_one',
confidence: input.confidence ?? 0.92,
isPrimaryKeyReference: true,
};
}
function resolvedRelationship(input: {
id: string;
status: 'accepted' | 'review' | 'rejected';
source?: 'normalized_table_match' | 'exact_column_match' | 'inflection' | 'self_reference' | 'llm_proposal';
fkScore?: number;
pkScore?: number;
validationReasons?: string[];
graphReasons?: string[];
}): KtxResolvedRelationshipDiscoveryCandidate {
return {
id: input.id,
from: endpoint('orders', 'customer_id'),
to: endpoint('customers', 'id'),
relationshipType: 'many_to_one',
confidence: 0.88,
source: input.source ?? 'normalized_table_match',
status: input.status,
evidence:
input.source === 'llm_proposal'
? {
sourceColumnBase: 'buyer',
targetTableBase: 'customer',
targetColumnBase: 'id',
targetKeyScore: 0.88,
nameScore: 0.45,
reasons: ['llm_proposal', 'llm_pk_proposal'],
llmConfidence: 0.89,
llmRationale: 'Buyer reference values align with customer identifiers.',
}
: {
sourceColumnBase: 'customer',
targetTableBase: 'customer',
targetColumnBase: 'id',
targetKeyScore: 0.9,
nameScore: 0.85,
reasons: ['table_name_matches_source_column'],
},
score: 0.91,
validation: {
targetUniqueness: 1,
sourceCoverage: input.status === 'rejected' ? 0.2 : 1,
violationCount: input.status === 'rejected' ? 8 : 0,
violationRatio: input.status === 'rejected' ? 0.8 : 0,
sourceNullRate: 0,
targetNullRate: 0,
childDistinct: 10,
parentDistinct: 10,
overlap: input.status === 'rejected' ? 2 : 10,
checkedValues: 10,
reasons: input.validationReasons ?? ['validation_passed'],
},
pkScore: input.pkScore ?? 0.97,
fkScore: input.fkScore ?? 0.94,
graph: {
targetPkScore: input.pkScore ?? 0.97,
incomingCandidateCount: 1,
conflictRank: 1,
reasons: input.graphReasons ?? ['target_pk_score_passed', 'fk_score_passed'],
},
};
}
describe('relationship diagnostics artifacts', () => {
it('groups graph-resolved relationships and preserves evidence reasons', () => {
const artifacts = buildKtxRelationshipArtifacts({
connectionId: 'warehouse',
resolvedRelationships: [
resolvedRelationship({ id: 'accepted-edge', status: 'accepted', source: 'llm_proposal' }),
resolvedRelationship({
id: 'review-edge',
status: 'review',
validationReasons: ['validation_unavailable'],
graphReasons: ['validation_unavailable_review_only', 'fk_score_review'],
}),
resolvedRelationship({
id: 'rejected-edge',
status: 'rejected',
validationReasons: ['low_source_coverage'],
graphReasons: ['fk_score_rejected'],
}),
],
});
expect(artifacts.accepted).toHaveLength(1);
expect(artifacts.accepted[0]).toMatchObject({
source: 'llm_proposal',
evidence: {
llmConfidence: 0.89,
llmRationale: 'Buyer reference values align with customer identifiers.',
},
reasons: expect.arrayContaining(['llm_proposal', 'llm_pk_proposal']),
});
expect(artifacts.review).toHaveLength(1);
expect(artifacts.rejected).toHaveLength(1);
expect(artifacts.review[0]).toMatchObject({
id: 'review-edge',
status: 'review',
source: 'normalized_table_match',
fkScore: 0.94,
reasons: expect.arrayContaining(['validation_unavailable', 'validation_unavailable_review_only']),
});
expect(artifacts.rejected[0]?.reasons).toEqual(
expect.arrayContaining(['table_name_matches_source_column', 'low_source_coverage', 'fk_score_rejected']),
);
});
it('adapts relationship updates into the artifact shape', () => {
const artifacts = buildKtxRelationshipArtifacts({
connectionId: 'warehouse',
relationshipUpdate: {
connectionId: 'warehouse',
accepted: [
enrichedRelationship({
id: 'orders-customer',
fromTable: 'orders',
fromColumn: 'customer_id',
toTable: 'customers',
toColumn: 'id',
}),
],
rejected: [
enrichedRelationship({
id: 'orders-account',
fromTable: 'orders',
fromColumn: 'account_id',
toTable: 'accounts',
toColumn: 'id',
confidence: 0.4,
}),
],
skipped: [{ relationshipId: 'orders-region', reason: 'validation_port_unavailable' }],
},
});
expect(artifacts.accepted[0]).toMatchObject({
id: 'orders-customer',
status: 'accepted',
source: 'inferred',
reasons: ['accepted_relationship_update'],
});
expect(artifacts.rejected[0]).toMatchObject({
id: 'orders-account',
status: 'rejected',
reasons: ['rejected_relationship_update'],
});
expect(artifacts.skipped).toEqual([{ relationshipId: 'orders-region', reason: 'validation_port_unavailable' }]);
});
it('deduplicates resolved and formal relationship update artifacts by edge id', () => {
const artifacts = buildKtxRelationshipArtifacts({
connectionId: 'warehouse',
resolvedRelationships: [
{
id: 'orders:orders.account_id->accounts:accounts.id',
from: endpoint('orders', 'account_id'),
to: endpoint('accounts', 'id'),
relationshipType: 'many_to_one',
source: 'normalized_table_match',
status: 'accepted',
confidence: 0.92,
score: 0.9,
pkScore: 0.92,
fkScore: 0.9,
evidence: {
sourceColumnBase: 'account',
targetTableBase: 'account',
targetColumnBase: 'id',
targetKeyScore: 0.92,
nameScore: 0.92,
reasons: ['foreign_key_suffix'],
},
validation: {
targetUniqueness: 1,
sourceCoverage: 1,
violationCount: 0,
violationRatio: 0,
sourceNullRate: 0,
targetNullRate: 0,
childDistinct: 2,
parentDistinct: 2,
overlap: 2,
checkedValues: 2,
reasons: ['validation_passed'],
},
graph: {
targetPkScore: 0.92,
incomingCandidateCount: 1,
conflictRank: 1,
reasons: ['fk_score_passed'],
},
},
],
relationshipUpdate: {
connectionId: 'warehouse',
accepted: [
{
id: 'orders:orders.account_id->accounts:accounts.id',
source: 'formal',
from: endpoint('orders', 'account_id'),
to: endpoint('accounts', 'id'),
relationshipType: 'many_to_one',
confidence: 1,
isPrimaryKeyReference: true,
},
],
rejected: [],
skipped: [],
},
});
expect(artifacts.accepted).toHaveLength(1);
expect(artifacts.accepted[0]).toMatchObject({
id: 'orders:orders.account_id->accounts:accounts.id',
source: 'normalized_table_match',
reasons: expect.arrayContaining(['foreign_key_suffix', 'validation_passed', 'fk_score_passed']),
});
});
it('explains validation-unavailable review candidates', () => {
const artifacts = buildKtxRelationshipArtifacts({
connectionId: 'warehouse',
resolvedRelationships: [
resolvedRelationship({
id: 'review-edge',
status: 'review',
validationReasons: ['validation_unavailable'],
graphReasons: ['validation_unavailable_review_only'],
}),
],
});
const profile = emptyKtxRelationshipProfileArtifact({
connectionId: 'warehouse',
driver: 'sqlite',
reason: 'read_only_sql_unavailable',
});
const diagnostics = buildKtxRelationshipDiagnostics({
connectionId: 'warehouse',
generatedAt: '2026-05-07T12:00:00.000Z',
artifacts,
profile,
warnings: [
{
code: 'connector_capability_missing',
message: 'KTX scan connector cannot run standalone statistical relationship validation',
recoverable: true,
metadata: { capability: 'readOnlySql' },
},
],
thresholds: { acceptThreshold: 0.85, reviewThreshold: 0.55 },
});
expect(diagnostics.summary).toEqual({ accepted: 0, review: 1, rejected: 0, skipped: 0 });
expect(diagnostics.noAcceptedReason).toBe('validation unavailable; review candidates written');
expect(diagnostics.candidateCountsBySource).toEqual({ normalized_table_match: 1 });
expect(diagnostics.validation).toEqual({
available: false,
sqlAvailable: false,
queryCount: 0,
});
expect(diagnostics.profileWarnings).toEqual(['read_only_sql_unavailable']);
expect(diagnostics.warnings[0]).toMatchObject({ code: 'connector_capability_missing' });
});
it('explains empty relationship output as a no-candidate outcome', () => {
const artifacts = buildKtxRelationshipArtifacts({ connectionId: 'warehouse' });
const diagnostics = buildKtxRelationshipDiagnostics({
connectionId: 'warehouse',
generatedAt: '2026-05-07T12:00:00.000Z',
artifacts,
profile: emptyKtxRelationshipProfileArtifact({
connectionId: 'warehouse',
driver: 'sqlite',
reason: 'relationship_profiling_not_run',
}),
});
expect(diagnostics.summary).toEqual({ accepted: 0, review: 0, rejected: 0, skipped: 0 });
expect(diagnostics.noAcceptedReason).toBe('no candidate pairs passed type compatibility');
expect(diagnostics.candidateCountsBySource).toEqual({});
});
it('records composite relationship endpoints in relationship artifacts', () => {
const artifacts = buildKtxRelationshipArtifacts({
connectionId: 'warehouse',
compositeRelationships: [
{
id: 'order_line_allocations.(order_id,line_number)->order_lines.(order_id,line_number)',
source: 'composite_profile_match',
status: 'accepted',
from: {
tableId: 'order_line_allocations',
columnIds: ['order_line_allocations.order_id', 'order_line_allocations.line_number'],
table: { catalog: null, db: null, name: 'order_line_allocations' },
columns: ['order_id', 'line_number'],
},
to: {
tableId: 'order_lines',
columnIds: ['order_lines.order_id', 'order_lines.line_number'],
table: { catalog: null, db: null, name: 'order_lines' },
columns: ['order_id', 'line_number'],
},
relationshipType: 'many_to_one',
confidence: 0.95,
validation: {
targetUniqueness: 1,
sourceCoverage: 1,
violationCount: 0,
violationRatio: 0,
childDistinct: 2,
parentDistinct: 2,
overlap: 2,
reasons: ['composite_validation_passed'],
},
},
],
});
expect(artifacts.accepted).toEqual([
expect.objectContaining({
id: 'order_line_allocations.(order_id,line_number)->order_lines.(order_id,line_number)',
source: 'composite_profile_match',
from: expect.objectContaining({
columnIds: ['order_line_allocations.order_id', 'order_line_allocations.line_number'],
columns: ['order_id', 'line_number'],
}),
to: expect.objectContaining({
columnIds: ['order_lines.order_id', 'order_lines.line_number'],
columns: ['order_id', 'line_number'],
}),
reasons: ['composite_validation_passed'],
validation: expect.objectContaining({ sourceCoverage: 1 }),
}),
]);
});
});