@skathio/somi 4.1.1 → 5.0.1

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 (372) hide show
  1. package/.claude-plugin/icon.png +0 -0
  2. package/.claude-plugin/marketplace.json +8 -3
  3. package/.claude-plugin/plugin.json +9 -10
  4. package/.copilot-extension/extension.json +32 -40
  5. package/.copilot-extension/marketplace.json +8 -3
  6. package/README.md +88 -227
  7. package/VERSION +1 -1
  8. package/agents/somi-reviewer.md +21 -40
  9. package/agents/somi-security-reviewer.md +16 -90
  10. package/agents/somi-worker-high.md +11 -0
  11. package/agents/somi-worker-low.md +11 -0
  12. package/agents/somi-worker-medium.md +11 -0
  13. package/agents/somi.md +8 -75
  14. package/commands/somi-config.md +5 -14
  15. package/commands/somi-deliver.md +11 -0
  16. package/commands/somi-quality.md +10 -0
  17. package/commands/somi-review.md +10 -0
  18. package/commands/somi-status.md +11 -0
  19. package/commands/somi.md +10 -0
  20. package/hooks/hooks.json +29 -23
  21. package/hooks/lib/common.mjs +45 -34
  22. package/hooks/pre-tool/apply-tier.mjs +31 -0
  23. package/hooks/pre-tool/block-dangerous-bash.mjs +15 -0
  24. package/hooks/pre-tool/gate-dep-install.mjs +2 -2
  25. package/hooks/pre-tool/guard-protected-paths.mjs +9 -16
  26. package/hooks/pre-tool/guard-tier-config.mjs +17 -0
  27. package/hooks/pre-tool/reviewers-read-only.mjs +11 -0
  28. package/hooks/session-start/inject-digest.mjs +51 -0
  29. package/hooks/stop/review-due.mjs +44 -0
  30. package/hooks/user-prompt/capture-prompt.mjs +17 -0
  31. package/library/lenses/architecture.md +1 -0
  32. package/library/lenses/test-strategy.md +1 -0
  33. package/library/roles/accessibility.md +1 -0
  34. package/library/roles/answer.md +1 -0
  35. package/library/roles/atlas.md +1 -0
  36. package/library/roles/build.md +1 -0
  37. package/library/roles/debug.md +6 -0
  38. package/library/roles/design.md +1 -0
  39. package/library/roles/discover.md +1 -0
  40. package/library/roles/incident.md +1 -0
  41. package/library/roles/migrate.md +1 -0
  42. package/library/roles/perf.md +1 -0
  43. package/library/roles/plan.md +1 -0
  44. package/library/roles/refactor.md +1 -0
  45. package/library/roles/review.md +1 -0
  46. package/library/roles/security-review.md +1 -0
  47. package/library/roles/upgrade.md +1 -0
  48. package/library/skills/accessibility.md +16 -0
  49. package/library/skills/ci-infra-gotchas.md +12 -0
  50. package/library/skills/perf-method.md +10 -0
  51. package/library/skills/secure-coding.md +18 -0
  52. package/library/skills/testing-checklist.md +16 -0
  53. package/library/skills/threat-modeling.md +10 -0
  54. package/package.json +12 -17
  55. package/profiles/claude.json +21 -0
  56. package/profiles/copilot.json +5 -0
  57. package/rules/digest.md +40 -0
  58. package/scripts/check-links.mjs +65 -76
  59. package/scripts/lib/advisor.mjs +207 -0
  60. package/scripts/lib/check.mjs +167 -0
  61. package/scripts/lib/copilot-workflow.mjs +41 -0
  62. package/scripts/lib/doctor.mjs +91 -0
  63. package/scripts/lib/gates.mjs +69 -0
  64. package/scripts/lib/git-tree.mjs +201 -0
  65. package/scripts/lib/init.mjs +23 -0
  66. package/scripts/lib/ledger.mjs +38 -0
  67. package/scripts/lib/mcp-project-root.mjs +63 -67
  68. package/scripts/lib/migrate.mjs +73 -0
  69. package/scripts/lib/path-facts.mjs +2 -2
  70. package/scripts/lib/path-safety.mjs +6 -134
  71. package/scripts/lib/plan.mjs +69 -0
  72. package/scripts/lib/policy.mjs +103 -0
  73. package/scripts/lib/pr.mjs +28 -0
  74. package/scripts/lib/prompt.mjs +72 -0
  75. package/scripts/lib/quality/clones.mjs +76 -0
  76. package/scripts/lib/quality/css.mjs +43 -0
  77. package/scripts/lib/quality/gate.mjs +230 -0
  78. package/scripts/lib/quality/limits.mjs +97 -0
  79. package/scripts/lib/quality/metrics.mjs +159 -0
  80. package/scripts/lib/quality/parse.mjs +73 -0
  81. package/scripts/lib/quality/repo.mjs +69 -0
  82. package/scripts/lib/quality/run.mjs +58 -0
  83. package/scripts/lib/reviews.mjs +132 -0
  84. package/scripts/lib/routes.mjs +108 -0
  85. package/scripts/lib/setup.mjs +34 -0
  86. package/scripts/lib/shards.mjs +166 -0
  87. package/scripts/lib/signals.mjs +110 -0
  88. package/scripts/lib/state.mjs +42 -0
  89. package/scripts/lib/tiers.mjs +42 -0
  90. package/scripts/lib/update-notice.mjs +48 -0
  91. package/scripts/lib/views.mjs +62 -0
  92. package/scripts/lib/workflows.mjs +56 -0
  93. package/scripts/somi-mcp.mjs +182 -323
  94. package/scripts/somi.mjs +208 -0
  95. package/scripts/vendor/tree-sitter/LICENSE.vscode-tree-sitter-wasm +21 -0
  96. package/scripts/vendor/tree-sitter/LICENSE.web-tree-sitter +21 -0
  97. package/scripts/vendor/tree-sitter/cgmanifest.vscode-tree-sitter-wasm.json +16 -0
  98. package/scripts/vendor/tree-sitter/manifest.json +59 -0
  99. package/scripts/vendor/tree-sitter/package.json +3 -0
  100. package/scripts/vendor/tree-sitter/tree-sitter-css.wasm +0 -0
  101. package/scripts/vendor/tree-sitter/tree-sitter-javascript.wasm +0 -0
  102. package/scripts/vendor/tree-sitter/tree-sitter-tsx.wasm +0 -0
  103. package/scripts/vendor/tree-sitter/tree-sitter-typescript.wasm +0 -0
  104. package/scripts/vendor/tree-sitter/web-tree-sitter.js +4081 -0
  105. package/scripts/vendor/tree-sitter/web-tree-sitter.wasm +0 -0
  106. package/skills/somi-expertise/SKILL.md +6 -0
  107. package/workflows/deliver-stages.js +81 -0
  108. package/.claude/settings.json +0 -131
  109. package/agents/somi-architecture-reviewer.md +0 -101
  110. package/agents/somi-atlas.md +0 -100
  111. package/agents/somi-coder.md +0 -60
  112. package/agents/somi-designer.md +0 -36
  113. package/agents/somi-discovery-analyst.md +0 -57
  114. package/agents/somi-flow.md +0 -47
  115. package/agents/somi-general.md +0 -36
  116. package/agents/somi-impact.md +0 -95
  117. package/agents/somi-incident.md +0 -94
  118. package/agents/somi-plan-reviewer.md +0 -68
  119. package/agents/somi-planner.md +0 -57
  120. package/agents/somi-pr.md +0 -99
  121. package/agents/somi-refactor-designer.md +0 -81
  122. package/agents/somi-refactorer.md +0 -99
  123. package/agents/somi-sdlc-reviewer.md +0 -67
  124. package/agents/somi-test-strategist.md +0 -87
  125. package/commands/adopt.md +0 -14
  126. package/commands/architecture-review.md +0 -19
  127. package/commands/atlas.md +0 -19
  128. package/commands/code-loop.md +0 -19
  129. package/commands/code-parallel.md +0 -19
  130. package/commands/code.md +0 -19
  131. package/commands/debug.md +0 -19
  132. package/commands/design.md +0 -19
  133. package/commands/discover.md +0 -19
  134. package/commands/impact.md +0 -19
  135. package/commands/incident.md +0 -19
  136. package/commands/plan-loop.md +0 -19
  137. package/commands/plan.md +0 -19
  138. package/commands/pr.md +0 -19
  139. package/commands/refactor-design.md +0 -19
  140. package/commands/refactor.md +0 -19
  141. package/commands/release-readiness.md +0 -19
  142. package/commands/review-panel.md +0 -19
  143. package/commands/review.md +0 -19
  144. package/commands/security-review.md +0 -19
  145. package/commands/ship-loop.md +0 -19
  146. package/commands/ship.md +0 -19
  147. package/commands/test-strategy.md +0 -19
  148. package/commands/upgrade.md +0 -19
  149. package/examples/README.md +0 -19
  150. package/examples/code-review-example.md +0 -88
  151. package/examples/discovery-example.md +0 -200
  152. package/examples/feature-plan-example.md +0 -377
  153. package/examples/full-pipeline-example.md +0 -188
  154. package/examples/sample-consumer/.claude/settings.json +0 -29
  155. package/examples/sample-consumer/CLAUDE.md +0 -78
  156. package/examples/sample-consumer/README.md +0 -102
  157. package/hooks/post-tool/lint-changed-files.mjs +0 -209
  158. package/hooks/pre-tool/guard-cost-lowering.mjs +0 -192
  159. package/hooks/session-start/detect-repo-instructions.mjs +0 -287
  160. package/hooks/session-start/ensure-default-config.mjs +0 -113
  161. package/hooks/user-prompt-submit/inject-workflow-context.mjs +0 -580
  162. package/rules/00-priorities.md +0 -48
  163. package/rules/10-solid.md +0 -87
  164. package/rules/20-clean-code.md +0 -62
  165. package/rules/30-security-owasp.md +0 -83
  166. package/rules/40-engineering-practices.md +0 -65
  167. package/rules/50-collaboration.md +0 -114
  168. package/rules/99-overrides.md +0 -52
  169. package/rules/CLAUDE.md +0 -200
  170. package/scripts/check-session-artefacts.mjs +0 -149
  171. package/scripts/check-size-budget.mjs +0 -137
  172. package/scripts/generate-digest.mjs +0 -176
  173. package/scripts/lib/agent-info.mjs +0 -85
  174. package/scripts/lib/agent-registry.mjs +0 -92
  175. package/scripts/lib/cost-ceiling.mjs +0 -328
  176. package/scripts/lib/cost-config-edit.mjs +0 -102
  177. package/scripts/lib/cost-config.mjs +0 -64
  178. package/scripts/lib/cost-defaults.mjs +0 -53
  179. package/scripts/lib/cost-lowering.mjs +0 -89
  180. package/scripts/lib/cost-model.mjs +0 -110
  181. package/scripts/lib/dispatch-resolver.mjs +0 -243
  182. package/scripts/lib/escalation-facts.mjs +0 -146
  183. package/scripts/lib/escalation.mjs +0 -129
  184. package/scripts/lib/findings-ledger.mjs +0 -241
  185. package/scripts/lib/install-text.mjs +0 -97
  186. package/scripts/lib/loop-caps.mjs +0 -140
  187. package/scripts/lib/loop-diff.mjs +0 -38
  188. package/scripts/lib/loop-dispatch.mjs +0 -19
  189. package/scripts/lib/loop-engine.mjs +0 -227
  190. package/scripts/lib/loop-escalate.mjs +0 -49
  191. package/scripts/lib/loop-exit.mjs +0 -47
  192. package/scripts/lib/loop-notes-compact.mjs +0 -72
  193. package/scripts/lib/loop-notes.mjs +0 -282
  194. package/scripts/lib/loop-review.mjs +0 -395
  195. package/scripts/lib/loop-state.mjs +0 -44
  196. package/scripts/lib/loop-step-close.mjs +0 -75
  197. package/scripts/lib/loop-step-kit.mjs +0 -179
  198. package/scripts/lib/loop-step-review.mjs +0 -140
  199. package/scripts/lib/loop-step-tool.mjs +0 -89
  200. package/scripts/lib/loop-step.mjs +0 -303
  201. package/scripts/lib/run-budget.mjs +0 -28
  202. package/scripts/lib/run-card.mjs +0 -73
  203. package/scripts/lib/size-tier.mjs +0 -184
  204. package/scripts/lib/tier-record.mjs +0 -82
  205. package/scripts/size-budget-overrides.json +0 -58
  206. package/scripts/somi-card.mjs +0 -39
  207. package/scripts/somi-check.mjs +0 -237
  208. package/scripts/somi-config.mjs +0 -421
  209. package/scripts/somi-dispatch.mjs +0 -141
  210. package/scripts/somi-findings.mjs +0 -100
  211. package/scripts/somi-loop.mjs +0 -139
  212. package/scripts/somi-tier.mjs +0 -393
  213. package/scripts/validate.sh +0 -653
  214. package/skills/api-design/SKILL.md +0 -147
  215. package/skills/clean-code/SKILL.md +0 -142
  216. package/skills/flow-adopt/SKILL.md +0 -92
  217. package/skills/flow-architecture-review/SKILL.md +0 -94
  218. package/skills/flow-atlas/SKILL.md +0 -34
  219. package/skills/flow-code/SKILL.md +0 -167
  220. package/skills/flow-code-loop/SKILL.md +0 -263
  221. package/skills/flow-code-parallel/SKILL.md +0 -160
  222. package/skills/flow-debug/SKILL.md +0 -141
  223. package/skills/flow-design/SKILL.md +0 -170
  224. package/skills/flow-discover/SKILL.md +0 -204
  225. package/skills/flow-impact/SKILL.md +0 -35
  226. package/skills/flow-incident/SKILL.md +0 -49
  227. package/skills/flow-plan/SKILL.md +0 -254
  228. package/skills/flow-plan-loop/SKILL.md +0 -254
  229. package/skills/flow-pr/SKILL.md +0 -34
  230. package/skills/flow-refactor/SKILL.md +0 -58
  231. package/skills/flow-refactor-design/SKILL.md +0 -97
  232. package/skills/flow-release-readiness/SKILL.md +0 -82
  233. package/skills/flow-review/SKILL.md +0 -193
  234. package/skills/flow-review-panel/SKILL.md +0 -154
  235. package/skills/flow-security-review/SKILL.md +0 -83
  236. package/skills/flow-ship/SKILL.md +0 -125
  237. package/skills/flow-ship-loop/SKILL.md +0 -274
  238. package/skills/flow-somi-config/SKILL.md +0 -142
  239. package/skills/flow-status/SKILL.md +0 -43
  240. package/skills/flow-test-strategy/SKILL.md +0 -83
  241. package/skills/flow-upgrade/SKILL.md +0 -82
  242. package/skills/market-research/SKILL.md +0 -125
  243. package/skills/observability/SKILL.md +0 -133
  244. package/skills/owasp-defense/SKILL.md +0 -141
  245. package/skills/plan-review/SKILL.md +0 -83
  246. package/skills/reasoning-craft/SKILL.md +0 -213
  247. package/skills/requirements-engineering/SKILL.md +0 -137
  248. package/skills/role-coder/SKILL.md +0 -247
  249. package/skills/role-designer/SKILL.md +0 -172
  250. package/skills/role-discovery-analyst/SKILL.md +0 -288
  251. package/skills/role-planner/SKILL.md +0 -353
  252. package/skills/role-reviewer/SKILL.md +0 -218
  253. package/skills/rules/SKILL.md +0 -47
  254. package/skills/sdlc-process/SKILL.md +0 -74
  255. package/skills/solid-principles/SKILL.md +0 -143
  256. package/skills/somi-checkpoint/SKILL.md +0 -95
  257. package/skills/somi-dispatch/SKILL.md +0 -259
  258. package/skills/somi-routing/SKILL.md +0 -158
  259. package/skills/testing-playbook/SKILL.md +0 -133
  260. package/skills/threat-modeling/SKILL.md +0 -117
  261. package/templates/ADR.md.tmpl +0 -73
  262. package/templates/ATLAS.md.tmpl +0 -75
  263. package/templates/BRD.md.tmpl +0 -68
  264. package/templates/BRIEF.md.tmpl +0 -119
  265. package/templates/CONTEXT.md.tmpl +0 -74
  266. package/templates/DECISIONS.md.tmpl +0 -105
  267. package/templates/DESIGN.md.tmpl +0 -83
  268. package/templates/DIARY.md.tmpl +0 -70
  269. package/templates/DOD.md.tmpl +0 -90
  270. package/templates/FRD.md.tmpl +0 -64
  271. package/templates/PHASE.md.tmpl +0 -80
  272. package/templates/PROGRESS.md.tmpl +0 -63
  273. package/templates/RCA.md.tmpl +0 -53
  274. package/templates/RD-README.md.tmpl +0 -70
  275. package/templates/RESEARCH.md.tmpl +0 -96
  276. package/templates/REVIEW.md.tmpl +0 -82
  277. package/templates/SDD.md.tmpl +0 -82
  278. package/templates/SOMI-README.md.tmpl +0 -83
  279. package/templates/SPEC.md.tmpl +0 -123
  280. package/templates/SRS.md.tmpl +0 -85
  281. package/templates/TDD.md.tmpl +0 -77
  282. package/tests/hooks/cases/audit-log.json +0 -21
  283. package/tests/hooks/cases/block-dangerous-bash.json +0 -166
  284. package/tests/hooks/cases/block-secret-writes.json +0 -140
  285. package/tests/hooks/cases/detect-repo-instructions.json +0 -105
  286. package/tests/hooks/cases/gate-dep-install.json +0 -42
  287. package/tests/hooks/cases/guard-protected-paths.json +0 -222
  288. package/tests/hooks/cases/inject-workflow-context.json +0 -239
  289. package/tests/hooks/cases/lint-changed-files.json +0 -120
  290. package/tests/hooks/run.sh +0 -392
  291. package/tests/scripts/agent-model-frontmatter.sh +0 -38
  292. package/tests/scripts/agent-names.sh +0 -77
  293. package/tests/scripts/check-frontmatter.sh +0 -37
  294. package/tests/scripts/check-links.sh +0 -105
  295. package/tests/scripts/check-session-artefacts.sh +0 -60
  296. package/tests/scripts/check-size-budget.sh +0 -71
  297. package/tests/scripts/checkpoint-gate.sh +0 -131
  298. package/tests/scripts/convergence-runner.sh +0 -1514
  299. package/tests/scripts/cost-ceiling.sh +0 -255
  300. package/tests/scripts/cost-defaults.sh +0 -130
  301. package/tests/scripts/cost-hardcap.sh +0 -338
  302. package/tests/scripts/cost-lowering.sh +0 -261
  303. package/tests/scripts/cost-model.sh +0 -196
  304. package/tests/scripts/dispatch-guard.sh +0 -108
  305. package/tests/scripts/dispatch-line-gate.sh +0 -61
  306. package/tests/scripts/dispatch-reference-gate.sh +0 -173
  307. package/tests/scripts/ensure-default-config.sh +0 -162
  308. package/tests/scripts/escalation.sh +0 -409
  309. package/tests/scripts/eval-runner.sh +0 -3692
  310. package/tests/scripts/evals-packaging.sh +0 -224
  311. package/tests/scripts/fact-sheet.sh +0 -296
  312. package/tests/scripts/fixtures/legacy-shard-no-schema.json +0 -50
  313. package/tests/scripts/fixtures/mock-stdin-read-throw.cjs +0 -18
  314. package/tests/scripts/fixtures/size-tier-cases.json +0 -87
  315. package/tests/scripts/generate-digest.sh +0 -180
  316. package/tests/scripts/global-config.sh +0 -167
  317. package/tests/scripts/goldens/loop-state-breach.json +0 -1
  318. package/tests/scripts/goldens/loop-state-done.json +0 -1
  319. package/tests/scripts/goldens/somi-findings.json +0 -336
  320. package/tests/scripts/goldens/somi-loop.json +0 -168
  321. package/tests/scripts/lib/adr-shape.mjs +0 -41
  322. package/tests/scripts/lib/agent-registry-tests.mjs +0 -95
  323. package/tests/scripts/lib/brief-only-guard.mjs +0 -27
  324. package/tests/scripts/lib/checkpoint-gate.mjs +0 -91
  325. package/tests/scripts/lib/digest-marker-coupling.mjs +0 -52
  326. package/tests/scripts/lib/dispatch-reference-gate.mjs +0 -121
  327. package/tests/scripts/lib/escalation-facts-tests.mjs +0 -140
  328. package/tests/scripts/lib/escalation-tests.mjs +0 -154
  329. package/tests/scripts/lib/findings-ledger-tests.mjs +0 -118
  330. package/tests/scripts/lib/loop-engine-tests.mjs +0 -287
  331. package/tests/scripts/lib/loop-escalate-tests.mjs +0 -356
  332. package/tests/scripts/lib/loop-flow-gate.mjs +0 -173
  333. package/tests/scripts/lib/loop-notes-tests.mjs +0 -384
  334. package/tests/scripts/lib/loop-step-cli-tests.mjs +0 -156
  335. package/tests/scripts/lib/loop-step-close-tests.mjs +0 -351
  336. package/tests/scripts/lib/loop-step-lenient-tests.mjs +0 -114
  337. package/tests/scripts/lib/loop-step-state-tests.mjs +0 -127
  338. package/tests/scripts/lib/loop-step-tests.mjs +0 -499
  339. package/tests/scripts/lib/loop-step-unwritten-tests.mjs +0 -55
  340. package/tests/scripts/lib/multipass-dependence.mjs +0 -192
  341. package/tests/scripts/lib/multipass-source-identity.mjs +0 -243
  342. package/tests/scripts/lib/path-facts-tests.mjs +0 -198
  343. package/tests/scripts/lib/path-safety-tests.mjs +0 -201
  344. package/tests/scripts/lib/reference-pair.mjs +0 -61
  345. package/tests/scripts/lib/retirement-gate.mjs +0 -172
  346. package/tests/scripts/lib/run-suites.mjs +0 -139
  347. package/tests/scripts/lib/shell-embedded-js.mjs +0 -47
  348. package/tests/scripts/lib/ship-loop-sizing-guard.mjs +0 -52
  349. package/tests/scripts/lib/site-roadmap-gate.mjs +0 -64
  350. package/tests/scripts/lib/size-tier-drift.mjs +0 -74
  351. package/tests/scripts/lib/sizing-score-tests.mjs +0 -210
  352. package/tests/scripts/lib/sizing-set-tests.mjs +0 -131
  353. package/tests/scripts/lib/somi-mcp-client.mjs +0 -102
  354. package/tests/scripts/lib/somi-mcp-config-tests.mjs +0 -92
  355. package/tests/scripts/lib/somi-mcp-loop-tests.mjs +0 -226
  356. package/tests/scripts/lib/somi-mcp-tests.mjs +0 -491
  357. package/tests/scripts/lib/somi-mcp-tier-tests.mjs +0 -64
  358. package/tests/scripts/lib/somi-mcp-tool-schema.mjs +0 -38
  359. package/tests/scripts/loop-engine.sh +0 -22
  360. package/tests/scripts/loop-flow-gate.sh +0 -11
  361. package/tests/scripts/retirement-gate.sh +0 -306
  362. package/tests/scripts/review-panel-seats.sh +0 -32
  363. package/tests/scripts/run-card.sh +0 -57
  364. package/tests/scripts/run-suites.sh +0 -74
  365. package/tests/scripts/run.sh +0 -689
  366. package/tests/scripts/site-roadmap-gate.sh +0 -76
  367. package/tests/scripts/size-tier.sh +0 -562
  368. package/tests/scripts/somi-agent-dispatch-contract.sh +0 -224
  369. package/tests/scripts/somi-config.sh +0 -286
  370. package/tests/scripts/somi-dispatch.sh +0 -465
  371. package/tests/scripts/somi-mcp.sh +0 -15
  372. package/tests/scripts/suite-plan.json +0 -20
