@skathio/somi 1.2.0 → 2.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/.claude/settings.json +9 -9
  2. package/.claude-plugin/marketplace.json +1 -1
  3. package/.claude-plugin/plugin.json +1 -1
  4. package/.copilot-extension/extension.json +1 -1
  5. package/.copilot-extension/marketplace.json +1 -1
  6. package/README.md +6 -1
  7. package/VERSION +1 -1
  8. package/commands/adopt.md +6 -4
  9. package/commands/code-loop.md +13 -13
  10. package/commands/plan-loop.md +10 -10
  11. package/commands/pr.md +1 -1
  12. package/commands/release-readiness.md +4 -4
  13. package/commands/review-panel.md +1 -1
  14. package/commands/review.md +3 -3
  15. package/commands/ship-loop.md +2 -2
  16. package/commands/somi.md +2 -2
  17. package/commands/upgrade.md +1 -1
  18. package/examples/sample-consumer/CLAUDE.md +5 -2
  19. package/examples/sample-consumer/README.md +20 -9
  20. package/hooks/hooks.json +8 -8
  21. package/hooks/lib/common.mjs +328 -0
  22. package/hooks/post-tool/audit-log.mjs +93 -0
  23. package/hooks/post-tool/lint-changed-files.mjs +212 -0
  24. package/hooks/pre-tool/block-dangerous-bash.mjs +382 -0
  25. package/hooks/pre-tool/block-secret-writes.mjs +96 -0
  26. package/hooks/pre-tool/gate-dep-install.mjs +229 -0
  27. package/hooks/pre-tool/guard-protected-paths.mjs +157 -0
  28. package/hooks/session-start/detect-repo-instructions.mjs +264 -0
  29. package/hooks/user-prompt-submit/inject-workflow-context.mjs +432 -0
  30. package/package.json +2 -2
  31. package/rules/CLAUDE.md +6 -5
  32. package/scripts/somi-check.mjs +243 -0
  33. package/scripts/somi-findings.mjs +307 -0
  34. package/scripts/somi-loop.mjs +354 -0
  35. package/scripts/validate.sh +21 -16
  36. package/skills/clean-code/SKILL.md +1 -1
  37. package/tests/hooks/cases/audit-log.json +21 -0
  38. package/tests/hooks/cases/block-dangerous-bash.json +90 -2
  39. package/tests/hooks/cases/block-secret-writes.json +1 -1
  40. package/tests/hooks/cases/detect-repo-instructions.json +84 -0
  41. package/tests/hooks/cases/gate-dep-install.json +6 -1
  42. package/tests/hooks/cases/guard-protected-paths.json +1 -1
  43. package/tests/hooks/cases/inject-workflow-context.json +126 -0
  44. package/tests/hooks/cases/lint-changed-files.json +120 -0
  45. package/tests/hooks/run.sh +280 -15
  46. package/tests/scripts/goldens/somi-findings.json +336 -0
  47. package/tests/scripts/goldens/somi-loop.json +168 -0
  48. package/tests/scripts/run.sh +251 -30
  49. package/hooks/lib/common.sh +0 -133
  50. package/hooks/post-tool/audit-log.sh +0 -40
  51. package/hooks/post-tool/lint-changed-files.sh +0 -80
  52. package/hooks/pre-tool/block-dangerous-bash.sh +0 -171
  53. package/hooks/pre-tool/block-secret-writes.sh +0 -83
  54. package/hooks/pre-tool/gate-dep-install.sh +0 -113
  55. package/hooks/pre-tool/guard-protected-paths.sh +0 -89
  56. package/hooks/session-start/detect-repo-instructions.sh +0 -73
  57. package/hooks/user-prompt-submit/inject-workflow-context.sh +0 -143
  58. package/scripts/somi-check.sh +0 -135
  59. package/scripts/somi-findings.sh +0 -173
  60. package/scripts/somi-loop.sh +0 -225
