ktx/packages/cli/src/context/wiki/tools/wiki-write.tool.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

344 lines
12 KiB
TypeScript

import { describe, expect, it, vi } from 'vitest';
import type { ToolSession } from '../../../context/tools/tool-session.js';
import { createTouchedSlSources } from '../../../context/tools/touched-sl-sources.js';
import type { ToolContext } from '../../../context/tools/base-tool.js';
import { WikiWriteTool } from './wiki-write.tool.js';
function makeTool(overrides: any = {}) {
const wikiService = {
readPage: vi.fn().mockResolvedValue(null),
listPageKeys: vi.fn().mockResolvedValue([]),
writePage: vi.fn().mockResolvedValue(undefined),
syncSinglePage: vi.fn().mockResolvedValue(undefined),
...overrides.wikiService,
};
const pagesRepository = {
findPageByKey: vi.fn().mockResolvedValue(null),
getUserPageCount: vi.fn().mockResolvedValue(0),
...overrides.pagesRepository,
};
const knowledgeRepository = {
createEvent: vi.fn().mockResolvedValue(undefined),
...overrides.knowledgeRepository,
};
const tool = new WikiWriteTool(wikiService as any, pagesRepository as any, knowledgeRepository as any);
return { tool, wikiService, pagesRepository, knowledgeRepository };
}
describe('WikiWriteTool', () => {
const baseContext: ToolContext = { sourceId: 's', messageId: 'm', userId: 'u' };
it('creates a new page and indexes it when no session is present', async () => {
const { tool, wikiService } = makeTool();
const result = await tool.call(
{ key: 'leads-source', summary: 'Lead source definitions', content: '# Leads' } as any,
baseContext,
);
expect(wikiService.writePage).toHaveBeenCalledTimes(1);
expect(wikiService.syncSinglePage).toHaveBeenCalledTimes(1);
expect(result.markdown).toMatch(/created/i);
});
it('rejects slash-delimited page keys with a flat-key suggestion', async () => {
const { tool, wikiService } = makeTool();
const result = await tool.call(
{ key: 'orbit/company-overview', summary: 'Company overview', content: '# Orbit' } as any,
baseContext,
);
expect(result.structured).toEqual({ success: false, key: 'orbit/company-overview' });
expect(result.markdown).toContain(
'Invalid wiki key "orbit/company-overview". Wiki keys must be flat; use "orbit-company-overview".',
);
expect(wikiService.readPage).not.toHaveBeenCalled();
expect(wikiService.writePage).not.toHaveBeenCalled();
});
it('normalizes accidentally escaped markdown newlines before writing', async () => {
const { tool, wikiService } = makeTool();
await tool.call(
{
key: 'large-contract-requesters',
summary: 'Cross-schema Metabase query',
content:
'# Large Contract Requesters\\n\\n**Source card:** Metabase #110\\n\\n## SQL\\n\\n```sql\\nselect * from orbit_analytics.mart_account_segments\\n```\\n',
} as any,
baseContext,
);
expect(wikiService.writePage.mock.calls[0][4]).toBe(
'# Large Contract Requesters\n\n**Source card:** Metabase #110\n\n## SQL\n\n```sql\nselect * from orbit_analytics.mart_account_segments\n```\n',
);
expect(wikiService.syncSinglePage.mock.calls[0][4]).toBe(
'# Large Contract Requesters\n\n**Source card:** Metabase #110\n\n## SQL\n\n```sql\nselect * from orbit_analytics.mart_account_segments\n```\n',
);
});
it('preserves intentional escaped newline examples in inline code', async () => {
const { tool, wikiService } = makeTool();
await tool.call(
{
key: 'newline-token',
summary: 'Escaped newline token',
content: 'Use `\\n\\n` when documenting the literal separator.',
} as any,
baseContext,
);
expect(wikiService.writePage.mock.calls[0][4]).toBe('Use `\\n\\n` when documenting the literal separator.');
});
it('skips syncSinglePage when session is worktree-scoped', async () => {
const { tool, wikiService } = makeTool();
const session: ToolSession = {
connectionId: 'conn-1',
isWorktreeScoped: true,
preHead: null,
touchedSlSources: createTouchedSlSources(),
actions: [],
semanticLayerService: {} as any,
wikiService: wikiService as any,
configService: {} as any,
gitService: {} as any,
};
const context: ToolContext = { ...baseContext, session };
await tool.call({ key: 'k', summary: 's', content: '# x' } as any, context);
expect(wikiService.writePage).toHaveBeenCalledTimes(1);
expect(wikiService.syncSinglePage).not.toHaveBeenCalled();
expect(session.actions).toContainEqual(expect.objectContaining({ target: 'wiki', type: 'created', key: 'k' }));
});
it('requires either content or replacements', async () => {
const { tool } = makeTool();
const result = await tool.call({ key: 'k', summary: 's' } as any, baseContext);
expect(result.structured.success).toBe(false);
expect(result.markdown).toMatch(/content.*or.*replacements/i);
});
it('updates frontmatter only on an existing page while preserving content', async () => {
const { tool, wikiService } = makeTool({
wikiService: {
readPage: vi.fn().mockResolvedValue({
pageKey: 'orbit-customers',
frontmatter: {
summary: 'Customer source details',
usage_mode: 'auto',
sort_order: 0,
tags: ['notion'],
refs: ['notion:old'],
sl_refs: ['postgres-warehouse/orbit_analytics.customer'],
},
content: '# Orbit Customers\n\nSource: Notion - Orbit Customers Source.',
}),
},
});
const result = await tool.call(
{
key: 'orbit-customers',
summary: 'Customer source details mapped to the warehouse customer view',
sl_refs: ['postgres-warehouse/orbit_analytics.customer', 'dbt-main/customer'],
} as any,
baseContext,
);
expect(result.structured).toMatchObject({ success: true, key: 'orbit-customers', action: 'updated' });
expect(wikiService.writePage).toHaveBeenCalledWith(
'USER',
'u',
'orbit-customers',
expect.objectContaining({
summary: 'Customer source details mapped to the warehouse customer view',
tags: ['notion'],
refs: ['notion:old'],
sl_refs: ['postgres-warehouse/orbit_analytics.customer', 'dbt-main/customer'],
}),
'# Orbit Customers\n\nSource: Notion - Orbit Customers Source.',
expect.any(String),
expect.any(String),
);
});
it('writes historic-SQL frontmatter fields', async () => {
const { tool, wikiService } = makeTool();
await tool.call(
{
key: 'monthly-paid-orders',
summary: 'Monthly paid orders',
tags: ['historic-sql', 'query-pattern'],
sl_refs: ['analytics.orders'],
source: 'historic-sql',
intent: 'Monthly paid order count',
tables: ['analytics.orders'],
representative_sql: "SELECT count(*) FROM analytics.orders WHERE status = 'paid'",
usage: {
executions: 42,
distinct_users: 3,
first_seen: '2026-02-01',
last_seen: '2026-05-04',
p50_runtime_ms: 100,
p95_runtime_ms: 200,
error_rate: 0,
rows_produced: 42,
},
fingerprints: ['fp_paid_orders'],
content: '## Monthly paid order count',
} as any,
baseContext,
);
expect(wikiService.writePage.mock.calls[0][3]).toEqual({
summary: 'Monthly paid orders',
usage_mode: 'auto',
sort_order: 0,
tags: ['historic-sql', 'query-pattern'],
refs: undefined,
sl_refs: ['analytics.orders'],
source: 'historic-sql',
intent: 'Monthly paid order count',
tables: ['analytics.orders'],
representative_sql: "SELECT count(*) FROM analytics.orders WHERE status = 'paid'",
usage: {
executions: 42,
distinct_users: 3,
first_seen: '2026-02-01',
last_seen: '2026-05-04',
p50_runtime_ms: 100,
p95_runtime_ms: 200,
error_rate: 0,
rows_produced: 42,
},
fingerprints: ['fp_paid_orders'],
});
});
it('preserves historic-SQL frontmatter fields when update omits them', async () => {
const existingFrontmatter = {
summary: 'Monthly paid orders',
usage_mode: 'auto' as const,
sort_order: 0,
tags: ['historic-sql'],
sl_refs: ['analytics.orders'],
source: 'historic-sql',
intent: 'Monthly paid order count',
tables: ['analytics.orders'],
representative_sql: "SELECT count(*) FROM analytics.orders WHERE status = 'paid'",
usage: {
executions: 42,
distinct_users: 3,
first_seen: '2026-02-01',
last_seen: '2026-05-04',
p50_runtime_ms: 100,
p95_runtime_ms: 200,
error_rate: 0,
rows_produced: 42,
},
fingerprints: ['fp_paid_orders'],
};
const { tool, wikiService } = makeTool({
wikiService: {
readPage: vi.fn().mockResolvedValue({
pageKey: 'monthly-paid-orders',
frontmatter: existingFrontmatter,
content: 'old body',
}),
},
});
await tool.call(
{
key: 'monthly-paid-orders',
summary: 'Monthly paid orders updated',
content: '## Monthly paid order count updated',
} as any,
baseContext,
);
expect(wikiService.writePage.mock.calls[0][3]).toEqual({
...existingFrontmatter,
summary: 'Monthly paid orders updated',
});
});
it('rejects frontmatter refs that target missing wiki pages', async () => {
const { tool, wikiService } = makeTool({
wikiService: {
listPageKeys: vi.fn().mockResolvedValue(['orbit-company-overview']),
},
});
const result = await tool.call(
{
key: 'orbit-how-we-work',
summary: 'Operating norms',
content: '## How We Work',
refs: ['orbit-company-overview', 'orbit-team-lanes-detail'],
} as any,
baseContext,
);
expect(result.structured.success).toBe(false);
expect(result.markdown).toMatch(/orbit-team-lanes-detail/);
expect(wikiService.writePage).not.toHaveBeenCalled();
});
it('rejects inline wiki links that target missing wiki pages', async () => {
const { tool, wikiService } = makeTool({
wikiService: {
listPageKeys: vi.fn().mockResolvedValue(['orbit-company-overview']),
},
});
const result = await tool.call(
{
key: 'orbit-how-we-work',
summary: 'Operating norms',
content: 'See [[orbit-company-overview]] and [[orbit-team-lanes-detail]].',
} as any,
baseContext,
);
expect(result.structured.success).toBe(false);
expect(result.markdown).toMatch(/orbit-team-lanes-detail/);
expect(wikiService.writePage).not.toHaveBeenCalled();
});
it('accepts forward refs during ingest sessions for post-pass validation', async () => {
const { tool, wikiService } = makeTool({
wikiService: {
listPageKeys: vi.fn().mockResolvedValue(['orbit-company-overview']),
},
});
const session: ToolSession = {
connectionId: 'conn-1',
isWorktreeScoped: true,
preHead: null,
touchedSlSources: createTouchedSlSources(),
actions: [],
semanticLayerService: {} as any,
wikiService: wikiService as any,
configService: {} as any,
gitService: {} as any,
ingest: { runId: 'run-1', jobId: 'job-1', syncId: 'sync-1', sourceKey: 'notion' },
};
const result = await tool.call(
{
key: 'orbit-how-we-work',
summary: 'Operating norms',
content: 'See [[orbit-team-lanes-detail]].',
refs: ['orbit-company-overview', 'orbit-team-lanes-detail'],
} as any,
{ ...baseContext, session },
);
expect(result.structured).toMatchObject({ success: true, key: 'orbit-how-we-work', action: 'created' });
expect(wikiService.writePage).toHaveBeenCalledTimes(1);
expect(session.actions).toContainEqual(
expect.objectContaining({ target: 'wiki', type: 'created', key: 'orbit-how-we-work' }),
);
});
});