@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
@@ -0,0 +1,389 @@
1
+ #!/usr/bin/env bash
2
+ # End-to-end tests for scripts/somi-loop.sh and scripts/somi-findings.sh.
3
+ #
4
+ # Exercises the deterministic loop core in a throwaway git repo: cap resolution
5
+ # (flag > env > config > default), pass counting, weighted diff measurement
6
+ # (out-of-scope double-counting, .somi/.claude exclusion), resume-after-death,
7
+ # and the findings ledger (identity, consecutive-pass breaker, cross-run
8
+ # recurrence, resolve lifecycle).
9
+ #
10
+ # Wired into scripts/validate.sh (npm test) — CI fails when the loop arithmetic
11
+ # or the breaker semantics regress.
12
+
13
+ set -euo pipefail
14
+
15
+ ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
16
+ LOOP="$ROOT/scripts/somi-loop.mjs"
17
+ FINDINGS="$ROOT/scripts/somi-findings.mjs"
18
+
19
+ TMP="$(mktemp -d)"
20
+ trap 'rm -rf "$TMP"' EXIT
21
+
22
+ failures=0
23
+ total=0
24
+ check() { # $1 = name, $2 = 0/1 pass
25
+ total=$((total + 1))
26
+ if [[ "$2" != "0" ]]; then
27
+ echo "FAIL: $1" >&2
28
+ failures=$((failures + 1))
29
+ fi
30
+ }
31
+ expect_exit() { # $1 = name, $2 = expected code, then the command …
32
+ local name="$1" want="$2" got=0; shift 2
33
+ "$@" >/dev/null 2>&1 || got=$?
34
+ if [[ "$got" != "$want" ]]; then
35
+ echo "FAIL: $name — expected exit $want, got $got" >&2
36
+ failures=$((failures + 1))
37
+ fi
38
+ total=$((total + 1))
39
+ }
40
+
41
+ # --- throwaway project repo ---------------------------------------------------
42
+ REPO="$TMP/repo"
43
+ mkdir -p "$REPO/src" "$REPO/.somi"
44
+ cd "$REPO"
45
+ git init -q -b main
46
+ git config user.email t@t && git config user.name t
47
+ printf 'one\n' > src/a.txt
48
+ printf 'one\n' > src/b.txt
49
+ git add -A && git commit -qm init
50
+
51
+ export CLAUDE_PROJECT_DIR="$REPO"
52
+ unset SOMI_CODE_LOOP_MAX_PASSES SOMI_CODE_LOOP_DIFF_CAP SOMI_CODE_LOOP_SEVERITY_FLOOR 2>/dev/null || true
53
+
54
+ # --- somi-loop: init + cap precedence ------------------------------------------
55
+ printf '{"code_loop": {"max_passes": 2, "diff_cap_lines": 10}}\n' > .somi/config.json
56
+ out="$(node "$LOOP" init --slug demo --loop code --iteration 1.1 --files "src/a.txt")"
57
+ check "init: config max_passes=2 wins over default" \
58
+ "$(jq -e '.caps.max_passes == 2 and .caps.diff_cap_lines == 10' <<<"$out" >/dev/null; echo $?)"
59
+
60
+ out="$(SOMI_CODE_LOOP_MAX_PASSES=5 node "$LOOP" init --force --slug demo --loop code --iteration 1.1 --files "src/a.txt")"
61
+ check "init: env beats config" \
62
+ "$(jq -e '.caps.max_passes == 5' <<<"$out" >/dev/null; echo $?)"
63
+
64
+ out="$(node "$LOOP" init --force --slug demo --loop code --iteration 1.1 --max-passes 1 --diff-cap 6 --files "src/a.txt")"
65
+ check "init: CLI flag beats env and config" \
66
+ "$(jq -e '.caps.max_passes == 1 and .caps.diff_cap_lines == 6' <<<"$out" >/dev/null; echo $?)"
67
+
68
+ expect_exit "init: refuses to clobber a running loop without --force" 64 \
69
+ node "$LOOP" init --slug demo --loop code --iteration 1.1 --files "src/a.txt"
70
+
71
+ # --- somi-loop: pass counting ---------------------------------------------------
72
+ node "$LOOP" pass --slug demo --iteration 1.1 >/dev/null
73
+ expect_exit "pass: exceeding max_passes exits 2" 2 \
74
+ node "$LOOP" pass --slug demo --iteration 1.1
75
+
76
+ # --- somi-loop: weighted diff + exclusions --------------------------------------
77
+ printf 'one\ntwo\nthree\n' > src/a.txt # in-scope: 2 added lines → weight 2
78
+ printf 'artifact churn\n' >> .somi/notes.md # excluded entirely
79
+ out="$(node "$LOOP" check-diff --slug demo --iteration 1.1)"
80
+ check "check-diff: in-scope lines counted, .somi excluded" \
81
+ "$(jq -e '.diff_lines == 2 and .weighted_lines == 2 and (.out_of_scope | length) == 0' <<<"$out" >/dev/null; echo $?)"
82
+
83
+ printf 'one\ntwo\nthree\n' > src/b.txt # out-of-scope: 2 added lines → weight 4; total weighted 6 = cap
84
+ out="$(node "$LOOP" check-diff --slug demo --iteration 1.1)"
85
+ check "check-diff: out-of-scope counts double, at cap is ok" \
86
+ "$(jq -e '.weighted_lines == 6 and .out_of_scope == ["src/b.txt"]' <<<"$out" >/dev/null; echo $?)"
87
+
88
+ printf 'four\n' >> src/b.txt # weighted 8 > cap 6
89
+ expect_exit "check-diff: over weighted cap exits 3" 3 \
90
+ node "$LOOP" check-diff --slug demo --iteration 1.1
91
+
92
+ # --- somi-loop: record/finish/resume (session-death recovery) -------------------
93
+ node "$LOOP" record-pass --slug demo --iteration 1.1 --verdict request-changes --blockers 0 --majors 2 >/dev/null
94
+ out="$(node "$LOOP" resume --slug demo --iteration 1.1)"
95
+ check "resume: state survives with pass count and history" \
96
+ "$(jq -e '.pass == 1 and (.history | length) == 1 and .status == "running"' <<<"$out" >/dev/null; echo $?)"
97
+ node "$LOOP" finish --slug demo --iteration 1.1 --status stopped-diff-cap >/dev/null
98
+ out="$(node "$LOOP" stats --slug demo --iteration 1.1)"
99
+ check "finish: status recorded for the run ledger" \
100
+ "$(jq -e '.status == "stopped-diff-cap"' <<<"$out" >/dev/null; echo $?)"
101
+
102
+ # --- somi-findings: identity + breaker semantics --------------------------------
103
+ F1='[{"file":"src/a.txt","symbol":"HandleWebhook","title":"Missing rate limit on retry path","severity":"Major","confidence":"High"}]'
104
+
105
+ out="$(printf '%s' "$F1" | node "$FINDINGS" record --slug demo --review r1.md --run RUN1 --pass 1)"
106
+ check "record: first sighting is new" \
107
+ "$(jq -e '.state == "new" and .id == "F-1"' <<<"$out" >/dev/null; echo $?)"
108
+
109
+ # Same locus, different line/wording case, next consecutive pass → breaker (exit 5).
110
+ F1b='[{"file":"src/a.txt","symbol":"handlewebhook","title":"missing rate limit on retry path","severity":"Major"}]'
111
+ got=0; out="$(printf '%s' "$F1b" | node "$FINDINGS" record --slug demo --review r2.md --run RUN1 --pass 2)" || got=$?
112
+ check "record: consecutive-pass recurrence exits 5" "$([[ "$got" == "5" ]]; echo $?)"
113
+ check "record: recurrence classified consecutive" \
114
+ "$(jq -e '.state == "known" and .recurring_consecutive == true' <<<"$out" >/dev/null; echo $?)"
115
+
116
+ # A different run (e.g. a later /code-loop) seeing the same open finding → cross-run.
117
+ got=0; out="$(printf '%s' "$F1" | node "$FINDINGS" record --slug demo --review r3.md --run RUN2 --pass 1)" || got=$?
118
+ check "record: cross-run recurrence flagged, not consecutive" \
119
+ "$(jq -e '.recurring_cross_run == true and .recurring_consecutive == false' <<<"$out" >/dev/null; echo $?)"
120
+ check "record: cross-run alone does not exit 5" "$([[ "$got" == "0" ]]; echo $?)"
121
+
122
+ # Resolve → open list empties → re-report of same locus becomes a NEW finding.
123
+ node "$FINDINGS" resolve --slug demo --id F-1 --status fixed --by r4.md >/dev/null
124
+ out="$(node "$FINDINGS" open --slug demo)"
125
+ check "resolve: open list is empty after fix" \
126
+ "$(jq -e 'length == 0' <<<"$out" >/dev/null; echo $?)"
127
+ out="$(printf '%s' "$F1" | node "$FINDINGS" record --slug demo --review r5.md --run RUN3 --pass 1)"
128
+ check "record: resolved locus re-reported becomes a new finding (F-2)" \
129
+ "$(jq -e '.state == "new" and .id == "F-2"' <<<"$out" >/dev/null; echo $?)"
130
+
131
+ # Ledger lives with the review artifacts.
132
+ check "ledger: stored under .somi/reviews/<slug>/findings.json" \
133
+ "$([[ -f "$REPO/.somi/reviews/demo/findings.json" ]]; echo $?)"
134
+
135
+ # --- somi-check: portable working-tree guard -------------------------------------
136
+ CHECK="$ROOT/scripts/somi-check.mjs"
137
+
138
+ printf 'KEY=1\n' > .env && git add .env
139
+ expect_exit "somi-check: staged .env fails" 1 node "$CHECK" --staged
140
+ git rm -q --cached .env && rm .env
141
+
142
+ printf 'KEY=\n' > .env.example && git add .env.example
143
+ expect_exit "somi-check: staged .env.example passes" 0 node "$CHECK" --staged
144
+ git rm -q --cached .env.example && rm .env.example
145
+
146
+ printf '{}\n' > package-lock.json && git add package-lock.json
147
+ expect_exit "somi-check: lockfile without manifest fails" 1 node "$CHECK" --staged
148
+ printf '{"name":"t"}\n' > package.json && git add package.json
149
+ expect_exit "somi-check: lockfile WITH manifest passes" 0 node "$CHECK" --staged
150
+ git rm -q --cached package.json && rm package.json
151
+ printf '{"lockfiles": {"allow_edit": true}}\n' > .somi/config.json
152
+ expect_exit "somi-check: config allow_edit passes bare lockfile" 0 node "$CHECK" --staged
153
+ got=0; SOMI_ALLOW_LOCKFILES=0 node "$CHECK" --staged >/dev/null 2>&1 || got=$?
154
+ check "somi-check: env=0 beats config allow_edit" "$([[ "$got" == "1" ]]; echo $?)"
155
+ git rm -q --cached package-lock.json && rm package-lock.json
156
+
157
+ printf 'x\n# TODO(claude): fix me\n' > src/todo.txt && git add src/todo.txt
158
+ expect_exit "somi-check: staged TODO(claude) marker fails" 1 node "$CHECK" --staged
159
+ git rm -q --cached src/todo.txt && rm src/todo.txt
160
+
161
+ expect_exit "somi-check: clean staged set passes" 0 node "$CHECK" --staged
162
+
163
+ # --- golden snapshots: byte-level diff target for the Node port (additive) ------
164
+ #
165
+ # Everything above asserts *behavioral properties* (cap precedence, weighting,
166
+ # recurrence semantics) — sufficient to gate this bash implementation, but it gives
167
+ # Phase 1's Node port no byte-level "does this match?" target. This section runs a
168
+ # second, independent, fully-scripted scenario against ITS OWN throwaway repo (kept
169
+ # separate from $REPO above, which by this point has accumulated a lot of
170
+ # scenario-specific mutations — reusing it would couple golden ordering to the
171
+ # inline assertions' ordering) and records each invocation's {argv, exit, stdout,
172
+ # stderr} — normalized — into a golden file. It never touches the checks above.
173
+ #
174
+ # Mode: `SOMI_GOLDEN_MODE=capture bash tests/scripts/run.sh` (re)writes the golden
175
+ # files under tests/scripts/goldens/; the default, `check` (every normal dev/CI
176
+ # run), replays the same scenario and fails loudly on any drift from what's
177
+ # committed. Once Phase 1 points $LOOP/$FINDINGS at the Node CLIs, `check` mode
178
+ # is exactly the parity gate: same scenario, same normalization, byte-for-byte
179
+ # comparison — a divergence here is a real behavior regression, not noise.
180
+ #
181
+ # Golden layout: one consolidated, pretty-printed JSON array per source script
182
+ # (tests/scripts/goldens/somi-loop.json, .../somi-findings.json) rather than one
183
+ # file per scenario — fewer files to keep in sync; each array element is still a
184
+ # self-contained {name, argv, exit, stdout, stderr} record, so a mismatch's `diff
185
+ # -u` output identifies the offending scenario by its "name" field without any
186
+ # extra tooling.
187
+ #
188
+ # Normalization masks ONLY values that legitimately vary run-to-run — never JSON
189
+ # key order, spacing, or field presence, since that IS the thing a Node port must
190
+ # reproduce exactly:
191
+ # - full ISO-8601 instants (YYYY-MM-DDTHH:MM:SSZ) -> <TS> (loop's started/at/finished)
192
+ # - bare dates (YYYY-MM-DD) -> <DATE> (findings' seen[].date)
193
+ # - 40-hex git SHAs -> <SHA> (loop's baseline_sha)
194
+ # - this golden run's own throwaway-repo path -> <DIR> (loop's state_file / jq input_filename)
195
+ # Order matters: instants are masked before bare dates, else the bare-date pattern
196
+ # would also eat the date portion of an instant, leaving a mangled "<DATE>T.....Z".
197
+ GOLDEN_DIR="$ROOT/tests/scripts/goldens"
198
+ GOLDEN_MODE="${SOMI_GOLDEN_MODE:-check}"
199
+ case "$GOLDEN_MODE" in
200
+ capture|check) ;;
201
+ *) echo "SOMI_GOLDEN_MODE must be 'capture' or 'check' (got: $GOLDEN_MODE)" >&2; exit 64 ;;
202
+ esac
203
+ mkdir -p "$GOLDEN_DIR"
204
+
205
+ GTMP="$TMP/goldens"
206
+ GREPO="$GTMP/repo"
207
+ mkdir -p "$GREPO/src" "$GREPO/.somi"
208
+ (
209
+ cd "$GREPO"
210
+ git init -q -b main
211
+ git config user.email t@t && git config user.name t
212
+ printf 'one\n' > src/a.txt
213
+ printf 'one\n' > src/b.txt
214
+ git add -A && git commit -qm init
215
+ )
216
+ export CLAUDE_PROJECT_DIR="$GREPO"
217
+ unset SOMI_CODE_LOOP_MAX_PASSES SOMI_CODE_LOOP_DIFF_CAP SOMI_CODE_LOOP_SEVERITY_FLOOR \
218
+ SOMI_PLAN_LOOP_MAX_PASSES SOMI_PLAN_LOOP_DIFF_CAP SOMI_PLAN_LOOP_SEVERITY_FLOOR 2>/dev/null || true
219
+ cd "$GREPO"
220
+
221
+ GSTEP_EXIT=0 GSTEP_STDOUT="" GSTEP_STDERR=""
222
+ golden_step() { # $@ = command (no stdin)
223
+ local out err rc=0
224
+ out="$(mktemp)"; err="$(mktemp)"
225
+ if "$@" >"$out" 2>"$err"; then rc=0; else rc=$?; fi
226
+ GSTEP_EXIT=$rc; GSTEP_STDOUT="$(cat "$out")"; GSTEP_STDERR="$(cat "$err")"
227
+ rm -f "$out" "$err"
228
+ }
229
+ golden_step_stdin() { # $1 = stdin payload, then command
230
+ local payload="$1"; shift
231
+ local out err rc=0
232
+ out="$(mktemp)"; err="$(mktemp)"
233
+ if printf '%s' "$payload" | "$@" >"$out" 2>"$err"; then rc=0; else rc=$?; fi
234
+ GSTEP_EXIT=$rc; GSTEP_STDOUT="$(cat "$out")"; GSTEP_STDERR="$(cat "$err")"
235
+ rm -f "$out" "$err"
236
+ }
237
+ golden_normalize() { # stdin -> normalized text on stdout
238
+ local text
239
+ text="$(cat)"
240
+ text="$(printf '%s' "$text" | sed -E \
241
+ -e 's/[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}Z/<TS>/g' \
242
+ -e 's/[0-9]{4}-[0-9]{2}-[0-9]{2}/<DATE>/g' \
243
+ -e 's/[0-9a-f]{40}/<SHA>/g')"
244
+ printf '%s' "${text//$GTMP/<DIR>}"
245
+ }
246
+ golden_case() { # $1=script $2=name, then argv... (uses GSTEP_* set by the caller)
247
+ local script="$1" name="$2"; shift 2
248
+ local argv_json norm_out norm_err
249
+ argv_json="$(printf '%s\n' "$@" | jq -R . | jq -s .)"
250
+ norm_out="$(printf '%s' "$GSTEP_STDOUT" | golden_normalize)"
251
+ norm_err="$(printf '%s' "$GSTEP_STDERR" | golden_normalize)"
252
+ jq -nc --arg script "$script" --arg name "$name" --argjson argv "$argv_json" \
253
+ --argjson exit "$GSTEP_EXIT" --arg stdout "$norm_out" --arg stderr "$norm_err" \
254
+ '{script:$script, name:$name, argv:$argv, exit:$exit, stdout:$stdout, stderr:$stderr}'
255
+ }
256
+ golden_case_stdin() { # $1=script $2=name $3=stdin, then argv...
257
+ local script="$1" name="$2" stdin_payload="$3"; shift 3
258
+ local argv_json norm_out norm_err
259
+ argv_json="$(printf '%s\n' "$@" | jq -R . | jq -s .)"
260
+ norm_out="$(printf '%s' "$GSTEP_STDOUT" | golden_normalize)"
261
+ norm_err="$(printf '%s' "$GSTEP_STDERR" | golden_normalize)"
262
+ jq -nc --arg script "$script" --arg name "$name" --argjson argv "$argv_json" --arg stdin "$stdin_payload" \
263
+ --argjson exit "$GSTEP_EXIT" --arg stdout "$norm_out" --arg stderr "$norm_err" \
264
+ '{script:$script, name:$name, argv:$argv, stdin:$stdin, exit:$exit, stdout:$stdout, stderr:$stderr}'
265
+ }
266
+
267
+ LOOP_GOLDEN_CASES=()
268
+ FINDINGS_GOLDEN_CASES=()
269
+
270
+ # --- somi-loop: init, pass, check-diff (in/out-of-scope, at/over cap), record-pass, resume, finish, stats
271
+ printf '{"code_loop": {"max_passes": 2, "diff_cap_lines": 10}}\n' > .somi/config.json
272
+
273
+ golden_step node "$LOOP" init --slug g --loop code --iteration 1.1 --files "src/a.txt"
274
+ LOOP_GOLDEN_CASES+=("$(golden_case somi-loop.sh "init: config-resolved caps" init --slug g --loop code --iteration 1.1 --files "src/a.txt")")
275
+
276
+ golden_step node "$LOOP" pass --slug g --iteration 1.1
277
+ LOOP_GOLDEN_CASES+=("$(golden_case somi-loop.sh "pass: 1st pass (1 of 2)" pass --slug g --iteration 1.1)")
278
+
279
+ golden_step node "$LOOP" pass --slug g --iteration 1.1
280
+ LOOP_GOLDEN_CASES+=("$(golden_case somi-loop.sh "pass: 2nd pass (2 of 2, at cap, allowed)" pass --slug g --iteration 1.1)")
281
+
282
+ golden_step node "$LOOP" pass --slug g --iteration 1.1
283
+ LOOP_GOLDEN_CASES+=("$(golden_case somi-loop.sh "pass: 3rd pass exceeds max_passes (exit 2)" pass --slug g --iteration 1.1)")
284
+
285
+ printf 'one\ntwo\nthree\n' > src/a.txt # in-scope: +2 lines
286
+ golden_step node "$LOOP" check-diff --slug g --iteration 1.1
287
+ LOOP_GOLDEN_CASES+=("$(golden_case somi-loop.sh "check-diff: in-scope only, under cap" check-diff --slug g --iteration 1.1)")
288
+
289
+ printf 'one\ntwo\nthree\nfour\nfive\n' > src/b.txt # out-of-scope: +4 lines -> weight 8; total 2+8=10 = cap
290
+ golden_step node "$LOOP" check-diff --slug g --iteration 1.1
291
+ LOOP_GOLDEN_CASES+=("$(golden_case somi-loop.sh "check-diff: out-of-scope doubled, exactly at cap" check-diff --slug g --iteration 1.1)")
292
+
293
+ printf 'six\n' >> src/b.txt # +1 more out-of-scope line -> weight 12 > cap 10
294
+ golden_step node "$LOOP" check-diff --slug g --iteration 1.1
295
+ LOOP_GOLDEN_CASES+=("$(golden_case somi-loop.sh "check-diff: over weighted cap (exit 3)" check-diff --slug g --iteration 1.1)")
296
+
297
+ golden_step node "$LOOP" record-pass --slug g --iteration 1.1 --verdict request-changes --blockers 0 --majors 2
298
+ LOOP_GOLDEN_CASES+=("$(golden_case somi-loop.sh "record-pass: appends history entry" record-pass --slug g --iteration 1.1 --verdict request-changes --blockers 0 --majors 2)")
299
+
300
+ golden_step node "$LOOP" resume --slug g --iteration 1.1
301
+ LOOP_GOLDEN_CASES+=("$(golden_case somi-loop.sh "resume: state with pass count and history" resume --slug g --iteration 1.1)")
302
+
303
+ golden_step node "$LOOP" finish --slug g --iteration 1.1 --status stopped-diff-cap
304
+ LOOP_GOLDEN_CASES+=("$(golden_case somi-loop.sh "finish: records terminal status" finish --slug g --iteration 1.1 --status stopped-diff-cap)")
305
+
306
+ golden_step node "$LOOP" stats --slug g --iteration 1.1
307
+ LOOP_GOLDEN_CASES+=("$(golden_case somi-loop.sh "stats: full state ledger" stats --slug g --iteration 1.1)")
308
+
309
+ # --- somi-findings: record (new/consecutive/cross-run), resolve, open, reopen, get
310
+ GF1='[{"file":"src/a.txt","symbol":"HandleWebhook","title":"Missing rate limit on retry path","severity":"Major","confidence":"High"}]'
311
+ GF1b='[{"file":"src/a.txt","symbol":"handlewebhook","title":"missing rate limit on retry path","severity":"Major"}]'
312
+
313
+ golden_step_stdin "$GF1" node "$FINDINGS" record --slug gf --review r1.md --run RUN1 --pass 1
314
+ FINDINGS_GOLDEN_CASES+=("$(golden_case_stdin somi-findings.sh "record: first sighting is new (F-1)" "$GF1" record --slug gf --review r1.md --run RUN1 --pass 1)")
315
+
316
+ golden_step_stdin "$GF1b" node "$FINDINGS" record --slug gf --review r2.md --run RUN1 --pass 2
317
+ FINDINGS_GOLDEN_CASES+=("$(golden_case_stdin somi-findings.sh "record: consecutive-pass recurrence (exit 5)" "$GF1b" record --slug gf --review r2.md --run RUN1 --pass 2)")
318
+
319
+ golden_step_stdin "$GF1" node "$FINDINGS" record --slug gf --review r3.md --run RUN2 --pass 1
320
+ FINDINGS_GOLDEN_CASES+=("$(golden_case_stdin somi-findings.sh "record: cross-run recurrence (exit 0, not consecutive)" "$GF1" record --slug gf --review r3.md --run RUN2 --pass 1)")
321
+
322
+ golden_step node "$FINDINGS" resolve --slug gf --id F-1 --status fixed --by r4.md
323
+ FINDINGS_GOLDEN_CASES+=("$(golden_case somi-findings.sh "resolve: F-1 fixed" resolve --slug gf --id F-1 --status fixed --by r4.md)")
324
+
325
+ golden_step node "$FINDINGS" open --slug gf
326
+ FINDINGS_GOLDEN_CASES+=("$(golden_case somi-findings.sh "open: empty after resolve" open --slug gf)")
327
+
328
+ golden_step_stdin "$GF1" node "$FINDINGS" record --slug gf --review r5.md --run RUN3 --pass 1
329
+ FINDINGS_GOLDEN_CASES+=("$(golden_case_stdin somi-findings.sh "record: resolved locus re-reported becomes new (F-2)" "$GF1" record --slug gf --review r5.md --run RUN3 --pass 1)")
330
+
331
+ golden_step node "$FINDINGS" reopen --slug gf --id F-1 --by r6.md
332
+ FINDINGS_GOLDEN_CASES+=("$(golden_case somi-findings.sh "reopen: F-1 back to open" reopen --slug gf --id F-1 --by r6.md)")
333
+
334
+ golden_step node "$FINDINGS" get --slug gf --id F-1
335
+ FINDINGS_GOLDEN_CASES+=("$(golden_case somi-findings.sh "get: F-1 (reopened)" get --slug gf --id F-1)")
336
+
337
+ golden_step node "$FINDINGS" get --slug gf --id F-2
338
+ FINDINGS_GOLDEN_CASES+=("$(golden_case somi-findings.sh "get: F-2" get --slug gf --id F-2)")
339
+
340
+ # --- normalize_title edge cases: each isolated on its own fresh slug, so the locus
341
+ # key it produces is directly comparable (only the title varies). The empty-title
342
+ # case is pinned to REALITY, not an invented pass: `record` requires both {file,
343
+ # title} and dies 64 before ever calling normalize_title, so its golden is the
344
+ # usage-error shape, not a fabricated success.
345
+ golden_edge_case() { # $1=slug $2=label $3=title
346
+ local slug="$1" label="$2" title="$3" payload
347
+ payload="$(jq -nc --arg f src/a.txt --arg t "$title" '[{file:$f, title:$t}]')"
348
+ golden_step_stdin "$payload" node "$FINDINGS" record --slug "$slug" --review r.md --run R1 --pass 1
349
+ FINDINGS_GOLDEN_CASES+=("$(golden_case_stdin somi-findings.sh "normalize_title: $label — record" "$payload" record --slug "$slug" --review r.md --run R1 --pass 1)")
350
+ if [[ "$GSTEP_EXIT" == "0" ]]; then
351
+ golden_step node "$FINDINGS" get --slug "$slug" --id F-1
352
+ FINDINGS_GOLDEN_CASES+=("$(golden_case somi-findings.sh "normalize_title: $label — get (exposes key)" get --slug "$slug" --id F-1)")
353
+ fi
354
+ }
355
+ golden_edge_case edge-empty "empty title (dies 64, never reaches normalize_title)" ""
356
+ golden_edge_case edge-single "single word" "Bug"
357
+ golden_edge_case edge-many ">8 words truncates" "one two three four five six seven eight nine ten"
358
+ golden_edge_case edge-ws "leading/trailing whitespace" " Missing rate limit "
359
+ golden_edge_case edge-multispace "multiple internal spaces" "Missing rate limit"
360
+ golden_edge_case edge-punct "punctuation stripped" "Missing rate-limit! (on retry) path?"
361
+
362
+ # --- write (capture) or compare (check) ------------------------------------------
363
+ golden_compare() { # $1 = golden file path, $2 = freshly-captured JSON array content
364
+ local file="$1" content="$2"
365
+ total=$((total + 1))
366
+ if [[ "$GOLDEN_MODE" == "capture" ]]; then
367
+ printf '%s\n' "$content" > "$file"
368
+ echo "captured golden: $file"
369
+ return
370
+ fi
371
+ if [[ ! -f "$file" ]]; then
372
+ echo "FAIL: golden missing — $file (run: SOMI_GOLDEN_MODE=capture bash tests/scripts/run.sh)" >&2
373
+ failures=$((failures + 1))
374
+ return
375
+ fi
376
+ if ! diff -u "$file" <(printf '%s\n' "$content") >&2; then
377
+ echo "FAIL: golden mismatch — $file" >&2
378
+ failures=$((failures + 1))
379
+ fi
380
+ }
381
+ golden_compare "$GOLDEN_DIR/somi-loop.json" "$(printf '%s\n' "${LOOP_GOLDEN_CASES[@]}" | jq -s '.')"
382
+ golden_compare "$GOLDEN_DIR/somi-findings.json" "$(printf '%s\n' "${FINDINGS_GOLDEN_CASES[@]}" | jq -s '.')"
383
+
384
+ # --- summary --------------------------------------------------------------------
385
+ if (( failures > 0 )); then
386
+ echo "script tests: $failures of $total checks FAILED" >&2
387
+ exit 1
388
+ fi
389
+ echo "script tests: all $total checks passed."
@@ -1,120 +0,0 @@
1
- #!/usr/bin/env bash
2
- # Shared helpers for somi hooks.
3
- #
4
- # Hooks receive a JSON payload on stdin describing the tool invocation, and may
5
- # emit a JSON response on stdout to control the harness. Output schema is
6
- # event-specific (see https://code.claude.com/docs/en/hooks):
7
- #
8
- # PreToolUse — { hookSpecificOutput: { hookEventName, permissionDecision, permissionDecisionReason } }
9
- # PostToolUse — { hookSpecificOutput: { hookEventName, additionalContext } } or { decision, reason }
10
- # UserPromptSubmit — { hookSpecificOutput: { hookEventName, additionalContext } } or { decision, reason }
11
- # Stop — { decision: "block", reason } (no additionalContext channel)
12
- #
13
- # Helpers below emit the right shape per event. Use them — do not hand-emit
14
- # legacy `{decision:"block"}` or bare `{additionalContext}` shapes; the harness
15
- # silently drops the wrong shape for the wrong event.
16
-
17
- set -euo pipefail
18
-
19
- # Read the full JSON payload from stdin once. Subsequent jq calls use this.
20
- somi::read_payload() {
21
- SOMI_PAYLOAD="$(cat)"
22
- export SOMI_PAYLOAD
23
- }
24
-
25
- # Extract a field from the payload using jq. Returns empty string if missing.
26
- somi::field() {
27
- local path="$1"
28
- printf '%s' "${SOMI_PAYLOAD:-}" | jq -r "${path} // empty" 2>/dev/null || true
29
- }
30
-
31
- # Path to the audit log. Project-local by default. Configurable via SOMI_AUDIT_LOG.
32
- #
33
- # Guards against UNEXPANDED variables. Some hosts don't expand ${CLAUDE_PROJECT_DIR}
34
- # inside settings.json's `env` block, so SOMI_AUDIT_LOG (or CLAUDE_PROJECT_DIR) can
35
- # arrive as the literal string "${CLAUDE_PROJECT_DIR}/.claude/audit.log". Without this
36
- # guard, `mkdir -p "$(dirname "$log")"` then creates a literal '${CLAUDE_PROJECT_DIR}'
37
- # directory in the repo root. If a candidate still contains a "${", we discard it and
38
- # fall back to a path the shell can resolve here.
39
- somi::audit_log_path() {
40
- local base="${CLAUDE_PROJECT_DIR:-$PWD}"
41
- [[ "$base" == *'${'* ]] && base="$PWD"
42
- local log="${SOMI_AUDIT_LOG:-${base}/.claude/audit.log}"
43
- [[ "$log" == *'${'* ]] && log="${base}/.claude/audit.log"
44
- printf '%s' "$log"
45
- }
46
-
47
- # Append a structured line to the audit log.
48
- somi::audit() {
49
- local kind="$1"
50
- local detail="$2"
51
- local tool
52
- local log
53
- tool="$(somi::field '.tool_name')"
54
- log="$(somi::audit_log_path)"
55
- mkdir -p "$(dirname "$log")"
56
- printf '%s\t%s\t%s\t%s\n' \
57
- "$(date -u +%Y-%m-%dT%H:%M:%SZ)" \
58
- "$kind" \
59
- "${tool:-unknown}" \
60
- "$detail" \
61
- >> "$log"
62
- }
63
-
64
- # Deny a PreToolUse tool call. Use this for block-* hooks.
65
- # Emits the modern hookSpecificOutput.permissionDecision schema.
66
- somi::deny_pretool() {
67
- local reason="$1"
68
- jq -nc --arg r "$reason" '{
69
- hookSpecificOutput: {
70
- hookEventName: "PreToolUse",
71
- permissionDecision: "deny",
72
- permissionDecisionReason: $r
73
- }
74
- }'
75
- somi::audit "DENY" "$reason"
76
- exit 0
77
- }
78
-
79
- # Emit additionalContext for events that support it (PreToolUse, PostToolUse,
80
- # UserPromptSubmit). The harness shows this to the model on its next turn.
81
- # First arg is the event name; second is the context string.
82
- # Stop does NOT support additionalContext — do not call this from a Stop hook.
83
- somi::context() {
84
- local event="$1"
85
- local context="$2"
86
- jq -nc --arg e "$event" --arg c "$context" '{
87
- hookSpecificOutput: {
88
- hookEventName: $e,
89
- additionalContext: $c
90
- }
91
- }'
92
- }
93
-
94
- # Test whether a command string matches any extended-regex pattern.
95
- # Usage: somi::matches_any "$cmd" "pattern1" "pattern2" ...
96
- somi::matches_any() {
97
- local cmd="$1"; shift
98
- local pattern
99
- for pattern in "$@"; do
100
- if [[ "$cmd" =~ $pattern ]]; then
101
- return 0
102
- fi
103
- done
104
- return 1
105
- }
106
-
107
- # Case-insensitive variant. Uses nocasematch in a subshell to avoid leaking shell state.
108
- somi::matches_any_nocase() {
109
- local cmd="$1"; shift
110
- local pattern
111
- (
112
- shopt -s nocasematch
113
- for pattern in "$@"; do
114
- if [[ "$cmd" =~ $pattern ]]; then
115
- exit 0
116
- fi
117
- done
118
- exit 1
119
- )
120
- }
@@ -1,40 +0,0 @@
1
- #!/usr/bin/env bash
2
- # PostToolUse hook (matcher: *) — record every tool call to the SOMI audit log.
3
- #
4
- # Pairs with the BLOCK entries written from pre-tool hooks: gives you a single
5
- # log to grep for "what did the agent actually do during this session?"
6
- #
7
- # Sensitive arguments are trimmed; we record tool name, status, and a short summary.
8
-
9
- set -euo pipefail
10
-
11
- SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
12
- # shellcheck source=../lib/common.sh
13
- source "$SCRIPT_DIR/../lib/common.sh"
14
-
15
- somi::read_payload
16
-
17
- TOOL="$(somi::field '.tool_name')"
18
- [[ -z "$TOOL" ]] && exit 0
19
-
20
- SUMMARY=""
21
- case "$TOOL" in
22
- Bash)
23
- CMD="$(somi::field '.tool_input.command' | head -c 240)"
24
- SUMMARY="cmd=\"${CMD}\""
25
- ;;
26
- Write|Edit)
27
- P="$(somi::field '.tool_input.file_path')"
28
- SUMMARY="path=\"${P}\""
29
- ;;
30
- Read)
31
- P="$(somi::field '.tool_input.file_path')"
32
- SUMMARY="path=\"${P}\""
33
- ;;
34
- *)
35
- SUMMARY="$(printf '%s' "$SOMI_PAYLOAD" | jq -c '.tool_input // {}' 2>/dev/null | head -c 240 || true)"
36
- ;;
37
- esac
38
-
39
- somi::audit "CALL" "$SUMMARY"
40
- exit 0
@@ -1,80 +0,0 @@
1
- #!/usr/bin/env bash
2
- # PostToolUse hook (matcher: Write|Edit) — best-effort lint of just-changed files.
3
- #
4
- # Runs the project's configured linter on the touched file, if one is available.
5
- # Result is informational — we never block from a post-tool hook (the file is
6
- # already written). We surface lint failures back to the model so it can self-correct.
7
-
8
- set -euo pipefail
9
-
10
- SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
11
- # shellcheck source=../lib/common.sh
12
- source "$SCRIPT_DIR/../lib/common.sh"
13
-
14
- somi::read_payload
15
-
16
- PATH_INPUT="$(somi::field '.tool_input.file_path')"
17
- [[ -z "$PATH_INPUT" ]] && exit 0
18
- [[ ! -f "$PATH_INPUT" ]] && exit 0
19
-
20
- # Skip oversized files (likely generated).
21
- SIZE_BYTES=$(wc -c < "$PATH_INPUT" 2>/dev/null || echo 0)
22
- if (( SIZE_BYTES > 500000 )); then
23
- exit 0
24
- fi
25
-
26
- PROJECT_ROOT="${CLAUDE_PROJECT_DIR:-$PWD}"
27
-
28
- run_if_present() {
29
- local cmd="$1"; shift
30
- if command -v "$cmd" >/dev/null 2>&1; then
31
- "$cmd" "$@" 2>&1 || true
32
- fi
33
- }
34
-
35
- LINT_OUTPUT=""
36
-
37
- case "$PATH_INPUT" in
38
- *.py)
39
- if [[ -f "$PROJECT_ROOT/pyproject.toml" ]] || [[ -f "$PROJECT_ROOT/.ruff.toml" ]]; then
40
- LINT_OUTPUT="$(run_if_present ruff check --quiet "$PATH_INPUT")"
41
- fi
42
- ;;
43
- *.ts|*.tsx|*.js|*.jsx|*.mjs|*.cjs)
44
- has_eslint_config=false
45
- shopt -s nullglob
46
- for file in "$PROJECT_ROOT"/.eslintrc*; do
47
- if [[ -f "$file" ]]; then
48
- has_eslint_config=true
49
- break
50
- fi
51
- done
52
- shopt -u nullglob
53
-
54
- if [[ "$has_eslint_config" = true ]] || [[ -f "$PROJECT_ROOT/eslint.config.js" ]] || [[ -f "$PROJECT_ROOT/eslint.config.mjs" ]]; then
55
- LINT_OUTPUT="$(cd "$PROJECT_ROOT" && run_if_present npx --no-install eslint --no-color "$PATH_INPUT")"
56
- fi
57
- ;;
58
- *.go)
59
- if [[ -f "$PROJECT_ROOT/go.mod" ]]; then
60
- LINT_OUTPUT="$(cd "$PROJECT_ROOT" && run_if_present go vet "./$(dirname "${PATH_INPUT#$PROJECT_ROOT/}")/...")"
61
- fi
62
- ;;
63
- *.rs)
64
- if [[ -f "$PROJECT_ROOT/Cargo.toml" ]]; then
65
- LINT_OUTPUT="$(cd "$PROJECT_ROOT" && run_if_present cargo clippy --quiet --message-format=short 2>&1 | head -50)"
66
- fi
67
- ;;
68
- *.sh)
69
- LINT_OUTPUT="$(run_if_present shellcheck "$PATH_INPUT")"
70
- ;;
71
- esac
72
-
73
- if [[ -n "$LINT_OUTPUT" ]]; then
74
- # PostToolUse additionalContext must live under hookSpecificOutput per the
75
- # Claude Code hook schema. The bare {additionalContext} form is silently dropped.
76
- somi::context "PostToolUse" "Lint output for the file just changed:
77
- $LINT_OUTPUT"
78
- fi
79
-
80
- exit 0