@skathio/somi 4.0.1 → 4.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (151) hide show
  1. package/.claude/settings.json +1 -1
  2. package/.claude-plugin/marketplace.json +1 -1
  3. package/.claude-plugin/plugin.json +1 -1
  4. package/.copilot-extension/extension.json +1 -1
  5. package/.copilot-extension/marketplace.json +1 -1
  6. package/README.md +5 -4
  7. package/VERSION +1 -1
  8. package/agents/somi-coder.md +4 -228
  9. package/agents/somi-designer.md +4 -160
  10. package/agents/somi-discovery-analyst.md +4 -276
  11. package/agents/somi-flow.md +47 -0
  12. package/agents/somi-general.md +36 -0
  13. package/agents/somi-planner.md +4 -341
  14. package/agents/somi-reviewer.md +4 -199
  15. package/agents/somi.md +81 -253
  16. package/commands/adopt.md +6 -84
  17. package/commands/architecture-review.md +11 -86
  18. package/commands/atlas.md +10 -25
  19. package/commands/code-loop.md +10 -221
  20. package/commands/code-parallel.md +10 -151
  21. package/commands/code.md +9 -157
  22. package/commands/debug.md +9 -131
  23. package/commands/design.md +9 -160
  24. package/commands/discover.md +9 -194
  25. package/commands/impact.md +9 -25
  26. package/commands/incident.md +9 -39
  27. package/commands/plan-loop.md +9 -181
  28. package/commands/plan.md +9 -244
  29. package/commands/pr.md +10 -25
  30. package/commands/refactor-design.md +11 -89
  31. package/commands/refactor.md +11 -50
  32. package/commands/release-readiness.md +11 -70
  33. package/commands/review-panel.md +10 -141
  34. package/commands/review.md +11 -181
  35. package/commands/security-review.md +11 -75
  36. package/commands/ship-loop.md +9 -260
  37. package/commands/ship.md +9 -115
  38. package/commands/somi-config.md +11 -130
  39. package/commands/test-strategy.md +11 -75
  40. package/commands/upgrade.md +9 -72
  41. package/hooks/hooks.json +1 -1
  42. package/hooks/lib/common.mjs +8 -5
  43. package/hooks/pre-tool/block-dangerous-bash.mjs +1 -1
  44. package/hooks/pre-tool/block-secret-writes.mjs +5 -7
  45. package/hooks/pre-tool/guard-protected-paths.mjs +54 -34
  46. package/package.json +1 -1
  47. package/scripts/lib/cost-defaults.mjs +2 -0
  48. package/scripts/lib/escalation-facts.mjs +146 -0
  49. package/scripts/lib/escalation.mjs +129 -0
  50. package/scripts/lib/findings-ledger.mjs +241 -0
  51. package/scripts/lib/install-text.mjs +97 -0
  52. package/scripts/lib/loop-caps.mjs +140 -0
  53. package/scripts/lib/loop-diff.mjs +12 -70
  54. package/scripts/lib/loop-engine.mjs +227 -0
  55. package/scripts/lib/loop-escalate.mjs +49 -0
  56. package/scripts/lib/loop-exit.mjs +47 -0
  57. package/scripts/lib/loop-notes-compact.mjs +72 -0
  58. package/scripts/lib/loop-notes.mjs +282 -0
  59. package/scripts/lib/loop-review.mjs +355 -12
  60. package/scripts/lib/loop-state.mjs +44 -0
  61. package/scripts/lib/loop-step-close.mjs +75 -0
  62. package/scripts/lib/loop-step-kit.mjs +179 -0
  63. package/scripts/lib/loop-step-review.mjs +140 -0
  64. package/scripts/lib/loop-step-tool.mjs +89 -0
  65. package/scripts/lib/loop-step.mjs +303 -0
  66. package/scripts/lib/mcp-project-root.mjs +18 -7
  67. package/scripts/lib/path-facts.mjs +187 -0
  68. package/scripts/lib/path-safety.mjs +171 -0
  69. package/scripts/lib/run-card.mjs +73 -0
  70. package/scripts/size-budget-overrides.json +5 -13
  71. package/scripts/somi-card.mjs +39 -0
  72. package/scripts/somi-findings.mjs +56 -271
  73. package/scripts/somi-loop.mjs +84 -443
  74. package/scripts/somi-mcp.mjs +26 -95
  75. package/scripts/validate.sh +75 -57
  76. package/skills/flow-adopt/SKILL.md +92 -0
  77. package/skills/flow-architecture-review/SKILL.md +94 -0
  78. package/skills/flow-atlas/SKILL.md +34 -0
  79. package/skills/flow-code/SKILL.md +167 -0
  80. package/skills/flow-code-loop/SKILL.md +263 -0
  81. package/skills/flow-code-parallel/SKILL.md +160 -0
  82. package/skills/flow-debug/SKILL.md +141 -0
  83. package/skills/flow-design/SKILL.md +170 -0
  84. package/skills/flow-discover/SKILL.md +204 -0
  85. package/skills/flow-impact/SKILL.md +35 -0
  86. package/skills/flow-incident/SKILL.md +49 -0
  87. package/skills/flow-plan/SKILL.md +254 -0
  88. package/skills/flow-plan-loop/SKILL.md +254 -0
  89. package/skills/flow-pr/SKILL.md +34 -0
  90. package/skills/flow-refactor/SKILL.md +58 -0
  91. package/skills/flow-refactor-design/SKILL.md +97 -0
  92. package/skills/flow-release-readiness/SKILL.md +82 -0
  93. package/skills/flow-review/SKILL.md +193 -0
  94. package/skills/flow-review-panel/SKILL.md +154 -0
  95. package/skills/flow-security-review/SKILL.md +83 -0
  96. package/skills/flow-ship/SKILL.md +125 -0
  97. package/skills/flow-ship-loop/SKILL.md +274 -0
  98. package/skills/flow-somi-config/SKILL.md +142 -0
  99. package/skills/flow-status/SKILL.md +43 -0
  100. package/skills/flow-test-strategy/SKILL.md +83 -0
  101. package/skills/flow-upgrade/SKILL.md +82 -0
  102. package/skills/role-coder/SKILL.md +247 -0
  103. package/skills/role-designer/SKILL.md +172 -0
  104. package/skills/role-discovery-analyst/SKILL.md +288 -0
  105. package/skills/role-planner/SKILL.md +353 -0
  106. package/skills/role-reviewer/SKILL.md +218 -0
  107. package/skills/somi-checkpoint/SKILL.md +95 -0
  108. package/skills/somi-dispatch/SKILL.md +14 -14
  109. package/skills/somi-routing/SKILL.md +6 -2
  110. package/tests/hooks/cases/block-secret-writes.json +6 -1
  111. package/tests/hooks/cases/guard-protected-paths.json +44 -2
  112. package/tests/hooks/run.sh +21 -0
  113. package/tests/scripts/checkpoint-gate.sh +2 -2
  114. package/tests/scripts/cost-defaults.sh +2 -0
  115. package/tests/scripts/dispatch-line-gate.sh +4 -4
  116. package/tests/scripts/dispatch-reference-gate.sh +14 -14
  117. package/tests/scripts/escalation.sh +409 -0
  118. package/tests/scripts/eval-runner.sh +8 -7
  119. package/tests/scripts/fact-sheet.sh +296 -0
  120. package/tests/scripts/goldens/somi-loop.json +2 -2
  121. package/tests/scripts/lib/dispatch-reference-gate.mjs +14 -5
  122. package/tests/scripts/lib/escalation-facts-tests.mjs +140 -0
  123. package/tests/scripts/lib/escalation-tests.mjs +154 -0
  124. package/tests/scripts/lib/findings-ledger-tests.mjs +118 -0
  125. package/tests/scripts/lib/loop-engine-tests.mjs +287 -0
  126. package/tests/scripts/lib/loop-escalate-tests.mjs +356 -0
  127. package/tests/scripts/lib/loop-flow-gate.mjs +173 -0
  128. package/tests/scripts/lib/loop-notes-tests.mjs +384 -0
  129. package/tests/scripts/lib/loop-step-cli-tests.mjs +156 -0
  130. package/tests/scripts/lib/loop-step-close-tests.mjs +351 -0
  131. package/tests/scripts/lib/loop-step-lenient-tests.mjs +114 -0
  132. package/tests/scripts/lib/loop-step-state-tests.mjs +127 -0
  133. package/tests/scripts/lib/loop-step-tests.mjs +499 -0
  134. package/tests/scripts/lib/loop-step-unwritten-tests.mjs +55 -0
  135. package/tests/scripts/lib/path-facts-tests.mjs +198 -0
  136. package/tests/scripts/lib/path-safety-tests.mjs +201 -0
  137. package/tests/scripts/lib/run-suites.mjs +139 -0
  138. package/tests/scripts/lib/sizing-score-tests.mjs +210 -0
  139. package/tests/scripts/lib/sizing-set-tests.mjs +131 -0
  140. package/tests/scripts/lib/somi-mcp-loop-tests.mjs +226 -0
  141. package/tests/scripts/lib/somi-mcp-tests.mjs +21 -1
  142. package/tests/scripts/loop-engine.sh +22 -0
  143. package/tests/scripts/loop-flow-gate.sh +11 -0
  144. package/tests/scripts/review-panel-seats.sh +4 -4
  145. package/tests/scripts/run-card.sh +57 -0
  146. package/tests/scripts/run-suites.sh +74 -0
  147. package/tests/scripts/run.sh +11 -0
  148. package/tests/scripts/size-tier.sh +3 -3
  149. package/tests/scripts/somi-agent-dispatch-contract.sh +23 -3
  150. package/tests/scripts/somi-mcp.sh +1 -0
  151. package/tests/scripts/suite-plan.json +20 -0
