@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,118 +0,0 @@
1
- #!/usr/bin/env node
2
- // In-process tests of scripts/lib/findings-ledger.mjs: locus identity, the consecutive-pass breaker, the
3
- // no-write guarantee on bad input and on an empty batch, the resolve/reopen/open/get lifecycle, and that the
4
- // library never reads the process environment.
5
- // Invoked from tests/scripts/loop-engine.sh. The CLI's bytes are pinned by tests/scripts/run.sh and its goldens.
6
-
7
- import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
8
- import { tmpdir } from 'node:os';
9
- import path from 'node:path';
10
- import { fileURLToPath } from 'node:url';
11
- import { isDeepStrictEqual } from 'node:util';
12
- import { getFinding, ledgerPaths, normalizeTitle, openFindings, recordFindings, reopenFinding, resolveFinding } from '../../../scripts/lib/findings-ledger.mjs';
13
-
14
- const LIB = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', '..', '..', 'scripts', 'lib');
15
- let pass = 0; let fail = 0;
16
- // Strict deep equality: undefined, null and a missing key are three different answers.
17
- const check = (name, got, want) => {
18
- if (isDeepStrictEqual(got, want)) { pass++; console.log(` ok ${name}`); } else { fail++; console.log(` FAIL ${name} (want ${JSON.stringify(want)}, got ${JSON.stringify(got)})`); }
19
- };
20
-
21
- const root = mkdtempSync(path.join(tmpdir(), 'findings-ledger-'));
22
- const decoy = mkdtempSync(path.join(tmpdir(), 'findings-decoy-'));
23
- const now = () => '2026-01-01';
24
- const rec = (slug, input, extra = {}) => recordFindings({ root, slug, review: 'r.md', run: 'R1', pass: 1, input, now, ...extra });
25
- const ledgerOf = (slug) => JSON.parse(readFileSync(ledgerPaths(root, slug).file, 'utf8'));
26
- const F = { file: 'src/a.txt', symbol: 'HandleWebhook', title: 'Missing rate limit on retry path', severity: 'Major', confidence: 'High' };
27
-
28
- console.log('== findings ledger: the environment is not an input ==');
29
- const envBefore = JSON.stringify(process.env);
30
- process.env.CLAUDE_PROJECT_DIR = decoy;
31
- process.env.SOMI_LOOP_STATE_DIR = decoy;
32
- const sentinel = rec('sentinel', [F]);
33
- check('a CLAUDE_PROJECT_DIR in process.env does not redirect the ledger away from the root it was given', [sentinel.code, existsSync(ledgerPaths(root, 'sentinel').file), existsSync(path.join(decoy, '.somi'))], [0, true, false]);
34
- delete process.env.CLAUDE_PROJECT_DIR;
35
- delete process.env.SOMI_LOOP_STATE_DIR;
36
- const source = readFileSync(path.join(LIB, 'findings-ledger.mjs'), 'utf8');
37
- const code = source.split('\n').filter((l) => !l.trimStart().startsWith('//')).join('\n');
38
- // Any use of `process` or `globalThis` in code (comments excluded) is a way to the environment: `process.env`,
39
- // `process['env']`, `const { env } = process`, `globalThis.process.env`. The library needs none of them.
40
- check('findings-ledger.mjs names neither process nor globalThis outside comments', /\b(process|globalThis)\b/.test(code), false);
41
-
42
- console.log('== findings ledger: normalizeTitle ==');
43
- const titles = [['', ''], ['Bug', 'bug'], ['one two three four five six seven eight nine ten', 'one two three four five six seven eight'], [' Missing rate limit ', 'missing rate limit'], ['Missing rate limit', 'missing rate limit'], ['Missing rate-limit! (on retry) path?', 'missing rate limit on retry path']];
44
- for (const [t, want] of titles) check(`normalizeTitle(${JSON.stringify(t)})`, normalizeTitle(t), want);
45
- check('İstanbul lowercases byte-wise (ASCII only): the dotted capital is dropped, not turned into an "i"', normalizeTitle('İstanbul'), 'stanbul');
46
- check('café loses its accented letter instead of keeping it', normalizeTitle('café'), 'caf');
47
-
48
- console.log('== findings ledger: locus identity ==');
49
- const first = rec('id', [F]);
50
- check('a first sighting is new F-1 and prints one JSON line', first, { lines: [JSON.stringify({ id: 'F-1', state: 'new', recurring_consecutive: false, recurring_cross_run: false })], code: 0, message: '' });
51
- check('the stored finding has the documented shape', ledgerOf('id'), { next_id: 2, findings: [{ id: 'F-1', key: 'src/a.txt|handlewebhook|missing rate limit on retry path', locus: { file: 'src/a.txt', symbol: 'HandleWebhook' }, title: F.title, severity: 'Major', confidence: 'High', status: 'open', introduced_by: 'r.md', resolved_by: null, seen: [{ review: 'r.md', run: 'R1', pass: 1, date: '2026-01-01' }] }] });
52
- const variant = rec('id', [{ file: 'src/a.txt', symbol: 'handlewebhook', title: 'MISSING rate-limit on retry path!' }], { pass: 3 });
53
- check('the same locus in another case and punctuation is the same finding (known, not new)', JSON.parse(variant.lines[0]).id + JSON.parse(variant.lines[0]).state, 'F-1known');
54
- const other = rec('id', [{ file: 'src/b.txt', title: 'Other' }]);
55
- check('a different file is a new finding with the next id and the defaults', [JSON.parse(other.lines[0]).id, ledgerOf('id').findings[1].severity, ledgerOf('id').findings[1].confidence, ledgerOf('id').findings[1].locus.symbol], ['F-2', 'Minor', 'Medium', '']);
56
-
57
- console.log('== findings ledger: the consecutive-pass breaker ==');
58
- const p1 = rec('brk', [F], { pass: 1 });
59
- const p2 = rec('brk', [F], { pass: 2 });
60
- check('pass 1 then pass 2 of the same run is a consecutive recurrence: code 5', [p1.code, p2.code, JSON.parse(p2.lines[0]).recurring_consecutive, JSON.parse(p2.lines[0]).recurring_cross_run], [0, 5, true, false]);
61
- const g1 = rec('gap', [F], { pass: 1 });
62
- const g3 = rec('gap', [F], { pass: 3 });
63
- check('pass 1 then pass 3 is not consecutive and not cross-run: code 0', [g1.code, g3.code, JSON.parse(g3.lines[0]).recurring_consecutive, JSON.parse(g3.lines[0]).recurring_cross_run], [0, 0, false, false]);
64
- const x2 = rec('gap', [F], { run: 'R2', pass: 4 });
65
- check('another run seeing an open finding is cross-run, not consecutive: code 0', [x2.code, JSON.parse(x2.lines[0]).recurring_consecutive, JSON.parse(x2.lines[0]).recurring_cross_run], [0, false, true]);
66
- const batch = rec('batch', [F, { file: 'src/c.txt', title: 'Fresh' }], { pass: 1 });
67
- const batch2 = rec('batch', [{ file: 'src/c.txt', title: 'Fresh' }, F], { pass: 2 });
68
- check('the breaker is judged after every finding is processed: every line comes back, in input order, then code 5', [batch.code, batch2.lines.map((l) => JSON.parse(l).id), batch2.code], [0, ['F-2', 'F-1'], 5]);
69
- const empty = rec('empty', []);
70
- check('an empty batch prints nothing and exits 0', empty, { lines: [], code: 0, message: '' });
71
-
72
- console.log('== findings ledger: bad input writes nothing ==');
73
- const missing = rec('bad1', [{ file: 'src/a.txt' }]);
74
- check('a finding with no title returns 64 and the exact stderr line, with no stdout', missing, { lines: [], code: 64, message: 'somi-findings: finding 0 needs at least {file, title}' });
75
- check('and the ledger was not even created', existsSync(ledgerPaths(root, 'bad1').dir), false);
76
- const later = rec('bad2', [F, { title: 'no file' }]);
77
- check('a bad element after a good one is named by index and the good one is not recorded either', [later.code, later.message, existsSync(ledgerPaths(root, 'bad2').file)], [64, 'somi-findings: finding 1 needs at least {file, title}', false]);
78
- check('a null element is malformed, not a crash', rec('bad3', [null]).code, 64);
79
- const before = readFileSync(ledgerPaths(root, 'id').file, 'utf8');
80
- rec('id', [F, { file: 'x' }]);
81
- check('a refused batch leaves an existing ledger byte for byte as it was', readFileSync(ledgerPaths(root, 'id').file, 'utf8'), before);
82
-
83
- console.log('== findings ledger: an empty batch leaves the ledger as it is ==');
84
- const seed = '{"next_id": 1, "findings": []}\n';
85
- check('record [] on a fresh slug leaves the seed literal, not the pretty form', readFileSync(ledgerPaths(root, 'empty').file, 'utf8'), seed);
86
- const handMade = ledgerPaths(root, 'hand');
87
- mkdirSync(handMade.dir, { recursive: true });
88
- const handBytes = '{"next_id":7,"findings":[]}';
89
- writeFileSync(handMade.file, handBytes);
90
- rec('hand', []);
91
- check('record [] on an existing ledger does not rewrite it', readFileSync(handMade.file, 'utf8'), handBytes);
92
-
93
- console.log('== findings ledger: resolve, reopen, open, get ==');
94
- const life = { root, slug: 'life' };
95
- rec('life', [F, { file: 'src/b.txt', symbol: 'S', title: 'Second' }]);
96
- check('resolve prints id, status and resolved_by', resolveFinding({ ...life, id: 'F-1', status: 'fixed', by: 'r2.md' }), { lines: [JSON.stringify({ id: 'F-1', status: 'fixed', resolved_by: 'r2.md' })], code: 0, message: '' });
97
- check('and the ledger holds the new state', [ledgerOf('life').findings[0].status, ledgerOf('life').findings[0].resolved_by], ['fixed', 'r2.md']);
98
- check('open lists only the open findings, with exactly these fields in this order', openFindings(life), { lines: [JSON.stringify([{ id: 'F-2', locus: { file: 'src/b.txt', symbol: 'S' }, title: 'Second', severity: 'Minor', confidence: 'Medium', introduced_by: 'r.md' }], null, 2)], code: 0, message: '' });
99
- check('the open finding keys come out in the documented order', Object.keys(JSON.parse(openFindings(life).lines[0])[0]), ['id', 'locus', 'title', 'severity', 'confidence', 'introduced_by']);
100
- check('get prints the whole stored finding, pretty', getFinding({ ...life, id: 'F-1' }), { lines: [JSON.stringify(ledgerOf('life').findings[0], null, 2)], code: 0, message: '' });
101
- check('reopen prints id and status', reopenFinding({ ...life, id: 'F-1', by: 'r3.md' }), { lines: [JSON.stringify({ id: 'F-1', status: 'open' })], code: 0, message: '' });
102
- check('and clears resolved_by and records reopened_by', [ledgerOf('life').findings[0].status, ledgerOf('life').findings[0].resolved_by, ledgerOf('life').findings[0].reopened_by], ['open', null, 'r3.md']);
103
- const lifeBytes = readFileSync(ledgerPaths(root, 'life').file, 'utf8');
104
- check('resolve of an unknown id prints nothing, exits 0 and writes nothing', [resolveFinding({ ...life, id: 'F-99', status: 'fixed', by: 'x' }), readFileSync(ledgerPaths(root, 'life').file, 'utf8')], [{ lines: [], code: 0, message: '' }, lifeBytes]);
105
- check('reopen of an unknown id prints nothing and exits 0', reopenFinding({ ...life, id: 'F-99', by: 'x' }), { lines: [], code: 0, message: '' });
106
- check('get of an unknown id prints nothing and exits 0', getFinding({ ...life, id: 'F-99' }), { lines: [], code: 0, message: '' });
107
- check('resolve without an id or a status is refused with 64', [resolveFinding({ ...life, status: 'fixed' }), resolveFinding({ ...life, id: 'F-1' })], [{ lines: [], code: 64, message: 'somi-findings: resolve requires --id and --status' }, { lines: [], code: 64, message: 'somi-findings: resolve requires --id and --status' }]);
108
- check('resolve with an unknown status is refused with 64 and writes nothing', [resolveFinding({ ...life, id: 'F-1', status: 'closed', by: 'x' }), readFileSync(ledgerPaths(root, 'life').file, 'utf8')], [{ lines: [], code: 64, message: 'somi-findings: --status must be fixed|accepted|wontfix' }, lifeBytes]);
109
- check('reopen and get without an id are refused with 64', [reopenFinding({ ...life }).message, getFinding({ ...life }).message], ['somi-findings: reopen requires --id', 'somi-findings: get requires --id']);
110
- check('open on a slug with no ledger seeds it and prints an empty array', [openFindings({ root, slug: 'fresh' }), readFileSync(ledgerPaths(root, 'fresh').file, 'utf8')], [{ lines: ['[]'], code: 0, message: '' }, seed]);
111
- check('a refused lifecycle call still seeds the ledger, as the bash original did', [getFinding({ root, slug: 'refused' }).code, readFileSync(ledgerPaths(root, 'refused').file, 'utf8')], [64, seed]);
112
-
113
- check('none of the calls touched process.env', JSON.stringify(process.env), envBefore);
114
-
115
- rmSync(root, { recursive: true, force: true });
116
- rmSync(decoy, { recursive: true, force: true });
117
- console.log(`findings ledger tests: ${pass} ok, ${fail} failed`);
118
- process.exit(fail === 0 ? 0 : 1);
@@ -1,287 +0,0 @@
1
- #!/usr/bin/env node
2
- // In-process tests of the loop engine libraries: scripts/lib/loop-caps.mjs, loop-exit.mjs, loop-state.mjs and
3
- // loop-engine.mjs (the lifecycle, measuring and recording handlers).
4
- // Invoked from tests/scripts/loop-engine.sh.
5
-
6
- import { chmodSync, existsSync, linkSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, symlinkSync, utimesSync, writeFileSync } from 'node:fs';
7
- import { execFileSync } from 'node:child_process';
8
- import { tmpdir } from 'node:os';
9
- import path from 'node:path';
10
- import { fileURLToPath } from 'node:url';
11
- import { isDeepStrictEqual } from 'node:util';
12
- import { applyCapOverride, configVal, firstDefined, resolveInitCap, reresolveCap, validateCap } from '../../../scripts/lib/loop-caps.mjs';
13
- import { checkDiff, finish, init, pass as passPass, recordDispatch, recordPass, resume, reviewScope, runStart } from '../../../scripts/lib/loop-engine.mjs';
14
- import { stateFile } from '../../../scripts/lib/loop-state.mjs';
15
- import { measuredTree, treeNumstat } from '../../../scripts/lib/loop-review.mjs';
16
- import { computeDiff } from '../../../scripts/lib/loop-diff.mjs';
17
- import { LoopExit, ok, refuse, usageError } from '../../../scripts/lib/loop-exit.mjs';
18
-
19
- const LIB = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', '..', '..', 'scripts', 'lib');
20
- let pass = 0; let fail = 0;
21
- // Strict deep equality: undefined, null and a missing key are three different answers (a refusal's `out` must be absent).
22
- const check = (name, got, want) => {
23
- if (isDeepStrictEqual(got, want)) { pass++; console.log(` ok ${name}`); } else { fail++; console.log(` FAIL ${name} (want ${JSON.stringify(want)}, got ${JSON.stringify(got)})`); }
24
- };
25
- // What a call that should exit looks like: [class, code, message], or the string 'no throw'.
26
- const exitOf = (fn) => {
27
- try { fn(); } catch (e) { return [e instanceof LoopExit, e.code, e.message]; }
28
- return 'no throw';
29
- };
30
-
31
- console.log('== loop caps: the environment is a parameter ==');
32
- process.env.SOMI_CODE_LOOP_MAX_PASSES = '9';
33
- process.env.SOMI_CODE_LOOP_DIFF_CAP = '999';
34
- check('resolveInitCap({}) ignores process.env and gives the default 3', resolveInitCap({}, {}, 'code', 'max_passes', ''), 3);
35
- check('resolveInitCap({}) ignores process.env for the diff cap too (default 400)', resolveInitCap({}, {}, 'code', 'diff_cap_lines', ''), 400);
36
- check('the env it is handed is what counts', resolveInitCap({ SOMI_CODE_LOOP_MAX_PASSES: '5' }, {}, 'code', 'max_passes', ''), 5);
37
- check('reresolveCap({}) ignores process.env: no override, the stored cap stands', reresolveCap({}, { loop: 'code', pass: 1, caps: { max_passes: 2 } }, 'max_passes', '', 'T'), { resolved: 2, override: null });
38
- delete process.env.SOMI_CODE_LOOP_MAX_PASSES;
39
- delete process.env.SOMI_CODE_LOOP_DIFF_CAP;
40
- const sources = ['loop-caps.mjs', 'loop-exit.mjs', 'loop-state.mjs', 'loop-engine.mjs'].map((f) => [f, readFileSync(path.join(LIB, f), 'utf8')]);
41
- for (const [f, src] of sources) {
42
- const code = src.split('\n').filter((l) => !l.trimStart().startsWith('//')).join('\n');
43
- check(`${f} has no process.env outside comments`, /process\s*(\.|\[)\s*['"]?env/.test(code), false);
44
- }
45
-
46
- console.log('== loop caps: precedence ==');
47
- const cfg = { code_loop: { max_passes: 7 }, plan_loop: { max_passes: 6 } };
48
- check('flag beats env, config and default', resolveInitCap({ SOMI_CODE_LOOP_MAX_PASSES: '5' }, cfg, 'code', 'max_passes', '2'), 2);
49
- check('env beats config', resolveInitCap({ SOMI_CODE_LOOP_MAX_PASSES: '5' }, cfg, 'code', 'max_passes', ''), 5);
50
- check('config beats the default', resolveInitCap({}, cfg, 'code', 'max_passes', ''), 7);
51
- check('a plan loop reads its own env var and config section', [resolveInitCap({ SOMI_PLAN_LOOP_MAX_PASSES: '4' }, cfg, 'plan', 'max_passes', ''), resolveInitCap({}, cfg, 'plan', 'max_passes', '')], [4, 6]);
52
- check('a plan loop has no diff cap, whatever is set', resolveInitCap({ SOMI_CODE_LOOP_DIFF_CAP: '50' }, {}, 'plan', 'diff_cap_lines', '80'), 0);
53
- check('a numeric 0 counts as set (the gate off is explicit)', resolveInitCap({}, {}, 'code', 'diff_cap_lines', '0'), 0);
54
- check('configVal walks keys and reads null as unset', [configVal(cfg, ['code_loop', 'max_passes']), configVal({ a: null }, ['a']), configVal({}, ['a', 'b'])], [7, undefined, undefined]);
55
- check('firstDefined skips undefined, null and the empty string', firstDefined(undefined, null, '', 0, 3), 0);
56
-
57
- console.log('== loop caps: malformed values are refused, not coerced ==');
58
- for (const raw of ['1,000', 'unlimited', '-1', '1.5']) {
59
- check(`validateCap(${JSON.stringify(raw)}) exits 64 with the label and the value`, exitOf(() => validateCap(raw, 'max_passes')), [true, 64, `somi-loop: max_passes: expected a non-negative integer, got "${raw}"`]);
60
- }
61
- check('validateCap accepts 0 and a plain integer', [validateCap('0', 'x'), validateCap(12, 'x')], [0, 12]);
62
- check('a malformed env cap at init exits 64 naming the field', exitOf(() => resolveInitCap({ SOMI_CODE_LOOP_MAX_PASSES: 'unlimited' }, {}, 'code', 'max_passes', '')), [true, 64, 'somi-loop: max_passes: expected a non-negative integer, got "unlimited"']);
63
- const st = (extra = {}) => ({ loop: 'code', pass: 2, caps: { max_passes: 3, diff_cap_lines: 400 }, ...extra });
64
- check('a malformed flag on re-resolution names the flag', exitOf(() => reresolveCap({}, st(), 'max_passes', '1,000', 'T')), [true, 64, 'somi-loop: --max-passes: expected a non-negative integer, got "1,000"']);
65
- check('a malformed env var on re-resolution names the variable', exitOf(() => reresolveCap({ SOMI_CODE_LOOP_DIFF_CAP: 'none' }, st(), 'diff_cap_lines', '', 'T')), [true, 64, 'somi-loop: SOMI_CODE_LOOP_DIFF_CAP: expected a non-negative integer, got "none"']);
66
-
67
- console.log('== loop caps: re-resolution and the override entry ==');
68
- const flagged = reresolveCap({ SOMI_CODE_LOOP_MAX_PASSES: '8' }, st(), 'max_passes', '5', '2026-01-01T00:00:00Z');
69
- check('a flag beats the env var and records source cli with the caller-supplied time', flagged, { resolved: 5, override: { field: 'max_passes', from: 3, to: 5, source: 'cli', after_pass: 2, at: '2026-01-01T00:00:00Z' } });
70
- check('an env var alone records source env', reresolveCap({ SOMI_CODE_LOOP_DIFF_CAP: '100' }, st(), 'diff_cap_lines', '', 'T').override.source, 'env');
71
- check('an explicit value equal to the stored one is no override', reresolveCap({ SOMI_CODE_LOOP_MAX_PASSES: '3' }, st(), 'max_passes', '', 'T'), { resolved: 3, override: null });
72
- check('a plan loop has no diff cap to re-resolve', reresolveCap({ SOMI_CODE_LOOP_DIFF_CAP: '100' }, st({ loop: 'plan' }), 'diff_cap_lines', '100', 'T'), { resolved: 0, override: null });
73
- const live = st();
74
- applyCapOverride(live, flagged.override);
75
- applyCapOverride(live, { ...flagged.override, from: 5, to: 6 });
76
- check('applyCapOverride sets the cap and appends to a lazily created trail', [live.caps.max_passes, live.cap_overrides.length, live.cap_overrides[0].to], [6, 2, 5]);
77
- check('a state never overridden keeps its shape (no cap_overrides key)', 'cap_overrides' in st(), false);
78
-
79
- console.log('== loop exit model ==');
80
- const e = usageError('bad');
81
- check('usageError is a LoopExit 64 with the program prefix', [e instanceof LoopExit, e instanceof Error, e.code, e.message], [true, true, 64, 'somi-loop: bad']);
82
- check('ok carries the output and no message', ok({ a: 1 }), { out: { a: 1 }, code: 0, message: '' });
83
- check('refuse carries no stdout by default', refuse(2, 'max-passes-exceeded'), { out: undefined, code: 2, message: 'max-passes-exceeded' });
84
- check('refuse can carry stdout printed before the failure', refuse(3, 'over', { cap: 1 }), { out: { cap: 1 }, code: 3, message: 'over' });
85
-
86
- console.log('== loop lifecycle: handlers return results, the environment is a parameter ==');
87
- const root = mkdtempSync(path.join(tmpdir(), 'loop-engine-'));
88
- const git = (...a) => execFileSync('git', ['-C', root, '-c', 'user.name=t', '-c', 'user.email=t@t', ...a], { encoding: 'utf8' }).trim();
89
- git('init', '-q'); git('commit', '-q', '--allow-empty', '-m', 'base');
90
- const stateDir = path.join(root, '.somi', 'somi-state', 'loop');
91
- // SOMI_GLOBAL_CONFIG='' switches the developer's global config off, so no handler here reads outside the temp root.
92
- const ctxFor = (env = {}) => ({ root, env: { SOMI_GLOBAL_CONFIG: '', ...env }, stateDir, now: () => '2026-01-01T00:00:00Z' });
93
- const base = { slug: 's', loop: 'code', iteration: '', files: 'a.js b.js', force: false, status: '', maxPasses: '', diffCap: '', severity: '', maxMinutes: '' };
94
- const envBefore = JSON.stringify(process.env);
95
- process.env.SOMI_CODE_LOOP_MAX_PASSES = '9';
96
- process.env.SOMI_CODE_LOOP_SEVERITY_FLOOR = 'Blocker';
97
- const globalDir = mkdtempSync(path.join(tmpdir(), 'loop-global-')); // outside root, or it counts as untracked diff
98
- const globalCfg = path.join(globalDir, 'config.json'); // a global config the process env points at; the handler's env must not follow it
99
- writeFileSync(globalCfg, JSON.stringify({ code_loop: { max_passes: 7 } }));
100
- const globalBefore = process.env.SOMI_GLOBAL_CONFIG;
101
- process.env.SOMI_GLOBAL_CONFIG = globalCfg;
102
- const sentinel = init(ctxFor(), { ...base, slug: 'sentinel' });
103
- check('an in-process init ignores sentinels planted in process.env (caps, severity floor, global config)', [sentinel.code, sentinel.out.caps.max_passes, sentinel.out.caps.severity_floor], [0, 3, 'Major']);
104
- delete process.env.SOMI_CODE_LOOP_MAX_PASSES;
105
- delete process.env.SOMI_CODE_LOOP_SEVERITY_FLOOR;
106
- if (globalBefore === undefined) delete process.env.SOMI_GLOBAL_CONFIG; else process.env.SOMI_GLOBAL_CONFIG = globalBefore;
107
- check('a handler given a global-config path in its env does read it (the sentinel file is live)', init(ctxFor({ SOMI_GLOBAL_CONFIG: globalCfg }), { ...base, slug: 'g' }).out.caps.max_passes, 7);
108
- const started = init(ctxFor({ SOMI_CODE_LOOP_MAX_PASSES: '2' }), base);
109
- check('init succeeds with the golden output keys and the env-given cap', [started.code, started.message, Object.keys(started.out), started.out.caps], [0, '', ['baseline_sha', 'caps', 'state_file'], { max_passes: 2, diff_cap_lines: 400, severity_floor: 'Major' }]);
110
- const sf = stateFile(stateDir, 's', '');
111
- check('the state file holds the golden state shape, in order', Object.keys(JSON.parse(readFileSync(sf, 'utf8'))), ['slug', 'loop', 'iteration', 'baseline_sha', 'started', 'status', 'caps', 'iteration_files', 'pass', 'history', 'ignored_guarded']);
112
- check('the init snapshot of the ignored files under the policy paths is empty and within its caps in a clean repository', JSON.parse(readFileSync(sf, 'utf8')).ignored_guarded, { over: false, files: {} });
113
- const again = init(ctxFor(), base);
114
- check('init over a running state is refused (64) with no stdout', [again.code, again.out, again.message], [64, undefined, `somi-loop: loop state already running at ${sf} — use 'resume' to continue it, or 'init --force' to discard`]);
115
- passPass(ctxFor(), base);
116
- const forced = init(ctxFor({ SOMI_CODE_LOOP_MAX_PASSES: '2' }), { ...base, force: true });
117
- check('init --force discards a running state: success, and the pass counter is back to 0', [forced.code, JSON.parse(readFileSync(sf, 'utf8')).pass], [0, 0]);
118
- mkdirSync(path.join(root, '.somi', 'plans', 'bo'), { recursive: true });
119
- const briefOnly = init(ctxFor(), { ...base, slug: 'bo' });
120
- check('a brief-only work item without a tier approval is refused (64) with no stdout', [briefOnly.code, briefOnly.out, briefOnly.message.startsWith('somi-loop: brief-only work item refused: ')], [64, undefined, true]);
121
- check('pass 1 and 2 of a cap-2 loop succeed', [passPass(ctxFor({ SOMI_CODE_LOOP_MAX_PASSES: '2' }), base).out, passPass(ctxFor({ SOMI_CODE_LOOP_MAX_PASSES: '2' }), base).out], [{ pass: 1, max_passes: 2 }, { pass: 2, max_passes: 2 }]);
122
- const third = passPass(ctxFor(), base);
123
- check('pass 3 of a cap-2 loop comes back as code 2 with no stdout', [third.code, third.out, third.message], [2, undefined, 'max-passes-exceeded: pass 3 > cap 2']);
124
- mkdirSync(path.join(root, '.somi', 'somi-state', 'run'), { recursive: true });
125
- writeFileSync(path.join(root, '.somi', 'somi-state', 'run', 's.json'), JSON.stringify({ started: '2000-01-01T00:00:00Z', max_minutes: 5 }));
126
- const late = passPass(ctxFor({ SOMI_CODE_LOOP_MAX_PASSES: '9' }), base);
127
- check('pass over the run budget comes back as code 4 with no stdout', [late.code, late.out, late.message.startsWith('time-budget-exceeded: ')], [4, undefined, true]);
128
- const planLoop = init(ctxFor(), { ...base, slug: 'p', loop: 'plan' });
129
- check('a plan loop has no diff cap and no review_min', [planLoop.out.caps.diff_cap_lines, 'review_min' in planLoop.out], [0, false]);
130
- const done = finish(ctxFor(), { ...base, status: 'approved' });
131
- check('finish records the status, the cap raise from the env var, and the injected clock', [done.out, JSON.parse(readFileSync(sf, 'utf8')).finished], [{ status: 'approved', pass: 2, history: 0, cap_overrides: [{ field: 'max_passes', from: 2, to: 9, source: 'env', after_pass: 2, at: '2026-01-01T00:00:00Z' }] }, '2026-01-01T00:00:00Z']);
132
- check('finish without --status is a usage error (64)', finish(ctxFor(), base).code, 64);
133
- check('resume reads a missing state as 64', resume(ctxFor(), { ...base, slug: 'none' }).code, 64);
134
- check('none of the lifecycle calls touched process.env', JSON.stringify(process.env), envBefore);
135
-
136
- console.log('== loop measure and record: results carry their stdout and their code ==');
137
- const mCtx = (env = {}) => ({ ...ctxFor(env), installRoot: path.join(LIB, '..', '..') });
138
- const m = { ...base, slug: 'm', files: 'a.js', diffCap: '4' };
139
- init(mCtx(), m);
140
- writeFileSync(path.join(root, 'a.js'), '1\n2\n3\n');
141
- writeFileSync(path.join(root, 'c.js'), '1\n2\n');
142
- const over = checkDiff(mCtx(), m);
143
- check('check-diff over the weighted cap returns code 3 with its JSON and the stderr line', [over.code, over.out, over.message], [3, { diff_lines: 5, weighted_lines: 7, cap: 4, out_of_scope: ['c.js'] }, 'diff-cap-exceeded: weighted 7 > cap 4 (out-of-scope counts double)']);
144
- const raised = checkDiff(mCtx({ SOMI_CODE_LOOP_DIFF_CAP: '100' }), { ...m, diffCap: '' });
145
- check('check-diff under a raised cap is code 0 with the same measurement', [raised.code, raised.out.weighted_lines, raised.out.cap], [0, 7, 100]);
146
- const firstScope = reviewScope(mCtx(), m);
147
- check('review-scope on pass 0 is the whole iteration', [firstScope.code, firstScope.out], [0, { scope: 'full', why: 'first-pass' }]);
148
- check('review-scope honours the env setting and refuses a bad one (64)', [reviewScope(mCtx({ SOMI_CODE_LOOP_REVIEW_SCOPE: 'full' }), m).out.why, reviewScope(mCtx({ SOMI_CODE_LOOP_REVIEW_SCOPE: 'x' }), m).code], ['setting', 64]);
149
- passPass(mCtx({ SOMI_CODE_LOOP_MAX_PASSES: '5' }), m);
150
- const rec = recordPass(mCtx(), { ...m, verdict: 'needs-changes', blockers: '1', majors: '2' });
151
- check('record-pass returns the history entry with the diff size and the reviewed tree', [rec.code, rec.out.pass, rec.out.verdict, rec.out.blockers, rec.out.majors, rec.out.diff_lines, typeof rec.out.tree], [0, 1, 'needs-changes', 1, 2, 5, 'string']);
152
- check('record-pass without --verdict is a usage error (64)', recordPass(mCtx(), m).code, 64);
153
- passPass(mCtx({ SOMI_CODE_LOOP_MAX_PASSES: '5' }), m);
154
- writeFileSync(path.join(root, 'a.js'), '1\n2\n3\n4\n');
155
- const delta = reviewScope(mCtx(), m);
156
- check('review-scope on a middle pass is the delta since the reviewed tree', [delta.out.scope, delta.out.since_pass, delta.out.files], ['delta', 1, ['a.js']]);
157
- const agent = recordDispatch(mCtx(), { ...m, agent: 'somi-coder' });
158
- check('record-dispatch appends the resolver\'s answer for a known agent', [agent.code, agent.out.agent, agent.out.pass], [0, 'somi-coder', 2]);
159
- const nobody = recordDispatch(mCtx(), { ...m, agent: 'no-such-agent' });
160
- check('record-dispatch refuses an unknown agent with the resolver\'s code (65) and no stdout', [nobody.code, nobody.out, nobody.message.startsWith('somi-loop: ')], [65, undefined, true]);
161
- check('record-dispatch without --agent is a usage error (64)', recordDispatch(mCtx(), m).code, 64);
162
- check('run-start records the budget, keeps it on a repeat, and refuses a zero budget (64)', [runStart(mCtx(), { ...m, maxMinutes: '30' }).out.max_minutes, runStart(mCtx(), { ...m, maxMinutes: '45' }).out.resumed, runStart(mCtx(), { ...m, slug: 'z', maxMinutes: '0' }).code], [30, true, 64]);
163
- check('none of the measure and record calls touched process.env', JSON.stringify(process.env), envBefore);
164
- { // init creates the state directory only just before it saves, so a refused init leaves nothing behind
165
- const bare = mkdtempSync(path.join(tmpdir(), 'loop-bare-'));
166
- const bctx = { root: bare, env: { SOMI_GLOBAL_CONFIG: '' }, stateDir: path.join(bare, '.somi', 'somi-state', 'loop'), now: () => '2026-01-01T00:00:00Z' };
167
- const refused = [init(bctx, { ...base, slug: 'x', severity: 'nope' }).code, init(bctx, { ...base, slug: 'x' }).code]; // a bad floor, then no HEAD to baseline on
168
- check('a refused init (bad severity floor, unresolvable HEAD) exits 64 and creates no state directory', [refused, existsSync(path.join(bare, '.somi'))], [[64, 64], false]);
169
- rmSync(bare, { recursive: true, force: true });
170
- }
171
- { // a repository the diff gate refuses is refused at init, before any coder pass; a plan loop has no diff gate
172
- const sub = mkdtempSync(path.join(tmpdir(), 'loop-initsub-'));
173
- const sg = (...a) => execFileSync('git', ['-C', sub, '-c', 'user.name=t', '-c', 'user.email=t@t', ...a], { encoding: 'utf8' });
174
- sg('init', '-q'); sg('commit', '-q', '--allow-empty', '-m', 'base');
175
- mkdirSync(path.join(sub, 'n')); execFileSync('git', ['-C', path.join(sub, 'n'), 'init', '-q']);
176
- const sctx = { root: sub, env: { SOMI_GLOBAL_CONFIG: '' }, stateDir: path.join(sub, '.somi', 'somi-state', 'loop'), now: () => '2026-01-01T00:00:00Z' };
177
- const code = init(sctx, { ...base, slug: 'x' });
178
- check('init in a repository with a nested repository is refused (64), names it with the .gitignore remedy, and writes nothing',
179
- [code.code, code.message.includes('does not support repositories with submodules (n/); if it is not a submodule, add it to .gitignore'), existsSync(path.join(sub, '.somi'))], [64, true, false]);
180
- check('a plan loop is not refused for a nested repository', init(sctx, { ...base, slug: 'p', loop: 'plan' }).code, 0);
181
- rmSync(sub, { recursive: true, force: true });
182
- }
183
- rmSync(root, { recursive: true, force: true });
184
- rmSync(globalDir, { recursive: true, force: true });
185
-
186
- console.log('== the snapshot tree is built from what is on disk, whatever the repository config says ==');
187
- { // each case: a committed baseline, one change, and what the measurement says about it
188
- const made = [];
189
- const repo = () => { const r = mkdtempSync(path.join(tmpdir(), 'loop-snap-')); made.push(r); const g = (...a) => execFileSync('git', ['-C', r, '-c', 'user.name=t', '-c', 'user.email=t@t', ...a], { encoding: 'utf8' }).trim(); g('init', '-q'); return { r, g }; };
190
- const put = (r, f, text, time) => { mkdirSync(path.dirname(path.join(r, f)), { recursive: true }); writeFileSync(path.join(r, f), text); if (time) utimesSync(path.join(r, f), time, time); };
191
- const measure = (r, g) => treeNumstat(r, g('rev-parse', 'HEAD'), measuredTree(r));
192
- const refused = (r) => { const [a, code, msg] = exitOf(() => measuredTree(r)); return [a, code, msg.startsWith('somi-loop: cannot measure the diff: ')]; };
193
- const racy = repo(); put(racy.r, 'f', 'aaaa\n', 1700000000); racy.g('add', '.'); racy.g('commit', '-q', '-m', 'f');
194
- utimesSync(path.join(racy.r, '.git', 'index'), 1700000000, 1700000000); put(racy.r, 'f', 'bbbb\n', 1700000000); // same size, same second as the index: git calls the entry racy
195
- check('a same-size edit made in the second the index was written is counted (the throwaway index keeps the real index\'s times)', measure(racy.r, racy.g), [{ added: 1, deleted: 1, file: 'f' }]);
196
- Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 1100); // git compares ctime to the second
197
- utimesSync(path.join(racy.r, '.git', 'index'), 1800000000, 1800000000); racy.g('config', 'core.trustctime', 'false'); racy.g('config', 'core.checkStat', 'minimal'); racy.g('config', 'core.ignoreStat', 'true'); put(racy.r, 'f', 'cccc\n', 1700000000); // the old mtime put back by hand
198
- check('a repository config that loosens the stat check does not hide a same-size edit that kept its old mtime', measure(racy.r, racy.g), [{ added: 1, deleted: 1, file: 'f' }]);
199
- const hook = path.join(racy.r, 'hook.sh'); put(racy.r, 'hook.sh', `#!/bin/sh\ntouch ${path.join(racy.r, 'RAN')}\nprintf '\\0'\n`); chmodSync(hook, 0o755); racy.g('config', 'core.fsmonitor', hook);
200
- check('a core.fsmonitor hook in the repository config does not run during the measurement', [measure(racy.r, racy.g).length, existsSync(path.join(racy.r, 'RAN'))], [2, false]);
201
- const rep = repo(); rep.g('commit', '-q', '--allow-empty', '-m', '0'); put(rep.r, 'f', 'x\n'.repeat(4000)); rep.g('add', '.'); rep.g('commit', '-q', '-m', 'f'); put(rep.r, 'one', 'x\n');
202
- rep.g('replace', rep.g('rev-parse', 'HEAD:f'), rep.g('hash-object', '-w', 'one'));
203
- check('a git replace ref is refused with 64, so a substituted blob is never counted in place of the real one', refused(rep.r), [true, 64, true]);
204
- check('and the diff itself ignores the replacement: the 4000 lines of the real blob, not the 1 of the substitute', treeNumstat(rep.r, rep.g('rev-parse', 'HEAD~1'), rep.g('rev-parse', 'HEAD'))[0].added, 4000);
205
- const sp = repo(); put(sp.r, 'src/a', 'a\n'); put(sp.r, 'other/b', 'b\n'); sp.g('add', '.'); sp.g('commit', '-q', '-m', 'f'); sp.g('sparse-checkout', 'set', '--cone', 'src'); put(sp.r, 'src/a', 'a\nb\n');
206
- check('a sparse checkout measures: files left out of the working tree are not an edit', [existsSync(path.join(sp.r, 'other')), measure(sp.r, sp.g)], [false, [{ added: 1, deleted: 0, file: 'src/a' }]]);
207
- sp.g('sparse-checkout', 'disable'); sp.g('update-index', '--skip-worktree', 'src/a'); // a hidden flag on a file that is on disk
208
- check('a skip-worktree file that is on disk refuses: its edit would be hidden', refused(sp.r), [true, 64, true]);
209
- const wt = repo(); wt.g('commit', '-q', '--allow-empty', '-m', 'f'); wt.g('config', 'extensions.worktreeConfig', 'true'); put(wt.r, '.gitattributes', '*.js filter=x\n'); put(wt.r, 'f.js', 'x\n');
210
- wt.g('config', '--worktree', 'filter.x.clean', `touch ${path.join(wt.r, 'RAN')}; cat`);
211
- check('a clean filter in the worktree config is refused and does not run', [...refused(wt.r), existsSync(path.join(wt.r, 'RAN'))], [true, 64, true, false]);
212
- const ign = repo(); put(ign.r, 'a', 'a\n'); ign.g('add', '.'); ign.g('commit', '-q', '-m', 'f'); put(ign.r, '.gitignore', '.somi\n'); put(ign.r, '.somi/n', 'x\n'.repeat(50)); put(ign.r, 'z', 'x\n');
213
- check('a .gitignore that ignores .somi does not stop the measurement, and .somi stays out of it', measure(ign.r, ign.g).map((x) => x.file).sort(), ['.gitignore', 'z']);
214
- const bin = repo(); bin.g('commit', '-q', '--allow-empty', '-m', 'f'); put(bin.r, 'b.bin', Buffer.alloc(4999));
215
- check('a binary with no newline counts one line per 50 bytes (100), not one', measure(bin.r, bin.g), [{ added: 100, deleted: 0, file: 'b.bin' }]);
216
- const wtr = repo(); put(wtr.r, 'f', 'a\n'); wtr.g('add', '.'); wtr.g('commit', '-q', '-m', 'f'); put(wtr.r, 'f', 'a\nb\nc\n');
217
- const empty = mkdtempSync(path.join(tmpdir(), 'loop-snap-')); made.push(empty); wtr.g('config', 'core.worktree', empty);
218
- check('a core.worktree that points elsewhere does not hide the real tree', measure(wtr.r, wtr.g), [{ added: 2, deleted: 0, file: 'f' }]);
219
- const decoy = repo(); const head = wtr.g('rev-parse', 'HEAD'); process.env.GIT_DIR = path.join(decoy.r, '.git'); process.env.GIT_INDEX_FILE = path.join(decoy.r, 'nope'); process.env.GIT_OBJECT_DIRECTORY = empty; process.env.GIT_LITERAL_PATHSPECS = '1';
220
- const viaEnv = treeNumstat(wtr.r, head, measuredTree(wtr.r)); delete process.env.GIT_DIR; delete process.env.GIT_INDEX_FILE; delete process.env.GIT_OBJECT_DIRECTORY; delete process.env.GIT_LITERAL_PATHSPECS;
221
- check('a GIT_DIR, GIT_INDEX_FILE, GIT_OBJECT_DIRECTORY and GIT_LITERAL_PATHSPECS in the caller\'s environment do not redirect the measurement', viaEnv, [{ added: 2, deleted: 0, file: 'f' }]);
222
- const sm = repo(); sm.g('commit', '-q', '--allow-empty', '-m', 'f'); put(sm.r, 'n/a', 'x\n'.repeat(50)); execFileSync('git', ['-C', path.join(sm.r, 'n'), 'init', '-q']); execFileSync('git', ['-C', path.join(sm.r, 'n'), '-c', 'user.name=t', '-c', 'user.email=t@t', 'add', '.']); execFileSync('git', ['-C', path.join(sm.r, 'n'), '-c', 'user.name=t', '-c', 'user.email=t@t', 'commit', '-q', '-m', 'n']);
223
- put(sm.r, '.gitmodules', '[submodule "n"]\n\tpath = n\n\turl = ./n\n\tignore = all\n');
224
- check('a nested repository hidden by .gitmodules ignore = all is refused like any other', exitOf(() => measure(sm.r, sm.g)).slice(0, 2), [true, 64]);
225
- const hk = repo(); hk.g('commit', '-q', '--allow-empty', '-m', 'f'); put(hk.r, 'f', 'x\n'); put(hk.r, '.git/hooks/post-index-change', `#!/bin/sh\ntouch ${path.join(hk.r, 'RAN')}\n`); chmodSync(path.join(hk.r, '.git/hooks/post-index-change'), 0o755);
226
- check('a post-index-change hook does not run during the measurement', [measure(hk.r, hk.g).length, existsSync(path.join(hk.r, 'RAN'))], [1, false]);
227
- const sq = repo(); put(sq.r, 'src/a', 'a\n'); put(sq.r, 'other/b', 'b\n'); sq.g('add', '.'); sq.g('commit', '-q', '-m', 'f'); sq.g('sparse-checkout', 'set', '--cone', 'src'); put(sq.r, 'other/new', 'n\nn\n');
228
- check('an untracked file outside the sparse checkout is counted, not refused', measure(sq.r, sq.g), [{ added: 2, deleted: 0, file: 'other/new' }]);
229
- const sub = repo(); put(sub.r, 'pkg/a', 'a\nb\n'); put(sub.r, 'big', 'x\n'.repeat(2000)); sub.g('add', '.'); sub.g('commit', '-q', '-m', 'f'); put(sub.r, 'pkg/a', 'a\nB\n'); put(sub.r, 'big', 'y\n'.repeat(2000));
230
- const subRoot = path.join(sub.r, 'pkg'); const subDiff = computeDiff(subRoot, sub.g('rev-parse', 'HEAD'), ['a']);
231
- check('a project directory below the repository top level counts its own subtree: a one-line edit is 2 lines, none out of scope', [subDiff.total, subDiff.weighted, subDiff.outOfScope], [2, 2, []]);
232
- const lk = repo(); put(lk.r, 'f', 'a\n'); lk.g('add', '.'); lk.g('commit', '-q', '-m', 'f'); const lkDir = path.join(lk.r, '..', path.basename(lk.r) + '-wt'); made.push(lkDir); lk.g('worktree', 'add', '-q', lkDir, '-b', 'x'); put(lkDir, 'f', 'a\nb\n');
233
- check('a linked worktree measures its own files', measure(lkDir, lk.g), [{ added: 1, deleted: 0, file: 'f' }]);
234
- const ic = repo(); put(ic.r, 'foo.txt', 'a\n'); ic.g('add', '.'); ic.g('commit', '-q', '-m', 'f'); ic.g('config', 'core.ignoreCase', 'true'); put(ic.r, 'Foo.txt', 'x\n'.repeat(3000));
235
- check('core.ignoreCase true in the repository config does not hide a new file whose name differs from a tracked one only by case', measure(ic.r, ic.g), [{ added: 3000, deleted: 0, file: 'Foo.txt' }]);
236
- symlinkSync('.git', path.join(ic.r, '.GIT'));
237
- check('and a .GIT symlink to .git does not either: git refuses the path, so the measurement refuses rather than count less', refused(ic.r), [true, 64, true]);
238
- const initAt = (r) => init({ root: r, env: { SOMI_GLOBAL_CONFIG: '' }, stateDir: path.join(r, '.somi', 'somi-state', 'loop'), now: () => 'T' }, { ...base, slug: 'i' });
239
- const nameInvalid = exitOf(() => measuredTree(ic.r))[2];
240
- check('git\'s invalid path is named in the refusal, bounded and without control characters', [nameInvalid.includes('"/.GIT"') || nameInvalid.includes('".GIT"'), nameInvalid.includes("'")], [true, false]);
241
- const hl = repo(); put(hl.r, 'f', 'a\n'); hl.g('add', '.'); hl.g('commit', '-q', '-m', 'f'); const hlDir = path.join(hl.r, '..', path.basename(hl.r) + '-wt'); made.push(hlDir); hl.g('worktree', 'add', '-q', hlDir, '-b', 'x'); put(hlDir, 'f', 'a\nb\n'); linkSync(path.join(hlDir, '.git'), path.join(hlDir, '.GIT'));
242
- check('a hard-linked gitfile .GIT in a linked worktree is refused (64), never counted as no change', refused(hlDir), [true, 64, true]);
243
- const sg = (r, ...a) => execFileSync('git', ['-C', r, '-c', 'user.name=t', '-c', 'user.email=t@t', '-c', 'protocol.file.allow=always', ...a], { encoding: 'utf8' }).trim();
244
- for (const [what, plant] of [['an empty .git directory', (d) => mkdirSync(path.join(d, '.git'))], ['a gitfile that is not a gitdir line', (d) => writeFileSync(path.join(d, '.git'), 'hello\n')], ['a gitfile pointing at a directory that is no repository', (d) => writeFileSync(path.join(d, '.git'), `gitdir: ${tmpdir()}\n`)]]) {
245
- const pl = repo(); pl.g('commit', '-q', '--allow-empty', '-m', 'f'); put(pl.r, 'pkg/f', 'x\n'); plant(path.join(pl.r, 'pkg'));
246
- check(`${what} between the project and the top is refused (64) with the .git cause, not walked past`, [refused(path.join(pl.r, 'pkg')), exitOf(() => measuredTree(path.join(pl.r, 'pkg')))[2].includes('.git" is neither a git directory nor'), initAt(path.join(pl.r, 'pkg')).code], [[true, 64, true], true, 64]);
247
- }
248
- const home = repo(); put(home.r, 'pkg/f', 'a\n'); home.g('add', '.'); home.g('commit', '-q', '-m', 'f'); const link = path.join(path.dirname(home.r), path.basename(home.r) + '-link'); made.push(link); symlinkSync(path.join(home.r, 'pkg'), link); put(home.r, 'pkg/f', 'a\nb\n');
249
- check('a project directory reached through a symlink to a subdirectory is measured like the real path', [treeNumstat(link, home.g('rev-parse', 'HEAD'), measuredTree(link)), computeDiff(link, home.g('rev-parse', 'HEAD'), ['f']).weighted], [[{ added: 1, deleted: 0, file: 'f' }], 1]);
250
- const decoy2 = repo(); decoy2.g('commit', '-q', '--allow-empty', '-m', 'other'); process.env.GIT_DIR = path.join(decoy2.r, '.git'); process.env.GIT_WORK_TREE = decoy2.r;
251
- const atInit = initAt(home.r).out?.baseline_sha; delete process.env.GIT_DIR; delete process.env.GIT_WORK_TREE;
252
- check('the init baseline is the project\'s HEAD whatever GIT_DIR the caller\'s environment holds', atInit, home.g('rev-parse', 'HEAD'));
253
- const noHead = repo(); const refusedInit = initAt(noHead.r);
254
- check('init in a repository with no commit is a refusal (64) that names HEAD, with no state written', [refusedInit.code, refusedInit.message.startsWith('somi-loop: cannot resolve HEAD') && refusedInit.message.includes('no commit'), existsSync(path.join(noHead.r, '.somi'))], [64, true, false]);
255
- const deep = repo(); deep.g('commit', '-q', '--allow-empty', '-m', 'f'); const deepDir = path.join(deep.r, 'a'.repeat(40), 'b'.repeat(40), 'c'.repeat(40)); mkdirSync(path.join(deepDir, '.git'), { recursive: true });
256
- check('a long path keeps its .git tail in the refusal', exitOf(() => measuredTree(deepDir))[2].includes('.git" is neither'), true);
257
- const gitfile = readFileSync(path.join(lkDir, '.git'), 'utf8').trim().slice('gitdir: '.length);
258
- writeFileSync(path.join(lkDir, '.git'), `gitdir: ${gitfile}\r\n\r\n`);
259
- check('a gitfile ending in CRLF and a blank line, as git reads it, is accepted', measure(lkDir, lk.g), [{ added: 1, deleted: 0, file: 'f' }]);
260
- const gf = repo(); gf.g('commit', '-q', '--allow-empty', '-m', 'f'); put(gf.r, 'pkg/f', 'x\n'); symlinkSync(path.join(lkDir, '.git'), path.join(gf.r, 'pkg', '.git'));
261
- check('a gitfile reached through a symlink is refused, not read', refused(path.join(gf.r, 'pkg')), [true, 64, true]);
262
- const fk = repo(); fk.g('commit', '-q', '--allow-empty', '-m', 'f'); put(fk.r, "x invalid path 'FAKE'", 'x\n'); chmodSync(path.join(fk.r, "x invalid path 'FAKE'"), 0);
263
- const fakeMsg = exitOf(() => measuredTree(fk.r))[2];
264
- check('a file name that contains git\'s invalid-path wording is not mistaken for it', [fakeMsg.startsWith('somi-loop: cannot measure the diff: '), fakeMsg.includes('refuses the path')], [true, false]);
265
- const nest = (r, rel) => { sg(r, 'init', '-q', rel); put(r, `${rel}/a`, 'x\n'); sg(path.join(r, rel), 'add', '.'); sg(path.join(r, rel), 'commit', '-q', '-m', 'n'); }; // a repository at r/rel
266
- const withSub = () => { const o = repo(); nest(o.r, '.'); const t = repo(); sg(t.r, 'submodule', 'add', '-q', o.r, 'n'); sg(t.r, 'commit', '-q', '-m', 't'); return t; }; // a committed submodule n
267
- const refusedAs = (r, where) => { const [a, code, msg] = exitOf(() => measuredTree(r)); return [a, code, msg.includes(`does not support repositories with submodules (${where})`)]; };
268
- const tmps = () => readdirSync(tmpdir()).filter((f) => f.startsWith('somi-tree-')).length;
269
- const indexOf = (r) => readFileSync(path.join(r, '.git', 'index')).toString('hex');
270
- const gl = repo(); gl.g('commit', '-q', '--allow-empty', '-m', 'f'); nest(gl.r, 'n'); sg(gl.r, 'add', 'n');
271
- check('a gitlink in the index is refused (64) with one message naming it', refusedAs(gl.r, 'n'), [true, 64, true]);
272
- const hd = withSub(); sg(hd.r, 'rm', '-q', '--cached', 'n'); rmSync(path.join(hd.r, 'n'), { recursive: true, force: true });
273
- check('a gitlink only in HEAD (git rm --cached, directory gone) is refused', refusedAs(hd.r, 'n'), [true, 64, true]);
274
- const ut = repo(); ut.g('commit', '-q', '--allow-empty', '-m', 'f'); nest(ut.r, 'd/e/inner');
275
- check('an untracked directory that holds a .git is refused, named with its path', refusedAs(ut.r, 'd/e/inner/'), [true, 64, true]);
276
- check('a gitlink refusal does not suggest .gitignore (only an untracked directory may be ignored)', [exitOf(() => measuredTree(gl.r))[2].includes('.gitignore'), exitOf(() => measuredTree(ut.r))[2].includes('add it to .gitignore')], [false, true]);
277
- const co = withSub(); put(co.r, 'n/a', 'x\ny\n'); put(co.r, 'f', 'z\n'); const idx = indexOf(co.r); const before = tmps();
278
- check('a checked-out submodule is refused whatever it holds, and the refusal writes nothing (index and temp directories as they were)', [refusedAs(co.r, 'n'), indexOf(co.r), tmps()], [[true, 64, true], idx, before]);
279
- const ig = repo(); ig.g('commit', '-q', '--allow-empty', '-m', 'f'); nest(ig.r, 'vendor'); put(ig.r, '.gitignore', 'vendor/\n'); put(ig.r, 'f', 'a\n');
280
- check('a nested repository that .gitignore lists is not a submodule: the rest is measured', measure(ig.r, ig.g).map((x) => x.file).sort(), ['.gitignore', 'f']);
281
- const so = repo(); so.g('commit', '-q', '--allow-empty', '-m', 'f'); nest(so.r, '.somi/x'); put(so.r, 'f', 'a\n');
282
- check('a repository under .somi is outside the measurement, not a submodule', measure(so.r, so.g), [{ added: 1, deleted: 0, file: 'f' }]);
283
- for (const r of made) rmSync(r, { recursive: true, force: true });
284
- }
285
-
286
- console.log(`loop engine tests: ${pass} ok, ${fail} failed`);
287
- process.exit(fail === 0 ? 0 : 1);