@skathio/somi 2.2.2 → 3.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (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 +225 -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 +691 -30
  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 +366 -0
  128. package/tests/scripts/somi-mcp.sh +12 -0
package/rules/CLAUDE.md CHANGED
@@ -30,28 +30,29 @@ This digest is **always in force** — it is the compressed form of the numbered
30
30
  act correctly on the common path without loading all of them. Each line points at the file that holds
31
31
  the full treatment; read that file when you **enter its domain** (see "How to load the rules" below).
32
32
 
33
+ <!-- digest:start -->
33
34
  - **Priorities:** security > correctness > maintainability > convenience. Compromise on the lower
34
- only to honor the higher, and say so. (`00`)
35
+ only to honor the higher, and say so. ([`00`](./00-priorities.md))
35
36
  - **Honesty:** identify uncertainty; verify before claiming (read the file, grep the symbol, run the
36
- command); never invent facts to sound confident. (`00`)
37
+ command); never invent facts to sound confident. ([`00`](./00-priorities.md))
37
38
  - **Discipline:** read before writing; smallest sufficient change (fix ≠ refactor); no silent
38
- compromises — name every shortcut in plain text. (`00`, `20`)
39
+ compromises — name every shortcut in plain text. ([`00`](./00-priorities.md), [`20`](./20-clean-code.md))
39
40
  - **SOLID, in practice:** one reason to change per unit; depend on abstractions at boundaries; keep
40
- interfaces small and caller-shaped; no god objects or `Manager`/`Helper` catch-alls. (`10`)
41
+ interfaces small and caller-shaped; no god objects or `Manager`/`Helper` catch-alls. ([`10`](./10-solid.md))
41
42
  - **Clean code:** names state intent and don't lie; small functions, one level of abstraction;
42
- comment the *why*, not the *what*; delete dead code rather than commenting it out. (`20`)
43
+ comment the *why*, not the *what*; delete dead code rather than commenting it out. ([`20`](./20-clean-code.md))
43
44
  - **Security floor:** validate untrusted input at the trust boundary; parameterize every sink (SQL,
44
45
  shell, template, path, HTTP); authorize at the sink; never log secrets; constant-time compare
45
- secrets; fail closed. (`30`)
46
+ secrets; fail closed. ([`30`](./30-security-owasp.md))
46
47
  - **Testing:** risk-driven coverage, not coverage-worship; don't mock what you don't own; tests must
47
- assert behavior and be deterministic. (`40`)
48
+ assert behavior and be deterministic. ([`40`](./40-engineering-practices.md))
48
49
  - **Observability:** structured logs with correlation, low-cardinality metrics, a signal on every
49
- critical path — "what does on-call see at 3am?" (`40`)
50
+ critical path — "what does on-call see at 3am?" ([`40`](./40-engineering-practices.md))
50
51
  - **Dependencies:** a new dependency is a decision — justify it, check its provenance, don't add one
51
- the hooks would gate. (`40`)
52
+ the hooks would gate. ([`40`](./40-engineering-practices.md))
52
53
  - **Collaboration:** challenge the premise, not just the architecture; match the answer to the
53
54
  question; recommend with concrete options, the user decides direction; surface tradeoffs and
