@dikolab/kbdb 0.1.1 → 0.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/dist/{chunk-QCCN7OZH.mjs → chunk-JG2UCKLI.mjs} +21 -8
  2. package/dist/chunk-JG2UCKLI.mjs.map +7 -0
  3. package/dist/cli.cjs +16 -4
  4. package/dist/cli.cjs.map +3 -3
  5. package/dist/cli.mjs +2 -2
  6. package/dist/cli.mjs.map +1 -1
  7. package/dist/kbdb-worker.cjs +38 -18
  8. package/dist/kbdb-worker.cjs.map +4 -4
  9. package/dist/mod.cjs +1 -1
  10. package/dist/mod.cjs.map +1 -1
  11. package/dist/mod.mjs +1 -1
  12. package/dist/mod.mjs.map +1 -1
  13. package/dist/src/shared/dir-resolver/functions/join-path.function.d.ts +2 -0
  14. package/dist/src/shared/dir-resolver/index.d.ts +1 -0
  15. package/dist/src/shared/version/constants/version.constant.d.ts +1 -1
  16. package/dist/src/shared/worker-daemon/functions/load-wasm-modules.function.d.ts +0 -16
  17. package/dist/wasm/fs-database/kbdb_fs_database.d.ts +220 -0
  18. package/dist/wasm/fs-database/kbdb_fs_database.js +458 -0
  19. package/dist/wasm/fs-database/kbdb_fs_database_bg.wasm +0 -0
  20. package/dist/wasm/fs-database/kbdb_fs_database_bg.wasm.d.ts +32 -0
  21. package/dist/wasm/fs-database/package.json +13 -0
  22. package/dist/wasm/kb-worker/kbdb_worker.d.ts +565 -0
  23. package/dist/wasm/kb-worker/kbdb_worker.js +1066 -0
  24. package/dist/wasm/kb-worker/kbdb_worker_bg.wasm +0 -0
  25. package/dist/wasm/kb-worker/kbdb_worker_bg.wasm.d.ts +72 -0
  26. package/dist/wasm/kb-worker/package.json +13 -0
  27. package/dist/wasm/query-parser/kbdb_query_parser.d.ts +195 -0
  28. package/dist/wasm/query-parser/kbdb_query_parser.js +403 -0
  29. package/dist/wasm/query-parser/kbdb_query_parser_bg.wasm +0 -0
  30. package/dist/wasm/query-parser/kbdb_query_parser_bg.wasm.d.ts +25 -0
  31. package/dist/wasm/query-parser/package.json +13 -0
  32. package/dist/worker.mjs +23 -13
  33. package/dist/worker.mjs.map +3 -3
  34. package/package.json +1 -1
  35. package/src/shared/dir-resolver/functions/join-path.function.ts +13 -0
  36. package/src/shared/dir-resolver/functions/resolve-wasm-dir.function.ts +2 -2
  37. package/src/shared/dir-resolver/functions/resolve-worker-script.function.ts +3 -3
  38. package/src/shared/dir-resolver/index.ts +4 -0
  39. package/src/shared/version/constants/version.constant.ts +1 -1
  40. package/src/shared/worker-daemon/functions/load-wasm-modules.function.ts +17 -20
  41. package/src/wasm/fs-database/kbdb_fs_database.d.ts +220 -0
  42. package/src/wasm/fs-database/kbdb_fs_database.js +458 -0
  43. package/src/wasm/fs-database/kbdb_fs_database_bg.wasm +0 -0
  44. package/src/wasm/fs-database/kbdb_fs_database_bg.wasm.d.ts +32 -0
  45. package/src/wasm/fs-database/package.json +13 -0
  46. package/src/wasm/kb-worker/kbdb_worker.d.ts +565 -0
  47. package/src/wasm/kb-worker/kbdb_worker.js +1066 -0
  48. package/src/wasm/kb-worker/kbdb_worker_bg.wasm +0 -0
  49. package/src/wasm/kb-worker/kbdb_worker_bg.wasm.d.ts +72 -0
  50. package/src/wasm/kb-worker/package.json +13 -0
  51. package/src/wasm/query-parser/kbdb_query_parser.d.ts +195 -0
  52. package/src/wasm/query-parser/kbdb_query_parser.js +403 -0
  53. package/src/wasm/query-parser/kbdb_query_parser_bg.wasm +0 -0
  54. package/src/wasm/query-parser/kbdb_query_parser_bg.wasm.d.ts +25 -0
  55. package/src/wasm/query-parser/package.json +13 -0
  56. package/dist/chunk-QCCN7OZH.mjs.map +0 -7
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../src/worker.ts", "../src/shared/worker-daemon/functions/read-config.function.ts", "../src/shared/worker-daemon/constants/daemon-defaults.constant.ts", "../src/shared/worker-daemon/functions/start-daemon.function.ts", "../src/shared/worker-daemon/classes/worker-daemon.class.ts", "../src/shared/worker-daemon/functions/load-wasm-modules.function.ts", "../src/shared/worker-daemon/functions/create-host-imports.function.ts", "../src/shared/worker-daemon/functions/create-ipc-server.function.ts", "../src/shared/wasm-codec/functions/encode-string.function.ts", "../src/shared/wasm-codec/functions/encode-u32.function.ts", "../src/shared/wasm-codec/functions/encode-option-string.function.ts", "../src/shared/wasm-codec/functions/encode-section-type.function.ts", "../src/shared/wasm-codec/functions/encode-add-section-params.function.ts", "../src/shared/wasm-codec/functions/encode-update-section-params.function.ts", "../src/shared/wasm-codec/functions/encode-kbid-list.function.ts", "../src/shared/wasm-codec/functions/encode-group-params.function.ts", "../src/shared/wasm-codec/functions/encode-identifier-list.function.ts", "../src/shared/wasm-codec/functions/encode-search-params.function.ts", "../src/shared/wasm-codec/functions/encode-type-filter-param.function.ts", "../src/shared/wasm-codec/functions/decode-string.function.ts", "../src/shared/wasm-codec/functions/decode-u32.function.ts", "../src/shared/wasm-codec/functions/decode-f32.function.ts", "../src/shared/wasm-codec/functions/decode-u64.function.ts", "../src/shared/wasm-codec/functions/decode-scored-results.function.ts", "../src/shared/wasm-codec/functions/decode-section-records.function.ts", "../src/shared/wasm-codec/functions/decode-section-record-list.function.ts", "../src/shared/wasm-codec/functions/decode-document-manifest.function.ts", "../src/shared/wasm-codec/functions/decode-document-manifest-list.function.ts", "../src/shared/wasm-codec/functions/decode-compose-output.function.ts", "../src/shared/wasm-codec/functions/decode-key-value-text.function.ts", "../src/shared/wasm-codec/functions/decode-remove-flag.function.ts", "../src/shared/worker-daemon/functions/run-worker.function.ts"],
4
- "sourcesContent": ["import { existsSync } from 'node:fs';\nimport { getArgs } from './shared/runtime/index.ts';\nimport {\n resolveBaseDir,\n resolveWasmDir,\n} from './shared/dir-resolver/index.ts';\nimport {\n startDaemon,\n runWorker,\n} from './shared/worker-daemon/index.ts';\n\nconst baseDir = resolveBaseDir(import.meta.url, import.meta.dirname);\nconst wasmDir = resolveWasmDir(baseDir.scriptDir);\n\nasync function main(): Promise<void> {\n const result = await runWorker(getArgs(), {\n existsSync,\n startDaemon,\n wasmDir,\n });\n if (result.error) {\n // eslint-disable-next-line no-console\n console.error(result.error);\n }\n if (result.exitCode !== 0) {\n process.exitCode = result.exitCode;\n }\n}\n\nmain().catch((err: unknown) => {\n // eslint-disable-next-line no-console\n console.error(err);\n process.exitCode = 1;\n});\n", "import { readFileSync } from 'node:fs';\nimport { join } from 'node:path';\nimport type { DaemonConfig } from '../typings/daemon-config.interface.ts';\nimport {\n DEFAULT_ITEM_LIMIT,\n DEFAULT_INDEX_LIMIT,\n DEFAULT_TIMEOUT_MS,\n DEFAULT_ITEM_TTL_MS,\n WORKER_TOML_FILENAME,\n} from '../constants/daemon-defaults.constant.ts';\n\n/**\n * Reads the `worker.toml` configuration file from the given\n * context directory and returns a `DaemonConfig`.\n *\n * Falls back to all-default values when the file is absent or\n * unreadable.\n *\n * @param contextPath - absolute path to the `.kbdb` context\n * directory\n */\nexport function readConfig(contextPath: string): DaemonConfig {\n const configPath = join(contextPath, WORKER_TOML_FILENAME);\n try {\n const text = readFileSync(configPath, 'utf-8');\n return parseWorkerToml(text, contextPath);\n } catch {\n return {\n contextPath,\n itemLimit: DEFAULT_ITEM_LIMIT,\n indexLimit: DEFAULT_INDEX_LIMIT,\n timeoutMs: DEFAULT_TIMEOUT_MS,\n itemTtlMs: DEFAULT_ITEM_TTL_MS,\n };\n }\n}\n\nfunction parseWorkerToml(\n text: string,\n contextPath: string,\n): DaemonConfig {\n const config: DaemonConfig = {\n contextPath,\n itemLimit: DEFAULT_ITEM_LIMIT,\n indexLimit: DEFAULT_INDEX_LIMIT,\n timeoutMs: DEFAULT_TIMEOUT_MS,\n itemTtlMs: DEFAULT_ITEM_TTL_MS,\n };\n\n const result = { ...config };\n\n for (const line of text.split('\\n')) {\n const trimmed = line.trim();\n if (trimmed.startsWith('#') || !trimmed.includes('=')) {\n continue;\n }\n const eqIdx = trimmed.indexOf('=');\n const key = trimmed.slice(0, eqIdx).trim();\n const value = trimmed.slice(eqIdx + 1).trim();\n switch (key) {\n case 'item_limit':\n result.itemLimit =\n parseInt(value, 10) || DEFAULT_ITEM_LIMIT;\n break;\n case 'index_limit':\n result.indexLimit =\n parseInt(value, 10) || DEFAULT_INDEX_LIMIT;\n break;\n case 'timeout_ms':\n result.timeoutMs =\n parseInt(value, 10) || DEFAULT_TIMEOUT_MS;\n break;\n case 'item_ttl_ms':\n result.itemTtlMs =\n parseInt(value, 10) || DEFAULT_ITEM_TTL_MS;\n break;\n default:\n break;\n }\n }\n\n return result;\n}\n", "/** Default maximum number of items held in daemon memory. */\nexport const DEFAULT_ITEM_LIMIT = 1000;\n\n/** Default maximum number of index entries held in daemon memory. */\nexport const DEFAULT_INDEX_LIMIT = 100;\n\n/**\n * Default idle timeout in milliseconds before the daemon shuts\n * down automatically (5 minutes).\n */\nexport const DEFAULT_TIMEOUT_MS = 300_000;\n\n/**\n * Default time-to-live in milliseconds for each cached item\n * (1 minute).\n */\nexport const DEFAULT_ITEM_TTL_MS = 60_000;\n\n/** Filename of the daemon configuration file inside `.kbdb/`. */\nexport const WORKER_TOML_FILENAME = 'worker.toml';\n\n/**\n * Database format version the daemon supports.\n *\n * Read from `catalog.toml` at startup. If the catalog version\n * differs, the daemon prints a structured error to stderr and\n * exits with code 1 before loading any WASM modules.\n */\nexport const DB_FORMAT_VERSION = 1;\n", "import { writeFileSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { tmpdir } from 'node:os';\nimport { readConfig } from './read-config.function.ts';\nimport { computeSha256 } from '../../hash/functions/compute-sha256.ts';\nimport { WorkerDaemon } from '../classes/worker-daemon.class.ts';\n\n/**\n * Starts the worker daemon for the given knowledge-base context.\n *\n * Reads configuration from `worker.toml` in the context directory,\n * validates startup preconditions (directory exists, accessible, and\n * database version compatible), and then starts the `WorkerDaemon`.\n *\n * Signal handlers for `SIGTERM` and `SIGINT` trigger a graceful stop.\n * Precondition failures are printed to stderr and cause exit code 1.\n *\n * @param contextPath - absolute path to the `.kbdb` context directory\n */\nexport async function startDaemon(\n contextPath: string,\n wasmDir?: string,\n): Promise<void> {\n const config = readConfig(contextPath);\n const hash = await computeSha256(contextPath);\n const contextId = hash.slice(0, 16);\n\n const daemon = new WorkerDaemon(\n contextId,\n contextPath,\n config,\n wasmDir,\n );\n\n try {\n daemon.checkPreconditions();\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n // eslint-disable-next-line no-console\n console.error(`kbdb-worker: ${message}`);\n writeCrashLog(contextId, message);\n process.exit(1);\n }\n\n try {\n await daemon.start();\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n // eslint-disable-next-line no-console\n console.error(`kbdb-worker: ${message}`);\n writeCrashLog(contextId, message);\n process.exit(1);\n }\n\n process.on('SIGTERM', () => {\n daemon.stop();\n });\n process.on('SIGINT', () => {\n daemon.stop();\n });\n}\n\nfunction writeCrashLog(contextId: string, message: string): void {\n try {\n const crashPath = join(tmpdir(), `kbdb-${contextId}.crash`);\n const payload = JSON.stringify({\n error: message,\n timestamp: Date.now(),\n });\n writeFileSync(crashPath, payload);\n } catch {\n // never mask the original error\n }\n}\n", "import {\n existsSync,\n readFileSync,\n accessSync,\n writeFileSync,\n unlinkSync,\n constants,\n} from 'node:fs';\nimport { join } from 'node:path';\nimport { tmpdir } from 'node:os';\nimport type { Server } from 'node:net';\nimport type { DaemonConfig } from '../typings/daemon-config.interface.ts';\nimport type { WasmModules } from '../typings/wasm-modules.interface.ts';\nimport type {\n IpcRequest,\n IpcResponse,\n IpcHandler,\n} from '../typings/ipc-handler.interface.ts';\nimport { DB_FORMAT_VERSION } from '../constants/daemon-defaults.constant.ts';\nimport { loadWasmModules } from '../functions/load-wasm-modules.function.ts';\nimport { createIpcServer } from '../functions/create-ipc-server.function.ts';\nimport { getIpcPath } from '../../platform/functions/get-ipc-path.function.ts';\nimport {\n encodeSearchParams,\n encodeAddSectionParams,\n encodeUpdateSectionParams,\n encodeKbidList,\n encodeGroupParams,\n encodeIdentifierList,\n encodeTypeFilterParam,\n decodeScoredResults,\n decodeSectionRecords,\n decodeSectionRecordList,\n decodeDocumentManifest,\n decodeDocumentManifestList,\n decodeComposeOutput,\n decodeKeyValueText,\n decodeRemoveFlag,\n} from '../../wasm-codec/index.ts';\n\nimport type { AddSectionInput } from '../../wasm-codec/index.ts';\n\n// ---------------------------------------------------------------------------\n// Internal types\n// ---------------------------------------------------------------------------\n\n/** Callable WASM export function signature. */\ntype WasmFn = (...args: unknown[]) => unknown;\n\n/** Mapping from IPC method name to kb-worker.wasm export name. */\nconst WASM_METHOD_MAP: Readonly<Partial<Record<string, string>>> = {\n search: 'worker_search',\n addSection: 'worker_add_section',\n add_section: 'worker_add_section',\n updateSection: 'worker_update_section',\n update_section: 'worker_update_section',\n removeSection: 'worker_remove_section',\n remove_section: 'worker_remove_section',\n readSections: 'worker_read_sections',\n read_sections: 'worker_read_sections',\n groupSections: 'worker_group_sections',\n group_sections: 'worker_group_sections',\n removeGrouping: 'worker_remove_grouping',\n remove_grouping: 'worker_remove_grouping',\n retrieveDocument: 'worker_retrieve_doc',\n retrieve_doc: 'worker_retrieve_doc',\n content: 'worker_compose',\n compose: 'worker_compose',\n integrity_check: 'worker_check_integrity',\n integrityCheck: 'worker_check_integrity',\n gc: 'worker_garbage_collect',\n rebuild_indexes: 'worker_rebuild_indexes',\n rebuildIndexes: 'worker_rebuild_indexes',\n init_directory: 'worker_init_directory',\n initDirectory: 'worker_init_directory',\n migrateDatabase: 'worker_migrate',\n query: 'worker_query',\n get_result_status: 'worker_result_status',\n get_result: 'worker_get_result',\n invalidate: 'worker_invalidate',\n invalidate_all: 'worker_invalidate_all',\n invalidateAll: 'worker_invalidate_all',\n db_status: 'worker_status',\n dbStatus: 'worker_status',\n listByType: 'worker_list_by_type',\n list_by_type: 'worker_list_by_type',\n listDocumentsByType: 'worker_list_docs_by_type',\n list_docs_by_type: 'worker_list_docs_by_type',\n};\n\n/** Config method name prefix. */\nconst CONFIG_PREFIX = 'config_';\n\n/** Config key \u2192 DaemonConfig property mapping. */\nconst CONFIG_KEY_MAP: Readonly<\n Partial<Record<string, keyof DaemonConfig>>\n> = {\n timeout_ms: 'timeoutMs',\n item_ttl_ms: 'itemTtlMs',\n item_limit: 'itemLimit',\n index_limit: 'indexLimit',\n};\n\n// ---------------------------------------------------------------------------\n// IpcError\n// ---------------------------------------------------------------------------\n\n/** Typed JSON-RPC error used internally by WorkerDaemon dispatch. */\nclass IpcError extends Error {\n /** JSON-RPC error code. */\n readonly code: number;\n\n constructor(code: number, message: string) {\n super(message);\n this.code = code;\n this.name = 'IpcError';\n }\n}\n\n// ---------------------------------------------------------------------------\n// WorkerDaemon\n// ---------------------------------------------------------------------------\n\n/**\n * Core daemon class that manages the full worker daemon lifecycle.\n *\n * Orchestrates WASM module loading, IPC server creation, request\n * routing to `kb-worker.wasm` exports, idle timeout tracking, and\n * graceful shutdown. The daemon validates startup preconditions before\n * loading WASM modules and rejects IPC requests whose `ctx` param does\n * not match the daemon's context ID.\n */\nexport class WorkerDaemon {\n /** Context ID (16-character hex SHA-256 prefix). */\n readonly ctx: string;\n\n /** Absolute path to the `.kbdb` directory. */\n readonly targetDir: string;\n\n /** Parsed daemon configuration from `worker.toml`. */\n readonly config: DaemonConfig;\n\n /** Number of currently active IPC client connections. */\n get connectionCount(): number {\n return this._connectionCount;\n }\n\n private _connectionCount = 0;\n private _wasmModules: WasmModules | null = null;\n private _idleAt = 0;\n private _idleTimer: ReturnType<typeof setTimeout> | null = null;\n private _server: Server | null = null;\n private readonly _wasmDir: string;\n\n /**\n * @param ctx - context ID (16-hex characters), the first 16 of\n * the SHA-256 hash of `targetDir`\n * @param targetDir - absolute path to the `.kbdb` directory\n * @param config - parsed daemon configuration\n * @param wasmDir - path to the WASM build output directory\n */\n constructor(\n ctx: string,\n targetDir: string,\n config: DaemonConfig,\n wasmDir?: string,\n ) {\n this.ctx = ctx;\n this.targetDir = targetDir;\n this.config = config;\n this._wasmDir = wasmDir ?? '';\n }\n\n // -----------------------------------------------------------------------\n // Public API\n // -----------------------------------------------------------------------\n\n /**\n * Validates startup preconditions before WASM module loading.\n *\n * Checks that the database directory exists, is readable and\n * writable, and that `catalog.toml` reports a compatible version.\n *\n * @throws {Error} if any precondition fails -- `startDaemon`\n * catches this, prints to stderr, and exits with code 1\n */\n checkPreconditions(): void {\n if (!existsSync(this.targetDir)) {\n throw new Error(\n `database directory not found: ${this.targetDir}`,\n );\n }\n\n try {\n accessSync(\n this.targetDir,\n\n constants.R_OK | constants.W_OK,\n );\n } catch {\n throw new Error(\n `cannot access database directory: ${this.targetDir}` +\n ' -- permission denied',\n );\n }\n\n this.checkCatalogVersion();\n }\n\n /**\n * Starts the daemon: loads WASM modules, writes the PID file,\n * creates the IPC socket, and begins listening for connections.\n *\n * Call `checkPreconditions()` before `start()` to validate the\n * database directory. The daemon will not start if any precondition\n * fails.\n *\n * @throws when WASM module loading fails or the IPC socket cannot\n * be created\n */\n async start(): Promise<void> {\n const wasmModules = await loadWasmModules(\n this.config,\n this._wasmDir,\n );\n this._wasmModules = wasmModules;\n\n this.initWorkerContext();\n\n const pidPath = join(tmpdir(), `kbdb-${this.ctx}.pid`);\n writeFileSync(pidPath, process.pid.toString());\n\n const ipcPath = getIpcPath(this.ctx);\n\n if (existsSync(ipcPath)) {\n try {\n unlinkSync(ipcPath);\n } catch {\n // ignore stale socket removal errors\n }\n }\n\n const handler: IpcHandler = (req) => this.handleRequest(req);\n this._server = createIpcServer(ipcPath, handler);\n\n this._server.on('connection', () => {\n this.incrementConnections();\n this.resetIdleTimer();\n });\n\n this._server.on('close', () => {\n this.decrementConnections();\n if (this._connectionCount === 0) {\n this.resetIdleTimer();\n }\n });\n\n this.resetIdleTimer();\n }\n\n /**\n * Gracefully shuts down the daemon.\n *\n * Stops accepting new connections, clears the idle timer, purges\n * WASM state, removes the PID file and IPC socket file, then exits\n * the process.\n */\n stop(): void {\n if (this._idleTimer !== null) {\n clearTimeout(this._idleTimer);\n this._idleTimer = null;\n }\n\n if (this._server !== null) {\n this._server.close();\n this._server = null;\n }\n\n this._wasmModules = null;\n\n const pidPath = join(tmpdir(), `kbdb-${this.ctx}.pid`);\n try {\n unlinkSync(pidPath);\n } catch {\n // ignore cleanup errors\n }\n\n const ipcPath = getIpcPath(this.ctx);\n try {\n unlinkSync(ipcPath);\n } catch {\n // ignore cleanup errors\n }\n\n const crashPath = join(tmpdir(), `kbdb-${this.ctx}.crash`);\n try {\n unlinkSync(crashPath);\n } catch {\n // ignore cleanup errors\n }\n\n process.exit(0);\n }\n\n /**\n * Handles a single JSON-RPC 2.0 request.\n *\n * Validates context, then routes to a daemon-state handler or a\n * WASM export. Requests whose `ctx` param does not match the\n * daemon's context ID are rejected with error code `-32001`.\n *\n * @param request - incoming JSON-RPC request\n * @returns the JSON-RPC response\n */\n async handleRequest(request: IpcRequest): Promise<IpcResponse> {\n const params = request.params as\n | Record<string, unknown>\n | undefined;\n if (params === undefined || params.ctx !== this.ctx) {\n return this.errorResponse(\n request.id,\n -32001,\n 'context mismatch',\n );\n }\n\n this.resetIdleTimer();\n\n try {\n const result = await this.dispatch(request.method, params);\n this._idleAt = Math.floor(Date.now() / 1000);\n return {\n jsonrpc: '2.0',\n id: request.id,\n result,\n };\n } catch (err) {\n this._idleAt = Math.floor(Date.now() / 1000);\n if (err instanceof IpcError) {\n return this.errorResponse(\n request.id,\n err.code,\n err.message,\n );\n }\n const message =\n err instanceof Error ? err.message : String(err);\n return this.errorResponse(request.id, -32000, message);\n }\n }\n\n /**\n * Increments the active connection count.\n *\n * Call when a new IPC client connects.\n */\n incrementConnections(): void {\n this._connectionCount++;\n }\n\n /**\n * Decrements the active connection count, clamped to zero.\n *\n * Call when an IPC client disconnects.\n */\n decrementConnections(): void {\n if (this._connectionCount > 0) {\n this._connectionCount--;\n }\n }\n\n /**\n * Injects pre-built WASM modules for unit testing.\n *\n * This method exists solely to support unit tests that cannot\n * load real WASM binaries. It must not be called in production\n * code -- production code uses `start()` to load modules.\n *\n * @param modules - pre-built WASM module instances\n * @internal\n */\n injectModulesForTesting(modules: WasmModules): void {\n this._wasmModules = modules;\n }\n\n // -----------------------------------------------------------------------\n // Private helpers\n // -----------------------------------------------------------------------\n\n /** Resets the idle timer; triggers stop() when it fires. */\n private resetIdleTimer(): void {\n if (this._idleTimer !== null) {\n clearTimeout(this._idleTimer);\n }\n if (this._connectionCount === 0) {\n this._idleTimer = setTimeout(() => {\n this.stop();\n }, this.config.timeoutMs);\n }\n }\n\n /** Reads catalog.toml and validates the version field. */\n private checkCatalogVersion(): void {\n const catalogPath = join(this.targetDir, 'catalog.toml');\n let text: string;\n try {\n text = readFileSync(catalogPath, 'utf-8');\n } catch {\n throw new Error(\n `cannot read database directory: ${this.targetDir}` +\n ' -- permission denied',\n );\n }\n\n const version = parseCatalogVersion(text);\n if (version === null) {\n throw new Error(\n 'database version 0 requires migration to version ' +\n String(DB_FORMAT_VERSION) +\n ' -- run `kbdb --migrate` before starting the daemon',\n );\n }\n\n if (version > DB_FORMAT_VERSION) {\n throw new Error(\n 'database version ' +\n String(version) +\n ' is newer than kbdb version ' +\n String(DB_FORMAT_VERSION) +\n ' -- upgrade kbdb to open this database',\n );\n }\n\n if (version < DB_FORMAT_VERSION) {\n throw new Error(\n 'database version ' +\n String(version) +\n ' requires migration to version ' +\n String(DB_FORMAT_VERSION) +\n ' -- run `kbdb --migrate` before starting the daemon',\n );\n }\n }\n\n /** Builds a JSON-RPC error response. */\n private errorResponse(\n id: number | string,\n code: number,\n message: string,\n ): IpcResponse {\n return {\n jsonrpc: '2.0',\n id,\n error: { code, message },\n };\n }\n\n /**\n * Dispatches a request method to the appropriate handler.\n *\n * Handles daemon-state methods (`status`, `idle_at`,\n * `config_{key}`) inline and routes WASM methods to the\n * correct calling convention for each export.\n */\n private dispatch(\n method: string,\n params: Record<string, unknown>,\n ): unknown {\n if (method === 'status') {\n return this._connectionCount > 0 ? 'busy' : 'idle';\n }\n\n if (method === 'idle_at') {\n return this._idleAt;\n }\n\n if (method === 'checkVersion') {\n return this.handleCheckVersion(params);\n }\n\n if (method.startsWith(CONFIG_PREFIX)) {\n return this.handleConfigMethod(method);\n }\n\n const wasmMethod = WASM_METHOD_MAP[method];\n if (wasmMethod !== undefined) {\n return this.dispatchWasm(method, wasmMethod, params);\n }\n\n throw new IpcError(-32601, `Method not found: ${method}`);\n }\n\n private dispatchWasm(\n method: string,\n wasmExport: string,\n params: Record<string, unknown>,\n ): unknown {\n if (method === 'search' || method === 'query') {\n return this.handleSearch(params);\n }\n if (method === 'addSection' || method === 'add_section') {\n return this.handleAddSection(params);\n }\n if (method === 'updateSection' || method === 'update_section') {\n return this.handleUpdateSection(params);\n }\n if (method === 'removeSection' || method === 'remove_section') {\n return this.handleRemoveSection(params);\n }\n if (method === 'readSections' || method === 'read_sections') {\n return this.handleReadSections(params);\n }\n if (method === 'retrieveDocument' || method === 'retrieve_doc') {\n return this.handleRetrieveDoc(params);\n }\n if (method === 'groupSections' || method === 'group_sections') {\n return this.handleGroupSections(params);\n }\n if (method === 'removeGrouping' || method === 'remove_grouping') {\n return this.handleRemoveGrouping(params);\n }\n if (method === 'content' || method === 'compose') {\n return this.handleCompose(params);\n }\n if (method === 'integrityCheck' || method === 'integrity_check') {\n return this.handleIntegrityCheck();\n }\n if (method === 'gc') {\n return this.handleGc();\n }\n if (method === 'rebuildIndexes' || method === 'rebuild_indexes') {\n return this.handleRebuild();\n }\n if (method === 'dbStatus' || method === 'db_status') {\n return this.handleDbStatus();\n }\n if (method === 'initDirectory' || method === 'init_directory') {\n return this.handleInitDirectory(params);\n }\n if (method === 'invalidate') {\n return this.handleInvalidate(params);\n }\n if (method === 'invalidateAll' || method === 'invalidate_all') {\n return this.handleInvalidateAll();\n }\n if (method === 'get_result_status') {\n return this.handleResultStatus(params);\n }\n if (method === 'get_result') {\n return this.handleGetResult(params);\n }\n if (method === 'migrateDatabase') {\n throw new IpcError(\n -32601,\n 'migrateDatabase is not yet supported',\n );\n }\n if (method === 'listByType' || method === 'list_by_type') {\n return this.handleListByType(params);\n }\n if (\n method === 'listDocumentsByType' ||\n method === 'list_docs_by_type'\n ) {\n return this.handleListDocsByType(params);\n }\n return this.invokeWasmRaw(wasmExport, new Uint8Array(0));\n }\n\n // -- Search/query (token-based async) --\n\n private handleSearch(params: Record<string, unknown>): unknown {\n const query = (params['query'] as string | undefined) ?? '';\n const mode = (params['mode'] as string | undefined) ?? 'and';\n const limit = Number(params['limit'] ?? 20);\n const encoded = encodeSearchParams(query, mode, limit);\n\n const searchFn = this.getExport('worker_search');\n const ptr = this.wasmAlloc(encoded.length);\n this.wasmWrite(ptr, encoded);\n const token = searchFn(ptr, encoded.length) as number;\n this.wasmFree(ptr, encoded.length);\n\n const statusFn = this.getExport('worker_result_status');\n const status = statusFn(token) as number;\n if (status === 3) {\n const getResultFn = this.getExport('worker_get_result');\n getResultFn(token);\n const errBytes = this.readReturnSlot();\n const errMsg = new TextDecoder().decode(errBytes);\n throw new IpcError(-32000, errMsg);\n }\n\n const getResultFn = this.getExport('worker_get_result');\n const rc = getResultFn(token) as number;\n if (rc === -1) {\n const errBytes = this.readReturnSlot();\n throw new IpcError(-32000, new TextDecoder().decode(errBytes));\n }\n const resultBytes = this.readReturnSlot();\n return decodeScoredResults(resultBytes);\n }\n\n // -- Token status/result (u32 direct params) --\n\n private handleResultStatus(\n params: Record<string, unknown>,\n ): unknown {\n const token = Number(params['token'] ?? 0);\n const fn = this.getExport('worker_result_status');\n const status = fn(token) as number;\n return { status };\n }\n\n private handleGetResult(params: Record<string, unknown>): unknown {\n const token = Number(params['token'] ?? 0);\n const fn = this.getExport('worker_get_result');\n const rc = fn(token) as number;\n if (rc === -1) {\n const errBytes = this.readReturnSlot();\n throw new IpcError(-32000, new TextDecoder().decode(errBytes));\n }\n const bytes = this.readReturnSlot();\n return decodeScoredResults(bytes);\n }\n\n // -- Binary-encoded input methods --\n\n private handleAddSection(params: Record<string, unknown>): unknown {\n const sectionType = (params['sectionType'] ?? 'text') as string;\n const semanticType =\n sectionType === 'text' ||\n sectionType === 'code' ||\n sectionType === 'image'\n ? sectionType\n : 'text';\n const typeName =\n sectionType !== semanticType ? sectionType : null;\n const input: AddSectionInput = {\n sectionType: semanticType,\n mimeType: params['mimeType'] as string | undefined,\n content: (params['content'] as string | undefined) ?? '',\n title: (params['title'] as string | null) ?? null,\n description: (params['description'] as string | null) ?? null,\n docid: (params['docid'] as string | null) ?? null,\n typeName,\n };\n const encoded = encodeAddSectionParams(input);\n const bytes = this.callWasmSync('worker_add_section', encoded);\n const kbid = new TextDecoder().decode(bytes);\n return { kbid };\n }\n\n private handleUpdateSection(\n params: Record<string, unknown>,\n ): unknown {\n const oldKbid = (params['kbid'] as string | undefined) ?? '';\n const updSectionType = (params['sectionType'] ??\n 'text') as string;\n const updSemanticType =\n updSectionType === 'text' ||\n updSectionType === 'code' ||\n updSectionType === 'image'\n ? updSectionType\n : 'text';\n const updTypeName =\n updSectionType !== updSemanticType ? updSectionType : null;\n const input: AddSectionInput = {\n sectionType: updSemanticType,\n mimeType: params['mimeType'] as string | undefined,\n content: (params['content'] as string | undefined) ?? '',\n title: (params['title'] as string | null) ?? null,\n description: (params['description'] as string | null) ?? null,\n docid: (params['docid'] as string | null) ?? null,\n typeName: updTypeName,\n };\n const encoded = encodeUpdateSectionParams(oldKbid, input);\n const bytes = this.callWasmSync('worker_update_section', encoded);\n const newKbid = new TextDecoder().decode(bytes);\n return { kbid: newKbid };\n }\n\n private handleReadSections(\n params: Record<string, unknown>,\n ): unknown {\n const kbids = (params['kbids'] ?? []) as string[];\n const encoded = encodeKbidList(kbids);\n const bytes = this.callWasmSync('worker_read_sections', encoded);\n return decodeSectionRecords(bytes);\n }\n\n private handleGroupSections(\n params: Record<string, unknown>,\n ): unknown {\n const title = (params['title'] as string | undefined) ?? '';\n const kbids = (params['kbids'] ?? []) as string[];\n const docType = (params['docType'] as string | undefined) ?? '';\n const encoded = encodeGroupParams(title, kbids, docType);\n const bytes = this.callWasmSync('worker_group_sections', encoded);\n const docid = new TextDecoder().decode(bytes);\n return { docid };\n }\n\n private handleCompose(params: Record<string, unknown>): unknown {\n const ids = (params['ids'] ?? []) as string[];\n const encoded = encodeIdentifierList(ids);\n const bytes = this.callWasmSync('worker_compose', encoded);\n const output = decodeComposeOutput(bytes);\n return {\n data: output.markdown,\n total: Number(output.totalChars),\n };\n }\n\n // -- Raw UTF-8 string input methods --\n\n private handleRemoveSection(\n params: Record<string, unknown>,\n ): unknown {\n const kbid = (params['kbid'] as string | undefined) ?? '';\n const encoded = new TextEncoder().encode(kbid);\n const bytes = this.callWasmSync('worker_remove_section', encoded);\n return { removed: decodeRemoveFlag(bytes) };\n }\n\n private handleRetrieveDoc(params: Record<string, unknown>): unknown {\n const docid = (params['docid'] as string | undefined) ?? '';\n const encoded = new TextEncoder().encode(docid);\n const bytes = this.callWasmSync('worker_retrieve_doc', encoded);\n return decodeDocumentManifest(bytes);\n }\n\n private handleRemoveGrouping(\n params: Record<string, unknown>,\n ): unknown {\n const docid = (params['docid'] as string | undefined) ?? '';\n const encoded = new TextEncoder().encode(docid);\n this.callWasmSync('worker_remove_grouping', encoded);\n return { ok: true };\n }\n\n private handleInitDirectory(\n params: Record<string, unknown>,\n ): unknown {\n const path =\n (params['path'] as string | undefined) ?? this.targetDir;\n const encoded = new TextEncoder().encode(path);\n this.callWasmSync('worker_init_directory', encoded);\n return { ok: true };\n }\n\n private handleInvalidate(params: Record<string, unknown>): unknown {\n const kbid = (params['kbid'] as string | undefined) ?? '';\n const encoded = new TextEncoder().encode(kbid);\n this.callWasmSync('worker_invalidate', encoded);\n return { ok: true };\n }\n\n private handleListByType(params: Record<string, unknown>): unknown {\n const typeStr =\n (params['sectionType'] as string | undefined) ?? '';\n const encoded = encodeTypeFilterParam(typeStr);\n const bytes = this.callWasmSync('worker_list_by_type', encoded);\n return decodeSectionRecordList(bytes);\n }\n\n private handleListDocsByType(\n params: Record<string, unknown>,\n ): unknown {\n const typeStr = (params['docType'] as string | undefined) ?? '';\n const encoded = encodeTypeFilterParam(typeStr);\n const bytes = this.callWasmSync(\n 'worker_list_docs_by_type',\n encoded,\n );\n return decodeDocumentManifestList(bytes);\n }\n\n // -- Zero-arg methods --\n\n private handleInvalidateAll(): unknown {\n this.callWasmZeroArg('worker_invalidate_all');\n return { ok: true };\n }\n\n private handleDbStatus(): unknown {\n this.callWasmZeroArg('worker_status');\n const bytes = this.readReturnSlot();\n const text = new TextDecoder().decode(bytes);\n return decodeKeyValueText(text);\n }\n\n private handleIntegrityCheck(): unknown {\n this.callWasmZeroArg('worker_check_integrity');\n const bytes = this.readReturnSlot();\n const text = new TextDecoder().decode(bytes);\n return decodeKeyValueText(text);\n }\n\n private handleGc(): unknown {\n this.callWasmZeroArg('worker_garbage_collect');\n const bytes = this.readReturnSlot();\n const text = new TextDecoder().decode(bytes);\n return decodeKeyValueText(text);\n }\n\n private handleRebuild(): unknown {\n this.callWasmZeroArg('worker_rebuild_indexes');\n return { ok: true };\n }\n\n // -- WASM lifecycle --\n\n private initWorkerContext(): void {\n const pathBytes = new TextEncoder().encode('.');\n this.callWasmSync('worker_init', pathBytes);\n }\n\n // -- WASM bridge primitives --\n\n private getExport(name: string): WasmFn {\n if (this._wasmModules === null) {\n throw new Error('WASM modules not loaded');\n }\n const fn = this._wasmModules.kbWorker.exports[name] as\n | WasmFn\n | undefined;\n if (typeof fn !== 'function') {\n throw new Error(`WASM export not found: ${name}`);\n }\n return fn;\n }\n\n private wasmAlloc(size: number): number {\n if (size === 0) return 0;\n const allocFn = this._wasmModules?.kbWorker.exports[\n 'kbdb_alloc'\n ] as WasmFn | undefined;\n if (typeof allocFn !== 'function') return 0;\n return allocFn(size) as number;\n }\n\n private wasmFree(ptr: number, size: number): void {\n if (ptr === 0 || size === 0) return;\n const freeFn = this._wasmModules?.kbWorker.exports[\n 'kbdb_free'\n ] as WasmFn | undefined;\n if (typeof freeFn === 'function') {\n freeFn(ptr, size);\n }\n }\n\n private wasmWrite(ptr: number, data: Uint8Array): void {\n if (data.length === 0) return;\n const memory = this._wasmModules?.memory;\n if (!memory) return;\n const memView = new Uint8Array(memory.buffer);\n if (ptr + data.length > memView.length) {\n throw new Error('WASM memory overflow');\n }\n memView.set(data, ptr);\n }\n\n private readReturnSlot(): Uint8Array {\n const getPtrFn = this._wasmModules?.kbWorker.exports[\n 'get_return_ptr'\n ] as WasmFn | undefined;\n const getLenFn = this._wasmModules?.kbWorker.exports[\n 'get_return_len'\n ] as WasmFn | undefined;\n if (\n typeof getPtrFn !== 'function' ||\n typeof getLenFn !== 'function'\n ) {\n return new Uint8Array(0);\n }\n const ptr = getPtrFn() as number;\n const len = getLenFn() as number;\n if (ptr === 0 || len === 0) {\n return new Uint8Array(0);\n }\n const memory = this._wasmModules?.memory;\n if (!memory) return new Uint8Array(0);\n const data = new Uint8Array(memory.buffer, ptr, len).slice();\n this.wasmFree(ptr, len);\n return data;\n }\n\n private callWasmSync(\n exportName: string,\n input: Uint8Array,\n ): Uint8Array {\n const fn = this.getExport(exportName);\n const ptr = this.wasmAlloc(input.length);\n this.wasmWrite(ptr, input);\n const rc = fn(ptr, input.length) as number;\n this.wasmFree(ptr, input.length);\n if (rc === -1) {\n const errBytes = this.readReturnSlot();\n const errMsg = new TextDecoder().decode(errBytes);\n throw new IpcError(-32000, errMsg || exportName + ' failed');\n }\n return this.readReturnSlot();\n }\n\n private callWasmZeroArg(exportName: string): void {\n const fn = this.getExport(exportName);\n const rc = fn() as number;\n if (rc === -1) {\n const errBytes = this.readReturnSlot();\n const errMsg = new TextDecoder().decode(errBytes);\n throw new IpcError(-32000, errMsg || exportName + ' failed');\n }\n }\n\n private invokeWasmRaw(\n exportName: string,\n input: Uint8Array,\n ): unknown {\n return this.callWasmSync(exportName, input);\n }\n\n private handleCheckVersion(\n params: Record<string, unknown>,\n ): unknown {\n const targetPath =\n typeof params.targetPath === 'string'\n ? params.targetPath\n : this.targetDir;\n const catalogPath = join(targetPath, 'catalog.toml');\n let text: string;\n try {\n text = readFileSync(catalogPath, 'utf-8');\n } catch {\n return {\n status: 'needs_migration',\n currentVersion: 0,\n requiredVersion: DB_FORMAT_VERSION,\n };\n }\n const version = parseCatalogVersion(text);\n if (version === null) {\n return {\n status: 'needs_migration',\n currentVersion: 0,\n requiredVersion: DB_FORMAT_VERSION,\n };\n }\n if (version > DB_FORMAT_VERSION) {\n return {\n status: 'too_new',\n currentVersion: version,\n requiredVersion: DB_FORMAT_VERSION,\n };\n }\n if (version < DB_FORMAT_VERSION) {\n return {\n status: 'needs_migration',\n currentVersion: version,\n requiredVersion: DB_FORMAT_VERSION,\n };\n }\n return {\n status: 'compatible',\n currentVersion: version,\n requiredVersion: DB_FORMAT_VERSION,\n };\n }\n\n /** Returns a daemon config value by config method name. */\n private handleConfigMethod(method: string): unknown {\n const key = method.slice(CONFIG_PREFIX.length);\n const prop = CONFIG_KEY_MAP[key];\n if (prop === undefined) {\n throw new IpcError(-32601, `Method not found: ${method}`);\n }\n return this.config[prop];\n }\n}\n\n// ---------------------------------------------------------------------------\n// Module-private helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Parses the `version` field from a minimal TOML string.\n *\n * Supports only `version = <integer>` syntax. Returns `null` if the\n * field is absent.\n */\nfunction parseCatalogVersion(text: string): number | null {\n for (const line of text.split('\\n')) {\n const trimmed = line.trim();\n if (trimmed.startsWith('#')) continue;\n const match = /^version\\s*=\\s*(\\d+)/.exec(trimmed);\n if (match?.[1] !== undefined) {\n return parseInt(match[1], 10);\n }\n }\n return null;\n}\n", "import { readFileSync } from 'node:fs';\nimport { join } from 'node:path';\nimport type { DaemonConfig } from '../typings/daemon-config.interface.ts';\nimport type { WasmModules } from '../typings/wasm-modules.interface.ts';\nimport { createHostImports } from './create-host-imports.function.ts';\nimport type {\n AllocatorRef,\n MemoryRef,\n} from './create-host-imports.function.ts';\n\n/**\n * Loads and instantiates the `kb-worker` WASM module.\n *\n * `kb-worker.wasm` statically links the `fs-database` and\n * `query-parser` crates, so only one module needs to be\n * instantiated. The module exports its own linear memory;\n * host I/O imports read it through a deferred `MemoryRef`\n * that is wired up immediately after instantiation.\n *\n * @param config - daemon configuration, used to supply the context\n * path to the host I/O imports\n * @param wasmDir - absolute path to the directory containing the\n * compiled WASM subdirectories (`query-parser/`, `fs-database/`,\n * `kb-worker/`)\n * @throws when the WASM file cannot be read or instantiated\n */\nexport async function loadWasmModules(\n config: DaemonConfig,\n wasmDir: string,\n): Promise<WasmModules> {\n const memoryRef: MemoryRef = { memory: null };\n const allocator: AllocatorRef = { alloc: null };\n\n const hostImports = createHostImports(\n config.contextPath,\n memoryRef,\n undefined,\n allocator,\n );\n\n const wkPath = join(wasmDir, 'kb-worker', 'kbdb_worker_bg.wasm');\n const wkBytes = readWasmFileOrThrow(wkPath, 'kb-worker');\n\n let wkModule: WebAssembly.Module;\n try {\n wkModule = await WebAssembly.compile(wkBytes);\n } catch (err) {\n rethrow('compile', 'kb-worker', err);\n }\n\n let kbWorker: WebAssembly.Instance;\n try {\n kbWorker = await WebAssembly.instantiate(wkModule, {\n env: { ...hostImports },\n });\n } catch (err) {\n rethrow('instantiate', 'kb-worker', err);\n }\n\n const memory = kbWorker.exports['memory'] as WebAssembly.Memory;\n memoryRef.memory = memory;\n\n allocator.alloc = (size: number): number => {\n const fn_ = kbWorker.exports['kbdb_alloc'] as\n | ((s: number) => number)\n | undefined;\n if (typeof fn_ !== 'function') return 0;\n return fn_(size);\n };\n\n return { memory, kbWorker };\n}\n\nfunction readWasmFileOrThrow(path: string, label: string): ArrayBuffer {\n try {\n const buf = readFileSync(path);\n return buf.buffer.slice(\n buf.byteOffset,\n buf.byteOffset + buf.byteLength,\n );\n } catch (err) {\n rethrow('load', label, err, path);\n }\n}\n\nfunction rethrow(\n stage: string,\n label: string,\n err: unknown,\n path?: string,\n): never {\n const detail = err instanceof Error ? err.message : String(err);\n const suffix = path ? ` (path: ${path})` : '';\n const message = `failed to ${stage} ${label} WASM: ${detail}${suffix}`;\n // eslint-disable-next-line no-console\n console.error(`kbdb-worker: ${message}`);\n throw new Error(message, { cause: err });\n}\n", "import {\n readFileSync,\n writeFileSync,\n renameSync,\n unlinkSync,\n readdirSync,\n mkdirSync,\n existsSync,\n} from 'node:fs';\nimport { join } from 'node:path';\n\n// ---------------------------------------------------------------------------\n// FsAdapter interface (enables dependency injection for testing)\n// ---------------------------------------------------------------------------\n\n/**\n * Minimal filesystem operations required by the host imports.\n *\n * The default implementation delegates to `node:fs` synchronous\n * APIs. Tests inject a stub to avoid touching the real filesystem.\n */\nexport interface FsAdapter {\n /** Read entire file as a Buffer. */\n readFileSync(path: string): Buffer;\n /** Write data buffer to file. */\n writeFileSync(path: string, data: Uint8Array): void;\n /** Rename `oldPath` to `newPath`. */\n renameSync(oldPath: string, newPath: string): void;\n /** Delete a file. */\n unlinkSync(path: string): void;\n /** List directory entries as strings. */\n readdirSync(path: string): string[];\n /** Create a directory (and parents) recursively. */\n mkdirSync(path: string): void;\n /** Return true if the path exists. */\n existsSync(path: string): boolean;\n}\n\n// ---------------------------------------------------------------------------\n// MemoryRef interface\n// ---------------------------------------------------------------------------\n\n/**\n * A mutable reference to the WASM linear memory.\n *\n * The `memory` field starts as `null` and is wired up after the\n * `kb-worker` WASM module is instantiated (the module exports its\n * own memory rather than importing one). Host import functions\n * read `memory` at call time, not at creation time, so the ref\n * can be populated after the import record is built.\n */\nexport interface MemoryRef {\n memory: WebAssembly.Memory | null;\n}\n\n// ---------------------------------------------------------------------------\n// AllocatorRef interface\n// ---------------------------------------------------------------------------\n\n/**\n * A mutable reference to the WASM allocator function.\n *\n * The `alloc` field starts as `null` and is wired up after the\n * `kb-worker` WASM module is instantiated. Host import functions\n * that must allocate memory in WASM linear memory check this\n * reference before proceeding and return -1 when it is null.\n */\nexport interface AllocatorRef {\n /**\n * Allocates `size` bytes in WASM linear memory and returns the\n * byte offset of the allocated region, or `null` when the\n * allocator is not yet available.\n */\n alloc: ((size: number) => number) | null;\n}\n\n/** Default `FsAdapter` backed by `node:fs` synchronous APIs. */\nconst nodeFsAdapter: FsAdapter = {\n readFileSync: (p) => readFileSync(p),\n writeFileSync: (p, d) => {\n writeFileSync(p, d);\n },\n renameSync: (o, n) => {\n renameSync(o, n);\n },\n unlinkSync: (p) => {\n unlinkSync(p);\n },\n readdirSync: (p) => readdirSync(p),\n mkdirSync: (p) => {\n mkdirSync(p, { recursive: true });\n },\n existsSync: (p) => existsSync(p),\n};\n\n/** Default `MemoryRef` with no memory wired. */\nconst nullMemory: MemoryRef = { memory: null };\n\n/** Default `AllocatorRef` with no allocator wired. */\nconst nullAllocator: AllocatorRef = { alloc: null };\n\n// ---------------------------------------------------------------------------\n// createHostImports\n// ---------------------------------------------------------------------------\n\n/**\n * Creates the host I/O import functions required by `kb-worker.wasm`.\n *\n * All functions read the WASM linear memory through `memoryRef`,\n * a deferred reference wired up after module instantiation (the\n * module exports its own memory). Paths from WASM are resolved\n * relative to `contextPath`.\n *\n * @param contextPath - absolute path to the `.kbdb` database directory\n * @param memoryRef - deferred reference to the WASM module's\n * exported memory; wired after instantiation\n * @param fs - filesystem adapter; defaults to real `node:fs` operations\n * @param allocator - reference to the WASM allocator; wired after\n * `kb-worker` instantiation. Defaults to a null (uninitialized) ref.\n * @returns a record of host import functions keyed by their WASM import\n * names\n */\nexport function createHostImports(\n contextPath: string,\n memoryRef: MemoryRef = nullMemory,\n fs: FsAdapter = nodeFsAdapter,\n allocator: AllocatorRef = nullAllocator,\n): Record<string, WebAssembly.ImportValue> {\n function getBuffer(): ArrayBuffer {\n if (!memoryRef.memory) {\n throw new Error('WASM memory not initialized');\n }\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion\n return memoryRef.memory.buffer as ArrayBuffer;\n }\n\n function readPathArg(ptr: number, len: number): string {\n const bytes = new Uint8Array(getBuffer(), ptr, len);\n const relative = new TextDecoder().decode(bytes);\n return join(contextPath, relative);\n }\n\n return {\n /**\n * Reads a file at the path encoded in shared memory and writes\n * the result back via the out-pointer protocol.\n *\n * `outPtr` and `outLen` are WASM linear-memory addresses. On\n * success, the host allocates a buffer via `allocator.alloc`,\n * copies the file data there, and writes the allocated pointer\n * as a LE u32 to `outPtr` and the data length as a LE u32 to\n * `outLen`. Returns 0 on success, -1 on error or when the\n * allocator is not yet available.\n */\n host_read_file(\n pathPtr: number,\n pathLen: number,\n outPtr: number,\n outLen: number,\n ): number {\n try {\n if (!allocator.alloc) return -1;\n const filePath = readPathArg(pathPtr, pathLen);\n const data = fs.readFileSync(filePath);\n const dataLen = data.byteLength;\n const dv = new DataView(getBuffer());\n if (dataLen === 0) {\n dv.setUint32(outPtr, 0, true);\n dv.setUint32(outLen, 0, true);\n return 0;\n }\n const dataPtr = allocator.alloc(dataLen);\n if (dataPtr === 0) return -1;\n const memView = new Uint8Array(getBuffer());\n memView.set(\n new Uint8Array(\n data.buffer,\n data.byteOffset,\n data.byteLength,\n ),\n dataPtr,\n );\n dv.setUint32(outPtr, dataPtr, true);\n dv.setUint32(outLen, dataLen, true);\n return 0;\n } catch {\n return -1;\n }\n },\n\n /**\n * Writes bytes from shared memory (`dataPtr`, `dataLen`) to the\n * file at the path encoded in shared memory. Returns 0 on\n * success, -1 on error.\n */\n host_write_file(\n pathPtr: number,\n pathLen: number,\n dataPtr: number,\n dataLen: number,\n ): number {\n try {\n const filePath = readPathArg(pathPtr, pathLen);\n const data = new Uint8Array(getBuffer(), dataPtr, dataLen);\n fs.writeFileSync(filePath, data);\n return 0;\n } catch {\n return -1;\n }\n },\n\n /**\n * Renames the file at `oldPtr/oldLen` to `newPtr/newLen`.\n * Both paths are resolved relative to `contextPath`. Returns 0\n * on success, -1 on error.\n */\n host_rename(\n oldPtr: number,\n oldLen: number,\n newPtr: number,\n newLen: number,\n ): number {\n try {\n const oldPath = readPathArg(oldPtr, oldLen);\n const newPath = readPathArg(newPtr, newLen);\n fs.renameSync(oldPath, newPath);\n return 0;\n } catch {\n return -1;\n }\n },\n\n /**\n * Deletes the file at the path encoded in shared memory.\n * Returns 0 on success, -1 on error.\n */\n host_remove_file(pathPtr: number, pathLen: number): number {\n try {\n const filePath = readPathArg(pathPtr, pathLen);\n fs.unlinkSync(filePath);\n return 0;\n } catch {\n return -1;\n }\n },\n\n /**\n * Lists the directory at the path encoded in shared memory and\n * writes the result back via the out-pointer protocol.\n *\n * `outPtr` and `outLen` are WASM linear-memory addresses. On\n * success, the host allocates a buffer via `allocator.alloc`,\n * copies a newline-delimited UTF-8 listing there, and writes\n * the allocated pointer as a LE u32 to `outPtr` and the byte\n * length as a LE u32 to `outLen`. Returns 0 on success, -1 on\n * error or when the allocator is not yet available.\n */\n host_list_dir(\n pathPtr: number,\n pathLen: number,\n outPtr: number,\n outLen: number,\n ): number {\n try {\n if (!allocator.alloc) return -1;\n const dirPath = readPathArg(pathPtr, pathLen);\n const entries = fs.readdirSync(dirPath);\n const text = entries.join('\\n');\n const encoded = new TextEncoder().encode(text);\n const dv = new DataView(getBuffer());\n if (encoded.length === 0) {\n dv.setUint32(outPtr, 0, true);\n dv.setUint32(outLen, 0, true);\n return 0;\n }\n const dataPtr = allocator.alloc(encoded.length);\n if (dataPtr === 0) return -1;\n new Uint8Array(getBuffer(), dataPtr, encoded.length).set(\n encoded,\n );\n dv.setUint32(outPtr, dataPtr, true);\n dv.setUint32(outLen, encoded.length, true);\n return 0;\n } catch {\n return -1;\n }\n },\n\n /**\n * Creates the directory at the path encoded in shared memory,\n * including any missing parent directories (recursive). Returns\n * 0 on success, -1 on error.\n */\n host_mkdir(pathPtr: number, pathLen: number): number {\n try {\n const dirPath = readPathArg(pathPtr, pathLen);\n fs.mkdirSync(dirPath);\n return 0;\n } catch {\n return -1;\n }\n },\n\n /**\n * Checks whether the file at the path encoded in shared memory\n * exists. Returns 1 if it exists, 0 if it does not.\n */\n host_file_exists(pathPtr: number, pathLen: number): number {\n const filePath = readPathArg(pathPtr, pathLen);\n return fs.existsSync(filePath) ? 1 : 0;\n },\n };\n}\n", "import { createServer } from 'node:net';\nimport type { Server, Socket } from 'node:net';\nimport type {\n IpcHandler,\n IpcRequest,\n IpcResponse,\n} from '../typings/ipc-handler.interface.ts';\n\n/**\n * Creates a Unix socket (or named pipe on Windows) IPC server that\n * reads newline-delimited JSON-RPC requests and writes responses.\n *\n * Each line received on a socket connection is parsed as an\n * `IpcRequest`, dispatched to `handler`, and the resulting\n * `IpcResponse` is written back as a newline-terminated JSON string.\n * A malformed line that cannot be parsed results in a JSON-RPC\n * parse-error response (`-32700`).\n *\n * @param socketPath - path to the Unix domain socket or Windows\n * named pipe\n * @param handler - async function invoked for each valid request\n * @returns the listening `net.Server` instance\n */\nexport function createIpcServer(\n socketPath: string,\n handler: IpcHandler,\n): Server {\n const server = createServer((socket) => {\n let buffer = '';\n\n socket.on('data', (chunk: Buffer) => {\n buffer += chunk.toString();\n const lines = buffer.split('\\n');\n buffer = lines.pop() ?? '';\n\n for (const line of lines) {\n if (!line.trim()) continue;\n void handleLine(line, handler, socket);\n }\n });\n\n socket.on('error', (err: Error) => {\n // eslint-disable-next-line no-console\n console.error(\n `kbdb-worker: ipc connection error: ${err.message}`,\n );\n });\n });\n\n server.on('error', (err: Error) => {\n // eslint-disable-next-line no-console\n console.error(`kbdb-worker: ipc server error: ${err.message}`);\n });\n\n server.listen(socketPath);\n return server;\n}\n\nfunction bigintReplacer(_key: string, value: unknown): unknown {\n return typeof value === 'bigint' ? Number(value) : value;\n}\n\nasync function handleLine(\n line: string,\n handler: IpcHandler,\n socket: Socket,\n): Promise<void> {\n let response: IpcResponse;\n try {\n const request = JSON.parse(line) as IpcRequest;\n response = await handler(request);\n } catch {\n response = {\n jsonrpc: '2.0',\n id: 0,\n error: {\n code: -32700,\n message: 'Parse error',\n },\n };\n }\n socket.write(JSON.stringify(response, bigintReplacer) + '\\n');\n}\n", "const encoder = new TextEncoder();\n\nexport function encodeString(value: string): Uint8Array {\n const utf8 = encoder.encode(value);\n const result = new Uint8Array(4 + utf8.length);\n new DataView(result.buffer).setUint32(0, utf8.length, true);\n result.set(utf8, 4);\n return result;\n}\n", "export function encodeU32(value: number): Uint8Array {\n const result = new Uint8Array(4);\n new DataView(result.buffer).setUint32(0, value, true);\n return result;\n}\n", "import { encodeString } from './encode-string.function.ts';\n\nexport function encodeOptionString(\n value: string | null | undefined,\n): Uint8Array {\n if (value == null) {\n return new Uint8Array([0x00]);\n }\n const encoded = encodeString(value);\n const result = new Uint8Array(1 + encoded.length);\n result[0] = 0x01;\n result.set(encoded, 1);\n return result;\n}\n", "import { encodeString } from './encode-string.function.ts';\n\nexport function encodeSectionType(\n kind: 'text' | 'code' | 'image',\n mimeType?: string,\n): Uint8Array {\n if (kind === 'text') {\n return new Uint8Array([0x00]);\n }\n\n const tag = kind === 'code' ? 0x01 : 0x02;\n const mime = mimeType ?? 'text/plain';\n const encoded = encodeString(mime);\n const result = new Uint8Array(1 + encoded.length);\n result[0] = tag;\n result.set(encoded, 1);\n return result;\n}\n", "import { encodeSectionType } from './encode-section-type.function.ts';\nimport { encodeString } from './encode-string.function.ts';\nimport { encodeOptionString } from './encode-option-string.function.ts';\n\nexport interface AddSectionInput {\n sectionType: 'text' | 'code' | 'image';\n mimeType?: string;\n content: string;\n title?: string | null;\n description?: string | null;\n docid?: string | null;\n typeName?: string | null;\n}\n\nexport function encodeAddSectionParams(\n params: AddSectionInput,\n): Uint8Array {\n const parts = [\n encodeSectionType(params.sectionType, params.mimeType),\n encodeString(params.content),\n encodeOptionString(params.title),\n encodeOptionString(params.description),\n encodeOptionString(params.docid),\n encodeOptionString(params.typeName),\n ];\n const totalLen = parts.reduce((sum, p) => sum + p.length, 0);\n const result = new Uint8Array(totalLen);\n let offset = 0;\n for (const part of parts) {\n result.set(part, offset);\n offset += part.length;\n }\n return result;\n}\n", "import { encodeString } from './encode-string.function.ts';\nimport { encodeAddSectionParams } from './encode-add-section-params.function.ts';\n\nimport type { AddSectionInput } from './encode-add-section-params.function.ts';\n\nexport function encodeUpdateSectionParams(\n oldKbid: string,\n params: AddSectionInput,\n): Uint8Array {\n const kbidBytes = encodeString(oldKbid);\n const paramBytes = encodeAddSectionParams(params);\n const result = new Uint8Array(kbidBytes.length + paramBytes.length);\n result.set(kbidBytes, 0);\n result.set(paramBytes, kbidBytes.length);\n return result;\n}\n", "import { encodeU32 } from './encode-u32.function.ts';\nimport { encodeString } from './encode-string.function.ts';\n\nexport function encodeKbidList(kbids: string[]): Uint8Array {\n if (kbids.length === 0) {\n return new Uint8Array(0);\n }\n const parts = [encodeU32(kbids.length), ...kbids.map(encodeString)];\n const totalLen = parts.reduce((sum, p) => sum + p.length, 0);\n const result = new Uint8Array(totalLen);\n let offset = 0;\n for (const part of parts) {\n result.set(part, offset);\n offset += part.length;\n }\n return result;\n}\n", "import { encodeString } from './encode-string.function.ts';\nimport { encodeKbidList } from './encode-kbid-list.function.ts';\n\n/**\n * Encodes parameters for the `worker_group_sections` WASM call into\n * a single byte buffer: title, kbid list, then doc type tag.\n *\n * @param title - human-readable document title\n * @param kbids - identifiers of the sections to group\n * @param docType - application-level document type tag; defaults to\n * empty string when not specified\n */\nexport function encodeGroupParams(\n title: string,\n kbids: string[],\n docType = '',\n): Uint8Array {\n const titleBytes = encodeString(title);\n const listBytes = encodeKbidList(kbids);\n const docTypeBytes = encodeString(docType);\n const result = new Uint8Array(\n titleBytes.length + listBytes.length + docTypeBytes.length,\n );\n result.set(titleBytes, 0);\n result.set(listBytes, titleBytes.length);\n result.set(docTypeBytes, titleBytes.length + listBytes.length);\n return result;\n}\n", "import { encodeU32 } from './encode-u32.function.ts';\nimport { encodeString } from './encode-string.function.ts';\n\nexport function encodeIdentifierList(ids: string[]): Uint8Array {\n if (ids.length === 0) {\n return new Uint8Array(0);\n }\n const parts = [encodeU32(ids.length), ...ids.map(encodeString)];\n const totalLen = parts.reduce((sum, p) => sum + p.length, 0);\n const result = new Uint8Array(totalLen);\n let offset = 0;\n for (const part of parts) {\n result.set(part, offset);\n offset += part.length;\n }\n return result;\n}\n", "const encoder = new TextEncoder();\n\nexport function encodeSearchParams(\n query: string,\n mode = 'and',\n limit = 20,\n): Uint8Array {\n return encoder.encode(`${query}\\n${mode}\\n${String(limit)}`);\n}\n", "/**\n * Encodes a type filter string as raw UTF-8 bytes for WASM input.\n *\n * Used to pass a type name to WASM exports such as\n * `worker_list_by_type` and `worker_list_docs_by_type`, which accept\n * a plain UTF-8 byte slice without a length prefix.\n *\n * @param typeStr - the type name to filter by (e.g. `'article'`)\n * @returns UTF-8 encoded bytes ready to pass to the WASM export\n */\nexport function encodeTypeFilterParam(typeStr: string): Uint8Array {\n return new TextEncoder().encode(typeStr);\n}\n", "const decoder = new TextDecoder();\n\nexport interface DecodeResult<T> {\n value: T;\n bytesRead: number;\n}\n\nexport function decodeString(\n bytes: Uint8Array,\n offset: number,\n): DecodeResult<string> {\n const view = new DataView(\n bytes.buffer,\n bytes.byteOffset,\n bytes.byteLength,\n );\n const len = view.getUint32(offset, true);\n const value = decoder.decode(\n bytes.subarray(offset + 4, offset + 4 + len),\n );\n return { value, bytesRead: 4 + len };\n}\n", "import type { DecodeResult } from './decode-string.function.ts';\n\nexport function decodeU32(\n bytes: Uint8Array,\n offset: number,\n): DecodeResult<number> {\n const view = new DataView(\n bytes.buffer,\n bytes.byteOffset,\n bytes.byteLength,\n );\n return {\n value: view.getUint32(offset, true),\n bytesRead: 4,\n };\n}\n", "import type { DecodeResult } from './decode-string.function.ts';\n\nexport function decodeF32(\n bytes: Uint8Array,\n offset: number,\n): DecodeResult<number> {\n const view = new DataView(\n bytes.buffer,\n bytes.byteOffset,\n bytes.byteLength,\n );\n return {\n value: view.getFloat32(offset, true),\n bytesRead: 4,\n };\n}\n", "import type { DecodeResult } from './decode-string.function.ts';\n\nexport function decodeU64(\n bytes: Uint8Array,\n offset: number,\n): DecodeResult<bigint> {\n const view = new DataView(\n bytes.buffer,\n bytes.byteOffset,\n bytes.byteLength,\n );\n return {\n value: view.getBigUint64(offset, true),\n bytesRead: 8,\n };\n}\n", "import { decodeString } from './decode-string.function.ts';\nimport { decodeU32 } from './decode-u32.function.ts';\nimport { decodeF32 } from './decode-f32.function.ts';\n\nexport interface TermMatch {\n term: string;\n frequency: number;\n}\n\nexport interface ScoredResult {\n kbid: string;\n score: number;\n matches: TermMatch[];\n}\n\nexport function decodeScoredResults(bytes: Uint8Array): ScoredResult[] {\n let offset = 0;\n const count = decodeU32(bytes, offset);\n offset += count.bytesRead;\n\n const results: ScoredResult[] = [];\n for (let i = 0; i < count.value; i++) {\n const kbid = decodeString(bytes, offset);\n offset += kbid.bytesRead;\n\n const score = decodeF32(bytes, offset);\n offset += score.bytesRead;\n\n const matchCount = decodeU32(bytes, offset);\n offset += matchCount.bytesRead;\n\n const matches: TermMatch[] = [];\n for (let j = 0; j < matchCount.value; j++) {\n const term = decodeString(bytes, offset);\n offset += term.bytesRead;\n\n const freq = decodeF32(bytes, offset);\n offset += freq.bytesRead;\n\n matches.push({\n term: term.value,\n frequency: freq.value,\n });\n }\n\n results.push({\n kbid: kbid.value,\n score: score.value,\n matches,\n });\n }\n\n return results;\n}\n", "import { decodeString } from './decode-string.function.ts';\nimport { decodeU32 } from './decode-u32.function.ts';\nimport { decodeU64 } from './decode-u64.function.ts';\n\n/**\n * A single section record decoded from WASM binary output.\n *\n * Represents a stored knowledge-base section with all its metadata\n * and token counts as returned by `worker_read_sections` or\n * `worker_list_by_type`.\n */\nexport interface SectionRecord {\n /** Unique knowledge-base identifier for this section. */\n kbid: string;\n /** Document identifier this section belongs to, or `null`. */\n docid: string | null;\n /** Semantic type discriminant: `'text'`, `'code'`, or `'image'`. */\n sectionType: string;\n /** MIME type string, present only for `'code'` and `'image'` types. */\n mimeType?: string;\n /** Human-readable title for the section, or `null`. */\n title: string | null;\n /** Optional description of the section content, or `null`. */\n description: string | null;\n /** Raw text or base64-encoded content of the section. */\n content: string;\n /** Byte size of the stored content. */\n size: number;\n /** Section creation timestamp as a Unix epoch value. */\n createdAt: bigint;\n /** Integrity checksum of the stored content. */\n checksum: string;\n /** Total number of tokens in the section. */\n tokenCount: number;\n /** Number of heading tokens in the section. */\n headingTokenCount: number;\n /** Number of body tokens in the section. */\n bodyTokenCount: number;\n /** Number of code tokens in the section. */\n codeTokenCount: number;\n /** Application-level type name assigned to this section. */\n typeName: string;\n}\n\nfunction decodeOptionString(\n bytes: Uint8Array,\n offset: number,\n): { value: string | null; bytesRead: number } {\n const tag = bytes[offset];\n if (tag === 0x00) {\n return { value: null, bytesRead: 1 };\n }\n const str = decodeString(bytes, offset + 1);\n return { value: str.value, bytesRead: 1 + str.bytesRead };\n}\n\nfunction decodeSectionType(\n bytes: Uint8Array,\n offset: number,\n): {\n sectionType: string;\n mimeType?: string;\n bytesRead: number;\n} {\n const tag = bytes[offset];\n if (tag === 0x00) {\n return { sectionType: 'text', bytesRead: 1 };\n }\n const mime = decodeString(bytes, offset + 1);\n const kind = tag === 0x01 ? 'code' : 'image';\n return {\n sectionType: kind,\n mimeType: mime.value,\n bytesRead: 1 + mime.bytesRead,\n };\n}\n\n/**\n * Decodes a list of `SectionRecord` values from WASM binary output.\n *\n * Reads a leading u32 count followed by that many encoded records.\n * Each record is decoded in field order as produced by the Rust\n * `SectionRecord::encode` implementation.\n *\n * @param bytes - raw bytes returned by a WASM section-list export\n * @returns decoded array of section records, empty when count is zero\n */\nexport function decodeSectionRecords(\n bytes: Uint8Array,\n): SectionRecord[] {\n let offset = 0;\n const count = decodeU32(bytes, offset);\n offset += count.bytesRead;\n\n const records: SectionRecord[] = [];\n for (let i = 0; i < count.value; i++) {\n const kbid = decodeString(bytes, offset);\n offset += kbid.bytesRead;\n\n const docid = decodeOptionString(bytes, offset);\n offset += docid.bytesRead;\n\n const st = decodeSectionType(bytes, offset);\n offset += st.bytesRead;\n\n const title = decodeOptionString(bytes, offset);\n offset += title.bytesRead;\n\n const description = decodeOptionString(bytes, offset);\n offset += description.bytesRead;\n\n const content = decodeString(bytes, offset);\n offset += content.bytesRead;\n\n const size = decodeU32(bytes, offset);\n offset += size.bytesRead;\n\n const createdAt = decodeU64(bytes, offset);\n offset += createdAt.bytesRead;\n\n const checksum = decodeString(bytes, offset);\n offset += checksum.bytesRead;\n\n const tokenCount = decodeU32(bytes, offset);\n offset += tokenCount.bytesRead;\n\n const headingTokenCount = decodeU32(bytes, offset);\n offset += headingTokenCount.bytesRead;\n\n const bodyTokenCount = decodeU32(bytes, offset);\n offset += bodyTokenCount.bytesRead;\n\n const codeTokenCount = decodeU32(bytes, offset);\n offset += codeTokenCount.bytesRead;\n\n const typeName = decodeString(bytes, offset);\n offset += typeName.bytesRead;\n\n const record: SectionRecord = {\n kbid: kbid.value,\n docid: docid.value,\n sectionType: st.sectionType,\n title: title.value,\n description: description.value,\n content: content.value,\n size: size.value,\n createdAt: createdAt.value,\n checksum: checksum.value,\n tokenCount: tokenCount.value,\n headingTokenCount: headingTokenCount.value,\n bodyTokenCount: bodyTokenCount.value,\n codeTokenCount: codeTokenCount.value,\n typeName: typeName.value,\n };\n if (st.mimeType !== undefined) {\n record.mimeType = st.mimeType;\n }\n records.push(record);\n }\n\n return records;\n}\n", "import { decodeSectionRecords } from './decode-section-records.function.ts';\nimport type { SectionRecord } from './decode-section-records.function.ts';\n\nexport type { SectionRecord };\n\n/**\n * Decodes a WASM byte slice into an array of `SectionRecord` values.\n *\n * Thin wrapper around `decodeSectionRecords` provided as the\n * canonical entry point for list-response decoding from WASM exports\n * such as `worker_list_by_type`.\n *\n * @param bytes - raw bytes returned by a WASM section-list export\n * @returns decoded array of section records\n */\nexport function decodeSectionRecordList(\n bytes: Uint8Array,\n): SectionRecord[] {\n return decodeSectionRecords(bytes);\n}\n", "import { decodeString } from './decode-string.function.ts';\nimport { decodeU32 } from './decode-u32.function.ts';\nimport { decodeU64 } from './decode-u64.function.ts';\n\n/**\n * A single section reference within a document manifest.\n *\n * Associates a knowledge-base identifier with the section's\n * ordinal position in the document.\n */\nexport interface DocumentSection {\n /** Knowledge-base identifier of the referenced section. */\n kbid: string;\n /** Zero-based position of this section within its document. */\n position: number;\n}\n\n/**\n * A document manifest decoded from WASM binary output.\n *\n * Represents a grouped document record with its ordered list of\n * section references as returned by `worker_retrieve_doc`.\n */\nexport interface DocumentManifest {\n /** Unique document identifier. */\n docid: string;\n /** Human-readable document title. */\n title: string;\n /** Document creation timestamp as a Unix epoch value. */\n createdAt: bigint;\n /** Application-level type name assigned to this document. */\n docType: string;\n /** Ordered list of section references belonging to the document. */\n sections: DocumentSection[];\n}\n\n/**\n * Decodes a single `DocumentManifest` from WASM binary output.\n *\n * Reads fields in the order: docid, title, createdAt, docType,\n * section count, then each section's kbid and position.\n *\n * @param bytes - raw bytes returned by `worker_retrieve_doc`\n * @returns the decoded document manifest\n */\nexport function decodeDocumentManifest(\n bytes: Uint8Array,\n): DocumentManifest {\n let offset = 0;\n\n const docid = decodeString(bytes, offset);\n offset += docid.bytesRead;\n\n const title = decodeString(bytes, offset);\n offset += title.bytesRead;\n\n const createdAt = decodeU64(bytes, offset);\n offset += createdAt.bytesRead;\n\n const docType = decodeString(bytes, offset);\n offset += docType.bytesRead;\n\n const count = decodeU32(bytes, offset);\n offset += count.bytesRead;\n\n const sections: DocumentSection[] = [];\n for (let i = 0; i < count.value; i++) {\n const kbid = decodeString(bytes, offset);\n offset += kbid.bytesRead;\n\n const position = decodeU32(bytes, offset);\n offset += position.bytesRead;\n\n sections.push({\n kbid: kbid.value,\n position: position.value,\n });\n }\n\n return {\n docid: docid.value,\n title: title.value,\n createdAt: createdAt.value,\n docType: docType.value,\n sections,\n };\n}\n", "import { decodeString } from './decode-string.function.ts';\nimport { decodeU32 } from './decode-u32.function.ts';\nimport { decodeU64 } from './decode-u64.function.ts';\nimport type {\n DocumentManifest,\n DocumentSection,\n} from './decode-document-manifest.function.ts';\n\nexport type { DocumentManifest, DocumentSection };\n\n/**\n * Decodes a WASM byte slice into an array of `DocumentManifest` values.\n *\n * The binary format is: u32 count, followed by count \u00D7 DocumentManifest\n * entries. Each entry contains: docid (string), title (string),\n * createdAt (u64), docType (string), section count (u32), then each\n * section's kbid (string) and position (u32).\n *\n * @param bytes - raw bytes returned by `worker_list_docs_by_type`\n * @returns decoded array of document manifests, empty when count is zero\n */\nexport function decodeDocumentManifestList(\n bytes: Uint8Array,\n): DocumentManifest[] {\n let offset = 0;\n const count = decodeU32(bytes, offset);\n offset += count.bytesRead;\n\n const manifests: DocumentManifest[] = [];\n for (let i = 0; i < count.value; i++) {\n const docid = decodeString(bytes, offset);\n offset += docid.bytesRead;\n\n const title = decodeString(bytes, offset);\n offset += title.bytesRead;\n\n const createdAt = decodeU64(bytes, offset);\n offset += createdAt.bytesRead;\n\n const docType = decodeString(bytes, offset);\n offset += docType.bytesRead;\n\n const secCount = decodeU32(bytes, offset);\n offset += secCount.bytesRead;\n\n const sections: DocumentSection[] = [];\n for (let j = 0; j < secCount.value; j++) {\n const kbid = decodeString(bytes, offset);\n offset += kbid.bytesRead;\n\n const position = decodeU32(bytes, offset);\n offset += position.bytesRead;\n\n sections.push({\n kbid: kbid.value,\n position: position.value,\n });\n }\n\n manifests.push({\n docid: docid.value,\n title: title.value,\n createdAt: createdAt.value,\n docType: docType.value,\n sections,\n });\n }\n\n return manifests;\n}\n", "import { decodeString } from './decode-string.function.ts';\nimport { decodeU64 } from './decode-u64.function.ts';\n\nexport interface ComposeOutput {\n markdown: string;\n totalChars: bigint;\n}\n\nexport function decodeComposeOutput(bytes: Uint8Array): ComposeOutput {\n const md = decodeString(bytes, 0);\n const totalChars = decodeU64(bytes, md.bytesRead);\n return {\n markdown: md.value,\n totalChars: totalChars.value,\n };\n}\n", "export function decodeKeyValueText(\n text: string,\n): Record<string, string> {\n const result: Record<string, string> = {};\n for (const line of text.split('\\n')) {\n const idx = line.indexOf('=');\n if (idx < 0) continue;\n const key = line.slice(0, idx);\n const value = line.slice(idx + 1);\n if (key) {\n result[key] = value;\n }\n }\n return result;\n}\n", "export function decodeRemoveFlag(bytes: Uint8Array): boolean {\n return bytes.length > 0 && bytes[0] === 0x01;\n}\n", "import { resolve } from 'node:path';\n\n/** Result of the worker entry point. */\nexport interface WorkerResult {\n /** Error message (if any). */\n error?: string;\n /** Process exit code. `0` means success. */\n exitCode: number;\n}\n\n/**\n * Injectable dependencies for the worker entry point.\n */\nexport interface WorkerDeps {\n existsSync: (path: string) => boolean;\n startDaemon: (\n contextPath: string,\n wasmDir?: string,\n ) => Promise<void>;\n wasmDir?: string;\n}\n\n/**\n * Worker daemon entry point extracted from `src/worker.ts`.\n *\n * Validates the context path argument, resolves it to an\n * absolute path, checks existence, and delegates to\n * `startDaemon`.\n *\n * @param argv - raw arguments (expects `[contextPath]`)\n * @param deps - injectable dependencies\n */\nexport async function runWorker(\n argv: string[],\n deps: WorkerDeps,\n): Promise<WorkerResult> {\n const contextPath = argv[0];\n\n if (!contextPath) {\n return {\n error: 'usage: kbdb-worker <context-path>',\n exitCode: 1,\n };\n }\n\n const resolved = resolve(contextPath);\n\n if (!deps.existsSync(resolved)) {\n return {\n error: `error: path not found: ${resolved}`,\n exitCode: 1,\n };\n }\n\n await deps.startDaemon(resolved, deps.wasmDir);\n return { exitCode: 0 };\n}\n"],
5
- "mappings": ";;;;;;;;;AAAA,SAAS,cAAAA,mBAAkB;;;ACA3B,SAAS,oBAAoB;AAC7B,SAAS,YAAY;;;ACAd,IAAM,qBAAqB;AAG3B,IAAM,sBAAsB;AAM5B,IAAM,qBAAqB;AAM3B,IAAM,sBAAsB;AAG5B,IAAM,uBAAuB;AAS7B,IAAM,oBAAoB;;;ADP1B,SAAS,WAAW,aAAmC;AAC3D,QAAM,aAAa,KAAK,aAAa,oBAAoB;AACzD,MAAI;AACD,UAAM,OAAO,aAAa,YAAY,OAAO;AAC7C,WAAO,gBAAgB,MAAM,WAAW;AAAA,EAC3C,QAAQ;AACL,WAAO;AAAA,MACJ;AAAA,MACA,WAAW;AAAA,MACX,YAAY;AAAA,MACZ,WAAW;AAAA,MACX,WAAW;AAAA,IACd;AAAA,EACH;AACH;AAEA,SAAS,gBACN,MACA,aACa;AACb,QAAM,SAAuB;AAAA,IAC1B;AAAA,IACA,WAAW;AAAA,IACX,YAAY;AAAA,IACZ,WAAW;A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A0B,QAAQ;AAAA,MACzC,UAAU;AAAA,IACb;AAAA,EACH;AAEA,QAAM,KAAK,YAAY,UAAU,KAAK,OAAO;AAC7C,SAAO,EAAE,UAAU,EAAE;AACxB;;;A/B7CA,IAAM,UAAU,eAAe,YAAY,KAAK,YAAY,OAAO;AACnE,IAAM,UAAU,eAAe,QAAQ,SAAS;AAEhD,eAAe,OAAsB;AAClC,QAAM,SAAS,MAAM,UAAU,QAAQ,GAAG;AAAA,IACvC,YAAAC;AAAA,IACA;AAAA,IACA;AAAA,EACH,CAAC;AACD,MAAI,OAAO,OAAO;AAEf,YAAQ,MAAM,OAAO,KAAK;AAAA,EAC7B;AACA,MAAI,OAAO,aAAa,GAAG;AACxB,YAAQ,WAAW,OAAO;AAAA,EAC7B;AACH;AAEA,KAAK,EAAE,MAAM,CAAC,QAAiB;AAE5B,UAAQ,MAAM,GAAG;AACjB,UAAQ,WAAW;AACtB,CAAC;",
6
- "names": ["existsSync", "writeFileSync", "join", "tmpdir", "existsSync", "readFileSync", "writeFileSync", "unlinkSync", "join", "readFileSync", "join", "readFileSync", "join", "wasmDir", "join", "readFileSync", "encoder", "wasmDir", "existsSync", "join", "writeFileSync", "unlinkSync", "readFileSync", "getResultFn", "wasmDir", "join", "tmpdir", "writeFileSync", "existsSync"]
4
+ "sourcesContent": ["import { existsSync } from 'node:fs';\nimport { getArgs } from './shared/runtime/index.ts';\nimport {\n resolveBaseDir,\n resolveWasmDir,\n} from './shared/dir-resolver/index.ts';\nimport {\n startDaemon,\n runWorker,\n} from './shared/worker-daemon/index.ts';\n\nconst baseDir = resolveBaseDir(import.meta.url, import.meta.dirname);\nconst wasmDir = resolveWasmDir(baseDir.scriptDir);\n\nasync function main(): Promise<void> {\n const result = await runWorker(getArgs(), {\n existsSync,\n startDaemon,\n wasmDir,\n });\n if (result.error) {\n // eslint-disable-next-line no-console\n console.error(result.error);\n }\n if (result.exitCode !== 0) {\n process.exitCode = result.exitCode;\n }\n}\n\nmain().catch((err: unknown) => {\n // eslint-disable-next-line no-console\n console.error(err);\n process.exitCode = 1;\n});\n", "import { readFileSync } from 'node:fs';\nimport { join } from 'node:path';\nimport type { DaemonConfig } from '../typings/daemon-config.interface.ts';\nimport {\n DEFAULT_ITEM_LIMIT,\n DEFAULT_INDEX_LIMIT,\n DEFAULT_TIMEOUT_MS,\n DEFAULT_ITEM_TTL_MS,\n WORKER_TOML_FILENAME,\n} from '../constants/daemon-defaults.constant.ts';\n\n/**\n * Reads the `worker.toml` configuration file from the given\n * context directory and returns a `DaemonConfig`.\n *\n * Falls back to all-default values when the file is absent or\n * unreadable.\n *\n * @param contextPath - absolute path to the `.kbdb` context\n * directory\n */\nexport function readConfig(contextPath: string): DaemonConfig {\n const configPath = join(contextPath, WORKER_TOML_FILENAME);\n try {\n const text = readFileSync(configPath, 'utf-8');\n return parseWorkerToml(text, contextPath);\n } catch {\n return {\n contextPath,\n itemLimit: DEFAULT_ITEM_LIMIT,\n indexLimit: DEFAULT_INDEX_LIMIT,\n timeoutMs: DEFAULT_TIMEOUT_MS,\n itemTtlMs: DEFAULT_ITEM_TTL_MS,\n };\n }\n}\n\nfunction parseWorkerToml(\n text: string,\n contextPath: string,\n): DaemonConfig {\n const config: DaemonConfig = {\n contextPath,\n itemLimit: DEFAULT_ITEM_LIMIT,\n indexLimit: DEFAULT_INDEX_LIMIT,\n timeoutMs: DEFAULT_TIMEOUT_MS,\n itemTtlMs: DEFAULT_ITEM_TTL_MS,\n };\n\n const result = { ...config };\n\n for (const line of text.split('\\n')) {\n const trimmed = line.trim();\n if (trimmed.startsWith('#') || !trimmed.includes('=')) {\n continue;\n }\n const eqIdx = trimmed.indexOf('=');\n const key = trimmed.slice(0, eqIdx).trim();\n const value = trimmed.slice(eqIdx + 1).trim();\n switch (key) {\n case 'item_limit':\n result.itemLimit =\n parseInt(value, 10) || DEFAULT_ITEM_LIMIT;\n break;\n case 'index_limit':\n result.indexLimit =\n parseInt(value, 10) || DEFAULT_INDEX_LIMIT;\n break;\n case 'timeout_ms':\n result.timeoutMs =\n parseInt(value, 10) || DEFAULT_TIMEOUT_MS;\n break;\n case 'item_ttl_ms':\n result.itemTtlMs =\n parseInt(value, 10) || DEFAULT_ITEM_TTL_MS;\n break;\n default:\n break;\n }\n }\n\n return result;\n}\n", "/** Default maximum number of items held in daemon memory. */\nexport const DEFAULT_ITEM_LIMIT = 1000;\n\n/** Default maximum number of index entries held in daemon memory. */\nexport const DEFAULT_INDEX_LIMIT = 100;\n\n/**\n * Default idle timeout in milliseconds before the daemon shuts\n * down automatically (5 minutes).\n */\nexport const DEFAULT_TIMEOUT_MS = 300_000;\n\n/**\n * Default time-to-live in milliseconds for each cached item\n * (1 minute).\n */\nexport const DEFAULT_ITEM_TTL_MS = 60_000;\n\n/** Filename of the daemon configuration file inside `.kbdb/`. */\nexport const WORKER_TOML_FILENAME = 'worker.toml';\n\n/**\n * Database format version the daemon supports.\n *\n * Read from `catalog.toml` at startup. If the catalog version\n * differs, the daemon prints a structured error to stderr and\n * exits with code 1 before loading any WASM modules.\n */\nexport const DB_FORMAT_VERSION = 1;\n", "import { writeFileSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { tmpdir } from 'node:os';\nimport { readConfig } from './read-config.function.ts';\nimport { computeSha256 } from '../../hash/functions/compute-sha256.ts';\nimport { WorkerDaemon } from '../classes/worker-daemon.class.ts';\n\n/**\n * Starts the worker daemon for the given knowledge-base context.\n *\n * Reads configuration from `worker.toml` in the context directory,\n * validates startup preconditions (directory exists, accessible, and\n * database version compatible), and then starts the `WorkerDaemon`.\n *\n * Signal handlers for `SIGTERM` and `SIGINT` trigger a graceful stop.\n * Precondition failures are printed to stderr and cause exit code 1.\n *\n * @param contextPath - absolute path to the `.kbdb` context directory\n */\nexport async function startDaemon(\n contextPath: string,\n wasmDir?: string,\n): Promise<void> {\n const config = readConfig(contextPath);\n const hash = await computeSha256(contextPath);\n const contextId = hash.slice(0, 16);\n\n const daemon = new WorkerDaemon(\n contextId,\n contextPath,\n config,\n wasmDir,\n );\n\n try {\n daemon.checkPreconditions();\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n // eslint-disable-next-line no-console\n console.error(`kbdb-worker: ${message}`);\n writeCrashLog(contextId, message);\n process.exit(1);\n }\n\n try {\n await daemon.start();\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n // eslint-disable-next-line no-console\n console.error(`kbdb-worker: ${message}`);\n writeCrashLog(contextId, message);\n process.exit(1);\n }\n\n process.on('SIGTERM', () => {\n daemon.stop();\n });\n process.on('SIGINT', () => {\n daemon.stop();\n });\n}\n\nfunction writeCrashLog(contextId: string, message: string): void {\n try {\n const crashPath = join(tmpdir(), `kbdb-${contextId}.crash`);\n const payload = JSON.stringify({\n error: message,\n timestamp: Date.now(),\n });\n writeFileSync(crashPath, payload);\n } catch {\n // never mask the original error\n }\n}\n", "import {\n existsSync,\n readFileSync,\n accessSync,\n writeFileSync,\n unlinkSync,\n constants,\n} from 'node:fs';\nimport { join } from 'node:path';\nimport { tmpdir } from 'node:os';\nimport type { Server } from 'node:net';\nimport type { DaemonConfig } from '../typings/daemon-config.interface.ts';\nimport type { WasmModules } from '../typings/wasm-modules.interface.ts';\nimport type {\n IpcRequest,\n IpcResponse,\n IpcHandler,\n} from '../typings/ipc-handler.interface.ts';\nimport { DB_FORMAT_VERSION } from '../constants/daemon-defaults.constant.ts';\nimport { loadWasmModules } from '../functions/load-wasm-modules.function.ts';\nimport { createIpcServer } from '../functions/create-ipc-server.function.ts';\nimport { getIpcPath } from '../../platform/functions/get-ipc-path.function.ts';\nimport {\n encodeSearchParams,\n encodeAddSectionParams,\n encodeUpdateSectionParams,\n encodeKbidList,\n encodeGroupParams,\n encodeIdentifierList,\n encodeTypeFilterParam,\n decodeScoredResults,\n decodeSectionRecords,\n decodeSectionRecordList,\n decodeDocumentManifest,\n decodeDocumentManifestList,\n decodeComposeOutput,\n decodeKeyValueText,\n decodeRemoveFlag,\n} from '../../wasm-codec/index.ts';\n\nimport type { AddSectionInput } from '../../wasm-codec/index.ts';\n\n// ---------------------------------------------------------------------------\n// Internal types\n// ---------------------------------------------------------------------------\n\n/** Callable WASM export function signature. */\ntype WasmFn = (...args: unknown[]) => unknown;\n\n/** Mapping from IPC method name to kb-worker.wasm export name. */\nconst WASM_METHOD_MAP: Readonly<Partial<Record<string, string>>> = {\n search: 'worker_search',\n addSection: 'worker_add_section',\n add_section: 'worker_add_section',\n updateSection: 'worker_update_section',\n update_section: 'worker_update_section',\n removeSection: 'worker_remove_section',\n remove_section: 'worker_remove_section',\n readSections: 'worker_read_sections',\n read_sections: 'worker_read_sections',\n groupSections: 'worker_group_sections',\n group_sections: 'worker_group_sections',\n removeGrouping: 'worker_remove_grouping',\n remove_grouping: 'worker_remove_grouping',\n retrieveDocument: 'worker_retrieve_doc',\n retrieve_doc: 'worker_retrieve_doc',\n content: 'worker_compose',\n compose: 'worker_compose',\n integrity_check: 'worker_check_integrity',\n integrityCheck: 'worker_check_integrity',\n gc: 'worker_garbage_collect',\n rebuild_indexes: 'worker_rebuild_indexes',\n rebuildIndexes: 'worker_rebuild_indexes',\n init_directory: 'worker_init_directory',\n initDirectory: 'worker_init_directory',\n migrateDatabase: 'worker_migrate',\n query: 'worker_query',\n get_result_status: 'worker_result_status',\n get_result: 'worker_get_result',\n invalidate: 'worker_invalidate',\n invalidate_all: 'worker_invalidate_all',\n invalidateAll: 'worker_invalidate_all',\n db_status: 'worker_status',\n dbStatus: 'worker_status',\n listByType: 'worker_list_by_type',\n list_by_type: 'worker_list_by_type',\n listDocumentsByType: 'worker_list_docs_by_type',\n list_docs_by_type: 'worker_list_docs_by_type',\n};\n\n/** Config method name prefix. */\nconst CONFIG_PREFIX = 'config_';\n\n/** Config key \u2192 DaemonConfig property mapping. */\nconst CONFIG_KEY_MAP: Readonly<\n Partial<Record<string, keyof DaemonConfig>>\n> = {\n timeout_ms: 'timeoutMs',\n item_ttl_ms: 'itemTtlMs',\n item_limit: 'itemLimit',\n index_limit: 'indexLimit',\n};\n\n// ---------------------------------------------------------------------------\n// IpcError\n// ---------------------------------------------------------------------------\n\n/** Typed JSON-RPC error used internally by WorkerDaemon dispatch. */\nclass IpcError extends Error {\n /** JSON-RPC error code. */\n readonly code: number;\n\n constructor(code: number, message: string) {\n super(message);\n this.code = code;\n this.name = 'IpcError';\n }\n}\n\n// ---------------------------------------------------------------------------\n// WorkerDaemon\n// ---------------------------------------------------------------------------\n\n/**\n * Core daemon class that manages the full worker daemon lifecycle.\n *\n * Orchestrates WASM module loading, IPC server creation, request\n * routing to `kb-worker.wasm` exports, idle timeout tracking, and\n * graceful shutdown. The daemon validates startup preconditions before\n * loading WASM modules and rejects IPC requests whose `ctx` param does\n * not match the daemon's context ID.\n */\nexport class WorkerDaemon {\n /** Context ID (16-character hex SHA-256 prefix). */\n readonly ctx: string;\n\n /** Absolute path to the `.kbdb` directory. */\n readonly targetDir: string;\n\n /** Parsed daemon configuration from `worker.toml`. */\n readonly config: DaemonConfig;\n\n /** Number of currently active IPC client connections. */\n get connectionCount(): number {\n return this._connectionCount;\n }\n\n private _connectionCount = 0;\n private _wasmModules: WasmModules | null = null;\n private _idleAt = 0;\n private _idleTimer: ReturnType<typeof setTimeout> | null = null;\n private _server: Server | null = null;\n private readonly _wasmDir: string;\n\n /**\n * @param ctx - context ID (16-hex characters), the first 16 of\n * the SHA-256 hash of `targetDir`\n * @param targetDir - absolute path to the `.kbdb` directory\n * @param config - parsed daemon configuration\n * @param wasmDir - path to the WASM build output directory\n */\n constructor(\n ctx: string,\n targetDir: string,\n config: DaemonConfig,\n wasmDir?: string,\n ) {\n this.ctx = ctx;\n this.targetDir = targetDir;\n this.config = config;\n this._wasmDir = wasmDir ?? '';\n }\n\n // -----------------------------------------------------------------------\n // Public API\n // -----------------------------------------------------------------------\n\n /**\n * Validates startup preconditions before WASM module loading.\n *\n * Checks that the database directory exists, is readable and\n * writable, and that `catalog.toml` reports a compatible version.\n *\n * @throws {Error} if any precondition fails -- `startDaemon`\n * catches this, prints to stderr, and exits with code 1\n */\n checkPreconditions(): void {\n if (!existsSync(this.targetDir)) {\n throw new Error(\n `database directory not found: ${this.targetDir}`,\n );\n }\n\n try {\n accessSync(\n this.targetDir,\n\n constants.R_OK | constants.W_OK,\n );\n } catch {\n throw new Error(\n `cannot access database directory: ${this.targetDir}` +\n ' -- permission denied',\n );\n }\n\n this.checkCatalogVersion();\n }\n\n /**\n * Starts the daemon: loads WASM modules, writes the PID file,\n * creates the IPC socket, and begins listening for connections.\n *\n * Call `checkPreconditions()` before `start()` to validate the\n * database directory. The daemon will not start if any precondition\n * fails.\n *\n * @throws when WASM module loading fails or the IPC socket cannot\n * be created\n */\n async start(): Promise<void> {\n const wasmModules = await loadWasmModules(\n this.config,\n this._wasmDir,\n );\n this._wasmModules = wasmModules;\n\n this.initWorkerContext();\n\n const pidPath = join(tmpdir(), `kbdb-${this.ctx}.pid`);\n writeFileSync(pidPath, process.pid.toString());\n\n const ipcPath = getIpcPath(this.ctx);\n\n if (existsSync(ipcPath)) {\n try {\n unlinkSync(ipcPath);\n } catch {\n // ignore stale socket removal errors\n }\n }\n\n const handler: IpcHandler = (req) => this.handleRequest(req);\n this._server = createIpcServer(ipcPath, handler);\n\n this._server.on('connection', () => {\n this.incrementConnections();\n this.resetIdleTimer();\n });\n\n this._server.on('close', () => {\n this.decrementConnections();\n if (this._connectionCount === 0) {\n this.resetIdleTimer();\n }\n });\n\n this.resetIdleTimer();\n }\n\n /**\n * Gracefully shuts down the daemon.\n *\n * Stops accepting new connections, clears the idle timer, purges\n * WASM state, removes the PID file and IPC socket file, then exits\n * the process.\n */\n stop(): void {\n if (this._idleTimer !== null) {\n clearTimeout(this._idleTimer);\n this._idleTimer = null;\n }\n\n if (this._server !== null) {\n this._server.close();\n this._server = null;\n }\n\n this._wasmModules = null;\n\n const pidPath = join(tmpdir(), `kbdb-${this.ctx}.pid`);\n try {\n unlinkSync(pidPath);\n } catch {\n // ignore cleanup errors\n }\n\n const ipcPath = getIpcPath(this.ctx);\n try {\n unlinkSync(ipcPath);\n } catch {\n // ignore cleanup errors\n }\n\n const crashPath = join(tmpdir(), `kbdb-${this.ctx}.crash`);\n try {\n unlinkSync(crashPath);\n } catch {\n // ignore cleanup errors\n }\n\n process.exit(0);\n }\n\n /**\n * Handles a single JSON-RPC 2.0 request.\n *\n * Validates context, then routes to a daemon-state handler or a\n * WASM export. Requests whose `ctx` param does not match the\n * daemon's context ID are rejected with error code `-32001`.\n *\n * @param request - incoming JSON-RPC request\n * @returns the JSON-RPC response\n */\n async handleRequest(request: IpcRequest): Promise<IpcResponse> {\n const params = request.params as\n | Record<string, unknown>\n | undefined;\n if (params === undefined || params.ctx !== this.ctx) {\n return this.errorResponse(\n request.id,\n -32001,\n 'context mismatch',\n );\n }\n\n this.resetIdleTimer();\n\n try {\n const result = await this.dispatch(request.method, params);\n this._idleAt = Math.floor(Date.now() / 1000);\n return {\n jsonrpc: '2.0',\n id: request.id,\n result,\n };\n } catch (err) {\n this._idleAt = Math.floor(Date.now() / 1000);\n if (err instanceof IpcError) {\n return this.errorResponse(\n request.id,\n err.code,\n err.message,\n );\n }\n const message =\n err instanceof Error ? err.message : String(err);\n return this.errorResponse(request.id, -32000, message);\n }\n }\n\n /**\n * Increments the active connection count.\n *\n * Call when a new IPC client connects.\n */\n incrementConnections(): void {\n this._connectionCount++;\n }\n\n /**\n * Decrements the active connection count, clamped to zero.\n *\n * Call when an IPC client disconnects.\n */\n decrementConnections(): void {\n if (this._connectionCount > 0) {\n this._connectionCount--;\n }\n }\n\n /**\n * Injects pre-built WASM modules for unit testing.\n *\n * This method exists solely to support unit tests that cannot\n * load real WASM binaries. It must not be called in production\n * code -- production code uses `start()` to load modules.\n *\n * @param modules - pre-built WASM module instances\n * @internal\n */\n injectModulesForTesting(modules: WasmModules): void {\n this._wasmModules = modules;\n }\n\n // -----------------------------------------------------------------------\n // Private helpers\n // -----------------------------------------------------------------------\n\n /** Resets the idle timer; triggers stop() when it fires. */\n private resetIdleTimer(): void {\n if (this._idleTimer !== null) {\n clearTimeout(this._idleTimer);\n }\n if (this._connectionCount === 0) {\n this._idleTimer = setTimeout(() => {\n this.stop();\n }, this.config.timeoutMs);\n }\n }\n\n /** Reads catalog.toml and validates the version field. */\n private checkCatalogVersion(): void {\n const catalogPath = join(this.targetDir, 'catalog.toml');\n let text: string;\n try {\n text = readFileSync(catalogPath, 'utf-8');\n } catch {\n throw new Error(\n `cannot read database directory: ${this.targetDir}` +\n ' -- permission denied',\n );\n }\n\n const version = parseCatalogVersion(text);\n if (version === null) {\n throw new Error(\n 'database version 0 requires migration to version ' +\n String(DB_FORMAT_VERSION) +\n ' -- run `kbdb --migrate` before starting the daemon',\n );\n }\n\n if (version > DB_FORMAT_VERSION) {\n throw new Error(\n 'database version ' +\n String(version) +\n ' is newer than kbdb version ' +\n String(DB_FORMAT_VERSION) +\n ' -- upgrade kbdb to open this database',\n );\n }\n\n if (version < DB_FORMAT_VERSION) {\n throw new Error(\n 'database version ' +\n String(version) +\n ' requires migration to version ' +\n String(DB_FORMAT_VERSION) +\n ' -- run `kbdb --migrate` before starting the daemon',\n );\n }\n }\n\n /** Builds a JSON-RPC error response. */\n private errorResponse(\n id: number | string,\n code: number,\n message: string,\n ): IpcResponse {\n return {\n jsonrpc: '2.0',\n id,\n error: { code, message },\n };\n }\n\n /**\n * Dispatches a request method to the appropriate handler.\n *\n * Handles daemon-state methods (`status`, `idle_at`,\n * `config_{key}`) inline and routes WASM methods to the\n * correct calling convention for each export.\n */\n private dispatch(\n method: string,\n params: Record<string, unknown>,\n ): unknown {\n if (method === 'status') {\n return this._connectionCount > 0 ? 'busy' : 'idle';\n }\n\n if (method === 'idle_at') {\n return this._idleAt;\n }\n\n if (method === 'checkVersion') {\n return this.handleCheckVersion(params);\n }\n\n if (method.startsWith(CONFIG_PREFIX)) {\n return this.handleConfigMethod(method);\n }\n\n const wasmMethod = WASM_METHOD_MAP[method];\n if (wasmMethod !== undefined) {\n return this.dispatchWasm(method, wasmMethod, params);\n }\n\n throw new IpcError(-32601, `Method not found: ${method}`);\n }\n\n private dispatchWasm(\n method: string,\n wasmExport: string,\n params: Record<string, unknown>,\n ): unknown {\n if (method === 'search' || method === 'query') {\n return this.handleSearch(params);\n }\n if (method === 'addSection' || method === 'add_section') {\n return this.handleAddSection(params);\n }\n if (method === 'updateSection' || method === 'update_section') {\n return this.handleUpdateSection(params);\n }\n if (method === 'removeSection' || method === 'remove_section') {\n return this.handleRemoveSection(params);\n }\n if (method === 'readSections' || method === 'read_sections') {\n return this.handleReadSections(params);\n }\n if (method === 'retrieveDocument' || method === 'retrieve_doc') {\n return this.handleRetrieveDoc(params);\n }\n if (method === 'groupSections' || method === 'group_sections') {\n return this.handleGroupSections(params);\n }\n if (method === 'removeGrouping' || method === 'remove_grouping') {\n return this.handleRemoveGrouping(params);\n }\n if (method === 'content' || method === 'compose') {\n return this.handleCompose(params);\n }\n if (method === 'integrityCheck' || method === 'integrity_check') {\n return this.handleIntegrityCheck();\n }\n if (method === 'gc') {\n return this.handleGc();\n }\n if (method === 'rebuildIndexes' || method === 'rebuild_indexes') {\n return this.handleRebuild();\n }\n if (method === 'dbStatus' || method === 'db_status') {\n return this.handleDbStatus();\n }\n if (method === 'initDirectory' || method === 'init_directory') {\n return this.handleInitDirectory(params);\n }\n if (method === 'invalidate') {\n return this.handleInvalidate(params);\n }\n if (method === 'invalidateAll' || method === 'invalidate_all') {\n return this.handleInvalidateAll();\n }\n if (method === 'get_result_status') {\n return this.handleResultStatus(params);\n }\n if (method === 'get_result') {\n return this.handleGetResult(params);\n }\n if (method === 'migrateDatabase') {\n throw new IpcError(\n -32601,\n 'migrateDatabase is not yet supported',\n );\n }\n if (method === 'listByType' || method === 'list_by_type') {\n return this.handleListByType(params);\n }\n if (\n method === 'listDocumentsByType' ||\n method === 'list_docs_by_type'\n ) {\n return this.handleListDocsByType(params);\n }\n return this.invokeWasmRaw(wasmExport, new Uint8Array(0));\n }\n\n // -- Search/query (token-based async) --\n\n private handleSearch(params: Record<string, unknown>): unknown {\n const query = (params['query'] as string | undefined) ?? '';\n const mode = (params['mode'] as string | undefined) ?? 'and';\n const limit = Number(params['limit'] ?? 20);\n const encoded = encodeSearchParams(query, mode, limit);\n\n const searchFn = this.getExport('worker_search');\n const ptr = this.wasmAlloc(encoded.length);\n this.wasmWrite(ptr, encoded);\n const token = searchFn(ptr, encoded.length) as number;\n this.wasmFree(ptr, encoded.length);\n\n const statusFn = this.getExport('worker_result_status');\n const status = statusFn(token) as number;\n if (status === 3) {\n const getResultFn = this.getExport('worker_get_result');\n getResultFn(token);\n const errBytes = this.readReturnSlot();\n const errMsg = new TextDecoder().decode(errBytes);\n throw new IpcError(-32000, errMsg);\n }\n\n const getResultFn = this.getExport('worker_get_result');\n const rc = getResultFn(token) as number;\n if (rc === -1) {\n const errBytes = this.readReturnSlot();\n throw new IpcError(-32000, new TextDecoder().decode(errBytes));\n }\n const resultBytes = this.readReturnSlot();\n return decodeScoredResults(resultBytes);\n }\n\n // -- Token status/result (u32 direct params) --\n\n private handleResultStatus(\n params: Record<string, unknown>,\n ): unknown {\n const token = Number(params['token'] ?? 0);\n const fn = this.getExport('worker_result_status');\n const status = fn(token) as number;\n return { status };\n }\n\n private handleGetResult(params: Record<string, unknown>): unknown {\n const token = Number(params['token'] ?? 0);\n const fn = this.getExport('worker_get_result');\n const rc = fn(token) as number;\n if (rc === -1) {\n const errBytes = this.readReturnSlot();\n throw new IpcError(-32000, new TextDecoder().decode(errBytes));\n }\n const bytes = this.readReturnSlot();\n return decodeScoredResults(bytes);\n }\n\n // -- Binary-encoded input methods --\n\n private handleAddSection(params: Record<string, unknown>): unknown {\n const sectionType = (params['sectionType'] ?? 'text') as string;\n const semanticType =\n sectionType === 'text' ||\n sectionType === 'code' ||\n sectionType === 'image'\n ? sectionType\n : 'text';\n const typeName =\n sectionType !== semanticType ? sectionType : null;\n const input: AddSectionInput = {\n sectionType: semanticType,\n mimeType: params['mimeType'] as string | undefined,\n content: (params['content'] as string | undefined) ?? '',\n title: (params['title'] as string | null) ?? null,\n description: (params['description'] as string | null) ?? null,\n docid: (params['docid'] as string | null) ?? null,\n typeName,\n };\n const encoded = encodeAddSectionParams(input);\n const bytes = this.callWasmSync('worker_add_section', encoded);\n const kbid = new TextDecoder().decode(bytes);\n return { kbid };\n }\n\n private handleUpdateSection(\n params: Record<string, unknown>,\n ): unknown {\n const oldKbid = (params['kbid'] as string | undefined) ?? '';\n const updSectionType = (params['sectionType'] ??\n 'text') as string;\n const updSemanticType =\n updSectionType === 'text' ||\n updSectionType === 'code' ||\n updSectionType === 'image'\n ? updSectionType\n : 'text';\n const updTypeName =\n updSectionType !== updSemanticType ? updSectionType : null;\n const input: AddSectionInput = {\n sectionType: updSemanticType,\n mimeType: params['mimeType'] as string | undefined,\n content: (params['content'] as string | undefined) ?? '',\n title: (params['title'] as string | null) ?? null,\n description: (params['description'] as string | null) ?? null,\n docid: (params['docid'] as string | null) ?? null,\n typeName: updTypeName,\n };\n const encoded = encodeUpdateSectionParams(oldKbid, input);\n const bytes = this.callWasmSync('worker_update_section', encoded);\n const newKbid = new TextDecoder().decode(bytes);\n return { kbid: newKbid };\n }\n\n private handleReadSections(\n params: Record<string, unknown>,\n ): unknown {\n const kbids = (params['kbids'] ?? []) as string[];\n const encoded = encodeKbidList(kbids);\n const bytes = this.callWasmSync('worker_read_sections', encoded);\n return decodeSectionRecords(bytes);\n }\n\n private handleGroupSections(\n params: Record<string, unknown>,\n ): unknown {\n const title = (params['title'] as string | undefined) ?? '';\n const kbids = (params['kbids'] ?? []) as string[];\n const docType = (params['docType'] as string | undefined) ?? '';\n const encoded = encodeGroupParams(title, kbids, docType);\n const bytes = this.callWasmSync('worker_group_sections', encoded);\n const docid = new TextDecoder().decode(bytes);\n return { docid };\n }\n\n private handleCompose(params: Record<string, unknown>): unknown {\n const ids = (params['ids'] ?? []) as string[];\n const encoded = encodeIdentifierList(ids);\n const bytes = this.callWasmSync('worker_compose', encoded);\n const output = decodeComposeOutput(bytes);\n return {\n data: output.markdown,\n total: Number(output.totalChars),\n };\n }\n\n // -- Raw UTF-8 string input methods --\n\n private handleRemoveSection(\n params: Record<string, unknown>,\n ): unknown {\n const kbid = (params['kbid'] as string | undefined) ?? '';\n const encoded = new TextEncoder().encode(kbid);\n const bytes = this.callWasmSync('worker_remove_section', encoded);\n return { removed: decodeRemoveFlag(bytes) };\n }\n\n private handleRetrieveDoc(params: Record<string, unknown>): unknown {\n const docid = (params['docid'] as string | undefined) ?? '';\n const encoded = new TextEncoder().encode(docid);\n const bytes = this.callWasmSync('worker_retrieve_doc', encoded);\n return decodeDocumentManifest(bytes);\n }\n\n private handleRemoveGrouping(\n params: Record<string, unknown>,\n ): unknown {\n const docid = (params['docid'] as string | undefined) ?? '';\n const encoded = new TextEncoder().encode(docid);\n this.callWasmSync('worker_remove_grouping', encoded);\n return { ok: true };\n }\n\n private handleInitDirectory(\n params: Record<string, unknown>,\n ): unknown {\n const path =\n (params['path'] as string | undefined) ?? this.targetDir;\n const encoded = new TextEncoder().encode(path);\n this.callWasmSync('worker_init_directory', encoded);\n return { ok: true };\n }\n\n private handleInvalidate(params: Record<string, unknown>): unknown {\n const kbid = (params['kbid'] as string | undefined) ?? '';\n const encoded = new TextEncoder().encode(kbid);\n this.callWasmSync('worker_invalidate', encoded);\n return { ok: true };\n }\n\n private handleListByType(params: Record<string, unknown>): unknown {\n const typeStr =\n (params['sectionType'] as string | undefined) ?? '';\n const encoded = encodeTypeFilterParam(typeStr);\n const bytes = this.callWasmSync('worker_list_by_type', encoded);\n return decodeSectionRecordList(bytes);\n }\n\n private handleListDocsByType(\n params: Record<string, unknown>,\n ): unknown {\n const typeStr = (params['docType'] as string | undefined) ?? '';\n const encoded = encodeTypeFilterParam(typeStr);\n const bytes = this.callWasmSync(\n 'worker_list_docs_by_type',\n encoded,\n );\n return decodeDocumentManifestList(bytes);\n }\n\n // -- Zero-arg methods --\n\n private handleInvalidateAll(): unknown {\n this.callWasmZeroArg('worker_invalidate_all');\n return { ok: true };\n }\n\n private handleDbStatus(): unknown {\n this.callWasmZeroArg('worker_status');\n const bytes = this.readReturnSlot();\n const text = new TextDecoder().decode(bytes);\n return decodeKeyValueText(text);\n }\n\n private handleIntegrityCheck(): unknown {\n this.callWasmZeroArg('worker_check_integrity');\n const bytes = this.readReturnSlot();\n const text = new TextDecoder().decode(bytes);\n return decodeKeyValueText(text);\n }\n\n private handleGc(): unknown {\n this.callWasmZeroArg('worker_garbage_collect');\n const bytes = this.readReturnSlot();\n const text = new TextDecoder().decode(bytes);\n return decodeKeyValueText(text);\n }\n\n private handleRebuild(): unknown {\n this.callWasmZeroArg('worker_rebuild_indexes');\n return { ok: true };\n }\n\n // -- WASM lifecycle --\n\n private initWorkerContext(): void {\n const pathBytes = new TextEncoder().encode('.');\n this.callWasmSync('worker_init', pathBytes);\n }\n\n // -- WASM bridge primitives --\n\n private getExport(name: string): WasmFn {\n if (this._wasmModules === null) {\n throw new Error('WASM modules not loaded');\n }\n const fn = this._wasmModules.kbWorker.exports[name] as\n | WasmFn\n | undefined;\n if (typeof fn !== 'function') {\n throw new Error(`WASM export not found: ${name}`);\n }\n return fn;\n }\n\n private wasmAlloc(size: number): number {\n if (size === 0) return 0;\n const allocFn = this._wasmModules?.kbWorker.exports[\n 'kbdb_alloc'\n ] as WasmFn | undefined;\n if (typeof allocFn !== 'function') return 0;\n return allocFn(size) as number;\n }\n\n private wasmFree(ptr: number, size: number): void {\n if (ptr === 0 || size === 0) return;\n const freeFn = this._wasmModules?.kbWorker.exports[\n 'kbdb_free'\n ] as WasmFn | undefined;\n if (typeof freeFn === 'function') {\n freeFn(ptr, size);\n }\n }\n\n private wasmWrite(ptr: number, data: Uint8Array): void {\n if (data.length === 0) return;\n const memory = this._wasmModules?.memory;\n if (!memory) return;\n const memView = new Uint8Array(memory.buffer);\n if (ptr + data.length > memView.length) {\n throw new Error('WASM memory overflow');\n }\n memView.set(data, ptr);\n }\n\n private readReturnSlot(): Uint8Array {\n const getPtrFn = this._wasmModules?.kbWorker.exports[\n 'get_return_ptr'\n ] as WasmFn | undefined;\n const getLenFn = this._wasmModules?.kbWorker.exports[\n 'get_return_len'\n ] as WasmFn | undefined;\n if (\n typeof getPtrFn !== 'function' ||\n typeof getLenFn !== 'function'\n ) {\n return new Uint8Array(0);\n }\n const ptr = getPtrFn() as number;\n const len = getLenFn() as number;\n if (ptr === 0 || len === 0) {\n return new Uint8Array(0);\n }\n const memory = this._wasmModules?.memory;\n if (!memory) return new Uint8Array(0);\n const data = new Uint8Array(memory.buffer, ptr, len).slice();\n this.wasmFree(ptr, len);\n return data;\n }\n\n private callWasmSync(\n exportName: string,\n input: Uint8Array,\n ): Uint8Array {\n const fn = this.getExport(exportName);\n const ptr = this.wasmAlloc(input.length);\n this.wasmWrite(ptr, input);\n const rc = fn(ptr, input.length) as number;\n this.wasmFree(ptr, input.length);\n if (rc === -1) {\n const errBytes = this.readReturnSlot();\n const errMsg = new TextDecoder().decode(errBytes);\n throw new IpcError(-32000, errMsg || exportName + ' failed');\n }\n return this.readReturnSlot();\n }\n\n private callWasmZeroArg(exportName: string): void {\n const fn = this.getExport(exportName);\n const rc = fn() as number;\n if (rc === -1) {\n const errBytes = this.readReturnSlot();\n const errMsg = new TextDecoder().decode(errBytes);\n throw new IpcError(-32000, errMsg || exportName + ' failed');\n }\n }\n\n private invokeWasmRaw(\n exportName: string,\n input: Uint8Array,\n ): unknown {\n return this.callWasmSync(exportName, input);\n }\n\n private handleCheckVersion(\n params: Record<string, unknown>,\n ): unknown {\n const targetPath =\n typeof params.targetPath === 'string'\n ? params.targetPath\n : this.targetDir;\n const catalogPath = join(targetPath, 'catalog.toml');\n let text: string;\n try {\n text = readFileSync(catalogPath, 'utf-8');\n } catch {\n return {\n status: 'needs_migration',\n currentVersion: 0,\n requiredVersion: DB_FORMAT_VERSION,\n };\n }\n const version = parseCatalogVersion(text);\n if (version === null) {\n return {\n status: 'needs_migration',\n currentVersion: 0,\n requiredVersion: DB_FORMAT_VERSION,\n };\n }\n if (version > DB_FORMAT_VERSION) {\n return {\n status: 'too_new',\n currentVersion: version,\n requiredVersion: DB_FORMAT_VERSION,\n };\n }\n if (version < DB_FORMAT_VERSION) {\n return {\n status: 'needs_migration',\n currentVersion: version,\n requiredVersion: DB_FORMAT_VERSION,\n };\n }\n return {\n status: 'compatible',\n currentVersion: version,\n requiredVersion: DB_FORMAT_VERSION,\n };\n }\n\n /** Returns a daemon config value by config method name. */\n private handleConfigMethod(method: string): unknown {\n const key = method.slice(CONFIG_PREFIX.length);\n const prop = CONFIG_KEY_MAP[key];\n if (prop === undefined) {\n throw new IpcError(-32601, `Method not found: ${method}`);\n }\n return this.config[prop];\n }\n}\n\n// ---------------------------------------------------------------------------\n// Module-private helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Parses the `version` field from a minimal TOML string.\n *\n * Supports only `version = <integer>` syntax. Returns `null` if the\n * field is absent.\n */\nfunction parseCatalogVersion(text: string): number | null {\n for (const line of text.split('\\n')) {\n const trimmed = line.trim();\n if (trimmed.startsWith('#')) continue;\n const match = /^version\\s*=\\s*(\\d+)/.exec(trimmed);\n if (match?.[1] !== undefined) {\n return parseInt(match[1], 10);\n }\n }\n return null;\n}\n", "import { readFileSync } from 'node:fs';\n\nimport type { DaemonConfig } from '../typings/daemon-config.interface.ts';\nimport type { WasmModules } from '../typings/wasm-modules.interface.ts';\nimport { createHostImports } from './create-host-imports.function.ts';\nimport type {\n AllocatorRef,\n MemoryRef,\n} from './create-host-imports.function.ts';\nimport { isRemoteUrl, joinPath } from '../../dir-resolver/index.ts';\n\nexport async function loadWasmModules(\n config: DaemonConfig,\n wasmDir: string,\n): Promise<WasmModules> {\n const memoryRef: MemoryRef = { memory: null };\n const allocator: AllocatorRef = { alloc: null };\n\n const hostImports = createHostImports(\n config.contextPath,\n memoryRef,\n undefined,\n allocator,\n );\n\n const wkPath = joinPath(wasmDir, 'kb-worker', 'kbdb_worker_bg.wasm');\n const wkBytes = await readWasmFile(wkPath, 'kb-worker');\n\n let wkModule: WebAssembly.Module;\n try {\n wkModule = await WebAssembly.compile(wkBytes);\n } catch (err) {\n rethrow('compile', 'kb-worker', err);\n }\n\n let kbWorker: WebAssembly.Instance;\n try {\n kbWorker = await WebAssembly.instantiate(wkModule, {\n env: { ...hostImports },\n });\n } catch (err) {\n rethrow('instantiate', 'kb-worker', err);\n }\n\n const memory = kbWorker.exports['memory'] as WebAssembly.Memory;\n memoryRef.memory = memory;\n\n allocator.alloc = (size: number): number => {\n const fn_ = kbWorker.exports['kbdb_alloc'] as\n | ((s: number) => number)\n | undefined;\n if (typeof fn_ !== 'function') return 0;\n return fn_(size);\n };\n\n return { memory, kbWorker };\n}\n\nasync function readWasmFile(\n path: string,\n label: string,\n): Promise<ArrayBuffer> {\n try {\n if (isRemoteUrl(path)) {\n const response = await fetch(path);\n if (!response.ok) {\n throw new Error(\n `HTTP ${String(response.status)} ${response.statusText}`,\n );\n }\n return await response.arrayBuffer();\n }\n const buf = readFileSync(path);\n return buf.buffer.slice(\n buf.byteOffset,\n buf.byteOffset + buf.byteLength,\n );\n } catch (err) {\n rethrow('load', label, err, path);\n }\n}\n\nfunction rethrow(\n stage: string,\n label: string,\n err: unknown,\n path?: string,\n): never {\n const detail = err instanceof Error ? err.message : String(err);\n const suffix = path ? ` (path: ${path})` : '';\n const message = `failed to ${stage} ${label} WASM: ${detail}${suffix}`;\n // eslint-disable-next-line no-console\n console.error(`kbdb-worker: ${message}`);\n throw new Error(message, { cause: err });\n}\n", "import {\n readFileSync,\n writeFileSync,\n renameSync,\n unlinkSync,\n readdirSync,\n mkdirSync,\n existsSync,\n} from 'node:fs';\nimport { join } from 'node:path';\n\n// ---------------------------------------------------------------------------\n// FsAdapter interface (enables dependency injection for testing)\n// ---------------------------------------------------------------------------\n\n/**\n * Minimal filesystem operations required by the host imports.\n *\n * The default implementation delegates to `node:fs` synchronous\n * APIs. Tests inject a stub to avoid touching the real filesystem.\n */\nexport interface FsAdapter {\n /** Read entire file as a Buffer. */\n readFileSync(path: string): Buffer;\n /** Write data buffer to file. */\n writeFileSync(path: string, data: Uint8Array): void;\n /** Rename `oldPath` to `newPath`. */\n renameSync(oldPath: string, newPath: string): void;\n /** Delete a file. */\n unlinkSync(path: string): void;\n /** List directory entries as strings. */\n readdirSync(path: string): string[];\n /** Create a directory (and parents) recursively. */\n mkdirSync(path: string): void;\n /** Return true if the path exists. */\n existsSync(path: string): boolean;\n}\n\n// ---------------------------------------------------------------------------\n// MemoryRef interface\n// ---------------------------------------------------------------------------\n\n/**\n * A mutable reference to the WASM linear memory.\n *\n * The `memory` field starts as `null` and is wired up after the\n * `kb-worker` WASM module is instantiated (the module exports its\n * own memory rather than importing one). Host import functions\n * read `memory` at call time, not at creation time, so the ref\n * can be populated after the import record is built.\n */\nexport interface MemoryRef {\n memory: WebAssembly.Memory | null;\n}\n\n// ---------------------------------------------------------------------------\n// AllocatorRef interface\n// ---------------------------------------------------------------------------\n\n/**\n * A mutable reference to the WASM allocator function.\n *\n * The `alloc` field starts as `null` and is wired up after the\n * `kb-worker` WASM module is instantiated. Host import functions\n * that must allocate memory in WASM linear memory check this\n * reference before proceeding and return -1 when it is null.\n */\nexport interface AllocatorRef {\n /**\n * Allocates `size` bytes in WASM linear memory and returns the\n * byte offset of the allocated region, or `null` when the\n * allocator is not yet available.\n */\n alloc: ((size: number) => number) | null;\n}\n\n/** Default `FsAdapter` backed by `node:fs` synchronous APIs. */\nconst nodeFsAdapter: FsAdapter = {\n readFileSync: (p) => readFileSync(p),\n writeFileSync: (p, d) => {\n writeFileSync(p, d);\n },\n renameSync: (o, n) => {\n renameSync(o, n);\n },\n unlinkSync: (p) => {\n unlinkSync(p);\n },\n readdirSync: (p) => readdirSync(p),\n mkdirSync: (p) => {\n mkdirSync(p, { recursive: true });\n },\n existsSync: (p) => existsSync(p),\n};\n\n/** Default `MemoryRef` with no memory wired. */\nconst nullMemory: MemoryRef = { memory: null };\n\n/** Default `AllocatorRef` with no allocator wired. */\nconst nullAllocator: AllocatorRef = { alloc: null };\n\n// ---------------------------------------------------------------------------\n// createHostImports\n// ---------------------------------------------------------------------------\n\n/**\n * Creates the host I/O import functions required by `kb-worker.wasm`.\n *\n * All functions read the WASM linear memory through `memoryRef`,\n * a deferred reference wired up after module instantiation (the\n * module exports its own memory). Paths from WASM are resolved\n * relative to `contextPath`.\n *\n * @param contextPath - absolute path to the `.kbdb` database directory\n * @param memoryRef - deferred reference to the WASM module's\n * exported memory; wired after instantiation\n * @param fs - filesystem adapter; defaults to real `node:fs` operations\n * @param allocator - reference to the WASM allocator; wired after\n * `kb-worker` instantiation. Defaults to a null (uninitialized) ref.\n * @returns a record of host import functions keyed by their WASM import\n * names\n */\nexport function createHostImports(\n contextPath: string,\n memoryRef: MemoryRef = nullMemory,\n fs: FsAdapter = nodeFsAdapter,\n allocator: AllocatorRef = nullAllocator,\n): Record<string, WebAssembly.ImportValue> {\n function getBuffer(): ArrayBuffer {\n if (!memoryRef.memory) {\n throw new Error('WASM memory not initialized');\n }\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion\n return memoryRef.memory.buffer as ArrayBuffer;\n }\n\n function readPathArg(ptr: number, len: number): string {\n const bytes = new Uint8Array(getBuffer(), ptr, len);\n const relative = new TextDecoder().decode(bytes);\n return join(contextPath, relative);\n }\n\n return {\n /**\n * Reads a file at the path encoded in shared memory and writes\n * the result back via the out-pointer protocol.\n *\n * `outPtr` and `outLen` are WASM linear-memory addresses. On\n * success, the host allocates a buffer via `allocator.alloc`,\n * copies the file data there, and writes the allocated pointer\n * as a LE u32 to `outPtr` and the data length as a LE u32 to\n * `outLen`. Returns 0 on success, -1 on error or when the\n * allocator is not yet available.\n */\n host_read_file(\n pathPtr: number,\n pathLen: number,\n outPtr: number,\n outLen: number,\n ): number {\n try {\n if (!allocator.alloc) return -1;\n const filePath = readPathArg(pathPtr, pathLen);\n const data = fs.readFileSync(filePath);\n const dataLen = data.byteLength;\n const dv = new DataView(getBuffer());\n if (dataLen === 0) {\n dv.setUint32(outPtr, 0, true);\n dv.setUint32(outLen, 0, true);\n return 0;\n }\n const dataPtr = allocator.alloc(dataLen);\n if (dataPtr === 0) return -1;\n const memView = new Uint8Array(getBuffer());\n memView.set(\n new Uint8Array(\n data.buffer,\n data.byteOffset,\n data.byteLength,\n ),\n dataPtr,\n );\n dv.setUint32(outPtr, dataPtr, true);\n dv.setUint32(outLen, dataLen, true);\n return 0;\n } catch {\n return -1;\n }\n },\n\n /**\n * Writes bytes from shared memory (`dataPtr`, `dataLen`) to the\n * file at the path encoded in shared memory. Returns 0 on\n * success, -1 on error.\n */\n host_write_file(\n pathPtr: number,\n pathLen: number,\n dataPtr: number,\n dataLen: number,\n ): number {\n try {\n const filePath = readPathArg(pathPtr, pathLen);\n const data = new Uint8Array(getBuffer(), dataPtr, dataLen);\n fs.writeFileSync(filePath, data);\n return 0;\n } catch {\n return -1;\n }\n },\n\n /**\n * Renames the file at `oldPtr/oldLen` to `newPtr/newLen`.\n * Both paths are resolved relative to `contextPath`. Returns 0\n * on success, -1 on error.\n */\n host_rename(\n oldPtr: number,\n oldLen: number,\n newPtr: number,\n newLen: number,\n ): number {\n try {\n const oldPath = readPathArg(oldPtr, oldLen);\n const newPath = readPathArg(newPtr, newLen);\n fs.renameSync(oldPath, newPath);\n return 0;\n } catch {\n return -1;\n }\n },\n\n /**\n * Deletes the file at the path encoded in shared memory.\n * Returns 0 on success, -1 on error.\n */\n host_remove_file(pathPtr: number, pathLen: number): number {\n try {\n const filePath = readPathArg(pathPtr, pathLen);\n fs.unlinkSync(filePath);\n return 0;\n } catch {\n return -1;\n }\n },\n\n /**\n * Lists the directory at the path encoded in shared memory and\n * writes the result back via the out-pointer protocol.\n *\n * `outPtr` and `outLen` are WASM linear-memory addresses. On\n * success, the host allocates a buffer via `allocator.alloc`,\n * copies a newline-delimited UTF-8 listing there, and writes\n * the allocated pointer as a LE u32 to `outPtr` and the byte\n * length as a LE u32 to `outLen`. Returns 0 on success, -1 on\n * error or when the allocator is not yet available.\n */\n host_list_dir(\n pathPtr: number,\n pathLen: number,\n outPtr: number,\n outLen: number,\n ): number {\n try {\n if (!allocator.alloc) return -1;\n const dirPath = readPathArg(pathPtr, pathLen);\n const entries = fs.readdirSync(dirPath);\n const text = entries.join('\\n');\n const encoded = new TextEncoder().encode(text);\n const dv = new DataView(getBuffer());\n if (encoded.length === 0) {\n dv.setUint32(outPtr, 0, true);\n dv.setUint32(outLen, 0, true);\n return 0;\n }\n const dataPtr = allocator.alloc(encoded.length);\n if (dataPtr === 0) return -1;\n new Uint8Array(getBuffer(), dataPtr, encoded.length).set(\n encoded,\n );\n dv.setUint32(outPtr, dataPtr, true);\n dv.setUint32(outLen, encoded.length, true);\n return 0;\n } catch {\n return -1;\n }\n },\n\n /**\n * Creates the directory at the path encoded in shared memory,\n * including any missing parent directories (recursive). Returns\n * 0 on success, -1 on error.\n */\n host_mkdir(pathPtr: number, pathLen: number): number {\n try {\n const dirPath = readPathArg(pathPtr, pathLen);\n fs.mkdirSync(dirPath);\n return 0;\n } catch {\n return -1;\n }\n },\n\n /**\n * Checks whether the file at the path encoded in shared memory\n * exists. Returns 1 if it exists, 0 if it does not.\n */\n host_file_exists(pathPtr: number, pathLen: number): number {\n const filePath = readPathArg(pathPtr, pathLen);\n return fs.existsSync(filePath) ? 1 : 0;\n },\n };\n}\n", "import { createServer } from 'node:net';\nimport type { Server, Socket } from 'node:net';\nimport type {\n IpcHandler,\n IpcRequest,\n IpcResponse,\n} from '../typings/ipc-handler.interface.ts';\n\n/**\n * Creates a Unix socket (or named pipe on Windows) IPC server that\n * reads newline-delimited JSON-RPC requests and writes responses.\n *\n * Each line received on a socket connection is parsed as an\n * `IpcRequest`, dispatched to `handler`, and the resulting\n * `IpcResponse` is written back as a newline-terminated JSON string.\n * A malformed line that cannot be parsed results in a JSON-RPC\n * parse-error response (`-32700`).\n *\n * @param socketPath - path to the Unix domain socket or Windows\n * named pipe\n * @param handler - async function invoked for each valid request\n * @returns the listening `net.Server` instance\n */\nexport function createIpcServer(\n socketPath: string,\n handler: IpcHandler,\n): Server {\n const server = createServer((socket) => {\n let buffer = '';\n\n socket.on('data', (chunk: Buffer) => {\n buffer += chunk.toString();\n const lines = buffer.split('\\n');\n buffer = lines.pop() ?? '';\n\n for (const line of lines) {\n if (!line.trim()) continue;\n void handleLine(line, handler, socket);\n }\n });\n\n socket.on('error', (err: Error) => {\n // eslint-disable-next-line no-console\n console.error(\n `kbdb-worker: ipc connection error: ${err.message}`,\n );\n });\n });\n\n server.on('error', (err: Error) => {\n // eslint-disable-next-line no-console\n console.error(`kbdb-worker: ipc server error: ${err.message}`);\n });\n\n server.listen(socketPath);\n return server;\n}\n\nfunction bigintReplacer(_key: string, value: unknown): unknown {\n return typeof value === 'bigint' ? Number(value) : value;\n}\n\nasync function handleLine(\n line: string,\n handler: IpcHandler,\n socket: Socket,\n): Promise<void> {\n let response: IpcResponse;\n try {\n const request = JSON.parse(line) as IpcRequest;\n response = await handler(request);\n } catch {\n response = {\n jsonrpc: '2.0',\n id: 0,\n error: {\n code: -32700,\n message: 'Parse error',\n },\n };\n }\n socket.write(JSON.stringify(response, bigintReplacer) + '\\n');\n}\n", "const encoder = new TextEncoder();\n\nexport function encodeString(value: string): Uint8Array {\n const utf8 = encoder.encode(value);\n const result = new Uint8Array(4 + utf8.length);\n new DataView(result.buffer).setUint32(0, utf8.length, true);\n result.set(utf8, 4);\n return result;\n}\n", "export function encodeU32(value: number): Uint8Array {\n const result = new Uint8Array(4);\n new DataView(result.buffer).setUint32(0, value, true);\n return result;\n}\n", "import { encodeString } from './encode-string.function.ts';\n\nexport function encodeOptionString(\n value: string | null | undefined,\n): Uint8Array {\n if (value == null) {\n return new Uint8Array([0x00]);\n }\n const encoded = encodeString(value);\n const result = new Uint8Array(1 + encoded.length);\n result[0] = 0x01;\n result.set(encoded, 1);\n return result;\n}\n", "import { encodeString } from './encode-string.function.ts';\n\nexport function encodeSectionType(\n kind: 'text' | 'code' | 'image',\n mimeType?: string,\n): Uint8Array {\n if (kind === 'text') {\n return new Uint8Array([0x00]);\n }\n\n const tag = kind === 'code' ? 0x01 : 0x02;\n const mime = mimeType ?? 'text/plain';\n const encoded = encodeString(mime);\n const result = new Uint8Array(1 + encoded.length);\n result[0] = tag;\n result.set(encoded, 1);\n return result;\n}\n", "import { encodeSectionType } from './encode-section-type.function.ts';\nimport { encodeString } from './encode-string.function.ts';\nimport { encodeOptionString } from './encode-option-string.function.ts';\n\nexport interface AddSectionInput {\n sectionType: 'text' | 'code' | 'image';\n mimeType?: string;\n content: string;\n title?: string | null;\n description?: string | null;\n docid?: string | null;\n typeName?: string | null;\n}\n\nexport function encodeAddSectionParams(\n params: AddSectionInput,\n): Uint8Array {\n const parts = [\n encodeSectionType(params.sectionType, params.mimeType),\n encodeString(params.content),\n encodeOptionString(params.title),\n encodeOptionString(params.description),\n encodeOptionString(params.docid),\n encodeOptionString(params.typeName),\n ];\n const totalLen = parts.reduce((sum, p) => sum + p.length, 0);\n const result = new Uint8Array(totalLen);\n let offset = 0;\n for (const part of parts) {\n result.set(part, offset);\n offset += part.length;\n }\n return result;\n}\n", "import { encodeString } from './encode-string.function.ts';\nimport { encodeAddSectionParams } from './encode-add-section-params.function.ts';\n\nimport type { AddSectionInput } from './encode-add-section-params.function.ts';\n\nexport function encodeUpdateSectionParams(\n oldKbid: string,\n params: AddSectionInput,\n): Uint8Array {\n const kbidBytes = encodeString(oldKbid);\n const paramBytes = encodeAddSectionParams(params);\n const result = new Uint8Array(kbidBytes.length + paramBytes.length);\n result.set(kbidBytes, 0);\n result.set(paramBytes, kbidBytes.length);\n return result;\n}\n", "import { encodeU32 } from './encode-u32.function.ts';\nimport { encodeString } from './encode-string.function.ts';\n\nexport function encodeKbidList(kbids: string[]): Uint8Array {\n if (kbids.length === 0) {\n return new Uint8Array(0);\n }\n const parts = [encodeU32(kbids.length), ...kbids.map(encodeString)];\n const totalLen = parts.reduce((sum, p) => sum + p.length, 0);\n const result = new Uint8Array(totalLen);\n let offset = 0;\n for (const part of parts) {\n result.set(part, offset);\n offset += part.length;\n }\n return result;\n}\n", "import { encodeString } from './encode-string.function.ts';\nimport { encodeKbidList } from './encode-kbid-list.function.ts';\n\n/**\n * Encodes parameters for the `worker_group_sections` WASM call into\n * a single byte buffer: title, kbid list, then doc type tag.\n *\n * @param title - human-readable document title\n * @param kbids - identifiers of the sections to group\n * @param docType - application-level document type tag; defaults to\n * empty string when not specified\n */\nexport function encodeGroupParams(\n title: string,\n kbids: string[],\n docType = '',\n): Uint8Array {\n const titleBytes = encodeString(title);\n const listBytes = encodeKbidList(kbids);\n const docTypeBytes = encodeString(docType);\n const result = new Uint8Array(\n titleBytes.length + listBytes.length + docTypeBytes.length,\n );\n result.set(titleBytes, 0);\n result.set(listBytes, titleBytes.length);\n result.set(docTypeBytes, titleBytes.length + listBytes.length);\n return result;\n}\n", "import { encodeU32 } from './encode-u32.function.ts';\nimport { encodeString } from './encode-string.function.ts';\n\nexport function encodeIdentifierList(ids: string[]): Uint8Array {\n if (ids.length === 0) {\n return new Uint8Array(0);\n }\n const parts = [encodeU32(ids.length), ...ids.map(encodeString)];\n const totalLen = parts.reduce((sum, p) => sum + p.length, 0);\n const result = new Uint8Array(totalLen);\n let offset = 0;\n for (const part of parts) {\n result.set(part, offset);\n offset += part.length;\n }\n return result;\n}\n", "const encoder = new TextEncoder();\n\nexport function encodeSearchParams(\n query: string,\n mode = 'and',\n limit = 20,\n): Uint8Array {\n return encoder.encode(`${query}\\n${mode}\\n${String(limit)}`);\n}\n", "/**\n * Encodes a type filter string as raw UTF-8 bytes for WASM input.\n *\n * Used to pass a type name to WASM exports such as\n * `worker_list_by_type` and `worker_list_docs_by_type`, which accept\n * a plain UTF-8 byte slice without a length prefix.\n *\n * @param typeStr - the type name to filter by (e.g. `'article'`)\n * @returns UTF-8 encoded bytes ready to pass to the WASM export\n */\nexport function encodeTypeFilterParam(typeStr: string): Uint8Array {\n return new TextEncoder().encode(typeStr);\n}\n", "const decoder = new TextDecoder();\n\nexport interface DecodeResult<T> {\n value: T;\n bytesRead: number;\n}\n\nexport function decodeString(\n bytes: Uint8Array,\n offset: number,\n): DecodeResult<string> {\n const view = new DataView(\n bytes.buffer,\n bytes.byteOffset,\n bytes.byteLength,\n );\n const len = view.getUint32(offset, true);\n const value = decoder.decode(\n bytes.subarray(offset + 4, offset + 4 + len),\n );\n return { value, bytesRead: 4 + len };\n}\n", "import type { DecodeResult } from './decode-string.function.ts';\n\nexport function decodeU32(\n bytes: Uint8Array,\n offset: number,\n): DecodeResult<number> {\n const view = new DataView(\n bytes.buffer,\n bytes.byteOffset,\n bytes.byteLength,\n );\n return {\n value: view.getUint32(offset, true),\n bytesRead: 4,\n };\n}\n", "import type { DecodeResult } from './decode-string.function.ts';\n\nexport function decodeF32(\n bytes: Uint8Array,\n offset: number,\n): DecodeResult<number> {\n const view = new DataView(\n bytes.buffer,\n bytes.byteOffset,\n bytes.byteLength,\n );\n return {\n value: view.getFloat32(offset, true),\n bytesRead: 4,\n };\n}\n", "import type { DecodeResult } from './decode-string.function.ts';\n\nexport function decodeU64(\n bytes: Uint8Array,\n offset: number,\n): DecodeResult<bigint> {\n const view = new DataView(\n bytes.buffer,\n bytes.byteOffset,\n bytes.byteLength,\n );\n return {\n value: view.getBigUint64(offset, true),\n bytesRead: 8,\n };\n}\n", "import { decodeString } from './decode-string.function.ts';\nimport { decodeU32 } from './decode-u32.function.ts';\nimport { decodeF32 } from './decode-f32.function.ts';\n\nexport interface TermMatch {\n term: string;\n frequency: number;\n}\n\nexport interface ScoredResult {\n kbid: string;\n score: number;\n matches: TermMatch[];\n}\n\nexport function decodeScoredResults(bytes: Uint8Array): ScoredResult[] {\n let offset = 0;\n const count = decodeU32(bytes, offset);\n offset += count.bytesRead;\n\n const results: ScoredResult[] = [];\n for (let i = 0; i < count.value; i++) {\n const kbid = decodeString(bytes, offset);\n offset += kbid.bytesRead;\n\n const score = decodeF32(bytes, offset);\n offset += score.bytesRead;\n\n const matchCount = decodeU32(bytes, offset);\n offset += matchCount.bytesRead;\n\n const matches: TermMatch[] = [];\n for (let j = 0; j < matchCount.value; j++) {\n const term = decodeString(bytes, offset);\n offset += term.bytesRead;\n\n const freq = decodeF32(bytes, offset);\n offset += freq.bytesRead;\n\n matches.push({\n term: term.value,\n frequency: freq.value,\n });\n }\n\n results.push({\n kbid: kbid.value,\n score: score.value,\n matches,\n });\n }\n\n return results;\n}\n", "import { decodeString } from './decode-string.function.ts';\nimport { decodeU32 } from './decode-u32.function.ts';\nimport { decodeU64 } from './decode-u64.function.ts';\n\n/**\n * A single section record decoded from WASM binary output.\n *\n * Represents a stored knowledge-base section with all its metadata\n * and token counts as returned by `worker_read_sections` or\n * `worker_list_by_type`.\n */\nexport interface SectionRecord {\n /** Unique knowledge-base identifier for this section. */\n kbid: string;\n /** Document identifier this section belongs to, or `null`. */\n docid: string | null;\n /** Semantic type discriminant: `'text'`, `'code'`, or `'image'`. */\n sectionType: string;\n /** MIME type string, present only for `'code'` and `'image'` types. */\n mimeType?: string;\n /** Human-readable title for the section, or `null`. */\n title: string | null;\n /** Optional description of the section content, or `null`. */\n description: string | null;\n /** Raw text or base64-encoded content of the section. */\n content: string;\n /** Byte size of the stored content. */\n size: number;\n /** Section creation timestamp as a Unix epoch value. */\n createdAt: bigint;\n /** Integrity checksum of the stored content. */\n checksum: string;\n /** Total number of tokens in the section. */\n tokenCount: number;\n /** Number of heading tokens in the section. */\n headingTokenCount: number;\n /** Number of body tokens in the section. */\n bodyTokenCount: number;\n /** Number of code tokens in the section. */\n codeTokenCount: number;\n /** Application-level type name assigned to this section. */\n typeName: string;\n}\n\nfunction decodeOptionString(\n bytes: Uint8Array,\n offset: number,\n): { value: string | null; bytesRead: number } {\n const tag = bytes[offset];\n if (tag === 0x00) {\n return { value: null, bytesRead: 1 };\n }\n const str = decodeString(bytes, offset + 1);\n return { value: str.value, bytesRead: 1 + str.bytesRead };\n}\n\nfunction decodeSectionType(\n bytes: Uint8Array,\n offset: number,\n): {\n sectionType: string;\n mimeType?: string;\n bytesRead: number;\n} {\n const tag = bytes[offset];\n if (tag === 0x00) {\n return { sectionType: 'text', bytesRead: 1 };\n }\n const mime = decodeString(bytes, offset + 1);\n const kind = tag === 0x01 ? 'code' : 'image';\n return {\n sectionType: kind,\n mimeType: mime.value,\n bytesRead: 1 + mime.bytesRead,\n };\n}\n\n/**\n * Decodes a list of `SectionRecord` values from WASM binary output.\n *\n * Reads a leading u32 count followed by that many encoded records.\n * Each record is decoded in field order as produced by the Rust\n * `SectionRecord::encode` implementation.\n *\n * @param bytes - raw bytes returned by a WASM section-list export\n * @returns decoded array of section records, empty when count is zero\n */\nexport function decodeSectionRecords(\n bytes: Uint8Array,\n): SectionRecord[] {\n let offset = 0;\n const count = decodeU32(bytes, offset);\n offset += count.bytesRead;\n\n const records: SectionRecord[] = [];\n for (let i = 0; i < count.value; i++) {\n const kbid = decodeString(bytes, offset);\n offset += kbid.bytesRead;\n\n const docid = decodeOptionString(bytes, offset);\n offset += docid.bytesRead;\n\n const st = decodeSectionType(bytes, offset);\n offset += st.bytesRead;\n\n const title = decodeOptionString(bytes, offset);\n offset += title.bytesRead;\n\n const description = decodeOptionString(bytes, offset);\n offset += description.bytesRead;\n\n const content = decodeString(bytes, offset);\n offset += content.bytesRead;\n\n const size = decodeU32(bytes, offset);\n offset += size.bytesRead;\n\n const createdAt = decodeU64(bytes, offset);\n offset += createdAt.bytesRead;\n\n const checksum = decodeString(bytes, offset);\n offset += checksum.bytesRead;\n\n const tokenCount = decodeU32(bytes, offset);\n offset += tokenCount.bytesRead;\n\n const headingTokenCount = decodeU32(bytes, offset);\n offset += headingTokenCount.bytesRead;\n\n const bodyTokenCount = decodeU32(bytes, offset);\n offset += bodyTokenCount.bytesRead;\n\n const codeTokenCount = decodeU32(bytes, offset);\n offset += codeTokenCount.bytesRead;\n\n const typeName = decodeString(bytes, offset);\n offset += typeName.bytesRead;\n\n const record: SectionRecord = {\n kbid: kbid.value,\n docid: docid.value,\n sectionType: st.sectionType,\n title: title.value,\n description: description.value,\n content: content.value,\n size: size.value,\n createdAt: createdAt.value,\n checksum: checksum.value,\n tokenCount: tokenCount.value,\n headingTokenCount: headingTokenCount.value,\n bodyTokenCount: bodyTokenCount.value,\n codeTokenCount: codeTokenCount.value,\n typeName: typeName.value,\n };\n if (st.mimeType !== undefined) {\n record.mimeType = st.mimeType;\n }\n records.push(record);\n }\n\n return records;\n}\n", "import { decodeSectionRecords } from './decode-section-records.function.ts';\nimport type { SectionRecord } from './decode-section-records.function.ts';\n\nexport type { SectionRecord };\n\n/**\n * Decodes a WASM byte slice into an array of `SectionRecord` values.\n *\n * Thin wrapper around `decodeSectionRecords` provided as the\n * canonical entry point for list-response decoding from WASM exports\n * such as `worker_list_by_type`.\n *\n * @param bytes - raw bytes returned by a WASM section-list export\n * @returns decoded array of section records\n */\nexport function decodeSectionRecordList(\n bytes: Uint8Array,\n): SectionRecord[] {\n return decodeSectionRecords(bytes);\n}\n", "import { decodeString } from './decode-string.function.ts';\nimport { decodeU32 } from './decode-u32.function.ts';\nimport { decodeU64 } from './decode-u64.function.ts';\n\n/**\n * A single section reference within a document manifest.\n *\n * Associates a knowledge-base identifier with the section's\n * ordinal position in the document.\n */\nexport interface DocumentSection {\n /** Knowledge-base identifier of the referenced section. */\n kbid: string;\n /** Zero-based position of this section within its document. */\n position: number;\n}\n\n/**\n * A document manifest decoded from WASM binary output.\n *\n * Represents a grouped document record with its ordered list of\n * section references as returned by `worker_retrieve_doc`.\n */\nexport interface DocumentManifest {\n /** Unique document identifier. */\n docid: string;\n /** Human-readable document title. */\n title: string;\n /** Document creation timestamp as a Unix epoch value. */\n createdAt: bigint;\n /** Application-level type name assigned to this document. */\n docType: string;\n /** Ordered list of section references belonging to the document. */\n sections: DocumentSection[];\n}\n\n/**\n * Decodes a single `DocumentManifest` from WASM binary output.\n *\n * Reads fields in the order: docid, title, createdAt, docType,\n * section count, then each section's kbid and position.\n *\n * @param bytes - raw bytes returned by `worker_retrieve_doc`\n * @returns the decoded document manifest\n */\nexport function decodeDocumentManifest(\n bytes: Uint8Array,\n): DocumentManifest {\n let offset = 0;\n\n const docid = decodeString(bytes, offset);\n offset += docid.bytesRead;\n\n const title = decodeString(bytes, offset);\n offset += title.bytesRead;\n\n const createdAt = decodeU64(bytes, offset);\n offset += createdAt.bytesRead;\n\n const docType = decodeString(bytes, offset);\n offset += docType.bytesRead;\n\n const count = decodeU32(bytes, offset);\n offset += count.bytesRead;\n\n const sections: DocumentSection[] = [];\n for (let i = 0; i < count.value; i++) {\n const kbid = decodeString(bytes, offset);\n offset += kbid.bytesRead;\n\n const position = decodeU32(bytes, offset);\n offset += position.bytesRead;\n\n sections.push({\n kbid: kbid.value,\n position: position.value,\n });\n }\n\n return {\n docid: docid.value,\n title: title.value,\n createdAt: createdAt.value,\n docType: docType.value,\n sections,\n };\n}\n", "import { decodeString } from './decode-string.function.ts';\nimport { decodeU32 } from './decode-u32.function.ts';\nimport { decodeU64 } from './decode-u64.function.ts';\nimport type {\n DocumentManifest,\n DocumentSection,\n} from './decode-document-manifest.function.ts';\n\nexport type { DocumentManifest, DocumentSection };\n\n/**\n * Decodes a WASM byte slice into an array of `DocumentManifest` values.\n *\n * The binary format is: u32 count, followed by count \u00D7 DocumentManifest\n * entries. Each entry contains: docid (string), title (string),\n * createdAt (u64), docType (string), section count (u32), then each\n * section's kbid (string) and position (u32).\n *\n * @param bytes - raw bytes returned by `worker_list_docs_by_type`\n * @returns decoded array of document manifests, empty when count is zero\n */\nexport function decodeDocumentManifestList(\n bytes: Uint8Array,\n): DocumentManifest[] {\n let offset = 0;\n const count = decodeU32(bytes, offset);\n offset += count.bytesRead;\n\n const manifests: DocumentManifest[] = [];\n for (let i = 0; i < count.value; i++) {\n const docid = decodeString(bytes, offset);\n offset += docid.bytesRead;\n\n const title = decodeString(bytes, offset);\n offset += title.bytesRead;\n\n const createdAt = decodeU64(bytes, offset);\n offset += createdAt.bytesRead;\n\n const docType = decodeString(bytes, offset);\n offset += docType.bytesRead;\n\n const secCount = decodeU32(bytes, offset);\n offset += secCount.bytesRead;\n\n const sections: DocumentSection[] = [];\n for (let j = 0; j < secCount.value; j++) {\n const kbid = decodeString(bytes, offset);\n offset += kbid.bytesRead;\n\n const position = decodeU32(bytes, offset);\n offset += position.bytesRead;\n\n sections.push({\n kbid: kbid.value,\n position: position.value,\n });\n }\n\n manifests.push({\n docid: docid.value,\n title: title.value,\n createdAt: createdAt.value,\n docType: docType.value,\n sections,\n });\n }\n\n return manifests;\n}\n", "import { decodeString } from './decode-string.function.ts';\nimport { decodeU64 } from './decode-u64.function.ts';\n\nexport interface ComposeOutput {\n markdown: string;\n totalChars: bigint;\n}\n\nexport function decodeComposeOutput(bytes: Uint8Array): ComposeOutput {\n const md = decodeString(bytes, 0);\n const totalChars = decodeU64(bytes, md.bytesRead);\n return {\n markdown: md.value,\n totalChars: totalChars.value,\n };\n}\n", "export function decodeKeyValueText(\n text: string,\n): Record<string, string> {\n const result: Record<string, string> = {};\n for (const line of text.split('\\n')) {\n const idx = line.indexOf('=');\n if (idx < 0) continue;\n const key = line.slice(0, idx);\n const value = line.slice(idx + 1);\n if (key) {\n result[key] = value;\n }\n }\n return result;\n}\n", "export function decodeRemoveFlag(bytes: Uint8Array): boolean {\n return bytes.length > 0 && bytes[0] === 0x01;\n}\n", "import { resolve } from 'node:path';\n\n/** Result of the worker entry point. */\nexport interface WorkerResult {\n /** Error message (if any). */\n error?: string;\n /** Process exit code. `0` means success. */\n exitCode: number;\n}\n\n/**\n * Injectable dependencies for the worker entry point.\n */\nexport interface WorkerDeps {\n existsSync: (path: string) => boolean;\n startDaemon: (\n contextPath: string,\n wasmDir?: string,\n ) => Promise<void>;\n wasmDir?: string;\n}\n\n/**\n * Worker daemon entry point extracted from `src/worker.ts`.\n *\n * Validates the context path argument, resolves it to an\n * absolute path, checks existence, and delegates to\n * `startDaemon`.\n *\n * @param argv - raw arguments (expects `[contextPath]`)\n * @param deps - injectable dependencies\n */\nexport async function runWorker(\n argv: string[],\n deps: WorkerDeps,\n): Promise<WorkerResult> {\n const contextPath = argv[0];\n\n if (!contextPath) {\n return {\n error: 'usage: kbdb-worker <context-path>',\n exitCode: 1,\n };\n }\n\n const resolved = resolve(contextPath);\n\n if (!deps.existsSync(resolved)) {\n return {\n error: `error: path not found: ${resolved}`,\n exitCode: 1,\n };\n }\n\n await deps.startDaemon(resolved, deps.wasmDir);\n return { exitCode: 0 };\n}\n"],
5
+ "mappings": ";;;;;;;;;;;AAAA,SAAS,cAAAA,mBAAkB;;;ACA3B,SAAS,oBAAoB;AAC7B,SAAS,YAAY;;;ACAd,IAAM,qBAAqB;AAG3B,IAAM,sBAAsB;AAM5B,IAAM,qBAAqB;AAM3B,IAAM,sBAAsB;AAG5B,IAAM,uBAAuB;AAS7B,IAAM,oBAAoB;;;ADP1B,SAAS,WAAW,aAAmC;AAC3D,QAAM,aAAa,KAAK,aAAa,oBAAoB;AACzD,MAAI;AACD,UAAM,OAAO,aAAa,YAAY,OAAO;AAC7C,WAAO,gBAAgB,MAAM,WAAW;AAAA,EAC3C,QAAQ;AACL,WAAO;AAAA,MACJ;AAAA,MACA,WAAW;AAAA,MACX,YAAY;AAAA,MACZ,WAAW;AAAA,MACX,WAAW;AAAA,IACd;AAAA,EACH;AACH;AAEA,SAAS,gBACN,MACA,aACa;AACb,QAAM,SAAuB;AAAA,IAC1B;AAAA,IACA,WAAW;AAAA,IACX,YAAY;AAAA,IACZ,WAAW;AAAA,IACX,WAAW;AAAA,EACd;AAEA,QAAM,SAAS,EAAE,GAAG,OAAO;AAE3B,aAAW,QAAQ,KAAK,MAAM,IAAI,GAAG;AAClC,UAAM,UAAU,KAAK,KAAK;AAC1B,QAAI,QAAQ,WAAW,GAAG,KAAK,CAAC,QAAQ,SAAS,GAAG,GAAG;AACpD;AAAA,IACH;AACA,UAAM,QAAQ,QAAQ,QAAQ,GAAG;AACjC,UAAM,MAAM,QAAQ,MAAM,GAAG,KAAK,EAAE,KAAK;AACzC,UAAM,QAAQ,QAAQ,MAAM,QAAQ,CAA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eAAe,YAAY,KAAK,YAAY,OAAO;AACnE,IAAM,UAAU,eAAe,QAAQ,SAAS;AAEhD,eAAe,OAAsB;AAClC,QAAM,SAAS,MAAM,UAAU,QAAQ,GAAG;AAAA,IACvC,YAAAC;AAAA,IACA;AAAA,IACA;AAAA,EACH,CAAC;AACD,MAAI,OAAO,OAAO;AAEf,YAAQ,MAAM,OAAO,KAAK;AAAA,EAC7B;AACA,MAAI,OAAO,aAAa,GAAG;AACxB,YAAQ,WAAW,OAAO;AAAA,EAC7B;AACH;AAEA,KAAK,EAAE,MAAM,CAAC,QAAiB;AAE5B,UAAQ,MAAM,GAAG;AACjB,UAAQ,WAAW;AACtB,CAAC;",
6
+ "names": ["existsSync", "writeFileSync", "join", "tmpdir", "existsSync", "readFileSync", "writeFileSync", "unlinkSync", "join", "readFileSync", "readFileSync", "join", "wasmDir", "readFileSync", "encoder", "wasmDir", "existsSync", "join", "writeFileSync", "unlinkSync", "readFileSync", "getResultFn", "wasmDir", "join", "tmpdir", "writeFileSync", "existsSync"]
7
7
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dikolab/kbdb",
3
- "version": "0.1.1",
3
+ "version": "0.1.3",
4
4
  "description": "CLI tool and MCP server for a file-based knowledge base database",
