2026-05-10 23:12:26 +02:00
|
|
|
import { describe, expect, it } from 'vitest';
|
2026-05-14 15:36:35 +02:00
|
|
|
import {
|
|
|
|
|
buildDefaultKtxProjectConfig,
|
2026-05-14 16:21:29 +02:00
|
|
|
generateKtxProjectConfigJsonSchema,
|
2026-05-14 15:36:35 +02:00
|
|
|
parseKtxProjectConfig,
|
|
|
|
|
serializeKtxProjectConfig,
|
|
|
|
|
validateKtxProjectConfig,
|
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/project/config.js';
|
2026-05-10 23:12:26 +02:00
|
|
|
|
2026-05-10 23:51:24 +02:00
|
|
|
describe('KTX project config', () => {
|
2026-05-14 01:43:06 +02:00
|
|
|
it.each(['status', 'replay', 'run', 'watch'])('accepts former ingest subcommand name "%s" as a connection id', (connectionId) => {
|
|
|
|
|
expect(
|
|
|
|
|
parseKtxProjectConfig(`
|
|
|
|
|
connections:
|
|
|
|
|
${connectionId}:
|
|
|
|
|
driver: postgres
|
|
|
|
|
`),
|
|
|
|
|
).toMatchObject({
|
|
|
|
|
connections: {
|
|
|
|
|
[connectionId]: { driver: 'postgres' },
|
|
|
|
|
},
|
|
|
|
|
});
|
|
|
|
|
});
|
|
|
|
|
|
2026-05-10 23:12:26 +02:00
|
|
|
it('builds the default standalone project config', () => {
|
2026-05-14 17:39:31 +02:00
|
|
|
expect(buildDefaultKtxProjectConfig()).toEqual({
|
2026-05-10 23:12:26 +02:00
|
|
|
connections: {},
|
|
|
|
|
storage: {
|
|
|
|
|
state: 'sqlite',
|
|
|
|
|
search: 'sqlite-fts5',
|
|
|
|
|
git: {
|
|
|
|
|
auto_commit: true,
|
2026-05-10 23:51:24 +02:00
|
|
|
author: 'ktx <ktx@example.com>',
|
2026-05-10 23:12:26 +02:00
|
|
|
},
|
|
|
|
|
},
|
|
|
|
|
llm: {
|
|
|
|
|
provider: {
|
|
|
|
|
backend: 'none',
|
|
|
|
|
},
|
|
|
|
|
models: {},
|
|
|
|
|
},
|
|
|
|
|
ingest: {
|
2026-05-14 01:43:06 +02:00
|
|
|
adapters: [],
|
2026-05-10 23:12:26 +02:00
|
|
|
embeddings: {
|
2026-05-19 16:40:01 +02:00
|
|
|
backend: 'none',
|
2026-05-10 23:12:26 +02:00
|
|
|
dimensions: 8,
|
|
|
|
|
},
|
|
|
|
|
workUnits: {
|
|
|
|
|
stepBudget: 40,
|
|
|
|
|
maxConcurrency: 1,
|
|
|
|
|
failureMode: 'continue',
|
|
|
|
|
},
|
feat(cli): add ingest LLM rate-limit governor with paced retries (#261)
* feat(cli): add ingest rate limit governor
* feat(cli): wire ingest rate-limit config
* feat(cli): report provider rate-limit signals
* feat(cli): show ingest rate-limit waits
* fix(cli): complete rate-limit event coverage
* fix(cli): abort ingest provider calls cleanly
* fix(cli): propagate ingest cancellation
* fix(cli): reject pre-aborted ingest rate-limit waits
* fix(cli): honor Claude rate-limit reset waits
* fix(cli): retry thrown Codex rate-limit failures
* fix(cli): type Claude rate-limit result details
* fix(cli): emit ingest rate-limit countdowns from rejected signals
* fix(cli): report ai sdk rate-limit header utilization
* fix(cli): gate LLM rate-limit retries on the governor budget
The AI SDK and Codex runtimes retried 429 / opaque rate-limit failures up
to 6-7 times with no backoff when constructed without a RateLimitGovernor
(scan, memory, setup) or with pacing disabled, ignoring Retry-After and
worsening the limit. The outer retry loop only cooperates with the
governor's pause, so without active pacing there is no backoff to apply.
Route the retry bound through a single source: RateLimitGovernor
.maxRetryAttempts(), which returns retry.maxAttempts when enabled and 1
(no outer retry) when absent or disabled. All three runtimes (ai-sdk,
codex, claude-code) now use it, so ingest.rateLimit.retry.maxAttempts
genuinely controls attempts and the hard-coded 6 (plus Codex's off-by-one
extra attempt) is gone. Backend-native retry (e.g. the AI SDK's maxRetries)
still handles transient 429s.
Also correct the ktx.yaml docs for maxWaitMs (caps each wait, not the whole
run) and maxAttempts, and sync uv.lock ktx-sl/ktx-daemon to 0.9.0.
2026-06-05 12:10:27 +02:00
|
|
|
rateLimit: {
|
|
|
|
|
enabled: true,
|
|
|
|
|
throttleThreshold: 0.8,
|
|
|
|
|
minConcurrencyUnderPressure: 1,
|
|
|
|
|
retry: {
|
|
|
|
|
maxAttempts: 6,
|
|
|
|
|
baseDelayMs: 1_000,
|
|
|
|
|
maxDelayMs: 60_000,
|
|
|
|
|
jitter: true,
|
|
|
|
|
},
|
|
|
|
|
},
|
feat(cli): profile ingest runs and split model vs tool time (#249)
* feat(cli): profile ingest runs to find where wall-clock time goes
Add opt-in profiling for `ktx ingest`. Each timed phase, work unit, and
agent loop now records durationMs / step count / token usage in the
trace, and a post-run aggregator rolls them up into a "where did the
time go" report printed to stderr.
Enable per run with KTX_PROFILE_INGEST (1/true -> human table, json ->
raw structured profile) or persistently via `ingest.profile` in
ktx.yaml. The json form emits raw milliseconds, token counts, and a
summary.headline one-line diagnosis so coding agents can parse it
directly; json wins when both env and config request profiling.
- runtime-port: RunLoopMetrics (totalMs, usage, stepCount,
stepBoundariesMs) plus onMetrics callbacks on text/object generation
- ai-sdk + claude-code runtimes: capture per-loop timing and token usage
- work-unit-executor and stages 3/4: thread metrics into trace events
- ingest-bundle.runner: time worktree / triage / clustering / index /
reconcile / squash phases and emit the profile in a finally block
(best-effort; never affects the run outcome)
- ingest-profile: new trace+transcript aggregator with table/json formatters
- config: ingest.profile flag; docs: profiling section in ktx-ingest.mdx
* fix(cli): flush tool-call logs before reading ingest profile
Tool transcripts are appended fire-and-forget so the agent hot path never
blocks on logging. The ingest profiler read them before the writes settled,
so per-work-unit toolMs (and the model-vs-tool split derived from it) could
be incomplete. Track in-flight appends and expose flushToolCallLogs() —
bounded by a timeout so it can never hang — and flush before the profiler
reads the transcript.
2026-06-01 15:49:17 +02:00
|
|
|
profile: false,
|
2026-05-10 23:12:26 +02:00
|
|
|
},
|
|
|
|
|
agent: {
|
|
|
|
|
run_research: {
|
|
|
|
|
enabled: false,
|
|
|
|
|
max_iterations: 20,
|
2026-05-13 16:05:58 +02:00
|
|
|
default_toolset: ['sl_query', 'wiki_search', 'sl_read_source'],
|
2026-05-10 23:12:26 +02:00
|
|
|
},
|
|
|
|
|
},
|
|
|
|
|
memory: {
|
|
|
|
|
auto_commit: true,
|
|
|
|
|
},
|
|
|
|
|
scan: {
|
|
|
|
|
enrichment: {
|
|
|
|
|
mode: 'none',
|
|
|
|
|
},
|
|
|
|
|
relationships: {
|
|
|
|
|
enabled: true,
|
|
|
|
|
llmProposals: true,
|
|
|
|
|
validationRequiredForManifest: true,
|
|
|
|
|
acceptThreshold: 0.85,
|
|
|
|
|
reviewThreshold: 0.55,
|
|
|
|
|
maxLlmTablesPerBatch: 40,
|
|
|
|
|
maxCandidatesPerColumn: 25,
|
|
|
|
|
profileSampleRows: 10000,
|
fix(snowflake): unblock multi-schema ingest and relationship discovery (#204)
* feat(setup): drop redundant Snowflake schema prompt; fall back to free-text on listSchemas failure
Snowflake setup previously asked for a single schema as free text, then
ran a multiselect against the discovered schemas — two schema questions
back-to-back, with the first being only a session bootstrap. The SDK's
`schema` is optional, so the bootstrap step is unnecessary.
- Remove the free-text Snowflake schema prompt; only pass `schema` to
snowflake-sdk when one is configured.
- When `listSchemas()` fails (e.g. role lacks SHOW SCHEMAS), prompt the
user for a comma-separated list, persist it as `schema_names`, and use
it as both the table-list filter and the multiselect default. Applies
to every driver with a scope-discovery spec, not just Snowflake.
- Update docs to lead with `schema_names`; keep `schema_name` as a
documented single-schema shorthand.
* fix(snowflake): keep introspecting when primary-key discovery is denied
The PK query joins INFORMATION_SCHEMA.TABLE_CONSTRAINTS and
INFORMATION_SCHEMA.KEY_COLUMN_USAGE, which require grants the
connection role may not have. Previously a 'SQL compilation error:
Object ANALYTICS.INFORMATION_SCHEMA.KEY_COLUMN_USAGE does not exist
or not authorized' aborted the entire introspect — schemas, columns,
and row counts were all discarded over a missing nice-to-have.
Wrap the constraint query in try/catch, log a one-line warning per
schema, and return an empty PK map. Columns end up with
primaryKey=false; relationship inference still has FK and profiling
to fall back on.
* fix(scan): unblock relationship discovery on Snowflake
Two adjacent bugs prevented the scan's relationship pipeline from producing
any joins on a Snowflake warehouse:
- relationship-profiling.ts fell through to a default `GROUP_CONCAT` branch
for unknown drivers. Snowflake has no GROUP_CONCAT, so every per-table
profile query failed with "Unknown function GROUP_CONCAT". Add an explicit
Snowflake branch that uses LISTAGG with a literal '\x1f' delimiter
(Snowflake requires the delimiter to be a constant, so CHR(31) is rejected).
- description-generation.ts destructured `connector.sampleTable` and
`connector.sampleColumn` into bare locals, losing the `this` binding when
the class-method connectors (Snowflake, Postgres, MySQL) were invoked.
Every sample call threw "Cannot read properties of undefined (reading
'assertConnection')" and degraded LLM descriptions to metadata-only
prompts. Call the methods through the connector instead.
Without these, even after the primary-key probe is allowed to fail softly,
the scan ends up with 0 validated relationships and an empty `joins:` block
in every shard YAML.
* test(scan): cover table-ref helpers
* feat(scan): plumb tableScope through live-database introspection port
* feat(scan): apply tableScope during metadata fetch
* feat(scan): enforce table scope at fetch boundary
* feat(scan): pool Snowflake sessions and batch enrichment for faster ingest (#206)
* feat(cli): add RSA key-pair auth option to Snowflake setup wizard
Extends the interactive Snowflake setup flow with an authentication-method
prompt (password vs RSA/JWT key-pair). The RSA branch collects a private-key
path (env/file/absolute) and an optional passphrase; the resulting connection
config records `authMethod: 'rsa'` with `privateKey` and `passphrase` instead
of `password`.
* feat(scan): pool Snowflake sessions
* fix(scan): reuse structural snapshots and cleanup connectors
* feat(scan): parallelize relationship profiling
* feat(scan): batch table description generation
* docs: document Snowflake ingest concurrency knobs
* fix(scan): close Snowflake ingest perf verification gaps
* fix(scan): keep batched description failure bounded
* feat(scan): dispatch query-history probes by connection driver
Extract historic-sql dialect resolution into a shared helper so the
status-project readiness check and the local ingest factory agree on
which connections enable query history and which probe to run. The
status command now picks the postgres/snowflake/bigquery probe based on
the connection's driver instead of always reporting against postgres,
which previously caused snowflake connections with queryHistory.enabled
to surface a misleading "driver is snowflake" failure.
Also drops a noisy console.warn from Snowflake primary-key discovery —
INFORMATION_SCHEMA.KEY_COLUMN_USAGE is commonly ungranted for read-only
roles and the FK + profiling paths handle the empty PK map already.
* fix(llm): allow StructuredOutput tool and raise maxTurns for generateObject
The Claude Code agent SDK announces an internal pseudo-tool named
StructuredOutput in the system/init message whenever outputFormat is set
to { type: 'json_schema' }. The runtime's isolation check built its
allowedToolIds set only from MCP tool ids and treated StructuredOutput
as an unexpected host-injected tool, so every generateObject call threw
"Claude Code runtime isolation failed: tools=StructuredOutput ..." and
the table-descriptions and relationship-LLM-proposal enrichment stages
recorded null output across the board.
Whitelist StructuredOutput specifically in generateObject's
allowedToolIds — the check also enforces missing_tools symmetry, so
generateText and runAgentLoop, which do not see StructuredOutput, must
not require it.
generateObject also ran with maxTurns: 1, which the model intermittently
breached when it emitted thinking text before the structured response.
Raised to 5 to give the schema-bound call enough headroom without
allowing unbounded loops. The existing tests now exercise the path with
an init message that announces StructuredOutput so the regression cannot
slip back in.
* chore(scripts): add ktx-reset.sh project-cleanup helper
Convenience script for repeatable ingest testing: takes a project
directory and prunes everything except ktx.yaml and .ktx/secrets/, so
the next ktx setup or ktx ingest run starts from a known-clean state.
2026-05-23 10:41:30 +02:00
|
|
|
profileConcurrency: 4,
|
2026-05-10 23:12:26 +02:00
|
|
|
validationConcurrency: 4,
|
|
|
|
|
},
|
|
|
|
|
},
|
|
|
|
|
});
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
it('round-trips through YAML with stable defaults', () => {
|
2026-05-14 17:39:31 +02:00
|
|
|
const serialized = serializeKtxProjectConfig(buildDefaultKtxProjectConfig());
|
2026-05-10 23:51:24 +02:00
|
|
|
const parsed = parseKtxProjectConfig(serialized);
|
2026-05-10 23:12:26 +02:00
|
|
|
|
2026-05-14 17:39:31 +02:00
|
|
|
expect(serialized).not.toContain('project:');
|
2026-05-14 01:43:06 +02:00
|
|
|
expect(serialized).not.toContain('live-database');
|
2026-05-19 16:40:01 +02:00
|
|
|
expect(serialized).toContain(' embeddings:\n backend: none\n dimensions: 8');
|
2026-05-14 01:43:06 +02:00
|
|
|
expect(parsed.ingest.adapters).toEqual([]);
|
2026-05-10 23:12:26 +02:00
|
|
|
expect(parsed.ingest.embeddings).toEqual({
|
2026-05-19 16:40:01 +02:00
|
|
|
backend: 'none',
|
2026-05-10 23:12:26 +02:00
|
|
|
dimensions: 8,
|
|
|
|
|
});
|
|
|
|
|
});
|
|
|
|
|
|
2026-05-13 13:55:21 +02:00
|
|
|
it('parses and serializes setup warehouse metadata without setup progress', () => {
|
2026-05-10 23:51:24 +02:00
|
|
|
const config = parseKtxProjectConfig(`
|
2026-05-10 23:12:26 +02:00
|
|
|
setup:
|
|
|
|
|
database_connection_ids:
|
|
|
|
|
- warehouse
|
|
|
|
|
- analytics
|
|
|
|
|
connections:
|
|
|
|
|
warehouse:
|
|
|
|
|
driver: postgres
|
|
|
|
|
url: env:WAREHOUSE_URL
|
|
|
|
|
`);
|
|
|
|
|
|
|
|
|
|
expect(config.setup).toEqual({
|
|
|
|
|
database_connection_ids: ['warehouse', 'analytics'],
|
|
|
|
|
});
|
|
|
|
|
|
2026-05-10 23:51:24 +02:00
|
|
|
const serialized = serializeKtxProjectConfig(config);
|
2026-05-10 23:12:26 +02:00
|
|
|
expect(serialized).toContain('setup:');
|
|
|
|
|
expect(serialized).toContain('database_connection_ids:');
|
2026-05-13 13:55:21 +02:00
|
|
|
expect(serialized).not.toContain('completed_steps:');
|
2026-05-10 23:12:26 +02:00
|
|
|
});
|
|
|
|
|
|
2026-06-09 13:05:15 +02:00
|
|
|
it('parses and serializes a warehouse connection marked execute-only (scan_enabled: false)', () => {
|
|
|
|
|
const config = parseKtxProjectConfig(`
|
|
|
|
|
connections:
|
|
|
|
|
public_bq:
|
|
|
|
|
driver: bigquery
|
|
|
|
|
scan_enabled: false
|
|
|
|
|
`);
|
|
|
|
|
|
|
|
|
|
expect(config.connections.public_bq).toMatchObject({ driver: 'bigquery', scan_enabled: false });
|
|
|
|
|
expect(serializeKtxProjectConfig(config)).toContain('scan_enabled: false');
|
|
|
|
|
});
|
|
|
|
|
|
2026-05-10 23:12:26 +02:00
|
|
|
it('parses global direct Anthropic LLM config', () => {
|
2026-05-10 23:51:24 +02:00
|
|
|
const config = parseKtxProjectConfig(`
|
2026-05-10 23:12:26 +02:00
|
|
|
llm:
|
|
|
|
|
provider:
|
|
|
|
|
backend: anthropic
|
|
|
|
|
anthropic:
|
|
|
|
|
api_key: env:ANTHROPIC_API_KEY
|
|
|
|
|
models:
|
|
|
|
|
default: claude-sonnet-4-6
|
|
|
|
|
triage: claude-haiku-4-5
|
|
|
|
|
repair: claude-opus-4-7
|
|
|
|
|
promptCaching:
|
|
|
|
|
enabled: false
|
|
|
|
|
ingest:
|
|
|
|
|
workUnits:
|
|
|
|
|
stepBudget: 30
|
|
|
|
|
maxConcurrency: 2
|
|
|
|
|
failureMode: abort
|
|
|
|
|
`);
|
|
|
|
|
|
|
|
|
|
expect(config.llm).toMatchObject({
|
|
|
|
|
provider: {
|
|
|
|
|
backend: 'anthropic',
|
|
|
|
|
anthropic: { api_key: 'env:ANTHROPIC_API_KEY' }, // pragma: allowlist secret
|
|
|
|
|
},
|
|
|
|
|
models: {
|
|
|
|
|
default: 'claude-sonnet-4-6',
|
|
|
|
|
triage: 'claude-haiku-4-5',
|
|
|
|
|
repair: 'claude-opus-4-7',
|
|
|
|
|
},
|
|
|
|
|
promptCaching: { enabled: false },
|
|
|
|
|
});
|
|
|
|
|
expect(config.ingest.workUnits).toEqual({
|
|
|
|
|
stepBudget: 30,
|
|
|
|
|
maxConcurrency: 2,
|
|
|
|
|
failureMode: 'abort',
|
|
|
|
|
});
|
|
|
|
|
});
|
|
|
|
|
|
feat(cli): profile ingest runs and split model vs tool time (#249)
* feat(cli): profile ingest runs to find where wall-clock time goes
Add opt-in profiling for `ktx ingest`. Each timed phase, work unit, and
agent loop now records durationMs / step count / token usage in the
trace, and a post-run aggregator rolls them up into a "where did the
time go" report printed to stderr.
Enable per run with KTX_PROFILE_INGEST (1/true -> human table, json ->
raw structured profile) or persistently via `ingest.profile` in
ktx.yaml. The json form emits raw milliseconds, token counts, and a
summary.headline one-line diagnosis so coding agents can parse it
directly; json wins when both env and config request profiling.
- runtime-port: RunLoopMetrics (totalMs, usage, stepCount,
stepBoundariesMs) plus onMetrics callbacks on text/object generation
- ai-sdk + claude-code runtimes: capture per-loop timing and token usage
- work-unit-executor and stages 3/4: thread metrics into trace events
- ingest-bundle.runner: time worktree / triage / clustering / index /
reconcile / squash phases and emit the profile in a finally block
(best-effort; never affects the run outcome)
- ingest-profile: new trace+transcript aggregator with table/json formatters
- config: ingest.profile flag; docs: profiling section in ktx-ingest.mdx
* fix(cli): flush tool-call logs before reading ingest profile
Tool transcripts are appended fire-and-forget so the agent hot path never
blocks on logging. The ingest profiler read them before the writes settled,
so per-work-unit toolMs (and the model-vs-tool split derived from it) could
be incomplete. Track in-flight appends and expose flushToolCallLogs() —
bounded by a timeout so it can never hang — and flush before the profiler
reads the transcript.
2026-06-01 15:49:17 +02:00
|
|
|
it('parses the ingest.profile flag (false default, true, or "json")', () => {
|
|
|
|
|
expect(parseKtxProjectConfig('ingest:\n adapters: []\n').ingest.profile).toBe(false);
|
|
|
|
|
expect(parseKtxProjectConfig('ingest:\n profile: true\n').ingest.profile).toBe(true);
|
|
|
|
|
expect(parseKtxProjectConfig('ingest:\n profile: json\n').ingest.profile).toBe('json');
|
|
|
|
|
});
|
|
|
|
|
|
feat(cli): add ingest LLM rate-limit governor with paced retries (#261)
* feat(cli): add ingest rate limit governor
* feat(cli): wire ingest rate-limit config
* feat(cli): report provider rate-limit signals
* feat(cli): show ingest rate-limit waits
* fix(cli): complete rate-limit event coverage
* fix(cli): abort ingest provider calls cleanly
* fix(cli): propagate ingest cancellation
* fix(cli): reject pre-aborted ingest rate-limit waits
* fix(cli): honor Claude rate-limit reset waits
* fix(cli): retry thrown Codex rate-limit failures
* fix(cli): type Claude rate-limit result details
* fix(cli): emit ingest rate-limit countdowns from rejected signals
* fix(cli): report ai sdk rate-limit header utilization
* fix(cli): gate LLM rate-limit retries on the governor budget
The AI SDK and Codex runtimes retried 429 / opaque rate-limit failures up
to 6-7 times with no backoff when constructed without a RateLimitGovernor
(scan, memory, setup) or with pacing disabled, ignoring Retry-After and
worsening the limit. The outer retry loop only cooperates with the
governor's pause, so without active pacing there is no backoff to apply.
Route the retry bound through a single source: RateLimitGovernor
.maxRetryAttempts(), which returns retry.maxAttempts when enabled and 1
(no outer retry) when absent or disabled. All three runtimes (ai-sdk,
codex, claude-code) now use it, so ingest.rateLimit.retry.maxAttempts
genuinely controls attempts and the hard-coded 6 (plus Codex's off-by-one
extra attempt) is gone. Backend-native retry (e.g. the AI SDK's maxRetries)
still handles transient 429s.
Also correct the ktx.yaml docs for maxWaitMs (caps each wait, not the whole
run) and maxAttempts, and sync uv.lock ktx-sl/ktx-daemon to 0.9.0.
2026-06-05 12:10:27 +02:00
|
|
|
it('defaults ingest rate-limit settings', () => {
|
|
|
|
|
const config = buildDefaultKtxProjectConfig();
|
|
|
|
|
expect(config.ingest.rateLimit).toEqual({
|
|
|
|
|
enabled: true,
|
|
|
|
|
throttleThreshold: 0.8,
|
|
|
|
|
minConcurrencyUnderPressure: 1,
|
|
|
|
|
retry: {
|
|
|
|
|
maxAttempts: 6,
|
|
|
|
|
baseDelayMs: 1_000,
|
|
|
|
|
maxDelayMs: 60_000,
|
|
|
|
|
jitter: true,
|
|
|
|
|
},
|
|
|
|
|
});
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
it('validates ingest rate-limit retry settings', () => {
|
|
|
|
|
const config = parseKtxProjectConfig(`
|
|
|
|
|
llm:
|
|
|
|
|
provider:
|
|
|
|
|
backend: none
|
|
|
|
|
ingest:
|
|
|
|
|
rateLimit:
|
|
|
|
|
enabled: true
|
|
|
|
|
throttleThreshold: 0.7
|
|
|
|
|
minConcurrencyUnderPressure: 2
|
|
|
|
|
maxWaitMs: 300000
|
|
|
|
|
retry:
|
|
|
|
|
maxAttempts: 4
|
|
|
|
|
baseDelayMs: 500
|
|
|
|
|
maxDelayMs: 30000
|
|
|
|
|
jitter: false
|
|
|
|
|
`);
|
|
|
|
|
expect(config.ingest.rateLimit).toEqual({
|
|
|
|
|
enabled: true,
|
|
|
|
|
throttleThreshold: 0.7,
|
|
|
|
|
minConcurrencyUnderPressure: 2,
|
|
|
|
|
maxWaitMs: 300_000,
|
|
|
|
|
retry: {
|
|
|
|
|
maxAttempts: 4,
|
|
|
|
|
baseDelayMs: 500,
|
|
|
|
|
maxDelayMs: 30_000,
|
|
|
|
|
jitter: false,
|
|
|
|
|
},
|
|
|
|
|
});
|
|
|
|
|
});
|
|
|
|
|
|
2026-05-10 23:12:26 +02:00
|
|
|
it('parses global Vertex LLM config', () => {
|
2026-05-10 23:51:24 +02:00
|
|
|
const config = parseKtxProjectConfig(`
|
2026-05-10 23:12:26 +02:00
|
|
|
llm:
|
|
|
|
|
provider:
|
|
|
|
|
backend: vertex
|
|
|
|
|
vertex:
|
|
|
|
|
project: local-gcp-project
|
|
|
|
|
location: us-east5
|
|
|
|
|
models:
|
|
|
|
|
default: claude-sonnet-4-6
|
|
|
|
|
triage: claude-haiku-4-5
|
|
|
|
|
`);
|
|
|
|
|
|
|
|
|
|
expect(config.llm.provider.backend).toBe('vertex');
|
|
|
|
|
expect(config.llm.provider.vertex).toEqual({ project: 'local-gcp-project', location: 'us-east5' });
|
|
|
|
|
expect(config.llm.models).toEqual({
|
|
|
|
|
default: 'claude-sonnet-4-6',
|
|
|
|
|
triage: 'claude-haiku-4-5',
|
|
|
|
|
});
|
|
|
|
|
});
|
|
|
|
|
|
2026-05-21 10:38:23 +02:00
|
|
|
it('requires a non-empty Vertex location when the Vertex provider block is present', () => {
|
|
|
|
|
const yaml = `
|
|
|
|
|
llm:
|
|
|
|
|
provider:
|
|
|
|
|
backend: vertex
|
|
|
|
|
vertex:
|
|
|
|
|
project: local-gcp-project
|
|
|
|
|
`;
|
|
|
|
|
|
|
|
|
|
expect(() => parseKtxProjectConfig(yaml)).toThrow(/llm\.provider\.vertex\.location/);
|
|
|
|
|
|
|
|
|
|
const validation = validateKtxProjectConfig(yaml);
|
|
|
|
|
expect(validation.ok).toBe(false);
|
|
|
|
|
expect(validation.issues).toEqual(
|
|
|
|
|
expect.arrayContaining([
|
|
|
|
|
expect.objectContaining({
|
|
|
|
|
path: 'llm.provider.vertex.location',
|
|
|
|
|
}),
|
|
|
|
|
]),
|
|
|
|
|
);
|
|
|
|
|
});
|
|
|
|
|
|
2026-05-16 12:06:34 +02:00
|
|
|
it('parses Claude Code as a first-class LLM backend', () => {
|
|
|
|
|
const config = parseKtxProjectConfig(`
|
|
|
|
|
llm:
|
|
|
|
|
provider:
|
|
|
|
|
backend: claude-code
|
|
|
|
|
models:
|
|
|
|
|
default: sonnet
|
|
|
|
|
triage: haiku
|
|
|
|
|
candidateExtraction: sonnet
|
|
|
|
|
curator: sonnet
|
|
|
|
|
reconcile: sonnet
|
|
|
|
|
repair: opus
|
|
|
|
|
`);
|
|
|
|
|
|
|
|
|
|
expect(config.llm.provider.backend).toBe('claude-code');
|
|
|
|
|
expect(config.llm.models).toEqual({
|
|
|
|
|
default: 'sonnet',
|
|
|
|
|
triage: 'haiku',
|
|
|
|
|
candidateExtraction: 'sonnet',
|
|
|
|
|
curator: 'sonnet',
|
|
|
|
|
reconcile: 'sonnet',
|
|
|
|
|
repair: 'opus',
|
|
|
|
|
});
|
|
|
|
|
});
|
|
|
|
|
|
feat: add codex llm backend for ktx runtime work (#253)
* feat: add codex sdk runner foundation
* feat: parse codex runtime events
* feat: expose codex runtime mcp tools
* feat: add codex llm runtime
* feat: wire codex llm backend
* test: avoid Array.fromAsync in codex runner test
* docs: document codex llm backend
* fix: tighten codex runtime config ownership
* fix: use codex sdk env and thread options
* fix: parse codex sdk event shapes
* test: add codex backend live smoke
* docs: clarify codex backend isolation
* fix: drive codex loop metrics from mcp events
* fix: enforce codex local step budget
* docs: disclose codex isolation limits
* fix: count all codex agent steps and stream step callbacks live
The agent-loop step budget only counted completed mcp_tool_call items, so
built-in command_execution steps (which the public Codex SDK/CLI surface can
still expose) never decremented the budget, letting ingest/reconciliation run
past stepBudget until Codex stopped on its own. onStepFinish was also replayed
only after the whole stream drained, so live work_unit_step / reconciliation
progress appeared stuck until the Codex process exited.
collectEvents is now the single live step accumulator: it counts every
completed agent-action item via a shared isCompletedAgentStep predicate
(command_execution, mcp_tool_call, file_change, web_search), fires onStepFinish
as each step completes, and enforces the budget on that broader count. A
no-tool turn still counts as one step. toolFailures stays MCP-specific, since a
non-zero command exit is normal agent exploration, not a loop failure.
* test: align ingest llm-guard assertions with codex backend
The skip-llm ingest guard message now lists codex as a valid backend and
mentions a Claude Code/Codex session plus a codex setup hint, but this slow
suite test still asserted the pre-codex wording. Update it to match the
production message (already covered by the local-bundle-runtime unit test) and
add the codex setup-line assertion.
* fix: treat codex error:null tool calls as success
The Codex SDK serializes error: null on successful mcp_tool_call items, so
the failure check (item.error !== undefined) flagged every successful tool
call as failed with the empty-payload default "Codex turn failed". This
killed every ingest work unit under the codex backend before it could
produce a patch.
Key on status === 'failed' (authoritative, always set) and only treat a
populated error object as a failure. Add a regression test built from a
verbatim real-SDK event capture.
* fix: default codex backend to gpt-5.5 and report real probe errors
The previous default gpt-5.3-codex is an API-key-only model that the OpenAI
API rejects under ChatGPT-account (subscription) auth, so codex status/setup
failed with a misleading "authentication is not usable" message even though
auth was fine.
- Default codex model is now gpt-5.5 (works on both subscription and API-key
auth); the curated setup picker offers gpt-5.5 / gpt-5.4 / gpt-5.4-mini and
keeps free-form entry for account-specific ids (e.g. gpt-5.3-codex-spark).
- runCodexAuthProbe now distinguishes "model not available" from an auth
failure and surfaces the real API error: collectEvents retains stream
events when the SDK throws on a non-zero exit, and the API error JSON
envelope is unwrapped to its human-readable message.
- The Codex isolation warning now renders inside the clack setup frame.
- Docs updated to gpt-5.5 with a note that *-codex ids require API-key auth.
* fix: require llm.models.default in status and match codex probe remediation
Status reported a project ready when a non-none LLM backend was configured
without llm.models.default, but the runtime (resolveModelSlots) hard-requires
it, so ingest/scan/memory threw after `ktx status` said the project was usable.
buildLlmStatus now fails for any non-none backend missing models.default and no
longer invents a fallback model for claude-code/codex.
Codex probe failures now carry a category-matched fix: a model-access failure
steers the user at llm.models.default instead of the auth/install remediation.
runCodexAuthProbe returns the fix and status consumes it; the message stays
self-sufficient so setup output is unchanged.
Docs: README now lists the codex backend and local Codex auth; ktx-setup.mdx
states --llm-model only accepts codex/default or gpt-*/codex-* ids.
Repaired four doctor fixtures that configured a backend without models.default
(the now-correctly-blocked config) and added coverage for the new behavior.
2026-06-02 13:57:11 +02:00
|
|
|
it('parses Codex as a first-class LLM backend', () => {
|
|
|
|
|
const config = parseKtxProjectConfig(`
|
|
|
|
|
llm:
|
|
|
|
|
provider:
|
|
|
|
|
backend: codex
|
|
|
|
|
models:
|
|
|
|
|
default: gpt-5.3-codex
|
|
|
|
|
triage: gpt-5.3-codex
|
|
|
|
|
candidateExtraction: gpt-5.3-codex
|
|
|
|
|
curator: gpt-5.3-codex
|
|
|
|
|
reconcile: gpt-5.3-codex
|
|
|
|
|
repair: gpt-5.3-codex
|
|
|
|
|
`);
|
|
|
|
|
|
|
|
|
|
expect(config.llm.provider.backend).toBe('codex');
|
|
|
|
|
expect(config.llm.models).toEqual({
|
|
|
|
|
default: 'gpt-5.3-codex',
|
|
|
|
|
triage: 'gpt-5.3-codex',
|
|
|
|
|
candidateExtraction: 'gpt-5.3-codex',
|
|
|
|
|
curator: 'gpt-5.3-codex',
|
|
|
|
|
reconcile: 'gpt-5.3-codex',
|
|
|
|
|
repair: 'gpt-5.3-codex',
|
|
|
|
|
});
|
|
|
|
|
});
|
|
|
|
|
|
2026-05-10 23:12:26 +02:00
|
|
|
it('parses gateway LLM, OpenAI scan embeddings, and sentence-transformers ingest embeddings', () => {
|
2026-05-10 23:51:24 +02:00
|
|
|
const config = parseKtxProjectConfig(`
|
2026-05-10 23:12:26 +02:00
|
|
|
llm:
|
|
|
|
|
provider:
|
|
|
|
|
backend: gateway
|
|
|
|
|
gateway:
|
|
|
|
|
api_key: env:AI_GATEWAY_API_KEY
|
|
|
|
|
base_url: https://gateway.example/v1
|
|
|
|
|
models:
|
|
|
|
|
default: anthropic/claude-sonnet-4-6
|
|
|
|
|
ingest:
|
|
|
|
|
embeddings:
|
|
|
|
|
backend: sentence-transformers
|
|
|
|
|
model: all-MiniLM-L6-v2
|
|
|
|
|
dimensions: 384
|
|
|
|
|
sentenceTransformers:
|
|
|
|
|
base_url: http://127.0.0.1:18081
|
|
|
|
|
pathPrefix: ""
|
|
|
|
|
batchSize: 16
|
|
|
|
|
scan:
|
|
|
|
|
enrichment:
|
|
|
|
|
mode: llm
|
|
|
|
|
embeddings:
|
|
|
|
|
backend: openai
|
|
|
|
|
model: text-embedding-3-small
|
|
|
|
|
dimensions: 1536
|
|
|
|
|
openai:
|
|
|
|
|
api_key: env:OPENAI_API_KEY
|
|
|
|
|
batchSize: 32
|
|
|
|
|
`);
|
|
|
|
|
|
|
|
|
|
expect(config.ingest.embeddings).toMatchObject({
|
|
|
|
|
backend: 'sentence-transformers',
|
|
|
|
|
model: 'all-MiniLM-L6-v2',
|
|
|
|
|
dimensions: 384,
|
|
|
|
|
sentenceTransformers: { base_url: 'http://127.0.0.1:18081', pathPrefix: '' },
|
|
|
|
|
batchSize: 16,
|
|
|
|
|
});
|
|
|
|
|
expect(config.llm.models.default).toBe('anthropic/claude-sonnet-4-6');
|
|
|
|
|
expect(config.scan.enrichment.mode).toBe('llm');
|
|
|
|
|
expect(config.scan.enrichment.embeddings?.dimensions).toBe(1536);
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
it('parses scan relationship settings', () => {
|
2026-05-10 23:51:24 +02:00
|
|
|
const config = parseKtxProjectConfig(`
|
2026-05-10 23:12:26 +02:00
|
|
|
scan:
|
|
|
|
|
relationships:
|
|
|
|
|
enabled: false
|
2026-05-13 15:55:00 +02:00
|
|
|
llmProposals: false
|
|
|
|
|
validationRequiredForManifest: true
|
|
|
|
|
acceptThreshold: 0.91
|
|
|
|
|
reviewThreshold: 0.61
|
|
|
|
|
maxLlmTablesPerBatch: 12
|
|
|
|
|
maxCandidatesPerColumn: 7
|
|
|
|
|
profileSampleRows: 500
|
fix(snowflake): unblock multi-schema ingest and relationship discovery (#204)
* feat(setup): drop redundant Snowflake schema prompt; fall back to free-text on listSchemas failure
Snowflake setup previously asked for a single schema as free text, then
ran a multiselect against the discovered schemas — two schema questions
back-to-back, with the first being only a session bootstrap. The SDK's
`schema` is optional, so the bootstrap step is unnecessary.
- Remove the free-text Snowflake schema prompt; only pass `schema` to
snowflake-sdk when one is configured.
- When `listSchemas()` fails (e.g. role lacks SHOW SCHEMAS), prompt the
user for a comma-separated list, persist it as `schema_names`, and use
it as both the table-list filter and the multiselect default. Applies
to every driver with a scope-discovery spec, not just Snowflake.
- Update docs to lead with `schema_names`; keep `schema_name` as a
documented single-schema shorthand.
* fix(snowflake): keep introspecting when primary-key discovery is denied
The PK query joins INFORMATION_SCHEMA.TABLE_CONSTRAINTS and
INFORMATION_SCHEMA.KEY_COLUMN_USAGE, which require grants the
connection role may not have. Previously a 'SQL compilation error:
Object ANALYTICS.INFORMATION_SCHEMA.KEY_COLUMN_USAGE does not exist
or not authorized' aborted the entire introspect — schemas, columns,
and row counts were all discarded over a missing nice-to-have.
Wrap the constraint query in try/catch, log a one-line warning per
schema, and return an empty PK map. Columns end up with
primaryKey=false; relationship inference still has FK and profiling
to fall back on.
* fix(scan): unblock relationship discovery on Snowflake
Two adjacent bugs prevented the scan's relationship pipeline from producing
any joins on a Snowflake warehouse:
- relationship-profiling.ts fell through to a default `GROUP_CONCAT` branch
for unknown drivers. Snowflake has no GROUP_CONCAT, so every per-table
profile query failed with "Unknown function GROUP_CONCAT". Add an explicit
Snowflake branch that uses LISTAGG with a literal '\x1f' delimiter
(Snowflake requires the delimiter to be a constant, so CHR(31) is rejected).
- description-generation.ts destructured `connector.sampleTable` and
`connector.sampleColumn` into bare locals, losing the `this` binding when
the class-method connectors (Snowflake, Postgres, MySQL) were invoked.
Every sample call threw "Cannot read properties of undefined (reading
'assertConnection')" and degraded LLM descriptions to metadata-only
prompts. Call the methods through the connector instead.
Without these, even after the primary-key probe is allowed to fail softly,
the scan ends up with 0 validated relationships and an empty `joins:` block
in every shard YAML.
* test(scan): cover table-ref helpers
* feat(scan): plumb tableScope through live-database introspection port
* feat(scan): apply tableScope during metadata fetch
* feat(scan): enforce table scope at fetch boundary
* feat(scan): pool Snowflake sessions and batch enrichment for faster ingest (#206)
* feat(cli): add RSA key-pair auth option to Snowflake setup wizard
Extends the interactive Snowflake setup flow with an authentication-method
prompt (password vs RSA/JWT key-pair). The RSA branch collects a private-key
path (env/file/absolute) and an optional passphrase; the resulting connection
config records `authMethod: 'rsa'` with `privateKey` and `passphrase` instead
of `password`.
* feat(scan): pool Snowflake sessions
* fix(scan): reuse structural snapshots and cleanup connectors
* feat(scan): parallelize relationship profiling
* feat(scan): batch table description generation
* docs: document Snowflake ingest concurrency knobs
* fix(scan): close Snowflake ingest perf verification gaps
* fix(scan): keep batched description failure bounded
* feat(scan): dispatch query-history probes by connection driver
Extract historic-sql dialect resolution into a shared helper so the
status-project readiness check and the local ingest factory agree on
which connections enable query history and which probe to run. The
status command now picks the postgres/snowflake/bigquery probe based on
the connection's driver instead of always reporting against postgres,
which previously caused snowflake connections with queryHistory.enabled
to surface a misleading "driver is snowflake" failure.
Also drops a noisy console.warn from Snowflake primary-key discovery —
INFORMATION_SCHEMA.KEY_COLUMN_USAGE is commonly ungranted for read-only
roles and the FK + profiling paths handle the empty PK map already.
* fix(llm): allow StructuredOutput tool and raise maxTurns for generateObject
The Claude Code agent SDK announces an internal pseudo-tool named
StructuredOutput in the system/init message whenever outputFormat is set
to { type: 'json_schema' }. The runtime's isolation check built its
allowedToolIds set only from MCP tool ids and treated StructuredOutput
as an unexpected host-injected tool, so every generateObject call threw
"Claude Code runtime isolation failed: tools=StructuredOutput ..." and
the table-descriptions and relationship-LLM-proposal enrichment stages
recorded null output across the board.
Whitelist StructuredOutput specifically in generateObject's
allowedToolIds — the check also enforces missing_tools symmetry, so
generateText and runAgentLoop, which do not see StructuredOutput, must
not require it.
generateObject also ran with maxTurns: 1, which the model intermittently
breached when it emitted thinking text before the structured response.
Raised to 5 to give the schema-bound call enough headroom without
allowing unbounded loops. The existing tests now exercise the path with
an init message that announces StructuredOutput so the regression cannot
slip back in.
* chore(scripts): add ktx-reset.sh project-cleanup helper
Convenience script for repeatable ingest testing: takes a project
directory and prunes everything except ktx.yaml and .ktx/secrets/, so
the next ktx setup or ktx ingest run starts from a known-clean state.
2026-05-23 10:41:30 +02:00
|
|
|
profileConcurrency: 3
|
2026-05-13 15:55:00 +02:00
|
|
|
validationConcurrency: 2
|
|
|
|
|
validationBudget: 0
|
2026-05-10 23:12:26 +02:00
|
|
|
`);
|
|
|
|
|
|
|
|
|
|
expect(config.scan.relationships).toEqual({
|
|
|
|
|
enabled: false,
|
|
|
|
|
llmProposals: false,
|
|
|
|
|
validationRequiredForManifest: true,
|
|
|
|
|
acceptThreshold: 0.91,
|
|
|
|
|
reviewThreshold: 0.61,
|
|
|
|
|
maxLlmTablesPerBatch: 12,
|
|
|
|
|
maxCandidatesPerColumn: 7,
|
|
|
|
|
profileSampleRows: 500,
|
fix(snowflake): unblock multi-schema ingest and relationship discovery (#204)
* feat(setup): drop redundant Snowflake schema prompt; fall back to free-text on listSchemas failure
Snowflake setup previously asked for a single schema as free text, then
ran a multiselect against the discovered schemas — two schema questions
back-to-back, with the first being only a session bootstrap. The SDK's
`schema` is optional, so the bootstrap step is unnecessary.
- Remove the free-text Snowflake schema prompt; only pass `schema` to
snowflake-sdk when one is configured.
- When `listSchemas()` fails (e.g. role lacks SHOW SCHEMAS), prompt the
user for a comma-separated list, persist it as `schema_names`, and use
it as both the table-list filter and the multiselect default. Applies
to every driver with a scope-discovery spec, not just Snowflake.
- Update docs to lead with `schema_names`; keep `schema_name` as a
documented single-schema shorthand.
* fix(snowflake): keep introspecting when primary-key discovery is denied
The PK query joins INFORMATION_SCHEMA.TABLE_CONSTRAINTS and
INFORMATION_SCHEMA.KEY_COLUMN_USAGE, which require grants the
connection role may not have. Previously a 'SQL compilation error:
Object ANALYTICS.INFORMATION_SCHEMA.KEY_COLUMN_USAGE does not exist
or not authorized' aborted the entire introspect — schemas, columns,
and row counts were all discarded over a missing nice-to-have.
Wrap the constraint query in try/catch, log a one-line warning per
schema, and return an empty PK map. Columns end up with
primaryKey=false; relationship inference still has FK and profiling
to fall back on.
* fix(scan): unblock relationship discovery on Snowflake
Two adjacent bugs prevented the scan's relationship pipeline from producing
any joins on a Snowflake warehouse:
- relationship-profiling.ts fell through to a default `GROUP_CONCAT` branch
for unknown drivers. Snowflake has no GROUP_CONCAT, so every per-table
profile query failed with "Unknown function GROUP_CONCAT". Add an explicit
Snowflake branch that uses LISTAGG with a literal '\x1f' delimiter
(Snowflake requires the delimiter to be a constant, so CHR(31) is rejected).
- description-generation.ts destructured `connector.sampleTable` and
`connector.sampleColumn` into bare locals, losing the `this` binding when
the class-method connectors (Snowflake, Postgres, MySQL) were invoked.
Every sample call threw "Cannot read properties of undefined (reading
'assertConnection')" and degraded LLM descriptions to metadata-only
prompts. Call the methods through the connector instead.
Without these, even after the primary-key probe is allowed to fail softly,
the scan ends up with 0 validated relationships and an empty `joins:` block
in every shard YAML.
* test(scan): cover table-ref helpers
* feat(scan): plumb tableScope through live-database introspection port
* feat(scan): apply tableScope during metadata fetch
* feat(scan): enforce table scope at fetch boundary
* feat(scan): pool Snowflake sessions and batch enrichment for faster ingest (#206)
* feat(cli): add RSA key-pair auth option to Snowflake setup wizard
Extends the interactive Snowflake setup flow with an authentication-method
prompt (password vs RSA/JWT key-pair). The RSA branch collects a private-key
path (env/file/absolute) and an optional passphrase; the resulting connection
config records `authMethod: 'rsa'` with `privateKey` and `passphrase` instead
of `password`.
* feat(scan): pool Snowflake sessions
* fix(scan): reuse structural snapshots and cleanup connectors
* feat(scan): parallelize relationship profiling
* feat(scan): batch table description generation
* docs: document Snowflake ingest concurrency knobs
* fix(scan): close Snowflake ingest perf verification gaps
* fix(scan): keep batched description failure bounded
* feat(scan): dispatch query-history probes by connection driver
Extract historic-sql dialect resolution into a shared helper so the
status-project readiness check and the local ingest factory agree on
which connections enable query history and which probe to run. The
status command now picks the postgres/snowflake/bigquery probe based on
the connection's driver instead of always reporting against postgres,
which previously caused snowflake connections with queryHistory.enabled
to surface a misleading "driver is snowflake" failure.
Also drops a noisy console.warn from Snowflake primary-key discovery —
INFORMATION_SCHEMA.KEY_COLUMN_USAGE is commonly ungranted for read-only
roles and the FK + profiling paths handle the empty PK map already.
* fix(llm): allow StructuredOutput tool and raise maxTurns for generateObject
The Claude Code agent SDK announces an internal pseudo-tool named
StructuredOutput in the system/init message whenever outputFormat is set
to { type: 'json_schema' }. The runtime's isolation check built its
allowedToolIds set only from MCP tool ids and treated StructuredOutput
as an unexpected host-injected tool, so every generateObject call threw
"Claude Code runtime isolation failed: tools=StructuredOutput ..." and
the table-descriptions and relationship-LLM-proposal enrichment stages
recorded null output across the board.
Whitelist StructuredOutput specifically in generateObject's
allowedToolIds — the check also enforces missing_tools symmetry, so
generateText and runAgentLoop, which do not see StructuredOutput, must
not require it.
generateObject also ran with maxTurns: 1, which the model intermittently
breached when it emitted thinking text before the structured response.
Raised to 5 to give the schema-bound call enough headroom without
allowing unbounded loops. The existing tests now exercise the path with
an init message that announces StructuredOutput so the regression cannot
slip back in.
* chore(scripts): add ktx-reset.sh project-cleanup helper
Convenience script for repeatable ingest testing: takes a project
directory and prunes everything except ktx.yaml and .ktx/secrets/, so
the next ktx setup or ktx ingest run starts from a known-clean state.
2026-05-23 10:41:30 +02:00
|
|
|
profileConcurrency: 3,
|
2026-05-10 23:12:26 +02:00
|
|
|
validationConcurrency: 2,
|
|
|
|
|
validationBudget: 0,
|
|
|
|
|
});
|
2026-05-10 23:51:24 +02:00
|
|
|
expect(serializeKtxProjectConfig(config)).toContain('enabled: false');
|
|
|
|
|
expect(serializeKtxProjectConfig(config)).toContain('llmProposals: false');
|
|
|
|
|
expect(serializeKtxProjectConfig(config)).toContain('validationRequiredForManifest: true');
|
|
|
|
|
expect(serializeKtxProjectConfig(config)).toContain('acceptThreshold: 0.91');
|
|
|
|
|
expect(serializeKtxProjectConfig(config)).toContain('reviewThreshold: 0.61');
|
|
|
|
|
expect(serializeKtxProjectConfig(config)).toContain('maxLlmTablesPerBatch: 12');
|
|
|
|
|
expect(serializeKtxProjectConfig(config)).toContain('maxCandidatesPerColumn: 7');
|
|
|
|
|
expect(serializeKtxProjectConfig(config)).toContain('profileSampleRows: 500');
|
fix(snowflake): unblock multi-schema ingest and relationship discovery (#204)
* feat(setup): drop redundant Snowflake schema prompt; fall back to free-text on listSchemas failure
Snowflake setup previously asked for a single schema as free text, then
ran a multiselect against the discovered schemas — two schema questions
back-to-back, with the first being only a session bootstrap. The SDK's
`schema` is optional, so the bootstrap step is unnecessary.
- Remove the free-text Snowflake schema prompt; only pass `schema` to
snowflake-sdk when one is configured.
- When `listSchemas()` fails (e.g. role lacks SHOW SCHEMAS), prompt the
user for a comma-separated list, persist it as `schema_names`, and use
it as both the table-list filter and the multiselect default. Applies
to every driver with a scope-discovery spec, not just Snowflake.
- Update docs to lead with `schema_names`; keep `schema_name` as a
documented single-schema shorthand.
* fix(snowflake): keep introspecting when primary-key discovery is denied
The PK query joins INFORMATION_SCHEMA.TABLE_CONSTRAINTS and
INFORMATION_SCHEMA.KEY_COLUMN_USAGE, which require grants the
connection role may not have. Previously a 'SQL compilation error:
Object ANALYTICS.INFORMATION_SCHEMA.KEY_COLUMN_USAGE does not exist
or not authorized' aborted the entire introspect — schemas, columns,
and row counts were all discarded over a missing nice-to-have.
Wrap the constraint query in try/catch, log a one-line warning per
schema, and return an empty PK map. Columns end up with
primaryKey=false; relationship inference still has FK and profiling
to fall back on.
* fix(scan): unblock relationship discovery on Snowflake
Two adjacent bugs prevented the scan's relationship pipeline from producing
any joins on a Snowflake warehouse:
- relationship-profiling.ts fell through to a default `GROUP_CONCAT` branch
for unknown drivers. Snowflake has no GROUP_CONCAT, so every per-table
profile query failed with "Unknown function GROUP_CONCAT". Add an explicit
Snowflake branch that uses LISTAGG with a literal '\x1f' delimiter
(Snowflake requires the delimiter to be a constant, so CHR(31) is rejected).
- description-generation.ts destructured `connector.sampleTable` and
`connector.sampleColumn` into bare locals, losing the `this` binding when
the class-method connectors (Snowflake, Postgres, MySQL) were invoked.
Every sample call threw "Cannot read properties of undefined (reading
'assertConnection')" and degraded LLM descriptions to metadata-only
prompts. Call the methods through the connector instead.
Without these, even after the primary-key probe is allowed to fail softly,
the scan ends up with 0 validated relationships and an empty `joins:` block
in every shard YAML.
* test(scan): cover table-ref helpers
* feat(scan): plumb tableScope through live-database introspection port
* feat(scan): apply tableScope during metadata fetch
* feat(scan): enforce table scope at fetch boundary
* feat(scan): pool Snowflake sessions and batch enrichment for faster ingest (#206)
* feat(cli): add RSA key-pair auth option to Snowflake setup wizard
Extends the interactive Snowflake setup flow with an authentication-method
prompt (password vs RSA/JWT key-pair). The RSA branch collects a private-key
path (env/file/absolute) and an optional passphrase; the resulting connection
config records `authMethod: 'rsa'` with `privateKey` and `passphrase` instead
of `password`.
* feat(scan): pool Snowflake sessions
* fix(scan): reuse structural snapshots and cleanup connectors
* feat(scan): parallelize relationship profiling
* feat(scan): batch table description generation
* docs: document Snowflake ingest concurrency knobs
* fix(scan): close Snowflake ingest perf verification gaps
* fix(scan): keep batched description failure bounded
* feat(scan): dispatch query-history probes by connection driver
Extract historic-sql dialect resolution into a shared helper so the
status-project readiness check and the local ingest factory agree on
which connections enable query history and which probe to run. The
status command now picks the postgres/snowflake/bigquery probe based on
the connection's driver instead of always reporting against postgres,
which previously caused snowflake connections with queryHistory.enabled
to surface a misleading "driver is snowflake" failure.
Also drops a noisy console.warn from Snowflake primary-key discovery —
INFORMATION_SCHEMA.KEY_COLUMN_USAGE is commonly ungranted for read-only
roles and the FK + profiling paths handle the empty PK map already.
* fix(llm): allow StructuredOutput tool and raise maxTurns for generateObject
The Claude Code agent SDK announces an internal pseudo-tool named
StructuredOutput in the system/init message whenever outputFormat is set
to { type: 'json_schema' }. The runtime's isolation check built its
allowedToolIds set only from MCP tool ids and treated StructuredOutput
as an unexpected host-injected tool, so every generateObject call threw
"Claude Code runtime isolation failed: tools=StructuredOutput ..." and
the table-descriptions and relationship-LLM-proposal enrichment stages
recorded null output across the board.
Whitelist StructuredOutput specifically in generateObject's
allowedToolIds — the check also enforces missing_tools symmetry, so
generateText and runAgentLoop, which do not see StructuredOutput, must
not require it.
generateObject also ran with maxTurns: 1, which the model intermittently
breached when it emitted thinking text before the structured response.
Raised to 5 to give the schema-bound call enough headroom without
allowing unbounded loops. The existing tests now exercise the path with
an init message that announces StructuredOutput so the regression cannot
slip back in.
* chore(scripts): add ktx-reset.sh project-cleanup helper
Convenience script for repeatable ingest testing: takes a project
directory and prunes everything except ktx.yaml and .ktx/secrets/, so
the next ktx setup or ktx ingest run starts from a known-clean state.
2026-05-23 10:41:30 +02:00
|
|
|
expect(serializeKtxProjectConfig(config)).toContain('profileConcurrency: 3');
|
2026-05-10 23:51:24 +02:00
|
|
|
expect(serializeKtxProjectConfig(config)).toContain('validationConcurrency: 2');
|
|
|
|
|
expect(serializeKtxProjectConfig(config)).toContain('validationBudget: 0');
|
2026-05-10 23:12:26 +02:00
|
|
|
});
|
|
|
|
|
|
|
|
|
|
it('parses the scan relationship validation budget sentinel', () => {
|
2026-05-10 23:51:24 +02:00
|
|
|
const config = parseKtxProjectConfig(`
|
2026-05-10 23:12:26 +02:00
|
|
|
scan:
|
|
|
|
|
relationships:
|
2026-05-13 15:55:00 +02:00
|
|
|
validationBudget: all
|
2026-05-10 23:12:26 +02:00
|
|
|
`);
|
|
|
|
|
|
|
|
|
|
expect(config.scan.relationships.validationBudget).toBe('all');
|
2026-05-10 23:51:24 +02:00
|
|
|
expect(serializeKtxProjectConfig(config)).toContain('validationBudget: all');
|
2026-05-10 23:12:26 +02:00
|
|
|
});
|
|
|
|
|
|
2026-05-14 15:36:35 +02:00
|
|
|
it('rejects out-of-range scan relationship numeric settings', () => {
|
|
|
|
|
const yaml = `
|
2026-05-10 23:12:26 +02:00
|
|
|
scan:
|
|
|
|
|
relationships:
|
2026-05-13 15:55:00 +02:00
|
|
|
acceptThreshold: 2
|
|
|
|
|
reviewThreshold: -1
|
|
|
|
|
maxLlmTablesPerBatch: 0
|
|
|
|
|
maxCandidatesPerColumn: -4
|
|
|
|
|
profileSampleRows: 0
|
fix(snowflake): unblock multi-schema ingest and relationship discovery (#204)
* feat(setup): drop redundant Snowflake schema prompt; fall back to free-text on listSchemas failure
Snowflake setup previously asked for a single schema as free text, then
ran a multiselect against the discovered schemas — two schema questions
back-to-back, with the first being only a session bootstrap. The SDK's
`schema` is optional, so the bootstrap step is unnecessary.
- Remove the free-text Snowflake schema prompt; only pass `schema` to
snowflake-sdk when one is configured.
- When `listSchemas()` fails (e.g. role lacks SHOW SCHEMAS), prompt the
user for a comma-separated list, persist it as `schema_names`, and use
it as both the table-list filter and the multiselect default. Applies
to every driver with a scope-discovery spec, not just Snowflake.
- Update docs to lead with `schema_names`; keep `schema_name` as a
documented single-schema shorthand.
* fix(snowflake): keep introspecting when primary-key discovery is denied
The PK query joins INFORMATION_SCHEMA.TABLE_CONSTRAINTS and
INFORMATION_SCHEMA.KEY_COLUMN_USAGE, which require grants the
connection role may not have. Previously a 'SQL compilation error:
Object ANALYTICS.INFORMATION_SCHEMA.KEY_COLUMN_USAGE does not exist
or not authorized' aborted the entire introspect — schemas, columns,
and row counts were all discarded over a missing nice-to-have.
Wrap the constraint query in try/catch, log a one-line warning per
schema, and return an empty PK map. Columns end up with
primaryKey=false; relationship inference still has FK and profiling
to fall back on.
* fix(scan): unblock relationship discovery on Snowflake
Two adjacent bugs prevented the scan's relationship pipeline from producing
any joins on a Snowflake warehouse:
- relationship-profiling.ts fell through to a default `GROUP_CONCAT` branch
for unknown drivers. Snowflake has no GROUP_CONCAT, so every per-table
profile query failed with "Unknown function GROUP_CONCAT". Add an explicit
Snowflake branch that uses LISTAGG with a literal '\x1f' delimiter
(Snowflake requires the delimiter to be a constant, so CHR(31) is rejected).
- description-generation.ts destructured `connector.sampleTable` and
`connector.sampleColumn` into bare locals, losing the `this` binding when
the class-method connectors (Snowflake, Postgres, MySQL) were invoked.
Every sample call threw "Cannot read properties of undefined (reading
'assertConnection')" and degraded LLM descriptions to metadata-only
prompts. Call the methods through the connector instead.
Without these, even after the primary-key probe is allowed to fail softly,
the scan ends up with 0 validated relationships and an empty `joins:` block
in every shard YAML.
* test(scan): cover table-ref helpers
* feat(scan): plumb tableScope through live-database introspection port
* feat(scan): apply tableScope during metadata fetch
* feat(scan): enforce table scope at fetch boundary
* feat(scan): pool Snowflake sessions and batch enrichment for faster ingest (#206)
* feat(cli): add RSA key-pair auth option to Snowflake setup wizard
Extends the interactive Snowflake setup flow with an authentication-method
prompt (password vs RSA/JWT key-pair). The RSA branch collects a private-key
path (env/file/absolute) and an optional passphrase; the resulting connection
config records `authMethod: 'rsa'` with `privateKey` and `passphrase` instead
of `password`.
* feat(scan): pool Snowflake sessions
* fix(scan): reuse structural snapshots and cleanup connectors
* feat(scan): parallelize relationship profiling
* feat(scan): batch table description generation
* docs: document Snowflake ingest concurrency knobs
* fix(scan): close Snowflake ingest perf verification gaps
* fix(scan): keep batched description failure bounded
* feat(scan): dispatch query-history probes by connection driver
Extract historic-sql dialect resolution into a shared helper so the
status-project readiness check and the local ingest factory agree on
which connections enable query history and which probe to run. The
status command now picks the postgres/snowflake/bigquery probe based on
the connection's driver instead of always reporting against postgres,
which previously caused snowflake connections with queryHistory.enabled
to surface a misleading "driver is snowflake" failure.
Also drops a noisy console.warn from Snowflake primary-key discovery —
INFORMATION_SCHEMA.KEY_COLUMN_USAGE is commonly ungranted for read-only
roles and the FK + profiling paths handle the empty PK map already.
* fix(llm): allow StructuredOutput tool and raise maxTurns for generateObject
The Claude Code agent SDK announces an internal pseudo-tool named
StructuredOutput in the system/init message whenever outputFormat is set
to { type: 'json_schema' }. The runtime's isolation check built its
allowedToolIds set only from MCP tool ids and treated StructuredOutput
as an unexpected host-injected tool, so every generateObject call threw
"Claude Code runtime isolation failed: tools=StructuredOutput ..." and
the table-descriptions and relationship-LLM-proposal enrichment stages
recorded null output across the board.
Whitelist StructuredOutput specifically in generateObject's
allowedToolIds — the check also enforces missing_tools symmetry, so
generateText and runAgentLoop, which do not see StructuredOutput, must
not require it.
generateObject also ran with maxTurns: 1, which the model intermittently
breached when it emitted thinking text before the structured response.
Raised to 5 to give the schema-bound call enough headroom without
allowing unbounded loops. The existing tests now exercise the path with
an init message that announces StructuredOutput so the regression cannot
slip back in.
* chore(scripts): add ktx-reset.sh project-cleanup helper
Convenience script for repeatable ingest testing: takes a project
directory and prunes everything except ktx.yaml and .ktx/secrets/, so
the next ktx setup or ktx ingest run starts from a known-clean state.
2026-05-23 10:41:30 +02:00
|
|
|
profileConcurrency: 0
|
2026-05-13 15:55:00 +02:00
|
|
|
validationConcurrency: 0
|
|
|
|
|
validationBudget: 1.5
|
2026-05-14 15:36:35 +02:00
|
|
|
`;
|
|
|
|
|
expect(() => parseKtxProjectConfig(yaml)).toThrow(/scan\.relationships\.acceptThreshold/);
|
2026-05-10 23:12:26 +02:00
|
|
|
|
2026-05-14 15:36:35 +02:00
|
|
|
const validation = validateKtxProjectConfig(yaml);
|
|
|
|
|
expect(validation.ok).toBe(false);
|
|
|
|
|
const paths = validation.issues.map((issue) => issue.path);
|
|
|
|
|
expect(paths).toEqual(
|
|
|
|
|
expect.arrayContaining([
|
|
|
|
|
'scan.relationships.acceptThreshold',
|
|
|
|
|
'scan.relationships.reviewThreshold',
|
|
|
|
|
'scan.relationships.maxLlmTablesPerBatch',
|
|
|
|
|
'scan.relationships.maxCandidatesPerColumn',
|
|
|
|
|
'scan.relationships.profileSampleRows',
|
fix(snowflake): unblock multi-schema ingest and relationship discovery (#204)
* feat(setup): drop redundant Snowflake schema prompt; fall back to free-text on listSchemas failure
Snowflake setup previously asked for a single schema as free text, then
ran a multiselect against the discovered schemas — two schema questions
back-to-back, with the first being only a session bootstrap. The SDK's
`schema` is optional, so the bootstrap step is unnecessary.
- Remove the free-text Snowflake schema prompt; only pass `schema` to
snowflake-sdk when one is configured.
- When `listSchemas()` fails (e.g. role lacks SHOW SCHEMAS), prompt the
user for a comma-separated list, persist it as `schema_names`, and use
it as both the table-list filter and the multiselect default. Applies
to every driver with a scope-discovery spec, not just Snowflake.
- Update docs to lead with `schema_names`; keep `schema_name` as a
documented single-schema shorthand.
* fix(snowflake): keep introspecting when primary-key discovery is denied
The PK query joins INFORMATION_SCHEMA.TABLE_CONSTRAINTS and
INFORMATION_SCHEMA.KEY_COLUMN_USAGE, which require grants the
connection role may not have. Previously a 'SQL compilation error:
Object ANALYTICS.INFORMATION_SCHEMA.KEY_COLUMN_USAGE does not exist
or not authorized' aborted the entire introspect — schemas, columns,
and row counts were all discarded over a missing nice-to-have.
Wrap the constraint query in try/catch, log a one-line warning per
schema, and return an empty PK map. Columns end up with
primaryKey=false; relationship inference still has FK and profiling
to fall back on.
* fix(scan): unblock relationship discovery on Snowflake
Two adjacent bugs prevented the scan's relationship pipeline from producing
any joins on a Snowflake warehouse:
- relationship-profiling.ts fell through to a default `GROUP_CONCAT` branch
for unknown drivers. Snowflake has no GROUP_CONCAT, so every per-table
profile query failed with "Unknown function GROUP_CONCAT". Add an explicit
Snowflake branch that uses LISTAGG with a literal '\x1f' delimiter
(Snowflake requires the delimiter to be a constant, so CHR(31) is rejected).
- description-generation.ts destructured `connector.sampleTable` and
`connector.sampleColumn` into bare locals, losing the `this` binding when
the class-method connectors (Snowflake, Postgres, MySQL) were invoked.
Every sample call threw "Cannot read properties of undefined (reading
'assertConnection')" and degraded LLM descriptions to metadata-only
prompts. Call the methods through the connector instead.
Without these, even after the primary-key probe is allowed to fail softly,
the scan ends up with 0 validated relationships and an empty `joins:` block
in every shard YAML.
* test(scan): cover table-ref helpers
* feat(scan): plumb tableScope through live-database introspection port
* feat(scan): apply tableScope during metadata fetch
* feat(scan): enforce table scope at fetch boundary
* feat(scan): pool Snowflake sessions and batch enrichment for faster ingest (#206)
* feat(cli): add RSA key-pair auth option to Snowflake setup wizard
Extends the interactive Snowflake setup flow with an authentication-method
prompt (password vs RSA/JWT key-pair). The RSA branch collects a private-key
path (env/file/absolute) and an optional passphrase; the resulting connection
config records `authMethod: 'rsa'` with `privateKey` and `passphrase` instead
of `password`.
* feat(scan): pool Snowflake sessions
* fix(scan): reuse structural snapshots and cleanup connectors
* feat(scan): parallelize relationship profiling
* feat(scan): batch table description generation
* docs: document Snowflake ingest concurrency knobs
* fix(scan): close Snowflake ingest perf verification gaps
* fix(scan): keep batched description failure bounded
* feat(scan): dispatch query-history probes by connection driver
Extract historic-sql dialect resolution into a shared helper so the
status-project readiness check and the local ingest factory agree on
which connections enable query history and which probe to run. The
status command now picks the postgres/snowflake/bigquery probe based on
the connection's driver instead of always reporting against postgres,
which previously caused snowflake connections with queryHistory.enabled
to surface a misleading "driver is snowflake" failure.
Also drops a noisy console.warn from Snowflake primary-key discovery —
INFORMATION_SCHEMA.KEY_COLUMN_USAGE is commonly ungranted for read-only
roles and the FK + profiling paths handle the empty PK map already.
* fix(llm): allow StructuredOutput tool and raise maxTurns for generateObject
The Claude Code agent SDK announces an internal pseudo-tool named
StructuredOutput in the system/init message whenever outputFormat is set
to { type: 'json_schema' }. The runtime's isolation check built its
allowedToolIds set only from MCP tool ids and treated StructuredOutput
as an unexpected host-injected tool, so every generateObject call threw
"Claude Code runtime isolation failed: tools=StructuredOutput ..." and
the table-descriptions and relationship-LLM-proposal enrichment stages
recorded null output across the board.
Whitelist StructuredOutput specifically in generateObject's
allowedToolIds — the check also enforces missing_tools symmetry, so
generateText and runAgentLoop, which do not see StructuredOutput, must
not require it.
generateObject also ran with maxTurns: 1, which the model intermittently
breached when it emitted thinking text before the structured response.
Raised to 5 to give the schema-bound call enough headroom without
allowing unbounded loops. The existing tests now exercise the path with
an init message that announces StructuredOutput so the regression cannot
slip back in.
* chore(scripts): add ktx-reset.sh project-cleanup helper
Convenience script for repeatable ingest testing: takes a project
directory and prunes everything except ktx.yaml and .ktx/secrets/, so
the next ktx setup or ktx ingest run starts from a known-clean state.
2026-05-23 10:41:30 +02:00
|
|
|
'scan.relationships.profileConcurrency',
|
2026-05-14 15:36:35 +02:00
|
|
|
'scan.relationships.validationConcurrency',
|
|
|
|
|
'scan.relationships.validationBudget',
|
|
|
|
|
]),
|
|
|
|
|
);
|
2026-05-10 23:12:26 +02:00
|
|
|
});
|
|
|
|
|
|
2026-05-14 15:36:35 +02:00
|
|
|
it('rejects invalid scan relationship validation budget strings', () => {
|
|
|
|
|
const yaml = `
|
2026-05-10 23:12:26 +02:00
|
|
|
scan:
|
|
|
|
|
relationships:
|
2026-05-13 15:55:00 +02:00
|
|
|
validationBudget: infinite
|
2026-05-14 15:36:35 +02:00
|
|
|
`;
|
|
|
|
|
expect(() => parseKtxProjectConfig(yaml)).toThrow(/scan\.relationships\.validationBudget/);
|
2026-05-10 23:12:26 +02:00
|
|
|
});
|
|
|
|
|
|
2026-05-13 15:55:00 +02:00
|
|
|
it('rejects unsupported local LLM and embedding fields', () => {
|
2026-05-10 23:12:26 +02:00
|
|
|
expect(() =>
|
2026-05-10 23:51:24 +02:00
|
|
|
parseKtxProjectConfig(`
|
2026-05-10 23:12:26 +02:00
|
|
|
ingest:
|
|
|
|
|
llm:
|
|
|
|
|
backend: anthropic
|
|
|
|
|
`),
|
2026-05-24 01:00:20 +02:00
|
|
|
).toThrow('Unsupported ingest.llm: unknown field');
|
2026-05-10 23:12:26 +02:00
|
|
|
|
|
|
|
|
expect(() =>
|
2026-05-10 23:51:24 +02:00
|
|
|
parseKtxProjectConfig(`
|
2026-05-10 23:12:26 +02:00
|
|
|
scan:
|
|
|
|
|
enrichment:
|
|
|
|
|
backend: gateway
|
|
|
|
|
`),
|
2026-05-24 01:00:20 +02:00
|
|
|
).toThrow('Unsupported scan.enrichment.backend: unknown field');
|
2026-05-10 23:12:26 +02:00
|
|
|
|
|
|
|
|
expect(() =>
|
2026-05-10 23:51:24 +02:00
|
|
|
parseKtxProjectConfig(`
|
2026-05-10 23:12:26 +02:00
|
|
|
scan:
|
|
|
|
|
enrichment:
|
|
|
|
|
mode: llm
|
|
|
|
|
llm:
|
|
|
|
|
backend: gateway
|
|
|
|
|
`),
|
2026-05-24 01:00:20 +02:00
|
|
|
).toThrow('Unsupported scan.enrichment.llm: unknown field');
|
2026-05-10 23:12:26 +02:00
|
|
|
|
|
|
|
|
expect(() =>
|
2026-05-10 23:51:24 +02:00
|
|
|
parseKtxProjectConfig(`
|
2026-05-10 23:12:26 +02:00
|
|
|
ingest:
|
|
|
|
|
embeddings:
|
|
|
|
|
provider: gateway
|
|
|
|
|
max_batch_size: 32
|
|
|
|
|
`),
|
|
|
|
|
).toThrow('Unsupported ingest.embeddings.provider');
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
it('rejects gateway embedding configs', () => {
|
|
|
|
|
expect(() =>
|
2026-05-10 23:51:24 +02:00
|
|
|
parseKtxProjectConfig(`
|
2026-05-10 23:12:26 +02:00
|
|
|
ingest:
|
|
|
|
|
embeddings:
|
|
|
|
|
backend: gateway
|
|
|
|
|
model: provider/text-embedding
|
|
|
|
|
dimensions: 1536
|
|
|
|
|
`),
|
|
|
|
|
).toThrow('Unsupported ingest.embeddings.backend: gateway');
|
|
|
|
|
|
|
|
|
|
expect(() =>
|
2026-05-10 23:51:24 +02:00
|
|
|
parseKtxProjectConfig(`
|
2026-05-10 23:12:26 +02:00
|
|
|
scan:
|
|
|
|
|
enrichment:
|
|
|
|
|
mode: llm
|
|
|
|
|
embeddings:
|
|
|
|
|
backend: gateway
|
|
|
|
|
model: provider/text-embedding
|
|
|
|
|
dimensions: 1536
|
|
|
|
|
`),
|
|
|
|
|
).toThrow('Unsupported scan.enrichment.embeddings.backend: gateway');
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
it('fills optional sections when a minimal config is loaded', () => {
|
2026-05-14 17:39:31 +02:00
|
|
|
const config = parseKtxProjectConfig('{}\n');
|
2026-05-10 23:12:26 +02:00
|
|
|
|
2026-05-14 17:39:31 +02:00
|
|
|
expect(config).toEqual(buildDefaultKtxProjectConfig());
|
2026-05-10 23:12:26 +02:00
|
|
|
expect(config.ingest.embeddings).toEqual({
|
2026-05-19 16:40:01 +02:00
|
|
|
backend: 'none',
|
2026-05-10 23:12:26 +02:00
|
|
|
dimensions: 8,
|
|
|
|
|
});
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
it('rejects configs without an object root', () => {
|
2026-05-10 23:51:24 +02:00
|
|
|
expect(() => parseKtxProjectConfig('- nope\n')).toThrow('ktx.yaml must contain a YAML object');
|
2026-05-10 23:12:26 +02:00
|
|
|
});
|
|
|
|
|
|
2026-05-14 17:39:31 +02:00
|
|
|
it('accepts configs without a project name', () => {
|
|
|
|
|
expect(parseKtxProjectConfig('connections: {}\n')).toMatchObject({
|
|
|
|
|
connections: {},
|
|
|
|
|
});
|
2026-05-10 23:12:26 +02:00
|
|
|
});
|
2026-05-14 15:36:35 +02:00
|
|
|
|
|
|
|
|
it('rejects unknown top-level fields under strict mode', () => {
|
|
|
|
|
expect(() =>
|
|
|
|
|
parseKtxProjectConfig(`
|
|
|
|
|
storrage:
|
|
|
|
|
state: sqlite
|
|
|
|
|
`),
|
|
|
|
|
).toThrow(/Unsupported storrage/);
|
|
|
|
|
});
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
describe('validateKtxProjectConfig', () => {
|
|
|
|
|
it('returns ok: true with no issues for a valid config', () => {
|
2026-05-14 17:39:31 +02:00
|
|
|
const result = validateKtxProjectConfig('connections: {}\n');
|
2026-05-14 15:36:35 +02:00
|
|
|
expect(result).toEqual({ ok: true, issues: [] });
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
it('collects every schema issue without throwing', () => {
|
|
|
|
|
const result = validateKtxProjectConfig(`
|
|
|
|
|
storage:
|
|
|
|
|
search: not-a-real-backend
|
|
|
|
|
scan:
|
|
|
|
|
relationships:
|
|
|
|
|
acceptThreshold: 1.7
|
|
|
|
|
`);
|
|
|
|
|
|
|
|
|
|
expect(result.ok).toBe(false);
|
|
|
|
|
const paths = result.issues.map((issue) => issue.path);
|
|
|
|
|
expect(paths).toEqual(
|
|
|
|
|
expect.arrayContaining([
|
|
|
|
|
'storage.search',
|
|
|
|
|
'scan.relationships.acceptThreshold',
|
|
|
|
|
]),
|
|
|
|
|
);
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
it('reports YAML parse errors as a root-level issue', () => {
|
|
|
|
|
const result = validateKtxProjectConfig(': not valid yaml :\n');
|
|
|
|
|
expect(result.ok).toBe(false);
|
|
|
|
|
expect(result.issues[0]?.path).toBe('');
|
|
|
|
|
expect(result.issues[0]?.message).toMatch(/ktx\.yaml parse error/);
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
it('reports a YAML scalar root as a single issue', () => {
|
|
|
|
|
const result = validateKtxProjectConfig('- nope\n');
|
|
|
|
|
expect(result).toEqual({
|
|
|
|
|
ok: false,
|
|
|
|
|
issues: [{ path: '', message: 'ktx.yaml must contain a YAML object' }],
|
|
|
|
|
});
|
|
|
|
|
});
|
2026-05-10 23:12:26 +02:00
|
|
|
});
|
2026-05-14 16:21:29 +02:00
|
|
|
|
|
|
|
|
describe('generateKtxProjectConfigJsonSchema', () => {
|
|
|
|
|
const schema = generateKtxProjectConfigJsonSchema();
|
|
|
|
|
|
|
|
|
|
it('emits draft-07 metadata', () => {
|
|
|
|
|
expect(schema.$schema).toBe('http://json-schema.org/draft-07/schema#');
|
|
|
|
|
expect(schema.$id).toBe('https://ktx.dev/schemas/ktx-project-config.json');
|
|
|
|
|
expect(schema.title).toBe('ktx.yaml');
|
|
|
|
|
expect(schema.type).toBe('object');
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
it('exposes every top-level ktx.yaml section under properties', () => {
|
|
|
|
|
const properties = schema.properties as Record<string, unknown>;
|
2026-05-14 17:39:31 +02:00
|
|
|
expect(Object.keys(properties).sort()).toEqual(['agent', 'connections', 'ingest', 'llm', 'memory', 'scan', 'setup', 'storage'].sort());
|
2026-05-14 16:21:29 +02:00
|
|
|
});
|
|
|
|
|
|
2026-05-14 17:39:31 +02:00
|
|
|
it('does not require any top-level fields', () => {
|
|
|
|
|
expect(schema.required).toBeUndefined();
|
2026-05-14 16:21:29 +02:00
|
|
|
});
|
|
|
|
|
|
|
|
|
|
it('carries .describe() text on top-level fields', () => {
|
|
|
|
|
const properties = schema.properties as Record<string, { description?: string }>;
|
|
|
|
|
expect(properties.llm?.description).toMatch(/LLM/);
|
|
|
|
|
expect(properties.scan?.description).toMatch(/Schema-scan/);
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
it('propagates enum values through to nested fields', () => {
|
|
|
|
|
const llm = (schema.properties as Record<string, { properties?: Record<string, unknown> }>).llm;
|
|
|
|
|
const provider = llm?.properties?.provider as { properties?: Record<string, unknown> };
|
|
|
|
|
const backend = provider?.properties?.backend as { enum?: readonly string[] };
|
feat: add codex llm backend for ktx runtime work (#253)
* feat: add codex sdk runner foundation
* feat: parse codex runtime events
* feat: expose codex runtime mcp tools
* feat: add codex llm runtime
* feat: wire codex llm backend
* test: avoid Array.fromAsync in codex runner test
* docs: document codex llm backend
* fix: tighten codex runtime config ownership
* fix: use codex sdk env and thread options
* fix: parse codex sdk event shapes
* test: add codex backend live smoke
* docs: clarify codex backend isolation
* fix: drive codex loop metrics from mcp events
* fix: enforce codex local step budget
* docs: disclose codex isolation limits
* fix: count all codex agent steps and stream step callbacks live
The agent-loop step budget only counted completed mcp_tool_call items, so
built-in command_execution steps (which the public Codex SDK/CLI surface can
still expose) never decremented the budget, letting ingest/reconciliation run
past stepBudget until Codex stopped on its own. onStepFinish was also replayed
only after the whole stream drained, so live work_unit_step / reconciliation
progress appeared stuck until the Codex process exited.
collectEvents is now the single live step accumulator: it counts every
completed agent-action item via a shared isCompletedAgentStep predicate
(command_execution, mcp_tool_call, file_change, web_search), fires onStepFinish
as each step completes, and enforces the budget on that broader count. A
no-tool turn still counts as one step. toolFailures stays MCP-specific, since a
non-zero command exit is normal agent exploration, not a loop failure.
* test: align ingest llm-guard assertions with codex backend
The skip-llm ingest guard message now lists codex as a valid backend and
mentions a Claude Code/Codex session plus a codex setup hint, but this slow
suite test still asserted the pre-codex wording. Update it to match the
production message (already covered by the local-bundle-runtime unit test) and
add the codex setup-line assertion.
* fix: treat codex error:null tool calls as success
The Codex SDK serializes error: null on successful mcp_tool_call items, so
the failure check (item.error !== undefined) flagged every successful tool
call as failed with the empty-payload default "Codex turn failed". This
killed every ingest work unit under the codex backend before it could
produce a patch.
Key on status === 'failed' (authoritative, always set) and only treat a
populated error object as a failure. Add a regression test built from a
verbatim real-SDK event capture.
* fix: default codex backend to gpt-5.5 and report real probe errors
The previous default gpt-5.3-codex is an API-key-only model that the OpenAI
API rejects under ChatGPT-account (subscription) auth, so codex status/setup
failed with a misleading "authentication is not usable" message even though
auth was fine.
- Default codex model is now gpt-5.5 (works on both subscription and API-key
auth); the curated setup picker offers gpt-5.5 / gpt-5.4 / gpt-5.4-mini and
keeps free-form entry for account-specific ids (e.g. gpt-5.3-codex-spark).
- runCodexAuthProbe now distinguishes "model not available" from an auth
failure and surfaces the real API error: collectEvents retains stream
events when the SDK throws on a non-zero exit, and the API error JSON
envelope is unwrapped to its human-readable message.
- The Codex isolation warning now renders inside the clack setup frame.
- Docs updated to gpt-5.5 with a note that *-codex ids require API-key auth.
* fix: require llm.models.default in status and match codex probe remediation
Status reported a project ready when a non-none LLM backend was configured
without llm.models.default, but the runtime (resolveModelSlots) hard-requires
it, so ingest/scan/memory threw after `ktx status` said the project was usable.
buildLlmStatus now fails for any non-none backend missing models.default and no
longer invents a fallback model for claude-code/codex.
Codex probe failures now carry a category-matched fix: a model-access failure
steers the user at llm.models.default instead of the auth/install remediation.
runCodexAuthProbe returns the fix and status consumes it; the message stays
self-sufficient so setup output is unchanged.
Docs: README now lists the codex backend and local Codex auth; ktx-setup.mdx
states --llm-model only accepts codex/default or gpt-*/codex-* ids.
Repaired four doctor fixtures that configured a backend without models.default
(the now-correctly-blocked config) and added coverage for the new behavior.
2026-06-02 13:57:11 +02:00
|
|
|
expect(backend?.enum).toEqual(['none', 'anthropic', 'vertex', 'gateway', 'claude-code', 'codex']);
|
2026-05-14 16:21:29 +02:00
|
|
|
|
|
|
|
|
const storage = (schema.properties as Record<string, { properties?: Record<string, unknown> }>).storage;
|
|
|
|
|
const state = storage?.properties?.state as { enum?: readonly string[] };
|
|
|
|
|
expect(state?.enum).toEqual(['sqlite', 'postgres']);
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
it('carries descriptions on deeply nested leaves', () => {
|
|
|
|
|
const scan = (schema.properties as Record<string, { properties?: Record<string, unknown> }>).scan;
|
|
|
|
|
const relationships = scan?.properties?.relationships as { properties?: Record<string, { description?: string }> };
|
|
|
|
|
expect(relationships?.properties?.acceptThreshold?.description).toMatch(/auto-accepted/);
|
|
|
|
|
});
|
2026-05-15 00:08:11 +02:00
|
|
|
|
|
|
|
|
it('emits the mappings shapes under connections', () => {
|
|
|
|
|
const serialized = JSON.stringify(schema);
|
|
|
|
|
expect(serialized).toContain('databaseMappings');
|
|
|
|
|
expect(serialized).toContain('connectionMappings');
|
|
|
|
|
expect(serialized).toContain('expectedLookerConnectionName');
|
|
|
|
|
});
|
2026-05-14 16:21:29 +02:00
|
|
|
});
|