@skathio/somi 1.1.1 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (81) hide show
  1. package/.claude/settings.json +8 -8
  2. package/.claude-plugin/marketplace.json +1 -1
  3. package/.claude-plugin/plugin.json +1 -1
  4. package/.copilot-extension/extension.json +11 -2
  5. package/.copilot-extension/marketplace.json +1 -1
  6. package/README.md +21 -4
  7. package/VERSION +1 -1
  8. package/agents/coder.md +8 -3
  9. package/agents/designer.md +22 -7
  10. package/agents/discovery-analyst.md +11 -0
  11. package/agents/planner.md +69 -9
  12. package/agents/refactorer.md +3 -1
  13. package/agents/reviewer.md +4 -0
  14. package/commands/adopt.md +77 -0
  15. package/commands/atlas.md +83 -0
  16. package/commands/code-loop.md +70 -44
  17. package/commands/code-parallel.md +3 -1
  18. package/commands/code.md +8 -2
  19. package/commands/debug.md +136 -0
  20. package/commands/design.md +17 -7
  21. package/commands/discover.md +23 -18
  22. package/commands/impact.md +74 -0
  23. package/commands/incident.md +83 -0
  24. package/commands/plan-loop.md +44 -19
  25. package/commands/plan.md +38 -26
  26. package/commands/pr.md +82 -0
  27. package/commands/release-readiness.md +70 -0
  28. package/commands/review-panel.md +5 -0
  29. package/commands/review.md +19 -0
  30. package/commands/ship-loop.md +18 -10
  31. package/commands/ship.md +4 -2
  32. package/commands/somi.md +85 -0
  33. package/commands/upgrade.md +81 -0
  34. package/hooks/hooks.json +8 -8
  35. package/hooks/lib/common.mjs +328 -0
  36. package/hooks/post-tool/audit-log.mjs +93 -0
  37. package/hooks/post-tool/lint-changed-files.mjs +212 -0
  38. package/hooks/pre-tool/block-dangerous-bash.mjs +382 -0
  39. package/hooks/pre-tool/block-secret-writes.mjs +96 -0
  40. package/hooks/pre-tool/gate-dep-install.mjs +229 -0
  41. package/hooks/pre-tool/guard-protected-paths.mjs +157 -0
  42. package/hooks/session-start/detect-repo-instructions.mjs +264 -0
  43. package/hooks/user-prompt-submit/inject-workflow-context.mjs +432 -0
  44. package/package.json +6 -1
  45. package/rules/50-collaboration.md +4 -1
  46. package/scripts/somi-check.mjs +243 -0
  47. package/scripts/somi-findings.mjs +307 -0
  48. package/scripts/somi-loop.mjs +354 -0
  49. package/scripts/validate.sh +120 -0
  50. package/skills/clean-code/SKILL.md +1 -1
  51. package/templates/ATLAS.md.tmpl +75 -0
  52. package/templates/BRIEF.md.tmpl +20 -4
  53. package/templates/DOD.md.tmpl +2 -2
  54. package/templates/PHASE.md.tmpl +1 -1
  55. package/templates/RCA.md.tmpl +53 -0
  56. package/templates/RD-README.md.tmpl +2 -2
  57. package/templates/SDD.md.tmpl +4 -4
  58. package/templates/SOMI-README.md.tmpl +20 -3
  59. package/templates/SRS.md.tmpl +1 -1
  60. package/templates/TDD.md.tmpl +5 -5
  61. package/tests/hooks/cases/audit-log.json +21 -0
  62. package/tests/hooks/cases/block-dangerous-bash.json +166 -0
  63. package/tests/hooks/cases/block-secret-writes.json +22 -0
  64. package/tests/hooks/cases/detect-repo-instructions.json +84 -0
  65. package/tests/hooks/cases/gate-dep-install.json +42 -0
  66. package/tests/hooks/cases/guard-protected-paths.json +30 -0
  67. package/tests/hooks/cases/inject-workflow-context.json +126 -0
  68. package/tests/hooks/cases/lint-changed-files.json +120 -0
  69. package/tests/hooks/run.sh +362 -0
  70. package/tests/scripts/goldens/somi-findings.json +336 -0
  71. package/tests/scripts/goldens/somi-loop.json +168 -0
  72. package/tests/scripts/run.sh +389 -0
  73. package/hooks/lib/common.sh +0 -120
  74. package/hooks/post-tool/audit-log.sh +0 -40
  75. package/hooks/post-tool/lint-changed-files.sh +0 -80
  76. package/hooks/pre-tool/block-dangerous-bash.sh +0 -83
  77. package/hooks/pre-tool/block-secret-writes.sh +0 -83
  78. package/hooks/pre-tool/gate-dep-install.sh +0 -72
  79. package/hooks/pre-tool/guard-protected-paths.sh +0 -74
  80. package/hooks/session-start/detect-repo-instructions.sh +0 -73
  81. package/hooks/user-prompt-submit/inject-workflow-context.sh +0 -143