5
5
  "publishConfig": {
6
6
  "access": "public"
@@ -0,0 +1,13 @@
1
+ import { join } from 'node:path';
2
+
3
+ export function isRemoteUrl(path: string): boolean {
4
+ return path.startsWith('http://') || path.startsWith('https://');
5
+ }
6
+
7
+ export function joinPath(base: string, ...segments: string[]): string {
8
+ if (isRemoteUrl(base)) {
9
+ const trailing = base.endsWith('/') ? '' : '/';
10
+ return base + trailing + segments.join('/');
11
+ }
12
+ return join(base, ...segments);
13
+ }
@@ -1,5 +1,5 @@
1
- import { join } from 'node:path';
1
+ import { joinPath } from './join-path.function.ts';
2
2
 
3
3
  export function resolveWasmDir(scriptDir: string): string {
4
- return join(scriptDir, 'wasm');
4
+ return joinPath(scriptDir, 'wasm');
5
5
  }
@@ -1,4 +1,4 @@
1
- import { join } from 'node:path';
1
+ import { joinPath } from './join-path.function.ts';
2
2
 
3
3
  import type { Runtime } from '../../runtime/typings/runtime.ts';
4
4
 
@@ -7,7 +7,7 @@ export function resolveWorkerScript(
7
7
  runtime: Runtime,
8
8
  ): string {
9
9
  if (runtime === 'deno') {
10
- return join(scriptDir, 'worker.ts');
10
+ return joinPath(scriptDir, 'worker.ts');
11
11
  }
12
- return join(scriptDir, 'kbdb-worker.cjs');
12
+ return joinPath(scriptDir, 'kbdb-worker.cjs');
13
13
  }