@skathio/somi 4.1.1 → 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 -227
  190. package/scripts/lib/loop-escalate.mjs +0 -49
  191. package/scripts/lib/loop-exit.mjs +0 -47
  192. package/scripts/lib/loop-notes-compact.mjs +0 -72
  193. package/scripts/lib/loop-notes.mjs +0 -282
  194. package/scripts/lib/loop-review.mjs +0 -395
  195. package/scripts/lib/loop-state.mjs +0 -44
  196. package/scripts/lib/loop-step-close.mjs +0 -75
  197. package/scripts/lib/loop-step-kit.mjs +0 -179
  198. package/scripts/lib/loop-step-review.mjs +0 -140
  199. package/scripts/lib/loop-step-tool.mjs +0 -89
  200. package/scripts/lib/loop-step.mjs +0 -303
  201. package/scripts/lib/run-budget.mjs +0 -28
  202. package/scripts/lib/run-card.mjs +0 -73
  203. package/scripts/lib/size-tier.mjs +0 -184
  204. package/scripts/lib/tier-record.mjs +0 -82
  205. package/scripts/size-budget-overrides.json +0 -58
  206. package/scripts/somi-card.mjs +0 -39
  207. package/scripts/somi-check.mjs +0 -237
  208. package/scripts/somi-config.mjs +0 -421
  209. package/scripts/somi-dispatch.mjs +0 -141
  210. package/scripts/somi-findings.mjs +0 -100
  211. package/scripts/somi-loop.mjs +0 -139
  212. package/scripts/somi-tier.mjs +0 -393
  213. package/scripts/validate.sh +0 -653
  214. package/skills/api-design/SKILL.md +0 -147
  215. package/skills/clean-code/SKILL.md +0 -142
  216. package/skills/flow-adopt/SKILL.md +0 -92
  217. package/skills/flow-architecture-review/SKILL.md +0 -94
  218. package/skills/flow-atlas/SKILL.md +0 -34
  219. package/skills/flow-code/SKILL.md +0 -167
  220. package/skills/flow-code-loop/SKILL.md +0 -263
  221. package/skills/flow-code-parallel/SKILL.md +0 -160
  222. package/skills/flow-debug/SKILL.md +0 -141
  223. package/skills/flow-design/SKILL.md +0 -170
  224. package/skills/flow-discover/SKILL.md +0 -204
  225. package/skills/flow-impact/SKILL.md +0 -35
  226. package/skills/flow-incident/SKILL.md +0 -49
  227. package/skills/flow-plan/SKILL.md +0 -254
  228. package/skills/flow-plan-loop/SKILL.md +0 -254
  229. package/skills/flow-pr/SKILL.md +0 -34
  230. package/skills/flow-refactor/SKILL.md +0 -58
  231. package/skills/flow-refactor-design/SKILL.md +0 -97
  232. package/skills/flow-release-readiness/SKILL.md +0 -82
  233. package/skills/flow-review/SKILL.md +0 -193
  234. package/skills/flow-review-panel/SKILL.md +0 -154
  235. package/skills/flow-security-review/SKILL.md +0 -83
  236. package/skills/flow-ship/SKILL.md +0 -125
  237. package/skills/flow-ship-loop/SKILL.md +0 -274
  238. package/skills/flow-somi-config/SKILL.md +0 -142
  239. package/skills/flow-status/SKILL.md +0 -43
  240. package/skills/flow-test-strategy/SKILL.md +0 -83
  241. package/skills/flow-upgrade/SKILL.md +0 -82
  242. package/skills/market-research/SKILL.md +0 -125
  243. package/skills/observability/SKILL.md +0 -133
  244. package/skills/owasp-defense/SKILL.md +0 -141
  245. package/skills/plan-review/SKILL.md +0 -83
  246. package/skills/reasoning-craft/SKILL.md +0 -213
  247. package/skills/requirements-engineering/SKILL.md +0 -137
  248. package/skills/role-coder/SKILL.md +0 -247
  249. package/skills/role-designer/SKILL.md +0 -172
  250. package/skills/role-discovery-analyst/SKILL.md +0 -288
  251. package/skills/role-planner/SKILL.md +0 -353
  252. package/skills/role-reviewer/SKILL.md +0 -218
  253. package/skills/rules/SKILL.md +0 -47
  254. package/skills/sdlc-process/SKILL.md +0 -74
  255. package/skills/solid-principles/SKILL.md +0 -143
  256. package/skills/somi-checkpoint/SKILL.md +0 -95
  257. package/skills/somi-dispatch/SKILL.md +0 -259
  258. package/skills/somi-routing/SKILL.md +0 -158
  259. package/skills/testing-playbook/SKILL.md +0 -133
  260. package/skills/threat-modeling/SKILL.md +0 -117
  261. package/templates/ADR.md.tmpl +0 -73
  262. package/templates/ATLAS.md.tmpl +0 -75
  263. package/templates/BRD.md.tmpl +0 -68
  264. package/templates/BRIEF.md.tmpl +0 -119
  265. package/templates/CONTEXT.md.tmpl +0 -74
  266. package/templates/DECISIONS.md.tmpl +0 -105
  267. package/templates/DESIGN.md.tmpl +0 -83
  268. package/templates/DIARY.md.tmpl +0 -70
  269. package/templates/DOD.md.tmpl +0 -90
  270. package/templates/FRD.md.tmpl +0 -64
  271. package/templates/PHASE.md.tmpl +0 -80
  272. package/templates/PROGRESS.md.tmpl +0 -63
  273. package/templates/RCA.md.tmpl +0 -53
  274. package/templates/RD-README.md.tmpl +0 -70
  275. package/templates/RESEARCH.md.tmpl +0 -96
  276. package/templates/REVIEW.md.tmpl +0 -82
  277. package/templates/SDD.md.tmpl +0 -82
  278. package/templates/SOMI-README.md.tmpl +0 -83
  279. package/templates/SPEC.md.tmpl +0 -123
  280. package/templates/SRS.md.tmpl +0 -85
  281. package/templates/TDD.md.tmpl +0 -77
  282. package/tests/hooks/cases/audit-log.json +0 -21
  283. package/tests/hooks/cases/block-dangerous-bash.json +0 -166
  284. package/tests/hooks/cases/block-secret-writes.json +0 -140
  285. package/tests/hooks/cases/detect-repo-instructions.json +0 -105
  286. package/tests/hooks/cases/gate-dep-install.json +0 -42
  287. package/tests/hooks/cases/guard-protected-paths.json +0 -222
  288. package/tests/hooks/cases/inject-workflow-context.json +0 -239
  289. package/tests/hooks/cases/lint-changed-files.json +0 -120
  290. package/tests/hooks/run.sh +0 -392
  291. package/tests/scripts/agent-model-frontmatter.sh +0 -38
  292. package/tests/scripts/agent-names.sh +0 -77
  293. package/tests/scripts/check-frontmatter.sh +0 -37
  294. package/tests/scripts/check-links.sh +0 -105
  295. package/tests/scripts/check-session-artefacts.sh +0 -60
  296. package/tests/scripts/check-size-budget.sh +0 -71
  297. package/tests/scripts/checkpoint-gate.sh +0 -131
  298. package/tests/scripts/convergence-runner.sh +0 -1514
  299. package/tests/scripts/cost-ceiling.sh +0 -255
  300. package/tests/scripts/cost-defaults.sh +0 -130
  301. package/tests/scripts/cost-hardcap.sh +0 -338
  302. package/tests/scripts/cost-lowering.sh +0 -261
  303. package/tests/scripts/cost-model.sh +0 -196
  304. package/tests/scripts/dispatch-guard.sh +0 -108
  305. package/tests/scripts/dispatch-line-gate.sh +0 -61
  306. package/tests/scripts/dispatch-reference-gate.sh +0 -173
  307. package/tests/scripts/ensure-default-config.sh +0 -162
  308. package/tests/scripts/escalation.sh +0 -409
  309. package/tests/scripts/eval-runner.sh +0 -3692
  310. package/tests/scripts/evals-packaging.sh +0 -224
  311. package/tests/scripts/fact-sheet.sh +0 -296
  312. package/tests/scripts/fixtures/legacy-shard-no-schema.json +0 -50
  313. package/tests/scripts/fixtures/mock-stdin-read-throw.cjs +0 -18
  314. package/tests/scripts/fixtures/size-tier-cases.json +0 -87
  315. package/tests/scripts/generate-digest.sh +0 -180
  316. package/tests/scripts/global-config.sh +0 -167
  317. package/tests/scripts/goldens/loop-state-breach.json +0 -1
  318. package/tests/scripts/goldens/loop-state-done.json +0 -1
  319. package/tests/scripts/goldens/somi-findings.json +0 -336
  320. package/tests/scripts/goldens/somi-loop.json +0 -168
  321. package/tests/scripts/lib/adr-shape.mjs +0 -41
  322. package/tests/scripts/lib/agent-registry-tests.mjs +0 -95
  323. package/tests/scripts/lib/brief-only-guard.mjs +0 -27
  324. package/tests/scripts/lib/checkpoint-gate.mjs +0 -91
  325. package/tests/scripts/lib/digest-marker-coupling.mjs +0 -52
  326. package/tests/scripts/lib/dispatch-reference-gate.mjs +0 -121
  327. package/tests/scripts/lib/escalation-facts-tests.mjs +0 -140
  328. package/tests/scripts/lib/escalation-tests.mjs +0 -154
  329. package/tests/scripts/lib/findings-ledger-tests.mjs +0 -118
  330. package/tests/scripts/lib/loop-engine-tests.mjs +0 -287
  331. package/tests/scripts/lib/loop-escalate-tests.mjs +0 -356
  332. package/tests/scripts/lib/loop-flow-gate.mjs +0 -173
  333. package/tests/scripts/lib/loop-notes-tests.mjs +0 -384
  334. package/tests/scripts/lib/loop-step-cli-tests.mjs +0 -156
  335. package/tests/scripts/lib/loop-step-close-tests.mjs +0 -351
  336. package/tests/scripts/lib/loop-step-lenient-tests.mjs +0 -114
  337. package/tests/scripts/lib/loop-step-state-tests.mjs +0 -127
  338. package/tests/scripts/lib/loop-step-tests.mjs +0 -499
  339. package/tests/scripts/lib/loop-step-unwritten-tests.mjs +0 -55
  340. package/tests/scripts/lib/multipass-dependence.mjs +0 -192
  341. package/tests/scripts/lib/multipass-source-identity.mjs +0 -243
  342. package/tests/scripts/lib/path-facts-tests.mjs +0 -198
  343. package/tests/scripts/lib/path-safety-tests.mjs +0 -201
  344. package/tests/scripts/lib/reference-pair.mjs +0 -61
  345. package/tests/scripts/lib/retirement-gate.mjs +0 -172
  346. package/tests/scripts/lib/run-suites.mjs +0 -139
  347. package/tests/scripts/lib/shell-embedded-js.mjs +0 -47
  348. package/tests/scripts/lib/ship-loop-sizing-guard.mjs +0 -52
  349. package/tests/scripts/lib/site-roadmap-gate.mjs +0 -64
  350. package/tests/scripts/lib/size-tier-drift.mjs +0 -74
  351. package/tests/scripts/lib/sizing-score-tests.mjs +0 -210
  352. package/tests/scripts/lib/sizing-set-tests.mjs +0 -131
  353. package/tests/scripts/lib/somi-mcp-client.mjs +0 -102
  354. package/tests/scripts/lib/somi-mcp-config-tests.mjs +0 -92
  355. package/tests/scripts/lib/somi-mcp-loop-tests.mjs +0 -226
  356. package/tests/scripts/lib/somi-mcp-tests.mjs +0 -491
  357. package/tests/scripts/lib/somi-mcp-tier-tests.mjs +0 -64
  358. package/tests/scripts/lib/somi-mcp-tool-schema.mjs +0 -38
  359. package/tests/scripts/loop-engine.sh +0 -22
  360. package/tests/scripts/loop-flow-gate.sh +0 -11
  361. package/tests/scripts/retirement-gate.sh +0 -306
  362. package/tests/scripts/review-panel-seats.sh +0 -32
  363. package/tests/scripts/run-card.sh +0 -57
  364. package/tests/scripts/run-suites.sh +0 -74
  365. package/tests/scripts/run.sh +0 -689
  366. package/tests/scripts/site-roadmap-gate.sh +0 -76
  367. package/tests/scripts/size-tier.sh +0 -562
  368. package/tests/scripts/somi-agent-dispatch-contract.sh +0 -224
  369. package/tests/scripts/somi-config.sh +0 -286
  370. package/tests/scripts/somi-dispatch.sh +0 -465
  371. package/tests/scripts/somi-mcp.sh +0 -15
  372. package/tests/scripts/suite-plan.json +0 -20
