@hassangameryt/freeflow 0.5.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (301) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/.claude-plugin/plugin.json +2 -2
  3. package/.codex-plugin/plugin.json +4 -5
  4. package/README.md +141 -163
  5. package/capabilities/cognitive-routing/SKILL.md +387 -0
  6. package/capabilities/context-virtualization/SKILL.md +103 -0
  7. package/capabilities/conversation-history/SKILL.md +53 -0
  8. package/command-surface.json +6 -37
  9. package/hooks/freeflow-runtime-context.mjs +50 -541
  10. package/hooks/hooks.json +1 -26
  11. package/hooks/tests/check-runtime-context-hook.sh +114 -308
  12. package/package.json +27 -17
  13. package/pi-extension/dist/cognitive-routing/commands.js +96 -0
  14. package/pi-extension/dist/cognitive-routing/config.js +232 -0
  15. package/pi-extension/dist/cognitive-routing/controller.js +1292 -0
  16. package/pi-extension/dist/cognitive-routing/history.js +451 -0
  17. package/pi-extension/dist/cognitive-routing/host.js +188 -0
  18. package/pi-extension/dist/cognitive-routing/pi-routing-session.js +414 -0
  19. package/pi-extension/dist/cognitive-routing/pi-session-control.js +320 -0
  20. package/pi-extension/dist/cognitive-routing/runtime.js +43 -0
  21. package/pi-extension/dist/cognitive-routing/tool.js +212 -0
  22. package/pi-extension/dist/cognitive-routing/types.js +6 -0
  23. package/pi-extension/dist/context-virtualization/commands.js +89 -0
  24. package/pi-extension/dist/context-virtualization/projector.js +42 -0
  25. package/pi-extension/dist/context-virtualization/runtime.js +356 -0
  26. package/pi-extension/dist/context-virtualization/state.js +57 -0
  27. package/pi-extension/dist/context-virtualization/types.js +10 -0
  28. package/pi-extension/dist/conversation-history/passages.js +66 -0
  29. package/pi-extension/dist/conversation-history/ranking.js +105 -0
  30. package/pi-extension/dist/conversation-history/runtime.js +226 -0
  31. package/pi-extension/dist/conversation-history/search.js +56 -0
  32. package/pi-extension/dist/conversation-history/types.js +1 -0
  33. package/pi-extension/dist/freeflow-context/resolver.js +120 -0
  34. package/pi-extension/dist/freeflow-context/runtime.js +80 -0
  35. package/pi-extension/dist/freeflow-context/source-projector.js +95 -0
  36. package/pi-extension/dist/freeflow-context/tool.js +308 -0
  37. package/pi-extension/dist/freeflow-context/types.js +12 -0
  38. package/pi-extension/dist/freeflow-context/visibility.js +28 -0
  39. package/pi-extension/dist/index.js +564 -129
  40. package/pi-extension/dist/runtime/runtime-context.js +357 -470
  41. package/pi-extension/dist/runtime/runtime-identity.js +5 -0
  42. package/pi-extension/dist/settings/settings-tui.js +78 -0
  43. package/pi-extension/dist/settings/settings-ui.js +572 -826
  44. package/pi-extension/dist/ui/text-component.js +57 -0
  45. package/pi-extension/src/cognitive-routing/commands.ts +129 -0
  46. package/pi-extension/src/cognitive-routing/config.ts +303 -0
  47. package/pi-extension/src/cognitive-routing/controller.ts +1628 -0
  48. package/pi-extension/src/cognitive-routing/history.ts +650 -0
  49. package/pi-extension/src/cognitive-routing/host.ts +266 -0
  50. package/pi-extension/src/cognitive-routing/pi-routing-session.ts +538 -0
  51. package/pi-extension/src/cognitive-routing/pi-session-control.ts +444 -0
  52. package/pi-extension/src/cognitive-routing/runtime.ts +57 -0
  53. package/pi-extension/src/cognitive-routing/tool.ts +273 -0
  54. package/pi-extension/src/cognitive-routing/types.ts +89 -0
  55. package/pi-extension/src/context-virtualization/commands.ts +111 -0
  56. package/pi-extension/src/context-virtualization/projector.ts +62 -0
  57. package/pi-extension/src/context-virtualization/runtime.ts +406 -0
  58. package/pi-extension/src/context-virtualization/state.ts +79 -0
  59. package/pi-extension/src/context-virtualization/types.ts +92 -0
  60. package/pi-extension/src/conversation-history/passages.ts +81 -0
  61. package/pi-extension/src/conversation-history/ranking.ts +155 -0
  62. package/pi-extension/src/conversation-history/runtime.ts +250 -0
  63. package/pi-extension/src/conversation-history/search.ts +79 -0
  64. package/pi-extension/src/conversation-history/types.ts +31 -0
  65. package/pi-extension/src/freeflow-context/resolver.ts +139 -0
  66. package/pi-extension/src/freeflow-context/runtime.ts +100 -0
  67. package/pi-extension/src/freeflow-context/source-projector.ts +106 -0
  68. package/pi-extension/src/freeflow-context/tool.ts +360 -0
  69. package/pi-extension/src/freeflow-context/types.ts +70 -0
  70. package/pi-extension/src/freeflow-context/visibility.ts +53 -0
  71. package/pi-extension/src/index.ts +597 -135
  72. package/pi-extension/src/runtime/runtime-context.ts +373 -491
  73. package/pi-extension/src/runtime/runtime-identity.ts +8 -0
  74. package/pi-extension/src/settings/settings-tui.ts +93 -0
  75. package/pi-extension/src/settings/settings-ui.ts +679 -910
  76. package/pi-extension/src/ui/text-component.ts +66 -0
  77. package/pi-extension/tests/cognitive-routing/commands.test.js +134 -0
  78. package/pi-extension/tests/cognitive-routing/controller.test.js +1128 -0
  79. package/pi-extension/tests/cognitive-routing/extension-lifecycle.test.js +1142 -0
  80. package/pi-extension/tests/cognitive-routing/history.test.js +274 -0
  81. package/pi-extension/tests/cognitive-routing/host-fixture.js +4 -0
  82. package/pi-extension/tests/cognitive-routing/host-identity.test.js +63 -0
  83. package/pi-extension/tests/cognitive-routing/pi-normal-lifecycle.test.js +434 -0
  84. package/pi-extension/tests/cognitive-routing/pi-session-control.test.js +174 -0
  85. package/pi-extension/tests/cognitive-routing/pi-session-history.test.js +91 -0
  86. package/pi-extension/tests/cognitive-routing/profile-resolution.test.js +279 -0
  87. package/pi-extension/tests/cognitive-routing/tool.test.js +230 -0
  88. package/pi-extension/tests/context-virtualization/extension.test.js +749 -0
  89. package/pi-extension/tests/context-virtualization/projector.test.js +110 -0
  90. package/pi-extension/tests/context-virtualization/runtime.test.js +216 -0
  91. package/pi-extension/tests/conversation-history/runtime.test.js +98 -0
  92. package/pi-extension/tests/conversation-history/search.test.js +97 -0
  93. package/pi-extension/tests/integration/mode-free-core.test.js +218 -0
  94. package/pi-extension/tests/integration/pi-extension.test.js +532 -3701
  95. package/pi-extension/tests/integration/prompt-architecture.test.js +350 -0
  96. package/pi-extension/tests/integration/unaffected-regressions.test.js +411 -0
  97. package/runtime/prompts/cognitive-routing.md +10 -0
  98. package/runtime/prompts/context-virtualization.md +3 -0
  99. package/runtime/prompts/conversation-history.md +3 -0
  100. package/runtime/prompts/core.md +84 -0
  101. package/runtime/prompts/interaction-contract.md +11 -0
  102. package/skills/action-selection/SKILL.md +140 -0
  103. package/skills/action-selection/references/trajectory-stalls.md +71 -0
  104. package/skills/bypass/SKILL.md +109 -38
  105. package/skills/commit-work/SKILL.md +94 -55
  106. package/skills/commit-work/references/git-state-edges.md +94 -0
  107. package/skills/commit-work/references/simple-push.md +92 -0
  108. package/skills/commit-work/references/staging-decisions.md +79 -46
  109. package/skills/decision-gate/SKILL.md +80 -22
  110. package/skills/design-for-depth/SKILL.md +206 -60
  111. package/skills/design-for-depth/references/design-pressure-signals.md +108 -240
  112. package/skills/design-for-depth/references/interface-design-loop.md +77 -97
  113. package/skills/design-for-depth/references/module-and-dependency-design.md +147 -0
  114. package/skills/design-for-depth/references/software-design-philosophy.md +128 -174
  115. package/skills/design-for-depth/references/state-and-failure-boundaries.md +136 -0
  116. package/skills/diagnose-failure/SKILL.md +200 -48
  117. package/skills/diagnose-failure/references/diagnostic-loop-catalog.md +18 -6
  118. package/skills/diagnose-failure/references/{flaky-and-performance.md → flaky-and-performance-diagnosis.md} +13 -5
  119. package/skills/discuss/SKILL.md +119 -65
  120. package/skills/discuss/references/discussion-continuity.md +123 -0
  121. package/skills/evaluate-skill/SKILL.md +166 -52
  122. package/skills/evaluate-skill/references/{definition-schema.md → evaluation-definition-schema.md} +43 -3
  123. package/skills/evaluate-skill/references/evaluation-design.md +56 -30
  124. package/skills/evaluate-skill/references/execution-and-evidence.md +8 -3
  125. package/skills/evaluate-skill/references/review-and-revision.md +62 -21
  126. package/skills/evaluate-skill/scripts/lib/definitions.mjs +114 -3
  127. package/skills/evaluate-skill/scripts/lib/grade-interaction.mjs +156 -1
  128. package/skills/evaluate-skill/scripts/lib/grade.mjs +9 -1
  129. package/skills/evaluate-skill/scripts/lib/pi.mjs +147 -32
  130. package/skills/evaluate-skill/scripts/lib/rpc.mjs +4 -4
  131. package/skills/evaluate-skill/scripts/lib/runner.mjs +36 -14
  132. package/skills/evaluate-skill/scripts/lib/sandbox.mjs +92 -0
  133. package/skills/evaluate-skill/scripts/pi-guard.mjs +1 -1
  134. package/skills/evaluate-skill/scripts/pi-observer.mjs +66 -0
  135. package/skills/evaluate-skill/scripts/skill-eval.mjs +6 -5
  136. package/skills/execute-work/SKILL.md +99 -57
  137. package/skills/execute-work/references/code-practices.md +4 -4
  138. package/skills/execute-work/references/execute-work-edges.md +62 -0
  139. package/skills/finish-branch/SKILL.md +2 -2
  140. package/skills/finish-branch/references/integration-options.md +1 -1
  141. package/skills/handoff/SKILL.md +3 -3
  142. package/skills/launch-work/SKILL.md +1 -1
  143. package/skills/launch-work/references/launch-readiness.md +2 -2
  144. package/skills/migration-work/SKILL.md +2 -2
  145. package/skills/migration-work/references/migration-lifecycle.md +1 -1
  146. package/skills/release-work/SKILL.md +1 -1
  147. package/skills/release-work/references/release-evidence.md +1 -1
  148. package/skills/review-artifact/SKILL.md +129 -66
  149. package/skills/review-artifact/references/adjudicate-artifact-review.md +101 -0
  150. package/skills/review-artifact/references/independent-artifact-reviewer-contract.md +159 -0
  151. package/skills/review-work/SKILL.md +113 -68
  152. package/skills/review-work/references/adjudicate-work-review.md +97 -0
  153. package/skills/review-work/references/independent-work-reviewer-contract.md +139 -0
  154. package/skills/review-work/references/security-risk-lens.md +18 -16
  155. package/skills/setup-freeflow/SKILL.md +16 -17
  156. package/skills/setup-freeflow/references/activation-contract.md +24 -30
  157. package/skills/setup-freeflow/references/host-setup.md +6 -7
  158. package/skills/simplify-code/SKILL.md +97 -39
  159. package/skills/simplify-code/references/simplification-patterns.md +1 -1
  160. package/skills/tdd/SKILL.md +100 -53
  161. package/skills/tdd/references/test-design.md +3 -3
  162. package/skills/track-work/SKILL.md +195 -58
  163. package/skills/track-work/references/working-record-format.md +515 -0
  164. package/skills/track-work/scripts/lib/document.mjs +713 -0
  165. package/skills/track-work/scripts/lib/format.mjs +166 -0
  166. package/skills/track-work/scripts/lib/store.mjs +233 -0
  167. package/skills/track-work/scripts/lib/transitions.mjs +790 -0
  168. package/skills/track-work/scripts/lib/views.mjs +40 -0
  169. package/skills/track-work/scripts/working-record.mjs +316 -0
  170. package/skills/verify-work/SKILL.md +57 -19
  171. package/skills/verify-work/references/browser-runtime-evidence.md +2 -2
  172. package/skills/verify-work/references/integration-evidence.md +1 -7
  173. package/skills/verify-work/references/performance-evidence.md +2 -2
  174. package/skills/workflow/SKILL.md +137 -55
  175. package/skills/workflow/references/domain-skill-composition.md +26 -40
  176. package/skills/write-plan/SKILL.md +1 -1
  177. package/skills/write-skill/SKILL.md +218 -61
  178. package/skills/write-skill/references/activation-boundaries.md +63 -21
  179. package/skills/write-skill/references/agent-first-instructions.md +61 -27
  180. package/skills/write-skill/references/progressive-disclosure.md +97 -33
  181. package/skills/write-skill/references/skill-dependency-graphs.md +190 -0
  182. package/capabilities/output-router/SKILL.md +0 -206
  183. package/capabilities/output-router/references/safety-policy.md +0 -40
  184. package/capabilities/output-router/references/setup.md +0 -110
  185. package/pi-extension/dist/output-router/host-producer-identification.js +0 -232
  186. package/pi-extension/dist/output-router/native-safety-net.js +0 -216
  187. package/pi-extension/dist/output-router/observed-tool-routing.js +0 -122
  188. package/pi-extension/dist/output-router/renderers.js +0 -1023
  189. package/pi-extension/dist/output-router/router-tools.js +0 -554
  190. package/pi-extension/dist/output-router/schemas.js +0 -383
  191. package/pi-extension/dist/output-router/status.js +0 -744
  192. package/pi-extension/dist/output-router/utils.js +0 -502
  193. package/pi-extension/src/output-router/host-producer-identification.ts +0 -256
  194. package/pi-extension/src/output-router/native-safety-net.ts +0 -248
  195. package/pi-extension/src/output-router/observed-tool-routing.ts +0 -134
  196. package/pi-extension/src/output-router/renderers.ts +0 -1108
  197. package/pi-extension/src/output-router/router-tools.ts +0 -579
  198. package/pi-extension/src/output-router/schemas.ts +0 -387
  199. package/pi-extension/src/output-router/status.ts +0 -791
  200. package/pi-extension/src/output-router/utils.ts +0 -554
  201. package/pi-extension/tests/output-router/observed-producers.test.js +0 -132
  202. package/pi-extension/tests/output-router/search.test.js +0 -722
  203. package/router/dist/benchmarks/benchmark-harness.d.ts +0 -35
  204. package/router/dist/benchmarks/benchmark-harness.js +0 -92
  205. package/router/dist/benchmarks/benchmarks.d.ts +0 -109
  206. package/router/dist/benchmarks/benchmarks.js +0 -979
  207. package/router/dist/benchmarks/codex-qa-benchmarks.d.ts +0 -95
  208. package/router/dist/benchmarks/codex-qa-benchmarks.js +0 -500
  209. package/router/dist/benchmarks/command-benchmarks.d.ts +0 -143
  210. package/router/dist/benchmarks/command-benchmarks.js +0 -698
  211. package/router/dist/benchmarks/context-mode-normalized-benchmarks.d.ts +0 -82
  212. package/router/dist/benchmarks/context-mode-normalized-benchmarks.js +0 -773
  213. package/router/dist/benchmarks/context-mode-real-deep-benchmark.d.ts +0 -132
  214. package/router/dist/benchmarks/context-mode-real-deep-benchmark.js +0 -1380
  215. package/router/dist/benchmarks/context-saving-baseline.d.ts +0 -60
  216. package/router/dist/benchmarks/context-saving-baseline.js +0 -470
  217. package/router/dist/benchmarks/index-benchmarks.d.ts +0 -103
  218. package/router/dist/benchmarks/index-benchmarks.js +0 -862
  219. package/router/dist/benchmarks/storage-policy-benchmarks.d.ts +0 -101
  220. package/router/dist/benchmarks/storage-policy-benchmarks.js +0 -618
  221. package/router/dist/benchmarks/vault-index-benchmarks.d.ts +0 -56
  222. package/router/dist/benchmarks/vault-index-benchmarks.js +0 -322
  223. package/router/dist/config/config.d.ts +0 -103
  224. package/router/dist/config/config.js +0 -632
  225. package/router/dist/config/router-contract.d.ts +0 -10
  226. package/router/dist/config/router-contract.js +0 -54
  227. package/router/dist/config/schema.d.ts +0 -27
  228. package/router/dist/config/schema.js +0 -648
  229. package/router/dist/config/types.d.ts +0 -573
  230. package/router/dist/config/types.js +0 -41
  231. package/router/dist/evidence/bounded-evidence.d.ts +0 -40
  232. package/router/dist/evidence/bounded-evidence.js +0 -323
  233. package/router/dist/evidence/evidence-range-selector.d.ts +0 -24
  234. package/router/dist/evidence/evidence-range-selector.js +0 -232
  235. package/router/dist/evidence/evidence-search.d.ts +0 -27
  236. package/router/dist/evidence/evidence-search.js +0 -490
  237. package/router/dist/evidence/evidence.d.ts +0 -38
  238. package/router/dist/evidence/evidence.js +0 -200
  239. package/router/dist/evidence/failure-contracts.d.ts +0 -37
  240. package/router/dist/evidence/failure-contracts.js +0 -166
  241. package/router/dist/evidence/line-ranges.d.ts +0 -24
  242. package/router/dist/evidence/line-ranges.js +0 -22
  243. package/router/dist/experiments/local-index.d.ts +0 -64
  244. package/router/dist/experiments/local-index.js +0 -581
  245. package/router/dist/index.d.ts +0 -30
  246. package/router/dist/index.js +0 -32
  247. package/router/dist/local/local-traversal.d.ts +0 -18
  248. package/router/dist/local/local-traversal.js +0 -334
  249. package/router/dist/processing/engine.d.ts +0 -132
  250. package/router/dist/processing/engine.js +0 -533
  251. package/router/dist/processing/reducers.d.ts +0 -280
  252. package/router/dist/processing/reducers.js +0 -1673
  253. package/router/dist/processing/renderers.d.ts +0 -31
  254. package/router/dist/processing/renderers.js +0 -195
  255. package/router/dist/processing/scripts.d.ts +0 -91
  256. package/router/dist/processing/scripts.js +0 -386
  257. package/router/dist/repo/repo-traversal.d.ts +0 -18
  258. package/router/dist/repo/repo-traversal.js +0 -245
  259. package/router/dist/routing/observed-reducers.d.ts +0 -41
  260. package/router/dist/routing/observed-reducers.js +0 -661
  261. package/router/dist/routing/observed-routing.d.ts +0 -26
  262. package/router/dist/routing/observed-routing.js +0 -378
  263. package/router/dist/routing/parsers.d.ts +0 -16
  264. package/router/dist/routing/parsers.js +0 -521
  265. package/router/dist/routing/run-filters.d.ts +0 -60
  266. package/router/dist/routing/run-filters.js +0 -238
  267. package/router/dist/routing/run-reducers.d.ts +0 -49
  268. package/router/dist/routing/run-reducers.js +0 -122
  269. package/router/dist/sandbox/adapter-roots.d.ts +0 -46
  270. package/router/dist/sandbox/adapter-roots.js +0 -66
  271. package/router/dist/sandbox/eryx-python-adapter.d.ts +0 -13
  272. package/router/dist/sandbox/eryx-python-adapter.js +0 -868
  273. package/router/dist/sandbox/jq-wasm-adapter.d.ts +0 -9
  274. package/router/dist/sandbox/jq-wasm-adapter.js +0 -429
  275. package/router/dist/sandbox/quickjs-wasi-adapter.d.ts +0 -13
  276. package/router/dist/sandbox/quickjs-wasi-adapter.js +0 -384
  277. package/router/dist/sandbox/script-sandbox.d.ts +0 -134
  278. package/router/dist/sandbox/script-sandbox.js +0 -337
  279. package/router/dist/setup/script-transform-adapters.d.ts +0 -32
  280. package/router/dist/setup/script-transform-adapters.js +0 -278
  281. package/router/dist/tools/batch.d.ts +0 -33
  282. package/router/dist/tools/batch.js +0 -586
  283. package/router/dist/tools/run.d.ts +0 -62
  284. package/router/dist/tools/run.js +0 -1304
  285. package/router/dist/tools/search.d.ts +0 -66
  286. package/router/dist/tools/search.js +0 -1364
  287. package/router/dist/transform/engine.d.ts +0 -168
  288. package/router/dist/transform/engine.js +0 -2072
  289. package/router/dist/vault/vault-index.d.ts +0 -125
  290. package/router/dist/vault/vault-index.js +0 -416
  291. package/router/dist/vault/vault.d.ts +0 -138
  292. package/router/dist/vault/vault.js +0 -630
  293. package/runtime/interaction-contract.md +0 -16
  294. package/skills/discuss/references/checkpoints.md +0 -66
  295. package/skills/execute-work/references/execution-loop.md +0 -77
  296. package/skills/mode-contract/SKILL.md +0 -104
  297. package/skills/review-artifact/references/reviewer-prompt.md +0 -148
  298. package/skills/review-work/references/reviewer-prompt.md +0 -134
  299. package/skills/track-work/references/working-record-schema.md +0 -378
  300. package/skills/workflow/references/workflow-loop.md +0 -92
  301. /package/skills/handoff/references/{templates.md → handoff-templates.md} +0 -0
