@skathio/somi 3.1.0 → 4.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 (148) hide show
  1. package/.claude/settings.json +13 -0
  2. package/.claude-plugin/marketplace.json +2 -2
  3. package/.claude-plugin/plugin.json +1 -1
  4. package/.copilot-extension/extension.json +1 -1
  5. package/.copilot-extension/marketplace.json +2 -2
  6. package/README.md +28 -23
  7. package/VERSION +1 -1
  8. package/agents/{architecture-reviewer.md → somi-architecture-reviewer.md} +10 -11
  9. package/agents/{atlas.md → somi-atlas.md} +3 -5
  10. package/agents/{coder.md → somi-coder.md} +29 -26
  11. package/agents/{designer.md → somi-designer.md} +9 -11
  12. package/agents/{discovery-analyst.md → somi-discovery-analyst.md} +7 -9
  13. package/agents/{impact.md → somi-impact.md} +6 -8
  14. package/agents/{incident.md → somi-incident.md} +2 -4
  15. package/agents/{plan-reviewer.md → somi-plan-reviewer.md} +9 -11
  16. package/agents/{planner.md → somi-planner.md} +19 -27
  17. package/agents/{pr.md → somi-pr.md} +2 -4
  18. package/agents/{refactor-designer.md → somi-refactor-designer.md} +14 -15
  19. package/agents/{refactorer.md → somi-refactorer.md} +14 -15
  20. package/agents/{reviewer.md → somi-reviewer.md} +8 -7
  21. package/agents/{sdlc-reviewer.md → somi-sdlc-reviewer.md} +8 -10
  22. package/agents/{security-reviewer.md → somi-security-reviewer.md} +8 -8
  23. package/agents/{test-strategist.md → somi-test-strategist.md} +4 -6
  24. package/agents/somi.md +27 -14
  25. package/commands/adopt.md +9 -10
  26. package/commands/architecture-review.md +4 -5
  27. package/commands/atlas.md +3 -4
  28. package/commands/code-loop.md +38 -14
  29. package/commands/code-parallel.md +4 -4
  30. package/commands/code.md +24 -15
  31. package/commands/debug.md +8 -9
  32. package/commands/design.md +14 -15
  33. package/commands/discover.md +11 -12
  34. package/commands/impact.md +2 -3
  35. package/commands/incident.md +3 -4
  36. package/commands/plan-loop.md +16 -12
  37. package/commands/plan.md +15 -16
  38. package/commands/pr.md +2 -3
  39. package/commands/refactor-design.md +10 -11
  40. package/commands/refactor.md +7 -8
  41. package/commands/release-readiness.md +6 -7
  42. package/commands/review-panel.md +24 -23
  43. package/commands/review.md +14 -14
  44. package/commands/security-review.md +8 -7
  45. package/commands/ship-loop.md +107 -28
  46. package/commands/ship.md +6 -6
  47. package/commands/somi-config.md +131 -0
  48. package/commands/test-strategy.md +3 -4
  49. package/commands/upgrade.md +4 -5
  50. package/examples/code-review-example.md +1 -1
  51. package/examples/discovery-example.md +1 -1
  52. package/examples/feature-plan-example.md +2 -2
  53. package/hooks/hooks.json +14 -1
  54. package/hooks/lib/common.mjs +64 -1
  55. package/hooks/post-tool/audit-log.mjs +3 -2
  56. package/hooks/pre-tool/block-secret-writes.mjs +12 -11
  57. package/hooks/pre-tool/guard-cost-lowering.mjs +177 -0
  58. package/hooks/pre-tool/guard-protected-paths.mjs +13 -3
  59. package/hooks/session-start/detect-repo-instructions.mjs +27 -2
  60. package/hooks/session-start/ensure-default-config.mjs +121 -0
  61. package/package.json +1 -1
  62. package/rules/00-priorities.md +1 -1
  63. package/rules/30-security-owasp.md +1 -1
  64. package/rules/50-collaboration.md +9 -6
  65. package/rules/CLAUDE.md +11 -10
  66. package/scripts/lib/agent-info.mjs +85 -0
  67. package/scripts/lib/agent-registry.mjs +92 -0
  68. package/scripts/lib/cost-ceiling.mjs +175 -171
  69. package/scripts/lib/cost-config-edit.mjs +102 -0
  70. package/scripts/lib/cost-config.mjs +64 -0
  71. package/scripts/lib/cost-defaults.mjs +51 -0
  72. package/scripts/lib/cost-lowering.mjs +89 -0
  73. package/scripts/lib/cost-model.mjs +37 -22
  74. package/scripts/lib/dispatch-resolver.mjs +68 -50
  75. package/scripts/lib/loop-diff.mjs +96 -0
  76. package/scripts/lib/loop-dispatch.mjs +19 -0
  77. package/scripts/lib/loop-review.mjs +52 -0
  78. package/scripts/lib/run-budget.mjs +28 -0
  79. package/scripts/lib/size-tier.mjs +184 -0
  80. package/scripts/lib/tier-record.mjs +82 -0
  81. package/scripts/size-budget-overrides.json +7 -15
  82. package/scripts/somi-config.mjs +358 -0
  83. package/scripts/somi-dispatch.mjs +1 -1
  84. package/scripts/somi-loop.mjs +71 -96
  85. package/scripts/somi-mcp.mjs +135 -14
  86. package/scripts/somi-tier.mjs +393 -0
  87. package/scripts/validate.sh +37 -215
  88. package/skills/api-design/SKILL.md +1 -1
  89. package/skills/clean-code/SKILL.md +1 -1
  90. package/skills/market-research/SKILL.md +2 -2
  91. package/skills/owasp-defense/SKILL.md +2 -2
  92. package/skills/plan-review/SKILL.md +5 -1
  93. package/skills/reasoning-craft/SKILL.md +1 -1
  94. package/skills/requirements-engineering/SKILL.md +3 -3
  95. package/skills/solid-principles/SKILL.md +1 -1
  96. package/skills/somi-dispatch/SKILL.md +116 -87
  97. package/skills/somi-routing/SKILL.md +88 -1
  98. package/skills/testing-playbook/SKILL.md +2 -2
  99. package/skills/threat-modeling/SKILL.md +3 -3
  100. package/templates/BRIEF.md.tmpl +2 -2
  101. package/templates/DESIGN.md.tmpl +1 -1
  102. package/templates/DOD.md.tmpl +2 -2
  103. package/templates/PHASE.md.tmpl +2 -2
  104. package/templates/RCA.md.tmpl +1 -1
  105. package/templates/REVIEW.md.tmpl +3 -2
  106. package/templates/SDD.md.tmpl +1 -1
  107. package/templates/SPEC.md.tmpl +1 -1
  108. package/templates/TDD.md.tmpl +1 -1
  109. package/tests/hooks/cases/block-secret-writes.json +130 -17
  110. package/tests/hooks/cases/detect-repo-instructions.json +22 -1
  111. package/tests/hooks/cases/guard-protected-paths.json +175 -25
  112. package/tests/scripts/agent-model-frontmatter.sh +38 -0
  113. package/tests/scripts/agent-names.sh +77 -0
  114. package/tests/scripts/check-frontmatter.sh +1 -1
  115. package/tests/scripts/checkpoint-gate.sh +44 -3
  116. package/tests/scripts/convergence-runner.sh +10 -6
  117. package/tests/scripts/cost-ceiling.sh +127 -215
  118. package/tests/scripts/cost-defaults.sh +128 -0
  119. package/tests/scripts/cost-hardcap.sh +329 -0
  120. package/tests/scripts/cost-lowering.sh +261 -0
  121. package/tests/scripts/cost-model.sh +18 -14
  122. package/tests/scripts/dispatch-guard.sh +7 -7
  123. package/tests/scripts/dispatch-line-gate.sh +61 -0
  124. package/tests/scripts/dispatch-reference-gate.sh +13 -13
  125. package/tests/scripts/ensure-default-config.sh +162 -0
  126. package/tests/scripts/eval-runner.sh +9 -9
  127. package/tests/scripts/evals-packaging.sh +127 -20
  128. package/tests/scripts/fixtures/size-tier-cases.json +87 -0
  129. package/tests/scripts/goldens/loop-state-done.json +1 -1
  130. package/tests/scripts/goldens/somi-loop.json +3 -3
  131. package/tests/scripts/lib/agent-registry-tests.mjs +95 -0
  132. package/tests/scripts/lib/brief-only-guard.mjs +27 -0
  133. package/tests/scripts/lib/checkpoint-gate.mjs +40 -3
  134. package/tests/scripts/lib/dispatch-reference-gate.mjs +5 -5
  135. package/tests/scripts/lib/retirement-gate.mjs +7 -2
  136. package/tests/scripts/lib/ship-loop-sizing-guard.mjs +52 -0
  137. package/tests/scripts/lib/size-tier-drift.mjs +74 -0
  138. package/tests/scripts/lib/somi-mcp-config-tests.mjs +92 -0
  139. package/tests/scripts/lib/somi-mcp-tests.mjs +80 -25
  140. package/tests/scripts/lib/somi-mcp-tier-tests.mjs +64 -0
  141. package/tests/scripts/retirement-gate.sh +19 -0
  142. package/tests/scripts/review-panel-seats.sh +2 -2
  143. package/tests/scripts/run.sh +95 -0
  144. package/tests/scripts/size-tier.sh +562 -0
  145. package/tests/scripts/somi-agent-dispatch-contract.sh +20 -11
  146. package/tests/scripts/somi-config.sh +281 -0
  147. package/tests/scripts/somi-dispatch.sh +194 -95
  148. package/tests/scripts/somi-mcp.sh +2 -0