@@ -0,0 +1,296 @@
1
+ #!/usr/bin/env bash
2
+ # Guards the fact-sheet library modules under scripts/lib. Each section runs a module's test lib, then proves
3
+ # the suite has teeth: every mutation of the module, applied to a scratch copy, must turn the test NAMED for it red
4
+ # (a mutant that fails some other way, or not at all, is a failure). Hermetic: temp tree only, no network, no model.
5
+ set -uo pipefail
6
+ umask 022
7
+
8
+ ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
9
+ TMP="$(mktemp -d)"
10
+ trap 'chmod -R u+rwx "$TMP" 2>/dev/null; rm -rf "$TMP"' EXIT
11
+ pass=0; fail=0
12
+ ok() { pass=$((pass+1)); printf ' ok %s\n' "$1"; }
13
+ bad() { fail=$((fail+1)); printf ' FAIL %s\n' "$1"; }
14
+
15
+ # run_suite <test lib> <module>: prints the suite's lines, folds its SUMMARY into the totals.
16
+ run_suite() {
17
+ local out rc total failed
18
+ out="$(node "$1" "$2" 2>&1)"; rc=$?
19
+ printf '%s\n' "$out" | grep -v '^SUMMARY'
20
+ total="$(printf '%s\n' "$out" | awk '/^SUMMARY/{print $2}')"; failed="$(printf '%s\n' "$out" | awk '/^SUMMARY/{print $3}')"
21
+ pass=$((pass + ${total:-0} - ${failed:-0})); fail=$((fail + ${failed:-1}))
22
+ [ "$rc" = 0 ] || [ "${failed:-1}" -gt 0 ] || fail=$((fail+1))
23
+ }
24
+
25
+ # mutate <test lib> <module> <label> <test it must break> <from> <to>: the first <from> in the module becomes <to>.
26
+ mutate() {
27
+ local lib="$1" mod="$2" label="$3" named="$4" mut="$TMP/mutant-$(basename "$2")"
28
+ node -e "const fs=require('fs');const s=fs.readFileSync(process.argv[1],'utf8');const t=s.replace(process.argv[2],()=>process.argv[3]);if(t===s)process.exit(3);fs.writeFileSync(process.argv[4],t)" "$mod" "$5" "$6" "$mut"
29
+ if [ $? != 0 ]; then bad "mutation '$label' did not change the module (stale pattern)"; return; fi
30
+ local out; out="$(node "$lib" "$mut" 2>&1)"
31
+ if grep -qF -- " FAIL $named" <<<"$out"; then ok "mutation '$label' turns '$named' red"; else bad "mutation '$label' did not turn '$named' red"; fi
32
+ }
33
+
34
+ # ---- scripts/lib/path-safety.mjs ----
35
+ echo "== fact sheet: path safety =="
36
+ PS="$ROOT/scripts/lib/path-safety.mjs"; PST="$ROOT/tests/scripts/lib/path-safety-tests.mjs"
37
+ run_suite "$PST" "$PS"
38
+ ps() { mutate "$PST" "$PS" "$@"; }
39
+ T_STAT='a deny-listed name is decided without any filesystem call'
40
+ ps 'deny-list stats the file' "$T_STAT" "if (denied) return { kind: 'denied' };" "if (denied) { try { fs.lstatSync(root); } catch { /* the probe is the call itself */ } return { kind: 'denied' }; }"
41
+ ps 'refusal drops the denied fact' 'a malformed deny-listed name returns the refusal id' 'if (bad) return refused(bad, denied);' 'if (bad) return refused(bad);'
42
+ ps 'case folding removed' 'denies case variants' ".normalize('NFKC').toUpperCase().toLowerCase()" ".normalize('NFKC')"
43
+ ps 'compatibility normalisation removed' 'denies a name written with another separator' ".normalize('NFKC').toUpperCase().toLowerCase()" '.toUpperCase().toLowerCase()'
44
+ ps 'full case folding reduced to lower-casing' 'denies a name that only full case folding' '.toUpperCase().toLowerCase()' '.toLowerCase()'
45
+ ps 'backslash not a separator in the deny test' 'denies a name written with another separator' 'const SEPARATORS = /[\\/]+/;' 'const SEPARATORS = /[/]+/;'
46
+ ps 'trailing dot and space not stripped' 'denies a name written with another separator' 'trimDots(piece)' 'piece'
47
+ T_SEP='denies a name whose compatibility fold writes a separator'
48
+ ps 'fold, then split, restored' "$T_SEP" 'return raw.split(SEPARATORS).some((segment) => {' "return raw.normalize('NFKC').toUpperCase().toLowerCase().split(SEPARATORS).some((segment) => {"
49
+ ps 'the folded segment tested only as its pieces' "$T_SEP" 'new Set([folded, ...folded.split(SEPARATORS)])' 'new Set(folded.split(SEPARATORS))'
50
+ ps 'the folded segment tested only whole' "$T_SEP" 'new Set([folded, ...folded.split(SEPARATORS)])' 'new Set([folded])'
51
+ T_BIG='a huge name is refused as path_length'
52
+ ps 'the raw-length bound removed' "$T_BIG" 'if (raw.length > MAX_PATH_CHARS) return true;' ''
53
+ ps 'the regex trim restored without the bound' "$T_BIG" "if (raw.length > MAX_PATH_CHARS) return true;
54
+ return raw.split(SEPARATORS).some((segment) => {
55
+ const folded = foldName(segment);
56
+ return [...new Set([folded, ...folded.split(SEPARATORS)])].some((piece) => {
57
+ const name = trimDots(piece);" "return raw.split(SEPARATORS).some((segment) => {
58
+ const folded = foldName(segment);
59
+ return [...new Set([folded, ...folded.split(SEPARATORS)])].some((piece) => {
60
+ const name = piece.replace(/[. ]+\$/, '');"
61
+ ps 'the short-name rule removed' 'denies Windows short names' '/~\d/.test(name) || ' ''
62
+ ps 'the stream-suffix rule removed' 'denies Windows short names' "name.includes(':') || " ''
63
+ ps 'the short-name rule over-matches a bare tilde' 'does not deny look-alikes' '/~\d/' '/~/'
64
+ ps 'the short-name rule narrowed to a bare stem' 'floors drive-letter paths and ~<digit> names' '/~\d/.test(name)' '/^[a-z]+~\d$/.test(name)'
65
+ ps 'the drive-letter floor removed' 'floors drive-letter paths and ~<digit> names' "name.includes(':') || " ''
66
+ ps 'the .ssh segment not matched' 'denies .env, key and certificate' "'.ssh', " ''
67
+ ps 'the .tfvars suffix not matched' 'denies .env, key and certificate' "'.tfvars', " ''
68
+ ps 'the .npmrc name not matched' 'denies .env, key and certificate' "'.npmrc', " ''
69
+ T_HOOK='denies the secret names the repository secret-write hook denies'
70
+ T_LIST='the hook secret-name patterns and the representative table list the same literals'
71
+ T_MATCH='each hook pattern, built with its own flags, matches the basename of its representative'
72
+ T_REP='every representative of a hook pattern is denied here'
73
+ T_ADDED='denies .env, key and certificate'
74
+ T_LOOK='does not deny the look-alikes of the added names'
75
+ ps 'the -key.json suffix not matched' "$T_HOOK" "'-key.json', " ''
76
+ ps 'the -key.json suffix over-matches key.json' 'does not deny look-alikes of those names' "'-key.json'" "'key.json'"
77
+ ps 'the credentials.json suffix not matched' "$T_REP" ", 'credentials.json'" ''
78
+ ps 'the credentials.json suffix not matched (file in the name table)' "$T_ADDED" ", 'credentials.json'" ''
79
+ ps 'the credentials.json suffix over-matches any json' 'does not deny look-alikes of those names' ", 'credentials.json'" ", '.json'"
80
+ ps 'the service-account rule not matched' "$T_HOOK" 'service[-_]?account[^]*\.json$|' ''
81
+ ps 'the service-account rule loses its extension' 'does not deny look-alikes of those names' 'service[-_]?account[^]*\.json$' 'service[-_]?account'
82
+ ps 'the service-account rule loses its underscore form' "$T_ADDED" 'service[-_]?account' 'service-?account'
83
+ ps 'the service-account rule loses its optional separator' "$T_ADDED" 'service[-_]?account' 'service[-_]account'
84
+ ps 'the service-account rule matches a bare account.json' "$T_LOOK" 'service[-_]?account' 'account'
85
+ ps 'the client_secret rule not matched' "$T_ADDED" '|client_secret[^]*\.json$' ''
86
+ ps 'the client_secret rule loses its extension' "$T_LOOK" 'client_secret[^]*\.json$' 'client_secret'
87
+ ps 'the .netrc suffix not matched' "$T_REP" " '.netrc', '.pgpass', '-key.json'" " '.pgpass', '-key.json'"
88
+ ps 'the .netrc suffix not matched (name table)' "$T_ADDED" " '.netrc', '.pgpass', '-key.json'" " '.pgpass', '-key.json'"
89
+ ps 'the .pgpass suffix not matched' "$T_REP" " '.pgpass', '-key.json'" " '-key.json'"
90
+ ps 'the .pgpass suffix not matched (name table)' "$T_ADDED" " '.pgpass', '-key.json'" " '-key.json'"
91
+ ps 'the .tfstate.backup suffix not matched' "$T_ADDED" " '.tfstate.backup'," ''
92
+ ps 'the .tfstate.backup suffix over-matches any .backup' "$T_LOOK" "'.tfstate.backup'" "'.backup'"
93
+ ps 'the exact key.json rule removed' "$T_ADDED" '|^key\.json$' ''
94
+ ps 'the key.json rule unanchored' 'does not deny look-alikes of those names' '^key\.json$' 'key\.json$'
95
+ ps 'the tfstate backup-copy rule removed' "$T_ADDED" '|\.tfstate\.[^]*\.backup$' ''
96
+ ps 'the tfstate backup-copy rule over-matches' "$T_LOOK" '\.tfstate\.[^]*\.backup$' '\.tfstate\.[^]*'
97
+ T_TERM='denies a name with a line terminator inside the matched span'
98
+ ps 'the service-account rule stops at a line terminator' "$T_TERM" 'service[-_]?account[^]*\.json$' 'service[-_]?account.*\.json$'
99
+ ps 'the client_secret rule stops at a line terminator' "$T_TERM" 'client_secret[^]*\.json$' 'client_secret.*\.json$'
100
+ ps 'the tfstate backup-copy rule stops at a line terminator' "$T_TERM" '\.tfstate\.[^]*\.backup$' '\.tfstate\..*\.backup$'
101
+ ps 'a bare config denied' 'a bare config stays allowed on purpose' "'.docker', 'credentials'];" "'.docker', 'credentials', 'config'];"
102
+ ps 'credentials denied only as a file, not as a directory' 'credentials/ is denied as a directory' "return raw.split(SEPARATORS).some((segment) => {
103
+ const folded = foldName(segment);
104
+ return [...new Set([folded, ...folded.split(SEPARATORS)])].some((piece) => {
105
+ const name = trimDots(piece);
106
+ return NAME_EXACT.includes(name) ||" "return raw.split(SEPARATORS).some((segment, _, all) => {
107
+ const folded = foldName(segment);
108
+ return [...new Set([folded, ...folded.split(SEPARATORS)])].some((piece) => {
109
+ const name = trimDots(piece);
110
+ return (NAME_EXACT.includes(name) && (name !== 'credentials' || segment === all.at(-1))) ||"
111
+ ps 'the secrets rule not matched' "$T_HOOK" '|secrets?\.(?:ya?ml|json)$' ''
112
+ ps 'the secrets rule loses its extension' 'does not deny look-alikes of those names' 'secrets?\.(?:ya?ml|json)$' 'secrets?\.'
113
+ ps 'the credentials name not matched' "$T_HOOK" ", 'credentials'];" '];'
114
+ ps 'the .tfstate suffix not matched' "$T_HOOK" "'.tfstate', " ''
115
+ ps 'the _netrc name not matched' "$T_HOOK" "'_netrc', " ''
116
+ ps 'the _pgpass name not matched' "$T_HOOK" "'_pgpass', " ''
117
+ ps 'the .htpasswd name not matched' "$T_HOOK" "'.htpasswd', " ''
118
+ ps 'the .p8 suffix not matched' "$T_HOOK" "'.p8', " ''
119
+ ps 'the .vault-token name not matched' "$T_HOOK" ", '.vault-token'" ''
120
+ ps 'the .kube segment not matched' "$T_HOOK" "'.kube', " ''
121
+ ps 'the .docker segment not matched' "$T_HOOK" "'.docker', " ''
122
+ ps 'the hook parity: -key.json dropped from the deny list' "$T_REP" "'-key.json', " ''
123
+ ps 'the hook parity: .kdbx dropped from the deny list (a representative no longer denied)' "$T_REP" "'.kdbx', " ''
124
+ # The hook's own source, copied with one edit and read by the test through SECRET_HOOK_SOURCE.
125
+ HOOK="$ROOT/hooks/pre-tool/block-secret-writes.mjs"
126
+ hk() {
127
+ local label="$1" named="$2" mut="$TMP/hook-mutant.mjs" out
128
+ node -e "const fs=require('fs');const s=fs.readFileSync(process.argv[1],'utf8');const t=s.replace(process.argv[2],()=>process.argv[3]);if(t===s)process.exit(3);fs.writeFileSync(process.argv[4],t)" "$HOOK" "$3" "$4" "$mut"
129
+ if [ $? != 0 ]; then bad "hook mutation '$label' did not change the hook (stale pattern)"; return; fi
130
+ out="$(SECRET_HOOK_SOURCE="$mut" node "$PST" "$PS" 2>&1)"
131
+ if grep -qF -- " FAIL $named" <<<"$out"; then ok "hook mutation '$label' turns '$named' red"; else bad "hook mutation '$label' did not turn '$named' red"; fi
132
+ }
133
+ hk 'a hook pattern gains a flag' "$T_LIST" ' /\.pem$/,' ' /\.pem$/i,'
134
+ hk 'a hook pattern gains a flag the test must build with' "$T_MATCH" ' /\.pem$/,' ' /\.pem$/y,'
135
+ hk 'a hook pattern is added with no representative' "$T_LIST" ' /\.kdbx$/,' ' /\.kdbx$/,
136
+ /\.tfplan$/,'
137
+ hk 'a hook pattern with a character class is added with no representative' "$T_LIST" ' /\.kdbx$/,' ' /\.kdbx$/,
138
+ /[a-z]\.tfplan$/,'
139
+ hk 'a hook entry that is not a plain literal is added' "$T_LIST" ' /\.kdbx$/,' ' /\.kdbx$/,
140
+ new RegExp("x"),'
141
+ hk 'a hook pattern is altered' "$T_LIST" '/-key\.json$/,' '/-key\.jsonl$/,'
142
+ hk 'a hook pattern is removed and its representative goes stale' "$T_LIST" ' /\.pgpass$/,
143
+ ' ''
144
+ ps 'the realpath re-check removed' 'a path whose canonical on-disk spelling is a denied name' "if (denyListed(rel)) return { kind: 'denied' };" ''
145
+ ps 'the .git segment not matched' 'denies .env, key and certificate' "NAME_EXACT.includes(name) || " ''
146
+ ps 'the .env prefix not matched' 'denies .env, key and certificate' "'.env', " ''
147
+ ps 'id_rsa not matched' 'denies .env, key and certificate' "'id_rsa', " ''
148
+ ps 'the .pfx suffix not matched' 'denies .env, key and certificate' "'.pfx', " ''
149
+ ps 'the deny list over-matches .gitignore' 'does not deny look-alikes' "NAME_EXACT.includes(name)" "name.startsWith('.git')"
150
+ ps 'the backslash dropped from the absolute check' 'refuses an absolute path' '^(?:[\\/]|[a-z]:)' '^(?:[/]|[a-z]:)'
151
+ ps 'the absolute check removed' 'refuses an absolute path' "if (ABSOLUTE.test(raw)) return 'absolute';" ''
152
+ ps 'the parent-segment check removed' 'refuses a parent segment' "if (segments.some((s) => PARENT_SEGMENT.test(s))) return 'traversal';" ''
153
+ ps 'control characters allowed' 'refuses NUL and control' '[\p{Cc}\p{Cf}' '[\p{Cf}'
154
+ ps 'bidi characters allowed' 'refuses bidi' '[\p{Cc}\p{Cf}' '[\p{Cc}'
155
+ ps 'lone surrogates allowed' 'refuses lone surrogates' '\p{Cs}' ''
156
+ ps 'a non-string name read as text' 'refuses an empty' "if (typeof raw !== 'string') return 'malformed';" ''
157
+ ps 'the length cap off by one' 'refuses a name over the length cap' 'raw.length > MAX_PATH_CHARS' 'raw.length >= MAX_PATH_CHARS'
158
+ ps 'the count cap off by one' 'refuses a list over the count cap' 'paths.length <= MAX_PATHS' 'paths.length < MAX_PATHS'
159
+ ps 'the list refusal drops the denied fact' 'a list over the cap keeps the denied fact' 'paths.some(denyListed)' 'false'
160
+ ps 'a far-over-cap list is scanned' 'a list far over the cap is refused as denied' "if (paths.length > 4 * MAX_PATHS) return refused('path_count', true);" ''
161
+ ps 'the scan bound off by one' 'a list far over the cap is refused as denied' 'paths.length > 4 * MAX_PATHS' 'paths.length >= 4 * MAX_PATHS'
162
+ ps 'a symlink component allowed' 'refuses a symlinked file' "if (stat.isSymbolicLink()) return { result: refused('symlink') };" ''
163
+ ps 'an escape outside the root allowed' 'refuses a path whose canonical form leaves the root' 'rel.startsWith(`..${path.sep}`) ||' ''
164
+ ps 'the root itself allowed' 'refuses a path whose canonical form leaves the root' "rel === '' ||" ''
165
+ ps 'the parent of the root allowed' 'refuses a path whose canonical form leaves the root' "rel === '..' ||" ''
166
+ ps 'a name starting with two dots read as an escape' 'a file whose name begins with two dots' 'rel.startsWith(`..${path.sep}`)' "rel.startsWith('..')"
167
+ if [ "$(uname -s)" = Linux ]; then ps 'a non-ENOENT lstat error read as a missing file' 'a name the filesystem cannot look up' "if (e.code !== 'ENOENT') return { result: refused('unreadable') };" ''
168
+ else echo " skip mutation 'a non-ENOENT lstat error read as a missing file' on the long-name test (not Linux: the name limit counts bytes only there)"; fi
169
+ if [ "$(id -u)" = 0 ]; then echo " skip mutation 'a non-ENOENT lstat error read as a missing file' on the unreadable-directory test (running as root, which reads it)"
170
+ else ps 'a non-ENOENT lstat error read as a missing file (directory case)' 'a file in an unreadable directory' "if (e.code !== 'ENOENT') return { result: refused('unreadable') };" ''; fi
171
+ ps 'the walk splits on slashes only' 'refuses a parent segment' 'raw.split(SEPARATORS).filter' "raw.split('/').filter"
172
+ ps 'a final non-file is opened' 'a path that does not exist, a directory or a FIFO opens nothing' "if (i === segments.length - 1 && !stat.isFile()) return { result: refused('not_file') };" ''
173
+ ps 'a probe error is rethrown' 'an error from the probe is a refusal' "result = refused('probe');" "throw new Error('PROBEMSG');"
174
+ ps 'a missing parent allowed' 'refuses a directory, a path through a file' "if (i < segments.length - 1) return { result: refused('no_parent') };" ''
175
+ ps 'a file read as a directory' 'refuses a directory, a path through a file' 'i < segments.length - 1 && !stat.isDirectory()' 'false'
176
+ ps 'a directory or device read as a file' 'refuses a directory, a path through a file' "if (!stat.isFile()) throw Object.assign(new Error(), { refusal: 'not_file' });" ''
177
+ ps 'the size cap not applied' 'refuses a file over the size cap' 'stat.size > MAX_FILE_BYTES' 'false'
178
+ ps 'the size cap off by one' 'refuses a file over the size cap' 'stat.size > MAX_FILE_BYTES' 'stat.size >= MAX_FILE_BYTES'
179
+ ps 'the open can block on a FIFO' 'a FIFO is refused and the call returns' ' | constants.O_NONBLOCK' ''
180
+ ps 'the open can take a controlling terminal' 'the open follows no link, cannot block' ' | (constants.O_NOCTTY ?? 0)' ''
181
+ ps 'the open follows a link' 'refuses a link swapped in after the check' ' | constants.O_NOFOLLOW' ''
182
+ ps 'no platform check' 'fails closed with `platform`' "if (!(constants.O_NOFOLLOW > 0 && constants.O_NONBLOCK > 0)) return refused('platform');" ''
183
+ ps 'the platform check ignores O_NONBLOCK' 'fails closed with `platform`' ' && constants.O_NONBLOCK > 0' ''
184
+ ps 'the descriptor is leaked after a probe' 'the descriptor is closed after a probe' 'fs.closeSync(opened.fd);' ''
185
+ ps 'a failed close of the descriptor is rethrown' 'a probe that closes the descriptor is a refusal' "try {
186
+ fs.closeSync(opened.fd);
187
+ } catch {
188
+ return refused(probe ? 'probe' : 'unreadable'); // with a probe, the likely cause is the probe closing the descriptor
189
+ }" 'fs.closeSync(opened.fd);'
190
+ T_CLOSE='a close that fails is unreadable with no probe'
191
+ ps 'a failed close with no probe labelled probe' "$T_CLOSE" "refused(probe ? 'probe' : 'unreadable')" "refused('probe')"
192
+ ps 'a failed close with a probe labelled unreadable' "$T_CLOSE" "refused(probe ? 'probe' : 'unreadable')" "refused('unreadable')"
193
+ ps 'the descriptor is leaked on a refusal' 'the descriptor is closed after a probe' 'fs.closeSync(fd);' ''
194
+ ps 'the probe answer is passed through' 'the probe gets an open descriptor and the size and its answer is a boolean' 'probe(opened.fd, opened.size) === true' 'probe(opened.fd, opened.size)'
195
+ ps 'an unreadable root is read through' 'an unreadable root is refused' "} catch {
196
+ return refused('unreadable');
197
+ }
198
+ if (found.result)" "} catch {
199
+ return { kind: 'contained', exists: false, rel: '' };
200
+ }
201
+ if (found.result)"
202
+
203
+ # ---- scripts/lib/path-facts.mjs ----
204
+ echo "== fact sheet: path facts =="
205
+ PF="$ROOT/scripts/lib/path-facts.mjs"; PFT="$ROOT/tests/scripts/lib/path-facts-tests.mjs"
206
+ ln -s "$PS" "$TMP/path-safety.mjs" # a scratch copy of the module imports its sibling
207
+ run_suite "$PFT" "$PF"
208
+ # The timed cost check costs about a second a run, so only the mutants that name it run it.
209
+ # SKIP_TIMED is honoured only as the value mutant-run (see the stray-seam check at the end).
210
+ pf() { local skip_timed=mutant-run; case "$2" in *nested-quantifier*|*adjacent*) skip_timed= ;; esac; SKIP_TIMED=$skip_timed mutate "$PFT" "$PF" "$@"; }
211
+ T_FLAG='an unconfigured repo flags .env, a migrations directory, a lockfile and a route file'
212
+ T_ADD='config globs are added to the built-ins, not instead of them'
213
+ T_CONT='still two with an empty container list'
214
+ T_HOSTILE='a hostile section reads as the defaults'
215
+ T_DIR='a directory glob with a slash is anchored'
216
+ T_LIT='a config glob is literal text except star'
217
+ T_UNUSABLE='an unusable entry floors instead of vanishing'
218
+ T_KEY='module key under a built-in container'
219
+ T_DENY='a denied name reports a deny_list hit'
220
+ pf 'a default glob dropped: migrations' "$T_FLAG" "migrations: ['migrations', 'migration*', 'migrate']," 'migrations: [],'
221
+ pf 'a default glob dropped: routes' "$T_FLAG" "routes: ['routes', " "routes: ["
222
+ pf 'a default glob dropped: the lockfile name' "$T_FLAG" "'package-lock.json', " ''
223
+ pf 'config replaces the sensitive globs' "$T_ADD" "const sensitive = [...SENSITIVE, ['config', extra.sensitive]];" "const sensitive = extra.sensitive.length ? [['config', extra.sensitive]] : SENSITIVE;"
224
+ pf 'config replaces the built-in containers' "$T_CONT" 'new Set([...BUILTIN_CONTAINERS, ...extra.containers])' 'new Set(extra.containers.length ? extra.containers : BUILTIN_CONTAINERS)'
225
+ T_CSPLIT='a configured container splits its children'
226
+ pf 'config containers are ignored' "$T_CSPLIT" 'out.containers.push(...names.map(containerName))' 'names.map(containerName)'
227
+ pf 'a container name is not reduced to one segment' "$T_CSPLIT" 'const s = globParts(g);' 'const s = [fold(g)];'
228
+ pf 'a container with a slash or wildcard accepted' "$T_HOSTILE" 's.length === 1 && !/[*?]/.test(s[0])' 's.length > 0'
229
+ pf 'a test file counted as production' 'a test file is not a production file' 'production: !isTest(segs)' 'production: true'
230
+ pf 'a test directory not recognised' 'a test file is not a production file' 'TEST_DIRS.has(s)' 'false'
231
+ pf 'a test file name not recognised' 'a test file is not a production file' " || TEST_FILES.some((g) => segMatch(g, segs.at(-1) ?? ''))" ''
232
+ pf 'the deny floor left out of the aggregates' "$T_DENY" 'const floor = denied ? [DENY_LIST] : [];' 'const floor = [];'
233
+ pf 'a hostile entry not floored' "$T_UNUSABLE" 'const denied = !usable || denyListed(raw);' 'const denied = usable && denyListed(raw);'
234
+ pf 'a list over the count cap classified' "$T_UNUSABLE" 'Array.isArray(paths) && paths.length <= MAX_PATHS && ' 'Array.isArray(paths) && '
235
+ pf 'a long path echoed' "$T_UNUSABLE" "path: usable ? raw : ''," 'path: raw,'
236
+ pf 'the module key loses its container' 'one name under two containers' '`${segs[0]}/${segs[1]}`' 'segs[1]'
237
+ pf 'the module count counts files' 'one name under two containers' 'modules: new Set(files.map((f) => f.module)).size' 'modules: files.length'
238
+ pf 'a root file keyed by its name' 'module key: first segment' "if (segs.length < 2) return '';" ''
239
+ pf 'a file in a container keyed by its name' "$T_KEY" 'containers.has(head) && segs.length > 2' 'containers.has(head)'
240
+ pf 'case folding removed' 'matching is case-folded' "denyListed, foldName as fold, trimDots as trim } from './path-safety.mjs';" "denyListed, trimDots as trim } from './path-safety.mjs'; const fold = (s) => s;"
241
+ pf 'the module key is folded' 'the module key keeps the case' '`${segs[0]}/${segs[1]}` : segs[0]' '`${segs[0]}/${segs[1]}`.toLowerCase() : segs[0].toLowerCase()'
242
+ pf 'the container match is not folded' 'the module key keeps the case' 'const head = trim(fold(segs[0]));' 'const head = trim(segs[0]);'
243
+ T_TRIM='the trim is an extra reading'
244
+ pf 'the trimmed readings dropped' 'a trailing dot or space on a segment' '[p, trimmed(p), r, trimmed(r)]' '[p, r]'
245
+ pf 'the untrimmed readings dropped' "$T_TRIM" '[p, trimmed(p), r, trimmed(r)]' '[trimmed(p), trimmed(r)]'
246
+ T_FOLDSEP='a code point that folds to a separator'
247
+ pf 'the re-split readings dropped' "$T_FOLDSEP: the primary" '[p, trimmed(p), r, trimmed(r)]' '[p, trimmed(p)]'
248
+ pf 'the primary reading is the re-split one' "$T_FOLDSEP stays inside" 'const split = (s) => parts(s).map(fold);' 'const split = (s) => parts(fold(s));'
249
+ pf 'the test judgement reads the trimmed segments' 'a name that trims to a test directory' 'production: !isTest(segs)' 'production: !isTest(trimmed(segs))'
250
+ T_GTRIM='a glob or a container written with a trailing dot or space'
251
+ pf 'a container lookup reads the first segment as written' "$T_GTRIM" 'const head = trim(fold(segs[0]));' 'const head = fold(segs[0]);'
252
+ pf 'a container name keeps its trailing dot' "$T_GTRIM" 'const s = globParts(g); return s.length === 1' 'const s = split(g); return s.length === 1'
253
+ pf 'a glob keeps its trailing dot' "$T_GTRIM" "? globParts(glob) : ['**', ...globParts(glob)]" "? split(glob) : ['**', ...split(glob)]"
254
+ pf 'a glob that trims to nothing accepted' "$T_HOSTILE" ' && globParts(g).length > 0' ''
255
+ pf 'a glob whose trim leaves only wildcards accepted' "$T_HOSTILE" ' && !widened(g)' ''
256
+ pf 'a glob that trims to nothing is judged untrimmed' "$T_HOSTILE" 'globParts(g).length > 0' 'split(g).length > 0'
257
+ pf 'the unusable-entry module key can collide with a real segment' 'an unusable entry has a module key no real path can have' '`/?${i}`' '`?${i}`'
258
+ pf 'a glob with a slash not anchored' "$T_DIR" "/[\\\\/]/.test(glob) ? globParts(glob) : ['**', ...globParts(glob)]" "['**', ...globParts(glob)]"
259
+ pf 'a ** segment read as one segment' "$T_DIR" "part === '**'" 'part === "\0"'
260
+ pf 'a ** step restarts from every position' 'nested-quantifier shapes' 'for (let k = Math.min(...at); k <= segs.length; k++) next.add(k);' 'for (const pos of at) for (let k = pos; k <= segs.length; k++) next.add(k);'
261
+ pf 'a test directory named fixtures' 'a test file is not a production file' "'e2e', '__mocks__'" "'e2e', 'fixtures', '__mocks__'"
262
+ pf 'layers read as the last one only' 'a later layer, valid, empty' 'Array.isArray(l) ? l : [l]' 'Array.isArray(l) ? l.slice(-1) : [l]'
263
+ pf 'one invalid key drops the whole layer' 'one invalid key drops only itself' 'if (bounded(globs, validGlob)) out' 'if (bounded(globs, validGlob) && bounded(names, validGlob)) out'
264
+ pf 'an unusable list reported as one entry' 'an unusable list reports the counts' 'Array(MAX_PATHS).fill(null)' '[null]'
265
+ pf 'a glob no longer matches what is under its directory' "$T_DIR" 'return at.size > 0;' 'return at.has(segs.length);'
266
+ pf 'a star cannot backtrack' "$T_LIT" 'else if (star >= 0) { i = star + 1; j = ++mark; }' ''
267
+ pf 'the matcher builds a regex from config text' "$T_LIT" 'function segMatch(p, s) {' 'function segMatch(p, s) { return new RegExp(`^${p.replace(/\*/g, ".*").replace(/\?/g, ".")}$`).test(s); }
268
+ function segMatchUnused(p, s) {'
269
+ pf 'the glob length cap removed' 'a glob whose fold exceeds the glob cap' ' && g.length <= MAX_GLOB_CHARS' ''
270
+ pf 'the glob count cap off by one' "$T_HOSTILE" 'v.length <= MAX_GLOBS' 'v.length <= MAX_GLOBS + 1'
271
+ pf 'a glob with .. accepted' "$T_HOSTILE" " && !g.includes('..')" ''
272
+ pf 'an absolute glob accepted' "$T_HOSTILE" ' && !/^(?:[\\/]|[a-z]:)/i.test(g)' ''
273
+ pf 'a glob with control characters accepted' "$T_HOSTILE" '!/[\p{C}\p{Zl}\p{Zp}]/u.test(g) && ' ''
274
+ pf 'a non-array section accepted' "$T_HOSTILE" 'Array.isArray(v) && ' ''
275
+ # the ci class, the layer cap and the folded caps
276
+ T_CI='every CI system is a ci hit'
277
+ pf 'the ci list emptied' "$T_CI" "ci: ['.github'," "cx: ['.github',"
278
+ pf 'a CI system dropped from the ci list' "$T_CI" "'.circleci', " ''
279
+ pf 'config removes the ci class' 'a config cannot remove the ci class' "const sensitive = [...SENSITIVE, ['config', extra.sensitive]];" "const sensitive = [...SENSITIVE.filter(([n]) => n !== 'ci' || extra.sensitive.length === 0), ['config', extra.sensitive]];"
280
+ pf 'the loadConfig result read as one layer' "loadConfig's {global, project} result is the layers" '[l.global.config, l.project.config]' '[l.config]'
281
+ pf 'the loadConfig result read as the global layer only' "loadConfig's {global, project} result is the layers" '[l.global.config, l.project.config]' '[l.global.config]'
282
+ pf 'the path cap counts the raw text only' 'a path whose fold exceeds the path cap' ' && fold(raw).length <= MAX_PATH_CHARS' ''
283
+ pf 'the glob cap counts the raw text only' 'a glob whose fold exceeds the glob cap' ' && fold(g).length <= MAX_GLOB_CHARS' ''
284
+ pf 'the layer cap removed' 'more layers than loadConfig supplies' ' && layerList.length <= MAX_LAYERS' ''
285
+ pf 'a refused key is not reported' 'a refused key is named in refused' "; else out.refused.push('sensitive_paths');" ';'
286
+ pf 'a wildcard then a dot segment still widens nothing' "$T_HOSTILE" "(t === '' && wild(r[i - 1] ?? ''))" 'false'
287
+ pf 'adjacent ** segments not collapsed' 'adjacent ** segments in a glob are one step' 'const compile = (glob) => collapse(' 'const compile = (glob) => ((x) => x)('
288
+
289
+ # A stray exported seam must change nothing: the timed cost check and the real-hook parity check still run.
290
+ # Stated residual: this runs the real module with a stray value, not a stale copy that is named like a sentinel; the guard under test is the exact comparison.
291
+ stray="$(env SKIP_TIMED=1 SECRET_HOOK_SOURCE=/dev/null node "$PFT" "$PF" 2>&1; env SKIP_TIMED=1 SECRET_HOOK_SOURCE=/dev/null node "$PST" "$PS" 2>&1)"
292
+ if grep -qF ' ok nested-quantifier shapes' <<<"$stray" && grep -qF ' ok the hook secret-name patterns and the representative table' <<<"$stray" && ! grep -qF ' skip nested-quantifier' <<<"$stray" && ! grep -qF ' skip adjacent' <<<"$stray"; then ok 'a stray exported SKIP_TIMED and SECRET_HOOK_SOURCE skip and repoint nothing'; else bad 'a stray exported SKIP_TIMED or SECRET_HOOK_SOURCE changed a check'; fi
293
+
294
+ total=$((pass + fail))
295
+ echo "SUMMARY $total checks, $fail failed"
296
+ [ "$fail" = 0 ]
@@ -132,7 +132,7 @@
132
132
  "1.1"
133
133
  ],
134
134
  "exit": 0,
135
- "stdout": "{\"slug\":\"g\",\"loop\":\"code\",\"iteration\":\"1.1\",\"baseline_sha\":\"<SHA>\",\"started\":\"<TS>\",\"status\":\"running\",\"caps\":{\"max_passes\":2,\"diff_cap_lines\":10,\"severity_floor\":\"Major\"},\"iteration_files\":[\"src/a.txt\"],\"pass\":2,\"history\":[{\"pass\":2,\"verdict\":\"request-changes\",\"blockers\":0,\"majors\":2,\"diff_lines\":7,\"tree\":\"<SHA>\",\"at\":\"<TS>\"}]}",
135
+ "stdout": "{\"slug\":\"g\",\"loop\":\"code\",\"iteration\":\"1.1\",\"baseline_sha\":\"<SHA>\",\"started\":\"<TS>\",\"status\":\"running\",\"caps\":{\"max_passes\":2,\"diff_cap_lines\":10,\"severity_floor\":\"Major\"},\"iteration_files\":[\"src/a.txt\"],\"pass\":2,\"history\":[{\"pass\":2,\"verdict\":\"request-changes\",\"blockers\":0,\"majors\":2,\"diff_lines\":7,\"tree\":\"<SHA>\",\"at\":\"<TS>\"}],\"ignored_guarded\":{\"over\":false,\"files\":{}}}",
136
136
  "stderr": ""
137
137
  },
138
138
  {
@@ -162,7 +162,7 @@
162
162
  "1.1"
163
163
  ],
164
164
  "exit": 0,
165
- "stdout": "{\n \"slug\": \"g\",\n \"loop\": \"code\",\n \"iteration\": \"1.1\",\n \"baseline_sha\": \"<SHA>\",\n \"started\": \"<TS>\",\n \"status\": \"stopped-diff-cap\",\n \"caps\": {\n \"max_passes\": 2,\n \"diff_cap_lines\": 10,\n \"severity_floor\": \"Major\"\n },\n \"iteration_files\": [\n \"src/a.txt\"\n ],\n \"pass\": 2,\n \"history\": [\n {\n \"pass\": 2,\n \"verdict\": \"request-changes\",\n \"blockers\": 0,\n \"majors\": 2,\n \"diff_lines\": 7,\n \"tree\": \"<SHA>\",\n \"at\": \"<TS>\"\n }\n ],\n \"finished\": \"<TS>\"\n}",
165
+ "stdout": "{\n \"slug\": \"g\",\n \"loop\": \"code\",\n \"iteration\": \"1.1\",\n \"baseline_sha\": \"<SHA>\",\n \"started\": \"<TS>\",\n \"status\": \"stopped-diff-cap\",\n \"caps\": {\n \"max_passes\": 2,\n \"diff_cap_lines\": 10,\n \"severity_floor\": \"Major\"\n },\n \"iteration_files\": [\n \"src/a.txt\"\n ],\n \"pass\": 2,\n \"history\": [\n {\n \"pass\": 2,\n \"verdict\": \"request-changes\",\n \"blockers\": 0,\n \"majors\": 2,\n \"diff_lines\": 7,\n \"tree\": \"<SHA>\",\n \"at\": \"<TS>\"\n }\n ],\n \"ignored_guarded\": {\n \"over\": false,\n \"files\": {}\n },\n \"finished\": \"<TS>\"\n}",
166
166
  "stderr": ""
167
167
  }
168
168
  ]
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- // dispatch-reference-gate.mjs — asserts that every commands/*.md file which starts a real agent
2
+ // dispatch-reference-gate.mjs — asserts that every workflow procedure (skills/flow-*/SKILL.md) that starts a real agent
3
3
  // (a `Task` call naming one of the files under agents/) references skills/somi-dispatch/SKILL.md
4
4
  // somewhere in its own text -- every entry path that starts an agent resolves it through the same
5
5
  // dispatch procedure, not just the front door. "Starts an agent" is DERIVED from the real
@@ -64,12 +64,21 @@ export function agentNamesFrom(agentsDir) {
64
64
  .filter((n) => n !== 'somi');
65
65
  }
66
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
+
67
79
  export function scan(commandsDir, agentsDir) {
68
80
  const agentNames = agentNamesFrom(agentsDir);
69
- const files = fs
70
- .readdirSync(commandsDir)
71
- .filter((f) => f.endsWith('.md'))
72
- .sort();
81
+ const files = procedureFiles(commandsDir);
73
82
 
74
83
  const checked = [];
75
84
  const missing = [];
@@ -0,0 +1,140 @@
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);