cognitive-core 0.2.1 → 0.2.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (332) hide show
  1. package/dist/atlas.d.ts +10 -0
  2. package/dist/atlas.d.ts.map +1 -1
  3. package/dist/atlas.js +65 -0
  4. package/dist/atlas.js.map +1 -1
  5. package/dist/bin/cognitive-core.js +0 -0
  6. package/dist/memory/curated-loader.d.ts +21 -4
  7. package/dist/memory/curated-loader.d.ts.map +1 -1
  8. package/dist/memory/curated-loader.js +53 -16
  9. package/dist/memory/curated-loader.js.map +1 -1
  10. package/dist/memory/index.d.ts +2 -1
  11. package/dist/memory/index.d.ts.map +1 -1
  12. package/dist/memory/index.js +3 -1
  13. package/dist/memory/index.js.map +1 -1
  14. package/dist/memory/playbook.d.ts +6 -0
  15. package/dist/memory/playbook.d.ts.map +1 -1
  16. package/dist/memory/playbook.js +15 -0
  17. package/dist/memory/playbook.js.map +1 -1
  18. package/dist/memory/source-resolver.d.ts +120 -0
  19. package/dist/memory/source-resolver.d.ts.map +1 -0
  20. package/dist/memory/source-resolver.js +300 -0
  21. package/dist/memory/source-resolver.js.map +1 -0
  22. package/dist/types/config.d.ts +141 -0
  23. package/dist/types/config.d.ts.map +1 -1
  24. package/dist/types/config.js +40 -0
  25. package/dist/types/config.js.map +1 -1
  26. package/dist/types/index.d.ts +1 -1
  27. package/dist/types/index.d.ts.map +1 -1
  28. package/dist/types/index.js +1 -1
  29. package/dist/types/index.js.map +1 -1
  30. package/dist/workspace/types.d.ts +12 -54
  31. package/dist/workspace/types.d.ts.map +1 -1
  32. package/dist/workspace/types.js.map +1 -1
  33. package/package.json +3 -3
  34. package/playbooks/compound-engineering/adversarial-review.json +51 -0
  35. package/playbooks/compound-engineering/agent-native-architecture.json +59 -0
  36. package/playbooks/compound-engineering/agent-native-review.json +54 -0
  37. package/playbooks/compound-engineering/api-contract-review.json +52 -0
  38. package/playbooks/compound-engineering/brainstorm-requirements.json +55 -0
  39. package/playbooks/compound-engineering/bug-reproduction.json +62 -0
  40. package/playbooks/compound-engineering/confidence-calibration.json +49 -0
  41. package/playbooks/compound-engineering/correctness-review.json +49 -0
  42. package/playbooks/compound-engineering/data-migration-safety.json +59 -0
  43. package/playbooks/compound-engineering/deployment-verification.json +63 -0
  44. package/playbooks/compound-engineering/error-recovery-patterns.json +53 -0
  45. package/playbooks/compound-engineering/implementation-planning.json +64 -0
  46. package/playbooks/compound-engineering/issue-pattern-analysis.json +53 -0
  47. package/playbooks/compound-engineering/knowledge-compounding.json +63 -0
  48. package/playbooks/compound-engineering/learnings-research.json +54 -0
  49. package/playbooks/compound-engineering/maintainability-review.json +49 -0
  50. package/playbooks/compound-engineering/performance-review.json +54 -0
  51. package/playbooks/compound-engineering/plan-adversarial-review.json +56 -0
  52. package/playbooks/compound-engineering/plan-feasibility-review.json +56 -0
  53. package/playbooks/compound-engineering/project-standards-review.json +52 -0
  54. package/playbooks/compound-engineering/reliability-review.json +53 -0
  55. package/playbooks/compound-engineering/review-orchestration.json +64 -0
  56. package/playbooks/compound-engineering/security-review.json +54 -0
  57. package/playbooks/compound-engineering/systematic-execution.json +64 -0
  58. package/playbooks/compound-engineering/testing-review.json +50 -0
  59. package/src/atlas.ts +96 -0
  60. package/src/memory/curated-loader.ts +69 -16
  61. package/src/memory/index.ts +16 -0
  62. package/src/memory/playbook.ts +19 -0
  63. package/src/memory/source-resolver.ts +422 -0
  64. package/src/types/config.ts +46 -0
  65. package/src/types/index.ts +4 -0
  66. package/src/workspace/types.ts +22 -78
  67. package/tests/integration/curated-sources-e2e.test.ts +502 -0
  68. package/tests/memory/compound-engineering-seed.test.ts +338 -0
  69. package/tests/memory/curated-loader-extended.test.ts +225 -0
  70. package/tests/memory/playbook-quality-validation.test.ts +430 -0
  71. package/tests/memory/source-resolver.test.ts +700 -0
  72. package/.claude/settings.local.json +0 -11
  73. package/dist/learning/llm-extractor.d.ts +0 -88
  74. package/dist/learning/llm-extractor.d.ts.map +0 -1
  75. package/dist/learning/llm-extractor.js +0 -372
  76. package/dist/learning/llm-extractor.js.map +0 -1
  77. package/dist/learning/loop-coordinator.d.ts +0 -61
  78. package/dist/learning/loop-coordinator.d.ts.map +0 -1
  79. package/dist/learning/loop-coordinator.js +0 -96
  80. package/dist/learning/loop-coordinator.js.map +0 -1
  81. package/dist/learning/pipeline.d.ts +0 -116
  82. package/dist/learning/pipeline.d.ts.map +0 -1
  83. package/dist/learning/pipeline.js +0 -288
  84. package/dist/learning/pipeline.js.map +0 -1
  85. package/references/agent-workspace/CLAUDE.md +0 -74
  86. package/references/agent-workspace/README.md +0 -587
  87. package/references/agent-workspace/media/banner.png +0 -0
  88. package/references/agent-workspace/package-lock.json +0 -2061
  89. package/references/agent-workspace/package.json +0 -54
  90. package/references/agent-workspace/src/handle.ts +0 -122
  91. package/references/agent-workspace/src/index.ts +0 -32
  92. package/references/agent-workspace/src/manager.ts +0 -102
  93. package/references/agent-workspace/src/readers/json.ts +0 -71
  94. package/references/agent-workspace/src/readers/markdown.ts +0 -37
  95. package/references/agent-workspace/src/readers/raw.ts +0 -27
  96. package/references/agent-workspace/src/types.ts +0 -68
  97. package/references/agent-workspace/src/validation.ts +0 -93
  98. package/references/agent-workspace/src/writers/json.ts +0 -17
  99. package/references/agent-workspace/src/writers/markdown.ts +0 -27
  100. package/references/agent-workspace/src/writers/raw.ts +0 -22
  101. package/references/agent-workspace/tests/errors.test.ts +0 -652
  102. package/references/agent-workspace/tests/handle.test.ts +0 -144
  103. package/references/agent-workspace/tests/manager.test.ts +0 -124
  104. package/references/agent-workspace/tests/readers.test.ts +0 -205
  105. package/references/agent-workspace/tests/validation.test.ts +0 -196
  106. package/references/agent-workspace/tests/writers.test.ts +0 -108
  107. package/references/agent-workspace/tsconfig.json +0 -20
  108. package/references/agent-workspace/tsup.config.ts +0 -9
  109. package/references/minimem/.claude/settings.json +0 -7
  110. package/references/minimem/.sudocode/issues.jsonl +0 -18
  111. package/references/minimem/.sudocode/specs.jsonl +0 -1
  112. package/references/minimem/CLAUDE.md +0 -310
  113. package/references/minimem/README.md +0 -556
  114. package/references/minimem/claude-plugin/.claude-plugin/plugin.json +0 -10
  115. package/references/minimem/claude-plugin/.mcp.json +0 -7
  116. package/references/minimem/claude-plugin/README.md +0 -158
  117. package/references/minimem/claude-plugin/commands/recall.md +0 -47
  118. package/references/minimem/claude-plugin/commands/remember.md +0 -41
  119. package/references/minimem/claude-plugin/hooks/__tests__/hooks.test.ts +0 -272
  120. package/references/minimem/claude-plugin/hooks/hooks.json +0 -27
  121. package/references/minimem/claude-plugin/hooks/session-end.sh +0 -86
  122. package/references/minimem/claude-plugin/hooks/session-start.sh +0 -85
  123. package/references/minimem/claude-plugin/skills/memory/SKILL.md +0 -108
  124. package/references/minimem/package-lock.json +0 -5373
  125. package/references/minimem/package.json +0 -60
  126. package/references/minimem/scripts/postbuild.js +0 -35
  127. package/references/minimem/src/__tests__/edge-cases.test.ts +0 -371
  128. package/references/minimem/src/__tests__/errors.test.ts +0 -265
  129. package/references/minimem/src/__tests__/helpers.ts +0 -199
  130. package/references/minimem/src/__tests__/internal.test.ts +0 -407
  131. package/references/minimem/src/__tests__/knowledge.test.ts +0 -287
  132. package/references/minimem/src/__tests__/minimem.integration.test.ts +0 -1127
  133. package/references/minimem/src/__tests__/session.test.ts +0 -190
  134. package/references/minimem/src/cli/__tests__/commands.test.ts +0 -759
  135. package/references/minimem/src/cli/commands/__tests__/conflicts.test.ts +0 -141
  136. package/references/minimem/src/cli/commands/append.ts +0 -76
  137. package/references/minimem/src/cli/commands/config.ts +0 -262
  138. package/references/minimem/src/cli/commands/conflicts.ts +0 -413
  139. package/references/minimem/src/cli/commands/daemon.ts +0 -169
  140. package/references/minimem/src/cli/commands/index.ts +0 -12
  141. package/references/minimem/src/cli/commands/init.ts +0 -88
  142. package/references/minimem/src/cli/commands/mcp.ts +0 -177
  143. package/references/minimem/src/cli/commands/push-pull.ts +0 -213
  144. package/references/minimem/src/cli/commands/search.ts +0 -158
  145. package/references/minimem/src/cli/commands/status.ts +0 -84
  146. package/references/minimem/src/cli/commands/sync-init.ts +0 -290
  147. package/references/minimem/src/cli/commands/sync.ts +0 -70
  148. package/references/minimem/src/cli/commands/upsert.ts +0 -197
  149. package/references/minimem/src/cli/config.ts +0 -584
  150. package/references/minimem/src/cli/index.ts +0 -264
  151. package/references/minimem/src/cli/shared.ts +0 -161
  152. package/references/minimem/src/cli/sync/__tests__/central.test.ts +0 -152
  153. package/references/minimem/src/cli/sync/__tests__/conflicts.test.ts +0 -209
  154. package/references/minimem/src/cli/sync/__tests__/daemon.test.ts +0 -118
  155. package/references/minimem/src/cli/sync/__tests__/detection.test.ts +0 -207
  156. package/references/minimem/src/cli/sync/__tests__/integration.test.ts +0 -476
  157. package/references/minimem/src/cli/sync/__tests__/registry.test.ts +0 -363
  158. package/references/minimem/src/cli/sync/__tests__/state.test.ts +0 -255
  159. package/references/minimem/src/cli/sync/__tests__/validation.test.ts +0 -193
  160. package/references/minimem/src/cli/sync/__tests__/watcher.test.ts +0 -178
  161. package/references/minimem/src/cli/sync/central.ts +0 -292
  162. package/references/minimem/src/cli/sync/conflicts.ts +0 -204
  163. package/references/minimem/src/cli/sync/daemon.ts +0 -407
  164. package/references/minimem/src/cli/sync/detection.ts +0 -138
  165. package/references/minimem/src/cli/sync/index.ts +0 -107
  166. package/references/minimem/src/cli/sync/operations.ts +0 -373
  167. package/references/minimem/src/cli/sync/registry.ts +0 -279
  168. package/references/minimem/src/cli/sync/state.ts +0 -355
  169. package/references/minimem/src/cli/sync/validation.ts +0 -206
  170. package/references/minimem/src/cli/sync/watcher.ts +0 -234
  171. package/references/minimem/src/cli/version.ts +0 -34
  172. package/references/minimem/src/core/index.ts +0 -9
  173. package/references/minimem/src/core/indexer.ts +0 -628
  174. package/references/minimem/src/core/searcher.ts +0 -221
  175. package/references/minimem/src/db/schema.ts +0 -183
  176. package/references/minimem/src/db/sqlite-vec.ts +0 -24
  177. package/references/minimem/src/embeddings/__tests__/embeddings.test.ts +0 -431
  178. package/references/minimem/src/embeddings/batch-gemini.ts +0 -392
  179. package/references/minimem/src/embeddings/batch-openai.ts +0 -409
  180. package/references/minimem/src/embeddings/embeddings.ts +0 -434
  181. package/references/minimem/src/index.ts +0 -109
  182. package/references/minimem/src/internal.ts +0 -299
  183. package/references/minimem/src/minimem.ts +0 -1276
  184. package/references/minimem/src/search/__tests__/hybrid.test.ts +0 -247
  185. package/references/minimem/src/search/graph.ts +0 -234
  186. package/references/minimem/src/search/hybrid.ts +0 -151
  187. package/references/minimem/src/search/search.ts +0 -256
  188. package/references/minimem/src/server/__tests__/mcp.test.ts +0 -341
  189. package/references/minimem/src/server/__tests__/tools.test.ts +0 -364
  190. package/references/minimem/src/server/mcp.ts +0 -326
  191. package/references/minimem/src/server/tools.ts +0 -720
  192. package/references/minimem/src/session.ts +0 -460
  193. package/references/minimem/tsconfig.json +0 -19
  194. package/references/minimem/tsup.config.ts +0 -26
  195. package/references/minimem/vitest.config.ts +0 -24
  196. package/references/sessionlog/.husky/pre-commit +0 -1
  197. package/references/sessionlog/.lintstagedrc.json +0 -4
  198. package/references/sessionlog/.prettierignore +0 -4
  199. package/references/sessionlog/.prettierrc.json +0 -11
  200. package/references/sessionlog/LICENSE +0 -21
  201. package/references/sessionlog/README.md +0 -453
  202. package/references/sessionlog/eslint.config.js +0 -58
  203. package/references/sessionlog/package-lock.json +0 -3672
  204. package/references/sessionlog/package.json +0 -65
  205. package/references/sessionlog/src/__tests__/agent-hooks.test.ts +0 -570
  206. package/references/sessionlog/src/__tests__/agent-registry.test.ts +0 -127
  207. package/references/sessionlog/src/__tests__/claude-code-hooks.test.ts +0 -225
  208. package/references/sessionlog/src/__tests__/claude-generator.test.ts +0 -46
  209. package/references/sessionlog/src/__tests__/commit-msg.test.ts +0 -86
  210. package/references/sessionlog/src/__tests__/cursor-agent.test.ts +0 -224
  211. package/references/sessionlog/src/__tests__/e2e-live.test.ts +0 -890
  212. package/references/sessionlog/src/__tests__/event-log.test.ts +0 -183
  213. package/references/sessionlog/src/__tests__/flush-sentinel.test.ts +0 -105
  214. package/references/sessionlog/src/__tests__/gemini-agent.test.ts +0 -375
  215. package/references/sessionlog/src/__tests__/git-hooks.test.ts +0 -78
  216. package/references/sessionlog/src/__tests__/hook-managers.test.ts +0 -121
  217. package/references/sessionlog/src/__tests__/lifecycle-tasks.test.ts +0 -759
  218. package/references/sessionlog/src/__tests__/opencode-agent.test.ts +0 -338
  219. package/references/sessionlog/src/__tests__/redaction.test.ts +0 -136
  220. package/references/sessionlog/src/__tests__/session-repo.test.ts +0 -353
  221. package/references/sessionlog/src/__tests__/session-store.test.ts +0 -166
  222. package/references/sessionlog/src/__tests__/setup-ccweb.test.ts +0 -466
  223. package/references/sessionlog/src/__tests__/skill-live.test.ts +0 -461
  224. package/references/sessionlog/src/__tests__/summarize.test.ts +0 -348
  225. package/references/sessionlog/src/__tests__/task-plan-e2e.test.ts +0 -610
  226. package/references/sessionlog/src/__tests__/task-plan-live.test.ts +0 -632
  227. package/references/sessionlog/src/__tests__/transcript-timestamp.test.ts +0 -121
  228. package/references/sessionlog/src/__tests__/types.test.ts +0 -166
  229. package/references/sessionlog/src/__tests__/utils.test.ts +0 -333
  230. package/references/sessionlog/src/__tests__/validation.test.ts +0 -103
  231. package/references/sessionlog/src/__tests__/worktree.test.ts +0 -57
  232. package/references/sessionlog/src/agent/agents/claude-code.ts +0 -1089
  233. package/references/sessionlog/src/agent/agents/cursor.ts +0 -361
  234. package/references/sessionlog/src/agent/agents/gemini-cli.ts +0 -632
  235. package/references/sessionlog/src/agent/agents/opencode.ts +0 -540
  236. package/references/sessionlog/src/agent/registry.ts +0 -143
  237. package/references/sessionlog/src/agent/session-types.ts +0 -113
  238. package/references/sessionlog/src/agent/types.ts +0 -220
  239. package/references/sessionlog/src/cli.ts +0 -597
  240. package/references/sessionlog/src/commands/clean.ts +0 -133
  241. package/references/sessionlog/src/commands/disable.ts +0 -84
  242. package/references/sessionlog/src/commands/doctor.ts +0 -145
  243. package/references/sessionlog/src/commands/enable.ts +0 -202
  244. package/references/sessionlog/src/commands/explain.ts +0 -261
  245. package/references/sessionlog/src/commands/reset.ts +0 -105
  246. package/references/sessionlog/src/commands/resume.ts +0 -180
  247. package/references/sessionlog/src/commands/rewind.ts +0 -195
  248. package/references/sessionlog/src/commands/setup-ccweb.ts +0 -275
  249. package/references/sessionlog/src/commands/status.ts +0 -172
  250. package/references/sessionlog/src/config.ts +0 -165
  251. package/references/sessionlog/src/events/event-log.ts +0 -126
  252. package/references/sessionlog/src/git-operations.ts +0 -558
  253. package/references/sessionlog/src/hooks/git-hooks.ts +0 -165
  254. package/references/sessionlog/src/hooks/lifecycle.ts +0 -391
  255. package/references/sessionlog/src/index.ts +0 -650
  256. package/references/sessionlog/src/security/redaction.ts +0 -283
  257. package/references/sessionlog/src/session/state-machine.ts +0 -452
  258. package/references/sessionlog/src/store/checkpoint-store.ts +0 -509
  259. package/references/sessionlog/src/store/native-store.ts +0 -173
  260. package/references/sessionlog/src/store/provider-types.ts +0 -99
  261. package/references/sessionlog/src/store/session-store.ts +0 -266
  262. package/references/sessionlog/src/strategy/attribution.ts +0 -296
  263. package/references/sessionlog/src/strategy/common.ts +0 -207
  264. package/references/sessionlog/src/strategy/content-overlap.ts +0 -228
  265. package/references/sessionlog/src/strategy/manual-commit.ts +0 -988
  266. package/references/sessionlog/src/strategy/types.ts +0 -279
  267. package/references/sessionlog/src/summarize/claude-generator.ts +0 -115
  268. package/references/sessionlog/src/summarize/summarize.ts +0 -432
  269. package/references/sessionlog/src/types.ts +0 -508
  270. package/references/sessionlog/src/utils/chunk-files.ts +0 -49
  271. package/references/sessionlog/src/utils/commit-message.ts +0 -65
  272. package/references/sessionlog/src/utils/detect-agent.ts +0 -36
  273. package/references/sessionlog/src/utils/hook-managers.ts +0 -125
  274. package/references/sessionlog/src/utils/ide-tags.ts +0 -32
  275. package/references/sessionlog/src/utils/paths.ts +0 -79
  276. package/references/sessionlog/src/utils/preview-rewind.ts +0 -80
  277. package/references/sessionlog/src/utils/rewind-conflict.ts +0 -121
  278. package/references/sessionlog/src/utils/shadow-branch.ts +0 -109
  279. package/references/sessionlog/src/utils/string-utils.ts +0 -46
  280. package/references/sessionlog/src/utils/todo-extract.ts +0 -188
  281. package/references/sessionlog/src/utils/trailers.ts +0 -187
  282. package/references/sessionlog/src/utils/transcript-parse.ts +0 -177
  283. package/references/sessionlog/src/utils/transcript-timestamp.ts +0 -59
  284. package/references/sessionlog/src/utils/tree-ops.ts +0 -219
  285. package/references/sessionlog/src/utils/tty.ts +0 -72
  286. package/references/sessionlog/src/utils/validation.ts +0 -65
  287. package/references/sessionlog/src/utils/worktree.ts +0 -58
  288. package/references/sessionlog/src/wire-types.ts +0 -59
  289. package/references/sessionlog/templates/setup-env.sh +0 -153
  290. package/references/sessionlog/tsconfig.json +0 -18
  291. package/references/sessionlog/vitest.config.ts +0 -12
  292. package/references/skill-tree/.claude/settings.json +0 -6
  293. package/references/skill-tree/.sudocode/issues.jsonl +0 -19
  294. package/references/skill-tree/.sudocode/specs.jsonl +0 -3
  295. package/references/skill-tree/CLAUDE.md +0 -126
  296. package/references/skill-tree/README.md +0 -372
  297. package/references/skill-tree/docs/GAPS_v1.md +0 -221
  298. package/references/skill-tree/docs/INTEGRATION_PLAN.md +0 -467
  299. package/references/skill-tree/docs/TODOS.md +0 -91
  300. package/references/skill-tree/docs/anthropic_skill_guide.md +0 -1364
  301. package/references/skill-tree/docs/design/federated-skill-trees.md +0 -524
  302. package/references/skill-tree/docs/design/multi-agent-sync.md +0 -759
  303. package/references/skill-tree/docs/scraper/BRAINSTORM.md +0 -583
  304. package/references/skill-tree/docs/scraper/POC_PLAN.md +0 -420
  305. package/references/skill-tree/docs/scraper/README.md +0 -170
  306. package/references/skill-tree/examples/basic-usage.ts +0 -164
  307. package/references/skill-tree/package-lock.json +0 -1852
  308. package/references/skill-tree/package.json +0 -66
  309. package/references/skill-tree/scraper/README.md +0 -123
  310. package/references/skill-tree/scraper/docs/DESIGN.md +0 -683
  311. package/references/skill-tree/scraper/docs/PLAN.md +0 -336
  312. package/references/skill-tree/scraper/drizzle.config.ts +0 -10
  313. package/references/skill-tree/scraper/package-lock.json +0 -6329
  314. package/references/skill-tree/scraper/package.json +0 -68
  315. package/references/skill-tree/scraper/test/fixtures/invalid-skill/missing-description.md +0 -7
  316. package/references/skill-tree/scraper/test/fixtures/invalid-skill/missing-name.md +0 -7
  317. package/references/skill-tree/scraper/test/fixtures/minimal-skill/SKILL.md +0 -27
  318. package/references/skill-tree/scraper/test/fixtures/skill-json/SKILL.json +0 -21
  319. package/references/skill-tree/scraper/test/fixtures/skill-with-meta/SKILL.md +0 -54
  320. package/references/skill-tree/scraper/test/fixtures/skill-with-meta/_meta.json +0 -24
  321. package/references/skill-tree/scraper/test/fixtures/valid-skill/SKILL.md +0 -93
  322. package/references/skill-tree/scraper/test/fixtures/valid-skill/_meta.json +0 -22
  323. package/references/skill-tree/scraper/tsup.config.ts +0 -14
  324. package/references/skill-tree/scraper/vitest.config.ts +0 -17
  325. package/references/skill-tree/scripts/convert-to-vitest.ts +0 -166
  326. package/references/skill-tree/skills/skill-writer/SKILL.md +0 -339
  327. package/references/skill-tree/skills/skill-writer/references/examples.md +0 -326
  328. package/references/skill-tree/skills/skill-writer/references/patterns.md +0 -210
  329. package/references/skill-tree/skills/skill-writer/references/quality-checklist.md +0 -123
  330. package/references/skill-tree/test/run-all.ts +0 -106
  331. package/references/skill-tree/test/utils.ts +0 -128
  332. package/references/skill-tree/vitest.config.ts +0 -16
