@tekmidian/pai 0.66.6 → 0.66.8
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/{aibroker-client-WCZi_tn-.mjs → aibroker-client-BfnVwGZl.mjs} +3 -3
- package/dist/{aibroker-client-WCZi_tn-.mjs.map → aibroker-client-BfnVwGZl.mjs.map} +1 -1
- package/dist/{aibroker-client-Ck3p3k_-.mjs → aibroker-client-C-O3Fflh.mjs} +1 -1
- package/dist/{auto-route-BnizyALK.mjs → auto-route-D8TBDNqb.mjs} +3 -3
- package/dist/{auto-route-BnizyALK.mjs.map → auto-route-D8TBDNqb.mjs.map} +1 -1
- package/dist/auto-route-DCxTKz19.mjs +7 -0
- package/dist/{chain-2_uoiEdD.mjs → chain-BL4khGgy.mjs} +4 -3
- package/dist/{chain-2_uoiEdD.mjs.map → chain-BL4khGgy.mjs.map} +1 -1
- package/dist/cli/index.mjs +20 -16
- package/dist/cli/index.mjs.map +1 -1
- package/dist/cli/program.mjs +19 -15
- package/dist/{config-Ddc4DIPk.mjs → config-DjZELvoA.mjs} +12 -3
- package/dist/config-DjZELvoA.mjs.map +1 -0
- package/dist/{run-env-CQRnxNht.mjs → config-Dpe2JlbY.mjs} +5 -114
- package/dist/config-Dpe2JlbY.mjs.map +1 -0
- package/dist/{config-CnsDMETf.mjs → config-yomayAwe.mjs} +1 -1
- package/dist/{context-handover-cache-SFkWucuT.mjs → context-handover-cache-DFqxNh-H.mjs} +27 -13
- package/dist/context-handover-cache-DFqxNh-H.mjs.map +1 -0
- package/dist/daemon/index.mjs +20 -15
- package/dist/daemon/index.mjs.map +1 -1
- package/dist/{daemon-vLtT3yaI.mjs → daemon-CsR1S_Qr.mjs} +762 -24
- package/dist/daemon-CsR1S_Qr.mjs.map +1 -0
- package/dist/daemon-WrncnGua.mjs +23 -0
- package/dist/daemon-mcp/index.mjs +15 -12
- package/dist/daemon-mcp/index.mjs.map +1 -1
- package/dist/embedding-gate-DqbKvn56.mjs +378 -0
- package/dist/embedding-gate-DqbKvn56.mjs.map +1 -0
- package/dist/embedding-gate-SJMCPwxG.mjs +5 -0
- package/dist/{embeddings-DMVzpvRZ.mjs → embeddings-BUjZMD9F.mjs} +16 -2
- package/dist/{embeddings-DMVzpvRZ.mjs.map → embeddings-BUjZMD9F.mjs.map} +1 -1
- package/dist/embeddings-DrJ-ewfi.mjs +3 -0
- package/dist/{env-DiolswKQ.mjs → env-CPCNHz3i.mjs} +1 -1
- package/dist/{env-DiolswKQ.mjs.map → env-CPCNHz3i.mjs.map} +1 -1
- package/dist/factory-DjtXElOI.mjs +9 -0
- package/dist/{factory-CXFHwvcv.mjs → factory-yElzJc6f.mjs} +31 -9
- package/dist/factory-yElzJc6f.mjs.map +1 -0
- package/dist/{fallback-DNzd3jJc.mjs → fallback-2yWDDYiT.mjs} +5 -4
- package/dist/{fallback-DNzd3jJc.mjs.map → fallback-2yWDDYiT.mjs.map} +1 -1
- package/dist/{helpers-CZsi_49C.mjs → helpers-B9LHRJ8R.mjs} +1 -1
- package/dist/{helpers-CZsi_49C.mjs.map → helpers-B9LHRJ8R.mjs.map} +1 -1
- package/dist/hooks/block-sleep-poll.mjs +7 -2
- package/dist/hooks/block-sleep-poll.mjs.map +3 -3
- package/dist/hooks/context-compression-hook.mjs +2 -0
- package/dist/hooks/context-compression-hook.mjs.map +2 -2
- package/dist/hooks/load-core-context.mjs +5 -5
- package/dist/hooks/load-core-context.mjs.map +2 -2
- package/dist/hooks/load-project-context.mjs +2 -0
- package/dist/hooks/load-project-context.mjs.map +2 -2
- package/dist/hooks/post-compact-inject.mjs +2 -0
- package/dist/hooks/post-compact-inject.mjs.map +2 -2
- package/dist/hooks/route-agents-to-worker.mjs +2 -0
- package/dist/hooks/route-agents-to-worker.mjs.map +2 -2
- package/dist/hooks/security-validator.mjs +2 -0
- package/dist/hooks/security-validator.mjs.map +2 -2
- package/dist/hooks/whisper-rules.mjs +2 -0
- package/dist/hooks/whisper-rules.mjs.map +2 -2
- package/dist/hooks/worker-guard.mjs +82 -5
- package/dist/hooks/worker-guard.mjs.map +4 -4
- package/dist/hooks/worker-proxy.mjs +2 -0
- package/dist/hooks/worker-proxy.mjs.map +2 -2
- package/dist/hooks/worker-status-line.mjs +7 -2
- package/dist/hooks/worker-status-line.mjs.map +3 -3
- package/dist/hooks/worker-supervision.mjs +2 -0
- package/dist/hooks/worker-supervision.mjs.map +2 -2
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +7 -4
- package/dist/{ipc-client-DkxRay-o.mjs → ipc-client-DVZ_EGnu.mjs} +2 -2
- package/dist/{ipc-client-DkxRay-o.mjs.map → ipc-client-DVZ_EGnu.mjs.map} +1 -1
- package/dist/main-resolver-DjQsexge.mjs +8 -0
- package/dist/{main-resolver-SfGGg1DB.mjs → main-resolver-Dxvn4Mv8.mjs} +7 -6
- package/dist/{main-resolver-SfGGg1DB.mjs.map → main-resolver-Dxvn4Mv8.mjs.map} +1 -1
- package/dist/{pai-marker-DXVpFsYz.mjs → pai-marker-1B7iC7oq.mjs} +121 -3
- package/dist/pai-marker-1B7iC7oq.mjs.map +1 -0
- package/dist/{planner-C-gzg7ye.mjs → planner-CspP59ya.mjs} +13 -10
- package/dist/{planner-C-gzg7ye.mjs.map → planner-CspP59ya.mjs.map} +1 -1
- package/dist/{postgres-BxmyQHoA.mjs → postgres-CCAGq1qp.mjs} +86 -5
- package/dist/postgres-CCAGq1qp.mjs.map +1 -0
- package/dist/postgres-CzkEPfAm.mjs +7 -0
- package/dist/{program-CfG1T_ko.mjs → program-cWqZI0_L.mjs} +231 -125
- package/dist/program-cWqZI0_L.mjs.map +1 -0
- package/dist/{query-feedback-BPdapXKd.mjs → query-feedback-GPeVGvIa.mjs} +2 -2
- package/dist/{query-feedback-BPdapXKd.mjs.map → query-feedback-GPeVGvIa.mjs.map} +1 -1
- package/dist/{reranker-3lnggwgq.mjs → reranker-BTiOia8Y.mjs} +1 -1
- package/dist/{reranker-3lnggwgq.mjs.map → reranker-BTiOia8Y.mjs.map} +1 -1
- package/dist/{reranker-CZ2mP4cf.mjs → reranker-YwDT2n5e.mjs} +1 -1
- package/dist/{router-BaTbc9VX.mjs → router-Bk_ySIZT.mjs} +2 -2
- package/dist/{router-BaTbc9VX.mjs.map → router-Bk_ySIZT.mjs.map} +1 -1
- package/dist/router-DyiZNI6o.mjs +3 -0
- package/dist/{run-ChlIbDJ0.mjs → run-BZNdpUGQ.mjs} +226 -1797
- package/dist/run-BZNdpUGQ.mjs.map +1 -0
- package/dist/run-env-Cd0Son-Y.mjs +115 -0
- package/dist/run-env-Cd0Son-Y.mjs.map +1 -0
- package/dist/{pai-home-UncxWxlX.mjs → runtime-paths-DkZoxofH.mjs} +50 -2
- package/dist/runtime-paths-DkZoxofH.mjs.map +1 -0
- package/dist/{search-CNAGTiJP.mjs → search-cPDj-9fO.mjs} +2 -2
- package/dist/{search-CNAGTiJP.mjs.map → search-cPDj-9fO.mjs.map} +1 -1
- package/dist/{sources-CM2g-CLT.mjs → sources-CvvzNZad.mjs} +1 -1
- package/dist/{sources-CM2g-CLT.mjs.map → sources-CvvzNZad.mjs.map} +1 -1
- package/dist/{stop-words-DtxaTWU_.mjs → stop-words-LtkS-Pej.mjs} +1 -1
- package/dist/{stop-words-DtxaTWU_.mjs.map → stop-words-LtkS-Pej.mjs.map} +1 -1
- package/dist/worktree-CwMRTa0H.mjs +1578 -0
- package/dist/worktree-CwMRTa0H.mjs.map +1 -0
- package/dist/{zettelkasten-BRIaHzFm.mjs → zettelkasten-DSIe6wpF.mjs} +6 -5
- package/dist/zettelkasten-DSIe6wpF.mjs.map +1 -0
- package/dist/{zettelkasten-G0-ZTybr.mjs → zettelkasten-DtkAvA18.mjs} +5 -3
- package/docker/docker-compose.yml +4 -0
- package/docs/commands/README.md +6 -0
- package/docs/commands/memory.md +52 -0
- package/docs/commands/worker.md +22 -0
- package/docs/install-linux.md +1 -0
- package/docs/memory.md +69 -0
- package/package.json +1 -1
- package/src/hooks/ts/lib/sleep-poll-gate.test.ts +2 -2
- package/src/hooks/ts/lib/sleep-poll-gate.ts +4 -4
- package/src/hooks/ts/lib/worker-guard-longwait.test.ts +48 -0
- package/src/hooks/ts/lib/worker-guard.ts +50 -6
- package/src/hooks/ts/pre-tool-use/block-sleep-poll.test.ts +1 -1
- package/src/hooks/ts/session-start/load-core-context.ts +11 -8
- package/src/hooks/ts/session-start/session-start-worker-guard.test.ts +34 -2
- package/dist/auto-route-D6fW1Q8z.mjs +0 -3
- package/dist/config-Ddc4DIPk.mjs.map +0 -1
- package/dist/context-handover-cache-SFkWucuT.mjs.map +0 -1
- package/dist/daemon-BHQoEjt0.mjs +0 -18
- package/dist/daemon-vLtT3yaI.mjs.map +0 -1
- package/dist/embeddings-D0WOQpYR.mjs +0 -3
- package/dist/factory-CXFHwvcv.mjs.map +0 -1
- package/dist/factory-CnKsU6zX.mjs +0 -8
- package/dist/main-resolver-DrHtx8iW.mjs +0 -7
- package/dist/pai-home-UncxWxlX.mjs.map +0 -1
- package/dist/pai-marker-DXVpFsYz.mjs.map +0 -1
- package/dist/postgres-B2BEBT-J.mjs +0 -5
- package/dist/postgres-BxmyQHoA.mjs.map +0 -1
- package/dist/program-CfG1T_ko.mjs.map +0 -1
- package/dist/router-BK-hFeQ6.mjs +0 -3
- package/dist/run-ChlIbDJ0.mjs.map +0 -1
- package/dist/run-env-CQRnxNht.mjs.map +0 -1
- package/dist/runtime-paths-Bw3Jk8qJ.mjs +0 -52
- package/dist/runtime-paths-Bw3Jk8qJ.mjs.map +0 -1
- package/dist/zettelkasten-BRIaHzFm.mjs.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"worktree-CwMRTa0H.mjs","names":[],"sources":["../src/workers/paths.ts","../src/workers/args.ts","../src/workers/status.ts","../src/workers/ledger.ts","../src/workers/pending.ts","../src/workers/worktree.ts"],"sourcesContent":["/**\n * paths.ts — where worker run artefacts live.\n *\n * Everything a run writes (event mirror, status file, pane registry, routing\n * state, the empty MCP config) sits under one logDir so the whole tree is\n * disposable and configurable: `workers.logDir`, default ~/.claude/logs/workers.\n */\n\nimport { existsSync, mkdirSync, writeFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { expandHome, DEFAULT_LOG_DIR, type WorkersConfig } from \"./config.js\";\nimport { paiHomePath, resolvePaiFile } from \"../config/pai-home.js\";\n\n/**\n * Absolute logDir for the given config. An explicit `logDir` in workers.yaml\n * is honored verbatim (the user chose it). Otherwise this resolves like every\n * other PAI_HOME file: PAI_HOME/logs/workers if it exists, else the old\n * ~/.claude/logs/workers (with a one-time notice), else the new path.\n */\nexport function workersLogDir(config: WorkersConfig): string {\n const expanded = expandHome(config.logDir);\n if (config.logDir !== DEFAULT_LOG_DIR) return expanded;\n return resolvePaiFile(paiHomePath(\"logs\", \"workers\"), [expanded], \"pai config migrate --logs\");\n}\n\n/** The strict empty MCP config for headless runs, written on demand. */\nexport function ensureNoMcpConfig(logDir: string): string {\n const path = noMcpConfigPath(logDir);\n if (!existsSync(path)) {\n mkdirSync(logDir, { recursive: true });\n writeFileSync(path, '{ \"mcpServers\": {} }\\n', \"utf8\");\n }\n return path;\n}\n\nexport function statusPath(logDir: string, id: string): string {\n return join(logDir, `${id}.status`);\n}\n\nexport function eventsPath(logDir: string, id: string): string {\n return join(logDir, `${id}.jsonl`);\n}\n\nexport function ledgerPath(logDir: string): string {\n return join(logDir, \"ledger.log\");\n}\n\nexport function routingStatePath(logDir: string): string {\n return join(logDir, \"routing-state.json\");\n}\n\nexport function panesDir(logDir: string): string {\n return join(logDir, \"panes\");\n}\n\n/**\n * The strict empty MCP config handed to headless workers. Written into the\n * logDir on demand (never into the user's vendor config directory — this is\n * PAI state, not vendor state).\n */\nexport function noMcpConfigPath(logDir: string): string {\n return join(logDir, \"no-mcp.json\");\n}\n","/**\n * args.ts — parse the claude-args tail that `pai worker run` receives.\n *\n * The runner needs a few things out of the caller's argument vector: the\n * prompt (for the default label), the requested --output-format (so the final\n * print matches what plain `claude -p` would have produced), whether the\n * caller already chose a --model or an --mcp-config (both suppress the\n * defaults the runner would otherwise force), any --mcp allowlist names, any\n * --allowedTools grants (their mcp__server__… entries decide which servers\n * load), and whether they appended their own system prompt (the worker\n * contract is then added alongside, not instead). Everything is passed\n * through untouched — the runner never rewrites the caller's task.\n */\n\nexport interface ParsedRunnerArgs {\n /** Prompt string after -p/--print, when the run is headless. */\n prompt: string | null;\n /** Caller's --output-format: text (default), json, or stream-json. */\n outputFormat: \"text\" | \"json\" | \"stream-json\";\n /** Args to hand to claude (minus --output-format/--verbose, which we add). */\n rest: string[];\n /** Headless: a -p/--print flag is present. */\n headless: boolean;\n /** Caller passed --model (or --model=…): do not force the provider model. */\n callerModel: boolean;\n /** Caller passed --mcp-config (or --mcp-config=…): keep their MCP setup. */\n callerMcpConfig: boolean;\n /** Caller passed --append-system-prompt: the contract is added alongside. */\n callerSystemPrompt: boolean;\n /** The caller's --append-system-prompt texts, pulled out of `rest` (claude keeps only the last flag). */\n callerSystemPrompts: string[];\n /** Caller passed --tools (or --tools=…): a project's `pai project tools` pin does not apply. */\n callerTools: boolean;\n /** --mcp values (repeatable, comma-separated inside one flag). */\n mcp: string[];\n /** --allowedTools values (repeatable, comma-separated inside one flag). */\n allowedTools: string[];\n}\n\nexport function parseRunnerArgs(argv: string[]): ParsedRunnerArgs {\n let prompt: string | null = null;\n let outputFormat: ParsedRunnerArgs[\"outputFormat\"] = \"text\";\n const rest: string[] = [];\n let headless = false;\n let callerModel = false;\n let callerMcpConfig = false;\n let callerSystemPrompt = false;\n const callerSystemPrompts: string[] = [];\n let callerTools = false;\n const mcp: string[] = [];\n const allowedTools: string[] = [];\n\n let i = 0;\n while (i < argv.length) {\n const a = argv[i];\n if (a === \"-p\" || a === \"--print\") {\n headless = true;\n rest.push(a);\n if (i + 1 < argv.length && !argv[i + 1].startsWith(\"-\")) {\n prompt = argv[i + 1];\n rest.push(prompt);\n i += 1;\n }\n } else if (a === \"--output-format\") {\n const v = argv[i + 1];\n if (v === \"json\" || v === \"stream-json\") outputFormat = v;\n i += 1; // dropped; the runner prints the result in this format itself\n } else if (a.startsWith(\"--output-format=\")) {\n const v = a.slice(\"--output-format=\".length);\n if (v === \"json\" || v === \"stream-json\") outputFormat = v;\n } else if (a === \"--verbose\") {\n // dropped; re-added by the runner\n } else if (a === \"--append-system-prompt\") {\n callerSystemPrompt = true;\n if (i + 1 < argv.length) callerSystemPrompts.push(argv[++i]);\n } else if (a.startsWith(\"--append-system-prompt=\")) {\n callerSystemPrompt = true;\n callerSystemPrompts.push(a.slice(\"--append-system-prompt=\".length));\n } else if (a === \"--mcp\") {\n const v = argv[i + 1];\n if (v !== undefined && !v.startsWith(\"-\")) {\n mcp.push(v);\n i += 1;\n }\n } else if (a.startsWith(\"--mcp=\")) {\n mcp.push(a.slice(\"--mcp=\".length));\n } else if (a === \"--allowedTools\") {\n // captured for the MCP derivation, but still claude's flag: it passes through\n rest.push(a);\n const v = argv[i + 1];\n if (v !== undefined && !v.startsWith(\"-\")) {\n allowedTools.push(v);\n rest.push(v);\n i += 1;\n }\n } else if (a.startsWith(\"--allowedTools=\")) {\n allowedTools.push(a.slice(\"--allowedTools=\".length));\n rest.push(a);\n } else {\n if (a === \"--model\") callerModel = true;\n if (a.startsWith(\"--model=\")) callerModel = true;\n if (a === \"--mcp-config\") callerMcpConfig = true;\n if (a.startsWith(\"--mcp-config=\")) callerMcpConfig = true;\n if (a === \"--tools\") callerTools = true;\n if (a.startsWith(\"--tools=\")) callerTools = true;\n if (\n prompt === null && !a.startsWith(\"-\") && rest.length > 0 &&\n (rest[rest.length - 1] === \"-p\" || rest[rest.length - 1] === \"--print\")\n ) {\n prompt = a;\n }\n rest.push(a);\n }\n i += 1;\n }\n\n return {\n prompt,\n outputFormat,\n rest,\n headless,\n callerModel,\n callerMcpConfig,\n callerSystemPrompt,\n callerSystemPrompts,\n callerTools,\n mcp,\n allowedTools,\n };\n}\n\n/**\n * The one --append-system-prompt flag for a spawn: claude keeps only the LAST\n * occurrence, so every piece is joined (blank line between) into a single flag.\n * Empty parts are dropped; no parts, no flag.\n */\nexport function appendSystemPromptArgs(parts: string[]): string[] {\n const text = parts.filter((p) => p.trim()).join(\"\\n\\n\");\n return text ? [\"--append-system-prompt\", text] : [];\n}\n\n/**\n * Turn `-p \"<prompt>\"` into bare `-p` (same for --print): for stream-json\n * stdin runs the prompt moves to the first user message on stdin, so the\n * value must not stay on the command line. Only prompt values directly\n * following the flag are touched; everything else passes through.\n */\nexport function stripPromptValues(argv: string[]): string[] {\n const out: string[] = [];\n for (let i = 0; i < argv.length; i++) {\n const a = argv[i];\n const isPrint = a === \"-p\" || a === \"--print\";\n out.push(a);\n if (isPrint && i + 1 < argv.length && !argv[i + 1].startsWith(\"-\")) {\n i += 1; // drop the prompt value; the flag itself stays\n }\n }\n return out;\n}\n\n/**\n * A one-line stderr hint (never blocking) for an inline -p prompt long or\n * multi-line enough to be a shell-quoting risk — write it to a file and pass\n * --spec instead. null when the prompt is short/simple enough to be fine.\n */\nexport function longInlinePromptHint(prompt: string | null): string | null {\n if (!prompt) return null;\n const newlines = (prompt.match(/\\n/g) ?? []).length;\n if (prompt.length > 600 || newlines > 3) {\n return \"hint: long inline prompts break on shell quoting — write the spec to a file and use --spec <file>\";\n }\n return null;\n}\n\n/** Collapse whitespace and cut to n chars with an ellipsis (label rendering). */\nexport function shortText(s: unknown, n: number): string {\n const t = String(s ?? \"\").split(/\\s+/).filter(Boolean).join(\" \");\n return t.length <= n ? t : t.slice(0, n - 1) + \"…\";\n}\n","/**\n * status.ts — the live per-worker status file.\n *\n * One JSON file per run, rewritten atomically on every turn, read by `ps`,\n * `follow`, the status line and the pane logic. Same field set the Python\n * runner wrote, plus `provider` (routing is multi-provider now) and `session`\n * (the AIBroker identity of the launching session, see scope.ts).\n */\n\nimport { execFileSync } from \"node:child_process\";\nimport {\n existsSync,\n mkdirSync,\n readFileSync,\n readdirSync,\n renameSync,\n rmSync,\n writeFileSync,\n} from \"node:fs\";\nimport { join } from \"node:path\";\nimport { shortText } from \"./args.js\";\nimport { statusPath } from \"./paths.js\";\n\nexport interface WorkerSessionRef {\n /** AIBroker/iTerm session id (the iTerm UUID). */\n id: string;\n /** AIBroker name of that session, when it has one. */\n name: string;\n}\n\nexport interface WorkerStatus {\n id: string;\n pid: number;\n label: string;\n cwd: string;\n /** iTerm session id of the launching terminal (\"\" outside iTerm). */\n term: string;\n provider: string;\n model: string;\n state: \"running\" | \"done\" | \"failed\" | \"killed\" | \"lost\";\n started: string;\n updated: string;\n turns: number;\n tools: number;\n last: string;\n rc: number | null;\n secs: number | null;\n /** Launching session resolved through AIBroker, when it was. */\n session?: WorkerSessionRef | null;\n /** Claude Code session id (system/init) — what `resume` continues. */\n claudeSession?: string | null;\n /**\n * Claude Code session id of the orchestrator whose Bash launched this run,\n * when the status line's session map knew it (see scope.ts). Distinct from\n * claudeSession, which is the run's own session.\n */\n spawnerSession?: string | null;\n /** Context meter: tokens of the last assistant turn (input+cache+output). */\n contextTokens?: number | null;\n /** Context meter: window size (init model info or provider default). */\n contextWindow?: number | null;\n /** Path the prompt was read from via --spec (\"-\" for stdin), when it was. */\n spec?: string | null;\n /**\n * Caller's --output-format, when the run was headless. A json/stream-json\n * caller reads its own result and is notified on process exit by the\n * harness — supervision.ts uses this to skip the duplicate relay send.\n */\n outputFormat?: \"text\" | \"json\" | \"stream-json\";\n /** Chain this stage belongs to (the chain id), when it is a chain stage. */\n parent?: string;\n /** Class name of the chain stage (\"draft\", \"implement\", …). */\n stage?: string;\n /** Worktree this run executed in, when it got one (see worktree.ts). */\n worktreeDir?: string | null;\n /** Branch the worker committed on (worker/<id>), set on worktree runs. */\n branch?: string | null;\n /** Commit the branch started from (worktree base) for the commits count. */\n worktreeBase?: string | null;\n /** Whether `worktreeBase` is a snapshot of uncommitted checkout state, not HEAD. */\n worktreeSnapshot?: boolean | null;\n /** Commits the worker made on its branch; set with `branch` on success. */\n commits?: number | null;\n /** Set by `pai worker merge` once the branch landed in the original checkout. */\n merged?: boolean;\n /** Set by `pai worker gc`: the hidden ref (refs/pai-archive/<id>) holding the leftover worktree's state. */\n archived?: string | null;\n /**\n * How the run came to be: \"spawn\" (a `pai worker run` subagent) or \"chat\"\n * (the terminal's interactive pane itself, tracked like a worker). Absent\n * on statuses written before the flag existed — read as a spawn.\n */\n origin?: \"spawn\" | \"chat\";\n /** Which contract/parser this run used for its final report (see report.ts). */\n reportFormat?: \"json\" | \"ag2\";\n /** Whether the final AG2 report passed `aibroker agentish check`; unset for json reports or when no validator ran. */\n reportValid?: boolean;\n /** Validation error messages, when reportValid is false. */\n reportErrors?: string[];\n /** Whether the headless prompt got the end-of-turn \"final message must be…\" trailer line. */\n promptTrailer?: boolean;\n /** Whether an invalid AG2 final message triggered the one bounded re-ask (see run.ts). */\n reportRetried?: boolean;\n /**\n * Consecutive failed tool executions in this run, maintained by the runner's\n * stream loop (0 after any success). Absent on old status files — every\n * reader must treat that as \"no signal\".\n */\n consecFails?: number | null;\n /**\n * Seconds of the most recent single long sleep observed in a Bash tool_use\n * (see parseSleepSecs), cleared when the command completes. Absent on old\n * status files.\n */\n sleepSec?: number | null;\n /** Epoch ms the run is stopped at (deadline.ts); absent = no limit. */\n deadlineAt?: number | null;\n /** Limit in minutes the deadline was derived from. */\n maxMinutes?: number | null;\n /** The deadline stopped this run (state failed, `last` says why). */\n timedOut?: boolean;\n /** Launching process (the parent of `pai worker run`) at start, and its command name. */\n parentPid?: number;\n parentComm?: string;\n parentBackground?: boolean;\n /** Why the run ended (endreason.ts): exit, deadline, pai-worker-kill, parent-gone, external-signal. */\n endReason?: string;\n /** Who asked for the stop, when known (kill caller, daemon:<reason>). */\n endBy?: string;\n /** Detail for the reason (signal, sender note). */\n endNote?: string;\n /** Ever granted clickr desktop controls (see controls.ts) — the runner returns them best-effort on exit. */\n controlsHeld?: boolean;\n}\n\n/** Label a worker gets when launched with neither --label nor a prompt. */\nexport const UNLABELED = \"unlabeled\";\n\n/**\n * Whether a status is the terminal's interactive chat pane, not a spawned\n * task worker. `origin` is the real discriminator; the fallback catches\n * running entries from before the flag existed (unlabeled, no turns yet).\n * Removable once every pane runs code that writes `origin`.\n */\nexport function isChatPane(s: Pick<WorkerStatus, \"origin\" | \"label\" | \"turns\">): boolean {\n return (\n s.origin === \"chat\" ||\n (!s.origin && (s.label === UNLABELED || s.label === \"(no prompt)\") && s.turns === 0)\n );\n}\n\n/** Context-meter percentage 0–100, null when the numbers are missing. */\nexport function contextPercent(s: Pick<WorkerStatus, \"contextTokens\" | \"contextWindow\">): number | null {\n if (!s.contextTokens || !s.contextWindow) return null;\n return Math.round((s.contextTokens / s.contextWindow) * 100);\n}\n\n/** Compact token count: 84k, 200k, 900. */\nexport function fmtContextK(n: number): string {\n return n >= 1000 ? `${Math.round(n / 1000)}k` : String(n);\n}\n\n/**\n * The one context-meter label, shared by every renderer so identical\n * numbers always render identically: `ctx 84k/200k (42%)` — used-style\n * percent. Empty when the numbers are missing (callers drop the part).\n */\nexport function contextLabel(\n s: Pick<WorkerStatus, \"contextTokens\" | \"contextWindow\">\n): string {\n const pct = contextPercent(s);\n if (pct === null) return \"\";\n return `ctx ${fmtContextK(s.contextTokens ?? 0)}/${fmtContextK(s.contextWindow ?? 0)} (${pct}%)`;\n}\n\n/** Timestamp format shared by status files and the ledger. */\nexport function nowStamp(d: Date = new Date()): string {\n const p = (n: number) => String(n).padStart(2, \"0\");\n return (\n `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ` +\n `${p(d.getHours())}:${p(d.getMinutes())}:${p(d.getSeconds())}`\n );\n}\n\n// second-resolution ids repeat when two workers/chains start together in one\n// process; a repeat gets a monotonic suffix so files never collide\nlet lastId = \"\";\nlet idSeq = 0;\n\nexport function newWorkerId(d: Date = new Date(), pid = process.pid): string {\n const p = (n: number) => String(n).padStart(2, \"0\");\n const base = `${d.getFullYear()}${p(d.getMonth() + 1)}${p(d.getDate())}-${p(d.getHours())}${p(d.getMinutes())}${p(d.getSeconds())}-${pid}`;\n if (base === lastId) {\n idSeq += 1;\n return `${base}-${String(idSeq).padStart(2, \"0\")}`;\n }\n lastId = base;\n idSeq = 0;\n return base;\n}\n\n// Temp names must be unique per writer, not just per worker: two processes\n// legitimately write the same id at the same moment (`pai worker kill` marking\n// a run killed while the run's own SIGTERM handler writes its terminal state).\n// With one shared `<id>.status.tmp` they clobber each other's temp file and the\n// loser's rename fails with ENOENT — observed live on 2026-09-19.\nlet tmpSeq = 0;\n\n/** A temp path only this call owns — never the same string twice. */\nexport function statusTmpPath(logDir: string, id: string): string {\n return `${statusPath(logDir, id)}.${process.pid}.${tmpSeq++}.tmp`;\n}\n\n// The label this process first wrote for a given worker id: run.ts holds one\n// unchanging label in memory for the whole run and passes it to every\n// periodic saveStatus call, so a later call whose label still equals this\n// baseline is that unmodified write, never an intentional change — on-disk\n// then wins, so an external `pai worker goal` relabel between two of a\n// worker's own writes survives instead of being reverted by the next one. A\n// call whose label differs from the baseline (or the first call for an id in\n// this process, which has no baseline yet) IS the intentional change and\n// always wins — exactly the one-shot `pai worker goal` process itself.\nconst firstWrittenLabel = new Map<string, string>();\n\n/** Write status atomically (temp + rename) and stamp `updated`. */\nexport function saveStatus(logDir: string, status: WorkerStatus, d: Date = new Date()): void {\n status.updated = nowStamp(d);\n const path = statusPath(logDir, status.id);\n const baseline = firstWrittenLabel.get(status.id);\n if (baseline === undefined) {\n firstWrittenLabel.set(status.id, status.label);\n }\n const onDisk = baseline === undefined ? undefined : loadStatus(logDir, status.id);\n if (onDisk) {\n if (status.label === baseline && onDisk.label !== status.label) status.label = onDisk.label;\n // Set by another process (`pai worker controls`); a true flag is never dropped by a stale in-memory copy.\n if (onDisk.controlsHeld) status.controlsHeld = true;\n }\n const tmp = statusTmpPath(logDir, status.id);\n if (!existsSync(logDir)) mkdirSync(logDir, { recursive: true });\n try {\n writeFileSync(tmp, JSON.stringify(status), \"utf8\");\n renameSync(tmp, path);\n } catch (e) {\n try {\n rmSync(tmp, { force: true });\n } catch {\n // nothing to clean up\n }\n throw e;\n }\n}\n\n/**\n * Set a worker's goal (the operator's `--label`), atomically, through the\n * same saveStatus path everything else writes with. Used by `pai worker\n * goal` and the `--goal` option of `say`: a fresh call in a fresh process, so\n * it always carries no baseline yet and always wins over the worker's own\n * next periodic write (see saveStatus above).\n */\nexport function setWorkerLabel(logDir: string, id: string, label: string): WorkerStatus {\n const status = loadStatus(logDir, id);\n if (!status) throw new Error(`no worker named \"${id}\"`);\n status.label = label;\n saveStatus(logDir, status);\n return status;\n}\n\n/** Load every status file in the logDir, oldest id first, skipping damage. */\nexport function loadStatuses(logDir: string): WorkerStatus[] {\n if (!existsSync(logDir)) return [];\n const out: WorkerStatus[] = [];\n for (const name of readdirSync(logDir).sort()) {\n if (!name.endsWith(\".status\")) continue;\n try {\n out.push(JSON.parse(readFileSync(join(logDir, name), \"utf8\")) as WorkerStatus);\n } catch {\n // a half-written or damaged status file is not worth a crash\n }\n }\n return out;\n}\n\nexport function loadStatus(logDir: string, id: string): WorkerStatus | null {\n const path = statusPath(logDir, id);\n if (!existsSync(path)) return null;\n try {\n return JSON.parse(readFileSync(path, \"utf8\")) as WorkerStatus;\n } catch {\n return null;\n }\n}\n\n/**\n * Wait for a worker to record its own terminal state (the run's signal\n * handler writes killed/rc/secs). Returns that status, or null when it is\n * still \"running\" after `timeoutMs` — the caller then writes the state itself.\n */\nexport async function waitForTerminalStatus(\n logDir: string,\n id: string,\n timeoutMs = 2000,\n stepMs = 50\n): Promise<WorkerStatus | null> {\n const deadline = Date.now() + timeoutMs;\n for (;;) {\n const s = loadStatus(logDir, id);\n if (s && s.state !== \"running\") return s;\n if (Date.now() >= deadline) return null;\n await new Promise((r) => setTimeout(r, stepMs));\n }\n}\n\nexport function alive(pid: number | null | undefined): boolean {\n if (!pid || pid <= 0) return false;\n try {\n process.kill(pid, 0);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Whether `status.pid` still names the process that was started as this\n * worker, not a later, unrelated process the OS handed the same pid to after\n * the worker exited. `alive()` alone can't tell these apart — a pid observed\n * live on 2026-09-19 (worker 20260919-083549-90913) had been reused, and\n * `pai worker kill` signalled the wrong, unrelated process. `ps -o lstart=`\n * reads the running process's actual start time and compares it against the\n * status file's own `started` stamp; a reused pid almost never starts within\n * 120s of the original, so a wider drift means \"different process\".\n */\nexport function ownsPid(status: Pick<WorkerStatus, \"pid\" | \"started\">): boolean {\n if (status.pid <= 0 || !alive(status.pid)) return false;\n try {\n const out = execFileSync(\"ps\", [\"-o\", \"lstart=\", \"-p\", String(status.pid)], {\n encoding: \"utf8\",\n env: { ...process.env, LC_ALL: \"C\" },\n }).trim();\n const psStart = Date.parse(out);\n const started = Date.parse(status.started.replace(\" \", \"T\"));\n if (Number.isNaN(psStart) || Number.isNaN(started)) return alive(status.pid);\n return Math.abs(psStart - started) <= 120_000;\n } catch {\n // pid exited between the alive() check and the ps call, or ps failed for\n // another reason — the pid-existence check is still better than nothing.\n return alive(status.pid);\n }\n}\n\n/** Whether a status is both marked \"running\" and still owns its recorded pid. */\nexport function isLive(status: Pick<WorkerStatus, \"pid\" | \"started\" | \"state\">): boolean {\n return status.state === \"running\" && ownsPid(status);\n}\n\n/** \"42s\" under 90s, \"7m\" above — the coarse age the table and bar show. */\nexport function ageOf(ts: string, now: Date = new Date()): string {\n const t = Date.parse(ts.replace(\" \", \"T\"));\n if (Number.isNaN(t)) return \"?\";\n const s = Math.max(0, Math.floor((now.getTime() - t) / 1000));\n return s < 90 ? `${s}s` : `${Math.floor(s / 60)}m`;\n}\n\n/** Precise elapsed time: \"45s\", \"1m 23s\", \"12m 05s\", \"1h 02m 05s\" — seconds zero-padded after a larger unit. */\nexport function elapsedOf(ts: string, now: Date = new Date()): string {\n const t = Date.parse(ts.replace(\" \", \"T\"));\n if (Number.isNaN(t)) return \"?\";\n const secs = Math.max(0, Math.floor((now.getTime() - t) / 1000));\n const hours = Math.floor(secs / 3600);\n const mins = Math.floor((secs % 3600) / 60);\n const sec = secs % 60;\n if (hours > 0) return `${hours}h ${String(mins).padStart(2, \"0\")}m ${String(sec).padStart(2, \"0\")}s`;\n if (mins > 0) return `${mins}m ${String(sec).padStart(2, \"0\")}s`;\n return `${sec}s`;\n}\n\n/** Shorter sleeps are legitimate polling — not worth a supervision event. */\nexport const SLEEP_FLOOR_SECS = 60;\n\nconst SLEEP_RE = /^\\s*sleep\\s+([0-9]+(?:\\.[0-9]+)?)([smhd]?)\\s*(?:$|[;&|])/;\n\n/** s/m/h/d suffix to seconds multiplier, shared by every `sleep N<unit>` parse below. */\nfunction sleepUnitMultiplier(unit: string): number {\n return unit === \"m\" ? 60 : unit === \"h\" ? 3600 : unit === \"d\" ? 86_400 : 1;\n}\n\n/**\n * Seconds of a `sleep N` (N plain or with an s/m/h/d suffix) that stands alone\n * or leads a compound command (`sleep 150; cat f`, `sleep 2m && tail f`,\n * `sleep 90 || true`, `sleep 60 &`), or null when no long sleep leads: anchored\n * to the start of the command, so a filename containing \"sleep\" or an\n * `echo sleep 500` never trips it, and floored at SLEEP_FLOOR_SECS so ordinary\n * polling stays invisible.\n */\nexport function parseSleepSecs(command: string): number | null {\n const m = command.match(SLEEP_RE);\n if (!m) return null;\n const secs = Number(m[1]) * sleepUnitMultiplier(m[2]);\n return Number.isFinite(secs) && secs >= SLEEP_FLOOR_SECS ? secs : null;\n}\n\n/**\n * Every command-segment boundary a shell recognises before a new simple\n * command can start: the very start of the string, `;`, `&`/`&&`, `|`/`||`,\n * a newline, an opening `(` or `{` (also covers `$(...)`, which ends in `(`),\n * or the keywords `do`/`then`. Segment end is the mirror image plus a closing\n * `)`, so `sleep 90` inside `$(sleep 90)` or `(sleep 90)` still counts.\n */\n// The terminator is a lookahead, not a consumed match: two sleeps sharing one\n// separator (`sleep 65; sleep 590`) both need that `;` available as their own\n// boundary — matchAll never revisits a character a previous match consumed.\nconst SLEEP_SEGMENT_RE =\n /(?:^|[;&|\\n(){]|\\bdo\\b|\\bthen\\b)\\s*sleep\\s+([0-9]+(?:\\.[0-9]+)?)([smhd]?)(?=\\s*(?:$|[;&|)\\n]))/g;\n\n/**\n * The longest `sleep N` found as its OWN command segment anywhere in\n * `command` — not just leading it, unlike {@link parseSleepSecs} — or null\n * when none reaches SLEEP_FLOOR_SECS. Used by the PreToolUse Bash gate\n * (block-sleep-poll.ts), which must catch a sleep buried after `&&`, inside a\n * `do ... done` loop, or in a subshell, not only one that leads the command.\n */\nexport function longestSleepSecs(command: string): number | null {\n let longest: number | null = null;\n for (const m of command.matchAll(SLEEP_SEGMENT_RE)) {\n const secs = Number(m[1]) * sleepUnitMultiplier(m[2]);\n if (!Number.isFinite(secs) || secs < SLEEP_FLOOR_SECS) continue;\n if (longest === null || secs > longest) longest = secs;\n }\n return longest;\n}\n\nconst LOOP_RE = /\\b(for|while|until)\\b([^;\\n]*)[;\\n]\\s*do\\b([\\s\\S]*?)\\bdone\\b/g;\n\nfunction sleepSum(text: string): number {\n let sum = 0;\n for (const m of text.matchAll(SLEEP_SEGMENT_RE)) {\n const secs = Number(m[1]) * sleepUnitMultiplier(m[2]);\n if (Number.isFinite(secs)) sum += secs;\n }\n return sum;\n}\n\n/** Iterations of a `for x in <words>` header, or null when not provably small. */\nfunction forIterations(header: string): number | null {\n const words = header.replace(/^\\s*\\w+\\s+in\\s+/, \"\").trim();\n if (words === header.trim() || /[$`*?]/.test(words)) return null;\n const range = /^\\{(-?\\d+)\\.\\.(-?\\d+)\\}$/.exec(words);\n if (range) return Math.abs(Number(range[2]) - Number(range[1])) + 1;\n return words ? words.split(/\\s+/).length : 0;\n}\n\n/**\n * Total sleep of one Bash command: every `sleep N` segment counted once, plus\n * loop repetition — `for x in a b c` multiplies its body by the word count;\n * `while`/`until` and any unbounded `for` count as at least SLEEP_FLOOR_SECS,\n * except a `kill -0` job-wait (the sanctioned wait-for-a-job loop). Used by\n * the PreToolUse gate so `sleep 58; sleep 58` is caught as the 116 s it is.\n */\n// ponytail: loops are not nested-aware (body ends at the first `done`); upgrade to a real shell parse if that bites.\nexport function totalSleepSecs(command: string): number {\n let total = sleepSum(command);\n for (const m of command.matchAll(LOOP_RE)) {\n const body = sleepSum(m[3]);\n if (body === 0) continue;\n if (m[1] === \"for\") {\n const n = forIterations(m[2]);\n total += n === null ? Math.max(SLEEP_FLOOR_SECS, body) : body * (n - 1);\n } else if (!/\\bkill\\s+-0\\b/.test(m[2])) {\n total += SLEEP_FLOOR_SECS;\n }\n }\n return total;\n}\n\n/** One-line description of a tool call, e.g. \"Bash: npm test\". */\nexport function describeTool(name: string, inp: unknown): string {\n if (typeof inp !== \"object\" || inp === null) return name;\n const i = inp as Record<string, unknown>;\n const get = (k: string) => (typeof i[k] === \"string\" ? (i[k] as string) : \"\");\n if (name === \"Bash\") return `Bash: ${shortText(get(\"command\"), 70)}`;\n if (name === \"Read\" || name === \"Edit\" || name === \"Write\" || name === \"MultiEdit\") {\n const file = get(\"file_path\").split(\"/\").pop() ?? \"\";\n return `${name}: ${file}`;\n }\n if (name === \"Grep\" || name === \"Glob\") return `${name}: ${shortText(get(\"pattern\"), 50)}`;\n if (name === \"WebSearch\") return `${name}: ${shortText(get(\"query\"), 50)}`;\n if (name === \"WebFetch\") return `${name}: ${shortText(get(\"url\"), 60)}`;\n return name;\n}\n","/**\n * ledger.ts — the routing ledger, one append-only log for every worker event.\n *\n * Line shapes (whitespace-aligned so `tail` reads as a table):\n *\n * 2026-09-17 12:00:00 WORKER-START id=<id> provider=<p> mode=headless model=<m> cwd=<cwd> label=<label>\n * 2026-09-17 12:01:00 WORKER-END id=<id> provider=<p> mode=headless model=<m> rc=0 secs=60 turns=3 tools=8 label=<label>\n * 2026-09-17 12:00:20 WORKER-REROUTE from=<a> to=<b> reason=quota\n * 2026-09-17 12:00:00 DENIED-ANTHROPIC-AGENT cwd=<cwd> desc=<desc>\n * 2026-09-17 12:00:00 ALLOWED-ANTHROPIC-AGENT cwd=<cwd> desc=<desc>\n *\n * `pai worker log` (and glm-log before it) counts these; keep the tags stable.\n */\n\nimport { appendFileSync, existsSync, mkdirSync, readFileSync } from \"node:fs\";\nimport { dirname } from \"node:path\";\n\nexport function ledgerStamp(d: Date = new Date()): string {\n const p = (n: number) => String(n).padStart(2, \"0\");\n return (\n `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ` +\n `${p(d.getHours())}:${p(d.getMinutes())}:${p(d.getSeconds())}`\n );\n}\n\nexport interface LedgerLine {\n stamp: string;\n event: string;\n fields: Record<string, string>;\n}\n\n/** Parse `2026-09-17 12:00:00 TAG key=value …` into its parts. */\nexport function parseLedgerLine(line: string): LedgerLine | null {\n const m = line.match(/^(\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}) (\\S+)(?: (.*))?$/);\n if (!m) return null;\n const fields: Record<string, string> = {};\n // values are whitespace-collapsed by the writers, so spaces safely delimit\n for (const part of (m[3] ?? \"\").split(\" \")) {\n if (!part) continue;\n const eq = part.indexOf(\"=\");\n if (eq <= 0) continue;\n fields[part.slice(0, eq)] = part.slice(eq + 1);\n }\n return { stamp: m[1], event: m[2], fields };\n}\n\nexport function parseLedger(text: string): LedgerLine[] {\n const out: LedgerLine[] = [];\n for (const line of text.split(\"\\n\")) {\n if (!line.trim()) continue;\n const parsed = parseLedgerLine(line);\n if (parsed) out.push(parsed);\n }\n return out;\n}\n\n/** Append one ledger line. `kv` order is the caller's; values are flattened. */\nexport function appendLedger(\n path: string,\n event: string,\n kv: Record<string, string | number | null | undefined>,\n now: Date = new Date()\n): void {\n const parts: string[] = [];\n for (const [k, v] of Object.entries(kv)) {\n if (v === undefined || v === null) continue;\n parts.push(`${k}=${String(v).replace(/\\s+/g, \" \")}`);\n }\n const dir = dirname(path);\n if (!existsSync(dir)) mkdirSync(dir, { recursive: true });\n const tail = parts.length ? \" \" + parts.join(\" \") : \"\";\n appendFileSync(path, `${ledgerStamp(now)} ${event}${tail}\\n`, \"utf8\");\n}\n\nexport interface LedgerSummary {\n scope: string;\n started: number;\n endedOk: number;\n endedFailed: number;\n denied: number;\n allowed: number;\n reroutes: number;\n lastLines: string[];\n}\n\n/** The counts `pai worker log` prints, over today's lines or the whole file. */\nexport function ledgerSummary(\n path: string,\n scope: \"today\" | \"all\",\n lastN = 15,\n now: Date = new Date()\n): LedgerSummary | null {\n if (!existsSync(path)) return null;\n const text = readFileSync(path, \"utf8\");\n const today = ledgerStamp(now).slice(0, 10);\n const lines = text.split(\"\\n\").filter((l) => l.trim());\n const scoped =\n scope === \"all\" ? lines : lines.filter((l) => l.startsWith(today));\n const parsed = scoped.map(parseLedgerLine).filter((x): x is LedgerLine => x !== null);\n const count = (ev: string) => parsed.filter((p) => p.event === ev).length;\n const ends = parsed.filter((p) => p.event === \"WORKER-END\");\n const ok = ends.filter((p) => p.fields.rc === \"0\").length;\n return {\n scope: scope === \"all\" ? \"all time\" : `today ${today}`,\n started: count(\"WORKER-START\"),\n endedOk: ok,\n endedFailed: ends.length - ok,\n denied: count(\"DENIED-ANTHROPIC-AGENT\"),\n allowed: count(\"ALLOWED-ANTHROPIC-AGENT\"),\n reroutes: count(\"WORKER-REROUTE\"),\n lastLines: lines.slice(-lastN),\n };\n}\n","/**\n * Pending worker results: finished workers whose worktree branch still holds\n * work that never reached the repo (commits not in HEAD, or uncommitted\n * files). Surfaced by `pai worker ps/pending`, the SessionStart hook, the\n * status line and the prepublish gate so an unmerged fix cannot be forgotten.\n */\n\nimport { existsSync, readFileSync, statSync, writeFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { isLive, loadStatuses } from \"./status.js\";\nimport { statusPath } from \"./paths.js\";\nimport { git, uncommittedPaths } from \"./worktree.js\";\n\nexport interface PendingResult {\n id: string;\n label: string;\n repo: string;\n /** ms since the worker's status file last changed (its end). */\n ageMs: number;\n age: string;\n /** commits on the branch not in the repo's HEAD (patch-id aware). */\n commits: number;\n /** uncommitted paths in the worktree, node_modules excluded. */\n dirty: number;\n}\n\n/** Stale after this long: `pai worker gc` (archive) instead of merge. */\nexport const STALE_HOURS = 24;\n\nfunction toplevel(dir: string): string | null {\n try {\n return git(dir, [\"rev-parse\", \"--show-toplevel\"]);\n } catch {\n return null;\n }\n}\n\nfunction fmtAge(ms: number): string {\n const h = Math.floor(ms / 3_600_000);\n return h >= 48 ? `${Math.floor(h / 24)}d` : h >= 1 ? `${h}h` : `${Math.floor(ms / 60_000)}m`;\n}\n\n/** Finished workers with unmerged work; `repoRoot` limits to one repo, else every repo. */\nexport function pendingResults(logDir: string, repoRoot?: string, now = Date.now()): PendingResult[] {\n const want = repoRoot ? toplevel(repoRoot) : null;\n if (repoRoot && !want) return [];\n const out: PendingResult[] = [];\n for (const st of loadStatuses(logDir)) {\n if (st.archived || st.merged || isLive(st)) continue;\n if (!st.worktreeDir || !existsSync(st.worktreeDir)) continue;\n const repo = toplevel(st.cwd);\n if (!repo || (want && repo !== want)) continue;\n let commits = 0;\n let dirty = 0;\n try {\n if (st.branch) {\n commits = git(repo, [\"cherry\", \"HEAD\", `refs/heads/${st.branch}`])\n .split(\"\\n\")\n .filter((l) => l.startsWith(\"+\")).length;\n }\n dirty = uncommittedPaths(st.worktreeDir).filter((p) => !/(^|\\/)node_modules(\\/|$)/.test(p)).length;\n } catch {\n continue; // branch or worktree unreadable: nothing verifiable to report\n }\n if (!commits && !dirty) continue;\n let ageMs = 0;\n try {\n ageMs = Math.max(0, now - statSync(statusPath(logDir, st.id)).mtimeMs);\n } catch {\n // status vanished mid-scan: age unknown, keep the entry\n }\n out.push({ id: st.id, label: st.label, repo, ageMs, age: fmtAge(ageMs), commits, dirty });\n }\n return out;\n}\n\n/** One human line per result, with the exact next command. */\nexport function formatPending(results: PendingResult[], showRepo = false): string {\n return results\n .map((r) => {\n const next = r.ageMs > STALE_HOURS * 3_600_000 ? \"pai worker gc\" : `pai worker merge ${r.id}`;\n const repo = showRepo ? ` ${r.repo}` : \"\";\n return `${r.id} ${r.age} ${r.commits} commit(s), ${r.dirty} dirty ${r.label}${repo} -> ${next}`;\n })\n .join(\"\\n\");\n}\n\n/**\n * Release gate: exit code and message for `pai worker pending --gate`.\n * PAI_ALLOW_PENDING=1 overrides.\n */\nexport function pendingGate(\n results: PendingResult[],\n env: NodeJS.ProcessEnv = process.env\n): { code: number; message: string } {\n if (!results.length || env.PAI_ALLOW_PENDING === \"1\") return { code: 0, message: \"\" };\n return {\n code: 1,\n message:\n `${results.length} unmerged worker result(s) in this repo — merge or discard before publishing:\\n` +\n `${formatPending(results)}\\n` +\n \"Override deliberately with PAI_ALLOW_PENDING=1.\",\n };\n}\n\n/** Cached count of pending results for `cwd`'s repo (statusline/hook: cheap on repeat). */\nexport function pendingCountCached(logDir: string, cwd: string, ttlMs = 60_000, now = Date.now()): number {\n const file = join(logDir, \"pending-cache.json\");\n let cache: Record<string, { at: number; n: number }> = {};\n try {\n cache = JSON.parse(readFileSync(file, \"utf8\"));\n } catch {\n // no cache yet\n }\n const hit = cache[cwd];\n if (hit && now - hit.at < ttlMs) return hit.n;\n const n = pendingResults(logDir, cwd, now).length;\n try {\n writeFileSync(file, JSON.stringify({ ...cache, [cwd]: { at: now, n } }));\n } catch {\n // read-only log dir: recompute next time\n }\n return n;\n}\n\n/** Invalidate pending cache entries for a repo and its subdirectories. */\nexport function invalidatePendingCache(logDir: string, repoRoot: string): void {\n const file = join(logDir, \"pending-cache.json\");\n let cache: Record<string, { at: number; n: number }> = {};\n try {\n cache = JSON.parse(readFileSync(file, \"utf8\"));\n } catch {\n // no cache yet\n return;\n }\n const resolved = repoRoot.endsWith(\"/\") ? repoRoot : `${repoRoot}/`;\n let changed = false;\n for (const key of Object.keys(cache)) {\n if (key === repoRoot || key.startsWith(resolved)) {\n delete cache[key];\n changed = true;\n }\n }\n if (!changed) return;\n try {\n writeFileSync(file, JSON.stringify(cache));\n } catch {\n // read-only log dir: best effort\n }\n}\n","/**\n * worktree.ts — one git worktree per writing worker.\n *\n * A run whose class edits files (implement, complex, plan) and whose cwd is a\n * git repository gets its own worktree by default: `git worktree add\n * <logDir>/worktrees/<id> -b worker/<id>` from the current HEAD. The worker\n * commits its own work on that branch — the no-commit rule applies to the\n * main branch only — and the parent (or the operator) merges the result back:\n *\n * pai worker merge <id> git merge --no-ff worker/<id> + remove worktree + delete branch\n * pai worker discard <id> remove worktree and branch, keep nothing\n *\n * `ps` marks a worker with an unmerged branch `⎇`. Draft and review run in\n * place; `--no-worktree` opts out, `--worktree` forces one on.\n */\n\nimport { execFileSync } from \"node:child_process\";\nimport { existsSync, lstatSync, mkdirSync, readFileSync, mkdtempSync, writeFileSync, readdirSync, readlinkSync, realpathSync, rmSync, statSync } from \"node:fs\";\nimport { dirname, isAbsolute, join, resolve, sep } from \"node:path\";\nimport { tmpdir, platform } from \"node:os\";\nimport { isLive, loadStatus, loadStatuses, saveStatus, UNLABELED, type WorkerStatus } from \"./status.js\";\nimport { appendLedger } from \"./ledger.js\";\nimport { ledgerPath, statusPath } from \"./paths.js\";\nimport { invalidatePendingCache } from \"./pending.js\";\n\nexport function worktreesDir(logDir: string): string {\n return join(logDir, \"worktrees\");\n}\n\nexport function worktreeBranch(id: string): string {\n return `worker/${id}`;\n}\n\nexport function worktreePath(logDir: string, id: string): string {\n return join(worktreesDir(logDir), id);\n}\n\n/** Run git in `cwd` with an optional env override, trimmed stdout, stderr on failure. */\nfunction runGit(cwd: string, args: string[], env?: NodeJS.ProcessEnv, timeout = 30_000): string {\n try {\n return execFileSync(\"git\", [\"-C\", cwd, ...args], {\n encoding: \"utf8\",\n timeout,\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n ...(env ? { env } : {}),\n }).trim();\n } catch (e) {\n const err = e as { stderr?: Buffer | string; message?: string };\n const why =\n (typeof err.stderr === \"string\" ? err.stderr : err.stderr?.toString(\"utf8\")) ||\n err.message ||\n String(e);\n throw new Error(`git ${args.join(\" \")} in ${cwd}: ${why.trim()}`);\n }\n}\n\n/** Run git in `cwd`, returning trimmed stdout; throws with stderr on failure. */\nexport function git(cwd: string, args: string[], timeoutMs?: number): string {\n return runGit(cwd, args, undefined, timeoutMs);\n}\n\n/** Is `cwd` inside a git repository (a .git dir — worktrees: a .git file)? */\nexport function isGitRepo(cwd: string): boolean {\n try {\n return git(cwd, [\"rev-parse\", \"--git-dir\"]) !== \"\";\n } catch {\n return false;\n }\n}\n\n/** Tools that can write to the checkout (Bash can, via the shell). */\nconst WRITING_TOOLS = [\"Edit\", \"Write\", \"MultiEdit\", \"NotebookEdit\", \"Bash\"];\n\n/** Can a run with these --allowedTools write? No restriction at all means yes. */\nexport function toolsCanWrite(allowedTools: string[]): boolean {\n const names = allowedTools.flatMap((e) => e.split(\",\")).map((s) => s.trim().replace(/\\(.*$/, \"\")).filter(Boolean);\n return !names.length || names.some((n) => WRITING_TOOLS.includes(n));\n}\n\n/** How the run flags decide the worktree question; undefined = decide by default. */\nexport type WorktreeFlag = boolean | undefined;\n\n/** Should this run get a worktree? Explicit flag first, then: can it write? */\nexport function worktreeWanted(flag: WorktreeFlag, opts: { cwd: string; allowedTools: string[] }): boolean {\n if (flag !== undefined) return flag;\n return toolsCanWrite(opts.allowedTools) && isGitRepo(opts.cwd);\n}\n\nexport interface WorktreeInfo {\n dir: string;\n branch: string;\n base: string;\n /** `base` is a snapshot commit of uncommitted checkout state, not HEAD itself. */\n snapshot: boolean;\n}\n\n/**\n * Commit `cwd`'s current index + working tree (including untracked files) as\n * a floating commit on top of HEAD, without touching the real index, working\n * tree or HEAD: a temporary `GIT_INDEX_FILE` collects the snapshot, `git\n * commit-tree` writes the commit object directly (it updates no ref). The\n * caller then branches a worktree from that commit, so the worktree sees\n * exactly what was on disk, uncommitted or not.\n */\nfunction snapshotUncommitted(cwd: string, id: string, head: string): string {\n const idxDir = mkdtempSync(join(tmpdir(), \"pai-worktree-idx-\"));\n const idx = join(idxDir, \"index\");\n try {\n const env = { ...process.env, GIT_INDEX_FILE: idx };\n runGit(cwd, [\"read-tree\", head], env);\n runGit(cwd, [\"add\", \"-A\"], env);\n const tree = runGit(cwd, [\"write-tree\"], env);\n return runGit(cwd, [\n \"commit-tree\",\n tree,\n \"-p\",\n head,\n \"-m\",\n `worker ${id}: snapshot of uncommitted checkout`,\n ]);\n } finally {\n rmSync(idxDir, { recursive: true, force: true });\n }\n}\n\n/**\n * Create the worktree and branch for `id` from `cwd`'s HEAD — or, when the\n * checkout has uncommitted changes, from a snapshot commit of that dirty\n * state (see `snapshotUncommitted`), so a worktree worker sees the same\n * files the operator sees, not just what was last committed. Throws when git\n * refuses (no commits yet, branch exists, …) — the caller decides whether to\n * degrade to an in-place run.\n */\nexport function addWorktree(logDir: string, id: string, cwd: string): WorktreeInfo {\n const dir = worktreePath(logDir, id);\n const branch = worktreeBranch(id);\n const head = git(cwd, [\"rev-parse\", \"HEAD\"]);\n const dirty = dirtyPaths(cwd).length > 0;\n const base = dirty ? snapshotUncommitted(cwd, id, head) : head;\n git(cwd, [\"worktree\", \"add\", dir, \"-b\", branch, base]);\n provisionDeps(logDir, id, cwd, dir);\n return { dir, branch, base, snapshot: dirty };\n}\n\n/**\n * Give the worktree its own dependencies so the worker never has to improvise\n * (symlinking node_modules to the main checkout, building in a /tmp copy).\n * A real node_modules directory in the main checkout is APFS-cloned\n * (`cp -c`, copy-on-write, near instant); elsewhere the lockfile installs it.\n * Never a symlink. Time-boxed and best effort: a failure is logged, the run\n * goes on.\n */\nexport function provisionDeps(logDir: string, id: string, cwd: string, wtDir: string): void {\n const note = (n: string) => appendLedger(ledgerPath(logDir), \"WORKER-NOTE\", { id, note: n });\n try {\n const root = git(cwd, [\"rev-parse\", \"--show-toplevel\"]);\n const main = join(root, \"node_modules\");\n const dest = join(wtDir, \"node_modules\");\n if (!existsSync(main) || lstatSync(main).isSymbolicLink() || existsSync(dest)) return;\n try {\n // an unignored node_modules would be committed by salvage\n git(wtDir, [\"check-ignore\", \"-q\", \"node_modules\"]);\n } catch {\n return;\n }\n const t0 = Date.now();\n const opts = { cwd: wtDir, stdio: \"ignore\" as const, timeout: 180_000 };\n if (platform() === \"darwin\") {\n try {\n execFileSync(\"cp\", [\"-cR\", main, dest], opts);\n note(`node_modules cloned (apfs) in ${Date.now() - t0}ms`);\n return;\n } catch {\n rmSync(dest, { recursive: true, force: true }); // half-copied\n }\n }\n if (existsSync(join(wtDir, \"bun.lock\"))) execFileSync(\"bun\", [\"install\", \"--frozen-lockfile\"], opts);\n else if (existsSync(join(wtDir, \"package-lock.json\"))) execFileSync(\"npm\", [\"ci\"], opts);\n else return;\n note(`node_modules installed from lockfile in ${Date.now() - t0}ms`);\n } catch (e) {\n try {\n note(`node_modules provisioning failed: ${(e as Error).message}`);\n } catch {\n /* ledger is best effort too */\n }\n }\n}\n\n/** Commits the branch collected on top of its base. */\nexport function commitsSince(dir: string, base: string): number {\n try {\n return parseInt(git(dir, [\"rev-list\", \"--count\", `${base}..HEAD`]), 10) || 0;\n } catch {\n return 0;\n }\n}\n\n/**\n * Record the worktree result in the status file: branch and commit count on\n * success, the worktree cleaned up on failure. Returns the updated status.\n */\nexport function recordWorktree(\n logDir: string,\n status: WorkerStatus,\n info: WorktreeInfo,\n ok: boolean\n): WorkerStatus {\n const s = { ...status };\n if (ok) {\n s.branch = info.branch;\n s.commits = commitsSince(info.dir, info.base);\n s.worktreeDir = info.dir;\n s.worktreeBase = info.base;\n s.worktreeSnapshot = info.snapshot;\n } else if (safeCommitsSince(info.dir, info.base) > 0) {\n // a failed or killed run that committed (or was salvaged) keeps its work:\n // branch and worktree stay for `pai worker merge` / `discard`\n s.branch = info.branch;\n s.commits = commitsSince(info.dir, info.base);\n s.worktreeDir = info.dir;\n s.worktreeBase = info.base;\n s.worktreeSnapshot = info.snapshot;\n } else {\n // a failed run with no commits leaves nothing to merge; the branch dies with the worktree\n removeWorktree(s.cwd, info.dir, true);\n try {\n git(s.cwd, [\"branch\", \"-D\", info.branch]);\n } catch {\n // already gone or never created\n }\n s.branch = null;\n s.worktreeDir = null;\n s.worktreeBase = null;\n s.commits = null;\n s.worktreeSnapshot = null;\n }\n saveStatus(logDir, s);\n invalidatePendingCache(logDir, s.cwd);\n return s;\n}\n\nfunction safeCommitsSince(dir: string, base: string): number {\n try {\n return commitsSince(dir, base);\n } catch {\n return 0;\n }\n}\n\n/**\n * Salvage for an exit path (run finaliser, kill signal): commit whatever the\n * worker left uncommitted, log WORKER-SALVAGE, never throw. Bounded by\n * `timeoutMs` per git call. Returns the committed paths.\n */\nexport function salvageOnExit(\n ledger: string,\n id: string,\n label: string,\n wtDir: string,\n timeoutMs?: number\n): string[] {\n try {\n const { committed, skipped } = salvageUncommitted(wtDir, label, timeoutMs);\n if (committed.length) appendLedger(ledger, \"WORKER-SALVAGE\", { id, paths: committed.join(\",\"), skipped: skipped.length });\n if (skipped.length) appendLedger(ledger, \"WORKER-NOTE\", { id, note: `salvage skipped: ${skipped.join(\"; \")}` });\n return committed;\n } catch (e) {\n try {\n appendLedger(ledger, \"WORKER-NOTE\", { id, note: `salvage failed: ${(e as Error).message}` });\n } catch {\n /* best effort */\n }\n return [];\n }\n}\n\n/** Remove a worktree directory from git's books and the filesystem. */\nfunction removeWorktree(cwd: string, dir: string, force: boolean): void {\n try {\n git(cwd, [\"worktree\", \"remove\", ...(force ? [\"--force\"] : []), dir]);\n return;\n } catch {\n // fall through to the manual cleanup\n }\n if (existsSync(dir)) {\n try {\n rmSync(dir, { recursive: true, force: true });\n git(cwd, [\"worktree\", \"prune\"]);\n } catch {\n // best effort: a leftover directory is visible in the logDir\n }\n }\n}\n\n/**\n * Tracked changes (staged or not) plus untracked files — everything a\n * `git add -A` in `wtDir` would commit. The same two calls the old patch\n * carry used; name-only, not porcelain: a worktree-only change renders as\n * \" M path\" and the shared git() helper trims that leading space away.\n */\nexport function uncommittedPaths(wtDir: string, timeoutMs?: number): string[] {\n const tracked = git(wtDir, [\"diff\", \"--name-only\", \"HEAD\"], timeoutMs).split(\"\\n\").filter(Boolean);\n const untracked = git(wtDir, [\"ls-files\", \"--others\", \"--exclude-standard\"], timeoutMs)\n .split(\"\\n\")\n .filter(Boolean);\n return [...tracked, ...untracked];\n}\n\n/**\n * True when `wtDir`/`relPath` is a symlink whose target resolves outside\n * `wtDir` — e.g. a worker's `node_modules -> <main checkout>/node_modules`\n * convenience link. A `.gitignore` using `dir/` (directories only) does not\n * ignore such a link, so it turns up as untracked; staging and merging it\n * lets git replace the real directory on the other side with a symlink to\n * itself. Never a candidate for salvage.\n */\nfunction symlinkEscapesWorktree(wtDir: string, relPath: string): boolean {\n const full = join(wtDir, relPath);\n let stat;\n try {\n stat = lstatSync(full);\n } catch {\n return false; // vanished; nothing to skip\n }\n if (!stat.isSymbolicLink()) return false;\n const target = readlinkSync(full);\n const resolvedTarget = isAbsolute(target) ? target : resolve(dirname(full), target);\n const realTarget = existsSync(resolvedTarget) ? realpathSync(resolvedTarget) : resolvedTarget;\n const realWtDir = realpathSync(wtDir);\n return realTarget !== realWtDir && !realTarget.startsWith(realWtDir + sep);\n}\n\nexport interface SalvageResult {\n /** Paths committed onto the branch. */\n committed: string[];\n /** Human-readable notes for paths left on disk, uncommitted, and why. */\n skipped: string[];\n}\n\n/**\n * Commit a worktree's uncommitted changes to its branch so the merge carries\n * them. `git merge` only moves committed work, so a worker that stopped\n * without committing would lose its edits to `worktree remove` — exactly\n * what happened live on 2026-09-17. Returns the salvaged paths, empty when\n * the worktree is clean. A symlink pointing outside the worktree (see\n * `symlinkEscapesWorktree`) is never staged; it is left on disk and reported\n * as skipped instead. A failed commit throws with the worktree untouched:\n * its edits are still on disk, so nothing is lost.\n */\nexport function salvageUncommitted(wtDir: string, label: string, timeoutMs?: number): SalvageResult {\n const paths = uncommittedPaths(wtDir, timeoutMs);\n if (!paths.length) return { committed: [], skipped: [] };\n const skipped: string[] = [];\n // tracked files gone from disk but not staged for removal: the worker never\n // ran `git rm`, so the absence is not its decision (see MAX_SALVAGE_DELETES)\n const missing = new Set(git(wtDir, [\"ls-files\", \"--deleted\"], timeoutMs).split(\"\\n\").filter(Boolean));\n const toStage: string[] = [];\n for (const p of paths) {\n if (missing.has(p)) {\n skipped.push(`${p} (missing, not committed)`);\n } else if (symlinkEscapesWorktree(wtDir, p)) {\n skipped.push(`symlink ${p} -> ${readlinkSync(join(wtDir, p))} (points outside the worktree)`);\n } else {\n toStage.push(p);\n }\n }\n if (!toStage.length) return { committed: [], skipped };\n try {\n // --ignore-removal: additions and modifications only. Deletions the worker\n // staged itself (git rm) are already in the index and ride along.\n const excludes = paths.filter((p) => !toStage.includes(p)).map((p) => `:(exclude,literal)${p}`);\n git(wtDir, [\"add\", \"--ignore-removal\", \"--\", \".\", ...excludes], timeoutMs);\n const deleted = git(wtDir, [\"diff\", \"--cached\", \"--diff-filter=D\", \"--name-only\"], timeoutMs).split(\"\\n\").filter(Boolean);\n if (deleted.length > MAX_SALVAGE_DELETES) {\n git(wtDir, [\"reset\", \"-q\"], timeoutMs);\n throw new Error(`salvage would delete ${deleted.length} tracked files (${deleted.slice(0, 5).join(\", \")}, ...), refused`);\n }\n git(wtDir, [\"commit\", \"-m\", `salvaged: ${label}`], timeoutMs);\n } catch (e) {\n throw new Error(\n `cannot salvage the uncommitted changes in ${wtDir} — ${(e as Error).message}; ` +\n `nothing was lost: commit them there by hand, then re-run merge`\n );\n }\n return { committed: toStage, skipped };\n}\n\n/** A salvage commit that deletes more tracked files than this is refused. */\nconst MAX_SALVAGE_DELETES = 5;\n\n/**\n * The dirty paths of a checkout, parsed from `git status --porcelain -z`:\n * NUL-separated (a path with a newline in it cannot corrupt the parse),\n * rename entries contribute both sides, and any quoting is stripped.\n */\nfunction dirtyPaths(cwd: string): string[] {\n // raw execFileSync, not the shared git(): it trims stdout, which eats the\n // leading space of a worktree-only \" M path\" record and breaks the parse\n const raw = execFileSync(\"git\", [\"-C\", cwd, \"status\", \"--porcelain\", \"-z\"], {\n encoding: \"utf8\",\n timeout: 30_000,\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n });\n const fields = raw.split(\"\\0\");\n const strip = (p: string) => (p.startsWith('\"') && p.endsWith('\"') ? p.slice(1, -1) : p);\n const out: string[] = [];\n for (let i = 0; i < fields.length; i++) {\n const f = fields[i];\n if (!f || f.length < 4 || f.charAt(2) !== \" \") continue; // not an \"XY path\" record\n out.push(strip(f.slice(3)));\n const xy = f.slice(0, 2);\n if (xy.includes(\"R\") || xy.includes(\"C\")) {\n const orig = fields[i + 1]; // rename/copy records carry the source path next\n if (orig && orig.charAt(2) !== \" \") {\n out.push(strip(orig));\n i += 1;\n }\n }\n }\n return out;\n}\n\n/**\n * Refuse the merge when the original checkout is dirty in paths the branch\n * touches: the merge would overwrite those edits or fail on them, either way\n * leaving a half-state. No merge is made, the worktree stays.\n */\nfunction assertNoDirtyOverlap(\n cwd: string,\n incoming: string[],\n id: string,\n branch: string\n): void {\n const dirty = new Set(dirtyPaths(cwd));\n const overlap = [...new Set(incoming)].filter((p) => dirty.has(p)).sort();\n if (!overlap.length) return;\n throw new Error(\n `worker ${id}: the checkout ${cwd} has uncommitted changes in paths ${branch} touches: ` +\n `${overlap.join(\", \")}. Commit or stash them in the checkout, then re-run: pai worker merge ${id}. ` +\n `No merge was made; the worktree was kept.`\n );\n}\n\n/**\n * Never remove a worktree that still holds uncommitted changes — except a\n * symlink escaping the worktree (see `symlinkEscapesWorktree`): it was\n * deliberately left uncommitted by `salvageUncommitted`, and deleting the\n * link itself touches nothing outside the worktree.\n */\nexport function assertWorktreeClean(wtDir: string, id: string): void {\n const leftover = uncommittedPaths(wtDir).filter((p) => !symlinkEscapesWorktree(wtDir, p));\n if (leftover.length) {\n throw new Error(\n `worker ${id}: the worktree ${wtDir} still holds uncommitted changes ` +\n `(${leftover.join(\", \")}) — it was NOT removed; commit or copy them by hand, then re-run merge`\n );\n }\n}\n\n/** Blob sha of `path` at `rev` in `cwd`, or null when it does not exist there. */\nfunction blobAt(cwd: string, rev: string, path: string): string | null {\n try {\n return git(cwd, [\"rev-parse\", \"--verify\", \"-q\", `${rev}:${path}`]);\n } catch {\n return null;\n }\n}\n\n/** Blob sha of `path` as it sits on disk in `cwd`, or null when it is absent. */\nfunction workingBlob(cwd: string, path: string): string | null {\n if (!existsSync(join(cwd, path))) return null;\n try {\n return git(cwd, [\"hash-object\", \"--\", path]);\n } catch {\n return null;\n }\n}\n\n/**\n * Refuse a snapshot merge when the checkout differs from the snapshot the\n * worker branched from, for any path the branch touched: the operator edited\n * it, or it was created/deleted since — applying the branch's diff on top\n * would silently discard that. Absent-in-both counts as equal.\n */\nfunction assertNoSnapshotDrift(cwd: string, snapshot: string, paths: string[], id: string): void {\n const drifted = paths\n .filter((p) => blobAt(cwd, snapshot, p) !== workingBlob(cwd, p))\n .sort();\n if (!drifted.length) return;\n throw new Error(\n `worker ${id}: the checkout ${cwd} has changed since the worktree's snapshot in paths the branch touches: ` +\n `${drifted.join(\", \")}. Resolve by hand, then re-run: pai worker merge ${id}. ` +\n `No merge was made; the worktree was kept.`\n );\n}\n\n/**\n * `pai worker merge <id>` for a snapshot-based worktree (see `addWorktree`):\n * git's own merge only moves committed history, and the snapshot commit was\n * never on any branch reachable from `cwd`'s HEAD, so there is nothing to\n * `git merge` here. Instead the worker's own changes — `git diff --binary\n * <snapshot> <branch>` — are applied straight onto the checkout's working\n * tree as uncommitted edits, exactly like the uncommitted state the worker\n * started from. Works even if `cwd`'s HEAD moved since the snapshot: the\n * diff is applied to files, not merged into a tree.\n */\nfunction mergeSnapshotWorker(\n logDir: string,\n id: string,\n st: WorkerStatus & Required<Pick<WorkerStatus, \"branch\" | \"worktreeDir\">>,\n noCommit = false\n): string {\n const snapshot = st.worktreeBase!;\n const branch = st.branch!;\n const worktreeDir = st.worktreeDir!;\n const salvage = existsSync(worktreeDir)\n ? salvageUncommitted(worktreeDir, st.label || UNLABELED)\n : { committed: [], skipped: [] };\n const incoming = parseInt(git(st.cwd, [\"rev-list\", \"--count\", `${snapshot}..${branch}`]), 10) || 0;\n if (incoming <= 0) {\n throw new Error(\n `worker ${id}: branch ${branch} has no commits beyond its snapshot to merge. ` +\n `The worktree ${worktreeDir} was NOT removed — uncommitted work there would be destroyed. ` +\n `Commit it yourself, or drop everything with: pai worker discard ${id}`\n );\n }\n const changedPaths = git(st.cwd, [\"diff\", \"--name-only\", snapshot, branch]).split(\"\\n\").filter(Boolean);\n assertNoSnapshotDrift(st.cwd, snapshot, changedPaths, id);\n const diff = execFileSync(\"git\", [\"-C\", st.cwd, \"diff\", \"--binary\", snapshot, branch], {\n encoding: \"utf8\",\n timeout: 30_000,\n maxBuffer: 64 * 1024 * 1024,\n });\n if (diff.trim()) {\n try {\n execFileSync(\"git\", [\"-C\", st.cwd, \"apply\", \"--binary\"], {\n input: diff,\n encoding: \"utf8\",\n timeout: 30_000,\n stdio: [\"pipe\", \"pipe\", \"pipe\"],\n });\n } catch (e) {\n const err = e as { stderr?: Buffer | string; message?: string };\n const why =\n (typeof err.stderr === \"string\" ? err.stderr : err.stderr?.toString(\"utf8\")) ||\n err.message ||\n String(e);\n throw new Error(\n `worker ${id}: git refused to apply ${branch}'s changes to ${st.cwd} — ${why.trim()}. ` +\n `The worktree ${worktreeDir} was kept: resolve by hand, then re-run merge`\n );\n }\n }\n if (noCommit) return noCommitNextSteps(id, branch, worktreeDir, changedPaths);\n removeWorktree(st.cwd, worktreeDir, true);\n try {\n git(st.cwd, [\"branch\", \"-D\", branch]); // never merged by git — nothing for -d to see\n } catch {\n // already gone\n }\n const s = { ...st, merged: true };\n saveStatus(logDir, s);\n const base =\n `applied worker ${id}'s changes (branch ${branch}) to ${st.cwd} as uncommitted changes: ` +\n `${changedPaths.join(\", \")} (worktree removed, branch deleted)`;\n const notes: string[] = [];\n if (salvage.committed.length) {\n notes.push(\n `salvaged ${salvage.committed.length} uncommitted change(s) onto the branch first: ${salvage.committed.join(\", \")}`\n );\n }\n if (salvage.skipped.length) {\n notes.push(`skipped ${salvage.skipped.join(\", \")}`);\n }\n return notes.length ? `${base}; ${notes.join(\"; \")}` : base;\n}\n\nfunction noCommitNextSteps(id: string, branch: string, worktreeDir: string, paths: string[]): string {\n return (\n `applied worker ${id}'s changes (branch ${branch}) to the checkout as uncommitted changes: ${paths.join(\", \")}. ` +\n `Branch and worktree ${worktreeDir} were kept. Next: review (git diff), commit, then run: pai worker gc`\n );\n}\n\n/**\n * `merge --no-commit`: apply base..branch to the checkout with a 3-way\n * `git apply`, leaving the result uncommitted. On conflict the tree is left\n * as is (markers + unmerged index entries) and the conflicted paths are listed.\n */\nfunction applyNoCommit(cwd: string, id: string, branch: string, worktreeDir: string, base: string, paths: string[]): string {\n const diff = execFileSync(\"git\", [\"-C\", cwd, \"diff\", \"--binary\", `${base}..${branch}`], {\n encoding: \"buffer\",\n timeout: 30_000,\n maxBuffer: 64 * 1024 * 1024,\n env: { ...process.env, LC_ALL: \"C\" },\n });\n try {\n execFileSync(\"git\", [\"-C\", cwd, \"apply\", \"--3way\", \"--binary\"], {\n input: diff,\n timeout: 30_000,\n stdio: [\"pipe\", \"pipe\", \"pipe\"],\n env: { ...process.env, LC_ALL: \"C\" },\n });\n } catch (e) {\n const conflicted = git(cwd, [\"diff\", \"--name-only\", \"--diff-filter=U\"]).split(\"\\n\").filter(Boolean);\n const err = e as { stderr?: Buffer | string; message?: string };\n const why = ((typeof err.stderr === \"string\" ? err.stderr : err.stderr?.toString(\"utf8\")) || err.message || \"\").trim();\n throw new Error(\n conflicted.length\n ? `worker ${id}: applying ${branch} conflicted in ${conflicted.join(\", \")}. The tree was left for you: ` +\n `resolve those paths, review, commit; branch and worktree ${worktreeDir} were kept`\n : `worker ${id}: git refused to apply ${branch} to ${cwd} — ${why}. Nothing was changed; branch and worktree were kept`\n );\n }\n return noCommitNextSteps(id, branch, worktreeDir, paths);\n}\n\nexport type VerifyState = \"identical\" | \"differs\" | \"missing\" | \"deleted\";\nexport interface VerifyResult {\n id: string;\n ref: string;\n base: string;\n against: string;\n files: { path: string; state: VerifyState }[];\n ok: boolean;\n}\n\n/**\n * `pai worker verify <id>`: for every file the worker's branch (or its\n * refs/pai-archive/<id> archive once the branch is gone) changed since its\n * base, compare bytes with the working tree or `--against <ref>`.\n * identical = the target already holds the worker's version (a worker delete\n * counts as identical when the target lacks the file too); differs = other\n * bytes; missing = the worker's file is absent in the target; deleted = the\n * worker deleted it but the target still has it. ok = every file identical.\n */\nexport function verifyWorker(logDir: string, id: string, opts: { against?: string } = {}): VerifyResult {\n const st = loadStatus(logDir, id);\n if (!st) throw new Error(`no worker named \"${id}\"`);\n const env = { ...process.env, LC_ALL: \"C\" };\n const bytes = (args: string[]): Buffer | null => {\n try {\n return execFileSync(\"git\", [\"-C\", st.cwd, ...args], {\n env,\n timeout: 30_000,\n maxBuffer: 256 * 1024 * 1024,\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n });\n } catch {\n return null;\n }\n };\n const has = (ref: string): boolean => bytes([\"rev-parse\", \"--verify\", \"-q\", `${ref}^{commit}`]) !== null;\n const ref = [`refs/heads/${worktreeBranch(id)}`, `refs/pai-archive/${id}`].find(has);\n if (!ref) throw new Error(`worker ${id}: neither ${worktreeBranch(id)} nor refs/pai-archive/${id} exists in ${st.cwd}`);\n const base = st.worktreeSnapshot && st.worktreeBase ? st.worktreeBase : git(st.cwd, [\"merge-base\", \"HEAD\", ref]);\n const list = (bytes([\"diff\", \"--name-status\", \"--no-renames\", \"-z\", `${base}..${ref}`]) ?? Buffer.alloc(0))\n .toString(\"utf8\")\n .split(\"\\0\")\n .filter(Boolean);\n const files: VerifyResult[\"files\"] = [];\n for (let i = 0; i + 1 < list.length; i += 2) {\n const path = list[i + 1];\n const deleted = list[i] === \"D\";\n const target = opts.against\n ? bytes([\"show\", `${opts.against}:${path}`])\n : existsSync(join(st.cwd, path))\n ? readFileSync(join(st.cwd, path))\n : null;\n let state: VerifyState;\n if (deleted) state = target ? \"deleted\" : \"identical\";\n else {\n const mine = bytes([\"show\", `${ref}:${path}`]);\n state = !target ? \"missing\" : mine && mine.equals(target) ? \"identical\" : \"differs\";\n }\n files.push({ path, state });\n }\n return { id, ref, base, against: opts.against ?? \"working tree\", files, ok: files.every((f) => f.state === \"identical\") };\n}\n\n/**\n * `pai worker merge <id>`: salvage whatever the worker left uncommitted onto\n * its branch, refuse when the original checkout is dirty in paths the branch\n * touches, merge with --no-ff (the merge commit names the worker), then\n * remove the worktree and delete the branch; the status gains `merged: true`.\n * A branch with nothing to merge is refused loudly — after salvage that\n * genuinely means it holds nothing, and reporting success there would\n * destroy the worktree for no gain.\n */\nexport function mergeWorker(logDir: string, id: string, opts: { noCommit?: boolean } = {}): string {\n const st = mustHaveBranch(logDir, id);\n if (st.merged) return `worker ${id}: branch ${st.branch} already merged`;\n if (st.worktreeSnapshot) return mergeSnapshotWorker(logDir, id, st, opts.noCommit);\n // salvage first: only a commit can carry uncommitted work through the merge\n const salvage = existsSync(st.worktreeDir!)\n ? salvageUncommitted(st.worktreeDir!, st.label || UNLABELED)\n : { committed: [], skipped: [] };\n const incoming = parseInt(git(st.cwd, [\"rev-list\", \"--count\", `HEAD..${st.branch}`]), 10) || 0;\n if (incoming <= 0) {\n throw new Error(\n `worker ${id}: branch ${st.branch} has no commits to merge. ` +\n `The worktree ${st.worktreeDir} was NOT removed — uncommitted work there would be destroyed. ` +\n `Commit it yourself, or drop everything with: pai worker discard ${id}`\n );\n }\n const mergeBase = git(st.cwd, [\"merge-base\", \"HEAD\", st.branch!]);\n const incomingPaths = git(st.cwd, [\"diff\", \"--name-only\", mergeBase, st.branch!])\n .split(\"\\n\")\n .filter(Boolean);\n assertNoDirtyOverlap(st.cwd, incomingPaths, id, st.branch!);\n if (opts.noCommit) return applyNoCommit(st.cwd, id, st.branch!, st.worktreeDir!, mergeBase, incomingPaths);\n try {\n git(st.cwd, [\"merge\", \"--no-ff\", st.branch!, \"-m\", `merge worker ${id} (${st.label})`]);\n } catch (e) {\n throw new Error(\n `worker ${id}: git refused the merge of ${st.branch} — ${(e as Error).message}. ` +\n `The worktree ${st.worktreeDir} was kept: resolve the conflict, then re-run merge`\n );\n }\n if (existsSync(st.worktreeDir!)) assertWorktreeClean(st.worktreeDir!, id);\n // force: assertWorktreeClean already confirmed nothing but a skipped\n // outside-pointing symlink (if anything) remains uncommitted\n removeWorktree(st.cwd, st.worktreeDir!, true);\n let branchGone = true;\n try {\n git(st.cwd, [\"branch\", \"-d\", st.branch!]);\n } catch {\n branchGone = false; // -d refuses anything not fully merged; keep the branch, say so\n }\n const s = { ...st, merged: true };\n saveStatus(logDir, s);\n invalidatePendingCache(logDir, st.cwd);\n const base = `merged ${st.branch} into ${st.cwd} (worktree removed${branchGone ? \", branch deleted\" : \"; branch kept: git refused -d\"})`;\n const notes: string[] = [];\n if (salvage.committed.length) {\n notes.push(`salvaged ${salvage.committed.length} uncommitted change(s): ${salvage.committed.join(\", \")}`);\n }\n if (salvage.skipped.length) {\n notes.push(`skipped ${salvage.skipped.join(\", \")}`);\n }\n return notes.length ? `${base}; ${notes.join(\"; \")}` : base;\n}\n\n/** `pai worker discard <id>`: drop worktree and branch, keep nothing. */\nexport function discardWorker(logDir: string, id: string): string {\n const st = mustHaveBranch(logDir, id);\n removeWorktree(st.cwd, st.worktreeDir!, true);\n let branchGone = false;\n try {\n git(st.cwd, [\"branch\", \"-D\", st.branch!]);\n branchGone = true;\n } catch {\n branchGone = false;\n }\n const s = {\n ...st,\n branch: null,\n worktreeDir: null,\n worktreeBase: null,\n worktreeSnapshot: null,\n commits: null,\n merged: false,\n };\n saveStatus(logDir, s);\n invalidatePendingCache(logDir, st.cwd);\n return `discarded worker ${id}: worktree removed${branchGone ? `, branch ${st.branch} deleted` : \"\"}`;\n}\n\nfunction mustHaveBranch(logDir: string, id: string): WorkerStatus & Required<Pick<WorkerStatus, \"branch\" | \"worktreeDir\">> {\n const st = loadStatus(logDir, id);\n if (!st) throw new Error(`no worker named \"${id}\"`);\n if (!st.branch || !st.worktreeDir) {\n throw new Error(\n `worker ${id} has no worktree branch to ${st.branch ? \"clean up\" : \"merge\"} — ` +\n `it ran in place or its branch was already handled`\n );\n }\n return st as WorkerStatus & Required<Pick<WorkerStatus, \"branch\" | \"worktreeDir\">>;\n}\n\n/**\n * The paragraph a worktree run's system prompt gains: it may commit on its\n * own branch (the no-commit rule holds for the main branch only), it must not\n * merge or push itself, and the parent or operator merges.\n */\nexport function worktreeSystemPrompt(id: string, branch: string, dir: string, snapshot = false): string {\n return [\n \"You are running in your own git worktree:\",\n ` ${dir} on branch ${branch} (worker id ${id}).`,\n \"Commit your work on that branch as you go (git add / git commit) — committing here is expected;\",\n \"the no-commit rule applies to the main branch only, and this is not it.\",\n \"Do not merge, rebase or push; the operator merges your branch back with `pai worker merge`.\",\n \"Use ONLY relative paths inside the worktree, never absolute worktree paths — absolute paths break after merge and leak machine layout.\",\n ...(snapshot\n ? [\n \"This worktree was branched from a snapshot that includes files the parent checkout had uncommitted at spawn time — not just its last commit.\",\n ]\n : []),\n ].join(\"\\n\");\n}\n\n/**\n * For headless runs WITHOUT a worktree: the worker shares the operator's\n * checkout with other in-flight workers, so a hook blocks git stash (except\n * list/show), reset, clean, checkout/restore of paths, switch, rebase and\n * merge — take baselines from measurements before editing, not from stash.\n */\nexport function inPlaceSystemPrompt(): string {\n return [\n \"You are running in the operator's shared git checkout, alongside other workers editing it at the same time.\",\n \"A hook blocks git stash (except list/show), reset, clean, checkout/restore of files, switch, rebase and merge — take baselines from measurements taken before you edit, not from stashing.\",\n \"Read-only git (status, diff, log, show, stash list) is fine.\",\n ].join(\"\\n\");\n}\n\nexport interface GcEntry {\n id: string;\n /** archive ref, or the reason the worktree was skipped. */\n archive?: string;\n skipped?: string;\n}\n\nconst GC_STAMP = \"gc-last\";\n\n/**\n * Archive worktrees of finished workers older than `olderThanHours` and\n * status-less orphan directories: uncommitted state is salvaged onto the\n * branch, the branch is x, the worktree is\n * removed. Nothing is deleted without a salvage first; a failed salvage skips\n * that worktree. Running workers are never touched. `dryRun` reports only.\n */\nexport function gcWorktrees(\n logDir: string,\n olderThanHours = 24,\n dryRun = false,\n now = Date.now()\n): GcEntry[] {\n const cutoff = now - olderThanHours * 3_600_000;\n const out: GcEntry[] = [];\n const root = worktreesDir(logDir);\n const known = new Set<string>();\n const archive = (id: string, dir: string, st: WorkerStatus | null): void => {\n const target = `refs/pai-archive/${id}`;\n if (dryRun) return void out.push({ id, archive: target });\n try {\n // The shared object store and refs live in the main repo; the recorded cwd\n // may be another worker's worktree that gc already removed.\n let repo: string;\n try {\n const raw = git(dir, [\"rev-parse\", \"--git-common-dir\"]);\n repo = isAbsolute(raw) ? raw : resolve(dir, raw);\n } catch {\n throw new Error(\"not a git worktree\");\n }\n const label = `archive: leftover state of worker ${id}`;\n if (uncommittedPaths(dir).length) {\n // salvageUncommitted labels \"salvaged: <label>\"; keep the requested subject\n const res = salvageUncommitted(dir, label);\n if (res.committed.length) git(dir, [\"commit\", \"--amend\", \"-q\", \"-m\", label]);\n if (res.skipped.length && uncommittedPaths(dir).some((p) => !symlinkEscapesWorktree(dir, p))) {\n throw new Error(\"uncommitted paths remain\");\n }\n }\n const src = worktreeBranch(id);\n let hasBranch = true;\n try {\n git(repo, [\"rev-parse\", \"--verify\", \"-q\", `refs/heads/${src}`]);\n } catch {\n hasBranch = false;\n }\n const tip = git(dir, [\"rev-parse\", \"HEAD\"]);\n // never drop a branch whose tip the archive ref would not keep reachable\n if (hasBranch) git(repo, [\"merge-base\", \"--is-ancestor\", `refs/heads/${src}`, tip]);\n git(repo, [\"update-ref\", target, tip]);\n git(repo, [\"worktree\", \"remove\", \"--force\", dir]);\n if (hasBranch) git(repo, [\"branch\", \"-D\", src]);\n if (st) saveStatus(logDir, { ...st, branch: null, worktreeDir: null, archived: target });\n appendLedger(ledgerPath(logDir), \"WORKER-GC\", { id, archive: target });\n out.push({ id, archive: target });\n } catch (e) {\n out.push({ id, skipped: (e as Error).message.split(\"\\n\")[0] });\n }\n };\n\n for (const st of loadStatuses(logDir)) {\n known.add(st.id);\n if (!st.worktreeDir || !existsSync(st.worktreeDir) || isLive(st)) continue;\n let end = 0;\n try {\n end = statSync(statusPath(logDir, st.id)).mtimeMs;\n } catch {\n continue;\n }\n if (end > cutoff) continue;\n archive(st.id, st.worktreeDir, st);\n }\n\n if (existsSync(root)) {\n for (const ent of readdirSync(root, { withFileTypes: true })) {\n if (!ent.isDirectory() || known.has(ent.name) || existsSync(statusPath(logDir, ent.name))) continue;\n const dir = join(root, ent.name);\n try {\n if (statSync(dir).mtimeMs > cutoff) continue;\n } catch {\n continue;\n }\n archive(ent.name, dir, null);\n }\n }\n if (!dryRun) {\n for (const repo of new Set(loadStatuses(logDir).map((s) => s.cwd))) {\n try {\n git(repo, [\"worktree\", \"prune\"]);\n } catch {\n // repo gone\n }\n invalidatePendingCache(logDir, repo);\n }\n }\n return out;\n}\n\n/** Run `gcWorktrees` at most once per `everyMin` minutes (stamp file in the logDir). */\nexport function gcWorktreesThrottled(logDir: string, everyMin = 60, now = Date.now()): GcEntry[] | null {\n const stamp = join(logDir, GC_STAMP);\n try {\n if (now - statSync(stamp).mtimeMs < everyMin * 60_000) return null;\n } catch {\n // never ran\n }\n mkdirSync(logDir, { recursive: true });\n writeFileSync(stamp, String(now), \"utf8\");\n return gcWorktrees(logDir, 24, false, now);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAmBA,SAAgB,cAAc,QAA+B;CAC3D,MAAM,WAAW,WAAW,OAAO,OAAO;AAC1C,KAAI,OAAO,WAAW,gBAAiB,QAAO;AAC9C,QAAO,eAAe,YAAY,QAAQ,UAAU,EAAE,CAAC,SAAS,EAAE,4BAA4B;;;AAIhG,SAAgB,kBAAkB,QAAwB;CACxD,MAAM,OAAO,gBAAgB,OAAO;AACpC,KAAI,CAAC,WAAW,KAAK,EAAE;AACrB,YAAU,QAAQ,EAAE,WAAW,MAAM,CAAC;AACtC,gBAAc,MAAM,4BAA0B,OAAO;;AAEvD,QAAO;;AAGT,SAAgB,WAAW,QAAgB,IAAoB;AAC7D,QAAO,KAAK,QAAQ,GAAG,GAAG,SAAS;;AAGrC,SAAgB,WAAW,QAAgB,IAAoB;AAC7D,QAAO,KAAK,QAAQ,GAAG,GAAG,QAAQ;;AAGpC,SAAgB,WAAW,QAAwB;AACjD,QAAO,KAAK,QAAQ,aAAa;;AAGnC,SAAgB,iBAAiB,QAA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OAAQ;UAC9B;AACN;;AAEF,UAAQ,IAAI,MAAM,KAAK,KAAK;;AAGhC,KAAI,CAAC,OACH,MAAK,MAAM,QAAQ,IAAI,IAAI,aAAa,OAAO,CAAC,KAAK,MAAM,EAAE,IAAI,CAAC,EAAE;AAClE,MAAI;AACF,OAAI,MAAM,CAAC,YAAY,QAAQ,CAAC;UAC1B;AAGR,yBAAuB,QAAQ,KAAK;;AAGxC,QAAO;;;AAIT,SAAgB,qBAAqB,QAAgB,WAAW,IAAI,MAAM,KAAK,KAAK,EAAoB;CACtG,MAAM,QAAQ,KAAK,QAAQ,SAAS;AACpC,KAAI;AACF,MAAI,MAAM,SAAS,MAAM,CAAC,UAAU,WAAW,IAAQ,QAAO;SACxD;AAGR,WAAU,QAAQ,EAAE,WAAW,MAAM,CAAC;AACtC,eAAc,OAAO,OAAO,IAAI,EAAE,OAAO;AACzC,QAAO,YAAY,QAAQ,IAAI,OAAO,IAAI"}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
|
-
import { t as STOP_WORDS$1 } from "./stop-words-
|
|
2
|
-
import {
|
|
1
|
+
import { t as STOP_WORDS$1 } from "./stop-words-LtkS-Pej.mjs";
|
|
2
|
+
import { a as requireQueryEmbedding } from "./embedding-gate-DqbKvn56.mjs";
|
|
3
|
+
import { i as deserializeEmbedding, r as cosineSimilarity } from "./embeddings-BUjZMD9F.mjs";
|
|
3
4
|
import { basename, dirname } from "node:path";
|
|
4
5
|
|
|
5
6
|
//#region src/zettelkasten/explore.ts
|
|
@@ -209,7 +210,7 @@ async function zettelSurprise(backend, opts) {
|
|
|
209
210
|
const minSimilarity = opts.minSimilarity ?? .3;
|
|
210
211
|
const minGraphDistance = opts.minGraphDistance ?? 3;
|
|
211
212
|
let { embedding: refEmbedding, found } = await getReferenceEmbedding(backend, opts.vaultProjectId, opts.referencePath);
|
|
212
|
-
if (!found) refEmbedding = await
|
|
213
|
+
if (!found) refEmbedding = await requireQueryEmbedding(backend, (await backend.getVaultFilesByPaths([opts.referencePath]))[0]?.title ?? opts.referencePath);
|
|
213
214
|
const allFileEmbeddings = await getFileEmbeddings(backend, opts.vaultProjectId);
|
|
214
215
|
allFileEmbeddings.delete(opts.referencePath);
|
|
215
216
|
const semanticCandidates = [];
|
|
@@ -319,7 +320,7 @@ async function zettelConverse(backend, opts) {
|
|
|
319
320
|
const depth = Math.max(opts.depth ?? 2, 0);
|
|
320
321
|
const limit = Math.max(opts.limit ?? 15, 1);
|
|
321
322
|
const candidateLimit = 20;
|
|
322
|
-
const queryEmbedding = await
|
|
323
|
+
const queryEmbedding = await requireQueryEmbedding(backend, opts.question);
|
|
323
324
|
const searchResults = await hybridSearch(backend, opts.question, queryEmbedding, {
|
|
324
325
|
projectIds: [opts.vaultProjectId],
|
|
325
326
|
maxResults: candidateLimit
|
|
@@ -1202,4 +1203,4 @@ async function zettelCommunities(backend, opts) {
|
|
|
1202
1203
|
|
|
1203
1204
|
//#endregion
|
|
1204
1205
|
export { zettelThemes as a, zettelExplore as c, zettelHealth as i, zettelGodNotes as n, zettelConverse as o, zettelSuggest as r, zettelSurprise as s, zettelCommunities as t };
|
|
1205
|
-
//# sourceMappingURL=zettelkasten-
|
|
1206
|
+
//# sourceMappingURL=zettelkasten-DSIe6wpF.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"zettelkasten-DSIe6wpF.mjs","names":["MAX_CHUNKS","MAX_CHUNKS","getTopFolder","STOP_WORDS"],"sources":["../src/zettelkasten/explore.ts","../src/zettelkasten/surprise.ts","../src/zettelkasten/converse.ts","../src/zettelkasten/themes.ts","../src/zettelkasten/health.ts","../src/zettelkasten/suggest.ts","../src/zettelkasten/god-notes.ts","../src/zettelkasten/communities.ts"],"sourcesContent":["import type { StorageBackend } from \"../storage/interface.js\";\nimport { dirname } from \"node:path\";\n\nexport interface ExploreOptions {\n startNote: string;\n depth?: number;\n direction?: \"forward\" | \"backward\" | \"both\";\n mode?: \"sequential\" | \"associative\" | \"all\";\n}\n\nexport interface ExploreNode {\n path: string;\n title: string | null;\n depth: number;\n linkType: \"sequential\" | \"associative\";\n inbound: number;\n outbound: number;\n}\n\nexport interface ExploreResult {\n root: string;\n nodes: ExploreNode[];\n edges: Array<{ from: string; to: string; type: \"sequential\" | \"associative\" }>;\n branchingPoints: string[];\n maxDepthReached: boolean;\n}\n\nfunction classifyEdge(source: string, target: string): \"sequential\" | \"associative\" {\n return dirname(source) === dirname(target) ? \"sequential\" : \"associative\";\n}\n\nasync function resolveStart(backend: StorageBackend, startNote: string): Promise<string | null> {\n // Try direct lookup first\n const files = await backend.getVaultFilesByPaths([startNote]);\n if (files.length > 0) return files[0].vaultPath;\n\n // Try alias lookup\n const alias = await backend.getVaultAlias(startNote);\n if (!alias) return null;\n\n const canonical = await backend.getVaultFilesByPaths([alias.canonicalPath]);\n return canonical.length > 0 ? canonical[0].vaultPath : null;\n}\n\nasync function getForwardNeighbors(backend: StorageBackend, path: string): Promise<string[]> {\n const links = await backend.getLinksFromSource(path);\n return links.filter(l => l.targetPath !== null).map(l => l.targetPath as string);\n}\n\nasync function getBackwardNeighbors(backend: StorageBackend, path: string): Promise<string[]> {\n const links = await backend.getLinksToTarget(path);\n return links.map(l => l.sourcePath);\n}\n\nasync function getFileInfo(\n backend: StorageBackend,\n path: string,\n): Promise<{ title: string | null; inbound: number; outbound: number }> {\n const [files, health] = await Promise.all([\n backend.getVaultFilesByPaths([path]),\n backend.getVaultHealth(path),\n ]);\n\n return {\n title: files[0]?.title ?? null,\n inbound: health?.inboundCount ?? 0,\n outbound: health?.outboundCount ?? 0,\n };\n}\n\n/**\n * Traverse the Zettelkasten link graph using BFS, following chains of thought\n * from a starting note up to a configurable depth.\n */\nexport async function zettelExplore(backend: StorageBackend, opts: ExploreOptions): Promise<ExploreResult> {\n const depth = Math.min(Math.max(opts.depth ?? 3, 1), 10);\n const direction = opts.direction ?? \"both\";\n const mode = opts.mode ?? \"all\";\n\n const root = await resolveStart(backend, opts.startNote);\n if (!root) {\n return {\n root: opts.startNote,\n nodes: [],\n edges: [],\n branchingPoints: [],\n maxDepthReached: false,\n };\n }\n\n const visited = new Set<string>([root]);\n const nodes: ExploreNode[] = [];\n const edges: Array<{ from: string; to: string; type: \"sequential\" | \"associative\" }> = [];\n let maxDepthReached = false;\n\n const queue: Array<{ path: string; depth: number }> = [{ path: root, depth: 0 }];\n\n while (queue.length > 0) {\n const current = queue.shift()!;\n\n if (current.depth >= depth) {\n maxDepthReached = true;\n continue;\n }\n\n const neighbors: Array<{ neighbor: string; from: string; to: string }> = [];\n\n if (direction === \"forward\" || direction === \"both\") {\n for (const n of await getForwardNeighbors(backend, current.path)) {\n neighbors.push({ neighbor: n, from: current.path, to: n });\n }\n }\n\n if (direction === \"backward\" || direction === \"both\") {\n for (const n of await getBackwardNeighbors(backend, current.path)) {\n neighbors.push({ neighbor: n, from: n, to: current.path });\n }\n }\n\n for (const { neighbor, from, to } of neighbors) {\n const edgeType = classifyEdge(from, to);\n\n if (mode !== \"all\" && edgeType !== mode) {\n continue;\n }\n\n const alreadyHasEdge = edges.some((e) => e.from === from && e.to === to);\n if (!alreadyHasEdge) {\n edges.push({ from, to, type: edgeType });\n }\n\n if (!visited.has(neighbor)) {\n visited.add(neighbor);\n\n const info = await getFileInfo(backend, neighbor);\n nodes.push({\n path: neighbor,\n title: info.title,\n depth: current.depth + 1,\n linkType: edgeType,\n inbound: info.inbound,\n outbound: info.outbound,\n });\n\n queue.push({ path: neighbor, depth: current.depth + 1 });\n }\n }\n }\n\n const branchingPoints = nodes\n .filter((n) => n.outbound > 2)\n .map((n) => n.path);\n\n const rootInfo = await getFileInfo(backend, root);\n if (rootInfo.outbound > 2) {\n branchingPoints.unshift(root);\n }\n\n return { root, nodes, edges, branchingPoints, maxDepthReached };\n}\n","import type { StorageBackend } from \"../storage/interface.js\";\nimport {\n deserializeEmbedding,\n cosineSimilarity,\n} from \"../memory/embeddings.js\";\nimport { requireQueryEmbedding } from \"../memory/embedding-gate.js\";\n\nexport interface SurpriseOptions {\n referencePath: string;\n vaultProjectId: number;\n limit?: number;\n minSimilarity?: number;\n minGraphDistance?: number;\n}\n\nexport interface SurpriseResult {\n path: string;\n title: string | null;\n cosineSimilarity: number;\n graphDistance: number;\n surpriseScore: number;\n sharedSnippet: string;\n}\n\nconst MAX_CHUNKS = 5000;\nconst BFS_HOP_CAP = 20;\n\nasync function getFileEmbeddings(\n backend: StorageBackend,\n projectId: number,\n): Promise<Map<string, { embedding: Float32Array; text: string }>> {\n const rows = await backend.getChunksWithEmbeddings(projectId, MAX_CHUNKS);\n\n const byPath = new Map<string, { sum: Float32Array; count: number; text: string }>();\n for (const row of rows) {\n const vec = deserializeEmbedding(row.embedding);\n const entry = byPath.get(row.path);\n if (!entry) {\n byPath.set(row.path, { sum: new Float32Array(vec), count: 1, text: row.text });\n } else {\n for (let i = 0; i < vec.length; i++) {\n entry.sum[i] += vec[i];\n }\n entry.count++;\n }\n }\n\n const result = new Map<string, { embedding: Float32Array; text: string }>();\n for (const [path, { sum, count, text }] of byPath) {\n const avg = new Float32Array(sum.length);\n for (let i = 0; i < sum.length; i++) {\n avg[i] = sum[i] / count;\n }\n result.set(path, { embedding: avg, text });\n }\n return result;\n}\n\nasync function getReferenceEmbedding(\n backend: StorageBackend,\n projectId: number,\n path: string,\n): Promise<{ embedding: Float32Array; found: boolean }> {\n const rows = await backend.getChunksForPath(projectId, path);\n\n if (rows.length === 0) {\n return { embedding: new Float32Array(0), found: false };\n }\n\n const embRows = rows.filter(r => r.embedding !== null) as Array<{ text: string; embedding: Buffer }>;\n if (embRows.length === 0) {\n return { embedding: new Float32Array(0), found: false };\n }\n\n const dim = deserializeEmbedding(embRows[0].embedding).length;\n const sum = new Float32Array(dim);\n for (const row of embRows) {\n const vec = deserializeEmbedding(row.embedding);\n for (let i = 0; i < dim; i++) {\n sum[i] += vec[i];\n }\n }\n const avg = new Float32Array(dim);\n for (let i = 0; i < dim; i++) {\n avg[i] = sum[i] / embRows.length;\n }\n return { embedding: avg, found: true };\n}\n\nasync function bfsGraphDistance(backend: StorageBackend, source: string, target: string): Promise<number> {\n if (source === target) return 0;\n\n const visited = new Set<string>([source]);\n const queue: Array<{ path: string; hops: number }> = [{ path: source, hops: 0 }];\n\n while (queue.length > 0) {\n const { path, hops } = queue.shift()!;\n if (hops >= BFS_HOP_CAP) continue;\n\n const [forwardLinks, backwardLinks] = await Promise.all([\n backend.getLinksFromSource(path),\n backend.getLinksToTarget(path),\n ]);\n\n const neighbors: string[] = [\n ...forwardLinks.filter(l => l.targetPath !== null).map(l => l.targetPath as string),\n ...backwardLinks.map(l => l.sourcePath),\n ];\n\n for (const neighbor of neighbors) {\n if (neighbor === target) return hops + 1;\n if (!visited.has(neighbor)) {\n visited.add(neighbor);\n queue.push({ path: neighbor, hops: hops + 1 });\n }\n }\n }\n\n return Infinity;\n}\n\nfunction getBestChunkText(\n chunkRows: Array<{ text: string; embedding: Buffer | null }>,\n refEmbedding: Float32Array,\n): string {\n const rows = chunkRows.filter(r => r.embedding !== null) as Array<{ text: string; embedding: Buffer }>;\n if (rows.length === 0) return \"\";\n\n let bestText = rows[0].text;\n let bestSim = -Infinity;\n\n for (const row of rows) {\n const vec = deserializeEmbedding(row.embedding);\n const sim = cosineSimilarity(refEmbedding, vec);\n if (sim > bestSim) {\n bestSim = sim;\n bestText = row.text;\n }\n }\n\n return bestText.trim().slice(0, 200);\n}\n\n/**\n * Find notes that are semantically similar to a reference note but graph-distant —\n * revealing surprising conceptual connections across unrelated areas of the Zettelkasten.\n */\nexport async function zettelSurprise(\n backend: StorageBackend,\n opts: SurpriseOptions,\n): Promise<SurpriseResult[]> {\n const limit = opts.limit ?? 10;\n const minSimilarity = opts.minSimilarity ?? 0.3;\n const minGraphDistance = opts.minGraphDistance ?? 3;\n\n let { embedding: refEmbedding, found } = await getReferenceEmbedding(\n backend,\n opts.vaultProjectId,\n opts.referencePath,\n );\n\n // Fall back to generating an embedding from the file title if no chunks exist\n if (!found) {\n const files = await backend.getVaultFilesByPaths([opts.referencePath]);\n const text = files[0]?.title ?? opts.referencePath;\n refEmbedding = await requireQueryEmbedding(backend, text);\n }\n\n const allFileEmbeddings = await getFileEmbeddings(backend, opts.vaultProjectId);\n\n // Remove the reference note itself from candidates\n allFileEmbeddings.delete(opts.referencePath);\n\n // First pass: filter by semantic similarity to avoid BFS on all nodes\n const semanticCandidates: Array<{ path: string; sim: number }> = [];\n for (const [path, { embedding }] of allFileEmbeddings) {\n const sim = cosineSimilarity(refEmbedding, embedding);\n if (sim >= minSimilarity) {\n semanticCandidates.push({ path, sim });\n }\n }\n\n // Compute graph distances for semantic candidates\n const results: SurpriseResult[] = [];\n\n for (const { path, sim } of semanticCandidates) {\n const graphDistance = await bfsGraphDistance(backend, opts.referencePath, path);\n\n const effectiveDistance = isFinite(graphDistance) ? graphDistance : BFS_HOP_CAP;\n if (effectiveDistance < minGraphDistance) continue;\n\n const files = await backend.getVaultFilesByPaths([path]);\n const chunkRows = await backend.getChunksForPath(opts.vaultProjectId, path, 20);\n\n const surpriseScore = sim * Math.log2(effectiveDistance + 1);\n const sharedSnippet = getBestChunkText(chunkRows, refEmbedding);\n\n results.push({\n path,\n title: files[0]?.title ?? null,\n cosineSimilarity: sim,\n graphDistance: isFinite(graphDistance) ? graphDistance : Infinity,\n surpriseScore,\n sharedSnippet,\n });\n }\n\n results.sort((a, b) => b.surpriseScore - a.surpriseScore);\n return results.slice(0, limit);\n}\n","import type { StorageBackend } from \"../storage/interface.js\";\nimport type { SearchResult } from \"../memory/search.js\";\nimport { requireQueryEmbedding } from \"../memory/embedding-gate.js\";\n\nexport interface ConverseOptions {\n /** The user's question or topic to explore. */\n question: string;\n /** project_id for vault chunks in memory_chunks. */\n vaultProjectId: number;\n /** Graph expansion depth. Default 2. */\n depth?: number;\n /** Maximum number of relevant notes to return. Default 15. */\n limit?: number;\n}\n\nexport interface ConverseConnection {\n fromPath: string;\n toPath: string;\n /** Top-level folder of fromPath. */\n fromDomain: string;\n /** Top-level folder of toPath. */\n toDomain: string;\n /** Link count between these two notes (can be > 1). */\n strength: number;\n}\n\nexport interface ConverseResult {\n relevantNotes: Array<{\n path: string;\n title: string | null;\n snippet: string;\n score: number;\n domain: string;\n }>;\n /** Cross-domain connections found among the selected notes. */\n connections: ConverseConnection[];\n /** Unique domains involved across all selected notes. */\n domains: string[];\n /** AI-ready prompt combining notes + connections for insight generation. */\n synthesisPrompt: string;\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\n/** Extract the top-level folder from a vault path (first path segment). */\nfunction extractDomain(vaultPath: string): string {\n const slash = vaultPath.indexOf(\"/\");\n return slash === -1 ? vaultPath : vaultPath.slice(0, slash);\n}\n\n/**\n * Expand one level of graph neighbors for a set of paths.\n * Returns all outbound and inbound neighbor paths (excluding already-visited).\n */\nasync function expandNeighbors(backend: StorageBackend, paths: Set<string>): Promise<string[]> {\n if (paths.size === 0) return [];\n const pathList = Array.from(paths);\n\n const [forwardLinks, backwardLinks] = await Promise.all([\n backend.getVaultLinksFromPaths(pathList),\n Promise.all(pathList.map(p => backend.getLinksToTarget(p))),\n ]);\n\n const neighbors: string[] = [];\n for (const link of forwardLinks) {\n if (link.targetPath) neighbors.push(link.targetPath);\n }\n for (const linkList of backwardLinks) {\n for (const link of linkList) {\n neighbors.push(link.sourcePath);\n }\n }\n return neighbors;\n}\n\n/**\n * Hybrid search combining keyword + semantic results using the StorageBackend.\n */\nasync function hybridSearch(\n backend: StorageBackend,\n query: string,\n queryEmbedding: Float32Array,\n opts: { projectIds?: number[]; maxResults?: number },\n): Promise<SearchResult[]> {\n const maxResults = opts.maxResults ?? 10;\n const kw = 0.5;\n const sw = 0.5;\n\n const [keywordResults, semanticResults] = await Promise.all([\n backend.searchKeyword(query, { ...opts, maxResults: 50 }),\n backend.searchSemantic(queryEmbedding, { ...opts, maxResults: 50 }),\n ]);\n\n if (keywordResults.length === 0 && semanticResults.length === 0) return [];\n\n const keyFor = (r: SearchResult) =>\n `${r.projectId}:${r.path}:${r.startLine}:${r.endLine}`;\n\n function minMaxNormalize(scores: number[]): number[] {\n const min = Math.min(...scores);\n const max = Math.max(...scores);\n const range = max - min;\n if (range === 0) return scores.map(() => 1.0);\n return scores.map(s => (s - min) / range);\n }\n\n const kwNorm = minMaxNormalize(keywordResults.map(r => r.score));\n const semNorm = minMaxNormalize(semanticResults.map(r => r.score));\n\n const combined = new Map<string, SearchResult & { combinedScore: number }>();\n\n for (let i = 0; i < keywordResults.length; i++) {\n const r = keywordResults[i];\n const k = keyFor(r);\n combined.set(k, { ...r, combinedScore: kw * kwNorm[i] });\n }\n\n for (let i = 0; i < semanticResults.length; i++) {\n const r = semanticResults[i];\n const k = keyFor(r);\n const existing = combined.get(k);\n if (existing) {\n existing.combinedScore += sw * semNorm[i];\n } else {\n combined.set(k, { ...r, combinedScore: sw * semNorm[i] });\n }\n }\n\n const sorted = Array.from(combined.values())\n .sort((a, b) => b.combinedScore - a.combinedScore)\n .slice(0, maxResults);\n\n return sorted.map(r => ({ ...r, score: r.combinedScore }));\n}\n\n// ---------------------------------------------------------------------------\n// Main export\n// ---------------------------------------------------------------------------\n\n/**\n * Let the vault \"talk back\" — find notes relevant to a question, expand\n * through the link graph, identify cross-domain connections, and return a\n * structured result including a synthesis prompt for an AI to generate insights.\n */\nexport async function zettelConverse(\n backend: StorageBackend,\n opts: ConverseOptions,\n): Promise<ConverseResult> {\n const depth = Math.max(opts.depth ?? 2, 0);\n const limit = Math.max(opts.limit ?? 15, 1);\n const candidateLimit = 20;\n\n // ------------------------------------------------------------------\n // 1. Hybrid search: find top candidates via BM25 + semantic similarity\n // ------------------------------------------------------------------\n const queryEmbedding = await requireQueryEmbedding(backend, opts.question);\n\n const searchResults = await hybridSearch(\n backend,\n opts.question,\n queryEmbedding,\n {\n projectIds: [opts.vaultProjectId],\n maxResults: candidateLimit,\n },\n );\n\n // Map of path -> best score + snippet from search results\n const searchHits = new Map<string, { score: number; snippet: string }>();\n for (const r of searchResults) {\n const existing = searchHits.get(r.path);\n if (!existing || r.score > existing.score) {\n searchHits.set(r.path, { score: r.score, snippet: r.snippet });\n }\n }\n\n // ------------------------------------------------------------------\n // 2. Graph expansion: BFS from each search result up to `depth` levels\n // ------------------------------------------------------------------\n const allPaths = new Set<string>(searchHits.keys());\n let frontier = new Set<string>(searchHits.keys());\n\n for (let d = 0; d < depth; d++) {\n const neighbors = await expandNeighbors(backend, frontier);\n const newFrontier = new Set<string>();\n for (const n of neighbors) {\n if (!allPaths.has(n)) {\n allPaths.add(n);\n newFrontier.add(n);\n }\n }\n if (newFrontier.size === 0) break;\n frontier = newFrontier;\n }\n\n // ------------------------------------------------------------------\n // 3. Deduplicate + trim to limit\n // ------------------------------------------------------------------\n const searchRanked = Array.from(searchHits.entries())\n .sort((a, b) => b[1].score - a[1].score)\n .map(([path, info]) => ({ path, ...info, isSearchResult: true }));\n\n const neighborPaths = Array.from(allPaths).filter((p) => !searchHits.has(p));\n\n // Fetch health data for neighbor ranking\n const neighborHealthRows = await Promise.all(\n neighborPaths.map(p => backend.getVaultHealth(p))\n );\n const neighborRanked = neighborPaths\n .map((path, idx) => ({\n path,\n score: 0,\n snippet: \"\",\n inbound: neighborHealthRows[idx]?.inboundCount ?? 0,\n isSearchResult: false,\n }))\n .sort((a, b) => b.inbound - a.inbound);\n\n const budgetForNeighbors = Math.max(limit - searchRanked.length, 0);\n const selectedNeighbors = neighborRanked.slice(0, budgetForNeighbors);\n\n const selectedSearchPaths = searchRanked.slice(0, limit);\n const selectedPaths = new Set<string>([\n ...selectedSearchPaths.map((r) => r.path),\n ...selectedNeighbors.map((r) => r.path),\n ]);\n\n // ------------------------------------------------------------------\n // 4. Build relevantNotes with titles + domains\n // ------------------------------------------------------------------\n\n // Fetch titles in bulk\n const allSelectedPaths = Array.from(selectedPaths);\n const fileRows = await backend.getVaultFilesByPaths(allSelectedPaths);\n const titleMap = new Map<string, string | null>(fileRows.map(f => [f.vaultPath, f.title]));\n\n const relevantNotes: ConverseResult[\"relevantNotes\"] = [];\n\n for (const r of selectedSearchPaths) {\n if (!selectedPaths.has(r.path)) continue;\n relevantNotes.push({\n path: r.path,\n title: titleMap.get(r.path) ?? null,\n snippet: r.snippet,\n score: r.score,\n domain: extractDomain(r.path),\n });\n }\n\n for (const r of selectedNeighbors) {\n relevantNotes.push({\n path: r.path,\n title: titleMap.get(r.path) ?? null,\n snippet: r.snippet,\n score: 0,\n domain: extractDomain(r.path),\n });\n }\n\n // ------------------------------------------------------------------\n // 5. Find connections between the selected notes\n // ------------------------------------------------------------------\n let connections: ConverseConnection[] = [];\n\n if (selectedPaths.size > 0) {\n const pathList = Array.from(selectedPaths);\n const pathSet = new Set(pathList);\n\n // Get all outbound links from the selected paths\n const linkRows = await backend.getVaultLinksFromPaths(pathList);\n\n // Count links between selected paths\n const edgeCounts = new Map<string, number>();\n for (const link of linkRows) {\n if (link.targetPath && pathSet.has(link.targetPath)) {\n const key = `${link.sourcePath}|||${link.targetPath}`;\n edgeCounts.set(key, (edgeCounts.get(key) ?? 0) + 1);\n }\n }\n\n for (const [key, cnt] of edgeCounts) {\n const [sourcePath, targetPath] = key.split(\"|||\");\n connections.push({\n fromPath: sourcePath,\n toPath: targetPath,\n fromDomain: extractDomain(sourcePath),\n toDomain: extractDomain(targetPath),\n strength: cnt,\n });\n }\n }\n\n // ------------------------------------------------------------------\n // 6. Domains + cross-domain filter\n // ------------------------------------------------------------------\n const domainSet = new Set<string>(relevantNotes.map((n) => n.domain));\n const domains = Array.from(domainSet).sort();\n\n const crossDomainConnections = connections.filter(\n (c) => c.fromDomain !== c.toDomain,\n );\n\n // ------------------------------------------------------------------\n // 7. Build synthesis prompt\n // ------------------------------------------------------------------\n const notesSummary = relevantNotes\n .map((n, i) => {\n const title = n.title ? `\"${n.title}\"` : \"(untitled)\";\n const domain = n.domain;\n const scoreLabel = n.score > 0 ? ` [relevance: ${n.score.toFixed(3)}]` : \" [context]\";\n const snippet = n.snippet.trim().slice(0, 300);\n return `${i + 1}. [${domain}] ${title}${scoreLabel}\\n Path: ${n.path}\\n \"${snippet}\"`;\n })\n .join(\"\\n\\n\");\n\n const connectionSummary =\n crossDomainConnections.length > 0\n ? crossDomainConnections\n .map(\n (c) =>\n `- \"${c.fromPath}\" (${c.fromDomain}) → \"${c.toPath}\" (${c.toDomain}) [strength: ${c.strength}]`,\n )\n .join(\"\\n\")\n : \"(no cross-domain connections found)\";\n\n const domainList = domains.join(\", \");\n\n const synthesisPrompt = `You are a Zettelkasten research assistant. The vault has surfaced the following notes in response to this question:\n\nQUESTION: ${opts.question}\n\n---\n\nRELEVANT NOTES (${relevantNotes.length} notes across ${domains.length} domain(s): ${domainList}):\n\n${notesSummary}\n\n---\n\nCROSS-DOMAIN CONNECTIONS (links bridging different knowledge areas):\n\n${connectionSummary}\n\n---\n\nSYNTHESIS TASK:\n\nBased on these notes and the connections between them, please:\n\n1. Identify the key insights that emerge in direct response to the question.\n2. Highlight any unexpected connections between notes from different domains (${domainList}).\n3. Point out tensions, contradictions, or open questions the vault raises but does not resolve.\n4. Suggest what is notably absent — what the vault does NOT yet contain that would strengthen the understanding of this topic.\n5. Propose 2-3 new notes that would meaningfully extend this knowledge cluster.\n\nThink like a scholar who has deeply internalized these ideas and is now synthesizing them for the first time.`;\n\n return {\n relevantNotes,\n connections: crossDomainConnections,\n domains,\n synthesisPrompt,\n };\n}\n","import type { StorageBackend } from \"../storage/interface.js\";\nimport { deserializeEmbedding, cosineSimilarity } from \"../memory/embeddings.js\";\nimport { STOP_WORDS } from \"../utils/stop-words.js\";\n\nexport interface ThemeOptions {\n vaultProjectId: number;\n lookbackDays?: number;\n minClusterSize?: number;\n maxThemes?: number;\n similarityThreshold?: number;\n}\n\nexport interface ThemeCluster {\n id: number;\n label: string;\n notes: Array<{\n path: string;\n title: string | null;\n }>;\n size: number;\n folderDiversity: number;\n avgRecency: number;\n linkedRatio: number;\n suggestIndexNote: boolean;\n}\n\nexport interface ThemeResult {\n themes: ThemeCluster[];\n totalNotesAnalyzed: number;\n timeWindow: { from: number; to: number };\n}\n\nconst MAX_CHUNKS = 5000;\n\n// STOP_WORDS imported from utils/stop-words.ts\n\nfunction getTopFolder(vaultPath: string): string {\n const parts = vaultPath.split(\"/\");\n return parts.length > 1 ? parts[0] : \"\";\n}\n\nfunction generateLabel(titles: Array<string | null>): string {\n const wordCounts = new Map<string, number>();\n for (const title of titles) {\n if (!title) continue;\n const words = title\n .toLowerCase()\n .replace(/[^a-z0-9\\s]/g, \" \")\n .split(/\\s+/)\n .filter((w) => w.length > 2 && !STOP_WORDS.has(w));\n for (const word of words) {\n wordCounts.set(word, (wordCounts.get(word) ?? 0) + 1);\n }\n }\n const sorted = [...wordCounts.entries()].sort((a, b) => b[1] - a[1]);\n return sorted\n .slice(0, 3)\n .map(([w]) => w)\n .join(\" / \");\n}\n\nasync function computeLinkedRatio(backend: StorageBackend, paths: string[]): Promise<number> {\n if (paths.length < 2) return 0;\n const totalPairs = (paths.length * (paths.length - 1)) / 2;\n const pathSet = new Set(paths);\n let linkedPairs = 0;\n\n for (const path of paths) {\n const links = await backend.getLinksFromSource(path);\n for (const link of links) {\n if (link.targetPath && pathSet.has(link.targetPath)) {\n linkedPairs++;\n }\n }\n }\n\n // Each bidirectional pair might be counted once per direction; divide by 2 to normalize\n const uniquePairs = linkedPairs / 2;\n return Math.min(1, uniquePairs / totalPairs);\n}\n\ntype ClusterNode = {\n paths: string[];\n titles: Array<string | null>;\n indexedAts: number[];\n centroid: Float32Array;\n};\n\nfunction averageEmbeddings(embeddings: Float32Array[]): Float32Array {\n if (embeddings.length === 0) return new Float32Array(0);\n const dim = embeddings[0].length;\n const sum = new Float32Array(dim);\n for (const vec of embeddings) {\n for (let i = 0; i < dim; i++) {\n sum[i] += vec[i];\n }\n }\n const avg = new Float32Array(dim);\n for (let i = 0; i < dim; i++) {\n avg[i] = sum[i] / embeddings.length;\n }\n return avg;\n}\n\n/**\n * Detect emerging themes in recently-modified notes using agglomerative single-linkage\n * clustering of note-level embeddings.\n */\nexport async function zettelThemes(\n backend: StorageBackend,\n opts: ThemeOptions,\n): Promise<ThemeResult> {\n const lookbackDays = opts.lookbackDays ?? 30;\n const minClusterSize = opts.minClusterSize ?? 3;\n const maxThemes = opts.maxThemes ?? 10;\n const similarityThreshold = opts.similarityThreshold ?? 0.65;\n\n const now = Date.now();\n const from = now - lookbackDays * 86400000;\n\n // Step 1: get recent notes\n const recentFiles = await backend.getRecentVaultFiles(from);\n const recentNotes = recentFiles.map(f => ({ vault_path: f.vaultPath, title: f.title, indexed_at: f.indexedAt }));\n\n // Step 2: get file-level embeddings from memory_chunks\n const chunkRows = await backend.getChunksWithEmbeddings(opts.vaultProjectId, MAX_CHUNKS);\n\n const embeddingsByPath = new Map<string, Float32Array[]>();\n for (const row of chunkRows) {\n const vec = deserializeEmbedding(row.embedding);\n const arr = embeddingsByPath.get(row.path);\n if (!arr) {\n embeddingsByPath.set(row.path, [vec]);\n } else {\n arr.push(vec);\n }\n }\n\n const fileEmbeddings = new Map<string, Float32Array>();\n for (const [path, vecs] of embeddingsByPath) {\n fileEmbeddings.set(path, averageEmbeddings(vecs));\n }\n\n // Step 3: build initial clusters — only include notes that have embeddings\n const clusters: ClusterNode[] = [];\n for (const note of recentNotes) {\n const embedding = fileEmbeddings.get(note.vault_path);\n if (!embedding) continue;\n clusters.push({\n paths: [note.vault_path],\n titles: [note.title],\n indexedAts: [note.indexed_at],\n centroid: embedding,\n });\n }\n\n const totalNotesAnalyzed = clusters.length;\n\n // Step 4: agglomerative single-linkage clustering\n // Stop when no two clusters have similarity >= threshold\n let merged = true;\n while (merged && clusters.length > 1) {\n merged = false;\n let bestSim = similarityThreshold;\n let bestI = -1;\n let bestJ = -1;\n\n for (let i = 0; i < clusters.length; i++) {\n for (let j = i + 1; j < clusters.length; j++) {\n const sim = cosineSimilarity(clusters[i].centroid, clusters[j].centroid);\n if (sim > bestSim) {\n bestSim = sim;\n bestI = i;\n bestJ = j;\n }\n }\n }\n\n if (bestI === -1) break;\n\n // Merge cluster j into cluster i\n const ci = clusters[bestI];\n const cj = clusters[bestJ];\n const mergedPaths = [...ci.paths, ...cj.paths];\n const mergedTitles = [...ci.titles, ...cj.titles];\n const mergedIndexedAts = [...ci.indexedAts, ...cj.indexedAts];\n\n // Recompute centroid from averaged embeddings of all member paths\n const memberEmbeddings: Float32Array[] = [];\n for (const p of mergedPaths) {\n const emb = fileEmbeddings.get(p);\n if (emb) memberEmbeddings.push(emb);\n }\n\n clusters[bestI] = {\n paths: mergedPaths,\n titles: mergedTitles,\n indexedAts: mergedIndexedAts,\n centroid: averageEmbeddings(memberEmbeddings),\n };\n\n clusters.splice(bestJ, 1);\n merged = true;\n }\n\n // Step 5: filter and annotate clusters\n const themes: ThemeCluster[] = [];\n let clusterIndex = 0;\n\n for (const cluster of clusters) {\n if (cluster.paths.length < minClusterSize) continue;\n\n const label = generateLabel(cluster.titles) || `Theme ${clusterIndex + 1}`;\n const avgRecency =\n cluster.indexedAts.reduce((sum, t) => sum + t, 0) / cluster.indexedAts.length;\n\n const uniqueFolders = new Set(cluster.paths.map(getTopFolder));\n const folderDiversity = uniqueFolders.size / cluster.paths.length;\n\n const linkedRatio = await computeLinkedRatio(backend, cluster.paths);\n const suggestIndexNote = linkedRatio < 0.3 && cluster.paths.length >= 5;\n\n themes.push({\n id: clusterIndex++,\n label,\n notes: cluster.paths.map((path, idx) => ({\n path,\n title: cluster.titles[idx],\n })),\n size: cluster.paths.length,\n folderDiversity,\n avgRecency,\n linkedRatio,\n suggestIndexNote,\n });\n }\n\n // Step 6: rank by size * folderDiversity * recency_ratio\n themes.sort(\n (a, b) =>\n b.size * b.folderDiversity * (b.avgRecency / now) -\n a.size * a.folderDiversity * (a.avgRecency / now),\n );\n\n return {\n themes: themes.slice(0, maxThemes),\n totalNotesAnalyzed,\n timeWindow: { from, to: now },\n };\n}\n","import type { StorageBackend } from \"../storage/interface.js\";\n\nexport interface HealthOptions {\n scope?: \"full\" | \"recent\" | \"project\";\n projectPath?: string;\n recentDays?: number;\n include?: Array<\"dead_links\" | \"orphans\" | \"disconnected\" | \"low_connectivity\">;\n}\n\nexport interface DeadLink {\n sourcePath: string;\n targetRaw: string;\n lineNumber: number;\n}\n\nexport interface HealthResult {\n totalFiles: number;\n totalLinks: number;\n deadLinks: DeadLink[];\n orphans: string[];\n disconnectedClusters: number;\n lowConnectivity: string[];\n healthScore: number;\n computedAt: number;\n /** Breakdown of links by confidence level (if confidence tagging is active). */\n linkConfidence?: {\n extracted: number;\n inferred: number;\n ambiguous: number;\n };\n}\n\nfunction countComponents(nodes: string[], edges: Array<{ source: string; target: string }>): number {\n if (nodes.length === 0) return 0;\n\n const parent = new Map<string, string>();\n const rank = new Map<string, number>();\n\n for (const n of nodes) {\n parent.set(n, n);\n rank.set(n, 0);\n }\n\n function find(x: string): string {\n let root = x;\n while (parent.get(root) !== root) {\n root = parent.get(root)!;\n }\n let current = x;\n while (current !== root) {\n const next = parent.get(current)!;\n parent.set(current, root);\n current = next;\n }\n return root;\n }\n\n function union(a: string, b: string): void {\n const ra = find(a);\n const rb = find(b);\n if (ra === rb) return;\n const rankA = rank.get(ra) ?? 0;\n const rankB = rank.get(rb) ?? 0;\n if (rankA < rankB) {\n parent.set(ra, rb);\n } else if (rankA > rankB) {\n parent.set(rb, ra);\n } else {\n parent.set(rb, ra);\n rank.set(ra, rankA + 1);\n }\n }\n\n for (const { source, target } of edges) {\n if (parent.has(source) && parent.has(target)) {\n union(source, target);\n }\n }\n\n const roots = new Set<string>();\n for (const n of nodes) {\n roots.add(find(n));\n }\n return roots.size;\n}\n\n/**\n * Audit the structural health of the Zettelkasten vault using graph metrics.\n */\nexport async function zettelHealth(backend: StorageBackend, opts?: HealthOptions): Promise<HealthResult> {\n const options = opts ?? {};\n const scope = options.scope ?? \"full\";\n const include = options.include ?? [\"dead_links\", \"orphans\", \"disconnected\", \"low_connectivity\"];\n\n const computedAt = Date.now();\n\n // --- totalFiles ---\n let totalFiles = 0;\n if (scope === \"full\") {\n totalFiles = await backend.countVaultFiles();\n } else if (scope === \"project\") {\n const prefix = options.projectPath ?? \"\";\n totalFiles = await backend.countVaultFilesWithPrefix(prefix);\n } else {\n const days = options.recentDays ?? 30;\n const cutoff = computedAt - days * 86400000;\n totalFiles = await backend.countVaultFilesAfter(cutoff);\n }\n\n // --- totalLinks ---\n let totalLinks = 0;\n if (scope === \"full\") {\n // Count total links via link graph length\n const graph = await backend.getVaultLinkGraph();\n totalLinks = graph.length;\n } else if (scope === \"project\") {\n const prefix = options.projectPath ?? \"\";\n totalLinks = await backend.countVaultLinksWithPrefix(prefix);\n } else {\n const days = options.recentDays ?? 30;\n const cutoff = computedAt - days * 86400000;\n totalLinks = await backend.countVaultLinksAfter(cutoff);\n }\n\n // --- deadLinks ---\n let deadLinks: DeadLink[] = [];\n if (include.includes(\"dead_links\")) {\n if (scope === \"full\") {\n deadLinks = await backend.getDeadLinksWithLineNumbers();\n } else if (scope === \"project\") {\n const prefix = options.projectPath ?? \"\";\n deadLinks = await backend.getDeadLinksWithPrefix(prefix);\n } else {\n const days = options.recentDays ?? 30;\n const cutoff = computedAt - days * 86400000;\n deadLinks = await backend.getDeadLinksAfter(cutoff);\n }\n }\n\n // --- orphans ---\n let orphans: string[] = [];\n if (include.includes(\"orphans\")) {\n if (scope === \"full\") {\n const orphanRows = await backend.getOrphans();\n orphans = orphanRows.map(r => r.vaultPath);\n } else if (scope === \"project\") {\n const prefix = options.projectPath ?? \"\";\n orphans = await backend.getOrphansWithPrefix(prefix);\n } else {\n const days = options.recentDays ?? 30;\n const cutoff = computedAt - days * 86400000;\n orphans = await backend.getOrphansAfter(cutoff);\n }\n }\n\n // --- disconnectedClusters (union-find) ---\n let disconnectedClusters = 1;\n if (include.includes(\"disconnected\")) {\n let allNodes: string[];\n let allEdges: Array<{ source: string; target: string }>;\n\n if (scope === \"full\") {\n [allNodes, allEdges] = await Promise.all([\n backend.getAllVaultFilePaths(),\n backend.getVaultLinkEdges(),\n ]);\n } else if (scope === \"project\") {\n const prefix = options.projectPath ?? \"\";\n [allNodes, allEdges] = await Promise.all([\n backend.getVaultFilePathsWithPrefix(prefix),\n backend.getVaultLinkEdgesWithPrefix(prefix),\n ]);\n } else {\n const days = options.recentDays ?? 30;\n const cutoff = computedAt - days * 86400000;\n [allNodes, allEdges] = await Promise.all([\n backend.getVaultFilePathsAfter(cutoff),\n backend.getVaultLinkEdgesAfter(cutoff),\n ]);\n }\n\n disconnectedClusters = countComponents(allNodes, allEdges);\n }\n\n // --- lowConnectivity ---\n let lowConnectivity: string[] = [];\n if (include.includes(\"low_connectivity\")) {\n if (scope === \"full\") {\n lowConnectivity = await backend.getLowConnectivity();\n } else if (scope === \"project\") {\n const prefix = options.projectPath ?? \"\";\n lowConnectivity = await backend.getLowConnectivityWithPrefix(prefix);\n } else {\n const days = options.recentDays ?? 30;\n const cutoff = computedAt - days * 86400000;\n lowConnectivity = await backend.getLowConnectivityAfter(cutoff);\n }\n }\n\n // --- linkConfidence ---\n // Count links by confidence level using a sampling of all vault file paths.\n // We reuse the link graph data we already fetched for totalLinks when scope=full.\n let linkConfidence: HealthResult[\"linkConfidence\"] | undefined;\n if (scope === \"full\") {\n try {\n // Get all file paths to iterate their outbound links with confidence\n const samplePaths = await backend.getAllVaultFilePaths();\n const sampleSize = Math.min(samplePaths.length, 200); // limit for performance\n const sampled = samplePaths.slice(0, sampleSize);\n let extracted = 0;\n let inferred = 0;\n let ambiguous = 0;\n for (const path of sampled) {\n const links = await backend.getLinksFromSource(path);\n for (const link of links) {\n const c = link.confidence ?? \"EXTRACTED\";\n if (c === \"EXTRACTED\") extracted++;\n else if (c === \"INFERRED\") inferred++;\n else ambiguous++;\n }\n }\n // Extrapolate if we sampled\n const factor = samplePaths.length > 0 ? samplePaths.length / sampleSize : 1;\n linkConfidence = {\n extracted: Math.round(extracted * factor),\n inferred: Math.round(inferred * factor),\n ambiguous: Math.round(ambiguous * factor),\n };\n } catch {\n // Backend may not support confidence field yet — ignore\n }\n }\n\n // --- healthScore ---\n const deadRatio = totalLinks > 0 ? deadLinks.length / totalLinks : 0;\n const orphanRatio = totalFiles > 0 ? orphans.length / totalFiles : 0;\n const lowConnRatio = totalFiles > 0 ? lowConnectivity.length / totalFiles : 0;\n const healthScore = Math.round(\n 100 * (1 - deadRatio) * (1 - orphanRatio * 0.5) * (1 - lowConnRatio * 0.3),\n );\n\n return {\n totalFiles,\n totalLinks,\n deadLinks,\n orphans,\n disconnectedClusters,\n lowConnectivity,\n healthScore,\n computedAt,\n linkConfidence,\n };\n}\n","import type { StorageBackend } from \"../storage/interface.js\";\nimport { deserializeEmbedding, cosineSimilarity } from \"../memory/embeddings.js\";\nimport { basename } from \"node:path\";\nimport { STOP_WORDS } from \"../utils/stop-words.js\";\n\nexport interface SuggestOptions {\n notePath: string;\n vaultProjectId: number;\n limit?: number;\n excludeLinked?: boolean;\n}\n\nexport interface Suggestion {\n path: string;\n title: string | null;\n score: number;\n semanticScore: number;\n tagScore: number;\n neighborScore: number;\n reason: string;\n suggestedWikilink: string;\n}\n\nconst MAX_CHUNKS = 5000;\nconst SEMANTIC_WEIGHT = 0.5;\nconst TAG_WEIGHT = 0.2;\nconst NEIGHBOR_WEIGHT = 0.3;\n\n// STOP_WORDS imported from utils/stop-words.ts\n\nfunction extractTagsFromChunkTexts(texts: string[]): Set<string> {\n const tags = new Set<string>();\n for (const text of texts) {\n // Match YAML frontmatter tags block: \"tags:\\n - tag1\\n - tag2\"\n const match = text.match(/^tags:\\s*\\n((?:[ \\t]*-[ \\t]*.+\\n?)*)/m);\n if (!match) continue;\n const block = match[1];\n const lines = block.split(\"\\n\");\n for (const line of lines) {\n const tagMatch = line.match(/^[ \\t]*-[ \\t]*(.+)/);\n if (tagMatch) {\n const tag = tagMatch[1].trim().toLowerCase();\n if (tag) tags.add(tag);\n }\n }\n }\n return tags;\n}\n\nfunction jaccardSimilarity(a: Set<string>, b: Set<string>): number {\n if (a.size === 0 && b.size === 0) return 0;\n let intersection = 0;\n for (const tag of a) {\n if (b.has(tag)) intersection++;\n }\n const union = a.size + b.size - intersection;\n return union === 0 ? 0 : intersection / union;\n}\n\nfunction buildReason(\n semanticScore: number,\n tagScore: number,\n neighborScore: number,\n neighborCount: number,\n): string {\n const signals: Array<{ label: string; value: number }> = [\n { label: `Semantically similar (${semanticScore.toFixed(2)})`, value: semanticScore * SEMANTIC_WEIGHT },\n { label: `Shared tags (${tagScore.toFixed(2)} Jaccard)`, value: tagScore * TAG_WEIGHT },\n { label: `Linked by ${neighborCount} mutual connection${neighborCount !== 1 ? \"s\" : \"\"}`, value: neighborScore * NEIGHBOR_WEIGHT },\n ];\n signals.sort((a, b) => b.value - a.value);\n return signals[0].label;\n}\n\nfunction suggestedWikilink(vaultPath: string): string {\n const base = basename(vaultPath);\n const name = base.endsWith(\".md\") ? base.slice(0, -3) : base;\n return `[[${name}]]`;\n}\n\n/**\n * Proactively find notes worth linking to a given note, combining semantic similarity,\n * shared tags, and graph-neighborhood signals into a ranked list of suggestions.\n */\nexport async function zettelSuggest(\n backend: StorageBackend,\n opts: SuggestOptions,\n): Promise<Suggestion[]> {\n const limit = opts.limit ?? 5;\n const excludeLinked = opts.excludeLinked ?? true;\n\n // Step 1: get current outbound links\n const outboundLinks = await backend.getLinksFromSource(opts.notePath);\n const linkedPaths = new Set(outboundLinks.filter(l => l.targetPath !== null).map(l => l.targetPath as string));\n\n // Step 2a: get all file-level embeddings for semantic scoring\n const chunkRows = await backend.getChunksWithEmbeddings(opts.vaultProjectId, MAX_CHUNKS);\n\n const byPath = new Map<string, { sum: Float32Array; count: number }>();\n for (const row of chunkRows) {\n const vec = deserializeEmbedding(row.embedding);\n const entry = byPath.get(row.path);\n if (!entry) {\n byPath.set(row.path, { sum: new Float32Array(vec), count: 1 });\n } else {\n for (let i = 0; i < vec.length; i++) {\n entry.sum[i] += vec[i];\n }\n entry.count++;\n }\n }\n\n const allEmbeddings = new Map<string, Float32Array>();\n for (const [path, { sum, count }] of byPath) {\n const avg = new Float32Array(sum.length);\n for (let i = 0; i < sum.length; i++) {\n avg[i] = sum[i] / count;\n }\n allEmbeddings.set(path, avg);\n }\n allEmbeddings.delete(opts.notePath);\n\n // Step 2b: get source embedding\n const sourceEmbedding = allEmbeddings.get(opts.notePath) ?? null;\n\n // Step 2c: get source tags\n const sourceChunkTexts = await backend.getChunksForPath(opts.vaultProjectId, opts.notePath, 5);\n const sourceTags = extractTagsFromChunkTexts(sourceChunkTexts.map(r => r.text));\n\n // Step 2d: compute graph neighborhood (friends-of-friends)\n const directLinks = await backend.getLinksFromSource(opts.notePath);\n const directTargets = directLinks.filter(l => l.targetPath !== null).map(l => l.targetPath as string);\n\n const friendLinkCounts = new Map<string, number>();\n for (const target of directTargets) {\n const friendLinks = await backend.getLinksFromSource(target);\n for (const link of friendLinks) {\n if (link.targetPath && link.targetPath !== opts.notePath) {\n friendLinkCounts.set(link.targetPath, (friendLinkCounts.get(link.targetPath) ?? 0) + 1);\n }\n }\n }\n const maxFriendLinks = Math.max(1, ...friendLinkCounts.values());\n\n // Get all vault files to enumerate candidates\n const allFiles = await backend.getAllVaultFiles();\n\n const suggestions: Suggestion[] = [];\n\n for (const fileRow of allFiles) {\n const vault_path = fileRow.vaultPath;\n const title = fileRow.title;\n\n if (vault_path === opts.notePath) continue;\n if (excludeLinked && linkedPaths.has(vault_path)) continue;\n\n // Semantic score\n let semanticScore = 0;\n if (sourceEmbedding) {\n const candidateEmbedding = allEmbeddings.get(vault_path);\n if (candidateEmbedding) {\n semanticScore = Math.max(0, cosineSimilarity(sourceEmbedding, candidateEmbedding));\n }\n }\n\n // Tag score (only compute if candidate might have chunks)\n let tagScore = 0;\n if (allEmbeddings.has(vault_path)) {\n const candidateChunkTexts = await backend.getChunksForPath(opts.vaultProjectId, vault_path, 5);\n const candidateTags = extractTagsFromChunkTexts(candidateChunkTexts.map(r => r.text));\n tagScore = jaccardSimilarity(sourceTags, candidateTags);\n }\n\n // Neighbor score\n const friendCount = friendLinkCounts.get(vault_path) ?? 0;\n const neighborScore = friendCount / maxFriendLinks;\n\n const score =\n SEMANTIC_WEIGHT * semanticScore +\n TAG_WEIGHT * tagScore +\n NEIGHBOR_WEIGHT * neighborScore;\n\n // Only include if there is at least some signal\n if (score <= 0) continue;\n\n const reason = buildReason(semanticScore, tagScore, neighborScore, friendCount);\n\n suggestions.push({\n path: vault_path,\n title,\n score,\n semanticScore,\n tagScore,\n neighborScore,\n reason,\n suggestedWikilink: suggestedWikilink(vault_path),\n });\n }\n\n suggestions.sort((a, b) => b.score - a.score);\n return suggestions.slice(0, limit);\n}\n","/**\n * God-note detection — find hub notes via degree centrality on the vault link graph.\n *\n * Hub notes (or \"god notes\") are notes with unusually high inbound link counts.\n * They represent core concepts that the rest of the vault frequently references.\n * Structural pages (index, MOC, master notes, tag pages) are filtered out.\n */\n\nimport type { StorageBackend } from \"../storage/interface.js\";\n\nexport interface GodNoteOptions {\n /** Maximum number of hub notes to return. Default: 20. */\n limit?: number;\n /** Minimum inbound link count to qualify as a hub. Default: 3. */\n minInbound?: number;\n /** Include outbound counts in the result. Default: true. */\n includeOutbound?: boolean;\n}\n\nexport interface GodNote {\n path: string;\n title: string | null;\n inboundCount: number;\n outboundCount: number;\n /** Ratio of inbound to total degree — higher means more \"sink\"-like. */\n inboundRatio: number;\n}\n\nexport interface GodNoteResult {\n godNotes: GodNote[];\n totalVaultFiles: number;\n /** Median inbound count across all vault files (for context). */\n medianInbound: number;\n}\n\n/** Patterns that identify structural/meta pages rather than concept notes. */\nconst STRUCTURAL_PATTERNS = [\n /\\bindex\\b/i,\n /\\bMOC\\b/,\n /\\bmaster\\b/i,\n /\\btag\\s*page/i,\n /\\bhome\\b/i,\n /\\bdashboard\\b/i,\n /\\btemplate/i,\n /^_/,\n];\n\nfunction isStructuralNote(title: string | null, path: string): boolean {\n const text = title ?? path;\n return STRUCTURAL_PATTERNS.some((pattern) => pattern.test(text));\n}\n\n/**\n * Find hub/\"god\" notes in the vault — notes with the highest inbound link counts,\n * excluding structural pages.\n */\nexport async function zettelGodNotes(\n backend: StorageBackend,\n opts?: GodNoteOptions,\n): Promise<GodNoteResult> {\n const limit = opts?.limit ?? 20;\n const minInbound = opts?.minInbound ?? 3;\n\n // Get the full link graph\n const linkGraph = await backend.getVaultLinkGraph();\n\n // Count inbound and outbound per path\n const inboundCounts = new Map<string, number>();\n const outboundCounts = new Map<string, number>();\n\n for (const { source_path, target_path } of linkGraph) {\n inboundCounts.set(target_path, (inboundCounts.get(target_path) ?? 0) + 1);\n outboundCounts.set(source_path, (outboundCounts.get(source_path) ?? 0) + 1);\n }\n\n // Get all vault files for title lookup and total count\n const allFiles = await backend.getAllVaultFiles();\n const titleMap = new Map<string, string | null>();\n for (const f of allFiles) {\n titleMap.set(f.vaultPath, f.title);\n }\n\n const totalVaultFiles = allFiles.length;\n\n // Compute median inbound for context\n const allInbounds = allFiles.map((f) => inboundCounts.get(f.vaultPath) ?? 0);\n allInbounds.sort((a, b) => a - b);\n const medianInbound =\n allInbounds.length > 0\n ? allInbounds[Math.floor(allInbounds.length / 2)]\n : 0;\n\n // Build candidate list: all paths with inbound >= minInbound, excluding structural\n const candidates: GodNote[] = [];\n\n for (const [path, inbound] of inboundCounts) {\n if (inbound < minInbound) continue;\n\n const title = titleMap.get(path) ?? null;\n if (isStructuralNote(title, path)) continue;\n\n const outbound = outboundCounts.get(path) ?? 0;\n const totalDegree = inbound + outbound;\n const inboundRatio = totalDegree > 0 ? inbound / totalDegree : 0;\n\n candidates.push({\n path,\n title,\n inboundCount: inbound,\n outboundCount: outbound,\n inboundRatio: Math.round(inboundRatio * 1000) / 1000,\n });\n }\n\n // Sort by inbound count descending\n candidates.sort((a, b) => b.inboundCount - a.inboundCount);\n\n return {\n godNotes: candidates.slice(0, limit),\n totalVaultFiles,\n medianInbound,\n };\n}\n","/**\n * Community detection for the Zettelkasten vault link graph.\n *\n * Implements the Louvain algorithm in pure TypeScript for discovering\n * densely connected clusters of notes. This reveals emergent knowledge\n * communities that may not be obvious from folder structure alone.\n *\n * The Louvain method optimizes modularity in two phases:\n * 1. Local: each node greedily moves to the community that maximizes modularity gain.\n * 2. Aggregation: communities are collapsed into super-nodes, forming a new graph.\n * Repeat until no further improvement.\n */\n\nimport type { StorageBackend } from \"../storage/interface.js\";\n\nexport interface CommunityOptions {\n /** Minimum community size to include in results. Default: 3. */\n minSize?: number;\n /** Maximum number of communities to return. Default: 20. */\n maxCommunities?: number;\n /** Resolution parameter for Louvain (higher = more communities). Default: 1.0. */\n resolution?: number;\n}\n\nexport interface CommunityNode {\n path: string;\n title: string | null;\n /** Degree (inbound + outbound) within the community. */\n internalDegree: number;\n}\n\nexport interface Community {\n id: number;\n /** Label derived from most common words in note titles. */\n label: string;\n nodes: CommunityNode[];\n size: number;\n /** Cohesion: ratio of internal edges to total possible internal edges. */\n cohesion: number;\n /** Top folders represented in this community. */\n topFolders: string[];\n}\n\nexport interface CommunityResult {\n communities: Community[];\n totalNodes: number;\n totalEdges: number;\n /** Global modularity score of the partition. */\n modularity: number;\n}\n\n// ---------------------------------------------------------------------------\n// Louvain algorithm implementation\n// ---------------------------------------------------------------------------\n\ninterface Graph {\n /** All node IDs */\n nodes: string[];\n /** Adjacency list: node -> Map<neighbor, weight> */\n adj: Map<string, Map<string, number>>;\n /** Total edge weight (sum of all edge weights, counting undirected edges once) */\n totalWeight: number;\n /** Weighted degree per node */\n degree: Map<string, number>;\n}\n\nfunction buildUndirectedGraph(\n edges: Array<{ source_path: string; target_path: string }>\n): Graph {\n const adj = new Map<string, Map<string, number>>();\n const nodeSet = new Set<string>();\n\n function getOrCreate(node: string): Map<string, number> {\n let m = adj.get(node);\n if (!m) {\n m = new Map();\n adj.set(node, m);\n }\n nodeSet.add(node);\n return m;\n }\n\n let totalWeight = 0;\n\n for (const { source_path, target_path } of edges) {\n if (source_path === target_path) continue; // skip self-loops\n\n const aMap = getOrCreate(source_path);\n const bMap = getOrCreate(target_path);\n\n // Undirected: add weight in both directions\n aMap.set(target_path, (aMap.get(target_path) ?? 0) + 1);\n bMap.set(source_path, (bMap.get(source_path) ?? 0) + 1);\n totalWeight += 1; // each undirected edge counted once\n }\n\n // Compute weighted degree\n const degree = new Map<string, number>();\n for (const [node, neighbors] of adj) {\n let d = 0;\n for (const w of neighbors.values()) d += w;\n degree.set(node, d);\n }\n\n return {\n nodes: Array.from(nodeSet),\n adj,\n totalWeight,\n degree,\n };\n}\n\n/**\n * Run one pass of Phase 1: local node movement.\n * Returns true if any node changed community.\n */\nfunction louvainPhase1(\n graph: Graph,\n community: Map<string, number>,\n resolution: number,\n): boolean {\n const m2 = 2 * graph.totalWeight;\n if (m2 === 0) return false;\n\n // Community -> sum of degrees of nodes in community\n const communityDegreeSum = new Map<number, number>();\n // Community -> sum of internal edge weights\n const communityInternalWeight = new Map<number, number>();\n\n for (const node of graph.nodes) {\n const c = community.get(node)!;\n communityDegreeSum.set(c, (communityDegreeSum.get(c) ?? 0) + (graph.degree.get(node) ?? 0));\n }\n\n // Compute internal weights\n for (const [node, neighbors] of graph.adj) {\n const nc = community.get(node)!;\n for (const [neighbor, weight] of neighbors) {\n if (community.get(neighbor) === nc) {\n communityInternalWeight.set(nc, (communityInternalWeight.get(nc) ?? 0) + weight);\n }\n }\n }\n // Each internal edge is counted twice (both endpoints), so divide\n for (const [c, w] of communityInternalWeight) {\n communityInternalWeight.set(c, w / 2);\n }\n\n let improved = false;\n // Shuffle node order for better convergence\n const shuffled = [...graph.nodes];\n for (let i = shuffled.length - 1; i > 0; i--) {\n const j = Math.floor(Math.random() * (i + 1));\n [shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];\n }\n\n for (const node of shuffled) {\n const currentComm = community.get(node)!;\n const ki = graph.degree.get(node) ?? 0;\n const neighbors = graph.adj.get(node) ?? new Map();\n\n // Compute weight to each neighboring community\n const weightToComm = new Map<number, number>();\n for (const [neighbor, weight] of neighbors) {\n const nc = community.get(neighbor)!;\n weightToComm.set(nc, (weightToComm.get(nc) ?? 0) + weight);\n }\n\n // Remove node from its current community\n communityDegreeSum.set(currentComm, (communityDegreeSum.get(currentComm) ?? 0) - ki);\n const weightToCurrent = weightToComm.get(currentComm) ?? 0;\n communityInternalWeight.set(\n currentComm,\n (communityInternalWeight.get(currentComm) ?? 0) - weightToCurrent,\n );\n\n // Find best community\n let bestComm = currentComm;\n let bestDelta = 0;\n\n for (const [candidateComm, weightToCandidate] of weightToComm) {\n const sigmaTot = communityDegreeSum.get(candidateComm) ?? 0;\n // Modularity gain of moving node to candidateComm\n const delta = weightToCandidate - resolution * (ki * sigmaTot) / m2;\n if (delta > bestDelta) {\n bestDelta = delta;\n bestComm = candidateComm;\n }\n }\n\n // Also consider staying (delta = 0, but need to re-add)\n // Move node to best community\n community.set(node, bestComm);\n communityDegreeSum.set(bestComm, (communityDegreeSum.get(bestComm) ?? 0) + ki);\n const weightToBest = weightToComm.get(bestComm) ?? 0;\n communityInternalWeight.set(\n bestComm,\n (communityInternalWeight.get(bestComm) ?? 0) + weightToBest,\n );\n\n if (bestComm !== currentComm) {\n improved = true;\n }\n }\n\n return improved;\n}\n\n/**\n * Compute modularity for a given partition.\n */\nfunction computeModularity(\n graph: Graph,\n community: Map<string, number>,\n resolution: number,\n): number {\n const m2 = 2 * graph.totalWeight;\n if (m2 === 0) return 0;\n\n let q = 0;\n for (const [node, neighbors] of graph.adj) {\n const ci = community.get(node)!;\n const ki = graph.degree.get(node) ?? 0;\n\n for (const [neighbor, weight] of neighbors) {\n if (community.get(neighbor) === ci) {\n q += weight - resolution * (ki * (graph.degree.get(neighbor) ?? 0)) / m2;\n }\n }\n }\n return q / m2;\n}\n\n/**\n * Run Louvain community detection on the vault link graph.\n */\nfunction runLouvain(\n graph: Graph,\n resolution: number,\n): Map<string, number> {\n // Initialize: each node in its own community\n const community = new Map<string, number>();\n let nextComm = 0;\n for (const node of graph.nodes) {\n community.set(node, nextComm++);\n }\n\n // Phase 1: iteratively move nodes until no improvement\n const MAX_ITERATIONS = 20;\n for (let iter = 0; iter < MAX_ITERATIONS; iter++) {\n const improved = louvainPhase1(graph, community, resolution);\n if (!improved) break;\n }\n\n // Compact community IDs\n const commRemap = new Map<number, number>();\n let remapIdx = 0;\n for (const [, c] of community) {\n if (!commRemap.has(c)) {\n commRemap.set(c, remapIdx++);\n }\n }\n for (const [node, c] of community) {\n community.set(node, commRemap.get(c)!);\n }\n\n return community;\n}\n\n// ---------------------------------------------------------------------------\n// Label generation\n// ---------------------------------------------------------------------------\n\nconst STOP_WORDS = new Set([\n \"the\", \"and\", \"for\", \"are\", \"but\", \"not\", \"you\", \"all\", \"can\", \"her\",\n \"was\", \"one\", \"our\", \"out\", \"has\", \"had\", \"how\", \"its\", \"may\", \"new\",\n \"now\", \"old\", \"see\", \"way\", \"who\", \"did\", \"get\", \"let\", \"say\", \"she\",\n \"too\", \"use\", \"from\", \"with\", \"this\", \"that\", \"will\", \"been\", \"have\",\n \"each\", \"make\", \"like\", \"long\", \"look\", \"many\", \"them\", \"then\", \"what\",\n \"when\", \"some\", \"time\", \"very\", \"your\", \"about\", \"could\", \"into\", \"just\",\n \"more\", \"note\", \"notes\", \"than\", \"over\",\n]);\n\nfunction generateCommunityLabel(titles: Array<string | null>): string {\n const wordCounts = new Map<string, number>();\n for (const title of titles) {\n if (!title) continue;\n const words = title\n .toLowerCase()\n .replace(/[^a-z0-9\\s]/g, \" \")\n .split(/\\s+/)\n .filter((w) => w.length > 2 && !STOP_WORDS.has(w));\n for (const word of words) {\n wordCounts.set(word, (wordCounts.get(word) ?? 0) + 1);\n }\n }\n const sorted = [...wordCounts.entries()].sort((a, b) => b[1] - a[1]);\n return sorted\n .slice(0, 3)\n .map(([w]) => w)\n .join(\" / \") || \"unnamed\";\n}\n\nfunction getTopFolder(path: string): string {\n const slash = path.indexOf(\"/\");\n return slash === -1 ? path : path.slice(0, slash);\n}\n\n// ---------------------------------------------------------------------------\n// Main export\n// ---------------------------------------------------------------------------\n\n/**\n * Detect communities in the vault link graph using the Louvain algorithm.\n * Returns clusters of densely connected notes with labels and cohesion scores.\n */\nexport async function zettelCommunities(\n backend: StorageBackend,\n opts?: CommunityOptions,\n): Promise<CommunityResult> {\n const minSize = opts?.minSize ?? 3;\n const maxCommunities = opts?.maxCommunities ?? 20;\n const resolution = opts?.resolution ?? 1.0;\n\n // Get the full link graph\n const linkGraph = await backend.getVaultLinkGraph();\n const graph = buildUndirectedGraph(linkGraph);\n\n if (graph.nodes.length === 0) {\n return {\n communities: [],\n totalNodes: 0,\n totalEdges: 0,\n modularity: 0,\n };\n }\n\n // Run Louvain\n const communityMap = runLouvain(graph, resolution);\n\n // Compute modularity\n const modularity = computeModularity(graph, communityMap, resolution);\n\n // Group nodes by community\n const groups = new Map<number, string[]>();\n for (const [node, comm] of communityMap) {\n const arr = groups.get(comm);\n if (arr) arr.push(node);\n else groups.set(comm, [node]);\n }\n\n // Get all vault files for title lookup\n const allFiles = await backend.getAllVaultFiles();\n const titleMap = new Map<string, string | null>();\n for (const f of allFiles) {\n titleMap.set(f.vaultPath, f.title);\n }\n\n // Build community results\n const communities: Community[] = [];\n let commId = 0;\n\n for (const [, members] of groups) {\n if (members.length < minSize) continue;\n\n const memberSet = new Set(members);\n const titles = members.map((p) => titleMap.get(p) ?? null);\n const label = generateCommunityLabel(titles);\n\n // Compute internal degree per node\n const nodes: CommunityNode[] = members.map((path) => {\n const neighbors = graph.adj.get(path) ?? new Map();\n let internalDeg = 0;\n for (const [neighbor, weight] of neighbors) {\n if (memberSet.has(neighbor)) internalDeg += weight;\n }\n return {\n path,\n title: titleMap.get(path) ?? null,\n internalDegree: internalDeg,\n };\n });\n\n // Sort nodes by internal degree descending\n nodes.sort((a, b) => b.internalDegree - a.internalDegree);\n\n // Compute cohesion: ratio of actual internal edges to possible\n let internalEdges = 0;\n for (const node of nodes) {\n internalEdges += node.internalDegree;\n }\n internalEdges /= 2; // each edge counted twice\n const possibleEdges = (members.length * (members.length - 1)) / 2;\n const cohesion = possibleEdges > 0 ? Math.round((internalEdges / possibleEdges) * 1000) / 1000 : 0;\n\n // Top folders\n const folderCounts = new Map<string, number>();\n for (const path of members) {\n const folder = getTopFolder(path);\n folderCounts.set(folder, (folderCounts.get(folder) ?? 0) + 1);\n }\n const topFolders = [...folderCounts.entries()]\n .sort((a, b) => b[1] - a[1])\n .slice(0, 5)\n .map(([f]) => f);\n\n communities.push({\n id: commId++,\n label,\n nodes,\n size: members.length,\n cohesion,\n topFolders,\n });\n }\n\n // Sort by size descending\n communities.sort((a, b) => b.size - a.size);\n\n return {\n communities: communities.slice(0, maxCommunities),\n totalNodes: graph.nodes.length,\n totalEdges: graph.totalWeight,\n modularity: Math.round(modularity * 10000) / 10000,\n };\n}\n"],"mappings":";;;;;;AA2BA,SAAS,aAAa,QAAgB,QAA8C;AAClF,QAAO,QAAQ,OAAO,KAAK,QAAQ,OAAO,GAAG,eAAe;;AAG9D,eAAe,aAAa,SAAyB,WAA2C;CAE9F,MAAM,QAAQ,MAAM,QAAQ,qBAAqB,CAAC,UAAU,CAAC;AAC7D,KAAI,MAAM,SAAS,EAAG,QAAO,MAAM,GAAG;CAGtC,MAAM,QAAQ,MAAM,QAAQ,cAAc,UAAU;AACpD,KAAI,CAAC,MAAO,QAAO;CAEnB,MAAM,YAAY,MAAM,QAAQ,qBAAqB,CAAC,MAAM,cAAc,CAAC;AAC3E,QAAO,UAAU,SAAS,IAAI,UAAU,GAAG,YAAY;;AAGzD,eAAe,oBAAoB,SAAyB,MAAiC;AAE3F,SADc,MAAM,QAAQ,mBAAmB,KAAK,EACvC,QAAO,MAAK,EAAE,eAAe,KAAK,CAAC,KAAI,MAAK,EAAE,WAAqB;;AAGlF,eAAe,qBAAqB,SAAyB,MAAiC;AAE5F,SADc,MAAM,QAAQ,iBAAiB,KAAK,EACrC,KAAI,MAAK,EAAE,WAAW;;AAGrC,eAAe,YACb,SACA,MACsE;CACtE,MAAM,CAAC,OAAO,UAAU,MAAM,QAAQ,IAAI,CACxC,QAAQ,qBAAqB,CAAC,KAAK,CAAC,EACpC,QAAQ,eAAe,KAAK,CAC7B,CAAC;AAEF,QAAO;EACL,OAAO,MAA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L,aAAa,YAAY,MAAM,GAAG,eAAe;EACjD,YAAY,MAAM,MAAM;EACxB,YAAY,MAAM;EAClB,YAAY,KAAK,MAAM,aAAa,IAAM,GAAG;EAC9C"}
|
|
@@ -1,5 +1,7 @@
|
|
|
1
|
-
import "./
|
|
2
|
-
import
|
|
3
|
-
import
|
|
1
|
+
import "./config-DjZELvoA.mjs";
|
|
2
|
+
import "./embedding-gate-DqbKvn56.mjs";
|
|
3
|
+
import "./embeddings-BUjZMD9F.mjs";
|
|
4
|
+
import { r as saveQueryResult } from "./query-feedback-GPeVGvIa.mjs";
|
|
5
|
+
import { a as zettelThemes, c as zettelExplore, i as zettelHealth, n as zettelGodNotes, o as zettelConverse, r as zettelSuggest, s as zettelSurprise, t as zettelCommunities } from "./zettelkasten-DSIe6wpF.mjs";
|
|
4
6
|
|
|
5
7
|
export { zettelConverse, zettelExplore, zettelHealth, zettelSuggest, zettelSurprise, zettelThemes };
|
|
@@ -5,6 +5,10 @@ services:
|
|
|
5
5
|
image: pgvector/pgvector:pg17
|
|
6
6
|
container_name: pai-pgvector
|
|
7
7
|
restart: unless-stopped
|
|
8
|
+
# A parallel vector index build keeps its graph in shared memory sized by
|
|
9
|
+
# maintenance_work_mem; Docker's default 64MB /dev/shm makes it fail with
|
|
10
|
+
# "No space left on device".
|
|
11
|
+
shm_size: ${PAI_PG_SHM_SIZE:-3g}
|
|
8
12
|
# Postgres ships with shared_buffers=128MB, which is far too small once the
|
|
9
13
|
# vector index runs to a gigabyte or more — the index can never stay cached
|
|
10
14
|
# and every similarity search hits disk. 25% of available RAM is the usual
|
package/docs/commands/README.md
CHANGED
|
@@ -102,8 +102,13 @@ Generated man pages for every `pai` command area. Read any page in the terminal
|
|
|
102
102
|
| `pai mcp install` | Register the PAI MCP server (pai) in ~/.claude.json (restart Claude Code to activate) |
|
|
103
103
|
| `pai mcp status` | Show whether the PAI MCP server (pai) is registered and the binary exists |
|
|
104
104
|
| `pai memory` | Memory engine: index, search, and status |
|
|
105
|
+
| `pai memory backend` | Embedding backends: detect, use, provision (an index is bound to the backend that embedded it) |
|
|
106
|
+
| `pai memory backend detect` | Probe the available embedding backends (ollama, then transformers-cpu) and recommend the fastest |
|
|
107
|
+
| `pai memory backend provision <backend>` | Provision a backend's model. ollama: download the F16 GGUF of arctic-embed-m-v1.5 and `ollama create` it |
|
|
108
|
+
| `pai memory backend use <id>` | Write the embedding backend to config (ollama-f16 \| transformers-cpu-q8); does not touch the index |
|
|
105
109
|
| `pai memory embed [project-slug]` | Generate embeddings for un-embedded chunks (Phase 2.5) |
|
|
106
110
|
| `pai memory index [project-slug]` | Index memory files for one project or all projects |
|
|
111
|
+
| `pai memory reembed` | Switch the index to an embedding backend: clears all vectors (batched, resumable); `pai memory embed` refills |
|
|
107
112
|
| `pai memory search <query>` | Search indexed memory (BM25 keyword, semantic, or hybrid) |
|
|
108
113
|
| `pai memory settings [key] [value]` | View or modify search settings in the PAI config file (`pai config path`) |
|
|
109
114
|
| `pai memory sources` | Show what the indexer has taken in: composition by source, which roots |
|
|
@@ -272,6 +277,7 @@ Generated man pages for every `pai` command area. Read any page in the terminal
|
|
|
272
277
|
| `pai worker status-line [term] [cwd] [session]` | One-line worker summary for a status bar (empty when none in scope). |
|
|
273
278
|
| `pai worker verify <id>` | Compare a worker's committed changes with the working tree (or --against <ref>); exit 0 when every file is identical, so discarding is safe. Also reads an archived worker (refs/pai-archive/<id>) |
|
|
274
279
|
| `pai worker wait <ids...>` | Poll workers until they finish; prints each result as one JSON line, exit 1 on failure or timeout |
|
|
280
|
+
| `pai worker wait-on <pid>` | Wait at most --max seconds (default 110, cap 115) for a detached job's pid; exit 0 gone, 3 still running, 2 never existed. |
|
|
275
281
|
| `pai worker watch` | ps refreshed every 2 seconds (plain `watch`, colors kept) |
|
|
276
282
|
| `pai zettel` | Zettelkasten intelligence: explore, surprise, converse, themes, health, suggest |
|
|
277
283
|
| `pai zettel converse <question>` | Ask the vault a question and get a synthesis prompt with relevant notes |
|