@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.
Files changed (56) 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 +1 -1
  5. package/.copilot-extension/marketplace.json +1 -1
  6. package/README.md +5 -0
  7. package/VERSION +1 -1
  8. package/commands/code-loop.md +12 -12
  9. package/commands/plan-loop.md +9 -9
  10. package/commands/pr.md +1 -1
  11. package/commands/release-readiness.md +3 -3
  12. package/commands/review-panel.md +1 -1
  13. package/commands/review.md +3 -3
  14. package/commands/ship-loop.md +2 -2
  15. package/commands/somi.md +1 -1
  16. package/commands/upgrade.md +1 -1
  17. package/hooks/hooks.json +8 -8
  18. package/hooks/lib/common.mjs +328 -0
  19. package/hooks/post-tool/audit-log.mjs +93 -0
  20. package/hooks/post-tool/lint-changed-files.mjs +212 -0
  21. package/hooks/pre-tool/block-dangerous-bash.mjs +382 -0
  22. package/hooks/pre-tool/block-secret-writes.mjs +96 -0
  23. package/hooks/pre-tool/gate-dep-install.mjs +229 -0
  24. package/hooks/pre-tool/guard-protected-paths.mjs +157 -0
  25. package/hooks/session-start/detect-repo-instructions.mjs +264 -0
  26. package/hooks/user-prompt-submit/inject-workflow-context.mjs +432 -0
  27. package/package.json +2 -2
  28. package/scripts/somi-check.mjs +243 -0
  29. package/scripts/somi-findings.mjs +307 -0
  30. package/scripts/somi-loop.mjs +354 -0
  31. package/scripts/validate.sh +21 -16
  32. package/skills/clean-code/SKILL.md +1 -1
  33. package/tests/hooks/cases/audit-log.json +21 -0
  34. package/tests/hooks/cases/block-dangerous-bash.json +90 -2
  35. package/tests/hooks/cases/block-secret-writes.json +1 -1
  36. package/tests/hooks/cases/detect-repo-instructions.json +84 -0
  37. package/tests/hooks/cases/gate-dep-install.json +6 -1
  38. package/tests/hooks/cases/guard-protected-paths.json +1 -1
  39. package/tests/hooks/cases/inject-workflow-context.json +126 -0
  40. package/tests/hooks/cases/lint-changed-files.json +120 -0
  41. package/tests/hooks/run.sh +280 -15
  42. package/tests/scripts/goldens/somi-findings.json +336 -0
  43. package/tests/scripts/goldens/somi-loop.json +168 -0
  44. package/tests/scripts/run.sh +251 -30
  45. package/hooks/lib/common.sh +0 -133
  46. package/hooks/post-tool/audit-log.sh +0 -40
  47. package/hooks/post-tool/lint-changed-files.sh +0 -80
  48. package/hooks/pre-tool/block-dangerous-bash.sh +0 -171
  49. package/hooks/pre-tool/block-secret-writes.sh +0 -83
  50. package/hooks/pre-tool/gate-dep-install.sh +0 -113
  51. package/hooks/pre-tool/guard-protected-paths.sh +0 -89
  52. package/hooks/session-start/detect-repo-instructions.sh +0 -73
  53. package/hooks/user-prompt-submit/inject-workflow-context.sh +0 -143
  54. package/scripts/somi-check.sh +0 -135
  55. package/scripts/somi-findings.sh +0 -173
  56. package/scripts/somi-loop.sh +0 -225