@@ -1,135 +0,0 @@
1
- #!/usr/bin/env bash
2
- # somi-check.sh — host-agnostic working-tree guard (the portable enforcement layer).
3
- #
4
- # SoMi's deterministic hooks only run inside Claude Code. This script carries the
5
- # working-tree subset of those guarantees to every other host: run it as a git
6
- # pre-commit hook, a CI step, or via `npx` on GitHub Copilot setups — the
7
- # environments where the tool-call-time hooks don't exist.
8
- #
9
- # Checks (each maps to a hook-layer guarantee):
10
- # 1. Staged secret-bearing files (block-secret-writes' basename patterns)
11
- # 2. Staged lockfile hand-edits (guard-protected-paths' lockfile gate;
12
- # honors .somi/config.json lockfiles.allow_edit and SOMI_ALLOW_LOCKFILES)
13
- # 3. TODO(claude)/FIXME(claude) markers staged for commit (the loose-end nudge)
14
- # 4. Scratch/backup files staged (.bak/.orig/scratch_ — the same nudge)
15
- #
16
- # Usage:
17
- # scripts/somi-check.sh [--staged|--all] (default: --staged; --all scans the
18
- # full working tree vs HEAD)
19
- # Exit codes: 0 clean · 1 findings (fail the commit / CI step) · 64 error.
20
- #
21
- # Install as a pre-commit hook:
22
- # ln -s ../../<path-to-somi>/scripts/somi-check.sh .git/hooks/pre-commit
23
- # Or as a CI step:
24
- # - run: bash <path-to-somi>/scripts/somi-check.sh --all
25
- #
26
- # Tested by tests/scripts/run.sh (wired into scripts/validate.sh / CI).
27
-
28
- set -euo pipefail
29
-
30
- die() { echo "somi-check: $*" >&2; exit 64; }
31
- command -v git >/dev/null 2>&1 || die "requires git"
32
-
33
- MODE="staged"
34
- case "${1:-}" in
35
- --all) MODE="all" ;;
36
- --staged|"") ;;
37
- *) die "unknown argument: $1" ;;
38
- esac
39
-
40
- ROOT="${CLAUDE_PROJECT_DIR:-$PWD}"
41
- [[ "$ROOT" == *'${'* ]] && ROOT="$PWD"
42
- git -C "$ROOT" rev-parse --git-dir >/dev/null 2>&1 || die "not a git repository: $ROOT"
43
-
44
- changed_files() {
45
- if [[ "$MODE" == "staged" ]]; then
46
- git -C "$ROOT" diff --cached --name-only --diff-filter=ACM
47
- else
48
- git -C "$ROOT" diff HEAD --name-only --diff-filter=ACM
49
- git -C "$ROOT" ls-files --others --exclude-standard
50
- fi
51
- }
52
-
53
- changed_content() { # additions only
54
- if [[ "$MODE" == "staged" ]]; then
55
- git -C "$ROOT" diff --cached --no-color --unified=0
56
- else
57
- git -C "$ROOT" diff HEAD --no-color --unified=0
58
- fi
59
- }
60
-
61
- # Mirrors block-secret-writes.sh's basename patterns (keep in sync when extending).
62
- SECRET_PATTERNS=(
63
- '^\.env$' '^\.env\.local$' '^\.env\.production$' '^\.env\.prod$' '^\.env\.staging$' '^\.env\.secret$'
64
- '\.pem$' '\.key$' '\.p12$' '\.pfx$' '\.jks$'
65
- '^id_rsa$' '^id_ed25519$' '^id_ecdsa$' '^id_dsa$'
66
- '-key\.json$' '-credentials\.json$' 'service-account.*\.json$'
67
- '\.netrc$' '\.pgpass$' '\.kdbx$' 'secrets?\.ya?ml$' 'secrets?\.json$'
68
- )
69
- EXAMPLE_BASENAMES=('.env.example' '.env.sample' '.env.template' '.env.dist')
70
-
71
- LOCKFILES=(package-lock.json yarn.lock pnpm-lock.yaml Cargo.lock Gemfile.lock poetry.lock uv.lock composer.lock go.sum)
72
-
73
- lockfiles_allowed() {
74
- # env wins (including =0); then committed config; default deny.
75
- if [[ -n "${SOMI_ALLOW_LOCKFILES:-}" ]]; then
76
- [[ "$SOMI_ALLOW_LOCKFILES" == "1" ]]
77
- return
78
- fi
79
- local cfg="$ROOT/.somi/config.json"
80
- [[ -f "$cfg" ]] && [[ "$(jq -r '.lockfiles.allow_edit // empty' "$cfg" 2>/dev/null)" == "true" ]]
81
- }
82
-
83
- findings=0
84
- report() { echo "somi-check: $1" >&2; findings=$((findings + 1)); }
85
-
86
- # 1 + 2 + 4 — file-name checks.
87
- while IFS= read -r f; do
88
- [[ -z "$f" ]] && continue
89
- base="$(basename "$f")"
90
-
91
- example=0
92
- for ex in "${EXAMPLE_BASENAMES[@]}"; do
93
- [[ "$base" == "$ex" ]] && { example=1; break; }
94
- done
95
- if (( ! example )); then
96
- for p in "${SECRET_PATTERNS[@]}"; do
97
- if [[ "$base" =~ $p ]]; then
98
- report "secret-bearing file in the change set: $f (commit only .env.example-style templates)"
99
- break
100
- fi
101
- done
102
- fi
103
-
104
- if ! lockfiles_allowed; then
105
- for l in "${LOCKFILES[@]}"; do
106
- if [[ "$base" == "$l" ]]; then
107
- # Hand-edit heuristic: a lockfile changing without its manifest alongside.
108
- dir="$(dirname "$f")"
109
- prefix=""
110
- [[ "$dir" != "." ]] && prefix="${dir}/"
111
- if ! changed_files | grep -qE "^${prefix}(package\.json|Cargo\.toml|Gemfile|pyproject\.toml|composer\.json|go\.mod)$"; then
112
- report "lockfile changed without its manifest: $f (regenerate via the package manager, or set lockfiles.allow_edit in .somi/config.json)"
113
- fi
114
- break
115
- fi
116
- done
117
- fi
118
-
119
- case "$base" in
120
- *.bak|*.orig|scratch_*)
121
- report "scratch/backup file in the change set: $f"
122
- ;;
123
- esac
124
- done < <(changed_files)
125
-
126
- # 3 — added TODO(claude)/FIXME(claude) markers.
127
- if changed_content | grep -E '^\+.*(TODO\(claude\)|TODO\(agent\)|FIXME\(claude\))' -q; then
128
- report "TODO(claude)/FIXME(claude) markers added — resolve them or convert to owned follow-ups before committing"
129
- fi
130
-
131
- if (( findings > 0 )); then
132
- echo "somi-check: $findings finding(s) — see above." >&2
133
- exit 1
134
- fi
135
- echo "somi-check: clean."
@@ -1,173 +0,0 @@
1
- #!/usr/bin/env bash
2
- # somi-findings.sh — the findings ledger: identity and lifecycle for review findings.
3
- #
4
- # Review findings used to live only as prose in per-review markdown files. The
5
- # loop circuit breakers matched recurrences from conversation memory (lost on
6
- # session death), and a re-review had no way to assert "is F-3 fixed?" — it
7
- # rediscovered everything. This ledger gives each finding a stable ID and a
8
- # status, computed mechanically on a stable locus (file + symbol + normalized
9
- # title), so:
10
- # - /code-loop's circuit breaker fires on a CONSECUTIVE-pass recurrence,
11
- # - /ship-loop's cross-layer breaker fires on a CROSS-RUN recurrence,
12
- # - /review starts by re-checking open findings instead of starting blind,
13
- # - progress.md follow-ups can reference F-<n> instead of prose.
14
- #
15
- # Ledger: .somi/reviews/<slug>/findings.json — committed with the other review
16
- # artifacts (it is the machine view; the markdown review file stays the human
17
- # view; the same command writes both in the same step).
18
- #
19
- # Subcommands:
20
- # record --slug S [--review FILE] [--run ID] [--pass N]
21
- # stdin: JSON array [{file, symbol, title, severity, confidence}, …]
22
- # Upserts each finding: new locus → new F-<n>; known OPEN locus →
23
- # appends a sighting. Prints one JSON line per finding with
24
- # {id, state: "new"|"known", recurring_consecutive, recurring_cross_run}.
25
- # Exit 5 if ANY finding is recurring_consecutive (the in-loop circuit
26
- # breaker signal) — the caller decides what to do with it.
27
- # resolve --slug S --id F-3 --status fixed|accepted|wontfix [--by REVIEW]
28
- # reopen --slug S --id F-3 [--by REVIEW]
29
- # open --slug S → JSON array of open findings
30
- # get --slug S --id F-3 → one finding
31
- #
32
- # Locus matching: same file + same symbol (case-insensitive) + same normalized
33
- # title (lowercased, non-alphanumerics collapsed, first 8 words). Line numbers
34
- # are deliberately NOT part of the locus — lines drift between passes.
35
- #
36
- # Exit codes: 0 ok · 5 consecutive recurrence detected (record only) · 64 error.
37
- # Tested by tests/scripts/run.sh (wired into scripts/validate.sh / CI).
38
-
39
- set -euo pipefail
40
-
41
- die() { echo "somi-findings: $*" >&2; exit 64; }
42
- command -v jq >/dev/null 2>&1 || die "requires jq"
43
-
44
- project_root() {
45
- local b="${CLAUDE_PROJECT_DIR:-$PWD}"
46
- [[ "$b" == *'${'* ]] && b="$PWD"
47
- printf '%s' "$b"
48
- }
49
-
50
- CMD="${1:-}"; shift || true
51
- SLUG="" REVIEW="" RUN="" PASS=0 ID="" STATUS="" BY=""
52
- while (( $# > 0 )); do
53
- case "$1" in
54
- --slug) SLUG="$2"; shift 2 ;;
55
- --review) REVIEW="$2"; shift 2 ;;
56
- --run) RUN="$2"; shift 2 ;;
57
- --pass) PASS="$2"; shift 2 ;;
58
- --id) ID="$2"; shift 2 ;;
59
- --status) STATUS="$2"; shift 2 ;;
60
- --by) BY="$2"; shift 2 ;;
61
- *) die "unknown argument: $1" ;;
62
- esac
63
- done
64
- [[ -n "$CMD" ]] || die "usage: somi-findings.sh <record|resolve|reopen|open|get> --slug <slug> …"
65
- [[ -n "$SLUG" ]] || die "--slug is required"
66
-
67
- LEDGER_DIR="$(project_root)/.somi/reviews/$SLUG"
68
- LEDGER="$LEDGER_DIR/findings.json"
69
-
70
- ensure_ledger() {
71
- mkdir -p "$LEDGER_DIR"
72
- [[ -f "$LEDGER" ]] || printf '{"next_id": 1, "findings": []}\n' > "$LEDGER"
73
- }
74
-
75
- normalize_title() {
76
- printf '%s' "$1" \
77
- | tr '[:upper:]' '[:lower:]' \
78
- | tr -cs 'a-z0-9' ' ' \
79
- | awk '{ for (i = 1; i <= NF && i <= 8; i++) printf "%s%s", (i > 1 ? " " : ""), $i }'
80
- }
81
-
82
- case "$CMD" in
83
- record)
84
- ensure_ledger
85
- input="$(cat)"
86
- count="$(jq 'length' <<<"$input")" || die "stdin must be a JSON array of findings"
87
- now="$(date -u +%Y-%m-%d)"
88
- breaker=0
89
- for ((i = 0; i < count; i++)); do
90
- f="$(jq -c ".[$i]" <<<"$input")"
91
- file="$(jq -r '.file // empty' <<<"$f")"
92
- symbol="$(jq -r '.symbol // ""' <<<"$f" | tr '[:upper:]' '[:lower:]')"
93
- title="$(jq -r '.title // empty' <<<"$f")"
94
- [[ -n "$file" && -n "$title" ]] || die "finding $i needs at least {file, title}"
95
- key="${file}|${symbol}|$(normalize_title "$title")"
96
-
97
- existing="$(jq -r --arg k "$key" \
98
- '[.findings[] | select(.key == $k and .status == "open")][0].id // empty' "$LEDGER")"
99
-
100
- if [[ -n "$existing" ]]; then
101
- # Known open finding: recurrence classification BEFORE appending the sighting.
102
- recurring_consecutive="$(jq -r --arg id "$existing" --arg run "$RUN" --argjson p "$PASS" \
103
- '[.findings[] | select(.id == $id) | .seen[]
104
- | select(.run == $run and .pass == ($p - 1))] | length > 0' "$LEDGER")"
105
- recurring_cross="$(jq -r --arg id "$existing" --arg run "$RUN" \
106
- '[.findings[] | select(.id == $id) | .seen[] | select(.run != $run)] | length > 0' "$LEDGER")"
107
- tmp="$(mktemp)"
108
- jq --arg id "$existing" --arg rev "$REVIEW" --arg run "$RUN" \
109
- --argjson p "$PASS" --arg d "$now" \
110
- '(.findings[] | select(.id == $id) | .seen) += [{review: $rev, run: $run, pass: $p, date: $d}]' \
111
- "$LEDGER" > "$tmp" && mv "$tmp" "$LEDGER"
112
- [[ "$recurring_consecutive" == "true" ]] && breaker=1
113
- jq -nc --arg id "$existing" --argjson rc "$recurring_consecutive" --argjson rx "$recurring_cross" \
114
- '{id: $id, state: "known", recurring_consecutive: $rc, recurring_cross_run: $rx}'
115
- else
116
- new_id="F-$(jq -r '.next_id' "$LEDGER")"
117
- tmp="$(mktemp)"
118
- jq --arg id "$new_id" --arg key "$key" --argjson f "$f" \
119
- --arg rev "$REVIEW" --arg run "$RUN" --argjson p "$PASS" --arg d "$now" \
120
- '.next_id += 1
121
- | .findings += [{
122
- id: $id, key: $key,
123
- locus: {file: $f.file, symbol: ($f.symbol // "")},
124
- title: $f.title,
125
- severity: ($f.severity // "Minor"),
126
- confidence: ($f.confidence // "Medium"),
127
- status: "open",
128
- introduced_by: $rev, resolved_by: null,
129
- seen: [{review: $rev, run: $run, pass: $p, date: $d}]
130
- }]' "$LEDGER" > "$tmp" && mv "$tmp" "$LEDGER"
131
- jq -nc --arg id "$new_id" \
132
- '{id: $id, state: "new", recurring_consecutive: false, recurring_cross_run: false}'
133
- fi
134
- done
135
- (( breaker )) && exit 5
136
- exit 0
137
- ;;
138
-
139
- resolve)
140
- ensure_ledger
141
- [[ -n "$ID" && -n "$STATUS" ]] || die "resolve requires --id and --status"
142
- case "$STATUS" in fixed|accepted|wontfix) ;; *) die "--status must be fixed|accepted|wontfix" ;; esac
143
- tmp="$(mktemp)"
144
- jq --arg id "$ID" --arg s "$STATUS" --arg by "$BY" \
145
- '(.findings[] | select(.id == $id)) |= (.status = $s | .resolved_by = $by)' \
146
- "$LEDGER" > "$tmp" && mv "$tmp" "$LEDGER"
147
- jq -c --arg id "$ID" '.findings[] | select(.id == $id) | {id, status, resolved_by}' "$LEDGER"
148
- ;;
149
-
150
- reopen)
151
- ensure_ledger
152
- [[ -n "$ID" ]] || die "reopen requires --id"
153
- tmp="$(mktemp)"
154
- jq --arg id "$ID" --arg by "$BY" \
155
- '(.findings[] | select(.id == $id)) |= (.status = "open" | .resolved_by = null | .reopened_by = $by)' \
156
- "$LEDGER" > "$tmp" && mv "$tmp" "$LEDGER"
157
- jq -c --arg id "$ID" '.findings[] | select(.id == $id) | {id, status}' "$LEDGER"
158
- ;;
159
-
160
- open)
161
- ensure_ledger
162
- jq '[.findings[] | select(.status == "open")
163
- | {id, locus, title, severity, confidence, introduced_by}]' "$LEDGER"
164
- ;;
165
-
166
- get)
167
- ensure_ledger
168
- [[ -n "$ID" ]] || die "get requires --id"
169
- jq --arg id "$ID" '.findings[] | select(.id == $id)' "$LEDGER"
170
- ;;
171
-
172
- *) die "unknown subcommand: $CMD" ;;
173
- esac
@@ -1,225 +0,0 @@
1
- #!/usr/bin/env bash
2
- # somi-loop.sh — deterministic state engine for the bounded loops.
3
- #
4
- # The loop commands (/code-loop, /plan-loop, /ship-loop, /code-parallel) used to
5
- # ask the orchestrating model to simulate a state machine in conversation
6
- # context: count passes, parse `git diff --shortstat`, remember a baseline SHA,
7
- # and compare findings across passes. Models miscount and sessions die; the
8
- # caps are SoMi's central safety claim, so their arithmetic lives here instead.
9
- # The model keeps the judgment (what to do when a gate fires); this script owns
10
- # the counting, and the state survives session death — a loop can RESUME.
11
- #
12
- # State: .claude/somi-state/loop/<slug>[.<iteration>].json under the project
13
- # root (project-local, gitignored by SoMi's conventions). Never committed.
14
- #
15
- # Cap precedence (matches the gate tables): CLI flag > env var > .somi/config.json
16
- # > default. Diff measurement EXCLUDES .somi/ and .claude/ — artifact churn
17
- # (progress/diary updates every pass) must not eat the code diff budget.
18
- #
19
- # Exit codes (callers branch on these — do not repurpose):
20
- # 0 ok
21
- # 2 max-passes-exceeded (`pass` would exceed the cap)
22
- # 3 diff-cap-exceeded (`check-diff`: weighted lines over the cap;
23
- # out-of-scope lines count double)
24
- # 64 usage / environment error
25
- #
26
- # Subcommands:
27
- # init --slug S --loop code|plan [--iteration N.M] [--files "p1 p2 …"]
28
- # [--max-passes N] [--diff-cap N] [--severity-floor Sev]
29
- # Captures BASELINE_SHA once, resolves caps, writes fresh state.
30
- # Refuses to clobber a still-running state unless --force.
31
- # resume --slug S [--iteration N.M]
32
- # Prints existing state (exit 64 if none) — session-death recovery.
33
- # pass --slug S [--iteration N.M]
34
- # Increments the pass counter; exit 2 when it would exceed max_passes.
35
- # check-diff --slug S [--iteration N.M]
36
- # Cumulative diff vs the recorded baseline (committed + working tree,
37
- # .somi/.claude excluded). Out-of-scope files (not in the iteration
38
- # file list) count DOUBLE. Prints JSON; exit 3 when over the cap.
39
- # record-pass --slug S [--iteration N.M] --verdict V [--blockers N] [--majors N]
40
- # Appends a history entry (with current diff size) for telemetry.
41
- # finish --slug S [--iteration N.M] --status done|stopped-<reason>
42
- # stats --slug S [--iteration N.M]
43
- # Prints the state JSON (passes used, history, caps — the run ledger).
44
- #
45
- # Tested by tests/scripts/run.sh (wired into scripts/validate.sh / CI).
46
-
47
- set -euo pipefail
48
-
49
- die() { echo "somi-loop: $*" >&2; exit 64; }
50
- command -v jq >/dev/null 2>&1 || die "requires jq"
51
- command -v git >/dev/null 2>&1 || die "requires git"
52
-
53
- project_root() {
54
- local b="${CLAUDE_PROJECT_DIR:-$PWD}"
55
- [[ "$b" == *'${'* ]] && b="$PWD"
56
- printf '%s' "$b"
57
- }
58
-
59
- config_val() { # $1 = jq path into .somi/config.json
60
- local cfg
61
- cfg="$(project_root)/.somi/config.json"
62
- [[ -f "$cfg" ]] || return 0
63
- jq -r "$1 // empty" "$cfg" 2>/dev/null || true
64
- }
65
-
66
- STATE_DIR="${SOMI_LOOP_STATE_DIR:-$(project_root)/.claude/somi-state/loop}"
67
-
68
- # --- argument parsing (shared) -----------------------------------------------
69
- CMD="${1:-}"; shift || true
70
- SLUG="" LOOP="code" ITERATION="" FILES="" VERDICT="" BLOCKERS=0 MAJORS=0
71
- STATUS="" FORCE=0
72
- ARG_MAX_PASSES="" ARG_DIFF_CAP="" ARG_SEVERITY=""
73
- while (( $# > 0 )); do
74
- case "$1" in
75
- --slug) SLUG="$2"; shift 2 ;;
76
- --loop) LOOP="$2"; shift 2 ;;
77
- --iteration) ITERATION="$2"; shift 2 ;;
78
- --files) FILES="$2"; shift 2 ;;
79
- --max-passes) ARG_MAX_PASSES="$2"; shift 2 ;;
80
- --diff-cap) ARG_DIFF_CAP="$2"; shift 2 ;;
81
- --severity-floor) ARG_SEVERITY="$2"; shift 2 ;;
82
- --verdict) VERDICT="$2"; shift 2 ;;
83
- --blockers) BLOCKERS="$2"; shift 2 ;;
84
- --majors) MAJORS="$2"; shift 2 ;;
85
- --status) STATUS="$2"; shift 2 ;;
86
- --force) FORCE=1; shift ;;
87
- *) die "unknown argument: $1" ;;
88
- esac
89
- done
90
- [[ -n "$CMD" ]] || die "usage: somi-loop.sh <init|resume|pass|check-diff|record-pass|finish|stats> --slug <slug> …"
91
- [[ -n "$SLUG" ]] || die "--slug is required"
92
-
93
- state_file() {
94
- local name="$SLUG"
95
- [[ -n "$ITERATION" ]] && name="$SLUG.$ITERATION"
96
- printf '%s/%s.json' "$STATE_DIR" "$name"
97
- }
98
- SF="$(state_file)"
99
-
100
- require_state() { [[ -f "$SF" ]] || die "no loop state at $SF — run init first"; }
101
-
102
- # Weighted cumulative diff vs baseline. Out-of-scope lines count double.
103
- compute_diff() { # prints: total_lines <TAB> weighted_lines <TAB> out_of_scope (space-joined)
104
- local base files_json root
105
- base="$(jq -r '.baseline_sha' "$SF")"
106
- files_json="$(jq -c '.iteration_files' "$SF")"
107
- root="$(project_root)"
108
- local total=0 weighted=0 oos=""
109
- local added deleted file lines in_scope entry
110
- while IFS=$'\t' read -r added deleted file; do
111
- [[ -z "$file" ]] && continue
112
- [[ "$added" == "-" ]] && added=0 # binary
113
- [[ "$deleted" == "-" ]] && deleted=0
114
- lines=$((added + deleted))
115
- total=$((total + lines))
116
- in_scope=0
117
- while IFS= read -r entry; do
118
- [[ -z "$entry" ]] && continue
119
- if [[ "$file" == "$entry" || ( "$entry" == */ && "$file" == "$entry"* ) ]]; then
120
- in_scope=1; break
121
- fi
122
- done < <(jq -r '.[]?' <<<"$files_json")
123
- if (( in_scope )); then
124
- weighted=$((weighted + lines))
125
- else
126
- weighted=$((weighted + 2 * lines))
127
- oos+="${oos:+ }$file"
128
- fi
129
- done < <(git -C "$root" diff --numstat "$base" -- . ':(exclude).somi' ':(exclude).claude' 2>/dev/null)
130
- # Trailing newline matters: `read` under `set -e` fails on EOF without one.
131
- printf '%s\t%s\t%s\n' "$total" "$weighted" "$oos"
132
- }
133
-
134
- case "$CMD" in
135
- init)
136
- mkdir -p "$STATE_DIR"
137
- if [[ -f "$SF" && $FORCE -eq 0 ]] && [[ "$(jq -r '.status' "$SF")" == "running" ]]; then
138
- die "loop state already running at $SF — use 'resume' to continue it, or 'init --force' to discard"
139
- fi
140
- # Cap resolution: CLI > env > config > default (per loop type).
141
- local_max="" local_cap="" local_sev=""
142
- if [[ "$LOOP" == "plan" ]]; then
143
- local_max="${ARG_MAX_PASSES:-${SOMI_PLAN_LOOP_MAX_PASSES:-$(config_val '.plan_loop.max_passes')}}"
144
- local_sev="${ARG_SEVERITY:-${SOMI_PLAN_LOOP_SEVERITY_FLOOR:-$(config_val '.plan_loop.severity_floor')}}"
145
- local_cap="0" # plan loops have no diff cap
146
- else
147
- local_max="${ARG_MAX_PASSES:-${SOMI_CODE_LOOP_MAX_PASSES:-$(config_val '.code_loop.max_passes')}}"
148
- local_sev="${ARG_SEVERITY:-${SOMI_CODE_LOOP_SEVERITY_FLOOR:-$(config_val '.code_loop.severity_floor')}}"
149
- local_cap="${ARG_DIFF_CAP:-${SOMI_CODE_LOOP_DIFF_CAP:-$(config_val '.code_loop.diff_cap_lines')}}"
150
- fi
151
- local_max="${local_max:-3}"; local_sev="${local_sev:-Major}"; local_cap="${local_cap:-400}"
152
- baseline="$(git -C "$(project_root)" rev-parse HEAD)" || die "cannot resolve HEAD"
153
- # printf with trailing newline: jq -R needs one line even when --files is empty.
154
- files_json="$(printf '%s\n' "$FILES" | jq -R 'split(" ") | map(select(length > 0))')"
155
- jq -n \
156
- --arg slug "$SLUG" --arg loop "$LOOP" --arg iteration "$ITERATION" \
157
- --arg baseline "$baseline" --arg started "$(date -u +%Y-%m-%dT%H:%M:%SZ)" \
158
- --argjson max "$local_max" --argjson cap "$local_cap" --arg sev "$local_sev" \
159
- --argjson files "$files_json" \
160
- '{slug: $slug, loop: $loop, iteration: $iteration,
161
- baseline_sha: $baseline, started: $started, status: "running",
162
- caps: {max_passes: $max, diff_cap_lines: $cap, severity_floor: $sev},
163
- iteration_files: $files, pass: 0, history: []}' > "$SF"
164
- jq -c '{baseline_sha, caps, state_file: input_filename}' "$SF"
165
- ;;
166
-
167
- resume)
168
- require_state
169
- jq -c . "$SF"
170
- ;;
171
-
172
- pass)
173
- require_state
174
- max="$(jq -r '.caps.max_passes' "$SF")"
175
- cur="$(jq -r '.pass' "$SF")"
176
- if (( cur + 1 > max )); then
177
- echo "max-passes-exceeded: pass $((cur + 1)) > cap $max" >&2
178
- exit 2
179
- fi
180
- tmp="$(mktemp)"; jq '.pass += 1' "$SF" > "$tmp" && mv "$tmp" "$SF"
181
- jq -c '{pass, max_passes: .caps.max_passes}' "$SF"
182
- ;;
183
-
184
- check-diff)
185
- require_state
186
- IFS=$'\t' read -r total weighted oos < <(compute_diff)
187
- cap="$(jq -r '.caps.diff_cap_lines' "$SF")"
188
- oos_json="$(printf '%s\n' "$oos" | jq -R 'split(" ") | map(select(length > 0))')"
189
- jq -nc --argjson total "$total" --argjson weighted "$weighted" \
190
- --argjson cap "$cap" --argjson oos "$oos_json" \
191
- '{diff_lines: $total, weighted_lines: $weighted, cap: $cap, out_of_scope: $oos}'
192
- if (( cap > 0 && weighted > cap )); then
193
- echo "diff-cap-exceeded: weighted $weighted > cap $cap (out-of-scope counts double)" >&2
194
- exit 3
195
- fi
196
- ;;
197
-
198
- record-pass)
199
- require_state
200
- [[ -n "$VERDICT" ]] || die "record-pass requires --verdict"
201
- IFS=$'\t' read -r total _ _ < <(compute_diff)
202
- tmp="$(mktemp)"
203
- jq --arg v "$VERDICT" --argjson b "$BLOCKERS" --argjson m "$MAJORS" \
204
- --argjson lines "$total" --arg at "$(date -u +%Y-%m-%dT%H:%M:%SZ)" \
205
- '.history += [{pass: .pass, verdict: $v, blockers: $b, majors: $m, diff_lines: $lines, at: $at}]' \
206
- "$SF" > "$tmp" && mv "$tmp" "$SF"
207
- jq -c '.history[-1]' "$SF"
208
- ;;
209
-
210
- finish)
211
- require_state
212
- [[ -n "$STATUS" ]] || die "finish requires --status"
213
- tmp="$(mktemp)"
214
- jq --arg s "$STATUS" --arg at "$(date -u +%Y-%m-%dT%H:%M:%SZ)" \
215
- '.status = $s | .finished = $at' "$SF" > "$tmp" && mv "$tmp" "$SF"
216
- jq -c '{status, pass, history: (.history | length)}' "$SF"
217
- ;;
218
-
219
- stats)
220
- require_state
221
- jq . "$SF"
222
- ;;
223
-
224
- *) die "unknown subcommand: $CMD" ;;
225
- esac