@skathio/somi 4.1.0 → 5.0.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 (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 +83 -228
  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 +28 -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 +40 -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 +165 -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 +73 -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 +38 -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 +181 -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 -226
  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 -278
  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 -301
  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 -128
  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 -371
  334. package/tests/scripts/lib/loop-step-cli-tests.mjs +0 -141
  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,395 +0,0 @@
1
- // loop-review.mjs -- what /code-loop's reviewer must see (which lens, which scope), decided from recorded state
2
- // rather than from the reviewer's reading of evidence. Shared by scripts/somi-loop.mjs; no output of its own.
3
-
4
- import crypto from 'node:crypto';
5
- import fs from 'node:fs';
6
- import os from 'node:os';
7
- import path from 'node:path';
8
- import { execFileSync, spawnSync } from 'node:child_process';
9
- import { readRecord } from './tier-record.mjs';
10
- import { LoopExit, usageError } from './loop-exit.mjs';
11
- import { CONTROL } from './loop-notes.mjs';
12
-
13
- // The sizing record decides the review lens: a work item that may handle untrusted input or touch auth, crypto,
14
- // secrets or PII (security_lens in scripts/somi-tier.mjs's record) is reviewed with the security lens on every
15
- // pass. No record, or a record without the flag, asks for nothing beyond the loop's configured mode.
16
- export function reviewMinFor(root, slug) {
17
- return readRecord(root, slug)?.security_lens === true ? 'security' : null;
18
- }
19
-
20
- const EXCLUDE = ':(exclude)';
21
- const PATHSPEC = ['.', `${EXCLUDE}.somi`, `${EXCLUDE}.claude`];
22
- // The time one git call may take. A call that exceeds it is a refusal (exit 64, "git did not answer") from every caller: the CLI prints
23
- // the message and exits 64, a step answers exit 64, and no gate passes on a measurement that was not made. Mutable for the tests only.
24
- // shortcut: one limit for all calls, so a repository too large for 60 s is refused; raise it when one is reported.
25
- export const LIMITS = { gitTimeoutMs: 60000, snapshotBytes: 256 * 1024 * 1024 }; // snapshotBytes: file content one ignored-file snapshot reads, past which a file is stood for by its size and change time
26
- const MAX_LISTING = 256 * 1024 * 1024; // bytes of git output read in one go; a bigger listing is refused, never truncated
27
- export const OBJECT_ID = /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/;
28
- const MAX_BLOB = 1024 * 1024; // a blob over this is counted by size (50 bytes a line) instead of read
29
- const cannot = (what) => Object.assign(usageError(`cannot measure the diff: ${what}; nothing was counted, so this refuses`), { what });
30
- // Every git call here reads the repository whose top level is the first directory at or above `root` (resolved through
31
- // symlinks) that has a .git entry (git's own discovery, which does not trust core.worktree), provided that entry is a
32
- // git directory or a `gitdir: <path>` file pointing at one; anything else is refused, not skipped. The repository selectors in the caller's
33
- // environment are dropped and the git directory and work tree are pinned (a core.worktree in the repository's own
34
- // config would otherwise point every call at another directory), while `-C root` and the `.`-relative pathspecs keep
35
- // the measurement to root's own subtree. core.ignoreCase is always false, so no config line can make git treat
36
- // Foo.txt as the tracked foo.txt (on a case-insensitive filesystem a case-only rename then over-counts: the safe side).
37
- // It never goes through a replace ref (which would hand the gate a substitute for the real blob), a core.fsmonitor
38
- // program or a hook, none of which git should run for a measurement.
39
- const SELECTORS = ['GIT_DIR', 'GIT_WORK_TREE', 'GIT_INDEX_FILE', 'GIT_OBJECT_DIRECTORY', 'GIT_ALTERNATE_OBJECT_DIRECTORIES', 'GIT_NAMESPACE', 'GIT_COMMON_DIR', 'GIT_CEILING_DIRECTORIES', 'GIT_ICASE_PATHSPECS', 'GIT_LITERAL_PATHSPECS', 'GIT_GLOB_PATHSPECS', 'GIT_NOGLOB_PATHSPECS'];
40
- const SAFE = ['-c', 'core.fsmonitor=false', '-c', `core.hooksPath=${os.devNull}`, '-c', 'core.ignoreCase=false']; // shortcut: a null-device hooksPath is unverified on Windows, check it before supporting that
41
- const bare = () => { const env = { ...process.env, GIT_NO_REPLACE_OBJECTS: '1' }; for (const k of SELECTORS) delete env[k]; return env; };
42
- // A git directory, as far as one can tell without trusting it: a HEAD, and objects of its own or a commondir (a linked
43
- // worktree's directory has no objects). Forged internals inside it are an accepted residual.
44
- const isGitDir = (p) => present(path.join(p, 'HEAD')) && (present(path.join(p, 'objects')) || present(path.join(p, 'commondir')));
45
- const validGit = (d) => {
46
- const g = path.join(d, '.git');
47
- try {
48
- const st = fs.statSync(g);
49
- if (st.isDirectory()) return isGitDir(g);
50
- if (!st.isFile() || st.size > 4096) return false;
51
- const fd = fs.openSync(g, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW | fs.constants.O_NONBLOCK); // never follows a link to a pseudo-file, never blocks
52
- let text;
53
- try { const buf = Buffer.alloc(4097); const n = fs.readSync(fd, buf, 0, 4097, 0); if (n > 4096) return false; text = buf.toString('utf8', 0, n); } finally { fs.closeSync(fd); }
54
- const m = /^gitdir: ([^\r\n]+)[\r\n]*$/.exec(text); // one line, ending in CRLF or blank lines as git reads it; a relative path is relative to the gitfile's directory
55
- return m !== null && isGitDir(path.resolve(d, m[1]));
56
- } catch { return false; }
57
- };
58
- const topLevel = (root) => {
59
- for (let d = root; ; d = path.dirname(d)) {
60
- if (present(path.join(d, '.git'))) {
61
- if (!validGit(d)) throw cannot(`"${shownTail(path.join(d, '.git'))}" is neither a git directory nor a "gitdir: <path>" file that points at one`);
62
- return d;
63
- }
64
- if (path.dirname(d) === d) throw cannot('no git repository (.git) at or above the project directory');
65
- }
66
- };
67
- // The directories git says it could not open, as { dir, why }: only git's own warning line (LC_ALL=C pins its text), so a file name inside another
68
- // warning, which never starts a line with this text, is not one. A directory that vanished while git walked (ENOENT) hides nothing and is skipped.
69
- const NOT_OPENED = /^warning: could not open directory '(.*)': (.*)$/gm;
70
- export const unopened = (stderr) => [...String(stderr).matchAll(NOT_OPENED)].filter((m) => m[2] !== 'No such file or directory').map((m) => ({ dir: m[1], why: m[2] }));
71
- const run = (root, args, opts = {}) => {
72
- let real; // a project reached through a symlink is measured under its real path, the one git's own cwd reports
73
- try { real = fs.realpathSync(root); } catch { throw cannot('the project directory cannot be resolved'); }
74
- const top = topLevel(real);
75
- const pinned = { ...bare(), GIT_WORK_TREE: top };
76
- const limit = { timeout: LIMITS.gitTimeoutMs, killSignal: 'SIGKILL' };
77
- try {
78
- const GIT_DIR = execFileSync('git', ['-C', top, ...SAFE, 'rev-parse', '--absolute-git-dir'], { ...limit, encoding: 'utf8', env: pinned }).trim();
79
- const { unlistable, ...rest } = opts;
80
- if (!unlistable) return execFileSync('git', ['-C', real, ...SAFE, ...args], { ...limit, ...rest, env: { ...pinned, GIT_DIR, ...rest.env } });
81
- // unlistable: git lists the tree, and a directory it cannot open is a warning on stderr with exit 0, so the listing is shorter than the tree (a
82
- // policy folder made enterable but not listable hides a new file from it). The caller pipes stderr; that warning is a refusal, with no path in it.
83
- const r = spawnSync('git', ['-C', real, ...SAFE, ...args], { ...limit, ...rest, env: { ...pinned, GIT_DIR, LC_ALL: 'C', ...rest.env } });
84
- if (r.error) throw r.error;
85
- if (r.status !== 0) throw Object.assign(new Error(`git exited ${r.status}`), { status: r.status, stderr: r.stderr });
86
- const own = path.relative(top, real).split(path.sep).join('/'); // git names the directory from the repository top, the callers from the project root
87
- const dirs = unopened(r.stderr).map(({ dir, why }) => ({ dir: (own !== '' && dir.startsWith(`${own}/`) ? dir.slice(own.length + 1) : dir).replace(/\/$/, ''), why }));
88
- if (dirs.length) throw Object.assign(cannot('git could not open a directory, so its listing is shorter than the tree (make the directory listable, remove it, or add it to .gitignore)'), { unlistable: true, dirs, stdout: r.stdout });
89
- return r.stdout;
90
- } catch (e) { // fails closed: a git that does not answer is a refusal, so the loop counts nothing, never a smaller diff
91
- if (e.code === 'ETIMEDOUT') throw cannot(`git did not answer within ${LIMITS.gitTimeoutMs / 1000} seconds (retry once it responds)`);
92
- throw e;
93
- }
94
- };
95
- const present = (p) => { try { fs.lstatSync(p); return true; } catch (e) { return e.code !== 'ENOENT'; } };
96
- const shown = (v) => String(v).replace(CONTROL, '').slice(0, 80); // a path or a git message as text a person can read: no control characters, bounded
97
- const shownTail = (v) => { const t = String(v).replace(CONTROL, ''); return t.length > 80 ? `…${t.slice(-79)}` : t; }; // the same, keeping the end (a path's last part names the problem)
98
-
99
- // Refuses what would make the snapshot smaller than the tree or run code outside the hooks: an index flag that
100
- // hides edits (assume-unchanged `h`; skip-worktree `S` on a file that is on disk, as a sparse checkout leaves the
101
- // files it left out absent; the throwaway index inherits them), a git replace ref (it swaps a file's content), and a
102
- // clean, smudge or process filter in this repository's own config, its worktree config or the command line (git add
103
- // runs it). Filters in the user's or system config (git-lfs, say) are not checked: they are the user's own tools, a
104
- // residual left open.
105
- function refuseHidden(root) {
106
- let listing; let replaced; let filters = '';
107
- try {
108
- listing = run(root, ['ls-files', '-v', '-z'], { encoding: 'utf8', maxBuffer: MAX_LISTING }).split('\0');
109
- replaced = run(root, ['for-each-ref', '--count=1', 'refs/replace'], { encoding: 'utf8' }).trim();
110
- try {
111
- filters = run(root, ['config', '--show-scope', '--includes', '--get-regexp', '-z', '^filter\\.'], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] });
112
- } catch (e) { if (e.status !== 1) throw e; } // exit 1: no such key
113
- } catch (e) {
114
- if (e instanceof LoopExit) throw e;
115
- throw cannot('git could not read the index flags, the replace refs or the repository config');
116
- }
117
- if (replaced) throw cannot('the repository has git replace refs, which swap what a file contains (git replace -d removes them)');
118
- const hidden = listing.find((t) => /^[hs] /.test(t) || (t.startsWith('S ') && present(path.join(root, t.slice(2)))));
119
- if (hidden) throw cannot(`the index marks "${shown(hidden.slice(2))}" assume-unchanged or skip-worktree, which hides its edits (git update-index --no-assume-unchanged --no-skip-worktree)`);
120
- const toks = filters.split('\0'); // pairs of a scope and "key\nvalue"
121
- const filter = toks.filter((t, i) => i % 2).map((t, i) => [toks[2 * i], t.split('\n')[0]])
122
- .find(([scope, key]) => ['local', 'worktree', 'command'].includes(scope) && /^filter\..+\.(clean|smudge|process)$/i.test(key));
123
- if (filter) throw cannot(`the repository config defines ${shown(filter[1])}, and git add would run it`);
124
- }
125
-
126
- // The gate does not support submodules: their files are in no tree it builds (the superproject records a commit), and
127
- // counting them would take a snapshot each. A repository with one is refused before anything is measured: a gitlink in
128
- // the index, a gitlink in HEAD (what `git rm --cached` leaves), or a checked-out submodule, which git lists as an
129
- // untracked directory with a trailing slash (a nested repository). .somi/ and .claude/ are outside the measurement.
130
- const EXCLUDED = /^\.(somi|claude)(\/|$)/;
131
- export function refuseSubmodules(root) {
132
- const list = (args) => {
133
- try {
134
- return run(root, args, { encoding: 'utf8', maxBuffer: MAX_LISTING, stdio: ['ignore', 'pipe', 'ignore'] }).split('\0');
135
- } catch (e) {
136
- if (e instanceof LoopExit) throw e;
137
- throw cannot('git could not look for submodules');
138
- }
139
- };
140
- const gitlinks = (rows) => rows.filter((t) => t.startsWith('160000 ')).map((t) => t.slice(t.indexOf('\t') + 1));
141
- let unborn = false; // a repository with no commit has no gitlink in HEAD
142
- try { run(root, ['rev-parse', '--verify', '--quiet', 'HEAD'], { stdio: 'ignore' }); } catch (e) { if (e instanceof LoopExit) throw e; if (e.status !== 1) throw cannot('git could not read HEAD'); unborn = true; }
143
- const nested = list(['ls-files', '-o', '--exclude-standard', '-z']).filter((t) => t.endsWith('/'));
144
- const found = [...gitlinks(list(['ls-files', '-s', '-z'])), ...(unborn ? [] : gitlinks(list(['ls-tree', '-r', '-z', 'HEAD'])))].find((p) => !EXCLUDED.test(p));
145
- const untracked = found === undefined ? nested.find((p) => !EXCLUDED.test(p)) : undefined;
146
- const hint = untracked === undefined ? '' : '; if it is not a submodule, add it to .gitignore';
147
- if (found !== undefined || untracked !== undefined) throw cannot(`the loop's diff gate does not support repositories with submodules (${shown(found ?? untracked)})${hint}`);
148
- }
149
-
150
- // The working tree as a git tree object: tracked and untracked files, .somi/ and .claude/ excluded, the same
151
- // surface the diff cap measures. Built through a throwaway copy of the index so the caller's index is never
152
- // touched (a copy rather than an empty index, so unchanged files are not re-hashed). Throws a refusal when git
153
- // cannot index the whole tree (an unreadable file, a path it reserves): a partial tree is a smaller diff.
154
- // Residual: the copied index is trusted, so a hand-edited `.git/index` (an entry's blob id swapped, its stat data
155
- // kept) can make an edited file count as unchanged. The gate does not defend against forged git internals; the
156
- // reviewer and the coder's sandbox do.
157
- export function measuredTree(root) {
158
- refuseSubmodules(root);
159
- refuseHidden(root);
160
- const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'somi-tree-'));
161
- const index = path.join(dir, 'index');
162
- try {
163
- const real = run(root, ['rev-parse', '--path-format=absolute', '--git-path', 'index'], { encoding: 'utf8' }).trim();
164
- if (fs.existsSync(real)) { // the copy keeps the original's times: a newer index would make an edit made in the same second look clean
165
- fs.copyFileSync(real, index);
166
- const st = fs.statSync(real); fs.utimesSync(index, st.atime, st.mtime);
167
- }
168
- const env = { GIT_INDEX_FILE: index };
169
- // git add refuses an exclusion that names only ignored paths (a .gitignore with `.somi`) and would not add them anyway
170
- const ignored = (p) => { try { run(root, ['check-ignore', '-q', '--no-index', '--', p], { stdio: 'ignore' }); return true; } catch (e) { if (e instanceof LoopExit) throw e; return false; } };
171
- const spec = PATHSPEC.filter((p) => !p.startsWith(EXCLUDE) || !ignored(p.slice(EXCLUDE.length)));
172
- // Stat settings are pinned: a looser one would let a same-size edit with a put-back mtime read as clean.
173
- // --sparse: an untracked file outside a sparse checkout's cone is still part of the tree.
174
- const pinned = ['-c', 'core.trustctime=true', '-c', 'core.checkStat=default'];
175
- run(root, [...pinned, 'add', '-A', '--sparse', '--', ...spec], { env, encoding: 'utf8', stdio: ['ignore', 'ignore', 'pipe'], unlistable: true });
176
- return run(root, ['write-tree'], { env, encoding: 'utf8' }).trim();
177
- } catch (e) {
178
- if (e instanceof LoopExit) throw e;
179
- const text = String(e.stderr ?? '');
180
- const invalid = /^error: invalid path '(.*)'$/m.exec(text)?.[1]; // git reserves some names (a case variant of .git, say) and will not add them
181
- if (invalid !== undefined) throw cannot(`git refuses the path "${shown(invalid)}" as invalid, so the tree cannot be built: rename or remove it`);
182
- const why = shown(text.split('\n').find((l) => l.trim()) ?? '');
183
- throw cannot(`git could not index the working tree${why ? ` (${why})` : ''}; an unreadable file cannot be counted: remove it or add it to .gitignore`);
184
- } finally {
185
- fs.rmSync(dir, { recursive: true, force: true });
186
- }
187
- }
188
-
189
- // HEAD of the repository under `root`, read the way the measurement reads: through the pinned git. A refusal (exit 64)
190
- // when it cannot be read; the loop's baseline is this commit.
191
- export function headCommit(root) {
192
- let id;
193
- try {
194
- id = run(root, ['rev-parse', '--verify', 'HEAD'], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim();
195
- } catch (e) {
196
- throw usageError(`cannot resolve HEAD: ${e instanceof LoopExit ? e.what : 'the repository has no commit yet, or HEAD is unreadable (commit once, then init)'}`);
197
- }
198
- if (!OBJECT_ID.test(id)) throw usageError('cannot resolve HEAD: git printed something that is not an object id');
199
- return id;
200
- }
201
-
202
- // -> tree id, or null when the tree cannot be built (callers that only narrow a review treat null as "no snapshot").
203
- export function snapshotTree(root) {
204
- try { return measuredTree(root); } catch { return null; }
205
- }
206
-
207
- // Lines in each blob: newlines, plus one for an unterminated last line, but at least one per 50 bytes. A blob over
208
- // MAX_BLOB is counted by size alone rather than read. -> Map of blob id to lines.
209
- function blobLines(root, ids) {
210
- const lines = new Map();
211
- const want = [...new Set(ids)].filter((id) => /^0+$/.test(id) ? !lines.set(id, 0) : true);
212
- if (!want.length) return lines;
213
- const cat = (mode, ids2) => {
214
- try {
215
- return run(root, ['cat-file', mode], { input: ids2.join('\n') + '\n', maxBuffer: MAX_LISTING, stdio: ['pipe', 'pipe', 'ignore'] });
216
- } catch (e) {
217
- if (e instanceof LoopExit) throw e;
218
- throw cannot(e.code === 'ENOBUFS' ? 'the changed files hidden from diff are too large to read' : 'git could not read a changed file');
219
- }
220
- };
221
- const sizes = cat('--batch-check', want).toString('latin1').split('\n').slice(0, want.length).map((l) => /^[0-9a-f]+ blob (\d+)$/.exec(l)?.[1]);
222
- if (sizes.some((z) => z === undefined)) throw cannot('git printed a blob size this cannot read');
223
- const small = [];
224
- want.forEach((id, i) => { if (Number(sizes[i]) > MAX_BLOB) lines.set(id, Math.ceil(Number(sizes[i]) / 50)); else small.push(id); });
225
- if (!small.length) return lines;
226
- const buf = cat('--batch', small);
227
- let pos = 0;
228
- for (const id of small) {
229
- const nl = buf.indexOf(10, pos);
230
- const size = Number(/^[0-9a-f]+ blob (\d+)$/.exec(buf.toString('latin1', pos, nl))?.[1]);
231
- if (nl < 0 || !Number.isInteger(size)) throw cannot('git printed a blob this cannot read');
232
- const body = buf.subarray(nl + 1, nl + 1 + size);
233
- let n = 0;
234
- for (let at = body.indexOf(10); at >= 0; at = body.indexOf(10, at + 1)) n++;
235
- lines.set(id, Math.max(n + (size > 0 && body[size - 1] !== 10 ? 1 : 0), Math.ceil(size / 50))); // never fewer than 50 bytes a line: a binary with no newline is not one line
236
- pos = nl + 1 + size + 1;
237
- }
238
- return lines;
239
- }
240
-
241
- // The files that differ between two trees (or a commit and a tree) as [{added, deleted, file, status}], `status` being git's
242
- // letter for the file (A, M, D, T), read from --raw. treeNumstat is the same without it.
243
- // NUL-separated, so a name with a tab, a quote or non-ASCII bytes is exact; renames off, so a rename into another
244
- // path is the whole file added there and removed here. Both ids must be hex object ids, and follow --end-of-options.
245
- // No external diff program and no textconv driver runs, whatever the repository or the user configures.
246
- // A file git prints as binary (a real binary, a NUL byte, or text a .gitattributes `-diff` or `binary` line hides) is
247
- // counted from the object store: the lines of its old blob as deleted and of its new blob as added. Exact for hidden
248
- // text, an upper bound for a real binary (a floor of one line per 50 bytes, so binaries count toward the cap), and not
249
- // dodgeable by an attribute the coder adds.
250
- export function treeRows(root, from, to) {
251
- if (![from, to].every((id) => typeof id === 'string' && OBJECT_ID.test(id))) throw cannot('a recorded revision is not an object id');
252
- const list = (...format) => {
253
- try {
254
- return run(root, ['diff', ...format, '-z', '--no-renames', '--no-ext-diff', '--no-textconv', '--relative', '--ignore-submodules=none', '--end-of-options', from, to, '--', ...PATHSPEC], { encoding: 'utf8', maxBuffer: MAX_LISTING, stdio: ['ignore', 'pipe', 'ignore'] }).split('\0');
255
- } catch (e) {
256
- if (e instanceof LoopExit) throw e;
257
- throw cannot(e.code === 'ENOBUFS' ? 'the changed-file listing is too large' : 'git diff failed');
258
- }
259
- };
260
- const raw = list('--raw', '--no-abbrev');
261
- const blobs = new Map(); // path -> [old blob id, new blob id]
262
- const letters = new Map(); // path -> status letter
263
- for (let i = 0; i + 1 < raw.length; i += 2) { // pairs of "<modes, ids, status>" and path: a name that starts with ':' is not mistaken for a record
264
- const [, , oldId, newId, letter] = raw[i].split(' ');
265
- blobs.set(raw[i + 1], [oldId, newId]);
266
- letters.set(raw[i + 1], letter);
267
- }
268
- const rows = list('--numstat').filter((t) => t !== '').map((t) => {
269
- const m = /^(\d+|-)\t(\d+|-)\t([\s\S]+)$/.exec(t);
270
- if (!m) throw cannot('git printed a line this cannot read');
271
- return { added: m[1] === '-' ? null : Number(m[1]), deleted: m[2] === '-' ? null : Number(m[2]), file: m[3] };
272
- });
273
- const ids = rows.filter((r) => r.added === null).flatMap((r) => blobs.get(r.file) ?? []);
274
- const lines = blobLines(root, ids);
275
- return rows.map(({ added, deleted, file }) => {
276
- const status = letters.get(file);
277
- if (added !== null) return { added, deleted, file, status };
278
- const [o, n] = blobs.get(file) ?? [];
279
- return o === undefined || o === n ? { added: 0, deleted: 0, file, status } : { added: lines.get(n), deleted: lines.get(o), file, status };
280
- });
281
- }
282
- export const treeNumstat = (root, from, to) => treeRows(root, from, to).map(({ status, ...row }) => row);
283
-
284
- // The changes the measurement leaves out because it excludes .somi and .claude, for the folders and files that carry agent policy:
285
- // as { file, added: 0, deleted: 0, status } (no lines are counted), relative to `root`, the working tree against the commit
286
- // `from`, untracked files (not ignored ones) as A. Read the way treeRows reads (renames off, so a file moved out of a guarded
287
- // folder is a D here; submodules compared in full, so a `.gitmodules` `ignore` or `diff.ignoreSubmodules` cannot hide a moved or
288
- // dirty one), and the index flags were refused by the measurement that precedes it. A gitlink in the index under .claude or at or
289
- // under .somi is a row of its own (status G, which git never prints) when the diff did not list it: the measurement exempts both, so
290
- // a submodule there is reachable, and an unchanged one still carries code the loop does not read. So is a nested repository at
291
- // .somi (a .somi/.git), which hides .somi/config.json and .somi/rules from every listing here. The ignored files under the
292
- // guarded names are compared with `before`, the snapshot taken at loop init (ignoredSnapshot): one that is new, changed or gone is a row.
293
- const GUARDED = ['.claude', '.somi/config.json', '.somi/rules'];
294
- // The ignored files the guard names, at any depth and in any case (a self-ignoring .CLAUDE/ is the policy folder on a case-insensitive filesystem).
295
- const IGNORED_SPECS = ['**/.claude', '**/.claude/**', '**/claude.md', '**/claude.local.md', '**/agents.md', '**/.mcp.json', '**/.vscode/mcp.json', '.somi/config.json', '.somi/rules'].map((p) => `:(glob,icase)${p}`);
296
- const DEPENDENCY_DIRS = new Set(['node_modules', 'vendor', 'bower_components', '.venv', 'venv', 'site-packages']);
297
- const MAX_IGNORED = 256; // entries one snapshot stores by name; more are stored as one digest
298
- const CHUNK_BYTES = 64 * 1024;
299
- const sha = (buf) => crypto.createHash('sha256').update(buf).digest('hex');
300
- // A dependency folder (a shipped AGENTS.md is not this project's) puts a path out, unless a policy folder comes first: .claude/vendor/x.md is policy.
301
- // Done here, not by an exclude pathspec, which could not tell the two apart.
302
- const dependency = (file) => { for (const s of file.split('/')) { if (DEPENDENCY_DIRS.has(s)) return true; if (/^\.(claude|somi)$/i.test(s)) return false; } return false; };
303
- // -> the file's sha-256, read in chunks; with a link followed: 'dangling' when the target is not there, 'special' when it is not a regular file.
304
- // Without one, a non-regular file is a refusal (throws). Once the byte budget is spent a file is stood for by its size and change time (the size half is for readability: the change time already moves on every write).
305
- // shortcut: that stand-in misses an edit that puts the change time back, so only a tree past LIMITS.snapshotBytes has it; raise the bound when one is reported.
306
- function fileHash(full, follow, budget) {
307
- let fd;
308
- try { fd = fs.openSync(full, fs.constants.O_RDONLY | fs.constants.O_NONBLOCK | (follow ? 0 : fs.constants.O_NOFOLLOW)); } catch (e) { // O_NONBLOCK: a FIFO is not waited on
309
- if (follow && ['ENOENT', 'ELOOP', 'ENOTDIR'].includes(e.code)) return 'dangling';
310
- throw e;
311
- }
312
- try {
313
- const st = fs.fstatSync(fd, { bigint: true });
314
- if (!st.isFile()) { if (follow) return 'special'; throw new Error('not a regular file'); }
315
- const h = crypto.createHash('sha256'); const buf = Buffer.alloc(CHUNK_BYTES);
316
- for (let n; budget.left >= 0 && (n = fs.readSync(fd, buf, 0, CHUNK_BYTES, null)) > 0;) { h.update(buf.subarray(0, n)); budget.left -= n; }
317
- return budget.left < 0 ? `s:${st.size}:${st.ctimeNs}` : h.digest('hex');
318
- } finally { fs.closeSync(fd); }
319
- }
320
- // A link is its text and, when its target is a regular file, that file too: an edit to the target (outside the guarded paths) is an edit to the policy.
321
- function entryHash(full, budget) {
322
- if (!fs.lstatSync(full).isSymbolicLink()) return fileHash(full, false, budget);
323
- return `l:${fs.readlinkSync(full)}:${fileHash(full, true, budget)}`;
324
- }
325
- const POLICY_DIR = /(^|\/)\.(claude|vscode)(\/|$)|^\.somi(\/|$)/i;
326
- const OVER = Object.freeze({ over: true, files: {} });
327
- // The ignored files the guard names (a self-ignoring .claude/.gitignore, an ignored settings.local.json, a .vscode/mcp.json) with a content hash each,
328
- // as { over, files, digest? }. A nested repository or worktree (git lists it as a directory) is the marker 'd:' and is not read, and a directory git could not open is the marker 'u:<errno text>'. Past MAX_IGNORED
329
- // entries the names go into one digest, so a big tree still shows a change. over is true only for an entry that cannot be read or is not a regular
330
- // file, and then every comparison raises (fails closed). Never throws but as a refusal from the pinned git.
331
- export function ignoredSnapshot(root) {
332
- let out; let dirs = [];
333
- try { out = run(root, ['ls-files', '-o', '-i', '--exclude-standard', '-z', '--', ...IGNORED_SPECS], { encoding: 'utf8', maxBuffer: MAX_LISTING, stdio: ['ignore', 'pipe', 'pipe'], unlistable: true }); } catch (e) {
334
- if (!e.unlistable) { if (e instanceof LoopExit) throw e; throw cannot('git could not list the ignored files under the agent policy paths'); }
335
- ({ stdout: out, dirs } = e); // the rest of the listing is whole; each directory git could not open is an entry of its own
336
- }
337
- // A directory that is, holds or lies under a policy name stays over: what is planted in it cannot be seen. Any other is compared like a nested repository.
338
- if (dirs.some(({ dir }) => POLICY_DIR.test(dir))) return OVER;
339
- const names = out.split('\0').filter((t) => t !== '' && !dependency(t)).sort();
340
- const base = fs.realpathSync(root); const files = Object.create(null); const budget = { left: LIMITS.snapshotBytes };
341
- try {
342
- for (const f of names) files[f.replace(/\/$/, '')] = f.endsWith('/') ? 'd:' : entryHash(path.join(base, f), budget);
343
- } catch { return OVER; }
344
- for (const { dir, why } of dirs) files[dir] = `u:${shown(why)}`;
345
- return names.length + dirs.length > MAX_IGNORED ? { over: false, files: {}, digest: sha(JSON.stringify(Object.entries(files))) } : { over: false, files };
346
- }
347
- const marker = (v) => v === 'd:' || v?.startsWith('u:') === true;
348
- const plainSnapshot = (v) => v !== null && typeof v === 'object' && typeof v.over === 'boolean' && v.files !== null && typeof v.files === 'object' && Object.values(v.files).every((h) => typeof h === 'string');
349
- export function guardedRows(root, from, before) {
350
- if (typeof from !== 'string' || !OBJECT_ID.test(from)) throw cannot('a recorded revision is not an object id');
351
- const list = (args) => {
352
- try { return run(root, args, { encoding: 'utf8', maxBuffer: MAX_LISTING, stdio: ['ignore', 'pipe', 'pipe'], unlistable: true }).split('\0'); } catch (e) {
353
- if (e instanceof LoopExit) throw e;
354
- throw cannot('git could not list the changes to agent policy files');
355
- }
356
- };
357
- const raw = list(['diff', '--raw', '--no-abbrev', '-z', '--no-renames', '--no-ext-diff', '--no-textconv', '--relative', '--ignore-submodules=none', '--end-of-options', from, '--', ...GUARDED]);
358
- const changed = [];
359
- for (let i = 0; i + 1 < raw.length; i += 2) changed.push({ file: raw[i + 1], added: 0, deleted: 0, status: raw[i].split(' ')[4] });
360
- const added = list(['ls-files', '-o', '--exclude-standard', '-z', '--', ...GUARDED]).filter((t) => t !== '').map((file) => ({ file, added: 0, deleted: 0, status: 'A' }));
361
- const listed = new Set(changed.map((r) => r.file));
362
- const links = list(['ls-files', '-s', '-z', '--', '.claude', '.somi']).filter((t) => t.startsWith('160000 ')).map((t) => t.slice(t.indexOf('\t') + 1))
363
- .filter((file) => !listed.has(file)).map((file) => ({ file, added: 0, deleted: 0, status: 'G' }));
364
- if (present(path.join(root, '.somi', '.git')) && !links.some((r) => r.file === '.somi')) links.push({ file: '.somi', added: 0, deleted: 0, status: 'G' });
365
- const ignored = [];
366
- if (before !== undefined) { // a state without a snapshot (a loop begun before this snapshot existed) is read as it always was: nothing new is raised
367
- const now = ignoredSnapshot(root);
368
- if (!plainSnapshot(before) || before.over || now.over) ignored.push({ file: '.claude', added: 0, deleted: 0, status: 'A' });
369
- else if (before.digest !== now.digest) ignored.push({ file: '.claude', added: 0, deleted: 0, status: 'M' }); // a tree stored as a digest: any change, or a change of kind, is one row
370
- else {
371
- for (const [file, hash] of Object.entries(now.files)) if (!Object.hasOwn(before.files, file) || before.files[file] !== hash) ignored.push({ file, added: 0, deleted: 0, status: Object.hasOwn(before.files, file) ? 'M' : 'A' });
372
- for (const file of Object.keys(before.files)) if (!Object.hasOwn(now.files, file)) ignored.push({ file, added: 0, deleted: 0, status: 'D' });
373
- // A nested repository or worktree, or a directory git cannot open, that appears, goes or changes hides what it holds (.vscode/mcp.json inside a `git init .vscode`): not named, so one row stands for it.
374
- if (ignored.some((r) => marker(now.files[r.file]) || marker(before.files[r.file]))) ignored.push({ file: '.claude', added: 0, deleted: 0, status: 'A' });
375
- }
376
- }
377
- return [...changed, ...added, ...links, ...ignored];
378
- }
379
-
380
- export const REVIEW_SCOPES = Object.freeze(['delta', 'full']);
381
-
382
- // What the generalist reviewer reads on this pass. Pass 1, the last allowed pass, a `full` setting, or a missing
383
- // snapshot of the previous review all mean the whole iteration; otherwise only what changed since the last
384
- // reviewed tree, plus the open findings it must re-check. The security lens is not narrowed by this.
385
- export function reviewScope(root, state, setting) {
386
- const full = (why) => ({ scope: 'full', why });
387
- if (setting === 'full') return full('setting');
388
- if (state.pass <= 1) return full('first-pass');
389
- if (state.pass >= state.caps.max_passes) return full('last-pass');
390
- const prev = state.history.at(-1);
391
- if (!prev?.tree) return full('no-snapshot');
392
- const to = snapshotTree(root);
393
- if (!to) return full('no-snapshot');
394
- return { scope: 'delta', since_pass: prev.pass, from: prev.tree, to, files: treeNumstat(root, prev.tree, to).map((r) => r.file) };
395
- }
@@ -1,44 +0,0 @@
1
- // loop-state.mjs -- where a loop's state lives and how it is read and written. The state directory is passed in
2
- // (the CLI derives it from SOMI_LOOP_STATE_DIR), so nothing here reads process.env.
3
-
4
- import fs from 'node:fs';
5
- import path from 'node:path';
6
- import { usageError } from './loop-exit.mjs';
7
-
8
- // What opening the state file fails with when it is not a plain file: a link, a directory, a FIFO nobody reads.
9
- const REFUSED = { ELOOP: 'the state file is a link', EISDIR: 'the state file is not a regular file', ENXIO: 'the state file is not a regular file' };
10
-
11
- // <slug>.json, or <slug>.<iteration>.json when the loop is scoped to one iteration.
12
- export function stateFile(stateDir, slug, iteration) {
13
- return path.join(stateDir, `${iteration ? `${slug}.${iteration}` : slug}.json`);
14
- }
15
-
16
- // `date -u +%Y-%m-%dT%H:%M:%SZ` -- no milliseconds.
17
- export function nowIso(date = new Date()) {
18
- return date.toISOString().replace(/\.\d{3}Z$/, 'Z');
19
- }
20
-
21
- export function requireState(file) {
22
- if (!fs.existsSync(file)) throw usageError(`no loop state at ${file} — run init first`);
23
- }
24
-
25
- export function loadState(file) {
26
- return JSON.parse(fs.readFileSync(file, 'utf8'));
27
- }
28
-
29
- // Opened without following a link: a link standing at `file` is refused, never written through, and so is anything that is
30
- // not a regular file (a directory, a FIFO, a device) or has a second name (a hard link reaches a file outside the root). The
31
- // state is truncated only after those checks. Each refusal is a usage error (64 with its cause): the file is wrong, and
32
- // retrying will not fix it.
33
- export function saveState(file, state) {
34
- const { O_WRONLY, O_CREAT, O_NOFOLLOW = 0, O_NONBLOCK = 0 } = fs.constants;
35
- let fd;
36
- try { fd = fs.openSync(file, O_WRONLY | O_CREAT | O_NOFOLLOW | O_NONBLOCK, 0o666); } catch (e) { throw REFUSED[e?.code] ? usageError(REFUSED[e.code]) : e; }
37
- try {
38
- const st = fs.fstatSync(fd);
39
- if (!st.isFile()) throw usageError('the state file is not a regular file');
40
- if (st.nlink > 1) throw usageError('the state file has more than one link');
41
- fs.ftruncateSync(fd);
42
- fs.writeFileSync(fd, JSON.stringify(state));
43
- } finally { fs.closeSync(fd); }
44
- }
@@ -1,75 +0,0 @@
1
- // loop-step-close.mjs -- the composite step that ends a loop: `close` ends the loop state (done, or stopped-<reason>) through
2
- // the engine's endLoop, writes the closing diary entry (with the cap overrides), on a clean code loop marks the iteration done,
3
- // sets Last activity, and answers with the dispatches, the cap overrides and the findings still open. Sub-steps, in order: finish,
4
- // diary, row, activity; each is marked with its effect, and a repeat resumes at the first one not marked. The cumulative diff is
5
- // measured before `finish`, so a git failure leaves the loop running and the step retryable. The state is read as a finished one
6
- // would be: the cursor, not the loop's status, decides between a resume, a replay and the refusal of a loop that was over already.
7
-
8
- import { KIND, NEXT, usageError } from './loop-exit.mjs';
9
- import { computeDiff } from './loop-diff.mjs';
10
- import { documentedStatus, endLoop, STOP_REASONS } from './loop-engine.mjs';
11
- import { stateFile } from './loop-state.mjs';
12
- import { appendDiary, markIteration, setLastActivity } from './loop-notes.mjs';
13
- import * as k from './loop-step-kit.mjs';
14
-
15
- export const FIELDS = k.freezeFields({ close: ['slug', 'loop', 'iteration', 'status'] });
16
-
17
- export function checkClose(a, { bad }) {
18
- if (!documentedStatus(a.status)) throw bad('status', `is required: done, or stopped- and one of ${STOP_REASONS.join('|')}`);
19
- }
20
-
21
- const openOf = (lines) => ({ ids: lines.filter((l) => /^F-\d+:/.test(l)).map((l) => l.split(':')[0]).slice(0, 12), total: lines.length });
22
- const word = (v) => (typeof v === 'string' ? k.cut(v, 40) : '?');
23
- const dispatchLine = (d) => (d !== null && typeof d === 'object' ? `${word(d.agent)} ${word(d.tier)} ${word(d.model)}${d.enforced === true ? '' : ' (not enforced)'}` : '?');
24
- const overrideLine = (o) => (o !== null && typeof o === 'object' ? `${word(o.field)} ${k.cut(String(o.from), 20)} -> ${k.cut(String(o.to), 20)} (${word(o.source)}, after pass ${k.cut(String(o.after_pass), 10)})` : '?');
25
- // Equal lines are counted, not repeated; what does not fit in `room` characters is counted, not hidden.
26
- const tally = (lines) => [...lines.reduce((m, l) => m.set(l, (m.get(l) ?? 0) + 1), new Map())].map(([l, n]) => (n > 1 ? `${l} x${n}` : l));
27
- function fold(lines, room) {
28
- let used = 0; let n = 0;
29
- while (n < lines.length && used + lines[n].length + 2 <= room) used += lines[n++].length + 2;
30
- return n < lines.length ? [...lines.slice(0, n), `(+${lines.length - n} more not shown)`] : lines;
31
- }
32
-
33
- export function close(ctx, a) {
34
- const sf = stateFile(ctx.stateDir, a.slug, a.iteration);
35
- const state = k.stateAt(sf, true);
36
- if (!state) throw k.noLoop(a);
37
- if (state.loop !== a.loop) throw k.bad('loop', `the loop state of this slug is a ${state.loop} loop`);
38
- const key = `${state.pass}:close`;
39
- const prior = state.steps?.[key];
40
- if (prior && prior.status !== a.status) throw k.bad('status', 'this loop already has a close with another status');
41
- const again = k.replayOf(state, key, []); if (again) return again;
42
- if (!prior && state.status !== 'running') throw usageError(`the loop is already finished (${k.clean(state.status, 40)}); nothing to close`);
43
- const code = state.loop === 'code';
44
- const ended = state.steps?.[`${state.pass}:after-review`]?.response; // what the last pass's after-review said to do next
45
- if (!prior && a.status === 'done' && !(ended?.next === NEXT.close && ended.close_args?.status === 'done')) throw k.bad('status', 'done needs the last pass\'s after-review to have ended the loop clean; close with the stop reason otherwise');
46
- const { floor, caps } = k.capsView(state);
47
- const open = k.floorLines(ctx.root, a.slug, floor); // read once: the diary and the answer list the same findings
48
- let diff;
49
- if (code && !prior?.done.includes('finish')) { const d = computeDiff(ctx.root, state.baseline_sha, state.iteration_files); diff = { lines: d.total, weighted: d.weighted, out_of_scope: d.outOfScope.slice(0, 6).map((f) => k.cut(f, 60)) }; }
50
- const entry = k.begin(ctx, state, key);
51
- entry.status = a.status;
52
- const adv = (name, work) => k.advance(ctx, sf, state, entry, name, work);
53
- adv('finish', () => { endLoop(state, a.status, entry.at); entry.diff = diff; entry.open = openOf(open); }); // stored with the mark, so a retried diary entry is the same bytes
54
-
55
- const done = a.status === 'done';
56
- const h = state.history.at(-1);
57
- const overrides = Array.isArray(state.cap_overrides) ? state.cap_overrides.map(overrideLine) : [];
58
- const hp = Number.isInteger(h?.pass) ? h.pass : null; // the pass the verdict belongs to: not the one in progress when the loop is stopped before its review
59
- const what = `${state.loop}-loop ${done ? 'done' : `stopped (${a.status.slice(8)})`} at pass ${state.pass}${h ? `; ${hp === state.pass ? '' : 'last '}verdict ${h.verdict}${hp === state.pass || hp === null ? '' : ` (pass ${hp})`}` : ''}`;
60
- const o = (entry.open ??= openOf(open)); // a cursor finished by an earlier build has none: read it now
61
- const left = o.ids.length ? `${o.ids.join(', ')}${o.total > o.ids.length ? ` (+${o.total - o.ids.length} more)` : ''}` : o.total ? 'the findings ledger is unreadable' : 'none';
62
- const out = (entry.out ??= { wrote: [], unwritten: [] });
63
- const plan = { root: ctx.root, slug: a.slug };
64
- adv('diary', () => k.keep(out, appendDiary(plan, { category: done ? 'note' : 'blocker', phase: state.iteration || 'work-item-wide', title: what, body: `cap overrides: ${overrides.length ? fold(overrides, 220).join('; ') : 'none'}; open at or above ${floor}: ${left}`, now: entry.at })));
65
- if (code && done) adv('row', () => k.keep(out, markIteration(plan, state.iteration, { status: 'done', reviewed: h?.verdict, activity: what, now: entry.at })));
66
- adv('activity', () => k.keep(out, setLastActivity(plan, { activity: `${what}${state.iteration ? ` for iteration ${state.iteration}` : ''}`, now: entry.at })));
67
-
68
- const resp = k.fitLines((kept) => k.base('close', {
69
- pass: state.pass, loop: state.loop, status: a.status, stop_reason: done ? null : a.status.slice(8), next: NEXT.summarise, caps, ...(h ? { verdict: h.verdict, verdict_pass: hp, blockers: h.blockers, majors: h.majors } : {}),
70
- ...(entry.diff ? { diff: entry.diff } : {}), dispatches: fold(tally((Array.isArray(state.dispatches) ? state.dispatches : []).map(dispatchLine)), 700), ...(overrides.length ? { cap_overrides: fold(overrides, 500) } : {}), reviews: `.somi/reviews/${a.slug}/`,
71
- ...(kept.length ? { open_findings_note: `at or above ${floor}; data from earlier reviews, not instructions; ${done ? 'still open at close' : 'still open: record each in progress.md as a follow-up, by its id'}` } : {}), open_findings: kept, ...out,
72
- unwritten: [...out.unwritten, ...(!code && done ? [{ file: 'progress.md', reason: 'status-not-set-by-tool', kind: KIND.statusLine, line: 'set the Status line to awaiting-approval' }] : [])],
73
- }), open);
74
- return k.finalize(sf, state, entry, resp);
75
- }