@pugi/cli 0.1.0-beta.7 → 0.1.0-beta.87

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 (402) hide show
  1. package/CHANGELOG.md +96 -0
  2. package/THIRD_PARTY_NOTICES.md +40 -0
  3. package/assets/pugi-prozr2-mascot.ansi +9 -0
  4. package/bin/run.js +33 -1
  5. package/dist/commands/deploy.js +40 -40
  6. package/dist/commands/flatten.js +191 -0
  7. package/dist/commands/jobs-watch.js +201 -0
  8. package/dist/commands/jobs.js +42 -27
  9. package/dist/commands/smoke.js +133 -0
  10. package/dist/core/agent-progress/cleanup.js +134 -0
  11. package/dist/core/agent-progress/schema.js +144 -0
  12. package/dist/core/agent-progress/writer.js +101 -0
  13. package/dist/core/agents/adaptive-router.js +330 -0
  14. package/dist/core/agents/query-decomposer.js +297 -0
  15. package/dist/core/agents/registry.js +2 -2
  16. package/dist/core/approvals/shortcut-resolver.js +98 -0
  17. package/dist/core/artifact-chain/dispatcher.js +148 -0
  18. package/dist/core/artifact-chain/exporter.js +164 -0
  19. package/dist/core/artifact-chain/state.js +243 -0
  20. package/dist/core/artifact-chain/steps.js +169 -0
  21. package/dist/core/ask-user/question.js +92 -0
  22. package/dist/core/audit/audit-trail.js +275 -0
  23. package/dist/core/auth/ensure-authenticated.js +129 -0
  24. package/dist/core/auth/env-provider.js +238 -0
  25. package/dist/core/auto-open-browser.js +4 -4
  26. package/dist/core/auto-update/channels.js +122 -0
  27. package/dist/core/auto-update/checker.js +241 -0
  28. package/dist/core/auto-update/state.js +235 -0
  29. package/dist/core/bare-mode/index.js +107 -0
  30. package/dist/core/bash/redirect.js +281 -0
  31. package/dist/core/bash-classifier.js +436 -40
  32. package/dist/core/checkpoint/resumer.js +149 -0
  33. package/dist/core/checkpoint/rewinder.js +291 -0
  34. package/dist/core/checkpoints/shadow-git.js +670 -0
  35. package/dist/core/citations/parser.js +109 -0
  36. package/dist/core/classifier/yolo-classifier.js +88 -0
  37. package/dist/core/codegraph/decision-store.js +248 -0
  38. package/dist/core/codegraph/detect-repo.js +459 -0
  39. package/dist/core/codegraph/install.js +134 -0
  40. package/dist/core/codegraph/offer-hook.js +220 -0
  41. package/dist/core/compact/auto-trigger.js +96 -0
  42. package/dist/core/compact/buffer-rewriter.js +115 -0
  43. package/dist/core/compact/summarizer.js +208 -0
  44. package/dist/core/compact/token-counter.js +108 -0
  45. package/dist/core/consensus/anvil-fanout.js +25 -25
  46. package/dist/core/consensus/diff-capture.js +121 -12
  47. package/dist/core/consensus/rubric.js +21 -21
  48. package/dist/core/context/builder.js +6 -6
  49. package/dist/core/context/compaction-events.js +8 -8
  50. package/dist/core/context/compaction.js +31 -31
  51. package/dist/core/context/index.js +15 -8
  52. package/dist/core/context/invariants.js +51 -51
  53. package/dist/core/context/markdown-loader.js +28 -10
  54. package/dist/core/context/markdown-traverse.js +255 -0
  55. package/dist/core/context/pugiignore.js +41 -41
  56. package/dist/core/context/repo-skeleton.js +37 -37
  57. package/dist/core/context/tool-eviction.js +55 -0
  58. package/dist/core/context/watcher.js +32 -32
  59. package/dist/core/context/working-set.js +23 -23
  60. package/dist/core/coordinator/agent-tools.js +77 -0
  61. package/dist/core/coordinator/agent-toolset.js +65 -0
  62. package/dist/core/coordinator/fsm.js +73 -0
  63. package/dist/core/coordinator/mode-fsm.js +70 -0
  64. package/dist/core/cost/rate-card.js +129 -0
  65. package/dist/core/cost/tracker.js +221 -0
  66. package/dist/core/credentials.js +12 -12
  67. package/dist/core/cron/scheduler.js +138 -0
  68. package/dist/core/denial-tracking/index.js +8 -0
  69. package/dist/core/denial-tracking/state.js +264 -0
  70. package/dist/core/diagnostics/probe-runner.js +93 -0
  71. package/dist/core/diagnostics/probes/api.js +46 -0
  72. package/dist/core/diagnostics/probes/auth.js +93 -0
  73. package/dist/core/diagnostics/probes/bare-mode.js +42 -0
  74. package/dist/core/diagnostics/probes/cli-version.js +127 -0
  75. package/dist/core/diagnostics/probes/config.js +72 -0
  76. package/dist/core/diagnostics/probes/denial-tracking.js +57 -0
  77. package/dist/core/diagnostics/probes/disk.js +81 -0
  78. package/dist/core/diagnostics/probes/engine-live.js +46 -0
  79. package/dist/core/diagnostics/probes/git.js +65 -0
  80. package/dist/core/diagnostics/probes/hooks.js +118 -0
  81. package/dist/core/diagnostics/probes/mcp.js +75 -0
  82. package/dist/core/diagnostics/probes/node.js +59 -0
  83. package/dist/core/diagnostics/probes/pnpm.js +36 -0
  84. package/dist/core/diagnostics/probes/pugi-md.js +89 -0
  85. package/dist/core/diagnostics/probes/sandbox.js +40 -0
  86. package/dist/core/diagnostics/probes/session.js +74 -0
  87. package/dist/core/diagnostics/probes/status-snapshot.js +488 -0
  88. package/dist/core/diagnostics/probes/workspace.js +63 -0
  89. package/dist/core/diagnostics/types.js +70 -0
  90. package/dist/core/dispatch/cache-cleanup.js +197 -0
  91. package/dist/core/dispatch/cache-handoff.js +295 -0
  92. package/dist/core/edits/apply-patch-layer-e.js +189 -0
  93. package/dist/core/edits/dispatch.js +293 -7
  94. package/dist/core/edits/format-matrix.js +26 -0
  95. package/dist/core/edits/fuzzy-ladder.js +650 -0
  96. package/dist/core/edits/index.js +3 -1
  97. package/dist/core/edits/journal.js +199 -0
  98. package/dist/core/edits/layer-a-apply.js +15 -15
  99. package/dist/core/edits/layer-a-fuzzy-apply.js +198 -0
  100. package/dist/core/edits/layer-b-apply.js +9 -9
  101. package/dist/core/edits/layer-c-apply.js +6 -6
  102. package/dist/core/edits/layer-d-ast.js +557 -14
  103. package/dist/core/edits/marker-parser.js +12 -12
  104. package/dist/core/edits/security-gate.js +27 -27
  105. package/dist/core/edits/verify-hook.js +273 -0
  106. package/dist/core/edits/worktree.js +322 -0
  107. package/dist/core/engine/anvil-client.js +140 -26
  108. package/dist/core/engine/auto-compact.js +179 -0
  109. package/dist/core/engine/budgets.js +186 -0
  110. package/dist/core/engine/context-prefix.js +155 -0
  111. package/dist/core/engine/index.js +1 -1
  112. package/dist/core/engine/intensity.js +158 -0
  113. package/dist/core/engine/intent.js +260 -0
  114. package/dist/core/engine/native-pugi.js +1295 -227
  115. package/dist/core/engine/prompts.js +134 -16
  116. package/dist/core/engine/strip-internal-fields.js +124 -0
  117. package/dist/core/engine/tool-bridge.js +1295 -59
  118. package/dist/core/evaluation/golden-dataset.js +293 -0
  119. package/dist/core/feedback/queue.js +177 -0
  120. package/dist/core/feedback/submitter.js +145 -0
  121. package/dist/core/file-cache.js +113 -1
  122. package/dist/core/flatten/flatten-repo.js +439 -0
  123. package/dist/core/format/osc8-link.js +28 -0
  124. package/dist/core/hook-chains.js +392 -0
  125. package/dist/core/hooks/citation-verify-hook.js +138 -0
  126. package/dist/core/hooks/citation-verify.js +112 -0
  127. package/dist/core/hooks/events.js +44 -0
  128. package/dist/core/hooks/index.js +15 -0
  129. package/dist/core/hooks/registry.js +213 -0
  130. package/dist/core/hooks/runner.js +236 -0
  131. package/dist/core/hooks/v2/event-emitter.js +115 -0
  132. package/dist/core/hooks/v2/executor.js +282 -0
  133. package/dist/core/hooks/v2/index.js +25 -0
  134. package/dist/core/hooks/v2/lifecycle.js +104 -0
  135. package/dist/core/hooks/v2/loader.js +216 -0
  136. package/dist/core/hooks/v2/matcher.js +125 -0
  137. package/dist/core/hooks/v2/trust.js +143 -0
  138. package/dist/core/hooks/v2/types.js +86 -0
  139. package/dist/core/image/renderer.js +71 -0
  140. package/dist/core/init/detector.js +582 -0
  141. package/dist/core/init/template-renderer.js +242 -0
  142. package/dist/core/jobs/registry.js +18 -18
  143. package/dist/core/ledger/results-tsv.js +142 -0
  144. package/dist/core/log-discipline/stdout-redirect.js +51 -0
  145. package/dist/core/lsp/cache.js +105 -0
  146. package/dist/core/lsp/client.js +776 -0
  147. package/dist/core/lsp/language-detect.js +66 -0
  148. package/dist/core/lsp/post-edit-diagnostics.js +171 -0
  149. package/dist/core/lsp/symbol-tools.js +372 -0
  150. package/dist/core/mcp/client.js +97 -28
  151. package/dist/core/mcp/http-server.js +553 -0
  152. package/dist/core/mcp/orchestrator-tools.js +662 -0
  153. package/dist/core/mcp/permission.js +190 -0
  154. package/dist/core/mcp/registry.js +39 -17
  155. package/dist/core/mcp/server-tools.js +219 -0
  156. package/dist/core/mcp/server.js +397 -0
  157. package/dist/core/mcp/trust.js +10 -10
  158. package/dist/core/memory/dual-write.js +416 -0
  159. package/dist/core/memory/passive-extract.js +130 -0
  160. package/dist/core/memory/phase1-kinds.js +20 -0
  161. package/dist/core/memory/secret-scanner.js +304 -0
  162. package/dist/core/memory-sync/queue.js +170 -0
  163. package/dist/core/metrics/extract.js +113 -0
  164. package/dist/core/modes/roo-modes.js +68 -0
  165. package/dist/core/onboarding/ensure-initialized.js +133 -0
  166. package/dist/core/onboarding/marker.js +111 -0
  167. package/dist/core/onboarding/telemetry-state.js +108 -0
  168. package/dist/core/output-style/presets.js +176 -0
  169. package/dist/core/output-style/state.js +185 -0
  170. package/dist/core/path-security.js +287 -5
  171. package/dist/core/permission.js +82 -22
  172. package/dist/core/permissions/auto-classifier.js +124 -0
  173. package/dist/core/permissions/bash-parser.js +371 -0
  174. package/dist/core/permissions/circuit-breaker.js +83 -0
  175. package/dist/core/permissions/constrained-edit.js +91 -0
  176. package/dist/core/permissions/gate.js +278 -0
  177. package/dist/core/permissions/index.js +20 -0
  178. package/dist/core/permissions/mode.js +174 -0
  179. package/dist/core/permissions/network-egress.js +137 -0
  180. package/dist/core/permissions/state.js +241 -0
  181. package/dist/core/permissions/tool-class.js +93 -0
  182. package/dist/core/plan-mode/ui-state.js +51 -0
  183. package/dist/core/plans/plan-artifact.js +721 -0
  184. package/dist/core/policy-limits/etag-store.js +122 -0
  185. package/dist/core/prd-check/parser.js +215 -0
  186. package/dist/core/prd-check/reporter.js +127 -0
  187. package/dist/core/prd-check/session-review.js +557 -0
  188. package/dist/core/prd-check/verifiers.js +223 -0
  189. package/dist/core/prompt-cache/client-cache.js +99 -0
  190. package/dist/core/prompts/assembly.js +29 -0
  191. package/dist/core/prompts/registry.js +364 -0
  192. package/dist/core/pugi-md/cc-compat-rules.js +735 -0
  193. package/dist/core/pugi-md/context-injector.js +76 -0
  194. package/dist/core/pugi-md/walk-up.js +207 -0
  195. package/dist/core/python/uv-installer.js +270 -0
  196. package/dist/core/python/uv-resolver.js +83 -0
  197. package/dist/core/rate-limit/narrator.js +146 -0
  198. package/dist/core/recipes/cli-types.js +20 -0
  199. package/dist/core/recipes/loader.js +103 -0
  200. package/dist/core/recipes/runner.js +345 -0
  201. package/dist/core/recipes/schema.js +587 -0
  202. package/dist/core/release-notes/parser.js +241 -0
  203. package/dist/core/release-notes/state.js +116 -0
  204. package/dist/core/repl/ask.js +37 -37
  205. package/dist/core/repl/cancellation.js +26 -26
  206. package/dist/core/repl/cap-warning.js +4 -4
  207. package/dist/core/repl/clipboard-read.js +11 -11
  208. package/dist/core/repl/dispatch-fsm.js +12 -12
  209. package/dist/core/repl/history-search.js +15 -15
  210. package/dist/core/repl/history.js +28 -18
  211. package/dist/core/repl/kill-ring.js +5 -5
  212. package/dist/core/repl/model-pricing.js +135 -0
  213. package/dist/core/repl/privacy-banner.js +22 -22
  214. package/dist/core/repl/session.js +2157 -214
  215. package/dist/core/repl/slash-commands.js +533 -40
  216. package/dist/core/repl/store/index.js +1 -1
  217. package/dist/core/repl/store/jsonl-log.js +22 -22
  218. package/dist/core/repl/store/lockfile.js +10 -10
  219. package/dist/core/repl/store/session-store.js +136 -107
  220. package/dist/core/repl/store/types.js +15 -15
  221. package/dist/core/repl/store/uuid-v7.js +12 -12
  222. package/dist/core/repl/workspace-context.js +43 -21
  223. package/dist/core/repo-map/build.js +125 -0
  224. package/dist/core/repo-map/cache.js +185 -0
  225. package/dist/core/repo-map/extractor.js +254 -0
  226. package/dist/core/repo-map/formatter.js +145 -0
  227. package/dist/core/repo-map/page-rank.js +105 -0
  228. package/dist/core/repo-map/scanner.js +211 -0
  229. package/dist/core/retry-budget/budget.js +284 -0
  230. package/dist/core/retry-budget/index.js +5 -0
  231. package/dist/core/retry-budget/retry-cap.js +74 -0
  232. package/dist/core/routing/lead-worker.js +43 -0
  233. package/dist/core/routing/pre-flight-estimator.js +108 -0
  234. package/dist/core/runs/run-tree.js +103 -0
  235. package/dist/core/security/injection-scanner.js +367 -0
  236. package/dist/core/security/output-filter.js +418 -0
  237. package/dist/core/session/env-file.js +105 -0
  238. package/dist/core/session/section-budgets.js +140 -0
  239. package/dist/core/session.js +92 -0
  240. package/dist/core/settings.js +286 -5
  241. package/dist/core/share/formatter.js +271 -0
  242. package/dist/core/share/redactor.js +221 -0
  243. package/dist/core/share/uploader.js +267 -0
  244. package/dist/core/skills/defaults.js +457 -0
  245. package/dist/core/skills/loader.js +22 -22
  246. package/dist/core/skills/sources.js +27 -27
  247. package/dist/core/smoke/headless-driver.js +174 -0
  248. package/dist/core/smoke/orchestrator.js +194 -0
  249. package/dist/core/smoke/runner.js +238 -0
  250. package/dist/core/smoke/scenario-parser.js +316 -0
  251. package/dist/core/statusline.js +99 -0
  252. package/dist/core/subagents/dispatcher-real.js +600 -0
  253. package/dist/core/subagents/dispatcher.js +132 -43
  254. package/dist/core/subagents/index.js +19 -6
  255. package/dist/core/subagents/isolation-matrix.js +213 -0
  256. package/dist/core/subagents/spawn.js +19 -4
  257. package/dist/core/telemetry/emitter.js +229 -0
  258. package/dist/core/telemetry/queue.js +251 -0
  259. package/dist/core/theme/context.js +91 -0
  260. package/dist/core/theme/presets.js +228 -0
  261. package/dist/core/theme/state.js +181 -0
  262. package/dist/core/todos/invariant.js +10 -0
  263. package/dist/core/todos/state.js +177 -0
  264. package/dist/core/tool-schema/compressor.js +89 -0
  265. package/dist/core/transport/version-interceptor.js +166 -0
  266. package/dist/core/trust.js +2 -2
  267. package/dist/core/tui/thinking-block.js +64 -0
  268. package/dist/core/vim/keymap.js +288 -0
  269. package/dist/core/vim/state.js +92 -0
  270. package/dist/core/watch-markers/marker-watcher.js +133 -0
  271. package/dist/core/worktree-manager/cleanup.js +123 -0
  272. package/dist/core/worktree-manager/manager.js +303 -0
  273. package/dist/index.js +28 -0
  274. package/dist/runtime/bootstrap.js +190 -0
  275. package/dist/runtime/cli.js +4162 -488
  276. package/dist/runtime/commands/agents.js +30 -30
  277. package/dist/runtime/commands/budget.js +5 -5
  278. package/dist/runtime/commands/cancel.js +231 -0
  279. package/dist/runtime/commands/chain.js +489 -0
  280. package/dist/runtime/commands/codegraph-status.js +227 -0
  281. package/dist/runtime/commands/compact.js +297 -0
  282. package/dist/runtime/commands/config.js +32 -32
  283. package/dist/runtime/commands/cost.js +199 -0
  284. package/dist/runtime/commands/delegate.js +244 -13
  285. package/dist/runtime/commands/dispatch.js +126 -0
  286. package/dist/runtime/commands/doctor.js +579 -0
  287. package/dist/runtime/commands/feedback.js +184 -0
  288. package/dist/runtime/commands/hooks.js +184 -0
  289. package/dist/runtime/commands/init.js +254 -0
  290. package/dist/runtime/commands/lsp.js +368 -0
  291. package/dist/runtime/commands/mcp.js +879 -0
  292. package/dist/runtime/commands/memory.js +582 -0
  293. package/dist/runtime/commands/model.js +237 -0
  294. package/dist/runtime/commands/onboarding.js +275 -0
  295. package/dist/runtime/commands/patch.js +128 -0
  296. package/dist/runtime/commands/permissions.js +112 -0
  297. package/dist/runtime/commands/plan.js +143 -0
  298. package/dist/runtime/commands/prd-check.js +285 -0
  299. package/dist/runtime/commands/privacy.js +17 -17
  300. package/dist/runtime/commands/recipe.js +325 -0
  301. package/dist/runtime/commands/redo-blob-store.js +92 -0
  302. package/dist/runtime/commands/redo.js +361 -0
  303. package/dist/runtime/commands/release-notes.js +229 -0
  304. package/dist/runtime/commands/repo-map.js +95 -0
  305. package/dist/runtime/commands/report.js +299 -0
  306. package/dist/runtime/commands/resume.js +118 -0
  307. package/dist/runtime/commands/review-consensus.js +68 -53
  308. package/dist/runtime/commands/rewind.js +333 -0
  309. package/dist/runtime/commands/roster.js +14 -14
  310. package/dist/runtime/commands/sessions.js +163 -0
  311. package/dist/runtime/commands/share.js +316 -0
  312. package/dist/runtime/commands/skills.js +31 -31
  313. package/dist/runtime/commands/status.js +186 -0
  314. package/dist/runtime/commands/stickers.js +82 -0
  315. package/dist/runtime/commands/style.js +194 -0
  316. package/dist/runtime/commands/theme.js +196 -0
  317. package/dist/runtime/commands/undo.js +54 -22
  318. package/dist/runtime/commands/update.js +289 -0
  319. package/dist/runtime/commands/vim.js +140 -0
  320. package/dist/runtime/commands/worktree.js +177 -0
  321. package/dist/runtime/commands/worktrees.js +155 -0
  322. package/dist/runtime/headless-repl.js +195 -0
  323. package/dist/runtime/headless.js +543 -0
  324. package/dist/runtime/load-hooks-or-exit.js +71 -0
  325. package/dist/runtime/plan-decompose.js +531 -0
  326. package/dist/runtime/update-check.js +28 -28
  327. package/dist/runtime/version.js +65 -0
  328. package/dist/skills/bundled/batch.js +617 -0
  329. package/dist/skills/bundled/index.js +45 -0
  330. package/dist/skills/bundled/loop.js +358 -0
  331. package/dist/skills/bundled/remember.js +383 -0
  332. package/dist/skills/bundled/simplify.js +289 -0
  333. package/dist/skills/bundled/skillify.js +373 -0
  334. package/dist/skills/bundled/stuck.js +558 -0
  335. package/dist/skills/bundled/verify.js +439 -0
  336. package/dist/testing/vcr.js +486 -0
  337. package/dist/tools/agent-tool.js +229 -0
  338. package/dist/tools/apply-patch.js +556 -0
  339. package/dist/tools/ask-user-question.js +222 -0
  340. package/dist/tools/ask-user.js +115 -0
  341. package/dist/tools/bash.js +623 -45
  342. package/dist/tools/brief.js +224 -0
  343. package/dist/tools/enter-worktree.js +250 -0
  344. package/dist/tools/exit-worktree.js +147 -0
  345. package/dist/tools/file-tools.js +161 -44
  346. package/dist/tools/lsp-tools.js +189 -0
  347. package/dist/tools/mcp-tool.js +260 -0
  348. package/dist/tools/multi-edit.js +361 -0
  349. package/dist/tools/powershell.js +268 -0
  350. package/dist/tools/registry.js +85 -0
  351. package/dist/tools/skill-tool.js +96 -0
  352. package/dist/tools/sleep.js +99 -0
  353. package/dist/tools/synthetic-output.js +133 -0
  354. package/dist/tools/tasks.js +208 -0
  355. package/dist/tools/todo-write.js +184 -0
  356. package/dist/tools/verify-plan-execution.js +295 -0
  357. package/dist/tools/web-fetch-injection-scanner.js +207 -0
  358. package/dist/tools/web-fetch.js +195 -10
  359. package/dist/tools/web-search.js +458 -0
  360. package/dist/tui/agent-progress-card.js +111 -0
  361. package/dist/tui/agent-tree.js +11 -1
  362. package/dist/tui/ask-modal.js +14 -14
  363. package/dist/tui/ask-user-question-prompt.js +203 -0
  364. package/dist/tui/compact-banner.js +81 -0
  365. package/dist/tui/conversation-pane.js +85 -11
  366. package/dist/tui/cost-table.js +111 -0
  367. package/dist/tui/device-flow.js +2 -2
  368. package/dist/tui/doctor-table.js +46 -0
  369. package/dist/tui/feedback-prompt.js +156 -0
  370. package/dist/tui/input-box.js +247 -32
  371. package/dist/tui/login-picker.js +3 -3
  372. package/dist/tui/markdown-render.js +6 -6
  373. package/dist/tui/onboarding-wizard.js +240 -0
  374. package/dist/tui/permissions-picker.js +86 -0
  375. package/dist/tui/render.js +35 -0
  376. package/dist/tui/repl-render.js +332 -54
  377. package/dist/tui/repl-splash-art.js +16 -16
  378. package/dist/tui/repl-splash-mascot.js +48 -24
  379. package/dist/tui/repl-splash.js +22 -22
  380. package/dist/tui/repl.js +124 -44
  381. package/dist/tui/slash-palette.js +6 -6
  382. package/dist/tui/splash.js +2 -2
  383. package/dist/tui/status-bar.js +109 -31
  384. package/dist/tui/status-table.js +7 -0
  385. package/dist/tui/stickers-art.js +136 -0
  386. package/dist/tui/style-table.js +28 -0
  387. package/dist/tui/theme-table.js +29 -0
  388. package/dist/tui/thinking-spinner.js +123 -0
  389. package/dist/tui/tool-stream-pane.js +53 -4
  390. package/dist/tui/update-banner.js +27 -2
  391. package/dist/tui/vim-input.js +267 -0
  392. package/dist/tui/welcome-banner.js +107 -0
  393. package/dist/tui/welcome-data.js +293 -0
  394. package/dist/tui/workspace-context.js +2 -2
  395. package/docs/examples/codegraph.mcp.json +10 -0
  396. package/package.json +23 -6
  397. package/test/scenarios/codegen-create-file.scenario.txt +13 -0
  398. package/test/scenarios/compact-force.scenario.txt +11 -0
  399. package/test/scenarios/identity.scenario.txt +11 -0
  400. package/test/scenarios/persona-handoff.scenario.txt +11 -0
  401. package/test/scenarios/walkback.scenario.txt +12 -0
  402. package/dist/core/engine/compaction-hook.js +0 -154