@@ -1,282 +0,0 @@
1
- // loop-notes.mjs -- the loop's two narrow writers into a work item (the tool writes only these): a diary entry at the
2
- // top of diary.md (40/15 compaction into diary-archive.md), and in progress.md only the `| N.M |` row of the iteration
3
- // table, the done count in that phase's row of the phase table (`a/b` in `Iterations done / total`, set to the number of
4
- // the phase's rows marked done; recounted on every row mark, `open` included) and the `**Last activity**` line (a
5
- // missing one is inserted at the end of `## Status`). Writes are confined to <root>/.somi/plans/<slug>/: slug and
6
- // iteration match a closed pattern before any path is built, links and special files are refused, free text is one
7
- // printable line, and a file or row not in template shape stays byte-identical and comes back in `unwritten`. Writes are
8
- // temp file + rename; time is the `now` parameter. Every writer returns { wrote: [paths relative to root], unwritten: [{
9
- // file, reason, line }] } (a write-failed item also carries the errno `code`; a replayed diary entry adds `skipped:
10
- // 'replay'`); a bad argument throws a usage error (64). Markdown safety rests on the callers: every title and body is
11
- // built from enums, numbers and ids, never from a model's text (oneLine strips breaks and control characters, not markup).
12
-
13
- import fs from 'node:fs';
14
- import path from 'node:path';
15
- import { randomBytes } from 'node:crypto';
16
- import { KIND, usageError } from './loop-exit.mjs';
17
- import { ITERATION_RE, SLUG_RE } from './run-card.mjs';
18
- import { archiveHead, archiveShape, CATEGORIES, compactDiary, formatEntry, insertEntry, isReplay, isSummaryTitle } from './loop-notes-compact.mjs';
19
-
20
- export { ITERATION_RE };
21
- export const STATUSES = ['not-started', 'in-progress', 'done', 'blocked', 'superseded'];
22
- const MAX_TEXT = 300;
23
- // Every entry the writer makes ends with this line, so a reader can tell it from a person's. The writer authors neither
24
- // decision-change nor plan-change: those are never compacted away, and only a person decides them.
25
- const PROVENANCE = 'Written by the loop step engine; every field comes from stored loop state.';
26
- const WRITABLE = CATEGORIES.filter((c) => c !== 'decision-change' && c !== 'plan-change');
27
- const MAX_FILE = 4 * 1024 * 1024;
28
- // Removed by Unicode property, so invisible code points (tags, variation selectors, fillers, bidi, zero-width) cannot pass.
29
- // Exported: the one definition, the step kit (loop-step-kit.mjs) cleans what it echoes with it too (\u{2800}, the blank braille cell, is not default-ignorable).
30
- export const CONTROL = /[\p{Cc}\p{Cf}\p{Cs}\p{Co}\p{Cn}\p{Default_Ignorable_Code_Point}\p{Variation_Selector}\u{2800}]/gu;
31
- const BREAKS = /[\r\n\t\v\f\u{85}\u{2028}\u{2029}]+/gu;
32
-
33
- // One printable line, at most 300 characters, that cannot open a heading. Throws on a non-string.
34
- function oneLine(v, what) {
35
- if (typeof v !== 'string') throw usageError(`${what} must be a string`);
36
- const s = v.replace(BREAKS, ' ').replace(CONTROL, '').replace(/\s+/g, ' ').trim().replace(/^[#\s]+/, '');
37
- return [...s].slice(0, MAX_TEXT).join('').trim();
38
- }
39
- // A table cell additionally cannot carry a pipe, so it cannot add a column.
40
- const cell = (v, what) => oneLine(v, what).replace(/\|/g, '');
41
-
42
- // `now` must start with a real instant, YYYY-MM-DDTHH:MM, in 2000..2099 (a Date round-trip rejects 02-30 and 99:99).
43
- function stampOf(now) {
44
- const minute = typeof now === 'string' && /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}/.test(now) ? now.slice(0, 16) : null;
45
- const at = minute && new Date(`${minute}:00Z`);
46
- if (!at || Number.isNaN(at.getTime()) || at.toISOString().slice(0, 16) !== minute || at.getUTCFullYear() < 2000 || at.getUTCFullYear() > 2099) throw usageError('now must be an ISO timestamp in 2000..2099');
47
- return { date: minute.slice(0, 10), stamp: minute.replace('T', ' ') };
48
- }
49
-
50
- // -> { dir } | { reason: 'missing' | 'unreadable' | 'not a plain directory' }. Every component of `parts` below `root` must
51
- // be a real directory (a link is refused). Exported: the step kit and the review step walk the findings ledger's directory with it too.
52
- export function plainDir(root, parts) {
53
- let dir = root;
54
- for (const part of parts) {
55
- try { if (!fs.lstatSync(dir = path.join(dir, part)).isDirectory()) return { reason: 'not a plain directory' }; } catch (e) { return { reason: e.code === 'ENOENT' ? 'missing' : 'unreadable' }; }
56
- }
57
- return { dir };
58
- }
59
-
60
- // -> { dir, rel } | { refused }. The plan directory, below the (realpath-resolved) root, through plainDir.
61
- function planDir({ root, slug }) {
62
- if (typeof slug !== 'string' || !SLUG_RE.test(slug)) throw usageError('slug must match ^[a-z0-9][a-z0-9-]{0,63}$');
63
- if (typeof root !== 'string' || !path.isAbsolute(root)) throw usageError('root must be an absolute path');
64
- let real;
65
- try { real = fs.realpathSync(root); } catch { throw usageError('root is not readable'); }
66
- const walked = plainDir(real, ['.somi', 'plans', slug]);
67
- if (walked.reason) return { refused: walked.reason === 'not a plain directory' ? 'plan-dir-not-a-plain-directory' : 'plan-dir-missing' };
68
- return { dir: walked.dir, rel: `.somi/plans/${slug}` };
69
- }
70
-
71
- // -> { text, mode } | { reason }. A symlink, a non-file (refused before open: a FIFO would block it) and an oversized file are refused.
72
- // The text is read as LF: a leading UTF-8 BOM is dropped and every CRLF becomes LF, so a plan file saved by an editor or a
73
- // shell that writes CRLF (Set-Content in Windows PowerShell 5.1) reads like the template; a writer saves it back as LF. A
74
- // lone CR is kept, and the shape checks still refuse it.
75
- const asLf = (text) => text.replace(/^\uFEFF/, '').replace(/\r\n/g, '\n');
76
- export function readPlanFile(file) {
77
- try {
78
- const l = fs.lstatSync(file);
79
- if (l.isSymbolicLink() || !l.isFile()) return { reason: l.isSymbolicLink() ? 'symlink' : 'not-a-regular-file' };
80
- const fd = fs.openSync(file, fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW ?? 0) | (fs.constants.O_NONBLOCK ?? 0) | (fs.constants.O_NOCTTY ?? 0));
81
- try {
82
- const st = fs.fstatSync(fd);
83
- if (!st.isFile() || st.size > MAX_FILE) return { reason: st.isFile() ? 'too-large' : 'not-a-regular-file' };
84
- return { text: asLf(fs.readFileSync(fd, 'utf8')), mode: st.mode & 0o777 };
85
- } finally { fs.closeSync(fd); }
86
- } catch (e) { return { reason: e.code === 'ENOENT' ? 'missing' : 'unreadable' }; }
87
- }
88
-
89
- // Temp file in the same directory, then rename: a crash leaves the old file or the new one, never half of either.
90
- // A failed write (EACCES, ENOSPC, rename) removes its temp file and returns the errno code; null on success. It never throws.
91
- function writeAtomic(file, text, mode = 0o644) {
92
- const tmp = path.join(path.dirname(file), `.${path.basename(file)}.${randomBytes(6).toString('hex')}.tmp`);
93
- try {
94
- fs.writeFileSync(tmp, text, { flag: 'wx', mode });
95
- fs.renameSync(tmp, file);
96
- return null;
97
- } catch (e) {
98
- try { fs.rmSync(tmp, { force: true }); } catch { /* the temp name is random; a leftover cannot be read as a plan file */ }
99
- return /^[A-Z0-9_]{1,32}$/.test(e?.code) ? e.code : 'UNKNOWN';
100
- }
101
- }
102
-
103
- // `kind` names the record the line summarises (diary-entry, iteration-row, last-activity), so the caller knows what to write where;
104
- // an item that asks for no write (a refused move, a skipped compaction) has the kind `notice`.
105
- const refusal = (file, reason, line, kind) => ({ wrote: [], unwritten: [{ file, reason, line, kind }] });
106
- const writeFailed = (file, code, line, kind) => ({ file, reason: 'write-failed', code, line, kind });
107
- // A diary with no entry yet: the title, then only blank, quoted (`> `) and `---` lines. The first entry goes after them.
108
- const bareDiary = (text) => archiveShape(text) && text.split('\n').slice(1).every((l) => l.trim() === '' || l.startsWith('>') || l.trim() === '---');
109
- const SKIPPED = 'compaction skipped; diary.md is over 40 entries';
110
- const skipped = (reason, code) => ({ file: 'diary-archive.md', reason, ...(code ? { code } : {}), line: SKIPPED, kind: KIND.notice });
111
-
112
- export function appendDiary(plan, entry) {
113
- const { stamp } = stampOf(entry.now);
114
- if (!WRITABLE.includes(entry.category)) throw usageError(`category must be one of ${WRITABLE.join('|')}`);
115
- const title = oneLine(entry.title, 'title');
116
- if (!/[\p{L}\p{N}]/u.test(title)) throw usageError('title must contain a letter or a digit');
117
- if (isSummaryTitle(title)) throw usageError('a title starting "Compacted:" is reserved for the compaction summary');
118
- const text = formatEntry({ stamp, title, category: entry.category, phase: oneLine(entry.phase ?? 'work-item-wide', 'phase') || 'work-item-wide', body: [oneLine(entry.body ?? '', 'body'), PROVENANCE].filter(Boolean).join('\n\n') });
119
- const line = [entry.category, title, oneLine(entry.body ?? '', 'body')].filter(Boolean).join(' — '); // what a caller reads: not the entry, whose stamp, markup and provenance it builds itself
120
- const p = planDir(plan);
121
- if (p.refused) return refusal('diary.md', p.refused, line, KIND.diaryEntry);
122
- const file = path.join(p.dir, 'diary.md');
123
- const cur = readPlanFile(file);
124
- const next = cur.text === undefined ? null : insertEntry(cur.text, text) ?? (bareDiary(cur.text) ? `${cur.text.replace(/\n*$/, '\n\n')}${text}` : null);
125
- if (next === null) return refusal('diary.md', cur.reason ?? 'not-template-shape', line, KIND.diaryEntry);
126
- if (isReplay(cur.text, text)) return { wrote: [], unwritten: [], skipped: 'replay' }; // a replayed step: this exact entry is already newest
127
- const wrote = []; const unwritten = [];
128
- let diary = next;
129
- const compacted = compactDiary(next, stamp);
130
- if (compacted) {
131
- const archiveFile = path.join(p.dir, 'diary-archive.md');
132
- const arch = readPlanFile(archiveFile);
133
- if (arch.reason === 'missing' || (arch.text !== undefined && archiveShape(arch.text))) {
134
- // The archive first: a crash between the two writes duplicates entries, it never loses any.
135
- const code = writeAtomic(archiveFile, (arch.text ?? archiveHead(plan.slug)).replace(/\n*$/, '\n\n') + compacted.archived, arch.mode);
136
- if (code) unwritten.push(skipped('write-failed', code));
137
- else {
138
- wrote.push(`${p.rel}/diary-archive.md`);
139
- diary = compacted.diary;
140
- }
141
- } else unwritten.push(skipped(arch.reason === 'too-large' ? 'archive-too-large' : arch.reason ?? 'not-template-shape'));
142
- }
143
- const failed = writeAtomic(file, diary, cur.mode);
144
- if (failed) return { wrote, unwritten: [...unwritten, writeFailed('diary.md', failed, line, KIND.diaryEntry)] };
145
- wrote.push(`${p.rel}/diary.md`);
146
- return { wrote, unwritten };
147
- }
148
-
149
- // Edit progress.md through `edit(text)` -> { text, notices? } (the new file; notices ride along as unwritten items) or { reason } (not in template shape: no write).
150
- function editProgress(plan, edit, line, kind) {
151
- const p = planDir(plan);
152
- if (p.refused) return refusal('progress.md', p.refused, line, kind);
153
- const file = path.join(p.dir, 'progress.md');
154
- const cur = readPlanFile(file);
155
- const out = cur.text === undefined ? cur : archiveShape(cur.text) ? edit(cur.text) : { reason: 'not-template-shape' };
156
- if (out.text === undefined) return refusal('progress.md', out.reason, line, out.notice ? KIND.notice : kind);
157
- const failed = writeAtomic(file, out.text, cur.mode);
158
- if (failed) return { wrote: [], unwritten: [writeFailed('progress.md', failed, line, kind)] };
159
- return { wrote: [`${p.rel}/progress.md`], unwritten: out.notices ?? [] };
160
- }
161
-
162
- // The `## <title>` section: { start, end } (the heading's line and the next heading's, or the end), or null unless the
163
- // heading is there exactly once and its section holds no code fence or `<!--`.
164
- function sectionOf(lines, title) {
165
- const at = lines.flatMap((l, i) => (l === `## ${title}` ? [i] : []));
166
- if (at.length !== 1) return null;
167
- const stop = lines.findIndex((l, i) => i > at[0] && /^#{1,6}\s/.test(l));
168
- const end = stop < 0 ? lines.length : stop;
169
- return lines.slice(at[0] + 1, end).some((l) => /^\s*(```|~~~)|<!--/.test(l)) ? null : { start: at[0], end };
170
- }
171
-
172
- const splitRow = (l) => (l.startsWith('|') && l.endsWith('|') ? l.slice(1, -1).split('|') : null);
173
- const HEADER = ['Iteration', null, 'Status', 'Reviewed', 'Last activity'];
174
-
175
- // The one reader of the `| N.M |` row, for markIteration and for `open`: the file is in template shape (a `# ` title
176
- // first, no CR), the `## Iteration progress` heading is there exactly once, its section (which ends at the next heading
177
- // of any level) holds no code fence or `<!--`, the template header and its separator open it, and the row exists once
178
- // with five cells. With `loose` the header need not be the template's: it must start with Iteration, name a Status column,
179
- // and the row must have as many cells as the header; Reviewed and Last activity are used where the header has them.
180
- // -> { lines, index, cells, cols } (the column of each cell, -1 where the table has none) | { reason: 'not-template-shape' |
181
- // 'row-not-template-shape' | 'missing' | 'ambiguous', why? } where `why` names the condition that failed (for a person;
182
- // nothing branches on it).
183
- export function findIterationRow(text, iteration, loose = false) {
184
- const lines = text.split('\n');
185
- const at = lines.flatMap((l, i) => (l === '## Iteration progress' ? [i] : []));
186
- const shape = (why) => ({ reason: 'not-template-shape', why });
187
- if (!archiveShape(text)) return shape('the file does not start with a "# " title, or holds a carriage return');
188
- if (at.length !== 1) return shape(`the "## Iteration progress" heading appears ${at.length} times, not once`);
189
- const start = at[0];
190
- const stop = lines.findIndex((l, i) => i > start && /^#{1,6}\s/.test(l));
191
- if (lines.slice(start + 1, stop < 0 ? undefined : stop).some((l) => /^\s*(```|~~~)|<!--/.test(l))) return shape('the section holds a code fence or <!--');
192
- const rows = lines.flatMap((l, i) => (i > start && (stop < 0 || i < stop) && l.startsWith('|') ? [i] : []));
193
- const head = rows.length >= 2 ? splitRow(lines[rows[0]]) : null;
194
- const names = head?.map((h) => h.trim());
195
- const template = head?.length === 5 && HEADER.every((h, i) => !h || names[i] === h);
196
- const lenient = loose && names?.[0] === 'Iteration' && names.includes('Status');
197
- if (!head || !/^\|[-| :]+\|$/.test(lines[rows[1]]) || !(template || lenient)) return shape('the table header or its separator row is not the template\'s');
198
- const cols = template ? { status: 2, reviewed: 3, activity: 4 } : { status: names.indexOf('Status'), reviewed: names.indexOf('Reviewed'), activity: names.indexOf('Last activity') };
199
- const hits = rows.slice(2).filter((i) => splitRow(lines[i])?.[0].trim() === iteration);
200
- if (hits.length !== 1) return { reason: hits.length === 0 ? 'missing' : 'ambiguous' };
201
- const cells = splitRow(lines[hits[0]]);
202
- return cells.length === head.length ? { lines, index: hits[0], cells, cols } : { reason: 'row-not-template-shape' };
203
- }
204
-
205
- // Set phase N's `a/b` cell of the `## Phase progress` table (column named `Iterations done / total`, row whose first cell is
206
- // N) to the number of the iteration table's `N.*` rows that are done, keeping the total and the cell's width. Edits `lines`.
207
- // -> [] (also when the table, the column, the row or an `a/b` cell is absent: nothing to keep in step) | [a notice
208
- // item] when the count is above the total, in which case the cell is left as it was.
209
- function setPhaseDone(lines, index, cols, iteration, line) {
210
- const phase = iteration.split('.')[0];
211
- const sec = sectionOf(lines, 'Phase progress');
212
- if (!sec) return [];
213
- let top = lines.findIndex((l, i) => i > sec.start && i < sec.end && l.startsWith('|')); // the table is the run of `|` lines from the first
214
- if (top < 0) return [];
215
- const rows = [];
216
- while (top < sec.end && lines[top].startsWith('|')) rows.push(top++);
217
- const names = rows.length >= 2 && /^\|[-| :]+\|$/.test(lines[rows[1]]) ? splitRow(lines[rows[0]])?.map((h) => h.trim()) : null;
218
- const col = names ? names.indexOf('Iterations done / total') : -1;
219
- const hits = col < 0 ? [] : rows.slice(2).filter((i) => splitRow(lines[i])?.[0].trim() === phase);
220
- const cells = hits.length === 1 ? splitRow(lines[hits[0]]) : null;
221
- const m = names && cells?.length === names.length ? /^(\s*)(\d{1,4})\/(\d{1,4})(\s*)$/.exec(cells[col]) : null;
222
- if (!m) return [];
223
- let first = index; let last = index; // the iteration table is the run of table lines around the row
224
- while (lines[first - 1]?.startsWith('|')) first--;
225
- while (lines[last + 1]?.startsWith('|')) last++;
226
- // the marked row's width (findIterationRow proved it equals the header's): a row of another width is not counted, a repeated id counts once
227
- const width = splitRow(lines[index]).length;
228
- const done = new Set(lines.slice(first, last + 1).flatMap((l) => { const c = splitRow(l); return c?.length === width && c[0].trim().startsWith(`${phase}.`) && c[cols.status]?.trim() === 'done' ? [c[0].trim()] : []; })).size;
229
- if (done > Number(m[3])) return [{ file: 'progress.md', reason: 'count-above-total', line: `phase ${phase}: ${done} iterations done, total ${m[3]}; ${line}`, kind: KIND.notice }];
230
- if (done !== Number(m[2])) {
231
- cells[col] = `${m[1]}${done}/${m[3]}`.padEnd(cells[col].length);
232
- lines[hits[0]] = `|${cells.join('|')}|`;
233
- }
234
- return [];
235
- }
236
-
237
- // The moves of a Status cell (a rewrite of the same status is always allowed). Nothing leaves done or superseded, and
238
- // superseded is set by a human editing the plan, never by this writer.
239
- const MOVES = { 'not-started': ['in-progress'], 'in-progress': ['done', 'blocked'], blocked: ['in-progress'] };
240
-
241
- // Change Status, Reviewed and Last activity of the `| N.M |` row (the template's columns 3 to 5, or the ones a table with
242
- // another header has), keeping the other cells and the column widths. The row must exist once with as many cells as its
243
- // header, and a Status change must be one of MOVES (else `transition-refused`, nothing written). In the same write the
244
- // phase's done count is brought in step with the table (setPhaseDone).
245
- export function markIteration(plan, iteration, { status, reviewed, activity, now }) {
246
- if (typeof iteration !== 'string' || !ITERATION_RE.test(iteration)) throw usageError('iteration must look like 1.2');
247
- const { date } = stampOf(now);
248
- if (status !== undefined && !STATUSES.includes(status)) throw usageError(`status must be one of ${STATUSES.join('|')}`);
249
- const patch = { status, reviewed: reviewed === undefined ? undefined : cell(reviewed, 'reviewed'), activity: activity === undefined ? date : `${date} — ${cell(activity, 'activity')}` };
250
- const line = `iteration ${iteration}: Status=${patch.status ?? '(unchanged)'}, Reviewed=${patch.reviewed ?? '(unchanged)'}, Last activity=${patch.activity}`;
251
- return editProgress(plan, (text) => {
252
- const found = findIterationRow(text, iteration, true);
253
- if (!found.lines) return { reason: { missing: 'row-missing', ambiguous: 'row-ambiguous' }[found.reason] ?? found.reason };
254
- const { lines, index, cells, cols } = found;
255
- const was = cells[cols.status].trim();
256
- if (status !== undefined && status !== was && !(Object.hasOwn(MOVES, was) && MOVES[was].includes(status))) return { reason: 'transition-refused', notice: true };
257
- for (const field of Object.keys(patch)) if (patch[field] !== undefined && cols[field] >= 0) cells[cols[field]] = ` ${patch[field]} `.padEnd(cells[cols[field]].length); // a column the table lacks is skipped
258
- lines[index] = `|${cells.join('|')}|`;
259
- const notices = setPhaseDone(lines, index, cols, iteration, line);
260
- return { text: lines.join('\n'), notices };
261
- }, line, KIND.iterationRow);
262
- }
263
-
264
- export function setLastActivity(plan, { activity, now }) {
265
- const { date } = stampOf(now);
266
- const value = `**Last activity**: ${date} — ${oneLine(activity, 'activity')}`;
267
- return editProgress(plan, (text) => {
268
- const lines = text.split('\n');
269
- const hits = lines.flatMap((l, i) => (l.startsWith('**Last activity**: ') ? [i] : []));
270
- if (hits.length > 1) return { reason: 'row-ambiguous' };
271
- if (hits.length === 1) lines[hits[0]] = value;
272
- else { // no line yet: it goes after the last line of `## Status`, set off by a blank line unless that is a `**key**: ` line
273
- const sec = sectionOf(lines, 'Status');
274
- if (!sec) return { reason: 'line-missing' };
275
- if (lines.slice(sec.start, sec.end).some((l) => /^[\W_]*last activity(?![a-z0-9])/i.test(l))) return { reason: 'row-ambiguous' }; // the line is there in another spelling
276
- let last = sec.end - 1;
277
- while (lines[last].trim() === '') last--;
278
- lines.splice(last + 1, 0, ...(/^\*\*[^*]+\*\*: /.test(lines[last]) ? [] : ['']), value);
279
- }
280
- return { text: lines.join('\n') };
281
- }, value, KIND.lastActivity);
282
- }