@skathio/somi 1.2.0 → 2.0.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 (60) hide show
  1. package/.claude/settings.json +9 -9
  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 +6 -1
  7. package/VERSION +1 -1
  8. package/commands/adopt.md +6 -4
  9. package/commands/code-loop.md +13 -13
  10. package/commands/plan-loop.md +10 -10
  11. package/commands/pr.md +1 -1
  12. package/commands/release-readiness.md +4 -4
  13. package/commands/review-panel.md +1 -1
  14. package/commands/review.md +3 -3
  15. package/commands/ship-loop.md +2 -2
  16. package/commands/somi.md +2 -2
  17. package/commands/upgrade.md +1 -1
  18. package/examples/sample-consumer/CLAUDE.md +5 -2
  19. package/examples/sample-consumer/README.md +20 -9
  20. package/hooks/hooks.json +8 -8
  21. package/hooks/lib/common.mjs +328 -0
  22. package/hooks/post-tool/audit-log.mjs +93 -0
  23. package/hooks/post-tool/lint-changed-files.mjs +212 -0
  24. package/hooks/pre-tool/block-dangerous-bash.mjs +382 -0
  25. package/hooks/pre-tool/block-secret-writes.mjs +96 -0
  26. package/hooks/pre-tool/gate-dep-install.mjs +229 -0
  27. package/hooks/pre-tool/guard-protected-paths.mjs +157 -0
  28. package/hooks/session-start/detect-repo-instructions.mjs +264 -0
  29. package/hooks/user-prompt-submit/inject-workflow-context.mjs +432 -0
  30. package/package.json +2 -2
  31. package/rules/CLAUDE.md +6 -5
  32. package/scripts/somi-check.mjs +243 -0
  33. package/scripts/somi-findings.mjs +307 -0
  34. package/scripts/somi-loop.mjs +354 -0
  35. package/scripts/validate.sh +21 -16
  36. package/skills/clean-code/SKILL.md +1 -1
  37. package/tests/hooks/cases/audit-log.json +21 -0
  38. package/tests/hooks/cases/block-dangerous-bash.json +90 -2
  39. package/tests/hooks/cases/block-secret-writes.json +1 -1
  40. package/tests/hooks/cases/detect-repo-instructions.json +84 -0
  41. package/tests/hooks/cases/gate-dep-install.json +6 -1
  42. package/tests/hooks/cases/guard-protected-paths.json +1 -1
  43. package/tests/hooks/cases/inject-workflow-context.json +126 -0
  44. package/tests/hooks/cases/lint-changed-files.json +120 -0
  45. package/tests/hooks/run.sh +280 -15
  46. package/tests/scripts/goldens/somi-findings.json +336 -0
  47. package/tests/scripts/goldens/somi-loop.json +168 -0
  48. package/tests/scripts/run.sh +251 -30
  49. package/hooks/lib/common.sh +0 -133
  50. package/hooks/post-tool/audit-log.sh +0 -40
  51. package/hooks/post-tool/lint-changed-files.sh +0 -80
  52. package/hooks/pre-tool/block-dangerous-bash.sh +0 -171
  53. package/hooks/pre-tool/block-secret-writes.sh +0 -83
  54. package/hooks/pre-tool/gate-dep-install.sh +0 -113
  55. package/hooks/pre-tool/guard-protected-paths.sh +0 -89
  56. package/hooks/session-start/detect-repo-instructions.sh +0 -73
  57. package/hooks/user-prompt-submit/inject-workflow-context.sh +0 -143
  58. package/scripts/somi-check.sh +0 -135
  59. package/scripts/somi-findings.sh +0 -173
  60. package/scripts/somi-loop.sh +0 -225