@@ -2,7 +2,7 @@
2
2
  // somi-mcp.mjs — a zero-dependency stdio MCP server bundling scripts/lib/dispatch-resolver.mjs's
3
3
  // resolveDispatch() as the `somi_resolve` tool, plus a command-procedure text reader as the
4
4
  // `somi_command` tool, a skill-text reader as the `somi_skill` tool and an agent-instructions
5
- // reader as the `somi_agent` tool. Both Claude Code and
5
+ // reader as the `somi_agent` tool, and the read-only `somi_agent_info` lookup. Both Claude Code and
6
6
  // Copilot CLI launch a plugin's bundled MCP server with its root already expanded
7
7
  // (${CLAUDE_PLUGIN_ROOT} / ${PLUGIN_ROOT}), so a prompt calling these tools never needs to know
8
8
  // where SoMi is installed — unlike scripts/somi-dispatch.mjs, which a prompt can only shell out to
@@ -24,6 +24,7 @@
24
24
  // error with `id: null` — the server keeps running; one bad line must never kill in-flight calls.
25
25
 
26
26
  import { createInterface } from 'node:readline';
27
+ import { spawnSync } from 'node:child_process';
27
28
  import fs from 'node:fs';
28
29
  import path from 'node:path';
29
30
  import { fileURLToPath } from 'node:url';
@@ -35,6 +36,8 @@ import {
35
36
  EXIT_UNKNOWN_AGENT,
36
37
  } from './lib/dispatch-resolver.mjs';
37
38
  import { resolveProjectRoot } from './lib/mcp-project-root.mjs';
39
+ import { AGENT_INFO_TOOL, agentInfo } from './lib/agent-info.mjs';
40
+ import { SIGNAL_IDS } from './lib/size-tier.mjs';
38
41
 
39
42
  const PROG = 'somi-dispatch'; // shared identity with the CLI: this is the SAME resolver speaking.
40
43
 
