@tekmidian/pai 0.42.5 → 0.43.0
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/ARCHITECTURE.md +9 -9
- package/README.md +26 -8
- package/dist/{aibroker-client-BP74gGwD.mjs → aibroker-client-Bn9SnGMa.mjs} +3 -3
- package/dist/{aibroker-client-BP74gGwD.mjs.map → aibroker-client-Bn9SnGMa.mjs.map} +1 -1
- package/dist/{aibroker-client-C6m71p6O.mjs → aibroker-client-D5NT0S1N.mjs} +1 -1
- package/dist/{auto-route-_5zzJz5q.mjs → auto-route-CcD0OWWB.mjs} +4 -4
- package/dist/{auto-route-_5zzJz5q.mjs.map → auto-route-CcD0OWWB.mjs.map} +1 -1
- package/dist/{chain-DTII7xeL.mjs → chain-CEC1a5mX.mjs} +5 -4
- package/dist/{chain-DTII7xeL.mjs.map → chain-CEC1a5mX.mjs.map} +1 -1
- package/dist/cli/index.mjs +23 -21
- package/dist/cli/index.mjs.map +1 -1
- package/dist/cli/program.d.mts.map +1 -1
- package/dist/cli/program.mjs +23 -21
- package/dist/{clusters-j0ZuNYp9.mjs → clusters-Cw_P6lO-.mjs} +2 -2
- package/dist/{clusters-j0ZuNYp9.mjs.map → clusters-Cw_P6lO-.mjs.map} +1 -1
- package/dist/{config-B64vFg14.mjs → config-DCu8THKi.mjs} +41 -9
- package/dist/{config-B64vFg14.mjs.map → config-DCu8THKi.mjs.map} +1 -1
- package/dist/config-DeqFqa1N.mjs +3 -0
- package/dist/config-DxMZjpvY.mjs +1289 -0
- package/dist/config-DxMZjpvY.mjs.map +1 -0
- package/dist/context-handover-cache-B9NKSjwR.mjs +3242 -0
- package/dist/context-handover-cache-B9NKSjwR.mjs.map +1 -0
- package/dist/daemon/index.mjs +23 -22
- package/dist/daemon/index.mjs.map +1 -1
- package/dist/{daemon-B8N1egl0.mjs → daemon-BhldpFvO.mjs} +52 -38
- package/dist/daemon-BhldpFvO.mjs.map +1 -0
- package/dist/daemon-QIvCXB5f.mjs +24 -0
- package/dist/daemon-mcp/index.mjs +144 -117
- package/dist/daemon-mcp/index.mjs.map +1 -1
- package/dist/db-BOBfewFH.mjs +3 -0
- package/dist/{db-a1ixZQjr.mjs → db-DJ8rk0VM.mjs} +15 -6
- package/dist/{db-a1ixZQjr.mjs.map → db-DJ8rk0VM.mjs.map} +1 -1
- package/dist/db-DbY2O8QO.mjs +3 -0
- package/dist/{db-Ca5qfsMC.mjs → db-Ddns80yf.mjs} +15 -6
- package/dist/{db-Ca5qfsMC.mjs.map → db-Ddns80yf.mjs.map} +1 -1
- package/dist/{detect-CdaA48EI.mjs → detect-Bf2z-oKB.mjs} +1 -1
- package/dist/{detect-CdaA48EI.mjs.map → detect-Bf2z-oKB.mjs.map} +1 -1
- package/dist/detector-CkwkXuGh.mjs +5 -0
- package/dist/{detector-C73Nxm94.mjs → detector-DWXkeTlk.mjs} +2 -2
- package/dist/{detector-C73Nxm94.mjs.map → detector-DWXkeTlk.mjs.map} +1 -1
- package/dist/{embeddings-CEBGrzwu.mjs → embeddings-ClqKtLZ8.mjs} +1 -1
- package/dist/{embeddings-DOLZnT1X.mjs → embeddings-DvRKcQyt.mjs} +1 -1
- package/dist/{embeddings-DOLZnT1X.mjs.map → embeddings-DvRKcQyt.mjs.map} +1 -1
- package/dist/factory-47Qf_df7.mjs +3 -0
- package/dist/{factory-DEb9NmHJ.mjs → factory-DNYAqjH0.mjs} +8 -8
- package/dist/{factory-DEb9NmHJ.mjs.map → factory-DNYAqjH0.mjs.map} +1 -1
- package/dist/{fallback-oJl3BaIN.mjs → fallback-BQJ8PbCK.mjs} +185 -123
- package/dist/fallback-BQJ8PbCK.mjs.map +1 -0
- package/dist/{helpers-IjZkXBhj.mjs → helpers-crDEr6S2.mjs} +1 -1
- package/dist/{helpers-IjZkXBhj.mjs.map → helpers-crDEr6S2.mjs.map} +1 -1
- package/dist/hooks/capture-all-events.mjs +117 -34
- package/dist/hooks/capture-all-events.mjs.map +4 -4
- package/dist/hooks/capture-session-summary.mjs +110 -33
- package/dist/hooks/capture-session-summary.mjs.map +4 -4
- package/dist/hooks/capture-tool-output.mjs +105 -28
- package/dist/hooks/capture-tool-output.mjs.map +4 -4
- package/dist/hooks/cleanup-session-files.mjs +54 -13
- package/dist/hooks/cleanup-session-files.mjs.map +2 -2
- package/dist/hooks/context-compression-hook.mjs +7565 -122
- package/dist/hooks/context-compression-hook.mjs.map +4 -4
- package/dist/hooks/initialize-session.mjs +55 -14
- package/dist/hooks/initialize-session.mjs.map +2 -2
- package/dist/hooks/inject-observations.mjs +79 -18
- package/dist/hooks/inject-observations.mjs.map +3 -3
- package/dist/hooks/load-core-context.mjs +55 -14
- package/dist/hooks/load-core-context.mjs.map +2 -2
- package/dist/hooks/load-project-context.mjs +207 -122
- package/dist/hooks/load-project-context.mjs.map +4 -4
- package/dist/hooks/mcp-deferred-gate.mjs +54 -13
- package/dist/hooks/mcp-deferred-gate.mjs.map +2 -2
- package/dist/hooks/mcp-deferred-reminder.mjs +9 -0
- package/dist/hooks/mcp-deferred-reminder.mjs.map +3 -3
- package/dist/hooks/observe.mjs +54 -13
- package/dist/hooks/observe.mjs.map +2 -2
- package/dist/hooks/post-compact-inject.mjs +7419 -16
- package/dist/hooks/post-compact-inject.mjs.map +4 -4
- package/dist/hooks/route-agents-to-worker.mjs +7778 -171
- package/dist/hooks/route-agents-to-worker.mjs.map +4 -4
- package/dist/hooks/route-edits-to-worker.mjs +90 -0
- package/dist/hooks/route-edits-to-worker.mjs.map +7 -0
- package/dist/hooks/security-validator.mjs +147 -6
- package/dist/hooks/security-validator.mjs.map +4 -4
- package/dist/hooks/session-commands.mjs +9 -0
- package/dist/hooks/session-commands.mjs.map +3 -3
- package/dist/hooks/stop-hook.mjs +182 -105
- package/dist/hooks/stop-hook.mjs.map +4 -4
- package/dist/hooks/subagent-stop-hook.mjs +3 -0
- package/dist/hooks/subagent-stop-hook.mjs.map +1 -1
- package/dist/hooks/sync-todo-to-md.mjs +54 -13
- package/dist/hooks/sync-todo-to-md.mjs.map +2 -2
- package/dist/hooks/update-tab-on-action.mjs +3 -0
- package/dist/hooks/update-tab-on-action.mjs.map +1 -1
- package/dist/hooks/update-tab-titles.mjs +3 -0
- package/dist/hooks/update-tab-titles.mjs.map +1 -1
- package/dist/hooks/whisper-reinject.mjs +11 -0
- package/dist/hooks/whisper-reinject.mjs.map +3 -3
- package/dist/hooks/whisper-rules.mjs +134 -29
- package/dist/hooks/whisper-rules.mjs.map +4 -4
- package/dist/hooks/worker-proxy.mjs +7737 -117
- package/dist/hooks/worker-proxy.mjs.map +4 -4
- package/dist/hooks/worker-status-line.mjs +7883 -169
- package/dist/hooks/worker-status-line.mjs.map +4 -4
- package/dist/hooks/worker-supervision.mjs +7721 -115
- package/dist/hooks/worker-supervision.mjs.map +4 -4
- package/dist/index.d.mts +4 -2
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +10 -10
- package/dist/{indexer-backend-BPTzKFZU.mjs → indexer-backend-CdvCJCkD.mjs} +3 -3
- package/dist/{indexer-backend-BPTzKFZU.mjs.map → indexer-backend-CdvCJCkD.mjs.map} +1 -1
- package/dist/{ipc-client-BmypMNYk.mjs → ipc-client-C6NryMMb.mjs} +2 -2
- package/dist/{ipc-client-BmypMNYk.mjs.map → ipc-client-C6NryMMb.mjs.map} +1 -1
- package/dist/{kg-entity-r8duqhi9.mjs → kg-entity-BSjM5xZh.mjs} +1 -1
- package/dist/{kg-entity-r8duqhi9.mjs.map → kg-entity-BSjM5xZh.mjs.map} +1 -1
- package/dist/{latent-ideas-CtSca4qG.mjs → latent-ideas-BfL4nCQ3.mjs} +4 -4
- package/dist/{latent-ideas-CtSca4qG.mjs.map → latent-ideas-BfL4nCQ3.mjs.map} +1 -1
- package/dist/{link-boost-Bucnz3n8.mjs → link-boost-C5PaNdzm.mjs} +1 -1
- package/dist/{link-boost-Bucnz3n8.mjs.map → link-boost-C5PaNdzm.mjs.map} +1 -1
- package/dist/main-resolver-CnfnWa8C.mjs +7 -0
- package/dist/{main-resolver-DnkxPYkr.mjs → main-resolver-DvYu9jbl.mjs} +21 -11
- package/dist/main-resolver-DvYu9jbl.mjs.map +1 -0
- package/dist/{migrate-Cjzeefn9.mjs → migrate-CfERwXhY.mjs} +2 -2
- package/dist/{migrate-Cjzeefn9.mjs.map → migrate-CfERwXhY.mjs.map} +1 -1
- package/dist/{neighborhood-CM7Jgb51.mjs → neighborhood-CETR_P4y.mjs} +2 -2
- package/dist/{neighborhood-CM7Jgb51.mjs.map → neighborhood-CETR_P4y.mjs.map} +1 -1
- package/dist/{note-context-DCwE2A-M.mjs → note-context-DCcRWBoN.mjs} +1 -1
- package/dist/{note-context-DCwE2A-M.mjs.map → note-context-DCcRWBoN.mjs.map} +1 -1
- package/dist/pai-home-ChAOupZc.mjs +164 -0
- package/dist/pai-home-ChAOupZc.mjs.map +1 -0
- package/dist/{pai-marker-CHtbJMwJ.mjs → pai-marker-B20KqhA8.mjs} +1 -1
- package/dist/{pai-marker-CHtbJMwJ.mjs.map → pai-marker-B20KqhA8.mjs.map} +1 -1
- package/dist/{planner-D5Ui7DAm.mjs → planner-BlKGgpWI.mjs} +7 -6
- package/dist/{planner-D5Ui7DAm.mjs.map → planner-BlKGgpWI.mjs.map} +1 -1
- package/dist/{postgres-CtOzfoQU.mjs → postgres-CUSXWgTG.mjs} +2 -2
- package/dist/{postgres-CtOzfoQU.mjs.map → postgres-CUSXWgTG.mjs.map} +1 -1
- package/dist/{program-zpoYnJGz.mjs → program-C5jRQ1kg.mjs} +8880 -5913
- package/dist/program-C5jRQ1kg.mjs.map +1 -0
- package/dist/query-feedback-C7rSfiXU.mjs +3 -0
- package/dist/{query-feedback-Dqz-HC__.mjs → query-feedback-CYyOGi3y.mjs} +20 -6
- package/dist/query-feedback-CYyOGi3y.mjs.map +1 -0
- package/dist/{reranker-CwTCNsgA.mjs → reranker-B5qUTamW.mjs} +1 -1
- package/dist/{reranker-xPm04PXx.mjs → reranker-HHmhZk6v.mjs} +1 -1
- package/dist/{reranker-xPm04PXx.mjs.map → reranker-HHmhZk6v.mjs.map} +1 -1
- package/dist/router-CremHKTI.mjs +3 -0
- package/dist/{router-DD6D4j31.mjs → router-DBAZfE7X.mjs} +2 -2
- package/dist/{router-DD6D4j31.mjs.map → router-DBAZfE7X.mjs.map} +1 -1
- package/dist/{run-D7K5UALn.mjs → run-ByBKowN5.mjs} +980 -247
- package/dist/run-ByBKowN5.mjs.map +1 -0
- package/dist/{runtime-paths-rni52zHX.mjs → runtime-paths-B0P1TvUr.mjs} +1 -1
- package/dist/{runtime-paths-rni52zHX.mjs.map → runtime-paths-B0P1TvUr.mjs.map} +1 -1
- package/dist/{search-Rpk1cSBC.mjs → search-B69cQwDB.mjs} +3 -3
- package/dist/{search-Rpk1cSBC.mjs.map → search-B69cQwDB.mjs.map} +1 -1
- package/dist/{search-CfPpJAWQ.mjs → search-fb-5ovj4.mjs} +2 -2
- package/dist/{server-D4vAieF4.mjs → server-Ch99xt5K.mjs} +15 -14
- package/dist/server-Ch99xt5K.mjs.map +1 -0
- package/dist/skills/Advisor/SKILL.md +3 -3
- package/dist/skills/Providers/SKILL.md +30 -0
- package/dist/skills/Reconstruct/SKILL.md +1 -1
- package/dist/skills/VaultContext/SKILL.md +1 -1
- package/dist/skills/Whisper/SKILL.md +3 -3
- package/dist/skills/Worker/SKILL.md +1 -1
- package/dist/{sources-CS43CpuS.mjs → sources-KBGEA_E6.mjs} +2 -2
- package/dist/{sources-CS43CpuS.mjs.map → sources-KBGEA_E6.mjs.map} +1 -1
- package/dist/{sqlite-Cq3gJcq9.mjs → sqlite-By6r2YhZ.mjs} +3 -3
- package/dist/{sqlite-Cq3gJcq9.mjs.map → sqlite-By6r2YhZ.mjs.map} +1 -1
- package/dist/{state-CY6I-Hnc.mjs → state-DnYGRmS7.mjs} +1 -1
- package/dist/{state-BRdB-Bf1.mjs → state-PJrgfDLW.mjs} +1 -1
- package/dist/{state-BRdB-Bf1.mjs.map → state-PJrgfDLW.mjs.map} +1 -1
- package/dist/{stop-words-Hfu8u22w.mjs → stop-words-BaMEGVeY.mjs} +1 -1
- package/dist/{stop-words-Hfu8u22w.mjs.map → stop-words-BaMEGVeY.mjs.map} +1 -1
- package/dist/{sync-BWbe8JTg.mjs → sync-Btcb6xA4.mjs} +3 -3
- package/dist/{sync-BWbe8JTg.mjs.map → sync-Btcb6xA4.mjs.map} +1 -1
- package/dist/{themes-B7h9YDiy.mjs → themes-BVoAnLZj.mjs} +3 -3
- package/dist/{themes-B7h9YDiy.mjs.map → themes-BVoAnLZj.mjs.map} +1 -1
- package/dist/{tools-BW3NLMPk.mjs → tools-CAG2sUjf.mjs} +4 -3
- package/dist/{tools-LlzcV_eK.mjs → tools-DiRC5glA.mjs} +30 -233
- package/dist/tools-DiRC5glA.mjs.map +1 -0
- package/dist/{trace-u4hT-pLD.mjs → trace-Cy8quQTm.mjs} +1 -1
- package/dist/{trace-u4hT-pLD.mjs.map → trace-Cy8quQTm.mjs.map} +1 -1
- package/dist/{utils-DhMex3Ox.mjs → utils-BD8g8oSf.mjs} +1 -1
- package/dist/{utils-9Err2RBW.mjs → utils-CJymHkYm.mjs} +1 -1
- package/dist/{utils-9Err2RBW.mjs.map → utils-CJymHkYm.mjs.map} +1 -1
- package/dist/{vault-indexer-mata9S7b.mjs → vault-indexer-C5i-OAyr.mjs} +2 -2
- package/dist/{vault-indexer-mata9S7b.mjs.map → vault-indexer-C5i-OAyr.mjs.map} +1 -1
- package/dist/wakeup-BfElduEU.mjs +231 -0
- package/dist/wakeup-BfElduEU.mjs.map +1 -0
- package/dist/work-queue-worker-BA5IDBwQ.mjs +567 -0
- package/dist/work-queue-worker-BA5IDBwQ.mjs.map +1 -0
- package/dist/work-queue-worker-DLM2wlqM.mjs +14 -0
- package/dist/{zettelkasten-F0D_XfQ4.mjs → zettelkasten-BBjA7GcP.mjs} +4 -4
- package/dist/{zettelkasten-F0D_XfQ4.mjs.map → zettelkasten-BBjA7GcP.mjs.map} +1 -1
- package/docs/commands/README.md +32 -3
- package/docs/commands/audit.md +113 -0
- package/docs/commands/backup.md +2 -2
- package/docs/commands/clear-names.md +1 -1
- package/docs/commands/config.md +59 -0
- package/docs/commands/daemon.md +1 -1
- package/docs/commands/db.md +1 -1
- package/docs/commands/end.md +1 -1
- package/docs/commands/help.md +1 -1
- package/docs/commands/identity.md +1 -1
- package/docs/commands/kg.md +1 -1
- package/docs/commands/launch.md +45 -0
- package/docs/commands/mcp.md +1 -1
- package/docs/commands/memory.md +3 -3
- package/docs/commands/notify.md +1 -1
- package/docs/commands/observation.md +1 -1
- package/docs/commands/obsidian.md +1 -1
- package/docs/commands/pause.md +1 -1
- package/docs/commands/project.md +46 -1
- package/docs/commands/projects.md +46 -1
- package/docs/commands/registry.md +1 -1
- package/docs/commands/restore.md +1 -1
- package/docs/commands/session.md +1 -1
- package/docs/commands/sessions.md +1 -1
- package/docs/commands/setup.md +1 -1
- package/docs/commands/shell-init.md +1 -1
- package/docs/commands/skill.md +1 -1
- package/docs/commands/task.md +1 -1
- package/docs/commands/topic.md +1 -1
- package/docs/commands/update.md +1 -1
- package/docs/commands/worker.md +97 -6
- package/docs/commands/zettel.md +1 -1
- package/docs/provider-abstraction.md +1 -1
- package/docs/provider-independence-details.md +8 -5
- package/docs/task-bus.md +1 -1
- package/docs/worker.md +136 -83
- package/docs/workers-config.md +446 -0
- package/package.json +4 -2
- package/scripts/build-hooks.mjs +58 -3
- package/src/hooks/pre-compact.sh +5 -2
- package/src/hooks/session-stop.sh +29 -4
- package/src/hooks/ts/capture-all-events.ts +3 -3
- package/src/hooks/ts/lib/advisor-budget.test.ts +98 -0
- package/src/hooks/ts/lib/advisor-budget.ts +90 -0
- package/src/hooks/ts/lib/agent-gate.test.ts +101 -0
- package/src/hooks/ts/lib/agent-gate.ts +112 -0
- package/src/hooks/ts/lib/context-fill.ts +2 -2
- package/src/hooks/ts/lib/edit-gate.test.ts +52 -0
- package/src/hooks/ts/lib/edit-gate.ts +51 -0
- package/src/hooks/ts/lib/mcp-deferred-reminder.test.ts +8 -0
- package/src/hooks/ts/lib/pai-paths.test.ts +93 -0
- package/src/hooks/ts/lib/pai-paths.ts +168 -24
- package/src/hooks/ts/lib/project-utils/index.ts +1 -0
- package/src/hooks/ts/lib/project-utils/paths.ts +5 -4
- package/src/hooks/ts/lib/project-utils.ts +1 -0
- package/src/hooks/ts/post-tool-use/capture-tool-output.ts +2 -2
- package/src/hooks/ts/post-tool-use/whisper-reinject.test.ts +55 -0
- package/src/hooks/ts/post-tool-use/whisper-reinject.ts +3 -0
- package/src/hooks/ts/pre-compact/context-compression-hook.ts +1 -1
- package/src/hooks/ts/pre-tool-use/route-agents-to-worker.ts +46 -99
- package/src/hooks/ts/pre-tool-use/route-edits-to-worker.test.ts +47 -0
- package/src/hooks/ts/pre-tool-use/route-edits-to-worker.ts +96 -0
- package/src/hooks/ts/pre-tool-use/security-validator.ts +2 -1
- package/src/hooks/ts/session-end/capture-session-summary.ts +4 -4
- package/src/hooks/ts/session-start/initialize-session.ts +3 -3
- package/src/hooks/ts/session-start/inject-observations.test.ts +56 -0
- package/src/hooks/ts/session-start/inject-observations.ts +28 -8
- package/src/hooks/ts/session-start/load-core-context.ts +4 -4
- package/src/hooks/ts/session-start/load-project-context.ts +2 -2
- package/src/hooks/ts/session-start/mcp-deferred-reminder.ts +2 -0
- package/src/hooks/ts/session-start/session-commands.ts +4 -0
- package/src/hooks/ts/session-start/session-start-worker-guard.test.ts +36 -0
- package/src/hooks/ts/stop/stop-hook.ts +6 -11
- package/src/hooks/ts/user-prompt/whisper-rules.test.ts +49 -0
- package/src/hooks/ts/user-prompt/whisper-rules.ts +88 -47
- package/src/hooks/ztk-auto.sh +28 -0
- package/src/hooks/ztk-auto.test.ts +72 -0
- package/src/hooks/ztk-passthrough.mjs +71 -0
- package/statusline-command.sh +277 -116
- package/templates/agent-prefs.example.md +8 -8
- package/templates/claude-md.template.md +1 -1
- package/templates/voices.example.json +3 -3
- package/dist/config-C_ErGddD.mjs +0 -3
- package/dist/config-_lQI_W08.mjs +0 -640
- package/dist/config-_lQI_W08.mjs.map +0 -1
- package/dist/context-handover-cache-pNFdBNrU.mjs +0 -1548
- package/dist/context-handover-cache-pNFdBNrU.mjs.map +0 -1
- package/dist/daemon-B8N1egl0.mjs.map +0 -1
- package/dist/daemon-DHfyoTlk.mjs +0 -23
- package/dist/db-O-cyAPfS.mjs +0 -3
- package/dist/db-XEwJbuGO.mjs +0 -3
- package/dist/detector-C-7KRi42.mjs +0 -5
- package/dist/factory-Dbo8yNPi.mjs +0 -3
- package/dist/fallback-oJl3BaIN.mjs.map +0 -1
- package/dist/main-resolver-BAfOMppW.mjs +0 -7
- package/dist/main-resolver-DnkxPYkr.mjs.map +0 -1
- package/dist/program-zpoYnJGz.mjs.map +0 -1
- package/dist/query-feedback-DGoVRaWD.mjs +0 -3
- package/dist/query-feedback-Dqz-HC__.mjs.map +0 -1
- package/dist/router-BTIGZR2_.mjs +0 -3
- package/dist/run-D7K5UALn.mjs.map +0 -1
- package/dist/server-D4vAieF4.mjs.map +0 -1
- package/dist/tools-LlzcV_eK.mjs.map +0 -1
- package/dist/work-queue-worker-AEmfVE0F.mjs +0 -14
- package/dist/work-queue-worker-DIT-VLSh.mjs +0 -2136
- package/dist/work-queue-worker-DIT-VLSh.mjs.map +0 -1
- /package/dist/{indexer-D7MvSQPY.mjs → indexer-C5Le7XE7.mjs} +0 -0
|
@@ -0,0 +1,3242 @@
|
|
|
1
|
+
import { a as paiHomePath, o as resolvePaiFile, r as migratePaiFile } from "./pai-home-ChAOupZc.mjs";
|
|
2
|
+
import { _ as warn, c as ok, i as err, n as dim, r as encodeDir, s as now, t as bold } from "./utils-CJymHkYm.mjs";
|
|
3
|
+
import { a as slugify, i as parseSessionFilename, n as decodeEncodedDir, t as buildEncodedDirMap } from "./migrate-CfERwXhY.mjs";
|
|
4
|
+
import { n as ensurePaiMarker, t as discoverPaiMarkers } from "./pai-marker-B20KqhA8.mjs";
|
|
5
|
+
import { r as openFederation } from "./db-DJ8rk0VM.mjs";
|
|
6
|
+
import { l as defaultWorkersConfig, v as readWorkersSection, y as resolveModelCapability } from "./config-DxMZjpvY.mjs";
|
|
7
|
+
import { i as kgAdd, o as kgInvalidate, r as upsertKgEntity, s as kgQuery } from "./kg-entity-BSjM5xZh.mjs";
|
|
8
|
+
import { _ as workersLogDir, f as ensureNoMcpConfig, i as buildRunEnv, n as ensureProxyRunning, t as DEFAULT_PROXY_PORT, u as resolveTarget } from "./server-Ch99xt5K.mjs";
|
|
9
|
+
import { d as registryDb, k as storageBackend, n as daemonConfig } from "./state-PJrgfDLW.mjs";
|
|
10
|
+
import { existsSync, mkdirSync, readFileSync, readdirSync, realpathSync, renameSync, statSync, unlinkSync, writeFileSync } from "node:fs";
|
|
11
|
+
import { homedir, tmpdir } from "node:os";
|
|
12
|
+
import { basename, dirname, join, resolve } from "node:path";
|
|
13
|
+
import { randomUUID } from "node:crypto";
|
|
14
|
+
import { copyFileSync as copyFileSync$1, existsSync as existsSync$1, linkSync as linkSync$1, mkdirSync as mkdirSync$1, readFileSync as readFileSync$1, readdirSync as readdirSync$1, renameSync as renameSync$1, writeFileSync as writeFileSync$1 } from "fs";
|
|
15
|
+
import { basename as basename$1, join as join$1, resolve as resolve$1 } from "path";
|
|
16
|
+
import { homedir as homedir$1 } from "os";
|
|
17
|
+
|
|
18
|
+
//#region src/registry/moved.ts
|
|
19
|
+
/**
|
|
20
|
+
* moved.ts — reconnect a project to transcripts that moved out from under it.
|
|
21
|
+
*
|
|
22
|
+
* The registry records an `encoded_dir`: the name Claude Code gave the folder
|
|
23
|
+
* holding a project's transcripts. It is written once, when the project is
|
|
24
|
+
* added, and nothing updates it when the project moves. So a project that has
|
|
25
|
+
* been relocated points at a directory that is empty or gone, and every lookup
|
|
26
|
+
* — checkpoints, handovers, session digests — quietly returns nothing.
|
|
27
|
+
*
|
|
28
|
+
* `resolveTranscriptDir` already re-derives the name from the project's current
|
|
29
|
+
* root path, which fixes the case where the encoding is stale but the path is
|
|
30
|
+
* right. It cannot fix the case where the ENCODING RULE itself does not
|
|
31
|
+
* reproduce the folder name: iCloud paths with `~` in them, emoji segments, or
|
|
32
|
+
* a folder Claude Code created under a path the project no longer has.
|
|
33
|
+
*
|
|
34
|
+
* This module answers that case by asking the transcripts instead of guessing.
|
|
35
|
+
* Every transcript entry records the `cwd` it was written in, so the mapping
|
|
36
|
+
* from a project root to its transcript folder is a fact sitting on disk rather
|
|
37
|
+
* than something to be inferred from a naming convention. Reading it is slower
|
|
38
|
+
* than a string transform and it is right, which is the correct trade for a
|
|
39
|
+
* repair that runs on demand.
|
|
40
|
+
*/
|
|
41
|
+
/** Where Claude Code keeps per-project transcript folders. */
|
|
42
|
+
function claudeProjectsDir() {
|
|
43
|
+
return join(homedir(), ".claude", "projects");
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* Every transcript file for one project folder — live and archived.
|
|
47
|
+
*
|
|
48
|
+
* The archived half matters: `session-stop` moves all but the newest transcript
|
|
49
|
+
* into `sessions/`, so a folder whose work is finished has an empty top level
|
|
50
|
+
* and everything underneath. Counting only the top level reports a busy project
|
|
51
|
+
* as unused, which is how an earlier audit of this same problem overstated the
|
|
52
|
+
* breakage by a factor of three.
|
|
53
|
+
*/
|
|
54
|
+
function transcriptFiles(projectDir) {
|
|
55
|
+
const out = [];
|
|
56
|
+
for (const dir of [projectDir, join(projectDir, "sessions")]) {
|
|
57
|
+
if (!existsSync(dir)) continue;
|
|
58
|
+
try {
|
|
59
|
+
for (const entry of readdirSync(dir)) if (entry.endsWith(".jsonl")) out.push(join(dir, entry));
|
|
60
|
+
} catch {}
|
|
61
|
+
}
|
|
62
|
+
return out;
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* The working directory a transcript was recorded in.
|
|
66
|
+
*
|
|
67
|
+
* Reads only the head of the file. `cwd` is present on the first entry and does
|
|
68
|
+
* not change within a session, so scanning further would cost time to learn
|
|
69
|
+
* nothing. Returns null rather than throwing: a truncated or half-written
|
|
70
|
+
* transcript is normal for a session that is still running.
|
|
71
|
+
*/
|
|
72
|
+
function cwdOfTranscript(file, maxBytes = 64 * 1024) {
|
|
73
|
+
let head;
|
|
74
|
+
try {
|
|
75
|
+
head = readFileSync(file).subarray(0, maxBytes).toString("utf-8");
|
|
76
|
+
} catch {
|
|
77
|
+
return null;
|
|
78
|
+
}
|
|
79
|
+
for (const line of head.split("\n")) {
|
|
80
|
+
if (!line.trim()) continue;
|
|
81
|
+
try {
|
|
82
|
+
const cwd = JSON.parse(line).cwd;
|
|
83
|
+
if (cwd) return cwd;
|
|
84
|
+
} catch {
|
|
85
|
+
continue;
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
return null;
|
|
89
|
+
}
|
|
90
|
+
/**
|
|
91
|
+
* Map every working directory seen on disk to the folders that hold its
|
|
92
|
+
* transcripts.
|
|
93
|
+
*
|
|
94
|
+
* A directory can legitimately map to more than one folder — Claude Code's
|
|
95
|
+
* encoding is lossy, so two different paths can collide, and a project moved
|
|
96
|
+
* and moved back leaves both. Callers pick; this reports.
|
|
97
|
+
*/
|
|
98
|
+
function scanTranscriptFolders(projectsDir = claudeProjectsDir(), sampleFilesPerFolder = 8) {
|
|
99
|
+
const byCwd = /* @__PURE__ */ new Map();
|
|
100
|
+
if (!existsSync(projectsDir)) return byCwd;
|
|
101
|
+
let entries;
|
|
102
|
+
try {
|
|
103
|
+
entries = readdirSync(projectsDir);
|
|
104
|
+
} catch {
|
|
105
|
+
return byCwd;
|
|
106
|
+
}
|
|
107
|
+
for (const name of entries) {
|
|
108
|
+
const dir = join(projectsDir, name);
|
|
109
|
+
try {
|
|
110
|
+
if (!statSync(dir).isDirectory()) continue;
|
|
111
|
+
} catch {
|
|
112
|
+
continue;
|
|
113
|
+
}
|
|
114
|
+
const files = transcriptFiles(dir);
|
|
115
|
+
if (files.length === 0) continue;
|
|
116
|
+
const mtimes = /* @__PURE__ */ new Map();
|
|
117
|
+
for (const f of files) try {
|
|
118
|
+
mtimes.set(f, statSync(f).mtimeMs);
|
|
119
|
+
} catch {
|
|
120
|
+
mtimes.set(f, 0);
|
|
121
|
+
}
|
|
122
|
+
const ordered = files.sort((a, b) => (mtimes.get(b) ?? 0) - (mtimes.get(a) ?? 0));
|
|
123
|
+
const newest = mtimes.get(ordered[0]) ?? 0;
|
|
124
|
+
const tally = /* @__PURE__ */ new Map();
|
|
125
|
+
let sampled = 0;
|
|
126
|
+
for (const f of ordered.slice(0, sampleFilesPerFolder)) {
|
|
127
|
+
const cwd = cwdOfTranscript(f);
|
|
128
|
+
if (!cwd) continue;
|
|
129
|
+
sampled++;
|
|
130
|
+
tally.set(cwd, (tally.get(cwd) ?? 0) + 1);
|
|
131
|
+
}
|
|
132
|
+
for (const [cwd, matching] of tally) {
|
|
133
|
+
const record = {
|
|
134
|
+
name,
|
|
135
|
+
count: files.length,
|
|
136
|
+
newest,
|
|
137
|
+
matching,
|
|
138
|
+
total: sampled
|
|
139
|
+
};
|
|
140
|
+
const list = byCwd.get(cwd);
|
|
141
|
+
if (list) list.push(record);
|
|
142
|
+
else byCwd.set(cwd, [record]);
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
return byCwd;
|
|
146
|
+
}
|
|
147
|
+
/**
|
|
148
|
+
* Which projects point at the wrong transcript folder, and where they belong.
|
|
149
|
+
*
|
|
150
|
+
* A project is only reported when its stored folder yields nothing AND its root
|
|
151
|
+
* path is recorded as a `cwd` somewhere else. Both halves matter: without the
|
|
152
|
+
* first this would rewrite entries that work, and without the second it would
|
|
153
|
+
* have nothing better to offer than the value already there.
|
|
154
|
+
*
|
|
155
|
+
* `resolvesNow` is supplied by the caller so this module does not have to
|
|
156
|
+
* duplicate the resolver's fallback logic — a project the shipped resolver
|
|
157
|
+
* already handles is not broken and must not be "repaired".
|
|
158
|
+
*/
|
|
159
|
+
function findMovedProjects(rows, byCwd, resolvesNow) {
|
|
160
|
+
const out = [];
|
|
161
|
+
for (const row of rows) {
|
|
162
|
+
if (resolvesNow(row)) continue;
|
|
163
|
+
const candidates = byCwd.get(row.root_path);
|
|
164
|
+
if (!candidates || candidates.length === 0) continue;
|
|
165
|
+
const owned = candidates.filter((c) => c.matching * 2 > c.total);
|
|
166
|
+
if (owned.length === 0) continue;
|
|
167
|
+
const best = [...owned].sort((a, b) => b.count - a.count || b.newest - a.newest)[0];
|
|
168
|
+
if (best.name === row.encoded_dir) continue;
|
|
169
|
+
out.push({
|
|
170
|
+
id: row.id,
|
|
171
|
+
slug: row.slug,
|
|
172
|
+
rootPath: row.root_path,
|
|
173
|
+
storedDir: row.encoded_dir,
|
|
174
|
+
correctDir: best.name,
|
|
175
|
+
transcripts: best.count,
|
|
176
|
+
sessions: row.sessions
|
|
177
|
+
});
|
|
178
|
+
}
|
|
179
|
+
return out.sort((a, b) => b.sessions - a.sessions || b.transcripts - a.transcripts);
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
//#endregion
|
|
183
|
+
//#region src/cli/commands/registry/utils.ts
|
|
184
|
+
/**
|
|
185
|
+
* Would writing this encoded_dir replace a working one with a broken one?
|
|
186
|
+
*
|
|
187
|
+
* `encodeDir` is lossy: `~` and emoji do not survive it, so a value derived
|
|
188
|
+
* from a project's path can name a folder Claude Code never created. Every
|
|
189
|
+
* caller here derives its value that way, and this function is the single
|
|
190
|
+
* point they all pass through.
|
|
191
|
+
*
|
|
192
|
+
* `pai registry reconnect` repairs those by reading the cwd recorded inside the
|
|
193
|
+
* transcripts. Without this check the next scan silently reverts the repair —
|
|
194
|
+
* and it reverts it in the most confusing possible way, because a read taken
|
|
195
|
+
* straight after the repair still shows it. Observed twice on 2026-08-02:
|
|
196
|
+
* three projects reconnected, verified, and rediscovered as broken within the
|
|
197
|
+
* hour, with the repair command reporting success both times.
|
|
198
|
+
*
|
|
199
|
+
* Permits the write when the new value resolves to transcripts, or when the
|
|
200
|
+
* existing one resolves to nothing — i.e. whenever it cannot make things worse.
|
|
201
|
+
*/
|
|
202
|
+
function worthWriting(db, projectId, encodedDir) {
|
|
203
|
+
if (transcriptFiles(join(claudeProjectsDir(), encodedDir)).length > 0) return true;
|
|
204
|
+
const current = db.prepare("SELECT encoded_dir FROM projects WHERE id = ?").get(projectId)?.encoded_dir;
|
|
205
|
+
if (!current) return true;
|
|
206
|
+
return transcriptFiles(join(claudeProjectsDir(), current)).length === 0;
|
|
207
|
+
}
|
|
208
|
+
/**
|
|
209
|
+
* Upsert a project row. Returns { id, isNew }.
|
|
210
|
+
*
|
|
211
|
+
* Matching priority:
|
|
212
|
+
* 1. root_path — most reliable; handles slug collisions
|
|
213
|
+
* 2. encoded_dir — Claude project dirs are canonical
|
|
214
|
+
* 3. Insert with suffix-deduplication on slug collision
|
|
215
|
+
*
|
|
216
|
+
* display_name is set to basename(rootPath) on INSERT so that the unified
|
|
217
|
+
* listing always shows a human-readable name rather than the kebab-case slug.
|
|
218
|
+
*/
|
|
219
|
+
function upsertProject(db, slug, rootPath, encodedDir) {
|
|
220
|
+
const ts = now();
|
|
221
|
+
const byPath = db.prepare("SELECT id FROM projects WHERE root_path = ?").get(rootPath);
|
|
222
|
+
if (byPath) {
|
|
223
|
+
const encodedOwner = db.prepare("SELECT id FROM projects WHERE encoded_dir = ?").get(encodedDir);
|
|
224
|
+
if ((!encodedOwner || encodedOwner.id === byPath.id) && worthWriting(db, byPath.id, encodedDir)) db.prepare("UPDATE projects SET encoded_dir = ?, updated_at = ? WHERE id = ?").run(encodedDir, ts, byPath.id);
|
|
225
|
+
return {
|
|
226
|
+
id: byPath.id,
|
|
227
|
+
isNew: false
|
|
228
|
+
};
|
|
229
|
+
}
|
|
230
|
+
const byEncoded = db.prepare("SELECT id FROM projects WHERE encoded_dir = ?").get(encodedDir);
|
|
231
|
+
if (byEncoded) {
|
|
232
|
+
const pathOwner = db.prepare("SELECT id FROM projects WHERE root_path = ?").get(rootPath);
|
|
233
|
+
if (!pathOwner || pathOwner.id === byEncoded.id) db.prepare("UPDATE projects SET root_path = ?, updated_at = ? WHERE id = ?").run(rootPath, ts, byEncoded.id);
|
|
234
|
+
return {
|
|
235
|
+
id: byEncoded.id,
|
|
236
|
+
isNew: false
|
|
237
|
+
};
|
|
238
|
+
}
|
|
239
|
+
let finalSlug = slug;
|
|
240
|
+
let attempt = 0;
|
|
241
|
+
while (true) {
|
|
242
|
+
if (!db.prepare("SELECT id FROM projects WHERE slug = ?").get(finalSlug)) break;
|
|
243
|
+
attempt++;
|
|
244
|
+
finalSlug = `${slug}-${attempt}`;
|
|
245
|
+
}
|
|
246
|
+
const displayName = basename(rootPath) || finalSlug;
|
|
247
|
+
const result = db.prepare(`INSERT OR IGNORE INTO projects
|
|
248
|
+
(slug, display_name, root_path, encoded_dir, type, status, created_at, updated_at)
|
|
249
|
+
VALUES (?, ?, ?, ?, 'local', 'active', ?, ?)`).run(finalSlug, displayName, rootPath, encodedDir, ts, ts);
|
|
250
|
+
if (result.changes === 0) {
|
|
251
|
+
const fallback = db.prepare("SELECT id FROM projects WHERE encoded_dir = ?").get(encodedDir) ?? db.prepare("SELECT id FROM projects WHERE root_path = ?").get(rootPath);
|
|
252
|
+
if (fallback) return {
|
|
253
|
+
id: fallback.id,
|
|
254
|
+
isNew: false
|
|
255
|
+
};
|
|
256
|
+
throw new Error(`upsertProject: INSERT OR IGNORE was suppressed but no matching row found for root_path=${rootPath} encoded_dir=${encodedDir}`);
|
|
257
|
+
}
|
|
258
|
+
return {
|
|
259
|
+
id: result.lastInsertRowid,
|
|
260
|
+
isNew: true
|
|
261
|
+
};
|
|
262
|
+
}
|
|
263
|
+
/** Upsert a session note. Returns true if newly inserted. */
|
|
264
|
+
function upsertSession(db, projectId, number, date, slug, title, filename) {
|
|
265
|
+
if (db.prepare("SELECT id FROM sessions WHERE project_id = ? AND number = ?").get(projectId, number)) return false;
|
|
266
|
+
const ts = now();
|
|
267
|
+
db.prepare(`INSERT INTO sessions
|
|
268
|
+
(project_id, number, date, slug, title, filename, status, created_at)
|
|
269
|
+
VALUES (?, ?, ?, ?, ?, ?, 'completed', ?)`).run(projectId, number, date, slug, title, filename, ts);
|
|
270
|
+
return true;
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
//#endregion
|
|
274
|
+
//#region src/cli/commands/registry/scan.ts
|
|
275
|
+
/** Registry scan command: walk ~/.claude/projects/ and populate the registry. */
|
|
276
|
+
/**
|
|
277
|
+
* Build a reverse map from encoded-dir → real path using the clc session
|
|
278
|
+
* registry (~/.claude/session.json).
|
|
279
|
+
*
|
|
280
|
+
* The clc registry stores { sessions: [{ directory, ... }, ...] }. For each
|
|
281
|
+
* entry with a resolvable directory, we encode the realpath and add it to
|
|
282
|
+
* the map. This lets the scanner recover project paths that are not in
|
|
283
|
+
* Claude's session-registry.json but were registered by clc.
|
|
284
|
+
*/
|
|
285
|
+
function buildClcDirMap() {
|
|
286
|
+
const map = /* @__PURE__ */ new Map();
|
|
287
|
+
const sessionFile = join(homedir(), ".claude", "session.json");
|
|
288
|
+
if (!existsSync(sessionFile)) return map;
|
|
289
|
+
try {
|
|
290
|
+
const raw = readFileSync(sessionFile, "utf8");
|
|
291
|
+
const parsed = JSON.parse(raw);
|
|
292
|
+
for (const entry of parsed.sessions ?? []) {
|
|
293
|
+
const dir = entry.directory;
|
|
294
|
+
if (!dir) continue;
|
|
295
|
+
try {
|
|
296
|
+
const real = realpathSync(dir);
|
|
297
|
+
if (!existsSync(real)) continue;
|
|
298
|
+
const encoded = encodeDir(real);
|
|
299
|
+
map.set(encoded, real);
|
|
300
|
+
} catch {}
|
|
301
|
+
}
|
|
302
|
+
} catch {}
|
|
303
|
+
return map;
|
|
304
|
+
}
|
|
305
|
+
const CLAUDE_PROJECTS_DIR$1 = join(homedir(), ".claude", "projects");
|
|
306
|
+
/** Old registry-scan config path: ~/.pai/config.json (pre-2026-09-19). Named
|
|
307
|
+
* "config.json" there, but that name is taken at PAI_HOME by the daemon
|
|
308
|
+
* config, so the new location is registry-scan.json instead. */
|
|
309
|
+
function oldScanConfigFile() {
|
|
310
|
+
return join(homedir(), ".pai", "config.json");
|
|
311
|
+
}
|
|
312
|
+
function scanConfigFilePath() {
|
|
313
|
+
return resolvePaiFile(paiHomePath("registry-scan.json"), [oldScanConfigFile()], "pai config migrate --registry-scan");
|
|
314
|
+
}
|
|
315
|
+
function migrateScanConfig(opts = {}) {
|
|
316
|
+
return migratePaiFile(paiHomePath("registry-scan.json"), [oldScanConfigFile()], opts);
|
|
317
|
+
}
|
|
318
|
+
function loadScanConfig() {
|
|
319
|
+
const file = scanConfigFilePath();
|
|
320
|
+
if (!existsSync(file)) return { scan_dirs: [] };
|
|
321
|
+
try {
|
|
322
|
+
return JSON.parse(readFileSync(file, "utf8"));
|
|
323
|
+
} catch {
|
|
324
|
+
return { scan_dirs: [] };
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
function saveScanConfig(config) {
|
|
328
|
+
const file = paiHomePath("registry-scan.json");
|
|
329
|
+
mkdirSync(paiHomePath(), { recursive: true });
|
|
330
|
+
writeFileSync(file, JSON.stringify(config, null, 2) + "\n", "utf8");
|
|
331
|
+
}
|
|
332
|
+
/**
|
|
333
|
+
* Resolve a path to its canonical form, falling back to the input.
|
|
334
|
+
*
|
|
335
|
+
* Every path that becomes a `projects.root_path` must go through this. That
|
|
336
|
+
* column is UNIQUE, so two spellings of one directory create two projects and
|
|
337
|
+
* split session history between them. The spellings are not hypothetical: a
|
|
338
|
+
* configured scan_dir of `~/dev/ai` (where `~/dev` is a symlink) makes every
|
|
339
|
+
* project under it register under the symlinked path, while a session started
|
|
340
|
+
* from the resolved path registers a rival row.
|
|
341
|
+
*/
|
|
342
|
+
function canonicalPath(p) {
|
|
343
|
+
try {
|
|
344
|
+
return realpathSync(p);
|
|
345
|
+
} catch {
|
|
346
|
+
return p;
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
function resolveHome(p) {
|
|
350
|
+
if (p.startsWith("~/")) return join(homedir(), p.slice(2));
|
|
351
|
+
return resolve(p);
|
|
352
|
+
}
|
|
353
|
+
/**
|
|
354
|
+
* Recursively find all .md files in a directory, including YYYY/MM subdirectories.
|
|
355
|
+
* Returns filenames (basename only).
|
|
356
|
+
*/
|
|
357
|
+
function findNoteFiles(dir) {
|
|
358
|
+
const results = [];
|
|
359
|
+
if (!existsSync(dir)) return results;
|
|
360
|
+
for (const entry of readdirSync(dir, { withFileTypes: true })) if (entry.isFile() && entry.name.endsWith(".md")) results.push(entry.name);
|
|
361
|
+
else if (entry.isDirectory() && /^\d{4}$/.test(entry.name)) {
|
|
362
|
+
const yearDir = join(dir, entry.name);
|
|
363
|
+
for (const monthEntry of readdirSync(yearDir, { withFileTypes: true })) if (monthEntry.isDirectory() && /^\d{2}$/.test(monthEntry.name)) {
|
|
364
|
+
const monthDir = join(yearDir, monthEntry.name);
|
|
365
|
+
for (const noteEntry of readdirSync(monthDir, { withFileTypes: true })) if (noteEntry.isFile() && noteEntry.name.endsWith(".md")) results.push(noteEntry.name);
|
|
366
|
+
}
|
|
367
|
+
}
|
|
368
|
+
return results;
|
|
369
|
+
}
|
|
370
|
+
function performScan(db) {
|
|
371
|
+
const result = {
|
|
372
|
+
projectsScanned: 0,
|
|
373
|
+
projectsNew: 0,
|
|
374
|
+
projectsUpdated: 0,
|
|
375
|
+
sessionsScanned: 0,
|
|
376
|
+
sessionsNew: 0,
|
|
377
|
+
skipped: []
|
|
378
|
+
};
|
|
379
|
+
if (!existsSync(CLAUDE_PROJECTS_DIR$1)) throw new Error(`Claude projects directory not found: ${CLAUDE_PROJECTS_DIR$1}`);
|
|
380
|
+
const entries = readdirSync(CLAUDE_PROJECTS_DIR$1).filter((name) => {
|
|
381
|
+
return statSync(join(CLAUDE_PROJECTS_DIR$1, name)).isDirectory();
|
|
382
|
+
});
|
|
383
|
+
const lookupMap = buildEncodedDirMap();
|
|
384
|
+
const clcMap = buildClcDirMap();
|
|
385
|
+
for (const encodedDir of entries) {
|
|
386
|
+
let rootPath = decodeEncodedDir(encodedDir, lookupMap);
|
|
387
|
+
if (!existsSync(rootPath) && clcMap.has(encodedDir)) {
|
|
388
|
+
const clcPath = clcMap.get(encodedDir);
|
|
389
|
+
if (existsSync(clcPath)) rootPath = clcPath;
|
|
390
|
+
}
|
|
391
|
+
if (!existsSync(rootPath)) {
|
|
392
|
+
result.skipped.push(`${encodedDir} (decoded: ${rootPath} — path not found on disk)`);
|
|
393
|
+
result.projectsScanned++;
|
|
394
|
+
continue;
|
|
395
|
+
}
|
|
396
|
+
rootPath = canonicalPath(rootPath);
|
|
397
|
+
const slug = slugify(basename(rootPath) || encodedDir);
|
|
398
|
+
const { id, isNew } = upsertProject(db, slug, rootPath, encodedDir);
|
|
399
|
+
result.projectsScanned++;
|
|
400
|
+
if (isNew) result.projectsNew++;
|
|
401
|
+
else result.projectsUpdated++;
|
|
402
|
+
try {
|
|
403
|
+
ensurePaiMarker(rootPath, slug);
|
|
404
|
+
} catch {}
|
|
405
|
+
const claudeNotesDir = join(CLAUDE_PROJECTS_DIR$1, encodedDir, "Notes");
|
|
406
|
+
if (existsSync(claudeNotesDir)) {
|
|
407
|
+
if (claudeNotesDir !== join(rootPath, "Notes")) db.prepare("UPDATE projects SET claude_notes_dir = ?, updated_at = ? WHERE id = ?").run(claudeNotesDir, Date.now(), id);
|
|
408
|
+
}
|
|
409
|
+
if (!existsSync(claudeNotesDir)) continue;
|
|
410
|
+
const noteFiles = findNoteFiles(claudeNotesDir);
|
|
411
|
+
for (const filename of noteFiles) {
|
|
412
|
+
const parsed = parseSessionFilename(filename);
|
|
413
|
+
if (!parsed) continue;
|
|
414
|
+
result.sessionsScanned++;
|
|
415
|
+
if (upsertSession(db, id, parsed.number, parsed.date, parsed.slug, parsed.title, parsed.filename)) result.sessionsNew++;
|
|
416
|
+
}
|
|
417
|
+
}
|
|
418
|
+
{
|
|
419
|
+
const activeProjects = db.prepare("SELECT id, slug, root_path FROM projects WHERE status = 'active'").all();
|
|
420
|
+
for (const project of activeProjects) {
|
|
421
|
+
const notesDir = join(project.root_path, "Notes");
|
|
422
|
+
if (!existsSync(notesDir)) continue;
|
|
423
|
+
let files;
|
|
424
|
+
try {
|
|
425
|
+
files = findNoteFiles(notesDir);
|
|
426
|
+
} catch {
|
|
427
|
+
continue;
|
|
428
|
+
}
|
|
429
|
+
for (const filename of files) {
|
|
430
|
+
const parsed = parseSessionFilename(filename);
|
|
431
|
+
if (!parsed) continue;
|
|
432
|
+
result.sessionsScanned++;
|
|
433
|
+
if (upsertSession(db, project.id, parsed.number, parsed.date, parsed.slug, parsed.title, parsed.filename)) result.sessionsNew++;
|
|
434
|
+
}
|
|
435
|
+
}
|
|
436
|
+
}
|
|
437
|
+
const config = loadScanConfig();
|
|
438
|
+
if (config.scan_dirs.length) for (const rawDir of config.scan_dirs) {
|
|
439
|
+
const scanDir = resolveHome(rawDir);
|
|
440
|
+
if (!existsSync(scanDir)) {
|
|
441
|
+
result.skipped.push(`${rawDir} (configured scan_dir not found)`);
|
|
442
|
+
continue;
|
|
443
|
+
}
|
|
444
|
+
const children = readdirSync(scanDir).filter((name) => {
|
|
445
|
+
if (name.startsWith(".")) return false;
|
|
446
|
+
const full = join(scanDir, name);
|
|
447
|
+
try {
|
|
448
|
+
return statSync(full).isDirectory();
|
|
449
|
+
} catch {
|
|
450
|
+
return false;
|
|
451
|
+
}
|
|
452
|
+
});
|
|
453
|
+
for (const child of children) {
|
|
454
|
+
const childPath = canonicalPath(join(scanDir, child));
|
|
455
|
+
const childSlug = slugify(child);
|
|
456
|
+
const childEncoded = encodeDir(childPath);
|
|
457
|
+
const existing = db.prepare("SELECT id FROM projects WHERE root_path = ?").get(childPath);
|
|
458
|
+
if (existing) {
|
|
459
|
+
result.projectsScanned++;
|
|
460
|
+
result.projectsUpdated++;
|
|
461
|
+
try {
|
|
462
|
+
ensurePaiMarker(childPath, childSlug);
|
|
463
|
+
} catch {}
|
|
464
|
+
const notesDir = join(childPath, "Notes");
|
|
465
|
+
if (existsSync(notesDir)) {
|
|
466
|
+
const noteFiles = readdirSync(notesDir).filter((f) => f.endsWith(".md"));
|
|
467
|
+
for (const filename of noteFiles) {
|
|
468
|
+
const parsed = parseSessionFilename(filename);
|
|
469
|
+
if (!parsed) continue;
|
|
470
|
+
result.sessionsScanned++;
|
|
471
|
+
if (upsertSession(db, existing.id, parsed.number, parsed.date, parsed.slug, parsed.title, parsed.filename)) result.sessionsNew++;
|
|
472
|
+
}
|
|
473
|
+
}
|
|
474
|
+
continue;
|
|
475
|
+
}
|
|
476
|
+
const { id, isNew } = upsertProject(db, childSlug, childPath, childEncoded);
|
|
477
|
+
result.projectsScanned++;
|
|
478
|
+
if (isNew) result.projectsNew++;
|
|
479
|
+
else result.projectsUpdated++;
|
|
480
|
+
try {
|
|
481
|
+
ensurePaiMarker(childPath, childSlug);
|
|
482
|
+
} catch {}
|
|
483
|
+
const notesDir = join(childPath, "Notes");
|
|
484
|
+
if (existsSync(notesDir)) {
|
|
485
|
+
const noteFiles = readdirSync(notesDir).filter((f) => f.endsWith(".md"));
|
|
486
|
+
for (const filename of noteFiles) {
|
|
487
|
+
const parsed = parseSessionFilename(filename);
|
|
488
|
+
if (!parsed) continue;
|
|
489
|
+
result.sessionsScanned++;
|
|
490
|
+
if (upsertSession(db, id, parsed.number, parsed.date, parsed.slug, parsed.title, parsed.filename)) result.sessionsNew++;
|
|
491
|
+
}
|
|
492
|
+
}
|
|
493
|
+
}
|
|
494
|
+
}
|
|
495
|
+
if (config.scan_dirs.length) {
|
|
496
|
+
const markers = discoverPaiMarkers(config.scan_dirs.map(resolveHome).filter(existsSync));
|
|
497
|
+
for (const marker of markers) {
|
|
498
|
+
const registeredRow = db.prepare("SELECT id, root_path, slug, encoded_dir FROM projects WHERE slug = ?").get(marker.slug);
|
|
499
|
+
if (!registeredRow) continue;
|
|
500
|
+
const markerRoot = canonicalPath(marker.projectRoot);
|
|
501
|
+
if (registeredRow.root_path !== markerRoot) {
|
|
502
|
+
const newEncoded = encodeDir(markerRoot);
|
|
503
|
+
const now4 = Date.now();
|
|
504
|
+
const encodedOwner = db.prepare("SELECT id FROM projects WHERE encoded_dir = ?").get(newEncoded);
|
|
505
|
+
const pathOwner = db.prepare("SELECT id FROM projects WHERE root_path = ?").get(markerRoot);
|
|
506
|
+
const encodedSafe = !encodedOwner || encodedOwner.id === registeredRow.id;
|
|
507
|
+
const pathSafe = !pathOwner || pathOwner.id === registeredRow.id;
|
|
508
|
+
const derivedResolves = transcriptFiles(join(claudeProjectsDir(), newEncoded)).length > 0;
|
|
509
|
+
const currentResolves = Boolean(registeredRow.encoded_dir) && transcriptFiles(join(claudeProjectsDir(), registeredRow.encoded_dir)).length > 0;
|
|
510
|
+
if (encodedSafe && pathSafe && (derivedResolves || !currentResolves)) db.prepare("UPDATE projects SET root_path = ?, encoded_dir = ?, updated_at = ? WHERE id = ?").run(markerRoot, newEncoded, now4, registeredRow.id);
|
|
511
|
+
else if (pathSafe) db.prepare("UPDATE projects SET root_path = ?, updated_at = ? WHERE id = ?").run(markerRoot, now4, registeredRow.id);
|
|
512
|
+
}
|
|
513
|
+
}
|
|
514
|
+
}
|
|
515
|
+
{
|
|
516
|
+
const stale = db.prepare("SELECT id, slug, root_path FROM projects WHERE display_name = slug AND root_path IS NOT NULL AND root_path != ''").all();
|
|
517
|
+
for (const row of stale) {
|
|
518
|
+
const name = basename(row.root_path);
|
|
519
|
+
if (name && name !== row.slug) db.prepare("UPDATE projects SET display_name = ?, updated_at = ? WHERE id = ?").run(name, Date.now(), row.id);
|
|
520
|
+
}
|
|
521
|
+
}
|
|
522
|
+
return result;
|
|
523
|
+
}
|
|
524
|
+
/**
|
|
525
|
+
* Run the registry scan CLI command.
|
|
526
|
+
*
|
|
527
|
+
* @param opts.quick When true, skips verbose output (same scan, less noise).
|
|
528
|
+
* The underlying scan is always incremental via upsert —
|
|
529
|
+
* this flag exists for hook/daemon-triggered invocations that
|
|
530
|
+
* want minimal log output.
|
|
531
|
+
*/
|
|
532
|
+
function cmdScan(db, opts = {}) {
|
|
533
|
+
const config = loadScanConfig();
|
|
534
|
+
if (!opts.quick) {
|
|
535
|
+
console.log(dim("Scanning ~/.claude/projects/ ..."));
|
|
536
|
+
if (config.scan_dirs.length) console.log(dim(`Scanning ${config.scan_dirs.length} extra dir(s): ${config.scan_dirs.join(", ")}`));
|
|
537
|
+
console.log(dim("Scanning project-root Notes/ directories ..."));
|
|
538
|
+
}
|
|
539
|
+
let result;
|
|
540
|
+
try {
|
|
541
|
+
result = performScan(db);
|
|
542
|
+
} catch (e) {
|
|
543
|
+
console.error(err(String(e)));
|
|
544
|
+
process.exitCode = 1;
|
|
545
|
+
return;
|
|
546
|
+
}
|
|
547
|
+
if (!opts.quick) {
|
|
548
|
+
console.log(ok(`Scanned ${bold(String(result.projectsScanned))} projects, ${bold(String(result.sessionsScanned))} session notes.`));
|
|
549
|
+
console.log(dim(` Projects: ${result.projectsNew} new, ${result.projectsUpdated} updated`));
|
|
550
|
+
console.log(dim(` Sessions: ${result.sessionsNew} new`));
|
|
551
|
+
if (result.skipped.length) {
|
|
552
|
+
console.log();
|
|
553
|
+
console.log(warn(` ${result.skipped.length} project(s) skipped (path not found on disk):`));
|
|
554
|
+
for (const s of result.skipped.slice(0, 10)) console.log(dim(` ${s}`));
|
|
555
|
+
if (result.skipped.length > 10) console.log(dim(` ... and ${result.skipped.length - 10} more`));
|
|
556
|
+
}
|
|
557
|
+
} else process.stderr.write(`[registry-scan] ${result.projectsScanned} projects, ${result.sessionsScanned} sessions (${result.projectsNew}+${result.sessionsNew} new).\n`);
|
|
558
|
+
}
|
|
559
|
+
|
|
560
|
+
//#endregion
|
|
561
|
+
//#region src/hooks/ts/lib/pai-paths.ts
|
|
562
|
+
/**
|
|
563
|
+
* PAI Path Resolution - Single Source of Truth
|
|
564
|
+
*
|
|
565
|
+
* This module provides consistent path resolution across all PAI hooks.
|
|
566
|
+
*
|
|
567
|
+
* Two different things live here, and they must not be confused:
|
|
568
|
+
*
|
|
569
|
+
* - ADAPTER_DIR (~/.claude by default) is the Claude Code harness adapter —
|
|
570
|
+
* fixed, hardcoded paths the harness itself loads from (Hooks/, Skills/,
|
|
571
|
+
* Agents/, Commands/, settings.json, statusline-command.sh,
|
|
572
|
+
* tab-color-command.sh). It is harness-specific: a future harness would
|
|
573
|
+
* need its own adapter directory with its own conventions.
|
|
574
|
+
* - PAI_HOME (~/.claude/pai by default — see ../../../config/pai-home.ts) is
|
|
575
|
+
* where PAI's own state lives: everything hooks WRITE (History/,
|
|
576
|
+
* agent-sessions.json, session-routing.json, ...) resolves there, with a
|
|
577
|
+
* fallback to the pre-2026-09-19 ADAPTER_DIR location and a one-time
|
|
578
|
+
* stderr notice, exactly like every other PAI_HOME file.
|
|
579
|
+
*
|
|
580
|
+
* ALSO loads .env file from ADAPTER_DIR so all hooks get environment
|
|
581
|
+
* variables without relying on Claude Code's settings.json injection.
|
|
582
|
+
*
|
|
583
|
+
* Usage in hooks:
|
|
584
|
+
* import { ADAPTER_DIR, HOOKS_DIR, SKILLS_DIR, historyDir } from './lib/pai-paths';
|
|
585
|
+
*/
|
|
586
|
+
/**
|
|
587
|
+
* Load .env file and inject into process.env
|
|
588
|
+
* Must run BEFORE ADAPTER_DIR resolution so .env can set ADAPTER_DIR/PAI_DIR if needed
|
|
589
|
+
*/
|
|
590
|
+
function loadEnvFile() {
|
|
591
|
+
const possiblePaths = [resolve$1(process.env.ADAPTER_DIR || process.env.PAI_DIR || "", ".env"), resolve$1(homedir$1(), ".claude", ".env")];
|
|
592
|
+
for (const envPath of possiblePaths) if (existsSync$1(envPath)) try {
|
|
593
|
+
const content = readFileSync$1(envPath, "utf-8");
|
|
594
|
+
for (const line of content.split("\n")) {
|
|
595
|
+
const trimmed = line.trim();
|
|
596
|
+
if (!trimmed || trimmed.startsWith("#")) continue;
|
|
597
|
+
const eqIndex = trimmed.indexOf("=");
|
|
598
|
+
if (eqIndex > 0) {
|
|
599
|
+
const key = trimmed.substring(0, eqIndex).trim();
|
|
600
|
+
let value = trimmed.substring(eqIndex + 1).trim();
|
|
601
|
+
if (value.startsWith("\"") && value.endsWith("\"") || value.startsWith("'") && value.endsWith("'")) value = value.slice(1, -1);
|
|
602
|
+
value = value.replace(/\$HOME/g, homedir$1());
|
|
603
|
+
value = value.replace(/^~(?=\/|$)/, homedir$1());
|
|
604
|
+
if (process.env[key] === void 0) process.env[key] = value;
|
|
605
|
+
}
|
|
606
|
+
}
|
|
607
|
+
break;
|
|
608
|
+
} catch {}
|
|
609
|
+
}
|
|
610
|
+
loadEnvFile();
|
|
611
|
+
function defaultAdapterDir() {
|
|
612
|
+
return resolve$1(homedir$1(), ".claude");
|
|
613
|
+
}
|
|
614
|
+
/**
|
|
615
|
+
* Never print when stdout/stderr is a data channel, not a human: hook
|
|
616
|
+
* bundles and worker-status-line.mjs set PAI_QUIET_NOTICES=1 via their
|
|
617
|
+
* esbuild banner (scripts/build-hooks.mjs), and a `pai worker run
|
|
618
|
+
* --output-format json` invocation is detected directly off argv since its
|
|
619
|
+
* env can't be set before this module's static imports resolve.
|
|
620
|
+
*/
|
|
621
|
+
function suppressDeprecationNotices() {
|
|
622
|
+
if (process.env.PAI_QUIET_NOTICES === "1") return true;
|
|
623
|
+
const idx = process.argv.indexOf("--output-format");
|
|
624
|
+
return idx !== -1 && process.argv[idx + 1] === "json";
|
|
625
|
+
}
|
|
626
|
+
/**
|
|
627
|
+
* At most once per process — a `globalThis` flag rather than a module-level
|
|
628
|
+
* `let` because hooks and the CLI can end up with more than one instance of
|
|
629
|
+
* this module loaded into the same process (separate bundles), each with its
|
|
630
|
+
* own module scope; only a property on the shared global survives that.
|
|
631
|
+
*/
|
|
632
|
+
function warnPaiDirDeprecatedOnce(message) {
|
|
633
|
+
const g = globalThis;
|
|
634
|
+
if (g.__paiDirNoticePrinted || suppressDeprecationNotices()) return;
|
|
635
|
+
g.__paiDirNoticePrinted = true;
|
|
636
|
+
process.stderr.write(`pai: ${message}\n`);
|
|
637
|
+
}
|
|
638
|
+
/**
|
|
639
|
+
* Smart ADAPTER_DIR detection with fallback
|
|
640
|
+
* Priority:
|
|
641
|
+
* 1. ADAPTER_DIR environment variable (if set) — warns once if PAI_DIR is
|
|
642
|
+
* ALSO set and resolves to a different path (naming both).
|
|
643
|
+
* 2. PAI_DIR environment variable (deprecated alias, one release) — warns
|
|
644
|
+
* once only when it differs from the default adapter root; PAI_DIR set to
|
|
645
|
+
* the same value as the default is the operator's current, correct
|
|
646
|
+
* setting and stays silent.
|
|
647
|
+
* 3. ~/.claude (standard location)
|
|
648
|
+
*/
|
|
649
|
+
function resolveAdapterDir() {
|
|
650
|
+
if (process.env.ADAPTER_DIR) {
|
|
651
|
+
const adapterDir = resolve$1(process.env.ADAPTER_DIR);
|
|
652
|
+
if (process.env.PAI_DIR) {
|
|
653
|
+
const paiDir = resolve$1(process.env.PAI_DIR);
|
|
654
|
+
if (paiDir !== adapterDir) warnPaiDirDeprecatedOnce(`ADAPTER_DIR (${adapterDir}) and PAI_DIR (${paiDir}) are both set and differ — ADAPTER_DIR wins. PAI_DIR still works for one release.`);
|
|
655
|
+
}
|
|
656
|
+
return adapterDir;
|
|
657
|
+
}
|
|
658
|
+
if (process.env.PAI_DIR) {
|
|
659
|
+
const paiDir = resolve$1(process.env.PAI_DIR);
|
|
660
|
+
if (paiDir !== defaultAdapterDir()) warnPaiDirDeprecatedOnce("PAI_DIR is deprecated — use ADAPTER_DIR for the harness adapter root (~/.claude). PAI_DIR still works for one release.");
|
|
661
|
+
return paiDir;
|
|
662
|
+
}
|
|
663
|
+
return defaultAdapterDir();
|
|
664
|
+
}
|
|
665
|
+
/** The Claude Code harness adapter root — NOT PAI's state home. See module doc above. */
|
|
666
|
+
const ADAPTER_DIR = resolveAdapterDir();
|
|
667
|
+
/**
|
|
668
|
+
* Adapter directories — fixed paths the Claude Code harness itself loads
|
|
669
|
+
* from. These stay under ADAPTER_DIR; they are not PAI state.
|
|
670
|
+
*/
|
|
671
|
+
const HOOKS_DIR = join$1(ADAPTER_DIR, "Hooks");
|
|
672
|
+
const SKILLS_DIR = join$1(ADAPTER_DIR, "Skills");
|
|
673
|
+
const AGENTS_DIR = join$1(ADAPTER_DIR, "Agents");
|
|
674
|
+
const COMMANDS_DIR = join$1(ADAPTER_DIR, "Commands");
|
|
675
|
+
/**
|
|
676
|
+
* Validate PAI directory structure on first import
|
|
677
|
+
* This fails fast with a clear error if PAI is misconfigured
|
|
678
|
+
*/
|
|
679
|
+
function validatePAIStructure() {
|
|
680
|
+
if (!existsSync$1(ADAPTER_DIR)) {
|
|
681
|
+
console.error(`ADAPTER_DIR does not exist: ${ADAPTER_DIR}`);
|
|
682
|
+
console.error(` Expected ~/.claude or set ADAPTER_DIR environment variable`);
|
|
683
|
+
process.exit(1);
|
|
684
|
+
}
|
|
685
|
+
if (!existsSync$1(HOOKS_DIR)) {
|
|
686
|
+
console.error(`PAI hooks directory not found: ${HOOKS_DIR}`);
|
|
687
|
+
console.error(` Your ADAPTER_DIR may be misconfigured`);
|
|
688
|
+
console.error(` Current ADAPTER_DIR: ${ADAPTER_DIR}`);
|
|
689
|
+
process.exit(1);
|
|
690
|
+
}
|
|
691
|
+
}
|
|
692
|
+
validatePAIStructure();
|
|
693
|
+
|
|
694
|
+
//#endregion
|
|
695
|
+
//#region src/hooks/ts/lib/project-utils/paths.ts
|
|
696
|
+
/**
|
|
697
|
+
* Path utilities — encoding, Notes/Sessions directory discovery and creation.
|
|
698
|
+
*/
|
|
699
|
+
const PROJECTS_DIR = join$1(ADAPTER_DIR, "projects");
|
|
700
|
+
/**
|
|
701
|
+
* Encode a path the same way Claude Code does:
|
|
702
|
+
* - Replace / with -
|
|
703
|
+
* - Replace . with -
|
|
704
|
+
* - Replace space with -
|
|
705
|
+
*/
|
|
706
|
+
function encodePath(path) {
|
|
707
|
+
return path.replace(/\//g, "-").replace(/\./g, "-").replace(/ /g, "-");
|
|
708
|
+
}
|
|
709
|
+
/** Get the project directory for a given working directory. */
|
|
710
|
+
function getProjectDir(cwd) {
|
|
711
|
+
return join$1(PROJECTS_DIR, encodePath(cwd));
|
|
712
|
+
}
|
|
713
|
+
/** Get the Notes directory for a project (central location). */
|
|
714
|
+
function getNotesDir(cwd) {
|
|
715
|
+
return join$1(getProjectDir(cwd), "Notes");
|
|
716
|
+
}
|
|
717
|
+
/**
|
|
718
|
+
* Find Notes directory — checks local first, falls back to central.
|
|
719
|
+
* Does NOT create the directory.
|
|
720
|
+
*/
|
|
721
|
+
function findNotesDir$1(cwd) {
|
|
722
|
+
if (basename$1(cwd).toLowerCase() === "notes" && existsSync$1(cwd)) return {
|
|
723
|
+
path: cwd,
|
|
724
|
+
isLocal: true
|
|
725
|
+
};
|
|
726
|
+
const localPaths = [
|
|
727
|
+
join$1(cwd, "Notes"),
|
|
728
|
+
join$1(cwd, "notes"),
|
|
729
|
+
join$1(cwd, ".claude", "Notes")
|
|
730
|
+
];
|
|
731
|
+
for (const path of localPaths) if (existsSync$1(path)) return {
|
|
732
|
+
path,
|
|
733
|
+
isLocal: true
|
|
734
|
+
};
|
|
735
|
+
return {
|
|
736
|
+
path: getNotesDir(cwd),
|
|
737
|
+
isLocal: false
|
|
738
|
+
};
|
|
739
|
+
}
|
|
740
|
+
/** Get the sessions/ directory from a project directory path. */
|
|
741
|
+
function getSessionsDirFromProjectDir(projectDir) {
|
|
742
|
+
return join$1(projectDir, "sessions");
|
|
743
|
+
}
|
|
744
|
+
/** Ensure the sessions/ directory exists (from project dir path). */
|
|
745
|
+
function ensureSessionsDirFromProjectDir(projectDir) {
|
|
746
|
+
const sessionsDir = getSessionsDirFromProjectDir(projectDir);
|
|
747
|
+
if (!existsSync$1(sessionsDir)) {
|
|
748
|
+
mkdirSync$1(sessionsDir, { recursive: true });
|
|
749
|
+
console.error(`Created sessions directory: ${sessionsDir}`);
|
|
750
|
+
}
|
|
751
|
+
return sessionsDir;
|
|
752
|
+
}
|
|
753
|
+
/**
|
|
754
|
+
* Publish every project-root .jsonl into sessions/ as well, WITHOUT removing it.
|
|
755
|
+
*
|
|
756
|
+
* This used to renameSync, and that is how PAI destroyed its users' sessions.
|
|
757
|
+
*
|
|
758
|
+
* `claude --resume <uuid>` finds a transcript only at the project root. Move it
|
|
759
|
+
* into sessions/ and the session becomes permanently unresumable — measured
|
|
760
|
+
* 2026-08-04: `claude --resume b3462801` (867 KB of real work, sessions/ only)
|
|
761
|
+
* answers "No conversation found with session ID", while a top-level id is found
|
|
762
|
+
* fine. Nothing warned; the id still looked valid everywhere PAI displayed it.
|
|
763
|
+
*
|
|
764
|
+
* The damage was not occasional. This ran from a UserPromptSubmit hook excluding
|
|
765
|
+
* only the CURRENT session, so every prompt anyone typed unresumed every other
|
|
766
|
+
* session in the project. One PAI project measured 1 transcript at top level
|
|
767
|
+
* against 52 underneath. Among the casualties was 046bb712 — the exact id PAI's
|
|
768
|
+
* own handover tells the user to resume.
|
|
769
|
+
*
|
|
770
|
+
* A hardlink satisfies both sides, which is why this is a two-line fix rather
|
|
771
|
+
* than a redesign: the archive genuinely has consumers that read sessions/
|
|
772
|
+
* (session-summary-worker, registry/moved, session/autosave), and `--resume`
|
|
773
|
+
* needs the root path. One inode, two names, no copy, no window where the file
|
|
774
|
+
* is missing from either place.
|
|
775
|
+
*
|
|
776
|
+
* Never unlink the source. Tidying up another tool's store was the whole
|
|
777
|
+
* mistake; a stale duplicate is free, a lost session is not. Every caller of
|
|
778
|
+
* `transcriptFiles()` was checked before choosing this — they all test emptiness
|
|
779
|
+
* (`.length > 0`), never count, so the duplicate cannot skew a project's stats.
|
|
780
|
+
*
|
|
781
|
+
* `excludeFile` keeps a hook from archiving the transcript it is itself watching
|
|
782
|
+
* being written. It is not a "finished sessions only" guard and must not be read
|
|
783
|
+
* as one: it excludes exactly one file, the caller's own, so with two sessions
|
|
784
|
+
* live in one project each still archives the other mid-turn. A consumer that
|
|
785
|
+
* needs "finished only" has to enforce that itself — this function cannot know
|
|
786
|
+
* what is live.
|
|
787
|
+
*
|
|
788
|
+
* Returns the number of files newly archived.
|
|
789
|
+
*/
|
|
790
|
+
function archiveSessionFilesToSessionsDir(projectDir, excludeFile, silent = false) {
|
|
791
|
+
const sessionsDir = ensureSessionsDirFromProjectDir(projectDir);
|
|
792
|
+
if (!existsSync$1(projectDir)) return 0;
|
|
793
|
+
const files = readdirSync$1(projectDir);
|
|
794
|
+
let archivedCount = 0;
|
|
795
|
+
for (const file of files) {
|
|
796
|
+
if (!file.endsWith(".jsonl") || file === excludeFile) continue;
|
|
797
|
+
const sourcePath = join$1(projectDir, file);
|
|
798
|
+
const destPath = join$1(sessionsDir, file);
|
|
799
|
+
if (existsSync$1(destPath)) continue;
|
|
800
|
+
try {
|
|
801
|
+
linkSync$1(sourcePath, destPath);
|
|
802
|
+
if (!silent) console.error(`Archived ${file} → sessions/ (still resumable)`);
|
|
803
|
+
archivedCount++;
|
|
804
|
+
} catch (error) {
|
|
805
|
+
try {
|
|
806
|
+
copyFileSync$1(sourcePath, destPath);
|
|
807
|
+
if (!silent) console.error(`Copied ${file} → sessions/ (hardlink unavailable)`);
|
|
808
|
+
archivedCount++;
|
|
809
|
+
} catch {
|
|
810
|
+
if (!silent) console.error(`Could not archive ${file}: ${error}`);
|
|
811
|
+
}
|
|
812
|
+
}
|
|
813
|
+
}
|
|
814
|
+
return archivedCount;
|
|
815
|
+
}
|
|
816
|
+
/** Find TODO.md — check local first, fallback to central. */
|
|
817
|
+
function findTodoPath(cwd) {
|
|
818
|
+
const localPaths = [
|
|
819
|
+
join$1(cwd, "TODO.md"),
|
|
820
|
+
join$1(cwd, "notes", "TODO.md"),
|
|
821
|
+
join$1(cwd, "Notes", "TODO.md"),
|
|
822
|
+
join$1(cwd, ".claude", "TODO.md")
|
|
823
|
+
];
|
|
824
|
+
for (const path of localPaths) if (existsSync$1(path)) return path;
|
|
825
|
+
return join$1(getNotesDir(cwd), "TODO.md");
|
|
826
|
+
}
|
|
827
|
+
|
|
828
|
+
//#endregion
|
|
829
|
+
//#region src/hooks/ts/lib/project-utils/session-notes.ts
|
|
830
|
+
/**
|
|
831
|
+
* Session note creation, editing, checkpointing, renaming, and finalization.
|
|
832
|
+
*/
|
|
833
|
+
/** Get or create the YYYY/MM subdirectory for the current month inside notesDir. */
|
|
834
|
+
function getMonthDir(notesDir) {
|
|
835
|
+
const now = /* @__PURE__ */ new Date();
|
|
836
|
+
const monthDir = join$1(notesDir, String(now.getFullYear()), String(now.getMonth() + 1).padStart(2, "0"));
|
|
837
|
+
if (!existsSync$1(monthDir)) mkdirSync$1(monthDir, { recursive: true });
|
|
838
|
+
return monthDir;
|
|
839
|
+
}
|
|
840
|
+
/**
|
|
841
|
+
* Get the next note number (4-digit format: 0001, 0002, etc.).
|
|
842
|
+
* Numbers are scoped per YYYY/MM directory.
|
|
843
|
+
*/
|
|
844
|
+
function getNextNoteNumber(notesDir) {
|
|
845
|
+
const files = readdirSync$1(getMonthDir(notesDir)).filter((f) => f.match(/^\d{3,4}[\s_-]/)).sort();
|
|
846
|
+
if (files.length === 0) return "0001";
|
|
847
|
+
let maxNumber = 0;
|
|
848
|
+
for (const file of files) {
|
|
849
|
+
const digitMatch = file.match(/^(\d+)/);
|
|
850
|
+
if (digitMatch) {
|
|
851
|
+
const num = parseInt(digitMatch[1], 10);
|
|
852
|
+
if (num > maxNumber) maxNumber = num;
|
|
853
|
+
}
|
|
854
|
+
}
|
|
855
|
+
return String(maxNumber + 1).padStart(4, "0");
|
|
856
|
+
}
|
|
857
|
+
/**
|
|
858
|
+
* Get the current (latest) note file path, or null if none exists.
|
|
859
|
+
* Searches current month → previous month → flat notesDir (legacy).
|
|
860
|
+
*/
|
|
861
|
+
function getCurrentNotePath(notesDir) {
|
|
862
|
+
if (!existsSync$1(notesDir)) return null;
|
|
863
|
+
const findLatestIn = (dir) => {
|
|
864
|
+
if (!existsSync$1(dir)) return null;
|
|
865
|
+
const files = readdirSync$1(dir).filter((f) => f.match(/^\d{3,4}[\s_-].*\.md$/)).sort((a, b) => {
|
|
866
|
+
return parseInt(a.match(/^(\d+)/)?.[1] || "0", 10) - parseInt(b.match(/^(\d+)/)?.[1] || "0", 10);
|
|
867
|
+
});
|
|
868
|
+
if (files.length === 0) return null;
|
|
869
|
+
return join$1(dir, files[files.length - 1]);
|
|
870
|
+
};
|
|
871
|
+
const now = /* @__PURE__ */ new Date();
|
|
872
|
+
const found = findLatestIn(join$1(notesDir, String(now.getFullYear()), String(now.getMonth() + 1).padStart(2, "0")));
|
|
873
|
+
if (found) return found;
|
|
874
|
+
const prevDate = new Date(now.getFullYear(), now.getMonth() - 1, 1);
|
|
875
|
+
const prevFound = findLatestIn(join$1(notesDir, String(prevDate.getFullYear()), String(prevDate.getMonth() + 1).padStart(2, "0")));
|
|
876
|
+
if (prevFound) return prevFound;
|
|
877
|
+
return findLatestIn(notesDir);
|
|
878
|
+
}
|
|
879
|
+
/**
|
|
880
|
+
* Create a new session note.
|
|
881
|
+
* Format: "NNNN - YYYY-MM-DD - New Session.md" filed into YYYY/MM subdirectory.
|
|
882
|
+
* Claude MUST rename at session end with a meaningful description.
|
|
883
|
+
*/
|
|
884
|
+
function createSessionNote(notesDir, description) {
|
|
885
|
+
const noteNumber = getNextNoteNumber(notesDir);
|
|
886
|
+
const date = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
|
|
887
|
+
const monthDir = getMonthDir(notesDir);
|
|
888
|
+
const filename = `${noteNumber} - ${date} - New Session.md`;
|
|
889
|
+
const filepath = join$1(monthDir, filename);
|
|
890
|
+
writeFileSync$1(filepath, `# Session ${noteNumber}: ${description}
|
|
891
|
+
|
|
892
|
+
**Date:** ${date}
|
|
893
|
+
**Status:** In Progress
|
|
894
|
+
|
|
895
|
+
---
|
|
896
|
+
|
|
897
|
+
## Work Done
|
|
898
|
+
|
|
899
|
+
<!-- PAI will add completed work here during session -->
|
|
900
|
+
|
|
901
|
+
---
|
|
902
|
+
|
|
903
|
+
## Next Steps
|
|
904
|
+
|
|
905
|
+
<!-- To be filled at session end -->
|
|
906
|
+
|
|
907
|
+
---
|
|
908
|
+
|
|
909
|
+
**Tags:** #Session
|
|
910
|
+
`);
|
|
911
|
+
console.error(`Created session note: ${filename}`);
|
|
912
|
+
return filepath;
|
|
913
|
+
}
|
|
914
|
+
/** Append a checkpoint to the current session note. */
|
|
915
|
+
function appendCheckpoint(notePath, checkpoint) {
|
|
916
|
+
if (!existsSync$1(notePath)) {
|
|
917
|
+
console.error(`Note file not found, recreating: ${notePath}`);
|
|
918
|
+
try {
|
|
919
|
+
const parentDir = join$1(notePath, "..");
|
|
920
|
+
if (!existsSync$1(parentDir)) mkdirSync$1(parentDir, { recursive: true });
|
|
921
|
+
const noteFilename = basename$1(notePath);
|
|
922
|
+
const numberMatch = noteFilename.match(/^(\d+)/);
|
|
923
|
+
writeFileSync$1(notePath, `# Session ${numberMatch ? numberMatch[1] : "0000"}: Recovered\n\n**Date:** ${(/* @__PURE__ */ new Date()).toISOString().split("T")[0]}\n**Status:** In Progress\n\n---\n\n## Work Done\n\n<!-- PAI will add completed work here during session -->\n\n---\n\n## Next Steps\n\n<!-- To be filled at session end -->\n\n---\n\n**Tags:** #Session\n`);
|
|
924
|
+
console.error(`Recreated session note: ${noteFilename}`);
|
|
925
|
+
} catch (err) {
|
|
926
|
+
console.error(`Failed to recreate note: ${err}`);
|
|
927
|
+
return;
|
|
928
|
+
}
|
|
929
|
+
}
|
|
930
|
+
const content = readFileSync$1(notePath, "utf-8");
|
|
931
|
+
const checkpointText = `\n### Checkpoint ${(/* @__PURE__ */ new Date()).toISOString()}\n\n${checkpoint}\n`;
|
|
932
|
+
const nextStepsIndex = content.indexOf("## Next Steps");
|
|
933
|
+
writeFileSync$1(notePath, nextStepsIndex !== -1 ? content.substring(0, nextStepsIndex) + checkpointText + content.substring(nextStepsIndex) : content + checkpointText);
|
|
934
|
+
console.error(`Checkpoint added to: ${basename$1(notePath)}`);
|
|
935
|
+
}
|
|
936
|
+
/** Add work items to the "Work Done" section of a session note. */
|
|
937
|
+
function addWorkToSessionNote(notePath, workItems, sectionTitle) {
|
|
938
|
+
if (!existsSync$1(notePath)) {
|
|
939
|
+
console.error(`Note file not found: ${notePath}`);
|
|
940
|
+
return;
|
|
941
|
+
}
|
|
942
|
+
let content = readFileSync$1(notePath, "utf-8");
|
|
943
|
+
let workText = "";
|
|
944
|
+
if (sectionTitle) workText += `\n### ${sectionTitle}\n\n`;
|
|
945
|
+
for (const item of workItems) {
|
|
946
|
+
const checkbox = item.completed !== false ? "[x]" : "[ ]";
|
|
947
|
+
workText += `- ${checkbox} **${item.title}**\n`;
|
|
948
|
+
if (item.details && item.details.length > 0) for (const detail of item.details) workText += ` - ${detail}\n`;
|
|
949
|
+
}
|
|
950
|
+
const workDoneMatch = content.match(/## Work Done\n\n(<!-- .*? -->)?/);
|
|
951
|
+
if (workDoneMatch) {
|
|
952
|
+
const insertPoint = content.indexOf(workDoneMatch[0]) + workDoneMatch[0].length;
|
|
953
|
+
content = content.substring(0, insertPoint) + workText + content.substring(insertPoint);
|
|
954
|
+
} else {
|
|
955
|
+
const nextStepsIndex = content.indexOf("## Next Steps");
|
|
956
|
+
if (nextStepsIndex !== -1) content = content.substring(0, nextStepsIndex) + workText + "\n" + content.substring(nextStepsIndex);
|
|
957
|
+
}
|
|
958
|
+
writeFileSync$1(notePath, content);
|
|
959
|
+
console.error(`Added ${workItems.length} work item(s) to: ${basename$1(notePath)}`);
|
|
960
|
+
}
|
|
961
|
+
/** Sanitize a string for use in a filename. */
|
|
962
|
+
function sanitizeForFilename(str) {
|
|
963
|
+
return str.toLowerCase().replace(/[^a-z0-9\s-]/g, "").replace(/\s+/g, "-").replace(/-+/g, "-").replace(/^-|-$/g, "").substring(0, 50);
|
|
964
|
+
}
|
|
965
|
+
/**
|
|
966
|
+
* Return true if the candidate string should be rejected as a meaningful name.
|
|
967
|
+
* Rejects file paths, shebangs, timestamps, system noise, XML tags, hashes, etc.
|
|
968
|
+
*/
|
|
969
|
+
function isMeaninglessCandidate(text) {
|
|
970
|
+
const t = text.trim();
|
|
971
|
+
if (!t) return true;
|
|
972
|
+
if (t.length < 5) return true;
|
|
973
|
+
if (t.startsWith("/") || t.startsWith("~")) return true;
|
|
974
|
+
if (t.startsWith("#!")) return true;
|
|
975
|
+
if (t.includes("[object Object]")) return true;
|
|
976
|
+
if (/^\d{4}-\d{2}-\d{2}(T[\d:.Z+-]+)?$/.test(t)) return true;
|
|
977
|
+
if (/^\d{1,2}:\d{2}(:\d{2})?(\s*(AM|PM))?$/i.test(t)) return true;
|
|
978
|
+
if (/^<[a-z-]+[\s/>]/i.test(t)) return true;
|
|
979
|
+
if (/^[0-9a-f]{10,}$/i.test(t)) return true;
|
|
980
|
+
if (/^Exit code \d+/i.test(t)) return true;
|
|
981
|
+
if (/^Error:/i.test(t)) return true;
|
|
982
|
+
if (/^This session is being continued/i.test(t)) return true;
|
|
983
|
+
if (/^\(Bash completed/i.test(t)) return true;
|
|
984
|
+
if (/^Task Notification$/i.test(t)) return true;
|
|
985
|
+
if (/^New Session$/i.test(t)) return true;
|
|
986
|
+
if (/^Recovered Session$/i.test(t)) return true;
|
|
987
|
+
if (/^Continued Session$/i.test(t)) return true;
|
|
988
|
+
if (/^Untitled Session$/i.test(t)) return true;
|
|
989
|
+
if (/^Context Compression$/i.test(t)) return true;
|
|
990
|
+
if (/^[A-Fa-f0-9]{8,}\s+Output$/i.test(t)) return true;
|
|
991
|
+
return false;
|
|
992
|
+
}
|
|
993
|
+
/**
|
|
994
|
+
* Extract a meaningful name from session note content and summary.
|
|
995
|
+
* Looks at Work Done section headers, bold text, and summary.
|
|
996
|
+
*/
|
|
997
|
+
function extractMeaningfulName(noteContent, summary) {
|
|
998
|
+
const workDoneMatch = noteContent.match(/## Work Done\n\n([\s\S]*?)(?=\n---|\n## Next)/);
|
|
999
|
+
if (workDoneMatch) {
|
|
1000
|
+
const workDoneSection = workDoneMatch[1];
|
|
1001
|
+
const subheadings = workDoneSection.match(/### ([^\n]+)/g);
|
|
1002
|
+
if (subheadings && subheadings.length > 0) {
|
|
1003
|
+
const firstHeading = subheadings[0].replace("### ", "").trim();
|
|
1004
|
+
if (!isMeaninglessCandidate(firstHeading) && firstHeading.length > 5 && firstHeading.length < 60) return sanitizeForFilename(firstHeading);
|
|
1005
|
+
}
|
|
1006
|
+
const boldMatches = workDoneSection.match(/\*\*([^*]+)\*\*/g);
|
|
1007
|
+
if (boldMatches && boldMatches.length > 0) {
|
|
1008
|
+
const firstBold = boldMatches[0].replace(/\*\*/g, "").trim();
|
|
1009
|
+
if (!isMeaninglessCandidate(firstBold) && firstBold.length > 3 && firstBold.length < 50) return sanitizeForFilename(firstBold);
|
|
1010
|
+
}
|
|
1011
|
+
const numberedItems = workDoneSection.match(/^\d+\.\s+\*\*([^*]+)\*\*/m);
|
|
1012
|
+
if (numberedItems && !isMeaninglessCandidate(numberedItems[1])) return sanitizeForFilename(numberedItems[1]);
|
|
1013
|
+
}
|
|
1014
|
+
if (summary && summary.length > 5 && summary !== "Session completed." && !isMeaninglessCandidate(summary)) {
|
|
1015
|
+
const cleanSummary = summary.replace(/[^\w\s-]/g, " ").trim().split(/\s+/).slice(0, 5).join(" ");
|
|
1016
|
+
if (cleanSummary.length > 3 && !isMeaninglessCandidate(cleanSummary)) return sanitizeForFilename(cleanSummary);
|
|
1017
|
+
}
|
|
1018
|
+
return "";
|
|
1019
|
+
}
|
|
1020
|
+
/**
|
|
1021
|
+
* Rename a session note with a meaningful name.
|
|
1022
|
+
* Always uses "NNNN - YYYY-MM-DD - Description.md" format.
|
|
1023
|
+
* Returns the new path, or original path if rename fails.
|
|
1024
|
+
*/
|
|
1025
|
+
function renameSessionNote(notePath, meaningfulName) {
|
|
1026
|
+
if (!meaningfulName || !existsSync$1(notePath)) return notePath;
|
|
1027
|
+
const dir = join$1(notePath, "..");
|
|
1028
|
+
const oldFilename = basename$1(notePath);
|
|
1029
|
+
const correctMatch = oldFilename.match(/^(\d{3,4}) - (\d{4}-\d{2}-\d{2}) - .*\.md$/);
|
|
1030
|
+
const legacyMatch = oldFilename.match(/^(\d{3,4})_(\d{4}-\d{2}-\d{2})_.*\.md$/);
|
|
1031
|
+
const match = correctMatch || legacyMatch;
|
|
1032
|
+
if (!match) return notePath;
|
|
1033
|
+
const [, noteNumber, date] = match;
|
|
1034
|
+
const titleCaseName = meaningfulName.split(/[\s_-]+/).map((word) => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase()).join(" ").trim();
|
|
1035
|
+
const newFilename = `${noteNumber.padStart(4, "0")} - ${date} - ${titleCaseName}.md`;
|
|
1036
|
+
const newPath = join$1(dir, newFilename);
|
|
1037
|
+
if (newFilename === oldFilename) return notePath;
|
|
1038
|
+
try {
|
|
1039
|
+
renameSync$1(notePath, newPath);
|
|
1040
|
+
console.error(`Renamed note: ${oldFilename} → ${newFilename}`);
|
|
1041
|
+
return newPath;
|
|
1042
|
+
} catch (error) {
|
|
1043
|
+
console.error(`Could not rename note: ${error}`);
|
|
1044
|
+
return notePath;
|
|
1045
|
+
}
|
|
1046
|
+
}
|
|
1047
|
+
/**
|
|
1048
|
+
* Finalize session note — mark as complete, add summary, rename with meaningful name.
|
|
1049
|
+
* IDEMPOTENT: subsequent calls are no-ops if already finalized.
|
|
1050
|
+
* Returns the final path (may be renamed).
|
|
1051
|
+
*/
|
|
1052
|
+
function finalizeSessionNote(notePath, summary) {
|
|
1053
|
+
if (!existsSync$1(notePath)) {
|
|
1054
|
+
console.error(`Note file not found: ${notePath}`);
|
|
1055
|
+
return notePath;
|
|
1056
|
+
}
|
|
1057
|
+
let content = readFileSync$1(notePath, "utf-8");
|
|
1058
|
+
if (content.includes("**Status:** Completed")) {
|
|
1059
|
+
console.error(`Note already finalized: ${basename$1(notePath)}`);
|
|
1060
|
+
return notePath;
|
|
1061
|
+
}
|
|
1062
|
+
content = content.replace("**Status:** In Progress", "**Status:** Completed");
|
|
1063
|
+
if (!content.includes("**Completed:**")) {
|
|
1064
|
+
const completionTime = (/* @__PURE__ */ new Date()).toISOString();
|
|
1065
|
+
content = content.replace("---\n\n## Work Done", `**Completed:** ${completionTime}\n\n---\n\n## Work Done`);
|
|
1066
|
+
}
|
|
1067
|
+
const nextStepsMatch = content.match(/## Next Steps\n\n(<!-- .*? -->)/);
|
|
1068
|
+
if (nextStepsMatch) content = content.replace(nextStepsMatch[0], `## Next Steps\n\n${summary || "Session completed."}`);
|
|
1069
|
+
writeFileSync$1(notePath, content);
|
|
1070
|
+
console.error(`Session note finalized: ${basename$1(notePath)}`);
|
|
1071
|
+
const meaningfulName = extractMeaningfulName(content, summary);
|
|
1072
|
+
if (meaningfulName) return renameSessionNote(notePath, meaningfulName);
|
|
1073
|
+
return notePath;
|
|
1074
|
+
}
|
|
1075
|
+
|
|
1076
|
+
//#endregion
|
|
1077
|
+
//#region src/session/checkpoint-block.ts
|
|
1078
|
+
/**
|
|
1079
|
+
* Shared "## Continue" checkpoint logic for a project's TODO.md.
|
|
1080
|
+
*
|
|
1081
|
+
* WHY THIS MODULE EXISTS
|
|
1082
|
+
* ----------------------
|
|
1083
|
+
* Before this, `pause.ts` and `handover.ts` each carried their own copy of
|
|
1084
|
+
* findProjectTodo / stripContinueSection / block-builder. Both wrote the same
|
|
1085
|
+
* fixed four-line block, and both stripped any existing ## Continue section
|
|
1086
|
+
* unconditionally. The consequence was that a rich, model-authored checkpoint
|
|
1087
|
+
* could never survive:
|
|
1088
|
+
*
|
|
1089
|
+
* 1. `pai pause` had no way to accept a body, so the model printed its
|
|
1090
|
+
* checkpoint to the terminal and it was lost.
|
|
1091
|
+
* 2. Even if a body had been written by hand, the session-stop hook runs
|
|
1092
|
+
* `pai session handover` on every clean exit, which regenerated the
|
|
1093
|
+
* generic block and erased it.
|
|
1094
|
+
*
|
|
1095
|
+
* So there are two jobs here:
|
|
1096
|
+
*
|
|
1097
|
+
* - AUTHORED writes (`pai pause --body-file`) carry the model's markdown
|
|
1098
|
+
* verbatim, wrapped in explicit start/end markers.
|
|
1099
|
+
* - AUTO writes (hooks) must never destroy an authored checkpoint belonging
|
|
1100
|
+
* to the *same* session. They may replace a stale one left by an earlier
|
|
1101
|
+
* session, otherwise TODO.md would show a checkpoint that no longer
|
|
1102
|
+
* describes where the work stands.
|
|
1103
|
+
*
|
|
1104
|
+
* PARSING
|
|
1105
|
+
* -------
|
|
1106
|
+
* A rich body can legitimately contain `---` rules and `##` headings, which the
|
|
1107
|
+
* old heuristic scanner treated as section terminators. Authored blocks are
|
|
1108
|
+
* therefore delimited by an explicit HTML-comment pair; the legacy heuristic is
|
|
1109
|
+
* kept only as a fallback for blocks written before this change.
|
|
1110
|
+
*/
|
|
1111
|
+
/** Locations searched for a project TODO.md, in priority order. */
|
|
1112
|
+
const TODO_LOCATIONS = [
|
|
1113
|
+
"Notes/TODO.md",
|
|
1114
|
+
".claude/Notes/TODO.md",
|
|
1115
|
+
"tasks/todo.md",
|
|
1116
|
+
"TODO.md"
|
|
1117
|
+
];
|
|
1118
|
+
const MARKER_OPEN = "<!-- pai:checkpoint";
|
|
1119
|
+
const MARKER_CLOSE = "<!-- /pai:checkpoint -->";
|
|
1120
|
+
/**
|
|
1121
|
+
* Markers for a handover that has been superseded but not thrown away.
|
|
1122
|
+
*
|
|
1123
|
+
* Deliberately NOT `pai:checkpoint`: `locateContinue` scans for that marker and
|
|
1124
|
+
* for the `## Continue` heading, so an archived block written verbatim would be
|
|
1125
|
+
* found as the live section and rewritten in place of it. Archived entries are
|
|
1126
|
+
* inert by construction — different marker, no heading.
|
|
1127
|
+
*/
|
|
1128
|
+
const ARCHIVE_OPEN = "<!-- pai:archived-handover";
|
|
1129
|
+
const ARCHIVE_CLOSE = "<!-- /pai:archived-handover -->";
|
|
1130
|
+
const ARCHIVE_HEADING = "## Previous handovers";
|
|
1131
|
+
/**
|
|
1132
|
+
* How many superseded handovers TODO.md keeps.
|
|
1133
|
+
*
|
|
1134
|
+
* Enough that a handover survives a run of sessions that each end without
|
|
1135
|
+
* pausing, which is the sequence that destroyed one on 2026-08-04. Not
|
|
1136
|
+
* unbounded: TODO.md is read by a human at the top of every session, and a file
|
|
1137
|
+
* that grows without limit stops being read, which is its own kind of loss.
|
|
1138
|
+
*/
|
|
1139
|
+
const ARCHIVE_LIMIT = 5;
|
|
1140
|
+
const CONTINUE_HEADING = "## Continue";
|
|
1141
|
+
function findProjectTodo(rootPath) {
|
|
1142
|
+
for (const rel of TODO_LOCATIONS) {
|
|
1143
|
+
const full = join(rootPath, rel);
|
|
1144
|
+
if (existsSync(full)) try {
|
|
1145
|
+
return {
|
|
1146
|
+
path: full,
|
|
1147
|
+
content: readFileSync(full, "utf8")
|
|
1148
|
+
};
|
|
1149
|
+
} catch {}
|
|
1150
|
+
}
|
|
1151
|
+
return null;
|
|
1152
|
+
}
|
|
1153
|
+
/**
|
|
1154
|
+
* Resolve the TODO.md to write to, creating Notes/ if nothing exists yet.
|
|
1155
|
+
* Returns null only when the directory could not be created.
|
|
1156
|
+
*/
|
|
1157
|
+
function resolveTodoTarget(rootPath, opts = {}) {
|
|
1158
|
+
const found = findProjectTodo(rootPath);
|
|
1159
|
+
if (found) return found;
|
|
1160
|
+
const notesDir = join(rootPath, "Notes");
|
|
1161
|
+
if (opts.create !== false) try {
|
|
1162
|
+
if (!existsSync(notesDir)) mkdirSync(notesDir, { recursive: true });
|
|
1163
|
+
} catch {
|
|
1164
|
+
return null;
|
|
1165
|
+
}
|
|
1166
|
+
return {
|
|
1167
|
+
path: join(notesDir, "TODO.md"),
|
|
1168
|
+
content: ""
|
|
1169
|
+
};
|
|
1170
|
+
}
|
|
1171
|
+
/**
|
|
1172
|
+
* Parse a `<!-- pai:checkpoint key="value" ... -->` marker line.
|
|
1173
|
+
* Returns null when the line is not a marker.
|
|
1174
|
+
*/
|
|
1175
|
+
function parseMarker(line) {
|
|
1176
|
+
const trimmed = line.trim();
|
|
1177
|
+
if (!trimmed.startsWith(MARKER_OPEN)) return null;
|
|
1178
|
+
const attrs = {};
|
|
1179
|
+
for (const m of trimmed.matchAll(/([a-zA-Z][\w-]*)="([^"]*)"/g)) attrs[m[1]] = m[2];
|
|
1180
|
+
return {
|
|
1181
|
+
authored: attrs.authored === "model" ? "model" : "auto",
|
|
1182
|
+
session: attrs.session || void 0,
|
|
1183
|
+
sessionId: attrs["session-id"] || void 0,
|
|
1184
|
+
ts: attrs.ts || void 0
|
|
1185
|
+
};
|
|
1186
|
+
}
|
|
1187
|
+
/**
|
|
1188
|
+
* Lines an auto-generated block is made of. Anything else in a section is
|
|
1189
|
+
* content somebody put there deliberately.
|
|
1190
|
+
*
|
|
1191
|
+
* The blockquote marker is optional on every pattern. These lines appear
|
|
1192
|
+
* quoted when the block builder emits them as its header, and unquoted when a
|
|
1193
|
+
* caller passes the same text as a BODY — which the session-stop hook does: it
|
|
1194
|
+
* builds `Working directory: ${cwd}` and hands it over as state. Matching only
|
|
1195
|
+
* the quoted form made such a body read as content, which is how a session
|
|
1196
|
+
* that did no work at all overwrote a real handover on 2026-08-04. A line that
|
|
1197
|
+
* merely restates the generated header is boilerplate wherever it sits.
|
|
1198
|
+
*/
|
|
1199
|
+
const BOILERPLATE_PATTERNS = [
|
|
1200
|
+
/^##\s+Continue$/,
|
|
1201
|
+
/^<!--\s*\/?pai:checkpoint/,
|
|
1202
|
+
/^>?\s*\*\*Last session:\*\*/,
|
|
1203
|
+
/^>?\s*\*\*Paused at:\*\*/,
|
|
1204
|
+
/^>?\s*Working directory:/,
|
|
1205
|
+
/^>?\s*Resume with:/,
|
|
1206
|
+
/^>?\s*_No checkpoint body was recorded/,
|
|
1207
|
+
/^-{3,}$/
|
|
1208
|
+
];
|
|
1209
|
+
/** A blank line, with or without a blockquote marker. */
|
|
1210
|
+
const BLANK_LINE = /^>?\s*$/;
|
|
1211
|
+
/**
|
|
1212
|
+
* True when a section contains nothing but generated header lines.
|
|
1213
|
+
*
|
|
1214
|
+
* This is the guard that stops an auto write from destroying content it did
|
|
1215
|
+
* not author. A session that hit the old clobbering bug may have worked around
|
|
1216
|
+
* it by hand — writing its state into a subsection underneath the generated
|
|
1217
|
+
* header lines, in an unmarked block. Those blocks predate the marker, so
|
|
1218
|
+
* authorship cannot be read off them; the only safe signal is whether anything
|
|
1219
|
+
* beyond boilerplate is present.
|
|
1220
|
+
*/
|
|
1221
|
+
function isBoilerplateOnly(lines) {
|
|
1222
|
+
return lines.every((line) => {
|
|
1223
|
+
const t = line.trim();
|
|
1224
|
+
return BLANK_LINE.test(t) || BOILERPLATE_PATTERNS.some((re) => re.test(t));
|
|
1225
|
+
});
|
|
1226
|
+
}
|
|
1227
|
+
/**
|
|
1228
|
+
* True when a checkpoint body says something the generated header does not.
|
|
1229
|
+
*
|
|
1230
|
+
* "Has a body" and "has something to say" are not the same question, and the
|
|
1231
|
+
* preservation rules care only about the second. An unattended writer that
|
|
1232
|
+
* emits a single line restating the working directory has produced a body by
|
|
1233
|
+
* any string test and a handover by none.
|
|
1234
|
+
*/
|
|
1235
|
+
function hasSubstance(body) {
|
|
1236
|
+
const text = (body ?? "").trim();
|
|
1237
|
+
if (!text) return false;
|
|
1238
|
+
return !isBoilerplateOnly(text.split("\n"));
|
|
1239
|
+
}
|
|
1240
|
+
/**
|
|
1241
|
+
* Extract the non-boilerplate content of a section, or "" if there is none.
|
|
1242
|
+
*
|
|
1243
|
+
* Interior blank lines are kept. They are not decoration — in Markdown they
|
|
1244
|
+
* are what separates a paragraph from the table or list that follows, so
|
|
1245
|
+
* dropping them (as this did while it treated every blank line as boilerplate)
|
|
1246
|
+
* silently welds a checkpoint body into one unreadable run.
|
|
1247
|
+
*/
|
|
1248
|
+
function extractSectionContent(lines) {
|
|
1249
|
+
const kept = [];
|
|
1250
|
+
for (const line of lines) {
|
|
1251
|
+
const t = line.trim();
|
|
1252
|
+
if (BOILERPLATE_PATTERNS.some((re) => re.test(t))) continue;
|
|
1253
|
+
kept.push(line);
|
|
1254
|
+
}
|
|
1255
|
+
return trimBlankEdges(collapseBlankRuns(kept)).join("\n");
|
|
1256
|
+
}
|
|
1257
|
+
/** Drop leading and trailing blank lines, leaving interior spacing alone. */
|
|
1258
|
+
function trimBlankEdges(lines) {
|
|
1259
|
+
let start = 0;
|
|
1260
|
+
let end = lines.length;
|
|
1261
|
+
while (start < end && BLANK_LINE.test(lines[start].trim())) start += 1;
|
|
1262
|
+
while (end > start && BLANK_LINE.test(lines[end - 1].trim())) end -= 1;
|
|
1263
|
+
return lines.slice(start, end);
|
|
1264
|
+
}
|
|
1265
|
+
/**
|
|
1266
|
+
* Collapse runs of blank lines to a single blank.
|
|
1267
|
+
*
|
|
1268
|
+
* Removing a boilerplate line leaves the blank that surrounded it behind, so
|
|
1269
|
+
* stripping the header can open a three-line gap in the middle of the body.
|
|
1270
|
+
* One blank line is all Markdown needs.
|
|
1271
|
+
*/
|
|
1272
|
+
function collapseBlankRuns(lines) {
|
|
1273
|
+
const out = [];
|
|
1274
|
+
let lastWasBlank = false;
|
|
1275
|
+
for (const line of lines) {
|
|
1276
|
+
const isBlank = BLANK_LINE.test(line.trim());
|
|
1277
|
+
if (isBlank && lastWasBlank) continue;
|
|
1278
|
+
out.push(line);
|
|
1279
|
+
lastWasBlank = isBlank;
|
|
1280
|
+
}
|
|
1281
|
+
return out;
|
|
1282
|
+
}
|
|
1283
|
+
/**
|
|
1284
|
+
* Locate the existing ## Continue section.
|
|
1285
|
+
*
|
|
1286
|
+
* When the section carries an explicit marker pair, the close marker defines
|
|
1287
|
+
* the end — this is what lets a rich body contain `---` and `##` safely.
|
|
1288
|
+
* Otherwise the legacy heuristic applies: stop at the first `---` or the next
|
|
1289
|
+
* `##` heading.
|
|
1290
|
+
*/
|
|
1291
|
+
function locateContinue(content) {
|
|
1292
|
+
const lines = content.split("\n");
|
|
1293
|
+
const startIdx = lines.findIndex((l) => l.trim() === CONTINUE_HEADING);
|
|
1294
|
+
if (startIdx === -1) return null;
|
|
1295
|
+
let meta = null;
|
|
1296
|
+
let markerIdx = -1;
|
|
1297
|
+
for (let i = startIdx + 1; i < Math.min(startIdx + 6, lines.length); i++) {
|
|
1298
|
+
const parsed = parseMarker(lines[i]);
|
|
1299
|
+
if (parsed) {
|
|
1300
|
+
meta = parsed;
|
|
1301
|
+
markerIdx = i;
|
|
1302
|
+
break;
|
|
1303
|
+
}
|
|
1304
|
+
if (lines[i].trim() !== "") break;
|
|
1305
|
+
}
|
|
1306
|
+
let endIdx = lines.length;
|
|
1307
|
+
if (markerIdx !== -1) {
|
|
1308
|
+
const closeIdx = lines.findIndex((l, i) => i > markerIdx && l.trim() === MARKER_CLOSE);
|
|
1309
|
+
if (closeIdx !== -1) endIdx = closeIdx + 1;
|
|
1310
|
+
else endIdx = heuristicEnd(lines, startIdx);
|
|
1311
|
+
} else endIdx = heuristicEnd(lines, startIdx);
|
|
1312
|
+
let trailingEnd = endIdx;
|
|
1313
|
+
while (trailingEnd < lines.length && lines[trailingEnd].trim() === "") trailingEnd += 1;
|
|
1314
|
+
if (trailingEnd < lines.length && lines[trailingEnd].trim() === "---") trailingEnd += 1;
|
|
1315
|
+
else trailingEnd = endIdx;
|
|
1316
|
+
return {
|
|
1317
|
+
startIdx,
|
|
1318
|
+
endIdx: trailingEnd,
|
|
1319
|
+
meta,
|
|
1320
|
+
lines: lines.slice(startIdx, trailingEnd)
|
|
1321
|
+
};
|
|
1322
|
+
}
|
|
1323
|
+
/**
|
|
1324
|
+
* Legacy scanner for blocks written before checkpoint markers existed.
|
|
1325
|
+
*
|
|
1326
|
+
* Terminates on a horizontal rule or the next level-1 or level-2 heading. Note
|
|
1327
|
+
* the `(?!#)` — `###` is a *subsection* of `## Continue`, not a terminator. The
|
|
1328
|
+
* original scanner stopped at any run of `#`, which meant a `### Restored
|
|
1329
|
+
* state` subsection fell outside the section entirely and could not be seen,
|
|
1330
|
+
* let alone carried forward.
|
|
1331
|
+
*
|
|
1332
|
+
* `#{1,2}` rather than `##`, because matching only `##` did not stop at an H1
|
|
1333
|
+
* and therefore ATE IT. A TODO.md whose `## Continue` block precedes its
|
|
1334
|
+
* `# TODO` title had the title absorbed into the section and destroyed on the
|
|
1335
|
+
* next regenerate — reported independently by three sessions on 2026-08-03,
|
|
1336
|
+
* one of which lost it three times and recovered from git each time.
|
|
1337
|
+
*
|
|
1338
|
+
* An H1 is a document-level heading. It can never be part of a `## Continue`
|
|
1339
|
+
* section, so treating it as a terminator is not a heuristic improvement but a
|
|
1340
|
+
* structural fact.
|
|
1341
|
+
*/
|
|
1342
|
+
function heuristicEnd(lines, startIdx) {
|
|
1343
|
+
for (let i = startIdx + 1; i < lines.length; i++) {
|
|
1344
|
+
const trimmed = lines[i].trim();
|
|
1345
|
+
if (trimmed === "---" || /^#{1,2}(?!#)/.test(trimmed) && trimmed !== CONTINUE_HEADING) return i;
|
|
1346
|
+
}
|
|
1347
|
+
return lines.length;
|
|
1348
|
+
}
|
|
1349
|
+
/** Remove the ## Continue section, returning the remainder of the document. */
|
|
1350
|
+
function stripContinue(content) {
|
|
1351
|
+
const found = locateContinue(content);
|
|
1352
|
+
if (!found) return content;
|
|
1353
|
+
const lines = content.split("\n");
|
|
1354
|
+
const before = lines.slice(0, found.startIdx);
|
|
1355
|
+
const after = lines.slice(found.endIdx);
|
|
1356
|
+
while (after.length > 0 && after[0].trim() === "") after.shift();
|
|
1357
|
+
return [...before, ...after].join("\n");
|
|
1358
|
+
}
|
|
1359
|
+
function escapeAttr(value) {
|
|
1360
|
+
return value.replace(/"/g, "'");
|
|
1361
|
+
}
|
|
1362
|
+
function buildContinueBlock(opts) {
|
|
1363
|
+
const ts = opts.timestamp ?? (/* @__PURE__ */ new Date()).toISOString();
|
|
1364
|
+
const attrs = [
|
|
1365
|
+
`authored="${opts.authored}"`,
|
|
1366
|
+
`session="${escapeAttr(opts.sessionLine)}"`,
|
|
1367
|
+
opts.sessionId ? `session-id="${escapeAttr(opts.sessionId)}"` : null,
|
|
1368
|
+
`ts="${ts}"`
|
|
1369
|
+
].filter(Boolean).join(" ");
|
|
1370
|
+
const header = [
|
|
1371
|
+
`> **Last session:** ${opts.sessionLine}`,
|
|
1372
|
+
`> **Paused at:** ${ts}`,
|
|
1373
|
+
">",
|
|
1374
|
+
`> Working directory: ${opts.cwd}`
|
|
1375
|
+
];
|
|
1376
|
+
if (opts.sessionId) header.push(">", `> Resume with: \`claude --resume ${opts.sessionId}\``);
|
|
1377
|
+
const body = (opts.body ?? "").trim();
|
|
1378
|
+
const parts = [
|
|
1379
|
+
CONTINUE_HEADING,
|
|
1380
|
+
"",
|
|
1381
|
+
`${MARKER_OPEN} ${attrs} -->`,
|
|
1382
|
+
"",
|
|
1383
|
+
...header
|
|
1384
|
+
];
|
|
1385
|
+
if (body) parts.push("", body);
|
|
1386
|
+
else parts.push(">", "> _No checkpoint body was recorded — see the latest session note._");
|
|
1387
|
+
parts.push("", MARKER_CLOSE, "", "---", "");
|
|
1388
|
+
return parts.join("\n");
|
|
1389
|
+
}
|
|
1390
|
+
/**
|
|
1391
|
+
* Write the ## Continue block, honouring the preservation rules.
|
|
1392
|
+
*
|
|
1393
|
+
* An AUTO write is unattended — it fires from the session-stop and pre-compact
|
|
1394
|
+
* hooks — so it operates under one governing rule: **never destroy content it
|
|
1395
|
+
* did not author.** Three cases follow from that:
|
|
1396
|
+
*
|
|
1397
|
+
* 1. An authored checkpoint for the SAME session is left untouched. The hooks
|
|
1398
|
+
* fire after the model has already recorded the real state; overwriting it
|
|
1399
|
+
* with metadata is the bug this module exists to fix.
|
|
1400
|
+
*
|
|
1401
|
+
* "Same session" is decided by the Claude session UUID whenever both sides
|
|
1402
|
+
* know it, and only falls back to the human-readable session line when one
|
|
1403
|
+
* of them does not. The line is derived from the session note filename,
|
|
1404
|
+
* and `session-stop.sh` *renames and renumbers that file* — via `session
|
|
1405
|
+
* slug --apply` and `session cleanup --execute` — before it reaches the
|
|
1406
|
+
* handover step. So the key the hook computes at exit is not the key the
|
|
1407
|
+
* model wrote seconds earlier, and a filename-keyed comparison mismatches
|
|
1408
|
+
* by construction. Observed live on 2026-08-01: notes renumbered twice
|
|
1409
|
+
* within a single session. The UUID is the only identifier that holds
|
|
1410
|
+
* still.
|
|
1411
|
+
* 2. An authored checkpoint from an EARLIER session is stale — TODO.md would
|
|
1412
|
+
* otherwise keep pointing at the wrong session — so it is replaced. Its
|
|
1413
|
+
* content is not lost: `pai pause` mirrors every authored body into the
|
|
1414
|
+
* session note.
|
|
1415
|
+
* 3. An UNMARKED block predates the marker, so authorship cannot be read off
|
|
1416
|
+
* it. If it is nothing but generated header lines it is replaced. If it
|
|
1417
|
+
* carries anything else, that content was put there deliberately — quite
|
|
1418
|
+
* possibly as a hand-rolled workaround for the very clobbering this fixes —
|
|
1419
|
+
* and is carried forward into the new block rather than dropped.
|
|
1420
|
+
*
|
|
1421
|
+
* A MODEL write always replaces: the model is authoring the checkpoint, and a
|
|
1422
|
+
* newer one supersedes an older one.
|
|
1423
|
+
*/
|
|
1424
|
+
/**
|
|
1425
|
+
* Do an existing checkpoint and an incoming write describe the same session?
|
|
1426
|
+
*
|
|
1427
|
+
* The UUID is authoritative when both sides carry one: it is assigned by Claude
|
|
1428
|
+
* Code and never changes for the life of the session. The session line is a
|
|
1429
|
+
* derived, mutable label and is only consulted when there is no UUID to compare
|
|
1430
|
+
* — a checkpoint written before `--session-id` was threaded through, or an auto
|
|
1431
|
+
* write from a caller that was not given one.
|
|
1432
|
+
*/
|
|
1433
|
+
function isSameSession(meta, opts) {
|
|
1434
|
+
if (meta.sessionId && opts.sessionId) return meta.sessionId === opts.sessionId;
|
|
1435
|
+
return meta.session === opts.sessionLine;
|
|
1436
|
+
}
|
|
1437
|
+
/**
|
|
1438
|
+
* How long a model-authored checkpoint is protected from automated overwriting.
|
|
1439
|
+
*
|
|
1440
|
+
* Sized for the race, not for the session: the gap between a model writing its
|
|
1441
|
+
* checkpoint and a hook firing is seconds to minutes, and an hour covers even a
|
|
1442
|
+
* slow checkpoint on a loaded machine. Anything genuinely from an earlier
|
|
1443
|
+
* session is hours or days old and still falls through to case 2, which is what
|
|
1444
|
+
* keeps TODO.md from freezing on a checkpoint nobody will ever replace.
|
|
1445
|
+
*/
|
|
1446
|
+
const AUTHORED_GRACE_MS = 3600 * 1e3;
|
|
1447
|
+
/** Was this checkpoint written recently enough to still belong to the run in progress? */
|
|
1448
|
+
function isRecent(meta, now) {
|
|
1449
|
+
if (!meta.ts) return false;
|
|
1450
|
+
const then = Date.parse(meta.ts);
|
|
1451
|
+
if (Number.isNaN(then)) return false;
|
|
1452
|
+
const nowMs = now ? Date.parse(now) : Date.now();
|
|
1453
|
+
if (Number.isNaN(nowMs)) return false;
|
|
1454
|
+
return nowMs - then < AUTHORED_GRACE_MS;
|
|
1455
|
+
}
|
|
1456
|
+
/**
|
|
1457
|
+
* Turn a live checkpoint block into an inert archive entry.
|
|
1458
|
+
*
|
|
1459
|
+
* Two things have to go: the `## Continue` heading and the `pai:checkpoint`
|
|
1460
|
+
* marker. Both are what `locateContinue` looks for, so leaving either in place
|
|
1461
|
+
* would let a later write treat the archive as the live section — and the next
|
|
1462
|
+
* one after that would then archive the archive. Everything else is kept
|
|
1463
|
+
* verbatim, because the body is the whole reason this exists.
|
|
1464
|
+
*/
|
|
1465
|
+
function toArchiveEntry(lines, meta) {
|
|
1466
|
+
const out = [];
|
|
1467
|
+
const label = meta?.session ?? "Unknown session";
|
|
1468
|
+
const stamp = meta?.ts ? ` — checkpointed ${meta.ts}` : "";
|
|
1469
|
+
out.push(`${ARCHIVE_OPEN} session="${label}"${meta?.ts ? ` ts="${meta.ts}"` : ""} -->`);
|
|
1470
|
+
out.push("");
|
|
1471
|
+
out.push(`### ${label}${stamp}`);
|
|
1472
|
+
out.push("");
|
|
1473
|
+
for (const line of lines) {
|
|
1474
|
+
if (line.trim() === CONTINUE_HEADING) continue;
|
|
1475
|
+
if (line.trim().startsWith(MARKER_OPEN)) continue;
|
|
1476
|
+
if (line.trim() === MARKER_CLOSE) continue;
|
|
1477
|
+
if (line.trim() === "---") continue;
|
|
1478
|
+
out.push(line);
|
|
1479
|
+
}
|
|
1480
|
+
while (out.length > 0 && out[out.length - 1].trim() === "") out.pop();
|
|
1481
|
+
out.push("");
|
|
1482
|
+
out.push(ARCHIVE_CLOSE);
|
|
1483
|
+
return out;
|
|
1484
|
+
}
|
|
1485
|
+
/**
|
|
1486
|
+
* Put a superseded handover into the archive section, newest first.
|
|
1487
|
+
*
|
|
1488
|
+
* `rest` is the document with the Continue section already stripped. The
|
|
1489
|
+
* archive lives immediately below it so a reader meets the current handover
|
|
1490
|
+
* first and the previous ones directly after, rather than hunting for them at
|
|
1491
|
+
* the bottom of a file that also holds the project's open work.
|
|
1492
|
+
*/
|
|
1493
|
+
function archiveInto(rest, entry) {
|
|
1494
|
+
const lines = rest.split("\n");
|
|
1495
|
+
const headingIdx = lines.findIndex((l) => l.trim() === ARCHIVE_HEADING);
|
|
1496
|
+
if (headingIdx === -1) return [
|
|
1497
|
+
ARCHIVE_HEADING,
|
|
1498
|
+
"",
|
|
1499
|
+
...entry,
|
|
1500
|
+
"",
|
|
1501
|
+
"---",
|
|
1502
|
+
"",
|
|
1503
|
+
rest.trimStart()
|
|
1504
|
+
].join("\n");
|
|
1505
|
+
const before = lines.slice(0, headingIdx + 1);
|
|
1506
|
+
const after = lines.slice(headingIdx + 1);
|
|
1507
|
+
while (after.length > 0 && after[0].trim() === "") after.shift();
|
|
1508
|
+
const merged = [
|
|
1509
|
+
...entry,
|
|
1510
|
+
"",
|
|
1511
|
+
...after
|
|
1512
|
+
];
|
|
1513
|
+
const kept = [];
|
|
1514
|
+
let seen = 0;
|
|
1515
|
+
for (let i = 0; i < merged.length; i++) {
|
|
1516
|
+
if (merged[i].trim().startsWith(ARCHIVE_OPEN)) {
|
|
1517
|
+
seen += 1;
|
|
1518
|
+
if (seen > ARCHIVE_LIMIT) {
|
|
1519
|
+
while (i < merged.length && merged[i].trim() !== ARCHIVE_CLOSE) i++;
|
|
1520
|
+
continue;
|
|
1521
|
+
}
|
|
1522
|
+
}
|
|
1523
|
+
kept.push(merged[i]);
|
|
1524
|
+
}
|
|
1525
|
+
return [
|
|
1526
|
+
...before,
|
|
1527
|
+
"",
|
|
1528
|
+
...kept
|
|
1529
|
+
].join("\n");
|
|
1530
|
+
}
|
|
1531
|
+
function applyContinue(opts) {
|
|
1532
|
+
const target = resolveTodoTarget(opts.rootPath, { create: !opts.dryRun });
|
|
1533
|
+
if (!target) return {
|
|
1534
|
+
action: "failed",
|
|
1535
|
+
path: null,
|
|
1536
|
+
block: buildContinueBlock(opts),
|
|
1537
|
+
error: "Could not resolve or create a TODO.md target"
|
|
1538
|
+
};
|
|
1539
|
+
const existing = locateContinue(target.content);
|
|
1540
|
+
let carriedForward = false;
|
|
1541
|
+
let effectiveBody = opts.body;
|
|
1542
|
+
let archiveEntry = null;
|
|
1543
|
+
if (opts.authored === "auto" && existing) {
|
|
1544
|
+
if (existing.meta?.authored === "model" && isSameSession(existing.meta, opts)) return {
|
|
1545
|
+
action: "preserved",
|
|
1546
|
+
path: target.path,
|
|
1547
|
+
block: buildContinueBlock(opts),
|
|
1548
|
+
preservedMeta: existing.meta
|
|
1549
|
+
};
|
|
1550
|
+
if (existing.meta && !hasSubstance(opts.body) && !isBoilerplateOnly(existing.lines)) return {
|
|
1551
|
+
action: "preserved",
|
|
1552
|
+
path: target.path,
|
|
1553
|
+
block: buildContinueBlock(opts),
|
|
1554
|
+
preservedMeta: existing.meta ?? void 0
|
|
1555
|
+
};
|
|
1556
|
+
if (existing.meta?.authored === "model" && isRecent(existing.meta, opts.timestamp) && !isBoilerplateOnly(existing.lines)) return {
|
|
1557
|
+
action: "preserved",
|
|
1558
|
+
path: target.path,
|
|
1559
|
+
block: buildContinueBlock(opts),
|
|
1560
|
+
preservedMeta: existing.meta
|
|
1561
|
+
};
|
|
1562
|
+
if (existing.meta?.authored === "model" && !isBoilerplateOnly(existing.lines) && !isSameSession(existing.meta, opts)) archiveEntry = toArchiveEntry(existing.lines, existing.meta);
|
|
1563
|
+
if (!existing.meta && !isBoilerplateOnly(existing.lines)) {
|
|
1564
|
+
const salvaged = extractSectionContent(existing.lines);
|
|
1565
|
+
if (salvaged) {
|
|
1566
|
+
effectiveBody = [
|
|
1567
|
+
"_Carried forward from the previous checkpoint (author unknown — this",
|
|
1568
|
+
"block predates checkpoint authorship markers):_",
|
|
1569
|
+
"",
|
|
1570
|
+
salvaged
|
|
1571
|
+
].join("\n");
|
|
1572
|
+
carriedForward = true;
|
|
1573
|
+
}
|
|
1574
|
+
}
|
|
1575
|
+
}
|
|
1576
|
+
const block = buildContinueBlock({
|
|
1577
|
+
...opts,
|
|
1578
|
+
body: effectiveBody
|
|
1579
|
+
});
|
|
1580
|
+
if (opts.dryRun) return {
|
|
1581
|
+
action: "written",
|
|
1582
|
+
path: target.path,
|
|
1583
|
+
block,
|
|
1584
|
+
carriedForward,
|
|
1585
|
+
archived: !!archiveEntry
|
|
1586
|
+
};
|
|
1587
|
+
const rest = stripContinue(target.content).trimStart();
|
|
1588
|
+
const newContent = block + (archiveEntry ? archiveInto(rest, archiveEntry) : rest);
|
|
1589
|
+
const tmpPath = `${target.path}.continue.tmp`;
|
|
1590
|
+
try {
|
|
1591
|
+
writeFileSync(tmpPath, newContent, "utf8");
|
|
1592
|
+
renameSync(tmpPath, target.path);
|
|
1593
|
+
} catch (err) {
|
|
1594
|
+
try {
|
|
1595
|
+
if (existsSync(tmpPath)) renameSync(tmpPath, `${tmpPath}.dead`);
|
|
1596
|
+
} catch {}
|
|
1597
|
+
return {
|
|
1598
|
+
action: "failed",
|
|
1599
|
+
path: target.path,
|
|
1600
|
+
block,
|
|
1601
|
+
error: String(err)
|
|
1602
|
+
};
|
|
1603
|
+
}
|
|
1604
|
+
return {
|
|
1605
|
+
action: "written",
|
|
1606
|
+
path: target.path,
|
|
1607
|
+
block,
|
|
1608
|
+
carriedForward,
|
|
1609
|
+
archived: !!archiveEntry
|
|
1610
|
+
};
|
|
1611
|
+
}
|
|
1612
|
+
/** ADAPTER_DIR (harness adapter root) — mirrors pai-paths.ts's resolveAdapterDir(),
|
|
1613
|
+
* kept self-contained here to avoid importing pai-paths.ts's process.exit(1)
|
|
1614
|
+
* validation side effect. PAI_DIR is the deprecated alias, same as there. */
|
|
1615
|
+
function getPaiDir() {
|
|
1616
|
+
const envDir = process.env.ADAPTER_DIR || process.env.PAI_DIR;
|
|
1617
|
+
if (envDir) try {
|
|
1618
|
+
return realpathSync(envDir);
|
|
1619
|
+
} catch {
|
|
1620
|
+
return envDir;
|
|
1621
|
+
}
|
|
1622
|
+
return join(homedir(), ".claude");
|
|
1623
|
+
}
|
|
1624
|
+
/**
|
|
1625
|
+
* Find the notes directory for a project — local first, then the central
|
|
1626
|
+
* ~/.claude/projects/<encoded>/Notes fallback. Never creates.
|
|
1627
|
+
*/
|
|
1628
|
+
function findNotesDir(rootPath, encodedDir) {
|
|
1629
|
+
for (const rel of [
|
|
1630
|
+
"Notes",
|
|
1631
|
+
"notes",
|
|
1632
|
+
".claude/Notes"
|
|
1633
|
+
]) {
|
|
1634
|
+
const p = join(rootPath, rel);
|
|
1635
|
+
if (existsSync(p)) return p;
|
|
1636
|
+
}
|
|
1637
|
+
const central = join(getPaiDir(), "projects", encodedDir, "Notes");
|
|
1638
|
+
if (existsSync(central)) return central;
|
|
1639
|
+
return null;
|
|
1640
|
+
}
|
|
1641
|
+
/**
|
|
1642
|
+
* Find the current (highest-numbered) session note: current month, then the
|
|
1643
|
+
* previous month, then a flat notesDir as legacy fallback.
|
|
1644
|
+
*/
|
|
1645
|
+
function findLatestNote(notesDir) {
|
|
1646
|
+
const findIn = (dir) => {
|
|
1647
|
+
if (!existsSync(dir)) return null;
|
|
1648
|
+
let files;
|
|
1649
|
+
try {
|
|
1650
|
+
files = readdirSync(dir);
|
|
1651
|
+
} catch {
|
|
1652
|
+
return null;
|
|
1653
|
+
}
|
|
1654
|
+
const notes = files.filter((f) => /^\d{3,4}[\s_-].*\.md$/.test(f)).sort((a, b) => {
|
|
1655
|
+
return parseInt(a.match(/^(\d+)/)?.[1] ?? "0", 10) - parseInt(b.match(/^(\d+)/)?.[1] ?? "0", 10);
|
|
1656
|
+
});
|
|
1657
|
+
return notes.length > 0 ? join(dir, notes[notes.length - 1]) : null;
|
|
1658
|
+
};
|
|
1659
|
+
const now = /* @__PURE__ */ new Date();
|
|
1660
|
+
const current = findIn(join(notesDir, String(now.getFullYear()), String(now.getMonth() + 1).padStart(2, "0")));
|
|
1661
|
+
if (current) return current;
|
|
1662
|
+
const prev = new Date(now.getFullYear(), now.getMonth() - 1, 1);
|
|
1663
|
+
const prevFound = findIn(join(notesDir, String(prev.getFullYear()), String(prev.getMonth() + 1).padStart(2, "0")));
|
|
1664
|
+
if (prevFound) return prevFound;
|
|
1665
|
+
return findIn(notesDir);
|
|
1666
|
+
}
|
|
1667
|
+
/**
|
|
1668
|
+
* Append the checkpoint body to a session note.
|
|
1669
|
+
*
|
|
1670
|
+
* TODO.md's ## Continue is a single slot that every later checkpoint
|
|
1671
|
+
* overwrites. The session note is the durable record, so the body goes to both.
|
|
1672
|
+
* Idempotent per timestamp: re-running with the same stamp will not duplicate.
|
|
1673
|
+
*/
|
|
1674
|
+
function appendCheckpointToNote(notePath, body, timestamp) {
|
|
1675
|
+
const heading = `## Pause Checkpoint — ${timestamp ?? (/* @__PURE__ */ new Date()).toISOString()}`;
|
|
1676
|
+
let existing;
|
|
1677
|
+
try {
|
|
1678
|
+
existing = readFileSync(notePath, "utf8");
|
|
1679
|
+
} catch (err) {
|
|
1680
|
+
return {
|
|
1681
|
+
appended: false,
|
|
1682
|
+
error: String(err)
|
|
1683
|
+
};
|
|
1684
|
+
}
|
|
1685
|
+
if (existing.includes(heading)) return { appended: false };
|
|
1686
|
+
const block = `\n\n---\n\n${heading}\n\n${body.trim()}\n`;
|
|
1687
|
+
const tmpPath = `${notePath}.checkpoint.tmp`;
|
|
1688
|
+
try {
|
|
1689
|
+
writeFileSync(tmpPath, existing.trimEnd() + block, "utf8");
|
|
1690
|
+
renameSync(tmpPath, notePath);
|
|
1691
|
+
} catch (err) {
|
|
1692
|
+
try {
|
|
1693
|
+
if (existsSync(tmpPath)) renameSync(tmpPath, `${tmpPath}.dead`);
|
|
1694
|
+
} catch {}
|
|
1695
|
+
return {
|
|
1696
|
+
appended: false,
|
|
1697
|
+
error: String(err)
|
|
1698
|
+
};
|
|
1699
|
+
}
|
|
1700
|
+
return { appended: true };
|
|
1701
|
+
}
|
|
1702
|
+
/** Read a checkpoint body from a file, or from stdin when path is "-". */
|
|
1703
|
+
function readBodyFile(path) {
|
|
1704
|
+
if (path === "-") return readFileSync(0, "utf8");
|
|
1705
|
+
return readFileSync(path, "utf8");
|
|
1706
|
+
}
|
|
1707
|
+
|
|
1708
|
+
//#endregion
|
|
1709
|
+
//#region src/hooks/ts/lib/project-utils/todo.ts
|
|
1710
|
+
/**
|
|
1711
|
+
* TODO.md management — creation, task updates, checkpoints, and Continue section.
|
|
1712
|
+
*/
|
|
1713
|
+
/**
|
|
1714
|
+
* Ensure TODO.md exists. Creates it with default structure if missing.
|
|
1715
|
+
* Returns the path to the TODO.md file.
|
|
1716
|
+
*/
|
|
1717
|
+
function ensureTodoMd(cwd) {
|
|
1718
|
+
const todoPath = findTodoPath(cwd);
|
|
1719
|
+
if (!existsSync$1(todoPath)) {
|
|
1720
|
+
const parentDir = join$1(todoPath, "..");
|
|
1721
|
+
if (!existsSync$1(parentDir)) mkdirSync$1(parentDir, { recursive: true });
|
|
1722
|
+
writeFileSync$1(todoPath, `# TODO
|
|
1723
|
+
|
|
1724
|
+
## Current Session
|
|
1725
|
+
|
|
1726
|
+
- [ ] (Tasks will be tracked here)
|
|
1727
|
+
|
|
1728
|
+
## Backlog
|
|
1729
|
+
|
|
1730
|
+
- [ ] (Future tasks)
|
|
1731
|
+
|
|
1732
|
+
---
|
|
1733
|
+
|
|
1734
|
+
*Last updated: ${(/* @__PURE__ */ new Date()).toISOString()}*
|
|
1735
|
+
`);
|
|
1736
|
+
console.error(`Created TODO.md: ${todoPath}`);
|
|
1737
|
+
}
|
|
1738
|
+
return todoPath;
|
|
1739
|
+
}
|
|
1740
|
+
/**
|
|
1741
|
+
* The Claude Code session UUID, read off the transcript path.
|
|
1742
|
+
*
|
|
1743
|
+
* Claude Code names a transcript `<session-uuid>.jsonl`, so the hooks that
|
|
1744
|
+
* receive a transcript path are holding the session's identity without knowing
|
|
1745
|
+
* it. Both session-end writers had one available and neither used it.
|
|
1746
|
+
*
|
|
1747
|
+
* Shape-checked rather than trusted: only a UUID is returned, so a renamed,
|
|
1748
|
+
* archived or otherwise unexpected filename yields undefined and the caller
|
|
1749
|
+
* falls back to the session line rather than writing a `session-id` that
|
|
1750
|
+
* identifies nothing. A wrong id is worse than none — it would make two
|
|
1751
|
+
* different sessions compare equal.
|
|
1752
|
+
*/
|
|
1753
|
+
function sessionIdFromTranscript(transcriptPath) {
|
|
1754
|
+
if (!transcriptPath) return void 0;
|
|
1755
|
+
const base = basename$1(transcriptPath).replace(/\.jsonl$/, "");
|
|
1756
|
+
return /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(base) ? base : void 0;
|
|
1757
|
+
}
|
|
1758
|
+
/**
|
|
1759
|
+
* Update the ## Continue section at the top of TODO.md.
|
|
1760
|
+
*
|
|
1761
|
+
* This is the unattended writer: the pre-compact hook and the daemon's
|
|
1762
|
+
* work-queue worker both come through here. It used to build its own block and
|
|
1763
|
+
* strip the existing section with `/## Continue\n[\s\S]*?\n---\n+/` — a
|
|
1764
|
+
* non-greedy match to the first `---`, which cuts a rich checkpoint in half at
|
|
1765
|
+
* the first horizontal rule inside its body and leaves the remainder orphaned
|
|
1766
|
+
* in the document.
|
|
1767
|
+
*
|
|
1768
|
+
* More importantly it was the writer that actually destroyed model-authored
|
|
1769
|
+
* checkpoints: `pai pause` wrote one, then this ran seconds later on session
|
|
1770
|
+
* end and replaced it with `Working directory: … Check the latest session note
|
|
1771
|
+
* for details.`
|
|
1772
|
+
*
|
|
1773
|
+
* It now delegates to the shared checkpoint module in "auto" mode, which means
|
|
1774
|
+
* it inherits the preservation rules rather than reimplementing them. Guarding
|
|
1775
|
+
* here rather than at each of the three call sites is deliberate: any future
|
|
1776
|
+
* caller inherits the behaviour without knowing it exists.
|
|
1777
|
+
*/
|
|
1778
|
+
function updateTodoContinue(cwd, noteFilename, state, tokenDisplay, sessionId) {
|
|
1779
|
+
ensureTodoMd(cwd);
|
|
1780
|
+
const result = applyContinue({
|
|
1781
|
+
rootPath: cwd,
|
|
1782
|
+
authored: "auto",
|
|
1783
|
+
sessionLine: noteFilename.replace(/\.md$/, ""),
|
|
1784
|
+
sessionId,
|
|
1785
|
+
cwd,
|
|
1786
|
+
body: state?.trim() || void 0
|
|
1787
|
+
});
|
|
1788
|
+
if (result.action === "preserved") {
|
|
1789
|
+
console.error("TODO.md ## Continue left intact — authored checkpoint for this session");
|
|
1790
|
+
return;
|
|
1791
|
+
}
|
|
1792
|
+
if (result.action === "failed") {
|
|
1793
|
+
console.error(`TODO.md ## Continue update failed: ${result.error}`);
|
|
1794
|
+
return;
|
|
1795
|
+
}
|
|
1796
|
+
try {
|
|
1797
|
+
const todoPath = result.path;
|
|
1798
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
1799
|
+
let content = readFileSync$1(todoPath, "utf-8");
|
|
1800
|
+
content = content.replace(/(\n---\s*)*(\n\*Last updated:.*\*\s*)+$/g, "");
|
|
1801
|
+
content = content.trimEnd() + `\n\n---\n\n*Last updated: ${now}*\n`;
|
|
1802
|
+
writeFileSync$1(todoPath, content);
|
|
1803
|
+
} catch {}
|
|
1804
|
+
console.error(result.carriedForward ? "TODO.md ## Continue section updated (previous content carried forward)" : "TODO.md ## Continue section updated");
|
|
1805
|
+
}
|
|
1806
|
+
|
|
1807
|
+
//#endregion
|
|
1808
|
+
//#region src/daemon/templates/session-summary-prompt.ts
|
|
1809
|
+
/**
|
|
1810
|
+
* Build the prompt string to send to the summarizer model.
|
|
1811
|
+
*
|
|
1812
|
+
* Returns a single string suitable for piping to `claude --model <model> --print`.
|
|
1813
|
+
*/
|
|
1814
|
+
function buildSessionSummaryPrompt(params) {
|
|
1815
|
+
const { userMessages, gitLog, cwd, date, filesModified, existingNote } = params;
|
|
1816
|
+
const userSection = userMessages.length > 0 ? userMessages.map((m, i) => `[${i + 1}] ${m}`).join("\n\n") : "(No user messages extracted)";
|
|
1817
|
+
const gitSection = gitLog.trim() || "(No git commits during this session)";
|
|
1818
|
+
const filesSection = filesModified && filesModified.length > 0 ? filesModified.map((f) => `- ${f}`).join("\n") : "";
|
|
1819
|
+
return `You are summarizing a coding session. Given the user messages and git commits below, write a session note.
|
|
1820
|
+
|
|
1821
|
+
Project directory: ${cwd}
|
|
1822
|
+
Date: ${date}
|
|
1823
|
+
|
|
1824
|
+
Focus on:
|
|
1825
|
+
- What problems were encountered and how they were solved
|
|
1826
|
+
- Key architectural decisions and their rationale
|
|
1827
|
+
- What was built (reference actual files and code patterns)
|
|
1828
|
+
- What was left unfinished or needs follow-up
|
|
1829
|
+
|
|
1830
|
+
Do NOT include:
|
|
1831
|
+
- Mechanical metadata (token counts, checkpoint timestamps)
|
|
1832
|
+
- System messages or tool results verbatim
|
|
1833
|
+
- Generic descriptions — be specific about what happened
|
|
1834
|
+
- Markdown frontmatter or YAML headers
|
|
1835
|
+
${existingNote ? `\nAn existing session note is provided below. Merge the new information into it,
|
|
1836
|
+
preserving what was already written. Add new work items and update the summary.
|
|
1837
|
+
Do NOT duplicate existing content.
|
|
1838
|
+
|
|
1839
|
+
EXISTING NOTE:
|
|
1840
|
+
${existingNote}
|
|
1841
|
+
` : ""}
|
|
1842
|
+
Format your response EXACTLY as follows (no extra text before or after):
|
|
1843
|
+
|
|
1844
|
+
TOPIC: [A short topic label, max 60 characters, describing the WORK DONE — not quoting user messages. Format as "Topic1, Topic2, and Topic3" if multiple themes. Example: "Session Summary Worker, Topic Detection"]
|
|
1845
|
+
|
|
1846
|
+
# Session: [Descriptive title summarizing what was ACCOMPLISHED, max 60 characters. Describe the work done, not the user's request. Bad: "Dark Mode Button Does Nothing". Good: "Dark Mode Toggle, Keyboard IPC, and Audio Fix"]
|
|
1847
|
+
|
|
1848
|
+
**Date:** ${date}
|
|
1849
|
+
**Status:** In Progress
|
|
1850
|
+
|
|
1851
|
+
---
|
|
1852
|
+
|
|
1853
|
+
## Work Done
|
|
1854
|
+
|
|
1855
|
+
[Organize by theme, not chronologically. Group related work under descriptive bullet points.
|
|
1856
|
+
Use checkbox format: - [x] for completed items, - [ ] for incomplete items.
|
|
1857
|
+
Include specific file names, function names, and technical details.]
|
|
1858
|
+
|
|
1859
|
+
## Key Decisions
|
|
1860
|
+
|
|
1861
|
+
[List important choices made during the session with brief rationale.
|
|
1862
|
+
Skip this section entirely if no significant decisions were made.]
|
|
1863
|
+
|
|
1864
|
+
## Known Issues
|
|
1865
|
+
|
|
1866
|
+
[What was left unfinished, bugs discovered, or follow-up items needed.
|
|
1867
|
+
Skip this section entirely if nothing is pending.]
|
|
1868
|
+
|
|
1869
|
+
---
|
|
1870
|
+
|
|
1871
|
+
USER MESSAGES:
|
|
1872
|
+
${userSection}
|
|
1873
|
+
|
|
1874
|
+
GIT COMMITS:
|
|
1875
|
+
${gitSection}
|
|
1876
|
+
${filesSection ? `\nFILES MODIFIED:\n${filesSection}` : ""}`;
|
|
1877
|
+
}
|
|
1878
|
+
|
|
1879
|
+
//#endregion
|
|
1880
|
+
//#region src/daemon/templates/triple-extraction-prompt.ts
|
|
1881
|
+
/**
|
|
1882
|
+
* triple-extraction-prompt.ts — Prompt template for KG triple extraction.
|
|
1883
|
+
*
|
|
1884
|
+
* Used by the session-summary-worker to extract structured facts from
|
|
1885
|
+
* a completed session summary and store them in the temporal knowledge graph.
|
|
1886
|
+
*/
|
|
1887
|
+
function buildTripleExtractionPrompt(params) {
|
|
1888
|
+
return `Extract structured entities and relations from this coding session.
|
|
1889
|
+
|
|
1890
|
+
Output a single JSON object with two arrays: "entities" and "relations".
|
|
1891
|
+
|
|
1892
|
+
Entity types: project | person | concept | tool | file | version | decision | technology | organization
|
|
1893
|
+
|
|
1894
|
+
Rules:
|
|
1895
|
+
- Be SPECIFIC: entity names must be concrete (e.g., "FSRS", "Glidr", "the owner")
|
|
1896
|
+
- Use snake_case relation verb phrases (e.g., "uses_algorithm", "decided_to", "shipped_version")
|
|
1897
|
+
- Skip opinions, speculation, and "we should" statements
|
|
1898
|
+
- Skip entities obvious from project metadata unless they have a meaningful relation
|
|
1899
|
+
- Maximum 15 relations per session — pick the most important
|
|
1900
|
+
- Each entity should have a brief description (1 sentence, what it is in this context)
|
|
1901
|
+
- Each relation must reference entity names that appear in the entities array
|
|
1902
|
+
|
|
1903
|
+
Example output:
|
|
1904
|
+
{
|
|
1905
|
+
"entities": [
|
|
1906
|
+
{"name": "Glidr", "type": "project", "description": "Flashcard app using FSRS spaced repetition"},
|
|
1907
|
+
{"name": "FSRS", "type": "concept", "description": "Free Spaced Repetition Scheduler algorithm"},
|
|
1908
|
+
{"name": "the owner", "type": "person", "description": "Developer of Glidr and Quassl"},
|
|
1909
|
+
{"name": "Quassl", "type": "project", "description": "iOS app being rewritten in Flutter"},
|
|
1910
|
+
{"name": "Flutter", "type": "technology", "description": "Cross-platform mobile framework"}
|
|
1911
|
+
],
|
|
1912
|
+
"relations": [
|
|
1913
|
+
{"source": "Glidr", "relation": "uses_algorithm", "target": "FSRS"},
|
|
1914
|
+
{"source": "Glidr", "relation": "shipped_version", "target": "1.0.5"},
|
|
1915
|
+
{"source": "the owner", "relation": "decided_to_rewrite", "target": "Quassl"},
|
|
1916
|
+
{"source": "Quassl", "relation": "migrating_to", "target": "Flutter"}
|
|
1917
|
+
]
|
|
1918
|
+
}
|
|
1919
|
+
|
|
1920
|
+
PROJECT: ${params.projectSlug}
|
|
1921
|
+
|
|
1922
|
+
SESSION CONTENT:
|
|
1923
|
+
${params.sessionContent}
|
|
1924
|
+
|
|
1925
|
+
GIT COMMITS:
|
|
1926
|
+
${params.gitLog}
|
|
1927
|
+
|
|
1928
|
+
Output ONLY the JSON object with no surrounding prose, no code fences, no trailing commas, and no comments.
|
|
1929
|
+
|
|
1930
|
+
JSON object (entities + relations):`;
|
|
1931
|
+
}
|
|
1932
|
+
|
|
1933
|
+
//#endregion
|
|
1934
|
+
//#region src/workers/daemon-llm.ts
|
|
1935
|
+
/**
|
|
1936
|
+
* daemon-llm.ts — provider-routed LLM spawns for daemon-side background calls.
|
|
1937
|
+
*
|
|
1938
|
+
* Session summaries, context handovers and KG extraction used to spawn a bare
|
|
1939
|
+
* `claude --model <tier>` with the ambient environment: on a machine whose
|
|
1940
|
+
* only login is a worker provider that spawn either dies (no Anthropic
|
|
1941
|
+
* credentials) or bills Anthropic outside the provider abstraction. This
|
|
1942
|
+
* module routes those spawns through the same registry and env build the
|
|
1943
|
+
* worker runner uses (`buildRunEnv`), resolving the tier alias to the
|
|
1944
|
+
* provider's concrete model id. With no usable provider configured it falls
|
|
1945
|
+
* back to the historical behaviour: the tier alias itself, ambient env minus
|
|
1946
|
+
* the Anthropic API key.
|
|
1947
|
+
*/
|
|
1948
|
+
/** Timeout per tier (ms) — a class-appropriate budget, not a per-model one. */
|
|
1949
|
+
const LLM_TIMEOUT_MS = {
|
|
1950
|
+
haiku: 6e4,
|
|
1951
|
+
sonnet: 12e4,
|
|
1952
|
+
opus: 3e5
|
|
1953
|
+
};
|
|
1954
|
+
/** Resolve a tier to the provider's concrete model id: the fast capability
|
|
1955
|
+
* for the cheap tier, the default model for the middle and top tiers. */
|
|
1956
|
+
function tierModel(provider, tier) {
|
|
1957
|
+
return resolveModelCapability(provider, tier === "haiku" ? "fast" : "default");
|
|
1958
|
+
}
|
|
1959
|
+
/**
|
|
1960
|
+
* Containment every daemon-side LLM spawn carries. These calls are
|
|
1961
|
+
* text-in/text-out: the prompt carries the context, the answer is the
|
|
1962
|
+
* product, and nothing about summarizing a session justifies a tool. An
|
|
1963
|
+
* unrestricted background summarizer was observed on 2026-09-18 (01:33-01:51)
|
|
1964
|
+
* rewriting the live config with a schema-shaped dump while the daemon ran;
|
|
1965
|
+
* with the tool grant empty and MCP strictly empty, that class of damage is
|
|
1966
|
+
* structurally impossible rather than merely unlikely.
|
|
1967
|
+
*/
|
|
1968
|
+
function containmentArgs(logDir) {
|
|
1969
|
+
return [
|
|
1970
|
+
"--strict-mcp-config",
|
|
1971
|
+
"--mcp-config",
|
|
1972
|
+
ensureNoMcpConfig(logDir),
|
|
1973
|
+
"--allowedTools",
|
|
1974
|
+
"",
|
|
1975
|
+
"--tools",
|
|
1976
|
+
""
|
|
1977
|
+
];
|
|
1978
|
+
}
|
|
1979
|
+
/** The historical fallback: tier alias as the model id, ambient env with the
|
|
1980
|
+
* Anthropic API key stripped (so the CLI uses its interactive login). */
|
|
1981
|
+
function legacyPlan(tier, config) {
|
|
1982
|
+
const { ANTHROPIC_API_KEY: _drop, ...env } = process.env;
|
|
1983
|
+
return {
|
|
1984
|
+
model: tier,
|
|
1985
|
+
args: [
|
|
1986
|
+
"--model",
|
|
1987
|
+
tier,
|
|
1988
|
+
...containmentArgs(workersLogDir(config ?? defaultWorkersConfig())),
|
|
1989
|
+
"-p",
|
|
1990
|
+
"--no-session-persistence"
|
|
1991
|
+
],
|
|
1992
|
+
env,
|
|
1993
|
+
timeoutMs: LLM_TIMEOUT_MS[tier],
|
|
1994
|
+
provider: null
|
|
1995
|
+
};
|
|
1996
|
+
}
|
|
1997
|
+
/**
|
|
1998
|
+
* Plan a daemon-side LLM spawn for a tier. Provider resolution failures (no
|
|
1999
|
+
* config, workers off, no usable provider) fall back to the tier-alias path;
|
|
2000
|
+
* a configured-but-broken provider (unreadable key file) throws, because
|
|
2001
|
+
* silently degrading to Anthropic billing is worse than a failed summary.
|
|
2002
|
+
*/
|
|
2003
|
+
async function planLlmSpawn(tier, configPath) {
|
|
2004
|
+
let provider = null;
|
|
2005
|
+
let providerName = null;
|
|
2006
|
+
let config = null;
|
|
2007
|
+
try {
|
|
2008
|
+
const { workers } = readWorkersSection(configPath);
|
|
2009
|
+
config = workers;
|
|
2010
|
+
if (workers.enabled) {
|
|
2011
|
+
const target = resolveTarget(workers, workersLogDir(workers), {});
|
|
2012
|
+
provider = target.provider;
|
|
2013
|
+
providerName = target.providerName;
|
|
2014
|
+
}
|
|
2015
|
+
} catch {
|
|
2016
|
+
provider = null;
|
|
2017
|
+
providerName = null;
|
|
2018
|
+
}
|
|
2019
|
+
if (!provider || !providerName || !config) return legacyPlan(tier, config);
|
|
2020
|
+
const logDir = workersLogDir(config);
|
|
2021
|
+
let proxyUrl;
|
|
2022
|
+
if (provider.protocol === "openai") {
|
|
2023
|
+
mkdirSync(logDir, { recursive: true });
|
|
2024
|
+
proxyUrl = `${await ensureProxyRunning(DEFAULT_PROXY_PORT, logDir)}/${providerName}`;
|
|
2025
|
+
}
|
|
2026
|
+
const model = tierModel(provider, tier);
|
|
2027
|
+
return {
|
|
2028
|
+
model,
|
|
2029
|
+
args: [
|
|
2030
|
+
"--model",
|
|
2031
|
+
model,
|
|
2032
|
+
...containmentArgs(logDir),
|
|
2033
|
+
"-p",
|
|
2034
|
+
"--no-session-persistence"
|
|
2035
|
+
],
|
|
2036
|
+
env: buildRunEnv(provider, true, proxyUrl),
|
|
2037
|
+
timeoutMs: LLM_TIMEOUT_MS[tier],
|
|
2038
|
+
provider: providerName
|
|
2039
|
+
};
|
|
2040
|
+
}
|
|
2041
|
+
|
|
2042
|
+
//#endregion
|
|
2043
|
+
//#region src/memory/kg-extraction.ts
|
|
2044
|
+
/**
|
|
2045
|
+
* kg-extraction.ts — Shared KG triple extraction logic.
|
|
2046
|
+
*
|
|
2047
|
+
* Extracted from session-summary-worker.ts so both the worker and the
|
|
2048
|
+
* CLI backfill (`pai kg backfill`) can use the same code path.
|
|
2049
|
+
*
|
|
2050
|
+
* Provides:
|
|
2051
|
+
* - findClaudeBinary() — locate the claude CLI
|
|
2052
|
+
* - spawnClaude() — generic prompt -> response runner (provider-routed)
|
|
2053
|
+
* - extractAndStoreTriples() — run the extractor prompt and persist triples to Postgres
|
|
2054
|
+
*/
|
|
2055
|
+
/**
|
|
2056
|
+
* Find the `claude` CLI binary. Checks common installation locations first
|
|
2057
|
+
* (launchd PATH is minimal so bare "claude" often won't resolve).
|
|
2058
|
+
*/
|
|
2059
|
+
function findClaudeBinary$1() {
|
|
2060
|
+
const candidates = [
|
|
2061
|
+
join(homedir(), ".local", "bin", "claude"),
|
|
2062
|
+
join(homedir(), ".claude", "local", "claude"),
|
|
2063
|
+
"/usr/local/bin/claude",
|
|
2064
|
+
"/opt/homebrew/bin/claude"
|
|
2065
|
+
];
|
|
2066
|
+
for (const candidate of candidates) try {
|
|
2067
|
+
if (existsSync(candidate)) return candidate;
|
|
2068
|
+
} catch {}
|
|
2069
|
+
return "claude";
|
|
2070
|
+
}
|
|
2071
|
+
/**
|
|
2072
|
+
* Spawn the claude CLI with a prompt on stdin and return stdout.
|
|
2073
|
+
*
|
|
2074
|
+
* Routed through the provider registry (planLlmSpawn): the tier resolves to
|
|
2075
|
+
* the configured provider's model id and the env carries its base URL and
|
|
2076
|
+
* token. With no provider configured it degrades to the historical behaviour
|
|
2077
|
+
* — the tier alias itself, ambient env minus ANTHROPIC_API_KEY.
|
|
2078
|
+
*/
|
|
2079
|
+
async function spawnClaude(prompt, tier = "sonnet") {
|
|
2080
|
+
const claudeBin = findClaudeBinary$1();
|
|
2081
|
+
if (!claudeBin) {
|
|
2082
|
+
process.stderr.write("[kg-extraction] claude CLI not found.\n");
|
|
2083
|
+
return null;
|
|
2084
|
+
}
|
|
2085
|
+
let plan;
|
|
2086
|
+
try {
|
|
2087
|
+
plan = await planLlmSpawn(tier);
|
|
2088
|
+
} catch (e) {
|
|
2089
|
+
process.stderr.write(`[kg-extraction] could not plan ${tier} spawn: ${e}\n`);
|
|
2090
|
+
return null;
|
|
2091
|
+
}
|
|
2092
|
+
const { spawn } = await import("node:child_process");
|
|
2093
|
+
return new Promise((resolve) => {
|
|
2094
|
+
let timer = null;
|
|
2095
|
+
const child = spawn(claudeBin, plan.args, {
|
|
2096
|
+
env: plan.env,
|
|
2097
|
+
stdio: [
|
|
2098
|
+
"pipe",
|
|
2099
|
+
"pipe",
|
|
2100
|
+
"pipe"
|
|
2101
|
+
]
|
|
2102
|
+
});
|
|
2103
|
+
let stdout = "";
|
|
2104
|
+
let stderr = "";
|
|
2105
|
+
child.stdout.on("data", (chunk) => {
|
|
2106
|
+
stdout += chunk.toString();
|
|
2107
|
+
});
|
|
2108
|
+
child.stderr.on("data", (chunk) => {
|
|
2109
|
+
stderr += chunk.toString();
|
|
2110
|
+
});
|
|
2111
|
+
child.on("error", (err) => {
|
|
2112
|
+
if (timer) {
|
|
2113
|
+
clearTimeout(timer);
|
|
2114
|
+
timer = null;
|
|
2115
|
+
}
|
|
2116
|
+
process.stderr.write(`[kg-extraction] ${plan.model} spawn error: ${err.message}\n`);
|
|
2117
|
+
resolve(null);
|
|
2118
|
+
});
|
|
2119
|
+
child.on("close", (code) => {
|
|
2120
|
+
if (timer) {
|
|
2121
|
+
clearTimeout(timer);
|
|
2122
|
+
timer = null;
|
|
2123
|
+
}
|
|
2124
|
+
if (code !== 0) {
|
|
2125
|
+
process.stderr.write(`[kg-extraction] ${plan.model} exited ${code}: ${stderr.slice(0, 300)}\n`);
|
|
2126
|
+
resolve(null);
|
|
2127
|
+
} else resolve(stdout.trim() || null);
|
|
2128
|
+
});
|
|
2129
|
+
timer = setTimeout(() => {
|
|
2130
|
+
process.stderr.write(`[kg-extraction] ${plan.model} timed out — killing process.\n`);
|
|
2131
|
+
child.kill("SIGTERM");
|
|
2132
|
+
resolve(null);
|
|
2133
|
+
}, plan.timeoutMs);
|
|
2134
|
+
child.stdin.write(prompt);
|
|
2135
|
+
child.stdin.end();
|
|
2136
|
+
});
|
|
2137
|
+
}
|
|
2138
|
+
/**
|
|
2139
|
+
* Slice text down to the outermost JSON structure, dropping any surrounding
|
|
2140
|
+
* prose or code-fence artifacts the LLM added around the JSON object/array.
|
|
2141
|
+
* Returns the input unchanged if no opening brace/bracket is found.
|
|
2142
|
+
*/
|
|
2143
|
+
function extractJsonSpan(text) {
|
|
2144
|
+
const firstBrace = text.indexOf("{");
|
|
2145
|
+
const firstBracket = text.indexOf("[");
|
|
2146
|
+
let start = -1;
|
|
2147
|
+
let closeChar = "";
|
|
2148
|
+
if (firstBrace !== -1 && (firstBracket === -1 || firstBrace < firstBracket)) {
|
|
2149
|
+
start = firstBrace;
|
|
2150
|
+
closeChar = "}";
|
|
2151
|
+
} else if (firstBracket !== -1) {
|
|
2152
|
+
start = firstBracket;
|
|
2153
|
+
closeChar = "]";
|
|
2154
|
+
}
|
|
2155
|
+
if (start === -1) return text;
|
|
2156
|
+
const end = text.lastIndexOf(closeChar);
|
|
2157
|
+
if (end === -1 || end <= start) return text;
|
|
2158
|
+
return text.slice(start, end + 1);
|
|
2159
|
+
}
|
|
2160
|
+
/**
|
|
2161
|
+
* Extract structured KG triples from a session summary and store them in
|
|
2162
|
+
* Postgres. Idempotent: if a (subject, predicate) pair already has the same
|
|
2163
|
+
* object, no new row is added; if the object differs, the old triple is
|
|
2164
|
+
* invalidated (valid_to = NOW()) and a new one is inserted.
|
|
2165
|
+
*
|
|
2166
|
+
* Best-effort: per-triple errors are caught and logged but never thrown.
|
|
2167
|
+
* Returns a small stats object so callers can report progress.
|
|
2168
|
+
*/
|
|
2169
|
+
async function extractAndStoreTriples$1(pool, params) {
|
|
2170
|
+
const stats = {
|
|
2171
|
+
extracted: 0,
|
|
2172
|
+
added: 0,
|
|
2173
|
+
superseded: 0
|
|
2174
|
+
};
|
|
2175
|
+
const jsonOutput = await spawnClaude(buildTripleExtractionPrompt({
|
|
2176
|
+
sessionContent: params.summaryText,
|
|
2177
|
+
projectSlug: params.projectSlug,
|
|
2178
|
+
gitLog: params.gitLog ?? ""
|
|
2179
|
+
}), params.model ?? "sonnet");
|
|
2180
|
+
if (!jsonOutput) return stats;
|
|
2181
|
+
let cleaned = jsonOutput.replace(/^```json\s*/m, "").replace(/^```\s*/m, "").replace(/\s*```$/m, "").trim();
|
|
2182
|
+
cleaned = extractJsonSpan(cleaned);
|
|
2183
|
+
let triples;
|
|
2184
|
+
try {
|
|
2185
|
+
const parsed = JSON.parse(cleaned);
|
|
2186
|
+
if (Array.isArray(parsed)) triples = parsed;
|
|
2187
|
+
else if (parsed && typeof parsed === "object" && Array.isArray(parsed.relations)) {
|
|
2188
|
+
const newFmt = parsed;
|
|
2189
|
+
if (params.federationDb && Array.isArray(newFmt.entities)) {
|
|
2190
|
+
const tenantId = params.tenantId ?? "default";
|
|
2191
|
+
for (const entity of newFmt.entities) {
|
|
2192
|
+
if (!entity.name) continue;
|
|
2193
|
+
try {
|
|
2194
|
+
upsertKgEntity(params.federationDb, {
|
|
2195
|
+
name: entity.name,
|
|
2196
|
+
type: entity.type ?? "unknown",
|
|
2197
|
+
description: entity.description,
|
|
2198
|
+
tenantId
|
|
2199
|
+
});
|
|
2200
|
+
} catch (entityErr) {
|
|
2201
|
+
process.stderr.write(`[kg-extraction] entity upsert error (${entity.name}): ${entityErr}\n`);
|
|
2202
|
+
}
|
|
2203
|
+
}
|
|
2204
|
+
}
|
|
2205
|
+
triples = newFmt.relations.map((r) => ({
|
|
2206
|
+
subject: r.source,
|
|
2207
|
+
predicate: r.relation,
|
|
2208
|
+
object: r.target
|
|
2209
|
+
}));
|
|
2210
|
+
} else {
|
|
2211
|
+
process.stderr.write(`[kg-extraction] Unexpected JSON shape — neither array nor {entities,relations}\n`);
|
|
2212
|
+
return stats;
|
|
2213
|
+
}
|
|
2214
|
+
} catch (e) {
|
|
2215
|
+
const collapse = (s) => s.replace(/\s+/g, " ").trim();
|
|
2216
|
+
const head200 = collapse(jsonOutput.slice(0, 200));
|
|
2217
|
+
const tail200 = collapse(jsonOutput.slice(-200));
|
|
2218
|
+
process.stderr.write(`[kg-extraction] JSON parse failed: ${e}. head200="${head200}" tail200="${tail200}"\n`);
|
|
2219
|
+
return stats;
|
|
2220
|
+
}
|
|
2221
|
+
if (!Array.isArray(triples)) return stats;
|
|
2222
|
+
stats.extracted = triples.length;
|
|
2223
|
+
for (const t of triples) {
|
|
2224
|
+
if (!t.subject || !t.predicate || !t.object) continue;
|
|
2225
|
+
try {
|
|
2226
|
+
const existing = await kgQuery(pool, {
|
|
2227
|
+
subject: t.subject,
|
|
2228
|
+
predicate: t.predicate,
|
|
2229
|
+
project_id: params.projectId ?? void 0
|
|
2230
|
+
});
|
|
2231
|
+
if (existing.find((e) => e.object === t.object && !e.valid_to)) continue;
|
|
2232
|
+
const supersedes = existing.find((e) => e.object !== t.object && !e.valid_to);
|
|
2233
|
+
if (supersedes) {
|
|
2234
|
+
await kgInvalidate(pool, supersedes.id);
|
|
2235
|
+
stats.superseded++;
|
|
2236
|
+
}
|
|
2237
|
+
await kgAdd(pool, {
|
|
2238
|
+
subject: t.subject,
|
|
2239
|
+
predicate: t.predicate,
|
|
2240
|
+
object: t.object,
|
|
2241
|
+
project_id: params.projectId ?? void 0,
|
|
2242
|
+
source_session: params.sessionId,
|
|
2243
|
+
confidence: "EXTRACTED"
|
|
2244
|
+
});
|
|
2245
|
+
stats.added++;
|
|
2246
|
+
} catch (tripleErr) {
|
|
2247
|
+
process.stderr.write(`[kg-extraction] store error (${t.subject}): ${tripleErr}\n`);
|
|
2248
|
+
}
|
|
2249
|
+
}
|
|
2250
|
+
return stats;
|
|
2251
|
+
}
|
|
2252
|
+
|
|
2253
|
+
//#endregion
|
|
2254
|
+
//#region src/daemon/session-summary-worker.ts
|
|
2255
|
+
/**
|
|
2256
|
+
* session-summary-worker.ts — AI-powered session note generation
|
|
2257
|
+
*
|
|
2258
|
+
* Processes `session-summary` work items by:
|
|
2259
|
+
* 1. Finding the current session's JSONL transcript
|
|
2260
|
+
* 2. Extracting user messages and assistant context
|
|
2261
|
+
* 3. Gathering git commits from the session period
|
|
2262
|
+
* 4. Spawning Claude (sonnet for compaction, opus for session end) to generate a structured summary
|
|
2263
|
+
* 5. Comparing the new topic against the existing note's topic
|
|
2264
|
+
* 6. Creating a NEW note if the topic shifted, or updating the existing one
|
|
2265
|
+
*
|
|
2266
|
+
* Topic detection: the summarizer outputs a TOPIC: line as the first line of
|
|
2267
|
+
* its response. This is compared against the existing note's title using word
|
|
2268
|
+
* overlap. If overlap is below ~30%, a new note is created.
|
|
2269
|
+
*
|
|
2270
|
+
* Designed to run inside the daemon's work queue worker. All errors are
|
|
2271
|
+
* thrown (not swallowed) so the work queue retry logic handles them.
|
|
2272
|
+
*/
|
|
2273
|
+
/** Minimum interval between summaries for the same project (ms). */
|
|
2274
|
+
const SUMMARY_COOLDOWN_MS = 1800 * 1e3;
|
|
2275
|
+
/** Maximum JSONL content to feed to the summarizer (characters). */
|
|
2276
|
+
/** Max JSONL chars per model. Opus/Sonnet can handle much more than Haiku. */
|
|
2277
|
+
const MAX_JSONL_CHARS = {
|
|
2278
|
+
haiku: 5e4,
|
|
2279
|
+
sonnet: 2e5,
|
|
2280
|
+
opus: 5e5
|
|
2281
|
+
};
|
|
2282
|
+
/** Maximum user messages to include in the prompt. */
|
|
2283
|
+
const MAX_USER_MESSAGES = 30;
|
|
2284
|
+
/** File tracking last summary timestamps per project — resolved under
|
|
2285
|
+
* PAI_HOME, falling back to the pre-2026-09-19 ~/.config/pai location. */
|
|
2286
|
+
function oldCooldownFile() {
|
|
2287
|
+
return join(homedir(), ".config", "pai", "summary-cooldowns.json");
|
|
2288
|
+
}
|
|
2289
|
+
function cooldownFilePath() {
|
|
2290
|
+
return resolvePaiFile(paiHomePath("summary-cooldowns.json"), [oldCooldownFile()], "pai config migrate");
|
|
2291
|
+
}
|
|
2292
|
+
function migrateSummaryCooldowns(opts = {}) {
|
|
2293
|
+
return migratePaiFile(paiHomePath("summary-cooldowns.json"), [oldCooldownFile()], opts);
|
|
2294
|
+
}
|
|
2295
|
+
/** Claude Code projects directory. */
|
|
2296
|
+
const CLAUDE_PROJECTS_DIR = join(homedir(), ".claude", "projects");
|
|
2297
|
+
function loadCooldowns() {
|
|
2298
|
+
try {
|
|
2299
|
+
const file = cooldownFilePath();
|
|
2300
|
+
if (existsSync(file)) return JSON.parse(readFileSync(file, "utf-8"));
|
|
2301
|
+
} catch {}
|
|
2302
|
+
return {};
|
|
2303
|
+
}
|
|
2304
|
+
function saveCooldowns(cooldowns) {
|
|
2305
|
+
try {
|
|
2306
|
+
const file = paiHomePath("summary-cooldowns.json");
|
|
2307
|
+
mkdirSync(dirname(file), { recursive: true });
|
|
2308
|
+
writeFileSync(file, JSON.stringify(cooldowns, null, 2), "utf-8");
|
|
2309
|
+
} catch {}
|
|
2310
|
+
}
|
|
2311
|
+
function isOnCooldown(cwd) {
|
|
2312
|
+
const lastRun = loadCooldowns()[cwd];
|
|
2313
|
+
if (!lastRun) return false;
|
|
2314
|
+
return Date.now() - lastRun < SUMMARY_COOLDOWN_MS;
|
|
2315
|
+
}
|
|
2316
|
+
function markCooldown(cwd) {
|
|
2317
|
+
const cooldowns = loadCooldowns();
|
|
2318
|
+
cooldowns[cwd] = Date.now();
|
|
2319
|
+
const cutoff = Date.now() - 1440 * 60 * 1e3;
|
|
2320
|
+
for (const key of Object.keys(cooldowns)) if (cooldowns[key] < cutoff) delete cooldowns[key];
|
|
2321
|
+
saveCooldowns(cooldowns);
|
|
2322
|
+
}
|
|
2323
|
+
/**
|
|
2324
|
+
* Encode a cwd path the same way Claude Code does for its project directories.
|
|
2325
|
+
* Replaces /, space, dot, and hyphen with -.
|
|
2326
|
+
*/
|
|
2327
|
+
function encodeProjectPath(cwd) {
|
|
2328
|
+
return cwd.replace(/[\/\s.\-]/g, "-");
|
|
2329
|
+
}
|
|
2330
|
+
/**
|
|
2331
|
+
* Find the most recently modified JSONL file for the given project.
|
|
2332
|
+
*
|
|
2333
|
+
* Claude Code stores transcripts in:
|
|
2334
|
+
* ~/.claude/projects/<encoded-path>/sessions/*.jsonl
|
|
2335
|
+
* ~/.claude/projects/<encoded-path>/<uuid>.jsonl (legacy)
|
|
2336
|
+
*/
|
|
2337
|
+
function findLatestJsonl(cwd) {
|
|
2338
|
+
const projectDir = join(CLAUDE_PROJECTS_DIR, encodeProjectPath(cwd));
|
|
2339
|
+
if (!existsSync(projectDir)) {
|
|
2340
|
+
process.stderr.write(`[session-summary] No Claude project dir found: ${projectDir}\n`);
|
|
2341
|
+
return null;
|
|
2342
|
+
}
|
|
2343
|
+
const candidates = [];
|
|
2344
|
+
const sessionsDir = join(projectDir, "sessions");
|
|
2345
|
+
if (existsSync(sessionsDir)) try {
|
|
2346
|
+
for (const f of readdirSync(sessionsDir)) {
|
|
2347
|
+
if (!f.endsWith(".jsonl")) continue;
|
|
2348
|
+
const fullPath = join(sessionsDir, f);
|
|
2349
|
+
try {
|
|
2350
|
+
const st = statSync(fullPath);
|
|
2351
|
+
candidates.push({
|
|
2352
|
+
path: fullPath,
|
|
2353
|
+
mtime: st.mtimeMs
|
|
2354
|
+
});
|
|
2355
|
+
} catch {}
|
|
2356
|
+
}
|
|
2357
|
+
} catch {}
|
|
2358
|
+
try {
|
|
2359
|
+
for (const f of readdirSync(projectDir)) {
|
|
2360
|
+
if (!f.endsWith(".jsonl")) continue;
|
|
2361
|
+
const fullPath = join(projectDir, f);
|
|
2362
|
+
try {
|
|
2363
|
+
const st = statSync(fullPath);
|
|
2364
|
+
candidates.push({
|
|
2365
|
+
path: fullPath,
|
|
2366
|
+
mtime: st.mtimeMs
|
|
2367
|
+
});
|
|
2368
|
+
} catch {}
|
|
2369
|
+
}
|
|
2370
|
+
} catch {}
|
|
2371
|
+
if (candidates.length === 0) {
|
|
2372
|
+
process.stderr.write(`[session-summary] No JSONL files found in ${projectDir}\n`);
|
|
2373
|
+
return null;
|
|
2374
|
+
}
|
|
2375
|
+
candidates.sort((a, b) => b.mtime - a.mtime);
|
|
2376
|
+
return candidates[0].path;
|
|
2377
|
+
}
|
|
2378
|
+
/**
|
|
2379
|
+
* Parse a JSONL transcript and extract relevant content.
|
|
2380
|
+
* Filters noise, truncates to model-appropriate size from the end of the file.
|
|
2381
|
+
*/
|
|
2382
|
+
function extractFromJsonl(jsonlPath, tier = "sonnet") {
|
|
2383
|
+
const result = {
|
|
2384
|
+
userMessages: [],
|
|
2385
|
+
filesModified: [],
|
|
2386
|
+
sessionStartTime: ""
|
|
2387
|
+
};
|
|
2388
|
+
let raw;
|
|
2389
|
+
try {
|
|
2390
|
+
raw = readFileSync(jsonlPath, "utf-8");
|
|
2391
|
+
} catch (e) {
|
|
2392
|
+
throw new Error(`Could not read JSONL at ${jsonlPath}: ${e}`);
|
|
2393
|
+
}
|
|
2394
|
+
const maxChars = MAX_JSONL_CHARS[tier] ?? 2e5;
|
|
2395
|
+
if (raw.length > maxChars) {
|
|
2396
|
+
const truncPoint = raw.indexOf("\n", raw.length - maxChars);
|
|
2397
|
+
raw = truncPoint >= 0 ? raw.slice(truncPoint + 1) : raw.slice(-MAX_JSONL_CHARS);
|
|
2398
|
+
}
|
|
2399
|
+
const lines = raw.trim().split("\n");
|
|
2400
|
+
const seenMessages = /* @__PURE__ */ new Set();
|
|
2401
|
+
for (const line of lines) {
|
|
2402
|
+
if (!line.trim()) continue;
|
|
2403
|
+
let entry;
|
|
2404
|
+
try {
|
|
2405
|
+
entry = JSON.parse(line);
|
|
2406
|
+
} catch {
|
|
2407
|
+
continue;
|
|
2408
|
+
}
|
|
2409
|
+
if (entry.timestamp && !result.sessionStartTime) result.sessionStartTime = String(entry.timestamp);
|
|
2410
|
+
if (entry.type === "user") {
|
|
2411
|
+
const msg = entry.message;
|
|
2412
|
+
if (msg?.content) {
|
|
2413
|
+
const text = contentToText(msg.content);
|
|
2414
|
+
if (text && !isNoise(text) && !seenMessages.has(text)) {
|
|
2415
|
+
seenMessages.add(text);
|
|
2416
|
+
result.userMessages.push(text.slice(0, 500));
|
|
2417
|
+
}
|
|
2418
|
+
}
|
|
2419
|
+
}
|
|
2420
|
+
if (entry.type === "assistant") {
|
|
2421
|
+
const msg = entry.message;
|
|
2422
|
+
if (msg?.content && Array.isArray(msg.content)) {
|
|
2423
|
+
for (const block of msg.content) if (block.type === "tool_use") {
|
|
2424
|
+
const name = block.name;
|
|
2425
|
+
const input = block.input;
|
|
2426
|
+
if ((name === "Edit" || name === "Write") && input?.file_path) {
|
|
2427
|
+
const fp = String(input.file_path);
|
|
2428
|
+
if (!result.filesModified.includes(fp)) result.filesModified.push(fp);
|
|
2429
|
+
}
|
|
2430
|
+
}
|
|
2431
|
+
}
|
|
2432
|
+
}
|
|
2433
|
+
}
|
|
2434
|
+
if (result.userMessages.length > MAX_USER_MESSAGES) result.userMessages = result.userMessages.slice(-MAX_USER_MESSAGES);
|
|
2435
|
+
return result;
|
|
2436
|
+
}
|
|
2437
|
+
/** Convert Claude content (string or content block array) to plain text. */
|
|
2438
|
+
function contentToText(content) {
|
|
2439
|
+
if (typeof content === "string") return content;
|
|
2440
|
+
if (Array.isArray(content)) return content.map((c) => {
|
|
2441
|
+
if (typeof c === "string") return c;
|
|
2442
|
+
const block = c;
|
|
2443
|
+
if (block?.text) return String(block.text);
|
|
2444
|
+
if (block?.content) return String(block.content);
|
|
2445
|
+
return "";
|
|
2446
|
+
}).join(" ").trim();
|
|
2447
|
+
return "";
|
|
2448
|
+
}
|
|
2449
|
+
/** Filter out noise entries that shouldn't be included in the summary. */
|
|
2450
|
+
function isNoise(text) {
|
|
2451
|
+
if (!text || text.length < 3) return true;
|
|
2452
|
+
if (text.includes("<task-notification>")) return true;
|
|
2453
|
+
if (text.includes("[object Object]")) return true;
|
|
2454
|
+
if (text.startsWith("<system-reminder>")) return true;
|
|
2455
|
+
if (/^(yes|ok|sure|go|continue|weiter|thanks|thank you)\.?$/i.test(text.trim())) return true;
|
|
2456
|
+
if (text.startsWith("Tool Result:") || text.startsWith("tool_result")) return true;
|
|
2457
|
+
return false;
|
|
2458
|
+
}
|
|
2459
|
+
/**
|
|
2460
|
+
* Get git log for the session period.
|
|
2461
|
+
* Falls back gracefully if git is not available or the dir is not a repo.
|
|
2462
|
+
*/
|
|
2463
|
+
async function getGitContext(cwd, sinceTime) {
|
|
2464
|
+
let since = "6 hours ago";
|
|
2465
|
+
if (sinceTime) {
|
|
2466
|
+
const asNum = Number(sinceTime);
|
|
2467
|
+
if (!isNaN(asNum) && asNum > 1e9) since = (/* @__PURE__ */ new Date(asNum * 1e3)).toISOString();
|
|
2468
|
+
else since = sinceTime;
|
|
2469
|
+
}
|
|
2470
|
+
try {
|
|
2471
|
+
const { execFile: execFileCb } = await import("node:child_process");
|
|
2472
|
+
const { promisify } = await import("node:util");
|
|
2473
|
+
const { stdout } = await promisify(execFileCb)("git", [
|
|
2474
|
+
"log",
|
|
2475
|
+
"--format=%h %ai %s",
|
|
2476
|
+
`--since=${since}`,
|
|
2477
|
+
"--stat",
|
|
2478
|
+
"--no-color"
|
|
2479
|
+
], {
|
|
2480
|
+
cwd,
|
|
2481
|
+
timeout: 1e4,
|
|
2482
|
+
env: {
|
|
2483
|
+
...process.env,
|
|
2484
|
+
GIT_TERMINAL_PROMPT: "0"
|
|
2485
|
+
}
|
|
2486
|
+
});
|
|
2487
|
+
return stdout.trim();
|
|
2488
|
+
} catch {
|
|
2489
|
+
return "";
|
|
2490
|
+
}
|
|
2491
|
+
}
|
|
2492
|
+
/**
|
|
2493
|
+
* Find the `claude` CLI binary.
|
|
2494
|
+
* Checks PATH first, then common installation locations.
|
|
2495
|
+
*/
|
|
2496
|
+
function findClaudeBinary() {
|
|
2497
|
+
const candidates = [
|
|
2498
|
+
join(homedir(), ".local", "bin", "claude"),
|
|
2499
|
+
join(homedir(), ".claude", "local", "claude"),
|
|
2500
|
+
"/usr/local/bin/claude",
|
|
2501
|
+
"/opt/homebrew/bin/claude"
|
|
2502
|
+
];
|
|
2503
|
+
for (const candidate of candidates) try {
|
|
2504
|
+
if (existsSync(candidate)) return candidate;
|
|
2505
|
+
} catch {}
|
|
2506
|
+
return "claude";
|
|
2507
|
+
}
|
|
2508
|
+
/**
|
|
2509
|
+
* Spawn a Claude model via the CLI to generate a session summary.
|
|
2510
|
+
* Pipes the prompt via stdin. Tier selection (resolved to the configured
|
|
2511
|
+
* provider's model id, falling back to the tier alias when no provider is
|
|
2512
|
+
* configured — see planLlmSpawn):
|
|
2513
|
+
* - opus: session end (best quality for final summary, runs once)
|
|
2514
|
+
* - sonnet: auto-compaction (good quality for incremental checkpoints, runs often)
|
|
2515
|
+
* - haiku: fallback / budget mode
|
|
2516
|
+
* Returns the generated text, or null if spawning fails.
|
|
2517
|
+
*/
|
|
2518
|
+
async function spawnSummarizer(prompt, tier = "sonnet") {
|
|
2519
|
+
const claudeBin = findClaudeBinary();
|
|
2520
|
+
if (!claudeBin) {
|
|
2521
|
+
process.stderr.write("[session-summary] Claude CLI not found in PATH or common locations.\n");
|
|
2522
|
+
return null;
|
|
2523
|
+
}
|
|
2524
|
+
let plan;
|
|
2525
|
+
try {
|
|
2526
|
+
plan = await planLlmSpawn(tier);
|
|
2527
|
+
} catch (e) {
|
|
2528
|
+
process.stderr.write(`[session-summary] could not plan ${tier} spawn: ${e}\n`);
|
|
2529
|
+
return null;
|
|
2530
|
+
}
|
|
2531
|
+
const { spawn } = await import("node:child_process");
|
|
2532
|
+
return new Promise((resolve) => {
|
|
2533
|
+
let timer = null;
|
|
2534
|
+
const child = spawn(claudeBin, plan.args, {
|
|
2535
|
+
env: plan.env,
|
|
2536
|
+
stdio: [
|
|
2537
|
+
"pipe",
|
|
2538
|
+
"pipe",
|
|
2539
|
+
"pipe"
|
|
2540
|
+
]
|
|
2541
|
+
});
|
|
2542
|
+
let stdout = "";
|
|
2543
|
+
let stderr = "";
|
|
2544
|
+
child.stdout.on("data", (chunk) => {
|
|
2545
|
+
stdout += chunk.toString();
|
|
2546
|
+
});
|
|
2547
|
+
child.stderr.on("data", (chunk) => {
|
|
2548
|
+
stderr += chunk.toString();
|
|
2549
|
+
});
|
|
2550
|
+
child.on("error", (err) => {
|
|
2551
|
+
if (timer) {
|
|
2552
|
+
clearTimeout(timer);
|
|
2553
|
+
timer = null;
|
|
2554
|
+
}
|
|
2555
|
+
process.stderr.write(`[session-summary] ${plan.model} spawn error: ${err.message}\n`);
|
|
2556
|
+
resolve(null);
|
|
2557
|
+
});
|
|
2558
|
+
child.on("close", (code) => {
|
|
2559
|
+
if (timer) {
|
|
2560
|
+
clearTimeout(timer);
|
|
2561
|
+
timer = null;
|
|
2562
|
+
}
|
|
2563
|
+
if (code !== 0) {
|
|
2564
|
+
process.stderr.write(`[session-summary] ${plan.model} exited with code ${code}: ${stderr.slice(0, 300)}\n`);
|
|
2565
|
+
resolve(null);
|
|
2566
|
+
} else resolve(stdout.trim() || null);
|
|
2567
|
+
});
|
|
2568
|
+
timer = setTimeout(() => {
|
|
2569
|
+
process.stderr.write(`[session-summary] ${plan.model} timed out — killing process.\n`);
|
|
2570
|
+
child.kill("SIGTERM");
|
|
2571
|
+
resolve(null);
|
|
2572
|
+
}, plan.timeoutMs);
|
|
2573
|
+
child.stdin.write(prompt);
|
|
2574
|
+
child.stdin.end();
|
|
2575
|
+
});
|
|
2576
|
+
}
|
|
2577
|
+
/**
|
|
2578
|
+
* Extract the TOPIC: line from the summarizer output.
|
|
2579
|
+
* Returns the topic string, or null if not found.
|
|
2580
|
+
*/
|
|
2581
|
+
function extractTopic(summaryText) {
|
|
2582
|
+
const match = summaryText.match(/^TOPIC:\s*(.+)$/m);
|
|
2583
|
+
if (!match) return null;
|
|
2584
|
+
return match[1].trim();
|
|
2585
|
+
}
|
|
2586
|
+
/**
|
|
2587
|
+
* Extract the topic from an existing session note.
|
|
2588
|
+
* First checks for a <!-- TOPIC: ... --> comment (stored by previous summaries).
|
|
2589
|
+
* Falls back to the H1 "# Session NNNN: Title" line.
|
|
2590
|
+
*
|
|
2591
|
+
* The HTML comment is the reliable source because the H1 gets renamed by
|
|
2592
|
+
* renameSessionNote, which can add/change words and cause false topic shifts.
|
|
2593
|
+
*/
|
|
2594
|
+
function extractExistingNoteTitle(notePath) {
|
|
2595
|
+
try {
|
|
2596
|
+
const content = readFileSync(notePath, "utf-8");
|
|
2597
|
+
const topicComment = content.match(/<!-- TOPIC:\s*(.+?)\s*-->/);
|
|
2598
|
+
if (topicComment) return topicComment[1].trim();
|
|
2599
|
+
const match = content.match(/^# Session \d+:\s*(.+)$/m);
|
|
2600
|
+
if (match) return match[1].trim();
|
|
2601
|
+
} catch {}
|
|
2602
|
+
return null;
|
|
2603
|
+
}
|
|
2604
|
+
/**
|
|
2605
|
+
* Compute word overlap ratio between two topic strings.
|
|
2606
|
+
* Returns a value in [0, 1] — 1.0 means identical word sets.
|
|
2607
|
+
*
|
|
2608
|
+
* Uses lowercased, normalized words. Stop words and very short words
|
|
2609
|
+
* are excluded to avoid false positives on common terms.
|
|
2610
|
+
*/
|
|
2611
|
+
function computeTopicOverlap(topicA, topicB) {
|
|
2612
|
+
const stopWords = new Set([
|
|
2613
|
+
"a",
|
|
2614
|
+
"an",
|
|
2615
|
+
"the",
|
|
2616
|
+
"and",
|
|
2617
|
+
"or",
|
|
2618
|
+
"but",
|
|
2619
|
+
"in",
|
|
2620
|
+
"on",
|
|
2621
|
+
"at",
|
|
2622
|
+
"to",
|
|
2623
|
+
"for",
|
|
2624
|
+
"of",
|
|
2625
|
+
"with",
|
|
2626
|
+
"by",
|
|
2627
|
+
"from",
|
|
2628
|
+
"is",
|
|
2629
|
+
"was",
|
|
2630
|
+
"are",
|
|
2631
|
+
"were",
|
|
2632
|
+
"be",
|
|
2633
|
+
"been",
|
|
2634
|
+
"being",
|
|
2635
|
+
"have",
|
|
2636
|
+
"has",
|
|
2637
|
+
"had",
|
|
2638
|
+
"do",
|
|
2639
|
+
"does",
|
|
2640
|
+
"did",
|
|
2641
|
+
"will",
|
|
2642
|
+
"would",
|
|
2643
|
+
"could",
|
|
2644
|
+
"should",
|
|
2645
|
+
"may",
|
|
2646
|
+
"might",
|
|
2647
|
+
"can",
|
|
2648
|
+
"shall",
|
|
2649
|
+
"this",
|
|
2650
|
+
"that",
|
|
2651
|
+
"these",
|
|
2652
|
+
"those",
|
|
2653
|
+
"it",
|
|
2654
|
+
"its",
|
|
2655
|
+
"new",
|
|
2656
|
+
"session",
|
|
2657
|
+
"work",
|
|
2658
|
+
"done"
|
|
2659
|
+
]);
|
|
2660
|
+
const normalize = (text) => {
|
|
2661
|
+
const words = text.toLowerCase().replace(/[^a-z0-9\s]/g, " ").split(/\s+/).filter((w) => w.length > 2 && !stopWords.has(w));
|
|
2662
|
+
return new Set(words);
|
|
2663
|
+
};
|
|
2664
|
+
const wordsA = normalize(topicA);
|
|
2665
|
+
const wordsB = normalize(topicB);
|
|
2666
|
+
if (wordsA.size === 0 || wordsB.size === 0) return 0;
|
|
2667
|
+
let intersection = 0;
|
|
2668
|
+
for (const w of wordsA) if (wordsB.has(w)) intersection++;
|
|
2669
|
+
const union = new Set([...wordsA, ...wordsB]).size;
|
|
2670
|
+
return union > 0 ? intersection / union : 0;
|
|
2671
|
+
}
|
|
2672
|
+
/** Threshold: below this overlap ratio, we consider topics different. */
|
|
2673
|
+
const TOPIC_OVERLAP_THRESHOLD = .15;
|
|
2674
|
+
/**
|
|
2675
|
+
* Write (or update) the session note with the AI-generated summary.
|
|
2676
|
+
*
|
|
2677
|
+
* Strategy:
|
|
2678
|
+
* - Find the current month's latest note
|
|
2679
|
+
* - If it's from today, compare topics:
|
|
2680
|
+
* - Same topic (overlap >= 30%) → update existing note
|
|
2681
|
+
* - Different topic (overlap < 30%) → create a NEW note
|
|
2682
|
+
* - If it's from a different day, create a new note
|
|
2683
|
+
*/
|
|
2684
|
+
/**
|
|
2685
|
+
* Return true if the summarizer output has a meaningful body — i.e. content
|
|
2686
|
+
* beyond the TOPIC:/title/metadata/horizontal-rule scaffolding.
|
|
2687
|
+
*
|
|
2688
|
+
* A summary that is only headers (no Work Done items) must NOT create or update
|
|
2689
|
+
* a note: doing so births an empty-bodied scaffold that later rename/finalize
|
|
2690
|
+
* can strip to a footer-only stub. This is the born-stub failure mode.
|
|
2691
|
+
*/
|
|
2692
|
+
function summaryHasContent(summaryText) {
|
|
2693
|
+
return summaryText.replace(/^TOPIC:.*$/m, "").replace(/^# Session:.*$/m, "").replace(/^\*\*(Date|Status|Completed):\*\*.*$/gm, "").replace(/^#{1,6}\s.*$/gm, "").replace(/^---$/gm, "").replace(/<!--[\s\S]*?-->/g, "").trim().length > 0;
|
|
2694
|
+
}
|
|
2695
|
+
function writeSessionNote(cwd, summaryText, filesModified, sessionId) {
|
|
2696
|
+
if (!summaryHasContent(summaryText)) {
|
|
2697
|
+
process.stderr.write(`[session-summary] Summary has no meaningful body — skipping note write.\n`);
|
|
2698
|
+
return null;
|
|
2699
|
+
}
|
|
2700
|
+
const notesInfo = findNotesDir$1(cwd);
|
|
2701
|
+
let notePath = sessionId && findNoteBySessionId(notesInfo.path, sessionId) || getCurrentNotePath(notesInfo.path);
|
|
2702
|
+
const today = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
|
|
2703
|
+
const newTopic = extractTopic(summaryText);
|
|
2704
|
+
if (notePath) {
|
|
2705
|
+
const noteFilename = basename(notePath);
|
|
2706
|
+
const dateMatch = noteFilename.match(/(\d{4}-\d{2}-\d{2})/);
|
|
2707
|
+
if ((dateMatch ? dateMatch[1] : "") === today) {
|
|
2708
|
+
const existingTitle = extractExistingNoteTitle(notePath);
|
|
2709
|
+
let topicShifted = false;
|
|
2710
|
+
if (newTopic && existingTitle) {
|
|
2711
|
+
const overlap = computeTopicOverlap(newTopic, existingTitle);
|
|
2712
|
+
process.stderr.write(`[session-summary] Topic overlap: ${(overlap * 100).toFixed(1)}% (new="${newTopic}", existing="${existingTitle}")\n`);
|
|
2713
|
+
if (overlap < TOPIC_OVERLAP_THRESHOLD) {
|
|
2714
|
+
topicShifted = true;
|
|
2715
|
+
process.stderr.write(`[session-summary] Topic shift detected (word overlap) — creating new note.\n`);
|
|
2716
|
+
}
|
|
2717
|
+
}
|
|
2718
|
+
if (!topicShifted) {
|
|
2719
|
+
const boundaryPath = join(notesInfo.path, "topic-boundary.json");
|
|
2720
|
+
if (existsSync(boundaryPath)) try {
|
|
2721
|
+
const boundary = JSON.parse(readFileSync(boundaryPath, "utf-8"));
|
|
2722
|
+
if (boundary.timestamp) {
|
|
2723
|
+
if (Date.now() - new Date(boundary.timestamp).getTime() < 1800 * 1e3) {
|
|
2724
|
+
topicShifted = true;
|
|
2725
|
+
process.stderr.write(`[session-summary] Topic shift detected (boundary marker) — ${boundary.previousProject} → ${boundary.suggestedProject}\n`);
|
|
2726
|
+
}
|
|
2727
|
+
}
|
|
2728
|
+
unlinkSync(boundaryPath);
|
|
2729
|
+
} catch {}
|
|
2730
|
+
}
|
|
2731
|
+
if (topicShifted) notePath = createNoteFromSummary(notesInfo.path, summaryText, sessionId);
|
|
2732
|
+
else {
|
|
2733
|
+
updateNoteWithSummary(notePath, summaryText);
|
|
2734
|
+
process.stderr.write(`[session-summary] Updated existing note: ${noteFilename}\n`);
|
|
2735
|
+
}
|
|
2736
|
+
} else notePath = createNoteFromSummary(notesInfo.path, summaryText, sessionId);
|
|
2737
|
+
} else notePath = createNoteFromSummary(notesInfo.path, summaryText, sessionId);
|
|
2738
|
+
if (notePath) {
|
|
2739
|
+
const titleMatch = summaryText.match(/^# Session:\s*(.+)$/m);
|
|
2740
|
+
if (titleMatch) {
|
|
2741
|
+
const title = titleMatch[1].trim();
|
|
2742
|
+
if (title.length > 5 && title.length < 80) {
|
|
2743
|
+
const newPath = renameSessionNote(notePath, title);
|
|
2744
|
+
if (newPath !== notePath) notePath = newPath;
|
|
2745
|
+
}
|
|
2746
|
+
}
|
|
2747
|
+
}
|
|
2748
|
+
return notePath;
|
|
2749
|
+
}
|
|
2750
|
+
/**
|
|
2751
|
+
* Update an existing session note's Work Done section with AI-generated content.
|
|
2752
|
+
*/
|
|
2753
|
+
function updateNoteWithSummary(notePath, summaryText) {
|
|
2754
|
+
if (!existsSync(notePath)) return;
|
|
2755
|
+
let content = readFileSync(notePath, "utf-8");
|
|
2756
|
+
const newTopic = extractTopic(summaryText);
|
|
2757
|
+
if (newTopic) if (content.includes("<!-- TOPIC:")) content = content.replace(/<!-- TOPIC:.*?-->/, `<!-- TOPIC: ${newTopic} -->`);
|
|
2758
|
+
else content = content.replace(/^(# Session .+)$/m, `$1\n<!-- TOPIC: ${newTopic} -->`);
|
|
2759
|
+
const workDoneMatch = summaryText.match(/## Work Done\n\n([\s\S]*?)(?=\n## Key Decisions|\n## Known Issues|\n\*\*Tags|\n$)/);
|
|
2760
|
+
if (workDoneMatch) {
|
|
2761
|
+
const aiWorkContent = workDoneMatch[1].trim();
|
|
2762
|
+
const sectionHeader = `\n### AI Summary (${(/* @__PURE__ */ new Date()).toISOString().split("T")[1].split(".")[0]})\n\n${aiWorkContent}\n`;
|
|
2763
|
+
const nextStepsIdx = content.indexOf("## Next Steps");
|
|
2764
|
+
const knownIssuesIdx = content.indexOf("## Known Issues");
|
|
2765
|
+
const insertBefore = knownIssuesIdx !== -1 ? knownIssuesIdx : nextStepsIdx !== -1 ? nextStepsIdx : content.length;
|
|
2766
|
+
content = content.slice(0, insertBefore) + sectionHeader + "\n" + content.slice(insertBefore);
|
|
2767
|
+
}
|
|
2768
|
+
const decisionsMatch = summaryText.match(/## Key Decisions\n\n([\s\S]*?)(?=\n## Known Issues|\n\*\*Tags|\n$)/);
|
|
2769
|
+
if (decisionsMatch) {
|
|
2770
|
+
const decisions = decisionsMatch[1].trim();
|
|
2771
|
+
if (decisions && !content.includes("## Key Decisions")) {
|
|
2772
|
+
const nextStepsIdx = content.indexOf("## Next Steps");
|
|
2773
|
+
const insertAt = nextStepsIdx !== -1 ? nextStepsIdx : content.length;
|
|
2774
|
+
content = content.slice(0, insertAt) + `## Key Decisions\n\n${decisions}\n\n` + content.slice(insertAt);
|
|
2775
|
+
}
|
|
2776
|
+
}
|
|
2777
|
+
const issuesMatch = summaryText.match(/## Known Issues\n\n([\s\S]*?)(?=\n\*\*Tags|\n$)/);
|
|
2778
|
+
if (issuesMatch) {
|
|
2779
|
+
const issues = issuesMatch[1].trim();
|
|
2780
|
+
if (issues && !content.includes("## Known Issues")) {
|
|
2781
|
+
const nextStepsIdx = content.indexOf("## Next Steps");
|
|
2782
|
+
const insertAt = nextStepsIdx !== -1 ? nextStepsIdx : content.length;
|
|
2783
|
+
content = content.slice(0, insertAt) + `## Known Issues\n\n${issues}\n\n` + content.slice(insertAt);
|
|
2784
|
+
}
|
|
2785
|
+
}
|
|
2786
|
+
writeFileSync(notePath, content, "utf-8");
|
|
2787
|
+
}
|
|
2788
|
+
/**
|
|
2789
|
+
* Create a brand new session note from the AI summary.
|
|
2790
|
+
*/
|
|
2791
|
+
/**
|
|
2792
|
+
* Find the note this session already owns, by the marker its first write left.
|
|
2793
|
+
*
|
|
2794
|
+
* The previous resolver, getCurrentNotePath, returned the numerically highest
|
|
2795
|
+
* note in the month directory. That is a position, not an identity, and it is
|
|
2796
|
+
* why one session produced many notes: whenever a session's own note was not
|
|
2797
|
+
* the current maximum — two sessions in one project, or a number collision, of
|
|
2798
|
+
* which one corpus had 110 — the lookup missed and the checkpoint created a
|
|
2799
|
+
* new file instead of updating. Measured consequence in that corpus: 303 of
|
|
2800
|
+
* 407 notes sat in 31 same-title groups, 48 of them sharing a single title.
|
|
2801
|
+
*
|
|
2802
|
+
* Matching on the session id makes the answer exact: a session either has a
|
|
2803
|
+
* note or it does not, regardless of what else the directory contains.
|
|
2804
|
+
*/
|
|
2805
|
+
function findNoteBySessionId(notesDir, sessionId) {
|
|
2806
|
+
if (!sessionId || !existsSync(notesDir)) return null;
|
|
2807
|
+
const marker = `<!-- SESSION: ${sessionId} -->`;
|
|
2808
|
+
const now = /* @__PURE__ */ new Date();
|
|
2809
|
+
const dirs = [0, -1].map((delta) => {
|
|
2810
|
+
const d = new Date(now.getFullYear(), now.getMonth() + delta, 1);
|
|
2811
|
+
return join(notesDir, String(d.getFullYear()), String(d.getMonth() + 1).padStart(2, "0"));
|
|
2812
|
+
});
|
|
2813
|
+
for (const dir of dirs) {
|
|
2814
|
+
if (!existsSync(dir)) continue;
|
|
2815
|
+
for (const f of readdirSync(dir)) {
|
|
2816
|
+
if (!f.endsWith(".md")) continue;
|
|
2817
|
+
const p = join(dir, f);
|
|
2818
|
+
try {
|
|
2819
|
+
if (readFileSync(p, "utf-8").includes(marker)) return p;
|
|
2820
|
+
} catch {}
|
|
2821
|
+
}
|
|
2822
|
+
}
|
|
2823
|
+
return null;
|
|
2824
|
+
}
|
|
2825
|
+
function createNoteFromSummary(notesDir, summaryText, sessionId) {
|
|
2826
|
+
try {
|
|
2827
|
+
const notePath = createSessionNote(notesDir, "New Session");
|
|
2828
|
+
const noteFilename = basename(notePath);
|
|
2829
|
+
const numberMatch = noteFilename.match(/^(\d+)/);
|
|
2830
|
+
const noteNumber = numberMatch ? numberMatch[1] : "0000";
|
|
2831
|
+
const titleMatch = summaryText.match(/^# Session:\s*(.+)$/m);
|
|
2832
|
+
const title = titleMatch ? titleMatch[1].trim() : "New Session";
|
|
2833
|
+
const date = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
|
|
2834
|
+
const topic = extractTopic(summaryText);
|
|
2835
|
+
const aiBody = summaryText.replace(/^TOPIC:.*$/m, "").replace(/^# Session:.*$/m, "").replace(/^\*\*Date:\*\*.*$/m, "").replace(/^\*\*Status:\*\*.*$/m, "").replace(/^---$/m, "").trim();
|
|
2836
|
+
writeFileSync(notePath, `# Session ${noteNumber}: ${title}
|
|
2837
|
+
${topic ? `<!-- TOPIC: ${topic} -->` : ""}${sessionId ? `\n<!-- SESSION: ${sessionId} -->` : ""}
|
|
2838
|
+
|
|
2839
|
+
**Date:** ${date}
|
|
2840
|
+
**Status:** In Progress
|
|
2841
|
+
|
|
2842
|
+
---
|
|
2843
|
+
|
|
2844
|
+
${aiBody}
|
|
2845
|
+
|
|
2846
|
+
---
|
|
2847
|
+
|
|
2848
|
+
## Next Steps
|
|
2849
|
+
|
|
2850
|
+
<!-- To be filled at session end -->
|
|
2851
|
+
|
|
2852
|
+
---
|
|
2853
|
+
|
|
2854
|
+
**Tags:** #Session
|
|
2855
|
+
`, "utf-8");
|
|
2856
|
+
process.stderr.write(`[session-summary] Created AI-powered note: ${noteFilename}\n`);
|
|
2857
|
+
return notePath;
|
|
2858
|
+
} catch (e) {
|
|
2859
|
+
process.stderr.write(`[session-summary] Failed to create note: ${e}\n`);
|
|
2860
|
+
return null;
|
|
2861
|
+
}
|
|
2862
|
+
}
|
|
2863
|
+
/**
|
|
2864
|
+
* Look up the integer project_id from the registry DB for a given slug.
|
|
2865
|
+
* Returns null if not found or registryDb is not yet initialized.
|
|
2866
|
+
*/
|
|
2867
|
+
function lookupProjectId(slug) {
|
|
2868
|
+
try {
|
|
2869
|
+
if (!registryDb) return null;
|
|
2870
|
+
return registryDb.prepare("SELECT id FROM projects WHERE slug = ? LIMIT 1").get(slug)?.id ?? null;
|
|
2871
|
+
} catch {
|
|
2872
|
+
return null;
|
|
2873
|
+
}
|
|
2874
|
+
}
|
|
2875
|
+
/**
|
|
2876
|
+
* Extract structured KG triples from a session summary and store them.
|
|
2877
|
+
*
|
|
2878
|
+
* This is best-effort: any error is logged but never propagated.
|
|
2879
|
+
* Requires Postgres backend — silently no-ops on SQLite.
|
|
2880
|
+
*/
|
|
2881
|
+
async function extractAndStoreTriples(params) {
|
|
2882
|
+
try {
|
|
2883
|
+
if (!storageBackend || storageBackend.backendType !== "postgres") return;
|
|
2884
|
+
const pool = storageBackend.getPool?.();
|
|
2885
|
+
if (!pool) {
|
|
2886
|
+
process.stderr.write("[session-summary] Triple extraction: no pool available.\n");
|
|
2887
|
+
return;
|
|
2888
|
+
}
|
|
2889
|
+
const cfg = daemonConfig;
|
|
2890
|
+
if (cfg && cfg.kg_extraction_enabled === false) {
|
|
2891
|
+
process.stderr.write("[session-summary] Triple extraction disabled via kg_extraction_enabled=false.\n");
|
|
2892
|
+
return;
|
|
2893
|
+
}
|
|
2894
|
+
const federationDb = openFederation();
|
|
2895
|
+
let result;
|
|
2896
|
+
try {
|
|
2897
|
+
result = await extractAndStoreTriples$1(pool, {
|
|
2898
|
+
summaryText: params.summaryText,
|
|
2899
|
+
projectSlug: params.projectSlug,
|
|
2900
|
+
projectId: params.projectId,
|
|
2901
|
+
sessionId: params.sessionId,
|
|
2902
|
+
gitLog: params.gitLog,
|
|
2903
|
+
model: "sonnet",
|
|
2904
|
+
federationDb
|
|
2905
|
+
});
|
|
2906
|
+
} finally {
|
|
2907
|
+
federationDb.close();
|
|
2908
|
+
}
|
|
2909
|
+
process.stderr.write(`[session-summary] Triple extraction complete: ${result.extracted} extracted, ${result.added} added, ${result.superseded} superseded.\n`);
|
|
2910
|
+
} catch (err) {
|
|
2911
|
+
process.stderr.write(`[session-summary] Triple extraction failed: ${err}\n`);
|
|
2912
|
+
}
|
|
2913
|
+
}
|
|
2914
|
+
/**
|
|
2915
|
+
* Process a `session-summary` work item.
|
|
2916
|
+
*
|
|
2917
|
+
* This is the main function called by work-queue-worker.ts.
|
|
2918
|
+
* Throws on fatal errors (work queue will retry with backoff).
|
|
2919
|
+
*/
|
|
2920
|
+
async function handleSessionSummary(payload) {
|
|
2921
|
+
const { cwd, sessionId, projectSlug, transcriptPath, force } = payload;
|
|
2922
|
+
if (!cwd) throw new Error("session-summary payload missing cwd");
|
|
2923
|
+
process.stderr.write(`[session-summary] Starting for ${cwd}${sessionId ? ` (session=${sessionId})` : ""}${force ? " (force=true)" : ""}\n`);
|
|
2924
|
+
if (!force && isOnCooldown(cwd)) {
|
|
2925
|
+
process.stderr.write("[session-summary] Skipping — last summary was less than 30 minutes ago.\n");
|
|
2926
|
+
return;
|
|
2927
|
+
}
|
|
2928
|
+
let jsonlPath = transcriptPath || null;
|
|
2929
|
+
if (jsonlPath && !existsSync(jsonlPath)) {
|
|
2930
|
+
process.stderr.write(`[session-summary] Provided transcript path not found: ${jsonlPath}\n`);
|
|
2931
|
+
jsonlPath = null;
|
|
2932
|
+
}
|
|
2933
|
+
if (!jsonlPath) jsonlPath = findLatestJsonl(cwd);
|
|
2934
|
+
if (!jsonlPath) {
|
|
2935
|
+
process.stderr.write("[session-summary] No JSONL transcript found — skipping.\n");
|
|
2936
|
+
return;
|
|
2937
|
+
}
|
|
2938
|
+
process.stderr.write(`[session-summary] Using transcript: ${jsonlPath}\n`);
|
|
2939
|
+
const selectedModel = payload.model ?? (force ? "haiku" : "sonnet");
|
|
2940
|
+
const extracted = extractFromJsonl(jsonlPath, selectedModel);
|
|
2941
|
+
if (extracted.userMessages.length === 0) {
|
|
2942
|
+
process.stderr.write("[session-summary] No user messages found in transcript — skipping.\n");
|
|
2943
|
+
return;
|
|
2944
|
+
}
|
|
2945
|
+
process.stderr.write(`[session-summary] Extracted ${extracted.userMessages.length} user messages, ${extracted.filesModified.length} modified files.\n`);
|
|
2946
|
+
const gitLog = await getGitContext(cwd, extracted.sessionStartTime);
|
|
2947
|
+
if (gitLog) process.stderr.write(`[session-summary] Got git context (${gitLog.split("\n").length} lines).\n`);
|
|
2948
|
+
const today = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
|
|
2949
|
+
const existingNotePath = getCurrentNotePath(findNotesDir$1(cwd).path);
|
|
2950
|
+
let existingNote;
|
|
2951
|
+
if (existingNotePath) {
|
|
2952
|
+
const dateMatch = basename(existingNotePath).match(/(\d{4}-\d{2}-\d{2})/);
|
|
2953
|
+
if (dateMatch && dateMatch[1] === today) try {
|
|
2954
|
+
existingNote = readFileSync(existingNotePath, "utf-8");
|
|
2955
|
+
} catch {}
|
|
2956
|
+
}
|
|
2957
|
+
const prompt = buildSessionSummaryPrompt({
|
|
2958
|
+
userMessages: extracted.userMessages,
|
|
2959
|
+
gitLog,
|
|
2960
|
+
cwd,
|
|
2961
|
+
date: today,
|
|
2962
|
+
filesModified: extracted.filesModified,
|
|
2963
|
+
existingNote
|
|
2964
|
+
});
|
|
2965
|
+
process.stderr.write(`[session-summary] Sending ${prompt.length} char prompt to ${selectedModel}...\n`);
|
|
2966
|
+
const summaryText = await spawnSummarizer(prompt, selectedModel);
|
|
2967
|
+
if (!summaryText) {
|
|
2968
|
+
process.stderr.write(`[session-summary] ${selectedModel} did not produce output — falling back to mechanical checkpoint.\n`);
|
|
2969
|
+
markCooldown(cwd);
|
|
2970
|
+
return;
|
|
2971
|
+
}
|
|
2972
|
+
process.stderr.write(`[session-summary] ${selectedModel} produced ${summaryText.length} char summary.\n`);
|
|
2973
|
+
const notePath = writeSessionNote(cwd, summaryText, extracted.filesModified, sessionId);
|
|
2974
|
+
if (notePath) process.stderr.write(`[session-summary] Session note written: ${basename(notePath)}\n`);
|
|
2975
|
+
await extractAndStoreTriples({
|
|
2976
|
+
summaryText,
|
|
2977
|
+
projectSlug: projectSlug ?? basename(cwd),
|
|
2978
|
+
projectId: projectSlug ? lookupProjectId(projectSlug) : null,
|
|
2979
|
+
sessionId: sessionId ?? cwd,
|
|
2980
|
+
gitLog,
|
|
2981
|
+
model: selectedModel
|
|
2982
|
+
});
|
|
2983
|
+
markCooldown(cwd);
|
|
2984
|
+
process.stderr.write("[session-summary] Done.\n");
|
|
2985
|
+
}
|
|
2986
|
+
|
|
2987
|
+
//#endregion
|
|
2988
|
+
//#region src/daemon/work-queue.ts
|
|
2989
|
+
/**
|
|
2990
|
+
* work-queue.ts — Persistent work queue for the PAI Daemon
|
|
2991
|
+
*
|
|
2992
|
+
* Provides a durable, file-backed queue that survives daemon restarts.
|
|
2993
|
+
* Items are processed sequentially to avoid concurrent writes to the same
|
|
2994
|
+
* session note. Failed items are retried with exponential backoff.
|
|
2995
|
+
*
|
|
2996
|
+
* Queue file: under PAI_HOME (~/.claude/pai/work-queue.json), falling back
|
|
2997
|
+
* to the pre-2026-09-19 ~/.config/pai/work-queue.json location.
|
|
2998
|
+
* Written atomically (write temp → rename) to prevent corruption.
|
|
2999
|
+
*/
|
|
3000
|
+
function oldQueueFile() {
|
|
3001
|
+
return join(homedir(), ".config", "pai", "work-queue.json");
|
|
3002
|
+
}
|
|
3003
|
+
const QUEUE_FILE = resolvePaiFile(paiHomePath("work-queue.json"), [oldQueueFile()], "pai config migrate");
|
|
3004
|
+
function migrateWorkQueue(opts = {}) {
|
|
3005
|
+
return migratePaiFile(paiHomePath("work-queue.json"), [oldQueueFile()], opts);
|
|
3006
|
+
}
|
|
3007
|
+
const MAX_QUEUE_SIZE = 1e3;
|
|
3008
|
+
const MAX_QUEUE_FILE_BYTES = 1024 * 1024;
|
|
3009
|
+
const COMPLETED_TTL_MS = 3600 * 1e3;
|
|
3010
|
+
const FAILED_TTL_MS = 1440 * 60 * 1e3;
|
|
3011
|
+
/** Backoff delays in ms by attempt number (0-indexed). */
|
|
3012
|
+
const BACKOFF_MS = [
|
|
3013
|
+
5e3,
|
|
3014
|
+
3e4,
|
|
3015
|
+
3e5
|
|
3016
|
+
];
|
|
3017
|
+
let _queue = [];
|
|
3018
|
+
let _dirty = false;
|
|
3019
|
+
/** Load queue from disk. Call once at daemon startup. */
|
|
3020
|
+
function loadQueue() {
|
|
3021
|
+
if (!existsSync(QUEUE_FILE)) {
|
|
3022
|
+
_queue = [];
|
|
3023
|
+
return;
|
|
3024
|
+
}
|
|
3025
|
+
try {
|
|
3026
|
+
const raw = readFileSync(QUEUE_FILE, "utf-8");
|
|
3027
|
+
const parsed = JSON.parse(raw);
|
|
3028
|
+
if (!Array.isArray(parsed)) {
|
|
3029
|
+
process.stderr.write("[work-queue] Invalid queue file format — starting empty.\n");
|
|
3030
|
+
_queue = [];
|
|
3031
|
+
return;
|
|
3032
|
+
}
|
|
3033
|
+
_queue = parsed.map((item) => {
|
|
3034
|
+
if (item.status === "processing") return {
|
|
3035
|
+
...item,
|
|
3036
|
+
status: "pending"
|
|
3037
|
+
};
|
|
3038
|
+
return item;
|
|
3039
|
+
});
|
|
3040
|
+
const stats = getStats();
|
|
3041
|
+
process.stderr.write(`[work-queue] Loaded ${_queue.length} items from disk (pending=${stats.pending}, failed=${stats.failed}).\n`);
|
|
3042
|
+
} catch (e) {
|
|
3043
|
+
process.stderr.write(`[work-queue] Could not load queue file: ${e}\n`);
|
|
3044
|
+
_queue = [];
|
|
3045
|
+
}
|
|
3046
|
+
}
|
|
3047
|
+
/** Persist queue to disk atomically. */
|
|
3048
|
+
function saveQueue() {
|
|
3049
|
+
const dir = dirname(QUEUE_FILE);
|
|
3050
|
+
if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
|
|
3051
|
+
const tmpFile = QUEUE_FILE + ".tmp";
|
|
3052
|
+
try {
|
|
3053
|
+
writeFileSync(tmpFile, JSON.stringify(_queue, null, 2), "utf-8");
|
|
3054
|
+
renameSync(tmpFile, QUEUE_FILE);
|
|
3055
|
+
_dirty = false;
|
|
3056
|
+
} catch (e) {
|
|
3057
|
+
process.stderr.write(`[work-queue] Could not persist queue: ${e}\n`);
|
|
3058
|
+
}
|
|
3059
|
+
}
|
|
3060
|
+
/** Persist only if there are unsaved changes. */
|
|
3061
|
+
function saveIfDirty() {
|
|
3062
|
+
if (_dirty) saveQueue();
|
|
3063
|
+
}
|
|
3064
|
+
/**
|
|
3065
|
+
* Enforce the maximum queue size cap.
|
|
3066
|
+
* Strategy: first drop oldest completed, then oldest low-priority pending.
|
|
3067
|
+
*/
|
|
3068
|
+
function enforceMaxSize() {
|
|
3069
|
+
if (_queue.length <= MAX_QUEUE_SIZE) return;
|
|
3070
|
+
const excess = _queue.length - MAX_QUEUE_SIZE;
|
|
3071
|
+
const toDropCompleted = _queue.filter((i) => i.status === "completed").sort((a, b) => a.createdAt.localeCompare(b.createdAt)).slice(0, excess);
|
|
3072
|
+
const dropIds = new Set(toDropCompleted.map((i) => i.id));
|
|
3073
|
+
_queue = _queue.filter((i) => !dropIds.has(i.id));
|
|
3074
|
+
if (_queue.length <= MAX_QUEUE_SIZE) return;
|
|
3075
|
+
const remainingExcess = _queue.length - MAX_QUEUE_SIZE;
|
|
3076
|
+
const toDropLow = _queue.filter((i) => i.status === "pending" && i.priority >= 4).sort((a, b) => a.priority - b.priority || a.createdAt.localeCompare(b.createdAt)).slice(0, remainingExcess);
|
|
3077
|
+
const dropLowIds = new Set(toDropLow.map((i) => i.id));
|
|
3078
|
+
_queue = _queue.filter((i) => !dropLowIds.has(i.id));
|
|
3079
|
+
process.stderr.write(`[work-queue] Pruned queue to ${_queue.length} items (cap=${MAX_QUEUE_SIZE}).\n`);
|
|
3080
|
+
}
|
|
3081
|
+
/**
|
|
3082
|
+
* Add a new work item to the queue.
|
|
3083
|
+
* Returns the created WorkItem.
|
|
3084
|
+
*/
|
|
3085
|
+
function enqueue(params) {
|
|
3086
|
+
const item = {
|
|
3087
|
+
id: randomUUID(),
|
|
3088
|
+
type: params.type,
|
|
3089
|
+
priority: params.priority ?? 3,
|
|
3090
|
+
payload: params.payload,
|
|
3091
|
+
status: "pending",
|
|
3092
|
+
createdAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
3093
|
+
attempts: 0,
|
|
3094
|
+
maxAttempts: params.maxAttempts ?? 3
|
|
3095
|
+
};
|
|
3096
|
+
_queue.push(item);
|
|
3097
|
+
enforceMaxSize();
|
|
3098
|
+
_dirty = true;
|
|
3099
|
+
saveIfDirty();
|
|
3100
|
+
process.stderr.write(`[work-queue] Enqueued ${item.type} (id=${item.id}, priority=${item.priority}).\n`);
|
|
3101
|
+
return item;
|
|
3102
|
+
}
|
|
3103
|
+
/**
|
|
3104
|
+
* Pick the next pending item that is ready to process (respects nextRetryAt).
|
|
3105
|
+
* Returns null if no eligible item exists.
|
|
3106
|
+
* Highest priority (lowest number) is processed first; ties broken by createdAt.
|
|
3107
|
+
*/
|
|
3108
|
+
function dequeue() {
|
|
3109
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
3110
|
+
const eligible = _queue.filter((i) => {
|
|
3111
|
+
if (i.status !== "pending") return false;
|
|
3112
|
+
if (i.nextRetryAt && i.nextRetryAt > now) return false;
|
|
3113
|
+
return true;
|
|
3114
|
+
}).sort((a, b) => {
|
|
3115
|
+
if (a.priority !== b.priority) return a.priority - b.priority;
|
|
3116
|
+
return a.createdAt.localeCompare(b.createdAt);
|
|
3117
|
+
});
|
|
3118
|
+
if (eligible.length === 0) return null;
|
|
3119
|
+
const item = eligible[0];
|
|
3120
|
+
item.status = "processing";
|
|
3121
|
+
item.attempts += 1;
|
|
3122
|
+
_dirty = true;
|
|
3123
|
+
saveIfDirty();
|
|
3124
|
+
return item;
|
|
3125
|
+
}
|
|
3126
|
+
/**
|
|
3127
|
+
* Mark an item as completed.
|
|
3128
|
+
*/
|
|
3129
|
+
function markCompleted(id) {
|
|
3130
|
+
const item = _queue.find((i) => i.id === id);
|
|
3131
|
+
if (!item) return;
|
|
3132
|
+
item.status = "completed";
|
|
3133
|
+
item.completedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
3134
|
+
item.error = void 0;
|
|
3135
|
+
_dirty = true;
|
|
3136
|
+
saveIfDirty();
|
|
3137
|
+
}
|
|
3138
|
+
/**
|
|
3139
|
+
* Mark an item as failed.
|
|
3140
|
+
* If attempts < maxAttempts, schedules a retry with exponential backoff.
|
|
3141
|
+
* Otherwise, leaves status as 'failed'.
|
|
3142
|
+
*/
|
|
3143
|
+
function markFailed(id, errorMsg) {
|
|
3144
|
+
const item = _queue.find((i) => i.id === id);
|
|
3145
|
+
if (!item) return;
|
|
3146
|
+
item.error = errorMsg;
|
|
3147
|
+
if (item.attempts < item.maxAttempts) {
|
|
3148
|
+
const backoffMs = BACKOFF_MS[item.attempts - 1] ?? BACKOFF_MS[BACKOFF_MS.length - 1];
|
|
3149
|
+
item.status = "pending";
|
|
3150
|
+
item.nextRetryAt = new Date(Date.now() + backoffMs).toISOString();
|
|
3151
|
+
process.stderr.write(`[work-queue] Item ${id} failed (attempt ${item.attempts}/${item.maxAttempts}), retry in ${backoffMs / 1e3}s: ${errorMsg}\n`);
|
|
3152
|
+
} else {
|
|
3153
|
+
item.status = "failed";
|
|
3154
|
+
process.stderr.write(`[work-queue] Item ${id} exhausted retries (${item.maxAttempts} attempts): ${errorMsg}\n`);
|
|
3155
|
+
}
|
|
3156
|
+
_dirty = true;
|
|
3157
|
+
saveIfDirty();
|
|
3158
|
+
}
|
|
3159
|
+
function getStats() {
|
|
3160
|
+
const stats = {
|
|
3161
|
+
pending: 0,
|
|
3162
|
+
processing: 0,
|
|
3163
|
+
completed: 0,
|
|
3164
|
+
failed: 0,
|
|
3165
|
+
total: _queue.length
|
|
3166
|
+
};
|
|
3167
|
+
for (const item of _queue) stats[item.status]++;
|
|
3168
|
+
return stats;
|
|
3169
|
+
}
|
|
3170
|
+
/**
|
|
3171
|
+
* Returns true if any pending or processing item of the given type exists.
|
|
3172
|
+
* Used for debouncing work items that are expensive to run concurrently.
|
|
3173
|
+
*/
|
|
3174
|
+
function hasPendingOrProcessingOfType(type) {
|
|
3175
|
+
return _queue.some((i) => i.type === type && (i.status === "pending" || i.status === "processing"));
|
|
3176
|
+
}
|
|
3177
|
+
/**
|
|
3178
|
+
* Remove completed and permanently-failed items older than their TTL.
|
|
3179
|
+
* Also force-cleans all completed items if the queue file exceeds 1 MB.
|
|
3180
|
+
*/
|
|
3181
|
+
function cleanup() {
|
|
3182
|
+
const now = Date.now();
|
|
3183
|
+
const before = _queue.length;
|
|
3184
|
+
let forceCleanCompleted = false;
|
|
3185
|
+
try {
|
|
3186
|
+
if (existsSync(QUEUE_FILE)) {
|
|
3187
|
+
const { size } = statSync(QUEUE_FILE);
|
|
3188
|
+
if (size > MAX_QUEUE_FILE_BYTES) {
|
|
3189
|
+
forceCleanCompleted = true;
|
|
3190
|
+
process.stderr.write(`[work-queue] Queue file exceeds 1 MB (${size} bytes) — force-cleaning completed items.\n`);
|
|
3191
|
+
}
|
|
3192
|
+
}
|
|
3193
|
+
} catch {}
|
|
3194
|
+
_queue = _queue.filter((item) => {
|
|
3195
|
+
if (item.status === "completed") {
|
|
3196
|
+
if (forceCleanCompleted) return false;
|
|
3197
|
+
return now - (item.completedAt ? new Date(item.completedAt).getTime() : 0) < COMPLETED_TTL_MS;
|
|
3198
|
+
}
|
|
3199
|
+
if (item.status === "failed") return now - new Date(item.createdAt).getTime() < FAILED_TTL_MS;
|
|
3200
|
+
return true;
|
|
3201
|
+
});
|
|
3202
|
+
const removed = before - _queue.length;
|
|
3203
|
+
const stats = getStats();
|
|
3204
|
+
if (removed > 0 || before === 0) process.stderr.write(`[work-queue] Cleanup: removed ${removed} items. Queue stats: pending=${stats.pending}, processing=${stats.processing}, completed=${stats.completed}, failed=${stats.failed}.\n`);
|
|
3205
|
+
_dirty = removed > 0;
|
|
3206
|
+
saveIfDirty();
|
|
3207
|
+
}
|
|
3208
|
+
|
|
3209
|
+
//#endregion
|
|
3210
|
+
//#region src/hooks/ts/lib/context-handover-cache.ts
|
|
3211
|
+
/**
|
|
3212
|
+
* context-handover-cache.ts — the well-known file where the threshold-
|
|
3213
|
+
* triggered pre-compaction handover (see ../../../daemon/context-handover-
|
|
3214
|
+
* worker.ts) is written, and where context-compression-hook.ts looks for it
|
|
3215
|
+
* at compaction time.
|
|
3216
|
+
*
|
|
3217
|
+
* Deliberately dependency-light (fs/os/path only). The daemon worker that
|
|
3218
|
+
* WRITES this file needs the heavier machinery in session-summary-worker.ts
|
|
3219
|
+
* (spawning Claude, git log, etc.), but the PreCompact hook that READS it
|
|
3220
|
+
* runs as a short-lived process on every compaction and must not drag in
|
|
3221
|
+
* daemon state, database pools, or anything else that module graph carries —
|
|
3222
|
+
* this file is the shared seam so neither side has to.
|
|
3223
|
+
*/
|
|
3224
|
+
function contextHandoverCachePath(sessionId) {
|
|
3225
|
+
return join(tmpdir(), `pai-context-handover-${sessionId}.json`);
|
|
3226
|
+
}
|
|
3227
|
+
function readContextHandoverCache(sessionId) {
|
|
3228
|
+
const path = contextHandoverCachePath(sessionId);
|
|
3229
|
+
if (!existsSync(path)) return null;
|
|
3230
|
+
try {
|
|
3231
|
+
return JSON.parse(readFileSync(path, "utf-8"));
|
|
3232
|
+
} catch {
|
|
3233
|
+
return null;
|
|
3234
|
+
}
|
|
3235
|
+
}
|
|
3236
|
+
function writeContextHandoverCache(cache) {
|
|
3237
|
+
writeFileSync(contextHandoverCachePath(cache.sessionId), JSON.stringify(cache, null, 2), "utf-8");
|
|
3238
|
+
}
|
|
3239
|
+
|
|
3240
|
+
//#endregion
|
|
3241
|
+
export { archiveSessionFilesToSessionsDir as A, claudeProjectsDir as B, findLatestNote as C, appendCheckpoint as D, addWorkToSessionNote as E, performScan as F, scanTranscriptFolders as H, resolveHome as I, saveScanConfig as L, cmdScan as M, loadScanConfig as N, finalizeSessionNote as O, migrateScanConfig as P, upsertProject as R, applyContinue as S, readBodyFile as T, transcriptFiles as U, findMovedProjects as V, spawnSummarizer as _, enqueue as a, updateTodoContinue as b, loadQueue as c, migrateWorkQueue as d, contentToText as f, migrateSummaryCooldowns as g, handleSessionSummary as h, dequeue as i, findNotesDir$1 as j, getCurrentNotePath as k, markCompleted as l, getGitContext as m, writeContextHandoverCache as n, getStats as o, findLatestJsonl as p, cleanup as r, hasPendingOrProcessingOfType as s, readContextHandoverCache as t, markFailed as u, extractAndStoreTriples$1 as v, findNotesDir as w, appendCheckpointToNote as x, sessionIdFromTranscript as y, upsertSession as z };
|
|
3242
|
+
//# sourceMappingURL=context-handover-cache-B9NKSjwR.mjs.map
|