package/hooks/hooks.json CHANGED
@@ -7,7 +7,7 @@
7
7
  "hooks": [
8
8
  {
9
9
  "type": "command",
10
- "command": "${CLAUDE_PLUGIN_ROOT}/hooks/session-start/detect-repo-instructions.sh"
10
+ "command": "node ${CLAUDE_PLUGIN_ROOT}/hooks/session-start/detect-repo-instructions.mjs"
11
11
  }
12
12
  ]
13
13
  }
@@ -18,11 +18,11 @@
18
18
  "hooks": [
19
19
  {
20
20
  "type": "command",
21
- "command": "${CLAUDE_PLUGIN_ROOT}/hooks/pre-tool/block-dangerous-bash.sh"
21
+ "command": "node ${CLAUDE_PLUGIN_ROOT}/hooks/pre-tool/block-dangerous-bash.mjs"
22
22
  },
23
23
  {
24
24
  "type": "command",
25
- "command": "${CLAUDE_PLUGIN_ROOT}/hooks/pre-tool/gate-dep-install.sh"
25
+ "command": "node ${CLAUDE_PLUGIN_ROOT}/hooks/pre-tool/gate-dep-install.mjs"
26
26
  }
27
27
  ]
28
28
  },
@@ -31,11 +31,11 @@
31
31
  "hooks": [
32
32
  {
33
33
  "type": "command",
34
- "command": "${CLAUDE_PLUGIN_ROOT}/hooks/pre-tool/block-secret-writes.sh"
34
+ "command": "node ${CLAUDE_PLUGIN_ROOT}/hooks/pre-tool/block-secret-writes.mjs"
35
35
  },
36
36
  {
37
37
  "type": "command",
38
- "command": "${CLAUDE_PLUGIN_ROOT}/hooks/pre-tool/guard-protected-paths.sh"
38
+ "command": "node ${CLAUDE_PLUGIN_ROOT}/hooks/pre-tool/guard-protected-paths.mjs"
39
39
  }
40
40
  ]
41
41
  }
@@ -46,7 +46,7 @@
46
46
  "hooks": [
47
47
  {
48
48
  "type": "command",
49
- "command": "${CLAUDE_PLUGIN_ROOT}/hooks/post-tool/lint-changed-files.sh"
49
+ "command": "node ${CLAUDE_PLUGIN_ROOT}/hooks/post-tool/lint-changed-files.mjs"
50
50
  }
51
51
  ]
52
52
  },
@@ -55,7 +55,7 @@
55
55
  "hooks": [
56
56
  {
57
57
  "type": "command",
58
- "command": "${CLAUDE_PLUGIN_ROOT}/hooks/post-tool/audit-log.sh"
58
+ "command": "node ${CLAUDE_PLUGIN_ROOT}/hooks/post-tool/audit-log.mjs"
59
59
  }
60
60
  ]
61
61
  }
@@ -65,7 +65,7 @@
65
65
  "hooks": [
66
66
  {
67
67
  "type": "command",
68
- "command": "${CLAUDE_PLUGIN_ROOT}/hooks/user-prompt-submit/inject-workflow-context.sh"
68
+ "command": "node ${CLAUDE_PLUGIN_ROOT}/hooks/user-prompt-submit/inject-workflow-context.mjs"
69
69
  }
70
70
  ]
