@skathio/somi 1.2.0 → 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.
- package/.claude/settings.json +8 -8
- package/.claude-plugin/marketplace.json +1 -1
- package/.claude-plugin/plugin.json +1 -1
- package/.copilot-extension/extension.json +1 -1
- package/.copilot-extension/marketplace.json +1 -1
- package/README.md +5 -0
- package/VERSION +1 -1
- package/commands/code-loop.md +12 -12
- package/commands/plan-loop.md +9 -9
- package/commands/pr.md +1 -1
- package/commands/release-readiness.md +3 -3
- package/commands/review-panel.md +1 -1
- package/commands/review.md +3 -3
- package/commands/ship-loop.md +2 -2
- package/commands/somi.md +1 -1
- package/commands/upgrade.md +1 -1
- package/hooks/hooks.json +8 -8
- package/hooks/lib/common.mjs +328 -0
- package/hooks/post-tool/audit-log.mjs +93 -0
- package/hooks/post-tool/lint-changed-files.mjs +212 -0
- package/hooks/pre-tool/block-dangerous-bash.mjs +382 -0
- package/hooks/pre-tool/block-secret-writes.mjs +96 -0
- package/hooks/pre-tool/gate-dep-install.mjs +229 -0
- package/hooks/pre-tool/guard-protected-paths.mjs +157 -0
- package/hooks/session-start/detect-repo-instructions.mjs +264 -0
- package/hooks/user-prompt-submit/inject-workflow-context.mjs +432 -0
- package/package.json +2 -2
- package/scripts/somi-check.mjs +243 -0
- package/scripts/somi-findings.mjs +307 -0
- package/scripts/somi-loop.mjs +354 -0
- package/scripts/validate.sh +21 -16
- package/skills/clean-code/SKILL.md +1 -1
- package/tests/hooks/cases/audit-log.json +21 -0
- package/tests/hooks/cases/block-dangerous-bash.json +90 -2
- package/tests/hooks/cases/block-secret-writes.json +1 -1
- package/tests/hooks/cases/detect-repo-instructions.json +84 -0
- package/tests/hooks/cases/gate-dep-install.json +6 -1
- package/tests/hooks/cases/guard-protected-paths.json +1 -1
- package/tests/hooks/cases/inject-workflow-context.json +126 -0
- package/tests/hooks/cases/lint-changed-files.json +120 -0
- package/tests/hooks/run.sh +280 -15
- package/tests/scripts/goldens/somi-findings.json +336 -0
- package/tests/scripts/goldens/somi-loop.json +168 -0
- package/tests/scripts/run.sh +251 -30
- package/hooks/lib/common.sh +0 -133
- package/hooks/post-tool/audit-log.sh +0 -40
- package/hooks/post-tool/lint-changed-files.sh +0 -80
- package/hooks/pre-tool/block-dangerous-bash.sh +0 -171
- package/hooks/pre-tool/block-secret-writes.sh +0 -83
- package/hooks/pre-tool/gate-dep-install.sh +0 -113
- package/hooks/pre-tool/guard-protected-paths.sh +0 -89
- package/hooks/session-start/detect-repo-instructions.sh +0 -73
- package/hooks/user-prompt-submit/inject-workflow-context.sh +0 -143
- package/scripts/somi-check.sh +0 -135
- package/scripts/somi-findings.sh +0 -173
- package/scripts/somi-loop.sh +0 -225
|
@@ -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);
|
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// hooks/post-tool/lint-changed-files.mjs — PostToolUse hook (matcher: Write|Edit) —
|
|
3
|
+
// best-effort lint of just-changed files.
|
|
4
|
+
//
|
|
5
|
+
// Node port of hooks/post-tool/lint-changed-files.sh (node-runtime-port, phase 2,
|
|
6
|
+
// iteration 2.5). Imports the shared read/context/projectRoot helpers from
|
|
7
|
+
// ../lib/common.mjs (2.1, reviewer-blessed) rather than reimplementing them.
|
|
8
|
+
//
|
|
9
|
+
// Runs the project's configured linter on the touched file, if one is available,
|
|
10
|
+
// keyed off file extension + presence of a config file. Result is informational —
|
|
11
|
+
// this hook NEVER blocks (PostToolUse: the file is already written by the time it
|
|
12
|
+
// runs). Every failure mode — missing linter, missing config, linter crash, linter
|
|
13
|
+
// non-zero exit, output truncated by maxBuffer — degrades to "no context emitted",
|
|
14
|
+
// never a deny, never a non-zero hook exit. Preserve that contract exactly; a
|
|
15
|
+
// future edit must not let any of these become a thrown, uncaught error.
|
|
16
|
+
//
|
|
17
|
+
// --- PROJECT_ROOT resolution: guarded projectRoot(), not bash's raw pattern ------
|
|
18
|
+
// bash: `PROJECT_ROOT="${CLAUDE_PROJECT_DIR:-$PWD}"` — no `${...}`-unexpanded-
|
|
19
|
+
// literal guard on THIS specific line (unlike most other ported hooks' PROJECT_ROOT
|
|
20
|
+
// lines, context.md §2). Using common.mjs's projectRoot() here anyway (which DOES
|
|
21
|
+
// carry the guard) is a deliberate, safe-direction improvement, not a silent
|
|
22
|
+
// behavior change: if a host ever fails to expand `${CLAUDE_PROJECT_DIR}` before
|
|
23
|
+
// setting it, bash's un-guarded line would set PROJECT_ROOT to that literal
|
|
24
|
+
// garbage string, and the .ts/.go/.rs branches' `cd "$PROJECT_ROOT" &&` would then
|
|
25
|
+
// FAIL (nonexistent directory) — which, under this script's `set -euo pipefail`,
|
|
26
|
+
// aborts the ENTIRE hook script non-gracefully (a crash, not the intended
|
|
27
|
+
// best-effort no-op). The guarded projectRoot() falls back to `process.cwd()` in
|
|
28
|
+
// that same scenario instead, so this port degrades to "no lint delegate ran" for
|
|
29
|
+
// the broken-host case rather than crashing — strictly safer, and consistent with
|
|
30
|
+
// 2.1's centralization intent (every port imports the one guarded helper rather
|
|
31
|
+
// than re-duplicating bash's un-guarded line).
|
|
32
|
+
//
|
|
33
|
+
// --- run_if_present() -> runIfPresent(), combined with the `command -v` gate ----
|
|
34
|
+
// bash checks presence first (`command -v "$cmd"`), then, only if found, execs it
|
|
35
|
+
// with `2>&1 || true` (swallow a non-zero exit AND merge stdout+stderr). Node's
|
|
36
|
+
// spawnSync already reports "executable not found on PATH" as
|
|
37
|
+
// `result.error.code === 'ENOENT'` (Node does the PATH search itself, including
|
|
38
|
+
// PATHEXT on Windows) — a single spawnSync call reproduces BOTH steps (presence
|
|
39
|
+
// check + conditional exec) without a separate hand-rolled PATH-search helper, and
|
|
40
|
+
// without the check-then-exec TOCTOU race the bash original technically has
|
|
41
|
+
// (immaterial for a best-effort hook either way, but a strictly safer property of
|
|
42
|
+
// this shape, not a behavior change). `result.error` covers every reason the
|
|
43
|
+
// subprocess output couldn't be captured (not found, EACCES, exceeded maxBuffer,
|
|
44
|
+
// ...) — all of them collapse to "no lint output," matching bash's blanket `|| true`
|
|
45
|
+
// swallow.
|
|
46
|
+
//
|
|
47
|
+
// stdout/stderr are captured as SEPARATE buffers by spawnSync and concatenated
|
|
48
|
+
// (`stdout + stderr`) rather than truly interleaved the way a shell's `2>&1`
|
|
49
|
+
// fd-level merge would produce — Node has no direct equivalent without opening a
|
|
50
|
+
// real on-disk fd shared by both streams, which would be needless complexity for
|
|
51
|
+
// output that is purely informational and never programmatically parsed
|
|
52
|
+
// downstream. This is an intentional, named divergence: the acceptance criteria
|
|
53
|
+
// for this port pin SHAPE (does the wrapped "Lint output for the file just
|
|
54
|
+
// changed:" envelope appear, non-empty, when a real delegate run produces
|
|
55
|
+
// anything), not exact interleaved text — verified per fixture case that every
|
|
56
|
+
// scenario this port is actually tested against produces output on only ONE of
|
|
57
|
+
// the two streams, so concatenation order is moot for what's tested.
|
|
58
|
+
//
|
|
59
|
+
// --- maxBuffer -------------------------------------------------------------------
|
|
60
|
+
// LINT_MAX_BUFFER below is set explicitly on every output-capturing spawnSync call.
|
|
61
|
+
// This is the first hook port that shells out to capture an ARBITRARY THIRD-PARTY
|
|
62
|
+
// TOOL's own output (prior ports only capture `git`'s output for decision logic,
|
|
63
|
+
// not a linter's free-form diagnostic text) — Node's child_process default
|
|
64
|
+
// maxBuffer is 1 MB, and a verbose linter run (e.g. `cargo clippy` across a whole
|
|
65
|
+
// crate, or `eslint` with a large ruleset) could plausibly exceed that. 10 MB is a
|
|
66
|
+
// generous ceiling: enough to never truncate a realistic single-file lint run,
|
|
67
|
+
// small enough to bound worst-case memory use from a hook that's supposed to be a
|
|
68
|
+
// cheap, best-effort side note. If a real run exceeds it, spawnSync sets
|
|
69
|
+
// `result.error`, which `runIfPresent`'s swallow-everything contract already
|
|
70
|
+
// treats as "nothing to report" — an over-the-cap linter run degrades to silence,
|
|
71
|
+
// not a crash. This establishes the explicit-maxBuffer convention 1.1's review
|
|
72
|
+
// asked Phase 2's first output-capturing hook to set
|
|
73
|
+
// (`.somi/reviews/node-runtime-port/2026-07-06-1.1-pass1-approve.md`); later hook
|
|
74
|
+
// ports that capture subprocess output should follow this precedent.
|
|
75
|
+
//
|
|
76
|
+
// --- command-substitution trailing-newline stripping -----------------------------
|
|
77
|
+
// bash builds LINT_OUTPUT via `"$(...)"` command substitution, which
|
|
78
|
+
// UNCONDITIONALLY strips ALL trailing newlines from the captured text (a bash
|
|
79
|
+
// `$(...)` primitive, not specific to this hook). Node's spawnSync does not do
|
|
80
|
+
// this — reproduced explicitly via stripTrailingNewlines() below, applied to every
|
|
81
|
+
// branch's captured output, not just the `cargo clippy | head -50` branch that
|
|
82
|
+
// visibly pipes through another command.
|
|
83
|
+
//
|
|
84
|
+
// --- extension dispatch + config gating -------------------------------------------
|
|
85
|
+
// Ported 1:1 from the bash `case "$PATH_INPUT" in ... esac` arms, same order,
|
|
86
|
+
// same per-linter config-file gate, same cd-vs-no-cd behavior per branch (verified
|
|
87
|
+
// line-by-line against the bash original: ts/go/rust branches `cd "$PROJECT_ROOT"`
|
|
88
|
+
// before running their delegate; py/sh branches do not).
|
|
89
|
+
//
|
|
90
|
+
// --- cargo clippy path unreachable in the authoring/CI sandbox -------------------
|
|
91
|
+
// No rust toolchain exists in either environment (confirmed absent both places) —
|
|
92
|
+
// headLines()'s "head -50" translation is a faithful, readable-output-preserving
|
|
93
|
+
// port (not byte-exact POSIX `head` semantics, which don't matter here since bash's
|
|
94
|
+
// own `$(...)` strips trailing newlines from the piped result anyway), but is
|
|
95
|
+
// UNVERIFIED against a real `cargo clippy` invocation. Flagged, not silently
|
|
96
|
+
// assumed correct.
|
|
97
|
+
import fs from 'node:fs';
|
|
98
|
+
import path from 'node:path';
|
|
99
|
+
import { spawnSync } from 'node:child_process';
|
|
100
|
+
import { readPayload, field, contextOutput, projectRoot, runHook } from '../lib/common.mjs';
|
|
101
|
+
|
|
102
|
+
const LINT_MAX_BUFFER = 10 * 1024 * 1024; // 10 MB — see header comment.
|
|
103
|
+
const MAX_LINT_FILE_BYTES = 500000; // bash: SIZE_BYTES > 500000 skip (likely generated).
|
|
104
|
+
|
|
105
|
+
function isFile(p) {
|
|
106
|
+
try {
|
|
107
|
+
return fs.statSync(p).isFile();
|
|
108
|
+
} catch {
|
|
109
|
+
return false;
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
function stripTrailingNewlines(text) {
|
|
114
|
+
return text.replace(/\n+$/, '');
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
// See the header comment's "run_if_present() -> runIfPresent()" section.
|
|
118
|
+
function runIfPresent(cmd, args, cwd) {
|
|
119
|
+
const result = spawnSync(cmd, args, { cwd, encoding: 'utf8', maxBuffer: LINT_MAX_BUFFER });
|
|
120
|
+
if (result.error) return '';
|
|
121
|
+
return stripTrailingNewlines((result.stdout || '') + (result.stderr || ''));
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
// head -N equivalent for the clippy branch. Bash's own `$(...)` strips trailing
|
|
125
|
+
// newlines from the piped-through result regardless, so byte-exact `head`
|
|
126
|
+
// semantics around a missing/present final newline don't matter here — see the
|
|
127
|
+
// header comment.
|
|
128
|
+
function headLines(text, n) {
|
|
129
|
+
const lines = text.split('\n');
|
|
130
|
+
if (lines.length <= n) return text;
|
|
131
|
+
return lines.slice(0, n).join('\n');
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
// bash: nullglob loop over "$PROJECT_ROOT"/.eslintrc* filtered to `-f` (regular
|
|
135
|
+
// files only), OR eslint.config.js, OR eslint.config.mjs.
|
|
136
|
+
function hasEslintConfig(root) {
|
|
137
|
+
let entries;
|
|
138
|
+
try {
|
|
139
|
+
entries = fs.readdirSync(root);
|
|
140
|
+
} catch {
|
|
141
|
+
entries = [];
|
|
142
|
+
}
|
|
143
|
+
const hasRcVariant = entries.some(
|
|
144
|
+
(name) => name.startsWith('.eslintrc') && isFile(path.join(root, name)),
|
|
145
|
+
);
|
|
146
|
+
if (hasRcVariant) return true;
|
|
147
|
+
return isFile(path.join(root, 'eslint.config.js')) || isFile(path.join(root, 'eslint.config.mjs'));
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
// bash: "./$(dirname "${PATH_INPUT#$PROJECT_ROOT/}")/..." — strip the
|
|
151
|
+
// PROJECT_ROOT/ prefix (a no-op if PATH_INPUT doesn't actually start with it,
|
|
152
|
+
// matching bash's `#`-prefix-removal no-op-on-no-match behavior), take the
|
|
153
|
+
// directory component, wrap as a `go vet` package pattern. Uses platform-default
|
|
154
|
+
// path.dirname (posix on Linux/macOS) — same Windows-backslash caveat 2.2/2.3
|
|
155
|
+
// already flagged and deferred (F-32-class divergence, not fixed here either).
|
|
156
|
+
function goVetPackageArg(pathInput, root) {
|
|
157
|
+
const prefix = root.endsWith(path.sep) ? root : root + path.sep;
|
|
158
|
+
const rel = pathInput.startsWith(prefix) ? pathInput.slice(prefix.length) : pathInput;
|
|
159
|
+
return `./${path.dirname(rel)}/...`;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
function main() {
|
|
163
|
+
const payload = readPayload();
|
|
164
|
+
const pathInput = field(payload, '.tool_input.file_path');
|
|
165
|
+
if (!pathInput) return;
|
|
166
|
+
if (!isFile(pathInput)) return;
|
|
167
|
+
|
|
168
|
+
// Skip oversized files (likely generated). bash: `wc -c < "$PATH_INPUT" 2>/dev/null
|
|
169
|
+
// || echo 0` — a stat race after the isFile() check above falls back to 0 (treated
|
|
170
|
+
// as "not oversized," matching bash's fallback exactly).
|
|
171
|
+
let sizeBytes = 0;
|
|
172
|
+
try {
|
|
173
|
+
sizeBytes = fs.statSync(pathInput).size;
|
|
174
|
+
} catch {
|
|
175
|
+
sizeBytes = 0;
|
|
176
|
+
}
|
|
177
|
+
if (sizeBytes > MAX_LINT_FILE_BYTES) return;
|
|
178
|
+
|
|
179
|
+
const root = projectRoot();
|
|
180
|
+
let lintOutput = '';
|
|
181
|
+
|
|
182
|
+
if (pathInput.endsWith('.py')) {
|
|
183
|
+
if (isFile(path.join(root, 'pyproject.toml')) || isFile(path.join(root, '.ruff.toml'))) {
|
|
184
|
+
lintOutput = runIfPresent('ruff', ['check', '--quiet', pathInput], undefined);
|
|
185
|
+
}
|
|
186
|
+
} else if (['.ts', '.tsx', '.js', '.jsx', '.mjs', '.cjs'].some((ext) => pathInput.endsWith(ext))) {
|
|
187
|
+
if (hasEslintConfig(root)) {
|
|
188
|
+
lintOutput = runIfPresent('npx', ['--no-install', 'eslint', '--no-color', pathInput], root);
|
|
189
|
+
}
|
|
190
|
+
} else if (pathInput.endsWith('.go')) {
|
|
191
|
+
if (isFile(path.join(root, 'go.mod'))) {
|
|
192
|
+
lintOutput = runIfPresent('go', ['vet', goVetPackageArg(pathInput, root)], root);
|
|
193
|
+
}
|
|
194
|
+
} else if (pathInput.endsWith('.rs')) {
|
|
195
|
+
if (isFile(path.join(root, 'Cargo.toml'))) {
|
|
196
|
+
lintOutput = headLines(
|
|
197
|
+
runIfPresent('cargo', ['clippy', '--quiet', '--message-format=short'], root),
|
|
198
|
+
50,
|
|
199
|
+
);
|
|
200
|
+
}
|
|
201
|
+
} else if (pathInput.endsWith('.sh')) {
|
|
202
|
+
lintOutput = runIfPresent('shellcheck', [pathInput], undefined);
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
if (lintOutput) {
|
|
206
|
+
// PostToolUse additionalContext must live under hookSpecificOutput per the
|
|
207
|
+
// Claude Code hook schema (same note the bash original carried).
|
|
208
|
+
contextOutput('PostToolUse', `Lint output for the file just changed:\n${lintOutput}`);
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
runHook(main);
|