@@ -113,23 +116,25 @@ const TOOLS = [
113
116
  {
114
117
  name: 'somi_resolve',
115
118
  description:
116
- "Resolve one agent's dispatch tier and model against the current session ceiling — the " +
119
+ "Resolve one agent's dispatch tier and model: its cost.agents override from .somi/config.json, " +
120
+ 'else the current session ceiling itself (a hard cap) — the ' +
117
121
  'MCP-native equivalent of `node scripts/somi-dispatch.mjs resolve`. Same validation, same ' +
118
- 'four-code failure family (64 usage / 65 unknown agent / 66 malformed cost: declaration / ' +
122
+ 'four-code failure family (64 usage / 65 unknown agent / 66 no default tier / ' +
119
123
  '67 project environment failure — including "no project root could be established": no ' +
120
124
  'CLAUDE_PROJECT_DIR, no usable MCP roots, and no project_dir given), reported in the tool ' +
121
125
  'result text on failure.',
122
126
  inputSchema: {
123
127
  type: 'object',
124
128
  properties: {
125
- agent: { type: 'string', description: 'agent name, e.g. "coder" (matches ^[a-z][a-z0-9-]*$)' },
129
+ agent: { type: 'string', description: 'agent name, e.g. "somi-coder" (matches ^[a-z][a-z0-9-]*$)' },
126
130
  host: { type: 'string', description: 'e.g. "claude-code" or "copilot"; defaults to "claude-code"' },
127
131
  ceiling: {
128
132
  type: 'string',
129
133
  description:
130
- 'one of low|medium|high. Sets and SAVES the session ceiling for every later dispatch ' +
131
- 'in this project, not just this call — omit it unless the user actually asked to ' +
132
- 'change the ceiling.',
134
+ 'one of low|medium|high. Used for this call and remembered as an explicitly set ' +
135
+ 'value, but cost.ceiling in .somi/config.json is read live and outranks it, so it ' +
136
+ 'does not last where the config sets one — omit it unless the user actually asked ' +
137
+ 'to change the ceiling.',
133
138
  },
134
139
  project_dir: {
135
140
  type: 'string',
@@ -143,6 +148,7 @@ const TOOLS = [
143
148
  required: ['agent'],
144
149
  },
145
150
  },
151
+ AGENT_INFO_TOOL,
146
152
  {
147
153
  name: 'somi_command',
148
154
  description:
@@ -178,17 +184,69 @@ const TOOLS = [
178
184
  name: 'somi_agent',
179
185
  description:
180
186
  "Read a SoMi agent's instructions (agents/<name>.md, frontmatter removed) from the install " +
181
- "root. For a host whose subagent tool cannot start a plugin agent by name (Copilot's task " +
182
- 'tool accepts only its built-in types): start a built-in general-purpose subagent with this ' +
183
- 'text as the start of its prompt, and the model somi_resolve returned.',
187
+ 'root, to inspect or quote them. Not a way to run the agent: start it as the agent_type ' +
188
+ 'somi_resolve returns, never as another agent given this text.',
184
189
  inputSchema: {
185
190
  type: 'object',
186
191
  properties: {
187
- name: { type: 'string', description: 'agent name, e.g. "reviewer" (matches ^[a-z][a-z0-9-]*$)' },
192
+ name: { type: 'string', description: 'agent name, e.g. "somi-reviewer" (matches ^[a-z][a-z0-9-]*$)' },
188
193
  },
189
194
  required: ['name'],
190
195
  },
191
196
  },
197
+ {
198
+ name: 'somi_config',
199
+ description:
200
+ 'Show or change the cost settings in the project\'s .somi/config.json by running ' +
201
+ '`node scripts/somi-config.mjs`, and return its one JSON line unchanged. Actions: show ' +
202
+ '(every agent\'s effective tier and warnings), get, set, unset, init (create the default file ' +
203
+ 'when absent). cost.ceiling and cost.agents.<name> take low|medium|high; ' +
204
+ 'cost.mapping.<host>.<tier> takes a model id or a comma-separated preference list (unset ' +
205
+ 'cost.mapping.<host> removes a host map). Any lowering or remap needs the user; ' +
206
+ 'the change is live, since the config is read on every dispatch. Failures report the CLI exit ' +
207
+ 'code: 64 usage (bad key, tier or name), 67 the project\'s config or .somi is unusable.',
208
+ inputSchema: {
209
+ type: 'object',
210
+ properties: {
211
+ action: { type: 'string', description: 'show, get, set, unset or init' },
212
+ key: { type: 'string', description: 'cost.ceiling, cost.agents.<name>, or cost.mapping.<host>[.<tier>] (get, set, unset)' },
213
+ value: { type: 'string', description: 'set: low, medium or high; for cost.mapping.<host>.<tier>, model-id[,model-id...]' },
214
+ project_dir: { type: 'string', description: 'absolute path of the project, as for somi_resolve' },
215
+ host: { type: 'string', description: 'show only: the host this session runs on (claude-code, copilot), as for somi_resolve; adds a warning when it has no model mapping' },
216
+ },
217
+ required: ['action'],
218
+ },
219
+ },
220
+ {
221
+ name: 'somi_tier',
222
+ description:
223
+ "Size a request: run `node scripts/somi-tier.mjs resolve` (no --record) on the signals you " +
224
+ 'extracted and return its one JSON line unchanged (tier, effective, source, floor, security_lens, reasons, ' +
225
+ 'basis). The rubric is the skill somi-routing, section Size tiers; this tool states no ' +
226
+ 'thresholds. The signal ids in `signals` are exact: use these names and no others. A name that ' +
227
+ 'is not one is ignored and listed back as `unrecognized` next to `expected`, and a missing ' +
228
+ 'signal is read as its worst case. Failures report the CLI exit code: 64 usage/input, 65 refused (a downward ' +
229
+ 'override below the security floor). It writes nothing: the tier record and the approval ' +
230
+ 'stamp need the CLI itself with --record and approve. SoMi is installed at ' + installRoot() +
231
+ ': run `node <that path>/scripts/somi-tier.mjs ...` from the project directory.',
232
+ inputSchema: {
233
+ type: 'object',
234
+ properties: {
235
+ signals: {
236
+ type: 'object',
237
+ description: 'One entry per rubric signal id, with exactly these names: { value, evidence }. What each means and how to extract it is in the skill somi-routing, section Size tiers.',
238
+ properties: Object.fromEntries(SIGNAL_IDS.map((id) => [id, {
239
+ type: 'object',
240
+ properties: { value: { description: 'true or false, or a whole number for a count signal; null when it cannot be determined' }, evidence: { type: 'string', description: 'files and lines you opened' } },
241
+ required: ['value', 'evidence'],
242
+ }])),
243
+ required: [...SIGNAL_IDS],
244
+ },
245
+ override: { type: 'string', description: 'small or full; only after a human reply' },
246
+ },
247
+ required: ['signals'],
248
+ },
249
+ },
192
250
  ];
193
251
 
194
252
  // --- tool implementations --------------------------------------------------------------------
@@ -232,6 +290,15 @@ async function callSomiResolve(args) {
232
290
  return textResult(JSON.stringify(outcome.result));
233
291
  }
234
292
 
293
+ // Read-only agent lookup; the logic lives in lib/agent-info.mjs, this only supplies the project root.
294
+ async function callSomiAgentInfo(args) {
295
+ const outcome = await agentInfo(args, {
296
+ resolveRoot: () => resolveProjectRoot({ projectDirArg: args?.project_dir, listRoots: () => listClientRoots() }),
297
+ installRoot: installRoot(),
298
+ });
299
+ return outcome.ok ? textResult(JSON.stringify(outcome.result)) : textResult(`somi-agent-info: ${outcome.message} (exit ${outcome.code})`, true);
300
+ }
301
+
235
302
  // One reader for every install-root text tool. The name is checked against AGENT_NAME_RE BEFORE
236
303
  // any path is built, so a traversal payload (`../x`, `a/b`) is a 64 and never reaches path.join.
237
304
  // JSON.stringify, not a template interpolation, for the invalid name: an object-shaped `name`
@@ -261,23 +328,77 @@ function callSomiSkill(args) {
261
328
  return r.error ?? textResult(r.content);
262
329
  }
263
330
 
264
- // The agent's instructions without its frontmatter: a host that cannot start a plugin agent by
265
- // type (Copilot's task tool) starts a built-in general-purpose subagent with this text instead, and
266
- // the frontmatter's `model:` would contradict the tier somi_resolve just selected.
331
+ // The agent's instructions without its frontmatter, for reading. Dispatch never uses this: an agent
332
+ // starts as its registered agent_type (see skills/somi-dispatch §5), so the text is never a payload.
267
333
  function callSomiAgent(args) {
268
334
  const r = readInstallText('somi-agent', 'agent', args?.name, (n) => ['agents', `${n}.md`]);
269
335
  return r.error ?? textResult(r.content.replace(/^---\r?\n[\s\S]*?\r?\n---\r?\n/, '').trimStart());
270
336
  }
271
337
 
338
+ // Runs the sizing CLI itself, so the result and the exit codes are the CLI's, byte for byte.
339
+ function callSomiTier(args) {
340
+ if (args.signals === null || typeof args.signals !== 'object' || Array.isArray(args.signals)) {
341
+ return textResult('somi-tier: signals must be an object (exit 64)', true);
342
+ }
343
+ const argv = [path.join(installRoot(), 'scripts', 'somi-tier.mjs'), 'resolve', '--signals', '-'];
344
+ if (args.override !== undefined) argv.push('--override', String(args.override));
345
+ const r = spawnSync(process.execPath, argv, { input: JSON.stringify(args.signals), encoding: 'utf8', timeout: 10000 });
346
+ if (r.status === 0) return textResult(r.stdout.trimEnd());
347
+ return textResult(`${(r.stderr || 'somi-tier: failed').trim()} (exit ${r.status ?? 'none'})`, true);
348
+ }
349
+
350
+ // Runs the config CLI itself (never a shell), so output and exit codes are the CLI's, byte for byte.
351
+ async function callSomiConfig(args) {
352
+ const text = (v) => v === undefined || typeof v === 'string';
353
+ if (typeof args.action !== 'string' || !['show', 'get', 'set', 'unset', 'init'].includes(args.action)) {
354
+ return textResult('somi-config: action must be one of show, get, set, unset, init (exit 64)', true);
355
+ }
356
+ if (args.host !== undefined && (args.action !== 'show' || typeof args.host !== 'string' || !/^[a-z][a-z0-9-]{0,31}$/.test(args.host))) {
357
+ return textResult('somi-config: host applies to show only and must be a lowercase host name (exit 64)', true);
358
+ }
359
+ if (!text(args.key) || !text(args.value) || [args.key, args.value].some((v) => v !== undefined && (v === '' || v.startsWith('-') || /[\u0000-\u001f\u007f]/.test(v)))) {
360
+ return textResult('somi-config: key and value must be non-empty strings without control characters that do not start with a dash (exit 64)', true);
361
+ }
362
+ // Writes need a root the HOST supplied: a model-supplied project_dir alone could point a write anywhere.
363
+ // The probe (no project_dir) succeeds, or fails as ambiguous, only when the host offered a root.
364
+ if (args.action !== 'show' && args.action !== 'get') {
365
+ const probe = await resolveProjectRoot({ projectDirArg: undefined, listRoots: () => listClientRoots() });
366
+ if (!probe.ok && !probe.message.startsWith('ambiguous')) {
367
+ return textResult('somi-config: no host project root; run the CLI yourself (node scripts/somi-config.mjs) to change the config (exit 67)', true);
368
+ }
369
+ }
370
+ const rootOutcome = await resolveProjectRoot({ projectDirArg: args.project_dir, listRoots: () => listClientRoots() });
371
+ if (!rootOutcome.ok) return textResult(`somi-config: ${rootOutcome.message} (exit ${rootOutcome.code})`, true);
372
+ const argv = [path.join(installRoot(), 'scripts', 'somi-config.mjs'), args.action];
373
+ if (args.key !== undefined) argv.push(args.key);
374
+ if (args.value !== undefined) argv.push(args.value);
375
+ if (args.host !== undefined) argv.push('--host', args.host);
376
+ // Lowering a tier or remapping a model needs the user. Where Claude Code runs the SoMi plugin's hooks
377
+ // (CLAUDE_PLUGIN_ROOT set) the cost-lowering PreToolUse hook asks; elsewhere nothing can ask, so the CLI
378
+ // refuses. Copilot CLI also sets CLAUDE_PLUGIN_ROOT, but names this tool `somi-somi_config`, which the
379
+ // hook's matcher does not catch (verified live on 1.0.103), so COPILOT_PLUGIN_ROOT means "refuse".
380
+ // A heuristic for "a hook can ask", failing closed on any host it does not recognise.
381
+ const pluginRoot = process.env.CLAUDE_PLUGIN_ROOT;
382
+ const hookCanAsk = pluginRoot && !pluginRoot.includes('${') && !process.env.COPILOT_PLUGIN_ROOT;
383
+ if ((args.action === 'set' || args.action === 'unset') && !hookCanAsk) argv.push('--refuse-lowering');
384
+ argv.push('--project-dir', fs.realpathSync(rootOutcome.root));
385
+ const r = spawnSync(process.execPath, argv, { encoding: 'utf8', timeout: 10000 });
386
+ if (r.status === 0) return textResult(r.stdout.trimEnd());
387
+ return textResult(`${(r.stderr || 'somi-config: failed').trim()} (exit ${r.status ?? 'none'})`, true);
388
+ }
389
+
272
390
  // Returns null for an unrecognized tool name — the caller turns that into a JSON-RPC error, since
273
391
  // an unknown TOOL is the protocol failing to find it at all, distinct from a known tool that ran
274
392
  // and failed (which reports isError:true in an otherwise-successful JSON-RPC response).
275
393
  async function callTool(name, args) {
276
394
  switch (name) {
277
395
  case 'somi_resolve': return await callSomiResolve(args || {});
396
+ case 'somi_agent_info': return await callSomiAgentInfo(args || {});
278
397
  case 'somi_command': return callSomiCommand(args || {});
279
398
  case 'somi_skill': return callSomiSkill(args || {});
280
399
  case 'somi_agent': return callSomiAgent(args || {});
400
+ case 'somi_tier': return callSomiTier(args || {});
401
+ case 'somi_config': return await callSomiConfig(args || {});
281
402
  default: return null;
282
403
  }
283
404
  }
@@ -0,0 +1,393 @@
1
+ #!/usr/bin/env node
2
+ // somi-tier.mjs — CLI over scripts/lib/size-tier.mjs's decideTier(): how much pipeline does this
3
+ // request deserve, and what was decided?
4
+ //
5
+ // resolve --signals <file|-> [--override small|full] [--record <slug> [--project-dir <dir>]]
6
+ // Reads signals JSON (a file path, or - for stdin; at most 64 KiB; a path must be a regular
7
+ // file, never a symlink or FIFO), calls decideTier, applies the optional override, prints one
8
+ // JSON line: { tier, effective, source, floor, security_lens, failed, unknown, invalid, reasons, basis }.
9
+ // security_lens is true unless the request is proven free of untrusted input and of auth, crypto,
10
+ // secrets and PII; /code-loop then reviews with the security lens at any tier.
11
+ // When the input holds keys that are not signal ids, the line also carries `unrecognized` (at
12
+ // most 8 of those names, each cut to 40 characters and ASCII-escaped; values are never
13
+ // echoed) and `expected` (the exact signal ids), so a caller can correct its input. Those two
14
+ // fields appear only then; the decision itself is unchanged (a missing signal is read as its
15
+ // worst case).
16
+ // tier what the function computed
17
+ // effective the tier to run: the computed one, or the override
18
+ // source 'computed' | 'override' (flag) | 'env' (SOMI_SHIP_LOOP_TIER)
19
+ // The override may only be small or full. The --override flag wins over the environment
20
+ // variable; an empty variable counts as unset. Raising the tier is always allowed; lowering
21
+ // it is refused when the result carries floor 'full'. Invalid signals are not an error here:
22
+ // decideTier already read them as their worst case and lists them in `invalid`.
23
+ //
24
+ // --record <slug> also writes <project>/.somi/somi-state/tier/<slug>.json from that same
25
+ // result, so the recorded tier, source, floor and signals hash are the computed ones by
26
+ // construction: { slug, tier (the effective one), source, computed_tier, floor, security_lens, reasons,
27
+ // failed, basis, signals_sha256, attempt, prior, recorded_at }, and the stdout line gains
28
+ // `recorded` (the path relative to the project). Every attempt that computed a tier, refusals
29
+ // included, is first appended to tier/<slug>.attempts.jsonl (append-only, 0600, links never
30
+ // followed); `attempt` is its number and `prior` the { computed_tier, signals_sha256 } of
31
+ // the earlier ones. A re-record whose computed tier is lower than any earlier computed tier
32
+ // is refused (65) unless --override is given. The basis is the whole one whenever the
33
+ // effective tier is lower than the computed tier. The project is --project-dir or the
34
+ // current directory.
35
+ // signals_sha256 is the sha256 of the signal entries only (their value and evidence, in id
36
+ // order, scalars only), so key order and extra keys do not change it. Directories it creates
37
+ // are 0700, the file is 0600, written to a temp file and renamed; a link at .somi,
38
+ // somi-state or tier is refused, and a link at the final path is replaced, not followed.
39
+ // Residual, accepted: a same-user process that swaps a checked directory for a link between
40
+ // the check and the write is not defended against.
41
+ //
42
+ // approve --slug <slug> [--project-dir <dir>]
43
+ // Stamps approved_at and brief_sha256 (of .somi/plans/<slug>/brief.md) into the slug's record.
44
+ // Run once, after the human replies approve and brief.md is written. Refused (65) unless the
45
+ // record is tier small with a signals hash and not yet approved; 64 when the record or the
46
+ // brief cannot be read. `somi-loop.mjs init` accepts a brief-only item only with this stamp.
47
+ //
48
+ // Output (stdout and the state file) is pure ASCII: every non-ASCII character is \uXXXX-escaped.
49
+ // Error messages never echo input text raw: values are JSON-quoted and non-ASCII is escaped.
50
+ //
51
+ // Exit codes (callers branch on these — do not repurpose):
52
+ // 0 ok
53
+ // 64 usage, input or I/O error: bad flag or value, unreadable or oversize input, JSON parse
54
+ // error, signals that are not an object, bad slug, unusable state directory, failed write
55
+ // 65 refused: a downward override below a security floor (names the floor on stderr), or a
56
+ // re-record whose computed tier is lower than an earlier one without --override
57
+ // Nothing is printed to stdout on an error path. Zero-dependency: stdlib only.
58
+
59
+ import crypto from 'node:crypto';
60
+ import fs from 'node:fs';
61
+ import path from 'node:path';
62
+ import { decideTier, SIGNAL_IDS } from './lib/size-tier.mjs';
63
+ import { briefSha256, readRecord } from './lib/tier-record.mjs';
64
+
65
+ const PROG = 'somi-tier';
66
+ const USAGE = `usage: ${PROG}.mjs resolve --signals <file|-> [--override small|full] [--record <slug> [--project-dir <dir>]] | approve --slug <slug> [--project-dir <dir>]`;
67
+
68
+ const EXIT_USAGE = 64;
69
+ const EXIT_FLOOR = 65;
70
+
71
+ const MAX_INPUT_BYTES = 64 * 1024;
72
+ const MAX_UNRECOGNIZED = 8;
73
+ const MAX_NAME_CHARS = 40;
74
+ const OVERRIDE_TARGETS = ['small', 'full'];
75
+ const TIERS = ['trivial', 'small', 'full'];
76
+ const SLUG = /^[a-z0-9][a-z0-9-]{0,63}$/;
77
+ const ENV_OVERRIDE = 'SOMI_SHIP_LOOP_TIER';
78
+ const STATE_DIRS = ['.somi', 'somi-state', 'tier'];
79
+ const MISSING = '\u0000missing';
80
+ const NON_SCALAR = '\u0000non-scalar';
81
+
82
+ class ExitSignal extends Error {
83
+ constructor(code) {
84
+ super(`exit ${code}`);
85
+ this.code = code;
86
+ }
87
+ }
88
+
89
+ // JSON with every non-ASCII character escaped, so neither stdout nor an error line can carry
90
+ // bidi, line-separator or C1 characters that a terminal would act on.
91
+ const ascii = (x, indent) => JSON.stringify(x, null, indent)
92
+ .replace(/[\u007f-\uffff]/g, (c) => `\\u${c.charCodeAt(0).toString(16).padStart(4, '0')}`);
93
+ const quote = (x) => ascii(String(x));
94
+
95
+ function fail(code, msg) {
96
+ process.stderr.write(`${PROG}: ${msg}\n`);
97
+ throw new ExitSignal(code);
98
+ }
99
+
100
+ function die(msg) {
101
+ fail(EXIT_USAGE, `${msg}\n${USAGE}`);
102
+ }
103
+
104
+ const rank = (t) => TIERS.indexOf(t);
105
+
106
+ // flags: { '--name': { oneOf?, pattern? } } -> { '--name': value }. A flag given twice, without a
107
+ // value, or with an empty or out-of-list value is a usage error.
108
+ function parseFlags(args, flags) {
109
+ const out = Object.create(null);
110
+ for (let i = 0; i < args.length; i += 2) {
111
+ const flag = args[i];
112
+ if (!Object.hasOwn(flags, flag)) die(`unknown argument: ${quote(flag)}`);
113
+ const spec = flags[flag];
114
+ const value = args[i + 1];
115
+ if (value === undefined || value === '') die(`${flag} requires a non-empty value`);
116
+ if (flag in out) die(`${flag} given twice`);
117
+ if (spec.oneOf && !spec.oneOf.includes(value)) die(`${flag} must be one of: ${spec.oneOf.join(', ')}`);
118
+ if (spec.pattern && !spec.pattern.test(value)) die(`${flag} is not a valid ${flag.slice(2)}`);
119
+ out[flag] = value;
120
+ }
121
+ return out;
122
+ }
123
+
124
+ // Reads at most MAX_INPUT_BYTES from a regular file (opened without following links or blocking
125
+ // on a FIFO) or stdin.
126
+ function readBounded(src) {
127
+ let fd = 0;
128
+ let opened = false;
129
+ try {
130
+ if (src !== '-') {
131
+ fd = fs.openSync(src, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW | fs.constants.O_NONBLOCK);
132
+ opened = true;
133
+ if (!fs.fstatSync(fd).isFile()) fail(EXIT_USAGE, `${quote(src)} is not a regular file`);
134
+ }
135
+ const buf = Buffer.alloc(MAX_INPUT_BYTES + 1);
136
+ let total = 0;
137
+ while (total < buf.length) {
138
+ let n;
139
+ try {
140
+ n = fs.readSync(fd, buf, total, buf.length - total, null);
141
+ } catch (e) {
142
+ if (e.code === 'EOF') break;
143
+ if (e.code === 'EAGAIN') {
144
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 10);
145
+ continue;
146
+ }
147
+ throw e;
148
+ }
149
+ if (n === 0) break;
150
+ total += n;
151
+ }
152
+ if (total > MAX_INPUT_BYTES) fail(EXIT_USAGE, `signals input exceeds ${MAX_INPUT_BYTES} bytes`);
153
+ return buf.subarray(0, total);
154
+ } catch (e) {
155
+ if (e instanceof ExitSignal) throw e;
156
+ return fail(EXIT_USAGE, `cannot read ${src === '-' ? 'stdin' : quote(src)}: ${e.code || 'error'}`);
157
+ } finally {
158
+ if (opened) fs.closeSync(fd);
159
+ }
160
+ }
161
+
162
+ // -> the parsed signals object. Only JSON.parse output ever reaches decideTier.
163
+ function loadSignals(src) {
164
+ const bytes = readBounded(src);
165
+ let parsed;
166
+ try {
167
+ parsed = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes));
168
+ } catch (e) {
169
+ // The engine's message quotes the offending input; only its position is safe to repeat.
170
+ const at = /position (\d+)/.exec(String(e && e.message));
171
+ return fail(EXIT_USAGE, `signals are not valid UTF-8 JSON${at ? ` (near position ${at[1]})` : ''}`);
172
+ }
173
+ if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {
174
+ fail(EXIT_USAGE, 'signals must be a JSON object');
175
+ }
176
+ return parsed;
177
+ }
178
+
179
+ const field = (o, k) => (o !== null && typeof o === 'object' && Object.hasOwn(o, k) ? o[k] : MISSING);
180
+ const scalar = (x) => (x === null || ['string', 'number', 'boolean'].includes(typeof x) ? x : NON_SCALAR);
181
+
182
+ // Hash of the signal entries only, scalars only: bounded work however deeply the input nests.
183
+ function signalsHash(signals) {
184
+ const rows = SIGNAL_IDS.map((id) => {
185
+ const entry = field(signals, id);
186
+ return [id, scalar(field(entry, 'value')), scalar(field(entry, 'evidence'))];
187
+ });
188
+ return crypto.createHash('sha256').update(JSON.stringify(rows)).digest('hex');
189
+ }
190
+
191
+ function refuseBelowFloor(tier, floor, what, beforeFail) {
192
+ if (floor && rank(tier) < rank(floor)) {
193
+ beforeFail?.('refused_floor');
194
+ fail(EXIT_FLOOR, `${what} to ${tier} is refused: the security floor is ${floor} (the request is not proven free of security-sensitive work)`);
195
+ }
196
+ }
197
+
198
+ // Creates the state directories under the project root, refusing any link on the way, and returns
199
+ // the real path of the tier directory after proving it sits inside the real project root.
200
+ function stateDir(projectDir) {
201
+ const root = fs.realpathSync(projectDir);
202
+ let dir = root;
203
+ for (const part of STATE_DIRS) {
204
+ dir = path.join(dir, part);
205
+ let st = null;
206
+ try {
207
+ st = fs.lstatSync(dir);
208
+ } catch (e) {
209
+ if (e.code !== 'ENOENT') throw e;
210
+ }
211
+ if (!st) fs.mkdirSync(dir, { mode: 0o700 });
212
+ else if (!st.isDirectory()) fail(EXIT_USAGE, `${path.relative(root, dir)} is not a real directory (links are not followed)`);
213
+ }
214
+ const real = fs.realpathSync(dir);
215
+ if (real !== path.join(root, ...STATE_DIRS)) fail(EXIT_USAGE, 'state directory escapes the project root');
216
+ return { root, real };
217
+ }
218
+
219
+ const MAX_ATTEMPTS = 50;
220
+ const MAX_LOG_BYTES = 256 * 1024;
221
+ const attemptsPath = (dirs, slug) => path.join(dirs.real, `${slug}.attempts.jsonl`);
222
+
223
+ // -> [{ computed_tier, signals_sha256 }] of every earlier attempt for the slug, oldest first.
224
+ // A log that cannot be read, is too large, or holds a malformed line fails closed.
225
+ function readAttempts(dirs, slug) {
226
+ let fd;
227
+ try {
228
+ try {
229
+ fd = fs.openSync(attemptsPath(dirs, slug), fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW | fs.constants.O_NONBLOCK);
230
+ } catch (e) {
231
+ if (e.code === 'ENOENT') return [];
232
+ throw e;
233
+ }
234
+ const st = fs.fstatSync(fd);
235
+ if (!st.isFile() || st.size > MAX_LOG_BYTES) fail(EXIT_USAGE, 'the attempts log is not a regular file or is too large');
236
+ const rows = fs.readFileSync(fd, 'utf8').split('\n').filter(Boolean).map((line) => {
237
+ let row;
238
+ try { row = JSON.parse(line); } catch { row = null; }
239
+ const ok = row !== null && typeof row === 'object' && TIERS.includes(row.computed_tier)
240
+ && (row.signals_sha256 === null || /^[0-9a-f]{64}$/.test(row.signals_sha256));
241
+ if (!ok) fail(EXIT_USAGE, 'the attempts log holds a malformed line');
242
+ return { computed_tier: row.computed_tier, signals_sha256: row.signals_sha256 };
243
+ });
244
+ if (rows.length >= MAX_ATTEMPTS) fail(EXIT_USAGE, `the attempts log is full (${MAX_ATTEMPTS} attempts); ask the human before sizing this work again`);
245
+ return rows;
246
+ } catch (e) {
247
+ if (e instanceof ExitSignal) throw e;
248
+ return fail(EXIT_USAGE, `cannot read the attempts log: ${e.code || 'error'}`);
249
+ } finally {
250
+ if (fd !== undefined) fs.closeSync(fd);
251
+ }
252
+ }
253
+
254
+ // Appends one line (append-only, 0600, links never followed).
255
+ function appendAttempt(dirs, slug, row) {
256
+ let fd;
257
+ try {
258
+ fd = fs.openSync(attemptsPath(dirs, slug), fs.constants.O_WRONLY | fs.constants.O_APPEND | fs.constants.O_CREAT | fs.constants.O_NOFOLLOW, 0o600);
259
+ if (!fs.fstatSync(fd).isFile()) fail(EXIT_USAGE, 'the attempts log is not a regular file');
260
+ const line = `${ascii(row)}\n`;
261
+ if (fs.writeSync(fd, line) !== line.length) throw Object.assign(new Error('short write'), { code: 'ESHORT' });
262
+ } catch (e) {
263
+ if (e instanceof ExitSignal) throw e;
264
+ fail(EXIT_USAGE, `cannot append to the attempts log: ${e.code || 'error'}`);
265
+ } finally {
266
+ if (fd !== undefined) fs.closeSync(fd);
267
+ }
268
+ }
269
+
270
+ function openState(projectDir) {
271
+ try {
272
+ return stateDir(projectDir);
273
+ } catch (e) {
274
+ if (e instanceof ExitSignal) throw e;
275
+ return fail(EXIT_USAGE, `cannot prepare the state directory: ${e.code || 'error'}`);
276
+ }
277
+ }
278
+
279
+ // Writes the record atomically (temp file, then rename); returns its path relative to the project.
280
+ function writeRecord(dirs, slug, doc) {
281
+ const body = `${ascii(doc, 2)}\n`;
282
+ const final = path.join(dirs.real, `${slug}.json`);
283
+ const tmp = path.join(dirs.real, `.${slug}.${process.pid}.${crypto.randomBytes(6).toString('hex')}.tmp`);
284
+ try {
285
+ const fd = fs.openSync(tmp, fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL | fs.constants.O_NOFOLLOW, 0o600);
286
+ try {
287
+ if (fs.writeSync(fd, body) !== body.length) throw Object.assign(new Error('short write'), { code: 'ESHORT' });
288
+ fs.fsyncSync(fd);
289
+ } finally {
290
+ fs.closeSync(fd);
291
+ }
292
+ fs.renameSync(tmp, final);
293
+ } catch (e) {
294
+ fs.rmSync(tmp, { force: true });
295
+ return fail(EXIT_USAGE, `cannot write the tier record: ${e.code || 'error'}`);
296
+ }
297
+ return path.relative(dirs.root, final);
298
+ }
299
+
300
+ function resolve(args) {
301
+ const f = parseFlags(args, {
302
+ '--signals': {}, '--override': { oneOf: OVERRIDE_TARGETS }, '--record': { pattern: SLUG }, '--project-dir': {},
303
+ });
304
+ if (!f['--signals']) die('--signals is required');
305
+ if (f['--project-dir'] && !f['--record']) die('--project-dir only applies with --record');
306
+ let requested = f['--override'];
307
+ let source = 'override';
308
+ if (!requested && process.env[ENV_OVERRIDE]) {
309
+ requested = process.env[ENV_OVERRIDE];
310
+ source = 'env';
311
+ if (!OVERRIDE_TARGETS.includes(requested)) die(`${ENV_OVERRIDE} must be one of: ${OVERRIDE_TARGETS.join(', ')}`);
312
+ }
313
+ const signals = loadSignals(f['--signals']);
314
+ const r = decideTier(signals);
315
+ const slug = f['--record'];
316
+ // The attempts log is the memory of this slug: every attempt that computed a tier is appended,
317
+ // refusals included, before the failure exit.
318
+ const dirs = slug ? openState(f['--project-dir'] || process.cwd()) : null;
319
+ const prior = slug ? readAttempts(dirs, slug) : [];
320
+ const hash = slug ? signalsHash(signals) : null;
321
+ const log = (outcome) => slug && appendAttempt(dirs, slug, {
322
+ n: prior.length + 1, at: new Date().toISOString(), computed_tier: r.tier, requested: requested || null, outcome, signals_sha256: hash,
323
+ });
324
+ let effective = r.tier;
325
+ if (requested) {
326
+ refuseBelowFloor(requested, r.floor, `overriding ${r.tier}`, log);
327
+ effective = requested;
328
+ } else {
329
+ source = 'computed';
330
+ }
331
+ // Re-extracting cannot talk the tier down: only a human reply (the flag) can.
332
+ const highest = Math.max(-1, ...prior.map((a) => rank(a.computed_tier)));
333
+ if (slug && !f['--override'] && rank(r.tier) < highest) {
334
+ log('refused_lower');
335
+ fail(EXIT_FLOOR, `computed tier ${r.tier} is lower than an earlier computed tier (${TIERS[highest]}) for this slug; re-extracting cannot lower the tier (a human reply with --override is required)`);
336
+ }
337
+ // An override that lowers the tier shows the whole basis, not only the security signal's.
338
+ const shown = requested && rank(effective) < rank(r.tier) ? decideTier(signals, { fullBasis: true }) : r;
339
+ const out = {
340
+ tier: r.tier, effective, source, floor: r.floor, security_lens: r.securityLens, failed: r.failed, unknown: r.unknown,
341
+ invalid: r.invalid, reasons: r.reasons, basis: shown.basis,
342
+ };
343
+ const strange = signals !== null && typeof signals === 'object' && !Array.isArray(signals) ? Object.keys(signals).filter((k) => !SIGNAL_IDS.includes(k)) : [];
344
+ if (strange.length > 0) {
345
+ out.unrecognized = strange.slice(0, MAX_UNRECOGNIZED).map((k) => k.slice(0, MAX_NAME_CHARS));
346
+ out.expected = [...SIGNAL_IDS];
347
+ }
348
+ if (slug) {
349
+ log('accepted');
350
+ out.recorded = writeRecord(dirs, slug, {
351
+ slug, tier: effective, source, computed_tier: r.tier, floor: r.floor, security_lens: r.securityLens,
352
+ reasons: r.reasons, failed: r.failed, basis: shown.basis, signals_sha256: hash,
353
+ attempt: prior.length + 1, prior, recorded_at: new Date().toISOString(),
354
+ });
355
+ }
356
+ console.log(ascii(out));
357
+ }
358
+
359
+ // Stamps the approval into the record: run after the human's reply and after brief.md is written.
360
+ // Binds the approval to the brief as it is now; a later change to the brief voids it.
361
+ function approve(args) {
362
+ const f = parseFlags(args, { '--slug': { pattern: SLUG }, '--project-dir': {} });
363
+ if (!f['--slug']) die('--slug is required');
364
+ const dirs = openState(f['--project-dir'] || process.cwd());
365
+ const rec = readRecord(dirs.root, f['--slug']);
366
+ if (!rec) fail(EXIT_USAGE, 'there is no readable tier record for this slug');
367
+ if (rec.tier !== 'small') fail(EXIT_FLOOR, 'only a small tier record can be approved for a brief-only run');
368
+ if (typeof rec.signals_sha256 !== 'string' || !/^[0-9a-f]{64}$/.test(rec.signals_sha256)) {
369
+ fail(EXIT_FLOOR, 'the record has no signals hash; resolve with --record first');
370
+ }
371
+ if (rec.approved_at) fail(EXIT_FLOOR, 'the record is already approved; a new approval needs a new resolve --record');
372
+ const brief = briefSha256(dirs.root, f['--slug']);
373
+ if (!brief) fail(EXIT_USAGE, 'brief.md is missing, a link, or too large');
374
+ const recorded = writeRecord(dirs, f['--slug'], { ...rec, approved_at: new Date().toISOString(), brief_sha256: brief });
375
+ console.log(ascii({ approved: true, recorded, brief_sha256: brief }));
376
+ }
377
+
378
+ function main() {
379
+ const [cmd, ...rest] = process.argv.slice(2);
380
+ if (cmd === 'resolve') resolve(rest);
381
+ else if (cmd === 'approve') approve(rest);
382
+ else die(cmd ? `unknown subcommand: ${quote(cmd)}` : 'a subcommand is required');
383
+ }
384
+
385
+ try {
386
+ main();
387
+ } catch (e) {
388
+ if (e instanceof ExitSignal) {
389
+ process.exitCode = e.code;
390
+ } else {
391
+ throw e;
392
+ }
393
+ }