71
71
  }
@@ -0,0 +1,328 @@
1
+ // hooks/lib/common.mjs — shared helpers for somi hooks.
2
+ //
3
+ // Node port of hooks/lib/common.sh (node-runtime-port, phase 2, iteration 2.1).
4
+ // Zero-dependency: stdlib only (node:fs, node:path). No jq, no bash — every
5
+ // hook port (2.2-2.9) imports named exports from this module instead of
6
+ // `source`-ing a shell file.
7
+ //
8
+ // Hooks receive a JSON payload on stdin describing the tool invocation, and may
9
+ // emit a JSON response on stdout to control the harness. Output schema is
10
+ // event-specific (see https://code.claude.com/docs/en/hooks):
11
+ //
12
+ // PreToolUse — { hookSpecificOutput: { hookEventName, permissionDecision, permissionDecisionReason } }
13
+ // PostToolUse — { hookSpecificOutput: { hookEventName, additionalContext } } or { decision, reason }
14
+ // UserPromptSubmit — { hookSpecificOutput: { hookEventName, additionalContext } } or { decision, reason }
15
+ // SessionStart — { hookSpecificOutput: { hookEventName, additionalContext } } (used by
16
+ // detect-repo-instructions.sh via somi::context/contextOutput, despite the
17
+ // bash original's doc-comment only naming three events for the
18
+ // additionalContext channel — ported per what the CODE does, confirmed by
19
+ // direct read, not per the stale comment)
20
+ // Stop — { decision: "block", reason } (no additionalContext channel; no Stop
21
+ // hooks are wired in hooks.json today, so no helper here emits this shape)
22
+ //
23
+ // Helpers below emit the right shape per event. Use them — do not hand-emit
24
+ // legacy `{decision:"block"}` or bare `{additionalContext}` shapes; the harness
25
+ // silently drops the wrong shape for the wrong event.
26
+
27
+ import fs from 'node:fs';
28
+ import path from 'node:path';
29
+
30
+ // Thrown by denyPretool() (and available to any hook that needs an early,
31
+ // non-local exit) to unwind to the hook's own top-level handler — mirrors
32
+ // bash's unconditional `exit N` from inside a sourced function, which stops
33
+ // the calling script immediately regardless of loop/nesting depth. Every
34
+ // hook today only ever exits 0 (deny-and-stop is still a *successful* hook
35
+ // invocation from the harness's point of view — see denyPretool below), but
36
+ // the signal carries an explicit code rather than a hard-coded 0 in case a
37
+ // future hook needs a different one.
38
+ //
39
+ // Deliberately NOT using process.exit() here: scripts/somi-loop.mjs (1.1,
40
+ // reviewer-blessed) established the precedent that process.exit() risks
41
+ // truncating buffered stdout/stderr on a pipe if Node hasn't finished
42
+ // flushing yet — exactly the scenario denyPretool()/contextOutput() create
43
+ // (a console.log() immediately followed by an exit). Throwing + a top-level
44
+ // catch that sets process.exitCode lets Node drain its buffers naturally
45
+ // before exiting. Pair with runHook() below.
46
+ export class HookExit extends Error {
47
+ constructor(code = 0) {
48
+ super(`hook exit ${code}`);
49
+ this.code = code;
50
+ }
51
+ }
52
+
53
+ // Runs a hook's main() and translates a thrown HookExit into process.exitCode.
54
+ // The standard wrapper every hook port (2.2-2.9) should use at its top level,
55
+ // so denyPretool()'s early-exit contract works without each hook file
56
+ // re-declaring the same try/catch boilerplate (the somi-loop.mjs/
57
+ // somi-findings.mjs/somi-check.mjs precedent, centralized here since EVERY
58
+ // hook that calls denyPretool needs exactly this).
59
+ export function runHook(main) {
60
+ try {
61
+ main();
62
+ } catch (e) {
63
+ if (e instanceof HookExit) {
64
+ process.exitCode = e.code;
65
+ } else {
66
+ throw e;
67
+ }
68
+ }
69
+ }
70
+
71
+ // project_root() — CLAUDE_PROJECT_DIR if set and resolvable, else cwd.
72
+ //
73
+ // Guards against UNEXPANDED variables: some hosts don't expand
74
+ // ${CLAUDE_PROJECT_DIR} inside settings.json's `env` block, so it (or
75
+ // SOMI_AUDIT_LOG, below) can arrive as the literal string
76
+ // "${CLAUDE_PROJECT_DIR}/...". Without this guard, a path built from that
77
+ // literal would create a directory named `${CLAUDE_PROJECT_DIR}` in the repo
78
+ // root. This guard is duplicated across 5+ bash files (context.md §2,
79
+ // brief.md §3) — centralized here as the ONE copy every hook port imports,
80
+ // rather than re-duplicating the `.includes('${')` check per file. (Note:
81
+ // scripts/*.mjs — a separate module graph, out of this iteration's scope —
82
+ // still carry their own copy; unifying those is a follow-up, not this pass.)
83
+ export function projectRoot() {
84
+ let base = process.env.CLAUDE_PROJECT_DIR || process.cwd();
85
+ if (base.includes('${')) base = process.cwd();
86
+ return base;
87
+ }
88
+
89
+ // Read the full JSON payload from stdin once, parse it. Tolerates empty or
90
+ // invalid input the way `somi::field`'s jq call does (`2>/dev/null || true`
91
+ // — no crash, just nothing to extract): returns null rather than throwing,
92
+ // and every field()/config() call below treats null the same as "field
93
+ // absent" (empty string / empty array).
94
+ export function readPayload() {
95
+ let text = '';
96
+ try {
97
+ text = fs.readFileSync(0, 'utf8');
98
+ } catch {
99
+ return null;
100
+ }
101
+ if (text.trim() === '') return null;
102
+ try {
103
+ return JSON.parse(text);
104
+ } catch {
105
+ return null;
106
+ }
107
+ }
108
+
109
+ // somi::field equivalent — dotted-path field extraction from the parsed
110
+ // payload, e.g. field(payload, '.tool_name'), field(payload, '.tool_input.command').
111
+ // Enumerated from every `somi::field` call site in hooks/ (grepped
112
+ // exhaustively): only ever simple dotted paths, never jq filters or array
113
+ // indexing — this is NOT a jq implementation, just the shape hooks actually
114
+ // use, and its parity claim is scoped to that: the SCALAR shapes hooks
115
+ // actually read (string, number, boolean). Mirrors `jq -r "$path // empty"`
116
+ // for those: null/missing/false collapses to '' (jq's `//` alternative only
117
+ // substitutes for null or false, not other falsy values — a value of 0 or
118
+ // "" is returned as-is by jq, matched here); a non-string scalar is
119
+ // JSON-stringified, matching jq -r's raw output for numbers/booleans. NOT
120
+ // claimed for object/array/big-int results: jq -r pretty-prints an object
121
+ // or array multi-line, where this emits compact JSON — a real divergence,
122
+ // just an inert one today, since no `somi::field` call site in hooks/ ever
123
+ // reads an object- or array-valued path (audit-log.sh's one object read
124
+ // goes through `jq -c` directly, matching compact output already).
125
+ export function field(payload, fieldPath) {
126
+ if (payload === null || payload === undefined) return '';
127
+ const keys = fieldPath.replace(/^\./, '').split('.').filter(Boolean);
128
+ let cur = payload;
129
+ for (const k of keys) {
130
+ if (cur === null || cur === undefined || typeof cur !== 'object') return '';
131
+ cur = cur[k];
132
+ }
133
+ if (cur === null || cur === undefined || cur === false) return '';
134
+ return typeof cur === 'string' ? cur : JSON.stringify(cur);
135
+ }
136
+
137
+ // Path to the audit log. Project-local by default; configurable via
138
+ // SOMI_AUDIT_LOG. Same unexpanded-variable guard as projectRoot(), applied a
139
+ // second time to the SOMI_AUDIT_LOG candidate itself (a host could pass an
140
+ // unexpanded literal there too, independent of CLAUDE_PROJECT_DIR).
141
+ export function auditLogPath() {
142
+ const base = projectRoot();
143
+ const fallback = path.join(base, '.claude', 'audit.log');
144
+ let log = process.env.SOMI_AUDIT_LOG || fallback;
145
+ if (log.includes('${')) log = fallback;
146
+ return log;
147
+ }
148
+
149
+ // somi::config equivalent — reads a value from the project's committed
150
+ // config at .somi/config.json. `fieldPath` is a minimal jq-path string:
151
+ // dotted keys, optionally ending in "[]?" to request every element of an
152
+ // array (mirrors gate-dep-install.sh's `.dep_install.allow[]?` /
153
+ // `mapfile -t` idiom). These are the ONLY two shapes any `somi::config` call
154
+ // site in hooks/ uses today (grepped exhaustively) — NOT a general jq
155
+ // implementation; do not extend this ad hoc. If a future hook needs a path
156
+ // shape neither branch below covers, extend deliberately and name the new
157
+ // shape in this comment.
158
+ //
159
+ // Precedence contract (callers enforce it, same as the bash original): env
160
+ // var > .somi/config.json > default.
161
+ export function config(fieldPath) {
162
+ const arrayMode = fieldPath.endsWith('[]?');
163
+ const keys = (arrayMode ? fieldPath.slice(0, -3) : fieldPath)
164
+ .replace(/^\./, '')
165
+ .split('.')
166
+ .filter(Boolean);
167
+
168
+ const base = projectRoot();
169
+ const cfgPath = path.join(base, '.somi', 'config.json');
170
+ if (!fs.existsSync(cfgPath)) return arrayMode ? [] : '';
171
+
172
+ let data;
173
+ try {
174
+ data = JSON.parse(fs.readFileSync(cfgPath, 'utf8'));
175
+ } catch {
176
+ return arrayMode ? [] : ''; // matches jq's `2>/dev/null || true` on invalid JSON
177
+ }
178
+
179
+ let cur = data;
180
+ for (const k of keys) {
181
+ if (cur === null || cur === undefined || typeof cur !== 'object') { cur = undefined; break; }
182
+ cur = cur[k];
183
+ }
184
+
185
+ if (arrayMode) {
186
+ if (!Array.isArray(cur)) return [];
187
+ // jq's "// empty" on a generator (`.dep_install.allow[]? // empty`)
188
+ // drops null/false elements from the output stream element-by-element —
189
+ // it does NOT stringify them to "null"/"false" (verified against real
190
+ // jq: F-29). A stray null/false entry in a committed config array is
191
+ // silently skipped, matching that.
192
+ return cur
193
+ .filter((v) => v !== null && v !== false)
194
+ .map((v) => (typeof v === 'string' ? v : JSON.stringify(v))); // jq -r per element
195
+ }
196
+ if (cur === null || cur === undefined || cur === false) return '';
197
+ return typeof cur === 'string' ? cur : JSON.stringify(cur);
198
+ }
199
+
200
+ // Append a structured line to the audit log. Frozen contract (spec.md §9):
201
+ // "timestamp\tkind\ttool\tdetail\n", byte-exact — any deviation here is a
202
+ // regression, not a style choice.
203
+ export function audit(payload, kind, detail) {
204
+ const tool = field(payload, '.tool_name');
205
+ const log = auditLogPath();
206
+ fs.mkdirSync(path.dirname(log), { recursive: true });
207
+ const timestamp = new Date().toISOString().replace(/\.\d{3}Z$/, 'Z'); // date -u +%Y-%m-%dT%H:%M:%SZ
208
+ fs.appendFileSync(log, `${timestamp}\t${kind}\t${tool || 'unknown'}\t${detail}\n`);
209
+ }
210
+
211
+ // Deny a PreToolUse tool call. Use this for block-* hooks. Emits the modern
212
+ // hookSpecificOutput.permissionDecision schema, writes the DENY audit line,
213
+ // then throws HookExit(0) — yes, exit 0: from the harness's point of view a
214
+ // hook that denies via this JSON shape completed successfully; the deny
215
+ // itself is communicated in the JSON body, not the process exit code. Pair
216
+ // with runHook() at the hook's top level so the throw is caught correctly
217
+ // and doesn't propagate as an uncaught exception.
218
+ export function denyPretool(payload, reason) {
219
+ console.log(JSON.stringify({
220
+ hookSpecificOutput: {
221
+ hookEventName: 'PreToolUse',
222
+ permissionDecision: 'deny',
223
+ permissionDecisionReason: reason,
224
+ },
225
+ }));
226
+ audit(payload, 'DENY', reason);
227
+ throw new HookExit(0);
228
+ }
229
+
230
+ // Emit additionalContext for events that support it (PreToolUse, PostToolUse,
231
+ // UserPromptSubmit, SessionStart — see the header comment). The harness shows
232
+ // this to the model on its next turn. Does NOT exit — callers still fall
233
+ // through to their own exit path, same as the bash original.
234
+ export function contextOutput(event, context) {
235
+ console.log(JSON.stringify({
236
+ hookSpecificOutput: {
237
+ hookEventName: event,
238
+ additionalContext: context,
239
+ },
240
+ }));
241
+ }
242
+
243
+ // --- pattern-list matching --------------------------------------------------
244
+ //
245
+ // somi::matches_any / somi::matches_any_nocase equivalents. Thin wrappers:
246
+ // hooks own their actual pattern lists (as RegExp literals — see
247
+ // scripts/somi-check.mjs's SECRET_PATTERNS for the established idiom); this
248
+ // lib only owns the "does this string match any of these patterns" shape —
249
+ // it is deliberately not a pattern-list registry or a translation layer.
250
+ //
251
+ // Return contract: the RegExpExecArray from the FIRST matching pattern (so
252
+ // match[0] is the matched substring — the BASH_REMATCH[0] equivalent bash
253
+ // hooks interpolate into deny messages), or null if none matched. Returning
254
+ // the match object rather than a boolean means a caller never has to re-run
255
+ // the same pattern a second time just to recover the substring it already
256
+ // matched.
257
+ //
258
+ // FIRST-MATCH-ONLY CONTRACT (F-28): both wrappers strip the "g"/"y" flags
259
+ // from every pattern before matching, UNCONDITIONALLY — even if the
260
+ // caller's own RegExp carries one. `.exec()` on a /g or /y regex is
261
+ // STATEFUL: it advances the object's own `lastIndex` on every call, so
262
+ // running the SAME pattern object through `matchesAny` twice (e.g. 2.9
263
+ // scans its whole pattern list against the raw command, then again against
264
+ // the quote-stripped copy — block-dangerous-bash.sh:166-167) could silently
265
+ // return null on the second call even though the string still matches.
266
+ // Bash's `[[ =~ ]]` has no equivalent statefulness, so this would be a
267
+ // NEW failure mode the port introduces into the security substrate 2.9
268
+ // depends on. Rather than trust every pattern literal across 2.2-2.9 to
269
+ // never accidentally carry "g"/"y", toRegExp() makes the hazard
270
+ // unrepresentable: the effective flags are always normalized to exclude
271
+ // "g"/"y" first, so neither wrapper's returned RegExp is ever stateful
272
+ // across calls.
273
+ function toRegExp(pattern, forcedFlags) {
274
+ const isRegExp = pattern instanceof RegExp;
275
+ const source = isRegExp ? pattern.source : pattern;
276
+ let flags = (isRegExp ? pattern.flags : '').replace(/[gy]/g, '');
277
+ if (forcedFlags) {
278
+ for (const f of forcedFlags) if (!flags.includes(f)) flags += f;
279
+ }
280
+ if (isRegExp && flags === pattern.flags) return pattern;
281
+ return new RegExp(source, flags);
282
+ }
283
+
284
+ export function matchesAny(str, patterns) {
285
+ for (const pattern of patterns) {
286
+ const m = toRegExp(pattern).exec(str);
287
+ if (m) return m;
288
+ }
289
+ return null;
290
+ }
291
+
292
+ // Case-insensitive variant. CONTRACT: the WRAPPER owns the "i" flag, not the
293
+ // caller — every pattern is matched case-insensitively regardless of what
294
+ // flags it was constructed with (a pattern missing "i" gets a flag-augmented
295
+ // copy built on the fly). This mirrors bash's actual mechanism: `shopt -s
296
+ // nocasematch` is an AMBIENT property of the matching operation, not a
297
+ // per-pattern annotation — the bash ERE pattern strings themselves have no
298
+ // case-flag syntax at all. Centralizing the flag here means a pattern added
299
+ // to a nocase list in a future hook port can never silently end up
300
+ // case-sensitive from one missing "/i" on one literal; the guarantee lives
301
+ // in which function you called, not in every pattern's own flags.
302
+ //
303
+ // ASCII-only, by construction of JS's own /i semantics — NOT by any bespoke
304
+ // folding logic here (1.2's F-23 precedent: bash's nocasematch is
305
+ // ASCII-only for these pattern classes, and Unicode-aware case folding can
306
+ // introduce surprises C-locale regex/`tr` never would). JS's /i flag
307
+ // WITHOUT the /u flag already refuses to fold a non-ASCII input character
308
+ // down to an ASCII pattern character — verified empirically:
309
+ // `/D/i.test('ď')`, `/D/i.test('Ð')`, `/i/i.test('İ')`, and
310
+ // `/k/i.test('K')` (Kelvin sign) are all `false`. Per ECMA-262's
311
+ // Canonicalize (22.2.2.9, non-Unicode mode): if a character's canonical
312
+ // form is < U+0080 but the character itself is >= U+0080, the algorithm
313
+ // returns the character UNCHANGED instead of folding it — the exact guard
314
+ // `String.prototype.toLowerCase()` lacks, which is what made
315
+ // normalizeTitle's İstanbul/café cases (somi-findings.mjs, F-23) a real
316
+ // bug. The one residual gap: two DIFFERENT non-ASCII characters Unicode
317
+ // considers case-equivalent to each other (e.g. é/É) would still fold under
318
+ // JS's /i, where bash's C-locale nocasematch would not — moot for every
319
+ // pattern in this codebase today (every nocase pattern source is pure
320
+ // ASCII), but worth naming if a future nocase pattern ever includes a
321
+ // literal non-ASCII character.
322
+ export function matchesAnyNocase(str, patterns) {
323
+ for (const pattern of patterns) {
324
+ const m = toRegExp(pattern, 'i').exec(str);
325
+ if (m) return m;
326
+ }
327
+ return null;
328
+ }
@@ -0,0 +1,93 @@
1
+ #!/usr/bin/env node
2
+ // hooks/post-tool/audit-log.mjs — PostToolUse hook (matcher: *) — record every tool call to
3
+ // the SOMI audit log.
4
+ //
5
+ // Node port of hooks/post-tool/audit-log.sh (node-runtime-port, phase 2, iteration 2.6).
6
+ // The simplest hook in the corpus: append-only, no decision logic beyond field extraction
7
+ // already ported in 2.1 (../lib/common.mjs). Pairs with the BLOCK entries written from
8
+ // pre-tool hooks: gives you a single log to grep for "what did the agent actually do during
9
+ // this session?" Sensitive arguments are trimmed; we record tool name, status, and a short
10
+ // summary.
11
+ //
12
+ // Line format is the frozen contract (spec.md §9): "timestamp\tkind\ttool\tdetail\n",
13
+ // byte-exact — common.mjs's audit() owns that shape; this file only builds `detail`.
14
+ //
15
+ // TRUNCATION-BOUNDARY NOTE (F-14, phase-2-hooks-port.md, iteration 2.6): bash's
16
+ // `head -c 240` truncates at exactly 240 BYTES, not characters — verified directly against
17
+ // the unmodified bash original before this port existed (see progress.md/diary.md, 2.6):
18
+ // a 271-byte compact tool_input truncates to exactly 240 bytes, dropping the tail including
19
+ // the closing `"}`. truncateBytes() below reproduces that byte-exact cut via a UTF-8 Buffer
20
+ // slice (Buffer.from(str, 'utf8').subarray(0, 240)), NOT a UTF-16-code-unit `.slice(0, 240)`
21
+ // — the latter would cut at the wrong BYTE position for any non-ASCII content before the
22
+ // boundary, not just diverge at the tail. One residual, DOCUMENTED divergence: bash's
23
+ // `head -c` writes raw, possibly-invalid-UTF-8 bytes straight to the file if the cut lands
24
+ // mid multi-byte character (confirmed directly: a command containing "€" split at its byte
25
+ // 240 boundary leaves bash's audit log with a lone, invalid lead byte). common.mjs's audit()
26
+ // takes a JS string, not a raw byte buffer, so this port must decode the truncated bytes back
27
+ // to a string before handing it to audit() — `.toString('utf8')` replaces an incomplete
28
+ // trailing sequence with U+FFFD instead of preserving bash's raw invalid bytes. This is a
29
+ // safe-direction divergence (well-formed UTF-8 emitted vs. bash's malformed tail), inert for
30
+ // every case in the fixture corpus (ASCII-only), and only reachable via genuinely pathological
31
+ // input (a command/tool_input whose UTF-8 encoding is >240 bytes with a multi-byte character
32
+ // straddling the cut) — named here rather than silently accepted.
33
+ //
34
+ // EMBEDDED TAB/NEWLINE NOTE: this hook's own line format is tab-delimited, but neither the
35
+ // bash original nor this port escapes a tab/newline that happens to be embedded IN the
36
+ // summary content itself (e.g. a Bash command containing a literal tab byte, verified
37
+ // directly: it lands as a real 0x09 byte in the audit line, silently misaligning any
38
+ // naive `split('\t')` consumer). Preserved as-is — this is pre-existing bash behavior, not
39
+ // port-introduced, and D2 (behavior preservation) governs this hook; escaping would be a
40
+ // behavior change out of this iteration's scope.
41
+
42
+ import { readPayload, field, audit, runHook } from '../lib/common.mjs';
43
+
44
+ // bash: `head -c 240`, used identically for both the Bash-command summary and the default
45
+ // branch's compact tool_input summary.
46
+ const MAX_SUMMARY_BYTES = 240;
47
+
48
+ // Truncate a string to at most maxBytes UTF-8 bytes — see the file header's
49
+ // TRUNCATION-BOUNDARY NOTE for the byte-vs-code-unit rationale and the one documented
50
+ // divergence at a mid-character cut.
51
+ function truncateBytes(str, maxBytes) {
52
+ const buf = Buffer.from(str, 'utf8');
53
+ if (buf.length <= maxBytes) return str;
54
+ return buf.subarray(0, maxBytes).toString('utf8');
55
+ }
56
+
57
+ // bash: `jq -c '.tool_input // {}'` — compact JSON of tool_input, defaulting to `{}` when
58
+ // tool_input is null/missing/false (jq's `//` alternative fires only for null and false, per
59
+ // common.mjs's field() doc comment — NOT reused here, since field() collapses null/false to
60
+ // '' rather than '{}', the wrong default for this call site).
61
+ function compactToolInput(payload) {
62
+ let value = payload && typeof payload === 'object' ? payload.tool_input : undefined;
63
+ if (value === null || value === undefined || value === false) value = {};
64
+ return JSON.stringify(value);
65
+ }
66
+
67
+ function main() {
68
+ const payload = readPayload();
69
+ const tool = field(payload, '.tool_name');
70
+ if (!tool) return;
71
+
72
+ let summary;
73
+ switch (tool) {
74
+ case 'Bash': {
75
+ const cmd = truncateBytes(field(payload, '.tool_input.command'), MAX_SUMMARY_BYTES);
76
+ summary = `cmd="${cmd}"`;
77
+ break;
78
+ }
79
+ case 'Write':
80
+ case 'Edit':
81
+ case 'Read': {
82
+ const filePath = field(payload, '.tool_input.file_path');
83
+ summary = `path="${filePath}"`;
84
+ break;
85
+ }
86
+ default:
87
+ summary = truncateBytes(compactToolInput(payload), MAX_SUMMARY_BYTES);
88
+ }
89
+
90
+ audit(payload, 'CALL', summary);
91
+ }
92
+
93
+ runHook(main);