@@ -0,0 +1,790 @@
1
+ import {
2
+ ACTIVE_SLICE_FIELDS,
3
+ DECISION_FIELDS,
4
+ HISTORICAL_CHECKPOINT_FIELDS,
5
+ HISTORICAL_CHECKPOINT_STATES,
6
+ HISTORICAL_SLICE_FIELDS,
7
+ HISTORICAL_SLICE_STATES,
8
+ TASK_STATES,
9
+ } from "./format.mjs";
10
+ import {
11
+ applyLineReplacements,
12
+ fieldLines,
13
+ fieldValue,
14
+ findEntity,
15
+ findFutureItem,
16
+ formatField,
17
+ nextEntityId,
18
+ parseDocument,
19
+ parseFragment,
20
+ renderBlock,
21
+ } from "./document.mjs";
22
+ import { writeAtomically } from "./store.mjs";
23
+
24
+ const ACTIVE_SLICE_ORDER = [
25
+ "State",
26
+ "Type",
27
+ "Intended result",
28
+ "Authority source",
29
+ "Scope",
30
+ "Expected evidence",
31
+ "Stop condition",
32
+ "Starting state",
33
+ "Dependencies",
34
+ "Reopened from",
35
+ ];
36
+ const PROPOSED_SLICE_ORDER = ["State", "Type", "Intended result", "Expected evidence", "Dependencies"];
37
+ const FUTURE_CHECKPOINT_ORDER = ["State", "Type", "Condition", "Applies to"];
38
+ const HISTORICAL_CHECKPOINT_ORDER = [
39
+ "State",
40
+ "Type",
41
+ "Condition",
42
+ "Applies to",
43
+ "Result",
44
+ "Evidence",
45
+ "Task effect",
46
+ "Reason",
47
+ "Replaced by",
48
+ ];
49
+ const DECISION_ORDER = [
50
+ "State",
51
+ "Decision",
52
+ "Established by",
53
+ "Rationale",
54
+ "Source references",
55
+ "Consequences",
56
+ "Revisit when",
57
+ "Superseded by",
58
+ "Retired because",
59
+ ];
60
+ const HISTORICAL_SLICE_ORDER = [
61
+ "State",
62
+ "Type",
63
+ "Intended result",
64
+ "Authority source",
65
+ "Result",
66
+ "Evidence and limits",
67
+ "Task effect",
68
+ "Reopened from",
69
+ "Resume when",
70
+ "Reason",
71
+ "Residual effects",
72
+ ];
73
+
74
+ function fail(code, message) {
75
+ const error = new Error(message);
76
+ error.code = code;
77
+ throw error;
78
+ }
79
+
80
+ function trimLines(lines = []) {
81
+ let start = 0;
82
+ let end = lines.length;
83
+ while (start < end && lines[start].trim() === "") start += 1;
84
+ while (end > start && lines[end - 1].trim() === "") end -= 1;
85
+ return lines.slice(start, end);
86
+ }
87
+
88
+ function fragmentValue(fragment, name) {
89
+ const field = fragment.fields.get(name);
90
+ return field ? trimLines(field.valueLines) : null;
91
+ }
92
+
93
+ function fragmentText(fragment, name) {
94
+ const lines = fragmentValue(fragment, name);
95
+ return lines ? lines.join("\n").trim() : "";
96
+ }
97
+
98
+ function requireFragment(fragment, name, command) {
99
+ const value = fragmentText(fragment, name);
100
+ if (!value) fail("missing-field", `${command} requires ${name}`);
101
+ return fragmentValue(fragment, name);
102
+ }
103
+
104
+ function parseInput(input, allowed, command) {
105
+ return parseFragment(input, allowed, `${command} input`);
106
+ }
107
+
108
+ function blockValues(block, order) {
109
+ const values = {};
110
+ for (const field of order) {
111
+ const lines = fieldLines(block, field);
112
+ if (lines && lines.length) values[field] = lines;
113
+ }
114
+ return values;
115
+ }
116
+
117
+ function mergeValues(base, fragment, fields) {
118
+ const values = { ...base };
119
+ for (const field of fields) {
120
+ const lines = fragmentValue(fragment, field);
121
+ if (lines && lines.length) values[field] = lines;
122
+ }
123
+ return values;
124
+ }
125
+
126
+ function fieldRange(block, name) {
127
+ const field = block.fields.get(name);
128
+ if (!field) fail("missing-field", `Missing field ${name} in ${block.path}`);
129
+ const next = [...block.fields.values()]
130
+ .filter((candidate) => candidate.start > field.start)
131
+ .sort((left, right) => left.start - right.start)[0];
132
+ return { start: field.start, end: next?.start ?? block.end };
133
+ }
134
+
135
+ function materialLines(document, block) {
136
+ for (let index = block.start + 1; index < block.end; index += 1) {
137
+ if (document.lines[index] === "##### Material updates") return document.lines.slice(index, block.end);
138
+ }
139
+ return null;
140
+ }
141
+
142
+ function renderCurrentSlice(document, block, overrides = {}, event = null) {
143
+ const values = { ...blockValues(block, ACTIVE_SLICE_FIELDS), ...overrides };
144
+ const lines = renderBlock(`#### ${block.id} — ${block.title}`, ACTIVE_SLICE_ORDER, values);
145
+ let material = materialLines(document, block);
146
+ if (event) {
147
+ const existing = trimLines(material ?? ["##### Material updates"]);
148
+ material = [...existing, ...(existing.length === 1 ? [""] : []), `- ${event}`, ""];
149
+ }
150
+ if (material) lines.push(...material);
151
+ return lines;
152
+ }
153
+
154
+ function renderFutureCheckpoint(block, overrides = {}) {
155
+ const values = { ...blockValues(block, FUTURE_CHECKPOINT_ORDER), ...overrides };
156
+ const heading = block.id ? `### Checkpoint ${block.id} — ${block.title}` : `### Checkpoint — ${block.title}`;
157
+ return renderBlock(heading, FUTURE_CHECKPOINT_ORDER, values);
158
+ }
159
+
160
+ function renderHistoricalCheckpoint(block, overrides = {}) {
161
+ const values = { ...blockValues(block, HISTORICAL_CHECKPOINT_FIELDS), ...overrides };
162
+ return renderBlock(`#### ${block.id} — ${block.title}`, HISTORICAL_CHECKPOINT_ORDER, values);
163
+ }
164
+
165
+ function renderHistoricalSlice(values, title, id) {
166
+ return renderBlock(`#### ${id} — ${title}`, HISTORICAL_SLICE_ORDER, values);
167
+ }
168
+
169
+ function renderDecision(values, title, id) {
170
+ return renderBlock(`#### ${id} — ${title}`, DECISION_ORDER, values);
171
+ }
172
+
173
+ function replacementForField(block, field, value) {
174
+ const range = fieldRange(block, field);
175
+ const style = block.fieldStyle ?? "expanded";
176
+ const lines = formatField(field, value, style);
177
+ if (style !== "compact") lines.push("");
178
+ return { start: range.start, end: range.end, lines };
179
+ }
180
+
181
+ function assertUniqueFutureTitle(document, title) {
182
+ if (document.future.items.some((item) => item.title === title))
183
+ fail("duplicate-title", `Future Work title already exists: ${title}`);
184
+ }
185
+
186
+ function assertNoCurrentSlice(document) {
187
+ if (document.current.currentSlice) fail("current-slice-exists", "A Current Slice already exists");
188
+ }
189
+
190
+ function assertTaskActive(document, action) {
191
+ if (document.header.state !== "active")
192
+ fail("invalid-task-state", `Cannot ${action} while task state is ${document.header.state}`);
193
+ }
194
+
195
+ function assertCurrentSlice(document) {
196
+ if (!document.current.currentSlice) fail("missing-current-slice", "There is no Current Slice");
197
+ return document.current.currentSlice;
198
+ }
199
+
200
+ function assertState(block, field, expected, message) {
201
+ const actual = fieldValue(block, field);
202
+ if (actual !== expected) fail("invalid-transition", message ?? `Expected ${field} ${expected}, found ${actual}`);
203
+ }
204
+
205
+ function currentCheckpoints(document, sliceId) {
206
+ return document.future.items.filter(
207
+ (item) =>
208
+ item.kind === "checkpoint" &&
209
+ ["pending", "deferred"].includes(fieldValue(item, "State")) &&
210
+ fieldValue(item, "Applies to") === sliceId,
211
+ );
212
+ }
213
+
214
+ function requiredStringOption(options, name) {
215
+ const value = options[name];
216
+ if (!value?.trim()) fail("missing-option", `Missing required option: ${name}`);
217
+ return value.trim();
218
+ }
219
+
220
+ function eventText(options, input, optionName, label) {
221
+ const text = options[optionName]?.trim() || input.trim();
222
+ if (!text) fail("missing-input", `${label} requires text through ${optionName} or --input -`);
223
+ return text.replace(/\s+/g, " ");
224
+ }
225
+
226
+ function requiredNextAction(options, label) {
227
+ const value = options["--next-action"]?.trim();
228
+ if (!value) fail("missing-option", `${label} requires --next-action`);
229
+ return value.replace(/\s+/g, " ");
230
+ }
231
+
232
+ function nextActionReplacement(document, value) {
233
+ return {
234
+ start: document.current.nextAction.start,
235
+ end: document.current.nextAction.end,
236
+ lines: ["", `- ${value}`, ""],
237
+ };
238
+ }
239
+
240
+ function optionalNextAction(document, options) {
241
+ const value = options["--next-action"]?.trim();
242
+ return value ? nextActionReplacement(document, value.replace(/\s+/g, " ")) : null;
243
+ }
244
+
245
+ async function publish(loaded, candidate, summary) {
246
+ const document = parseDocument(candidate);
247
+ const stamped = withLineChanges(document, [
248
+ {
249
+ start: document.header.lastUpdatedLine,
250
+ end: document.header.lastUpdatedLine + 1,
251
+ lines: [`Last updated: ${new Date().toISOString()}`],
252
+ },
253
+ ]);
254
+ parseDocument(stamped);
255
+ await writeAtomically(loaded.root, loaded.path, loaded.text, stamped);
256
+ return `${summary}\n`;
257
+ }
258
+
259
+ function withLineChanges(document, replacements) {
260
+ return applyLineReplacements(document, replacements);
261
+ }
262
+
263
+ function proposedSliceValues(fragment) {
264
+ const values = { State: "proposed" };
265
+ for (const field of ["Type", "Intended result", "Expected evidence", "Dependencies"]) {
266
+ const lines = fragmentValue(fragment, field);
267
+ if (lines?.length) values[field] = lines;
268
+ }
269
+ requireFragment(fragment, "Intended result", "slice propose");
270
+ return values;
271
+ }
272
+
273
+ async function proposeSlice(options, input, loaded) {
274
+ const document = parseDocument(loaded.text);
275
+ const title = requiredStringOption(options, "--title");
276
+ assertUniqueFutureTitle(document, title);
277
+ const fragment = parseInput(
278
+ input,
279
+ new Set(["Type", "Intended result", "Expected evidence", "Dependencies"]),
280
+ "slice propose",
281
+ );
282
+ const values = proposedSliceValues(fragment);
283
+ const candidate = withLineChanges(document, [
284
+ {
285
+ start: document.future.end,
286
+ end: document.future.end,
287
+ lines: renderBlock(`### Slice — ${title}`, PROPOSED_SLICE_ORDER, values),
288
+ },
289
+ ]);
290
+ return publish(loaded, candidate, `Proposed Slice: ${title}`);
291
+ }
292
+
293
+ async function startSlice(options, input, loaded) {
294
+ const document = parseDocument(loaded.text);
295
+ assertTaskActive(document, "start a Slice");
296
+ assertNoCurrentSlice(document);
297
+ const title = requiredStringOption(options, "--title");
298
+ const proposal = findFutureItem(document, title, "slice");
299
+ const fragment = parseInput(
300
+ input,
301
+ new Set([
302
+ "Type",
303
+ "Expected evidence",
304
+ "Dependencies",
305
+ "Authority source",
306
+ "Scope",
307
+ "Stop condition",
308
+ "Starting state",
309
+ ]),
310
+ "slice start",
311
+ );
312
+ const proposalValues = blockValues(proposal, PROPOSED_SLICE_ORDER);
313
+ const values = mergeValues(proposalValues, fragment, [
314
+ "Type",
315
+ "Expected evidence",
316
+ "Dependencies",
317
+ "Authority source",
318
+ "Scope",
319
+ "Stop condition",
320
+ "Starting state",
321
+ ]);
322
+ values.State = "in_progress";
323
+ values["Intended result"] = proposalValues["Intended result"];
324
+ for (const field of ["Authority source", "Scope", "Expected evidence", "Stop condition", "Starting state"]) {
325
+ if (!values[field]?.length) requireFragment(fragment, field, "slice start");
326
+ }
327
+ const id = nextEntityId(document, "slice");
328
+ const currentLines = renderBlock(`#### ${id} — ${title}`, ACTIVE_SLICE_ORDER, values);
329
+ const nextAction = requiredNextAction(options, "slice start");
330
+ const replacements = [
331
+ { start: proposal.start, end: proposal.end, lines: [] },
332
+ {
333
+ start: document.current.sliceHeadingIndex + 1,
334
+ end: document.current.nextActionHeadingIndex,
335
+ lines: ["", ...currentLines, ""],
336
+ },
337
+ nextActionReplacement(document, nextAction),
338
+ ];
339
+ for (const checkpoint of document.future.items.filter((item) => item.kind === "checkpoint")) {
340
+ if (fieldValue(checkpoint, "Applies to") === title) {
341
+ replacements.push(replacementForField(checkpoint, "Applies to", `S-${id.slice(2)}`));
342
+ }
343
+ }
344
+ const candidate = withLineChanges(document, replacements);
345
+ return publish(loaded, candidate, `Started Slice: ${id} — ${title}`);
346
+ }
347
+
348
+ async function startDirectSlice(options, input, loaded) {
349
+ const document = parseDocument(loaded.text);
350
+ assertTaskActive(document, "start a Slice");
351
+ assertNoCurrentSlice(document);
352
+ const title = requiredStringOption(options, "--title");
353
+ if (document.future.items.some((item) => item.title === title))
354
+ fail("future-title-conflict", `Direct Slice title conflicts with Future Work: ${title}`);
355
+ const fragment = parseInput(
356
+ input,
357
+ new Set([
358
+ "Type",
359
+ "Intended result",
360
+ "Authority source",
361
+ "Scope",
362
+ "Expected evidence",
363
+ "Stop condition",
364
+ "Starting state",
365
+ "Dependencies",
366
+ ]),
367
+ "slice start-direct",
368
+ );
369
+ for (const field of [
370
+ "Intended result",
371
+ "Authority source",
372
+ "Scope",
373
+ "Expected evidence",
374
+ "Stop condition",
375
+ "Starting state",
376
+ ])
377
+ requireFragment(fragment, field, "slice start-direct");
378
+ const values = { State: "in_progress" };
379
+ for (const field of [
380
+ "Type",
381
+ "Intended result",
382
+ "Authority source",
383
+ "Scope",
384
+ "Expected evidence",
385
+ "Stop condition",
386
+ "Starting state",
387
+ "Dependencies",
388
+ ])
389
+ values[field] = fragmentValue(fragment, field) ?? undefined;
390
+ const id = nextEntityId(document, "slice");
391
+ const currentLines = renderBlock(`#### ${id} — ${title}`, ACTIVE_SLICE_ORDER, values);
392
+ const nextAction = requiredNextAction(options, "slice start-direct");
393
+ const candidate = withLineChanges(document, [
394
+ {
395
+ start: document.current.sliceHeadingIndex + 1,
396
+ end: document.current.nextActionHeadingIndex,
397
+ lines: ["", ...currentLines, ""],
398
+ },
399
+ nextActionReplacement(document, nextAction),
400
+ ]);
401
+ return publish(loaded, candidate, `Started direct Slice: ${id} — ${title}`);
402
+ }
403
+
404
+ async function pauseSlice(options, input, loaded) {
405
+ const document = parseDocument(loaded.text);
406
+ const slice = assertCurrentSlice(document);
407
+ assertState(slice, "State", "in_progress", "Only an in-progress Current Slice can be paused");
408
+ const reason = eventText(options, input, "--reason", "slice pause");
409
+ const resumeWhen = requiredStringOption(options, "--resume-when");
410
+ const event = `Paused — reason: ${reason}; resume when: ${resumeWhen}`;
411
+ const nextAction = requiredNextAction(options, "slice pause");
412
+ const candidate = withLineChanges(document, [
413
+ { start: slice.start, end: slice.end, lines: renderCurrentSlice(document, slice, { State: "paused" }, event) },
414
+ nextActionReplacement(document, nextAction),
415
+ ]);
416
+ return publish(loaded, candidate, `Paused Slice: ${slice.id}`);
417
+ }
418
+
419
+ async function resumeSlice(options, input, loaded) {
420
+ const document = parseDocument(loaded.text);
421
+ assertTaskActive(document, "resume a Slice");
422
+ const slice = assertCurrentSlice(document);
423
+ assertState(slice, "State", "paused", "Only a paused Current Slice can be resumed");
424
+ const source = eventText(options, input, "--resolution", "slice resume");
425
+ const event = `Resumed — resolution source: ${source}`;
426
+ const nextAction = requiredNextAction(options, "slice resume");
427
+ const candidate = withLineChanges(document, [
428
+ { start: slice.start, end: slice.end, lines: renderCurrentSlice(document, slice, { State: "in_progress" }, event) },
429
+ nextActionReplacement(document, nextAction),
430
+ ]);
431
+ return publish(loaded, candidate, `Resumed Slice: ${slice.id}`);
432
+ }
433
+
434
+ function closeValues(slice, state, fragment) {
435
+ const values = { ...blockValues(slice, HISTORICAL_SLICE_FIELDS), State: state };
436
+ values["Intended result"] = fieldLines(slice, "Intended result");
437
+ values.Result = requireFragment(fragment, "Result", "slice close");
438
+ values["Evidence and limits"] = requireFragment(fragment, "Evidence and limits", "slice close");
439
+ values["Task effect"] = requireFragment(fragment, "Task effect", "slice close");
440
+ for (const field of ["Type", "Authority source", "Reopened from", "Resume when", "Reason", "Residual effects"]) {
441
+ const lines = fragmentValue(fragment, field);
442
+ if (lines?.length) values[field] = lines;
443
+ }
444
+ if (state === "blocked") values["Resume when"] = requireFragment(fragment, "Resume when", "slice close");
445
+ if (state === "abandoned") values.Reason = requireFragment(fragment, "Reason", "slice close");
446
+ return values;
447
+ }
448
+
449
+ async function closeSlice(options, input, loaded) {
450
+ const document = parseDocument(loaded.text);
451
+ const slice = assertCurrentSlice(document);
452
+ const state = requiredStringOption(options, "--state");
453
+ if (!HISTORICAL_SLICE_STATES.has(state)) fail("invalid-state", `Invalid historical Slice state: ${state}`);
454
+ if (state === "blocked" && fieldValue(slice, "State") !== "paused")
455
+ fail("invalid-transition", "A Slice can close as blocked only from paused");
456
+ if (currentCheckpoints(document, slice.id).length)
457
+ fail("pending-checkpoint", `Slice ${slice.id} has an unresolved Checkpoint`);
458
+ const fragment = parseInput(
459
+ input,
460
+ new Set([
461
+ "Type",
462
+ "Authority source",
463
+ "Result",
464
+ "Evidence and limits",
465
+ "Task effect",
466
+ "Reopened from",
467
+ "Resume when",
468
+ "Reason",
469
+ "Residual effects",
470
+ ]),
471
+ "slice close",
472
+ );
473
+ const values = closeValues(slice, state, fragment);
474
+ const historical = renderHistoricalSlice(values, slice.title, slice.id);
475
+ const nextAction = requiredNextAction(options, "slice close");
476
+ const candidate = withLineChanges(document, [
477
+ {
478
+ start: document.current.sliceHeadingIndex + 1,
479
+ end: document.current.nextActionHeadingIndex,
480
+ lines: ["", "None", ""],
481
+ },
482
+ { start: document.history.slices.end, end: document.history.slices.end, lines: historical },
483
+ nextActionReplacement(document, nextAction),
484
+ ]);
485
+ return publish(loaded, candidate, `Closed Slice: ${slice.id} — ${state}`);
486
+ }
487
+
488
+ async function reopenSlice(options, input, loaded) {
489
+ const document = parseDocument(loaded.text);
490
+ assertTaskActive(document, "reopen a Slice");
491
+ assertNoCurrentSlice(document);
492
+ const oldId = requiredStringOption(options, "--id");
493
+ const historical = findEntity(document, oldId, "slice");
494
+ const oldState = fieldValue(historical, "State");
495
+ if (!new Set(["completed", "blocked"]).has(oldState))
496
+ fail("invalid-transition", "Only completed or blocked historical Slices can be reopened");
497
+ const fragment = parseInput(
498
+ input,
499
+ new Set([
500
+ "Type",
501
+ "Authority source",
502
+ "Scope",
503
+ "Expected evidence",
504
+ "Stop condition",
505
+ "Starting state",
506
+ "Dependencies",
507
+ ]),
508
+ "slice reopen",
509
+ );
510
+ for (const field of ["Authority source", "Scope", "Expected evidence", "Stop condition", "Starting state"])
511
+ requireFragment(fragment, field, "slice reopen");
512
+ const id = nextEntityId(document, "slice");
513
+ const title = options["--title"]?.trim() || historical.title;
514
+ const values = {
515
+ State: "in_progress",
516
+ Type: fragmentValue(fragment, "Type") ?? fieldLines(historical, "Type"),
517
+ "Intended result": fieldLines(historical, "Intended result"),
518
+ "Authority source": fragmentValue(fragment, "Authority source"),
519
+ Scope: fragmentValue(fragment, "Scope"),
520
+ "Expected evidence": fragmentValue(fragment, "Expected evidence"),
521
+ "Stop condition": fragmentValue(fragment, "Stop condition"),
522
+ "Starting state": fragmentValue(fragment, "Starting state"),
523
+ Dependencies: fragmentValue(fragment, "Dependencies") ?? undefined,
524
+ "Reopened from": [oldId],
525
+ };
526
+ const currentLines = renderBlock(`#### ${id} — ${title}`, ACTIVE_SLICE_ORDER, values);
527
+ const nextAction = requiredNextAction(options, "slice reopen");
528
+ const candidate = withLineChanges(document, [
529
+ {
530
+ start: document.current.sliceHeadingIndex + 1,
531
+ end: document.current.nextActionHeadingIndex,
532
+ lines: ["", ...currentLines, ""],
533
+ },
534
+ nextActionReplacement(document, nextAction),
535
+ ]);
536
+ return publish(loaded, candidate, `Reopened Slice: ${id} — reopened from ${oldId}`);
537
+ }
538
+
539
+ function checkpointInput(input, command) {
540
+ return parseInput(input, new Set(["Type", "Condition", "Applies to"]), command);
541
+ }
542
+
543
+ async function proposeCheckpoint(options, input, loaded) {
544
+ const document = parseDocument(loaded.text);
545
+ const title = requiredStringOption(options, "--title");
546
+ assertUniqueFutureTitle(document, title);
547
+ const fragment = checkpointInput(input, "checkpoint propose");
548
+ requireFragment(fragment, "Type", "checkpoint propose");
549
+ requireFragment(fragment, "Condition", "checkpoint propose");
550
+ requireFragment(fragment, "Applies to", "checkpoint propose");
551
+ const values = {
552
+ State: "proposed",
553
+ Type: fragmentValue(fragment, "Type"),
554
+ Condition: fragmentValue(fragment, "Condition"),
555
+ "Applies to": fragmentValue(fragment, "Applies to"),
556
+ };
557
+ const candidate = withLineChanges(document, [
558
+ {
559
+ start: document.future.end,
560
+ end: document.future.end,
561
+ lines: renderBlock(`### Checkpoint — ${title}`, FUTURE_CHECKPOINT_ORDER, values),
562
+ },
563
+ ]);
564
+ return publish(loaded, candidate, `Proposed Checkpoint: ${title}`);
565
+ }
566
+
567
+ async function activateCheckpoint(options, loaded) {
568
+ const document = parseDocument(loaded.text);
569
+ assertTaskActive(document, "activate a Checkpoint");
570
+ const title = requiredStringOption(options, "--title");
571
+ const checkpoint = findFutureItem(document, title, "checkpoint");
572
+ assertState(checkpoint, "State", "proposed", "Only a proposed Checkpoint can be activated");
573
+ const id = nextEntityId(document, "checkpoint");
574
+ const replacements = [
575
+ {
576
+ start: checkpoint.start,
577
+ end: checkpoint.end,
578
+ lines: renderFutureCheckpoint({ ...checkpoint, id }, { State: "pending" }),
579
+ },
580
+ ];
581
+ const nextAction = optionalNextAction(document, options);
582
+ if (nextAction) replacements.push(nextAction);
583
+ const candidate = withLineChanges(document, replacements);
584
+ return publish(loaded, candidate, `Activated Checkpoint: ${id}`);
585
+ }
586
+
587
+ async function changeCheckpointState(options, loaded, nextState) {
588
+ const document = parseDocument(loaded.text);
589
+ const id = requiredStringOption(options, "--id");
590
+ const checkpoint = findEntity(document, id, "checkpoint");
591
+ const currentState = fieldValue(checkpoint, "State");
592
+ if (nextState === "deferred" && currentState !== "pending")
593
+ fail("invalid-transition", "Only a pending Checkpoint can be deferred");
594
+ if (nextState === "pending" && currentState !== "deferred")
595
+ fail("invalid-transition", "Only a deferred Checkpoint can return to pending");
596
+ if (nextState === "pending") assertTaskActive(document, "resume a Checkpoint");
597
+ const replacements = [
598
+ { start: checkpoint.start, end: checkpoint.end, lines: renderFutureCheckpoint(checkpoint, { State: nextState }) },
599
+ ];
600
+ const nextAction = optionalNextAction(document, options);
601
+ if (nextAction) replacements.push(nextAction);
602
+ const candidate = withLineChanges(document, replacements);
603
+ return publish(loaded, candidate, `${nextState === "pending" ? "Resumed" : "Deferred"} Checkpoint: ${id}`);
604
+ }
605
+
606
+ async function closeCheckpoint(options, input, loaded) {
607
+ const document = parseDocument(loaded.text);
608
+ const id = requiredStringOption(options, "--id");
609
+ const checkpoint = findEntity(document, id, "checkpoint");
610
+ if (!new Set(["pending", "deferred"]).has(fieldValue(checkpoint, "State")))
611
+ fail("invalid-transition", "Only a pending or deferred Checkpoint can be closed");
612
+ const state = requiredStringOption(options, "--state");
613
+ if (!HISTORICAL_CHECKPOINT_STATES.has(state)) fail("invalid-state", `Invalid historical Checkpoint state: ${state}`);
614
+ const fragment = parseInput(
615
+ input,
616
+ new Set(["Result", "Evidence", "Task effect", "Reason", "Replaced by"]),
617
+ "checkpoint close",
618
+ );
619
+ const values = {
620
+ State: state,
621
+ Type: fieldLines(checkpoint, "Type"),
622
+ Condition: fieldLines(checkpoint, "Condition"),
623
+ "Applies to": fieldLines(checkpoint, "Applies to"),
624
+ Result: requireFragment(fragment, "Result", "checkpoint close"),
625
+ Evidence: fragmentValue(fragment, "Evidence") ?? undefined,
626
+ "Task effect": requireFragment(fragment, "Task effect", "checkpoint close"),
627
+ Reason: ["cancelled", "replaced"].includes(state)
628
+ ? requireFragment(fragment, "Reason", "checkpoint close")
629
+ : undefined,
630
+ "Replaced by": state === "replaced" ? requireFragment(fragment, "Replaced by", "checkpoint close") : undefined,
631
+ };
632
+ const historical = renderHistoricalCheckpoint(checkpoint, values);
633
+ const replacements = [
634
+ { start: checkpoint.start, end: checkpoint.end, lines: [] },
635
+ { start: document.history.checkpoints.end, end: document.history.checkpoints.end, lines: historical },
636
+ ];
637
+ const nextAction = optionalNextAction(document, options);
638
+ if (nextAction) replacements.push(nextAction);
639
+ const candidate = withLineChanges(document, replacements);
640
+ return publish(loaded, candidate, `Closed Checkpoint: ${id} — ${state}`);
641
+ }
642
+
643
+ function decisionInput(input, command) {
644
+ return parseInput(
645
+ input,
646
+ new Set(["Decision", "Established by", "Rationale", "Source references", "Consequences", "Revisit when"]),
647
+ command,
648
+ );
649
+ }
650
+
651
+ async function addDecision(options, input, loaded) {
652
+ const document = parseDocument(loaded.text);
653
+ const title = requiredStringOption(options, "--title");
654
+ const fragment = decisionInput(input, "decision add");
655
+ for (const field of ["Decision", "Established by", "Rationale", "Consequences", "Revisit when"])
656
+ requireFragment(fragment, field, "decision add");
657
+ const id = nextEntityId(document, "decision");
658
+ const values = {
659
+ State: "active",
660
+ Decision: fragmentValue(fragment, "Decision"),
661
+ "Established by": fragmentValue(fragment, "Established by"),
662
+ Rationale: fragmentValue(fragment, "Rationale"),
663
+ "Source references": fragmentValue(fragment, "Source references") ?? undefined,
664
+ Consequences: fragmentValue(fragment, "Consequences"),
665
+ "Revisit when": fragmentValue(fragment, "Revisit when"),
666
+ };
667
+ const candidate = withLineChanges(document, [
668
+ {
669
+ start: document.history.decisions.end,
670
+ end: document.history.decisions.end,
671
+ lines: renderDecision(values, title, id),
672
+ },
673
+ ]);
674
+ return publish(loaded, candidate, `Added Decision: ${id}`);
675
+ }
676
+
677
+ async function supersedeDecision(options, input, loaded) {
678
+ const document = parseDocument(loaded.text);
679
+ const oldId = requiredStringOption(options, "--id");
680
+ const oldDecision = findEntity(document, oldId, "decision");
681
+ assertState(oldDecision, "State", "active", "Only an active Decision can be superseded");
682
+ const title = requiredStringOption(options, "--title");
683
+ const fragment = decisionInput(input, "decision supersede");
684
+ for (const field of ["Decision", "Established by", "Rationale", "Consequences", "Revisit when"])
685
+ requireFragment(fragment, field, "decision supersede");
686
+ const newId = nextEntityId(document, "decision");
687
+ const oldValues = { ...blockValues(oldDecision, DECISION_FIELDS), State: "superseded", "Superseded by": [newId] };
688
+ const newValues = {
689
+ State: "active",
690
+ Decision: fragmentValue(fragment, "Decision"),
691
+ "Established by": fragmentValue(fragment, "Established by"),
692
+ Rationale: fragmentValue(fragment, "Rationale"),
693
+ "Source references": fragmentValue(fragment, "Source references") ?? undefined,
694
+ Consequences: fragmentValue(fragment, "Consequences"),
695
+ "Revisit when": fragmentValue(fragment, "Revisit when"),
696
+ };
697
+ const candidate = withLineChanges(document, [
698
+ {
699
+ start: oldDecision.start,
700
+ end: oldDecision.end,
701
+ lines: [...renderDecision(oldValues, oldDecision.title, oldId), ...renderDecision(newValues, title, newId)],
702
+ },
703
+ ]);
704
+ return publish(loaded, candidate, `Superseded Decision: ${oldId} → ${newId}`);
705
+ }
706
+
707
+ async function retireDecision(options, input, loaded) {
708
+ const document = parseDocument(loaded.text);
709
+ const id = requiredStringOption(options, "--id");
710
+ const decision = findEntity(document, id, "decision");
711
+ assertState(decision, "State", "active", "Only an active Decision can be retired");
712
+ const reason = eventText(options, input, "--reason", "decision retire");
713
+ const values = { ...blockValues(decision, DECISION_FIELDS), State: "retired", "Retired because": [reason] };
714
+ const candidate = withLineChanges(document, [
715
+ { start: decision.start, end: decision.end, lines: renderDecision(values, decision.title, id) },
716
+ ]);
717
+ return publish(loaded, candidate, `Retired Decision: ${id}`);
718
+ }
719
+
720
+ async function setTaskState(options, loaded) {
721
+ const document = parseDocument(loaded.text);
722
+ const state = requiredStringOption(options, "--state");
723
+ if (!TASK_STATES.has(state)) fail("invalid-state", `Invalid task state: ${state}`);
724
+ const currentState = document.header.state;
725
+ const allowedNext = {
726
+ active: new Set(["active", "paused", "completed", "abandoned"]),
727
+ paused: new Set(["paused", "active", "completed", "abandoned"]),
728
+ completed: new Set(["completed", "active"]),
729
+ abandoned: new Set(["abandoned", "active"]),
730
+ };
731
+ if (!allowedNext[currentState].has(state))
732
+ fail("invalid-transition", `Task state cannot transition from ${currentState} to ${state}`);
733
+ if (currentState === state) return `No change: task state is already ${state}\n`;
734
+ const nextAction = requiredNextAction(options, "task set-state");
735
+ const replacements = [
736
+ { start: document.header.stateLine, end: document.header.stateLine + 1, lines: [`State: ${state}`] },
737
+ ];
738
+ const slice = document.current.currentSlice;
739
+ if (state === "paused" && slice && fieldValue(slice, "State") === "in_progress") {
740
+ replacements.push({
741
+ start: slice.start,
742
+ end: slice.end,
743
+ lines: renderCurrentSlice(
744
+ document,
745
+ slice,
746
+ { State: "paused" },
747
+ "Paused — reason: task paused; resume when: task is reactivated.",
748
+ ),
749
+ });
750
+ }
751
+ if (["completed", "abandoned"].includes(state)) {
752
+ if (slice) fail("invalid-task-state", `A ${state} task cannot have a Current Slice`);
753
+ if (
754
+ document.future.items.some(
755
+ (item) => item.kind === "checkpoint" && ["pending", "deferred"].includes(fieldValue(item, "State")),
756
+ )
757
+ )
758
+ fail("invalid-task-state", `A ${state} task cannot have a pending or deferred Checkpoint`);
759
+ }
760
+ if (nextAction) replacements.push(nextActionReplacement(document, nextAction));
761
+ const candidate = withLineChanges(document, replacements);
762
+ return publish(loaded, candidate, `Set task state: ${state}`);
763
+ }
764
+
765
+ export async function runTransition(command, positionals, options, input, loaded) {
766
+ const operation = positionals[0];
767
+ if (command === "slice") {
768
+ if (operation === "propose") return proposeSlice(options, input, loaded);
769
+ if (operation === "start") return startSlice(options, input, loaded);
770
+ if (operation === "start-direct") return startDirectSlice(options, input, loaded);
771
+ if (operation === "pause") return pauseSlice(options, input, loaded);
772
+ if (operation === "resume") return resumeSlice(options, input, loaded);
773
+ if (operation === "close") return closeSlice(options, input, loaded);
774
+ if (operation === "reopen") return reopenSlice(options, input, loaded);
775
+ }
776
+ if (command === "checkpoint") {
777
+ if (operation === "propose") return proposeCheckpoint(options, input, loaded);
778
+ if (operation === "activate") return activateCheckpoint(options, loaded);
779
+ if (operation === "defer") return changeCheckpointState(options, loaded, "deferred");
780
+ if (operation === "resume") return changeCheckpointState(options, loaded, "pending");
781
+ if (operation === "close") return closeCheckpoint(options, input, loaded);
782
+ }
783
+ if (command === "decision") {
784
+ if (operation === "add") return addDecision(options, input, loaded);
785
+ if (operation === "supersede") return supersedeDecision(options, input, loaded);
786
+ if (operation === "retire") return retireDecision(options, input, loaded);
787
+ }
788
+ if (command === "task" && operation === "set-state") return setTaskState(options, loaded);
789
+ fail("unknown-command", `Unknown lifecycle command: ${command} ${operation ?? ""}`.trim());
790
+ }