@@ -1,988 +0,0 @@
1
- /**
2
- * Manual Commit Strategy
3
- *
4
- * Core strategy implementation that orchestrates session tracking,
5
- * checkpoint creation, condensation, and git hook integration.
6
- *
7
- * Data flow:
8
- * 1. InitializeSession -> Creates SessionState, calculates initial attribution
9
- * 2. SaveStep/SaveTaskStep -> Writes to shadow branch via CheckpointStore
10
- * 3. PrepareCommitMsg -> Adds Sessionlog-Checkpoint trailer to commit messages
11
- * 4. PostCommit -> Condenses session data, handles carry-forward
12
- * 5. PrePush -> Pushes metadata branch alongside user push
13
- */
14
-
15
- import * as fs from 'node:fs';
16
- import * as path from 'node:path';
17
- import type { SessionStore } from '../store/session-store.js';
18
- import type { CheckpointStore } from '../store/checkpoint-store.js';
19
- import type { SessionState, CheckpointID } from '../types.js';
20
- import {
21
- addTokenUsage,
22
- CHECKPOINTS_BRANCH,
23
- SHADOW_BRANCH_PREFIX,
24
- validateCheckpointID,
25
- } from '../types.js';
26
- import {
27
- git,
28
- gitSafe,
29
- getHead,
30
- getCurrentBranch,
31
- getWorktreeRoot,
32
- getGitAuthor,
33
- getUntrackedFiles,
34
- refExists,
35
- pushBranch,
36
- hasUncommittedChanges,
37
- listBranches,
38
- showFile,
39
- lsTree,
40
- deleteBranch,
41
- updateRef,
42
- diffNameOnly,
43
- } from '../git-operations.js';
44
- import { parseCheckpoint, formatShadowCommit, CheckpointTrailerKey } from '../utils/trailers.js';
45
- import {
46
- filesOverlapWithContent,
47
- stagedFilesOverlapWithContent,
48
- filesWithRemainingAgentChanges,
49
- } from './content-overlap.js';
50
- import type {
51
- Strategy,
52
- StepContext,
53
- TaskStepContext,
54
- CondensationResult,
55
- RewindPoint,
56
- OrphanedItem,
57
- } from './types.js';
58
- import { STRATEGY_NAME_MANUAL_COMMIT, formatSubagentEndMessage } from './types.js';
59
- import { appendCheckpointEvent } from '../events/event-log.js';
60
-
61
- // ============================================================================
62
- // ManualCommitStrategy
63
- // ============================================================================
64
-
65
- export interface ManualCommitStrategyConfig {
66
- sessionStore: SessionStore;
67
- checkpointStore: CheckpointStore;
68
- cwd?: string;
69
- /** When a separate session repo is configured, this is its working directory.
70
- * Used for pushing the checkpoints branch from the correct repo. */
71
- sessionRepoCwd?: string;
72
- /** Override for the checkpoints branch name (e.g. project-namespaced). */
73
- checkpointsBranch?: string;
74
- /** Enable the JSONL event log (.sessionlog/events.jsonl).
75
- * When true, checkpoint events are appended after each commit. */
76
- eventLogEnabled?: boolean;
77
- /** Maximum number of events to retain in the event log file.
78
- * When set, the log is pruned to this many entries after each write.
79
- * 0 or undefined means keep all events. */
80
- eventLogMaxEvents?: number;
81
- }
82
-
83
- export function createManualCommitStrategy(config: ManualCommitStrategyConfig): Strategy {
84
- const { sessionStore, checkpointStore, cwd, sessionRepoCwd } = config;
85
- /** The cwd for operations on the committed checkpoints branch */
86
- const committedCwd = sessionRepoCwd ?? cwd;
87
- /** Branch name for committed checkpoints */
88
- const cpBranch = config.checkpointsBranch ?? CHECKPOINTS_BRANCH;
89
-
90
- // ========================================================================
91
- // Session State Helpers
92
- // ========================================================================
93
-
94
- async function loadSession(sessionID: string): Promise<SessionState | null> {
95
- return sessionStore.load(sessionID);
96
- }
97
-
98
- async function saveSession(state: SessionState): Promise<void> {
99
- await sessionStore.save(state);
100
- }
101
-
102
- async function listAllSessions(): Promise<SessionState[]> {
103
- return sessionStore.list();
104
- }
105
-
106
- async function findSessionsForCommit(baseCommitSHA: string): Promise<SessionState[]> {
107
- const all = await listAllSessions();
108
- return all.filter((s) => s.baseCommit === baseCommitSHA);
109
- }
110
-
111
- function getShadowBranchName(baseCommit: string, worktreeID?: string): string {
112
- return checkpointStore.getShadowBranchName(baseCommit, worktreeID);
113
- }
114
-
115
- // ========================================================================
116
- // File Merging Helpers
117
- // ========================================================================
118
-
119
- function mergeFilesTouched(existing: string[], ...fileLists: string[][]): string[] {
120
- const seen = new Set(existing);
121
- for (const list of fileLists) {
122
- for (const f of list) seen.add(f);
123
- }
124
- return Array.from(seen).sort();
125
- }
126
-
127
- // ========================================================================
128
- // Strategy Implementation
129
- // ========================================================================
130
-
131
- const strategy: Strategy = {
132
- name: STRATEGY_NAME_MANUAL_COMMIT,
133
-
134
- // ======================================================================
135
- // PrepareCommitMsg - Add checkpoint trailer to commit messages
136
- // ======================================================================
137
- async prepareCommitMsg(commitMsgFile: string, source: string, _sha: string): Promise<void> {
138
- // Read the current commit message
139
- const commitMsg = fs.readFileSync(commitMsgFile, 'utf-8');
140
-
141
- // Skip merge commits
142
- if (source === 'merge') return;
143
-
144
- // Handle amend: preserve existing checkpoint trailer
145
- if (source === 'commit') {
146
- const [cpID, found] = parseCheckpoint(commitMsg);
147
- if (found && cpID) {
148
- // Trailer already present, nothing to do
149
- return;
150
- }
151
- }
152
-
153
- // Get current HEAD
154
- const head = await getHead(cwd);
155
-
156
- // Find active sessions for this commit
157
- const sessions = await findSessionsForCommit(head);
158
- if (sessions.length === 0) return;
159
-
160
- // Get staged files
161
- const stagedOutput = await gitSafe(
162
- ['diff', '--cached', '--name-only', '--diff-filter=ACMRD'],
163
- { cwd },
164
- );
165
- if (!stagedOutput) return;
166
- const stagedFiles = stagedOutput
167
- .trim()
168
- .split('\n')
169
- .filter((f) => f.length > 0);
170
- if (stagedFiles.length === 0) return;
171
-
172
- // Check if any session has overlapping work
173
- let hasOverlap = false;
174
- let overlappingSession: SessionState | null = null;
175
-
176
- for (const state of sessions) {
177
- if (state.stepCount === 0 || state.filesTouched.length === 0) continue;
178
-
179
- const shadowBranch = getShadowBranchName(state.baseCommit, state.worktreeID);
180
- const exists = await refExists(`refs/heads/${shadowBranch}`, cwd);
181
- if (!exists) continue;
182
-
183
- // Content-aware overlap check
184
- const overlap = await stagedFilesOverlapWithContent(
185
- shadowBranch,
186
- stagedFiles,
187
- state.filesTouched,
188
- cwd,
189
- );
190
-
191
- if (overlap) {
192
- hasOverlap = true;
193
- overlappingSession = state;
194
- break;
195
- }
196
- }
197
-
198
- // Fallback: handle active sessions where the agent is committing mid-turn.
199
- // At this point TurnEnd hasn't fired, so stepCount/filesTouched/shadow branch
200
- // may not exist yet. Use staged files as a proxy for agent work.
201
- if (!hasOverlap) {
202
- for (const state of sessions) {
203
- if (state.phase !== 'active') continue;
204
-
205
- try {
206
- const shadowBranch = getShadowBranchName(state.baseCommit, state.worktreeID);
207
- let shadowExists = await refExists(`refs/heads/${shadowBranch}`, cwd);
208
-
209
- if (!shadowExists) {
210
- const author = await getGitAuthor(cwd);
211
- // Use flat name (no slashes) — mergeMetadataIntoTree can't handle nested paths
212
- const metadataDir = `sessionlog-${state.sessionID}`;
213
- const result = await checkpointStore.writeTemporary({
214
- sessionID: state.sessionID,
215
- baseCommit: state.baseCommit,
216
- worktreeID: state.worktreeID,
217
- modifiedFiles: stagedFiles,
218
- newFiles: [],
219
- deletedFiles: [],
220
- metadataDir,
221
- metadataDirAbs: path.resolve(cwd ?? '.', metadataDir),
222
- commitMessage: formatShadowCommit(
223
- `Checkpoint: ${stagedFiles.length} file(s)`,
224
- metadataDir,
225
- state.sessionID,
226
- ),
227
- authorName: author.name,
228
- authorEmail: author.email,
229
- isFirstCheckpoint: true,
230
- });
231
- if (!result.skipped) {
232
- shadowExists = true;
233
- }
234
- }
235
-
236
- if (shadowExists) {
237
- // Update session state so postCommit can process it
238
- state.stepCount = Math.max(state.stepCount, 1);
239
- state.filesTouched = mergeFilesTouched(state.filesTouched, stagedFiles);
240
- await saveSession(state);
241
- hasOverlap = true;
242
- overlappingSession = state;
243
- break;
244
- }
245
- } catch {
246
- // Non-fatal
247
- }
248
- }
249
- }
250
-
251
- if (!hasOverlap || !overlappingSession) return;
252
-
253
- // Generate or reuse checkpoint ID
254
- let cpID: CheckpointID;
255
- if (
256
- overlappingSession.lastCheckpointID &&
257
- validateCheckpointID(overlappingSession.lastCheckpointID)
258
- ) {
259
- cpID = overlappingSession.lastCheckpointID;
260
- } else {
261
- cpID = await checkpointStore.generateID();
262
- }
263
-
264
- // Inject trailer into commit message
265
- const trailer = `${CheckpointTrailerKey}: ${cpID}`;
266
- const injected = injectCheckpointTrailer(commitMsg, trailer);
267
- fs.writeFileSync(commitMsgFile, injected, 'utf-8');
268
- },
269
-
270
- // ======================================================================
271
- // PostCommit - Condense session data after commit
272
- // ======================================================================
273
- async postCommit(): Promise<void> {
274
- // Read HEAD commit message
275
- const headHash = await getHead(cwd);
276
- const commitMsg = await git(['log', '-1', '--format=%B', headHash], { cwd });
277
-
278
- // Check for checkpoint trailer
279
- const [cpID, found] = parseCheckpoint(commitMsg);
280
- if (!found || !cpID) return;
281
-
282
- // Find sessions for the parent commit (our base)
283
- const parentHash = await gitSafe(['rev-parse', `${headHash}^`], { cwd });
284
- if (!parentHash) return;
285
-
286
- const sessions = await findSessionsForCommit(parentHash.trim());
287
- if (sessions.length === 0) return;
288
-
289
- // Get files changed in this commit
290
- const { added, modified, deleted } = await diffNameOnly(`${headHash}^`, headHash, cwd);
291
- const committedFiles = new Set([...added, ...modified, ...deleted]);
292
-
293
- // Process each session
294
- for (const state of sessions) {
295
- if (state.stepCount === 0 || state.filesTouched.length === 0) continue;
296
-
297
- const shadowBranch = getShadowBranchName(state.baseCommit, state.worktreeID);
298
- const exists = await refExists(`refs/heads/${shadowBranch}`, cwd);
299
- if (!exists) continue;
300
-
301
- // Check overlap with committed files
302
- const overlap = await filesOverlapWithContent(
303
- shadowBranch,
304
- headHash,
305
- parentHash.trim(),
306
- state.filesTouched,
307
- cwd,
308
- );
309
- if (!overlap) continue;
310
-
311
- // Condense this session
312
- try {
313
- await condenseSession(state, cpID, committedFiles);
314
- } catch {
315
- // Log but continue with other sessions
316
- }
317
-
318
- // Handle carry-forward for remaining files
319
- const remaining = await filesWithRemainingAgentChanges(
320
- shadowBranch,
321
- headHash,
322
- state.filesTouched,
323
- committedFiles,
324
- cwd,
325
- );
326
-
327
- if (remaining.length === 0) {
328
- // All files committed - clean up shadow branch
329
- try {
330
- await checkpointStore.deleteShadowBranch(shadowBranch);
331
- } catch {
332
- // Best effort cleanup
333
- }
334
-
335
- // Update session for new base commit
336
- state.baseCommit = headHash;
337
- state.stepCount = 0;
338
- state.filesTouched = [];
339
- state.promptAttributions = [];
340
- state.lastCheckpointID = cpID;
341
- await saveSession(state);
342
- } else {
343
- // Carry forward: update state for remaining files
344
- state.baseCommit = headHash;
345
- state.filesTouched = remaining;
346
- state.stepCount = 0;
347
- state.promptAttributions = [];
348
- state.lastCheckpointID = cpID;
349
- await saveSession(state);
350
- }
351
- }
352
- },
353
-
354
- // ======================================================================
355
- // CommitMsg - Strip trailer if no user content (prevents empty commits)
356
- // ======================================================================
357
- async commitMsg(commitMsgFile: string): Promise<void> {
358
- let content: string;
359
- try {
360
- content = fs.readFileSync(commitMsgFile, 'utf-8');
361
- } catch {
362
- return; // Hook must be silent on failure
363
- }
364
-
365
- // Check if our trailer is present
366
- const [, found] = parseCheckpoint(content);
367
- if (!found) return;
368
-
369
- // Check if there's any user content (non-comment, non-trailer lines)
370
- if (!hasUserContent(content)) {
371
- // No user content - strip the trailer so git aborts the commit
372
- const stripped = stripCheckpointTrailer(content);
373
- try {
374
- fs.writeFileSync(commitMsgFile, stripped, 'utf-8');
375
- } catch {
376
- // Hook must be silent on failure
377
- }
378
- }
379
- },
380
-
381
- // ======================================================================
382
- // PrePush - Push metadata branch alongside user push
383
- // ======================================================================
384
- async prePush(remote: string): Promise<void> {
385
- const pushCwd = committedCwd;
386
- const branchExists = await refExists(`refs/heads/${cpBranch}`, pushCwd);
387
- if (!branchExists) return;
388
-
389
- try {
390
- await pushBranch(remote, cpBranch, false, pushCwd);
391
- } catch {
392
- // Non-fatal: metadata push failure shouldn't block user push
393
- }
394
- },
395
-
396
- // ======================================================================
397
- // SaveStep - Create session checkpoint on shadow branch
398
- // ======================================================================
399
- async saveStep(step: StepContext): Promise<void> {
400
- const sessionID = path.basename(step.metadataDir);
401
- let state = await loadSession(sessionID);
402
-
403
- // Initialize if needed
404
- if (!state || !state.baseCommit) {
405
- const head = await getHead(cwd);
406
- const untrackedFiles = await getUntrackedFiles(cwd);
407
- const worktreeRoot = await getWorktreeRoot(cwd);
408
-
409
- state = {
410
- sessionID,
411
- baseCommit: head,
412
- attributionBaseCommit: head,
413
- startedAt: new Date().toISOString(),
414
- phase: 'active',
415
- turnCheckpointIDs: [],
416
- stepCount: 0,
417
- checkpointTranscriptStart: 0,
418
- untrackedFilesAtStart: untrackedFiles,
419
- filesTouched: [],
420
- agentType: step.agentType,
421
- worktreePath: worktreeRoot,
422
- };
423
- await saveSession(state);
424
- }
425
-
426
- // Migrate shadow branch if HEAD changed (rebase/pull mid-session)
427
- await migrateAndPersist(state);
428
-
429
- // Write temporary checkpoint
430
- const isFirstCheckpoint = state.stepCount === 0;
431
- const result = await checkpointStore.writeTemporary({
432
- sessionID,
433
- baseCommit: state.baseCommit,
434
- worktreeID: state.worktreeID,
435
- modifiedFiles: step.modifiedFiles,
436
- newFiles: step.newFiles,
437
- deletedFiles: step.deletedFiles,
438
- metadataDir: step.metadataDir,
439
- metadataDirAbs: step.metadataDirAbs,
440
- commitMessage: step.commitMessage,
441
- authorName: step.authorName,
442
- authorEmail: step.authorEmail,
443
- isFirstCheckpoint,
444
- });
445
-
446
- if (result.skipped) return;
447
-
448
- // Update session state
449
- state.stepCount++;
450
- state.filesTouched = mergeFilesTouched(
451
- state.filesTouched,
452
- step.modifiedFiles,
453
- step.newFiles,
454
- step.deletedFiles,
455
- );
456
-
457
- if (state.stepCount === 1 && step.stepTranscriptIdentifier) {
458
- state.transcriptIdentifierAtStart = step.stepTranscriptIdentifier;
459
- }
460
-
461
- if (step.tokenUsage) {
462
- state.tokenUsage = state.tokenUsage
463
- ? addTokenUsage(state.tokenUsage, step.tokenUsage)
464
- : step.tokenUsage;
465
- }
466
-
467
- await saveSession(state);
468
- },
469
-
470
- // ======================================================================
471
- // SaveTaskStep - Create task checkpoint on shadow branch
472
- // ======================================================================
473
- async saveTaskStep(step: TaskStepContext): Promise<void> {
474
- let state = await loadSession(step.sessionID);
475
-
476
- if (!state || !state.baseCommit) {
477
- const head = await getHead(cwd);
478
- const untrackedFiles = await getUntrackedFiles(cwd);
479
- const worktreeRoot = await getWorktreeRoot(cwd);
480
-
481
- state = {
482
- sessionID: step.sessionID,
483
- baseCommit: head,
484
- attributionBaseCommit: head,
485
- startedAt: new Date().toISOString(),
486
- phase: 'active',
487
- turnCheckpointIDs: [],
488
- stepCount: 0,
489
- checkpointTranscriptStart: 0,
490
- untrackedFilesAtStart: untrackedFiles,
491
- filesTouched: [],
492
- agentType: step.agentType,
493
- worktreePath: worktreeRoot,
494
- };
495
- await saveSession(state);
496
- }
497
-
498
- // Migrate shadow branch if HEAD changed (rebase/pull mid-session)
499
- await migrateAndPersist(state);
500
-
501
- // Generate commit message for task checkpoint
502
- const shortToolUseID =
503
- step.toolUseID.length > 7 ? step.toolUseID.slice(0, 7) : step.toolUseID;
504
- const messageSubject = formatSubagentEndMessage(
505
- step.subagentType,
506
- step.taskDescription,
507
- shortToolUseID,
508
- );
509
- const metadataDir = `.sessionlog/metadata/${step.sessionID}/tasks/${step.toolUseID}`;
510
- const commitMsg = formatShadowCommit(messageSubject, metadataDir, step.sessionID);
511
-
512
- // Write temporary checkpoint
513
- await checkpointStore.writeTemporary({
514
- sessionID: step.sessionID,
515
- baseCommit: state.baseCommit,
516
- worktreeID: state.worktreeID,
517
- modifiedFiles: step.modifiedFiles,
518
- newFiles: step.newFiles,
519
- deletedFiles: step.deletedFiles,
520
- metadataDir,
521
- metadataDirAbs: path.resolve(cwd ?? '.', metadataDir),
522
- commitMessage: commitMsg,
523
- authorName: step.authorName,
524
- authorEmail: step.authorEmail,
525
- isFirstCheckpoint: state.stepCount === 0,
526
- });
527
-
528
- // Update session state
529
- state.filesTouched = mergeFilesTouched(
530
- state.filesTouched,
531
- step.modifiedFiles,
532
- step.newFiles,
533
- step.deletedFiles,
534
- );
535
- await saveSession(state);
536
- },
537
-
538
- // ======================================================================
539
- // Rewind operations
540
- // ======================================================================
541
- async getRewindPoints(limit: number): Promise<RewindPoint[]> {
542
- const head = await getHead(cwd);
543
- const sessions = await findSessionsForCommit(head);
544
- const allPoints: RewindPoint[] = [];
545
-
546
- for (const state of sessions) {
547
- const shadowBranch = getShadowBranchName(state.baseCommit, state.worktreeID);
548
- const exists = await refExists(`refs/heads/${shadowBranch}`, cwd);
549
- if (!exists) continue;
550
-
551
- // List temporary checkpoints
552
- const temps = await checkpointStore.listTemporary();
553
- for (const temp of temps) {
554
- if (temp.baseCommit !== state.baseCommit) continue;
555
-
556
- allPoints.push({
557
- id: temp.latestCommit,
558
- message: `Checkpoint on ${shadowBranch}`,
559
- date: new Date(temp.timestamp),
560
- isTaskCheckpoint: false,
561
- isLogsOnly: false,
562
- agent: state.agentType,
563
- sessionID: state.sessionID,
564
- sessionPrompt: state.firstPrompt,
565
- sessionCount: 1,
566
- sessionIDs: [state.sessionID],
567
- });
568
- }
569
- }
570
-
571
- // Sort by date descending
572
- allPoints.sort((a, b) => b.date.getTime() - a.date.getTime());
573
-
574
- // Also add logs-only points from commit history
575
- const logsOnlyPoints = await getLogsOnlyRewindPoints(limit);
576
- const existingIDs = new Set(allPoints.map((p) => p.id));
577
- for (const p of logsOnlyPoints) {
578
- if (!existingIDs.has(p.id)) {
579
- allPoints.push(p);
580
- }
581
- }
582
-
583
- // Re-sort and trim
584
- allPoints.sort((a, b) => b.date.getTime() - a.date.getTime());
585
- return allPoints.slice(0, limit);
586
- },
587
-
588
- async rewind(point: RewindPoint): Promise<void> {
589
- if (point.isLogsOnly) {
590
- throw new Error('Use restoreLogsOnly for logs-only rewind points');
591
- }
592
-
593
- // Read checkpoint tree and restore files
594
- const treeEntries = await lsTree(point.id, undefined, cwd);
595
- const worktreeRoot = await getWorktreeRoot(cwd);
596
-
597
- for (const entry of treeEntries) {
598
- if (entry.name.startsWith('.sessionlog/')) continue;
599
-
600
- try {
601
- const content = await showFile(point.id, entry.name, cwd);
602
- const absPath = path.join(worktreeRoot, entry.name);
603
- const dir = path.dirname(absPath);
604
- fs.mkdirSync(dir, { recursive: true });
605
-
606
- const perm = entry.mode === '100755' ? 0o755 : 0o644;
607
- fs.writeFileSync(absPath, content, { mode: perm });
608
- } catch {
609
- // Skip files that can't be restored
610
- }
611
- }
612
- },
613
-
614
- async canRewind(): Promise<[boolean, string]> {
615
- const hasChanges = await hasUncommittedChanges(cwd);
616
- if (hasChanges) {
617
- return [
618
- true,
619
- 'Warning: You have uncommitted changes that will be overwritten by the rewind.',
620
- ];
621
- }
622
- return [true, ''];
623
- },
624
-
625
- // ======================================================================
626
- // Condensation
627
- // ======================================================================
628
- async condense(sessionID: string): Promise<CondensationResult> {
629
- const state = await loadSession(sessionID);
630
- if (!state) {
631
- throw new Error(`Session not found: ${sessionID}`);
632
- }
633
-
634
- const cpID = await checkpointStore.generateID();
635
- const committedFiles = new Set(state.filesTouched);
636
- return condenseSession(state, cpID, committedFiles);
637
- },
638
-
639
- // ======================================================================
640
- // Validation & Cleanup
641
- // ======================================================================
642
-
643
- async validateRepository(): Promise<void> {
644
- const { validateRepository: validate } = await import('./common.js');
645
- await validate(cwd);
646
- },
647
-
648
- async listOrphanedItems(): Promise<OrphanedItem[]> {
649
- const items: OrphanedItem[] = [];
650
-
651
- // Find orphaned shadow branches
652
- const allBranches = await listBranches(cwd);
653
- for (const branch of allBranches) {
654
- if (branch.startsWith(SHADOW_BRANCH_PREFIX) && branch !== CHECKPOINTS_BRANCH) {
655
- items.push({
656
- type: 'shadow-branch',
657
- id: branch,
658
- reason: 'shadow branch (should have been auto-cleaned)',
659
- });
660
- }
661
- }
662
-
663
- return items;
664
- },
665
- };
666
-
667
- // ========================================================================
668
- // Internal: Condensation
669
- // ========================================================================
670
-
671
- async function condenseSession(
672
- state: SessionState,
673
- checkpointID: CheckpointID,
674
- committedFiles: Set<string>,
675
- ): Promise<CondensationResult> {
676
- const author = await getGitAuthor(cwd);
677
- const branch = await getCurrentBranch(cwd);
678
-
679
- // Filter filesTouched to committed subset
680
- const filesTouched = state.filesTouched.filter((f) => committedFiles.has(f));
681
-
682
- // Build transcript and prompts from shadow branch
683
- let transcript = Buffer.alloc(0);
684
- let prompts: string[] = [];
685
- let context = Buffer.alloc(0);
686
-
687
- const shadowBranch = getShadowBranchName(state.baseCommit, state.worktreeID);
688
- const shadowExists = await refExists(`refs/heads/${shadowBranch}`, cwd);
689
-
690
- if (shadowExists) {
691
- // Read transcript from shadow branch metadata
692
- try {
693
- const metadataDir = `.sessionlog/metadata/${state.sessionID}`;
694
- const fullContent = await gitSafe(
695
- ['show', `refs/heads/${shadowBranch}:${metadataDir}/full.jsonl`],
696
- { cwd },
697
- );
698
- if (fullContent) {
699
- transcript = Buffer.from(fullContent, 'utf-8');
700
- }
701
- } catch {
702
- // Use empty transcript
703
- }
704
-
705
- // Read prompts
706
- try {
707
- const metadataDir = `.sessionlog/metadata/${state.sessionID}`;
708
- const promptContent = await gitSafe(
709
- ['show', `refs/heads/${shadowBranch}:${metadataDir}/prompt.txt`],
710
- { cwd },
711
- );
712
- if (promptContent) {
713
- prompts = promptContent.split('\n---\n').filter((p) => p.trim().length > 0);
714
- }
715
- } catch {
716
- // Use empty prompts
717
- }
718
- }
719
-
720
- // If we have a live transcript path, try to read from there
721
- if (transcript.length === 0 && state.transcriptPath) {
722
- try {
723
- transcript = fs.readFileSync(state.transcriptPath);
724
- } catch {
725
- // Keep empty
726
- }
727
- }
728
-
729
- // Generate context from prompts
730
- if (prompts.length > 0) {
731
- const contextLines = prompts.map((p, i) => `## Prompt ${i + 1}\n\n${p}`);
732
- context = Buffer.from(contextLines.join('\n\n---\n\n'), 'utf-8');
733
- }
734
-
735
- // Write committed checkpoint
736
- await checkpointStore.writeCommitted({
737
- checkpointID,
738
- sessionID: state.sessionID,
739
- strategy: STRATEGY_NAME_MANUAL_COMMIT,
740
- branch: branch ?? undefined,
741
- transcript,
742
- prompts,
743
- context,
744
- filesTouched,
745
- checkpointsCount: state.stepCount,
746
- authorName: author.name,
747
- authorEmail: author.email,
748
- agent: state.agentType,
749
- turnID: state.turnID,
750
- transcriptIdentifierAtStart: state.transcriptIdentifierAtStart,
751
- checkpointTranscriptStart: state.checkpointTranscriptStart,
752
- tokenUsage: state.tokenUsage,
753
- tasks: state.tasks,
754
- planModeUsed: (state.planModeEntries ?? 0) > 0,
755
- planModeEntries: state.planModeEntries,
756
- planEntries: state.planEntries,
757
- skillsUsed: state.skillsUsed,
758
- });
759
-
760
- // Write event to the JSONL event log for external consumers (opt-in)
761
- if (config.eventLogEnabled) {
762
- try {
763
- const eventCwd = cwd ?? process.cwd();
764
- await appendCheckpointEvent(
765
- eventCwd,
766
- {
767
- type: 'checkpoint_committed',
768
- timestamp: new Date().toISOString(),
769
- checkpointID,
770
- sessionID: state.sessionID,
771
- agent: state.agentType,
772
- branch: branch ?? undefined,
773
- filesTouched,
774
- checkpointsCount: state.stepCount,
775
- tokenUsage: state.tokenUsage,
776
- },
777
- { maxEvents: config.eventLogMaxEvents },
778
- );
779
- } catch {
780
- // Non-fatal: event log failure shouldn't break checkpoint flow
781
- }
782
- }
783
-
784
- return {
785
- checkpointID,
786
- sessionsCondensed: 1,
787
- checkpointsCount: state.stepCount,
788
- filesTouched,
789
- tokenUsage: state.tokenUsage,
790
- };
791
- }
792
-
793
- // ========================================================================
794
- // Internal: Logs-only rewind points from commit history
795
- // ========================================================================
796
-
797
- async function getLogsOnlyRewindPoints(limit: number): Promise<RewindPoint[]> {
798
- const points: RewindPoint[] = [];
799
-
800
- // Check if checkpoints branch exists (in session repo if configured)
801
- const branchExists = await refExists(`refs/heads/${cpBranch}`, committedCwd);
802
- if (!branchExists) return points;
803
-
804
- // Get committed checkpoints
805
- const committed = await checkpointStore.listCommitted(limit);
806
- if (committed.length === 0) return points;
807
-
808
- // Build map of checkpoint IDs
809
- const cpMap = new Map<string, (typeof committed)[0]>();
810
- for (const cp of committed) {
811
- if (cp.checkpointID) {
812
- cpMap.set(cp.checkpointID, cp);
813
- }
814
- }
815
-
816
- // Walk commit history looking for checkpoint trailers
817
- const head = await getHead(cwd);
818
- const logOutput = await gitSafe(
819
- ['log', '--format=%H %s%n%b', `--max-count=${limit * 2}`, head],
820
- { cwd },
821
- );
822
- if (!logOutput) return points;
823
-
824
- // Parse log output looking for checkpoint trailers
825
- const commits = logOutput.split('\n\n').filter((c) => c.trim().length > 0);
826
-
827
- for (const commitBlock of commits) {
828
- const lines = commitBlock.split('\n');
829
- if (lines.length === 0) continue;
830
-
831
- const firstLine = lines[0];
832
- const spaceIdx = firstLine.indexOf(' ');
833
- if (spaceIdx < 0) continue;
834
-
835
- const sha = firstLine.slice(0, spaceIdx);
836
- const message = firstLine.slice(spaceIdx + 1);
837
- const body = lines.slice(1).join('\n');
838
- const fullMessage = `${message}\n${body}`;
839
-
840
- const [cpID, found] = parseCheckpoint(fullMessage);
841
- if (!found || !cpID) continue;
842
-
843
- const cpInfo = cpMap.get(cpID);
844
- if (!cpInfo) continue;
845
-
846
- points.push({
847
- id: sha,
848
- message,
849
- date: new Date(),
850
- isLogsOnly: true,
851
- isTaskCheckpoint: false,
852
- checkpointID: cpID,
853
- sessionCount: cpInfo.sessions?.length ?? 1,
854
- sessionIDs: [],
855
- });
856
-
857
- if (points.length >= limit) break;
858
- }
859
-
860
- return points;
861
- }
862
-
863
- // ========================================================================
864
- // Internal: Shadow branch migration
865
- // ========================================================================
866
-
867
- /**
868
- * Check if HEAD has changed since the session started and migrate the
869
- * shadow branch to the new base commit if needed.
870
- *
871
- * This handles the scenario where the agent performs a rebase, pull, or
872
- * other git operation that changes HEAD mid-session. Without migration,
873
- * checkpoints would be saved to an orphaned shadow branch.
874
- */
875
- async function migrateShadowBranchIfNeeded(state: SessionState): Promise<boolean> {
876
- if (!state.baseCommit) return false;
877
-
878
- const currentHead = await getHead(cwd);
879
- if (state.baseCommit === currentHead) return false;
880
-
881
- const oldShadowBranch = getShadowBranchName(state.baseCommit, state.worktreeID);
882
- const newShadowBranch = getShadowBranchName(currentHead, state.worktreeID);
883
-
884
- // Guard: if both commits produce the same shadow branch name
885
- // (same 7-char prefix), just update state
886
- if (oldShadowBranch === newShadowBranch) {
887
- state.baseCommit = currentHead;
888
- return true;
889
- }
890
-
891
- const oldExists = await refExists(`refs/heads/${oldShadowBranch}`, cwd);
892
- if (!oldExists) {
893
- // Old shadow branch doesn't exist — just update baseCommit
894
- state.baseCommit = currentHead;
895
- return true;
896
- }
897
-
898
- // Old shadow branch exists — rename it to the new base
899
- try {
900
- // Read the current tip of the old branch
901
- const oldTip = await git(['rev-parse', `refs/heads/${oldShadowBranch}`], { cwd });
902
-
903
- // Create new branch pointing to same commit
904
- await updateRef(`refs/heads/${newShadowBranch}`, oldTip.trim(), cwd);
905
-
906
- // Delete old branch (best effort)
907
- try {
908
- await deleteBranch(oldShadowBranch, false, cwd);
909
- } catch {
910
- // Non-fatal
911
- }
912
- } catch {
913
- // If rename fails, just update state
914
- }
915
-
916
- state.baseCommit = currentHead;
917
- return true;
918
- }
919
-
920
- /**
921
- * Check for HEAD changes, migrate shadow branch if needed, and persist.
922
- */
923
- async function migrateAndPersist(state: SessionState): Promise<void> {
924
- const migrated = await migrateShadowBranchIfNeeded(state);
925
- if (migrated) {
926
- await saveSession(state);
927
- }
928
- }
929
-
930
- return strategy;
931
- }
932
-
933
- // ============================================================================
934
- // Helpers
935
- // ============================================================================
936
-
937
- /**
938
- * Inject a checkpoint trailer before any git comments in the commit message.
939
- */
940
- function injectCheckpointTrailer(message: string, trailer: string): string {
941
- const lines = message.split('\n');
942
-
943
- // Find where git comments start (lines beginning with #)
944
- let insertIndex = lines.length;
945
- for (let i = 0; i < lines.length; i++) {
946
- if (lines[i].startsWith('#')) {
947
- insertIndex = i;
948
- break;
949
- }
950
- }
951
-
952
- // Insert trailer before comments, with a blank line separator
953
- const before = lines.slice(0, insertIndex);
954
- const after = lines.slice(insertIndex);
955
-
956
- // Ensure there's a blank line before the trailer
957
- while (before.length > 0 && before[before.length - 1].trim() === '') {
958
- before.pop();
959
- }
960
-
961
- return [...before, '', trailer, '', ...after].join('\n');
962
- }
963
-
964
- /**
965
- * Check if a commit message has any content besides comments and our trailer.
966
- */
967
- export function hasUserContent(message: string): boolean {
968
- const trailerPrefix = CheckpointTrailerKey + ':';
969
- for (const line of message.split('\n')) {
970
- const trimmed = line.trim();
971
- if (!trimmed) continue;
972
- if (trimmed.startsWith('#')) continue;
973
- if (trimmed.startsWith(trailerPrefix)) continue;
974
- return true;
975
- }
976
- return false;
977
- }
978
-
979
- /**
980
- * Remove the Sessionlog-Checkpoint trailer line from a commit message.
981
- */
982
- export function stripCheckpointTrailer(message: string): string {
983
- const trailerPrefix = CheckpointTrailerKey + ':';
984
- return message
985
- .split('\n')
986
- .filter((line) => !line.trim().startsWith(trailerPrefix))
987
- .join('\n');
988
- }