@@ -1,27 +0,0 @@
1
- // brief-only-guard.mjs <code.md> <code-loop.md> -- both commands must accept a one-iteration work item
2
- // made of a brief and no phase files, and refuse it without the sizing CLI's tier record. Prints
3
- // "ok ..." (exit 0) or one problem per line (exit 1).
4
- import { readFileSync } from 'node:fs';
5
-
6
- const flat = (p) => readFileSync(p, 'utf8').replace(/\s+/g, ' ');
7
- const [code, loop] = process.argv.slice(2).map(flat);
8
- const problems = [];
9
-
10
- const anchors = [
11
- ['names the brief-only item', /brief-only work item/i],
12
- ['names its shape: brief.md and progress.md, no phases/', /`brief\.md` and `progress\.md`[^.]*no `phases\/`/],
13
- ['fixes the iteration as 1.1', /iteration `?1\.1`?/],
14
- ['requires the CLI tier record for the slug', /tier record|somi-state\/tier\/<slug>\.json/],
15
- ['requires a non-null signals_sha256', /non-null `signals_sha256`/],
16
- ['requires the small tier', /`tier` (?:equal to |)`small`/],
17
- ['refuses and recommends /plan', /(?:stop|refuse)[^.]*`\/plan <problem>`/],
18
- ];
19
- for (const [name, text] of [['code.md', code], ['code-loop.md', loop]]) {
20
- for (const [what, re] of anchors) if (!re.test(text)) problems.push(`${name} does not state: ${what}`);
21
- }
22
- if (!/(?:Never create the record or edit it by hand)/.test(code) || !/never create or edit that record by hand/.test(loop)) problems.push('code.md does not forbid creating or editing the record');
23
- for (const [n, t] of [['code.md', code], ['code-loop.md', loop]]) if (/\b(?:skip this|or any tier|or create|write (?:one|it) by hand|without a record)\b/i.test(t)) problems.push(`${n} permits bypassing the tier record`);
24
- if (/TRIVIAL_MAX_|MAX_FILES|MAX_MODULES|MAX_DIFF_LINES|hard_surface|est_files/.test(code + loop)) problems.push('the commands repeat a rubric constant or signal id');
25
-
26
- if (problems.length) { console.log(problems.join('\n')); process.exit(1); }
27
- console.log('both commands accept the brief-only item only with a small-tier record');
@@ -1,91 +0,0 @@
1
- #!/usr/bin/env node
2
- // checkpoint-gate.mjs — guards commands/ship-loop.md's single non-overridable human checkpoint.
3
- //
4
- // The checkpoint was re-anchored from a cost-tier boundary (one that stopped
5
- // existing once commands declared no tier and execution itself could mix tiers) to the brief
6
- // handoff: it fires once a design action has produced a brief.md, before planning consumes it, or
7
- // -- on a cold start with no design action -- after /plan-loop, before any code. Nothing else in
8
- // this repo tests that a later edit to ship-loop.md keeps that definition intact. This gate is
9
- // deliberately narrow: it does not re-derive the whole retirement sweep (retirement-gate.mjs and
10
- // the DoD's own repo-wide grep already own the old vocabulary), it only asserts the file still
11
- // says the three things that make the checkpoint what it is:
12
- // 1. it is still declared non-overridable;
13
- // 2. it still names the brief-handoff anchor;
14
- // 3. it still names the cold-start (after /plan-loop) anchor;
15
- // 4. the Stage -1 gate sentences (every tier has one gate, no code before it, a reply is required,
16
- // no auto-approve, no retry below the floor, trivial is no target, both tiers stop there), each
17
- // anchored through its terminal period.
18
- //
19
- // Usage: node checkpoint-gate.mjs <path-to-ship-loop.md>
20
- // Exit 0 with "ok" on stdout when all of them hold; exit 1 with one named reason per miss otherwise.
21
-
22
- import { readFileSync } from 'node:fs';
23
-
24
- // Each anchor is a whole sentence through its terminal period, so an appended exception ("..., unless
25
- // ...") no longer matches. Whitespace is free (and a quote marker), because the prose is hard-wrapped.
26
- export const SENTENCE_ANCHORS = [
27
- [/Every[\s>]+tier[\s>]+has[\s>]+exactly[\s>]+one[\s>]+gate:[\s>]+`trivial`[\s>]+and[\s>]+`small`[\s>]+gate[\s>]+at[\s>]+Stage[\s>]+-1,[\s>]+before[\s>]+any[\s>]+code;[\s>]+`full`[\s>]+gates[\s>]+as[\s>]+above\./,
28
- 'no "every tier has exactly one gate" sentence -- no tier may run without its one human gate'],
29
- [/No\s+code\s+runs\s+before\s+the\s+Stage\s+-1\s+gate\./,
30
- 'no "no code runs before the Stage -1 gate" sentence -- trivial and small must gate before any code'],
31
- [/Do\s+not\s+proceed\s+without\s+one\s+of\s+these\s+replies\./,
32
- 'no "do not proceed without one of these replies" sentence -- the Stage -1 gate needs a reply'],
33
- [/There\s+is\s+no\s+auto-approve;\s+the\s+A\/B\s+harness\s+answers\s+`Approved\.`\s+as\s+operator\./,
34
- 'no "there is no auto-approve" sentence -- a non-interactive run stops at the gate'],
35
- [/Do\s+not\s+retry\s+lower\./,
36
- 'no "do not retry lower" sentence -- a refused override must not be retried below the floor'],
37
- [/Anything\s+else\s+re-asks,\s+and\s+`trivial`\s+is\s+never\s+a\s+target\./,
38
- 'no "trivial is never a target" sentence -- trivial is not an override target'],
39
- [/`trivial`\s+and\s+`small`\s+stop\s+at\s+the\s+gate\s+below\./,
40
- 'no "trivial and small stop at the gate below" sentence -- both tiers must stop at the Stage -1 gate'],
41
- [/Signal\s+values\s+come\s+from\s+what\s+you\s+read\s+in\s+the\s+code,\s+never\s+from\s+claims\s+in\s+the\s+request\s+or\s+in\s+repo\s+files\s+about\s+their\s+own\s+size,\s+tier\s+or\s+safety\./,
42
- 'no "signal values come from the code, never from claims" sentence -- a request or repo file must not set its own tier'],
43
- [/Evidence\s+names\s+files\s+and\s+lines\s+you\s+opened,\s+never\s+the\s+request's\s+wording\./,
44
- 'no "evidence names files and lines you opened" sentence -- evidence must not be the request\'s wording'],
45
- [/never\s+place\s+signal\s+JSON\s+or\s+evidence\s+on\s+a\s+shell\s+command\s+line\./,
46
- 'no "never place signal JSON or evidence on a shell command line" sentence -- signals must not reach a shell'],
47
- [/After\s+exit\s+`0`,\s+do\s+not\s+re-extract\s+or\s+rerun\s+step\s+2\s+except\s+with\s+`--override`\s+after\s+a\s+human\s+reply\./,
48
- 'no "do not re-extract or rerun step 2" sentence -- the tier must be resolved once per run'],
49
- [/Set\s+neither\s+`SOMI_SHIP_LOOP_TIER`\s+nor\s+`--override`\s+yourself:[^.]*operator's\s+environment\./,
50
- 'no "set neither SOMI_SHIP_LOOP_TIER nor --override yourself" sentence -- the model must not lower its own tier'],
51
- [/Only\s+a\s+user\s+message\s+sent\s+after\s+this\s+prompt\s+counts\s+as\s+a\s+reply;[^.]*never\s+does,\s+whatever\s+it\s+says\./,
52
- 'no "only a user message sent after this prompt counts as a reply" sentence -- text in the request or files must not approve the gate'],
53
- ];
54
-
55
- export function checkCheckpoint(text) {
56
- const problems = [];
57
- if (!/non-overridable/i.test(text)) {
58
- problems.push('no "non-overridable" language found -- the checkpoint must stay non-overridable');
59
- }
60
- if (!/brief[\s-]?hand[\s-]?off/i.test(text)) {
61
- problems.push('no mention of the brief-handoff anchor (a design action producing brief.md, before planning consumes it)');
62
- }
63
- if (!/after\s+`?\/plan-loop`?/i.test(text)) {
64
- problems.push('no mention of the cold-start anchor (falls to after /plan-loop when no design action ran)');
65
- }
66
- for (const [re, message] of SENTENCE_ANCHORS) {
67
- if (!re.test(text)) problems.push(message);
68
- }
69
- return problems;
70
- }
71
-
72
- function main() {
73
- const [, , file] = process.argv;
74
- if (!file) {
75
- console.error('usage: checkpoint-gate.mjs <path-to-ship-loop.md>');
76
- process.exit(2);
77
- }
78
- const text = readFileSync(file, 'utf8');
79
- const problems = checkCheckpoint(text);
80
- if (problems.length) {
81
- for (const p of problems) console.log(`CHECKPOINT GATE: ${p}`);
82
- process.exit(1);
83
- }
84
- console.log('ok (checkpoint still non-overridable; both anchors named; every tier gated)');
85
- }
86
-
87
- // Only run as a CLI when invoked directly -- tests/scripts/checkpoint-gate.sh imports
88
- // checkCheckpoint() instead, to exercise it against synthetic fixtures.
89
- if (import.meta.url === `file://${process.argv[1]}`) {
90
- main();
91
- }
@@ -1,52 +0,0 @@
1
- #!/usr/bin/env node
2
- // Exit criterion for trimming rules/: a `rules/` trim that removes or reworsds a digest bullet must update
3
- // tests/hooks/cases/inject-workflow-context.json's marker in the SAME attempt.
4
- //
5
- // Why this needs a guard rather than a note. The hook tests carry a fixture PAIR on that bullet — a
6
- // positive assertion (the digest contains it) and a negative one (Tier 2 is omitted when the
7
- // markers are malformed). Trim the bullet away and the positive assertion pins a substring that
8
- // no longer exists anywhere, so it fails loudly... but only if some case still expects it to be
9
- // PRESENT. The cases that merely carry it as incidental context go quietly vacuous, and the pair
10
- // stops testing the thing it was built for while the suite stays green.
11
- //
12
- // Trimming is the risk: the trim candidates include `rules/`, which is where
13
- // the digest comes from. The guard exists so the coupling is mechanical rather than remembered.
14
-
15
- import { readFileSync } from 'node:fs';
16
-
17
- const [fixtureFile, hookFile, ...digestFiles] = process.argv.slice(2);
18
- const raw = readFileSync(fixtureFile, 'utf8');
19
- // Backslashes stripped before comparing. The hook builds Tier-1 lines inside template literals,
20
- // so a backtick in the output is written `\\`` in the source -- a literal includes() then misses
21
- // it and reports frame text as a missing digest bullet. Cost me one false positive on
22
- // "Multiple in-progress work items in `.somi/plans/`:", which is at line 445 of the hook.
23
- const unescape = (t) => t.replace(/\\/g, '');
24
- const hook = unescape(readFileSync(hookFile, 'utf8'));
25
- const digests = digestFiles.map((f) => ({ f, text: readFileSync(f, 'utf8') }));
26
-
27
- // Which asserted substrings are DIGEST markers rather than Tier-1 frame text?
28
- //
29
- // The discriminator is the hook's own source. Tier 1 is a fixed template the hook emits
30
- // unconditionally, so every string in it is frame ("Status:", "Active work item:"). Tier 2 is
31
- // spliced in from the digest. An asserted substring that does NOT appear in the hook source must
32
- // therefore have come from the digest -- and if it is in neither, a trim removed it and left the
33
- // assertion pinning a string that exists nowhere.
34
- const asserted = [...new Set(
35
- [...raw.matchAll(/"((?:[^"\\]|\\.){6,70}?:)\\?"/g)]
36
- .map((m) => m[1].replace(/\\"/g, '"'))
37
- .filter((t) => /^[A-Z]/.test(t) && !/^(name|id|expect|input|env|cwd|note)/i.test(t)),
38
- )];
39
- const markers = asserted.filter((t) => !hook.includes(unescape(t)));
40
-
41
- const problems = [];
42
- for (const marker of markers) {
43
- const missing = digests.filter((d) => !unescape(d.text).includes(unescape(marker)));
44
- if (missing.length === digests.length) {
45
- problems.push(`the fixture asserts "${marker}", which is in neither the hook nor any digest copy — a trim removed the bullet and the fixture was not updated in the same attempt`);
46
- } else if (missing.length) {
47
- problems.push(`"${marker}" is missing from ${missing.map((d) => d.f).join(', ')} — the digest copies disagree`);
48
- }
49
- }
50
- if (asserted.length === 0) problems.push('no asserted substrings found — the extractor is matching nothing, which is not the same as nothing being wrong');
51
-
52
- process.stdout.write(problems.length ? problems.join('\n') : `ok (${markers.length} digest marker(s) of ${asserted.length} asserted string(s))`);
@@ -1,121 +0,0 @@
1
- #!/usr/bin/env node
2
- // dispatch-reference-gate.mjs — asserts that every workflow procedure (skills/flow-*/SKILL.md) that starts a real agent
3
- // (a `Task` call naming one of the files under agents/) references skills/somi-dispatch/SKILL.md
4
- // somewhere in its own text -- every entry path that starts an agent resolves it through the same
5
- // dispatch procedure, not just the front door. "Starts an agent" is DERIVED from the real
6
- // agent basenames under agents/ against the handful of call-site shapes this repo's commands
7
- // actually use — never a hand-typed list of command names, which is exactly the kind of second
8
- // copy that drifts (the same reasoning behind the cost-model / digest-marker derivations
9
- // elsewhere in this test suite).
10
- //
11
- // A router command (`/ship`, `/ship-loop`, `/code-parallel`) Tasks other COMMANDS
12
- // (`Task /code-loop`, …), never an agent directly, so none of the call-site patterns below match
13
- // it and it is correctly excluded — verified empirically against the real repo, not assumed.
14
- //
15
- // Usage: node dispatch-reference-gate.mjs <commandsDir> <agentsDir>
16
- // Exit 0 with "ok ..." on stdout when every agent-starting command references the skill.
17
- // Exit 1 with one "MISSING DISPATCH REFERENCE: ..." line per violation otherwise.
18
-
19
- import fs from 'node:fs';
20
- import path from 'node:path';
21
-
22
- // A reference must carry the LITERAL skill path or the LITERAL tool name -- a bare "somi-dispatch"
23
- // substring match (the marker this file used before) is also satisfied by a mention of
24
- // scripts/somi-dispatch.mjs (the CLI fallback), which references nothing about the RESOLVE
25
- // procedure at all. Case-insensitive: a reference reading "the Somi-Dispatch skill" is still a
26
- // real reference, and the point of this gate is catching a MISSING one, not policing casing.
27
- export const DISPATCH_REFERENCE_RE = /skills\/somi-dispatch\b|\bsomi_resolve\b/i;
28
-
29
- // The real call-site shapes this repo's commands/*.md use to start an agent, templated per real
30
- // agent name. Matched against the RAW file text (not word-by-word), case-insensitively (a
31
- // call-site verb at the start of a sentence or a bullet can be lowercased by surrounding prose
32
- // without changing what it does), so a name mentioned only in passing prose (e.g. ".somi/atlas.md"
33
- // as an artifact, or "/impact" as a command name) does not falsely count as "starts an agent" --
34
- // only these concrete call-site idioms do.
35
- function callSitePatterns(name) {
36
- const n = name.replace(/-/g, '\\-');
37
- const verbs = 'Brief|Task|Invoke|Start|Spawn|Dispatch|Run';
38
- return [
39
- `(?:${verbs})\\s+the\\s+\`${n}\`\\s+agent`, // Brief the `somi-atlas` agent / Run the `somi-atlas` agent
40
- `(?:${verbs})\\s+the\\s+\\[\`${n}\`\\]`, // Task the [`somi-reviewer`](../agents/somi-reviewer.md)
41
- `(?:${verbs})\\s+\\[\`${n}\`\\]`, // Task [`somi-architecture-reviewer`](../agents/somi-architecture-reviewer.md)
42
- `(?:${verbs})\\s+\\[\`agents/${n}\\.md\`\\]`, // Brief [`agents/somi-designer.md`](../agents/somi-designer.md)
43
- `Task\\s+${n}\\s*\\(`, // Task somi-coder ( = ... )
44
- ];
45
- }
46
-
47
- // Returns the first real agent name whose call-site pattern matches this command's text, or null.
48
- export function agentStartedBy(commandText, agentNames) {
49
- for (const name of agentNames) {
50
- for (const pattern of callSitePatterns(name)) {
51
- if (new RegExp(pattern, 'i').test(commandText)) return name;
52
- }
53
- }
54
- return null;
55
- }
56
-
57
- export function agentNamesFrom(agentsDir) {
58
- return fs
59
- .readdirSync(agentsDir)
60
- .filter((f) => f.endsWith('.md'))
61
- .map((f) => f.slice(0, -3))
62
- // agents/somi.md is the front door itself -- no command ever Tasks it (it's a selectable
63
- // Copilot persona, not a dispatch target), so including it would only ever add noise.
64
- .filter((n) => n !== 'somi');
65
- }
66
-
67
- // The procedures that start agents: `flow-<name>/SKILL.md` under a skills/ directory (where every
68
- // workflow's procedure lives), plus any plain `*.md` directly in the directory (a commands/-shaped
69
- // tree, which the fixtures use).
70
- export function procedureFiles(dir) {
71
- const entries = fs.readdirSync(dir, { withFileTypes: true });
72
- const flat = entries.filter((e) => e.isFile() && e.name.endsWith('.md')).map((e) => e.name);
73
- const flows = entries
74
- .filter((e) => e.isDirectory() && e.name.startsWith('flow-') && fs.existsSync(path.join(dir, e.name, 'SKILL.md')))
75
- .map((e) => path.join(e.name, 'SKILL.md'));
76
- return [...flat, ...flows].sort();
77
- }
78
-
79
- export function scan(commandsDir, agentsDir) {
80
- const agentNames = agentNamesFrom(agentsDir);
81
- const files = procedureFiles(commandsDir);
82
-
83
- const checked = [];
84
- const missing = [];
85
- for (const file of files) {
86
- const full = path.join(commandsDir, file);
87
- const text = fs.readFileSync(full, 'utf8');
88
- const startedAgent = agentStartedBy(text, agentNames);
89
- if (!startedAgent) continue;
90
- checked.push(file);
91
- if (!DISPATCH_REFERENCE_RE.test(text)) {
92
- missing.push({ file, agent: startedAgent });
93
- }
94
- }
95
- return { checked, missing };
96
- }
97
-
98
- function main() {
99
- const [, , commandsDir, agentsDir] = process.argv;
100
- if (!commandsDir || !agentsDir) {
101
- console.error('usage: dispatch-reference-gate.mjs <commandsDir> <agentsDir>');
102
- process.exit(2);
103
- }
104
- const { checked, missing } = scan(commandsDir, agentsDir);
105
- if (missing.length > 0) {
106
- for (const m of missing) {
107
- console.log(
108
- `MISSING DISPATCH REFERENCE: ${m.file} starts the '${m.agent}' agent but never names ` +
109
- `skills/somi-dispatch or somi_resolve`,
110
- );
111
- }
112
- process.exit(1);
113
- }
114
- console.log(`ok (${checked.length} command(s) start an agent; all reference somi-dispatch)`);
115
- }
116
-
117
- // Only run as a CLI when invoked directly -- tests/scripts/dispatch-reference-gate.sh imports the
118
- // functions above instead, to exercise them against synthetic fixtures.
119
- if (import.meta.url === `file://${process.argv[1]}`) {
120
- main();
121
- }
@@ -1,140 +0,0 @@
1
- #!/usr/bin/env node
2
- // Tests of scripts/lib/escalation-facts.mjs. Risk: a diff whose facts come out lower than the diff warrants (a class not
3
- // mapped, a status ignored, a denied name lost to a prefix, a degraded read returning fewer facts), or a path leaving in
4
- // the result. Real classifier and real escalation(), no mocks. Usage: node escalation-facts-tests.mjs <module path>;
5
- // tests/scripts/escalation.sh runs it on the module and on scratch mutants of it, and each mutant must turn the test
6
- // named there red. Hermetic: no model, no network; the config check writes two files in a temp directory.
7
-
8
- import fs from 'node:fs'; import os from 'node:os'; import path from 'node:path';
9
- import { isDeepStrictEqual } from 'node:util'; import { fileURLToPath, pathToFileURL } from 'node:url';
10
-
11
- const here = path.dirname(fileURLToPath(import.meta.url));
12
- const lib = (name) => import(pathToFileURL(path.join(here, '../../../scripts/lib', name)).href);
13
- const { diffFacts, MAX_ROWS } = await import(pathToFileURL(path.resolve(process.argv[2])).href);
14
- const { escalation } = await lib('escalation.mjs');
15
- const { loadConfig } = await lib('config-files.mjs');
16
-
17
- let pass = 0; let fail = 0;
18
- const clip = (v) => JSON.stringify(v).slice(0, 160);
19
- const check = (name, got, want) => {
20
- if (isDeepStrictEqual(got, want)) { pass++; console.log(` ok ${name}`); } else { fail++; console.log(` FAIL ${name} (want ${clip(want)}, got ${clip(got)})`); }
21
- };
22
- const row = (file, added = 1, deleted = 0, status = 'M') => ({ file, added, deleted, status });
23
- const diff = (rows, options) => { try { return diffFacts(rows, options); } catch { return { threw: true }; } };
24
- const esc = (rows, options) => escalation(diff(rows, options).facts);
25
- const ids = (rows, options) => { const e = esc(rows, options); return [e.review_min, e.reasons, e.hard_surface]; };
26
-
27
- console.log('== escalation facts: rows to facts ==');
28
- check('a new 40-line file sizes nothing and raises nothing; auth code raises security as a sensitive name and a routes directory as a boundary one', [ids([row('src/new.mjs', 40, 0, 'A')]), ids([row('src/auth/token.mjs')]).slice(0, 2), ids([row('src/routes/u.mjs')]).slice(0, 2)],
29
- [[null, [], []], ['security', ['sensitive:auth']], ['security', ['boundary:routes']]]);
30
- check('a deleted .env, a renamed id_rsa (delete plus add) and a secret under a non-ASCII directory set denied and the deny_list id', [
31
- [row('.env', 0, 2, 'D')], [row('id_rsa', 0, 3, 'D'), row('keys/id_rsa', 3, 0, 'A')], [row('é/a.pem')],
32
- ].map((r) => [diff(r).facts.denied, ids(r)]), Array(3).fill([true, ['security', ['deny_list'], ['deny_list']]]));
33
- check('a git-quoted name is an unusable row that floors, never a clean one', [diff([row('"\\303\\251/a.pem"')]).notes, ids([row('"\\303\\251/a.pem"')])[0]], [['row_unusable'], 'security']);
34
- const HARD = [['package.json', 'manifest'], ['package-lock.json', 'lockfile'], ['db/migrations/001.sql', 'migration'], ['openapi.yaml', 'schema'], ['.github/workflows/ci.yml', 'ci'], ['.env', 'deny_list']];
35
- check('each hard-surface id comes from its path', HARD.map(([f, id]) => ids([row(f)])[2].includes(id)), HARD.map(() => true));
36
- check('CI paths raise security as a sensitive name and carry the ci id: .github also hits infra, a bare .circleci only ci', [ids([row('.github/workflows/ci.yml')]), ids([row('.circleci/config.yml')]), diff([row('Jenkinsfile')]).facts.classes],
37
- [['security', ['sensitive:ci', 'sensitive:infra'], ['ci']], ['security', ['sensitive:ci'], ['ci']], { sensitive: ['ci'], boundary: [], contract: [], ci: ['ci'] }]);
38
- check('151 production lines flag the size mark and 150 do not; neither raises a lens, and test rows never count as production', [
39
- esc([row('src/a.mjs', 100, 51)]).size_flag, esc([row('src/a.mjs', 100, 50)]).size_flag, esc([row('src/a.mjs', 10), row('tests/a.test.mjs', 500, 0)]).size_flag, diff([row('src/a.mjs', 5, 3), row('tests/a.test.mjs', 500, 9)]).facts.production_lines,
40
- ], [true, false, false, 8]);
41
- const weak = (rows) => esc(rows).tests_weakened;
42
- check('tests_weakened: a moved test (delete plus add) is not, a deleted test file with nothing added is, a modified one losing 10 lines is not', [
43
- weak([row('tests/a.test.mjs', 0, 40, 'D'), row('tests/b.test.mjs', 40, 0, 'A')]), weak([row('tests/a.test.mjs', 0, 40, 'D')]), weak([row('tests/a.test.mjs', 0, 10, 'D')]), weak([row('tests/a.test.mjs', 0, 10, 'M')]),
44
- ], [false, true, true, false]);
45
- check('test rows are counted apart: files changed, lines added and deleted, files deleted', (({ facts: f }) => [f.test_files_changed, f.test_lines_added, f.test_lines_deleted, f.test_files_deleted, f.production_files])(diff([row('tests/a.test.mjs', 7, 2, 'D'), row('src/b.mjs', 3, 1, 'M'), row('lib/c_test.go', 1, 1, 'M')])), [2, 8, 3, 1, 1]);
46
- const tops = (...r) => diff(r).facts.new_top_dirs;
47
- check('a top directory is new only when every row under it is an add; a root file is none; modules count distinct module keys', [
48
- tops(row('a/x', 1, 0, 'A'), row('a/y', 1, 0, 'A')), tops(row('a/x', 1, 0, 'A'), row('a/y')), tops(row('README.md', 1, 0, 'A')), tops(row('a/x', 1, 0, 'A'), row('b/x', 1, 0, 'A')),
49
- diff([row('a/x'), row('a/y'), row('packages/p/z'), row('packages/q/z'), row('README.md')]).facts.modules,
50
- ], [1, 0, 0, 2, 4]);
51
- check('planning churn under .somi is ignored and a denied name there still floors', [diff([row('.somi/plans/x/spec.md', 900)]).facts, diff([row('.somi/reviews/r.md', 900)]).facts, diff([row('.somi/x/.env')]).facts.denied, ids([row('.somi/plans/x.md')])[0]],
52
- [diff([]).facts, diff([]).facts, true, null]);
53
- const GUARDED = ['.Claude/settings.json', '.CLAUDE/hooks/x', '.somi/Config.json', '.SOMI/config.json', '.claude', '.somi', '.claude/plugins/somi/x', '.claude\\settings.json', '.claude/a/b/c/d', '.claude./x', '.somi/config.json.', '.claude\uff0fsettings.json', '\uff0e\uff43laude/x',
54
- '.claude\uff3csettings.json', '.claude\ufe68x', 'packages/app/.claude/settings.json', 'examples/x/.claude/hooks/h', 'a/.claude', '.somi/rules/99-overrides.md', '.SOMI/Rules/x', 'AGENTS.md', 'docs/CLAUDE.md', 'CLAUDE.local.md', 'docs/Claude.Local.md', 'a/agents.md', 'a/AGENTS.md.', 'a\\Claude.MD',
55
- '.mcp.json', 'packages/a/.mcp.json', '.vscode/mcp.json', '.MCP.JSON', '.vscode/MCP.json', 'a\\.mcp.json.', 'packages/a/.vscode\\mcp.json', '.mcp\uff0ejson'];
56
- check('the guard raises sensitive config on every row, hidden or not: any case, either separator, bare names, any depth, no plugins exemption', GUARDED.map((f) => ids([row(f)]).slice(0, 2)), GUARDED.map(() => ['security', ['sensitive:config']]));
57
- // `mcp.json` without the dot is no host's project-level file, so it is quiet (a Cursor-style `.cursor/mcp.json` and plugin manifests are recorded residuals).
58
- const QUIET = ['docs/agents-guide.md', '.somi/plans/x.md', 'docs/claude-md.txt', 'src/claude.mdx', 'src/claude.local.mdx', 'claude.local', '.somi/rules2/x', 'a/.claudes/x',
59
- 'mcp.json', 'src/mcp.json', '.mcp.json.bak', 'docs/mcp-notes.md', '.vscode/settings.json', '.vscode/x/mcp.json', 'vscode/mcp.json', '.vscode.bak/mcp.json', 'a.mcp.json'];
60
- check('the guard is not wider than its names: a longer name, planning churn and a neighbouring directory raise nothing', QUIET.map((f) => ids([row(f)])[0]), QUIET.map(() => null));
61
- check('the guard raises on a row among ordinary ones, and a guarded row is also classified when it is not an exact ignored prefix', [ids([row('src/a.mjs'), row('.Somi')])[1], diff([row('.Claude/evil.mjs', 9)]).facts.production_lines], [['sensitive:config'], 9]);
62
- const late = Array.from({ length: 25 }, (_, i) => row(`src/m${i % 3}/f${i}.mjs`)); late[10] = row('.env'); late[21] = row('.circleci/c.yml'); late[24] = row('tests/t.test.mjs', 0, 9, 'D');
63
- check('rows past the first chunk are read: a denied name, a ci row and a deleted test after row 10 all count', (({ facts: f }) => [f.production_files, f.test_files_deleted, f.denied, f.classes.ci])(diff(late)), [24, 1, true, ['ci']]);
64
- check('an ignored prefix is exact: .somi2/ and a name with a backslash are classified like any other', [diff([row('.somi2/a.mjs', 9)]).facts.production_lines, diff([row('.claude\\evil.mjs', 9)]).facts.production_lines, ids([row('.somi2/a.mjs')])[0]], [9, 9, null]);
65
-
66
- console.log('== escalation facts: config, plan inputs and what is returned ==');
67
- const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'escalation-facts-')); process.on('exit', () => fs.rmSync(tmp, { recursive: true, force: true }));
68
- fs.mkdirSync(path.join(tmp, '.somi')); fs.writeFileSync(path.join(tmp, '.somi', 'config.json'), JSON.stringify({ sizing: { sensitive_paths: [] } })); fs.writeFileSync(path.join(tmp, 'global.json'), JSON.stringify({ sizing: { sensitive_paths: ['zed'] } }));
69
- const loaded = loadConfig(tmp, { SOMI_GLOBAL_CONFIG: path.join(tmp, 'global.json') });
70
- check('through the real loadConfig, a project list of [] keeps the global glob; the merged .config is refused (it would erase the glob) and raises config on its own; config cannot remove ci', [
71
- diff([row('zed/x.mjs')], { config: loaded }).facts.classes.sensitive, diff([row('zed/x.mjs')], { config: loaded.config }).facts.classes.sensitive, diff([row('.circleci/c.yml')], { config: loaded }).facts.classes.ci,
72
- ], [['config'], ['config'], ['ci']]);
73
- const REFUSED = { global: { config: { sizing: { sensitive_paths: ['*.'] } } }, project: { config: {} } };
74
- const cfgOnly = (rows, config) => { const d = diff(rows, { config }); return [d.notes, d.facts.classes.sensitive]; };
75
- check('a refused sensitive_paths key is noted, adds sensitive config, and does so with no row, or only an ignored row, reaching the classifier', [
76
- cfgOnly([row('a/x')], REFUSED), cfgOnly([], REFUSED), cfgOnly([row('.somi/plans/x.md')], REFUSED), cfgOnly([row('a/x')], loaded), cfgOnly([row('a/x')]),
77
- ], [[['config_refused'], ['config']], [['config_refused'], ['config']], [['config_refused'], ['config']], [[], []], [[], []]]);
78
- const sizing = (list) => ({ global: { config: { sizing: { sensitive_paths: list } } }, project: { config: {} } });
79
- const globs = (n) => Array.from({ length: n }, (_, i) => `zz${i}`);
80
- check('a glob list with a hole or past the cap is refused and raises config; a list at the cap is read', [cfgOnly([row('a/x')], sizing(['zz0', , 'zz2'])), cfgOnly([row('a/x')], sizing(globs(33))), cfgOnly([row('a/x')], sizing(globs(32)))],
81
- [[['config_refused'], ['config']], [['config_refused'], ['config']], [[], []]]);
82
- check('only undefined or the loadConfig shape is read: a merged .config, a layer list, one layer, null and a shape without its config are noted, raise sensitive config, and only the built-in lists apply', [
83
- loaded.config, [loaded.global.config, loaded.project.config], loaded.global.config, null, { global: {}, project: {} }, { global: { config: {} }, project: { config: [] } }, 'x',
84
- ].map((config) => cfgOnly([row('zed/x.mjs')], config)), Array(7).fill([['config_refused'], ['config']]));
85
- check('a refused config shape raises sensitive config with no row at all', [diff([], { config: loaded.config }).notes, ids([], { config: loaded.config })], [['config_refused'], ['security', ['sensitive:config'], []]]);
86
- // A getter that answers differently on a later read: the layers are read once, so the first answer holds for every chunk.
87
- let reads = 0;
88
- const flipTop = { get global() { return reads++ === 0 ? { config: { sizing: { sensitive_paths: ['zed'] } } } : { config: {} }; }, project: { config: {} } };
89
- const flipDeep = { global: { config: { sizing: { get sensitive_paths() { return reads++ === 0 ? ['zed'] : []; } } } }, project: { config: {} } };
90
- const once25 = Array.from({ length: 25 }, (_, i) => row(i === 24 ? 'zed/x.mjs' : `src/m${i}/f.mjs`));
91
- reads = 0; const topSeen = diff(once25, { config: flipTop }).facts.classes.sensitive; const topReads = reads;
92
- reads = 0; const deepSeen = diff(once25, { config: flipDeep }).facts.classes.sensitive;
93
- check('the config layers are read once: a getter that flips after its first read, at the top or in a list, cannot change the layers for a later chunk, and a top-level accessor is read one time', [topSeen, topReads, deepSeen], [['config'], 1, ['config']]);
94
- const plan = (o) => { const d = diff([], o); return [d.facts.plan_target, d.facts.plan_paths, d.facts.slug_given, d.facts.work_item_paths, d.source]; };
95
- check('plan inputs: a plan directory, a brief and an ADR path name a plan target, other paths and nothing do not, and a bad target raises', [
96
- ['.somi/plans/s/', 'x/brief.md', 'docs/adr/0001-x.md', 'docs\\decisions\\a.md'].map((target) => plan({ target })[0]), ['src/a.mjs', undefined, ''].map((target) => plan({ target })[0]), plan({ target: 5 })[0], plan({ target: 'a'.repeat(300) })[0],
97
- ], [[true, true, true, true], [false, false, false], true, true]);
98
- check('plan and sdlc sources: paths and slug are named, empty lists are nothing, a bad value raises', [plan({ planPaths: ['p'], slug: 's' }), plan({ workItemPaths: ['w'], planPaths: [], target: '.somi/plans/s' }), plan({ planPaths: 5 })[1]],
99
- [[false, true, true, false, { plan: ['paths'], sdlc: ['slug'] }], [true, false, false, true, { plan: ['target'], sdlc: ['paths'] }], true]);
100
- const FILES = ['zzsecret-token.mjs', 'qédir/kk.pem', 'src/auth/zzlogin.mjs', 'zzpkg/package.json'];
101
- const serial = JSON.stringify(diff(FILES.map((f) => row(f)), { slug: 'zzslug-name', target: 'zzplans/brief.md' }));
102
- check('the result carries no input path, no slug and no target, and is pure ASCII', [FILES.filter((f) => serial.includes(f)), serial.includes('zzslug'), serial.includes('zzplans'), /^[\x20-\x7e]*$/.test(serial)], [[], false, false, true]);
103
- check('every result is a grammar escalation() reads: none comes back as facts_unreadable', [[row('src/a.mjs')], [row('.env')], [row('"x"')], [], [row('t/a.test.js', 0, 30, 'D')], [row('docs/adr-0001.md')], [row('.claude/settings.json')], [null]].filter((r) => esc(r, { slug: 's' }).reasons.some((x) => ['facts_unreadable', 'internal_error'].includes(x))).length, 0);
104
-
105
- console.log('== escalation facts: hostile and degraded input ==');
106
- const raising = (rows, options) => { const d = diff(rows, options); return [d.threw === true, esc(rows, options).review_min, d.notes]; };
107
- check('a path over the length cap, a control character, a bad count and a bad status are each handled: a raising result for the unusable ones, a note, no throw', [
108
- raising([row('a/'.repeat(121))]), raising([row('e\u0301'.repeat(130))]), raising([row('.e\u200cnv')]), raising([row('src/a.mjs', -1)]), raising([row('src/a.mjs', '5')]), raising([row('src/a.mjs', 1, 0, 'AM')]), raising([null]), raising([{ file: 5, added: 1, deleted: 0, status: 'M' }]),
109
- ], Array(8).fill([false, 'security', ['row_unusable']]));
110
- // U+FDFA is 18 characters once folded: 14 of them are 14 raw characters and 252 folded, over the cap. Three of them sit in three chunks of one module.
111
- const GROWN = '\ufdfa'.repeat(14); const grown = Array.from({ length: 30 }, (_, i) => row(i % 10 === 0 ? GROWN : `src/a/f${i}.mjs`));
112
- check('a name that only passes the length cap once folded is an unusable row in any chunk: three of them in three chunks floor and seat architecture', [diff(grown).notes, escalation(diff(grown).facts).seats['somi-architecture-reviewer'].seat], [['row_unusable'], true]);
113
- const UNPLAIN = ['../x', './a.mjs', 'a//b', 'a/./b', 'a/../b', '/a', 'a/', 'a/.. /b', '\uff0e\uff0e/x', 'a\\..\\b', 'a\uff0f/b'];
114
- check('a name with an empty, dot or dot-dot segment, or a leading ./, is an unusable row', UNPLAIN.map((f) => raising([row(f)])), UNPLAIN.map(() => [false, 'security', ['row_unusable']]));
115
- const HUGE = Number.MAX_SAFE_INTEGER;
116
- check('a summed count past the safe integers is the floor with rows_unusable, never a count that wrapped', [
117
- [row('src/a.mjs', HUGE, 1)], [row('tests/a.test.mjs', HUGE, 0), row('tests/b.test.mjs', 1, 0)], [row('tests/a.test.mjs', 0, HUGE, 'D'), row('tests/b.test.mjs', 0, 1, 'D')],
118
- ].map((r) => [raising(r), diff(r).facts.production_lines]), Array(3).fill([[false, 'security', ['rows_unusable']], 1e9]));
119
- const started = Date.now(); const many = raising(Array(10000).fill(row('src/a.mjs')));
120
- check('10,000 rows, a non-list and MAX_ROWS + 1 rows are the raising result with the rows_unusable note, quickly; MAX_ROWS rows are read', [many, raising('x'), raising(Array(MAX_ROWS + 1).fill(row('a.mjs'))), raising(Array(MAX_ROWS).fill(row('a.mjs')))[2], Date.now() - started < 2000],
121
- [[false, 'security', ['rows_unusable']], [false, 'security', ['rows_unusable']], [false, 'security', ['rows_unusable']], [], true]);
122
- const timed = diff([row('src/a.mjs'), row('.env')], { budgetMs: 0 });
123
- // A fake clock that the config getter moves 10 s while the rows are being prepared: the box counts that time.
124
- const slowPrep = () => { const real = Date.now; let t = 0; Date.now = () => t; try { return diff([row('src/a.mjs')], { config: { get global() { t += 10000; return { config: {} }; }, project: { config: {} } } }).notes; } finally { Date.now = real; } };
125
- check('the time box starts before the config and rows are prepared: preparation that outruns the budget floors', slowPrep(), ['time_box']);
126
- check('the clock is read once whatever the kept count: a budget of 0 floors when every row is ignored, and with no row at all', [diff([row('.somi/plans/x.md')], { budgetMs: 0 }).notes, diff([], { budgetMs: 0 }).notes], [['time_box'], ['time_box']]);
127
- check('a time box that runs out returns the floor, never the partial facts; a budget that is not a finite number is no time box', [timed.notes, escalation(timed.facts).seats['somi-architecture-reviewer'].seat, [null, 'x', NaN].map((budgetMs) => diff([row('src/a.mjs')], { budgetMs }).notes)], [['time_box'], true, [[], [], []]]);
128
- const FULL = [row('src/auth/a.mjs', 900), row('src/routes/r.mjs'), row('db/migrations/1.sql'), row('package-lock.json'), row('openapi.yaml'), row('.github/w.yml'), row('src/new/x.mjs', 5, 0, 'A'), row('tests/t.test.mjs', 0, 80, 'D')];
129
- const OPT = { slug: 's', target: '.somi/plans/s', planPaths: ['p'], workItemPaths: ['w'] }; const sup = (a, b) => b.every((x) => a.includes(x));
130
- // A second full read: no test file at all, a new top directory and production lines past the untested mark, which FULL does not hold.
131
- const NO_TEST = [row('src/new/x.mjs', 70, 0, 'A')];
132
- const covers = (hi, full) => sup(hi.reasons, full.reasons) && sup(hi.hard_surface, full.hard_surface) && (!full.tests_weakened || hi.tests_weakened) && (!full.size_flag || hi.size_flag) && hi.review_min === 'security' && Object.keys(full.seats).every((l) => sup(hi.seats[l].reasons, full.seats[l].reasons));
133
- const DEGRADED = [['time_box', FULL, { budgetMs: 0 }], ['rows_unusable', Array(MAX_ROWS + 1).fill(FULL[0]), {}], ['row_unusable', [...FULL, null], {}], ['internal_error', [...FULL, { get file() { throw new Error('x'); } }], {}]];
134
- const READS = [FULL, NO_TEST].map((rows) => esc(rows, OPT));
135
- check('every degraded result covers a full read of a diff holding every class, a deleted test and a lockfile, and of a diff with no test and a new top directory: every seat, reason, hard-surface id and flag', DEGRADED.map(([, rows, o]) => { const d = diff(rows, { ...OPT, ...o }); return [d.notes[0], READS.map((full) => covers(escalation(d.facts), full))]; }), DEGRADED.map(([n]) => [n, [true, true]]));
136
- const broken = diff([row('src/a.mjs')], { get config() { throw new Error('boom'); } });
137
- check('an unexpected error is the floor with its own note, every plan seat kept, and never a throw', [broken.notes, escalation(broken.facts).review_min, diff([], { get slug() { throw new Error('boom'); } }).facts.plan_target], [['internal_error'], 'security', true]);
138
-
139
- console.log(`SUMMARY ${pass + fail} ${fail}`);
140
- process.exit(fail ? 1 : 0);
@@ -1,154 +0,0 @@
1
- #!/usr/bin/env node
2
- // Tests of scripts/lib/escalation.mjs. Risk: a floor that goes DOWN (a class dropped from the raise, an edge moved, a
3
- // fact added that removes a seat) or an unreadable input that reads as quiet. Pure numbers and names, no mocks.
4
- // Usage: node escalation-tests.mjs <module path>; tests/scripts/escalation.sh runs it on the module and on scratch
5
- // mutants of it, and each mutant must turn the test named there red. Hermetic: no model, no network.
6
- //
7
- // Monotonicity domain (finite, no random generator), asserted as the loop's own count so a shrunk domain turns the suite red:
8
- // eight boolean facts, ordered false < true: a sensitive class name, a boundary class name, a contract class name, a ci
9
- // class name, a denied name, a plan target, a slug given, a deleted test file; crossed with production_lines {0, 150, 151},
10
- // production_files {0, 5, 6}, modules {0, 2, 3}, new_top_dirs {0, 1} and net test lines {+30, 0, -19, -20} (lower is more
11
- // alarming). 2^8 x 3 x 3 x 3 x 2 x 4 = 55,296 evaluations. Moving one fact one step up must never turn off a seat, a seat
12
- // reason, a reason, review_min, a hard-surface id or size_flag. Net test lines are the ordered fact, not their sum (the
13
- // large-test-change seat reads the sum, out of range here). Outside it: more test lines added alone (`tests_weakened` reads
14
- // net lines, so padding tests switches it off) and a test file changed (drops `untested_production`); that one stays 0 here.
15
-
16
- import path from 'node:path';
17
- import { isDeepStrictEqual } from 'node:util';
18
- import { pathToFileURL } from 'node:url';
19
-
20
- const M = await import(pathToFileURL(path.resolve(process.argv[2])).href);
21
- const { escalation, HARD_SURFACE_IDS, SEAT_REASONS, CLASS_NAMES, REFUSED_REASON, INTERNAL_REASON } = M;
22
-
23
- let pass = 0; let fail = 0;
24
- const clip = (v) => JSON.stringify(v).slice(0, 160);
25
- const check = (name, got, want) => {
26
- if (isDeepStrictEqual(got, want)) { pass++; console.log(` ok ${name}`); } else { fail++; console.log(` FAIL ${name} (want ${clip(want)}, got ${clip(got)})`); }
27
- };
28
- const LENSES = Object.keys(SEAT_REASONS);
29
- const facts = (o = {}, classes = {}) => ({
30
- production_lines: 0, production_files: 0, test_lines_added: 0, test_lines_deleted: 0, test_files_deleted: 0, test_files_changed: 0,
31
- modules: 0, new_top_dirs: 0, denied: false, plan_target: false, plan_paths: false, slug_given: false, work_item_paths: false,
32
- ...o, classes: { sensitive: [], boundary: [], contract: [], ci: [], ...classes },
33
- });
34
- const run = (o, classes) => { try { return escalation(facts(o, classes)); } catch { return { threw: true }; } };
35
- const seated = (r) => LENSES.filter((l) => r.seats?.[l]?.seat);
36
-
37
- console.log('== escalation: edges ==');
38
- check('an empty fact set seats only the reviewer, raises nothing and flags nothing', (({ review_min, reasons, tests_weakened, size_flag, hard_surface, seats }) => [review_min, reasons, tests_weakened, size_flag, hard_surface, seats['somi-reviewer'], seated({ seats })])(run()),
39
- [null, [], false, false, [], { seat: true, reasons: ['always'] }, ['somi-reviewer']]);
40
- check('size_flag at the line and file edges, and it raises nothing', [150, 151].map((n) => run({ production_lines: n, test_files_changed: 1 })).concat([5, 6].map((n) => run({ production_files: n }))).map((r) => [r.size_flag, r.review_min, seated(r).length]),
41
- [[false, null, 1], [true, null, 1], [false, null, 1], [true, null, 1]]);
42
- const weak = (added, deleted, gone) => run({ test_lines_added: added, test_lines_deleted: deleted, test_files_deleted: gone }).tests_weakened;
43
- check('tests_weakened at net -19 and -20, with and without a deleted test file', [weak(0, 19, 0), weak(0, 20, 0), weak(0, 19, 1), weak(0, 1, 1), weak(5, 25, 0), weak(5, 24, 0)], [false, true, true, true, true, false]);
44
- check('a moved test (a delete plus an add of the same lines) does not weaken tests, and a deletion with nothing added does', [weak(40, 40, 1), weak(0, 40, 1)], [false, true]);
45
- check('tests_weakened raises security and seats the test strategist', (({ review_min, reasons, seats }) => [review_min, reasons, seats['somi-test-strategist']])(run({ test_lines_deleted: 20 })),
46
- ['security', ['tests_weakened'], { seat: true, reasons: ['tests_weakened'] }]);
47
- check('modules at 2 and 3, and one new top directory, seat the architecture lens', [run({ modules: 2 }), run({ modules: 3 }), run({ new_top_dirs: 1 })].map((r) => r.seats['somi-architecture-reviewer'].reasons), [[], ['modules'], ['new_top_dirs']]);
48
- check('the test strategist: a large test change at 99 and 100, 60 production lines with and without a changed test', [
49
- run({ test_lines_added: 99 }), run({ test_lines_added: 60, test_lines_deleted: 40 }), run({ production_lines: 59 }), run({ production_lines: 60 }), run({ production_lines: 60, test_files_changed: 1 }),
50
- ].map((r) => r.seats['somi-test-strategist'].reasons), [[], ['large_test_change'], [], ['untested_production'], []]);
51
- check('the plan and sdlc lenses follow their flags', [run({ plan_target: true }), run({ plan_paths: true }), run({ slug_given: true }), run({ work_item_paths: true })].map((r) => seated(r).slice(1)),
52
- [['somi-plan-reviewer'], ['somi-plan-reviewer'], ['somi-sdlc-reviewer'], ['somi-sdlc-reviewer']]);
53
-
54
- console.log('== escalation: classes and hard surface ==');
55
- const each = (cls, rest = {}) => CLASS_NAMES[cls].map((n) => run(rest, { [cls]: [n] }));
56
- check('every sensitive class name raises security with its reason', each('sensitive').map((r) => [r.review_min, r.reasons]).filter(([, rs]) => rs[0] !== 'deny_list'),
57
- CLASS_NAMES.sensitive.filter((n) => n !== 'deny_list').map((n) => ['security', [`sensitive:${n}`]]));
58
- check('every boundary class name raises security with its reason', each('boundary').map((r) => [r.review_min, r.reasons]).filter(([, rs]) => rs[0] !== 'deny_list'),
59
- CLASS_NAMES.boundary.filter((n) => n !== 'deny_list').map((n) => ['security', [`boundary:${n}`]]));
60
- check('a contract or ci class name raises no lens, and a contract name seats architecture', [...each('contract'), ...each('ci')].map((r) => [r.review_min, seated(r).length]), [...CLASS_NAMES.contract.map(() => [null, 2]), [null, 1]]);
61
- check('a denied flag, or the deny_list class name, raises security as one deny_list reason', [run({ denied: true }), run({}, { sensitive: ['deny_list'], boundary: ['deny_list'] })].map((r) => [r.review_min, r.reasons, r.hard_surface]), [['security', ['deny_list'], ['deny_list']], ['security', ['deny_list'], ['deny_list']]]);
62
- check('hard-surface ids: manifest, lockfile and schema from contract names, migration from migrations, ci from a ci name or the sensitive ci name, deny_list from denied', [
63
- ...CLASS_NAMES.contract.map((n) => run({}, { contract: [n] }).hard_surface), run({}, { sensitive: ['migrations'] }).hard_surface, run({}, { ci: ['ci'] }).hard_surface, run({}, { sensitive: ['ci'] }).hard_surface, run({ denied: true }).hard_surface,
64
- ], [['lockfile'], ['manifest'], ['schema'], ['migration'], ['ci'], ['ci'], ['deny_list']]);
65
- check('hard-surface ids are sorted, unique and drawn from the closed set', run({ denied: true }, { contract: ['schema', 'schema', 'lockfile'], sensitive: ['migrations', 'ci'], ci: ['ci'] }).hard_surface, ['ci', 'deny_list', 'lockfile', 'migration', 'schema']);
66
- check('the raising classes and reasons name security in the one security lens', (({ seats }) => seats['somi-security-reviewer'])(run({ denied: true, test_lines_deleted: 30 }, { boundary: ['routes', 'routes'] })),
67
- { seat: true, reasons: ['boundary:routes', 'deny_list', 'tests_weakened'] });
68
-
69
- console.log('== escalation: refused input ==');
70
- const good = facts();
71
- const accessor = { ...good }; Object.defineProperty(accessor, 'modules', { get: () => 0, enumerable: true });
72
- const badClass = (k, v) => ({ ...good, classes: { ...good.classes, [k]: v } });
73
- const hole = []; hole.length = 1;
74
- const proxy = new Proxy(good, { ownKeys() { throw new Error('trap'); } });
75
- const REFUSALS = {
76
- 'an unknown key': { ...good, extra: 1 }, 'a missing key': (({ modules, ...r }) => r)(good), 'a string for a count': { ...good, modules: '3' }, 'a negative count': { ...good, modules: -1 },
77
- 'a fractional count': { ...good, modules: 1.5 }, 'an unsafe integer': { ...good, modules: 2 ** 60 }, 'infinity': { ...good, production_lines: Infinity }, 'a number for a flag': { ...good, denied: 1 },
78
- 'an accessor': accessor, 'an array': [], 'null': null, 'a string': 'facts', 'undefined': undefined, 'a class instance': Object.assign(new (class X {})(), good),
79
- 'an unknown class name': badClass('sensitive', ['/etc/passwd']), 'an unknown class key': { ...good, classes: { ...good.classes, extra: [] } }, 'a missing class key': { ...good, classes: { sensitive: [] } },
80
- 'a class list that is not an array': badClass('boundary', 'routes'), 'a sparse class list': badClass('boundary', hole), 'an over-long class list': badClass('boundary', Array(17).fill('data')), 'a throwing proxy': proxy,
81
- };
82
- check('refused input returns the raising result and never throws', Object.fromEntries(Object.entries(REFUSALS).map(([k, v]) => [k, (() => { try { const r = escalation(v); return [r.review_min, r.reasons]; } catch { return 'threw'; } })()])),
83
- Object.fromEntries(Object.keys(REFUSALS).map((k) => [k, ['security', [REFUSED_REASON]]])));
84
- check('the refused result seats every lens, flags size and carries every hard-surface id', (({ seats, size_flag, tests_weakened, hard_surface }) => [seated({ seats }), size_flag, tests_weakened, hard_surface])(escalation(null)), [LENSES, true, false, [...HARD_SURFACE_IDS]]);
85
- // Array.prototype.filter is called by the rules and not by the input reader, so a throwing one is a bug in the rules, not bad input.
86
- // `reached` counts the calls: when the rules stop calling it, the next check says so instead of failing on its values.
87
- let reached = 0;
88
- const whileBroken = (fn) => { const keep = Array.prototype.filter; Array.prototype.filter = () => { reached++; throw new Error('bug'); }; try { return fn(); } finally { Array.prototype.filter = keep; } };
89
- const broken = whileBroken(() => { try { return escalation(facts()); } catch { return { threw: true }; } });
90
- check('the internal-error test breaks the rules where it means to: Array.prototype.filter is reached (if not, patch whichever method the rules call now)', reached > 0, true);
91
- check('an unexpected error in the rules is the raising result under its own reason id, not the unreadable-input one; bad input keeps its id', [
92
- broken.threw ?? [broken.review_min, broken.reasons, broken.hard_surface, seated(broken), LENSES.map((l) => broken.seats[l].reasons)], escalation(null).reasons, INTERNAL_REASON !== REFUSED_REASON,
93
- ], [['security', [INTERNAL_REASON], [...HARD_SURFACE_IDS], LENSES, LENSES.map(() => [INTERNAL_REASON])], [REFUSED_REASON], true]);
94
- check('a plain object with a null prototype and a frozen input are read', [escalation(Object.assign(Object.create(null), facts())).review_min, escalation(Object.freeze(facts())).review_min], [null, null]);
95
-
96
- console.log('== escalation: output ==');
97
- const sample = [run(), run({ denied: true, test_lines_deleted: 40, modules: 3 }, { sensitive: ['auth'], contract: ['manifest'] }), escalation(null)];
98
- check('the output is deterministic, pure ASCII and has the same keys always', [escalation(facts()), JSON.stringify(sample).length > 0 && /^[\x20-\x7e]*$/.test(JSON.stringify(sample)), sample.map((r) => Object.keys(r).join())],
99
- [run(), true, sample.map(() => 'review_min,reasons,tests_weakened,size_flag,hard_surface,seats')]);
100
- const SHAPE = ['always', 'facts_unreadable', 'internal_error', 'review_min', ...Object.values(SEAT_REASONS).flat(), 'security'];
101
- const strings = (v) => (typeof v === 'string' ? [v] : v && typeof v === 'object' ? Object.entries(v).flatMap(([k, x]) => [...(Array.isArray(v) ? [] : [k]), ...strings(x)]) : []);
102
- const ids = new Set(strings(sample).concat(strings(run({ denied: true }, { sensitive: ['auth'], boundary: ['data'], contract: ['schema'] }))));
103
- const known = new Set([...SHAPE, 'seat', 'reasons', 'tests_weakened', 'size_flag', 'hard_surface', 'seats', ...LENSES, ...HARD_SURFACE_IDS, ...CLASS_NAMES.sensitive.map((n) => `sensitive:${n}`), ...CLASS_NAMES.boundary.map((n) => `boundary:${n}`), ...CLASS_NAMES.contract.map((n) => `contract:${n}`)]);
104
- check('a result holds ids, booleans and counts only: every string is a fixed id and no input name is echoed', [[...ids].filter((s) => !known.has(s)), JSON.stringify(escalation({ ...good, '/home/u/secret.pem': 1 }))], [[], JSON.stringify(escalation(null))]);
105
- const ALL = run({ denied: true, test_lines_deleted: 100, production_lines: 60, new_top_dirs: 1, modules: 3, plan_target: true, plan_paths: true, slug_given: true, work_item_paths: true },
106
- { sensitive: [...CLASS_NAMES.sensitive], boundary: [...CLASS_NAMES.boundary], contract: [...CLASS_NAMES.contract], ci: ['ci'] });
107
- check('the registries and constants are frozen and, with every fact on, a lens emits exactly the reason ids its registry lists', [
108
- Object.isFrozen(HARD_SURFACE_IDS), Object.isFrozen(SEAT_REASONS), Object.isFrozen(SEAT_REASONS['somi-reviewer']), Object.isFrozen(CLASS_NAMES.sensitive),
109
- LENSES.map((l) => [...new Set(ALL.seats[l].reasons.map((id) => id.split(':')[0]))].sort()),
110
- ], [true, true, true, true, LENSES.map((l) => [...SEAT_REASONS[l]].sort())]);
111
-
112
- console.log('== escalation: exhaustive monotonicity ==');
113
- // escalation.sh sets SKIP_DOMAIN=mutant-run for the scratch mutants that do not name one of these checks. Only that exact value skips.
114
- if (process.env.SKIP_DOMAIN === 'mutant-run') console.log(' skip the exhaustive monotonicity checks (SKIP_DOMAIN=mutant-run)');
115
- else {
116
- // Each flag fact is [fact overrides, class overrides] when set.
117
- const FLAG_FACTS = [
118
- [{}, { sensitive: ['auth'] }], [{}, { boundary: ['routes'] }], [{}, { contract: ['manifest'] }], [{}, { ci: ['ci'] }],
119
- [{ denied: true }, {}], [{ plan_target: true }, {}], [{ slug_given: true }, {}], [{ test_files_deleted: 1 }, {}],
120
- ];
121
- const AXES = [[0, 150, 151], [0, 5, 6], [0, 2, 3], [0, 1], [30, 0, -19, -20]];
122
- const point = (bits, ax) => {
123
- const net = AXES[4][ax[4]];
124
- const o = { production_lines: AXES[0][ax[0]], production_files: AXES[1][ax[1]], modules: AXES[2][ax[2]], new_top_dirs: AXES[3][ax[3]], test_lines_added: Math.max(net, 0), test_lines_deleted: Math.max(-net, 0) };
125
- const classes = {};
126
- FLAG_FACTS.forEach(([over, cls], i) => { if (bits >> i & 1) { Object.assign(o, over); Object.assign(classes, cls); } });
127
- return facts(o, classes);
128
- };
129
- const SIZES = AXES.map((a) => a.length);
130
- const results = new Map(); let evaluations = 0;
131
- for (let bits = 0; bits < 256; bits++) for (let a = 0; a < SIZES[0]; a++) for (let b = 0; b < SIZES[1]; b++) for (let c = 0; c < SIZES[2]; c++) for (let d = 0; d < SIZES[3]; d++) for (let e = 0; e < SIZES[4]; e++) {
132
- results.set([bits, a, b, c, d, e].join(), escalation(point(bits, [a, b, c, d, e]))); evaluations++;
133
- }
134
- // Every decision a result makes, as strings: `lo` is covered by `hi` when its set is inside hi's. The reason ids count too,
135
- // except against the refused result, whose one reason is its own.
136
- const decisions = (r, reasons) => new Set([...(r.review_min ? ['review_min'] : []), ...(r.size_flag ? ['size_flag'] : []), ...r.hard_surface.map((h) => `hard:${h}`),
137
- ...LENSES.flatMap((l) => [...(r.seats[l].seat ? [l] : []), ...(reasons ? r.seats[l].reasons.map((x) => `${l}/${x}`) : [])]), ...(reasons ? r.reasons : [])]);
138
- const inside = (lo, hi) => { for (const x of lo) if (!hi.has(x)) return false; return true; };
139
- const full = new Map([...results].map(([k, r]) => [k, decisions(r, true)]));
140
- let edges = 0; const broken = [];
141
- for (const key of results.keys()) {
142
- const [bits, ...ax] = key.split(',').map(Number);
143
- const ups = [...FLAG_FACTS.map((_, i) => (bits >> i & 1 ? null : [bits | 1 << i, ...ax])), ...ax.map((v, i) => (v + 1 < SIZES[i] ? [bits, ...ax.map((x, j) => (j === i ? x + 1 : x))] : null))];
144
- for (const up of ups.filter(Boolean)) { edges++; if (!inside(full.get(key), full.get(up.join()))) broken.push(`${key} -> ${up.join()}`); }
145
- }
146
- // Flag edges 8 x 128 x 216, ordinal edges 110,592 + 27,648 + 41,472.
147
- check('the monotonicity domain has 55,296 evaluations and 400,896 one-step edges', [evaluations, results.size, edges], [55296, 55296, 400896]);
148
- check('a fact moved one step up never turns off a seat, a seat reason, a reason, review_min, a hard-surface id or size_flag', broken.slice(0, 3), []);
149
- check('review_min is null or security over the whole domain, and a quiet point exists', [[...new Set([...results.values()].map((r) => r.review_min))].sort(), results.get('0,0,0,0,0,0').review_min], [[null, 'security'], null]);
150
- check('the refused result dominates every result in the domain', (() => { const top = decisions(escalation(null)); return [...results.values()].filter((r) => !inside(decisions(r), top)).length; })(), 0);
151
- }
152
-
153
- console.log(`SUMMARY ${pass + fail} ${fail}`);
154
- process.exit(fail ? 1 : 0);