@@ -0,0 +1,721 @@
1
+ /**
2
+ * Plan-as-FILE artifact store (Pugi backlog).
3
+ *
4
+ * Pattern absorbed from the the upstream tool `ExitPlanMode` leak intel
5
+ * (clean-room TypeScript reimplementation — no source was copied; only
6
+ * the file-as-artifact concept). When Pugi enters plan-mode the engine
7
+ * routes the plan body to `.pugi/plans/<plan-id>.md` instead of the
8
+ * message stream so it survives `/compact`, becomes diffable across
9
+ * sessions, and stays queryable / chainable across multi-version
10
+ * iterations.
11
+ *
12
+ * Public surface (lifecycle):
13
+ *
14
+ * writePlan(taskId, body, metadata?) — create + return {planId, path}
15
+ * readPlan(planId) — load frontmatter + body
16
+ * listPlans({ taskId? }) — list, newest first
17
+ * diffPlans(planA, planB?) — unified diff (planB = latest)
18
+ * markSuperseded(planId, supersededBy) — add chain pointer
19
+ * prunePlans({ maxAgeDays }) — GC ancient plans
20
+ *
21
+ * Plan-id format (sortable + filename-safe):
22
+ *
23
+ * `pln_<base32-timestamp>_<short-hash>`
24
+ *
25
+ * - `pln_` — fixed prefix; gates listPlans + parser.
26
+ * - base32-timestamp — Crockford base32 encoding of `Date.now()`. 10
27
+ * chars at the millisecond range, monotonically
28
+ * sortable, no '_' / '-' collision with the
29
+ * separator.
30
+ * - short-hash — 8 chars from `crypto.randomBytes(5)` rendered as
31
+ * Crockford base32. Disambiguates same-ms writes
32
+ * (plan races during agent ensemble fan-out).
33
+ *
34
+ * Example: `pln_01HEZ7C2QM_X3R8WK9P`.
35
+ *
36
+ * Frontmatter schema (minimal YAML-ish, parsed without `js-yaml`):
37
+ *
38
+ * ---
39
+ * planId: pln_<base32>_<hash>
40
+ * taskId: <task-slug> # opaque caller-provided string
41
+ * createdAt: <ISO-8601 UTC>
42
+ * ttlDays: 30 # GC budget; default 30
43
+ * supersededBy: pln_… # absent unless markSuperseded() ran
44
+ * title: <one-line summary> # optional, caller-provided
45
+ * ---
46
+ *
47
+ * - One `key: value` pair per line, no quoting, no nested maps.
48
+ * - Keys validated against an allowlist (`KNOWN_FRONTMATTER_KEYS`);
49
+ * unknown keys are dropped to avoid silent typos becoming chain
50
+ * poison.
51
+ * - Body follows the closing `---\n` literally — no body escaping.
52
+ *
53
+ * Storage layout:
54
+ *
55
+ * <root>/.pugi/plans/<plan-id>.md — file mode 0o600.
56
+ * <root>/.pugi/plans/ — dir mode 0o700.
57
+ *
58
+ * Atomic write: tmp file (`<id>.md.pugi-tmp-<epoch>`) + `renameSync`.
59
+ * Mirrors `apps/pugi-cli/src/tools/file-tools.ts` `editTool` so the
60
+ * plan store inherits the same crash-tolerant write contract.
61
+ */
62
+ import { existsSync, linkSync, lstatSync, mkdirSync, readFileSync, readdirSync, renameSync, statSync, unlinkSync, writeFileSync, } from 'node:fs';
63
+ import { randomBytes } from 'node:crypto';
64
+ import { basename, join, resolve } from 'node:path';
65
+ /**
66
+ * Crockford base32 alphabet — sortable in the same order as decoded
67
+ * numeric value (lowercased here so plan-ids match the `pln_` prefix
68
+ * casing). Excludes I, L, O, U intentionally; we never include them
69
+ * in encoded output so the parser doesn't need a normalisation pass.
70
+ */
71
+ const CROCKFORD = '0123456789abcdefghjkmnpqrstvwxyz';
72
+ const PLAN_ID_RE = /^pln_[0-9a-z]{10}_[0-9a-z]{8}$/;
73
+ const DEFAULT_TTL_DAYS = 30;
74
+ const MS_PER_DAY = 86_400_000;
75
+ const KNOWN_FRONTMATTER_KEYS = new Set([
76
+ 'planId',
77
+ 'taskId',
78
+ 'createdAt',
79
+ 'ttlDays',
80
+ 'supersededBy',
81
+ 'title',
82
+ ]);
83
+ export class PlanNotFoundError extends Error {
84
+ planId;
85
+ constructor(planId) {
86
+ super(`plan not found: ${planId}`);
87
+ this.planId = planId;
88
+ this.name = 'PlanNotFoundError';
89
+ }
90
+ }
91
+ export class InvalidPlanIdError extends Error {
92
+ planId;
93
+ constructor(planId) {
94
+ super(`invalid plan id: ${planId} (expected pln_<base32-timestamp>_<short-hash>)`);
95
+ this.planId = planId;
96
+ this.name = 'InvalidPlanIdError';
97
+ }
98
+ }
99
+ /**
100
+ * Resolve the `.pugi/plans` directory under a root, creating it (and
101
+ * the parent `.pugi/`) if missing. Dir mode is 0o700 — only the owner
102
+ * should be able to enumerate plans. File mode 0o600 is enforced
103
+ * separately at write-time.
104
+ */
105
+ function plansDir(root) {
106
+ const dir = resolve(root, '.pugi', 'plans');
107
+ if (!existsSync(dir)) {
108
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
109
+ }
110
+ return dir;
111
+ }
112
+ /** Encode a non-negative integer in Crockford base32 (lowercased). */
113
+ function encodeBase32(input, length) {
114
+ if (!Number.isFinite(input) || input < 0) {
115
+ throw new Error(`encodeBase32: non-negative finite required, got ${input}`);
116
+ }
117
+ let value = Math.floor(input);
118
+ const out = [];
119
+ while (value > 0) {
120
+ const idx = value % 32;
121
+ const ch = CROCKFORD[idx];
122
+ if (ch === undefined) {
123
+ throw new Error('encodeBase32: alphabet lookup failed');
124
+ }
125
+ out.unshift(ch);
126
+ value = Math.floor(value / 32);
127
+ }
128
+ while (out.length < length) {
129
+ out.unshift('0');
130
+ }
131
+ return out.join('').slice(-length);
132
+ }
133
+ /** Encode a byte buffer as Crockford base32 (lowercased), no padding. */
134
+ function bytesToBase32(buf, length) {
135
+ let bits = 0;
136
+ let bitCount = 0;
137
+ const out = [];
138
+ for (let i = 0; i < buf.length; i += 1) {
139
+ const byte = buf[i];
140
+ if (byte === undefined)
141
+ continue;
142
+ bits = (bits << 8) | byte;
143
+ bitCount += 8;
144
+ while (bitCount >= 5 && out.length < length) {
145
+ const shift = bitCount - 5;
146
+ const idx = (bits >> shift) & 0x1f;
147
+ const ch = CROCKFORD[idx];
148
+ if (ch === undefined) {
149
+ throw new Error('bytesToBase32: alphabet lookup failed');
150
+ }
151
+ out.push(ch);
152
+ bits &= (1 << shift) - 1;
153
+ bitCount -= 5;
154
+ }
155
+ }
156
+ while (out.length < length) {
157
+ out.push('0');
158
+ }
159
+ return out.join('').slice(0, length);
160
+ }
161
+ /**
162
+ * Generate a new plan-id. Caller can override the timestamp + RNG for
163
+ * deterministic tests; production code calls with no args.
164
+ */
165
+ export function generatePlanId(now = Date.now(), rng) {
166
+ const ts = encodeBase32(now, 10);
167
+ const buf = rng ? rng() : randomBytes(5);
168
+ const hash = bytesToBase32(buf, 8);
169
+ return `pln_${ts}_${hash}`;
170
+ }
171
+ /**
172
+ * Validate a plan-id at the shape level. Returns the id unchanged on
173
+ * pass; throws `InvalidPlanIdError` on fail. Keeps the parser tight so
174
+ * stray `../../.ssh/id_rsa` injection attempts cannot reach disk.
175
+ */
176
+ export function assertValidPlanId(planId) {
177
+ if (typeof planId !== 'string' || !PLAN_ID_RE.test(planId)) {
178
+ throw new InvalidPlanIdError(planId);
179
+ }
180
+ return planId;
181
+ }
182
+ /**
183
+ * Triple-review P1-4 — escape YAML-ambiguous string values so an
184
+ * adversarial `title` containing `:`, `#`, leading `-`/`*`, leading
185
+ * whitespace, control chars, newlines, or quotes cannot break the
186
+ * frontmatter parse OR inject a second key.
187
+ *
188
+ * Strategy: if the raw value contains ANY ambiguous character, fall
189
+ * back to JSON.stringify which gives us a valid YAML-double-quoted
190
+ * scalar (YAML accepts JSON's quoting + escape rules as a strict
191
+ * superset for double-quoted flow scalars). For "boring" values we
192
+ * keep the bareword form so the round-trip stays human-readable.
193
+ *
194
+ * `planId`, `taskId`, `createdAt`, `ttlDays`, `supersededBy` are not
195
+ * routed through this escaper because they are validated upstream to a
196
+ * conservative grapheme set (regex / Number) and the bareword form is
197
+ * the only legitimate shape. Title is the one operator-supplied free
198
+ * field.
199
+ */
200
+ function yamlScalar(value) {
201
+ // Ambiguous chars from the YAML 1.2 spec + practical Pugi history:
202
+ // ':' '#' newline tab '"' "'" leading whitespace leading '-' leading '*'
203
+ // leading '?' leading '|' leading '>' leading '&' leading '!' leading '@'
204
+ // leading '`' leading '%' leading '[' leading '{' or any control char.
205
+ // Empty string is also disambiguated by quoting.
206
+ if (value.length === 0)
207
+ return '""';
208
+ if (/[-"]/.test(value)) {
209
+ return JSON.stringify(value);
210
+ }
211
+ if (/[:#\n\t]/.test(value)) {
212
+ return JSON.stringify(value);
213
+ }
214
+ if (/^[\s\-*?|>&!@`%[{]/.test(value)) {
215
+ return JSON.stringify(value);
216
+ }
217
+ return value;
218
+ }
219
+ /** Serialize frontmatter + body into the on-disk envelope. */
220
+ function serializePlan(frontmatter, body) {
221
+ const lines = ['---'];
222
+ // Stable key order — keeps round-trip deterministic for tests.
223
+ // planId / taskId / createdAt / supersededBy are validated upstream
224
+ // to safe shapes; ttlDays is a number. Title is operator-supplied
225
+ // free text → route through `yamlScalar`.
226
+ lines.push(`planId: ${frontmatter.planId}`);
227
+ lines.push(`taskId: ${yamlScalar(frontmatter.taskId)}`);
228
+ lines.push(`createdAt: ${frontmatter.createdAt}`);
229
+ lines.push(`ttlDays: ${frontmatter.ttlDays}`);
230
+ if (frontmatter.supersededBy !== undefined) {
231
+ lines.push(`supersededBy: ${frontmatter.supersededBy}`);
232
+ }
233
+ if (frontmatter.title !== undefined) {
234
+ lines.push(`title: ${yamlScalar(frontmatter.title)}`);
235
+ }
236
+ lines.push('---');
237
+ lines.push('');
238
+ return `${lines.join('\n')}${body.endsWith('\n') ? body : `${body}\n`}`;
239
+ }
240
+ /**
241
+ * Triple-review P1-4 (parse side) — decode the scalar form
242
+ * `serializePlan` produces. Bareword inputs pass through; a JSON-quoted
243
+ * scalar is unquoted via JSON.parse so the value matches what the
244
+ * writer recorded. Invalid quoted scalars surface as a clear parse
245
+ * error so a corrupt plan never silently returns half-decoded data.
246
+ */
247
+ function parseYamlScalar(raw, path, key) {
248
+ if (raw.length === 0)
249
+ return raw;
250
+ if (raw.startsWith('"')) {
251
+ try {
252
+ const decoded = JSON.parse(raw);
253
+ if (typeof decoded !== 'string') {
254
+ throw new Error(`expected string scalar`);
255
+ }
256
+ return decoded;
257
+ }
258
+ catch (err) {
259
+ throw new Error(`plan file ${path}: invalid quoted scalar for '${key}': ${err.message}`);
260
+ }
261
+ }
262
+ return raw;
263
+ }
264
+ /**
265
+ * Parse the on-disk envelope. Tolerant of trailing whitespace on
266
+ * frontmatter values and missing `title` / `supersededBy`. Throws if
267
+ * a required key is missing OR the frontmatter delimiter is absent —
268
+ * a corrupt plan file should never silently return a half-state record.
269
+ *
270
+ * Triple-review P1-2 — also asserts that the on-disk filename
271
+ * basename matches the `planId` in the frontmatter. Defends against
272
+ * rename-then-edit drift where someone (an editor, an agent, a CI
273
+ * step) renamed `<a>.md` к `<b>.md` without rewriting the body.
274
+ */
275
+ function parsePlan(text, path) {
276
+ const lines = text.split('\n');
277
+ if (lines[0] !== '---') {
278
+ throw new Error(`plan file missing opening '---': ${path}`);
279
+ }
280
+ const closingIdx = lines.indexOf('---', 1);
281
+ if (closingIdx === -1) {
282
+ throw new Error(`plan file missing closing '---': ${path}`);
283
+ }
284
+ const fm = {};
285
+ for (let i = 1; i < closingIdx; i += 1) {
286
+ const line = lines[i];
287
+ if (line === undefined)
288
+ continue;
289
+ const sepIdx = line.indexOf(':');
290
+ if (sepIdx === -1)
291
+ continue;
292
+ const rawKey = line.slice(0, sepIdx).trim();
293
+ const rawVal = line.slice(sepIdx + 1).trim();
294
+ if (!KNOWN_FRONTMATTER_KEYS.has(rawKey))
295
+ continue;
296
+ if (rawKey === 'ttlDays') {
297
+ const n = Number(rawVal);
298
+ if (!Number.isFinite(n) || n <= 0) {
299
+ throw new Error(`plan file ${path}: invalid ttlDays '${rawVal}'`);
300
+ }
301
+ fm.ttlDays = n;
302
+ }
303
+ else if (rawKey === 'title' || rawKey === 'taskId') {
304
+ // Operator / caller free-text fields — decode through the
305
+ // YAML-scalar parser к round-trip the writer's quoting.
306
+ fm[rawKey] = parseYamlScalar(rawVal, path, rawKey);
307
+ }
308
+ else {
309
+ // planId / createdAt / supersededBy — validated upstream к safe
310
+ // shapes; bareword.
311
+ fm[rawKey] = rawVal;
312
+ }
313
+ }
314
+ if (!fm.planId || !fm.taskId || !fm.createdAt || fm.ttlDays === undefined) {
315
+ throw new Error(`plan file ${path}: frontmatter missing required keys (planId/taskId/createdAt/ttlDays)`);
316
+ }
317
+ // Re-validate the on-disk planId — defends against rename-tampering
318
+ // where the filename was renamed but the body planId was not (or
319
+ // vice-versa). The caller will trust frontmatter, not the basename.
320
+ assertValidPlanId(fm.planId);
321
+ // Triple-review P1-2 — assert filename ↔ frontmatter coherence.
322
+ // The on-disk basename MUST equal `<planId>.md`; mismatch indicates
323
+ // tampering and we refuse loud rather than returning a record whose
324
+ // `path` and `planId` point at different artifacts.
325
+ const expectedBasename = `${fm.planId}.md`;
326
+ const actualBasename = basename(path);
327
+ if (actualBasename !== expectedBasename) {
328
+ throw new Error(`plan file ${path}: filename '${actualBasename}' does not match frontmatter planId '${fm.planId}'`);
329
+ }
330
+ const body = lines.slice(closingIdx + 1).join('\n').replace(/^\n/, '');
331
+ return {
332
+ frontmatter: fm,
333
+ body,
334
+ path,
335
+ };
336
+ }
337
+ /**
338
+ * Triple-review P1-1 — reject any pre-existing symlink at the
339
+ * target plan path. `existsSync` follows symlinks, so a hostile
340
+ * symlink at `.pugi/plans/<id>.md` pointing к an arbitrary location
341
+ * would let a write escape the plan dir. `lstatSync` inspects the link
342
+ * itself; we refuse loud rather than silently following it.
343
+ *
344
+ * Returns true when the path is safe (does not exist OR exists as a
345
+ * regular file); throws when the path exists as a symlink. Other entry
346
+ * types (directory, socket, fifo, ...) also throw because they are
347
+ * never legitimate plan targets.
348
+ */
349
+ function assertPlanPathSafe(targetPath) {
350
+ let stats;
351
+ try {
352
+ stats = lstatSync(targetPath);
353
+ }
354
+ catch (err) {
355
+ const code = err.code;
356
+ if (code === 'ENOENT' || code === 'ENOTDIR')
357
+ return;
358
+ throw err;
359
+ }
360
+ if (stats.isSymbolicLink()) {
361
+ throw new Error(`plan path '${targetPath}' is a symlink — refusing к follow (security)`);
362
+ }
363
+ if (!stats.isFile()) {
364
+ throw new Error(`plan path '${targetPath}' exists but is not a regular file (type=${stats.mode & 0o170000})`);
365
+ }
366
+ }
367
+ /**
368
+ * Atomically write a new plan to disk. Returns the generated `planId`
369
+ * and absolute `path`. Plan-id collisions are statistically
370
+ * negligible (40-bit hash + ms timestamp); on the freak collision we
371
+ * regenerate up to 3 times before bubbling an error.
372
+ *
373
+ * Triple-review P1-1 +-3 — write path is now TOCTOU-free:
374
+ *
375
+ * 1. `assertPlanPathSafe` rejects а pre-existing symlink before we
376
+ * touch the filesystem (defends against `.pugi/plans/<id>.md`
377
+ * being a planted alias к `.ssh/id_rsa`).
378
+ * 2. The tmp + `linkSync` + `unlinkSync(tmp)` sequence is the
379
+ * POSIX atomic-claim idiom: linkSync fails with EEXIST when the
380
+ * target is already present, so two racing writers cannot both
381
+ * `existsSync = false`-then-`writeFile` over each other. This
382
+ * replaces the previous `existsSync` check that opened а
383
+ * check-then-write window.
384
+ */
385
+ export function writePlan(taskId, planText, metadata = {}, options = {}) {
386
+ if (typeof taskId !== 'string' || taskId.length === 0) {
387
+ throw new Error('writePlan: taskId must be a non-empty string');
388
+ }
389
+ if (typeof planText !== 'string') {
390
+ throw new Error('writePlan: planText must be a string');
391
+ }
392
+ const root = options.root ?? process.cwd();
393
+ const dir = plansDir(root);
394
+ const ttlDays = clampTtl(metadata.ttlDays ?? DEFAULT_TTL_DAYS);
395
+ let planId = '';
396
+ let target = '';
397
+ for (let attempt = 0; attempt < 3; attempt += 1) {
398
+ planId = generatePlanId(options.now ?? Date.now());
399
+ target = join(dir, `${planId}.md`);
400
+ // lstat-based safety — refuses symlinks AND surfaces dir / socket
401
+ // / fifo as errors. existsSync would have silently followed а
402
+ // hostile symlink.
403
+ assertPlanPathSafe(target);
404
+ if (!existsSync(target))
405
+ break;
406
+ if (attempt === 2) {
407
+ throw new Error(`writePlan: failed to allocate unique plan id after 3 attempts`);
408
+ }
409
+ }
410
+ const frontmatter = {
411
+ planId,
412
+ taskId,
413
+ createdAt: new Date(options.now ?? Date.now()).toISOString(),
414
+ ttlDays,
415
+ ...(metadata.title !== undefined ? { title: metadata.title } : {}),
416
+ };
417
+ const envelope = serializePlan(frontmatter, planText);
418
+ const tmp = `${target}.pugi-tmp-${Date.now()}-${process.pid}`;
419
+ writeFileSync(tmp, envelope, { encoding: 'utf8', mode: 0o600 });
420
+ // Atomic claim: linkSync(tmp, target) succeeds iff `target` does not
421
+ // exist (errno EEXIST otherwise — surfaced as а clear error). The
422
+ // tmp is then unlinked. Cross-filesystem links are not а concern
423
+ // because tmp + target live in the same dir.
424
+ try {
425
+ linkSync(tmp, target);
426
+ }
427
+ catch (err) {
428
+ // Best-effort cleanup of the orphan tmp before rethrowing.
429
+ try {
430
+ unlinkSync(tmp);
431
+ }
432
+ catch {
433
+ /* ignore */
434
+ }
435
+ const code = err.code;
436
+ if (code === 'EEXIST') {
437
+ throw new Error(`writePlan: plan ${planId}.md already exists; use а different planId or remove the existing file`);
438
+ }
439
+ throw err;
440
+ }
441
+ // Drop the tmp — the inode is now linked at `target` so the data is
442
+ // safe even if the unlink fails (we then leak а tmp file, recoverable
443
+ // by а future GC). Wrapped in а best-effort so the unlink failure
444
+ // does not surface as а write failure.
445
+ try {
446
+ unlinkSync(tmp);
447
+ }
448
+ catch {
449
+ /* ignore — tmp leak is recoverable */
450
+ }
451
+ return { planId, path: target };
452
+ }
453
+ function clampTtl(raw) {
454
+ if (!Number.isFinite(raw))
455
+ return DEFAULT_TTL_DAYS;
456
+ if (raw < 1)
457
+ return 1;
458
+ if (raw > 365)
459
+ return 365;
460
+ return Math.floor(raw);
461
+ }
462
+ /** Load a plan record by id. Throws `PlanNotFoundError` if missing. */
463
+ export function readPlan(planId, options = {}) {
464
+ assertValidPlanId(planId);
465
+ const root = options.root ?? process.cwd();
466
+ const target = join(plansDir(root), `${planId}.md`);
467
+ if (!existsSync(target)) {
468
+ throw new PlanNotFoundError(planId);
469
+ }
470
+ const text = readFileSync(target, 'utf8');
471
+ return parsePlan(text, target);
472
+ }
473
+ /**
474
+ * Enumerate plans newest-first, optionally filtered by taskId. Files
475
+ * with malformed frontmatter are silently skipped — they will surface
476
+ * in the next `/plan diff` attempt against them.
477
+ */
478
+ export function listPlans(options = {}) {
479
+ const root = options.root ?? process.cwd();
480
+ const dir = plansDir(root);
481
+ const entries = readdirSync(dir).filter((name) => name.endsWith('.md'));
482
+ const records = [];
483
+ for (const name of entries) {
484
+ const planId = name.slice(0, -'.md'.length);
485
+ if (!PLAN_ID_RE.test(planId))
486
+ continue;
487
+ try {
488
+ const record = readPlan(planId, { root });
489
+ if (options.taskId && record.frontmatter.taskId !== options.taskId) {
490
+ continue;
491
+ }
492
+ records.push(record);
493
+ }
494
+ catch {
495
+ // Malformed plan files are skipped; the maintainer can run
496
+ // `/plan show <id>` to surface the parse error explicitly.
497
+ continue;
498
+ }
499
+ }
500
+ // Sort newest first by createdAt (ISO-8601 sorts lexicographically).
501
+ records.sort((a, b) => (a.frontmatter.createdAt < b.frontmatter.createdAt ? 1 : -1));
502
+ return records;
503
+ }
504
+ /**
505
+ * Compute a unified diff between two plans. When `planB` is omitted,
506
+ * diffs `planA` against the most recent plan that is NOT `planA`. A
507
+ * small in-process diff implementation avoids pulling in a `diff` dep —
508
+ * the algorithm is the well-known Hunt-Szymanski-lite LCS adequate for
509
+ * line-oriented prose under ~10k lines.
510
+ */
511
+ export function diffPlans(planA, planB, options = {}) {
512
+ const root = options.root ?? process.cwd();
513
+ const recordA = readPlan(planA, { root });
514
+ let recordB;
515
+ if (planB) {
516
+ recordB = readPlan(planB, { root });
517
+ }
518
+ else {
519
+ const all = listPlans({ root });
520
+ const other = all.find((rec) => rec.frontmatter.planId !== planA);
521
+ if (!other) {
522
+ throw new PlanNotFoundError('<latest-other>');
523
+ }
524
+ recordB = other;
525
+ }
526
+ return unifiedDiff(`${recordB.frontmatter.planId}.md`, `${recordA.frontmatter.planId}.md`, recordB.body, recordA.body);
527
+ }
528
+ /**
529
+ * Update an existing plan to record that it has been superseded by
530
+ * another plan-id. Both ids must exist on disk — we refuse to write a
531
+ * dangling pointer. Re-writes the file atomically.
532
+ */
533
+ export function markSuperseded(planId, supersededBy, options = {}) {
534
+ assertValidPlanId(planId);
535
+ assertValidPlanId(supersededBy);
536
+ if (planId === supersededBy) {
537
+ throw new Error(`markSuperseded: plan cannot supersede itself (${planId})`);
538
+ }
539
+ const root = options.root ?? process.cwd();
540
+ const current = readPlan(planId, { root });
541
+ // Confirm the successor exists too — refuse dangling pointers so
542
+ // chain-walks in the runtime can trust the graph.
543
+ readPlan(supersededBy, { root });
544
+ const next = {
545
+ ...current.frontmatter,
546
+ supersededBy,
547
+ };
548
+ const target = join(plansDir(root), `${planId}.md`);
549
+ // Triple-review P1-1 — symlink check before the rewrite. The
550
+ // existing target MUST be а regular file; а symlink swapped в
551
+ // between `readPlan` and this point would otherwise let an attacker
552
+ // redirect the atomic rename к а protected basename.
553
+ assertPlanPathSafe(target);
554
+ const tmp = `${target}.pugi-tmp-${Date.now()}-${process.pid}`;
555
+ const envelope = serializePlan(next, current.body);
556
+ writeFileSync(tmp, envelope, { encoding: 'utf8', mode: 0o600 });
557
+ try {
558
+ // renameSync is the right primitive HERE (in markSuperseded) — we
559
+ // are intentionally overwriting an existing plan. writePlan uses
560
+ // linkSync because it MUST refuse pre-existing targets; the two
561
+ // semantics are intentionally different.
562
+ renameSync(tmp, target);
563
+ }
564
+ catch (err) {
565
+ try {
566
+ unlinkSync(tmp);
567
+ }
568
+ catch {
569
+ /* ignore */
570
+ }
571
+ throw err;
572
+ }
573
+ return { frontmatter: next, body: current.body, path: target };
574
+ }
575
+ /**
576
+ * Garbage-collect plans older than `maxAgeDays`. Default budget is 30
577
+ * days, matching the default `ttlDays` on `writePlan`. Plans flagged
578
+ * with their own larger `ttlDays` are preserved beyond the sweep
579
+ * window — the per-plan TTL wins over the sweep floor.
580
+ */
581
+ export function prunePlans(options = {}) {
582
+ const root = options.root ?? process.cwd();
583
+ const dir = plansDir(root);
584
+ const floorDays = options.maxAgeDays ?? DEFAULT_TTL_DAYS;
585
+ const now = Date.now();
586
+ const removed = [];
587
+ for (const name of readdirSync(dir)) {
588
+ if (!name.endsWith('.md'))
589
+ continue;
590
+ const planId = name.slice(0, -'.md'.length);
591
+ if (!PLAN_ID_RE.test(planId))
592
+ continue;
593
+ const target = join(dir, name);
594
+ let record;
595
+ try {
596
+ record = readPlan(planId, { root });
597
+ }
598
+ catch {
599
+ // Malformed plan files are removed too — they cannot be
600
+ // recovered and they shadow the listing. Belt-and-braces with
601
+ // mtime fallback so a brand-new corrupt file is not wiped if
602
+ // its mtime is below the floor.
603
+ const stat = statSync(target);
604
+ const ageDays = (now - stat.mtimeMs) / MS_PER_DAY;
605
+ if (ageDays > floorDays) {
606
+ try {
607
+ unlinkSync(target);
608
+ removed.push(planId);
609
+ }
610
+ catch {
611
+ /* ignore */
612
+ }
613
+ }
614
+ continue;
615
+ }
616
+ const createdMs = Date.parse(record.frontmatter.createdAt);
617
+ if (!Number.isFinite(createdMs))
618
+ continue;
619
+ const ageDays = (now - createdMs) / MS_PER_DAY;
620
+ const ttl = Math.max(record.frontmatter.ttlDays, floorDays);
621
+ if (ageDays > ttl) {
622
+ try {
623
+ unlinkSync(target);
624
+ removed.push(planId);
625
+ }
626
+ catch {
627
+ /* ignore */
628
+ }
629
+ }
630
+ }
631
+ return { cleaned: removed.length, removedIds: removed };
632
+ }
633
+ /**
634
+ * Minimal unified-diff renderer. Uses an O(n*m) DP table; adequate for
635
+ * the plan body sizes we expect (sub-kB to mid-kB Markdown). Output
636
+ * matches the GNU `diff -u` envelope so existing CLI tooling (`less
637
+ * -R`, `delta`, etc.) can colourise it without translation.
638
+ */
639
+ function unifiedDiff(fromName, toName, fromText, toText) {
640
+ const a = fromText.split('\n');
641
+ const b = toText.split('\n');
642
+ const n = a.length;
643
+ const m = b.length;
644
+ // LCS DP table.
645
+ const dp = Array.from({ length: n + 1 }, () => new Array(m + 1).fill(0));
646
+ for (let i = n - 1; i >= 0; i -= 1) {
647
+ for (let j = m - 1; j >= 0; j -= 1) {
648
+ const rowI = dp[i];
649
+ const rowI1 = dp[i + 1];
650
+ if (!rowI || !rowI1)
651
+ continue;
652
+ const ai = a[i];
653
+ const bj = b[j];
654
+ const next = rowI1[j + 1] ?? 0;
655
+ const down = rowI1[j] ?? 0;
656
+ const right = rowI[j + 1] ?? 0;
657
+ if (ai === bj) {
658
+ rowI[j] = next + 1;
659
+ }
660
+ else {
661
+ rowI[j] = Math.max(down, right);
662
+ }
663
+ }
664
+ }
665
+ const ops = [];
666
+ let i = 0;
667
+ let j = 0;
668
+ while (i < n && j < m) {
669
+ const ai = a[i];
670
+ const bj = b[j];
671
+ const rowI1 = dp[i + 1];
672
+ const rowI = dp[i];
673
+ const down = rowI1?.[j] ?? 0;
674
+ const right = rowI?.[j + 1] ?? 0;
675
+ if (ai === bj) {
676
+ ops.push({ kind: 'eq', line: ai ?? '' });
677
+ i += 1;
678
+ j += 1;
679
+ }
680
+ else if (down >= right) {
681
+ ops.push({ kind: 'del', line: ai ?? '' });
682
+ i += 1;
683
+ }
684
+ else {
685
+ ops.push({ kind: 'add', line: bj ?? '' });
686
+ j += 1;
687
+ }
688
+ }
689
+ while (i < n) {
690
+ ops.push({ kind: 'del', line: a[i] ?? '' });
691
+ i += 1;
692
+ }
693
+ while (j < m) {
694
+ ops.push({ kind: 'add', line: b[j] ?? '' });
695
+ j += 1;
696
+ }
697
+ // Render. We emit one big hunk that spans the whole document — fine
698
+ // for plan-sized prose and keeps the renderer simple. Header counts
699
+ // are the full file lengths because hunk == file.
700
+ const out = [];
701
+ out.push(`--- a/${fromName}`);
702
+ out.push(`+++ b/${toName}`);
703
+ out.push(`@@ -1,${n} +1,${m} @@`);
704
+ for (const op of ops) {
705
+ if (op.kind === 'eq')
706
+ out.push(` ${op.line}`);
707
+ else if (op.kind === 'del')
708
+ out.push(`-${op.line}`);
709
+ else
710
+ out.push(`+${op.line}`);
711
+ }
712
+ return out.join('\n');
713
+ }
714
+ /** Test-only accessor — kept for future tooling that needs to peek. */
715
+ export const __test__ = {
716
+ PLAN_ID_RE,
717
+ CROCKFORD,
718
+ KNOWN_FRONTMATTER_KEYS,
719
+ DEFAULT_TTL_DAYS,
720
+ };
721
+ //# sourceMappingURL=plan-artifact.js.map