@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,562 +0,0 @@
1
- #!/usr/bin/env bash
2
- # Guards scripts/lib/size-tier.mjs: decideTier(signals) -> {tier, floor?, failed, reasons}.
3
- # Runs the signals -> tier table (tests/scripts/fixtures/size-tier-cases.json), the exported
4
- # thresholds, the never-lower property (an unknown signal can only keep or raise the tier), and
5
- # hostile inputs; then proves the table has teeth: each mutation of a threshold, comparison or
6
- # rule order, applied to a scratch copy of the module, must turn the same suite red.
7
- # Hermetic: pure computation, scratch dir only, no network, no model.
8
- set -uo pipefail
9
- umask 022
10
-
11
- ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
12
- MOD="$ROOT/scripts/lib/size-tier.mjs"
13
- CASES="$ROOT/tests/scripts/fixtures/size-tier-cases.json"
14
- TMP="$(mktemp -d)"
15
- trap 'rm -rf "$TMP"' EXIT
16
- echo "== size tier: decideTier table =="
17
-
18
- cat > "$TMP/run.mjs" <<'JS'
19
- import { readFileSync } from 'node:fs';
20
- import { pathToFileURL } from 'node:url';
21
- const m = await import(pathToFileURL(process.argv[2]).href);
22
- const { decideTier, SIGNAL_IDS } = m;
23
- const { base, cases } = JSON.parse(readFileSync(process.argv[3], 'utf8'));
24
- const j = JSON.stringify;
25
- let bad = 0, n = 0;
26
- const check = (name, got, want) => { n++; if (j(got) === j(want)) console.log(' ok ' + name); else { bad++; console.log(' FAIL ' + name + ' (want ' + j(want) + ', got ' + j(got) + ')'); } };
27
- const safe = (f) => { try { return f(); } catch (e) { return 'THREW ' + e.message; } };
28
- const entry = (v) => ({ value: v, evidence: 'e' });
29
- const rank = { trivial: 0, small: 1, full: 2 };
30
- const build = (c) => {
31
- const o = {};
32
- for (const id of Object.keys(base)) o[id] = entry(base[id]);
33
- for (const [id, v] of Object.entries(c.set || {})) o[id] = v !== null && typeof v === 'object' && 'entry' in v ? v.entry : entry(v);
34
- for (const id of c.drop || []) delete o[id];
35
- for (const id of c.noEvidence || []) o[id] = { value: base[id] };
36
- for (const [id, len] of Object.entries(c.evidenceLength || {})) o[id].evidence = 'x'.repeat(len);
37
- return o;
38
- };
39
-
40
- check('thresholds and ids', [m.MAX_MODULES, m.MAX_FILES, m.MAX_DIFF_LINES, m.TRIVIAL_MAX_FILES, m.TRIVIAL_MAX_MODULES, m.TRIVIAL_MAX_DIFF_LINES, m.MAX_EVIDENCE_CHARS, SIGNAL_IDS.join()],
41
- [2, 6, 100, 1, 1, 50, 300, 'T1,T2,T3,T4,T5,sensitive_core,hard_surface,design_open,open_questions,acceptance_testable,modules_touched,est_files,est_diff_lines,existing_work_item,brief_exists']);
42
-
43
- for (const c of cases) {
44
- const input = 'raw' in c ? c.raw : build(c);
45
- const ids = (x) => (x === 'ALL' ? [...SIGNAL_IDS] : x || []);
46
- const unknown = ids(c.expect.unknown), invalid = ids(c.expect.invalid);
47
- const want = { tier: c.expect.tier, floor: c.expect.floor || null, securityLens: c.expect.securityLens === true,
48
- failed: SIGNAL_IDS.filter((id) => unknown.includes(id) || invalid.includes(id)), unknown, invalid, reasons: c.expect.reasons };
49
- const got = safe(() => decideTier(input));
50
- const { basis, ...rest } = got;
51
- check('case: ' + c.name, rest, want);
52
- if (c.expect.basis) check('basis: ' + c.name, Object.keys(basis), c.expect.basis);
53
- if ('raw' in c) continue;
54
- // Never lower: making any one signal unknown keeps or raises the tier, keeps any floor, and names the id.
55
- const before = decideTier(input);
56
- let lowered = [];
57
- for (const id of SIGNAL_IDS) for (const value of ['unknown', 'bogus']) {
58
- const after = decideTier({ ...input, [id]: { value, evidence: 'e' } });
59
- if (rank[after.tier] < rank[before.tier] || (before.floor && !after.floor) || (before.securityLens && !after.securityLens) || !after.failed.includes(id)) lowered.push(id + ':' + value);
60
- }
61
- check('unknown or invalid never lowers: ' + c.name, lowered, []);
62
- }
63
-
64
- check('fullBasis shows every signal read cleanly even at full', [Object.keys(decideTier(build({ set: { hard_surface: true } })).basis), Object.keys(decideTier(build({ set: { hard_surface: true } }), { fullBasis: true }).basis).length], [['T3', 'sensitive_core'], SIGNAL_IDS.length]);
65
- const shapeOk = (r) => j(r) === j({ tier: 'full', floor: 'full', securityLens: true, failed: [...SIGNAL_IDS], unknown: [], invalid: [...SIGNAL_IDS], reasons: ['signals_unreadable'], basis: {} });
66
- const good = () => Object.fromEntries(Object.keys(base).map((id) => [id, entry(base[id])]));
67
- let reads = 0;
68
- const getterEntry = Object.defineProperty({ evidence: 'e' }, 'value', { get() { reads++; throw new Error('boom'); }, enumerable: true });
69
- const refused = {
70
- 'throwing proxy as input': new Proxy({}, { get() { throw new Error('boom'); }, ownKeys() { throw new Error('boom'); }, getOwnPropertyDescriptor() { throw new Error('boom'); }, getPrototypeOf() { throw new Error('boom'); } }),
71
- 'inherited values only': Object.create(good()),
72
- 'class instance': new (class S { constructor() { Object.assign(this, good()); } })(),
73
- 'sparse array': [, , ,],
74
- 'Map': new Map(),
75
- 'Date': new Date(0),
76
- 'function': () => 1,
77
- };
78
- for (const [name, input] of Object.entries(refused)) check('refused with signals_unreadable: ' + name, shapeOk(safe(() => decideTier(input))), true);
79
- const hostile = {
80
- 'throwing getter on value': { ...good(), T1: getterEntry },
81
- 'throwing getter on entry': Object.defineProperty(good(), 'T2', { get() { reads++; throw new Error('boom'); }, enumerable: true }),
82
- 'proxy entry': { ...good(), T3: new Proxy({}, { getOwnPropertyDescriptor() { throw new Error('boom'); } }) },
83
- 'symbol key': { [Symbol('T1')]: entry(true) },
84
- 'NaN count': { ...good(), est_files: entry(NaN) },
85
- 'Infinity count': { ...good(), est_diff_lines: entry(Infinity) },
86
- 'JSON __proto__ key': JSON.parse('{"__proto__": {"T3": {"value": true, "evidence": "x"}}}'),
87
- };
88
- for (const [name, input] of Object.entries(hostile)) {
89
- const r = safe(() => decideTier(input));
90
- check('hostile never throws, never reaches trivial: ' + name, typeof r === 'object' && r !== null && r.tier in rank && r.tier !== 'trivial', true);
91
- }
92
- check('a huge evidence string is invalid, not a crash', decideTier({ ...good(), T1: { value: true, evidence: 'x'.repeat(2e6) } }).invalid, ['T1']);
93
- check('hostile getters are never invoked', reads, 0);
94
- check('prototype-key input is the worst case', decideTier(JSON.parse('{"__proto__": {"T3": {"value": true, "evidence": "x"}}}')).invalid.length, SIGNAL_IDS.length);
95
- const frozen = Object.freeze(Object.fromEntries(Object.entries(good()).map(([k, v]) => [k, Object.freeze(v)])));
96
- check('frozen input is read without mutation', safe(() => decideTier(frozen).tier), 'trivial');
97
- const snapshot = j(good());
98
- const probe = good(); decideTier(probe);
99
- check('input is not mutated', j(probe), snapshot);
100
- check('result is plain JSON', j(JSON.parse(j(decideTier(good())))), j(decideTier(good())));
101
-
102
- console.log('SUMMARY ' + n + ' ' + bad);
103
- process.exit(bad ? 1 : 0);
104
- JS
105
-
106
- out="$(node "$TMP/run.mjs" "$MOD" "$CASES" 2>&1)"; rc=$?
107
- printf '%s\n' "$out" | grep -v '^SUMMARY'
108
- total="$(printf '%s\n' "$out" | awk '/^SUMMARY/{print $2}')"; failed="$(printf '%s\n' "$out" | awk '/^SUMMARY/{print $3}')"
109
- pass=$((${total:-0} - ${failed:-0})); fail=${failed:-1}
110
- [ "$rc" = 0 ] || fail=$((fail > 0 ? fail : 1))
111
- ok() { pass=$((pass+1)); printf ' ok %s\n' "$1"; }
112
- bad() { fail=$((fail+1)); printf ' FAIL %s\n' "$1"; }
113
-
114
- # The table must be big enough to mean something.
115
- cases_n="$(node -e "console.log(JSON.parse(require('fs').readFileSync(process.argv[1])).cases.length)" "$CASES")"
116
- if [ "${cases_n:-0}" -ge 25 ]; then ok "table has $cases_n cases (floor 25)"; else bad "table has only ${cases_n:-0} cases (floor 25)"; fi
117
- if [ "$pass" -ge 150 ]; then ok "check count $pass meets the floor of 150"; else bad "check count $pass is under the floor of 150"; fi
118
-
119
- # Mutation proof: the suite must go red on each scratch mutation of the module.
120
- mutate() { # $1 = label, $2 = node expression over `s` (the source) returning the mutated source
121
- node -e "const fs=require('fs');const s=fs.readFileSync(process.argv[1],'utf8');const t=($2);if(t===s){process.exit(3)}fs.writeFileSync(process.argv[2],t)" "$MOD" "$TMP/mut.mjs"
122
- local made=$?
123
- if [ "$made" != 0 ]; then bad "mutation '$1' did not change the module (stale pattern)"; return; fi
124
- if node "$TMP/run.mjs" "$TMP/mut.mjs" "$CASES" >/dev/null 2>&1; then bad "mutation '$1' left the suite green"; else ok "mutation '$1' turns the suite red"; fi
125
- }
126
- mutate "full basis flag ignored" "s.replace('(fullBasis || ','(')"
127
- mutate "diff threshold 100 -> 101" "s.replace('MAX_DIFF_LINES = 100','MAX_DIFF_LINES = 101')"
128
- mutate "file threshold 6 -> 7" "s.replace('MAX_FILES = 6','MAX_FILES = 7')"
129
- mutate "module threshold 2 -> 3" "s.replace('MAX_MODULES = 2','MAX_MODULES = 3')"
130
- mutate "trivial file limit 1 -> 2" "s.replace('TRIVIAL_MAX_FILES = 1','TRIVIAL_MAX_FILES = 2')"
131
- mutate "diff comparison > -> >=" "s.replace('x > MAX_DIFF_LINES','x >= MAX_DIFF_LINES')"
132
- mutate "files comparison > -> >=" "s.replace('x > MAX_FILES','x >= MAX_FILES')"
133
- mutate "trivial comparison <= -> <" "s.replace('v.est_files <= TRIVIAL_MAX_FILES','v.est_files < TRIVIAL_MAX_FILES')"
134
- mutate "trivial diff limit 50 -> 51" "s.replace('TRIVIAL_MAX_DIFF_LINES = 50','TRIVIAL_MAX_DIFF_LINES = 51')"
135
- mutate "trivial diff comparison > -> >=" "s.replace('x > TRIVIAL_MAX_DIFF_LINES','x >= TRIVIAL_MAX_DIFF_LINES')"
136
- mutate "trivial rule ignores the diff limit" "s.replace(' && v.est_diff_lines <= TRIVIAL_MAX_DIFF_LINES','')"
137
- mutate "trivial module limit 1 -> 2" "s.replace('TRIVIAL_MAX_MODULES = 1','TRIVIAL_MAX_MODULES = 2')"
138
- mutate "contradiction check removed" "s.replace(\"read.T1.state === 'ok' && read.T1.value\",'false')"
139
- mutate "evidence cap 300 -> 301" "s.replace('MAX_EVIDENCE_CHARS = 300','MAX_EVIDENCE_CHARS = 301')"
140
- mutate "control characters allowed in evidence" "s.replace('&& !CONTROL_CHARS.test(e)','')"
141
- mutate "count minimum dropped (0 allowed)" "s.replace('modules_touched: 1, est_files: 1, est_diff_lines: 1 }','modules_touched: 0, est_files: 0, est_diff_lines: 0 }')"
142
- mutate "unknown work-item reason suffix removed" "s.replace('? \`\${id}_unknown\` : id','? id : id')"
143
- mutate "basis drops T3" "s.replace(\"(id === 'T3' || id === 'sensitive_core' || decided.tier !== 'full')\",\"(id === 'sensitive_core' || decided.tier !== 'full')\")"
144
- mutate "basis drops sensitive_core" "s.replace(\"(id === 'T3' || id === 'sensitive_core' || decided.tier !== 'full')\",\"(id === 'T3' || decided.tier !== 'full')\")"
145
- mutate "worst case of T3 flipped to true" "s.replace('T3: false, T4','T3: true, T4')"
146
- mutate "worst case of sensitive_core flipped to false" "s.replace('sensitive_core: true,\n','sensitive_core: false,\n')"
147
- mutate "floor dropped" "s.replace(\"floor: v.sensitive_core === false ? null : 'full'\",'floor: null')"
148
- mutate "sensitive_core rule removed" "s.replace(\"v.sensitive_core === true ? { tier: 'full', reasons: ['sensitive_core'] } : null\",'null')"
149
- mutate "security lens ignores T3" "s.replace('securityLens: v.T3 !== true || ','securityLens: ')"
150
- mutate "security lens ignores an unknown core" "s.replace(' || v.sensitive_core !== false, failed',', failed')"
151
- mutate "core contradiction check removed" "s.replace(\"read.T3.state === 'ok' && read.T3.value && read.sensitive_core\",'false && read.sensitive_core')"
152
- # Rules 4 and 5 can never both match (the size caps sit above the trivial caps), so only 1-4 are swapped.
153
- for i in 0 1 2; do
154
- j=$((i+1))
155
- mutate "rules $((i+1)) and $((j+1)) swapped" "s.replace('const RULES = [','const RULES_IN_ORDER = [').replace('export function decideTier', 'const RULES = RULES_IN_ORDER.map((_, k, a) => a[k === $i ? $j : k === $j ? $i : k]);\nexport function decideTier')"
156
- done
157
-
158
- # ---- CLI: scripts/somi-tier.mjs (resolve, resolve --record) ----
159
- echo "== size tier: somi-tier CLI =="
160
- cat > "$TMP/cli.mjs" <<'JS'
161
- import { spawnSync } from 'node:child_process';
162
- import fs from 'node:fs';
163
- import path from 'node:path';
164
- import crypto from 'node:crypto';
165
- const [CLI, TMPDIR, mode] = process.argv.slice(2);
166
- const quiet = mode === 'quiet';
167
- const work = fs.mkdtempSync(path.join(TMPDIR, 'w-'));
168
- let n = 0, bad = 0;
169
- // Quiet mode (mutants) stops at the first failure: one red check is all a mutant needs.
170
- const check = (name, got, want) => {
171
- n++;
172
- const g = JSON.stringify(got), w = JSON.stringify(want);
173
- if (g === w) { if (!quiet) console.log(' ok ' + name); return; }
174
- bad++; console.log(' FAIL ' + name + ' (want ' + w + ', got ' + g + ')');
175
- if (quiet) process.exit(1);
176
- };
177
- const run = (args, { input, env = {}, cwd, timeout } = {}) => {
178
- const e = { ...process.env, ...env };
179
- if (!('SOMI_SHIP_LOOP_TIER' in env)) delete e.SOMI_SHIP_LOOP_TIER;
180
- const r = spawnSync(process.execPath, [CLI, ...args], { input, env: e, cwd, encoding: 'utf8', timeout });
181
- return { rc: r.status, out: r.stdout, err: r.stderr };
182
- };
183
- const json = (s) => { try { return JSON.parse(s); } catch { return 'NOT JSON'; } };
184
- const isAscii = (s) => /^[\x00-\x7f]*$/.test(s);
185
- const BASE = { T1: true, T2: true, T3: true, T4: true, T5: true, sensitive_core: false, hard_surface: false, design_open: false, open_questions: 0,
186
- acceptance_testable: true, modules_touched: 1, est_files: 1, est_diff_lines: 40, existing_work_item: false, brief_exists: false };
187
- const signals = (over = {}) => Object.fromEntries(Object.entries({ ...BASE, ...over }).map(([k, v]) => [k, { value: v, evidence: 'e' }]));
188
- const write = (name, content) => { const f = path.join(work, name); fs.writeFileSync(f, typeof content === 'string' || Buffer.isBuffer(content) ? content : JSON.stringify(content)); return f; };
189
- const F = {
190
- trivial: write('trivial.json', signals()),
191
- small: write('small.json', signals({ T2: false, est_diff_lines: 80 })),
192
- floor: write('floor.json', signals({ T3: false, sensitive_core: true, hard_surface: true })),
193
- nofloor: write('nofloor.json', signals({ hard_surface: true })),
194
- };
195
- const KEYS = ['basis', 'effective', 'failed', 'floor', 'invalid', 'reasons', 'security_lens', 'source', 'tier', 'unknown'];
196
-
197
- // resolve: one result per corpus tier, by file and by stdin
198
- for (const [name, tier, floor] of [['trivial', 'trivial', null], ['small', 'small', null], ['floor', 'full', 'full'], ['nofloor', 'full', null]]) {
199
- const r = run(['resolve', '--signals', F[name]]);
200
- const o = json(r.out);
201
- check(`resolve ${name}: exit 0, tier, floor, source`, [r.rc, o.tier, o.effective, o.floor, o.source], [0, tier, tier, floor, 'computed']);
202
- check(`resolve ${name}: exact key set, one line`, [Object.keys(o).sort(), r.out.trim().split('\n').length], [KEYS, 1]);
203
- const s = run(['resolve', '--signals', '-'], { input: fs.readFileSync(F[name]) });
204
- check(`resolve ${name}: stdin equals file`, s.out, r.out);
205
- }
206
- // Unrecognized keys: reported by name (bounded, escaped, no values) with the expected ids, only when present.
207
- {
208
- const { SIGNAL_IDS: IDS_LIST } = await import('file://' + path.join(path.dirname(CLI), 'lib', 'size-tier.mjs'));
209
- const hostile = { ...JSON.parse(fs.readFileSync(F.trivial, 'utf8')), business_logic_complexity: { value: true, evidence: 'LEAK-ME' }, ['k\u202e\u0000' + 'x'.repeat(100)]: 1 };
210
- for (let i = 0; i < 12; i++) hostile['extra' + i] = i;
211
- const r = run(['resolve', '--signals', '-'], { input: JSON.stringify(hostile) });
212
- const o = json(r.out);
213
- check('unrecognized keys: exit 0, the two fields appear, the decision is unchanged', [r.rc, Object.keys(o).sort(), o.tier], [0, [...KEYS, 'expected', 'unrecognized'].sort(), 'trivial']);
214
- check('unrecognized: at most 8 names, each at most 40 characters, pure ASCII on the wire, no value echoed', [o.unrecognized.length, o.unrecognized.every((n) => n.length <= 40), /^[\x20-\x7e]*$/.test(r.out.trim()), r.out.includes('LEAK-ME')], [8, true, true, false]);
215
- check('unrecognized: expected is the exact id list', o.expected, IDS_LIST);
216
- const none = json(run(['resolve', '--signals', F.trivial]).out);
217
- check('no unrecognized keys: neither field is present', ['unrecognized' in none, 'expected' in none], [false, false]);
218
- const invented = json(run(['resolve', '--signals', '-'], { input: JSON.stringify({ input_handling_detail: 'x', T1: 'yes' }) }).out);
219
- check('invented names only: fail-closed as before, names listed back', [invented.tier, invented.unrecognized], ['full', ['input_handling_detail']]);
220
- const arr = run(['resolve', '--signals', '-'], { input: '[]' });
221
- check('a non-object input is still a usage error', arr.rc, 64);
222
- }
223
- check('resolve: reasons and failed are echoed', (({ reasons, failed }) => [reasons, failed])(json(run(['resolve', '--signals', F.floor]).out)), [['sensitive_core'], []]);
224
-
225
- // input errors
226
- const big = write('big.json', ' '.repeat(70000) + '{}');
227
- const exact = write('exact.json', JSON.stringify(signals()) + ' '.repeat(64 * 1024 - JSON.stringify(signals()).length));
228
- const link = path.join(work, 'link.json'); fs.symlinkSync(F.trivial, link);
229
- const fifo = path.join(work, 'fifo.json'); spawnSync('mkfifo', [fifo]);
230
- const deep = (open, close, k) => open.repeat(k) + close.repeat(k);
231
- const badInputs = {
232
- 'oversize file': ['resolve', '--signals', big], 'missing file': ['resolve', '--signals', path.join(work, 'nope.json')],
233
- 'directory': ['resolve', '--signals', work], 'symlink': ['resolve', '--signals', link],
234
- 'JSON parse error': ['resolve', '--signals', write('p.json', '{"T1": ')], 'empty file': ['resolve', '--signals', write('e.json', '')],
235
- 'array': ['resolve', '--signals', write('a.json', '[]')], 'string': ['resolve', '--signals', write('s.json', '"x"')],
236
- 'null': ['resolve', '--signals', write('n.json', 'null')], 'number': ['resolve', '--signals', write('num.json', '5')],
237
- 'deeply nested array': ['resolve', '--signals', write('deep.json', deep('[', ']', 30000))],
238
- 'invalid UTF-8': ['resolve', '--signals', write('u.json', Buffer.from([0x7b, 0xff, 0x7d]))],
239
- 'invalid UTF-8 inside evidence': ['resolve', '--signals', write('ue.json', (() => { const t = JSON.stringify(signals()); const k = t.indexOf('"evidence":"e"') + 12; return Buffer.concat([Buffer.from(t.slice(0, k)), Buffer.from([0xff]), Buffer.from(t.slice(k + 1))]); })())],
240
- 'unknown flag': ['resolve', '--signals', F.trivial, '--bogus', 'x'], 'no --signals': ['resolve'],
241
- 'flag without value': ['resolve', '--signals'], 'empty flag value': ['resolve', '--signals', ''],
242
- 'duplicate flag': ['resolve', '--signals', F.trivial, '--signals', F.trivial], 'no subcommand': [], 'unknown subcommand': ['frobnicate'],
243
- 'the removed record subcommand': ['record', '--slug', 'x', '--tier', 'small', '--source', 'override'],
244
- '--project-dir without --record': ['resolve', '--signals', F.trivial, '--project-dir', work],
245
- 'prototype-named flag': ['resolve', '--signals', F.trivial, '__proto__', 'x'],
246
- };
247
- for (const [name, args] of Object.entries(badInputs)) {
248
- const r = run(args);
249
- check(`resolve rejects ${name}: exit 64, stdout empty`, [r.rc, r.out], [64, '']);
250
- }
251
- const fifoRun = run(['resolve', '--signals', fifo], { timeout: 3000 });
252
- check('a FIFO is refused without hanging', [fifoRun.rc, fifoRun.out], [64, '']);
253
- check('resolve accepts a file of exactly 64 KiB', run(['resolve', '--signals', exact]).rc, 0);
254
- const bigStdin = run(['resolve', '--signals', '-'], { input: ' '.repeat(70000) + '{}' });
255
- check('resolve rejects oversize stdin', [bigStdin.rc, bigStdin.out], [64, '']);
256
- check('resolve rejects empty stdin', run(['resolve', '--signals', '-'], { input: '' }).rc, 64);
257
- const invalid = json(run(['resolve', '--signals', write('empty-obj.json', '{}')]).out);
258
- check('invalid signals resolve normally to the worst case', [invalid.tier, invalid.floor, invalid.invalid.length > 0], ['full', 'full', true]);
259
- const nestedValue = write('nested.json', `{"T1":{"value":${deep('[', ']', 30000)},"evidence":"e"}}`);
260
- const nestedRun = run(['resolve', '--signals', nestedValue, '--record', 'nested', '--project-dir', work]);
261
- check('a deeply nested value is invalid, not a crash, and still recorded', [nestedRun.rc, json(nestedRun.out).invalid.includes('T1'), /^[0-9a-f]{64}$/.test(json(fs.readFileSync(path.join(work, '.somi/somi-state/tier/nested.json'), 'utf8')).signals_sha256)], [0, true, true]);
262
-
263
- // no raw input on stderr, no non-ASCII anywhere in the output
264
- const secret = run(['resolve', '--signals', write('secret.json', '{"T1": xSECRETx}')]);
265
- check('a parse error does not echo the input', [secret.rc, /SECRET/.test(secret.err)], [64, false]);
266
- const hostileFlag = run(['resolve', '--signals', F.trivial, '‮--evil\u009b
'], {});
267
- check('a hostile argument is quoted and ASCII on stderr', [hostileFlag.rc, isAscii(hostileFlag.err), /\\u202e/.test(hostileFlag.err)], [64, true, true]);
268
- const hostilePath = run(['resolve', '--signals', path.join(work, 'no‮\u009bfile')]);
269
- check('a hostile path is quoted and ASCII on stderr', [hostilePath.rc, isAscii(hostilePath.err), /\\u202e/.test(hostilePath.err)], [64, true, true]);
270
- const hostileSub = run(['
‮']);
271
- check('a hostile subcommand is quoted and ASCII on stderr', [hostileSub.rc, isAscii(hostileSub.err)], [64, true]);
272
- const nasty = 'say "hi" \\ </script> é 中 😀';
273
- const small2 = { ...signals({ T2: false, est_diff_lines: 80 }), T3: { value: true, evidence: nasty } };
274
- const echo = run(['resolve', '--signals', write('nasty.json', small2)]);
275
- check('evidence echoes on one line, ASCII, and decodes back exactly', [json(echo.out).basis?.T3, echo.out.trim().split('\n').length, isAscii(echo.out)], [nasty, 1, true]);
276
- for (const [name, ch] of [['bidi override U+202E', '‮'], ['line separator U+2028', '
'], ['C1 control U+009B', '\u009b']]) {
277
- const r = run(['resolve', '--signals', write('ctl.json', { ...signals({ T2: false, est_diff_lines: 80 }), T3: { value: true, evidence: `a${ch}b` } })]);
278
- check(`${name} in evidence is refused as invalid, output stays ASCII`, [r.rc, json(r.out).invalid, isAscii(r.out)], [0, ['T3'], true]);
279
- }
280
-
281
- // override
282
- const ov = (file, tier, env) => run(['resolve', '--signals', file, ...(tier ? ['--override', tier] : [])], env !== undefined ? { env: { SOMI_SHIP_LOOP_TIER: env } } : {});
283
- let r = ov(F.floor, 'small');
284
- check('downward override below the floor: exit 65, no stdout, names the floor', [r.rc, r.out, /floor/.test(r.err) && /full/.test(r.err)], [65, '', true]);
285
- r = ov(F.nofloor, 'small');
286
- check('downward override without a floor is allowed', [r.rc, json(r.out).tier, json(r.out).effective, json(r.out).source], [0, 'full', 'small', 'override']);
287
- r = ov(F.small, 'full');
288
- check('upward override small -> full', [r.rc, json(r.out).tier, json(r.out).effective, json(r.out).source], [0, 'small', 'full', 'override']);
289
- r = ov(F.trivial, 'small');
290
- check('upward override trivial -> small', [r.rc, json(r.out).effective], [0, 'small']);
291
- r = ov(F.floor, 'full');
292
- check('override equal to the computed tier is allowed under a floor', [r.rc, json(r.out).effective, json(r.out).source], [0, 'full', 'override']);
293
- for (const bad of ['trivial', 'Small', 'medium']) { r = ov(F.small, bad); check(`override target ${bad} is a usage error`, [r.rc, r.out], [64, '']); }
294
- r = ov(F.small, null, 'full');
295
- check('env override raises the tier, source env', [r.rc, json(r.out).effective, json(r.out).source], [0, 'full', 'env']);
296
- r = ov(F.small, 'small', 'full');
297
- check('the flag wins over the environment', [r.rc, json(r.out).effective, json(r.out).source], [0, 'small', 'override']);
298
- r = ov(F.nofloor, null, 'small');
299
- check('env override may lower when there is no floor', [r.rc, json(r.out).effective, json(r.out).source], [0, 'small', 'env']);
300
- r = ov(F.floor, null, 'small');
301
- check('env override below the floor: exit 65', [r.rc, r.out], [65, '']);
302
- for (const bad of ['trivial', 'FULL', 'x y']) { r = ov(F.small, null, bad); check(`env value ${JSON.stringify(bad)} is a usage error`, [r.rc, r.out], [64, '']); }
303
- r = ov(F.small, null, '');
304
- check('an empty env value counts as unset', [r.rc, json(r.out).source], [0, 'computed']);
305
- r = ov(F.small, 'full', 'bogus');
306
- check('a valid flag does not read an invalid env value', [r.rc, json(r.out).effective], [0, 'full']);
307
- r = run(['resolve', '--signals', F.small], { env: { SOMI_SHIP_LOOP_TIER: '‮' } });
308
- check('a hostile env value leaves stderr ASCII', [r.rc, isAscii(r.err)], [64, true]);
309
-
310
- // --record
311
- const proj = path.join(work, 'proj'); fs.mkdirSync(proj);
312
- const tierDir = path.join(proj, '.somi', 'somi-state', 'tier');
313
- const mode9 = (p) => (fs.lstatSync(p).mode & 0o777).toString(8);
314
- const sha = (x) => crypto.createHash('sha256').update(x).digest('hex');
315
- const IDS = Object.keys(BASE);
316
- const hashOf = (file) => { const o = JSON.parse(fs.readFileSync(file, 'utf8')); return sha(JSON.stringify(IDS.map((id) => [id, o[id].value, o[id].evidence]))); };
317
- const rec = (slug, file, extra = [], opts) => run(['resolve', '--signals', file, ...extra, '--record', slug, '--project-dir', proj], opts);
318
- const readRec = (slug) => json(fs.readFileSync(path.join(tierDir, `${slug}.json`), 'utf8'));
319
- r = rec('my-item', F.small);
320
- const file = path.join(tierDir, 'my-item.json');
321
- const doc = readRec('my-item');
322
- check('record: exit 0, stdout gains the relative path, other keys unchanged', [r.rc, json(r.out).recorded, Object.keys(json(r.out)).sort()], [0, '.somi/somi-state/tier/my-item.json', ['recorded', ...KEYS].sort()]);
323
- check('record: modes 0600 file, 0700 directories', [mode9(file), mode9(tierDir), mode9(path.dirname(tierDir)), mode9(path.join(proj, '.somi'))], ['600', '700', '700', '700']);
324
- check('record: content is the computed result', [doc.slug, doc.tier, doc.source, doc.computed_tier, doc.floor, doc.reasons, doc.failed, Object.keys(doc).sort()],
325
- ['my-item', 'small', 'computed', 'small', null, ['T2', 'est_diff_lines'], [], ['attempt', 'basis', 'computed_tier', 'failed', 'floor', 'prior', 'reasons', 'recorded_at', 'security_lens', 'signals_sha256', 'slug', 'source', 'tier']]);
326
- check('record: timestamp is ISO', new Date(doc.recorded_at).toISOString(), doc.recorded_at);
327
- check('record: sha256 covers the signal entries', doc.signals_sha256, hashOf(F.small));
328
- rec('reordered', write('reordered.json', Object.fromEntries(Object.entries(JSON.parse(fs.readFileSync(F.small, 'utf8'))).reverse())));
329
- check('record: the hash ignores key order', readRec('reordered').signals_sha256, doc.signals_sha256);
330
- check('record: no stray temp files', fs.readdirSync(tierDir).filter((x) => x.endsWith('.tmp')), []);
331
- const ino = fs.statSync(file).ino;
332
- r = rec('my-item', F.small, ['--override', 'full']);
333
- check('record: an existing file is replaced atomically, with the effective tier and the computed one', [r.rc, fs.statSync(file).ino !== ino, readRec('my-item').tier, readRec('my-item').computed_tier, readRec('my-item').source, mode9(file)], [0, true, 'full', 'small', 'override', '600']);
334
- rec('env-item', F.small, [], { env: { SOMI_SHIP_LOOP_TIER: 'full' } });
335
- check('record: the env source is recorded only because the env was read', [readRec('env-item').source, readRec('env-item').tier], ['env', 'full']);
336
- r = rec('floor-ok', F.floor, ['--override', 'full']);
337
- check('record: tier full against a floor is allowed', [r.rc, readRec('floor-ok').tier, readRec('floor-ok').floor], [0, 'full', 'full']);
338
- rec('ascii', write('ascii.json', { ...signals({ T2: false, est_diff_lines: 80 }), T3: { value: true, evidence: 'café 中' } }));
339
- check('record: the state file is pure ASCII and decodes back', [isAscii(fs.readFileSync(path.join(tierDir, 'ascii.json'), 'utf8')), readRec('ascii').basis.T3], [true, 'café 中']);
340
- r = run(['resolve', '--signals', F.small, '--record', 'from-cwd'], { cwd: proj });
341
- check('record defaults the project to the current directory', [r.rc, fs.existsSync(path.join(tierDir, 'from-cwd.json'))], [0, true]);
342
- check('record accepts a 64-character slug', rec('a' + '-'.repeat(63), F.small).rc, 0);
343
- const before = fs.readdirSync(tierDir).sort();
344
- for (const slug of ['../x', '/etc/x', 'Upper', 'a'.repeat(65), '', '-lead', 'a/b', 'a.json', 'a b', '..']) {
345
- r = rec(slug, F.small);
346
- check(`record rejects slug ${JSON.stringify(slug.length > 20 ? slug.length + ' chars' : slug)}: 64`, [r.rc, r.out], [64, '']);
347
- }
348
- check('rejected slugs wrote nothing, here or above', [fs.readdirSync(tierDir).sort(), fs.existsSync(path.join(proj, '.somi', 'somi-state', 'x.json')), fs.existsSync('/etc/x.json')], [before, false, false]);
349
- r = rec('s3', F.floor, ['--override', 'small']);
350
- check('record below the floor: exit 65, nothing written', [r.rc, r.out, fs.existsSync(path.join(tierDir, 's3.json'))], [65, '', false]);
351
- r = rec('s4', write('bad.json', '[]'));
352
- check('record with unusable signals: 64, nothing written', [r.rc, fs.existsSync(path.join(tierDir, 's4.json'))], [64, false]);
353
- check('record: project dir that does not exist is a usage error', run(['resolve', '--signals', F.small, '--record', 's5', '--project-dir', path.join(work, 'nope')]).rc, 64);
354
-
355
- // attempts log, re-extraction bounds, whole basis on a lowering override
356
- const logOf = (slug) => fs.readFileSync(path.join(tierDir, `${slug}.attempts.jsonl`), 'utf8').split('\n').filter(Boolean).map((l) => JSON.parse(l));
357
- const logFile = path.join(tierDir, 'my-item.attempts.jsonl');
358
- check('attempts: two attempts logged in order, 0600, every line pure ASCII', [logOf('my-item').map((a) => [a.n, a.computed_tier, a.outcome]), mode9(logFile), isAscii(fs.readFileSync(logFile, 'utf8'))], [[[1, 'small', 'accepted'], [2, 'small', 'accepted']], '600', true]);
359
- check('attempts: the record carries attempt and prior', [readRec('my-item').attempt, readRec('my-item').prior], [2, [{ computed_tier: 'small', signals_sha256: hashOf(F.small) }]]);
360
- check('attempts: a first record has attempt 1 and no prior', [doc.attempt, doc.prior], [1, []]);
361
- rec('lower', F.floor);
362
- r = rec('lower', F.small);
363
- check('a re-record with a lower computed tier is refused: 65, record unchanged, refusal logged', [r.rc, r.out, /earlier computed tier/.test(r.err), readRec('lower').tier, logOf('lower').map((a) => a.outcome)], [65, '', true, 'full', ['accepted', 'refused_lower']]);
364
- r = rec('lower', F.small, ['--override', 'full']);
365
- check('a re-record with --override is allowed to compute lower', [r.rc, readRec('lower').attempt, readRec('lower').prior.map((p) => p.computed_tier)], [0, 3, ['full', 'small']]);
366
- r = rec('lower', F.floor);
367
- check('a re-record with an equal or higher computed tier is allowed', [r.rc, readRec('lower').attempt], [0, 4]);
368
- check('a refused floor override is logged before the failure exit', [logOf('s3').length, logOf('s3')[0].outcome, logOf('s3')[0].requested], [1, 'refused_floor', 'small']);
369
- r = ov(F.nofloor, 'small');
370
- check('a lowering override shows the whole basis', [Object.keys(json(r.out).basis).length, json(ov(F.nofloor, null).out).basis && Object.keys(json(ov(F.nofloor, null).out).basis)], [IDS.length, ['T3', 'sensitive_core']]);
371
- check('a non-lowering override keeps the short basis', Object.keys(json(ov(F.nofloor, 'full').out).basis), ['T3', 'sensitive_core']);
372
- const victim = path.join(work, 'victim-log.txt'); fs.writeFileSync(victim, 'keep');
373
- const evil = path.join(tierDir, 'evil.attempts.jsonl'); fs.symlinkSync(victim, evil);
374
- r = rec('evil', F.small);
375
- check('a symlinked attempts log is refused, the target is untouched', [r.rc, fs.readFileSync(victim, 'utf8'), fs.existsSync(path.join(tierDir, 'evil.json'))], [64, 'keep', false]);
376
- fs.writeFileSync(path.join(tierDir, 'junk.attempts.jsonl'), '{"computed_tier":"bogus","signals_sha256":null}\n');
377
- check('a malformed attempts line fails closed', [rec('junk', F.small).rc, fs.existsSync(path.join(tierDir, 'junk.json'))], [64, false]);
378
- fs.writeFileSync(path.join(tierDir, 'notjson.attempts.jsonl'), 'garbage\n');
379
- check('an unparsable attempts line fails closed', rec('notjson', F.small).rc, 64);
380
- fs.writeFileSync(path.join(tierDir, 'full-log.attempts.jsonl'), '{"computed_tier":"small","signals_sha256":null}\n'.repeat(50));
381
- check('a full attempts log (50) stops further attempts', [rec('full-log', F.small).rc, fs.existsSync(path.join(tierDir, 'full-log.json'))], [64, false]);
382
- fs.writeFileSync(path.join(tierDir, 'big.attempts.jsonl'), `{"computed_tier":"small","signals_sha256":null,"pad":"${'x'.repeat(300 * 1024)}"}\n`);
383
- check('an oversize attempts log is refused', rec('big', F.small).rc, 64);
384
-
385
- // approve: stamps the approval and the brief hash; only a small, hashed, unapproved record
386
- const brief = (slug, text = 'brief one') => { const d = path.join(proj, '.somi', 'plans', slug); fs.mkdirSync(d, { recursive: true }); fs.writeFileSync(path.join(d, 'brief.md'), text); };
387
- const appr = (slug) => run(['approve', '--slug', slug, '--project-dir', proj]);
388
- const shaOf = (t) => crypto.createHash('sha256').update(t).digest('hex');
389
- rec('ap', F.small); brief('ap');
390
- r = appr('ap');
391
- check('approve: exit 0, stamps approved_at and the brief hash, keeps the rest', [r.rc, json(r.out).approved, readRec('ap').brief_sha256, typeof readRec('ap').approved_at, readRec('ap').tier, mode9(path.join(tierDir, 'ap.json'))], [0, true, shaOf('brief one'), 'string', 'small', '600']);
392
- check('approve twice is refused: 65', appr('ap').rc, 65);
393
- rec('ap', F.small);
394
- check('a new resolve --record voids the approval', [readRec('ap').approved_at, readRec('ap').brief_sha256], [undefined, undefined]);
395
- check('approve without a record: 64', appr('no-such').rc, 64);
396
- rec('ap-full', F.floor); brief('ap-full');
397
- check('approve refuses a full record: 65', appr('ap-full').rc, 65);
398
- rec('ap-nobrief', F.small);
399
- check('approve without a brief: 64, record unapproved', [appr('ap-nobrief').rc, readRec('ap-nobrief').approved_at], [64, undefined]);
400
- rec('ap-null', F.small); brief('ap-null');
401
- const nullDoc = readRec('ap-null'); nullDoc.signals_sha256 = null; fs.writeFileSync(path.join(tierDir, 'ap-null.json'), JSON.stringify(nullDoc));
402
- check('approve refuses a record with no signals hash: 65', appr('ap-null').rc, 65);
403
- check('approve rejects a bad slug: 64', run(['approve', '--slug', '../x', '--project-dir', proj]).rc, 64);
404
- check('approve requires --slug: 64', run(['approve', '--project-dir', proj]).rc, 64);
405
-
406
- // links are never followed
407
- const outside = path.join(work, 'outside'); fs.mkdirSync(outside);
408
- const p2 = path.join(work, 'proj2'); fs.mkdirSync(path.join(p2, '.somi', 'somi-state'), { recursive: true });
409
- fs.symlinkSync(outside, path.join(p2, '.somi', 'somi-state', 'tier'));
410
- r = run(['resolve', '--signals', F.small, '--record', 'x', '--project-dir', p2]);
411
- check('symlinked tier directory is refused, nothing lands outside', [r.rc, r.out, fs.readdirSync(outside)], [64, '', []]);
412
- const p3 = path.join(work, 'proj3'); fs.mkdirSync(p3); fs.symlinkSync(outside, path.join(p3, '.somi'));
413
- r = run(['resolve', '--signals', F.small, '--record', 'x', '--project-dir', p3]);
414
- check('symlinked .somi is refused, nothing lands outside', [r.rc, fs.readdirSync(outside)], [64, []]);
415
- const victim2 = path.join(outside, 'victim.txt'); fs.writeFileSync(victim2, 'keep');
416
- fs.symlinkSync(victim2, path.join(tierDir, 'linked.json'));
417
- r = rec('linked', F.small);
418
- check('a symlink at the final path is replaced, never written through', [r.rc, fs.readFileSync(victim2, 'utf8'), fs.lstatSync(path.join(tierDir, 'linked.json')).isFile()], [0, 'keep', true]);
419
-
420
- fs.rmSync(work, { recursive: true, force: true });
421
- console.log('SUMMARY ' + n + ' ' + bad);
422
- process.exit(bad ? 1 : 0);
423
- JS
424
-
425
- CLI="$ROOT/scripts/somi-tier.mjs"
426
- # The full suite runs beside the mutants (they share the cores) and is collected before the report.
427
- ( node "$TMP/cli.mjs" "$CLI" "$TMP" > "$TMP/cli.out" 2>&1; echo $? > "$TMP/cli.rc" ) &
428
-
429
- # CLI mutation proof: each mutant is a scratch copy of the CLI (beside a copy of the module) run
430
- # by the quiet, fail-fast suite in its own directory; up to JOBS run at once, results are
431
- # collected and counted serially. kind "holds" marks a mutant that is meant to stay green because
432
- # a second guard covers the same hole.
433
- JOBS="${JOBS:-8}"
434
- mkdir -p "$TMP/cm"
435
- cm_n=0
436
- cmutate() { # $1 = label, $2 = node expression over `s` (the source); $3 = holds (optional)
437
- cm_n=$((cm_n + 1)); local d="$TMP/cm/$cm_n"
438
- mkdir -p "$d/lib"; cp "$MOD" "$d/lib/size-tier.mjs"; cp "$ROOT/scripts/lib/tier-record.mjs" "$d/lib/tier-record.mjs"
439
- printf '%s' "$1" > "$d/label"; printf '%s' "${3:-red}" > "$d/kind"
440
- (
441
- node -e "const fs=require('fs');const s=fs.readFileSync(process.argv[1],'utf8');const t=($2);if(t===s){process.exit(3)}fs.writeFileSync(process.argv[2],t)" "$CLI" "$d/somi-tier.mjs" || { echo stale > "$d/rc"; exit 0; }
442
- node "$TMP/cli.mjs" "$d/somi-tier.mjs" "$TMP" quiet >/dev/null 2>&1; echo $? > "$d/rc"
443
- ) &
444
- while [ "$(jobs -rp | wc -l)" -ge "$JOBS" ]; do wait -n; done
445
- }
446
- cmutate "floor refusal removed" 's.replace("if (floor && rank(tier) < rank(floor))","if (false)")'
447
- cmutate "resolve ignores the floor" 's.replace("refuseBelowFloor(requested, r.floor,","refuseBelowFloor(requested, null,")'
448
- cmutate "floor refusal exit code 65 -> 64" 's.replace("EXIT_FLOOR = 65","EXIT_FLOOR = 64")'
449
- cmutate "override may target trivial" 's.replace(/OVERRIDE_TARGETS = \[.small., .full.\]/,"OVERRIDE_TARGETS = [\"trivial\", \"small\", \"full\"]")'
450
- cmutate "slug pattern unanchored" 's.replace(/const SLUG = .*/,"const SLUG = /[a-z0-9-]/;")'
451
- cmutate "slug length cap 64 -> 200" 's.replace("{0,63}","{0,199}")'
452
- cmutate "environment wins over the flag" 's.replace("if (!requested && process.env[ENV_OVERRIDE])","if (process.env[ENV_OVERRIDE])")'
453
- cmutate "empty environment value read as a value" 's.replace("!requested && process.env[ENV_OVERRIDE])","!requested && ENV_OVERRIDE in process.env)")'
454
- cmutate "environment value not validated" 's.replace("if (!OVERRIDE_TARGETS.includes(requested)) die(","if (false) die(")'
455
- cmutate "file mode 0600 -> 0666" 's.replace("fs.constants.O_NOFOLLOW, 0o600)","fs.constants.O_NOFOLLOW, 0o666)")'
456
- cmutate "directory mode 0700 -> 0777" 's.replace("{ mode: 0o700 }","{ mode: 0o777 }")'
457
- cmutate "input cap 64 KiB -> 640 KiB" 's.replace("MAX_INPUT_BYTES = 64 * 1024","MAX_INPUT_BYTES = 640 * 1024")'
458
- cmutate "array signals accepted" 's.replace(" || Array.isArray(parsed)","")'
459
- cmutate "state directory links followed (both guards removed)" 's.replace("else if (!st.isDirectory())","else if (false)").replace("if (real !== path.join(root, ...STATE_DIRS))","if (false)")'
460
- cmutate "directory link check alone removed" 's.replace("else if (!st.isDirectory())","else if (false)")'
461
- cmutate "signals symlink followed" 's.replace("fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW | fs.constants.O_NONBLOCK","fs.constants.O_RDONLY | fs.constants.O_NONBLOCK")'
462
- cmutate "FIFO opened blocking" 's.replace(" | fs.constants.O_NONBLOCK","")'
463
- cmutate "regular-file check on the descriptor removed" 's.replace("if (!fs.fstatSync(fd).isFile())","if (false)")' holds
464
- cmutate "lower re-record check removed" 's.replace("rank(r.tier) < highest","false")'
465
- cmutate "override no longer exempts a lower re-record" 's.replace("slug && !f[\x27--override\x27] &&","slug &&")'
466
- cmutate "lower re-record refusal not logged" 's.replace("log(\x27refused_lower\x27);","")'
467
- cmutate "floor refusal not logged" 's.replace("beforeFail?.(\x27refused_floor\x27);","")'
468
- cmutate "attempts log not append-only" 's.replace("fs.constants.O_APPEND | ","")'
469
- cmutate "attempts log follows links" 's.replace("fs.constants.O_APPEND | fs.constants.O_CREAT | fs.constants.O_NOFOLLOW","fs.constants.O_APPEND | fs.constants.O_CREAT")' holds
470
- cmutate "attempts log mode 0600 -> 0666" 's.replace("O_APPEND | fs.constants.O_CREAT | fs.constants.O_NOFOLLOW, 0o600","O_APPEND | fs.constants.O_CREAT | fs.constants.O_NOFOLLOW, 0o666")'
471
- cmutate "prior and attempt not recorded" 's.replace("attempt: prior.length + 1, prior, ","attempt: 1, prior: [], ")'
472
- cmutate "lowering override keeps the short basis" 's.replace("requested && rank(effective) < rank(r.tier) ? decideTier(signals, { fullBasis: true }) : r","r")'
473
- cmutate "malformed attempts line accepted" 's.replace("if (!ok) fail(","if (false) fail(")'
474
- cmutate "attempts cap removed" 's.replace("rows.length >= MAX_ATTEMPTS","false")'
475
- cmutate "attempts size cap removed" 's.replace(" || st.size > MAX_LOG_BYTES","")'
476
- cmutate "approve accepts a full record" 's.replace("rec.tier !== \x27small\x27) fail(EXIT_FLOOR","false) fail(EXIT_FLOOR")'
477
- cmutate "approve accepts a record with no hash" 's.replace("if (typeof rec.signals_sha256 !== \x27string\x27 || !/^[0-9a-f]{64}$/.test(rec.signals_sha256)) {\n fail(EXIT_FLOOR","if (false) {\n fail(EXIT_FLOOR")'
478
- cmutate "approve repeatable" 's.replace("if (rec.approved_at) fail(","if (false) fail(")'
479
- cmutate "approve does not bind the brief" 's.replace(", brief_sha256: brief }",", brief_sha256: null }")'
480
- cmutate "output not ASCII-escaped" 's.replace("[\\u007f-\\uffff]","[\\uffff]")'
481
- cmutate "parse error echoes the engine message" 's.replace("signals are not valid UTF-8 JSON${","signals are not valid UTF-8 JSON ${String(e.message)}${")'
482
- cmutate "arguments echoed raw" 's.replace("const quote = (x) => ascii(String(x));","const quote = (x) => String(x);")'
483
- wait
484
- for d in "$TMP"/cm/*/; do
485
- label="$(cat "$d/label")"; kind="$(cat "$d/kind")"; rc="$(cat "$d/rc" 2>/dev/null || echo missing)"
486
- if [ "$rc" = stale ] || [ "$rc" = missing ]; then bad "CLI mutation '$label' did not apply (stale pattern)"
487
- elif [ "$kind" = holds ]; then
488
- if [ "$rc" = 0 ]; then ok "CLI mutation '$label' is still caught by a second guard"; else bad "CLI mutation '$label' went red but a second guard should hold"; fi
489
- elif [ "$rc" = 0 ]; then bad "CLI mutation '$label' left the suite green"
490
- else ok "CLI mutation '$label' turns the suite red"; fi
491
- done
492
- cli_rc="$(cat "$TMP/cli.rc" 2>/dev/null || echo 1)"
493
- cli_out="$(cat "$TMP/cli.out")"
494
- printf '%s\n' "$cli_out" | grep -v '^SUMMARY'
495
- cli_total="$(printf '%s\n' "$cli_out" | awk '/^SUMMARY/{print $2}')"; cli_failed="$(printf '%s\n' "$cli_out" | awk '/^SUMMARY/{print $3}')"
496
- pass=$((pass + ${cli_total:-0} - ${cli_failed:-0})); fail=$((fail + ${cli_failed:-0}))
497
- [ "$cli_rc" = 0 ] || { [ "${cli_failed:-0}" -gt 0 ] || bad "CLI suite crashed"; }
498
- if [ "${cli_total:-0}" -ge 95 ]; then ok "CLI check count ${cli_total} meets the floor of 95"; else bad "CLI check count ${cli_total:-0} is under the floor of 95"; fi
499
- # The widened evidence filter is part of the module, so its mutants run against the table.
500
- mutate "C1 controls allowed in evidence" "s.replace('\\\\u007f-\\\\u009f','\\\\u007f')"
501
- mutate "bidi and separator characters allowed in evidence" "s.replace('\\\\u2028-\\\\u202e','')"
502
- mutate "zero-width and mark characters allowed in evidence" "s.replace('\\\\u200b-\\\\u200f','')"
503
-
504
- # ---- drift guard: the routing skill's Size tiers section vs the module ----
505
- echo "== size tier: skill drift guard =="
506
- DRIFT="$ROOT/tests/scripts/lib/size-tier-drift.mjs"; SKILL="$ROOT/skills/somi-routing/SKILL.md"
507
- if d="$(node "$DRIFT" "$SKILL" "$MOD" 2>&1)"; then ok "skill and module agree: $d"; else bad "skill and module drifted: $d"; fi
508
- drift_red() { # $1 = label, $2 = skill|module, $3 = node expression over `s` returning the mutated source
509
- local src="$SKILL" out="$TMP/drift-skill.md" mod="$MOD"
510
- [ "$2" = module ] && { src="$MOD"; out="$TMP/drift-mod.mjs"; }
511
- node -e "const fs=require('fs');const s=fs.readFileSync(process.argv[1],'utf8');const t=($3);if(t===s){process.exit(3)}fs.writeFileSync(process.argv[2],t)" "$src" "$out" || { bad "drift mutation '$1' did not apply"; return; }
512
- if [ "$2" = module ]; then mod="$out"; src="$SKILL"; else src="$out"; fi
513
- if node "$DRIFT" "$src" "$mod" >/dev/null 2>&1; then bad "drift mutation '$1' left the guard green"; else ok "drift mutation '$1' turns the guard red"; fi
514
- }
515
- drift_red "signal id removed from the skill" skill "s.replace('| \`hard_surface\` |','| \`hard_surface_x\` |')"
516
- drift_red "signal id removed from the module" module "s.replace(\"'design_open', \",'')"
517
- drift_red "signal order swapped in the skill" skill "s.replace('| \`est_files\` |','| \`TMP\` |').replace('| \`est_diff_lines\` |','| \`est_files\` |').replace('| \`TMP\` |','| \`est_diff_lines\` |')"
518
- drift_red "threshold changed in the skill" skill "s.replace('| \`MAX_FILES\` | 6 |','| \`MAX_FILES\` | 7 |')"
519
- drift_red "threshold changed in the module" module "s.replace('MAX_MODULES = 2','MAX_MODULES = 3')"
520
- drift_red "threshold row removed from the skill" skill "s.replace('| \`TRIVIAL_MAX_DIFF_LINES\` | 50 |','| \`TRIVIAL_MAX_DIFF_LINES_X\` | 50 |')"
521
- drift_red "threshold sentence pasted into the section" skill "s.replace('### Thresholds','Not security-sensitive: touches no auth, crypto, secrets, PII, or untrusted-input boundary.\n\n### Thresholds')"
522
- drift_red "threshold label pasted into the section" skill "s.replace('### Thresholds','Cheap to reverse.\n\n### Thresholds')"
523
-
524
- # ---- text guard: skills/flow-ship-loop/SKILL.md points at the rubric and holds no copy of it ----
525
- echo "== size tier: ship-loop text guard =="
526
- SHIPGUARD="$ROOT/tests/scripts/lib/ship-loop-sizing-guard.mjs"; SHIP="$ROOT/skills/flow-ship-loop/SKILL.md"
527
- if d="$(node "$SHIPGUARD" "$SHIP" "$SKILL" 2>&1)"; then ok "ship-loop and skill agree: $d"; else bad "ship-loop text guard failed: $d"; fi
528
- ship_red() { # $1 = label, $2 = node expression over `s` (ship-loop.md) returning the mutated text
529
- node -e "const fs=require('fs');const s=fs.readFileSync(process.argv[1],'utf8');const t=($2);if(t===s){process.exit(3)}fs.writeFileSync(process.argv[2],t)" "$SHIP" "$TMP/ship.md" || { bad "ship-loop mutation '$1' did not apply"; return; }
530
- if node "$SHIPGUARD" "$TMP/ship.md" "$SKILL" >/dev/null 2>&1; then bad "ship-loop mutation '$1' left the guard green"; else ok "ship-loop mutation '$1' turns the guard red"; fi
531
- }
532
- ship_red "skill reference removed" "s.replace('somi-routing/SKILL.md#size-tiers','somi-routing/SKILL.md')"
533
- ship_red "skill reference duplicated" "s.replace('### Stage 0','See ../skills/somi-routing/SKILL.md#size-tiers again.\n\n### Stage 0')"
534
- ship_red "threshold constant pasted" "s.replace('### Stage 0','Above MAX_FILES it is full.\n\n### Stage 0')"
535
- ship_red "signal id pasted" "s.replace('### Stage 0','Check hard_surface first.\n\n### Stage 0')"
536
- ship_red "threshold number pasted" "s.replace('### Stage 0','More than 6 files is full.\n\n### Stage 0')"
537
- ship_red "spelled-out limit pasted" "s.replace('### Stage 0','More than six files is full.\\n\\n### Stage 0')"
538
- ship_red "line limit pasted" "s.replace('### Stage 0','Over 100 production lines is full.\\n\\n### Stage 0')"
539
- ship_red "small line limit pasted" "s.replace('### Stage 0','Trivial means 50 lines at most.\\n\\n### Stage 0')"
540
- ship_red "numeric comparison pasted" "s.replace('### Stage 0','Use full when est >= 7.\\n\\n### Stage 0')"
541
- ship_red "trivial-threshold sentence pasted" "s.replace('### Stage 0','Not security-sensitive: touches no auth, crypto, secrets, PII, or untrusted-input boundary.\n\n### Stage 0')"
542
- ship_red "trivial-threshold label pasted" "s.replace('### Stage 0','Cheap to reverse.\n\n### Stage 0')"
543
-
544
- # ---- text guard: /code and /code-loop accept a brief-only item only with the CLI's tier record ----
545
- echo "== size tier: brief-only text guard =="
546
- BRIEFGUARD="$ROOT/tests/scripts/lib/brief-only-guard.mjs"; CODE="$ROOT/skills/flow-code/SKILL.md"; LOOP="$ROOT/skills/flow-code-loop/SKILL.md"
547
- if d="$(node "$BRIEFGUARD" "$CODE" "$LOOP" 2>&1)"; then ok "brief-only rule: $d"; else bad "brief-only text guard failed: $d"; fi
548
- brief_red() { # $1 = label, $2 = which file (code|loop), $3 = node expression over `s`
549
- local src="$CODE" a="$TMP/code.md" b="$LOOP"; [ "$2" = loop ] && { src="$LOOP"; a="$CODE"; b="$TMP/loop.md"; }
550
- local out="$TMP/$2.md"
551
- node -e "const fs=require('fs');const s=fs.readFileSync(process.argv[1],'utf8');const t=($3);if(t===s){process.exit(3)}fs.writeFileSync(process.argv[2],t)" "$src" "$out" || { bad "brief-only mutation '$1' did not apply"; return; }
552
- if node "$BRIEFGUARD" "$a" "$b" >/dev/null 2>&1; then bad "brief-only mutation '$1' left the guard green"; else ok "brief-only mutation '$1' turns the guard red"; fi
553
- }
554
- brief_red "code.md drops the non-null hash requirement" code "s.replace('non-null \`signals_sha256\`','a \`signals_sha256\`')"
555
- brief_red "code.md drops the small-tier requirement" code "s.replace('\`tier\` equal to\n\`small\`','\`tier\` set').replace('\`tier\` equal to \`small\`','\`tier\` set')"
556
- brief_red "code.md allows hand-made records" code "s.replace('Never create the record or edit it by hand.','')"
557
- brief_red "code.md drops the /plan recommendation" code "s.replace(/recommend\s+\`\/plan <problem>\`/,'carry on')"
558
- brief_red "code-loop.md drops the hash requirement" loop "s.replace('non-null \`signals_sha256\`','a \`signals_sha256\`')"
559
- brief_red "code-loop.md drops the iteration" loop "s.replace('is iteration \`1.1\`','is an iteration')"
560
-
561
- echo "== size tier: $pass passed, $fail failed =="
562
- [ "$fail" = 0 ]