@skathio/somi 2.2.2 → 3.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 (128) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/.claude-plugin/plugin.json +8 -2
  3. package/.copilot-extension/extension.json +9 -8
  4. package/.copilot-extension/marketplace.json +2 -2
  5. package/README.md +45 -33
  6. package/VERSION +1 -1
  7. package/agents/architecture-reviewer.md +16 -0
  8. package/agents/atlas.md +102 -0
  9. package/agents/coder.md +66 -22
  10. package/agents/designer.md +20 -16
  11. package/agents/discovery-analyst.md +6 -5
  12. package/agents/impact.md +97 -0
  13. package/agents/incident.md +96 -0
  14. package/agents/plan-reviewer.md +70 -0
  15. package/agents/planner.md +77 -20
  16. package/agents/pr.md +101 -0
  17. package/agents/refactor-designer.md +82 -0
  18. package/agents/refactorer.md +30 -24
  19. package/agents/reviewer.md +28 -25
  20. package/agents/sdlc-reviewer.md +69 -0
  21. package/agents/security-reviewer.md +17 -0
  22. package/agents/somi.md +204 -153
  23. package/agents/test-strategist.md +16 -1
  24. package/commands/adopt.md +21 -7
  25. package/commands/architecture-review.md +8 -5
  26. package/commands/atlas.md +24 -72
  27. package/commands/code-loop.md +46 -15
  28. package/commands/code-parallel.md +6 -4
  29. package/commands/code.md +29 -21
  30. package/commands/debug.md +17 -11
  31. package/commands/design.md +48 -31
  32. package/commands/discover.md +26 -16
  33. package/commands/impact.md +16 -54
  34. package/commands/incident.md +22 -55
  35. package/commands/plan-loop.md +43 -17
  36. package/commands/plan.md +64 -26
  37. package/commands/pr.md +19 -66
  38. package/commands/refactor-design.md +98 -0
  39. package/commands/refactor.md +22 -23
  40. package/commands/release-readiness.md +16 -7
  41. package/commands/review-panel.md +31 -10
  42. package/commands/review.md +21 -14
  43. package/commands/security-review.md +12 -3
  44. package/commands/ship-loop.md +71 -54
  45. package/commands/ship.md +17 -13
  46. package/commands/test-strategy.md +6 -4
  47. package/commands/upgrade.md +10 -8
  48. package/examples/discovery-example.md +2 -2
  49. package/examples/sample-consumer/CLAUDE.md +41 -7
  50. package/examples/sample-consumer/README.md +36 -22
  51. package/hooks/lib/common.mjs +66 -20
  52. package/hooks/post-tool/audit-log.mjs +7 -11
  53. package/hooks/post-tool/lint-changed-files.mjs +8 -11
  54. package/hooks/pre-tool/block-dangerous-bash.mjs +32 -44
  55. package/hooks/pre-tool/block-secret-writes.mjs +6 -9
  56. package/hooks/pre-tool/gate-dep-install.mjs +18 -27
  57. package/hooks/pre-tool/guard-protected-paths.mjs +9 -11
  58. package/hooks/session-start/detect-repo-instructions.mjs +21 -23
  59. package/hooks/user-prompt-submit/inject-workflow-context.mjs +190 -42
  60. package/mcp.json +10 -0
  61. package/package.json +5 -2
  62. package/rules/CLAUDE.md +22 -19
  63. package/scripts/check-links.mjs +218 -0
  64. package/scripts/check-session-artefacts.mjs +149 -0
  65. package/scripts/check-size-budget.mjs +137 -0
  66. package/scripts/generate-digest.mjs +176 -0
  67. package/scripts/lib/cost-ceiling.mjs +317 -0
  68. package/scripts/lib/cost-model.mjs +95 -0
  69. package/scripts/lib/dispatch-resolver.mjs +224 -0
  70. package/scripts/lib/mcp-project-root.mjs +183 -0
  71. package/scripts/size-budget-overrides.json +74 -0
  72. package/scripts/somi-check.mjs +6 -13
  73. package/scripts/somi-dispatch.mjs +141 -0
  74. package/scripts/somi-findings.mjs +4 -5
  75. package/scripts/somi-loop.mjs +181 -13
  76. package/scripts/somi-mcp.mjs +357 -0
  77. package/scripts/validate.sh +690 -29
  78. package/skills/clean-code/SKILL.md +1 -1
  79. package/skills/plan-review/SKILL.md +79 -0
  80. package/skills/rules/SKILL.md +47 -0
  81. package/skills/sdlc-process/SKILL.md +74 -0
  82. package/skills/somi-dispatch/SKILL.md +220 -0
  83. package/skills/somi-routing/SKILL.md +31 -6
  84. package/skills/{test-strategy → testing-playbook}/SKILL.md +1 -1
  85. package/templates/ATLAS.md.tmpl +4 -4
  86. package/templates/BRIEF.md.tmpl +23 -22
  87. package/templates/DECISIONS.md.tmpl +1 -0
  88. package/templates/DESIGN.md.tmpl +5 -5
  89. package/templates/DIARY.md.tmpl +10 -5
  90. package/templates/DOD.md.tmpl +24 -0
  91. package/templates/PROGRESS.md.tmpl +3 -16
  92. package/templates/SOMI-README.md.tmpl +3 -3
  93. package/tests/hooks/cases/inject-workflow-context.json +120 -7
  94. package/tests/hooks/run.sh +20 -11
  95. package/tests/scripts/check-links.sh +105 -0
  96. package/tests/scripts/check-session-artefacts.sh +60 -0
  97. package/tests/scripts/check-size-budget.sh +71 -0
  98. package/tests/scripts/checkpoint-gate.sh +90 -0
  99. package/tests/scripts/convergence-runner.sh +1510 -0
  100. package/tests/scripts/cost-ceiling.sh +343 -0
  101. package/tests/scripts/cost-model.sh +192 -0
  102. package/tests/scripts/dispatch-guard.sh +108 -0
  103. package/tests/scripts/dispatch-reference-gate.sh +173 -0
  104. package/tests/scripts/eval-runner.sh +3691 -0
  105. package/tests/scripts/evals-packaging.sh +117 -0
  106. package/tests/scripts/fixtures/legacy-shard-no-schema.json +50 -0
  107. package/tests/scripts/generate-digest.sh +180 -0
  108. package/tests/scripts/goldens/loop-state-breach.json +1 -0
  109. package/tests/scripts/goldens/loop-state-done.json +1 -0
  110. package/tests/scripts/goldens/somi-loop.json +1 -1
  111. package/tests/scripts/lib/adr-shape.mjs +41 -0
  112. package/tests/scripts/lib/checkpoint-gate.mjs +54 -0
  113. package/tests/scripts/lib/digest-marker-coupling.mjs +52 -0
  114. package/tests/scripts/lib/dispatch-reference-gate.mjs +112 -0
  115. package/tests/scripts/lib/multipass-dependence.mjs +192 -0
  116. package/tests/scripts/lib/multipass-source-identity.mjs +243 -0
  117. package/tests/scripts/lib/reference-pair.mjs +61 -0
  118. package/tests/scripts/lib/retirement-gate.mjs +167 -0
  119. package/tests/scripts/lib/shell-embedded-js.mjs +47 -0
  120. package/tests/scripts/lib/somi-mcp-client.mjs +102 -0
  121. package/tests/scripts/lib/somi-mcp-tests.mjs +401 -0
  122. package/tests/scripts/lib/somi-mcp-tool-schema.mjs +38 -0
  123. package/tests/scripts/retirement-gate.sh +287 -0
  124. package/tests/scripts/review-panel-seats.sh +32 -0
  125. package/tests/scripts/run.sh +184 -2
  126. package/tests/scripts/somi-agent-dispatch-contract.sh +195 -0
  127. package/tests/scripts/somi-dispatch.sh +354 -0
  128. package/tests/scripts/somi-mcp.sh +12 -0