@@ -0,0 +1,229 @@
1
+ #!/usr/bin/env node
2
+ // hooks/pre-tool/gate-dep-install.mjs — PreToolUse hook (matcher: Bash) — gate
3
+ // dependency-adding commands.
4
+ //
5
+ // Node port of hooks/pre-tool/gate-dep-install.sh (node-runtime-port, phase 2,
6
+ // iteration 2.4). Imports the shared read/deny/audit/config helpers from
7
+ // ../lib/common.mjs (2.1, reviewer-blessed) rather than reimplementing them.
8
+ //
9
+ // Adding a runtime dependency crosses a trust boundary: it imports unreviewed code,
10
+ // expands attack surface, and creates a long-term maintenance obligation. The coder
11
+ // should not add deps as a drive-by — they belong in `decisions.md` or at minimum in
12
+ // the iteration summary so a human can sign off.
13
+ //
14
+ // This hook denies adding a *new* dep without an explicit acknowledgement
15
+ // (SOMI_ALLOW_DEP_INSTALL=1 in the env, set by the human for the session). Lockfile-
16
+ // respecting reinstalls (bare `npm install`, `yarn install`, etc.) are allowed — those
17
+ // don't add deps, they materialize what's already declared.
18
+ //
19
+ // COUNT CORRECTION (verified by direct read, not inherited from the phase file's
20
+ // prose): the bash original's DEP_ADD_PATTERNS array holds 19 patterns, not 18 — and
21
+ // the trailing "generic curl-to-installer" trio (brew/apt/apt-get) sits outside the
22
+ // six named package-manager ecosystems the file's own comments group (js: npm/yarn/
23
+ // pnpm/bun; python: pip/pipx/uv/poetry/conda; rust/go/ruby/php: cargo/go/gem/bundle/
24
+ // composer). All 19 are ported below — "port ALL of the patterns" wins over an
25
+ // inherited miscount; the phase file's iteration-2.4 scope line is corrected
26
+ // alongside this port (see the diary entry for this pass).
27
+ //
28
+ // ERE→RegExp translation notes:
29
+ // - `[[:space:]]` → `\s`. NOT byte-identical: POSIX `[[:space:]]` matches exactly
30
+ // the 6 ASCII whitespace bytes (space/tab/newline/CR/FF/VT); JS `\s` matches those
31
+ // same 6 PLUS additional Unicode whitespace (U+00A0, U+2028, U+2029, U+FEFF, and
32
+ // other Unicode Zs-category characters) — a strict SUPERSET, not the dot-narrowing
33
+ // divergence 2.9 has to worry about. Direction matters: a wider `\s` can only make
34
+ // this hook MATCH (and therefore gate) a *broader* set of verb/package-argument
35
+ // separators than bash would — the safe direction for a security-adjacent gate.
36
+ // The widening DOES produce observable fail-closed decision divergences on some
37
+ // Unicode-whitespace separators — e.g. `npm<NBSP>install x`: bash ALLOWS (NBSP is
38
+ // not [[:space:]], so no pattern matches), this port DENIES (NBSP is JS \s). Always
39
+ // over-gating, never under-gating (verified in review: backtracking prevents the
40
+ // reverse direction), and inert-to-security: every diverging input is non-functional
41
+ // as a real shell command anyway (bash IFS only splits ASCII whitespace, so
42
+ // `npm<NBSP>install` is a single nonexistent command token — nothing denied here
43
+ // would have worked as an unblocked command downstream).
44
+ // - `[^[:space:]]` → `[^\s]`: same superset relationship, applied to the negated
45
+ // class (excludes slightly more from "package token" chars) — same safe direction.
46
+ // - Bare/unescaped `.` or `.*` wildcard (the live POSIX-vs-JS `.` line-terminator
47
+ // divergence that matters for block-dangerous-bash.sh, 2.9): NONE of this file's
48
+ // 19 patterns use one. The only `.` occurrences are the escaped literal
49
+ // `\.txt` in the `pip install -r ...txt` pattern — an escaped dot means "literal
50
+ // dot", identical in ERE and JS regex syntax, so there is no line-terminator
51
+ // divergence to translate here. Checked every pattern by hand, not assumed.
52
+ // - Everything else (`+`, `*`, `?`, alternation groups, negated single-char classes
53
+ // `[^-]`) is byte-identical ERE/JS syntax — a mechanical, pattern-by-pattern port.
54
+ // - Matching is UNANCHORED substring search in both bash (`[[ "$CMD" =~ $pattern ]]`)
55
+ // and here (`RegExp.prototype.exec` with no `^`/`$`), and case-sensitive in both
56
+ // (no `shopt -s nocasematch` in the bash original for this pattern set) — no
57
+ // nocase wrapper needed.
58
+ //
59
+ // FIRST-MATCH-WINS / single-decision semantics: bash's per-pattern loop body ends in
60
+ // either `exit 0` (ALLOW, audited) or `somi::deny_pretool` (which itself calls
61
+ // `exit 0` — see common.sh:89) — so only the FIRST pattern to match the command is
62
+ // ever evaluated; the loop never reaches a second pattern. `matchesAny()` (2.1)
63
+ // returns the first-matching pattern's `RegExpExecArray` in array order, reproducing
64
+ // this exactly, and `m[0]` is the `${BASH_REMATCH[0]}` equivalent interpolated into
65
+ // the deny message.
66
+ //
67
+ // SOMI_ALLOW_DEP_INSTALL exact-value semantics: bash's `"${SOMI_ALLOW_DEP_INSTALL:-0}"
68
+ // == "1"` uses `:-`, which substitutes the default "0" for BOTH unset AND
69
+ // explicitly-empty ("") — so unset, "", and "0" are all NOT-opted-in, and every other
70
+ // string value (e.g. "true", "yes") is also NOT-opted-in; only the literal "1" opts
71
+ // in. `process.env.SOMI_ALLOW_DEP_INSTALL === '1'` below is an exact behavioral
72
+ // equivalent of that comparison (not merely a shortcut): for every value other than
73
+ // literal "1", both the bash substitution-then-compare and the direct JS comparison
74
+ // land on the same false/true outcome — verified case-by-case, not assumed.
75
+ //
76
+ // COMPOUND-COMMAND REFUSAL (config_allows_dep → configAllowsDep, the security-relevant
77
+ // detail this iteration was told to preserve exactly): the allowlist prefix-match only
78
+ // ever applies to the RAW, unmodified `$CMD`/`cmd` string — bash tests
79
+ // `[[ "$c" == *';'* || "$c" == *'&'* || "$c" == *'|'* ]]` against the WHOLE command
80
+ // text (not just the matched substring) and refuses the allow (returns 1 / false) if
81
+ // ANY of those three characters appears ANYWHERE in it — a single `&` (not just `&&`)
82
+ // or single `|` (not just `||`) is enough to refuse, same as bash's glob-style `*x*`
83
+ // substring test. Ported as three `.includes()` checks against the same raw string,
84
+ // in the same order, before any tokenization happens — not simplified to a regex or a
85
+ // "look compound" heuristic.
86
+ //
87
+ // TOKENIZATION judgment call (named per this iteration's "check exactly what bash
88
+ // checks" instruction, not a silent default): bash's `for tok in $c` performs BOTH
89
+ // IFS word-splitting AND pathname (glob) expansion on the unquoted `$c` — a token
90
+ // containing `*`/`?`/`[...]` could silently expand against files in the hook's cwd,
91
+ // making the allowlist check's actual token set depend on the filesystem at hook-run
92
+ // time. That side effect is not reproduced here: it would make the gate's outcome
93
+ // non-deterministic and cwd-dependent, a strictly worse property for a security
94
+ // control, and no realistic package-name argument or fixture case exercises it.
95
+ // `tokensAfterVerb()` below reproduces the WORD-SPLITTING half only (split on runs of
96
+ // whitespace), which is the behavior this hook's allowlist logic actually depends on.
97
+ //
98
+ // DISCOVERED DIVERGENCE, decided explicitly (differential-probe finding, not a silent
99
+ // default — same category of call as 2.7's prune-list decision and 2.8's regex-
100
+ // widening decision): the bash original's `${BASH_REMATCH[0]}` interpolation in its
101
+ // deny message is CORRUPTED whenever `.somi/config.json`'s `dep_install.allow` is
102
+ // configured (non-empty) and the command is denied via a non-compound path. Root
103
+ // cause, confirmed by isolated repro: `$BASH_REMATCH` is a bash GLOBAL, not scoped to
104
+ // the `[[ "$CMD" =~ $pattern ]]` test that finds the real match — `config_allows_dep`'s
105
+ // own internal `[[ "$tok" =~ ^(install|i|add|get|require)$ ]]` verb-detection test
106
+ // (run once `allow` is non-empty and the command isn't compound, i.e. on every
107
+ // allow-list-configured deny that reaches the token loop) OVERWRITES it as a side
108
+ // effect. By the time `somi::deny_pretool` reads `${BASH_REMATCH[0]}`, it holds the
109
+ // bare verb word ("install"/"i"/"add"/"get"/"require") from that internal test, not
110
+ // the actual matched command — e.g. `npm install lodash` denied under
111
+ // `{"dep_install":{"allow":["@types/"]}}` shows `` `install` `` in the bash original's
112
+ // message, not `` `npm install lodash` ``. Verified with a standalone bash repro
113
+ // (isolated from the hook, tracing `$BASH_REMATCH` before/after the verb loop) before
114
+ // concluding this, not inferred. The COMPOUND-command path is unaffected (its checks
115
+ // use `[[ == ]]` glob comparisons, never `=~`, so it returns before ever touching
116
+ // `$BASH_REMATCH` — confirmed by differential probe, zero divergence there).
117
+ // This corrupted text is NOT reproduced here. Reasons: (1) no fixture in
118
+ // `tests/hooks/cases/gate-dep-install.json` asserts `expect_reason` at all, so no
119
+ // pinned contract is broken; (2) D2's behavior-preservation contract is scoped to
120
+ // "identical exit codes and stdout SHAPES" (decisions.md D2) — the shape is identical,
121
+ // only this one interpolated substring's content differs, and only on an untested
122
+ // path; (3) reproducing it would mean deliberately shipping a message that names the
123
+ // wrong thing as "the dependency" in a security-relevant, audit-logged, user-facing
124
+ // deny reason — strictly worse for the human/agent reading it, not a feature. This
125
+ // port always interpolates the REAL `DEP_ADD_PATTERNS` match (`m[0]` from the outer
126
+ // `matchesAny` call, captured once and never touched by `configAllowsDep`), for every
127
+ // deny path, allow-list-configured or not. Flagged here and in the diary for explicit
128
+ // reviewer sign-off, per this iteration's "verify precisely, do not simplify or
129
+ // improve" instruction for `config_allows_dep` — this is the one place a literal
130
+ // bug-for-bug port was deliberately NOT chosen, named rather than silent.
131
+ import { readPayload, field, denyPretool, audit, matchesAny, runHook, config } from '../lib/common.mjs';
132
+
133
+ // Patterns for "add a new dependency". A trailing package argument is required;
134
+ // bare `<pm> install` (no package) is the lockfile-respecting form and is fine.
135
+ const DEP_ADD_PATTERNS = [
136
+ // npm / yarn / pnpm / bun: install with at least one positional package
137
+ /npm\s+(install|i|add)\s+([^-][^\s]*|--save\s+[^\s]+|--save-dev\s+[^\s]+)/,
138
+ /yarn\s+add\s+[^-][^\s]*/,
139
+ /pnpm\s+(add|install)\s+[^-][^\s]*/,
140
+ /bun\s+(add|install)\s+[^-][^\s]*/,
141
+
142
+ // python: pip / pipx / uv / poetry / conda
143
+ /pip[0-9]*\s+install\s+([^-][^\s]*|-r\s+[^\s]+\.txt)/,
144
+ /pip[0-9]*\s+install\s+--upgrade\s+[^-][^\s]*/,
145
+ /pipx\s+install\s+[^-][^\s]*/,
146
+ /uv\s+(add|pip\s+install)\s+[^-][^\s]*/,
147
+ /poetry\s+add\s+[^-][^\s]*/,
148
+ /conda\s+install\s+[^-][^\s]*/,
149
+
150
+ // rust / go / ruby / php
151
+ /cargo\s+(add|install)\s+[^-][^\s]*/,
152
+ /go\s+get\s+[^-][^\s]*/,
153
+ /go\s+install\s+[^-][^\s]*/,
154
+ /gem\s+install\s+[^-][^\s]*/,
155
+ /bundle\s+add\s+[^-][^\s]*/,
156
+ /composer\s+(require|install)\s+[^-][^\s]*/,
157
+
158
+ // generic curl-to-installer (`brew install` is borderline; install scripts often add tools).
159
+ /brew\s+install\s+[^-][^\s]*/,
160
+ /apt\s+(install|add)\s+[^-][^\s]*/,
161
+ /apt-get\s+install\s+[^-][^\s]*/,
162
+ ];
163
+
164
+ // Verb-detection alternation, matched as a FULL-token match (`^...$`), never a
165
+ // substring — mirrors bash's `[[ "$tok" =~ ^(install|i|add|get|require)$ ]]`.
166
+ const VERB_RE = /^(install|i|add|get|require)$/;
167
+
168
+ // Splits on runs of whitespace only — see the header's TOKENIZATION note for why
169
+ // bash's incidental glob-expansion side effect is deliberately not reproduced.
170
+ function tokensAfterVerb(cmd) {
171
+ const words = cmd.split(/\s+/).filter(Boolean);
172
+ const toks = [];
173
+ let seenVerb = false;
174
+ for (const tok of words) {
175
+ if (seenVerb) {
176
+ if (tok.startsWith('-')) continue;
177
+ toks.push(tok);
178
+ } else if (VERB_RE.test(tok)) {
179
+ seenVerb = true;
180
+ }
181
+ }
182
+ return toks;
183
+ }
184
+
185
+ // Per-project allowlist from .somi/config.json (`dep_install.allow`) — committed,
186
+ // reviewable policy, scoped to name prefixes, unlike the all-or-nothing env opt-in.
187
+ // An entry is a PREFIX of a package argument: "@types/" allows `npm install
188
+ // @types/node`. Conservative by construction: compound commands (`;`, `&`, `|`)
189
+ // never qualify, and EVERY package token must match an entry. See the header's
190
+ // COMPOUND-COMMAND REFUSAL note.
191
+ function configAllowsDep(cmd) {
192
+ const allow = config('.dep_install.allow[]?');
193
+ if (allow.length === 0) return false;
194
+ if (cmd.includes(';') || cmd.includes('&') || cmd.includes('|')) return false;
195
+
196
+ const toks = tokensAfterVerb(cmd);
197
+ if (toks.length === 0) return false;
198
+
199
+ return toks.every((t) => allow.some((a) => t.startsWith(a)));
200
+ }
201
+
202
+ function main() {
203
+ const payload = readPayload();
204
+ const cmd = field(payload, '.tool_input.command');
205
+ if (!cmd) return;
206
+
207
+ // Explicit opt-in: human acknowledged this session may add deps. See the header's
208
+ // SOMI_ALLOW_DEP_INSTALL note for why this direct comparison is an exact bash
209
+ // equivalent, not an approximation.
210
+ if (process.env.SOMI_ALLOW_DEP_INSTALL === '1') return;
211
+
212
+ const m = matchesAny(cmd, DEP_ADD_PATTERNS);
213
+ if (!m) return;
214
+
215
+ if (configAllowsDep(cmd)) {
216
+ audit(payload, 'ALLOW', `dep install permitted by .somi/config.json dep_install.allow: ${cmd}`);
217
+ return;
218
+ }
219
+
220
+ denyPretool(payload, `somi refused this command: it would add a new dependency (\`${m[0]}\`).
221
+ Adding a dep is a decision — record it in \`.somi/plans/<slug>/decisions.md\` (or surface it in
222
+ the iteration summary for the human) and re-run with \`SOMI_ALLOW_DEP_INSTALL=1\` in the
223
+ environment for this session, or have the human run the install themselves. Projects can also
224
+ allowlist package-name prefixes in \`.somi/config.json\` under \`dep_install.allow\`.
225
+ Lockfile-respecting reinstalls (bare \`npm install\` / \`pip install -r requirements.txt\`-less,
226
+ \`bundle install\`, etc.) are allowed without acknowledgement.`);
227
+ }
228
+
229
+ runHook(main);
@@ -0,0 +1,157 @@
1
+ #!/usr/bin/env node
2
+ // hooks/pre-tool/guard-protected-paths.mjs — PreToolUse hook (matcher: Write|Edit) — block
3
+ // writes to paths the agent shouldn't be editing.
4
+ //
5
+ // Node port of hooks/pre-tool/guard-protected-paths.sh (node-runtime-port, phase 2,
6
+ // iteration 2.3). Imports the shared read/deny/config helpers from ../lib/common.mjs (2.1,
7
+ // reviewer-blessed) rather than reimplementing them.
8
+ //
9
+ // Targets the most common "agent overstep" cases: .git internals, vendored deps, build
10
+ // outputs, and the SOMI plugin install (so an agent doesn't rewrite its own ruleset under
11
+ // itself). Lockfile writes are blocked by default (use `npm install <pkg>` etc instead), but a
12
+ // project can opt out via SOMI_ALLOW_LOCKFILES=1 or .somi/config.json's `lockfiles.allow_edit`.
13
+ //
14
+ // --- glob translation (bash `shopt -s extglob` -> JS) --------------------------------------
15
+ // PROTECTED_GLOBS is grepped exhaustively from guard-protected-paths.sh: every entry uses ONLY
16
+ // the plain `*` wildcard — no `?`, no `[...]` bracket expressions, no extglob operator
17
+ // (`@()`/`+()`/`!()`/etc). `shopt -s extglob` is enabled in the bash original but nothing in
18
+ // this pattern set actually exercises extglob syntax, so globToRegExp() below is deliberately
19
+ // scoped to `*`-only translation, not a general fnmatch engine.
20
+ // - `*` -> `[\s\S]*`, NOT `.*`. `[[ str == pattern ]]` is bash's plain pattern matching (no
21
+ // FNM_PATHNAME), so `*` matches `/` AND newlines — verified empirically:
22
+ // `[[ $'a\nb' == a*b ]]` is true, and `[[ "/x/node_modules/y" == */node_modules/* ]]` is
23
+ // true (crosses the `/`). JS `.` excludes `\n` (and, without `/s`, `\r`/U+2028/U+2029) — the
24
+ // same class of divergence block-secret-writes.mjs (2.2) flagged for ERE `.` vs JS `.`, here
25
+ // applied to glob `*`. `[\s\S]*` matches every character unconditionally, closing the gap.
26
+ // - Literal segments (`.git`, `node_modules`, ...) are regex-escaped. `.` has no special
27
+ // meaning in glob/fnmatch syntax (unlike ERE, where it's "any char") — escaping it prevents
28
+ // a literal `.git` segment from silently becoming a regex wildcard.
29
+ // - Whole pattern is anchored `^...$`: `[[ str == pattern ]]` matches the ENTIRE string, not a
30
+ // substring — distinct from block-dangerous-bash.sh's `=~` (substring search). The leading/
31
+ // trailing `*` in each pattern is what makes "anywhere in the path" work; the match itself
32
+ // is still full-string.
33
+ //
34
+ // --- lockfile-gate precedence reconciliation ------------------------------------------------
35
+ // Precedence: SOMI_ALLOW_LOCKFILES (env, session override, even "0") > .somi/config.json's
36
+ // `lockfiles.allow_edit` (committed project policy) > default deny. scripts/somi-check.mjs's
37
+ // lockfilesAllowed() (1.3, reviewer-blessed) already solved this exact precedence problem,
38
+ // including the jq-text string-vs-boolean subtlety: bash's `somi::config` shells out to
39
+ // `jq -r`, so a config author writing `"allow_edit": "true"` (a JSON STRING) produces the
40
+ // identical jq -r output ("true") as `"allow_edit": true` (the boolean) — both are honored as
41
+ // allowed. common.mjs's config() (2.1) already reproduces that jq -r text shape for scalar
42
+ // reads (returns '' for null/undefined/false, else the string itself or JSON.stringify(cur) for
43
+ // a non-string scalar), so `config('.lockfiles.allow_edit') === 'true'` below reproduces the
44
+ // SAME text comparison bash performs, without re-implementing a config reader the way
45
+ // somi-check.mjs (which predates common.mjs) had to. Env-side fall-through matches too: bash's
46
+ // `${SOMI_ALLOW_LOCKFILES:-}` treats unset AND explicitly-empty (`SOMI_ALLOW_LOCKFILES=""`)
47
+ // identically (falls through to the config check); the `env !== undefined && env !== ''` guard
48
+ // below reproduces that, matching lockfilesAllowed()'s own env branch. Verified by hand-tracing
49
+ // every fixture case plus the differential probes (see diary).
50
+ //
51
+ // --- platform reasoning (posix vs win32) ----------------------------------------------------
52
+ // This is the "path-heavier hook" block-secret-writes.mjs's header warned 2.3+ to reason
53
+ // through explicitly — its own divergence there was Windows-SAFER; here one of them is not:
54
+ // 1. PROTECTED_GLOBS are forward-slash literals (`*/node_modules/*`). If `tool_input.file_path`
55
+ // ever arrives with backslash separators (a native-Windows path not already normalized to
56
+ // forward slashes upstream), the translated regex requires a literal `/` and will NOT match
57
+ // a `\`-separated path — a protected write could slip through undenied. This reproduces the
58
+ // bash original's identical gap (its globs were just as forward-slash-only) rather than
59
+ // introducing a new one; documented per this iteration's brief, not fixed — fixing would
60
+ // mean choosing a separator-normalization policy this behavior-preserving port doesn't own.
61
+ // 2. The relative-path check (`pathInput.startsWith('/')`) hardcodes a literal POSIX leading-
62
+ // `/` test, deliberately NOT `path.isAbsolute()` (platform-aware; would treat `C:\...` as
63
+ // absolute on win32) — this mirrors bash's own `[[ "$PATH_INPUT" != /* ]]` glob-prefix test
64
+ // byte-for-byte. A Windows-style absolute path would be misclassified as relative and get
65
+ // the project root prepended — the same failure bash's own check would have on such input
66
+ // (bash never ran natively on Windows either, so this is not a new gap either).
67
+ // 3. `path.basename()` (platform-default: posix on Linux, win32 on Windows) is used for the
68
+ // lockfile-name comparison. Unlike (1), this divergence is SAFE: win32's basename
69
+ // recognizes BOTH `/` and `\` as separators (documented Node behavior), so on Windows it is
70
+ // a superset of bash's posix-only basename — never narrower. Same conclusion class as
71
+ // block-secret-writes.mjs's own basename note, on the safe side here too.
72
+
73
+ import path from 'node:path';
74
+ import { readPayload, field, denyPretool, runHook, projectRoot, config } from '../lib/common.mjs';
75
+
76
+ const PROTECTED_GLOBS = [
77
+ // Source-control internals.
78
+ '*/.git/*',
79
+
80
+ // SOMI plugin install — never let an agent rewrite the ruleset under itself.
81
+ '*/.claude/plugins/somi/*',
82
+
83
+ // Vendored deps & build outputs.
84
+ '*/node_modules/*',
85
+ '*/vendor/*',
86
+ '*/dist/*',
87
+ '*/build/*',
88
+ '*/target/*',
89
+ '*/.next/*',
90
+ '*/.nuxt/*',
91
+ '*/__pycache__/*',
92
+ ];
93
+
94
+ const LOCKFILES = [
95
+ 'package-lock.json',
96
+ 'yarn.lock',
97
+ 'pnpm-lock.yaml',
98
+ 'Cargo.lock',
99
+ 'Gemfile.lock',
100
+ 'poetry.lock',
101
+ 'uv.lock',
102
+ 'composer.lock',
103
+ 'go.sum',
104
+ ];
105
+
106
+ // See the glob-translation notes in the header comment.
107
+ function globToRegExp(glob) {
108
+ const body = glob
109
+ .split('*')
110
+ .map((segment) => segment.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'))
111
+ .join('[\\s\\S]*');
112
+ return new RegExp(`^${body}$`);
113
+ }
114
+
115
+ const PROTECTED_PATTERNS = PROTECTED_GLOBS.map((glob) => ({ glob, re: globToRegExp(glob) }));
116
+
117
+ // See the lockfile-gate reconciliation notes in the header comment.
118
+ function lockfilesAllowed() {
119
+ const env = process.env.SOMI_ALLOW_LOCKFILES;
120
+ if (env !== undefined && env !== '') return env === '1';
121
+ return config('.lockfiles.allow_edit') === 'true';
122
+ }
123
+
124
+ function main() {
125
+ const payload = readPayload();
126
+ const tool = field(payload, '.tool_name');
127
+ let pathInput = field(payload, '.tool_input.file_path');
128
+ if (!pathInput) return;
129
+
130
+ // Normalise relative paths so the leading-`*/` globs above still match (a relative
131
+ // `node_modules/x.js` would otherwise slip past `*/node_modules/*`). Reuses common.mjs's
132
+ // projectRoot() — the centralized ${...}-unexpanded-variable guard (2.1) — rather than
133
+ // re-duplicating it here.
134
+ if (!pathInput.startsWith('/')) {
135
+ pathInput = `${projectRoot()}/${pathInput}`;
136
+ }
137
+
138
+ for (const { glob, re } of PROTECTED_PATTERNS) {
139
+ if (re.test(pathInput)) {
140
+ denyPretool(payload, `somi refused to ${tool} \`${pathInput}\`: this path matches a protected glob (\`${glob}\`).
141
+ These paths are owned by tooling (git / package managers / SOMI itself); changes belong in their respective workflows.`);
142
+ }
143
+ }
144
+
145
+ // Lockfile gate. Precedence: env (session override, even "0") > .somi/config.json
146
+ // (`lockfiles.allow_edit`, committed project policy) > default (deny).
147
+ if (!lockfilesAllowed()) {
148
+ const basename = path.basename(pathInput);
149
+ if (LOCKFILES.includes(basename)) {
150
+ denyPretool(payload, `somi refused to ${tool} \`${pathInput}\`: lockfiles should be regenerated by the package manager, not hand-edited.
151
+ If you genuinely need to hand-edit this lockfile, set SOMI_ALLOW_LOCKFILES=1 in your environment
152
+ for this session (or set \`lockfiles.allow_edit: true\` in \`.somi/config.json\` as project policy).`);
153
+ }
154
+ }
155
+ }
156
+
157
+ runHook(main);
@@ -0,0 +1,264 @@
1
+ #!/usr/bin/env node
2
+ // hooks/session-start/detect-repo-instructions.mjs — SessionStart hook — detect repo-local
3
+ // agent/instruction files and surface them.
4
+ //
5
+ // Node port of hooks/session-start/detect-repo-instructions.sh (node-runtime-port, phase 2,
6
+ // iteration 2.7). Imports the shared read/context/projectRoot helpers from ../lib/common.mjs
7
+ // (2.1, reviewer-blessed) rather than reimplementing them.
8
+ //
9
+ // SoMi's MAX→ECO economy is "respect repo conventions as context": when a project ships its
10
+ // own instructions (CLAUDE.md / AGENTS.md / copilot-instructions / .cursorrules) or its own
11
+ // subagents (.claude/agents/), SoMi's MAX actions should read them once and fold the relevant
12
+ // conventions into the work-item brief.md, so the ECO tier inherits them without re-reading.
13
+ // Repo-local instructions WIN over SoMi defaults where they conflict; SoMi does NOT
14
+ // auto-invoke foreign agents. This hook only *surfaces* what exists (paths + a one-line
15
+ // directive) — it does not read or ingest file contents. It fires once per session and stays
16
+ // silent when nothing repo-local is present.
17
+ //
18
+ // === THE PRUNE-LIST DECISION (explicit, named, per the phase file's requirement) =============
19
+ //
20
+ // bash's nested-file find (`detect-repo-instructions.sh:41-46`) declares a prune list
21
+ // (.git/node_modules/.somi/vendor) but it is CONFIRMED NON-FUNCTIONAL on GNU find (0.4's
22
+ // finding, independently reproduced by 0.4 pass 2's review with a control experiment): GNU
23
+ // find's `-mindepth 2` suppresses evaluation of EVERY predicate — including `-prune` — for
24
+ // entries at depth < 2, and the pruned directories themselves (.git, node_modules, .somi,
25
+ // vendor) are always depth-1 children of PROJECT_ROOT. The `-prune` clause therefore never
26
+ // fires; find still descends into all four directories, bounded only by `-maxdepth 3`.
27
+ //
28
+ // This port chooses **(b): fix forward.** A directory whose basename is one of the four
29
+ // pruned names, when it appears as a direct (depth-1) child of PROJECT_ROOT — exactly the
30
+ // entries bash's `-path "$PROJECT_ROOT/.git"`-style literal-path tests target, no broader — is
31
+ // never descended into. This is the narrowest possible fix: it reproduces exactly what the
32
+ // bash `-prune` clause is WRITTEN to do (literal full-path equality against the four
33
+ // top-level names, not a basename match at arbitrary depth), just makes it actually fire. It
34
+ // is not a redesign of the prune policy, only a bug fix confined to this one file.
35
+ //
36
+ // Reasoning, considered against reproducing the bug for strict parity instead:
37
+ //
38
+ // 1. Self-documented intent, violated by an accident, not a choice. This file's own header
39
+ // comment (both bash's and this one's) states the design goal in plain language: "cap
40
+ // depth and count so this stays cheap and never wanders into .git / node_modules /
41
+ // .somi." The current bash behavior directly contradicts its own stated purpose because
42
+ // of a mechanical find/mindepth interaction bug, not because anyone decided vendored
43
+ // dependencies should be scanned. Reproducing a bug that contradicts the file's own
44
+ // documented intent is a weaker form of "parity" than fixing it to match that intent.
45
+ //
46
+ // 2. Correctness, not just performance: what gets SURFACED. A CLAUDE.md/AGENTS.md that
47
+ // happens to live inside a vendored dependency (node_modules), a submodule under
48
+ // vendor/, or somi's own internal state directory is not "this repository's own
49
+ // instructions" in the sense this hook's entire purpose describes to the MAX actions
50
+ // that consume its signal. Surfacing a third-party package's own CLAUDE.md as if it were
51
+ // this repo's convention is actively misleading downstream context, not neutral noise.
52
+ //
53
+ // 3. Performance, empirically measured, not assumed (this is the argument the phase file
54
+ // flagged as possibly strongest, and it held up under measurement). Built a synthetic
55
+ // 800-package node_modules (4802 fs entries at depth <= 3, no matches, so `head -n 10`
56
+ // cannot short-circuit either implementation — full traversal is forced both ways) and
57
+ // timed three walks against it: bash's find (buggy, still descends node_modules) ~14ms;
58
+ // a naive Node readdirSync walk reproducing the SAME non-pruning bug ~31-62ms (Node's
59
+ // per-entry overhead — Dirent construction, JS call/recursion cost — is measurably higher
60
+ // than find's C-native traversal, so "just port the bug" is not perf-neutral, it is
61
+ // WORSE); the fix-forward pruned walk below ~0.17-0.24ms (2 entries visited: node_modules
62
+ // itself, pruned before descending, plus the one root-level file). That is a ~150-350x
63
+ // difference in this synthetic case, and it scales with real node_modules trees, which
64
+ // commonly have thousands of packages — non-negligible for a hook whose whole premise is
65
+ // being cheap enough to run unconditionally on every SessionStart.
66
+ //
67
+ // 4. Fail-quiet in the safe direction, matching this work item's existing precedent for
68
+ // accepted divergences (2.4's BASH_REMATCH-clobber fix, 2.6's UTF-8 truncation
69
+ // divergence): this change can only ever make a previously-surfaced file go silent
70
+ // (prune now excludes something it used to include); in every realistic case it never
71
+ // surfaces something new. (Pedantic corner from the 2.7 review: with >10 nested matches
72
+ // where pruned-dir junk sorts ahead of real files, bash's head -n 10 could truncate a
73
+ // REAL file the pruned walk now surfaces — arguably more correct, but not absolutely
74
+ // "never new".) A regression from this fix is "the hook says nothing when it used to
75
+ // say something," never a false positive.
76
+ //
77
+ // 5. Confined blast radius: unlike the audit()-embedded-delimiter issue (filed work-item-
78
+ // wide, deliberately NOT fixed in a single hook's port), this fix touches only this file
79
+ // — no shared common.mjs contract, no other hook's behavior, no cross-file coupling.
80
+ //
81
+ // What this means for the fixture (tests/hooks/cases/detect-repo-instructions.json):
82
+ // `surfaces-nested-claude-md-under-pruned-dir` (which pinned the CURRENT bash bug — a
83
+ // node_modules/CLAUDE.md being surfaced) is renamed and re-pointed to assert the FIXED
84
+ // behavior (silent exit — node_modules is now actually pruned) as a named, reviewed edit, per
85
+ // the same convention 2.8's status-detection decision is instructed to follow. The stated
86
+ // fixture-implications of the OTHER option (had (a) been chosen instead): every other case in
87
+ // the corpus would be untouched, this one case would pass completely as-is with zero edits,
88
+ // and the.mjs would need to intentionally NOT prune node_modules/.git/.somi/vendor at
89
+ // depth 1 — i.e. deliberately reproduce the bug, at the ~150-350x-in-synthetic-testing
90
+ // performance cost measured above, and at the cost of surfacing third-party CLAUDE.md files
91
+ // as if they were this repository's own conventions.
92
+ //
93
+ // === Depth-semantics translation (find -maxdepth 3 -mindepth 2) ==============================
94
+ // PROJECT_ROOT itself is depth 0; its direct children are depth 1; two directories down is
95
+ // depth 3 — the deepest this scan reaches (maxdepth 3). mindepth 2 excludes depth-0 (root
96
+ // itself, never a candidate anyway) and depth-1 files (root-level files are handled by the
97
+ // separate ROOT_FILES loop below, matching bash's separate `-f` loop + find). Verified against
98
+ // the fixture's depth-boundary pair: a/b/CLAUDE.md (file depth 3) IS surfaced
99
+ // (surfaces-nested-claude-md-at-max-scan-depth); a/b/c/CLAUDE.md (file depth 4) is NOT
100
+ // (omits-claude-md-beyond-scan-depth).
101
+ //
102
+ // === Symlink semantics (verified by direct probe against the unmodified bash hook, not
103
+ // assumed) ======================================================================================
104
+ // bash's ROOT-file loop uses `[[ -f "$PROJECT_ROOT/$f" ]]`, which FOLLOWS symlinks — a
105
+ // symlinked root CLAUDE.md IS surfaced. bash's nested find and the .claude/agents/ count both
106
+ // use `-type f` WITHOUT `-L`/`-follow` — this does NOT follow symlinks (a symlink has type
107
+ // 'l', not 'f'), confirmed with a live probe: a symlinked nested CLAUDE.md is silently
108
+ // excluded from the find output. Node's `fs.readdirSync(dir, { withFileTypes: true })` Dirent
109
+ // entries mirror this exactly, by construction, with no special-casing needed: `isFile()`/
110
+ // `isDirectory()` are both `false` for a symlink entry (confirmed with a live probe on the
111
+ // same fixture directories) — using `fs.statSync` (follows symlinks, like bash's `-f`) for the
112
+ // root-file loop and Dirent's `isFile()`/`isDirectory()` (does not follow, like bash's
113
+ // `-type f`/`-type d`) for the nested walk and the agents count reproduces both behaviors for
114
+ // free. Same reasoning covers a CLAUDE.md that is a DIRECTORY, not a file (verified live): the
115
+ // root loop's `-f` test is false for a directory, and the nested find's `-type f` test is
116
+ // false too (but the directory is still descended into like any other, matching bash) —
117
+ // `fs.statSync(...).isFile()` and Dirent's `isFile()` both return `false` for a directory
118
+ // identically, no extra branch required.
119
+ //
120
+ // === Windows caveat (same class already flagged in 2.2/2.3/2.5) ==============================
121
+ // `path.relative()` (platform-default separator: posix on Linux/macOS, win32 on Windows) is
122
+ // used to build the relative paths this hook emits in its message text. On Windows this would
123
+ // emit backslash-separated relative paths where bash's `${nested#"$PROJECT_ROOT"/}` prefix
124
+ // strip always produced forward slashes — cosmetic only (the message is free text shown to the
125
+ // model, not machine-parsed), not fixed here, consistent with prior ports' documented-not-
126
+ // fixed Windows path-separator gaps.
127
+
128
+ import fs from 'node:fs';
129
+ import path from 'node:path';
130
+ import { readPayload, projectRoot, contextOutput, runHook } from '../lib/common.mjs';
131
+
132
+ // bash: `for f in "CLAUDE.md" "AGENTS.md" ".cursorrules" ".github/copilot-instructions.md"`.
133
+ const ROOT_FILES = ['CLAUDE.md', 'AGENTS.md', '.cursorrules', '.github/copilot-instructions.md'];
134
+
135
+ // bash: `-name 'CLAUDE.md' -o -name 'AGENTS.md'` in the nested find.
136
+ const NESTED_NAMES = new Set(['CLAUDE.md', 'AGENTS.md']);
137
+
138
+ // bash's documented prune list (`detect-repo-instructions.sh:42-43`), now actually enforced —
139
+ // see THE PRUNE-LIST DECISION above. Only matched at depth 1 (PROJECT_ROOT's direct children),
140
+ // mirroring bash's literal `-path "$PROJECT_ROOT/<name>"` full-path equality tests exactly —
141
+ // this is not a basename match at arbitrary depth.
142
+ const PRUNED_TOP_LEVEL_DIRS = new Set(['.git', 'node_modules', '.somi', 'vendor']);
143
+
144
+ const MAX_DEPTH = 3; // bash: find -maxdepth 3
145
+ const MIN_DEPTH = 2; // bash: -mindepth 2
146
+ const MAX_NESTED_RESULTS = 10; // bash: | head -n 10
147
+
148
+ // bash's closing directive line (verbatim, including the embedded single quotes bash's
149
+ // `$'...'\''...'\''...'` escaping decodes to). Byte-exact against the fixture's
150
+ // expect_context substrings.
151
+ const DIRECTIVE =
152
+ "\nMAX actions (/discover, /design, /refactor analysis, and /plan on a cold start) should read these once and distil the relevant conventions into the work item's brief.md / context.md so the ECO tier inherits them without re-reading. Repo-local instructions WIN over SoMi defaults where they conflict. Do NOT auto-invoke the repo's own agents — surface them for the user to opt into.";
153
+
154
+ function isFile(p) {
155
+ try {
156
+ return fs.statSync(p).isFile();
157
+ } catch {
158
+ return false;
159
+ }
160
+ }
161
+
162
+ function isDirectory(p) {
163
+ try {
164
+ return fs.statSync(p).isDirectory();
165
+ } catch {
166
+ return false;
167
+ }
168
+ }
169
+
170
+ // Nested CLAUDE.md/AGENTS.md scan, bounded to depth 3, actually pruning the four top-level
171
+ // directories (see THE PRUNE-LIST DECISION above). `depth` is the depth of the entries being
172
+ // iterated inside `dir` (root's direct children are depth 1). Capped at MAX_NESTED_RESULTS,
173
+ // matching bash's `| head -n 10`. Directory-listing order is filesystem-dependent in both
174
+ // implementations (find and readdirSync both return raw, unsorted directory order) — not a
175
+ // port-introduced nondeterminism, and no fixture case stages more than 2 nested matches, so
176
+ // this never matters for what's actually asserted.
177
+ function scanNested(root) {
178
+ const results = [];
179
+
180
+ function walk(dir, depth) {
181
+ if (results.length >= MAX_NESTED_RESULTS) return;
182
+ let entries;
183
+ try {
184
+ entries = fs.readdirSync(dir, { withFileTypes: true });
185
+ } catch {
186
+ return; // matches find's `2>/dev/null` — an unreadable subtree is silently skipped.
187
+ }
188
+ for (const entry of entries) {
189
+ if (results.length >= MAX_NESTED_RESULTS) return;
190
+ const full = path.join(dir, entry.name);
191
+ if (entry.isDirectory()) {
192
+ if (depth === 1 && PRUNED_TOP_LEVEL_DIRS.has(entry.name)) continue;
193
+ if (depth + 1 <= MAX_DEPTH) walk(full, depth + 1);
194
+ continue;
195
+ }
196
+ if (!entry.isFile()) continue; // false for symlinks and dir-named entries — see header.
197
+ if (depth < MIN_DEPTH) continue;
198
+ if (!NESTED_NAMES.has(entry.name)) continue;
199
+ results.push(path.relative(root, full));
200
+ }
201
+ }
202
+
203
+ walk(root, 1);
204
+ return results;
205
+ }
206
+
207
+ // bash: `find "$PROJECT_ROOT/.claude/agents" -maxdepth 1 -name '*.md' -type f | wc -l`.
208
+ function countAgentDefs(agentsDir) {
209
+ let entries;
210
+ try {
211
+ entries = fs.readdirSync(agentsDir, { withFileTypes: true });
212
+ } catch {
213
+ return 0;
214
+ }
215
+ return entries.filter((e) => e.isFile() && e.name.endsWith('.md')).length;
216
+ }
217
+
218
+ function main() {
219
+ readPayload(); // Drains stdin, matching bash's `somi::read_payload` call. No payload field is
220
+ // read anywhere in this hook (grepped: bash never calls `somi::field` here either) — this is
221
+ // pure discovery over the filesystem, not the tool-call JSON.
222
+
223
+ const root = projectRoot();
224
+
225
+ const found = [];
226
+ for (const f of ROOT_FILES) {
227
+ if (isFile(path.join(root, f))) found.push(f);
228
+ }
229
+ for (const rel of scanNested(root)) {
230
+ found.push(rel);
231
+ }
232
+
233
+ let repoAgents = '';
234
+ const agentsDir = path.join(root, '.claude', 'agents');
235
+ if (isDirectory(agentsDir)) {
236
+ const count = countAgentDefs(agentsDir);
237
+ if (count > 0) {
238
+ repoAgents = `.claude/agents/ (${count} repo-local subagent definition(s))`;
239
+ }
240
+ }
241
+
242
+ if (found.length === 0 && !repoAgents) return;
243
+
244
+ let msg =
245
+ 'somi repo-awareness — this repository ships its own instructions/agents. Respect them as context:';
246
+
247
+ // De-duplicate while preserving order (mirrors bash's `seen` accumulator). Structurally
248
+ // unreachable today — ROOT_FILES entries and scanNested() results can never collide, since
249
+ // the former are always single-segment (or the fixed two-segment copilot path) and the
250
+ // latter are always depth >= 2 relative paths pointing at a different filename set — but
251
+ // reproduced anyway for defensive fidelity with the bash original.
252
+ const seen = new Set();
253
+ for (const f of found) {
254
+ if (seen.has(f)) continue;
255
+ seen.add(f);
256
+ msg += `\n - ${f}`;
257
+ }
258
+ if (repoAgents) msg += `\n - ${repoAgents}`;
259
+ msg += DIRECTIVE;
260
+
261
+ contextOutput('SessionStart', msg);
262
+ }
263
+
264
+ runHook(main);