ktx/packages/cli/src/managed-mcp-daemon.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

254 lines
8.4 KiB
TypeScript

import { spawn } from 'node:child_process';
import { mkdir, open, readFile, rm, writeFile } from 'node:fs/promises';
import { createServer } from 'node:net';
import { dirname, join } from 'node:path';
import { setTimeout as delay } from 'node:timers/promises';
import { z } from 'zod';
import { sanitizeChildProxyEnv } from './proxy-env.js';
export interface KtxMcpDaemonState {
schemaVersion: 1;
pid: number;
host: string;
port: number;
tokenAuth: boolean;
projectDir: string;
startedAt: string;
logPath: string;
}
/** @internal */
export interface KtxMcpDaemonChild {
pid?: number;
unref(): void;
}
export type KtxMcpDaemonStatus =
| { kind: 'stopped'; detail: string }
| { kind: 'running'; detail: string; state: KtxMcpDaemonState; url: string }
| { kind: 'stale'; detail: string; state?: KtxMcpDaemonState };
const stateSchema = z.object({
schemaVersion: z.literal(1),
pid: z.number().int().positive(),
host: z.string().min(1),
port: z.number().int().min(1).max(65535),
tokenAuth: z.boolean(),
projectDir: z.string().min(1),
startedAt: z.string().min(1),
logPath: z.string().min(1),
});
export function mcpDaemonLayout(projectDir: string): { statePath: string; logPath: string } {
return {
statePath: join(projectDir, '.ktx/mcp.json'),
logPath: join(projectDir, '.ktx/logs/mcp.log'),
};
}
function defaultProcessAlive(pid: number): boolean {
try {
process.kill(pid, 0);
return true;
} catch {
return false;
}
}
function defaultKillProcess(pid: number, signal: NodeJS.Signals): void {
try {
process.kill(pid, signal);
} catch (error) {
if ((error as { code?: unknown }).code !== 'ESRCH') {
throw error;
}
}
}
async function readState(projectDir: string): Promise<KtxMcpDaemonState | undefined> {
try {
return stateSchema.parse(JSON.parse(await readFile(mcpDaemonLayout(projectDir).statePath, 'utf8')) as unknown);
} catch (error) {
if ((error as { code?: unknown }).code === 'ENOENT') {
return undefined;
}
throw error;
}
}
async function writeState(projectDir: string, state: KtxMcpDaemonState): Promise<void> {
const { statePath } = mcpDaemonLayout(projectDir);
await mkdir(dirname(statePath), { recursive: true });
await writeFile(statePath, `${JSON.stringify(state, null, 2)}\n`, 'utf8');
}
async function defaultPortAvailable(host: string, port: number): Promise<boolean> {
return await new Promise((resolve) => {
const server = createServer();
server.once('error', () => resolve(false));
server.listen(port, host, () => server.close(() => resolve(true)));
});
}
function defaultSpawnDaemon(
command: string,
args: string[],
options: { detached: boolean; stdio: ['ignore', number, number]; env: NodeJS.ProcessEnv },
): KtxMcpDaemonChild {
return spawn(command, args, options);
}
async function defaultFetchHealth(state: KtxMcpDaemonState): Promise<{ ok: boolean; body: unknown; detail?: string }> {
try {
const response = await fetch(`http://${state.host}:${state.port}/health`, {
headers: { host: `${state.host}:${state.port}` },
});
const body = await response.json();
return { ok: response.ok, body, detail: response.ok ? undefined : `HTTP ${response.status}` };
} catch (error) {
return { ok: false, body: null, detail: error instanceof Error ? error.message : String(error) };
}
}
export async function startKtxMcpDaemon(options: {
projectDir: string;
cliVersion: string;
host: string;
port: number;
token?: string;
allowedHosts: string[];
allowedOrigins: string[];
binPath: string;
processAlive?: (pid: number) => boolean;
portAvailable?: (host: string, port: number) => Promise<boolean>;
spawnDaemon?: typeof defaultSpawnDaemon;
now?: () => Date;
}): Promise<{ status: 'started' | 'already-running'; state: KtxMcpDaemonState; url: string }> {
const existing = await readState(options.projectDir).catch(() => undefined);
const processAlive = options.processAlive ?? defaultProcessAlive;
if (existing && processAlive(existing.pid)) {
const sameConfig =
existing.host === options.host &&
existing.port === options.port &&
existing.tokenAuth === Boolean(options.token);
if (sameConfig) {
return {
status: 'already-running',
state: existing,
url: `http://${existing.host}:${existing.port}/mcp`,
};
}
throw new Error(
`KTX MCP daemon is already running at http://${existing.host}:${existing.port}/mcp ` +
'with a different configuration. Run `ktx mcp stop` first, then start again.',
);
}
const portAvailable = options.portAvailable ?? defaultPortAvailable;
if (!(await portAvailable(options.host, options.port))) {
throw new Error(`Port ${options.port} is already in use. Choose another port with --port <n>.`);
}
const { logPath } = mcpDaemonLayout(options.projectDir);
await mkdir(dirname(logPath), { recursive: true });
const log = await open(logPath, 'a');
try {
const args = [
options.binPath,
'--project-dir',
options.projectDir,
'mcp',
'serve-internal',
'--host',
options.host,
'--port',
String(options.port),
...options.allowedHosts.flatMap((host) => ['--allowed-host', host]),
...options.allowedOrigins.flatMap((origin) => ['--allowed-origin', origin]),
];
const child = (options.spawnDaemon ?? defaultSpawnDaemon)(process.execPath, args, {
detached: true,
stdio: ['ignore', log.fd, log.fd],
env: sanitizeChildProxyEnv({
...process.env,
KTX_CLI_VERSION: options.cliVersion,
...(options.token ? { KTX_MCP_TOKEN: options.token } : {}),
}),
});
if (!child.pid) {
throw new Error('Failed to start KTX MCP daemon: child process pid was not available.');
}
child.unref();
const state: KtxMcpDaemonState = {
schemaVersion: 1,
pid: child.pid,
host: options.host,
port: options.port,
tokenAuth: Boolean(options.token),
projectDir: options.projectDir,
startedAt: (options.now ?? (() => new Date()))().toISOString(),
logPath,
};
await writeState(options.projectDir, state);
return { status: 'started', state, url: `http://${state.host}:${state.port}/mcp` };
} finally {
await log.close();
}
}
export async function readKtxMcpDaemonStatus(options: {
projectDir: string;
processAlive?: (pid: number) => boolean;
fetchHealth?: (state: KtxMcpDaemonState) => Promise<{ ok: boolean; body: unknown; detail?: string }>;
}): Promise<KtxMcpDaemonStatus> {
let state: KtxMcpDaemonState | undefined;
try {
state = await readState(options.projectDir);
} catch (error) {
return { kind: 'stale', detail: `MCP daemon state is invalid: ${error instanceof Error ? error.message : String(error)}` };
}
if (!state) {
return { kind: 'stopped', detail: `No MCP daemon state at ${mcpDaemonLayout(options.projectDir).statePath}` };
}
const processAlive = options.processAlive ?? defaultProcessAlive;
if (!processAlive(state.pid)) {
return { kind: 'stale', detail: `MCP daemon process ${state.pid} is not running`, state };
}
const health = await (options.fetchHealth ?? defaultFetchHealth)(state);
if (!health.ok) {
return { kind: 'stale', detail: health.detail ?? 'MCP daemon health check failed', state };
}
return {
kind: 'running',
detail: `KTX MCP daemon running at http://${state.host}:${state.port}/mcp`,
state,
url: `http://${state.host}:${state.port}/mcp`,
};
}
export async function stopKtxMcpDaemon(options: {
projectDir: string;
processAlive?: (pid: number) => boolean;
killProcess?: (pid: number, signal: NodeJS.Signals) => void;
stopGraceMs?: number;
pollIntervalMs?: number;
}): Promise<{ status: 'stopped' | 'already-stopped' }> {
const state = await readState(options.projectDir);
const { statePath } = mcpDaemonLayout(options.projectDir);
if (!state) {
return { status: 'already-stopped' };
}
const processAlive = options.processAlive ?? defaultProcessAlive;
const killProcess = options.killProcess ?? defaultKillProcess;
if (processAlive(state.pid)) {
killProcess(state.pid, 'SIGTERM');
const deadline = Date.now() + (options.stopGraceMs ?? 10_000);
while (Date.now() <= deadline && processAlive(state.pid)) {
await delay(options.pollIntervalMs ?? 100);
}
if (processAlive(state.pid)) {
killProcess(state.pid, 'SIGKILL');
}
}
await rm(statePath, { force: true });
return { status: 'stopped' };
}