54
- blockers in the first line. (`50`)
55
+ blockers in the first line. ([`50`](./50-collaboration.md))
55
56
  - **Reasoning craft:** before writing, parse trajectory (what will the reader do with this in 10
56
57
  minutes; answer the predictable next question now) → shape (choose the deliverable's form before
57
58
  the words; put the answer first) → verify (mark inference as inference; never trade "I confirmed"
@@ -60,7 +61,8 @@ the full treatment; read that file when you **enter its domain** (see "How to lo
60
61
  (delete any sentence true of every project), deletion (cut anything whose removal wouldn't change
61
62
  what the reader does). At most one metaphor, only if it lets the reader predict something new —
62
63
  otherwise name the single axis the decision turns on. As stakes rise, get blunter, not more
63
- hedged. (`50`)
64
+ hedged. ([`50`](./50-collaboration.md))
65
+ <!-- digest:end -->
64
66
 
65
67
  ## What composes this ruleset
66
68
 
@@ -120,10 +122,11 @@ treats these as **context to respect**, not competition:
120
122
  - **Repo-local instructions WIN** over SOMI defaults where they conflict (the project's own
121
123
  `CLAUDE.md` already wins per the top of this file). Follow the repo's conventions for naming, error
122
124
  handling, testing, dependencies, and structure.
123
- - **Read them once, carry them forward.** MAX actions (`/discover`, `/design`, `/refactor` analysis,
124
- and `/plan` on a cold start) distil the relevant conventions into the work item's `brief.md` /
125
- `context.md` so the ECO tier (`/plan`, `/code`) inherits them **without re-reading** — this is part
126
- of the MAX→ECO economy. The SessionStart hook surfaces which files exist.
125
+ - **Read them once, carry them forward.** `cost: high` actions (`/discover`, `/design`,
126
+ `/refactor-design`, and `/plan` on a cold start) distil the relevant conventions into the work item's
127
+ `brief.md` / `context.md` so `cost: medium` (`/plan`, `/code`) inherits them **without
128
+ re-reading** — this is part of the design→execution economy. The SessionStart hook surfaces which
129
+ files exist.
127
130
  - **Do NOT auto-invoke the repo's own agents.** Foreign subagents are unknown-quality and
128
131
  untrusted-by-default; surface that they exist and let the user opt into them. Never call them
129
132
  silently.
@@ -151,9 +154,9 @@ See [docs/HOOKS.md](../docs/HOOKS.md) for the full list and how to extend it.
151
154
 
152
155
  SOMI provides specialized agents in `agents/`. Use them when the work matches their description:
153
156
 
154
- - **`discovery-analyst`** — a new product / greenfield idea needing requirements engineering, competitive research, and high-level design *before* planning (writes `.somi/rd/<slug>/`). Optional and upstream; skip for incremental work with settled requirements. **MAX tier (`opus`).**
155
- - **`designer`** — a feature / user story on an existing codebase that is design-heavy (crosses modules, touches auth/crypto/PII, needs a migration or new contract, or the architecture is open). Compiles the design + the `brief.md` the ECO tier executes against. Use *before* `/plan` when the architecture isn't settled. **MAX tier (`opus`).**
156
- - **`planner`** — before writing non-trivial code, or whenever the user asks "how should we approach X". **ECO tier (`sonnet`)** — consumes the `brief.md` a MAX action left.
157
+ - **`discovery-analyst`** — a new product / greenfield idea needing requirements engineering, competitive research, and high-level design *before* planning (writes `.somi/rd/<slug>/`). Optional and upstream; skip for incremental work with settled requirements. **`cost: high`.**
158
+ - **`designer`** — a feature / user story on an existing codebase that is design-heavy (crosses modules, touches auth/crypto/PII, needs a migration or new contract, or the architecture is open). Compiles the design + the `brief.md` execution runs against. Use *before* `/plan` when the architecture isn't settled. **`cost: high`.**
159
+ - **`planner`** — before writing non-trivial code, or whenever the user asks "how should we approach X". **`cost: medium`** — consumes the `brief.md` a `cost: high` action left.
157
160
  - **`coder`** — to execute against an approved plan or do a constrained implementation task.
158
161
  - **`reviewer`** — before declaring work done; before merging; whenever you want a skeptical second opinion.
159
162
  - **`security-reviewer`** — auth, crypto, input handling, third-party data, file uploads, anything touching secrets.
@@ -173,7 +176,7 @@ Skills under `skills/` are on-demand expert packs. Pull one in when the work cle
173
176
  - Writing/critiquing requirements or design docs (BRD/SRS/FRD/SDD/TDD) → **`requirements-engineering`**
174
177
  - Touching authentication, sessions, input validation, deserialization → **`owasp-defense`**
175
178
  - Designing a module, naming a class, deciding what a function should know → **`solid-principles`**, **`clean-code`**
176
- - Deciding what to test, how to test, whether to mock → **`test-strategy`**
179
+ - Deciding what to test, how to test, whether to mock → **`testing-playbook`**
177
180
  - Adding/changing an HTTP/gRPC endpoint → **`api-design`**
178
181
  - Adding logging, metrics, tracing → **`observability`**
179
182
  - Adding a new external integration or attack surface → **`threat-modeling`**
@@ -0,0 +1,218 @@
1
+ #!/usr/bin/env node
2
+ // scripts/check-links.mjs — fail the build on a relative markdown link whose target doesn't exist.
3
+ //
4
+ // WHY A SEPARATE SCRIPT
5
+ // A ~120-line walker inside a `validate.sh` heredoc would be unreadable and untestable, and the
6
+ // repo already has the pattern of validate.sh invoking a focused Node script (generate-digest.mjs).
7
+ //
8
+ // WHAT IT WALKS
9
+ // Every git-tracked `*.md`, minus `CHANGELOG.md` (generated release history). `.somi/` needs no filter: it is
10
+ // gitignored, so `git ls-files` can never produce a path inside it.
11
+ //
12
+ // FENCED AND INLINE CODE ARE SKIPPED — this is the whole correctness story.
13
+ // A fence-blind walker once reported "7 links across 3 files fail today". **Four of the seven were sample content
14
+ // inside a ```markdown fence** in examples/feature-plan-example.md — displayed source, not links;
15
+ // no renderer resolves them. Marking them wrote a SoMi-internal CI token into the rendered body of
16
+ // the canonical example spec, which ships in the npm tarball and is what users copy. With fence
17
+ // awareness the repo has ZERO non-resolving links. A checker that flags displayed source teaches
18
+ // people to silence it, which is worse than not having it.
19
+ //
20
+ // SCANS WHOLE FILE CONTENT, NOT LINE BY LINE.
21
+ // A per-line scan cannot see a link whose text wraps across lines — and this repo hard-wraps prose
22
+ // at ~100 characters, so `See [the write-discipline contract in the reviewer\nagent](../x.md)` would
23
+ // pass forever. A single-line grep has already paid for exactly this blind spot once
24
+ // (it undercounted a 12-item inventory as 11 because one claim wrapped). Reference-style links
25
+ // (`[text][ref]` + `[ref]: ./path`) are resolved too.
26
+ //
27
+ // THE illustrative-path ESCAPE HATCH, deliberately narrowed.
28
+ // THIRD RESORT, not first. Before reaching for a marker: (1) if the text need not be a link, make
29
+ // it an inline code span (that is how the real `examples/sample-consumer/` case was
30
+ // resolved), and a non-link cannot rot; (2) if it is displayed sample source, put it in a fence, which
31
+ // this walker now skips. Mark only when the link must stay a live link and its target genuinely
32
+ // lives outside this repo.
33
+ //
34
+ // The marker sits on the SAME LINE, immediately before the link:
35
+ //
36
+ // <!-- illustrative-path -->[text](./path.md)
37
+ //
38
+ // Two constraints keep it from becoming a blanket, both added after review:
39
+ // 1. **Scoped to `examples/`.** A marker anywhere else FAILS rather than exempts. Silencing a
40
+ // genuinely broken link would otherwise be a 26-character insertion mid-sentence — the least
41
+ // noticeable edit shape in a prose diff.
42
+ // 2. **The exemption inventory prints on success**, so growth from 0 to 40 is a visible CI
43
+ // artifact rather than something you'd have to diff markdown by eye to notice.
44
+ // A marker on a link that DOES resolve also fails: an escape hatch that cannot detect its own
45
+ // obsolescence becomes permanent. A separate allowlist file was rejected — it drifts out of sync
46
+ // with the links it covers, the same anti-pattern rejected for the digest copies.
47
+ //
48
+ // KNOWN BOUNDARY (asserted by negative tests, not left to assumption): HTML `<a href>` is not
49
+ // checked, directories satisfy existence, and `#fragment` targets are not validated — only the file
50
+ // path before the fragment.
51
+
52
+ import fs from 'node:fs';
53
+ import path from 'node:path';
54
+ import { execFileSync } from 'node:child_process';
55
+
56
+ const MARKER = '<!-- illustrative-path -->';
57
+ const MARKER_SCOPE = 'examples/';
58
+ // Inline link. `[^)\s]+` for the destination, optional `"title"`. Applied to fence-stripped content
59
+ // with the `s` flag absent — link text may span lines, so `[^\]]*` is allowed to match newlines.
60
+ const INLINE_RE = /\[[^\]]*\]\(\s*<?([^)>\s]+)>?(?:\s+"[^"]*")?\s*\)/g;
61
+ // Reference-style usage `[text][ref]` (and collapsed `[ref][]`), plus the definition `[ref]: target`.
62
+ const REF_USE_RE = /\[([^\]]*)\]\[([^\]]*)\]/g;
63
+ const REF_DEF_RE = /^[ \t]{0,3}\[([^\]]+)\]:[ \t]*<?([^>\s]+)>?/gm;
64
+
65
+ function trackedMarkdown() {
66
+ const out = execFileSync('git', ['ls-files', '*.md'], { encoding: 'utf8', maxBuffer: 10 * 1024 * 1024 });
67
+ return out.split('\n').filter(Boolean).filter((f) => f !== 'CHANGELOG.md');
68
+ }
69
+
70
+ // Replace every fenced block and inline code span with equal-length blanks, preserving newlines and
71
+ // byte offsets so line numbers stay accurate. Blanking rather than deleting is what lets the caller
72
+ // keep using indexes into the original content.
73
+ function blankCode(src, file) {
74
+ // Fences are handled with an explicit line-state pass, NOT a regex. A regex of the shape
75
+ // /^```[\s\S]*?(^```$|$)/gm looks right and is not: with the `m` flag the `|$` fallback matches
76
+ // end-of-LINE, so an unterminated-looking block collapses to its opening line and every link
77
+ // below it is treated as prose. That bug is what let four fenced sample links read as real.
78
+ const lines = src.split('\n');
79
+ let inFence = false;
80
+ let fenceChar = null;
81
+ let fenceLen = 0;
82
+ const blanked = lines.map((line) => {
83
+ // Indent is `[ \t]*`, not `[ \t]{0,3}`. CommonMark caps a fence at 3 spaces relative to its
84
+ // CONTAINING BLOCK — inside a list item that is the item's content column, so a fence indented
85
+ // 4+ spaces is legal and common. Tracking list context to compute the relative cap is not worth
86
+ // it here; accepting any indent means a 4-space *indented code block* is also skipped, which is
87
+ // the safe direction. Be precise about the cost: it is not only displayed source. Two unrelated
88
+ // stray fence-looking lines can pair up and silently swallow the real prose between them —
89
+ // demonstrated, a planted dead link between two stray indented ``` lines is missed. Accepted
90
+ // because the other direction is worse: flagging displayed source costs a broken illustration,
91
+ // which is exactly what an earlier version of this walker did. Zero indented fences in the corpus today.
92
+ const open = line.match(/^[ \t]*(`{3,}|~{3,})/);
93
+ if (open) {
94
+ const [char, len] = [open[1][0], open[1].length];
95
+ if (!inFence) {
96
+ inFence = true;
97
+ fenceChar = char;
98
+ fenceLen = len; // RUN LENGTH matters: CommonMark requires the closer be at least as long as
99
+ // the opener, so a ``` inside a ```` block does NOT close it. Comparing only the character
100
+ // let an inner example fence terminate its outer block, and everything between the inner
101
+ // pair then read as prose.
102
+ return ' '.repeat(line.length);
103
+ }
104
+ if (char === fenceChar && len >= fenceLen) {
105
+ inFence = false;
106
+ fenceChar = null;
107
+ fenceLen = 0;
108
+ return ' '.repeat(line.length);
109
+ }
110
+ }
111
+ return inFence ? ' '.repeat(line.length) : line;
112
+ });
113
+ if (inFence) {
114
+ // An unclosed fence blanks everything to EOF — safe (nothing is falsely flagged) but silent,
115
+ // so links after it are never checked. Surfaced rather than swallowed.
116
+ console.error(`check-links: WARNING unclosed code fence — links after it are unchecked`);
117
+ }
118
+ // Inline code spans, after fences so a backtick inside a fence can't confuse the pairing.
119
+ return blanked.join('\n').replace(/`+[^`\n]*`+/g, (span) => span.replace(/[^\n]/g, ' '));
120
+ }
121
+
122
+ function isExternal(t) {
123
+ return /^(https?:\/\/|mailto:)/i.test(t) || t.startsWith('#');
124
+ }
125
+
126
+ function lineOf(src, index) {
127
+ return src.slice(0, index).split('\n').length;
128
+ }
129
+
130
+ function main() {
131
+ const dead = [];
132
+ const stale = [];
133
+ const misplaced = [];
134
+ let exemptions = 0;
135
+ let checked = 0;
136
+
137
+ for (const file of trackedMarkdown()) {
138
+ const dir = path.dirname(file);
139
+ let raw;
140
+ try {
141
+ raw = fs.readFileSync(file, 'utf8');
142
+ } catch (err) {
143
+ // A tracked file missing from the worktree is a real condition (mid-rebase, partial
144
+ // checkout). Diagnose it rather than dying on an ENOENT stack.
145
+ dead.push(`${file}: unreadable (${err.code || err.message})`);
146
+ continue;
147
+ }
148
+ const src = blankCode(raw, file);
149
+
150
+ // Reference definitions, harvested from the same blanked content so a definition inside a fence
151
+ // is not honoured.
152
+ const refs = new Map();
153
+ REF_DEF_RE.lastIndex = 0;
154
+ let d;
155
+ while ((d = REF_DEF_RE.exec(src))) refs.set(d[1].toLowerCase(), d[2]);
156
+
157
+ const found = [];
158
+ INLINE_RE.lastIndex = 0;
159
+ let m;
160
+ while ((m = INLINE_RE.exec(src))) found.push({ target: m[1], index: m.index });
161
+ REF_USE_RE.lastIndex = 0;
162
+ while ((m = REF_USE_RE.exec(src))) {
163
+ const key = (m[2] || m[1]).toLowerCase();
164
+ if (refs.has(key)) found.push({ target: refs.get(key), index: m.index });
165
+ }
166
+
167
+ for (const { target: rawTarget, index } of found) {
168
+ if (isExternal(rawTarget)) continue;
169
+ const target = rawTarget.split('#')[0];
170
+ if (target === '') continue;
171
+
172
+ const lineStart = src.lastIndexOf('\n', index) + 1;
173
+ const marked = src.slice(lineStart, index).trimEnd().endsWith(MARKER);
174
+ const resolves = fs.existsSync(path.resolve(dir, target));
175
+ const where = `${file}:${lineOf(src, index)} -> ${rawTarget}`;
176
+
177
+ if (marked && !file.startsWith(MARKER_SCOPE)) {
178
+ misplaced.push(where);
179
+ } else if (!resolves && !marked) {
180
+ dead.push(where);
181
+ } else if (resolves && marked) {
182
+ stale.push(where);
183
+ } else if (marked) {
184
+ exemptions++;
185
+ } else {
186
+ checked++;
187
+ }
188
+ }
189
+ }
190
+
191
+ let failed = false;
192
+ if (dead.length) {
193
+ console.error('DEAD RELATIVE LINK(S):');
194
+ for (const x of dead) console.error(` ${x}`);
195
+ console.error(`\nIf a link is correct for the context an example illustrates but does not resolve\n` +
196
+ `here, mark it inline on the SAME line, in ${MARKER_SCOPE}: ${MARKER}[text](path)`);
197
+ failed = true;
198
+ }
199
+ if (stale.length) {
200
+ console.error('STALE illustrative-path MARKER(S) — the target now resolves, drop the marker:');
201
+ for (const x of stale) console.error(` ${x}`);
202
+ failed = true;
203
+ }
204
+ if (misplaced.length) {
205
+ console.error(`illustrative-path MARKER OUTSIDE ${MARKER_SCOPE} — the hatch is scoped to examples:`);
206
+ for (const x of misplaced) console.error(` ${x}`);
207
+ failed = true;
208
+ }
209
+ if (failed) {
210
+ process.exitCode = 1;
211
+ return;
212
+ }
213
+ console.log(
214
+ `check-links: ${checked} relative link(s) resolve; ${exemptions} illustrative-path exemption(s)`
215
+ );
216
+ }
217
+
218
+ main();
@@ -0,0 +1,149 @@
1
+ #!/usr/bin/env node
2
+ // scripts/check-session-artefacts.mjs — fail the build when shipped code or prose points at the
3
+ // maintainers' gitignored `.somi/` planning folder.
4
+ //
5
+ // A comment that says "see the plan's third decision" or "the review finding numbered 28" is a
6
+ // dangling pointer for everyone who clones the repo: the plan and the ledger are not shipped, so
7
+ // the reader cannot resolve it. State the reasoning in words instead, or delete the comment.
8
+ //
9
+ // WHAT COUNTS
10
+ // A reference that only resolves inside `.somi/`: a finding id with two or more digits, a decision
11
+ // tag, an iteration or phase number from a plan, a `decisions.md#` anchor, a planning-slug name.
12
+ // Single-digit finding ids (the CLI usage examples) are domain text and pass.
13
+ //
14
+ // "phase" and "work item" are deliberately NOT banned as words — they are SoMi product vocabulary
15
+ // (a pipeline stage; a planning unit users create). Only a numbered phase/iteration, or the phrase
16
+ // "this work item" in a code comment (which can only mean the maintainers' own planning item),
17
+ // counts.
18
+ //
19
+ // WHERE
20
+ // - code (`.mjs`, `.sh`) under hooks/ and scripts/: comment text only, so a string literal that
21
+ // legitimately mentions a decision tag is not flagged.
22
+ // - code under tests/scripts/ too (comments only, as above).
23
+ // - markdown under agents/, commands/, skills/, docs/, rules/, templates/: every line, with a narrower pattern, because
24
+ // those files teach the plan format and use `D1:` / `phase 1, iteration 1` as sample content.
25
+ //
26
+ // EXCLUSIONS are explicit and few (EXCLUDED below). To gate another tree, add one SCOPES row.
27
+
28
+ import fs from 'node:fs';
29
+ import path from 'node:path';
30
+
31
+ const FINDING = String.raw`\bF-?\d{2,}\b`;
32
+ const DECISION_ANCHOR = String.raw`decisions\.md#`;
33
+ const PLAN_SLUG = String.raw`node-runtime-port|somi-3-0-rework`;
34
+
35
+ const CODE_PATTERN = new RegExp(
36
+ [
37
+ FINDING,
38
+ String.raw`\bD\d+[a-z]?\b`,
39
+ DECISION_ANCHOR,
40
+ String.raw`\b[Ii]teration \d`,
41
+ String.raw`\b[Pp]hase[ -]\d`,
42
+ String.raw`\bphases/\d`,
43
+ String.raw`\b\d\.\d+[a-z]?(?:'s)? pass \d`,
44
+ String.raw`\b\d\.\d{1,2}[a-z]?'s\b`,
45
+ String.raw`\b\d\.\d{1,2}[a-z]?[/+-]\d\.\d{1,2}\b`,
46
+ String.raw`\(\d\.\d{1,2}[a-z]?[,)]`,
47
+ String.raw`\b(?:this|that) iteration\b`,
48
+ String.raw`\breviewer-blessed\b`,
49
+ // A pointer ("see the diary") sends the reader into the planning folder; the diary and phase
50
+ // files are also product artifacts SoMi's own code describes, so bare mentions are allowed.
51
+ String.raw`\bsee (?:the )?(?:diary|phase file)\b`,
52
+ String.raw`\b(?:spec|context|brief)\.md §`,
53
+ String.raw`\bthis work[ -]item\b`,
54
+ PLAN_SLUG,
55
+ ].join('|'),
56
+ );
57
+
58
+ const MARKDOWN_PATTERN = new RegExp(
59
+ [
60
+ FINDING,
61
+ String.raw`\(D\d+[a-z]?\)`,
62
+ String.raw`\bD\d+[a-z]?'s\b`,
63
+ DECISION_ANCHOR,
64
+ PLAN_SLUG,
65
+ ].join('|'),
66
+ );
67
+
68
+ // One row per gated tree. Adding another tree is a one-line change here. Only `.md` is read for
69
+ // markdown trees, so `templates/*.tmpl` (which carry sample decision ids for users to copy) is not.
70
+ const SCOPES = [
71
+ { dir: 'hooks', kind: 'code' },
72
+ { dir: 'scripts', kind: 'code' },
73
+ { dir: 'agents', kind: 'markdown' },
74
+ { dir: 'commands', kind: 'markdown' },
75
+ { dir: 'skills', kind: 'markdown' },
76
+ { dir: 'tests/scripts', kind: 'code' },
77
+ { dir: 'docs', kind: 'markdown' },
78
+ { dir: 'rules', kind: 'markdown' },
79
+ { dir: 'templates', kind: 'markdown' },
80
+ ];
81
+
82
+ // Repo-relative paths (file or directory prefix). The checker holds its own pattern definitions.
83
+ const EXCLUDED = [
84
+ 'scripts/check-session-artefacts.mjs',
85
+ 'tests/evals/results',
86
+ 'CHANGELOG.md',
87
+ ];
88
+
89
+ const CODE_EXT = new Set(['.mjs', '.sh']);
90
+
91
+ function isExcluded(rel) {
92
+ return EXCLUDED.some((e) => rel === e || rel.startsWith(`${e}/`));
93
+ }
94
+
95
+ function* walk(root, rel) {
96
+ const abs = path.join(root, rel);
97
+ if (!fs.existsSync(abs)) return;
98
+ for (const entry of fs.readdirSync(abs, { withFileTypes: true })) {
99
+ if (entry.name === 'node_modules') continue;
100
+ const child = path.posix.join(rel, entry.name);
101
+ if (isExcluded(child)) continue;
102
+ if (entry.isDirectory()) yield* walk(root, child);
103
+ else if (entry.isFile()) yield child;
104
+ }
105
+ }
106
+
107
+ function commentText(line, ext) {
108
+ const trimmed = line.trim();
109
+ if (ext === '.sh') {
110
+ if (trimmed.startsWith('#!')) return null;
111
+ if (trimmed.startsWith('#')) return trimmed;
112
+ const at = line.search(/\s#\s/);
113
+ return at === -1 ? null : line.slice(at);
114
+ }
115
+ if (/^(\/\/|\/\*|\*)/.test(trimmed)) return trimmed;
116
+ const at = line.search(/\s\/\/\s/);
117
+ return at === -1 ? null : line.slice(at);
118
+ }
119
+
120
+ export function findArtefacts(root) {
121
+ const hits = [];
122
+ for (const { dir, kind } of SCOPES) {
123
+ for (const rel of walk(root, dir)) {
124
+ const ext = path.extname(rel);
125
+ if (kind === 'code' && !CODE_EXT.has(ext)) continue;
126
+ if (kind === 'markdown' && ext !== '.md') continue;
127
+ const lines = fs.readFileSync(path.join(root, rel), 'utf8').split('\n');
128
+ lines.forEach((line, i) => {
129
+ const text = kind === 'code' ? commentText(line, ext) : line;
130
+ const pattern = kind === 'code' ? CODE_PATTERN : MARKDOWN_PATTERN;
131
+ if (text !== null && pattern.test(text)) hits.push(`${rel}:${i + 1}: ${line.trim()}`);
132
+ });
133
+ }
134
+ }
135
+ return hits;
136
+ }
137
+
138
+ if (import.meta.url === `file://${process.argv[1]}`) {
139
+ const rootIdx = process.argv.indexOf('--root');
140
+ const root = rootIdx === -1 ? process.cwd() : path.resolve(process.argv[rootIdx + 1]);
141
+ const hits = findArtefacts(root);
142
+ if (hits.length > 0) {
143
+ console.error('SESSION-ARTEFACT REFERENCES (point into the gitignored .somi/ folder):');
144
+ for (const h of hits) console.error(` ${h}`);
145
+ console.error(`${hits.length} line(s). Say the reason in plain words, or delete the comment.`);
146
+ process.exit(1);
147
+ }
148
+ console.log(' ok: no session-artefact references in gated paths');
149
+ }
@@ -0,0 +1,137 @@
1
+ #!/usr/bin/env node
2
+ // scripts/check-size-budget.mjs -- fail the build when a tracked file outgrows its line budget.
3
+ //
4
+ // BUDGETS (lines; one table, BUDGETS below)
5
+ // prompt files agents/*.md, commands/*.md, skills/**/*.md 300 (loaded into a model's context
6
+ // on every run, so size is cost)
7
+ // .mjs any tracked file except tests/evals/results/ 500
8
+ // .sh any tracked file 800
9
+ // Docs are not gated.
10
+ //
11
+ // Only tracked files count (`git ls-files`), so untracked scratch never trips the gate.
12
+ //
13
+ // THE LEDGER: scripts/size-budget-overrides.json
14
+ // A file already over budget is recorded there, one entry each, shaped
15
+ // `{file, budget, current_size, source, at, reason}` (the same audit idiom as the loop's
16
+ // `cap_overrides`). The ledger is tracked so an exemption is reviewable in a diff.
17
+ // - An un-ledgered file over budget FAILS.
18
+ // - A ledgered file larger than its recorded `current_size` FAILS: the entry exempts the file
19
+ // as it is, not as it may become. Shrinking is always fine. Growth means updating the entry
20
+ // with a reason a reviewer can challenge.
21
+ // - A ledgered file now within budget WARNS (does not fail): delete its entry.
22
+ // - A malformed ledger fails loudly (exit 2) rather than being read leniently.
23
+ //
24
+ // GOVERNANCE
25
+ // - Who may add an entry: anyone introducing or materially touching an over-budget file, with a
26
+ // concrete `reason` and a `source` (the commit that introduced or last touched it, from
27
+ // `git log -1 --format=%h -- <file>`). Never a blanket exemption without attribution.
28
+ // - Entries are revisited at every /release-readiness pass.
29
+ // - The goal is an empty ledger: shrink or split a file, then remove its entry.
30
+ //
31
+ // Usage: node scripts/check-size-budget.mjs [--root <dir>]
32
+
33
+ import fs from 'node:fs';
34
+ import path from 'node:path';
35
+ import { execFileSync } from 'node:child_process';
36
+
37
+ const LEDGER = 'scripts/size-budget-overrides.json';
38
+ const NOT_GATED = ['tests/evals/results/'];
39
+
40
+ // First matching row wins. `test` receives the repo-relative posix path.
41
+ const BUDGETS = [
42
+ { kind: 'prompt', limit: 300, test: (f) => /^(agents|commands)\/[^/]+\.md$/.test(f) || /^skills\/.+\.md$/.test(f) },
43
+ { kind: 'mjs', limit: 500, test: (f) => f.endsWith('.mjs') },
44
+ { kind: 'sh', limit: 800, test: (f) => f.endsWith('.sh') },
45
+ ];
46
+
47
+ const ENTRY_FIELDS = { file: 'string', budget: 'number', current_size: 'number', source: 'string', at: 'string', reason: 'string' };
48
+
49
+ function fatal(msg) {
50
+ console.error(`size-budget: ${msg}`);
51
+ process.exit(2);
52
+ }
53
+
54
+ function budgetFor(file) {
55
+ if (NOT_GATED.some((p) => file.startsWith(p))) return null;
56
+ return BUDGETS.find((b) => b.test(file)) || null;
57
+ }
58
+
59
+ function lineCount(abs) {
60
+ const text = fs.readFileSync(abs, 'utf8');
61
+ if (text === '') return 0;
62
+ return text.split('\n').length - (text.endsWith('\n') ? 1 : 0);
63
+ }
64
+
65
+ function trackedFiles(root) {
66
+ try {
67
+ const out = execFileSync('git', ['-C', root, 'ls-files', '-z'], { encoding: 'utf8', maxBuffer: 64 * 1024 * 1024 });
68
+ return out.split('\0').filter(Boolean);
69
+ } catch (e) {
70
+ return fatal(`cannot enumerate tracked files under ${root}: ${e.message}`);
71
+ }
72
+ }
73
+
74
+ export function loadLedger(root) {
75
+ const abs = path.join(root, LEDGER);
76
+ if (!fs.existsSync(abs)) return new Map();
77
+ let data;
78
+ try {
79
+ data = JSON.parse(fs.readFileSync(abs, 'utf8'));
80
+ } catch (e) {
81
+ return fatal(`${LEDGER} is not valid JSON: ${e.message}`);
82
+ }
83
+ if (!Array.isArray(data)) return fatal(`${LEDGER} must be a JSON array of entries`);
84
+ const byFile = new Map();
85
+ data.forEach((entry, i) => {
86
+ if (entry === null || typeof entry !== 'object' || Array.isArray(entry)) fatal(`${LEDGER}[${i}] is not an object`);
87
+ for (const [field, type] of Object.entries(ENTRY_FIELDS)) {
88
+ const v = entry[field];
89
+ const ok = typeof v === type && (type !== 'string' || v.trim() !== '') && (type !== 'number' || (Number.isInteger(v) && v > 0));
90
+ if (!ok) fatal(`${LEDGER}[${i}] needs a ${type === 'number' ? 'positive integer' : 'non-empty string'} "${field}"`);
91
+ }
92
+ if (byFile.has(entry.file)) fatal(`${LEDGER} lists ${entry.file} twice`);
93
+ byFile.set(entry.file, entry);
94
+ });
95
+ return byFile;
96
+ }
97
+
98
+ export function checkBudgets(root) {
99
+ const ledger = loadLedger(root);
100
+ const failures = [];
101
+ const warnings = [];
102
+ const tracked = new Set(trackedFiles(root));
103
+
104
+ for (const file of [...tracked].sort()) {
105
+ const budget = budgetFor(file);
106
+ if (!budget) continue;
107
+ const abs = path.join(root, file);
108
+ if (!fs.existsSync(abs)) continue;
109
+ const size = lineCount(abs);
110
+ const entry = ledger.get(file);
111
+ if (size <= budget.limit) {
112
+ if (entry) warnings.push(`${file} is ${size} lines, within its ${budget.limit} budget: remove its ledger entry`);
113
+ } else if (!entry) {
114
+ failures.push(`${file}: ${size} lines exceeds the ${budget.limit}-line ${budget.kind} budget and is not in ${LEDGER}`);
115
+ } else if (size > entry.current_size) {
116
+ failures.push(`${file}: ${size} lines grew past its ledgered ${entry.current_size}; shrink it, or update the entry with a reason`);
117
+ }
118
+ }
119
+ for (const file of ledger.keys()) {
120
+ if (!tracked.has(file)) warnings.push(`${file} is in the ledger but is not a tracked file: remove its entry`);
121
+ }
122
+ return { failures, warnings, ledgered: ledger.size };
123
+ }
124
+
125
+ if (import.meta.url === `file://${process.argv[1]}`) {
126
+ const rootIdx = process.argv.indexOf('--root');
127
+ const root = rootIdx === -1 ? process.cwd() : path.resolve(process.argv[rootIdx + 1]);
128
+ const { failures, warnings, ledgered } = checkBudgets(root);
129
+ for (const w of warnings) console.warn(` warn: ${w}`);
130
+ if (failures.length > 0) {
131
+ console.error('FILE-SIZE BUDGET EXCEEDED:');
132
+ for (const f of failures) console.error(` ${f}`);
133
+ console.error(`${failures.length} file(s). Shrink the file; see the header of scripts/check-size-budget.mjs for the ledger rules.`);
134
+ process.exit(1);
135
+ }
136
+ console.log(` ok: every tracked file is within its size budget (${ledgered} ledgered)`);
137
+ }