@@ -2,9 +2,8 @@
2
2
  // hooks/pre-tool/guard-protected-paths.mjs — PreToolUse hook (matcher: Write|Edit) — block
3
3
  // writes to paths the agent shouldn't be editing.
4
4
  //
5
- // Node port of hooks/pre-tool/guard-protected-paths.sh (node-runtime-port, phase 2,
6
- // iteration 2.3). Imports the shared read/deny/config helpers from ../lib/common.mjs (2.1,
7
- // reviewer-blessed) rather than reimplementing them.
5
+ // Imports the shared read/deny/config helpers from ../lib/common.mjs rather than
6
+ // reimplementing them.
8
7
  //
9
8
  // Targets the most common "agent overstep" cases: .git internals, vendored deps, build
10
9
  // outputs, and the SOMI plugin install (so an agent doesn't rewrite its own ruleset under
@@ -21,7 +20,7 @@
21
20
  // FNM_PATHNAME), so `*` matches `/` AND newlines — verified empirically:
22
21
  // `[[ $'a\nb' == a*b ]]` is true, and `[[ "/x/node_modules/y" == */node_modules/* ]]` is
23
22
  // true (crosses the `/`). JS `.` excludes `\n` (and, without `/s`, `\r`/U+2028/U+2029) — the
24
- // same class of divergence block-secret-writes.mjs (2.2) flagged for ERE `.` vs JS `.`, here
23
+ // same class of divergence block-secret-writes.mjs flagged for ERE `.` vs JS `.`, here
25
24
  // applied to glob `*`. `[\s\S]*` matches every character unconditionally, closing the gap.
26
25
  // - Literal segments (`.git`, `node_modules`, ...) are regex-escaped. `.` has no special
27
26
  // meaning in glob/fnmatch syntax (unlike ERE, where it's "any char") — escaping it prevents
@@ -34,29 +33,28 @@
34
33
  // --- lockfile-gate precedence reconciliation ------------------------------------------------
35
34
  // Precedence: SOMI_ALLOW_LOCKFILES (env, session override, even "0") > .somi/config.json's
36
35
  // `lockfiles.allow_edit` (committed project policy) > default deny. scripts/somi-check.mjs's
37
- // lockfilesAllowed() (1.3, reviewer-blessed) already solved this exact precedence problem,
36
+ // lockfilesAllowed() already solved this exact precedence problem,
38
37
  // including the jq-text string-vs-boolean subtlety: bash's `somi::config` shells out to
39
38
  // `jq -r`, so a config author writing `"allow_edit": "true"` (a JSON STRING) produces the
40
39
  // identical jq -r output ("true") as `"allow_edit": true` (the boolean) — both are honored as
41
- // allowed. common.mjs's config() (2.1) already reproduces that jq -r text shape for scalar
40
+ // allowed. common.mjs's config() already reproduces that jq -r text shape for scalar
42
41
  // reads (returns '' for null/undefined/false, else the string itself or JSON.stringify(cur) for
43
42
  // a non-string scalar), so `config('.lockfiles.allow_edit') === 'true'` below reproduces the
44
43
  // SAME text comparison bash performs, without re-implementing a config reader the way
45
44
  // somi-check.mjs (which predates common.mjs) had to. Env-side fall-through matches too: bash's
46
45
  // `${SOMI_ALLOW_LOCKFILES:-}` treats unset AND explicitly-empty (`SOMI_ALLOW_LOCKFILES=""`)
47
46
  // identically (falls through to the config check); the `env !== undefined && env !== ''` guard
48
- // below reproduces that, matching lockfilesAllowed()'s own env branch. Verified by hand-tracing
49
- // every fixture case plus the differential probes (see diary).
47
+ // below reproduces that, matching lockfilesAllowed()'s own env branch.
50
48
  //
