@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,432 @@
1
+ #!/usr/bin/env node
2
+ // hooks/user-prompt-submit/inject-workflow-context.mjs — UserPromptSubmit hook — inject SOMI
3
+ // context on relevant turns.
4
+ //
5
+ // Node port of hooks/user-prompt-submit/inject-workflow-context.sh (node-runtime-port, phase 2,
6
+ // iteration 2.8 — the heaviest hook in the corpus: 12 bash arrays, process substitution, a
7
+ // signature-hash gate). Imports the shared read/context/projectRoot helpers from
8
+ // ../lib/common.mjs (2.1, reviewer-blessed) rather than reimplementing them.
9
+ //
10
+ // Two responsibilities (unchanged from bash):
11
+ // 1. Remind the agent of the priority stack and active work-item state.
12
+ // 2. Surface end-of-turn loose ends (TODO(claude) markers, scratch files) on the NEXT user
13
+ // turn — this replaces the old Stop hook, which used an additionalContext channel that Stop
14
+ // events don't actually have.
15
+ //
16
+ // To avoid double-loading content that's already always-on, the reminder block only fires on the
17
+ // first turn of a session OR when work-item state has changed since the last turn (the signature
18
+ // gate below). The loose-end nudges fire whenever there is something to nudge about, completely
19
+ // independent of the reminder gate (see main() — this independence is pinned by the fixture case
20
+ // "nudge-fires-independent-of-suppressed-reminder").
21
+ //
22
+ // === THE SIGNATURE-HASH GATE: what bash actually feeds sha256sum ================================
23
+ //
24
+ // bash's compute_signature() runs THREE independent `find ... -printf '%T@ %p\n' | sort |
25
+ // sha256sum | cut -d' ' -f1` pipelines (plans, reviews, rd) and joins the three resulting hex
26
+ // digests with `printf '%s:%s:%s'`. Two things here are easy to get subtly wrong, both verified
27
+ // directly against the unmodified bash hook (via `sha256sum`, `find -printf`, and staged
28
+ // throwaway directories) rather than assumed:
29
+ //
30
+ // 1. ABSENT DIRECTORY vs. EMPTY DIRECTORY are NOT the same segment value. If `.somi/plans`
31
+ // doesn't exist at all, bash's `if [[ -d ... ]]` guard is false and `plans_state` stays the
32
+ // shell's default empty string (`""`) — NOT a hash of anything. If `.somi/plans` exists but
33
+ // contains zero matching `progress.md` files, `find` produces zero lines, `sort` passes
34
+ // zero lines through, and `sha256sum` hashes the EMPTY STRING, producing the well-known
35
+ // constant `e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b85`. Verified
36
+ // directly: a project dir with no `.somi/*` at all writes state-file content `"::\n"` (two
37
+ // bare colons, zero-length segments); a project dir with an empty `.somi/plans/` writes
38
+ // `"e3b0c44...b7852b85::\n"`. Reproduced below via `hashSegment()`'s `isDirectory` guard
39
+ // returning `''` before ever calling `findMatchingPaths`, keeping the two cases distinct.
40
+ // 2. THE `%T@` FRACTIONAL-SECOND FORMAT is 10 digits, not 9, and the 10th digit is always `0`
41
+ // at any real filesystem's resolution. Verified empirically (not from documentation, which
42
+ // doesn't pin this precisely) by setting a file's mtime to an exact, known nanosecond value
43
+ // via `os.utime(..., ns=...)` and reading back `find -printf '%T@\n'` against BOTH the
44
+ // genuine GNU findutils binary at `/usr/bin/find` (bypassing this sandbox's own `find`→`bfs`
45
+ // shell-function shim, which is layered on top of the real binary and reformats output
46
+ // differently) and the shimmed one: mtime_ns=1712345678987654321 (987654321 ns past the
47
+ // second) printed as `1712345678.9876543210` — the 9-digit nanosecond remainder with a
48
+ // literal `0` appended, not a 9-digit value. Reproduced exactly below via
49
+ // `mtimeField()`: BigInt seconds/nanoseconds from `fs.statSync(p, {bigint:true}).mtimeNs`,
50
+ // formatted as `${seconds}.${nanos.toString().padStart(9,'0')}0`.
51
+ //
52
+ // IMPORTANT SCOPE LIMIT on point 2: this reproduces GNU findutils' specific `%T@` format
53
+ // (confirmed against the real `/usr/bin/find` binary on this host). It is NOT a claim that
54
+ // every `find` implementation formats `%T@` identically — BSD find (stock macOS) doesn't
55
+ // support `-printf` at all (a GNU extension), so bash's `compute_signature()` already silently
56
+ // produces empty segments there today (`-printf` errors, `2>/dev/null` swallows it, `find`
57
+ // exits non-zero, the pipeline's stdout is empty) — a pre-existing bash-only portability gap,
58
+ // not introduced by this port. More importantly: **the gate is self-referential.** The state
59
+ // file at `.claude/somi-state/last-context-signature` is only ever compared against a value
60
+ // THIS SAME hook previously wrote — never against an external oracle, never read by any other
61
+ // tool. Byte-identical hex-digest parity between a bash-computed signature and a Node-computed
62
+ // signature for the identical on-disk state is therefore neither achievable in general (it
63
+ // depends on which `find` binary happens to resolve first on PATH, which varies by host and
64
+ // doesn't exist at all on Windows) nor required for correctness. What IS required, and IS
65
+ // preserved exactly, is the gate's BEHAVIORAL contract: stable across repeated invocations when
66
+ // nothing changed, and different whenever the matched file set or any matched file's mtime
67
+ // changes — both verified by direct probe (see the diary). One bounded, expected consequence:
68
+ // the FIRST Node-hook invocation on a host whose `.claude/somi-state/last-context-signature`
69
+ // was last written by the bash hook will see a "changed" signature (different hash algorithms
70
+ // for the same state) and re-emit the reminder ONE extra time at cutover — benign, not a bug.
71
+ //
72
+ // === THE STATUS-DETECTION DECISION (explicit, named, per the phase file's requirement) ==========
73
+ //
74
+ // 0.5's fixture pinned a real gap: bash's in-progress detection recognizes a bare status line
75
+ // matching `^[[:space:]]*<?in-progress>?[[:space:]]*$` (optional ANGLE brackets, not backticks)
76
+ // or a line matching `status:[[:space:]]*`?in-progress`?` (requires a literal "status:" prefix).
77
+ // Neither pattern matches this project's OWN `progress.md` convention: a bare, BACKTICK-wrapped
78
+ // status line with no "Status:" prefix — confirmed not just by the fixture's synthetic example
79
+ // but by this work item's own `.somi/plans/node-runtime-port/progress.md` line 10 (`` `in-progress` ``)
80
+ // and by `templates/PROGRESS.md.tmpl` line 16 (`<One of: ... | in-progress | ...>` under a bare
81
+ // `## Status` heading, zero "Status:" prefix) — the CANONICAL template every `/plan`-generated
82
+ // work item's `progress.md` follows. So the narrow bash regexes miss the mainline case, not an
83
+ // edge case: every SoMi work item created via the documented template is invisible to this
84
+ // hook's plan-hint scan today.
85
+ //
86
+ // Chosen: **(b) widen** — narrowly. `PLAN_STATUS_BARE_RE` below adds backtick as a second
87
+ // optional wrap character alongside the existing angle bracket, preserving the ORIGINAL pattern's
88
+ // own already-independent (non-paired) optionality — the bash original already accepts a
89
+ // mismatched `<in-progress` (leading `<`, no trailing `>`) since each is independently `?`; this
90
+ // widening adds backtick to the same independently-optional set, not a stricter, newly-paired
91
+ // rule the original never had. The full-line anchor (`^...$`, tested per PHYSICAL LINE, matching
92
+ // grep's line-oriented semantics, not a whole-file substring search) is preserved exactly.
93
+ //
94
+ // Reasoning, weighed explicitly against reproducing the narrow detection for parity (mirroring
95
+ // 2.7's prune-list decision structure):
96
+ //
97
+ // 1. Self-inconsistency, not a deliberate choice being preserved. SoMi's OWN planning tooling
98
+ // generates `progress.md` files in the exact format its OWN hook fails to recognize. This
99
+ // is not a hypothetical third-party format difference — it is SoMi authoring content for
100
+ // itself that its own runtime cannot read.
101
+ // 2. Bounded, precisely-scoped false-positive risk — verified empirically, not assumed. Unlike
102
+ // 2.7's prune fix (which could only ever go quiet, never surface something new — fail-quiet
103
+ // in the safe direction), THIS widening is in the OPPOSITE risk direction: it can make the
104
+ // hook say MORE than it used to, and a badly-shaped widening could false-positive on
105
+ // narrative text. Checked directly: `grep -nE '^\s*[<`]?in-progress[>`]?\s*$'` against this
106
+ // work item's own ~1100-line `progress.md` — which repeatedly contains the SUBSTRING
107
+ // "in-progress" inside narrative sentences (e.g. "Iteration left `in-progress` (pass 1);
108
+ // review decides `done`." appears a dozen+ times in the Recent-activity/diary prose) —
109
+ // matches EXACTLY ONE line: the real `## Status` field's own bare `` `in-progress` `` line.
110
+ // Every narrative occurrence is disqualified by the full-line anchor (surrounding text on
111
+ // the same physical line breaks the `^...$` match). This is the concrete evidence that a
112
+ // substring-anywhere widening would be dangerous (it would false-positive on nearly every
113
+ // real `progress.md` once it accumulates iteration history) while the full-line-anchored
114
+ // widening actually chosen is not.
115
+ // 3. Confined blast radius: only `PLAN_STATUS_BARE_RE` changes. The R&D status scan
116
+ // (`researching|drafting|awaiting-verification|ready-for-planning`) already matches this
117
+ // repo's actual R&D README convention (`> Status: `researching``, already carrying the
118
+ // "Status:" prefix the regex requires) — 0.5's review found no gap there, so it is
119
+ // reproduced unchanged. `PLAN_STATUS_PREFIXED_RE` (the "status:"-prefixed in-progress form)
120
+ // is also reproduced unchanged — it already matches its own fixture cases correctly.
121
+ //
122
+ // Consumer-observable consequence, named per D6's precedent: a work item using the bare-backtick
123
+ // `progress.md` convention (this repo's own convention) now surfaces its "Active work item:" hint
124
+ // on turns where it previously stayed silent. This is a real behavior change, not a bug fix to an
125
+ // internal-only mechanism (unlike 2.7's prune fix, which only affected an already-informational,
126
+ // no-decision-consequence context surface) — flagged for the close-out to record in decisions.md
127
+ // (a new D-entry, D6-style) and 4.4's CHANGELOG scope, alongside D6's SessionStart prune change.
128
+ //
129
+ // Fixture implication: `tests/hooks/cases/inject-workflow-context.json`'s
130
+ // `plan-hint-bare-backtick-status-not-detected` case (which pinned the bash gap as current
131
+ // behavior) is renamed to `plan-hint-bare-backtick-status-now-detected` and its expectation
132
+ // FLIPPED (`expect_context_excludes: "Active work item:"` → `expect_context: "Active work item:
133
+ // \`.somi/plans/demo-slug/\`."`) — the one deliberate, named, reviewed case edit this iteration
134
+ // makes. Every other case passes with only the `"script"` field retargeted.
135
+ //
136
+ // === Loose-end nudges: execFileSync argument arrays, explicit maxBuffer ==========================
137
+ // `git diff`/`git status` are invoked via `execFileSync` with argument ARRAYS (never a shell
138
+ // string), avoiding any shell-injection surface entirely (paths interpolated into a shell command
139
+ // string is exactly the class of bug `execFileSync(cmd, [args])` structurally forecloses). Both
140
+ // calls set `maxBuffer` explicitly (10 MB — the convention 2.5's review established for every
141
+ // output-capturing subprocess call in this port series), rather than relying on Node's low
142
+ // 1 MB default. A failed/absent `git` (ENOENT) or a non-zero exit from either command degrades to
143
+ // "no nudge from that check" — mirrors bash's `2>/dev/null` + `set -o pipefail`-tolerant `if
144
+ // pipeline; then` idiom, where either failure mode collapses to the same "condition false" outcome
145
+ // (a pipeline's non-zero exit inside an `if` condition does not abort under `set -e`).
146
+ //
147
+ // === Windows caveat (same class already flagged in 2.2/2.3/2.5/2.7) ==============================
148
+ // Paths embedded in the signature hash and extracted slugs use `path.join`/`path.basename`
149
+ // (platform-default separator). Purely internal (signature) or free-text-message (slugs) use —
150
+ // not fixed here, consistent with prior ports' documented-not-fixed Windows path-separator gaps.
151
+
152
+ import fs from 'node:fs';
153
+ import path from 'node:path';
154
+ import crypto from 'node:crypto';
155
+ import { execFileSync } from 'node:child_process';
156
+ import { readPayload, projectRoot, contextOutput, runHook } from '../lib/common.mjs';
157
+
158
+ // bash: `grep -qiE '^[[:space:]]*<?in-progress>?[[:space:]]*$'` — WIDENED per THE
159
+ // STATUS-DETECTION DECISION above: backtick added as a second optional wrap character alongside
160
+ // the original's angle bracket, independently optional on each side exactly as the original was.
161
+ const PLAN_STATUS_BARE_RE = /^\s*[<`]?in-progress[>`]?\s*$/i;
162
+ // bash: `grep -qiE 'status:[[:space:]]*`?in-progress`?'` — reproduced unchanged (already matches
163
+ // its fixture cases; no gap found here).
164
+ const PLAN_STATUS_PREFIXED_RE = /status:\s*`?in-progress`?/i;
165
+
166
+ // bash: `grep -qiE 'status:[[:space:]]*`?(researching|drafting|awaiting-verification)`?'` /
167
+ // `grep -qiE 'status:[[:space:]]*`?ready-for-planning`?'` — reproduced unchanged; 0.5's review
168
+ // found the real R&D README.md convention already carries the required "Status:" prefix.
169
+ const RD_STATUS_ACTIVE_RE = /status:\s*`?(researching|drafting|awaiting-verification)`?/i;
170
+ const RD_STATUS_READY_RE = /status:\s*`?ready-for-planning`?/i;
171
+
172
+ // bash: `grep -E '^\+.*(TODO\(claude\)|TODO\(agent\)|FIXME\(claude\))'` against `git diff` output.
173
+ const TODO_MARKER_RE = /^\+.*(TODO\(claude\)|TODO\(agent\)|FIXME\(claude\))/;
174
+ // bash: `grep -E '^\?\? .*(\.bak|\.orig|scratch_)'` against `git status --porcelain` output.
175
+ const SCRATCH_FILE_RE = /^\?\? .*(\.bak|\.orig|scratch_)/;
176
+
177
+ // 2.5's review-established convention for every output-capturing subprocess call in this port
178
+ // series (Node's spawnSync/execFileSync default maxBuffer is 1 MB — too small for a real `git
179
+ // diff`/`git status --porcelain` on a large working tree).
180
+ const GIT_MAX_BUFFER = 10 * 1024 * 1024;
181
+
182
+ const REMINDER_BODY =
183
+ 'somi is active. Reminders:\n' +
184
+ '- Follow rules/CLAUDE.md priorities: security > correctness > maintainability > performance > convenience.\n' +
185
+ '- Plan before coding non-trivial work. Code from the plan, not around it.\n' +
186
+ '- Surface tradeoffs and shortcuts in plain text; never silently compromise.\n' +
187
+ '- Hooks may deny dangerous bash, secret writes, protected paths, and unsanctioned dep installs — do not work around them.';
188
+
189
+ function isDirectory(p) {
190
+ try {
191
+ return fs.statSync(p).isDirectory();
192
+ } catch {
193
+ return false;
194
+ }
195
+ }
196
+
197
+ // Every filesystem entry within `dir` (bounded to `maxDepth` levels below it, `dir` itself being
198
+ // depth 0) whose basename satisfies `isMatch`. Mirrors bash's `find "$dir" -maxdepth N -name
199
+ // 'X'`: EVERY visited node (the starting dir plus every descendant up to maxDepth) is tested by
200
+ // basename — there is no `-type f` in the bash original, so a directory can match too — and only
201
+ // directories are descended into further. Shared by the signature scan (mtime hashing) and the
202
+ // plan-hint/rd-hint scans (content grep) below, exactly as bash independently runs the SAME
203
+ // `find "$dir" -maxdepth N -name 'X'` shape twice for two different purposes (once with
204
+ // `-printf`, once without).
205
+ function findMatchingPaths(dir, maxDepth, isMatch) {
206
+ const results = [];
207
+ function visit(p, depth) {
208
+ if (isMatch(path.basename(p))) results.push(p);
209
+ if (depth >= maxDepth) return;
210
+ let entries;
211
+ try {
212
+ entries = fs.readdirSync(p, { withFileTypes: true });
213
+ } catch {
214
+ return; // matches find's `2>/dev/null` — an unreadable subtree is silently skipped.
215
+ }
216
+ for (const entry of entries) {
217
+ const full = path.join(p, entry.name);
218
+ if (entry.isDirectory()) {
219
+ visit(full, depth + 1);
220
+ } else if (isMatch(entry.name)) {
221
+ results.push(full);
222
+ }
223
+ }
224
+ }
225
+ visit(dir, 0);
226
+ return results;
227
+ }
228
+
229
+ // bash: `%T@` — seconds since epoch, DOT, then a 10-digit fractional part (9-digit nanosecond
230
+ // remainder plus a literal trailing `0`; see the header's empirical finding). `fs.statSync(p,
231
+ // {bigint:true}).mtimeNs` gives nanoseconds since epoch as a BigInt, letting seconds/nanoseconds
232
+ // be split exactly rather than through a lossy float.
233
+ function mtimeField(p) {
234
+ const st = fs.statSync(p, { bigint: true });
235
+ const seconds = st.mtimeNs / 1000000000n;
236
+ const nanos = st.mtimeNs % 1000000000n;
237
+ return `${seconds}.${nanos.toString().padStart(9, '0')}0`;
238
+ }
239
+
240
+ // One signature segment: `''` if `dir` doesn't exist (matches bash leaving the variable at its
241
+ // default empty string), else the sha256 hex digest of the sorted "`mtimeField` `path`" lines —
242
+ // including the digest of the EMPTY STRING when the directory exists but nothing matches (see the
243
+ // header's "absent vs. empty" finding; these are deliberately different values).
244
+ function hashSegment(dir, maxDepth, isMatch) {
245
+ if (!isDirectory(dir)) return '';
246
+ const lines = findMatchingPaths(dir, maxDepth, isMatch).map((p) => `${mtimeField(p)} ${p}`);
247
+ lines.sort(); // matches `sort`'s lexicographic line order (ASCII paths only in practice, same
248
+ // caveat class as this port series' other ASCII-only nocase/sort notes).
249
+ const input = lines.length > 0 ? `${lines.join('\n')}\n` : '';
250
+ return crypto.createHash('sha256').update(input, 'utf8').digest('hex');
251
+ }
252
+
253
+ // bash: `printf '%s:%s:%s' "$plans_state" "$reviews_state" "$rd_state"`.
254
+ function computeSignature(root) {
255
+ const plansState = hashSegment(path.join(root, '.somi', 'plans'), 2, (n) => n === 'progress.md');
256
+ const reviewsState = hashSegment(path.join(root, '.somi', 'reviews'), 3, (n) => n.endsWith('.md'));
257
+ const rdState = hashSegment(path.join(root, '.somi', 'rd'), 2, (n) => n === 'README.md');
258
+ return `${plansState}:${reviewsState}:${rdState}`;
259
+ }
260
+
261
+ function fileHasInProgressStatus(filePath) {
262
+ let content;
263
+ try {
264
+ content = fs.readFileSync(filePath, 'utf8');
265
+ } catch {
266
+ return false; // matches grep's `2>/dev/null` on an unreadable path (or a directory, EISDIR).
267
+ }
268
+ return content
269
+ .split(/\r?\n/)
270
+ .some((line) => PLAN_STATUS_BARE_RE.test(line) || PLAN_STATUS_PREFIXED_RE.test(line));
271
+ }
272
+
273
+ // 'active' | 'ready' | null — bash's `if grep -qiE active-pattern ...; then ...; elif grep -qiE
274
+ // ready-pattern ...; then ...; fi`: active takes precedence when a file (implausibly) matches
275
+ // both.
276
+ function readmeStatus(filePath) {
277
+ let content;
278
+ try {
279
+ content = fs.readFileSync(filePath, 'utf8');
280
+ } catch {
281
+ return null;
282
+ }
283
+ const lines = content.split(/\r?\n/);
284
+ if (lines.some((l) => RD_STATUS_ACTIVE_RE.test(l))) return 'active';
285
+ if (lines.some((l) => RD_STATUS_READY_RE.test(l))) return 'ready';
286
+ return null;
287
+ }
288
+
289
+ function computePlanHint(root) {
290
+ const plansDir = path.join(root, '.somi', 'plans');
291
+ if (!isDirectory(plansDir)) return '';
292
+ const inProgress = [];
293
+ for (const progressFile of findMatchingPaths(plansDir, 2, (n) => n === 'progress.md')) {
294
+ if (fileHasInProgressStatus(progressFile)) {
295
+ inProgress.push(path.basename(path.dirname(progressFile)));
296
+ }
297
+ }
298
+ if (inProgress.length === 1) {
299
+ return `\n- Active work item: \`.somi/plans/${inProgress[0]}/\`. Follow its \`spec.md\` and active iteration in \`phases/\`; update \`progress.md\` / \`diary.md\` as work proceeds.`;
300
+ }
301
+ if (inProgress.length > 1) {
302
+ return `\n- Multiple in-progress work items in \`.somi/plans/\`: ${inProgress.join(',')}. Confirm with the user which one applies before coding.`;
303
+ }
304
+ return '';
305
+ }
306
+
307
+ function computeRdHint(root) {
308
+ const rdDir = path.join(root, '.somi', 'rd');
309
+ if (!isDirectory(rdDir)) return '';
310
+ const rdActive = [];
311
+ const rdReady = [];
312
+ for (const readme of findMatchingPaths(rdDir, 2, (n) => n === 'README.md')) {
313
+ const status = readmeStatus(readme);
314
+ const slug = path.basename(path.dirname(readme));
315
+ if (status === 'active') rdActive.push(slug);
316
+ else if (status === 'ready') rdReady.push(slug);
317
+ }
318
+ if (rdActive.length >= 1) {
319
+ return `\n- Active discovery in \`.somi/rd/\`: ${rdActive.join(',')}. This is requirements-engineering work (\`/discover\`): research the competition, author the R&D doc set, verify crossroads, before handing to \`/plan\`.`;
320
+ }
321
+ if (rdReady.length === 1) {
322
+ return `\n- R&D foundation ready in \`.somi/rd/${rdReady[0]}/\`. \`/plan ${rdReady[0]}\` will consume its SRS/FRD as the requirements source and SDD/TDD as architectural direction.`;
323
+ }
324
+ return '';
325
+ }
326
+
327
+ // bash: `command -v git >/dev/null 2>&1`.
328
+ function isGitAvailable() {
329
+ try {
330
+ execFileSync('git', ['--version'], { stdio: 'ignore' });
331
+ return true;
332
+ } catch {
333
+ return false;
334
+ }
335
+ }
336
+
337
+ // bash: `git -C "$PROJECT_ROOT" diff --no-color --unified=0 HEAD 2>/dev/null | grep -E '...' -q`.
338
+ function hasTodoMarkerInDiff(root) {
339
+ let out;
340
+ try {
341
+ out = execFileSync('git', ['-C', root, 'diff', '--no-color', '--unified=0', 'HEAD'], {
342
+ encoding: 'utf8',
343
+ maxBuffer: GIT_MAX_BUFFER,
344
+ });
345
+ } catch {
346
+ return false; // no HEAD, git error, or non-zero exit — same "no nudge" outcome as bash's
347
+ // pipefail-tolerant `if pipeline; then` when either side of the pipe fails.
348
+ }
349
+ return out.split('\n').some((line) => TODO_MARKER_RE.test(line));
350
+ }
351
+
352
+ // bash: `git -C "$PROJECT_ROOT" status --porcelain 2>/dev/null | grep -E '...' -q`.
353
+ function hasScratchFileInStatus(root) {
354
+ let out;
355
+ try {
356
+ out = execFileSync('git', ['-C', root, 'status', '--porcelain'], {
357
+ encoding: 'utf8',
358
+ maxBuffer: GIT_MAX_BUFFER,
359
+ });
360
+ } catch {
361
+ return false;
362
+ }
363
+ return out.split('\n').some((line) => SCRATCH_FILE_RE.test(line));
364
+ }
365
+
366
+ // bash: `if command -v git ... && [[ -d "$PROJECT_ROOT/.git" ]]; then ...; fi` gates BOTH nudge
367
+ // checks together — computed unconditionally every call, independent of the reminder-emission
368
+ // gate (see main()).
369
+ function computeNudges(root) {
370
+ const nudges = [];
371
+ if (isGitAvailable() && isDirectory(path.join(root, '.git'))) {
372
+ if (hasTodoMarkerInDiff(root)) {
373
+ nudges.push(
374
+ "Detected new TODO(claude)/FIXME(claude) markers in the diff against HEAD. List them explicitly as 'not done' in your next summary."
375
+ );
376
+ }
377
+ if (hasScratchFileInStatus(root)) {
378
+ nudges.push('Detected scratch / .bak files in working tree. Clean them up before declaring done.');
379
+ }
380
+ }
381
+ return nudges;
382
+ }
383
+
384
+ function main() {
385
+ readPayload();
386
+
387
+ const root = projectRoot();
388
+ const stateDir = path.join(root, '.claude', 'somi-state');
389
+ const stateFile = path.join(stateDir, 'last-context-signature');
390
+ fs.mkdirSync(stateDir, { recursive: true });
391
+
392
+ const currentSig = computeSignature(root);
393
+ let lastSig = '';
394
+ if (fs.existsSync(stateFile)) {
395
+ try {
396
+ // bash: `LAST_SIG="$(cat "$STATE_FILE" 2>/dev/null || true)"` — command substitution
397
+ // strips ALL trailing newlines (not general whitespace), so `.replace(/\n+$/, '')` rather
398
+ // than a generic `.trim()`.
399
+ lastSig = fs.readFileSync(stateFile, 'utf8').replace(/\n+$/, '');
400
+ } catch {
401
+ lastSig = '';
402
+ }
403
+ }
404
+ fs.writeFileSync(stateFile, `${currentSig}\n`); // bash: `echo "$CURRENT_SIG" > "$STATE_FILE"`.
405
+
406
+ // bash: `[[ -z "$LAST_SIG" ]] || [[ "$LAST_SIG" != "$CURRENT_SIG" ]]` — reproduced as the exact
407
+ // two-part condition (CURRENT_SIG is never truly empty, it's at minimum "::", but the explicit
408
+ // first-turn branch is preserved for fidelity/clarity rather than collapsed to a single `!==`).
409
+ const emitReminder = lastSig === '' || lastSig !== currentSig;
410
+
411
+ const planHint = computePlanHint(root);
412
+ const rdHint = computeRdHint(root);
413
+ const nudges = computeNudges(root);
414
+
415
+ const parts = [];
416
+ if (emitReminder) {
417
+ parts.push(`${REMINDER_BODY}${planHint}${rdHint}`);
418
+ }
419
+ if (nudges.length > 0) {
420
+ let nudgeBlock = 'somi loose-end check:';
421
+ for (const n of nudges) {
422
+ nudgeBlock += `\n - ${n}`;
423
+ }
424
+ parts.push(nudgeBlock);
425
+ }
426
+
427
+ if (parts.length > 0) {
428
+ contextOutput('UserPromptSubmit', parts.join('\n\n'));
429
+ }
430
+ }
431
+
432
+ runHook(main);
package/package.json CHANGED
@@ -1,11 +1,11 @@
1
1
  {
2
2
  "name": "@skathio/somi",
3
- "version": "1.2.0",
3
+ "version": "2.0.0",
4
4
  "scripts": {
5
5
  "test": "bash scripts/validate.sh"
6
6
  },
7
7
  "bin": {
8
- "somi-check": "scripts/somi-check.sh"
8
+ "somi-check": "scripts/somi-check.mjs"
9
9
  },
10
10
  "description": "SoMi — multi-agent engineering workflow system: plan, code, review — with SOLID/OWASP guardrails, deterministic hooks, and a global ruleset.",
11
11
  "keywords": [