dsh-agent-memory-hub 0.1.5 → 0.1.6
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.
- package/dist/index.js +8 -0
- package/dist/index.js.map +2 -2
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1693,6 +1693,14 @@ function startServer(state, options) {
|
|
|
1693
1693
|
async function route(state, req, res) {
|
|
1694
1694
|
const url = new URL(req.url ?? "/", `http://${req.headers.host ?? "localhost"}`);
|
|
1695
1695
|
const path = url.pathname;
|
|
1696
|
+
res.setHeader("Access-Control-Allow-Origin", "*");
|
|
1697
|
+
res.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
|
|
1698
|
+
res.setHeader("Access-Control-Allow-Headers", "content-type");
|
|
1699
|
+
if (req.method === "OPTIONS") {
|
|
1700
|
+
res.writeHead(204);
|
|
1701
|
+
res.end();
|
|
1702
|
+
return;
|
|
1703
|
+
}
|
|
1696
1704
|
if (req.method === "GET" && (path === "/" || path === "/panel")) {
|
|
1697
1705
|
res.writeHead(200, { "content-type": "text/html; charset=utf-8" });
|
|
1698
1706
|
res.end(PANEL_HTML);
|
package/dist/index.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/index.ts", "../../../src/core/errors.ts", "../../../src/core/time.ts", "../../../src/core/ids.ts", "../../../src/core/hub.ts", "../../../src/core/atomic.ts", "../../../src/core/ledger.ts", "../../../src/core/store.ts", "../../../src/core/frontmatter.ts", "../../../src/core/registry.ts", "../../../src/core/lock.ts", "../../../src/core/search.ts", "../../../src/core/inject.ts", "../../../src/core/journal.ts", "../../../src/core/transcript.ts", "../../../src/transport/http.ts", "../../../src/transport/panel.ts", "../../../src/transport/server.ts", "../../../src/transport/autocommit.ts", "../src/host-types.ts", "../src/tools.ts"],
|
|
4
|
-
"sourcesContent": ["import * as hub from 'agent-memory-hub'\nimport { resolveHubRoot, type AdapterConfig, type HostContext, type ToolDefinition } from './host-types.js'\nimport { createTools, createHubContext } from './tools.js'\n\n/**\n * DSH thin adapter for agent-memory-hub (ADR-0001: no host glue in core \u2014\n * the host side is this package). Registers memory_* tools on the cordis\n * tools service; initialization is async-safe: registration is synchronous,\n * tool bodies handle hub errors and return structured payloads, so a failed\n * mount never throws into the host loader.\n *\n * Also embeds the panel HTTP surface in-process (127.0.0.1:7777, ADR-0012)\n * so the DSH sidebar panel always has its audited data source \u2014 no manual\n * `memhub serve` step. Port conflicts (a user-started serve, another session)\n * are tolerated: we skip and the existing server keeps serving.\n */\n\nexport const name = 'agent-memory-hub-dsh'\nexport const inject = ['tools']\n\nconst PANEL_PORT = 7777\n\nfunction startPanelServer(ctx: HostContext, root: string): void {\n try {\n const state = hub.createApiState(root)\n const server = hub.startServer(state, { port: PANEL_PORT, host: '127.0.0.1' })\n server.on('error', (error: NodeJS.ErrnoException) => {\n if (error.code === 'EADDRINUSE') {\n ctx.logger?.info(`agent-memory-hub-dsh: panel port ${PANEL_PORT} already serving (manual serve or another session) \u2014 reusing it`)\n return\n }\n ctx.logger?.warn(`agent-memory-hub-dsh: panel server error: ${error.message}`)\n })\n ctx.logger?.info(`agent-memory-hub-dsh: panel console serving at http://127.0.0.1:${PANEL_PORT}/ (hub: ${root})`)\n ctx.effect?.(() => () => {\n try {\n server.close()\n } catch {\n // already closed\n }\n }, `${name}-panel`)\n } catch (error) {\n ctx.logger?.warn(`agent-memory-hub-dsh: panel server failed to start: ${error instanceof Error ? error.message : String(error)}`)\n }\n}\n\nexport function apply(ctx: HostContext, config?: AdapterConfig): void {\n const root = resolveHubRoot(config)\n if (!hub.isHubInitialized(root)) {\n ctx.logger?.warn(\n `agent-memory-hub-dsh: hub not initialized at ${root} \u2014 memory tools disabled until \\`memhub init --root ${root}\\` runs`,\n )\n return\n }\n startPanelServer(ctx, root)\n const hubCtx = createHubContext(config)\n const conflict = config?.toolConflict ?? 'skip'\n const disposers: Array<() => void> = []\n for (const definition of createTools(hubCtx)) {\n const { run, ...rest } = definition\n let toolName = rest.name\n const existing = ctx.tools.get(toolName)\n if (existing !== undefined) {\n if (conflict === 'skip') {\n ctx.logger?.warn(\n `agent-memory-hub-dsh: tool ${toolName} already registered by host or another plugin; skipping (toolConflict: skip)`,\n )\n continue\n }\n toolName = `${toolName}__amh`\n ctx.logger?.warn(`agent-memory-hub-dsh: tool name collision \u2014 registered as ${toolName} (toolConflict: suffix)`)\n }\n const tool: ToolDefinition = {\n ...rest,\n name: toolName,\n execute: (args) => run(args),\n }\n disposers.push(ctx.tools.register(tool))\n }\n ctx.logger?.info(`agent-memory-hub-dsh: ${disposers.length} memory tools registered (hub: ${root})`)\n ctx.effect?.(() => () => {\n for (const dispose of disposers) dispose()\n }, name)\n}\n", "/** Error codes shared across core and transport. Transport translates these to\n * protocol-specific shapes; the codes themselves are part of the contract. */\nexport const ErrorCode = {\n E_HUB_NOT_INITIALIZED: 'E_HUB_NOT_INITIALIZED',\n E_NOT_FOUND: 'E_NOT_FOUND',\n E_VALIDATION: 'E_VALIDATION',\n E_CONFLICT: 'E_CONFLICT',\n E_LOCK_HELD: 'E_LOCK_HELD',\n E_APPROVAL_REQUIRED: 'E_APPROVAL_REQUIRED',\n E_READONLY: 'E_READONLY',\n} as const\n\nexport type ErrorCodeValue = (typeof ErrorCode)[keyof typeof ErrorCode]\n\nexport class HubError extends Error {\n readonly code: ErrorCodeValue\n readonly details?: Record<string, unknown>\n\n constructor(code: ErrorCodeValue, message: string, details?: Record<string, unknown>) {\n super(message)\n this.name = 'HubError'\n this.code = code\n this.details = details\n }\n}\n", "/** ISO-8601 timestamps with local offset, matching the predecessor's format\n * (e.g. 2026-11-15T16:41:52+08:00). All persisted timestamps use this shape. */\n\nexport function nowIso(): string {\n return new Date().toISOString().replace('Z', offsetString(new Date()))\n}\n\nfunction offsetString(date: Date): string {\n const minutes = -date.getTimezoneOffset()\n const sign = minutes >= 0 ? '+' : '-'\n const abs = Math.abs(minutes)\n const hh = String(Math.floor(abs / 60)).padStart(2, '0')\n const mm = String(abs % 60).padStart(2, '0')\n return `${sign}${hh}:${mm}`\n}\n\n/** Parse an ISO timestamp; returns epoch ms, or null when invalid/missing. */\nexport function parseIso(value: string | undefined): number | null {\n if (value === undefined || value === '') return null\n const ms = Date.parse(value)\n return Number.isNaN(ms) ? null : ms\n}\n", "import { randomUUID } from 'node:crypto'\nimport { ErrorCode, HubError } from './errors.js'\nimport type { KnowledgeType } from './types.js'\n\n/** ID prefixes per knowledge type (shared contract with dsh-memory-hub). */\nconst PREFIX: Record<KnowledgeType, string> = {\n decision: 'DEC',\n constraint: 'CON',\n knowledge: 'KNO',\n 'api-catalog': 'API',\n process: 'PRC',\n 'open-questions': 'OPQ',\n 'runtime-base': 'RTB',\n playbooks: 'PLB',\n assets: 'AST',\n}\n\nconst PENDING_PREFIX = 'PRO'\n\n/** Persisted per-type counters (records/sequences.json). */\nexport interface Sequences {\n [prefix: string]: number\n}\n\nexport function prefixFor(type: KnowledgeType): string {\n return PREFIX[type]\n}\n\n/** Next ID for a knowledge type. Mutates and persists the sequence file. */\nexport function nextKnowledgeId(\n seqDir: string,\n type: KnowledgeType,\n readSequences: (dir: string) => Sequences,\n writeSequences: (dir: string, seq: Sequences) => void,\n): string {\n const prefix = prefixFor(type)\n const seq = readSequences(seqDir)\n const next = (seq[prefix] ?? 0) + 1\n seq[prefix] = next\n writeSequences(seqDir, seq)\n return `${prefix}-${String(next).padStart(6, '0')}`\n}\n\n/** Next pending proposal ID (PRO-\u2026). */\nexport function nextProposalId(\n seqDir: string,\n readSequences: (dir: string) => Sequences,\n writeSequences: (dir: string, seq: Sequences) => void,\n): string {\n const seq = readSequences(seqDir)\n const next = (seq[PENDING_PREFIX] ?? 0) + 1\n seq[PENDING_PREFIX] = next\n writeSequences(seqDir, seq)\n return `${PENDING_PREFIX}-${String(next).padStart(6, '0')}`\n}\n\n/** Fresh fencing token for the writer lock (monotonicity comes from time+random). */\nexport function newLockToken(): string {\n return `lk-${Date.now().toString(36)}-${randomUUID().slice(0, 8)}`\n}\n\nexport function assertNonEmpty(value: string, field: string): string {\n if (value.trim() === '') throw new HubError(ErrorCode.E_VALIDATION, `\\`${field}\\` must not be empty`)\n return value\n}\n", "import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'\nimport { join } from 'node:path'\nimport { atomicWrite } from './atomic.js'\n\n/** Hub directory layout (storage contract). */\nexport const HUB_DIRS = ['knowledge', 'pending', 'history', 'records', 'journal'] as const\nexport const KNOWLEDGE_TYPES_DIR = [\n 'decision',\n 'constraint',\n 'knowledge',\n 'api-catalog',\n 'process',\n 'open-questions',\n 'runtime-base',\n 'playbooks',\n 'assets',\n] as const\nexport const HUB_CONFIG = 'hub.yaml'\nexport const HUB_README = 'MEMORY-HUB.md'\nexport const LEDGER_FILE = 'records/ledger.jsonl'\nexport const SEQUENCES_FILE = 'records/sequences.json'\nexport const LOCK_FILE = '.writer.lock'\n\nexport function isHubInitialized(root: string): boolean {\n return existsSync(join(root, 'knowledge')) && existsSync(join(root, LEDGER_FILE))\n}\n\nexport function knowledgeDir(root: string, type: string): string {\n return join(root, 'knowledge', type)\n}\n\nexport function historyDir(root: string, type: string): string {\n return join(root, 'history', type)\n}\n\nexport function pendingDir(root: string): string {\n return join(root, 'pending')\n}\n\nexport function journalDir(root: string): string {\n return join(root, 'journal')\n}\n\n/**\n * Initialize a hub directory. Idempotent: existing files are never touched\n * (fail-open for re-runs). Generates MEMORY-HUB.md explaining every folder's\n * writer/mutability/deletion semantics \u2014 except when a user README already\n * exists at that name (predecessor rule PRC-000009: never overwrite).\n */\nexport function initHub(root: string): { created: string[]; readme: 'written' | 'skipped-existing' } {\n const created: string[] = []\n for (const dir of HUB_DIRS) {\n const target = join(root, dir)\n if (!existsSync(target)) {\n mkdirSync(target, { recursive: true })\n created.push(dir)\n }\n }\n for (const type of KNOWLEDGE_TYPES_DIR) {\n const target = knowledgeDir(root, type)\n if (!existsSync(target)) mkdirSync(target, { recursive: true })\n }\n const records = join(root, 'records')\n if (!existsSync(join(records, 'sequences.json'))) {\n atomicWrite(join(records, 'sequences.json'), '{}\\n')\n }\n if (!existsSync(join(records, 'ledger.jsonl'))) {\n writeFileSync(join(records, 'ledger.jsonl'), '', 'utf8')\n }\n // Git-when-ready: a .gitignore written at init time so the day the hub is\n // pushed to a remote, derived indexes and machine-local secrets (serve\n // token, lock files) never land in the shared history. Idempotent: an\n // existing .gitignore is never overwritten (predecessor rule PRC-000009).\n if (!existsSync(join(root, '.gitignore'))) {\n atomicWrite(join(root, '.gitignore'), hubGitignoreContent())\n }\n let readme: 'written' | 'skipped-existing' = 'skipped-existing'\n const readmePath = join(root, HUB_README)\n if (!existsSync(readmePath)) {\n atomicWrite(readmePath, hubReadmeContent())\n readme = 'written'\n }\n if (!existsSync(join(root, HUB_CONFIG))) {\n atomicWrite(join(root, HUB_CONFIG), defaultHubConfig())\n }\n return { created, readme }\n}\n\n/** Load and parse hub.yaml (flat `key: value` / one-level sections). */\nexport function readHubConfig(root: string): Record<string, string> {\n const path = join(root, HUB_CONFIG)\n if (!existsSync(path)) return {}\n const raw = readFileSync(path, 'utf8')\n const out: Record<string, string> = {}\n for (const line of raw.split('\\n')) {\n const trimmed = line.trim()\n if (trimmed === '' || trimmed.startsWith('#')) continue\n const colon = trimmed.indexOf(':')\n if (colon === -1) continue\n out[trimmed.slice(0, colon).trim()] = trimmed.slice(colon + 1).trim()\n }\n return out\n}\n\nfunction defaultHubConfig(): string {\n return [\n '# agent-memory-hub configuration (plain text, diff-friendly).',\n '# workspaces auto-register on first use (ADR-0002); domains are optional.',\n 'version: 1',\n '# domains: [] # optional grouping: domainId -> member workspace ids',\n '# --- publish (ADR-0015): where approved entries go. APIs are yours to define.',\n '# publish.adapter: http # POST {entries:[...]} to publish.endpoint',\n '# publish.endpoint: https://memory-hub.example.internal/api/entries',\n '# publish.header.Authorization: Bearer <token>',\n '# publish.adapter: exec # run your own script; stdin = entries JSON',\n '# publish.script: publish-to-memory-hub.mjs',\n '# publish.adapter: none # (default) publishing disabled',\n '',\n ].join('\\n')\n}\n\nfunction hubGitignoreContent(): string {\n return `# agent-memory-hub \u2014 git \u4ED3\u5E93\u89C4\u5212\uFF08init \u65F6\u81EA\u52A8\u751F\u6210\uFF0C\u53EF\u6309\u9700\u8C03\u6574\uFF09\n#\n# \u539F\u5219\uFF1A\u6743\u5A01\u6570\u636E\u5168\u90E8\u63D0\u4EA4\uFF1B\u6D3E\u751F\u7F13\u5B58\u4E0E\u673A\u5668\u672C\u5730\u72B6\u6001\u4E00\u5F8B\u5FFD\u7565\u3002\n\n# \u2500\u2500 \u6D3E\u751F\u7F13\u5B58\uFF1A\u8FD0\u884C\u65F6\u81EA\u52A8\u91CD\u5EFA\uFF0C\u63D0\u4EA4\u53EA\u4F1A\u5236\u9020\u5408\u5E76\u51B2\u7A81 \u2500\u2500\nindex/\n\n# \u2500\u2500 \u673A\u5668\u672C\u5730\u72B6\u6001\uFF1A\u7EDD\u4E0D\u80FD\u8FDB\u5171\u4EAB\u5386\u53F2 \u2500\u2500\nrecords/.writer.lock\nrecords/server.json\nrecords/server-token\n\n# \u2500\u2500 \u5E38\u89C4\u7CFB\u7EDF\u566A\u58F0 \u2500\u2500\n.DS_Store\nThumbs.db\n`\n}\n\nfunction hubReadmeContent(): string {\n return `# MEMORY-HUB \u2014 \u76EE\u5F55\u8BF4\u660E\u4E66\n\n\u672C\u76EE\u5F55\u662F agent-memory-hub \u7684\u4E8B\u5B9E\u6E90\u3002\u6240\u6709\u5185\u5BB9\u90FD\u662F\u7EAF\u6587\u672C\uFF0C\u53EF\u7528 git \u7BA1\u7406\u3002\n\n| \u76EE\u5F55 | \u5185\u5BB9 | \u8C01\u5199 | \u53EF\u6539\u6027 | \u5220\u9664\u540E\u679C |\n| --- | --- | --- | --- | --- |\n| knowledge/ | \u5DF2\u6279\u51C6\u7684\u77E5\u8BC6\uFF08\u6309\u7C7B\u578B\u5206\u76EE\u5F55\uFF09 | \u53EA\u6709\"\u4EBA\u6279\u51C6\"\u8DEF\u5F84\uFF08commit\uFF09 | \u6761\u76EE\u6B63\u6587\u53EF\u7531\u4EBA\u76F4\u63A5\u7F16\u8F91\uFF1B\u5143\u6570\u636E\u6539\u52A8\u8BF7\u8D70\u5DE5\u5177 | \u8BE5\u7C7B\u77E5\u8BC6\u6D88\u5931\uFF1B\u7D22\u5F15\u53EF\u91CD\u5EFA\uFF0C\u6587\u4EF6\u4E0D\u53EF\u6062\u590D |\n| pending/ | \u6A21\u578B\u521B\u5EFA\u7684\u5019\u9009\uFF08PRO-*.md\uFF09 | \u6A21\u578B\uFF08propose\uFF09\u4E0E\u8403\u53D6\u5668 | \u4EBA\u53EF\u7F16\u8F91\u540E\u6279\u51C6\uFF1B\u53EF\u6574\u4F53\u5220\u9664 | \u5019\u9009\u4E22\u5931\uFF0C\u53EF\u91CD\u65B0\u751F\u6210 |\n| history/ | \u6BCF\u6B21\u7248\u672C\u53D8\u66F4\u7684\u539F\u6587\u5FEB\u7167 | commit/update \u81EA\u52A8\u5199 | **\u53EA\u8FFD\u52A0**\uFF0C\u8BF7\u52FF\u6539\u5199 | \u7248\u672C\u8FFD\u6EAF\u80FD\u529B\u4E22\u5931 |\n| records/ | ledger.jsonl\uFF08\u5BA1\u6279\u8D26\u672C\uFF09+ sequences.json\uFF08ID \u5E8F\u5217\uFF09 | \u5DE5\u5177\u81EA\u52A8 | **\u53EA\u8FFD\u52A0**\uFF08ledger\uFF09 | \u5BA1\u8BA1\u94FE\u65AD\u88C2\uFF0C\u6279\u51C6\u5386\u53F2\u4E0D\u53EF\u8BC1 |\n| journal/ | \u60C5\u666F\u5C42\uFF1A\u81EA\u52A8\u6355\u83B7\u7684\u4F1A\u8BDD\u6D41\u6C34 | \u5DE5\u5177\u81EA\u52A8 | \u53EF\u6574\u4F53\u4E22\u5F03 | \u65E0\u5F71\u54CD\uFF08\u53EF\u518D\u751F\u6210\uFF09\uFF0C\u4E0D\u5F71\u54CD knowledge |\n| .writer.lock | \u5199\u9501\u79DF\u7EA6\uFF08\u5FC3\u8DF3\u6587\u4EF6\uFF09 | \u5199\u9501\u81EA\u52A8 | \u52FF\u624B\u6539 | \u79DF\u7EA6\u8D85\u9F84\u81EA\u52A8\u56DE\u6536 |\n\n\u89C4\u5219\uFF1A\u6A21\u578B\u6C38\u8FDC\u4E0D\u80FD\u81EA\u6279\uFF1Bknowledge/ \u7684\u6BCF\u4E00\u6B21\u5199\u5165\u90FD\u5728 records/ledger.jsonl \u6709\u5BF9\u5E94\u8BB0\u5F55\u3002\n`\n}\n", "import { mkdirSync, renameSync, rmSync, writeFileSync } from 'node:fs'\nimport { dirname, join, parse } from 'node:path'\nimport { ErrorCode, HubError } from './errors.js'\n\n/**\n * Atomic write: write to a temp file in the same directory, then rename over\n * the target. Same-directory rename is atomic on NTFS/ext4/APFS. Never write\n * the final path directly (storage contract, rule 1).\n */\nexport function atomicWrite(filePath: string, content: string): void {\n const dir = dirname(filePath)\n mkdirSync(dir, { recursive: true })\n const base = parse(filePath).name\n const tmp = join(dir, `.${base}.${process.pid}.${Date.now()}.tmp`)\n try {\n writeFileSync(tmp, content, 'utf8')\n // Windows rename over an existing file fails; remove first (tiny window,\n // acceptable for a single-writer-locked store).\n try {\n rmSync(filePath, { force: true })\n } catch {\n // target did not exist\n }\n renameSync(tmp, filePath)\n } catch (error) {\n try {\n rmSync(tmp, { force: true })\n } catch {\n // best effort cleanup\n }\n const detail = error instanceof Error ? error.message : String(error)\n throw new HubError(ErrorCode.E_VALIDATION, `atomic write failed for ${filePath}: ${detail}`)\n }\n}\n", "import { existsSync, readFileSync } from 'node:fs'\nimport { join } from 'node:path'\nimport { atomicWrite } from './atomic.js'\nimport { LEDGER_FILE, SEQUENCES_FILE } from './hub.js'\nimport type { Sequences } from './ids.js'\n\n/**\n * Approval ledger \u2014 append-only JSONL. Every write into knowledge/ has a\n * corresponding record here: who, when, on what evidence (invariant 2).\n * Never rewritten, never compacted (storage contract rule 3).\n */\n\nexport type LedgerAction =\n | 'propose'\n | 'approve'\n | 'reject'\n | 'update'\n | 'deprecate'\n | 'delete'\n | 'register-workspace'\n | 'conflict-freeze'\n | 'publish'\n\n/**\n * Event-stream record (the predecessor ledger shape \u2014 type discriminates the\n * event; see docs/04-development/search-replay-2026-11-15.md appendix).\n * knowledge-lifecycle events carry ts/actor/action/id/version convenience\n * fields; harness events (citation.added, approval.missing, proposal.committed\u2026)\n * carry only type + their own payload.\n */\nexport interface LedgerRecord {\n type?: string\n ts?: string\n actor?: string\n action?: LedgerAction\n id?: string\n version?: number\n /** Evidence refs backing the decision (file:/session:/url:/note:). */\n source_refs?: string[]\n note?: string\n [key: string]: unknown\n}\n\nexport function ledgerPath(root: string): string {\n return join(root, LEDGER_FILE)\n}\n\n/** Append one record. The whole file is rewritten atomically (append = read+atomicWrite). */\nexport function appendLedger(path: string, record: LedgerRecord): void {\n const existing = existsSync(path) ? readFileSync(path, 'utf8') : ''\n atomicWrite(path, existing + `${JSON.stringify(record)}\\n`)\n}\n\nexport function readLedger(path: string): LedgerRecord[] {\n if (!existsSync(path)) return []\n return readFileSync(path, 'utf8')\n .split('\\n')\n .filter((line) => line.trim() !== '')\n .map((line) => JSON.parse(line) as LedgerRecord)\n}\n\nexport function readSequences(root: string): Sequences {\n const path = join(root, SEQUENCES_FILE)\n if (!existsSync(path)) return {}\n try {\n return JSON.parse(readFileSync(path, 'utf8')) as Sequences\n } catch {\n return {}\n }\n}\n\nexport function writeSequences(root: string, seq: Sequences): void {\n atomicWrite(join(root, SEQUENCES_FILE), `${JSON.stringify(seq, null, 2)}\\n`)\n}\n", "import { existsSync, readFileSync, rmSync, readdirSync } from 'node:fs'\nimport { join } from 'node:path'\nimport { atomicWrite } from './atomic.js'\nimport { ErrorCode, HubError } from './errors.js'\nimport { historyDir, knowledgeDir, pendingDir } from './hub.js'\nimport { nextKnowledgeId, nextProposalId } from './ids.js'\nimport { parseIso, nowIso } from './time.js'\nimport { parseKnowledgeFile, parseKnowledgeFrontmatter } from './frontmatter.js'\nimport type { LedgerRecord } from './ledger.js'\nimport type {\n KnowledgeFrontmatter,\n KnowledgeScope,\n KnowledgeStatus,\n KnowledgeType,\n} from './types.js'\n\n/**\n * Store: knowledge / pending / history CRUD. All writes are atomic; every\n * knowledge mutation snapshots the previous version into history/ (append-only)\n * and appends a ledger record (caller supplies the ledger callback).\n */\n\nexport interface SaveKnowledgeInput {\n type: KnowledgeType\n title: string\n summary: string\n scope: KnowledgeScope\n tags?: string[]\n body: string\n /** Existing entry id to update; omit to create a new one. */\n id?: string\n /** Expires-at ISO timestamp (aging / validity window). */\n expiresAt?: string\n sourceRefs?: string[]\n actor?: string\n}\n\nexport interface KnowledgeEntry {\n frontmatter: KnowledgeFrontmatter\n body: string\n path: string\n /** Epoch ms when the entry expires (aging), or null. */\n expiresAtMs: number | null\n /** True when status is deprecated or expiresAt has passed (soft-removed). */\n softRemoved: boolean\n}\n\nfunction entryPath(root: string, type: KnowledgeType, id: string): string {\n return join(knowledgeDir(root, type), `${id}.md`)\n}\n\nexport function renderKnowledgeMarkdown(fm: KnowledgeFrontmatter, body: string): string {\n const lines: string[] = ['---']\n lines.push(`id: ${fm.id}`)\n lines.push(`version: ${fm.version}`)\n lines.push(`type: ${fm.type}`)\n lines.push(`status: ${fm.status}`)\n lines.push(`title: ${fm.title}`)\n lines.push(`summary: ${fm.summary}`)\n if (fm.scope.level === 'global') {\n lines.push('scope:')\n lines.push(' level: global')\n } else if (fm.scope.level === 'domain') {\n lines.push('scope:')\n lines.push(' level: domain')\n lines.push(` domainId: ${fm.scope.domainId}`)\n } else {\n lines.push('scope:')\n lines.push(' level: project')\n lines.push(` workspaceId: ${fm.scope.workspaceId}`)\n }\n lines.push(`tags: [${fm.tags.join(', ')}]`)\n if (fm.created !== undefined) lines.push(`created: ${fm.created}`)\n if (fm.updated !== undefined) lines.push(`updated: ${fm.updated}`)\n if (fm.last_verified !== undefined) lines.push(`last_verified: ${fm.last_verified}`)\n for (const [key, value] of Object.entries(fm.extra)) {\n lines.push(`${key}: ${typeof value === 'string' ? value : JSON.stringify(value)}`)\n }\n lines.push('---')\n lines.push('')\n lines.push(body.trimEnd())\n lines.push('')\n return lines.join('\\n')\n}\n\n/** Read one knowledge entry by id (searches all type dirs). */\nexport function getEntry(root: string, id: string): KnowledgeEntry {\n for (const type of readdirSync(join(root, 'knowledge'))) {\n const path = entryPath(root, type as KnowledgeType, id)\n if (!existsSync(path)) continue\n const raw = readFileSync(path, 'utf8')\n const parsed = parseKnowledgeFile(raw)\n return toEntry(parsed.frontmatter, parsed.body, path)\n }\n throw new HubError(ErrorCode.E_NOT_FOUND, `knowledge entry not found: ${id}`, { id })\n}\n\nfunction toEntry(fm: KnowledgeFrontmatter, body: string, path: string): KnowledgeEntry {\n const expiresRaw = fm.extra['expires_at']\n const expiresAtMs = parseIso(typeof expiresRaw === 'string' ? expiresRaw : undefined)\n return {\n frontmatter: fm,\n body,\n path,\n expiresAtMs,\n softRemoved: fm.status === 'deprecated' || (expiresAtMs !== null && expiresAtMs <= Date.now()),\n }\n}\n\n/** List all entries; soft-removed included unless includeSoftRemoved=false. */\nexport function listEntries(root: string, options?: { includeSoftRemoved?: boolean }): KnowledgeEntry[] {\n const out: KnowledgeEntry[] = []\n const typesRoot = join(root, 'knowledge')\n if (!existsSync(typesRoot)) return out\n for (const type of readdirSync(typesRoot)) {\n const dir = knowledgeDir(root, type)\n for (const file of readdirSync(dir)) {\n if (!file.endsWith('.md')) continue\n const path = join(dir, file)\n try {\n const parsed = parseKnowledgeFile(readFileSync(path, 'utf8'))\n const entry = toEntry(parsed.frontmatter, parsed.body, path)\n if (options?.includeSoftRemoved !== true && entry.softRemoved) continue\n out.push(entry)\n } catch {\n // Unreadable entry: skip, never break listing (index rebuildable).\n }\n }\n }\n return out\n}\n\n/** Title-level conflict detection: same title among accepted entries. */\nexport function findTitleConflict(root: string, title: string, excludeId?: string): KnowledgeEntry | null {\n const hit = listEntries(root).find(\n (entry) => entry.frontmatter.title === title && entry.frontmatter.id !== excludeId,\n )\n return hit ?? null\n}\n\n/**\n * Create or update a knowledge entry. Creates are caller-authorized (the human\n * approval already happened \u2014 this function is the post-approval write path).\n * Updates snapshot the previous version into history/ first.\n */\nexport function commitKnowledge(\n root: string,\n input: SaveKnowledgeInput,\n helpers: {\n nowIsoValue?: string\n readSequences: (root: string) => Record<string, number>\n writeSequences: (root: string, seq: Record<string, number>) => void\n appendLedger: (root: string, record: LedgerRecord) => void\n },\n): { id: string; version: number; path: string } {\n const ts = helpers.nowIsoValue ?? nowIso()\n if (input.id === undefined) {\n // create\n const conflict = findTitleConflict(root, input.title)\n if (conflict !== null) {\n throw new HubError(ErrorCode.E_CONFLICT, `an accepted entry with the same title exists: ${conflict.frontmatter.id}`, {\n existingId: conflict.frontmatter.id,\n existingTitle: conflict.frontmatter.title,\n })\n }\n const id = nextKnowledgeId(root, input.type, helpers.readSequences, helpers.writeSequences)\n const fm: KnowledgeFrontmatter = {\n id,\n version: 1,\n type: input.type,\n status: 'accepted',\n title: input.title,\n summary: input.summary,\n scope: input.scope,\n tags: input.tags ?? [],\n created: ts,\n updated: ts,\n last_verified: ts,\n extra: input.expiresAt !== undefined ? { expires_at: input.expiresAt } : {},\n }\n const path = entryPath(root, input.type, id)\n atomicWrite(path, renderKnowledgeMarkdown(fm, input.body))\n helpers.appendLedger(root, {\n ts,\n actor: input.actor ?? 'human',\n action: 'approve',\n id,\n version: 1,\n source_refs: input.sourceRefs,\n })\n return { id, version: 1, path }\n }\n // Explicit id: ADR-0012 cross-hub upsert. When the id does not exist\n // locally yet, it is created AS that id (keeps hub-to-hub identity\n // stable); otherwise it is the usual version upgrade.\n let previous: { frontmatter: KnowledgeFrontmatter; path: string; body: string }\n try {\n const found = getEntry(root, input.id)\n previous = { frontmatter: found.frontmatter, path: found.path, body: found.body }\n } catch {\n const fm: KnowledgeFrontmatter = {\n id: input.id,\n version: 1,\n type: input.type,\n status: 'accepted',\n title: input.title,\n summary: input.summary,\n scope: input.scope,\n tags: input.tags ?? [],\n created: ts,\n updated: ts,\n last_verified: ts,\n extra: input.expiresAt !== undefined ? { expires_at: input.expiresAt } : {},\n }\n const path = entryPath(root, input.type, input.id)\n atomicWrite(path, renderKnowledgeMarkdown(fm, input.body))\n helpers.appendLedger(root, {\n ts,\n actor: input.actor ?? 'human',\n action: 'approve',\n id: input.id,\n version: 1,\n source_refs: input.sourceRefs,\n })\n return { id: input.id, version: 1, path }\n }\n const prevFm = previous.frontmatter\n if (prevFm.type !== input.type) {\n throw new HubError(ErrorCode.E_VALIDATION, `type mismatch for ${input.id}: ${prevFm.type} \u2260 ${input.type}`)\n }\n const historyPath = join(historyDir(root, prevFm.type), `${prevFm.id}@v${prevFm.version}.md`)\n atomicWrite(historyPath, readFileSync(previous.path, 'utf8'))\n const fm: KnowledgeFrontmatter = {\n ...prevFm,\n version: prevFm.version + 1,\n title: input.title,\n summary: input.summary,\n tags: input.tags ?? prevFm.tags,\n updated: ts,\n last_verified: ts,\n extra: input.expiresAt !== undefined ? { ...prevFm.extra, expires_at: input.expiresAt } : prevFm.extra,\n }\n atomicWrite(previous.path, renderKnowledgeMarkdown(fm, input.body))\n helpers.appendLedger(root, {\n ts,\n actor: input.actor ?? 'human',\n action: 'update',\n id: prevFm.id,\n version: fm.version,\n source_refs: input.sourceRefs,\n })\n return { id: prevFm.id, version: fm.version, path: previous.path }\n}\n\n/** Soft-remove: status=deprecated + ledger record. Physical delete is explicit-only. */\nexport function deprecateEntry(\n root: string,\n id: string,\n reason: string,\n helpers: {\n nowIsoValue?: string\n appendLedger: (root: string, record: LedgerRecord) => void\n },\n): void {\n const entry = getEntry(root, id)\n const ts = helpers.nowIsoValue ?? nowIso()\n const fm: KnowledgeFrontmatter = { ...entry.frontmatter, status: 'deprecated', updated: ts }\n atomicWrite(entry.path, renderKnowledgeMarkdown(fm, entry.body))\n helpers.appendLedger(root, {\n ts,\n actor: 'human',\n action: 'deprecate',\n id,\n version: entry.frontmatter.version,\n note: reason,\n })\n}\n\n/** Hard delete (GDPR path): explicit caller authorization required; ledger first, then unlink. */\nexport function hardDeleteEntry(\n root: string,\n id: string,\n reason: string,\n helpers: {\n nowIsoValue?: string\n appendLedger: (root: string, record: LedgerRecord) => void\n },\n): void {\n const entry = getEntry(root, id)\n const ts = helpers.nowIsoValue ?? nowIso()\n helpers.appendLedger(root, {\n ts,\n actor: 'human',\n action: 'delete',\n id,\n version: entry.frontmatter.version,\n note: reason,\n })\n rmSync(entry.path, { force: true })\n}\n\n/** Create a pending candidate (models may do this; humans approve via commitKnowledge).\n * `supersedes` names an existing entry this proposal re-extracts: approving it\n * bumps that entry's version instead of creating a duplicate. */\nexport function createProposal(\n root: string,\n input: Omit<SaveKnowledgeInput, 'id'> & { sourceRefs: string[]; supersedes?: string[]; origin?: string; originId?: string },\n helpers: {\n nowIsoValue?: string\n readSequences: (root: string) => Record<string, number>\n writeSequences: (root: string, seq: Record<string, number>) => void\n appendLedger: (root: string, record: LedgerRecord) => void\n },\n): { id: string; path: string } {\n const ts = helpers.nowIsoValue ?? nowIso()\n const proposalId = nextProposalId(root, helpers.readSequences, helpers.writeSequences)\n const fm: KnowledgeFrontmatter = {\n id: proposalId,\n version: 1,\n type: input.type,\n status: 'candidate',\n title: input.title,\n summary: input.summary,\n scope: input.scope,\n tags: input.tags ?? [],\n created: ts,\n updated: ts,\n extra: {\n source_refs: input.sourceRefs.join(' '),\n ...(input.supersedes !== undefined && input.supersedes.length > 0 ? { supersedes: input.supersedes.join(' ') } : {}),\n ...(input.origin !== undefined ? { origin: input.origin } : {}),\n ...(input.originId !== undefined ? { origin_id: input.originId } : {}),\n },\n }\n const path = join(pendingDir(root), `${proposalId}.md`)\n atomicWrite(path, renderKnowledgeMarkdown(fm, input.body))\n helpers.appendLedger(root, {\n ts,\n actor: input.actor ?? 'model',\n action: 'propose',\n id: proposalId,\n source_refs: input.sourceRefs,\n ...(input.supersedes !== undefined && input.supersedes.length > 0 ? { supersedes: input.supersedes } : {}),\n })\n return { id: proposalId, path }\n}\n\n/** List pending candidates. */\nexport function listProposals(root: string): Array<{ id: string; frontmatter: KnowledgeFrontmatter; path: string }> {\n const dir = pendingDir(root)\n if (!existsSync(dir)) return []\n const out: Array<{ id: string; frontmatter: KnowledgeFrontmatter; path: string }> = []\n for (const file of readdirSync(dir)) {\n if (!file.endsWith('.md')) continue\n const path = join(dir, file)\n try {\n const fm = parseKnowledgeFrontmatter(readFileSync(path, 'utf8'), { context: 'proposal' })\n out.push({ id: fm.id, frontmatter: fm, path })\n } catch {\n // skip unreadable candidate\n }\n }\n return out\n}\n\n/** All statuses the store understands. */\nexport const STATUSES: readonly KnowledgeStatus[] = ['candidate', 'accepted', 'rejected', 'superseded', 'deprecated']\n", "import type {\n KnowledgeFrontmatter,\n KnowledgeScope,\n KnowledgeStatus,\n KnowledgeType,\n} from './types.js'\n\n/**\n * Minimal zero-dependency YAML frontmatter parser for the hub-directory\n * knowledge format. This is a contract implementation: it must parse exactly\n * what dsh-memory-hub writes (single-level scalars, inline arrays, and the\n * nested `scope` object), and preserve unknown keys verbatim.\n *\n * Deliberately NOT a general YAML parser \u2014 see invariant 3 (plain text) and\n * principle 6 (zero dependencies). The contract tests in tests/format.test.ts\n * lock the supported surface; extend the parser only together with those tests.\n */\n\nconst KNOWLEDGE_TYPES: readonly KnowledgeType[] = [\n 'decision',\n 'constraint',\n 'knowledge',\n 'api-catalog',\n 'process',\n 'open-questions',\n 'runtime-base',\n 'playbooks',\n 'assets',\n]\n\nconst KNOWLEDGE_STATUSES: readonly KnowledgeStatus[] = [\n 'candidate',\n 'accepted',\n 'rejected',\n 'superseded',\n 'deprecated',\n]\n\nconst FENCED_DELIMITER = '---'\n\n/**\n * Extract the leading frontmatter block (between the first two `---` lines).\n * Returns null when the file does not start with a frontmatter block.\n */\nexport function splitFrontmatter(raw: string): { yaml: string; body: string } | null {\n if (!raw.startsWith(FENCED_DELIMITER)) return null\n const firstNewline = raw.indexOf('\\n')\n if (firstNewline === -1) return null\n const opener = raw.slice(0, firstNewline).trim()\n if (opener !== FENCED_DELIMITER) return null\n const rest = raw.slice(firstNewline + 1)\n const closing = findClosingLine(rest)\n if (closing === -1) return null\n const yaml = rest.slice(0, closing)\n const body = rest.slice(closing + FENCED_DELIMITER.length).replace(/^\\n/, '')\n return { yaml, body: body.trim() }\n}\n\nfunction findClosingLine(text: string): number {\n let offset = 0\n for (const line of text.split('\\n')) {\n if (line.trim() === FENCED_DELIMITER) return offset\n offset += line.length + 1\n }\n return -1\n}\n\n/** Parse one scalar value: quoted/unquoted string, number, boolean. */\nfunction parseScalar(value: string): string | number | boolean {\n const trimmed = value.trim()\n if (\n (trimmed.startsWith('\"') && trimmed.endsWith('\"') && trimmed.length >= 2) ||\n (trimmed.startsWith(\"'\") && trimmed.endsWith(\"'\") && trimmed.length >= 2)\n ) {\n return trimmed.slice(1, -1)\n }\n if (trimmed === 'true') return true\n if (trimmed === 'false') return false\n const num = Number(trimmed)\n if (trimmed !== '' && Number.isFinite(num) && /^-?\\d+(\\.\\d+)?$/.test(trimmed)) return num\n return trimmed\n}\n\n/** Parse an inline array: `[a, b, c]` or an empty `[]`. */\nfunction parseInlineArray(value: string): string[] {\n const inner = value.trim().slice(1, -1).trim()\n if (inner === '') return []\n return inner.split(',').map((item) => String(parseScalar(item)))\n}\n\nfunction parseScope(lines: string[], start: number): { scope: KnowledgeScope; next: number } {\n // Nested object under `scope:` \u2014 exactly two indented keys in the contract:\n // level plus domainId|workspaceId.\n const scopeLines: string[] = []\n let index = start\n while (index < lines.length) {\n const line = lines[index]\n if (line === undefined) break\n if (line.trim() === '' || /^\\S/.test(line)) break\n scopeLines.push(line.trim())\n index += 1\n }\n const entries = new Map<string, string>()\n for (const line of scopeLines) {\n const colon = line.indexOf(':')\n if (colon === -1) continue\n entries.set(line.slice(0, colon).trim(), line.slice(colon + 1).trim())\n }\n const level = entries.get('level')\n let scope: KnowledgeScope = { level: 'global' }\n if (level === 'domain' && entries.get('domainId')) {\n scope = { level: 'domain', domainId: entries.get('domainId') as string }\n } else if (level === 'project' && entries.get('workspaceId')) {\n scope = { level: 'project', workspaceId: entries.get('workspaceId') as string }\n }\n return { scope, next: index }\n}\n\n/**\n * Parse a knowledge file's frontmatter into the contract type.\n * Throws with a descriptive message on contract violations (id/type/status\n * missing or invalid) \u2014 the caller decides how to surface the error.\n *\n * `context: 'proposal'` relaxes the contract for pending-proposal files:\n * predecessor-era proposals carry `status: pending` and no version (assigned\n * at commit time), both of which are legacy aliases mapped here.\n */\nexport function parseKnowledgeFrontmatter(\n raw: string,\n options?: { context?: 'entry' | 'proposal' },\n): KnowledgeFrontmatter {\n const split = splitFrontmatter(raw)\n if (split === null) {\n throw new Error('knowledge file must start with a `---` frontmatter block')\n }\n const lines = split.yaml.split('\\n')\n const scalars = new Map<string, string | number | boolean>()\n const extra: Record<string, unknown> = {}\n let scope: KnowledgeScope = { level: 'global' }\n let index = 0\n while (index < lines.length) {\n const line = lines[index]\n if (line === undefined || line.trim() === '' || line.trim().startsWith('#')) {\n index += 1\n continue\n }\n if (/^\\S/.test(line)) {\n const colon = line.indexOf(':')\n if (colon === -1) {\n index += 1\n continue\n }\n const key = line.slice(0, colon).trim()\n const value = line.slice(colon + 1).trim()\n if (key === 'scope') {\n if (value === '') {\n const parsed = parseScope(lines, index + 1)\n scope = parsed.scope\n index = parsed.next\n continue\n }\n scope = parseInlineArrayOrScalarAsScope(value)\n index += 1\n continue\n }\n if (key === 'tags' || key === 'source_refs') {\n if (value === '') {\n // Legacy block-style list: `key:` followed by indented `- item` lines.\n const items: string[] = []\n let cursor = index + 1\n while (cursor < lines.length) {\n const item = lines[cursor]\n if (item === undefined || !/^\\s+-\\s/.test(item)) break\n items.push(item.replace(/^\\s+-\\s*/, '').trim())\n cursor += 1\n }\n if (items.length > 0) {\n if (key === 'tags') {\n // Re-encode into the inline `[a, b]` convention parseInlineArray expects.\n scalars.set('tags', `[${items.join(', ')}]`)\n } else {\n // Match the renderer's single-line convention (join with spaces).\n const joined = items.join(' ')\n scalars.set('source_refs', joined)\n extra['source_refs'] = joined\n }\n index = cursor\n continue\n }\n }\n const parsedValue = value === '[]' ? '[]' : parseScalar(value)\n scalars.set(key, parsedValue)\n if (key === 'source_refs') extra['source_refs'] = parsedValue\n index += 1\n continue\n }\n const parsed = parseScalar(value)\n scalars.set(key, parsed)\n extra[key] = parsed\n index += 1\n continue\n }\n index += 1\n }\n\n const id = scalars.get('id')\n if (typeof id !== 'string' || id === '') throw new Error('frontmatter missing `id`')\n const type = scalars.get('type')\n if (typeof type !== 'string' || !KNOWLEDGE_TYPES.includes(type as KnowledgeType)) {\n throw new Error(`frontmatter has invalid \\`type\\`: ${String(type)}`)\n }\n const rawStatus = scalars.get('status')\n // Legacy alias: predecessor-era pending proposals carry `status: pending` \u2014\n // the same concept as the new `candidate` status.\n const status = rawStatus === 'pending' ? 'candidate' : rawStatus\n if (typeof status !== 'string' || !KNOWLEDGE_STATUSES.includes(status as KnowledgeStatus)) {\n throw new Error(`frontmatter has invalid \\`status\\`: ${String(status)}`)\n }\n const versionRaw = scalars.get('version')\n // Proposal context: predecessor-era pending files carry no version \u2014 the\n // version is assigned at commit time, so default to 1.\n const version =\n typeof versionRaw === 'number'\n ? versionRaw\n : options?.context === 'proposal'\n ? 1\n : (undefined as unknown as number)\n if (typeof version !== 'number') throw new Error('frontmatter missing numeric `version`')\n const title = scalars.get('title')\n if (typeof title !== 'string' || title === '') throw new Error('frontmatter missing `title`')\n const summary = scalars.get('summary')\n if (typeof summary !== 'string') throw new Error('frontmatter missing `summary`')\n const tagsRaw = scalars.get('tags')\n const tags = typeof tagsRaw === 'string' && tagsRaw !== '[]'\n ? parseInlineArray(tagsRaw)\n : typeof tagsRaw === 'string'\n ? []\n : []\n\n // Contract keys are hoisted into their typed fields; unknown keys stay in extra.\n for (const contractKey of [\n 'id',\n 'version',\n 'type',\n 'status',\n 'title',\n 'summary',\n 'created',\n 'updated',\n 'last_verified',\n ]) {\n delete extra[contractKey]\n }\n\n return {\n id,\n version,\n type: type as KnowledgeType,\n status: status as KnowledgeStatus,\n title,\n summary,\n scope,\n tags,\n // Optional keys are omitted (never `undefined`) so parsed frontmatter is\n // lossless-JSON safe for host tool outputs, even on legacy entries that\n // predate these fields (old format kept timestamps in extra.*_at).\n ...(asOptionalString(scalars.get('created')) !== undefined\n ? { created: asOptionalString(scalars.get('created')) }\n : {}),\n ...(asOptionalString(scalars.get('updated')) !== undefined\n ? { updated: asOptionalString(scalars.get('updated')) }\n : {}),\n ...(asOptionalString(scalars.get('last_verified')) !== undefined\n ? { last_verified: asOptionalString(scalars.get('last_verified')) }\n : {}),\n extra,\n }\n}\n\nfunction asOptionalString(value: string | number | boolean | undefined): string | undefined {\n return typeof value === 'string' && value !== '' ? value : undefined\n}\n\nfunction parseInlineArrayOrScalarAsScope(value: string): KnowledgeScope {\n // Legacy bare shorthand: `scope: project:<id>` / `scope: domain:<id>` / `scope: global`.\n const bare = /^(global|domain:([\\w.-]+)|project:([\\w.-]+))$/.exec(value)\n if (bare !== null) {\n if (bare[1] === 'global') return { level: 'global' }\n if (bare[2] !== undefined) return { level: 'domain', domainId: bare[2] }\n if (bare[3] !== undefined) return { level: 'project', workspaceId: bare[3] }\n }\n // Accept `{level: global}` style inline maps for the global case only.\n if (/level:\\s*global/.test(value)) return { level: 'global' }\n if (/level:\\s*domain/.test(value)) {\n const domainId = /domainId:\\s*([\\w.-]+)/.exec(value)?.[1]\n if (domainId) return { level: 'domain', domainId }\n }\n if (/level:\\s*project/.test(value)) {\n const workspaceId = /workspaceId:\\s*([\\w.-]+)/.exec(value)?.[1]\n if (workspaceId) return { level: 'project', workspaceId }\n }\n return { level: 'global' }\n}\n\n/** Parse a full knowledge file (frontmatter + body). */\nexport function parseKnowledgeFile(raw: string): { frontmatter: KnowledgeFrontmatter; body: string } {\n const split = splitFrontmatter(raw)\n if (split === null) throw new Error('knowledge file must start with a `---` frontmatter block')\n return { frontmatter: parseKnowledgeFrontmatter(raw), body: split.body }\n}\n", "import { execFileSync } from 'node:child_process'\nimport { basename, isAbsolute, resolve } from 'node:path'\nimport type { KnowledgeScope } from './types.js'\n\n/**\n * Workspace identity resolution (ADR-0002, zero-config):\n * 1. explicit --workspace argument (human-specified, highest priority)\n * 2. git origin remote URL (stable across subdirs & worktrees)\n * 3. canonical project directory (git root, else cwd)\n * 4. synthetic workspace with exact=false (honest fallback)\n * First use auto-registers (persisted by the caller on the write path);\n * resolution itself is pure/read-only.\n */\n\nexport interface ResolvedWorkspace {\n /** Stable workspace id (slug of origin owner/repo or directory name). */\n workspaceId: string\n /** Human-editable display name. */\n name: string\n /** Canonical absolute path this identity was derived from. */\n path: string\n /** Git origin URL when available. */\n origin?: string\n /** false when the identity is a synthetic fallback (honest labeling). */\n exact: boolean\n}\n\n/** Run a git command; return stdout or null on any failure (git missing, not a repo). */\nexport function git(args: string[], cwd: string): string | null {\n try {\n const out = execFileSync('git', args, { cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], timeout: 5000 })\n return out.trim() === '' ? null : out.trim()\n } catch {\n return null\n }\n}\n\n/** Slugify an origin URL (\"git@github.com:owner/repo.git\" -> \"owner-repo\"). */\nexport function workspaceIdFromOrigin(origin: string): string {\n const cleaned = origin\n .replace(/^git@[^:]+:/, '')\n .replace(/^https?:\\/\\/[^/]+\\//, '')\n .replace(/\\.git$/, '')\n .toLowerCase()\n const slug = cleaned.replace(/[^a-z0-9._-]+/g, '-').replace(/^-+|-+$/g, '')\n return slug === '' ? 'workspace' : slug\n}\n\nexport function slugifyDir(path: string): string {\n // Split on BOTH separators explicitly: path.basename is platform-aware\n // (Windows-only '\\' on win32, '/' on POSIX) and hubs legitimately carry\n // cross-platform path strings.\n const lastSegment = path.split(/[\\\\/]/).filter(Boolean).pop() ?? ''\n const slug = lastSegment\n .toLowerCase()\n .replace(/[^a-z0-9._-]+/g, '-')\n .replace(/^-+|-+$/g, '')\n return slug === '' ? 'workspace' : slug\n}\n\n/** Find the git root upward from dir; null when not inside a repository. */\nexport function gitRoot(dir: string): string | null {\n const top = git(['rev-parse', '--show-toplevel'], dir)\n return top !== null && isAbsolute(top) ? resolve(top) : null\n}\n\n/** Resolve workspace identity for a working directory (pure \u2014 never writes). */\nexport function resolveWorkspace(dir: string, explicitId?: string): ResolvedWorkspace {\n const abs = resolve(dir)\n if (explicitId !== undefined && explicitId !== '') {\n return { workspaceId: explicitId, name: explicitId, path: abs, exact: true }\n }\n const origin = git(['remote', 'get-url', 'origin'], abs)\n if (origin !== null) {\n return { workspaceId: workspaceIdFromOrigin(origin), name: basename(abs), path: abs, origin, exact: true }\n }\n const root = gitRoot(abs)\n const canonical = root ?? abs\n return { workspaceId: slugifyDir(canonical), name: basename(canonical), path: canonical, exact: true }\n}\n\n/** Scope for read/write from a resolved workspace. */\nexport function scopeForWorkspace(workspaceId: string): KnowledgeScope {\n return { level: 'project', workspaceId }\n}\n\n/** Registered workspace record (persisted in hub.yaml workspaces table). */\nexport interface RegisteredWorkspace {\n workspaceId: string\n name: string\n origin?: string\n registeredAt: string\n}\n\n/** Load the workspaces table from hub.yaml's flat `workspaces.<id>.name` rows. */\nexport function readRegisteredWorkspaces(config: Record<string, string>): RegisteredWorkspace[] {\n const out: RegisteredWorkspace[] = []\n for (const [key, value] of Object.entries(config)) {\n const match = /^workspaces\\.([.\\w-]+)\\.name$/.exec(key)\n if (match?.[1] === undefined) continue\n const id = match[1]\n out.push({\n workspaceId: id,\n name: value,\n origin: config[`workspaces.${id}.origin`],\n registeredAt: config[`workspaces.${id}.registeredAt`] ?? '',\n })\n }\n return out\n}\n\n/** Persist (upsert) a workspace row into hub.yaml. Caller must hold the write lock. */\nexport function registerWorkspace(\n hubRoot: string,\n ws: ResolvedWorkspace,\n nowIso: () => string,\n readConfig: (root: string) => Record<string, string>,\n writeConfig: (root: string, content: string) => void,\n): void {\n const config = readConfig(hubRoot)\n const nameKey = `workspaces.${ws.workspaceId}.name`\n if (config[nameKey] !== undefined) {\n // Already registered \u2014 keep as-is (name edits go through the panel/CLI).\n return\n }\n // Append the new row(s) instead of rewriting the whole file (keeps comments).\n const lines: string[] = [`workspaces.${ws.workspaceId}.name: ${ws.name}`]\n if (ws.origin !== undefined) lines.push(`workspaces.${ws.workspaceId}.origin: ${ws.origin}`)\n lines.push(`workspaces.${ws.workspaceId}.registeredAt: ${nowIso()}`)\n writeConfig(hubRoot, `${lines.join('\\n')}\\n`)\n}\n", "import { existsSync, readFileSync, rmSync, statSync } from 'node:fs'\nimport { join } from 'node:path'\nimport { randomUUID } from 'node:crypto'\nimport { atomicWrite } from './atomic.js'\nimport { ErrorCode, HubError } from './errors.js'\nimport { LOCK_FILE } from './hub.js'\n\n/**\n * Writer lock with lease + fencing token (predecessor ADR-0009, reimplemented):\n * a stuck writer is recovered by heartbeat age, not by manual lock deletion.\n * Old writers holding an older token degrade to read-only when they see a\n * newer token. All writers of one hub share this single process-agnostic file.\n */\n\nexport interface WriterLock {\n pid: number\n host: string\n acquiredAt: string\n heartbeatAt: string\n /** Monotonic fencing token: `lk-<base36 ms>-<rand>`; later acquirer wins. */\n token: string\n}\n\nexport interface LockOptions {\n heartbeatMs?: number\n staleMs?: number\n now?: () => number\n host?: string\n}\n\nconst DEFAULT_HEARTBEAT_MS = 15_000\nconst DEFAULT_STALE_MS = 45_000\n\nfunction lockPath(root: string): string {\n return join(root, LOCK_FILE)\n}\n\nexport function readLock(root: string): WriterLock | null {\n const path = lockPath(root)\n if (!existsSync(path)) return null\n try {\n return JSON.parse(readFileSync(path, 'utf8')) as WriterLock\n } catch {\n // Corrupt lock file: treat as absent (recovery path, predecessor lesson).\n return null\n }\n}\n\nfunction lockAgeMs(lock: WriterLock, now: number): number {\n const parsed = Date.parse(lock.heartbeatAt)\n return Number.isNaN(parsed) ? Number.POSITIVE_INFINITY : now - parsed\n}\n\n/** True when the lock exists and its heartbeat is younger than staleMs. */\nexport function isLockFresh(root: string, options?: LockOptions): boolean {\n const lock = readLock(root)\n if (lock === null) return false\n const now = (options?.now ?? Date.now)()\n return lockAgeMs(lock, now) < (options?.staleMs ?? DEFAULT_STALE_MS)\n}\n\nexport interface AcquireResult {\n ok: boolean\n lock?: WriterLock\n /** When !ok, the fresh lock held by someone else (readonly consumers surface this). */\n holder?: WriterLock\n}\n\n/**\n * Acquire the writer lease. Succeeds when no lock exists, or the existing\n * lock's heartbeat is older than staleMs (stuck writer auto-recovery).\n */\nexport function acquireLock(root: string, options?: LockOptions): AcquireResult {\n const now = (options?.now ?? Date.now)()\n const existing = readLock(root)\n if (existing !== null && lockAgeMs(existing, now) < (options?.staleMs ?? DEFAULT_STALE_MS)) {\n return { ok: false, holder: existing }\n }\n const lock: WriterLock = {\n pid: process.pid,\n host: options?.host ?? process.env.COMPUTERNAME ?? process.env.HOSTNAME ?? 'unknown-host',\n acquiredAt: new Date(now).toISOString(),\n heartbeatAt: new Date(now).toISOString(),\n token: `lk-${now.toString(36)}-${randomUUID().slice(0, 8)}`,\n }\n atomicWrite(lockPath(root), `${JSON.stringify(lock, null, 2)}\\n`)\n return { ok: true, lock }\n}\n\n/** Refresh the heartbeat; only succeeds while our own token is current. */\nexport function heartbeatLock(root: string, token: string, options?: LockOptions): boolean {\n const existing = readLock(root)\n if (existing === null || existing.token !== token) return false\n const now = (options?.now ?? Date.now)()\n existing.heartbeatAt = new Date(now).toISOString()\n atomicWrite(lockPath(root), `${JSON.stringify(existing, null, 2)}\\n`)\n return true\n}\n\n/** Release only when we still hold the current token (never delete a successor's lock). */\nexport function releaseLock(root: string, token: string): boolean {\n const existing = readLock(root)\n if (existing === null || existing.token !== token) return false\n rmSync(lockPath(root), { force: true })\n return true\n}\n\n/**\n * Fencing check for a write performed under `token`: throws E_READONLY when a\n * newer writer has taken over (stale token). Call before every store mutation.\n */\nexport function assertFencing(root: string, token: string, options?: LockOptions): void {\n const existing = readLock(root)\n if (existing === null) return\n if (existing.token !== token) {\n throw new HubError(ErrorCode.E_READONLY, 'writer lease superseded by a newer writer (fencing token mismatch)', {\n currentToken: existing.token,\n holder: existing.host,\n })\n }\n const now = (options?.now ?? Date.now)()\n if (lockAgeMs(existing, now) >= (options?.staleMs ?? DEFAULT_STALE_MS)) {\n throw new HubError(ErrorCode.E_READONLY, 'writer lease expired (heartbeat overdue)', {\n heartbeatAt: existing.heartbeatAt,\n })\n }\n}\n\n/** File-level diagnostics (status tooling). Never emits `undefined` values \u2014\n * host tool outputs are lossless-JSON validated, so optional keys are omitted. */\nexport function lockInfo(\n root: string,\n options?: LockOptions,\n): { held: boolean; fresh: boolean; lock?: WriterLock; sizeBytes?: number } {\n const lock = readLock(root)\n if (lock === null) return { held: false, fresh: false }\n const path = lockPath(root)\n return {\n held: true,\n fresh: isLockFresh(root, options),\n lock,\n ...(existsSync(path) ? { sizeBytes: statSync(path).size } : {}),\n }\n}\n", "import { listEntries } from './store.js'\nimport type { KnowledgeEntry } from './store.js'\nimport type { KnowledgeScope } from './types.js'\n\n/**\n * Search: CJK bigram + ASCII word tokenization over an in-memory inverted\n * index with BM25-lite scoring and scope-ancestor filtering.\n *\n * Design rules (V2): directory-scoped before whole-index; L0/L1/L2 progressive\n * loading (abstract \u2192 overview \u2192 details); min_score is caller-calibrated via\n * ledger replay, never hard-coded folklore.\n */\n\n// ---------------------------------------------------------------------------\n// Tokenization\n// ---------------------------------------------------------------------------\n\nconst CJK_RANGE = /[\\u3400-\\u4DBF\\u4E00-\\u9FFF\\u3040-\\u30FF\\uAC00-\\uD7AF]/\n\n/** CJK bigrams + lowercase ASCII/digit words. Zero dependencies. */\nexport function tokenize(text: string): string[] {\n const tokens: string[] = []\n let ascii = ''\n let cjkRun: string[] = []\n const flushAscii = () => {\n if (ascii !== '') {\n tokens.push(ascii.toLowerCase())\n ascii = ''\n }\n }\n const flushCjk = () => {\n for (let i = 0; i < cjkRun.length - 1; i += 1) {\n tokens.push(`${cjkRun[i]}${cjkRun[i + 1]}`)\n }\n cjkRun = []\n }\n for (const char of text) {\n if (/[a-zA-Z0-9]/.test(char)) {\n flushCjk()\n ascii += char\n } else if (CJK_RANGE.test(char)) {\n flushAscii()\n cjkRun.push(char)\n } else {\n flushAscii()\n flushCjk()\n }\n }\n flushAscii()\n flushCjk()\n return tokens\n}\n\n// ---------------------------------------------------------------------------\n// Index\n// ---------------------------------------------------------------------------\n\n/** Field weights: title hits matter most, then summary/tags, then body. */\nconst FIELD_WEIGHTS = { title: 3, summary: 2, tags: 2, body: 1 } as const\n\ninterface IndexedDoc {\n id: string\n entry: KnowledgeEntry\n /** term -> weighted term frequency within this doc. */\n tf: Map<string, number>\n length: number\n}\n\nexport interface SearchIndex {\n docs: Map<string, IndexedDoc>\n /** term -> doc ids containing it. */\n postings: Map<string, Set<string>>\n totalLength: number\n builtAt: string\n}\n\nexport function buildIndex(root: string, nowIso: () => string): SearchIndex {\n const docs = new Map<string, IndexedDoc>()\n const postings = new Map<string, Set<string>>()\n let totalLength = 0\n for (const entry of listEntries(root)) {\n const bag = termBag(entry)\n const id = entry.frontmatter.id\n let length = 0\n for (const [term, tf] of bag) {\n length += tf\n let set = postings.get(term)\n if (set === undefined) {\n set = new Set()\n postings.set(term, set)\n }\n set.add(id)\n }\n docs.set(id, { id, entry, tf: bag, length })\n totalLength += length\n }\n return { docs, postings, totalLength, builtAt: nowIso() }\n}\n\nfunction termBag(entry: KnowledgeEntry): Map<string, number> {\n const bag = new Map<string, number>()\n const add = (text: string, weight: number) => {\n for (const term of tokenize(text)) {\n bag.set(term, (bag.get(term) ?? 0) + weight)\n }\n }\n add(entry.frontmatter.title, FIELD_WEIGHTS.title)\n add(entry.frontmatter.summary, FIELD_WEIGHTS.summary)\n add(entry.frontmatter.tags.join(' '), FIELD_WEIGHTS.tags)\n add(entry.body, FIELD_WEIGHTS.body)\n return bag\n}\n\n// ---------------------------------------------------------------------------\n// Scope filtering (ADR-0002: project \u222A global; domains optional later)\n// ---------------------------------------------------------------------------\n\n/** Ancestor-chain visibility: the workspace sees itself + global (+ domains when configured). */\nexport function isVisible(scope: KnowledgeScope, workspaceId: string): boolean {\n if (scope.level === 'global') return true\n if (scope.level === 'project') return scope.workspaceId === workspaceId\n // Domain entries are visible from their member workspaces; without a\n // configured domains table (V0.1) treat them as invisible to projects.\n return false\n}\n\n// ---------------------------------------------------------------------------\n// Query\n// ---------------------------------------------------------------------------\n\nexport type DetailLevel = 'L0' | 'L1' | 'L2'\n\nexport interface SearchHit {\n id: string\n version: number\n type: string\n status: string\n title: string\n /** L0: one-line abstract. */\n abstract: string\n score: number\n scope: KnowledgeScope\n tags: string[]\n /** L1: full summary. */\n summary?: string\n /** L2: full body. */\n body?: string\n}\n\nexport interface SearchMetrics {\n indexedCount: number\n queryCount: number\n totalHits: number\n lastHitCount: number\n lastQuery: string\n builtAt: string\n}\n\nexport interface SearchOptions {\n workspaceId: string\n detail?: DetailLevel\n minScore?: number\n limit?: number\n types?: string[]\n}\n\nconst BM25_K1 = 1.2\nconst BM25_B = 0.75\nconst LOCAL_BOOST = 1.2\n\n/** Run a query against the index (pure read). */\nexport function search(index: SearchIndex, query: string, options: SearchOptions): SearchHit[] {\n const queryTerms = tokenize(query)\n if (queryTerms.length === 0) return []\n const avgLength = index.docs.size === 0 ? 1 : index.totalLength / index.docs.size\n const scores = new Map<string, number>()\n for (const term of new Set(queryTerms)) {\n const posting = index.postings.get(term)\n if (posting === undefined) continue\n const idf = Math.log(1 + (index.docs.size - posting.size + 0.5) / (posting.size + 0.5))\n for (const docId of posting) {\n const doc = index.docs.get(docId)\n if (doc === undefined) continue\n if (!isVisible(doc.entry.frontmatter.scope, options.workspaceId)) continue\n if (options.types !== undefined && !options.types.includes(doc.entry.frontmatter.type)) continue\n const tf = doc.tf.get(term) ?? 0\n const norm = tf * (BM25_K1 + 1) / (tf + BM25_K1 * (1 - BM25_B + BM25_B * (doc.length / avgLength)))\n scores.set(docId, (scores.get(docId) ?? 0) + idf * norm)\n }\n }\n const minScore = options.minScore ?? 0\n const hits: SearchHit[] = []\n for (const [docId, score] of scores) {\n if (score < minScore) continue\n const doc = index.docs.get(docId)\n if (doc === undefined) continue\n // Local boost: entries of the querying workspace rank higher (predecessor DEC-000002).\n const boosted =\n doc.entry.frontmatter.scope.level === 'project' && doc.entry.frontmatter.scope.workspaceId === options.workspaceId\n ? score * LOCAL_BOOST\n : score\n hits.push(toHit(doc, boosted, options.detail ?? 'L1'))\n }\n hits.sort((a, b) => b.score - a.score)\n return options.limit !== undefined ? hits.slice(0, options.limit) : hits\n}\n\nfunction toHit(doc: IndexedDoc, score: number, detail: DetailLevel): SearchHit {\n const fm = doc.entry.frontmatter\n const hit: SearchHit = {\n id: fm.id,\n version: fm.version,\n type: fm.type,\n status: fm.status,\n title: fm.title,\n abstract: firstLine(fm.summary, 80),\n score: Math.round(score * 1000) / 1000,\n scope: fm.scope,\n tags: fm.tags,\n }\n if (detail === 'L1' || detail === 'L2') hit.summary = fm.summary\n if (detail === 'L2') hit.body = doc.entry.body\n return hit\n}\n\nfunction firstLine(text: string, maxChars: number): string {\n const line = text.split('\\n')[0] ?? ''\n return line.length <= maxChars ? line : `${line.slice(0, maxChars)}\u2026`\n}\n\n/** Query with metrics bookkeeping (mutates a metrics record owned by the caller). */\nexport function searchWithMetrics(\n index: SearchIndex,\n metrics: SearchMetrics,\n query: string,\n options: SearchOptions,\n): SearchHit[] {\n const hits = search(index, query, options)\n metrics.queryCount += 1\n metrics.totalHits += hits.length\n metrics.lastHitCount = hits.length\n metrics.lastQuery = query\n return hits\n}\n\nexport function emptyMetrics(index: SearchIndex): SearchMetrics {\n return {\n indexedCount: index.docs.size,\n queryCount: 0,\n totalHits: 0,\n lastHitCount: 0,\n lastQuery: '',\n builtAt: index.builtAt,\n }\n}\n", "import { buildIndex, search, type SearchHit } from './search.js'\nimport type { SearchIndex } from './search.js'\nimport { appendLedger, ledgerPath } from './ledger.js'\nimport { randomUUID } from 'node:crypto'\n\n/**\n * Preflight / injection \u2014 the L0 static pack the host can paste into context\n * every turn. Denoising is top-k truncation (k<=3) + local boost (measured in\n * docs/04-development/search-replay-2026-11-15.md); min_score stays a\n * zero-relevance guard at 0. The pack targets ~250 tokens; the token estimate\n * is documented, not magic.\n */\n\nexport interface PreflightResult {\n /** ready = hits found; no_match = nothing surfaced (host injects nothing). */\n status: 'ready' | 'no_match'\n hits: Array<{ id: string; version: number; title: string; abstract: string; score: number }>\n /** Rough token estimate of the rendered pack (see estimateTokens). */\n tokens: number\n pack?: string\n}\n\n/**\n * Token estimate: CJK chars \u2248 1 token each, ASCII words \u2248 1.3. Documented\n * approximation for budget math \u2014 not a claim about any specific tokenizer.\n */\nexport function estimateTokens(text: string): number {\n let cjk = 0\n const asciiWords = text.split(/[^a-zA-Z0-9]+/).filter((w) => w !== '').length\n for (const char of text) {\n if (/[\\u3400-\\u4DBF\\u4E00-\\u9FFF\\u3040-\\u30FF\\uAC00-\\uD7AF]/.test(char)) cjk += 1\n }\n return Math.ceil(cjk + asciiWords * 1.3)\n}\n\n/** Render the L0 pack: one line per hit \u2014 [ID] title \u2014 abstract. */\nexport function renderPack(hits: SearchHit[]): string {\n return hits\n .map((hit) => `[${hit.id}] ${hit.title} \u2014 ${hit.abstract}`)\n .join('\\n')\n}\n\nexport interface PreflightOptions {\n /** Max hits in the pack; 3 is the replay-calibrated default. */\n limit?: number\n types?: string[]\n nowIso?: () => string\n}\n\n/**\n * Run a preflight: search the current workspace scope (itself + global),\n * top-k truncated, and record a preflight.recorded event shaped like the\n * predecessor ledger (replay scripts keep working across repos).\n */\nexport function preflight(\n index: SearchIndex,\n hubRoot: string,\n workspaceId: string,\n intent: string,\n options?: PreflightOptions,\n): PreflightResult {\n const limit = options?.limit ?? 3\n const hits = search(index, intent, { workspaceId, detail: 'L0', limit, types: options?.types })\n const surfaced = hits.map((hit) => ({\n id: hit.id,\n version: hit.version,\n title: hit.title,\n abstract: hit.abstract,\n score: hit.score,\n }))\n const pack = surfaced.length > 0 ? renderPack(hits) : undefined\n const result: PreflightResult = {\n status: surfaced.length > 0 ? 'ready' : 'no_match',\n hits: surfaced,\n tokens: pack === undefined ? 0 : estimateTokens(pack),\n // Lossless-JSON contract (host tool outputs): omit absent keys instead of\n // emitting `undefined` values.\n ...(pack === undefined ? {} : { pack }),\n }\n appendLedger(ledgerPath(hubRoot), {\n type: 'preflight.recorded',\n preflightId: `PF-${randomUUID().slice(0, 8)}`,\n status: result.status,\n hits: surfaced.map((hit) => ({ id: hit.id, version: hit.version })),\n tokens: result.tokens,\n intent,\n at: options?.nowIso?.() ?? new Date().toISOString(),\n })\n return result\n}\n\n/** Rebuild an index for repeated preflights (host does this once per turn). */\nexport function preflightIndex(hubRoot: string, nowIso?: () => string): SearchIndex {\n return buildIndex(hubRoot, nowIso ?? (() => new Date().toISOString()))\n}\n", "import { existsSync, mkdirSync, readFileSync, readdirSync, appendFileSync, rmSync } from 'node:fs'\nimport { join } from 'node:path'\nimport { journalDir } from './hub.js'\nimport { nowIso } from './time.js'\n\n/**\n * Journal \u2014 the episodic layer. AUTO-CAPTURE \u2260 AUTO-WRITE: journal files are\n * append-only, disposable, and NEVER indexed into search (knowledge stays the\n * only authoritative layer). One JSONL file per local day; trimming is a\n * caller decision (storage hygiene), not an automatic behavior.\n */\n\nexport interface JournalEntry {\n ts: string\n sessionId?: string\n /** Free-form episodic note (what happened in the conversation). */\n text: string\n [key: string]: unknown\n}\n\nfunction dayStamp(iso: string): string {\n return iso.slice(0, 10)\n}\n\nfunction journalFile(root: string, iso: string): string {\n const dir = journalDir(root)\n if (!existsSync(dir)) mkdirSync(dir, { recursive: true })\n return join(dir, `${dayStamp(iso)}.jsonl`)\n}\n\nexport interface AppendJournalInput {\n ts?: string\n sessionId?: string\n text: string\n [key: string]: unknown\n}\n\n/** Append one episodic entry to the day file. Never touches knowledge/. */\nexport function appendJournal(root: string, entry: AppendJournalInput): JournalEntry {\n const stamped: JournalEntry = { ...entry, ts: entry.ts ?? nowIso() }\n appendFileSync(journalFile(root, stamped.ts), `${JSON.stringify(stamped)}\\n`, 'utf8')\n return stamped\n}\n\n/** Read one day's entries (or all days when day is omitted). */\nexport function readJournal(root: string, day?: string): JournalEntry[] {\n const dir = journalDir(root)\n if (!existsSync(dir)) return []\n const files =\n day !== undefined\n ? [join(dir, `${day}.jsonl`)]\n : readdirSync(dir)\n .filter((f) => f.endsWith('.jsonl'))\n .sort()\n .map((f) => join(dir, f))\n const out: JournalEntry[] = []\n for (const file of files) {\n if (!existsSync(file)) continue\n for (const line of readFileSync(file, 'utf8').split('\\n')) {\n if (line.trim() === '') continue\n try {\n out.push(JSON.parse(line) as JournalEntry)\n } catch {\n // skip malformed lines \u2014 journal is disposable, never load-bearing\n }\n }\n }\n return out\n}\n\n/** Explicit trim: delete day files older than keepDays (caller decides when). */\nexport function trimJournal(root: string, keepDays: number, todayIso?: string): number {\n const dir = journalDir(root)\n if (!existsSync(dir)) return 0\n const cutoff = dayStamp(todayIso ?? nowIso())\n let removed = 0\n for (const file of readdirSync(dir)) {\n if (!file.endsWith('.jsonl')) continue\n const day = file.replace('.jsonl', '')\n if (day < cutoff && isOlderThan(day, cutoff, keepDays)) {\n rmSync(join(dir, file), { force: true })\n removed += 1\n }\n }\n return removed\n}\n\nfunction isOlderThan(day: string, cutoff: string, keepDays: number): boolean {\n const dayMs = Date.parse(`${day}T00:00:00Z`)\n const cutoffMs = Date.parse(`${cutoff}T00:00:00Z`)\n if (Number.isNaN(dayMs) || Number.isNaN(cutoffMs)) return false\n return cutoffMs - dayMs > keepDays * 86_400_000\n}\n", "import { existsSync, readFileSync, appendFileSync } from 'node:fs'\nimport { join } from 'node:path'\nimport { tokenize } from './search.js'\nimport { atomicWrite } from './atomic.js'\n\n/**\n * Day-zero transcript index (the deja-vu route): hosts keep transcript bodies\n * authoritative; we store only a compact per-session token index + a short\n * preview. Deja-vu = a new task's intent matches tokens from earlier sessions,\n * surfaced BEFORE duplication happens (day zero), not by dedup afterwards.\n */\n\nexport interface TranscriptRecord {\n sessionId: string\n /** ISO timestamp of the session (or its first message). */\n at: string\n /** Bigram/word token set (serialized array) \u2014 the only searchable content. */\n tokens: string[]\n /** \u2264160 char preview for human display; never searched. */\n preview: string\n /** Host-side pointer back to the full body (path/URL \u2014 host resolves it). */\n location: string\n}\n\nexport const TRANSCRIPT_INDEX_FILE = 'records/transcript-index.jsonl'\n\nfunction indexPath(root: string): string {\n return join(root, TRANSCRIPT_INDEX_FILE)\n}\n\n/** Index one session transcript: tokens + preview only (body stays with the host). */\nexport function indexTranscript(\n root: string,\n input: { sessionId: string; at?: string; text: string; location: string },\n): TranscriptRecord {\n const tokens = [...new Set(tokenize(input.text))]\n const record: TranscriptRecord = {\n sessionId: input.sessionId,\n at: input.at ?? new Date().toISOString(),\n tokens,\n preview: input.text.replace(/\\s+/g, ' ').slice(0, 160),\n location: input.location,\n }\n appendFileSync(indexPath(root), `${JSON.stringify(record)}\\n`, 'utf8')\n return record\n}\n\nexport function readTranscriptIndex(root: string): TranscriptRecord[] {\n const path = indexPath(root)\n if (!existsSync(path)) return []\n const out: TranscriptRecord[] = []\n for (const line of readFileSync(path, 'utf8').split('\\n')) {\n if (line.trim() === '') continue\n try {\n out.push(JSON.parse(line) as TranscriptRecord)\n } catch {\n // skip malformed\n }\n }\n return out\n}\n\nexport interface DejaVu {\n sessionId: string\n at: string\n preview: string\n location: string\n /** Jaccard overlap between the query tokens and the session tokens. */\n overlap: number\n}\n\n/**\n * Detect deja-vu: sessions whose token set overlaps the query tokens above the\n * threshold (default 0.35 \u2014 deliberately conservative; this is a hint, not a\n * verdict). Read-only; the host decides what to do with the pointer.\n */\nexport function detectDejaVu(root: string, query: string, threshold?: number): DejaVu[] {\n const queryTokens = new Set(tokenize(query))\n if (queryTokens.size === 0) return []\n const min = threshold ?? 0.35\n const hits: DejaVu[] = []\n for (const record of readTranscriptIndex(root)) {\n const set = new Set(record.tokens)\n let shared = 0\n for (const token of queryTokens) if (set.has(token)) shared += 1\n const overlap = shared / queryTokens.size\n if (overlap >= min) {\n hits.push({\n sessionId: record.sessionId,\n at: record.at,\n preview: record.preview,\n location: record.location,\n overlap: Math.round(overlap * 1000) / 1000,\n })\n }\n }\n return hits.sort((a, b) => b.overlap - a.overlap)\n}\n\n/** Rebuild the index file atomically (dedup by sessionId keeps the latest). */\nexport function rebuildTranscriptIndex(root: string, records: TranscriptRecord[]): void {\n const bySession = new Map<string, TranscriptRecord>()\n for (const record of records) bySession.set(record.sessionId, record)\n const lines = [...bySession.values()].map((r) => `${JSON.stringify(r)}\\n`)\n atomicWrite(indexPath(root), lines.join(''))\n}\n", "import { createServer, type IncomingMessage, type ServerResponse } from 'node:http'\nimport { PANEL_HTML } from './panel.js'\nimport { handleApi, type ApiState } from './server.js'\n\n/**\n * HTTP adapter: thin node:http server delegating to the pure handleApi\n * router. Binds 127.0.0.1 by default (the panel is a local human channel).\n */\n\nexport interface ServeOptions {\n port?: number\n host?: string\n}\n\nexport function startServer(state: ApiState, options?: ServeOptions): ReturnType<typeof createServer> {\n const server = createServer((req, res) => {\n void route(state, req, res)\n })\n server.listen(options?.port ?? 7777, options?.host ?? '127.0.0.1')\n return server\n}\n\n/** The URL the server is actually reachable at (resolves port 0 to the OS-assigned port). */\nexport function serverUrl(server: ReturnType<typeof createServer>): string {\n const address = server.address()\n if (address !== null && typeof address === 'object') {\n return `http://${address.address === '::' ? '127.0.0.1' : address.address}:${address.port}/`\n }\n return 'http://127.0.0.1/'\n}\n\nasync function route(state: ApiState, req: IncomingMessage, res: ServerResponse): Promise<void> {\n const url = new URL(req.url ?? '/', `http://${req.headers.host ?? 'localhost'}`)\n const path = url.pathname\n if (req.method === 'GET' && (path === '/' || path === '/panel')) {\n res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' })\n res.end(PANEL_HTML)\n return\n }\n if (path.startsWith('/api/')) {\n let body: Record<string, unknown> | undefined\n // Query params flow into body so GET handlers can accept options (ADR-0012 hub pull since=).\n if (url.searchParams.size > 0) body = Object.fromEntries(url.searchParams.entries())\n if (req.method === 'POST') {\n const chunks: Buffer[] = []\n for await (const chunk of req) chunks.push(chunk as Buffer)\n const raw = Buffer.concat(chunks).toString('utf8')\n if (raw !== '') {\n try {\n body = { ...(body ?? {}), ...(JSON.parse(raw) as Record<string, unknown>) }\n } catch {\n res.writeHead(400, { 'content-type': 'application/json' })\n res.end(JSON.stringify({ error: 'invalid JSON body' }))\n return\n }\n }\n }\n const response = handleApi(state, req.method ?? 'GET', path, body)\n res.writeHead(response.status, { 'content-type': 'application/json' })\n res.end(JSON.stringify(response.body))\n return\n }\n res.writeHead(404, { 'content-type': 'application/json' })\n res.end(JSON.stringify({ error: `no route: ${req.method} ${path}` }))\n}\n", "/**\n * Zero-dependency single-file console (no build step). ADR-0010: the\n * standalone web console is the first-class human management surface for\n * every host. Tabs: approval inbox (graded), knowledge browser (search /\n * detail / deprecate / hard-delete), audit (ledger + journal). Human\n * clicking approve = panel channel.\n */\nexport const PANEL_HTML = `<!doctype html>\n<html lang=\"zh\">\n<head>\n<meta charset=\"utf-8\">\n<title>memhub console</title>\n<style>\n :root { color-scheme: dark; }\n body { font-family: ui-sans-serif, system-ui; margin: 0; background: #0f1115; color: #e6e6e6; }\n header { padding: 14px 20px; border-bottom: 1px solid #262b36; display: flex; gap: 16px; align-items: baseline; }\n header h1 { font-size: 16px; margin: 0; }\n header span { color: #8b93a7; font-size: 12px; }\n nav { display: flex; gap: 4px; padding: 0 20px; border-bottom: 1px solid #262b36; }\n nav button { border: none; background: none; color: #8b93a7; padding: 10px 16px; font-size: 14px; cursor: pointer; border-bottom: 2px solid transparent; }\n nav button.active { color: #e6e6e6; border-bottom-color: #4d7cff; }\n main { max-width: 900px; margin: 0 auto; padding: 16px; }\n .card { border: 1px solid #262b36; border-radius: 10px; padding: 14px 16px; margin: 10px 0; background: #161a22; }\n .card h3 { margin: 0 0 6px; font-size: 14px; }\n .meta { color: #8b93a7; font-size: 12px; margin-bottom: 8px; }\n .grade { border-radius: 6px; padding: 1px 8px; font-size: 11px; }\n .grade.individual { background: #3a2a2a; color: #ff9e9e; }\n .grade.batch { background: #233a2c; color: #8ee39b; }\n .status-tag { border-radius: 6px; padding: 1px 8px; font-size: 11px; background: #262b36; color: #a9b1c2; }\n .status-tag.deprecated { background: #3a2f1e; color: #e3b98e; }\n button { border: 1px solid #2f3542; background: #1d2330; color: #e6e6e6; border-radius: 8px; padding: 6px 14px; cursor: pointer; font-size: 13px; }\n button:hover { background: #262d3d; }\n button.primary { background: #245639; border-color: #2f7a4d; }\n button.danger { background: #5a2a2a; border-color: #7a3a3a; }\n .row { display: flex; gap: 8px; margin-top: 8px; }\n #statusbar { font-size: 12px; color: #8b93a7; }\n pre { white-space: pre-wrap; font-size: 12px; color: #a9b1c2; }\n .empty { color: #8b93a7; padding: 30px 0; text-align: center; }\n #batchbar { display: none; margin: 10px 0; }\n .tabpane { display: none; }\n .tabpane.active { display: block; }\n .entryline { border-bottom: 1px solid #20242e; padding: 9px 4px; cursor: pointer; display: flex; gap: 10px; align-items: baseline; }\n .entryline:hover { background: #1a1f29; }\n .entryline .id { color: #6f9bff; font-size: 12px; min-width: 90px; }\n .entryline .title { flex: 1; font-size: 13px; }\n .entryline .type { color: #8b93a7; font-size: 11px; }\n .detail pre { background: #12151c; border-radius: 8px; padding: 12px; max-height: 320px; overflow: auto; }\n</style>\n</head>\n<body>\n<header><h1>memhub console</h1><span id=\"statusbar\">loading\u2026</span></header>\n<nav>\n <button id=\"tab-inbox\" class=\"active\" onclick=\"showTab('inbox')\">\u6536\u4EF6\u7BB1</button>\n <button id=\"tab-entries\" onclick=\"showTab('entries')\">\u8BB0\u5FC6\u5E93</button>\n <button id=\"tab-audit\" onclick=\"showTab('audit')\">\u5BA1\u8BA1</button>\n</nav>\n<main>\n <div id=\"pane-inbox\" class=\"tabpane active\">\n <div id=\"batchbar\"><button class=\"primary\" onclick=\"approveBatch()\">\u6279\u51C6\u6240\u9009\u4F4E\u98CE\u9669\u6761\u76EE\uFF08\u6279\u91CF\uFF09</button></div>\n <div id=\"inbox\"><div class=\"empty\">\u52A0\u8F7D\u4E2D\u2026</div></div>\n </div>\n <div id=\"pane-entries\" class=\"tabpane\">\n <div class=\"row\"><input id=\"q\" placeholder=\"BM25 \u68C0\u7D22\u2026\" style=\"flex:1\" onkeydown=\"if(event.key==='Enter')doSearch()\"><button onclick=\"doSearch()\">\u641C\u7D22</button><button onclick=\"loadEntries()\">\u5168\u90E8</button></div>\n <div id=\"entrylist\"><div class=\"empty\">\u70B9\u51FB\u300C\u5168\u90E8\u300D\u6D4F\u89C8\u6216\u8F93\u5165\u68C0\u7D22\u8BCD</div></div>\n <div id=\"entrydetail\" class=\"detail\"></div>\n </div>\n <div id=\"pane-audit\" class=\"tabpane\">\n <div class=\"row\"><button onclick=\"loadLedger()\">\u5237\u65B0\u8D26\u672C</button><button onclick=\"loadJournal()\">\u5237\u65B0\u60C5\u666F\u65E5\u5FD7</button></div>\n <div id=\"auditview\"><div class=\"empty\">\u70B9\u51FB\u5237\u65B0\u52A0\u8F7D</div></div>\n </div>\n</main>\n<script>\nlet inbox = [];\nasync function j(url, opts) { const r = await fetch(url, opts); return { ok: r.ok, status: r.status, data: await r.json().catch(() => ({})) }; }\nfunction esc(s) { return String(s ?? '').replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>').replace(/\"/g,'"'); }\nfunction showTab(name) {\n document.querySelectorAll('.tabpane').forEach(p => p.classList.remove('active'));\n document.getElementById('pane-' + name).classList.add('active');\n document.querySelectorAll('nav button').forEach(b => b.classList.remove('active'));\n document.getElementById('tab-' + name).classList.add('active');\n if (name === 'inbox') refreshInbox();\n if (name === 'entries' && document.getElementById('entrylist').dataset.loaded !== '1') loadEntries();\n}\nasync function refreshStatus() {\n const s = await j('/api/status');\n document.getElementById('statusbar').textContent =\n (s.data.workspace ? s.data.workspace.workspaceId + (s.data.workspace.exact ? '' : ' (synthetic)') : '?') +\n ' \u00B7 accepted ' + (s.data.acceptedCount ?? 0) + ' \u00B7 hub ' + (s.data.hubRoot ?? '?');\n}\nasync function refreshInbox() {\n refreshStatus();\n const i = await j('/api/inbox');\n inbox = i.data.proposals ?? [];\n const el = document.getElementById('inbox');\n if (inbox.length === 0) { el.innerHTML = '<div class=\"empty\">\u2713 inbox \u6E05\u7A7A\uFF0C\u65E0\u5F85\u5BA1\u6761\u76EE</div>'; }\n else {\n el.innerHTML = inbox.map(p => \\`\n <div class=\"card\" id=\"card-\\${p.id}\">\n <h3>\\${esc(p.title)} <span class=\"grade \\${p.grade}\">\\${p.grade === 'individual' ? '\u9010\u6761\u5BA1\u6279' : '\u53EF\u6279\u91CF'}</span></h3>\n <div class=\"meta\">\\${esc(p.id)} \u00B7 \\${esc(p.type)} \u00B7 \\${esc((p.tags ?? []).join(', '))}</div>\n <div>\\${esc(p.summary)}</div>\n <div class=\"row\">\n <button class=\"primary\" onclick=\"approveOne('\\${p.id}')\">\u6279\u51C6</button>\n <button class=\"danger\" onclick=\"rejectOne('\\${p.id}')\">\u62D2\u7EDD</button>\n </div>\n </div>\\`).join('');\n }\n const batchables = inbox.filter(p => p.grade === 'batch');\n document.getElementById('batchbar').style.display = batchables.length > 1 ? 'block' : 'none';\n}\nasync function approveOne(id) { await j('/api/inbox/' + id + '/approve', { method: 'POST', headers: {'content-type':'application/json'}, body: '{}' }); refreshInbox(); }\nasync function rejectOne(id) { await j('/api/inbox/' + id + '/reject', { method: 'POST', headers: {'content-type':'application/json'}, body: '{}' }); refreshInbox(); }\nasync function approveBatch() {\n const ids = inbox.filter(p => p.grade === 'batch').map(p => p.id);\n await j('/api/inbox/approve', { method: 'POST', headers: {'content-type':'application/json'}, body: JSON.stringify({ ids }) });\n refreshInbox();\n}\nasync function loadEntries() {\n const r = await j('/api/entries');\n renderEntries(r.data.entries ?? []);\n document.getElementById('entrylist').dataset.loaded = '1';\n}\nasync function doSearch() {\n const q = document.getElementById('q').value;\n if (q === '') return loadEntries();\n const r = await j('/api/search', { method: 'POST', headers: {'content-type':'application/json'}, body: JSON.stringify({ query: q, limit: 25 }) });\n renderEntries((r.data.hits ?? []).map(h => ({ id: h.id, type: h.type, status: 'accepted', title: h.title, summary: h.abstract, score: h.score })));\n}\nfunction renderEntries(entries) {\n const el = document.getElementById('entrylist');\n if (entries.length === 0) { el.innerHTML = '<div class=\"empty\">\u65E0\u6761\u76EE</div>'; return; }\n el.innerHTML = entries.map(e => \\`\n <div class=\"entryline\" onclick=\"openEntry('\\${esc(e.id)}')\">\n <span class=\"id\">\\${esc(e.id)}@v\\${e.version ?? '?'}</span>\n <span class=\"title\">\\${esc(e.title)} <span class=\"status-tag \\${e.status === 'deprecated' ? 'deprecated' : ''}\">\\${esc(e.status ?? '')}</span>\\${e.score !== undefined ? ' \u00B7 ' + Number(e.score).toFixed(2) : ''}</span>\n <span class=\"type\">\\${esc(e.type)}</span>\n </div>\\`).join('');\n}\nasync function openEntry(id) {\n const r = await j('/api/entries/' + id);\n if (!r.ok) { document.getElementById('entrydetail').innerHTML = '<div class=\"card\">\u52A0\u8F7D\u5931\u8D25: ' + esc(r.data.error ?? r.status) + '</div>'; return; }\n const fm = r.data.frontmatter ?? {};\n document.getElementById('entrydetail').innerHTML = \\`\n <div class=\"card\">\n <h3>\\${esc(fm.title)} <span class=\"status-tag\">\\${esc(fm.status)}</span></h3>\n <div class=\"meta\">\\${esc(fm.id)}@v\\${fm.version} \u00B7 \\${esc(fm.type)} \u00B7 \\${esc(JSON.stringify(fm.scope))} \u00B7 \\${esc((fm.tags ?? []).join(', '))}</div>\n <div class=\"meta\">path: \\${esc(r.data.path)}</div>\n <pre id=\"entry-body\">\\${esc(r.data.body)}</pre>\n <div class=\"row\">\n <button class=\"primary\" onclick=\"editEntry('\\${esc(id)}')\">\u7F16\u8F91\uFF08\u91CD\u65B0\u8403\u53D6\uFF09</button>\n <button class=\"danger\" onclick=\"deprecateEntry('\\${esc(id)}')\">\u5E9F\u5F03\uFF08\u8F6F\u5220\u9664\uFF09</button>\n <button class=\"danger\" onclick=\"hardDeleteEntry('\\${esc(id)}')\">\u6C38\u4E45\u5220\u9664\uFF08\u4E0D\u53EF\u6062\u590D\uFF09</button>\n </div>\n </div>\\`;\n}\nasync function editEntry(id) {\n const r = await j('/api/entries/' + id);\n if (!r.ok) { alert('\u52A0\u8F7D\u5931\u8D25: ' + (r.data.error ?? r.status)); return; }\n const fm = r.data.frontmatter ?? {};\n document.getElementById('entrydetail').innerHTML = \\`\n <div class=\"card\">\n <h3>\u7F16\u8F91 \\${esc(fm.id)}\uFF08\u4FDD\u5B58 = v\\${(fm.version ?? 1) + 1}\uFF0C\u65E7\u7248\u672C\u8FDB history/\uFF09</h3>\n <div class=\"meta\">\u6807\u9898\u4E0E\u7C7B\u578B\u4E0D\u53EF\u6539\uFF1B\u6458\u8981\u4E0E\u6B63\u6587\u901A\u7528\u5316\u6539\u5199\u540E\u4FDD\u5B58\u5373\u91CD\u65B0\u8403\u53D6\u3002</div>\n <div style=\"margin:8px 0\"><label>\u6458\u8981</label><br><textarea id=\"edit-summary\" rows=\"3\" style=\"width:98%\">\\${esc(fm.summary)}</textarea></div>\n <div style=\"margin:8px 0\"><label>\u6B63\u6587</label><br><textarea id=\"edit-body\" rows=\"14\" style=\"width:98%;font-family:monospace\">\\${esc(r.data.body)}</textarea></div>\n <div class=\"row\">\n <button class=\"primary\" onclick=\"saveEntry('\\${esc(id)}')\">\u4FDD\u5B58\u4E3A\u65B0\u7248\u672C</button>\n <button onclick=\"openEntry('\\${esc(id)}')\">\u53D6\u6D88</button>\n </div>\n </div>\\`;\n}\nasync function saveEntry(id) {\n const payload = { summary: document.getElementById('edit-summary').value, body: document.getElementById('edit-body').value };\n const r = await j('/api/entries/' + id + '/update', { method: 'POST', headers: {'content-type':'application/json'}, body: JSON.stringify(payload) });\n if (r.ok) { document.getElementById('entrydetail').innerHTML = '<div class=\"card\">\u2713 \u5DF2\u4FDD\u5B58 ' + esc(r.data.updated) + '@v' + esc(r.data.version) + '\uFF08\u65E7\u7248\u672C\u8FDB history/\uFF0C\u8D26\u672C\u5DF2\u8BB0\u5F55\uFF09</div>'; loadEntries(); }\n else alert('\u5931\u8D25: ' + (r.data.error ?? r.status));\n}\nasync function deprecateEntry(id) {\n if (!confirm('\u786E\u8BA4\u5E9F\u5F03 ' + id + '\uFF1F\uFF08status=deprecated\uFF0C\u53EF\u8FFD\u6EAF\uFF09')) return;\n const reason = prompt('\u5E9F\u5F03\u539F\u56E0\uFF1A', 'via console') ?? '';\n const r = await j('/api/entries/' + id + '/deprecate', { method: 'POST', headers: {'content-type':'application/json'}, body: JSON.stringify({ reason }) });\n if (r.ok) { document.getElementById('entrydetail').innerHTML = '<div class=\"card\">\u2713 \u5DF2\u5E9F\u5F03 ' + esc(id) + '</div>'; loadEntries(); }\n else alert('\u5931\u8D25: ' + (r.data.error ?? r.status));\n}\nasync function hardDeleteEntry(id) {\n if (!confirm('\u6C38\u4E45\u5220\u9664 ' + id + '\uFF1F\u6587\u4EF6\u5C06\u88AB\u7269\u7406\u5220\u9664\uFF0C\u4E0D\u53EF\u6062\u590D\uFF08\u8D26\u672C\u7559\u75D5\uFF09\u3002')) return;\n if (!confirm('\u518D\u6B21\u786E\u8BA4\uFF1A\u771F\u7684\u8981\u6C38\u4E45\u5220\u9664 ' + id + ' \u5417\uFF1F')) return;\n const reason = prompt('\u5220\u9664\u539F\u56E0\uFF1A', 'via console') ?? '';\n const r = await j('/api/entries/' + id + '/delete', { method: 'POST', headers: {'content-type':'application/json'}, body: JSON.stringify({ reason }) });\n if (r.ok) { document.getElementById('entrydetail').innerHTML = '<div class=\"card\">\u2713 \u5DF2\u6C38\u4E45\u5220\u9664 ' + esc(id) + '\uFF08\u8D26\u672C\u7559\u75D5\uFF09</div>'; loadEntries(); }\n else alert('\u5931\u8D25: ' + (r.data.error ?? r.status));\n}\nasync function loadLedger() {\n const r = await j('/api/ledger');\n const records = r.data.records ?? [];\n document.getElementById('auditview').innerHTML = '<div class=\"card\"><h3>\u8D26\u672C\u4E8B\u4EF6\uFF08\u6700\u8FD1 ' + records.length + ' / \u5171 ' + (r.data.total ?? 0) + '\uFF09</h3><pre>' + esc(JSON.stringify(records, null, 2)) + '</pre></div>';\n}\nasync function loadJournal() {\n const r = await j('/api/journal');\n const entries = r.data.entries ?? [];\n document.getElementById('auditview').innerHTML = '<div class=\"card\"><h3>\u60C5\u666F\u65E5\u5FD7\uFF08\u6700\u8FD1 ' + entries.length + '\uFF09</h3><pre>' + esc(JSON.stringify(entries, null, 2)) + '</pre></div>';\n}\nrefreshInbox();\n</script>\n</body>\n</html>`\n", "import { readFileSync, unlinkSync, appendFileSync, existsSync } from 'node:fs'\nimport { join } from 'node:path'\nimport { ErrorCode, HubError } from '../core/errors.js'\nimport { readHubConfig } from '../core/hub.js'\nimport { appendLedger, ledgerPath, readSequences, writeSequences } from '../core/ledger.js'\nimport { acquireLock, assertFencing, lockInfo, releaseLock } from '../core/lock.js'\nimport { commitKnowledge, createProposal, deprecateEntry, getEntry, hardDeleteEntry, listEntries, listProposals } from '../core/store.js'\nimport { buildIndex, emptyMetrics, search, type SearchIndex, type SearchMetrics } from '../core/search.js'\nimport { registerWorkspace, resolveWorkspace, type ResolvedWorkspace } from '../core/registry.js'\nimport { readJournal } from '../core/journal.js'\nimport { readLedger } from '../core/ledger.js'\nimport { autoCommit } from './autocommit.js'\nimport type { KnowledgeType } from '../core/types.js'\n\n/**\n * Serve panel HTTP API \u2014 pure request handler (createServer is a thin\n * adapter). The panel is a human channel (panel): approving from it carries\n * real approval, unlike memory_commit over MCP.\n *\n * Graded approval: decision / constraint / api-catalog entries shape future\n * behavior, so they must be approved individually; lower-risk types may be\n * approved in batches.\n */\n\n/** Types whose approval must be one-by-one (they constrain future behavior). */\nconst INDIVIDUAL_TYPES: readonly KnowledgeType[] = ['decision', 'constraint', 'api-catalog']\n\nexport type ApprovalGrade = 'individual' | 'batch'\n\nexport function gradeFor(type: KnowledgeType): ApprovalGrade {\n return INDIVIDUAL_TYPES.includes(type) ? 'individual' : 'batch'\n}\n\nexport interface ApiState {\n hubRoot: string\n workspace: ResolvedWorkspace\n index: SearchIndex\n metrics: SearchMetrics\n}\n\nexport function createApiState(hubRoot: string, workspaceArg?: string): ApiState {\n const workspace = resolveWorkspace(process.cwd(), workspaceArg)\n const index = buildIndex(hubRoot, () => new Date().toISOString())\n return { hubRoot, workspace, index, metrics: emptyMetrics(index) }\n}\n\nexport interface ApiResponse {\n status: number\n body: unknown\n}\n\nfunction ok(body: unknown): ApiResponse {\n return { status: 200, body }\n}\n\nfunction bad(status: number, message: string, details?: unknown): ApiResponse {\n return { status, body: { error: message, details } }\n}\n\nfunction withWriteLock<T>(hubRoot: string, fn: () => T): T {\n const acquired = acquireLock(hubRoot)\n if (!acquired.ok) {\n throw new HubError(ErrorCode.E_READONLY, 'another writer holds the lease', { holder: acquired.holder })\n }\n const token = acquired.lock?.token ?? ''\n try {\n assertFencing(hubRoot, token)\n return fn()\n } finally {\n releaseLock(hubRoot, token)\n }\n}\n\nfunction commitOne(hubRoot: string, proposalId: string, note?: string): { knowledgeId: string; version: number; superseded?: string; git: { committed: boolean; detail?: string } } {\n const proposal = listProposals(hubRoot).find((p) => p.id === proposalId)\n if (proposal === undefined) {\n throw new HubError(ErrorCode.E_NOT_FOUND, `pending proposal not found: ${proposalId}`, { proposalId })\n }\n // Target selection (ADR-0012): a proposal carrying origin_id upserts that\n // entry in place (create with the same id when the central hub has never\n // seen it; version bump when it has). A legacy `supersedes` still works\n // for local re-extraction proposals, and requires the target to exist.\n const rawOriginId = proposal.frontmatter.extra['origin_id']\n const originId = typeof rawOriginId === 'string' && rawOriginId !== '' && rawOriginId !== '[]' ? rawOriginId : undefined\n const rawSupersedes = proposal.frontmatter.extra['supersedes']\n const supersedesTarget = typeof rawSupersedes === 'string' && rawSupersedes !== '' && rawSupersedes !== '[]' ? rawSupersedes.split(/\\s+/)[0] : undefined\n const targetId = originId ?? supersedesTarget\n const superseding = targetId !== undefined && (originId !== undefined || existsSyncSafe(hubRoot, targetId))\n const committed = commitKnowledge(\n hubRoot,\n {\n ...(superseding ? { id: targetId } : {}),\n type: proposal.frontmatter.type,\n title: proposal.frontmatter.title,\n summary: proposal.frontmatter.summary,\n scope: proposal.frontmatter.scope,\n tags: proposal.frontmatter.tags,\n body: readFileSync(proposal.path, 'utf8').split('---')[2]?.trim() ?? '',\n actor: 'panel',\n },\n { readSequences, writeSequences, appendLedger: (root, record) => appendLedger(ledgerPath(root), record) },\n )\n unlinkSync(proposal.path)\n appendLedger(ledgerPath(hubRoot), {\n type: 'proposal.committed',\n proposalId,\n knowledgeId: committed.id,\n ...(superseding ? { supersedes: targetId } : {}),\n channel: 'panel',\n note,\n at: new Date().toISOString(),\n })\n const gitCommit = autoCommit(hubRoot, `approve: ${committed.id}@v${committed.version} ${proposal.frontmatter.title}`)\n return { knowledgeId: committed.id, version: committed.version, ...(superseding ? { superseded: targetId } : {}), git: gitCommit }\n}\n\nfunction existsSyncSafe(hubRoot: string, id: string): boolean {\n try {\n getEntry(hubRoot, id)\n return true\n } catch {\n return false\n }\n}\n\n/** Route one API request. `body` is the parsed JSON body or undefined. */\nexport function handleApi(state: ApiState, method: string, path: string, body?: Record<string, unknown>): ApiResponse {\n try {\n switch (`${method} ${path}`) {\n case 'GET /api/status':\n return ok({\n hubRoot: state.hubRoot,\n workspace: state.workspace,\n lock: lockInfo(state.hubRoot),\n metrics: state.metrics,\n acceptedCount: listEntries(state.hubRoot).length,\n })\n case 'GET /api/inbox':\n return ok({\n proposals: listProposals(state.hubRoot).map((p) => ({\n id: p.id,\n type: p.frontmatter.type,\n title: p.frontmatter.title,\n summary: p.frontmatter.summary,\n tags: p.frontmatter.tags,\n grade: gradeFor(p.frontmatter.type),\n path: p.path,\n })),\n })\n case 'POST /api/propose': {\n // ADR-0012: remote hubs push their approved entries here as proposals \u2014\n // this inbox IS the central review (approve = merge, reject = declined).\n // originId keeps the source hub's entry id so approval upserts in place.\n const type = body?.['type']\n const title = body?.['title']\n const summary = body?.['summary']\n const bodyText = body?.['body']\n if (typeof type !== 'string' || typeof title !== 'string' || typeof summary !== 'string' || typeof bodyText !== 'string') {\n return bad(400, 'propose requires type, title, summary, body')\n }\n return withWriteLock(state.hubRoot, () => {\n const proposal = createProposal(\n state.hubRoot,\n {\n type: type as KnowledgeType,\n title,\n summary,\n scope: { level: 'project', workspaceId: state.workspace.workspaceId },\n tags: Array.isArray(body?.['tags']) ? (body?.['tags'] as string[]).map(String) : [],\n body: bodyText,\n sourceRefs: Array.isArray(body?.['sourceRefs']) ? (body?.['sourceRefs'] as string[]).map(String) : [`remote:${new Date().toISOString()}`],\n supersedes: Array.isArray(body?.['supersedes']) ? (body?.['supersedes'] as string[]).map(String) : undefined,\n originId: typeof body?.['originId'] === 'string' ? body['originId'] : undefined,\n origin: typeof body?.['origin'] === 'string' ? body['origin'] : 'remote-hub',\n actor: 'remote',\n },\n { readSequences, writeSequences, appendLedger: (root, record) => appendLedger(ledgerPath(root), record) },\n )\n registerWorkspace(\n state.hubRoot,\n state.workspace,\n () => new Date().toISOString(),\n readHubConfig,\n (root, content) => {\n appendFileSync(join(root, 'hub.yaml'), content, 'utf8')\n },\n )\n state.index = buildIndex(state.hubRoot, () => new Date().toISOString())\n state.metrics = emptyMetrics(state.index)\n return ok({ proposalId: proposal.id, nextStep: 'central review via inbox' })\n })\n }\n case 'POST /api/search': {\n const query = String(body?.['query'] ?? '')\n if (query === '') return bad(400, 'query is required')\n const hits = search(state.index, query, {\n workspaceId: state.workspace.workspaceId,\n detail: 'L1',\n limit: typeof body?.['limit'] === 'number' ? body['limit'] : 10,\n })\n return ok({ hits })\n }\n case 'GET /api/entries': {\n const since = typeof body?.['since'] === 'string' ? body['since'] : undefined\n const all = listEntries(state.hubRoot, { includeSoftRemoved: true }).map((e) => ({\n id: e.frontmatter.id,\n version: e.frontmatter.version,\n type: e.frontmatter.type,\n status: e.frontmatter.status,\n title: e.frontmatter.title,\n summary: e.frontmatter.summary,\n scope: e.frontmatter.scope,\n tags: e.frontmatter.tags,\n updated: e.frontmatter.updated,\n path: e.path,\n }))\n // ADR-0012: `since` enables incremental hub pull (updated > since).\n const entries = since === undefined ? all : all.filter((e) => (e.updated ?? '') > since)\n return ok({ entries, since: since ?? null, count: entries.length })\n }\n case 'GET /api/ledger': {\n const records = readLedger(ledgerPath(state.hubRoot))\n const limit = typeof body?.['limit'] === 'number' ? body['limit'] : 200\n return ok({ records: records.slice(-limit).reverse(), total: records.length })\n }\n case 'GET /api/journal': {\n const day = typeof body?.['day'] === 'string' ? body['day'] : undefined\n const entries = readJournal(state.hubRoot, day)\n return ok({ entries: entries.slice(-200).reverse() })\n }\n default:\n break\n }\n const approveMatch = /^\\/api\\/inbox\\/([A-Za-z0-9-]+)\\/approve$/.exec(path)\n if (approveMatch !== null && method === 'POST') {\n return approve(state, [approveMatch[1] ?? ''], body)\n }\n const batchMatch = /^\\/api\\/inbox\\/approve$/.exec(path)\n if (batchMatch !== null && method === 'POST') {\n const ids = body?.['ids']\n if (!Array.isArray(ids) || ids.length === 0) return bad(400, 'ids array is required for batch approval')\n return approve(state, ids.map(String), body)\n }\n const rejectMatch = /^\\/api\\/inbox\\/([A-Za-z0-9-]+)\\/reject$/.exec(path)\n if (rejectMatch !== null && method === 'POST') {\n return reject(state, rejectMatch[1] ?? '', body)\n }\n const entryMatch = /^\\/api\\/entries\\/([A-Za-z0-9-]+)$/.exec(path)\n if (entryMatch !== null && method === 'GET') {\n const entry = getEntry(state.hubRoot, entryMatch[1] ?? '')\n return ok({ frontmatter: entry.frontmatter, body: entry.body, path: entry.path })\n }\n const deprecateMatch = /^\\/api\\/entries\\/([A-Za-z0-9-]+)\\/deprecate$/.exec(path)\n if (deprecateMatch !== null && method === 'POST') {\n const reason = typeof body?.['reason'] === 'string' && body['reason'] !== '' ? body['reason'] : 'deprecated via panel'\n return withWriteLock(state.hubRoot, () => {\n deprecateEntry(state.hubRoot, deprecateMatch[1] ?? '', reason, {\n appendLedger: (root, record) => appendLedger(ledgerPath(root), record),\n })\n state.index = buildIndex(state.hubRoot, () => new Date().toISOString())\n state.metrics = emptyMetrics(state.index)\n return ok({ deprecated: deprecateMatch[1] ?? '', reason, git: autoCommit(state.hubRoot, `deprecate: ${deprecateMatch[1]} (${reason})`) })\n })\n }\n const deleteMatch = /^\\/api\\/entries\\/([A-Za-z0-9-]+)\\/delete$/.exec(path)\n if (deleteMatch !== null && method === 'POST') {\n const reason = typeof body?.['reason'] === 'string' && body['reason'] !== '' ? body['reason'] : 'hard-deleted via panel'\n return withWriteLock(state.hubRoot, () => {\n hardDeleteEntry(state.hubRoot, deleteMatch[1] ?? '', reason, {\n appendLedger: (root, record) => appendLedger(ledgerPath(root), record),\n })\n state.index = buildIndex(state.hubRoot, () => new Date().toISOString())\n state.metrics = emptyMetrics(state.index)\n return ok({ deleted: deleteMatch[1] ?? '', reason, git: autoCommit(state.hubRoot, `delete: ${deleteMatch[1]} (${reason})`) })\n })\n }\n const updateMatch = /^\\/api\\/entries\\/([A-Za-z0-9-]+)\\/update$/.exec(path)\n if (updateMatch !== null && method === 'POST') {\n const existing = getEntry(state.hubRoot, updateMatch[1] ?? '')\n const summary = typeof body?.['summary'] === 'string' && body['summary'] !== '' ? body['summary'] : existing.frontmatter.summary\n const nextBody = typeof body?.['body'] === 'string' ? body['body'] : existing.body\n const tags = Array.isArray(body?.['tags']) ? (body?.['tags'] as string[]).map(String) : existing.frontmatter.tags\n return withWriteLock(state.hubRoot, () => {\n const updated = commitKnowledge(\n state.hubRoot,\n {\n id: existing.frontmatter.id,\n type: existing.frontmatter.type,\n title: existing.frontmatter.title,\n summary,\n scope: existing.frontmatter.scope,\n tags,\n body: nextBody,\n actor: 'panel',\n },\n { readSequences, writeSequences, appendLedger: (root, record) => appendLedger(ledgerPath(root), record) },\n )\n state.index = buildIndex(state.hubRoot, () => new Date().toISOString())\n state.metrics = emptyMetrics(state.index)\n return ok({ updated: updated.id, version: updated.version, git: autoCommit(state.hubRoot, `update: ${updated.id}@v${updated.version}`) })\n })\n }\n return bad(404, `no route: ${method} ${path}`)\n } catch (error) {\n if (error instanceof HubError) {\n const map: Record<string, number> = {\n [ErrorCode.E_NOT_FOUND]: 404,\n [ErrorCode.E_VALIDATION]: 400,\n [ErrorCode.E_CONFLICT]: 409,\n [ErrorCode.E_READONLY]: 423,\n [ErrorCode.E_APPROVAL_REQUIRED]: 403,\n [ErrorCode.E_HUB_NOT_INITIALIZED]: 404,\n }\n return bad(map[error.code] ?? 500, error.message, error.details)\n }\n return bad(500, error instanceof Error ? error.message : String(error))\n }\n}\n\nfunction approve(state: ApiState, ids: string[], body?: Record<string, unknown>): ApiResponse {\n if (ids.length > 1) {\n // Graded approval: batch only when every id is a batch-grade type.\n const proposals = listProposals(state.hubRoot)\n const types = ids.map((id) => proposals.find((p) => p.id === id)?.frontmatter.type)\n if (types.some((t) => t === undefined)) return bad(404, 'unknown proposal id in batch')\n if (types.some((t) => gradeFor(t as KnowledgeType) === 'individual')) {\n return bad(403, 'decision/constraint/api-catalog must be approved individually (graded approval)', {\n individualTypes: INDIVIDUAL_TYPES,\n })\n }\n }\n const note = typeof body?.['note'] === 'string' ? body['note'] : undefined\n return withWriteLock(state.hubRoot, () => {\n const results: Array<{ proposalId: string; knowledgeId?: string; version?: number; superseded?: string; git?: { committed: boolean; detail?: string }; error?: string }> = []\n let firstError: HubError | null = null\n for (const id of ids) {\n try {\n const committed = commitOne(state.hubRoot, id, note)\n results.push({ proposalId: id, knowledgeId: committed.knowledgeId, version: committed.version, ...(committed.superseded !== undefined ? { superseded: committed.superseded } : {}), git: committed.git })\n } catch (error) {\n if (error instanceof HubError && firstError === null) firstError = error\n results.push({ proposalId: id, error: error instanceof Error ? error.message : String(error) })\n }\n }\n // Single-id approval surfaces the real status (404 for unknown id, etc.);\n // batches report partial success as 207.\n if (ids.length === 1 && firstError !== null) {\n return bad(httpStatusFor(firstError), firstError.message, firstError.details)\n }\n // Refresh the index so the panel search sees new entries.\n state.index = buildIndex(state.hubRoot, () => new Date().toISOString())\n state.metrics = emptyMetrics(state.index)\n const failed = results.some((r) => r.error !== undefined)\n return { status: failed ? 207 : 200, body: { results } }\n })\n}\n\nfunction httpStatusFor(error: HubError): number {\n const map: Record<string, number> = {\n [ErrorCode.E_NOT_FOUND]: 404,\n [ErrorCode.E_VALIDATION]: 400,\n [ErrorCode.E_CONFLICT]: 409,\n [ErrorCode.E_READONLY]: 423,\n [ErrorCode.E_APPROVAL_REQUIRED]: 403,\n [ErrorCode.E_HUB_NOT_INITIALIZED]: 404,\n }\n return map[error.code] ?? 500\n}\n\nfunction reject(state: ApiState, id: string, body?: Record<string, unknown>): ApiResponse {\n const proposal = listProposals(state.hubRoot).find((p) => p.id === id)\n if (proposal === undefined) return bad(404, `pending proposal not found: ${id}`)\n const note = typeof body?.['note'] === 'string' ? body['note'] : undefined\n appendLedger(ledgerPath(state.hubRoot), {\n type: 'proposal.rejected',\n proposalId: id,\n channel: 'panel',\n note,\n at: new Date().toISOString(),\n })\n unlinkSync(proposal.path)\n return ok({ rejected: id })\n}\n\n// Re-export for the server adapter + CLI.\nexport { getEntry, listEntries, readLedger, readJournal, readHubConfig }\n", "import { spawnSync } from 'node:child_process'\n\n/**\n * ADR-0011 push policy (user decision 2026-11-15): approved knowledge\n * changes are committed to the LOCAL git history immediately \u2014 fine-grained\n * history, offline-safe. `git push` stays an explicit / scheduled step so\n * central-repo commits remain batched and reviewable. Silently no-ops when\n * the hub root is not a git repository (never blocks approval).\n */\nexport function autoCommit(root: string, message: string): { committed: boolean; detail?: string } {\n const inside = spawnSync('git', ['rev-parse', '--is-inside-work-tree'], { cwd: root, encoding: 'utf8' })\n if (inside.error !== undefined || inside.status !== 0) return { committed: false, detail: 'not a git repository' }\n const add = spawnSync('git', ['add', '-A'], { cwd: root, encoding: 'utf8' })\n if (add.error !== undefined || add.status !== 0) return { committed: false, detail: `git add failed: ${(add.stderr ?? '').trim().slice(0, 200)}` }\n const commit = spawnSync('git', ['commit', '-m', message], { cwd: root, encoding: 'utf8' })\n const output = `${commit.stdout ?? ''}${commit.stderr ?? ''}`\n if (commit.status !== 0) {\n if (output.includes('nothing to commit')) return { committed: false, detail: 'nothing to commit' }\n return { committed: false, detail: output.trim().slice(0, 200) }\n }\n return { committed: true }\n}\n", "/**\n * Minimal structural types for the DSH host surface the adapter touches.\n * Declared here (not imported from the host SDK) so the adapter has zero\n * host dependencies at build time \u2014 the host provides these capabilities.\n */\n\nexport interface ContentBlock {\n type: 'text'\n text: string\n}\n\nexport interface ToolOutput {\n schema: Record<string, unknown>\n render: (args: unknown, value: unknown) => ContentBlock[]\n}\n\nexport interface ToolDefinition {\n name: string\n description: string\n parameters: Record<string, unknown>\n /** Host contract: every tool declares its output shape + renderer. */\n output: ToolOutput\n isConcurrencySafe?: () => boolean\n execute: (args: Record<string, unknown>, exec: unknown) => Promise<unknown> | unknown\n}\n\nexport function renderJson(_args: unknown, value: unknown): ContentBlock[] {\n return [{ type: 'text', text: JSON.stringify(value, null, 2) }]\n}\n\nexport interface HostContext {\n tools: {\n get(name: string): ToolDefinition | undefined\n register(tool: ToolDefinition): () => void\n }\n logger?: {\n info(message: string): void\n warn(message: string): void\n }\n effect?(dispose: () => () => void, name?: string): void\n}\n\nexport interface AdapterConfig {\n /** Hub root directory. Empty/missing = $MEMHUB_ROOT or the process cwd. */\n root?: string\n /**\n * What to do when a tool name is already registered (host or another\n * plugin \u2014 e.g. the predecessor dsh-memory-hub): 'skip' (default) drops\n * ours and keeps the existing one; 'suffix' renames ours to `<name>__amh`.\n */\n toolConflict?: 'skip' | 'suffix'\n}\n\nexport function resolveHubRoot(config?: AdapterConfig): string {\n const explicit = config?.root\n if (explicit !== undefined && explicit !== '') return explicit\n return process.env['MEMHUB_ROOT'] ?? process.cwd()\n}\n", "import * as hub from 'agent-memory-hub'\nimport { renderJson, resolveHubRoot, type AdapterConfig, type HostContext, type ToolDefinition } from './host-types.js'\n\n/**\n * Tool shells: one behavior, one implementation. Every tool is a thin forward\n * to agent-memory-hub core. There is deliberately NO memory_commit tool here:\n * commits enter knowledge/ only through the human channels (`memhub inbox`\n * / the serve panel) \u2014 the fail-closed gate stays closed inside the host.\n *\n * Host contract (dsh 0.2.x): every tool must declare\n * `output { schema, render }` and expose `isConcurrencySafe()` as a method.\n */\n\ninterface HubContext {\n root: string\n workspace: hub.ResolvedWorkspace\n index: hub.SearchIndex\n metrics: hub.SearchMetrics\n}\n\nexport function createHubContext(config?: AdapterConfig): HubContext {\n const root = resolveHubRoot(config)\n const workspace = hub.resolveWorkspace(process.cwd())\n const index = hub.preflightIndex(root)\n return { root, workspace, index, metrics: hub.emptyMetrics(index) }\n}\n\nfunction refreshIndex(ctx: HubContext): void {\n ctx.index = hub.preflightIndex(ctx.root)\n ctx.metrics = hub.emptyMetrics(ctx.index)\n}\n\nfunction errorPayload(error: unknown): { error: string; code?: string } {\n if (error instanceof hub.HubError) return { error: error.message, code: error.code }\n return { error: error instanceof Error ? error.message : String(error) }\n}\n\n/** Host output contract is lossless JSON: strip explicit `undefined` values\n * from every tool result at the boundary \u2014 legacy hub data can carry optional\n * keys in any shape, so the adapter normalizes rather than trusting each path. */\nfunction stripUndefined<T>(value: T): T {\n if (Array.isArray(value)) return value.map((item) => stripUndefined(item)) as T\n if (value !== null && typeof value === 'object') {\n const out: Record<string, unknown> = {}\n for (const [key, item] of Object.entries(value as Record<string, unknown>)) {\n if (item !== undefined) out[key] = stripUndefined(item)\n }\n return out as T\n }\n return value\n}\n\nasync function safe(tool: ToolDefinition, args: Record<string, unknown>): Promise<unknown> {\n try {\n return stripUndefined(await tool.execute(args, undefined))\n } catch (error) {\n return errorPayload(error)\n }\n}\n\nexport function createTools(ctx: HubContext): Array<ToolDefinition & { run: (args: Record<string, unknown>) => Promise<unknown> }> {\n const definitions: Array<ToolDefinition & { run: (args: Record<string, unknown>) => Promise<unknown> }> = []\n\n const define = (tool: Omit<ToolDefinition, 'execute' | 'output' | 'isConcurrencySafe'> & {\n execute: ToolDefinition['execute']\n concurrencySafe?: boolean\n }) => {\n definitions.push({\n ...tool,\n output: { schema: {}, render: renderJson },\n ...(tool.concurrencySafe === true ? { isConcurrencySafe: () => true } : {}),\n run: (args: Record<string, unknown>) => safe({ ...tool, execute: tool.execute } as ToolDefinition, args),\n } as ToolDefinition & { run: (args: Record<string, unknown>) => Promise<unknown> })\n }\n\n define({\n name: 'memory_search',\n description:\n \"Search the user's accepted long-term memory (workspace + global). Use it before planning or modifying a project, and after a preflight hint points at an entry. Returns ranked hits with summaries; call memory_get for the body and memory_cite after actually using an entry.\",\n concurrencySafe: true,\n parameters: {\n type: 'object',\n properties: {\n query: { type: 'string', description: 'Keywords or a natural-language question.' },\n detail: { type: 'string', enum: ['L0', 'L1', 'L2'], description: 'L0 abstract only; L1 adds summary; L2 adds body.' },\n limit: { type: 'number' },\n types: { type: 'array', items: { type: 'string' } },\n },\n required: ['query'],\n },\n execute: (args) => {\n const hits = hub.searchWithMetrics(ctx.index, ctx.metrics, String(args['query']), {\n workspaceId: ctx.workspace.workspaceId,\n detail: (args['detail'] as hub.DetailLevel | undefined) ?? 'L1',\n limit: typeof args['limit'] === 'number' ? args['limit'] : undefined,\n types: args['types'] as string[] | undefined,\n })\n return {\n hits: hits.map((hit) => ({\n id: hit.id,\n version: hit.version,\n type: hit.type,\n title: hit.title,\n abstract: hit.abstract,\n ...(hit.summary !== undefined ? { summary: hit.summary } : {}),\n score: hit.score,\n })),\n workspace: ctx.workspace.workspaceId,\n exact: ctx.workspace.exact,\n }\n },\n })\n\n define({\n name: 'memory_get',\n description:\n 'Read one knowledge entry by ID. Returns metadata + summary by default; pass full=true only when the whole body is needed.',\n concurrencySafe: true,\n parameters: {\n type: 'object',\n properties: {\n id: { type: 'string' },\n full: { type: 'boolean' },\n },\n required: ['id'],\n },\n execute: (args) => {\n const entry = hub.getEntry(ctx.root, String(args['id']))\n // Host output contract is lossless JSON: never emit explicit `undefined`\n // property values \u2014 omit the key instead.\n return {\n frontmatter: entry.frontmatter,\n ...(args['full'] === true ? { body: entry.body } : {}),\n path: entry.path,\n }\n },\n })\n\n define({\n name: 'memory_status',\n description:\n 'Read-only self check: hub root, workspace identity (exact=false means synthetic fallback), writer lock holder, metrics, counts.',\n concurrencySafe: true,\n parameters: { type: 'object', properties: {} },\n execute: () => ({\n hubRoot: ctx.root,\n initialized: hub.isHubInitialized(ctx.root),\n workspace: ctx.workspace,\n lock: hub.lockInfo(ctx.root),\n metrics: ctx.metrics,\n acceptedCount: hub.listEntries(ctx.root).length,\n pendingCount: hub.listProposals(ctx.root).length,\n }),\n })\n\n define({\n name: 'memory_preflight',\n description:\n 'Build the L0 static pack for this turn: top-3 hits, one line each, with a token estimate. Records a preflight.recorded event. Inject the pack only when status=ready.',\n concurrencySafe: true,\n parameters: {\n type: 'object',\n properties: {\n intent: { type: 'string' },\n limit: { type: 'number' },\n },\n required: ['intent'],\n },\n execute: (args) =>\n hub.preflight(ctx.index, ctx.root, ctx.workspace.workspaceId, String(args['intent']), {\n limit: typeof args['limit'] === 'number' ? args['limit'] : undefined,\n }),\n })\n\n define({\n name: 'memory_propose',\n description:\n 'Create a pending candidate (pending/PRO-*.md). This NEVER writes knowledge/ directly \u2014 a human must approve via the serve panel or `memhub inbox`. Always include sourceRefs evidence. To RE-EXTRACT an existing entry (e.g. generalize an environment-specific flow into a universal one), pass supersedes: [entryId] \u2014 approval then bumps that entry\\'s version instead of creating a duplicate.',\n parameters: {\n type: 'object',\n properties: {\n type: { type: 'string', enum: ['decision', 'constraint', 'knowledge', 'api-catalog', 'process', 'open-questions', 'runtime-base', 'playbooks', 'assets'] },\n title: { type: 'string' },\n summary: { type: 'string' },\n tags: { type: 'array', items: { type: 'string' } },\n body: { type: 'string' },\n sourceRefs: { type: 'array', items: { type: 'string' } },\n supersedes: { type: 'array', items: { type: 'string' }, description: 'Entry id(s) this proposal re-extracts; approval upgrades their version.' },\n },\n required: ['type', 'title', 'summary', 'body'],\n },\n execute: (args) => {\n const acquired = hub.acquireLock(ctx.root)\n if (!acquired.ok) return { error: 'another writer holds the lease', code: hub.ErrorCode.E_READONLY }\n const token = acquired.lock?.token ?? ''\n try {\n hub.assertFencing(ctx.root, token)\n const supersedes = args['supersedes'] as string[] | undefined\n const proposal = hub.createProposal(\n ctx.root,\n {\n type: args['type'] as hub.KnowledgeType,\n title: String(args['title']),\n summary: String(args['summary']),\n scope: { level: 'project', workspaceId: ctx.workspace.workspaceId },\n tags: args['tags'] as string[] | undefined,\n body: String(args['body']),\n sourceRefs: (args['sourceRefs'] as string[] | undefined) ?? [],\n ...(supersedes !== undefined && supersedes.length > 0 ? { supersedes } : {}),\n actor: 'model',\n },\n {\n readSequences: hub.readSequences,\n writeSequences: hub.writeSequences,\n appendLedger: (root, record) => hub.appendLedger(hub.ledgerPath(root), record),\n },\n )\n return { proposalId: proposal.id, path: proposal.path, nextStep: 'human approval via panel or `memhub inbox approve`' }\n } finally {\n hub.releaseLock(ctx.root, token)\n }\n },\n })\n\n define({\n name: 'memory_cite',\n description:\n 'Record that a knowledge entry influenced the current task (audit + aging signal). Cite after actually using an entry \u2014 search hits are not citations.',\n parameters: {\n type: 'object',\n properties: {\n id: { type: 'string' },\n purpose: { type: 'string' },\n },\n required: ['id', 'purpose'],\n },\n execute: (args) => {\n const id = String(args['id'])\n hub.getEntry(ctx.root, id) // must exist\n hub.appendLedger(hub.ledgerPath(ctx.root), {\n type: 'citation.added',\n id,\n purpose: String(args['purpose']),\n at: new Date().toISOString(),\n })\n return { cited: id }\n },\n })\n\n define({\n name: 'memory_close_task',\n description:\n 'Close the current task with a writeback assessment (proposed / no_new_knowledge / needs_evidence / deferred). Bookkeeping only.',\n parameters: {\n type: 'object',\n properties: {\n assessment: { type: 'string', enum: ['proposed', 'no_new_knowledge', 'needs_evidence', 'deferred'] },\n note: { type: 'string' },\n },\n required: ['assessment'],\n },\n execute: (args) => {\n hub.appendLedger(hub.ledgerPath(ctx.root), {\n type: 'task.closed',\n assessment: args['assessment'],\n note: typeof args['note'] === 'string' ? args['note'] : undefined,\n at: new Date().toISOString(),\n })\n return { closed: true }\n },\n })\n\n define({\n name: 'memory_dejavu',\n description:\n 'Day-zero deja-vu check: has a similar conversation already happened? Index a transcript (action=index; tokens + preview only \u2014 the body stays with the host) or query overlaps (action=check).',\n concurrencySafe: true,\n parameters: {\n type: 'object',\n properties: {\n action: { type: 'string', enum: ['index', 'check'] },\n sessionId: { type: 'string' },\n text: { type: 'string' },\n location: { type: 'string' },\n query: { type: 'string' },\n },\n required: ['action'],\n },\n execute: (args) => {\n const action = String(args['action'])\n if (action === 'index') {\n const sessionId = args['sessionId'] as string | undefined\n const text = String(args['text'] ?? '')\n const location = String(args['location'] ?? '')\n if (sessionId === undefined || text === '' || location === '') {\n throw new hub.HubError(hub.ErrorCode.E_VALIDATION, 'dejavu index requires sessionId, text and location')\n }\n return hub.indexTranscript(ctx.root, { sessionId, text, location })\n }\n return {\n sessions: hub.readTranscriptIndex(ctx.root).length,\n dejaVu: hub.detectDejaVu(ctx.root, String(args['query'] ?? '')),\n }\n },\n })\n\n return definitions\n}\n\nexport { refreshIndex, resolveHubRoot, type HostContext }\n"],
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACEO,IAAM,YAAY;EACvB,uBAAuB;EACvB,aAAa;EACb,cAAc;EACd,YAAY;EACZ,aAAa;EACb,qBAAqB;EACrB,YAAY;;AAKR,IAAO,WAAP,cAAwB,MAAK;EACxB;EACA;EAET,YAAY,MAAsB,SAAiB,SAAiC;AAClF,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,OAAO;AACZ,SAAK,UAAU;EACjB;;;;ACpBI,SAAU,SAAM;AACpB,UAAO,oBAAI,KAAI,GAAG,YAAW,EAAG,QAAQ,KAAK,aAAa,oBAAI,KAAI,CAAE,CAAC;AACvE;AAEA,SAAS,aAAa,MAAU;AAC9B,QAAM,UAAU,CAAC,KAAK,kBAAiB;AACvC,QAAM,OAAO,WAAW,IAAI,MAAM;AAClC,QAAM,MAAM,KAAK,IAAI,OAAO;AAC5B,QAAM,KAAK,OAAO,KAAK,MAAM,MAAM,EAAE,CAAC,EAAE,SAAS,GAAG,GAAG;AACvD,QAAM,KAAK,OAAO,MAAM,EAAE,EAAE,SAAS,GAAG,GAAG;AAC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AM,MAAM;AACvB,eAAW,WAAW,UAAW,SAAQ;AAAA,EAC3C,GAAG,IAAI;AACT;",
|
|
4
|
+
"sourcesContent": ["import * as hub from 'agent-memory-hub'\nimport { resolveHubRoot, type AdapterConfig, type HostContext, type ToolDefinition } from './host-types.js'\nimport { createTools, createHubContext } from './tools.js'\n\n/**\n * DSH thin adapter for agent-memory-hub (ADR-0001: no host glue in core \u2014\n * the host side is this package). Registers memory_* tools on the cordis\n * tools service; initialization is async-safe: registration is synchronous,\n * tool bodies handle hub errors and return structured payloads, so a failed\n * mount never throws into the host loader.\n *\n * Also embeds the panel HTTP surface in-process (127.0.0.1:7777, ADR-0012)\n * so the DSH sidebar panel always has its audited data source \u2014 no manual\n * `memhub serve` step. Port conflicts (a user-started serve, another session)\n * are tolerated: we skip and the existing server keeps serving.\n */\n\nexport const name = 'agent-memory-hub-dsh'\nexport const inject = ['tools']\n\nconst PANEL_PORT = 7777\n\nfunction startPanelServer(ctx: HostContext, root: string): void {\n try {\n const state = hub.createApiState(root)\n const server = hub.startServer(state, { port: PANEL_PORT, host: '127.0.0.1' })\n server.on('error', (error: NodeJS.ErrnoException) => {\n if (error.code === 'EADDRINUSE') {\n ctx.logger?.info(`agent-memory-hub-dsh: panel port ${PANEL_PORT} already serving (manual serve or another session) \u2014 reusing it`)\n return\n }\n ctx.logger?.warn(`agent-memory-hub-dsh: panel server error: ${error.message}`)\n })\n ctx.logger?.info(`agent-memory-hub-dsh: panel console serving at http://127.0.0.1:${PANEL_PORT}/ (hub: ${root})`)\n ctx.effect?.(() => () => {\n try {\n server.close()\n } catch {\n // already closed\n }\n }, `${name}-panel`)\n } catch (error) {\n ctx.logger?.warn(`agent-memory-hub-dsh: panel server failed to start: ${error instanceof Error ? error.message : String(error)}`)\n }\n}\n\nexport function apply(ctx: HostContext, config?: AdapterConfig): void {\n const root = resolveHubRoot(config)\n if (!hub.isHubInitialized(root)) {\n ctx.logger?.warn(\n `agent-memory-hub-dsh: hub not initialized at ${root} \u2014 memory tools disabled until \\`memhub init --root ${root}\\` runs`,\n )\n return\n }\n startPanelServer(ctx, root)\n const hubCtx = createHubContext(config)\n const conflict = config?.toolConflict ?? 'skip'\n const disposers: Array<() => void> = []\n for (const definition of createTools(hubCtx)) {\n const { run, ...rest } = definition\n let toolName = rest.name\n const existing = ctx.tools.get(toolName)\n if (existing !== undefined) {\n if (conflict === 'skip') {\n ctx.logger?.warn(\n `agent-memory-hub-dsh: tool ${toolName} already registered by host or another plugin; skipping (toolConflict: skip)`,\n )\n continue\n }\n toolName = `${toolName}__amh`\n ctx.logger?.warn(`agent-memory-hub-dsh: tool name collision \u2014 registered as ${toolName} (toolConflict: suffix)`)\n }\n const tool: ToolDefinition = {\n ...rest,\n name: toolName,\n execute: (args) => run(args),\n }\n disposers.push(ctx.tools.register(tool))\n }\n ctx.logger?.info(`agent-memory-hub-dsh: ${disposers.length} memory tools registered (hub: ${root})`)\n ctx.effect?.(() => () => {\n for (const dispose of disposers) dispose()\n }, name)\n}\n", "/** Error codes shared across core and transport. Transport translates these to\n * protocol-specific shapes; the codes themselves are part of the contract. */\nexport const ErrorCode = {\n E_HUB_NOT_INITIALIZED: 'E_HUB_NOT_INITIALIZED',\n E_NOT_FOUND: 'E_NOT_FOUND',\n E_VALIDATION: 'E_VALIDATION',\n E_CONFLICT: 'E_CONFLICT',\n E_LOCK_HELD: 'E_LOCK_HELD',\n E_APPROVAL_REQUIRED: 'E_APPROVAL_REQUIRED',\n E_READONLY: 'E_READONLY',\n} as const\n\nexport type ErrorCodeValue = (typeof ErrorCode)[keyof typeof ErrorCode]\n\nexport class HubError extends Error {\n readonly code: ErrorCodeValue\n readonly details?: Record<string, unknown>\n\n constructor(code: ErrorCodeValue, message: string, details?: Record<string, unknown>) {\n super(message)\n this.name = 'HubError'\n this.code = code\n this.details = details\n }\n}\n", "/** ISO-8601 timestamps with local offset, matching the predecessor's format\n * (e.g. 2026-11-15T16:41:52+08:00). All persisted timestamps use this shape. */\n\nexport function nowIso(): string {\n return new Date().toISOString().replace('Z', offsetString(new Date()))\n}\n\nfunction offsetString(date: Date): string {\n const minutes = -date.getTimezoneOffset()\n const sign = minutes >= 0 ? '+' : '-'\n const abs = Math.abs(minutes)\n const hh = String(Math.floor(abs / 60)).padStart(2, '0')\n const mm = String(abs % 60).padStart(2, '0')\n return `${sign}${hh}:${mm}`\n}\n\n/** Parse an ISO timestamp; returns epoch ms, or null when invalid/missing. */\nexport function parseIso(value: string | undefined): number | null {\n if (value === undefined || value === '') return null\n const ms = Date.parse(value)\n return Number.isNaN(ms) ? null : ms\n}\n", "import { randomUUID } from 'node:crypto'\nimport { ErrorCode, HubError } from './errors.js'\nimport type { KnowledgeType } from './types.js'\n\n/** ID prefixes per knowledge type (shared contract with dsh-memory-hub). */\nconst PREFIX: Record<KnowledgeType, string> = {\n decision: 'DEC',\n constraint: 'CON',\n knowledge: 'KNO',\n 'api-catalog': 'API',\n process: 'PRC',\n 'open-questions': 'OPQ',\n 'runtime-base': 'RTB',\n playbooks: 'PLB',\n assets: 'AST',\n}\n\nconst PENDING_PREFIX = 'PRO'\n\n/** Persisted per-type counters (records/sequences.json). */\nexport interface Sequences {\n [prefix: string]: number\n}\n\nexport function prefixFor(type: KnowledgeType): string {\n return PREFIX[type]\n}\n\n/** Next ID for a knowledge type. Mutates and persists the sequence file. */\nexport function nextKnowledgeId(\n seqDir: string,\n type: KnowledgeType,\n readSequences: (dir: string) => Sequences,\n writeSequences: (dir: string, seq: Sequences) => void,\n): string {\n const prefix = prefixFor(type)\n const seq = readSequences(seqDir)\n const next = (seq[prefix] ?? 0) + 1\n seq[prefix] = next\n writeSequences(seqDir, seq)\n return `${prefix}-${String(next).padStart(6, '0')}`\n}\n\n/** Next pending proposal ID (PRO-\u2026). */\nexport function nextProposalId(\n seqDir: string,\n readSequences: (dir: string) => Sequences,\n writeSequences: (dir: string, seq: Sequences) => void,\n): string {\n const seq = readSequences(seqDir)\n const next = (seq[PENDING_PREFIX] ?? 0) + 1\n seq[PENDING_PREFIX] = next\n writeSequences(seqDir, seq)\n return `${PENDING_PREFIX}-${String(next).padStart(6, '0')}`\n}\n\n/** Fresh fencing token for the writer lock (monotonicity comes from time+random). */\nexport function newLockToken(): string {\n return `lk-${Date.now().toString(36)}-${randomUUID().slice(0, 8)}`\n}\n\nexport function assertNonEmpty(value: string, field: string): string {\n if (value.trim() === '') throw new HubError(ErrorCode.E_VALIDATION, `\\`${field}\\` must not be empty`)\n return value\n}\n", "import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'\nimport { join } from 'node:path'\nimport { atomicWrite } from './atomic.js'\n\n/** Hub directory layout (storage contract). */\nexport const HUB_DIRS = ['knowledge', 'pending', 'history', 'records', 'journal'] as const\nexport const KNOWLEDGE_TYPES_DIR = [\n 'decision',\n 'constraint',\n 'knowledge',\n 'api-catalog',\n 'process',\n 'open-questions',\n 'runtime-base',\n 'playbooks',\n 'assets',\n] as const\nexport const HUB_CONFIG = 'hub.yaml'\nexport const HUB_README = 'MEMORY-HUB.md'\nexport const LEDGER_FILE = 'records/ledger.jsonl'\nexport const SEQUENCES_FILE = 'records/sequences.json'\nexport const LOCK_FILE = '.writer.lock'\n\nexport function isHubInitialized(root: string): boolean {\n return existsSync(join(root, 'knowledge')) && existsSync(join(root, LEDGER_FILE))\n}\n\nexport function knowledgeDir(root: string, type: string): string {\n return join(root, 'knowledge', type)\n}\n\nexport function historyDir(root: string, type: string): string {\n return join(root, 'history', type)\n}\n\nexport function pendingDir(root: string): string {\n return join(root, 'pending')\n}\n\nexport function journalDir(root: string): string {\n return join(root, 'journal')\n}\n\n/**\n * Initialize a hub directory. Idempotent: existing files are never touched\n * (fail-open for re-runs). Generates MEMORY-HUB.md explaining every folder's\n * writer/mutability/deletion semantics \u2014 except when a user README already\n * exists at that name (predecessor rule PRC-000009: never overwrite).\n */\nexport function initHub(root: string): { created: string[]; readme: 'written' | 'skipped-existing' } {\n const created: string[] = []\n for (const dir of HUB_DIRS) {\n const target = join(root, dir)\n if (!existsSync(target)) {\n mkdirSync(target, { recursive: true })\n created.push(dir)\n }\n }\n for (const type of KNOWLEDGE_TYPES_DIR) {\n const target = knowledgeDir(root, type)\n if (!existsSync(target)) mkdirSync(target, { recursive: true })\n }\n const records = join(root, 'records')\n if (!existsSync(join(records, 'sequences.json'))) {\n atomicWrite(join(records, 'sequences.json'), '{}\\n')\n }\n if (!existsSync(join(records, 'ledger.jsonl'))) {\n writeFileSync(join(records, 'ledger.jsonl'), '', 'utf8')\n }\n // Git-when-ready: a .gitignore written at init time so the day the hub is\n // pushed to a remote, derived indexes and machine-local secrets (serve\n // token, lock files) never land in the shared history. Idempotent: an\n // existing .gitignore is never overwritten (predecessor rule PRC-000009).\n if (!existsSync(join(root, '.gitignore'))) {\n atomicWrite(join(root, '.gitignore'), hubGitignoreContent())\n }\n let readme: 'written' | 'skipped-existing' = 'skipped-existing'\n const readmePath = join(root, HUB_README)\n if (!existsSync(readmePath)) {\n atomicWrite(readmePath, hubReadmeContent())\n readme = 'written'\n }\n if (!existsSync(join(root, HUB_CONFIG))) {\n atomicWrite(join(root, HUB_CONFIG), defaultHubConfig())\n }\n return { created, readme }\n}\n\n/** Load and parse hub.yaml (flat `key: value` / one-level sections). */\nexport function readHubConfig(root: string): Record<string, string> {\n const path = join(root, HUB_CONFIG)\n if (!existsSync(path)) return {}\n const raw = readFileSync(path, 'utf8')\n const out: Record<string, string> = {}\n for (const line of raw.split('\\n')) {\n const trimmed = line.trim()\n if (trimmed === '' || trimmed.startsWith('#')) continue\n const colon = trimmed.indexOf(':')\n if (colon === -1) continue\n out[trimmed.slice(0, colon).trim()] = trimmed.slice(colon + 1).trim()\n }\n return out\n}\n\nfunction defaultHubConfig(): string {\n return [\n '# agent-memory-hub configuration (plain text, diff-friendly).',\n '# workspaces auto-register on first use (ADR-0002); domains are optional.',\n 'version: 1',\n '# domains: [] # optional grouping: domainId -> member workspace ids',\n '# --- publish (ADR-0015): where approved entries go. APIs are yours to define.',\n '# publish.adapter: http # POST {entries:[...]} to publish.endpoint',\n '# publish.endpoint: https://memory-hub.example.internal/api/entries',\n '# publish.header.Authorization: Bearer <token>',\n '# publish.adapter: exec # run your own script; stdin = entries JSON',\n '# publish.script: publish-to-memory-hub.mjs',\n '# publish.adapter: none # (default) publishing disabled',\n '',\n ].join('\\n')\n}\n\nfunction hubGitignoreContent(): string {\n return `# agent-memory-hub \u2014 git \u4ED3\u5E93\u89C4\u5212\uFF08init \u65F6\u81EA\u52A8\u751F\u6210\uFF0C\u53EF\u6309\u9700\u8C03\u6574\uFF09\n#\n# \u539F\u5219\uFF1A\u6743\u5A01\u6570\u636E\u5168\u90E8\u63D0\u4EA4\uFF1B\u6D3E\u751F\u7F13\u5B58\u4E0E\u673A\u5668\u672C\u5730\u72B6\u6001\u4E00\u5F8B\u5FFD\u7565\u3002\n\n# \u2500\u2500 \u6D3E\u751F\u7F13\u5B58\uFF1A\u8FD0\u884C\u65F6\u81EA\u52A8\u91CD\u5EFA\uFF0C\u63D0\u4EA4\u53EA\u4F1A\u5236\u9020\u5408\u5E76\u51B2\u7A81 \u2500\u2500\nindex/\n\n# \u2500\u2500 \u673A\u5668\u672C\u5730\u72B6\u6001\uFF1A\u7EDD\u4E0D\u80FD\u8FDB\u5171\u4EAB\u5386\u53F2 \u2500\u2500\nrecords/.writer.lock\nrecords/server.json\nrecords/server-token\n\n# \u2500\u2500 \u5E38\u89C4\u7CFB\u7EDF\u566A\u58F0 \u2500\u2500\n.DS_Store\nThumbs.db\n`\n}\n\nfunction hubReadmeContent(): string {\n return `# MEMORY-HUB \u2014 \u76EE\u5F55\u8BF4\u660E\u4E66\n\n\u672C\u76EE\u5F55\u662F agent-memory-hub \u7684\u4E8B\u5B9E\u6E90\u3002\u6240\u6709\u5185\u5BB9\u90FD\u662F\u7EAF\u6587\u672C\uFF0C\u53EF\u7528 git \u7BA1\u7406\u3002\n\n| \u76EE\u5F55 | \u5185\u5BB9 | \u8C01\u5199 | \u53EF\u6539\u6027 | \u5220\u9664\u540E\u679C |\n| --- | --- | --- | --- | --- |\n| knowledge/ | \u5DF2\u6279\u51C6\u7684\u77E5\u8BC6\uFF08\u6309\u7C7B\u578B\u5206\u76EE\u5F55\uFF09 | \u53EA\u6709\"\u4EBA\u6279\u51C6\"\u8DEF\u5F84\uFF08commit\uFF09 | \u6761\u76EE\u6B63\u6587\u53EF\u7531\u4EBA\u76F4\u63A5\u7F16\u8F91\uFF1B\u5143\u6570\u636E\u6539\u52A8\u8BF7\u8D70\u5DE5\u5177 | \u8BE5\u7C7B\u77E5\u8BC6\u6D88\u5931\uFF1B\u7D22\u5F15\u53EF\u91CD\u5EFA\uFF0C\u6587\u4EF6\u4E0D\u53EF\u6062\u590D |\n| pending/ | \u6A21\u578B\u521B\u5EFA\u7684\u5019\u9009\uFF08PRO-*.md\uFF09 | \u6A21\u578B\uFF08propose\uFF09\u4E0E\u8403\u53D6\u5668 | \u4EBA\u53EF\u7F16\u8F91\u540E\u6279\u51C6\uFF1B\u53EF\u6574\u4F53\u5220\u9664 | \u5019\u9009\u4E22\u5931\uFF0C\u53EF\u91CD\u65B0\u751F\u6210 |\n| history/ | \u6BCF\u6B21\u7248\u672C\u53D8\u66F4\u7684\u539F\u6587\u5FEB\u7167 | commit/update \u81EA\u52A8\u5199 | **\u53EA\u8FFD\u52A0**\uFF0C\u8BF7\u52FF\u6539\u5199 | \u7248\u672C\u8FFD\u6EAF\u80FD\u529B\u4E22\u5931 |\n| records/ | ledger.jsonl\uFF08\u5BA1\u6279\u8D26\u672C\uFF09+ sequences.json\uFF08ID \u5E8F\u5217\uFF09 | \u5DE5\u5177\u81EA\u52A8 | **\u53EA\u8FFD\u52A0**\uFF08ledger\uFF09 | \u5BA1\u8BA1\u94FE\u65AD\u88C2\uFF0C\u6279\u51C6\u5386\u53F2\u4E0D\u53EF\u8BC1 |\n| journal/ | \u60C5\u666F\u5C42\uFF1A\u81EA\u52A8\u6355\u83B7\u7684\u4F1A\u8BDD\u6D41\u6C34 | \u5DE5\u5177\u81EA\u52A8 | \u53EF\u6574\u4F53\u4E22\u5F03 | \u65E0\u5F71\u54CD\uFF08\u53EF\u518D\u751F\u6210\uFF09\uFF0C\u4E0D\u5F71\u54CD knowledge |\n| .writer.lock | \u5199\u9501\u79DF\u7EA6\uFF08\u5FC3\u8DF3\u6587\u4EF6\uFF09 | \u5199\u9501\u81EA\u52A8 | \u52FF\u624B\u6539 | \u79DF\u7EA6\u8D85\u9F84\u81EA\u52A8\u56DE\u6536 |\n\n\u89C4\u5219\uFF1A\u6A21\u578B\u6C38\u8FDC\u4E0D\u80FD\u81EA\u6279\uFF1Bknowledge/ \u7684\u6BCF\u4E00\u6B21\u5199\u5165\u90FD\u5728 records/ledger.jsonl \u6709\u5BF9\u5E94\u8BB0\u5F55\u3002\n`\n}\n", "import { mkdirSync, renameSync, rmSync, writeFileSync } from 'node:fs'\nimport { dirname, join, parse } from 'node:path'\nimport { ErrorCode, HubError } from './errors.js'\n\n/**\n * Atomic write: write to a temp file in the same directory, then rename over\n * the target. Same-directory rename is atomic on NTFS/ext4/APFS. Never write\n * the final path directly (storage contract, rule 1).\n */\nexport function atomicWrite(filePath: string, content: string): void {\n const dir = dirname(filePath)\n mkdirSync(dir, { recursive: true })\n const base = parse(filePath).name\n const tmp = join(dir, `.${base}.${process.pid}.${Date.now()}.tmp`)\n try {\n writeFileSync(tmp, content, 'utf8')\n // Windows rename over an existing file fails; remove first (tiny window,\n // acceptable for a single-writer-locked store).\n try {\n rmSync(filePath, { force: true })\n } catch {\n // target did not exist\n }\n renameSync(tmp, filePath)\n } catch (error) {\n try {\n rmSync(tmp, { force: true })\n } catch {\n // best effort cleanup\n }\n const detail = error instanceof Error ? error.message : String(error)\n throw new HubError(ErrorCode.E_VALIDATION, `atomic write failed for ${filePath}: ${detail}`)\n }\n}\n", "import { existsSync, readFileSync } from 'node:fs'\nimport { join } from 'node:path'\nimport { atomicWrite } from './atomic.js'\nimport { LEDGER_FILE, SEQUENCES_FILE } from './hub.js'\nimport type { Sequences } from './ids.js'\n\n/**\n * Approval ledger \u2014 append-only JSONL. Every write into knowledge/ has a\n * corresponding record here: who, when, on what evidence (invariant 2).\n * Never rewritten, never compacted (storage contract rule 3).\n */\n\nexport type LedgerAction =\n | 'propose'\n | 'approve'\n | 'reject'\n | 'update'\n | 'deprecate'\n | 'delete'\n | 'register-workspace'\n | 'conflict-freeze'\n | 'publish'\n\n/**\n * Event-stream record (the predecessor ledger shape \u2014 type discriminates the\n * event; see docs/04-development/search-replay-2026-11-15.md appendix).\n * knowledge-lifecycle events carry ts/actor/action/id/version convenience\n * fields; harness events (citation.added, approval.missing, proposal.committed\u2026)\n * carry only type + their own payload.\n */\nexport interface LedgerRecord {\n type?: string\n ts?: string\n actor?: string\n action?: LedgerAction\n id?: string\n version?: number\n /** Evidence refs backing the decision (file:/session:/url:/note:). */\n source_refs?: string[]\n note?: string\n [key: string]: unknown\n}\n\nexport function ledgerPath(root: string): string {\n return join(root, LEDGER_FILE)\n}\n\n/** Append one record. The whole file is rewritten atomically (append = read+atomicWrite). */\nexport function appendLedger(path: string, record: LedgerRecord): void {\n const existing = existsSync(path) ? readFileSync(path, 'utf8') : ''\n atomicWrite(path, existing + `${JSON.stringify(record)}\\n`)\n}\n\nexport function readLedger(path: string): LedgerRecord[] {\n if (!existsSync(path)) return []\n return readFileSync(path, 'utf8')\n .split('\\n')\n .filter((line) => line.trim() !== '')\n .map((line) => JSON.parse(line) as LedgerRecord)\n}\n\nexport function readSequences(root: string): Sequences {\n const path = join(root, SEQUENCES_FILE)\n if (!existsSync(path)) return {}\n try {\n return JSON.parse(readFileSync(path, 'utf8')) as Sequences\n } catch {\n return {}\n }\n}\n\nexport function writeSequences(root: string, seq: Sequences): void {\n atomicWrite(join(root, SEQUENCES_FILE), `${JSON.stringify(seq, null, 2)}\\n`)\n}\n", "import { existsSync, readFileSync, rmSync, readdirSync } from 'node:fs'\nimport { join } from 'node:path'\nimport { atomicWrite } from './atomic.js'\nimport { ErrorCode, HubError } from './errors.js'\nimport { historyDir, knowledgeDir, pendingDir } from './hub.js'\nimport { nextKnowledgeId, nextProposalId } from './ids.js'\nimport { parseIso, nowIso } from './time.js'\nimport { parseKnowledgeFile, parseKnowledgeFrontmatter } from './frontmatter.js'\nimport type { LedgerRecord } from './ledger.js'\nimport type {\n KnowledgeFrontmatter,\n KnowledgeScope,\n KnowledgeStatus,\n KnowledgeType,\n} from './types.js'\n\n/**\n * Store: knowledge / pending / history CRUD. All writes are atomic; every\n * knowledge mutation snapshots the previous version into history/ (append-only)\n * and appends a ledger record (caller supplies the ledger callback).\n */\n\nexport interface SaveKnowledgeInput {\n type: KnowledgeType\n title: string\n summary: string\n scope: KnowledgeScope\n tags?: string[]\n body: string\n /** Existing entry id to update; omit to create a new one. */\n id?: string\n /** Expires-at ISO timestamp (aging / validity window). */\n expiresAt?: string\n sourceRefs?: string[]\n actor?: string\n}\n\nexport interface KnowledgeEntry {\n frontmatter: KnowledgeFrontmatter\n body: string\n path: string\n /** Epoch ms when the entry expires (aging), or null. */\n expiresAtMs: number | null\n /** True when status is deprecated or expiresAt has passed (soft-removed). */\n softRemoved: boolean\n}\n\nfunction entryPath(root: string, type: KnowledgeType, id: string): string {\n return join(knowledgeDir(root, type), `${id}.md`)\n}\n\nexport function renderKnowledgeMarkdown(fm: KnowledgeFrontmatter, body: string): string {\n const lines: string[] = ['---']\n lines.push(`id: ${fm.id}`)\n lines.push(`version: ${fm.version}`)\n lines.push(`type: ${fm.type}`)\n lines.push(`status: ${fm.status}`)\n lines.push(`title: ${fm.title}`)\n lines.push(`summary: ${fm.summary}`)\n if (fm.scope.level === 'global') {\n lines.push('scope:')\n lines.push(' level: global')\n } else if (fm.scope.level === 'domain') {\n lines.push('scope:')\n lines.push(' level: domain')\n lines.push(` domainId: ${fm.scope.domainId}`)\n } else {\n lines.push('scope:')\n lines.push(' level: project')\n lines.push(` workspaceId: ${fm.scope.workspaceId}`)\n }\n lines.push(`tags: [${fm.tags.join(', ')}]`)\n if (fm.created !== undefined) lines.push(`created: ${fm.created}`)\n if (fm.updated !== undefined) lines.push(`updated: ${fm.updated}`)\n if (fm.last_verified !== undefined) lines.push(`last_verified: ${fm.last_verified}`)\n for (const [key, value] of Object.entries(fm.extra)) {\n lines.push(`${key}: ${typeof value === 'string' ? value : JSON.stringify(value)}`)\n }\n lines.push('---')\n lines.push('')\n lines.push(body.trimEnd())\n lines.push('')\n return lines.join('\\n')\n}\n\n/** Read one knowledge entry by id (searches all type dirs). */\nexport function getEntry(root: string, id: string): KnowledgeEntry {\n for (const type of readdirSync(join(root, 'knowledge'))) {\n const path = entryPath(root, type as KnowledgeType, id)\n if (!existsSync(path)) continue\n const raw = readFileSync(path, 'utf8')\n const parsed = parseKnowledgeFile(raw)\n return toEntry(parsed.frontmatter, parsed.body, path)\n }\n throw new HubError(ErrorCode.E_NOT_FOUND, `knowledge entry not found: ${id}`, { id })\n}\n\nfunction toEntry(fm: KnowledgeFrontmatter, body: string, path: string): KnowledgeEntry {\n const expiresRaw = fm.extra['expires_at']\n const expiresAtMs = parseIso(typeof expiresRaw === 'string' ? expiresRaw : undefined)\n return {\n frontmatter: fm,\n body,\n path,\n expiresAtMs,\n softRemoved: fm.status === 'deprecated' || (expiresAtMs !== null && expiresAtMs <= Date.now()),\n }\n}\n\n/** List all entries; soft-removed included unless includeSoftRemoved=false. */\nexport function listEntries(root: string, options?: { includeSoftRemoved?: boolean }): KnowledgeEntry[] {\n const out: KnowledgeEntry[] = []\n const typesRoot = join(root, 'knowledge')\n if (!existsSync(typesRoot)) return out\n for (const type of readdirSync(typesRoot)) {\n const dir = knowledgeDir(root, type)\n for (const file of readdirSync(dir)) {\n if (!file.endsWith('.md')) continue\n const path = join(dir, file)\n try {\n const parsed = parseKnowledgeFile(readFileSync(path, 'utf8'))\n const entry = toEntry(parsed.frontmatter, parsed.body, path)\n if (options?.includeSoftRemoved !== true && entry.softRemoved) continue\n out.push(entry)\n } catch {\n // Unreadable entry: skip, never break listing (index rebuildable).\n }\n }\n }\n return out\n}\n\n/** Title-level conflict detection: same title among accepted entries. */\nexport function findTitleConflict(root: string, title: string, excludeId?: string): KnowledgeEntry | null {\n const hit = listEntries(root).find(\n (entry) => entry.frontmatter.title === title && entry.frontmatter.id !== excludeId,\n )\n return hit ?? null\n}\n\n/**\n * Create or update a knowledge entry. Creates are caller-authorized (the human\n * approval already happened \u2014 this function is the post-approval write path).\n * Updates snapshot the previous version into history/ first.\n */\nexport function commitKnowledge(\n root: string,\n input: SaveKnowledgeInput,\n helpers: {\n nowIsoValue?: string\n readSequences: (root: string) => Record<string, number>\n writeSequences: (root: string, seq: Record<string, number>) => void\n appendLedger: (root: string, record: LedgerRecord) => void\n },\n): { id: string; version: number; path: string } {\n const ts = helpers.nowIsoValue ?? nowIso()\n if (input.id === undefined) {\n // create\n const conflict = findTitleConflict(root, input.title)\n if (conflict !== null) {\n throw new HubError(ErrorCode.E_CONFLICT, `an accepted entry with the same title exists: ${conflict.frontmatter.id}`, {\n existingId: conflict.frontmatter.id,\n existingTitle: conflict.frontmatter.title,\n })\n }\n const id = nextKnowledgeId(root, input.type, helpers.readSequences, helpers.writeSequences)\n const fm: KnowledgeFrontmatter = {\n id,\n version: 1,\n type: input.type,\n status: 'accepted',\n title: input.title,\n summary: input.summary,\n scope: input.scope,\n tags: input.tags ?? [],\n created: ts,\n updated: ts,\n last_verified: ts,\n extra: input.expiresAt !== undefined ? { expires_at: input.expiresAt } : {},\n }\n const path = entryPath(root, input.type, id)\n atomicWrite(path, renderKnowledgeMarkdown(fm, input.body))\n helpers.appendLedger(root, {\n ts,\n actor: input.actor ?? 'human',\n action: 'approve',\n id,\n version: 1,\n source_refs: input.sourceRefs,\n })\n return { id, version: 1, path }\n }\n // Explicit id: ADR-0012 cross-hub upsert. When the id does not exist\n // locally yet, it is created AS that id (keeps hub-to-hub identity\n // stable); otherwise it is the usual version upgrade.\n let previous: { frontmatter: KnowledgeFrontmatter; path: string; body: string }\n try {\n const found = getEntry(root, input.id)\n previous = { frontmatter: found.frontmatter, path: found.path, body: found.body }\n } catch {\n const fm: KnowledgeFrontmatter = {\n id: input.id,\n version: 1,\n type: input.type,\n status: 'accepted',\n title: input.title,\n summary: input.summary,\n scope: input.scope,\n tags: input.tags ?? [],\n created: ts,\n updated: ts,\n last_verified: ts,\n extra: input.expiresAt !== undefined ? { expires_at: input.expiresAt } : {},\n }\n const path = entryPath(root, input.type, input.id)\n atomicWrite(path, renderKnowledgeMarkdown(fm, input.body))\n helpers.appendLedger(root, {\n ts,\n actor: input.actor ?? 'human',\n action: 'approve',\n id: input.id,\n version: 1,\n source_refs: input.sourceRefs,\n })\n return { id: input.id, version: 1, path }\n }\n const prevFm = previous.frontmatter\n if (prevFm.type !== input.type) {\n throw new HubError(ErrorCode.E_VALIDATION, `type mismatch for ${input.id}: ${prevFm.type} \u2260 ${input.type}`)\n }\n const historyPath = join(historyDir(root, prevFm.type), `${prevFm.id}@v${prevFm.version}.md`)\n atomicWrite(historyPath, readFileSync(previous.path, 'utf8'))\n const fm: KnowledgeFrontmatter = {\n ...prevFm,\n version: prevFm.version + 1,\n title: input.title,\n summary: input.summary,\n tags: input.tags ?? prevFm.tags,\n updated: ts,\n last_verified: ts,\n extra: input.expiresAt !== undefined ? { ...prevFm.extra, expires_at: input.expiresAt } : prevFm.extra,\n }\n atomicWrite(previous.path, renderKnowledgeMarkdown(fm, input.body))\n helpers.appendLedger(root, {\n ts,\n actor: input.actor ?? 'human',\n action: 'update',\n id: prevFm.id,\n version: fm.version,\n source_refs: input.sourceRefs,\n })\n return { id: prevFm.id, version: fm.version, path: previous.path }\n}\n\n/** Soft-remove: status=deprecated + ledger record. Physical delete is explicit-only. */\nexport function deprecateEntry(\n root: string,\n id: string,\n reason: string,\n helpers: {\n nowIsoValue?: string\n appendLedger: (root: string, record: LedgerRecord) => void\n },\n): void {\n const entry = getEntry(root, id)\n const ts = helpers.nowIsoValue ?? nowIso()\n const fm: KnowledgeFrontmatter = { ...entry.frontmatter, status: 'deprecated', updated: ts }\n atomicWrite(entry.path, renderKnowledgeMarkdown(fm, entry.body))\n helpers.appendLedger(root, {\n ts,\n actor: 'human',\n action: 'deprecate',\n id,\n version: entry.frontmatter.version,\n note: reason,\n })\n}\n\n/** Hard delete (GDPR path): explicit caller authorization required; ledger first, then unlink. */\nexport function hardDeleteEntry(\n root: string,\n id: string,\n reason: string,\n helpers: {\n nowIsoValue?: string\n appendLedger: (root: string, record: LedgerRecord) => void\n },\n): void {\n const entry = getEntry(root, id)\n const ts = helpers.nowIsoValue ?? nowIso()\n helpers.appendLedger(root, {\n ts,\n actor: 'human',\n action: 'delete',\n id,\n version: entry.frontmatter.version,\n note: reason,\n })\n rmSync(entry.path, { force: true })\n}\n\n/** Create a pending candidate (models may do this; humans approve via commitKnowledge).\n * `supersedes` names an existing entry this proposal re-extracts: approving it\n * bumps that entry's version instead of creating a duplicate. */\nexport function createProposal(\n root: string,\n input: Omit<SaveKnowledgeInput, 'id'> & { sourceRefs: string[]; supersedes?: string[]; origin?: string; originId?: string },\n helpers: {\n nowIsoValue?: string\n readSequences: (root: string) => Record<string, number>\n writeSequences: (root: string, seq: Record<string, number>) => void\n appendLedger: (root: string, record: LedgerRecord) => void\n },\n): { id: string; path: string } {\n const ts = helpers.nowIsoValue ?? nowIso()\n const proposalId = nextProposalId(root, helpers.readSequences, helpers.writeSequences)\n const fm: KnowledgeFrontmatter = {\n id: proposalId,\n version: 1,\n type: input.type,\n status: 'candidate',\n title: input.title,\n summary: input.summary,\n scope: input.scope,\n tags: input.tags ?? [],\n created: ts,\n updated: ts,\n extra: {\n source_refs: input.sourceRefs.join(' '),\n ...(input.supersedes !== undefined && input.supersedes.length > 0 ? { supersedes: input.supersedes.join(' ') } : {}),\n ...(input.origin !== undefined ? { origin: input.origin } : {}),\n ...(input.originId !== undefined ? { origin_id: input.originId } : {}),\n },\n }\n const path = join(pendingDir(root), `${proposalId}.md`)\n atomicWrite(path, renderKnowledgeMarkdown(fm, input.body))\n helpers.appendLedger(root, {\n ts,\n actor: input.actor ?? 'model',\n action: 'propose',\n id: proposalId,\n source_refs: input.sourceRefs,\n ...(input.supersedes !== undefined && input.supersedes.length > 0 ? { supersedes: input.supersedes } : {}),\n })\n return { id: proposalId, path }\n}\n\n/** List pending candidates. */\nexport function listProposals(root: string): Array<{ id: string; frontmatter: KnowledgeFrontmatter; path: string }> {\n const dir = pendingDir(root)\n if (!existsSync(dir)) return []\n const out: Array<{ id: string; frontmatter: KnowledgeFrontmatter; path: string }> = []\n for (const file of readdirSync(dir)) {\n if (!file.endsWith('.md')) continue\n const path = join(dir, file)\n try {\n const fm = parseKnowledgeFrontmatter(readFileSync(path, 'utf8'), { context: 'proposal' })\n out.push({ id: fm.id, frontmatter: fm, path })\n } catch {\n // skip unreadable candidate\n }\n }\n return out\n}\n\n/** All statuses the store understands. */\nexport const STATUSES: readonly KnowledgeStatus[] = ['candidate', 'accepted', 'rejected', 'superseded', 'deprecated']\n", "import type {\n KnowledgeFrontmatter,\n KnowledgeScope,\n KnowledgeStatus,\n KnowledgeType,\n} from './types.js'\n\n/**\n * Minimal zero-dependency YAML frontmatter parser for the hub-directory\n * knowledge format. This is a contract implementation: it must parse exactly\n * what dsh-memory-hub writes (single-level scalars, inline arrays, and the\n * nested `scope` object), and preserve unknown keys verbatim.\n *\n * Deliberately NOT a general YAML parser \u2014 see invariant 3 (plain text) and\n * principle 6 (zero dependencies). The contract tests in tests/format.test.ts\n * lock the supported surface; extend the parser only together with those tests.\n */\n\nconst KNOWLEDGE_TYPES: readonly KnowledgeType[] = [\n 'decision',\n 'constraint',\n 'knowledge',\n 'api-catalog',\n 'process',\n 'open-questions',\n 'runtime-base',\n 'playbooks',\n 'assets',\n]\n\nconst KNOWLEDGE_STATUSES: readonly KnowledgeStatus[] = [\n 'candidate',\n 'accepted',\n 'rejected',\n 'superseded',\n 'deprecated',\n]\n\nconst FENCED_DELIMITER = '---'\n\n/**\n * Extract the leading frontmatter block (between the first two `---` lines).\n * Returns null when the file does not start with a frontmatter block.\n */\nexport function splitFrontmatter(raw: string): { yaml: string; body: string } | null {\n if (!raw.startsWith(FENCED_DELIMITER)) return null\n const firstNewline = raw.indexOf('\\n')\n if (firstNewline === -1) return null\n const opener = raw.slice(0, firstNewline).trim()\n if (opener !== FENCED_DELIMITER) return null\n const rest = raw.slice(firstNewline + 1)\n const closing = findClosingLine(rest)\n if (closing === -1) return null\n const yaml = rest.slice(0, closing)\n const body = rest.slice(closing + FENCED_DELIMITER.length).replace(/^\\n/, '')\n return { yaml, body: body.trim() }\n}\n\nfunction findClosingLine(text: string): number {\n let offset = 0\n for (const line of text.split('\\n')) {\n if (line.trim() === FENCED_DELIMITER) return offset\n offset += line.length + 1\n }\n return -1\n}\n\n/** Parse one scalar value: quoted/unquoted string, number, boolean. */\nfunction parseScalar(value: string): string | number | boolean {\n const trimmed = value.trim()\n if (\n (trimmed.startsWith('\"') && trimmed.endsWith('\"') && trimmed.length >= 2) ||\n (trimmed.startsWith(\"'\") && trimmed.endsWith(\"'\") && trimmed.length >= 2)\n ) {\n return trimmed.slice(1, -1)\n }\n if (trimmed === 'true') return true\n if (trimmed === 'false') return false\n const num = Number(trimmed)\n if (trimmed !== '' && Number.isFinite(num) && /^-?\\d+(\\.\\d+)?$/.test(trimmed)) return num\n return trimmed\n}\n\n/** Parse an inline array: `[a, b, c]` or an empty `[]`. */\nfunction parseInlineArray(value: string): string[] {\n const inner = value.trim().slice(1, -1).trim()\n if (inner === '') return []\n return inner.split(',').map((item) => String(parseScalar(item)))\n}\n\nfunction parseScope(lines: string[], start: number): { scope: KnowledgeScope; next: number } {\n // Nested object under `scope:` \u2014 exactly two indented keys in the contract:\n // level plus domainId|workspaceId.\n const scopeLines: string[] = []\n let index = start\n while (index < lines.length) {\n const line = lines[index]\n if (line === undefined) break\n if (line.trim() === '' || /^\\S/.test(line)) break\n scopeLines.push(line.trim())\n index += 1\n }\n const entries = new Map<string, string>()\n for (const line of scopeLines) {\n const colon = line.indexOf(':')\n if (colon === -1) continue\n entries.set(line.slice(0, colon).trim(), line.slice(colon + 1).trim())\n }\n const level = entries.get('level')\n let scope: KnowledgeScope = { level: 'global' }\n if (level === 'domain' && entries.get('domainId')) {\n scope = { level: 'domain', domainId: entries.get('domainId') as string }\n } else if (level === 'project' && entries.get('workspaceId')) {\n scope = { level: 'project', workspaceId: entries.get('workspaceId') as string }\n }\n return { scope, next: index }\n}\n\n/**\n * Parse a knowledge file's frontmatter into the contract type.\n * Throws with a descriptive message on contract violations (id/type/status\n * missing or invalid) \u2014 the caller decides how to surface the error.\n *\n * `context: 'proposal'` relaxes the contract for pending-proposal files:\n * predecessor-era proposals carry `status: pending` and no version (assigned\n * at commit time), both of which are legacy aliases mapped here.\n */\nexport function parseKnowledgeFrontmatter(\n raw: string,\n options?: { context?: 'entry' | 'proposal' },\n): KnowledgeFrontmatter {\n const split = splitFrontmatter(raw)\n if (split === null) {\n throw new Error('knowledge file must start with a `---` frontmatter block')\n }\n const lines = split.yaml.split('\\n')\n const scalars = new Map<string, string | number | boolean>()\n const extra: Record<string, unknown> = {}\n let scope: KnowledgeScope = { level: 'global' }\n let index = 0\n while (index < lines.length) {\n const line = lines[index]\n if (line === undefined || line.trim() === '' || line.trim().startsWith('#')) {\n index += 1\n continue\n }\n if (/^\\S/.test(line)) {\n const colon = line.indexOf(':')\n if (colon === -1) {\n index += 1\n continue\n }\n const key = line.slice(0, colon).trim()\n const value = line.slice(colon + 1).trim()\n if (key === 'scope') {\n if (value === '') {\n const parsed = parseScope(lines, index + 1)\n scope = parsed.scope\n index = parsed.next\n continue\n }\n scope = parseInlineArrayOrScalarAsScope(value)\n index += 1\n continue\n }\n if (key === 'tags' || key === 'source_refs') {\n if (value === '') {\n // Legacy block-style list: `key:` followed by indented `- item` lines.\n const items: string[] = []\n let cursor = index + 1\n while (cursor < lines.length) {\n const item = lines[cursor]\n if (item === undefined || !/^\\s+-\\s/.test(item)) break\n items.push(item.replace(/^\\s+-\\s*/, '').trim())\n cursor += 1\n }\n if (items.length > 0) {\n if (key === 'tags') {\n // Re-encode into the inline `[a, b]` convention parseInlineArray expects.\n scalars.set('tags', `[${items.join(', ')}]`)\n } else {\n // Match the renderer's single-line convention (join with spaces).\n const joined = items.join(' ')\n scalars.set('source_refs', joined)\n extra['source_refs'] = joined\n }\n index = cursor\n continue\n }\n }\n const parsedValue = value === '[]' ? '[]' : parseScalar(value)\n scalars.set(key, parsedValue)\n if (key === 'source_refs') extra['source_refs'] = parsedValue\n index += 1\n continue\n }\n const parsed = parseScalar(value)\n scalars.set(key, parsed)\n extra[key] = parsed\n index += 1\n continue\n }\n index += 1\n }\n\n const id = scalars.get('id')\n if (typeof id !== 'string' || id === '') throw new Error('frontmatter missing `id`')\n const type = scalars.get('type')\n if (typeof type !== 'string' || !KNOWLEDGE_TYPES.includes(type as KnowledgeType)) {\n throw new Error(`frontmatter has invalid \\`type\\`: ${String(type)}`)\n }\n const rawStatus = scalars.get('status')\n // Legacy alias: predecessor-era pending proposals carry `status: pending` \u2014\n // the same concept as the new `candidate` status.\n const status = rawStatus === 'pending' ? 'candidate' : rawStatus\n if (typeof status !== 'string' || !KNOWLEDGE_STATUSES.includes(status as KnowledgeStatus)) {\n throw new Error(`frontmatter has invalid \\`status\\`: ${String(status)}`)\n }\n const versionRaw = scalars.get('version')\n // Proposal context: predecessor-era pending files carry no version \u2014 the\n // version is assigned at commit time, so default to 1.\n const version =\n typeof versionRaw === 'number'\n ? versionRaw\n : options?.context === 'proposal'\n ? 1\n : (undefined as unknown as number)\n if (typeof version !== 'number') throw new Error('frontmatter missing numeric `version`')\n const title = scalars.get('title')\n if (typeof title !== 'string' || title === '') throw new Error('frontmatter missing `title`')\n const summary = scalars.get('summary')\n if (typeof summary !== 'string') throw new Error('frontmatter missing `summary`')\n const tagsRaw = scalars.get('tags')\n const tags = typeof tagsRaw === 'string' && tagsRaw !== '[]'\n ? parseInlineArray(tagsRaw)\n : typeof tagsRaw === 'string'\n ? []\n : []\n\n // Contract keys are hoisted into their typed fields; unknown keys stay in extra.\n for (const contractKey of [\n 'id',\n 'version',\n 'type',\n 'status',\n 'title',\n 'summary',\n 'created',\n 'updated',\n 'last_verified',\n ]) {\n delete extra[contractKey]\n }\n\n return {\n id,\n version,\n type: type as KnowledgeType,\n status: status as KnowledgeStatus,\n title,\n summary,\n scope,\n tags,\n // Optional keys are omitted (never `undefined`) so parsed frontmatter is\n // lossless-JSON safe for host tool outputs, even on legacy entries that\n // predate these fields (old format kept timestamps in extra.*_at).\n ...(asOptionalString(scalars.get('created')) !== undefined\n ? { created: asOptionalString(scalars.get('created')) }\n : {}),\n ...(asOptionalString(scalars.get('updated')) !== undefined\n ? { updated: asOptionalString(scalars.get('updated')) }\n : {}),\n ...(asOptionalString(scalars.get('last_verified')) !== undefined\n ? { last_verified: asOptionalString(scalars.get('last_verified')) }\n : {}),\n extra,\n }\n}\n\nfunction asOptionalString(value: string | number | boolean | undefined): string | undefined {\n return typeof value === 'string' && value !== '' ? value : undefined\n}\n\nfunction parseInlineArrayOrScalarAsScope(value: string): KnowledgeScope {\n // Legacy bare shorthand: `scope: project:<id>` / `scope: domain:<id>` / `scope: global`.\n const bare = /^(global|domain:([\\w.-]+)|project:([\\w.-]+))$/.exec(value)\n if (bare !== null) {\n if (bare[1] === 'global') return { level: 'global' }\n if (bare[2] !== undefined) return { level: 'domain', domainId: bare[2] }\n if (bare[3] !== undefined) return { level: 'project', workspaceId: bare[3] }\n }\n // Accept `{level: global}` style inline maps for the global case only.\n if (/level:\\s*global/.test(value)) return { level: 'global' }\n if (/level:\\s*domain/.test(value)) {\n const domainId = /domainId:\\s*([\\w.-]+)/.exec(value)?.[1]\n if (domainId) return { level: 'domain', domainId }\n }\n if (/level:\\s*project/.test(value)) {\n const workspaceId = /workspaceId:\\s*([\\w.-]+)/.exec(value)?.[1]\n if (workspaceId) return { level: 'project', workspaceId }\n }\n return { level: 'global' }\n}\n\n/** Parse a full knowledge file (frontmatter + body). */\nexport function parseKnowledgeFile(raw: string): { frontmatter: KnowledgeFrontmatter; body: string } {\n const split = splitFrontmatter(raw)\n if (split === null) throw new Error('knowledge file must start with a `---` frontmatter block')\n return { frontmatter: parseKnowledgeFrontmatter(raw), body: split.body }\n}\n", "import { execFileSync } from 'node:child_process'\nimport { basename, isAbsolute, resolve } from 'node:path'\nimport type { KnowledgeScope } from './types.js'\n\n/**\n * Workspace identity resolution (ADR-0002, zero-config):\n * 1. explicit --workspace argument (human-specified, highest priority)\n * 2. git origin remote URL (stable across subdirs & worktrees)\n * 3. canonical project directory (git root, else cwd)\n * 4. synthetic workspace with exact=false (honest fallback)\n * First use auto-registers (persisted by the caller on the write path);\n * resolution itself is pure/read-only.\n */\n\nexport interface ResolvedWorkspace {\n /** Stable workspace id (slug of origin owner/repo or directory name). */\n workspaceId: string\n /** Human-editable display name. */\n name: string\n /** Canonical absolute path this identity was derived from. */\n path: string\n /** Git origin URL when available. */\n origin?: string\n /** false when the identity is a synthetic fallback (honest labeling). */\n exact: boolean\n}\n\n/** Run a git command; return stdout or null on any failure (git missing, not a repo). */\nexport function git(args: string[], cwd: string): string | null {\n try {\n const out = execFileSync('git', args, { cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], timeout: 5000 })\n return out.trim() === '' ? null : out.trim()\n } catch {\n return null\n }\n}\n\n/** Slugify an origin URL (\"git@github.com:owner/repo.git\" -> \"owner-repo\"). */\nexport function workspaceIdFromOrigin(origin: string): string {\n const cleaned = origin\n .replace(/^git@[^:]+:/, '')\n .replace(/^https?:\\/\\/[^/]+\\//, '')\n .replace(/\\.git$/, '')\n .toLowerCase()\n const slug = cleaned.replace(/[^a-z0-9._-]+/g, '-').replace(/^-+|-+$/g, '')\n return slug === '' ? 'workspace' : slug\n}\n\nexport function slugifyDir(path: string): string {\n // Split on BOTH separators explicitly: path.basename is platform-aware\n // (Windows-only '\\' on win32, '/' on POSIX) and hubs legitimately carry\n // cross-platform path strings.\n const lastSegment = path.split(/[\\\\/]/).filter(Boolean).pop() ?? ''\n const slug = lastSegment\n .toLowerCase()\n .replace(/[^a-z0-9._-]+/g, '-')\n .replace(/^-+|-+$/g, '')\n return slug === '' ? 'workspace' : slug\n}\n\n/** Find the git root upward from dir; null when not inside a repository. */\nexport function gitRoot(dir: string): string | null {\n const top = git(['rev-parse', '--show-toplevel'], dir)\n return top !== null && isAbsolute(top) ? resolve(top) : null\n}\n\n/** Resolve workspace identity for a working directory (pure \u2014 never writes). */\nexport function resolveWorkspace(dir: string, explicitId?: string): ResolvedWorkspace {\n const abs = resolve(dir)\n if (explicitId !== undefined && explicitId !== '') {\n return { workspaceId: explicitId, name: explicitId, path: abs, exact: true }\n }\n const origin = git(['remote', 'get-url', 'origin'], abs)\n if (origin !== null) {\n return { workspaceId: workspaceIdFromOrigin(origin), name: basename(abs), path: abs, origin, exact: true }\n }\n const root = gitRoot(abs)\n const canonical = root ?? abs\n return { workspaceId: slugifyDir(canonical), name: basename(canonical), path: canonical, exact: true }\n}\n\n/** Scope for read/write from a resolved workspace. */\nexport function scopeForWorkspace(workspaceId: string): KnowledgeScope {\n return { level: 'project', workspaceId }\n}\n\n/** Registered workspace record (persisted in hub.yaml workspaces table). */\nexport interface RegisteredWorkspace {\n workspaceId: string\n name: string\n origin?: string\n registeredAt: string\n}\n\n/** Load the workspaces table from hub.yaml's flat `workspaces.<id>.name` rows. */\nexport function readRegisteredWorkspaces(config: Record<string, string>): RegisteredWorkspace[] {\n const out: RegisteredWorkspace[] = []\n for (const [key, value] of Object.entries(config)) {\n const match = /^workspaces\\.([.\\w-]+)\\.name$/.exec(key)\n if (match?.[1] === undefined) continue\n const id = match[1]\n out.push({\n workspaceId: id,\n name: value,\n origin: config[`workspaces.${id}.origin`],\n registeredAt: config[`workspaces.${id}.registeredAt`] ?? '',\n })\n }\n return out\n}\n\n/** Persist (upsert) a workspace row into hub.yaml. Caller must hold the write lock. */\nexport function registerWorkspace(\n hubRoot: string,\n ws: ResolvedWorkspace,\n nowIso: () => string,\n readConfig: (root: string) => Record<string, string>,\n writeConfig: (root: string, content: string) => void,\n): void {\n const config = readConfig(hubRoot)\n const nameKey = `workspaces.${ws.workspaceId}.name`\n if (config[nameKey] !== undefined) {\n // Already registered \u2014 keep as-is (name edits go through the panel/CLI).\n return\n }\n // Append the new row(s) instead of rewriting the whole file (keeps comments).\n const lines: string[] = [`workspaces.${ws.workspaceId}.name: ${ws.name}`]\n if (ws.origin !== undefined) lines.push(`workspaces.${ws.workspaceId}.origin: ${ws.origin}`)\n lines.push(`workspaces.${ws.workspaceId}.registeredAt: ${nowIso()}`)\n writeConfig(hubRoot, `${lines.join('\\n')}\\n`)\n}\n", "import { existsSync, readFileSync, rmSync, statSync } from 'node:fs'\nimport { join } from 'node:path'\nimport { randomUUID } from 'node:crypto'\nimport { atomicWrite } from './atomic.js'\nimport { ErrorCode, HubError } from './errors.js'\nimport { LOCK_FILE } from './hub.js'\n\n/**\n * Writer lock with lease + fencing token (predecessor ADR-0009, reimplemented):\n * a stuck writer is recovered by heartbeat age, not by manual lock deletion.\n * Old writers holding an older token degrade to read-only when they see a\n * newer token. All writers of one hub share this single process-agnostic file.\n */\n\nexport interface WriterLock {\n pid: number\n host: string\n acquiredAt: string\n heartbeatAt: string\n /** Monotonic fencing token: `lk-<base36 ms>-<rand>`; later acquirer wins. */\n token: string\n}\n\nexport interface LockOptions {\n heartbeatMs?: number\n staleMs?: number\n now?: () => number\n host?: string\n}\n\nconst DEFAULT_HEARTBEAT_MS = 15_000\nconst DEFAULT_STALE_MS = 45_000\n\nfunction lockPath(root: string): string {\n return join(root, LOCK_FILE)\n}\n\nexport function readLock(root: string): WriterLock | null {\n const path = lockPath(root)\n if (!existsSync(path)) return null\n try {\n return JSON.parse(readFileSync(path, 'utf8')) as WriterLock\n } catch {\n // Corrupt lock file: treat as absent (recovery path, predecessor lesson).\n return null\n }\n}\n\nfunction lockAgeMs(lock: WriterLock, now: number): number {\n const parsed = Date.parse(lock.heartbeatAt)\n return Number.isNaN(parsed) ? Number.POSITIVE_INFINITY : now - parsed\n}\n\n/** True when the lock exists and its heartbeat is younger than staleMs. */\nexport function isLockFresh(root: string, options?: LockOptions): boolean {\n const lock = readLock(root)\n if (lock === null) return false\n const now = (options?.now ?? Date.now)()\n return lockAgeMs(lock, now) < (options?.staleMs ?? DEFAULT_STALE_MS)\n}\n\nexport interface AcquireResult {\n ok: boolean\n lock?: WriterLock\n /** When !ok, the fresh lock held by someone else (readonly consumers surface this). */\n holder?: WriterLock\n}\n\n/**\n * Acquire the writer lease. Succeeds when no lock exists, or the existing\n * lock's heartbeat is older than staleMs (stuck writer auto-recovery).\n */\nexport function acquireLock(root: string, options?: LockOptions): AcquireResult {\n const now = (options?.now ?? Date.now)()\n const existing = readLock(root)\n if (existing !== null && lockAgeMs(existing, now) < (options?.staleMs ?? DEFAULT_STALE_MS)) {\n return { ok: false, holder: existing }\n }\n const lock: WriterLock = {\n pid: process.pid,\n host: options?.host ?? process.env.COMPUTERNAME ?? process.env.HOSTNAME ?? 'unknown-host',\n acquiredAt: new Date(now).toISOString(),\n heartbeatAt: new Date(now).toISOString(),\n token: `lk-${now.toString(36)}-${randomUUID().slice(0, 8)}`,\n }\n atomicWrite(lockPath(root), `${JSON.stringify(lock, null, 2)}\\n`)\n return { ok: true, lock }\n}\n\n/** Refresh the heartbeat; only succeeds while our own token is current. */\nexport function heartbeatLock(root: string, token: string, options?: LockOptions): boolean {\n const existing = readLock(root)\n if (existing === null || existing.token !== token) return false\n const now = (options?.now ?? Date.now)()\n existing.heartbeatAt = new Date(now).toISOString()\n atomicWrite(lockPath(root), `${JSON.stringify(existing, null, 2)}\\n`)\n return true\n}\n\n/** Release only when we still hold the current token (never delete a successor's lock). */\nexport function releaseLock(root: string, token: string): boolean {\n const existing = readLock(root)\n if (existing === null || existing.token !== token) return false\n rmSync(lockPath(root), { force: true })\n return true\n}\n\n/**\n * Fencing check for a write performed under `token`: throws E_READONLY when a\n * newer writer has taken over (stale token). Call before every store mutation.\n */\nexport function assertFencing(root: string, token: string, options?: LockOptions): void {\n const existing = readLock(root)\n if (existing === null) return\n if (existing.token !== token) {\n throw new HubError(ErrorCode.E_READONLY, 'writer lease superseded by a newer writer (fencing token mismatch)', {\n currentToken: existing.token,\n holder: existing.host,\n })\n }\n const now = (options?.now ?? Date.now)()\n if (lockAgeMs(existing, now) >= (options?.staleMs ?? DEFAULT_STALE_MS)) {\n throw new HubError(ErrorCode.E_READONLY, 'writer lease expired (heartbeat overdue)', {\n heartbeatAt: existing.heartbeatAt,\n })\n }\n}\n\n/** File-level diagnostics (status tooling). Never emits `undefined` values \u2014\n * host tool outputs are lossless-JSON validated, so optional keys are omitted. */\nexport function lockInfo(\n root: string,\n options?: LockOptions,\n): { held: boolean; fresh: boolean; lock?: WriterLock; sizeBytes?: number } {\n const lock = readLock(root)\n if (lock === null) return { held: false, fresh: false }\n const path = lockPath(root)\n return {\n held: true,\n fresh: isLockFresh(root, options),\n lock,\n ...(existsSync(path) ? { sizeBytes: statSync(path).size } : {}),\n }\n}\n", "import { listEntries } from './store.js'\nimport type { KnowledgeEntry } from './store.js'\nimport type { KnowledgeScope } from './types.js'\n\n/**\n * Search: CJK bigram + ASCII word tokenization over an in-memory inverted\n * index with BM25-lite scoring and scope-ancestor filtering.\n *\n * Design rules (V2): directory-scoped before whole-index; L0/L1/L2 progressive\n * loading (abstract \u2192 overview \u2192 details); min_score is caller-calibrated via\n * ledger replay, never hard-coded folklore.\n */\n\n// ---------------------------------------------------------------------------\n// Tokenization\n// ---------------------------------------------------------------------------\n\nconst CJK_RANGE = /[\\u3400-\\u4DBF\\u4E00-\\u9FFF\\u3040-\\u30FF\\uAC00-\\uD7AF]/\n\n/** CJK bigrams + lowercase ASCII/digit words. Zero dependencies. */\nexport function tokenize(text: string): string[] {\n const tokens: string[] = []\n let ascii = ''\n let cjkRun: string[] = []\n const flushAscii = () => {\n if (ascii !== '') {\n tokens.push(ascii.toLowerCase())\n ascii = ''\n }\n }\n const flushCjk = () => {\n for (let i = 0; i < cjkRun.length - 1; i += 1) {\n tokens.push(`${cjkRun[i]}${cjkRun[i + 1]}`)\n }\n cjkRun = []\n }\n for (const char of text) {\n if (/[a-zA-Z0-9]/.test(char)) {\n flushCjk()\n ascii += char\n } else if (CJK_RANGE.test(char)) {\n flushAscii()\n cjkRun.push(char)\n } else {\n flushAscii()\n flushCjk()\n }\n }\n flushAscii()\n flushCjk()\n return tokens\n}\n\n// ---------------------------------------------------------------------------\n// Index\n// ---------------------------------------------------------------------------\n\n/** Field weights: title hits matter most, then summary/tags, then body. */\nconst FIELD_WEIGHTS = { title: 3, summary: 2, tags: 2, body: 1 } as const\n\ninterface IndexedDoc {\n id: string\n entry: KnowledgeEntry\n /** term -> weighted term frequency within this doc. */\n tf: Map<string, number>\n length: number\n}\n\nexport interface SearchIndex {\n docs: Map<string, IndexedDoc>\n /** term -> doc ids containing it. */\n postings: Map<string, Set<string>>\n totalLength: number\n builtAt: string\n}\n\nexport function buildIndex(root: string, nowIso: () => string): SearchIndex {\n const docs = new Map<string, IndexedDoc>()\n const postings = new Map<string, Set<string>>()\n let totalLength = 0\n for (const entry of listEntries(root)) {\n const bag = termBag(entry)\n const id = entry.frontmatter.id\n let length = 0\n for (const [term, tf] of bag) {\n length += tf\n let set = postings.get(term)\n if (set === undefined) {\n set = new Set()\n postings.set(term, set)\n }\n set.add(id)\n }\n docs.set(id, { id, entry, tf: bag, length })\n totalLength += length\n }\n return { docs, postings, totalLength, builtAt: nowIso() }\n}\n\nfunction termBag(entry: KnowledgeEntry): Map<string, number> {\n const bag = new Map<string, number>()\n const add = (text: string, weight: number) => {\n for (const term of tokenize(text)) {\n bag.set(term, (bag.get(term) ?? 0) + weight)\n }\n }\n add(entry.frontmatter.title, FIELD_WEIGHTS.title)\n add(entry.frontmatter.summary, FIELD_WEIGHTS.summary)\n add(entry.frontmatter.tags.join(' '), FIELD_WEIGHTS.tags)\n add(entry.body, FIELD_WEIGHTS.body)\n return bag\n}\n\n// ---------------------------------------------------------------------------\n// Scope filtering (ADR-0002: project \u222A global; domains optional later)\n// ---------------------------------------------------------------------------\n\n/** Ancestor-chain visibility: the workspace sees itself + global (+ domains when configured). */\nexport function isVisible(scope: KnowledgeScope, workspaceId: string): boolean {\n if (scope.level === 'global') return true\n if (scope.level === 'project') return scope.workspaceId === workspaceId\n // Domain entries are visible from their member workspaces; without a\n // configured domains table (V0.1) treat them as invisible to projects.\n return false\n}\n\n// ---------------------------------------------------------------------------\n// Query\n// ---------------------------------------------------------------------------\n\nexport type DetailLevel = 'L0' | 'L1' | 'L2'\n\nexport interface SearchHit {\n id: string\n version: number\n type: string\n status: string\n title: string\n /** L0: one-line abstract. */\n abstract: string\n score: number\n scope: KnowledgeScope\n tags: string[]\n /** L1: full summary. */\n summary?: string\n /** L2: full body. */\n body?: string\n}\n\nexport interface SearchMetrics {\n indexedCount: number\n queryCount: number\n totalHits: number\n lastHitCount: number\n lastQuery: string\n builtAt: string\n}\n\nexport interface SearchOptions {\n workspaceId: string\n detail?: DetailLevel\n minScore?: number\n limit?: number\n types?: string[]\n}\n\nconst BM25_K1 = 1.2\nconst BM25_B = 0.75\nconst LOCAL_BOOST = 1.2\n\n/** Run a query against the index (pure read). */\nexport function search(index: SearchIndex, query: string, options: SearchOptions): SearchHit[] {\n const queryTerms = tokenize(query)\n if (queryTerms.length === 0) return []\n const avgLength = index.docs.size === 0 ? 1 : index.totalLength / index.docs.size\n const scores = new Map<string, number>()\n for (const term of new Set(queryTerms)) {\n const posting = index.postings.get(term)\n if (posting === undefined) continue\n const idf = Math.log(1 + (index.docs.size - posting.size + 0.5) / (posting.size + 0.5))\n for (const docId of posting) {\n const doc = index.docs.get(docId)\n if (doc === undefined) continue\n if (!isVisible(doc.entry.frontmatter.scope, options.workspaceId)) continue\n if (options.types !== undefined && !options.types.includes(doc.entry.frontmatter.type)) continue\n const tf = doc.tf.get(term) ?? 0\n const norm = tf * (BM25_K1 + 1) / (tf + BM25_K1 * (1 - BM25_B + BM25_B * (doc.length / avgLength)))\n scores.set(docId, (scores.get(docId) ?? 0) + idf * norm)\n }\n }\n const minScore = options.minScore ?? 0\n const hits: SearchHit[] = []\n for (const [docId, score] of scores) {\n if (score < minScore) continue\n const doc = index.docs.get(docId)\n if (doc === undefined) continue\n // Local boost: entries of the querying workspace rank higher (predecessor DEC-000002).\n const boosted =\n doc.entry.frontmatter.scope.level === 'project' && doc.entry.frontmatter.scope.workspaceId === options.workspaceId\n ? score * LOCAL_BOOST\n : score\n hits.push(toHit(doc, boosted, options.detail ?? 'L1'))\n }\n hits.sort((a, b) => b.score - a.score)\n return options.limit !== undefined ? hits.slice(0, options.limit) : hits\n}\n\nfunction toHit(doc: IndexedDoc, score: number, detail: DetailLevel): SearchHit {\n const fm = doc.entry.frontmatter\n const hit: SearchHit = {\n id: fm.id,\n version: fm.version,\n type: fm.type,\n status: fm.status,\n title: fm.title,\n abstract: firstLine(fm.summary, 80),\n score: Math.round(score * 1000) / 1000,\n scope: fm.scope,\n tags: fm.tags,\n }\n if (detail === 'L1' || detail === 'L2') hit.summary = fm.summary\n if (detail === 'L2') hit.body = doc.entry.body\n return hit\n}\n\nfunction firstLine(text: string, maxChars: number): string {\n const line = text.split('\\n')[0] ?? ''\n return line.length <= maxChars ? line : `${line.slice(0, maxChars)}\u2026`\n}\n\n/** Query with metrics bookkeeping (mutates a metrics record owned by the caller). */\nexport function searchWithMetrics(\n index: SearchIndex,\n metrics: SearchMetrics,\n query: string,\n options: SearchOptions,\n): SearchHit[] {\n const hits = search(index, query, options)\n metrics.queryCount += 1\n metrics.totalHits += hits.length\n metrics.lastHitCount = hits.length\n metrics.lastQuery = query\n return hits\n}\n\nexport function emptyMetrics(index: SearchIndex): SearchMetrics {\n return {\n indexedCount: index.docs.size,\n queryCount: 0,\n totalHits: 0,\n lastHitCount: 0,\n lastQuery: '',\n builtAt: index.builtAt,\n }\n}\n", "import { buildIndex, search, type SearchHit } from './search.js'\nimport type { SearchIndex } from './search.js'\nimport { appendLedger, ledgerPath } from './ledger.js'\nimport { randomUUID } from 'node:crypto'\n\n/**\n * Preflight / injection \u2014 the L0 static pack the host can paste into context\n * every turn. Denoising is top-k truncation (k<=3) + local boost (measured in\n * docs/04-development/search-replay-2026-11-15.md); min_score stays a\n * zero-relevance guard at 0. The pack targets ~250 tokens; the token estimate\n * is documented, not magic.\n */\n\nexport interface PreflightResult {\n /** ready = hits found; no_match = nothing surfaced (host injects nothing). */\n status: 'ready' | 'no_match'\n hits: Array<{ id: string; version: number; title: string; abstract: string; score: number }>\n /** Rough token estimate of the rendered pack (see estimateTokens). */\n tokens: number\n pack?: string\n}\n\n/**\n * Token estimate: CJK chars \u2248 1 token each, ASCII words \u2248 1.3. Documented\n * approximation for budget math \u2014 not a claim about any specific tokenizer.\n */\nexport function estimateTokens(text: string): number {\n let cjk = 0\n const asciiWords = text.split(/[^a-zA-Z0-9]+/).filter((w) => w !== '').length\n for (const char of text) {\n if (/[\\u3400-\\u4DBF\\u4E00-\\u9FFF\\u3040-\\u30FF\\uAC00-\\uD7AF]/.test(char)) cjk += 1\n }\n return Math.ceil(cjk + asciiWords * 1.3)\n}\n\n/** Render the L0 pack: one line per hit \u2014 [ID] title \u2014 abstract. */\nexport function renderPack(hits: SearchHit[]): string {\n return hits\n .map((hit) => `[${hit.id}] ${hit.title} \u2014 ${hit.abstract}`)\n .join('\\n')\n}\n\nexport interface PreflightOptions {\n /** Max hits in the pack; 3 is the replay-calibrated default. */\n limit?: number\n types?: string[]\n nowIso?: () => string\n}\n\n/**\n * Run a preflight: search the current workspace scope (itself + global),\n * top-k truncated, and record a preflight.recorded event shaped like the\n * predecessor ledger (replay scripts keep working across repos).\n */\nexport function preflight(\n index: SearchIndex,\n hubRoot: string,\n workspaceId: string,\n intent: string,\n options?: PreflightOptions,\n): PreflightResult {\n const limit = options?.limit ?? 3\n const hits = search(index, intent, { workspaceId, detail: 'L0', limit, types: options?.types })\n const surfaced = hits.map((hit) => ({\n id: hit.id,\n version: hit.version,\n title: hit.title,\n abstract: hit.abstract,\n score: hit.score,\n }))\n const pack = surfaced.length > 0 ? renderPack(hits) : undefined\n const result: PreflightResult = {\n status: surfaced.length > 0 ? 'ready' : 'no_match',\n hits: surfaced,\n tokens: pack === undefined ? 0 : estimateTokens(pack),\n // Lossless-JSON contract (host tool outputs): omit absent keys instead of\n // emitting `undefined` values.\n ...(pack === undefined ? {} : { pack }),\n }\n appendLedger(ledgerPath(hubRoot), {\n type: 'preflight.recorded',\n preflightId: `PF-${randomUUID().slice(0, 8)}`,\n status: result.status,\n hits: surfaced.map((hit) => ({ id: hit.id, version: hit.version })),\n tokens: result.tokens,\n intent,\n at: options?.nowIso?.() ?? new Date().toISOString(),\n })\n return result\n}\n\n/** Rebuild an index for repeated preflights (host does this once per turn). */\nexport function preflightIndex(hubRoot: string, nowIso?: () => string): SearchIndex {\n return buildIndex(hubRoot, nowIso ?? (() => new Date().toISOString()))\n}\n", "import { existsSync, mkdirSync, readFileSync, readdirSync, appendFileSync, rmSync } from 'node:fs'\nimport { join } from 'node:path'\nimport { journalDir } from './hub.js'\nimport { nowIso } from './time.js'\n\n/**\n * Journal \u2014 the episodic layer. AUTO-CAPTURE \u2260 AUTO-WRITE: journal files are\n * append-only, disposable, and NEVER indexed into search (knowledge stays the\n * only authoritative layer). One JSONL file per local day; trimming is a\n * caller decision (storage hygiene), not an automatic behavior.\n */\n\nexport interface JournalEntry {\n ts: string\n sessionId?: string\n /** Free-form episodic note (what happened in the conversation). */\n text: string\n [key: string]: unknown\n}\n\nfunction dayStamp(iso: string): string {\n return iso.slice(0, 10)\n}\n\nfunction journalFile(root: string, iso: string): string {\n const dir = journalDir(root)\n if (!existsSync(dir)) mkdirSync(dir, { recursive: true })\n return join(dir, `${dayStamp(iso)}.jsonl`)\n}\n\nexport interface AppendJournalInput {\n ts?: string\n sessionId?: string\n text: string\n [key: string]: unknown\n}\n\n/** Append one episodic entry to the day file. Never touches knowledge/. */\nexport function appendJournal(root: string, entry: AppendJournalInput): JournalEntry {\n const stamped: JournalEntry = { ...entry, ts: entry.ts ?? nowIso() }\n appendFileSync(journalFile(root, stamped.ts), `${JSON.stringify(stamped)}\\n`, 'utf8')\n return stamped\n}\n\n/** Read one day's entries (or all days when day is omitted). */\nexport function readJournal(root: string, day?: string): JournalEntry[] {\n const dir = journalDir(root)\n if (!existsSync(dir)) return []\n const files =\n day !== undefined\n ? [join(dir, `${day}.jsonl`)]\n : readdirSync(dir)\n .filter((f) => f.endsWith('.jsonl'))\n .sort()\n .map((f) => join(dir, f))\n const out: JournalEntry[] = []\n for (const file of files) {\n if (!existsSync(file)) continue\n for (const line of readFileSync(file, 'utf8').split('\\n')) {\n if (line.trim() === '') continue\n try {\n out.push(JSON.parse(line) as JournalEntry)\n } catch {\n // skip malformed lines \u2014 journal is disposable, never load-bearing\n }\n }\n }\n return out\n}\n\n/** Explicit trim: delete day files older than keepDays (caller decides when). */\nexport function trimJournal(root: string, keepDays: number, todayIso?: string): number {\n const dir = journalDir(root)\n if (!existsSync(dir)) return 0\n const cutoff = dayStamp(todayIso ?? nowIso())\n let removed = 0\n for (const file of readdirSync(dir)) {\n if (!file.endsWith('.jsonl')) continue\n const day = file.replace('.jsonl', '')\n if (day < cutoff && isOlderThan(day, cutoff, keepDays)) {\n rmSync(join(dir, file), { force: true })\n removed += 1\n }\n }\n return removed\n}\n\nfunction isOlderThan(day: string, cutoff: string, keepDays: number): boolean {\n const dayMs = Date.parse(`${day}T00:00:00Z`)\n const cutoffMs = Date.parse(`${cutoff}T00:00:00Z`)\n if (Number.isNaN(dayMs) || Number.isNaN(cutoffMs)) return false\n return cutoffMs - dayMs > keepDays * 86_400_000\n}\n", "import { existsSync, readFileSync, appendFileSync } from 'node:fs'\nimport { join } from 'node:path'\nimport { tokenize } from './search.js'\nimport { atomicWrite } from './atomic.js'\n\n/**\n * Day-zero transcript index (the deja-vu route): hosts keep transcript bodies\n * authoritative; we store only a compact per-session token index + a short\n * preview. Deja-vu = a new task's intent matches tokens from earlier sessions,\n * surfaced BEFORE duplication happens (day zero), not by dedup afterwards.\n */\n\nexport interface TranscriptRecord {\n sessionId: string\n /** ISO timestamp of the session (or its first message). */\n at: string\n /** Bigram/word token set (serialized array) \u2014 the only searchable content. */\n tokens: string[]\n /** \u2264160 char preview for human display; never searched. */\n preview: string\n /** Host-side pointer back to the full body (path/URL \u2014 host resolves it). */\n location: string\n}\n\nexport const TRANSCRIPT_INDEX_FILE = 'records/transcript-index.jsonl'\n\nfunction indexPath(root: string): string {\n return join(root, TRANSCRIPT_INDEX_FILE)\n}\n\n/** Index one session transcript: tokens + preview only (body stays with the host). */\nexport function indexTranscript(\n root: string,\n input: { sessionId: string; at?: string; text: string; location: string },\n): TranscriptRecord {\n const tokens = [...new Set(tokenize(input.text))]\n const record: TranscriptRecord = {\n sessionId: input.sessionId,\n at: input.at ?? new Date().toISOString(),\n tokens,\n preview: input.text.replace(/\\s+/g, ' ').slice(0, 160),\n location: input.location,\n }\n appendFileSync(indexPath(root), `${JSON.stringify(record)}\\n`, 'utf8')\n return record\n}\n\nexport function readTranscriptIndex(root: string): TranscriptRecord[] {\n const path = indexPath(root)\n if (!existsSync(path)) return []\n const out: TranscriptRecord[] = []\n for (const line of readFileSync(path, 'utf8').split('\\n')) {\n if (line.trim() === '') continue\n try {\n out.push(JSON.parse(line) as TranscriptRecord)\n } catch {\n // skip malformed\n }\n }\n return out\n}\n\nexport interface DejaVu {\n sessionId: string\n at: string\n preview: string\n location: string\n /** Jaccard overlap between the query tokens and the session tokens. */\n overlap: number\n}\n\n/**\n * Detect deja-vu: sessions whose token set overlaps the query tokens above the\n * threshold (default 0.35 \u2014 deliberately conservative; this is a hint, not a\n * verdict). Read-only; the host decides what to do with the pointer.\n */\nexport function detectDejaVu(root: string, query: string, threshold?: number): DejaVu[] {\n const queryTokens = new Set(tokenize(query))\n if (queryTokens.size === 0) return []\n const min = threshold ?? 0.35\n const hits: DejaVu[] = []\n for (const record of readTranscriptIndex(root)) {\n const set = new Set(record.tokens)\n let shared = 0\n for (const token of queryTokens) if (set.has(token)) shared += 1\n const overlap = shared / queryTokens.size\n if (overlap >= min) {\n hits.push({\n sessionId: record.sessionId,\n at: record.at,\n preview: record.preview,\n location: record.location,\n overlap: Math.round(overlap * 1000) / 1000,\n })\n }\n }\n return hits.sort((a, b) => b.overlap - a.overlap)\n}\n\n/** Rebuild the index file atomically (dedup by sessionId keeps the latest). */\nexport function rebuildTranscriptIndex(root: string, records: TranscriptRecord[]): void {\n const bySession = new Map<string, TranscriptRecord>()\n for (const record of records) bySession.set(record.sessionId, record)\n const lines = [...bySession.values()].map((r) => `${JSON.stringify(r)}\\n`)\n atomicWrite(indexPath(root), lines.join(''))\n}\n", "import { createServer, type IncomingMessage, type ServerResponse } from 'node:http'\nimport { PANEL_HTML } from './panel.js'\nimport { handleApi, type ApiState } from './server.js'\n\n/**\n * HTTP adapter: thin node:http server delegating to the pure handleApi\n * router. Binds 127.0.0.1 by default (the panel is a local human channel).\n */\n\nexport interface ServeOptions {\n port?: number\n host?: string\n}\n\nexport function startServer(state: ApiState, options?: ServeOptions): ReturnType<typeof createServer> {\n const server = createServer((req, res) => {\n void route(state, req, res)\n })\n server.listen(options?.port ?? 7777, options?.host ?? '127.0.0.1')\n return server\n}\n\n/** The URL the server is actually reachable at (resolves port 0 to the OS-assigned port). */\nexport function serverUrl(server: ReturnType<typeof createServer>): string {\n const address = server.address()\n if (address !== null && typeof address === 'object') {\n return `http://${address.address === '::' ? '127.0.0.1' : address.address}:${address.port}/`\n }\n return 'http://127.0.0.1/'\n}\n\nasync function route(state: ApiState, req: IncomingMessage, res: ServerResponse): Promise<void> {\n const url = new URL(req.url ?? '/', `http://${req.headers.host ?? 'localhost'}`)\n const path = url.pathname\n // CORS: the panel is consumed cross-origin (DSH web page on its own port\n // fetching 127.0.0.1:7777). The server binds loopback only and holds no\n // credentials, so a permissive header is the local-tool tradeoff.\n res.setHeader('Access-Control-Allow-Origin', '*')\n res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')\n res.setHeader('Access-Control-Allow-Headers', 'content-type')\n if (req.method === 'OPTIONS') {\n res.writeHead(204)\n res.end()\n return\n }\n if (req.method === 'GET' && (path === '/' || path === '/panel')) {\n res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' })\n res.end(PANEL_HTML)\n return\n }\n if (path.startsWith('/api/')) {\n let body: Record<string, unknown> | undefined\n // Query params flow into body so GET handlers can accept options (ADR-0012 hub pull since=).\n if (url.searchParams.size > 0) body = Object.fromEntries(url.searchParams.entries())\n if (req.method === 'POST') {\n const chunks: Buffer[] = []\n for await (const chunk of req) chunks.push(chunk as Buffer)\n const raw = Buffer.concat(chunks).toString('utf8')\n if (raw !== '') {\n try {\n body = { ...(body ?? {}), ...(JSON.parse(raw) as Record<string, unknown>) }\n } catch {\n res.writeHead(400, { 'content-type': 'application/json' })\n res.end(JSON.stringify({ error: 'invalid JSON body' }))\n return\n }\n }\n }\n const response = handleApi(state, req.method ?? 'GET', path, body)\n res.writeHead(response.status, { 'content-type': 'application/json' })\n res.end(JSON.stringify(response.body))\n return\n }\n res.writeHead(404, { 'content-type': 'application/json' })\n res.end(JSON.stringify({ error: `no route: ${req.method} ${path}` }))\n}\n", "/**\n * Zero-dependency single-file console (no build step). ADR-0010: the\n * standalone web console is the first-class human management surface for\n * every host. Tabs: approval inbox (graded), knowledge browser (search /\n * detail / deprecate / hard-delete), audit (ledger + journal). Human\n * clicking approve = panel channel.\n */\nexport const PANEL_HTML = `<!doctype html>\n<html lang=\"zh\">\n<head>\n<meta charset=\"utf-8\">\n<title>memhub console</title>\n<style>\n :root { color-scheme: dark; }\n body { font-family: ui-sans-serif, system-ui; margin: 0; background: #0f1115; color: #e6e6e6; }\n header { padding: 14px 20px; border-bottom: 1px solid #262b36; display: flex; gap: 16px; align-items: baseline; }\n header h1 { font-size: 16px; margin: 0; }\n header span { color: #8b93a7; font-size: 12px; }\n nav { display: flex; gap: 4px; padding: 0 20px; border-bottom: 1px solid #262b36; }\n nav button { border: none; background: none; color: #8b93a7; padding: 10px 16px; font-size: 14px; cursor: pointer; border-bottom: 2px solid transparent; }\n nav button.active { color: #e6e6e6; border-bottom-color: #4d7cff; }\n main { max-width: 900px; margin: 0 auto; padding: 16px; }\n .card { border: 1px solid #262b36; border-radius: 10px; padding: 14px 16px; margin: 10px 0; background: #161a22; }\n .card h3 { margin: 0 0 6px; font-size: 14px; }\n .meta { color: #8b93a7; font-size: 12px; margin-bottom: 8px; }\n .grade { border-radius: 6px; padding: 1px 8px; font-size: 11px; }\n .grade.individual { background: #3a2a2a; color: #ff9e9e; }\n .grade.batch { background: #233a2c; color: #8ee39b; }\n .status-tag { border-radius: 6px; padding: 1px 8px; font-size: 11px; background: #262b36; color: #a9b1c2; }\n .status-tag.deprecated { background: #3a2f1e; color: #e3b98e; }\n button { border: 1px solid #2f3542; background: #1d2330; color: #e6e6e6; border-radius: 8px; padding: 6px 14px; cursor: pointer; font-size: 13px; }\n button:hover { background: #262d3d; }\n button.primary { background: #245639; border-color: #2f7a4d; }\n button.danger { background: #5a2a2a; border-color: #7a3a3a; }\n .row { display: flex; gap: 8px; margin-top: 8px; }\n #statusbar { font-size: 12px; color: #8b93a7; }\n pre { white-space: pre-wrap; font-size: 12px; color: #a9b1c2; }\n .empty { color: #8b93a7; padding: 30px 0; text-align: center; }\n #batchbar { display: none; margin: 10px 0; }\n .tabpane { display: none; }\n .tabpane.active { display: block; }\n .entryline { border-bottom: 1px solid #20242e; padding: 9px 4px; cursor: pointer; display: flex; gap: 10px; align-items: baseline; }\n .entryline:hover { background: #1a1f29; }\n .entryline .id { color: #6f9bff; font-size: 12px; min-width: 90px; }\n .entryline .title { flex: 1; font-size: 13px; }\n .entryline .type { color: #8b93a7; font-size: 11px; }\n .detail pre { background: #12151c; border-radius: 8px; padding: 12px; max-height: 320px; overflow: auto; }\n</style>\n</head>\n<body>\n<header><h1>memhub console</h1><span id=\"statusbar\">loading\u2026</span></header>\n<nav>\n <button id=\"tab-inbox\" class=\"active\" onclick=\"showTab('inbox')\">\u6536\u4EF6\u7BB1</button>\n <button id=\"tab-entries\" onclick=\"showTab('entries')\">\u8BB0\u5FC6\u5E93</button>\n <button id=\"tab-audit\" onclick=\"showTab('audit')\">\u5BA1\u8BA1</button>\n</nav>\n<main>\n <div id=\"pane-inbox\" class=\"tabpane active\">\n <div id=\"batchbar\"><button class=\"primary\" onclick=\"approveBatch()\">\u6279\u51C6\u6240\u9009\u4F4E\u98CE\u9669\u6761\u76EE\uFF08\u6279\u91CF\uFF09</button></div>\n <div id=\"inbox\"><div class=\"empty\">\u52A0\u8F7D\u4E2D\u2026</div></div>\n </div>\n <div id=\"pane-entries\" class=\"tabpane\">\n <div class=\"row\"><input id=\"q\" placeholder=\"BM25 \u68C0\u7D22\u2026\" style=\"flex:1\" onkeydown=\"if(event.key==='Enter')doSearch()\"><button onclick=\"doSearch()\">\u641C\u7D22</button><button onclick=\"loadEntries()\">\u5168\u90E8</button></div>\n <div id=\"entrylist\"><div class=\"empty\">\u70B9\u51FB\u300C\u5168\u90E8\u300D\u6D4F\u89C8\u6216\u8F93\u5165\u68C0\u7D22\u8BCD</div></div>\n <div id=\"entrydetail\" class=\"detail\"></div>\n </div>\n <div id=\"pane-audit\" class=\"tabpane\">\n <div class=\"row\"><button onclick=\"loadLedger()\">\u5237\u65B0\u8D26\u672C</button><button onclick=\"loadJournal()\">\u5237\u65B0\u60C5\u666F\u65E5\u5FD7</button></div>\n <div id=\"auditview\"><div class=\"empty\">\u70B9\u51FB\u5237\u65B0\u52A0\u8F7D</div></div>\n </div>\n</main>\n<script>\nlet inbox = [];\nasync function j(url, opts) { const r = await fetch(url, opts); return { ok: r.ok, status: r.status, data: await r.json().catch(() => ({})) }; }\nfunction esc(s) { return String(s ?? '').replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>').replace(/\"/g,'"'); }\nfunction showTab(name) {\n document.querySelectorAll('.tabpane').forEach(p => p.classList.remove('active'));\n document.getElementById('pane-' + name).classList.add('active');\n document.querySelectorAll('nav button').forEach(b => b.classList.remove('active'));\n document.getElementById('tab-' + name).classList.add('active');\n if (name === 'inbox') refreshInbox();\n if (name === 'entries' && document.getElementById('entrylist').dataset.loaded !== '1') loadEntries();\n}\nasync function refreshStatus() {\n const s = await j('/api/status');\n document.getElementById('statusbar').textContent =\n (s.data.workspace ? s.data.workspace.workspaceId + (s.data.workspace.exact ? '' : ' (synthetic)') : '?') +\n ' \u00B7 accepted ' + (s.data.acceptedCount ?? 0) + ' \u00B7 hub ' + (s.data.hubRoot ?? '?');\n}\nasync function refreshInbox() {\n refreshStatus();\n const i = await j('/api/inbox');\n inbox = i.data.proposals ?? [];\n const el = document.getElementById('inbox');\n if (inbox.length === 0) { el.innerHTML = '<div class=\"empty\">\u2713 inbox \u6E05\u7A7A\uFF0C\u65E0\u5F85\u5BA1\u6761\u76EE</div>'; }\n else {\n el.innerHTML = inbox.map(p => \\`\n <div class=\"card\" id=\"card-\\${p.id}\">\n <h3>\\${esc(p.title)} <span class=\"grade \\${p.grade}\">\\${p.grade === 'individual' ? '\u9010\u6761\u5BA1\u6279' : '\u53EF\u6279\u91CF'}</span></h3>\n <div class=\"meta\">\\${esc(p.id)} \u00B7 \\${esc(p.type)} \u00B7 \\${esc((p.tags ?? []).join(', '))}</div>\n <div>\\${esc(p.summary)}</div>\n <div class=\"row\">\n <button class=\"primary\" onclick=\"approveOne('\\${p.id}')\">\u6279\u51C6</button>\n <button class=\"danger\" onclick=\"rejectOne('\\${p.id}')\">\u62D2\u7EDD</button>\n </div>\n </div>\\`).join('');\n }\n const batchables = inbox.filter(p => p.grade === 'batch');\n document.getElementById('batchbar').style.display = batchables.length > 1 ? 'block' : 'none';\n}\nasync function approveOne(id) { await j('/api/inbox/' + id + '/approve', { method: 'POST', headers: {'content-type':'application/json'}, body: '{}' }); refreshInbox(); }\nasync function rejectOne(id) { await j('/api/inbox/' + id + '/reject', { method: 'POST', headers: {'content-type':'application/json'}, body: '{}' }); refreshInbox(); }\nasync function approveBatch() {\n const ids = inbox.filter(p => p.grade === 'batch').map(p => p.id);\n await j('/api/inbox/approve', { method: 'POST', headers: {'content-type':'application/json'}, body: JSON.stringify({ ids }) });\n refreshInbox();\n}\nasync function loadEntries() {\n const r = await j('/api/entries');\n renderEntries(r.data.entries ?? []);\n document.getElementById('entrylist').dataset.loaded = '1';\n}\nasync function doSearch() {\n const q = document.getElementById('q').value;\n if (q === '') return loadEntries();\n const r = await j('/api/search', { method: 'POST', headers: {'content-type':'application/json'}, body: JSON.stringify({ query: q, limit: 25 }) });\n renderEntries((r.data.hits ?? []).map(h => ({ id: h.id, type: h.type, status: 'accepted', title: h.title, summary: h.abstract, score: h.score })));\n}\nfunction renderEntries(entries) {\n const el = document.getElementById('entrylist');\n if (entries.length === 0) { el.innerHTML = '<div class=\"empty\">\u65E0\u6761\u76EE</div>'; return; }\n el.innerHTML = entries.map(e => \\`\n <div class=\"entryline\" onclick=\"openEntry('\\${esc(e.id)}')\">\n <span class=\"id\">\\${esc(e.id)}@v\\${e.version ?? '?'}</span>\n <span class=\"title\">\\${esc(e.title)} <span class=\"status-tag \\${e.status === 'deprecated' ? 'deprecated' : ''}\">\\${esc(e.status ?? '')}</span>\\${e.score !== undefined ? ' \u00B7 ' + Number(e.score).toFixed(2) : ''}</span>\n <span class=\"type\">\\${esc(e.type)}</span>\n </div>\\`).join('');\n}\nasync function openEntry(id) {\n const r = await j('/api/entries/' + id);\n if (!r.ok) { document.getElementById('entrydetail').innerHTML = '<div class=\"card\">\u52A0\u8F7D\u5931\u8D25: ' + esc(r.data.error ?? r.status) + '</div>'; return; }\n const fm = r.data.frontmatter ?? {};\n document.getElementById('entrydetail').innerHTML = \\`\n <div class=\"card\">\n <h3>\\${esc(fm.title)} <span class=\"status-tag\">\\${esc(fm.status)}</span></h3>\n <div class=\"meta\">\\${esc(fm.id)}@v\\${fm.version} \u00B7 \\${esc(fm.type)} \u00B7 \\${esc(JSON.stringify(fm.scope))} \u00B7 \\${esc((fm.tags ?? []).join(', '))}</div>\n <div class=\"meta\">path: \\${esc(r.data.path)}</div>\n <pre id=\"entry-body\">\\${esc(r.data.body)}</pre>\n <div class=\"row\">\n <button class=\"primary\" onclick=\"editEntry('\\${esc(id)}')\">\u7F16\u8F91\uFF08\u91CD\u65B0\u8403\u53D6\uFF09</button>\n <button class=\"danger\" onclick=\"deprecateEntry('\\${esc(id)}')\">\u5E9F\u5F03\uFF08\u8F6F\u5220\u9664\uFF09</button>\n <button class=\"danger\" onclick=\"hardDeleteEntry('\\${esc(id)}')\">\u6C38\u4E45\u5220\u9664\uFF08\u4E0D\u53EF\u6062\u590D\uFF09</button>\n </div>\n </div>\\`;\n}\nasync function editEntry(id) {\n const r = await j('/api/entries/' + id);\n if (!r.ok) { alert('\u52A0\u8F7D\u5931\u8D25: ' + (r.data.error ?? r.status)); return; }\n const fm = r.data.frontmatter ?? {};\n document.getElementById('entrydetail').innerHTML = \\`\n <div class=\"card\">\n <h3>\u7F16\u8F91 \\${esc(fm.id)}\uFF08\u4FDD\u5B58 = v\\${(fm.version ?? 1) + 1}\uFF0C\u65E7\u7248\u672C\u8FDB history/\uFF09</h3>\n <div class=\"meta\">\u6807\u9898\u4E0E\u7C7B\u578B\u4E0D\u53EF\u6539\uFF1B\u6458\u8981\u4E0E\u6B63\u6587\u901A\u7528\u5316\u6539\u5199\u540E\u4FDD\u5B58\u5373\u91CD\u65B0\u8403\u53D6\u3002</div>\n <div style=\"margin:8px 0\"><label>\u6458\u8981</label><br><textarea id=\"edit-summary\" rows=\"3\" style=\"width:98%\">\\${esc(fm.summary)}</textarea></div>\n <div style=\"margin:8px 0\"><label>\u6B63\u6587</label><br><textarea id=\"edit-body\" rows=\"14\" style=\"width:98%;font-family:monospace\">\\${esc(r.data.body)}</textarea></div>\n <div class=\"row\">\n <button class=\"primary\" onclick=\"saveEntry('\\${esc(id)}')\">\u4FDD\u5B58\u4E3A\u65B0\u7248\u672C</button>\n <button onclick=\"openEntry('\\${esc(id)}')\">\u53D6\u6D88</button>\n </div>\n </div>\\`;\n}\nasync function saveEntry(id) {\n const payload = { summary: document.getElementById('edit-summary').value, body: document.getElementById('edit-body').value };\n const r = await j('/api/entries/' + id + '/update', { method: 'POST', headers: {'content-type':'application/json'}, body: JSON.stringify(payload) });\n if (r.ok) { document.getElementById('entrydetail').innerHTML = '<div class=\"card\">\u2713 \u5DF2\u4FDD\u5B58 ' + esc(r.data.updated) + '@v' + esc(r.data.version) + '\uFF08\u65E7\u7248\u672C\u8FDB history/\uFF0C\u8D26\u672C\u5DF2\u8BB0\u5F55\uFF09</div>'; loadEntries(); }\n else alert('\u5931\u8D25: ' + (r.data.error ?? r.status));\n}\nasync function deprecateEntry(id) {\n if (!confirm('\u786E\u8BA4\u5E9F\u5F03 ' + id + '\uFF1F\uFF08status=deprecated\uFF0C\u53EF\u8FFD\u6EAF\uFF09')) return;\n const reason = prompt('\u5E9F\u5F03\u539F\u56E0\uFF1A', 'via console') ?? '';\n const r = await j('/api/entries/' + id + '/deprecate', { method: 'POST', headers: {'content-type':'application/json'}, body: JSON.stringify({ reason }) });\n if (r.ok) { document.getElementById('entrydetail').innerHTML = '<div class=\"card\">\u2713 \u5DF2\u5E9F\u5F03 ' + esc(id) + '</div>'; loadEntries(); }\n else alert('\u5931\u8D25: ' + (r.data.error ?? r.status));\n}\nasync function hardDeleteEntry(id) {\n if (!confirm('\u6C38\u4E45\u5220\u9664 ' + id + '\uFF1F\u6587\u4EF6\u5C06\u88AB\u7269\u7406\u5220\u9664\uFF0C\u4E0D\u53EF\u6062\u590D\uFF08\u8D26\u672C\u7559\u75D5\uFF09\u3002')) return;\n if (!confirm('\u518D\u6B21\u786E\u8BA4\uFF1A\u771F\u7684\u8981\u6C38\u4E45\u5220\u9664 ' + id + ' \u5417\uFF1F')) return;\n const reason = prompt('\u5220\u9664\u539F\u56E0\uFF1A', 'via console') ?? '';\n const r = await j('/api/entries/' + id + '/delete', { method: 'POST', headers: {'content-type':'application/json'}, body: JSON.stringify({ reason }) });\n if (r.ok) { document.getElementById('entrydetail').innerHTML = '<div class=\"card\">\u2713 \u5DF2\u6C38\u4E45\u5220\u9664 ' + esc(id) + '\uFF08\u8D26\u672C\u7559\u75D5\uFF09</div>'; loadEntries(); }\n else alert('\u5931\u8D25: ' + (r.data.error ?? r.status));\n}\nasync function loadLedger() {\n const r = await j('/api/ledger');\n const records = r.data.records ?? [];\n document.getElementById('auditview').innerHTML = '<div class=\"card\"><h3>\u8D26\u672C\u4E8B\u4EF6\uFF08\u6700\u8FD1 ' + records.length + ' / \u5171 ' + (r.data.total ?? 0) + '\uFF09</h3><pre>' + esc(JSON.stringify(records, null, 2)) + '</pre></div>';\n}\nasync function loadJournal() {\n const r = await j('/api/journal');\n const entries = r.data.entries ?? [];\n document.getElementById('auditview').innerHTML = '<div class=\"card\"><h3>\u60C5\u666F\u65E5\u5FD7\uFF08\u6700\u8FD1 ' + entries.length + '\uFF09</h3><pre>' + esc(JSON.stringify(entries, null, 2)) + '</pre></div>';\n}\nrefreshInbox();\n</script>\n</body>\n</html>`\n", "import { readFileSync, unlinkSync, appendFileSync, existsSync } from 'node:fs'\nimport { join } from 'node:path'\nimport { ErrorCode, HubError } from '../core/errors.js'\nimport { readHubConfig } from '../core/hub.js'\nimport { appendLedger, ledgerPath, readSequences, writeSequences } from '../core/ledger.js'\nimport { acquireLock, assertFencing, lockInfo, releaseLock } from '../core/lock.js'\nimport { commitKnowledge, createProposal, deprecateEntry, getEntry, hardDeleteEntry, listEntries, listProposals } from '../core/store.js'\nimport { buildIndex, emptyMetrics, search, type SearchIndex, type SearchMetrics } from '../core/search.js'\nimport { registerWorkspace, resolveWorkspace, type ResolvedWorkspace } from '../core/registry.js'\nimport { readJournal } from '../core/journal.js'\nimport { readLedger } from '../core/ledger.js'\nimport { autoCommit } from './autocommit.js'\nimport type { KnowledgeType } from '../core/types.js'\n\n/**\n * Serve panel HTTP API \u2014 pure request handler (createServer is a thin\n * adapter). The panel is a human channel (panel): approving from it carries\n * real approval, unlike memory_commit over MCP.\n *\n * Graded approval: decision / constraint / api-catalog entries shape future\n * behavior, so they must be approved individually; lower-risk types may be\n * approved in batches.\n */\n\n/** Types whose approval must be one-by-one (they constrain future behavior). */\nconst INDIVIDUAL_TYPES: readonly KnowledgeType[] = ['decision', 'constraint', 'api-catalog']\n\nexport type ApprovalGrade = 'individual' | 'batch'\n\nexport function gradeFor(type: KnowledgeType): ApprovalGrade {\n return INDIVIDUAL_TYPES.includes(type) ? 'individual' : 'batch'\n}\n\nexport interface ApiState {\n hubRoot: string\n workspace: ResolvedWorkspace\n index: SearchIndex\n metrics: SearchMetrics\n}\n\nexport function createApiState(hubRoot: string, workspaceArg?: string): ApiState {\n const workspace = resolveWorkspace(process.cwd(), workspaceArg)\n const index = buildIndex(hubRoot, () => new Date().toISOString())\n return { hubRoot, workspace, index, metrics: emptyMetrics(index) }\n}\n\nexport interface ApiResponse {\n status: number\n body: unknown\n}\n\nfunction ok(body: unknown): ApiResponse {\n return { status: 200, body }\n}\n\nfunction bad(status: number, message: string, details?: unknown): ApiResponse {\n return { status, body: { error: message, details } }\n}\n\nfunction withWriteLock<T>(hubRoot: string, fn: () => T): T {\n const acquired = acquireLock(hubRoot)\n if (!acquired.ok) {\n throw new HubError(ErrorCode.E_READONLY, 'another writer holds the lease', { holder: acquired.holder })\n }\n const token = acquired.lock?.token ?? ''\n try {\n assertFencing(hubRoot, token)\n return fn()\n } finally {\n releaseLock(hubRoot, token)\n }\n}\n\nfunction commitOne(hubRoot: string, proposalId: string, note?: string): { knowledgeId: string; version: number; superseded?: string; git: { committed: boolean; detail?: string } } {\n const proposal = listProposals(hubRoot).find((p) => p.id === proposalId)\n if (proposal === undefined) {\n throw new HubError(ErrorCode.E_NOT_FOUND, `pending proposal not found: ${proposalId}`, { proposalId })\n }\n // Target selection (ADR-0012): a proposal carrying origin_id upserts that\n // entry in place (create with the same id when the central hub has never\n // seen it; version bump when it has). A legacy `supersedes` still works\n // for local re-extraction proposals, and requires the target to exist.\n const rawOriginId = proposal.frontmatter.extra['origin_id']\n const originId = typeof rawOriginId === 'string' && rawOriginId !== '' && rawOriginId !== '[]' ? rawOriginId : undefined\n const rawSupersedes = proposal.frontmatter.extra['supersedes']\n const supersedesTarget = typeof rawSupersedes === 'string' && rawSupersedes !== '' && rawSupersedes !== '[]' ? rawSupersedes.split(/\\s+/)[0] : undefined\n const targetId = originId ?? supersedesTarget\n const superseding = targetId !== undefined && (originId !== undefined || existsSyncSafe(hubRoot, targetId))\n const committed = commitKnowledge(\n hubRoot,\n {\n ...(superseding ? { id: targetId } : {}),\n type: proposal.frontmatter.type,\n title: proposal.frontmatter.title,\n summary: proposal.frontmatter.summary,\n scope: proposal.frontmatter.scope,\n tags: proposal.frontmatter.tags,\n body: readFileSync(proposal.path, 'utf8').split('---')[2]?.trim() ?? '',\n actor: 'panel',\n },\n { readSequences, writeSequences, appendLedger: (root, record) => appendLedger(ledgerPath(root), record) },\n )\n unlinkSync(proposal.path)\n appendLedger(ledgerPath(hubRoot), {\n type: 'proposal.committed',\n proposalId,\n knowledgeId: committed.id,\n ...(superseding ? { supersedes: targetId } : {}),\n channel: 'panel',\n note,\n at: new Date().toISOString(),\n })\n const gitCommit = autoCommit(hubRoot, `approve: ${committed.id}@v${committed.version} ${proposal.frontmatter.title}`)\n return { knowledgeId: committed.id, version: committed.version, ...(superseding ? { superseded: targetId } : {}), git: gitCommit }\n}\n\nfunction existsSyncSafe(hubRoot: string, id: string): boolean {\n try {\n getEntry(hubRoot, id)\n return true\n } catch {\n return false\n }\n}\n\n/** Route one API request. `body` is the parsed JSON body or undefined. */\nexport function handleApi(state: ApiState, method: string, path: string, body?: Record<string, unknown>): ApiResponse {\n try {\n switch (`${method} ${path}`) {\n case 'GET /api/status':\n return ok({\n hubRoot: state.hubRoot,\n workspace: state.workspace,\n lock: lockInfo(state.hubRoot),\n metrics: state.metrics,\n acceptedCount: listEntries(state.hubRoot).length,\n })\n case 'GET /api/inbox':\n return ok({\n proposals: listProposals(state.hubRoot).map((p) => ({\n id: p.id,\n type: p.frontmatter.type,\n title: p.frontmatter.title,\n summary: p.frontmatter.summary,\n tags: p.frontmatter.tags,\n grade: gradeFor(p.frontmatter.type),\n path: p.path,\n })),\n })\n case 'POST /api/propose': {\n // ADR-0012: remote hubs push their approved entries here as proposals \u2014\n // this inbox IS the central review (approve = merge, reject = declined).\n // originId keeps the source hub's entry id so approval upserts in place.\n const type = body?.['type']\n const title = body?.['title']\n const summary = body?.['summary']\n const bodyText = body?.['body']\n if (typeof type !== 'string' || typeof title !== 'string' || typeof summary !== 'string' || typeof bodyText !== 'string') {\n return bad(400, 'propose requires type, title, summary, body')\n }\n return withWriteLock(state.hubRoot, () => {\n const proposal = createProposal(\n state.hubRoot,\n {\n type: type as KnowledgeType,\n title,\n summary,\n scope: { level: 'project', workspaceId: state.workspace.workspaceId },\n tags: Array.isArray(body?.['tags']) ? (body?.['tags'] as string[]).map(String) : [],\n body: bodyText,\n sourceRefs: Array.isArray(body?.['sourceRefs']) ? (body?.['sourceRefs'] as string[]).map(String) : [`remote:${new Date().toISOString()}`],\n supersedes: Array.isArray(body?.['supersedes']) ? (body?.['supersedes'] as string[]).map(String) : undefined,\n originId: typeof body?.['originId'] === 'string' ? body['originId'] : undefined,\n origin: typeof body?.['origin'] === 'string' ? body['origin'] : 'remote-hub',\n actor: 'remote',\n },\n { readSequences, writeSequences, appendLedger: (root, record) => appendLedger(ledgerPath(root), record) },\n )\n registerWorkspace(\n state.hubRoot,\n state.workspace,\n () => new Date().toISOString(),\n readHubConfig,\n (root, content) => {\n appendFileSync(join(root, 'hub.yaml'), content, 'utf8')\n },\n )\n state.index = buildIndex(state.hubRoot, () => new Date().toISOString())\n state.metrics = emptyMetrics(state.index)\n return ok({ proposalId: proposal.id, nextStep: 'central review via inbox' })\n })\n }\n case 'POST /api/search': {\n const query = String(body?.['query'] ?? '')\n if (query === '') return bad(400, 'query is required')\n const hits = search(state.index, query, {\n workspaceId: state.workspace.workspaceId,\n detail: 'L1',\n limit: typeof body?.['limit'] === 'number' ? body['limit'] : 10,\n })\n return ok({ hits })\n }\n case 'GET /api/entries': {\n const since = typeof body?.['since'] === 'string' ? body['since'] : undefined\n const all = listEntries(state.hubRoot, { includeSoftRemoved: true }).map((e) => ({\n id: e.frontmatter.id,\n version: e.frontmatter.version,\n type: e.frontmatter.type,\n status: e.frontmatter.status,\n title: e.frontmatter.title,\n summary: e.frontmatter.summary,\n scope: e.frontmatter.scope,\n tags: e.frontmatter.tags,\n updated: e.frontmatter.updated,\n path: e.path,\n }))\n // ADR-0012: `since` enables incremental hub pull (updated > since).\n const entries = since === undefined ? all : all.filter((e) => (e.updated ?? '') > since)\n return ok({ entries, since: since ?? null, count: entries.length })\n }\n case 'GET /api/ledger': {\n const records = readLedger(ledgerPath(state.hubRoot))\n const limit = typeof body?.['limit'] === 'number' ? body['limit'] : 200\n return ok({ records: records.slice(-limit).reverse(), total: records.length })\n }\n case 'GET /api/journal': {\n const day = typeof body?.['day'] === 'string' ? body['day'] : undefined\n const entries = readJournal(state.hubRoot, day)\n return ok({ entries: entries.slice(-200).reverse() })\n }\n default:\n break\n }\n const approveMatch = /^\\/api\\/inbox\\/([A-Za-z0-9-]+)\\/approve$/.exec(path)\n if (approveMatch !== null && method === 'POST') {\n return approve(state, [approveMatch[1] ?? ''], body)\n }\n const batchMatch = /^\\/api\\/inbox\\/approve$/.exec(path)\n if (batchMatch !== null && method === 'POST') {\n const ids = body?.['ids']\n if (!Array.isArray(ids) || ids.length === 0) return bad(400, 'ids array is required for batch approval')\n return approve(state, ids.map(String), body)\n }\n const rejectMatch = /^\\/api\\/inbox\\/([A-Za-z0-9-]+)\\/reject$/.exec(path)\n if (rejectMatch !== null && method === 'POST') {\n return reject(state, rejectMatch[1] ?? '', body)\n }\n const entryMatch = /^\\/api\\/entries\\/([A-Za-z0-9-]+)$/.exec(path)\n if (entryMatch !== null && method === 'GET') {\n const entry = getEntry(state.hubRoot, entryMatch[1] ?? '')\n return ok({ frontmatter: entry.frontmatter, body: entry.body, path: entry.path })\n }\n const deprecateMatch = /^\\/api\\/entries\\/([A-Za-z0-9-]+)\\/deprecate$/.exec(path)\n if (deprecateMatch !== null && method === 'POST') {\n const reason = typeof body?.['reason'] === 'string' && body['reason'] !== '' ? body['reason'] : 'deprecated via panel'\n return withWriteLock(state.hubRoot, () => {\n deprecateEntry(state.hubRoot, deprecateMatch[1] ?? '', reason, {\n appendLedger: (root, record) => appendLedger(ledgerPath(root), record),\n })\n state.index = buildIndex(state.hubRoot, () => new Date().toISOString())\n state.metrics = emptyMetrics(state.index)\n return ok({ deprecated: deprecateMatch[1] ?? '', reason, git: autoCommit(state.hubRoot, `deprecate: ${deprecateMatch[1]} (${reason})`) })\n })\n }\n const deleteMatch = /^\\/api\\/entries\\/([A-Za-z0-9-]+)\\/delete$/.exec(path)\n if (deleteMatch !== null && method === 'POST') {\n const reason = typeof body?.['reason'] === 'string' && body['reason'] !== '' ? body['reason'] : 'hard-deleted via panel'\n return withWriteLock(state.hubRoot, () => {\n hardDeleteEntry(state.hubRoot, deleteMatch[1] ?? '', reason, {\n appendLedger: (root, record) => appendLedger(ledgerPath(root), record),\n })\n state.index = buildIndex(state.hubRoot, () => new Date().toISOString())\n state.metrics = emptyMetrics(state.index)\n return ok({ deleted: deleteMatch[1] ?? '', reason, git: autoCommit(state.hubRoot, `delete: ${deleteMatch[1]} (${reason})`) })\n })\n }\n const updateMatch = /^\\/api\\/entries\\/([A-Za-z0-9-]+)\\/update$/.exec(path)\n if (updateMatch !== null && method === 'POST') {\n const existing = getEntry(state.hubRoot, updateMatch[1] ?? '')\n const summary = typeof body?.['summary'] === 'string' && body['summary'] !== '' ? body['summary'] : existing.frontmatter.summary\n const nextBody = typeof body?.['body'] === 'string' ? body['body'] : existing.body\n const tags = Array.isArray(body?.['tags']) ? (body?.['tags'] as string[]).map(String) : existing.frontmatter.tags\n return withWriteLock(state.hubRoot, () => {\n const updated = commitKnowledge(\n state.hubRoot,\n {\n id: existing.frontmatter.id,\n type: existing.frontmatter.type,\n title: existing.frontmatter.title,\n summary,\n scope: existing.frontmatter.scope,\n tags,\n body: nextBody,\n actor: 'panel',\n },\n { readSequences, writeSequences, appendLedger: (root, record) => appendLedger(ledgerPath(root), record) },\n )\n state.index = buildIndex(state.hubRoot, () => new Date().toISOString())\n state.metrics = emptyMetrics(state.index)\n return ok({ updated: updated.id, version: updated.version, git: autoCommit(state.hubRoot, `update: ${updated.id}@v${updated.version}`) })\n })\n }\n return bad(404, `no route: ${method} ${path}`)\n } catch (error) {\n if (error instanceof HubError) {\n const map: Record<string, number> = {\n [ErrorCode.E_NOT_FOUND]: 404,\n [ErrorCode.E_VALIDATION]: 400,\n [ErrorCode.E_CONFLICT]: 409,\n [ErrorCode.E_READONLY]: 423,\n [ErrorCode.E_APPROVAL_REQUIRED]: 403,\n [ErrorCode.E_HUB_NOT_INITIALIZED]: 404,\n }\n return bad(map[error.code] ?? 500, error.message, error.details)\n }\n return bad(500, error instanceof Error ? error.message : String(error))\n }\n}\n\nfunction approve(state: ApiState, ids: string[], body?: Record<string, unknown>): ApiResponse {\n if (ids.length > 1) {\n // Graded approval: batch only when every id is a batch-grade type.\n const proposals = listProposals(state.hubRoot)\n const types = ids.map((id) => proposals.find((p) => p.id === id)?.frontmatter.type)\n if (types.some((t) => t === undefined)) return bad(404, 'unknown proposal id in batch')\n if (types.some((t) => gradeFor(t as KnowledgeType) === 'individual')) {\n return bad(403, 'decision/constraint/api-catalog must be approved individually (graded approval)', {\n individualTypes: INDIVIDUAL_TYPES,\n })\n }\n }\n const note = typeof body?.['note'] === 'string' ? body['note'] : undefined\n return withWriteLock(state.hubRoot, () => {\n const results: Array<{ proposalId: string; knowledgeId?: string; version?: number; superseded?: string; git?: { committed: boolean; detail?: string }; error?: string }> = []\n let firstError: HubError | null = null\n for (const id of ids) {\n try {\n const committed = commitOne(state.hubRoot, id, note)\n results.push({ proposalId: id, knowledgeId: committed.knowledgeId, version: committed.version, ...(committed.superseded !== undefined ? { superseded: committed.superseded } : {}), git: committed.git })\n } catch (error) {\n if (error instanceof HubError && firstError === null) firstError = error\n results.push({ proposalId: id, error: error instanceof Error ? error.message : String(error) })\n }\n }\n // Single-id approval surfaces the real status (404 for unknown id, etc.);\n // batches report partial success as 207.\n if (ids.length === 1 && firstError !== null) {\n return bad(httpStatusFor(firstError), firstError.message, firstError.details)\n }\n // Refresh the index so the panel search sees new entries.\n state.index = buildIndex(state.hubRoot, () => new Date().toISOString())\n state.metrics = emptyMetrics(state.index)\n const failed = results.some((r) => r.error !== undefined)\n return { status: failed ? 207 : 200, body: { results } }\n })\n}\n\nfunction httpStatusFor(error: HubError): number {\n const map: Record<string, number> = {\n [ErrorCode.E_NOT_FOUND]: 404,\n [ErrorCode.E_VALIDATION]: 400,\n [ErrorCode.E_CONFLICT]: 409,\n [ErrorCode.E_READONLY]: 423,\n [ErrorCode.E_APPROVAL_REQUIRED]: 403,\n [ErrorCode.E_HUB_NOT_INITIALIZED]: 404,\n }\n return map[error.code] ?? 500\n}\n\nfunction reject(state: ApiState, id: string, body?: Record<string, unknown>): ApiResponse {\n const proposal = listProposals(state.hubRoot).find((p) => p.id === id)\n if (proposal === undefined) return bad(404, `pending proposal not found: ${id}`)\n const note = typeof body?.['note'] === 'string' ? body['note'] : undefined\n appendLedger(ledgerPath(state.hubRoot), {\n type: 'proposal.rejected',\n proposalId: id,\n channel: 'panel',\n note,\n at: new Date().toISOString(),\n })\n unlinkSync(proposal.path)\n return ok({ rejected: id })\n}\n\n// Re-export for the server adapter + CLI.\nexport { getEntry, listEntries, readLedger, readJournal, readHubConfig }\n", "import { spawnSync } from 'node:child_process'\n\n/**\n * ADR-0011 push policy (user decision 2026-11-15): approved knowledge\n * changes are committed to the LOCAL git history immediately \u2014 fine-grained\n * history, offline-safe. `git push` stays an explicit / scheduled step so\n * central-repo commits remain batched and reviewable. Silently no-ops when\n * the hub root is not a git repository (never blocks approval).\n */\nexport function autoCommit(root: string, message: string): { committed: boolean; detail?: string } {\n const inside = spawnSync('git', ['rev-parse', '--is-inside-work-tree'], { cwd: root, encoding: 'utf8' })\n if (inside.error !== undefined || inside.status !== 0) return { committed: false, detail: 'not a git repository' }\n const add = spawnSync('git', ['add', '-A'], { cwd: root, encoding: 'utf8' })\n if (add.error !== undefined || add.status !== 0) return { committed: false, detail: `git add failed: ${(add.stderr ?? '').trim().slice(0, 200)}` }\n const commit = spawnSync('git', ['commit', '-m', message], { cwd: root, encoding: 'utf8' })\n const output = `${commit.stdout ?? ''}${commit.stderr ?? ''}`\n if (commit.status !== 0) {\n if (output.includes('nothing to commit')) return { committed: false, detail: 'nothing to commit' }\n return { committed: false, detail: output.trim().slice(0, 200) }\n }\n return { committed: true }\n}\n", "/**\n * Minimal structural types for the DSH host surface the adapter touches.\n * Declared here (not imported from the host SDK) so the adapter has zero\n * host dependencies at build time \u2014 the host provides these capabilities.\n */\n\nexport interface ContentBlock {\n type: 'text'\n text: string\n}\n\nexport interface ToolOutput {\n schema: Record<string, unknown>\n render: (args: unknown, value: unknown) => ContentBlock[]\n}\n\nexport interface ToolDefinition {\n name: string\n description: string\n parameters: Record<string, unknown>\n /** Host contract: every tool declares its output shape + renderer. */\n output: ToolOutput\n isConcurrencySafe?: () => boolean\n execute: (args: Record<string, unknown>, exec: unknown) => Promise<unknown> | unknown\n}\n\nexport function renderJson(_args: unknown, value: unknown): ContentBlock[] {\n return [{ type: 'text', text: JSON.stringify(value, null, 2) }]\n}\n\nexport interface HostContext {\n tools: {\n get(name: string): ToolDefinition | undefined\n register(tool: ToolDefinition): () => void\n }\n logger?: {\n info(message: string): void\n warn(message: string): void\n }\n effect?(dispose: () => () => void, name?: string): void\n}\n\nexport interface AdapterConfig {\n /** Hub root directory. Empty/missing = $MEMHUB_ROOT or the process cwd. */\n root?: string\n /**\n * What to do when a tool name is already registered (host or another\n * plugin \u2014 e.g. the predecessor dsh-memory-hub): 'skip' (default) drops\n * ours and keeps the existing one; 'suffix' renames ours to `<name>__amh`.\n */\n toolConflict?: 'skip' | 'suffix'\n}\n\nexport function resolveHubRoot(config?: AdapterConfig): string {\n const explicit = config?.root\n if (explicit !== undefined && explicit !== '') return explicit\n return process.env['MEMHUB_ROOT'] ?? process.cwd()\n}\n", "import * as hub from 'agent-memory-hub'\nimport { renderJson, resolveHubRoot, type AdapterConfig, type HostContext, type ToolDefinition } from './host-types.js'\n\n/**\n * Tool shells: one behavior, one implementation. Every tool is a thin forward\n * to agent-memory-hub core. There is deliberately NO memory_commit tool here:\n * commits enter knowledge/ only through the human channels (`memhub inbox`\n * / the serve panel) \u2014 the fail-closed gate stays closed inside the host.\n *\n * Host contract (dsh 0.2.x): every tool must declare\n * `output { schema, render }` and expose `isConcurrencySafe()` as a method.\n */\n\ninterface HubContext {\n root: string\n workspace: hub.ResolvedWorkspace\n index: hub.SearchIndex\n metrics: hub.SearchMetrics\n}\n\nexport function createHubContext(config?: AdapterConfig): HubContext {\n const root = resolveHubRoot(config)\n const workspace = hub.resolveWorkspace(process.cwd())\n const index = hub.preflightIndex(root)\n return { root, workspace, index, metrics: hub.emptyMetrics(index) }\n}\n\nfunction refreshIndex(ctx: HubContext): void {\n ctx.index = hub.preflightIndex(ctx.root)\n ctx.metrics = hub.emptyMetrics(ctx.index)\n}\n\nfunction errorPayload(error: unknown): { error: string; code?: string } {\n if (error instanceof hub.HubError) return { error: error.message, code: error.code }\n return { error: error instanceof Error ? error.message : String(error) }\n}\n\n/** Host output contract is lossless JSON: strip explicit `undefined` values\n * from every tool result at the boundary \u2014 legacy hub data can carry optional\n * keys in any shape, so the adapter normalizes rather than trusting each path. */\nfunction stripUndefined<T>(value: T): T {\n if (Array.isArray(value)) return value.map((item) => stripUndefined(item)) as T\n if (value !== null && typeof value === 'object') {\n const out: Record<string, unknown> = {}\n for (const [key, item] of Object.entries(value as Record<string, unknown>)) {\n if (item !== undefined) out[key] = stripUndefined(item)\n }\n return out as T\n }\n return value\n}\n\nasync function safe(tool: ToolDefinition, args: Record<string, unknown>): Promise<unknown> {\n try {\n return stripUndefined(await tool.execute(args, undefined))\n } catch (error) {\n return errorPayload(error)\n }\n}\n\nexport function createTools(ctx: HubContext): Array<ToolDefinition & { run: (args: Record<string, unknown>) => Promise<unknown> }> {\n const definitions: Array<ToolDefinition & { run: (args: Record<string, unknown>) => Promise<unknown> }> = []\n\n const define = (tool: Omit<ToolDefinition, 'execute' | 'output' | 'isConcurrencySafe'> & {\n execute: ToolDefinition['execute']\n concurrencySafe?: boolean\n }) => {\n definitions.push({\n ...tool,\n output: { schema: {}, render: renderJson },\n ...(tool.concurrencySafe === true ? { isConcurrencySafe: () => true } : {}),\n run: (args: Record<string, unknown>) => safe({ ...tool, execute: tool.execute } as ToolDefinition, args),\n } as ToolDefinition & { run: (args: Record<string, unknown>) => Promise<unknown> })\n }\n\n define({\n name: 'memory_search',\n description:\n \"Search the user's accepted long-term memory (workspace + global). Use it before planning or modifying a project, and after a preflight hint points at an entry. Returns ranked hits with summaries; call memory_get for the body and memory_cite after actually using an entry.\",\n concurrencySafe: true,\n parameters: {\n type: 'object',\n properties: {\n query: { type: 'string', description: 'Keywords or a natural-language question.' },\n detail: { type: 'string', enum: ['L0', 'L1', 'L2'], description: 'L0 abstract only; L1 adds summary; L2 adds body.' },\n limit: { type: 'number' },\n types: { type: 'array', items: { type: 'string' } },\n },\n required: ['query'],\n },\n execute: (args) => {\n const hits = hub.searchWithMetrics(ctx.index, ctx.metrics, String(args['query']), {\n workspaceId: ctx.workspace.workspaceId,\n detail: (args['detail'] as hub.DetailLevel | undefined) ?? 'L1',\n limit: typeof args['limit'] === 'number' ? args['limit'] : undefined,\n types: args['types'] as string[] | undefined,\n })\n return {\n hits: hits.map((hit) => ({\n id: hit.id,\n version: hit.version,\n type: hit.type,\n title: hit.title,\n abstract: hit.abstract,\n ...(hit.summary !== undefined ? { summary: hit.summary } : {}),\n score: hit.score,\n })),\n workspace: ctx.workspace.workspaceId,\n exact: ctx.workspace.exact,\n }\n },\n })\n\n define({\n name: 'memory_get',\n description:\n 'Read one knowledge entry by ID. Returns metadata + summary by default; pass full=true only when the whole body is needed.',\n concurrencySafe: true,\n parameters: {\n type: 'object',\n properties: {\n id: { type: 'string' },\n full: { type: 'boolean' },\n },\n required: ['id'],\n },\n execute: (args) => {\n const entry = hub.getEntry(ctx.root, String(args['id']))\n // Host output contract is lossless JSON: never emit explicit `undefined`\n // property values \u2014 omit the key instead.\n return {\n frontmatter: entry.frontmatter,\n ...(args['full'] === true ? { body: entry.body } : {}),\n path: entry.path,\n }\n },\n })\n\n define({\n name: 'memory_status',\n description:\n 'Read-only self check: hub root, workspace identity (exact=false means synthetic fallback), writer lock holder, metrics, counts.',\n concurrencySafe: true,\n parameters: { type: 'object', properties: {} },\n execute: () => ({\n hubRoot: ctx.root,\n initialized: hub.isHubInitialized(ctx.root),\n workspace: ctx.workspace,\n lock: hub.lockInfo(ctx.root),\n metrics: ctx.metrics,\n acceptedCount: hub.listEntries(ctx.root).length,\n pendingCount: hub.listProposals(ctx.root).length,\n }),\n })\n\n define({\n name: 'memory_preflight',\n description:\n 'Build the L0 static pack for this turn: top-3 hits, one line each, with a token estimate. Records a preflight.recorded event. Inject the pack only when status=ready.',\n concurrencySafe: true,\n parameters: {\n type: 'object',\n properties: {\n intent: { type: 'string' },\n limit: { type: 'number' },\n },\n required: ['intent'],\n },\n execute: (args) =>\n hub.preflight(ctx.index, ctx.root, ctx.workspace.workspaceId, String(args['intent']), {\n limit: typeof args['limit'] === 'number' ? args['limit'] : undefined,\n }),\n })\n\n define({\n name: 'memory_propose',\n description:\n 'Create a pending candidate (pending/PRO-*.md). This NEVER writes knowledge/ directly \u2014 a human must approve via the serve panel or `memhub inbox`. Always include sourceRefs evidence. To RE-EXTRACT an existing entry (e.g. generalize an environment-specific flow into a universal one), pass supersedes: [entryId] \u2014 approval then bumps that entry\\'s version instead of creating a duplicate.',\n parameters: {\n type: 'object',\n properties: {\n type: { type: 'string', enum: ['decision', 'constraint', 'knowledge', 'api-catalog', 'process', 'open-questions', 'runtime-base', 'playbooks', 'assets'] },\n title: { type: 'string' },\n summary: { type: 'string' },\n tags: { type: 'array', items: { type: 'string' } },\n body: { type: 'string' },\n sourceRefs: { type: 'array', items: { type: 'string' } },\n supersedes: { type: 'array', items: { type: 'string' }, description: 'Entry id(s) this proposal re-extracts; approval upgrades their version.' },\n },\n required: ['type', 'title', 'summary', 'body'],\n },\n execute: (args) => {\n const acquired = hub.acquireLock(ctx.root)\n if (!acquired.ok) return { error: 'another writer holds the lease', code: hub.ErrorCode.E_READONLY }\n const token = acquired.lock?.token ?? ''\n try {\n hub.assertFencing(ctx.root, token)\n const supersedes = args['supersedes'] as string[] | undefined\n const proposal = hub.createProposal(\n ctx.root,\n {\n type: args['type'] as hub.KnowledgeType,\n title: String(args['title']),\n summary: String(args['summary']),\n scope: { level: 'project', workspaceId: ctx.workspace.workspaceId },\n tags: args['tags'] as string[] | undefined,\n body: String(args['body']),\n sourceRefs: (args['sourceRefs'] as string[] | undefined) ?? [],\n ...(supersedes !== undefined && supersedes.length > 0 ? { supersedes } : {}),\n actor: 'model',\n },\n {\n readSequences: hub.readSequences,\n writeSequences: hub.writeSequences,\n appendLedger: (root, record) => hub.appendLedger(hub.ledgerPath(root), record),\n },\n )\n return { proposalId: proposal.id, path: proposal.path, nextStep: 'human approval via panel or `memhub inbox approve`' }\n } finally {\n hub.releaseLock(ctx.root, token)\n }\n },\n })\n\n define({\n name: 'memory_cite',\n description:\n 'Record that a knowledge entry influenced the current task (audit + aging signal). Cite after actually using an entry \u2014 search hits are not citations.',\n parameters: {\n type: 'object',\n properties: {\n id: { type: 'string' },\n purpose: { type: 'string' },\n },\n required: ['id', 'purpose'],\n },\n execute: (args) => {\n const id = String(args['id'])\n hub.getEntry(ctx.root, id) // must exist\n hub.appendLedger(hub.ledgerPath(ctx.root), {\n type: 'citation.added',\n id,\n purpose: String(args['purpose']),\n at: new Date().toISOString(),\n })\n return { cited: id }\n },\n })\n\n define({\n name: 'memory_close_task',\n description:\n 'Close the current task with a writeback assessment (proposed / no_new_knowledge / needs_evidence / deferred). Bookkeeping only.',\n parameters: {\n type: 'object',\n properties: {\n assessment: { type: 'string', enum: ['proposed', 'no_new_knowledge', 'needs_evidence', 'deferred'] },\n note: { type: 'string' },\n },\n required: ['assessment'],\n },\n execute: (args) => {\n hub.appendLedger(hub.ledgerPath(ctx.root), {\n type: 'task.closed',\n assessment: args['assessment'],\n note: typeof args['note'] === 'string' ? args['note'] : undefined,\n at: new Date().toISOString(),\n })\n return { closed: true }\n },\n })\n\n define({\n name: 'memory_dejavu',\n description:\n 'Day-zero deja-vu check: has a similar conversation already happened? Index a transcript (action=index; tokens + preview only \u2014 the body stays with the host) or query overlaps (action=check).',\n concurrencySafe: true,\n parameters: {\n type: 'object',\n properties: {\n action: { type: 'string', enum: ['index', 'check'] },\n sessionId: { type: 'string' },\n text: { type: 'string' },\n location: { type: 'string' },\n query: { type: 'string' },\n },\n required: ['action'],\n },\n execute: (args) => {\n const action = String(args['action'])\n if (action === 'index') {\n const sessionId = args['sessionId'] as string | undefined\n const text = String(args['text'] ?? '')\n const location = String(args['location'] ?? '')\n if (sessionId === undefined || text === '' || location === '') {\n throw new hub.HubError(hub.ErrorCode.E_VALIDATION, 'dejavu index requires sessionId, text and location')\n }\n return hub.indexTranscript(ctx.root, { sessionId, text, location })\n }\n return {\n sessions: hub.readTranscriptIndex(ctx.root).length,\n dejaVu: hub.detectDejaVu(ctx.root, String(args['query'] ?? '')),\n }\n },\n })\n\n return definitions\n}\n\nexport { refreshIndex, resolveHubRoot, type HostContext }\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACEO,IAAM,YAAY;EACvB,uBAAuB;EACvB,aAAa;EACb,cAAc;EACd,YAAY;EACZ,aAAa;EACb,qBAAqB;EACrB,YAAY;;AAKR,IAAO,WAAP,cAAwB,MAAK;EACxB;EACA;EAET,YAAY,MAAsB,SAAiB,SAAiC;AAClF,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,OAAO;AACZ,SAAK,UAAU;EACjB;;;;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G;AAC5C,UAAM,EAAE,KAAK,GAAG,KAAK,IAAI;AACzB,QAAI,WAAW,KAAK;AACpB,UAAM,WAAW,IAAI,MAAM,IAAI,QAAQ;AACvC,QAAI,aAAa,QAAW;AAC1B,UAAI,aAAa,QAAQ;AACvB,YAAI,QAAQ;AAAA,UACV,8BAA8B,QAAQ;AAAA,QACxC;AACA;AAAA,MACF;AACA,iBAAW,GAAG,QAAQ;AACtB,UAAI,QAAQ,KAAK,kEAA6D,QAAQ,yBAAyB;AAAA,IACjH;AACA,UAAM,OAAuB;AAAA,MAC3B,GAAG;AAAA,MACH,MAAM;AAAA,MACN,SAAS,CAAC,SAAS,IAAI,IAAI;AAAA,IAC7B;AACA,cAAU,KAAK,IAAI,MAAM,SAAS,IAAI,CAAC;AAAA,EACzC;AACA,MAAI,QAAQ,KAAK,yBAAyB,UAAU,MAAM,kCAAkC,IAAI,GAAG;AACnG,MAAI,SAAS,MAAM,MAAM;AACvB,eAAW,WAAW,UAAW,SAAQ;AAAA,EAC3C,GAAG,IAAI;AACT;",
|
|
6
6
|
"names": ["readSequences", "writeSequences", "import_node_fs", "import_node_path", "import_node_fs", "import_node_path", "import_node_fs", "import_node_path", "parsed", "fm", "import_node_path", "nowIso", "import_node_fs", "import_node_path", "nowIso", "import_node_crypto", "nowIso", "import_node_fs", "import_node_path", "import_node_fs", "import_node_path", "import_node_fs", "import_node_path", "import_node_child_process"]
|
|
7
7
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-agent-memory-hub",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.6",
|
|
4
4
|
"description": "Memory hub for DeepSeek Harness (DSH): human-approved long-term memory with local-first search, proposal/Approval workflow, citations and journaling. Thin host adapter — all logic lives in agent-memory-hub core; also ships as a standalone MCP server / CLI for OpenCode, Claude Code and any MCP host.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"main": "./dist/index.js",
|