51
49
  // --- platform reasoning (posix vs win32) ----------------------------------------------------
52
- // This is the "path-heavier hook" block-secret-writes.mjs's header warned 2.3+ to reason
50
+ // This is the "path-heavier hook" block-secret-writes.mjs's header warned later hooks to reason
53
51
  // through explicitly — its own divergence there was Windows-SAFER; here one of them is not:
54
52
  // 1. PROTECTED_GLOBS are forward-slash literals (`*/node_modules/*`). If `tool_input.file_path`
55
53
  // ever arrives with backslash separators (a native-Windows path not already normalized to
56
54
  // forward slashes upstream), the translated regex requires a literal `/` and will NOT match
57
55
  // a `\`-separated path — a protected write could slip through undenied. This reproduces the
58
56
  // bash original's identical gap (its globs were just as forward-slash-only) rather than
59
- // introducing a new one; documented per this iteration's brief, not fixed — fixing would
57
+ // introducing a new one; documented, not fixed — fixing would
60
58
  // mean choosing a separator-normalization policy this behavior-preserving port doesn't own.
61
59
  // 2. The relative-path check (`pathInput.startsWith('/')`) hardcodes a literal POSIX leading-
62
60
  // `/` test, deliberately NOT `path.isAbsolute()` (platform-aware; would treat `C:\...` as
