mirror of
https://github.com/Kaelio/ktx.git
synced 2026-06-22 08:38:08 +02:00
* 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.
286 lines
9.8 KiB
TypeScript
286 lines
9.8 KiB
TypeScript
import { resolveNotionConnectionAuthToken } from './context/connections/notion-config.js';
|
|
import { type NotionApi, type NotionBotInfo, NotionClient } from './context/ingest/adapters/notion/notion-client.js';
|
|
import type { KtxProjectConnectionConfig } from './context/project/config.js';
|
|
import type { KtxCliIo } from './cli-runtime.js';
|
|
import { profileMark } from './startup-profile.js';
|
|
import {
|
|
buildInitialState,
|
|
buildPickerTree,
|
|
flattenSelection,
|
|
type PickerState,
|
|
type TreePickerNodeInput,
|
|
} from './tree-picker-state.js';
|
|
import {
|
|
renderTreePickerTui,
|
|
type TreePickerChrome,
|
|
type TreePickerResult,
|
|
type TreePickerTuiIo,
|
|
} from './tree-picker-tui.js';
|
|
|
|
profileMark('module:notion-page-picker');
|
|
|
|
export interface PickNotionRootPagesArgs {
|
|
connectionId: string;
|
|
connection: KtxProjectConnectionConfig;
|
|
}
|
|
|
|
/** @internal */
|
|
export type NotionPickerApi = Pick<NotionApi, 'search' | 'retrieveBotUser'>;
|
|
export type NotionRootPagePickResult =
|
|
| { kind: 'selected'; rootPageIds: string[] }
|
|
| { kind: 'back' }
|
|
| { kind: 'unavailable'; message: string };
|
|
|
|
export interface NotionRootPagePickerDeps {
|
|
env?: Record<string, string | undefined>;
|
|
createNotionApi?: (authToken: string) => NotionPickerApi;
|
|
renderPicker?: (
|
|
chrome: TreePickerChrome,
|
|
initialState: PickerState,
|
|
io: TreePickerTuiIo,
|
|
) => Promise<TreePickerResult>;
|
|
}
|
|
|
|
const NOTION_PICKER_PAGE_CAP = 5000;
|
|
const NOTION_SCRIPTED_MODE_HINT =
|
|
'Notion picker requires a TTY. Use --no-input --notion-root-page-id <UUID> for scripted mode.';
|
|
|
|
function assertSafeNotionPickerConnectionId(connectionId: string): void {
|
|
if (!/^[a-zA-Z0-9][a-zA-Z0-9_-]*$/.test(connectionId)) {
|
|
throw new Error(`Unsafe connection id: ${connectionId}`);
|
|
}
|
|
}
|
|
|
|
/** @internal */
|
|
export function normalizeNotionPageId(value: string): string {
|
|
const trimmed = value.trim();
|
|
const compact = trimmed.includes('-') ? trimmed.replace(/-/g, '') : trimmed;
|
|
if (!/^[0-9a-fA-F]{32}$/.test(compact)) {
|
|
throw new Error(`Invalid Notion page UUID: ${value}`);
|
|
}
|
|
const lower = compact.toLowerCase();
|
|
return `${lower.slice(0, 8)}-${lower.slice(8, 12)}-${lower.slice(12, 16)}-${lower.slice(16, 20)}-${lower.slice(20)}`;
|
|
}
|
|
|
|
function tryNormalizeNotionPageId(value: string): string | null {
|
|
try {
|
|
return normalizeNotionPageId(value);
|
|
} catch {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
function recordValue(value: unknown): Record<string, unknown> | null {
|
|
return typeof value === 'object' && value !== null && !Array.isArray(value)
|
|
? (value as Record<string, unknown>)
|
|
: null;
|
|
}
|
|
|
|
function extractTitleFromNotionPage(page: Record<string, unknown>): string {
|
|
const properties = recordValue(page.properties);
|
|
if (!properties) {
|
|
return 'Untitled';
|
|
}
|
|
for (const property of Object.values(properties)) {
|
|
const value = recordValue(property);
|
|
if (!value || value.type !== 'title' || !Array.isArray(value.title)) {
|
|
continue;
|
|
}
|
|
const text = value.title
|
|
.map((part) => {
|
|
const richText = recordValue(part);
|
|
return typeof richText?.plain_text === 'string' ? richText.plain_text : '';
|
|
})
|
|
.join('')
|
|
.trim();
|
|
if (text.length > 0) {
|
|
return text;
|
|
}
|
|
}
|
|
return 'Untitled';
|
|
}
|
|
|
|
function extractParentPageId(page: Record<string, unknown>): string | null {
|
|
const parent = recordValue(page.parent);
|
|
if (!parent || parent.type !== 'page_id' || typeof parent.page_id !== 'string') {
|
|
return null;
|
|
}
|
|
return normalizeNotionPageId(parent.page_id);
|
|
}
|
|
|
|
/** @internal */
|
|
export function notionPickerPageFromSearchResult(result: Record<string, unknown>): TreePickerNodeInput {
|
|
const id = typeof result.id === 'string' ? normalizeNotionPageId(result.id) : '';
|
|
if (!id) {
|
|
throw new Error('Notion page search result is missing id');
|
|
}
|
|
return {
|
|
id,
|
|
title: extractTitleFromNotionPage(result),
|
|
archived: result.archived === true,
|
|
parentId: extractParentPageId(result),
|
|
};
|
|
}
|
|
|
|
/** @internal */
|
|
export async function discoverNotionPickerPages(
|
|
api: NotionPickerApi,
|
|
options: { cap?: number } = {},
|
|
): Promise<{ pages: TreePickerNodeInput[]; cappedAtCount: number | null; warnings: string[] }> {
|
|
const cap = options.cap ?? NOTION_PICKER_PAGE_CAP;
|
|
const pages: TreePickerNodeInput[] = [];
|
|
const warnings: string[] = [];
|
|
let cursor: string | null | undefined = null;
|
|
|
|
while (pages.length < cap) {
|
|
let response: Awaited<ReturnType<NotionPickerApi['search']>>;
|
|
try {
|
|
response = await api.search('page', cursor, Math.min(100, cap - pages.length));
|
|
} catch (error) {
|
|
if (pages.length === 0) {
|
|
throw error;
|
|
}
|
|
const message = error instanceof Error ? error.message : String(error);
|
|
warnings.push(`Notion search stopped early: ${message}`);
|
|
return { pages, cappedAtCount: null, warnings };
|
|
}
|
|
|
|
for (const result of response.results) {
|
|
pages.push(notionPickerPageFromSearchResult(result));
|
|
if (pages.length >= cap) {
|
|
break;
|
|
}
|
|
}
|
|
|
|
if (!response.hasMore || !response.nextCursor || pages.length >= cap) {
|
|
return {
|
|
pages,
|
|
cappedAtCount: response.hasMore ? cap : null,
|
|
warnings,
|
|
};
|
|
}
|
|
cursor = response.nextCursor;
|
|
}
|
|
|
|
return { pages, cappedAtCount: cap, warnings };
|
|
}
|
|
|
|
/** @internal */
|
|
export async function resolveNotionWorkspaceLabel(api: NotionPickerApi, connectionId: string): Promise<string> {
|
|
try {
|
|
const bot = (await api.retrieveBotUser()) as NotionBotInfo;
|
|
const workspaceName = typeof bot.bot?.workspace_name === 'string' ? bot.bot.workspace_name.trim() : '';
|
|
if (workspaceName.length > 0) {
|
|
return workspaceName;
|
|
}
|
|
const name = typeof bot.name === 'string' ? bot.name.trim() : '';
|
|
return name.length > 0 ? name : connectionId;
|
|
} catch {
|
|
return connectionId;
|
|
}
|
|
}
|
|
|
|
function assertNotionConnection(connection: KtxProjectConnectionConfig, connectionId: string): void {
|
|
if (connection.driver !== 'notion') {
|
|
throw new Error(`Connection "${connectionId}" is not a Notion connection`);
|
|
}
|
|
}
|
|
|
|
function stringArray(value: unknown): string[] {
|
|
return Array.isArray(value) ? value.filter((item): item is string => typeof item === 'string' && item.trim().length > 0) : [];
|
|
}
|
|
|
|
function notionCrawlMode(connection: KtxProjectConnectionConfig): 'all_accessible' | 'selected_roots' {
|
|
return connection.crawl_mode === 'all_accessible' ? 'all_accessible' : 'selected_roots';
|
|
}
|
|
|
|
function selectedPageCountText(count: number): string {
|
|
return `${count} selected ${count === 1 ? 'page' : 'pages'}`;
|
|
}
|
|
|
|
function notionChrome(args: {
|
|
workspaceLabel: string;
|
|
cappedAtCount: number | null;
|
|
currentCrawlMode: 'all_accessible' | 'selected_roots';
|
|
}): TreePickerChrome {
|
|
const warningLines: string[] = [];
|
|
if (args.cappedAtCount) {
|
|
warningLines.push(`${args.cappedAtCount}-page cap reached - some pages not shown`);
|
|
}
|
|
return {
|
|
title: 'Select Notion pages to ingest',
|
|
subtitleLines: [`Workspace: ${args.workspaceLabel}`],
|
|
warningLines,
|
|
confirmSaveMessage:
|
|
args.currentCrawlMode === 'all_accessible'
|
|
? (state) =>
|
|
`Switch crawl_mode from all_accessible to selected_roots? Will limit ingest to ${selectedPageCountText(
|
|
flattenSelection(state.checked, state.byId).length,
|
|
)}. Press Enter to confirm or Escape to go back.`
|
|
: undefined,
|
|
};
|
|
}
|
|
|
|
export async function pickNotionRootPages(
|
|
args: PickNotionRootPagesArgs,
|
|
io: KtxCliIo = process,
|
|
deps: NotionRootPagePickerDeps = {},
|
|
): Promise<NotionRootPagePickResult> {
|
|
try {
|
|
assertSafeNotionPickerConnectionId(args.connectionId);
|
|
assertNotionConnection(args.connection, args.connectionId);
|
|
const crawlMode = notionCrawlMode(args.connection);
|
|
const authToken = await resolveNotionConnectionAuthToken(
|
|
{
|
|
auth_token: typeof args.connection.auth_token === 'string' ? args.connection.auth_token : null,
|
|
auth_token_ref: typeof args.connection.auth_token_ref === 'string' ? args.connection.auth_token_ref : null,
|
|
},
|
|
{ env: deps.env },
|
|
);
|
|
const api = deps.createNotionApi ? deps.createNotionApi(authToken) : new NotionClient(authToken);
|
|
const discovery = await discoverNotionPickerPages(api);
|
|
const tree = buildPickerTree(discovery.pages);
|
|
const normalizedExistingIds = stringArray(args.connection.root_page_ids)
|
|
.map((raw) => tryNormalizeNotionPageId(raw))
|
|
.filter((id): id is string => id !== null);
|
|
const initialState = buildInitialState({
|
|
tree,
|
|
existingSelectedIds: normalizedExistingIds,
|
|
requireConfirmOnSave: crawlMode === 'all_accessible',
|
|
staleWarning: (count) => `${count} stored root_page_ids no longer visible - they will be removed if you save`,
|
|
});
|
|
const preLoadWarnings = [...discovery.warnings, ...initialState.preLoadWarnings];
|
|
const renderState =
|
|
preLoadWarnings.length > 0
|
|
? {
|
|
...initialState,
|
|
preLoadWarnings,
|
|
}
|
|
: initialState;
|
|
for (const warning of preLoadWarnings) {
|
|
io.stderr.write(`${warning}\n`);
|
|
}
|
|
const workspaceLabel = await resolveNotionWorkspaceLabel(api, args.connectionId);
|
|
const chrome = notionChrome({
|
|
workspaceLabel,
|
|
cappedAtCount: discovery.cappedAtCount,
|
|
currentCrawlMode: crawlMode,
|
|
});
|
|
const renderPicker =
|
|
deps.renderPicker ??
|
|
((chromeArg, state, ioArg) =>
|
|
renderTreePickerTui({ chrome: chromeArg, initialState: state }, ioArg, {
|
|
scriptedModeHint: NOTION_SCRIPTED_MODE_HINT,
|
|
}));
|
|
const result = await renderPicker(chrome, renderState, io as TreePickerTuiIo);
|
|
if (result.kind === 'quit') {
|
|
return { kind: 'back' };
|
|
}
|
|
if (result.selectedIds.length === 0) {
|
|
return { kind: 'unavailable', message: 'Notion picker did not return any selected pages.' };
|
|
}
|
|
return { kind: 'selected', rootPageIds: result.selectedIds };
|
|
} catch (error) {
|
|
return { kind: 'unavailable', message: error instanceof Error ? error.message : String(error) };
|
|
}
|
|
}
|