@@ -0,0 +1,243 @@
1
+ #!/usr/bin/env node
2
+ // somi-check.mjs — host-agnostic working-tree guard (the portable enforcement layer).
3
+ //
4
+ // Node port of scripts/somi-check.sh (node-runtime-port, phase 1, iteration 1.3).
5
+ // Zero-dependency: stdlib only (node:fs, node:path, node:child_process). No jq, no bash.
6
+ // Behavior-preserving — exit codes are frozen and reproduced exactly; see the bash
7
+ // original's header comment for the full rationale.
8
+ //
9
+ // SHEBANG NOTE (the sanctioned exception to D1's "no shebang/exec-bit reliance"
10
+ // principle for the hook/manifest invocation path): every other Node port in this
11
+ // work item (somi-loop.mjs, somi-findings.mjs) is invoked as `node <file>` and carries
12
+ // no shebang. This file keeps one because package.json's `bin` field
13
+ // ("somi-check": "scripts/somi-check.sh", repointed to this file in Phase 3 iteration
14
+ // 3.2) is a *separate* invocation path via npm's own bin-symlinking, which on POSIX
15
+ // needs the linked file to be directly executable — that relies on a shebang. That's
16
+ // npm's own contract, distinct from how hooks.json/somi-loop/somi-findings are invoked.
17
+ // See phases/01-state-scripts-port.md's Iteration 1.3 implementation note. (The
18
+ // executable bit itself is left to Phase 3 iteration 3.2, which owns the bin repoint
19
+ // and the live-wiring smoke test — this iteration only adds the file content needed.)
20
+ //
21
+ // Checks (each maps to a hook-layer guarantee):
22
+ // 1. Staged secret-bearing files (block-secret-writes' basename patterns)
23
+ // 2. Staged lockfile hand-edits (guard-protected-paths' lockfile gate;
24
+ // honors .somi/config.json lockfiles.allow_edit and SOMI_ALLOW_LOCKFILES)
25
+ // 3. TODO(claude)/FIXME(claude) markers staged for commit (the loose-end nudge)
26
+ // 4. Scratch/backup files staged (.bak/.orig/scratch_ — the same nudge)
27
+ //
28
+ // Usage:
29
+ // node scripts/somi-check.mjs [--staged|--all] (default: --staged; --all scans the
30
+ // full working tree vs HEAD)
31
+ // Exit codes: 0 clean · 1 findings (fail the commit / CI step) · 64 error.
32
+ //
33
+ // Tested by tests/scripts/run.sh (wired into scripts/validate.sh / CI).
34
+
35
+ import fs from 'node:fs';
36
+ import path from 'node:path';
37
+ import { execFileSync } from 'node:child_process';
38
+
39
+ const PROG = 'somi-check';
40
+
41
+ // Thrown to unwind to the top-level handler, which sets process.exitCode and lets Node
42
+ // exit naturally — avoids process.exit()'s risk of truncating buffered stdout/stderr
43
+ // writes on a pipe. Same idiom as somi-loop.mjs / somi-findings.mjs (1.1/1.2,
44
+ // reviewer-blessed).
45
+ class ExitSignal extends Error {
46
+ constructor(code) {
47
+ super(`exit ${code}`);
48
+ this.code = code;
49
+ }
50
+ }
51
+
52
+ function die(msg) {
53
+ process.stderr.write(`${PROG}: ${msg}\n`);
54
+ throw new ExitSignal(64);
55
+ }
56
+
57
+ function requireGit() {
58
+ try {
59
+ execFileSync('git', ['--version'], { stdio: 'ignore' });
60
+ } catch {
61
+ die('requires git');
62
+ }
63
+ }
64
+
65
+ function projectRoot() {
66
+ let b = process.env.CLAUDE_PROJECT_DIR || process.cwd();
67
+ if (b.includes('${')) b = process.cwd();
68
+ return b;
69
+ }
70
+
71
+ // Mirrors block-secret-writes.sh's basename patterns (keep in sync when extending).
72
+ // Bash matches these as POSIX ERE via `[[ "$base" =~ $p ]]` — every pattern here uses
73
+ // only `^`/`$`/`.`/`*`/`?` and escaped literal dots, which are byte-identical in ERE
74
+ // and JS regex syntax (no `[[:class:]]` bracket expressions, no ERE-vs-PCRE anchor
75
+ // divergence to worry about). CAVEAT, do not inherit blindly in 2.9: JS `.` refuses to
76
+ // match \r/U+2028/U+2029 where POSIX `.` matches every byte except \n — harmless HERE
77
+ // only because git's core.quotePath C-escapes non-ASCII filenames before either
78
+ // implementation sees them; on raw CONTENT (see the TODO-marker check below, and all of
79
+ // block-dangerous-bash.sh's command-string patterns) that difference is live.
80
+ const SECRET_PATTERNS = [
81
+ /^\.env$/, /^\.env\.local$/, /^\.env\.production$/, /^\.env\.prod$/, /^\.env\.staging$/, /^\.env\.secret$/,
82
+ /\.pem$/, /\.key$/, /\.p12$/, /\.pfx$/, /\.jks$/,
83
+ /^id_rsa$/, /^id_ed25519$/, /^id_ecdsa$/, /^id_dsa$/,
84
+ /-key\.json$/, /-credentials\.json$/, /service-account.*\.json$/,
85
+ /\.netrc$/, /\.pgpass$/, /\.kdbx$/, /secrets?\.ya?ml$/, /secrets?\.json$/,
86
+ ];
87
+ const EXAMPLE_BASENAMES = ['.env.example', '.env.sample', '.env.template', '.env.dist'];
88
+
89
+ const LOCKFILES = [
90
+ 'package-lock.json', 'yarn.lock', 'pnpm-lock.yaml', 'Cargo.lock', 'Gemfile.lock',
91
+ 'poetry.lock', 'uv.lock', 'composer.lock', 'go.sum',
92
+ ];
93
+
94
+ function readConfig(root) {
95
+ const cfgPath = path.join(root, '.somi', 'config.json');
96
+ if (!fs.existsSync(cfgPath)) return {};
97
+ try {
98
+ return JSON.parse(fs.readFileSync(cfgPath, 'utf8'));
99
+ } catch {
100
+ return {};
101
+ }
102
+ }
103
+
104
+ // lockfiles_allowed() — env wins (including "0"); then committed config; default deny.
105
+ // The config half is this script's ONE jq use (`jq -r '.lockfiles.allow_edit // empty'
106
+ // == "true"`), preserved exactly rather than approximated with a JS-typed `=== true`
107
+ // check. jq's `//` alternative only substitutes for null/false (NOT other falsy values),
108
+ // and `-r` prints strings raw / other scalars as their JSON text — so a config author
109
+ // who writes `"allow_edit": "true"` (a JSON STRING, not a boolean) gets the exact same
110
+ // jq -r output ("true") as `"allow_edit": true` (the boolean) and is ALSO treated as
111
+ // allowed by bash. A naive `config.lockfiles.allow_edit === true` in JS would silently
112
+ // diverge on that string-vs-boolean case (deny where bash allows) — reproduced the
113
+ // text-comparison semantics instead so both forms match bash byte-for-byte.
114
+ function lockfilesAllowed(root) {
115
+ const env = process.env.SOMI_ALLOW_LOCKFILES;
116
+ if (env !== undefined && env !== '') {
117
+ return env === '1';
118
+ }
119
+ const config = readConfig(root);
120
+ const v = config?.lockfiles?.allow_edit;
121
+ if (v === null || v === undefined || v === false) return false; // jq's `// empty`
122
+ const raw = typeof v === 'string' ? v : JSON.stringify(v);
123
+ return raw === 'true';
124
+ }
125
+
126
+ function changedFiles(root, mode) {
127
+ if (mode === 'staged') {
128
+ const out = execFileSync(
129
+ 'git',
130
+ ['-C', root, 'diff', '--cached', '--name-only', '--diff-filter=ACM'],
131
+ { encoding: 'utf8' },
132
+ );
133
+ return out.split('\n').filter((s) => s !== '');
134
+ }
135
+ const out1 = execFileSync(
136
+ 'git',
137
+ ['-C', root, 'diff', 'HEAD', '--name-only', '--diff-filter=ACM'],
138
+ { encoding: 'utf8' },
139
+ );
140
+ const out2 = execFileSync(
141
+ 'git',
142
+ ['-C', root, 'ls-files', '--others', '--exclude-standard'],
143
+ { encoding: 'utf8' },
144
+ );
145
+ return [...out1.split('\n'), ...out2.split('\n')].filter((s) => s !== '');
146
+ }
147
+
148
+ function changedContent(root, mode) { // additions only
149
+ const args = mode === 'staged'
150
+ ? ['-C', root, 'diff', '--cached', '--no-color', '--unified=0']
151
+ : ['-C', root, 'diff', 'HEAD', '--no-color', '--unified=0'];
152
+ return execFileSync('git', args, { encoding: 'utf8' });
153
+ }
154
+
155
+ function main() {
156
+ requireGit();
157
+
158
+ const argv = process.argv.slice(2);
159
+ const arg = argv[0];
160
+ let mode = 'staged';
161
+ if (arg === '--all') mode = 'all';
162
+ else if (arg === '--staged' || arg === undefined || arg === '') mode = 'staged';
163
+ else die(`unknown argument: ${arg}`);
164
+
165
+ const root = projectRoot();
166
+ try {
167
+ execFileSync('git', ['-C', root, 'rev-parse', '--git-dir'], { stdio: 'ignore' });
168
+ } catch {
169
+ die(`not a git repository: ${root}`);
170
+ }
171
+
172
+ let findings = 0;
173
+ function report(msg) {
174
+ process.stderr.write(`${PROG}: ${msg}\n`);
175
+ findings += 1;
176
+ }
177
+
178
+ // Computed once and reused below (bash re-invokes `changed_files()` — a fresh `git`
179
+ // process per call — inside its per-lockfile manifest check too; nothing about the
180
+ // repo's staged/working state changes mid-run, so caching here is behavior-identical,
181
+ // just fewer subprocess spawns).
182
+ const files = changedFiles(root, mode);
183
+ const allowLockfiles = lockfilesAllowed(root);
184
+
185
+ for (const f of files) {
186
+ const base = path.basename(f);
187
+
188
+ if (!EXAMPLE_BASENAMES.includes(base)) {
189
+ if (SECRET_PATTERNS.some((p) => p.test(base))) {
190
+ report(`secret-bearing file in the change set: ${f} (commit only .env.example-style templates)`);
191
+ }
192
+ }
193
+
194
+ if (!allowLockfiles && LOCKFILES.includes(base)) {
195
+ // Hand-edit heuristic: a lockfile changing without its manifest alongside.
196
+ const dir = path.dirname(f);
197
+ const prefix = dir === '.' ? '' : `${dir}/`;
198
+ // NOTE: `prefix` is interpolated into the RegExp source unescaped, exactly like
199
+ // bash's `grep -qE "^${prefix}(package\.json|...)$"` interpolates it into the ERE
200
+ // unescaped. A directory name containing regex metacharacters (e.g. a real dir
201
+ // named "a.b" or "a+b") would be mis-treated identically by both implementations
202
+ // — a shared, pre-existing quirk in the bash original, preserved here for parity
203
+ // rather than silently fixed.
204
+ const manifestPattern = new RegExp(`^${prefix}(package\\.json|Cargo\\.toml|Gemfile|pyproject\\.toml|composer\\.json|go\\.mod)$`);
205
+ if (!files.some((cf) => manifestPattern.test(cf))) {
206
+ report(`lockfile changed without its manifest: ${f} (regenerate via the package manager, or set lockfiles.allow_edit in .somi/config.json)`);
207
+ }
208
+ }
209
+
210
+ if (base.endsWith('.bak') || base.endsWith('.orig') || base.startsWith('scratch_')) {
211
+ report(`scratch/backup file in the change set: ${f}`);
212
+ }
213
+ }
214
+
215
+ // 3 — added TODO(claude)/FIXME(claude) markers. grep splits lines on \n ONLY and its
216
+ // `.` matches every byte except \n — JS differs on both counts: `m`-flag `^` also
217
+ // anchors after \r/U+2028/U+2029, and `.` refuses to match those same terminators, so
218
+ // a marker preceded by a Unicode line separator on the same git diff line would be
219
+ // silently missed (under-matching — the wrong direction for a guard). Split on \n and
220
+ // use [^\n] to reproduce grep's byte semantics exactly.
221
+ const content = changedContent(root, mode);
222
+ const todoRe = /^\+[^\n]*(TODO\(claude\)|TODO\(agent\)|FIXME\(claude\))/;
223
+ if (content.split('\n').some((line) => todoRe.test(line))) {
224
+ report('TODO(claude)/FIXME(claude) markers added — resolve them or convert to owned follow-ups before committing');
225
+ }
226
+
227
+ if (findings > 0) {
228
+ process.stderr.write(`${PROG}: ${findings} finding(s) — see above.\n`);
229
+ process.exitCode = 1;
230
+ return;
231
+ }
232
+ console.log(`${PROG}: clean.`);
233
+ }
234
+
235
+ try {
236
+ main();
237
+ } catch (e) {
238
+ if (e instanceof ExitSignal) {
239
+ process.exitCode = e.code;
240
+ } else {
241
+ throw e;
242
+ }
243
+ }
@@ -0,0 +1,307 @@
1
+ // somi-findings.mjs — the findings ledger: identity and lifecycle for review findings.
2
+ //
3
+ // Node port of scripts/somi-findings.sh (node-runtime-port, phase 1, iteration 1.2).
4
+ // Zero-dependency: stdlib only (node:fs, node:path). No jq, no bash. Behavior-preserving
5
+ // — exit codes and stdout JSON shapes are frozen and reproduced exactly; see the bash
6
+ // original's header comment for the full rationale (finding identity/lifecycle, the
7
+ // consecutive-vs-cross-run recurrence distinction, why line numbers are excluded from
8
+ // the locus).
9
+ //
10
+ // Ledger: .somi/reviews/<slug>/findings.json under the project root — committed with
11
+ // the other review artifacts (it is the machine view; the markdown review file stays
12
+ // the human view).
13
+ //
14
+ // Subcommands:
15
+ // record --slug S [--review FILE] [--run ID] [--pass N]
16
+ // stdin: JSON array [{file, symbol, title, severity, confidence}, …]
17
+ // Upserts each finding: new locus → new F-<n>; known OPEN locus → appends a
18
+ // sighting. Prints one JSON line per finding with {id, state, recurring_consecutive,
19
+ // recurring_cross_run}. Exit 5 if ANY finding was recurring_consecutive (checked
20
+ // after processing ALL findings) — the caller decides what to do with it.
21
+ // resolve --slug S --id F-3 --status fixed|accepted|wontfix [--by REVIEW]
22
+ // reopen --slug S --id F-3 [--by REVIEW]
23
+ // open --slug S → JSON array of open findings
24
+ // get --slug S --id F-3 → one finding
25
+ //
26
+ // Locus matching: same file + same symbol (case-insensitive) + same normalized title
27
+ // (lowercased, non-alphanumerics collapsed, first 8 words). Line numbers are
28
+ // deliberately NOT part of the locus — lines drift between passes.
29
+ //
30
+ // Exit codes: 0 ok · 5 consecutive recurrence detected (record only) · 64 error.
31
+ // Tested by tests/scripts/run.sh (wired into scripts/validate.sh / CI).
32
+
33
+ import fs from 'node:fs';
34
+ import path from 'node:path';
35
+
36
+ const PROG = 'somi-findings';
37
+
38
+ // Thrown to unwind to the top-level handler, which sets process.exitCode and lets Node
39
+ // exit naturally — avoids process.exit()'s risk of truncating buffered stdout/stderr
40
+ // writes on a pipe. Same idiom as somi-loop.mjs (1.1, reviewer-blessed).
41
+ class ExitSignal extends Error {
42
+ constructor(code) {
43
+ super(`exit ${code}`);
44
+ this.code = code;
45
+ }
46
+ }
47
+
48
+ function die(msg) {
49
+ process.stderr.write(`${PROG}: ${msg}\n`);
50
+ throw new ExitSignal(64);
51
+ }
52
+
53
+ function projectRoot() {
54
+ let b = process.env.CLAUDE_PROJECT_DIR || process.cwd();
55
+ if (b.includes('${')) b = process.cwd();
56
+ return b;
57
+ }
58
+
59
+ function nowDateUtc() {
60
+ // `date -u +%Y-%m-%d` — bare date, no time component (findings' seen[].date).
61
+ return new Date().toISOString().slice(0, 10);
62
+ }
63
+
64
+ // Mirrors jq's `//` alternative operator at the JSON-value level: substitutes the
65
+ // fallback only when the left side is `null`/missing or `false` — NOT for other
66
+ // falsy values like `""` or `0`, which jq treats as present. Used wherever the bash
67
+ // script keeps a raw JSON value (locus/severity/confidence on a newly created finding).
68
+ function orElse(v, fallback) {
69
+ return v === null || v === undefined || v === false ? fallback : v;
70
+ }
71
+
72
+ // Mirrors `jq -r '<expr> // empty'` captured into a bash variable: same null/false
73
+ // substitution as orElse, then stringified (bash captures everything as text) — used
74
+ // wherever the bash script tests `[[ -n "$var" ]]` or concatenates into the locus key.
75
+ function rawStr(v) {
76
+ const x = orElse(v, '');
77
+ return x === '' ? '' : String(x);
78
+ }
79
+
80
+ // normalize_title() — bash pipeline: `tr '[:upper:]' '[:lower:]'` (byte-wise, ASCII-only —
81
+ // it only maps the 26 ASCII uppercase bytes; any multi-byte UTF-8 sequence passes through
82
+ // untouched) -> `tr -cs 'a-z0-9' ' '` (every maximal run of non-alphanumerics — including a
83
+ // leading or trailing run — collapses to ONE space; this is what then eats those untouched
84
+ // UTF-8 bytes) -> awk takes fields 1-8 (awk's default field-splitting ignores leading/
85
+ // trailing whitespace and splits on whitespace runs). By the time the tr step is done,
86
+ // the only characters left in the string are lowercase alphanumerics and single-space
87
+ // separators (with at most one leading and one trailing space) — so the awk step's only
88
+ // remaining job is to drop that leading/trailing space and truncate to 8 fields, which
89
+ // is exactly what trim + split + slice does below — PROVIDED the lowercasing step is also
90
+ // byte-wise ASCII-only. JS's `String.prototype.toLowerCase()` is Unicode-aware (e.g. U+0130
91
+ // İ -> "i" + combining dot above), which can *introduce* a fresh ASCII letter that bash's
92
+ // byte-wise `tr` would never produce (bash leaves İ's UTF-8 bytes alone; the following
93
+ // `tr -cs 'a-z0-9' ' '` step then discards all of them as non-alphanumeric). So the
94
+ // lowercasing below only maps `A`-`Z`, mirroring `tr '[:upper:]' '[:lower:]'` exactly.
95
+ // Verified against all six of Phase 0.6's normalize_title edge-case goldens (empty,
96
+ // single-word, >8-word, leading/trailing whitespace, multi-space, punctuation) plus
97
+ // adversarial Unicode probes (café, İstanbul) — see diary for the case-by-case trace.
98
+ function normalizeTitle(title) {
99
+ const lowered = title.replace(/[A-Z]/g, (c) => c.toLowerCase());
100
+ const squeezed = lowered.replace(/[^a-z0-9]+/g, ' ').trim();
101
+ if (squeezed === '') return '';
102
+ return squeezed.split(/\s+/).slice(0, 8).join(' ');
103
+ }
104
+
105
+ function ensureLedger(ledgerDir, ledgerPath) {
106
+ fs.mkdirSync(ledgerDir, { recursive: true });
107
+ if (!fs.existsSync(ledgerPath)) {
108
+ // Byte-for-byte the bash seed: `printf '{"next_id": 1, "findings": []}\n' > "$LEDGER"` —
109
+ // a literal, NOT jq output (note the space after each colon but no other jq-pretty
110
+ // formatting). Immediately superseded by the jq-pretty form on the first record/resolve/
111
+ // reopen that touches this ledger; only matters at rest if `open`/`get` is called first.
112
+ fs.writeFileSync(ledgerPath, '{"next_id": 1, "findings": []}\n');
113
+ }
114
+ }
115
+
116
+ function loadLedger(ledgerPath) {
117
+ return JSON.parse(fs.readFileSync(ledgerPath, 'utf8'));
118
+ }
119
+
120
+ function saveLedger(ledgerPath, ledger) {
121
+ // Mirror bash's `tmp="$(mktemp)"; jq ... "$LEDGER" > "$tmp" && mv "$tmp" "$LEDGER"`:
122
+ // pretty 2-space + trailing newline (jq's default pretty-print, verified byte-identical
123
+ // against JSON.stringify(ledger, null, 2) + '\n' — see diary), written to a temp file in
124
+ // the SAME directory as the target and renamed into place so the write is atomic and the
125
+ // rename never crosses a filesystem boundary.
126
+ const tmpPath = `${ledgerPath}.tmp`;
127
+ fs.writeFileSync(tmpPath, JSON.stringify(ledger, null, 2) + '\n');
128
+ fs.renameSync(tmpPath, ledgerPath);
129
+ }
130
+
131
+ function main() {
132
+ const argv = process.argv.slice(2);
133
+ const CMD = argv[0] || '';
134
+ let rest = argv.slice(1);
135
+
136
+ let SLUG = '';
137
+ let REVIEW = '';
138
+ let RUN = '';
139
+ let PASS = 0;
140
+ let ID = '';
141
+ let STATUS = '';
142
+ let BY = '';
143
+
144
+ while (rest.length > 0) {
145
+ const a = rest[0];
146
+ switch (a) {
147
+ case '--slug': SLUG = rest[1]; rest = rest.slice(2); break;
148
+ case '--review': REVIEW = rest[1]; rest = rest.slice(2); break;
149
+ case '--run': RUN = rest[1]; rest = rest.slice(2); break;
150
+ case '--pass': PASS = Number(rest[1]); rest = rest.slice(2); break;
151
+ case '--id': ID = rest[1]; rest = rest.slice(2); break;
152
+ case '--status': STATUS = rest[1]; rest = rest.slice(2); break;
153
+ case '--by': BY = rest[1]; rest = rest.slice(2); break;
154
+ default: die(`unknown argument: ${a}`);
155
+ }
156
+ }
157
+
158
+ if (!CMD) die('usage: somi-findings.mjs <record|resolve|reopen|open|get> --slug <slug> …');
159
+ if (!SLUG) die('--slug is required');
160
+
161
+ const root = projectRoot();
162
+ const LEDGER_DIR = path.join(root, '.somi', 'reviews', SLUG);
163
+ const LEDGER = path.join(LEDGER_DIR, 'findings.json');
164
+
165
+ switch (CMD) {
166
+ case 'record': {
167
+ ensureLedger(LEDGER_DIR, LEDGER);
168
+
169
+ const stdinText = fs.readFileSync(0, 'utf8');
170
+ let input;
171
+ try {
172
+ input = JSON.parse(stdinText);
173
+ } catch {
174
+ die('stdin must be a JSON array of findings');
175
+ }
176
+ if (!Array.isArray(input)) die('stdin must be a JSON array of findings');
177
+
178
+ const ledger = loadLedger(LEDGER);
179
+ const now = nowDateUtc();
180
+ let breaker = false;
181
+
182
+ for (let i = 0; i < input.length; i++) {
183
+ const f = input[i] ?? {};
184
+ const file = rawStr(f.file);
185
+ // ASCII-only lowercase — same reasoning as normalizeTitle above: bash uses byte-wise
186
+ // `tr '[:upper:]' '[:lower:]'` here too, so Unicode-aware toLowerCase would diverge.
187
+ const symbol = rawStr(f.symbol).replace(/[A-Z]/g, (c) => c.toLowerCase());
188
+ const title = rawStr(f.title);
189
+ if (!file || !title) die(`finding ${i} needs at least {file, title}`);
190
+ const key = `${file}|${symbol}|${normalizeTitle(title)}`;
191
+
192
+ // Known open locus: recurrence classification BEFORE the sighting is appended.
193
+ const existing = ledger.findings.find((x) => x.key === key && x.status === 'open');
194
+
195
+ if (existing) {
196
+ const recurringConsecutive = existing.seen.some((s) => s.run === RUN && s.pass === PASS - 1);
197
+ const recurringCross = existing.seen.some((s) => s.run !== RUN);
198
+ existing.seen.push({ review: REVIEW, run: RUN, pass: PASS, date: now });
199
+ saveLedger(LEDGER, ledger);
200
+ if (recurringConsecutive) breaker = true;
201
+ console.log(JSON.stringify({
202
+ id: existing.id,
203
+ state: 'known',
204
+ recurring_consecutive: recurringConsecutive,
205
+ recurring_cross_run: recurringCross,
206
+ }));
207
+ } else {
208
+ const newId = `F-${ledger.next_id}`;
209
+ ledger.next_id += 1;
210
+ ledger.findings.push({
211
+ id: newId,
212
+ key,
213
+ locus: { file: f.file, symbol: orElse(f.symbol, '') },
214
+ title: f.title,
215
+ severity: orElse(f.severity, 'Minor'),
216
+ confidence: orElse(f.confidence, 'Medium'),
217
+ status: 'open',
218
+ introduced_by: REVIEW,
219
+ resolved_by: null,
220
+ seen: [{ review: REVIEW, run: RUN, pass: PASS, date: now }],
221
+ });
222
+ saveLedger(LEDGER, ledger);
223
+ console.log(JSON.stringify({
224
+ id: newId,
225
+ state: 'new',
226
+ recurring_consecutive: false,
227
+ recurring_cross_run: false,
228
+ }));
229
+ }
230
+ }
231
+
232
+ if (breaker) process.exitCode = 5;
233
+ break;
234
+ }
235
+
236
+ case 'resolve': {
237
+ ensureLedger(LEDGER_DIR, LEDGER);
238
+ if (!ID || !STATUS) die('resolve requires --id and --status');
239
+ if (!['fixed', 'accepted', 'wontfix'].includes(STATUS)) {
240
+ die('--status must be fixed|accepted|wontfix');
241
+ }
242
+ const ledger = loadLedger(LEDGER);
243
+ const found = ledger.findings.find((x) => x.id === ID);
244
+ if (found) {
245
+ found.status = STATUS;
246
+ found.resolved_by = BY;
247
+ saveLedger(LEDGER, ledger);
248
+ console.log(JSON.stringify({ id: found.id, status: found.status, resolved_by: found.resolved_by }));
249
+ }
250
+ break;
251
+ }
252
+
253
+ case 'reopen': {
254
+ ensureLedger(LEDGER_DIR, LEDGER);
255
+ if (!ID) die('reopen requires --id');
256
+ const ledger = loadLedger(LEDGER);
257
+ const found = ledger.findings.find((x) => x.id === ID);
258
+ if (found) {
259
+ found.status = 'open';
260
+ found.resolved_by = null;
261
+ found.reopened_by = BY;
262
+ saveLedger(LEDGER, ledger);
263
+ console.log(JSON.stringify({ id: found.id, status: found.status }));
264
+ }
265
+ break;
266
+ }
267
+
268
+ case 'open': {
269
+ ensureLedger(LEDGER_DIR, LEDGER);
270
+ const ledger = loadLedger(LEDGER);
271
+ const openFindings = ledger.findings
272
+ .filter((x) => x.status === 'open')
273
+ .map((x) => ({
274
+ id: x.id,
275
+ locus: x.locus,
276
+ title: x.title,
277
+ severity: x.severity,
278
+ confidence: x.confidence,
279
+ introduced_by: x.introduced_by,
280
+ }));
281
+ console.log(JSON.stringify(openFindings, null, 2));
282
+ break;
283
+ }
284
+
285
+ case 'get': {
286
+ ensureLedger(LEDGER_DIR, LEDGER);
287
+ if (!ID) die('get requires --id');
288
+ const ledger = loadLedger(LEDGER);
289
+ const found = ledger.findings.find((x) => x.id === ID);
290
+ if (found) console.log(JSON.stringify(found, null, 2));
291
+ break;
292
+ }
293
+
294
+ default:
295
+ die(`unknown subcommand: ${CMD}`);
296
+ }
297
+ }
298
+
299
+ try {
300
+ main();
301
+ } catch (e) {
302
+ if (e instanceof ExitSignal) {
303
+ process.exitCode = e.code;
304
+ } else {
305
+ throw e;
306
+ }
307
+ }