@@ -129,7 +127,7 @@ function main() {
129
127
 
130
128
  // Normalise relative paths so the leading-`*/` globs above still match (a relative
131
129
  // `node_modules/x.js` would otherwise slip past `*/node_modules/*`). Reuses common.mjs's
132
- // projectRoot() — the centralized ${...}-unexpanded-variable guard (2.1) — rather than
130
+ // projectRoot() — the centralized ${...}-unexpanded-variable guard — rather than
133
131
  // re-duplicating it here.
134
132
  if (!pathInput.startsWith('/')) {
135
133
  pathInput = `${projectRoot()}/${pathInput}`;
@@ -2,24 +2,23 @@
2
2
  // hooks/session-start/detect-repo-instructions.mjs — SessionStart hook — detect repo-local
3
3
  // agent/instruction files and surface them.
4
4
  //
5
- // Node port of hooks/session-start/detect-repo-instructions.sh (node-runtime-port, phase 2,
6
- // iteration 2.7). Imports the shared read/context/projectRoot helpers from ../lib/common.mjs
7
- // (2.1, reviewer-blessed) rather than reimplementing them.
5
+ // Imports the shared read/context/projectRoot helpers from ../lib/common.mjs rather than
6
+ // reimplementing them.
8
7
  //
9
- // SoMi's MAX→ECO economy is "respect repo conventions as context": when a project ships its
10
- // own instructions (CLAUDE.md / AGENTS.md / copilot-instructions / .cursorrules) or its own
11
- // subagents (.claude/agents/), SoMi's MAX actions should read them once and fold the relevant
12
- // conventions into the work-item brief.md, so the ECO tier inherits them without re-reading.
8
+ // SoMi's design→execution economy is "respect repo conventions as context": when a project ships
9
+ // its own instructions (CLAUDE.md / AGENTS.md / copilot-instructions / .cursorrules) or its own
10
+ // subagents (.claude/agents/), SoMi's `cost: high` actions should read them once and fold the
11
+ // relevant conventions into the work-item brief.md, so execution inherits them without re-reading.
13
12
  // Repo-local instructions WIN over SoMi defaults where they conflict; SoMi does NOT
14
13
  // auto-invoke foreign agents. This hook only *surfaces* what exists (paths + a one-line
15
14
  // directive) — it does not read or ingest file contents. It fires once per session and stays
16
15
  // silent when nothing repo-local is present.
17
16
  //
18
- // === THE PRUNE-LIST DECISION (explicit, named, per the phase file's requirement) =============
17
+ // === THE PRUNE-LIST DECISION (explicit and named) ==============================
19
18
  //
20
19
  // bash's nested-file find (`detect-repo-instructions.sh:41-46`) declares a prune list
21
- // (.git/node_modules/.somi/vendor) but it is CONFIRMED NON-FUNCTIONAL on GNU find (0.4's
22
- // finding, independently reproduced by 0.4 pass 2's review with a control experiment): GNU
20
+ // (.git/node_modules/.somi/vendor) but it is CONFIRMED NON-FUNCTIONAL on GNU find (found by a
21
+ // probe and reproduced independently with a control experiment): GNU
23
22
  // find's `-mindepth 2` suppresses evaluation of EVERY predicate — including `-prune` — for
24
23
  // entries at depth < 2, and the pruned directories themselves (.git, node_modules, .somi,
25
24
  // vendor) are always depth-1 children of PROJECT_ROOT. The `-prune` clause therefore never
@@ -46,12 +45,12 @@
46
45
  // 2. Correctness, not just performance: what gets SURFACED. A CLAUDE.md/AGENTS.md that
47
46
  // happens to live inside a vendored dependency (node_modules), a submodule under
48
47
  // vendor/, or somi's own internal state directory is not "this repository's own
49
- // instructions" in the sense this hook's entire purpose describes to the MAX actions
50
- // that consume its signal. Surfacing a third-party package's own CLAUDE.md as if it were
48
+ // instructions" in the sense this hook's entire purpose describes to the `cost: high`
49
+ // actions that consume its signal. Surfacing a third-party package's own CLAUDE.md as if it were
51
50
  // this repo's convention is actively misleading downstream context, not neutral noise.
52
51
  //
53
- // 3. Performance, empirically measured, not assumed (this is the argument the phase file
54
- // flagged as possibly strongest, and it held up under measurement). Built a synthetic
52
+ // 3. Performance, empirically measured, not assumed (possibly the strongest argument, and it
53
+ // held up under measurement). Built a synthetic
55
54
  // 800-package node_modules (4802 fs entries at depth <= 3, no matches, so `head -n 10`
56
55
  // cannot short-circuit either implementation — full traversal is forced both ways) and
57
56
  // timed three walks against it: bash's find (buggy, still descends node_modules) ~14ms;
@@ -64,25 +63,24 @@
64
63
  // commonly have thousands of packages — non-negligible for a hook whose whole premise is
65
64
  // being cheap enough to run unconditionally on every SessionStart.
66
65
  //
67
- // 4. Fail-quiet in the safe direction, matching this work item's existing precedent for
68
- // accepted divergences (2.4's BASH_REMATCH-clobber fix, 2.6's UTF-8 truncation
66
+ // 4. Fail-quiet in the safe direction, matching the other accepted divergences from the
67
+ // original bash hooks (the BASH_REMATCH-clobber fix, the UTF-8 truncation
69
68
  // divergence): this change can only ever make a previously-surfaced file go silent
70
69
  // (prune now excludes something it used to include); in every realistic case it never
71
- // surfaces something new. (Pedantic corner from the 2.7 review: with >10 nested matches
70
+ // surfaces something new. (Pedantic corner: with >10 nested matches
72
71
  // where pruned-dir junk sorts ahead of real files, bash's head -n 10 could truncate a
73
72
  // REAL file the pruned walk now surfaces — arguably more correct, but not absolutely
74
73
  // "never new".) A regression from this fix is "the hook says nothing when it used to
75
74
  // say something," never a false positive.
76
75
  //
77
- // 5. Confined blast radius: unlike the audit()-embedded-delimiter issue (filed work-item-
78
- // wide, deliberately NOT fixed in a single hook's port), this fix touches only this file
76
+ // 5. Confined blast radius: unlike the audit()-embedded-delimiter issue (shared by every hook,
77
+ // deliberately NOT fixed in a single hook), this fix touches only this file
79
78
  // — no shared common.mjs contract, no other hook's behavior, no cross-file coupling.
80
79
  //
81
80
  // What this means for the fixture (tests/hooks/cases/detect-repo-instructions.json):
82
81
  // `surfaces-nested-claude-md-under-pruned-dir` (which pinned the CURRENT bash bug — a
83
82
  // node_modules/CLAUDE.md being surfaced) is renamed and re-pointed to assert the FIXED
84
- // behavior (silent exit — node_modules is now actually pruned) as a named, reviewed edit, per
85
- // the same convention 2.8's status-detection decision is instructed to follow. The stated
83
+ // behavior (silent exit — node_modules is now actually pruned) as a named, reviewed edit. The stated
86
84
  // fixture-implications of the OTHER option (had (a) been chosen instead): every other case in
87
85
  // the corpus would be untouched, this one case would pass completely as-is with zero edits,
88
86
  // and the.mjs would need to intentionally NOT prune node_modules/.git/.somi/vendor at
@@ -117,7 +115,7 @@
117
115
  // `fs.statSync(...).isFile()` and Dirent's `isFile()` both return `false` for a directory
118
116
  // identically, no extra branch required.
119
117
  //
120
- // === Windows caveat (same class already flagged in 2.2/2.3/2.5) ==============================
118
+ // === Windows caveat (same class already flagged in the other path-handling hooks) ==============================
121
119
  // `path.relative()` (platform-default separator: posix on Linux/macOS, win32 on Windows) is
122
120
  // used to build the relative paths this hook emits in its message text. On Windows this would
123
121
  // emit backslash-separated relative paths where bash's `${nested#"$PROJECT_ROOT"/}` prefix
@@ -149,7 +147,7 @@ const MAX_NESTED_RESULTS = 10; // bash: | head -n 10
149
147
  // `$'...'\''...'\''...'` escaping decodes to). Byte-exact against the fixture's
150
148
  // expect_context substrings.
151
149
  const DIRECTIVE =
152
- "\nMAX actions (/discover, /design, /refactor analysis, and /plan on a cold start) should read these once and distil the relevant conventions into the work item's brief.md / context.md so the ECO tier inherits them without re-reading. Repo-local instructions WIN over SoMi defaults where they conflict. Do NOT auto-invoke the repo's own agents — surface them for the user to opt into.";
150
+ "\n`cost: high` actions (/discover, /design, /refactor-design, and /plan on a cold start) should read these once and distil the relevant conventions into the work item's brief.md / context.md so execution inherits them without re-reading. Repo-local instructions WIN over SoMi defaults where they conflict. Do NOT auto-invoke the repo's own agents — surface them for the user to opt into.";
153
151
 
154
152
  function isFile(p) {
155
153
  try {
@@ -2,12 +2,10 @@
2
2
  // hooks/user-prompt-submit/inject-workflow-context.mjs — UserPromptSubmit hook — inject SOMI
3
3
  // context on relevant turns.
4
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.
5
+ // The heaviest hook in the set: several pattern lists and a signature-hash gate. Imports the
6
+ // shared read/context/projectRoot helpers from ../lib/common.mjs rather than reimplementing them.
9
7
  //
10
- // Two responsibilities (unchanged from bash):
8
+ // Two responsibilities (unchanged from the original bash hook):
11
9
  // 1. Remind the agent of the priority stack and active work-item state.
12
10
  // 2. Surface end-of-turn loose ends (TODO(claude) markers, scratch files) on the NEXT user
13
11
  // turn — this replaces the old Stop hook, which used an additionalContext channel that Stop
@@ -19,6 +17,31 @@
19
17
  // independent of the reminder gate (see main() — this independence is pinned by the fixture case
20
18
  // "nudge-fires-independent-of-suppressed-reminder").
21
19
  //
20
+ // === THE TIER 1 / TIER 2 DIGEST SPLIT =========================================================
21
+ //
22
+ // This hook carries rules/CLAUDE.md's always-on digest into a consuming Claude Code project —
23
+ // the only delivery path that reaches one (plugin.json has no `rules` key). An always-on floor and the state-change gate below want opposite behavior from the same
24
+ // mechanism, so emission is split into two independent tiers rather than picking one:
25
+ //
26
+ // Tier 1 — REMINDER_BODY, unconditional, every UserPromptSubmit turn, independent of the
27
+ // signature gate below (the same independence pattern the loose-end nudges already use).
28
+ //
29
+ // Tier 2 — the full eleven-bullet digest, extracted at RUNTIME from rules/CLAUDE.md's
30
+ // `<!-- digest:start/end -->` markers (never hand-copied into this hook as a fourth drift-prone
31
+ // copy), plus planHint/rdHint. Both hints STAY on Tier 2 rather than moving to
32
+ // Tier 1: they are themselves state-change signals (which plan/rd is active), so gating them
33
+ // here preserves their gated behavior rather than making them newly always-on. Tier 2 rides the signature gate exactly as the old single-tier reminder did.
34
+ //
35
+ // Tier 2's bullets are read via pluginRoot() (hooks/lib/common.mjs), not assumed to live at this
36
+ // repo's own path, because this hook also runs inside a CONSUMING project, where SoMi's rules/
37
+ // lives inside the plugin's install directory, not at ./rules/... relative to the consumer's
38
+ // project root. For the same reason, each bullet's trailing citation is rewritten to a bare
39
+ // `` `NN` `` numeric code before injection (stripDigestCitations() below) rather than left as
40
+ // whatever link form rules/CLAUDE.md's canonical file uses — an unmodified normalized link would
41
+ // assert six paths that ENOENT in the consumer's context, on every gated turn. Fails safe:
42
+ // an unresolved pluginRoot(), or a rules/CLAUDE.md missing/malformed digest markers, silently
43
+ // omits Tier 2 rather than throwing — Tier 1 still fires regardless (see buildTier2Digest()).
44
+ //
22
45
  // === THE SIGNATURE-HASH GATE: what bash actually feeds sha256sum ================================
23
46
  //
24
47
  // bash's compute_signature() runs THREE independent `find ... -printf '%T@ %p\n' | sort |
@@ -64,20 +87,19 @@
64
87
  // doesn't exist at all on Windows) nor required for correctness. What IS required, and IS
65
88
  // preserved exactly, is the gate's BEHAVIORAL contract: stable across repeated invocations when
66
89
  // 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:
90
+ // changes — both verified by direct probe. One bounded, expected consequence:
68
91
  // the FIRST Node-hook invocation on a host whose `.somi/somi-state/last-context-signature`
69
92
  // was last written by the bash hook will see a "changed" signature (different hash algorithms
70
93
  // for the same state) and re-emit the reminder ONE extra time at cutover — benign, not a bug.
71
94
  //
72
- // === THE STATUS-DETECTION DECISION (explicit, named, per the phase file's requirement) ==========
95
+ // === THE STATUS-DETECTION DECISION (explicit and named) =============================
73
96
  //
74
- // 0.5's fixture pinned a real gap: bash's in-progress detection recognizes a bare status line
97
+ // A fixture pinned a real gap in the original bash hook: its in-progress detection recognizes a bare status line
75
98
  // matching `^[[:space:]]*<?in-progress>?[[:space:]]*$` (optional ANGLE brackets, not backticks)
76
99
  // or a line matching `status:[[:space:]]*`?in-progress`?` (requires a literal "status:" prefix).
77
100
  // Neither pattern matches this project's OWN `progress.md` convention: a bare, BACKTICK-wrapped
78
101
  // 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
102
+ // but by `templates/PROGRESS.md.tmpl` (`<One of: ... | in-progress | ...>` under a bare
81
103
  // `## Status` heading, zero "Status:" prefix) — the CANONICAL template every `/plan`-generated
82
104
  // work item's `progress.md` follows. So the narrow bash regexes miss the mainline case, not an
83
105
  // edge case: every SoMi work item created via the documented template is invisible to this
@@ -91,69 +113,66 @@
91
113
  // rule the original never had. The full-line anchor (`^...$`, tested per PHYSICAL LINE, matching
92
114
  // grep's line-oriented semantics, not a whole-file substring search) is preserved exactly.
93
115
  //
94
- // Reasoning, weighed explicitly against reproducing the narrow detection for parity (mirroring
95
- // 2.7's prune-list decision structure):
116
+ // Reasoning, weighed explicitly against reproducing the narrow detection for parity:
96
117
  //
97
118
  // 1. Self-inconsistency, not a deliberate choice being preserved. SoMi's OWN planning tooling
98
119
  // generates `progress.md` files in the exact format its OWN hook fails to recognize. This
99
120
  // is not a hypothetical third-party format difference — it is SoMi authoring content for
100
121
  // itself that its own runtime cannot read.
101
122
  // 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
123
+ // the prune-list fix in detect-repo-instructions.mjs (which could only ever go quiet, never
124
+ // surface something new — fail-quiet in the safe direction), THIS widening is in the OPPOSITE risk direction: it can make the
104
125
  // 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
126
+ // narrative text. Checked directly: `grep -nE '^\s*[<`]?in-progress[>`]?\s*$'` against a
127
+ // real ~1100-line `progress.md` — which repeatedly contains the SUBSTRING
107
128
  // "in-progress" inside narrative sentences (e.g. "Iteration left `in-progress` (pass 1);
108
129
  // review decides `done`." appears a dozen+ times in the Recent-activity/diary prose) —
109
130
  // matches EXACTLY ONE line: the real `## Status` field's own bare `` `in-progress` `` line.
110
131
  // Every narrative occurrence is disqualified by the full-line anchor (surrounding text on
111
132
  // the same physical line breaks the `^...$` match). This is the concrete evidence that a
112
133
  // 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
134
+ // real `progress.md` once it accumulates history) while the full-line-anchored
114
135
  // widening actually chosen is not.
115
136
  // 3. Confined blast radius: only `PLAN_STATUS_BARE_RE` changes. The R&D status scan
116
137
  // (`researching|drafting|awaiting-verification|ready-for-planning`) already matches this
117
138
  // 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
139
+ // "Status:" prefix the regex requires) — no gap there, so it is
119
140
  // reproduced unchanged. `PLAN_STATUS_PREFIXED_RE` (the "status:"-prefixed in-progress form)
120
141
  // is also reproduced unchanged — it already matches its own fixture cases correctly.
121
142
  //
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.
143
+ // Consumer-observable consequence: a work item using the bare-backtick `progress.md` convention
144
+ // now surfaces its "Active work item:" hint on turns where it previously stayed silent. This is a
145
+ // real behavior change, not a bug fix to an internal-only mechanism (unlike the SessionStart
146
+ // prune fix, which only affected an already-informational context surface), so it belongs in
147
+ // the CHANGELOG.
128
148
  //
129
149
  // Fixture implication: `tests/hooks/cases/inject-workflow-context.json`'s
130
150
  // `plan-hint-bare-backtick-status-not-detected` case (which pinned the bash gap as current
131
151
  // behavior) is renamed to `plan-hint-bare-backtick-status-now-detected` and its expectation
132
152
  // 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.
153
+ // \`.somi/plans/demo-slug/\`."`) — the one deliberate case edit this change required.
135
154
  //
136
155
  // === Loose-end nudges: execFileSync argument arrays, explicit maxBuffer ==========================
137
156
  // `git diff`/`git status` are invoked via `execFileSync` with argument ARRAYS (never a shell
138
157
  // string), avoiding any shell-injection surface entirely (paths interpolated into a shell command
139
158
  // 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
159
+ // calls set `maxBuffer` explicitly (10 MB — the convention for every
160
+ // output-capturing subprocess call in the hooks), rather than relying on Node's low
142
161
  // 1 MB default. A failed/absent `git` (ENOENT) or a non-zero exit from either command degrades to
143
162
  // "no nudge from that check" — mirrors bash's `2>/dev/null` + `set -o pipefail`-tolerant `if
144
163
  // pipeline; then` idiom, where either failure mode collapses to the same "condition false" outcome
145
164
  // (a pipeline's non-zero exit inside an `if` condition does not abort under `set -e`).
146
165
  //
147
- // === Windows caveat (same class already flagged in 2.2/2.3/2.5/2.7) ==============================
166
+ // === Windows caveat (same class already flagged in the other path-handling hooks) ==========
148
167
  // Paths embedded in the signature hash and extracted slugs use `path.join`/`path.basename`
149
168
  // (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.
169
+ // not fixed here, consistent with the other hooks' documented-not-fixed Windows path-separator gaps.
151
170
 
152
171
  import fs from 'node:fs';
153
172
  import path from 'node:path';
154
173
  import crypto from 'node:crypto';
155
174
  import { execFileSync } from 'node:child_process';
156
- import { readPayload, projectRoot, contextOutput, runHook } from '../lib/common.mjs';
175
+ import { readPayload, projectRoot, pluginRoot, contextOutput, runHook } from '../lib/common.mjs';
157
176
 
158
177
  // bash: `grep -qiE '^[[:space:]]*<?in-progress>?[[:space:]]*$'` — WIDENED per THE
159
178
  // STATUS-DETECTION DECISION above: backtick added as a second optional wrap character alongside
@@ -164,8 +183,8 @@ const PLAN_STATUS_BARE_RE = /^\s*[<`]?in-progress[>`]?\s*$/i;
164
183
  const PLAN_STATUS_PREFIXED_RE = /status:\s*`?in-progress`?/i;
165
184
 
166
185
  // 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.
186
+ // `grep -qiE 'status:[[:space:]]*`?ready-for-planning`?'` — reproduced unchanged; the real R&D
187
+ // README.md convention already carries the required "Status:" prefix.
169
188
  const RD_STATUS_ACTIVE_RE = /status:\s*`?(researching|drafting|awaiting-verification)`?/i;
170
189
  const RD_STATUS_READY_RE = /status:\s*`?ready-for-planning`?/i;
171
190
 
@@ -174,18 +193,133 @@ const TODO_MARKER_RE = /^\+.*(TODO\(claude\)|TODO\(agent\)|FIXME\(claude\))/;
174
193
  // bash: `grep -E '^\?\? .*(\.bak|\.orig|scratch_)'` against `git status --porcelain` output.
175
194
  const SCRATCH_FILE_RE = /^\?\? .*(\.bak|\.orig|scratch_)/;
176
195
 
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).
196
+ // The convention for every output-capturing subprocess call (Node's spawnSync/execFileSync default
197
+ // maxBuffer is 1 MB — too small for a real `git diff`/`git status --porcelain` on a large
198
+ // working tree).
180
199
  const GIT_MAX_BUFFER = 10 * 1024 * 1024;
181
200
 
182
201
  const REMINDER_BODY =
183
202
  'somi is active. Reminders:\n' +
184
- '- Follow rules/CLAUDE.md priorities: security > correctness > maintainability > performance > convenience.\n' +
203
+ // No `rules/...` path here, deliberately. This text is injected into a CONSUMING
204
+ // project's context, where SoMi's `rules/` lives inside the plugin install dir, not at
205
+ // `./rules/`. Naming the path asserted a file that ENOENTs there — the same defect the Tier 2
206
+ // digest avoids — and this block is emitted on EVERY turn, so the false assertion would be
207
+ // loud. Stating the priority order directly needs no path at all. Keeping
208
+ // Tier 1 free of `rules/` is also what lets the Tier 2 assertion be a flat "no `rules/`".
209
+ '- Follow SoMi\'s priority order: security > correctness > maintainability > performance > convenience.\n' +
185
210
  '- Plan before coding non-trivial work. Code from the plan, not around it.\n' +
186
211
  '- Surface tradeoffs and shortcuts in plain text; never silently compromise.\n' +
187
212
  '- Hooks may deny dangerous bash, secret writes, protected paths, and unsanctioned dep installs — do not work around them.';
188
213
 
214
+ // Markers pinned in rules/CLAUDE.md's own "Always-on digest" section so extraction never depends
215
+ // on heading text staying stable — scripts/generate-digest.mjs consumes the same two markers for
216
+ // its own targets.
217
+ const DIGEST_MARKER_RE = /<!-- digest:start -->\r?\n([\s\S]*?)\r?\n<!-- digest:end -->/;
218
+
219
+ // Flattens a markdown link to its target, e.g. `[label](target)` -> `target` — the first half of
220
+ // rewriting each bullet's trailing citation to a bare numeric code (see stripDigestCitations()
221
+ // below). `.replace()` with a global regex resets its own lastIndex at the start of every call
222
+ // (per spec), so reusing this module-level pattern across lines carries none of the
223
+ // stateful-/g-regex hazard common.mjs's toRegExp()/matchesAny() guard against.
224
+ const DIGEST_LINK_RE = /\[([^\]]*)\]\(([^)]*)\)/g;
225
+
226
+ // Rewrites each physical line's trailing `(...)` citation to bare backtick-wrapped numeric
227
+ // code(s): `(`00`)` stays `(`00`)`; `([rules/00-priorities.md](./rules/00-priorities.md))`
228
+ // becomes `(`00`)`; `(`00`, `20`)` stays `(`00`, `20`)`. This is the required OUTPUT, not "strip
229
+ // back to the parenthetical it wrapped" — the latter, applied to a markdown-link source, still
230
+ // leaves a path assertion behind (`(rules/00-priorities.md)` still ENOENTs in a consuming
231
+ // project). Handles the already-bare canonical form and the
232
+ // full-markdown-link form identically — a markdown link is flattened to its target text before
233
+ // the numeric code is extracted, so this function doesn't need to know which form rules/CLAUDE.md
234
+ // is currently in.
235
+ function stripDigestCitations(block) {
236
+ return block
237
+ .split('\n')
238
+ .map((line) => {
239
+ // Match the trailing parenthetical on the ORIGINAL line — never on a pre-flattened copy
240
+ // Flattening the whole line first and returning that copy from the reject paths meant
241
+ // any line the recognizer DECLINED still had its markdown links destroyed: a bullet reading
242
+ // `read [the security file](./rules/30-security-owasp.md) before touching a sink` was injected
243
+ // as `read ./rules/30-security-owasp.md before touching a sink` — the very output this function exists
244
+ // to prevent, reached through the opposite door, and via the `!citationMatch` branch, which has nothing to do with
245
+ // citations at all. The mutation is now confined to the citation: links are flattened ONLY
246
+ // inside the captured body, and every reject path returns `line` byte-identical.
247
+ //
248
+ // One level of nesting is tolerated so a full markdown-link citation —
249
+ // `([rules/00-priorities.md](./rules/00-priorities.md))`, the form the digest generator
250
+ // normalizes to — is captured whole rather than truncated at its inner `)`.
251
+ const citationMatch = line.match(/\((?:[^()]|\([^()]*\))*\)\s*$/);
252
+ if (!citationMatch) return line; // no trailing parenthetical on this physical line — a
253
+ // bullet's citation sits on its own word-wrapped continuation line, not every line has one.
254
+ // Returns `line`, NOT a flattened copy: a line with no citation is none of this function's
255
+ // business, whatever else it contains.
256
+ const inner = citationMatch[0].slice(1, -1); // drop the outer parens
257
+ const flattenedBody = inner.replace(DIGEST_LINK_RE, (_m, label, target) => target || label);
258
+ // ANCHORED recognizer. An earlier form scanned the parenthetical unanchored
259
+ // for any two-digit run, so ANY line-final parenthetical containing two consecutive digits
260
+ // became a rule citation: a bullet ending `(ISO 27001)` was rewritten to (`27`, `00`) —
261
+ // fabricating a citation to two rule files and delivering it to the model as fact. Rewrapping or trimming this block is precisely when a non-citation
262
+ // parenthetical lands at end-of-line.
263
+ //
264
+ // The whole body must now BE a citation list — comma-separated `NN` / `` `NN` `` /
265
+ // `rules/NN-*.md` / `./rules/NN-*.md` — or the line is left untouched. Partial matches no
266
+ // longer leak: `ISO 27001` fails because `27001` is not a two-digit item.
267
+ const body = flattenedBody.trim();
268
+ // The `rules/` segment is OPTIONAL (widened after review). The canonical
269
+ // digest lives at rules/CLAUDE.md, so a link that RESOLVES from there is `./NN-*.md` with no
270
+ // `rules/` segment — the form the composition table in that same file already uses. Requiring
271
+ // `rules/` accepted only `./rules/NN-*.md`, which resolves to `rules/rules/...` and is a dead
272
+ // link; the round-trip appeared to pass precisely BECAUSE the canonical was broken. Both forms
273
+ // are accepted now so correcting the canonical cannot silently reintroduce path assertions.
274
+ const ITEM_RE = /^(?:`?(\d{2})`?|\.?\/?(?:rules\/)?(\d{2})-[A-Za-z0-9-]+\.md)$/;
275
+ const items = body === '' ? [] : body.split(',').map((s) => s.trim());
276
+ const codes = [];
277
+ let allItemsAreCitations = items.length > 0;
278
+ for (const item of items) {
279
+ const m = ITEM_RE.exec(item);
280
+ if (!m) {
281
+ allItemsAreCitations = false;
282
+ break;
283
+ }
284
+ const code = m[1] ?? m[2];
285
+ if (!codes.includes(code)) codes.push(code);
286
+ }
287
+ // Not a citation list — return `line` UNCHANGED. A rejected line keeps its original
288
+ // markdown links intact. If such a link points into `rules/`, a digest-wide
289
+ // `excludes: "rules/"` assertion goes red and forces the digest's author to use the accepted
290
+ // grammar rather than having the link silently mangled into a bare path. Loud beats silent.
291
+ if (!allItemsAreCitations || codes.length === 0) return line;
292
+ const rewritten = `(${codes.map((c) => `\`${c}\``).join(', ')})`;
293
+ return line.slice(0, citationMatch.index) + rewritten;
294
+ })
295
+ .join('\n');
296
+ }
297
+
298
+ // Tier 2's content, read fresh from rules/CLAUDE.md at runtime rather than hand-copied into this
299
+ // hook as a fourth drift-prone copy. Fails safe at every step — an unresolved
300
+ // pluginRoot(), an unreadable file, or missing/malformed digest markers all return '' (Tier 2
301
+ // silently omitted) rather than throwing; Tier 1 (REMINDER_BODY) fires regardless, in main().
302
+ function buildTier2Digest() {
303
+ const base = pluginRoot();
304
+ if (!base) return '';
305
+ let content;
306
+ try {
307
+ content = fs.readFileSync(path.join(base, 'rules', 'CLAUDE.md'), 'utf8');
308
+ } catch {
309
+ return '';
310
+ }
311
+ const match = DIGEST_MARKER_RE.exec(content);
312
+ if (!match) return '';
313
+ return stripDigestCitations(match[1]);
314
+ }
315
+
316
+ // The single, durable pointer that replaces the per-bullet paths stripDigestCitations() removes.
317
+ // Appended by main() AFTER planHint/rdHint so it is genuinely trailing: building it into
318
+ // buildTier2Digest() put it before the hints, leaving a hint rendered as a dangling bullet hanging
319
+ // off a prose sentence — readable as an elaboration of "load the rules skill" rather than as the
320
+ // work-item notice it is.
321
+ const RULES_SKILL_POINTER = 'For full detail on any of these, load the `rules` skill.';
322
+
189
323
  function isDirectory(p) {
190
324
  try {
191
325
  return fs.statSync(p).isDirectory();
@@ -412,10 +546,23 @@ function main() {
412
546
  const rdHint = computeRdHint(root);
413
547
  const nudges = computeNudges(root);
414
548
 
415
- const parts = [];
549
+ // Tier 1: unconditional, every turn, independent of emitReminder.
550
+ const parts = [REMINDER_BODY];
551
+
552
+ // Tier 2: gated exactly as the old single-tier reminder was. planHint/rdHint ride Tier 2 (see
553
+ // the header note above) — concatenated the same way REMINDER_BODY+hints were joined before
554
+ // this split, then any leading newline left over from an empty/omitted digest is trimmed so a
555
+ // fail-safe-omitted Tier 2 with a present hint doesn't emit a stray blank line.
416
556
  if (emitReminder) {
417
- parts.push(`${REMINDER_BODY}${planHint}${rdHint}`);
557
+ const tier2Digest = buildTier2Digest();
558
+ let tier2Block = `${tier2Digest}${planHint}${rdHint}`.replace(/^\n+/, '');
559
+ // The pointer goes last, after the hints — and only when a digest was actually
560
+ // extracted, so the fail-safe path (missing/marker-less rules/CLAUDE.md) doesn't advertise a
561
+ // skill for content it just failed to deliver.
562
+ if (tier2Digest !== '') tier2Block += `\n\n${RULES_SKILL_POINTER}`;
563
+ if (tier2Block !== '') parts.push(tier2Block);
418
564
  }
565
+
419
566
  if (nudges.length > 0) {
420
567
  let nudgeBlock = 'somi loose-end check:';
421
568
  for (const n of nudges) {
@@ -424,9 +571,10 @@ function main() {
424
571
  parts.push(nudgeBlock);
425
572
  }
426
573
 
427
- if (parts.length > 0) {
428
- contextOutput('UserPromptSubmit', parts.join('\n\n'));
429
- }
574
+ // Tier 1 is unconditional, so `parts` is never empty — the old `if (parts.length > 0)` guard
575
+ // became dead code with the tier split and is dropped rather than left as a false suggestion that
576
+ // a silent turn is still reachable.
577
+ contextOutput('UserPromptSubmit', parts.join('\n\n'));
430
578
  }
431
579
 
432
580
  runHook(main);
package/mcp.json ADDED
@@ -0,0 +1,10 @@
1
+ {
2
+ "$schema": "https://agent-plugins.org/schemas/1.0.0/mcp.schema.json",
3
+ "mcpServers": {
4
+ "somi": {
5
+ "type": "stdio",
6
+ "command": "node",
7
+ "args": ["${PLUGIN_ROOT}/scripts/somi-mcp.mjs"]
8
+ }
9
+ }
10
+ }
package/package.json CHANGED
@@ -1,8 +1,10 @@
1
1
  {
2
2
  "name": "@skathio/somi",
3
- "version": "2.2.2",
3
+ "version": "3.0.0",
4
4
  "scripts": {
5
- "test": "bash scripts/validate.sh"
5
+ "test": "bash scripts/validate.sh",
6
+ "eval:behavioral": "node tests/evals/run.mjs",
7
+ "eval:convergence": "node tests/evals/convergence.mjs"
6
8
  },
7
9
  "bin": {
8
10
  "somi-check": "scripts/somi-check.mjs"
@@ -50,6 +52,7 @@
50
52
  ".claude-plugin/",
51
53
  ".copilot-extension/",
52
54
  ".claude/",
55
+ "mcp.json",
53
56
  "VERSION",
54
57
  "LICENSE"
55
58
  ]