@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
@@ -29,7 +29,7 @@
29
29
  // cut the unsafe way. The Linux fixture corpus validates only the posix axis.
30
30
 
31
31
  import path from 'node:path';
32
- import { readPayload, field, denyPretool, matchesAny, runHook } from '../lib/common.mjs';
32
+ import { readPayload, field, denyPretool, matchesAny, runHook, writeTargets } from '../lib/common.mjs';
33
33
 
34
34
  const SECRET_PATTERNS = [
35
35
  // env files (allow .env.example, .env.sample, .env.template explicitly)
@@ -76,17 +76,18 @@ const EXAMPLE_BASENAMES = ['.env.example', '.env.sample', '.env.template', '.env
76
76
  function main() {
77
77
  const payload = readPayload();
78
78
  const tool = field(payload, '.tool_name');
79
- const pathInput = field(payload, '.tool_input.file_path');
80
- if (!pathInput) return;
81
-
82
- // Normalise to basename for pattern matching.
83
- const basename = path.basename(pathInput);
84
-
85
- if (EXAMPLE_BASENAMES.includes(basename)) return;
86
-
87
- if (matchesAny(basename, SECRET_PATTERNS)) {
88
- denyPretool(payload, `somi refused to ${tool} \`${pathInput}\`: this path is in the secret-bearing allowlist.
79
+ const { paths, known } = writeTargets(payload);
80
+ if (!known) {
81
+ denyPretool(payload, `somi refused to ${tool}: it could not tell which file this writes, so the secret-write guard cannot check it.`);
82
+ }
83
+ for (const pathInput of paths) {
84
+ // Normalise to basename for pattern matching.
85
+ const basename = path.basename(pathInput);
86
+ if (EXAMPLE_BASENAMES.includes(basename)) continue;
87
+ if (matchesAny(basename, SECRET_PATTERNS)) {
88
+ denyPretool(payload, `somi refused to ${tool} \`${pathInput}\`: this path is in the secret-bearing allowlist.
89
89
  Bootstrap secret files by hand, or commit only \`.env.example\`-style templates.`);
90
+ }
90
91
  }
91
92
  }
92
93
 
@@ -0,0 +1,177 @@
1
+ #!/usr/bin/env node
2
+ // hooks/pre-tool/guard-cost-lowering.mjs — PreToolUse hook (matcher: Write|Edit|MultiEdit|mcp__.*somi_config)
3
+ // — ask the USER before a change that lowers a cost tier.
4
+ //
5
+ // A model steered by injected text could lower security-reviewer or the ceiling through the somi_config
6
+ // MCP tool or by editing .somi/config.json, and the warning would only reach that model. This hook
7
+ // computes what the change would do and, if it lowers any agent's effective tier (see
8
+ // scripts/lib/cost-lowering.mjs for the exact rules), answers permissionDecision "ask" with a plain-text
9
+ // reason built from fixed strings. Raises and no-ops are silent, and so is every unrelated tool call.
10
+ //
11
+ // - somi_config (set|unset): `after` = the current config with tool_input applied by the shared edit
12
+ // lib (scripts/lib/cost-config-edit.mjs), so the hook and the tool cannot disagree on meaning.
13
+ // - Write / Edit / MultiEdit of <project>/.somi/config.json (the path is resolved against the project
14
+ // root, so `.somi/../.somi/config.json` and a symlinked .somi resolve to the same file): `after` = the
15
+ // written content, or the current text with the edits applied exactly as the Edit tool would.
16
+ //
17
+ // Fail closed to the user: for a config-file path, any inability to evaluate (unreadable or unparsable
18
+ // content, an edit that does not apply, an exception) asks. Nothing from any file is ever echoed.
19
+ // Accepted limits: a model with an approved Bash tool can still edit the file by other means; the
20
+ // somi_config tool's own refusal (--refuse-lowering) covers hosts where this hook does not run.
21
+
22
+ import fs from 'node:fs';
23
+ import path from 'node:path';
24
+ import { pathToFileURL } from 'node:url';
25
+ import { readPayload, field, askPretool, HookExit, projectRoot, writeTargets } from '../lib/common.mjs';
26
+
27
+ const LIB = path.join(import.meta.dirname, '..', '..', 'scripts', 'lib');
28
+ const UNEVALUABLE = 'SoMi: this change to .somi/config.json could not be evaluated, so it needs your confirmation.';
29
+ const OUTSIDE = 'SoMi: this call names a project directory outside the project root, so it needs your confirmation.';
30
+ const STATE_WRITE = 'SoMi: this writes the persisted cost ceiling (.somi/somi-state/ceiling.json), which can lower the ceiling, so it needs your confirmation.';
31
+ const UNREADABLE_WRITE = 'SoMi: this writes the SoMi cost config or ceiling in a form the guard cannot evaluate, so it needs your confirmation.';
32
+ const RESOLVE_LOWER = 'SoMi: this somi_resolve call sets a session ceiling lower than the current one, so it needs your confirmation.';
33
+ const SECURITY_ONLY = 'SoMi: after this change security-reviewer would run below high (it is not pinned to high). Confirm only if you intend that.';
34
+ const reasonFor = (reasons, REASONS) => (reasons.length === 1 && reasons[0] === REASONS.security
35
+ ? SECURITY_ONLY
36
+ : `SoMi: this change lowers a cost setting (${reasons.join('; ')}). Confirm only if you intend it.`);
37
+
38
+ const realOrNull = (p) => { try { return fs.realpathSync(p); } catch { return null; } };
39
+ const statOrNull = (p) => { try { return fs.statSync(p); } catch { return null; } };
40
+ const same = (a, b) => a !== null && b !== null && a.dev === b.dev && a.ino === b.ino;
41
+
42
+ // Is `target` (as given by the tool) the project's .somi/config.json? Decided by identity, not spelling:
43
+ // - it is the same file (dev/ino, following links), or
44
+ // - its nearest existing ancestor is the same directory as <root>/.somi and the rest is config.json
45
+ // (any case), or that ancestor is the root itself and the rest is .somi/config.json (any case), so an
46
+ // absent file, an absent .somi, a symlinked .somi, an aliased root and a case-insensitive filesystem
47
+ // are all caught, or
48
+ // - lexically it is <root>/.somi/config.json in any letter case (fail closed when nothing resolves).
49
+ // `segs` is the file's path below the root: ['.somi', 'config.json'] or ['.somi', 'somi-state', 'ceiling.json'].
50
+ function isProjectPath(root, target, segs) {
51
+ const lexical = path.resolve(root, target);
52
+ if (same(statOrNull(lexical), statOrNull(path.join(root, ...segs)))) return true;
53
+ let anc = lexical; const rest = [];
54
+ while (statOrNull(anc) === null && path.dirname(anc) !== anc) { rest.unshift(path.basename(anc)); anc = path.dirname(anc); }
55
+ const low = rest.map((x) => x.toLowerCase());
56
+ const ancStat = statOrNull(anc);
57
+ const n = low.length;
58
+ if (n >= 1 && n <= segs.length && low.join('/') === segs.slice(segs.length - n).join('/') && same(ancStat, statOrNull(path.join(root, ...segs.slice(0, segs.length - n))))) return true;
59
+ const rel = path.relative(root, lexical).split(path.sep).map((x) => x.toLowerCase());
60
+ return rel.join('/') === segs.join('/');
61
+ }
62
+ const isConfigPath = (root, target) => isProjectPath(root, target, ['.somi', 'config.json']);
63
+ const isStatePath = (root, target) => isProjectPath(root, target, ['.somi', 'somi-state', 'ceiling.json']);
64
+
65
+ // The project directory a somi_config / somi_resolve call acts on: project_dir when it resolves to the root
66
+ // or inside it, the root when none is given; anything else is something the hook cannot evaluate: ask.
67
+ function narrowedDir(payload, input, root) {
68
+ if (input.project_dir === undefined) return root;
69
+ const dir = typeof input.project_dir === 'string' && path.isAbsolute(input.project_dir) ? realOrNull(input.project_dir) : null;
70
+ const host = realOrNull(root);
71
+ if (!dir || !host || !(dir === host || dir.startsWith(host + path.sep))) askPretool(payload, OUTSIDE);
72
+ return dir;
73
+ }
74
+
75
+ // The Edit tool's rule: old_string must occur (once, unless replace_all). Returns the new text or null.
76
+ function applyOneEdit(text, e) {
77
+ if (typeof e?.old_string !== 'string' || typeof e?.new_string !== 'string' || e.old_string === '') return null;
78
+ const n = text.split(e.old_string).length - 1;
79
+ if (n === 0 || (n > 1 && e.replace_all !== true)) return null;
80
+ return e.replace_all === true ? text.split(e.old_string).join(e.new_string) : text.replace(e.old_string, () => e.new_string);
81
+ }
82
+
83
+ function readCurrent(readTextFile, file) {
84
+ try { return readTextFile(file); } catch (e) { if (e.code === 'ENOENT') return null; throw e; }
85
+ }
86
+
87
+ // somi_resolve({ceiling}) persists a CLI-style ceiling; one below the ceiling in force needs the user.
88
+ async function resolveCheck(payload, input, root) {
89
+ if (input.ceiling === undefined) return;
90
+ const dir = narrowedDir(payload, input, root);
91
+ try {
92
+ const [{ readTextFile, loadState, DEFAULT_CEILING }, { VALID_COSTS }] = await Promise.all(
93
+ ['cost-ceiling', 'cost-model'].map((m) => import(pathToFileURL(path.join(LIB, `${m}.mjs`)).href)),
94
+ );
95
+ if (!VALID_COSTS.includes(input.ceiling)) return; // the tool rejects it itself
96
+ const text = readCurrent(readTextFile, path.join(dir, '.somi', 'config.json'));
97
+ const cfg = text === null ? {} : JSON.parse(text);
98
+ const state = loadState(dir);
99
+ const effective = VALID_COSTS.includes(cfg?.cost?.ceiling) ? cfg.cost.ceiling
100
+ : (state && ['cli', 'env'].includes(state.ceiling_origin) ? state.ceiling : DEFAULT_CEILING);
101
+ if (VALID_COSTS.indexOf(input.ceiling) < VALID_COSTS.indexOf(effective)) askPretool(payload, RESOLVE_LOWER);
102
+ } catch (e) {
103
+ if (e instanceof HookExit) throw e;
104
+ askPretool(payload, RESOLVE_LOWER);
105
+ }
106
+ }
107
+
108
+ async function main() {
109
+ const payload = readPayload();
110
+ const tool = field(payload, 'tool_name');
111
+ const input = payload?.tool_input && typeof payload.tool_input === 'object' ? payload.tool_input : {};
112
+ const isMcp = /^mcp__.*somi_config$/.test(tool) || tool === 'somi_config';
113
+ const isResolve = /^mcp__.*somi_resolve$/.test(tool) || tool === 'somi_resolve';
114
+ const isFileTool = tool === 'Write' || tool === 'Edit' || tool === 'MultiEdit';
115
+ if (!isMcp && !isFileTool && !isResolve) return;
116
+
117
+ const root = projectRoot();
118
+ if (isResolve) return resolveCheck(payload, input, root);
119
+ // Copilot CLI's file tools (Write with `path`, Edit with a raw patch) carry no file_path and no
120
+ // before/after the evaluation below can read: a write that reaches the config or the persisted
121
+ // ceiling in that shape asks. One whose target cannot be read at all is the path guards' to refuse.
122
+ if (isFileTool && !(typeof input.file_path === 'string' && input.file_path !== '')) {
123
+ const { paths } = writeTargets(payload);
124
+ if (paths.some((p) => isConfigPath(root, p) || isStatePath(root, p))) askPretool(payload, UNREADABLE_WRITE);
125
+ return;
126
+ }
127
+ // Any write to the persisted ceiling file asks: it is the other way to lower the ceiling.
128
+ if (isFileTool && typeof input.file_path === 'string' && input.file_path !== '' && isStatePath(root, input.file_path)) askPretool(payload, STATE_WRITE);
129
+ let projDir = root; // the directory whose config is evaluated (and whose persisted ceiling applies)
130
+ if (isMcp) {
131
+ if (input.action !== 'set' && input.action !== 'unset') return;
132
+ // The tool writes into project_dir when it narrows the host root; evaluate THAT config. A project_dir
133
+ // that does not resolve to the root or a directory inside it is something the hook cannot evaluate: ask.
134
+ projDir = narrowedDir(payload, input, root);
135
+ } else {
136
+ const target = input.file_path;
137
+ if (typeof target !== 'string' || target === '' || !isConfigPath(root, target)) return;
138
+ }
139
+ const file = path.join(projDir, '.somi', 'config.json');
140
+
141
+ // From here the call is about the project config: any failure asks.
142
+ try {
143
+ const [{ readTextFile }, { applyEdit, EditError }, { lowers, REASONS }] = await Promise.all(
144
+ ['cost-ceiling', 'cost-config-edit', 'cost-lowering'].map((m) => import(pathToFileURL(path.join(LIB, `${m}.mjs`)).href)),
145
+ );
146
+ const currentText = readCurrent(readTextFile, file);
147
+ let before = {};
148
+ if (currentText !== null) { try { before = JSON.parse(currentText); } catch { before = {}; } }
149
+ let after;
150
+ if (isMcp) {
151
+ try { after = applyEdit(currentText === null ? null : JSON.parse(currentText), { action: input.action, key: input.key, value: input.value }).next; } catch (e) {
152
+ if (e instanceof EditError) return; // the tool rejects this call itself; nothing would change
153
+ throw e;
154
+ }
155
+ } else if (tool === 'Write') {
156
+ if (typeof input.content !== 'string') throw new Error('no content');
157
+ after = JSON.parse(input.content);
158
+ } else {
159
+ let text = currentText ?? '';
160
+ const edits = tool === 'MultiEdit' ? input.edits : [input];
161
+ if (!Array.isArray(edits)) throw new Error('no edits');
162
+ for (const e of edits) {
163
+ text = applyOneEdit(text, e);
164
+ if (text === null) throw new Error('edit does not apply');
165
+ }
166
+ after = JSON.parse(text);
167
+ }
168
+ const verdict = lowers(before, after, projDir);
169
+ if (verdict.lowers) askPretool(payload, reasonFor(verdict.reasons, REASONS));
170
+ } catch (e) {
171
+ if (e instanceof HookExit) throw e;
172
+ askPretool(payload, UNEVALUABLE);
173
+ }
174
+ }
175
+
176
+ // Exit 0 on every path: a HookExit is the question already asked, anything else is silence.
177
+ main().then(() => {}, () => {}).finally(() => { process.exitCode = 0; });
@@ -69,7 +69,7 @@
69
69
  // block-secret-writes.mjs's own basename note, on the safe side here too.
70
70
 
71
71
  import path from 'node:path';
72
- import { readPayload, field, denyPretool, runHook, projectRoot, config } from '../lib/common.mjs';
72
+ import { readPayload, field, denyPretool, runHook, projectRoot, config, writeTargets } from '../lib/common.mjs';
73
73
 
74
74
  const PROTECTED_GLOBS = [
75
75
  // Source-control internals.
@@ -78,6 +78,10 @@ const PROTECTED_GLOBS = [
78
78
  // SOMI plugin install — never let an agent rewrite the ruleset under itself.
79
79
  '*/.claude/plugins/somi/*',
80
80
 
81
+ // The sizing CLI's records (scripts/somi-tier.mjs): they gate the brief-only path, so only the
82
+ // CLI writes them, never an agent's Write/Edit.
83
+ '*/.somi/somi-state/tier/*',
84
+
81
85
  // Vendored deps & build outputs.
82
86
  '*/node_modules/*',
83
87
  '*/vendor/*',
@@ -122,9 +126,15 @@ function lockfilesAllowed() {
122
126
  function main() {
123
127
  const payload = readPayload();
124
128
  const tool = field(payload, '.tool_name');
125
- let pathInput = field(payload, '.tool_input.file_path');
126
- if (!pathInput) return;
129
+ const { paths, known } = writeTargets(payload);
130
+ if (!known) {
131
+ denyPretool(payload, `somi refused to ${tool}: it could not tell which file this writes, so the protected-path guard cannot check it.`);
132
+ }
133
+ for (const target of paths) checkPath(payload, tool, target);
134
+ }
127
135
 
136
+ function checkPath(payload, tool, target) {
137
+ let pathInput = target;
128
138
  // Normalise relative paths so the leading-`*/` globs above still match (a relative
129
139
  // `node_modules/x.js` would otherwise slip past `*/node_modules/*`). Reuses common.mjs's
130
140
  // projectRoot() — the centralized ${...}-unexpanded-variable guard — rather than
@@ -143,6 +143,22 @@ const MAX_DEPTH = 3; // bash: find -maxdepth 3
143
143
  const MIN_DEPTH = 2; // bash: -mindepth 2
144
144
  const MAX_NESTED_RESULTS = 10; // bash: | head -n 10
145
145
 
146
+ // The walk's own bounds, beyond depth: a repo with a huge directory at depth <= 3 must not stall
147
+ // session start. The entry budget is the deterministic bound (tested); the deadline is the
148
+ // backstop for a slow filesystem. Hitting either just ends the scan with what was found so far.
149
+ const MAX_ENTRIES_VISITED = 5000;
150
+ const SCAN_DEADLINE_MS = 1000;
151
+
152
+ // Directory names are repo-controlled text, and this hook's output lands in the model's context.
153
+ // A nested path is listed only when every segment is a plain name; anything else (spaces, newlines,
154
+ // backticks, prose) is counted but never echoed, so a folder cannot be named into an instruction.
155
+ // Tradeoff, named: a legitimate folder like "my app/CLAUDE.md" is counted, not listed.
156
+ const SAFE_SEGMENT_RE = /^[A-Za-z0-9._-]{1,64}$/;
157
+
158
+ function isListablePath(rel) {
159
+ return rel.split(/[\\/]/).every((seg) => SAFE_SEGMENT_RE.test(seg));
160
+ }
161
+
146
162
  // bash's closing directive line (verbatim, including the embedded single quotes bash's
147
163
  // `$'...'\''...'\''...'` escaping decodes to). Byte-exact against the fixture's
148
164
  // expect_context substrings.
@@ -174,9 +190,12 @@ function isDirectory(p) {
174
190
  // this never matters for what's actually asserted.
175
191
  function scanNested(root) {
176
192
  const results = [];
193
+ const deadline = Date.now() + SCAN_DEADLINE_MS;
194
+ let visited = 0;
177
195
 
178
196
  function walk(dir, depth) {
179
197
  if (results.length >= MAX_NESTED_RESULTS) return;
198
+ if (visited >= MAX_ENTRIES_VISITED || Date.now() > deadline) return;
180
199
  let entries;
181
200
  try {
182
201
  entries = fs.readdirSync(dir, { withFileTypes: true });
@@ -185,6 +204,7 @@ function scanNested(root) {
185
204
  }
186
205
  for (const entry of entries) {
187
206
  if (results.length >= MAX_NESTED_RESULTS) return;
207
+ if (++visited > MAX_ENTRIES_VISITED) return;
188
208
  const full = path.join(dir, entry.name);
189
209
  if (entry.isDirectory()) {
190
210
  if (depth === 1 && PRUNED_TOP_LEVEL_DIRS.has(entry.name)) continue;
@@ -224,8 +244,10 @@ function main() {
224
244
  for (const f of ROOT_FILES) {
225
245
  if (isFile(path.join(root, f))) found.push(f);
226
246
  }
247
+ let unlisted = 0;
227
248
  for (const rel of scanNested(root)) {
228
- found.push(rel);
249
+ if (isListablePath(rel)) found.push(rel);
250
+ else unlisted += 1;
229
251
  }
230
252
 
231
253
  let repoAgents = '';
@@ -237,7 +259,7 @@ function main() {
237
259
  }
238
260
  }
239
261
 
240
- if (found.length === 0 && !repoAgents) return;
262
+ if (found.length === 0 && !repoAgents && unlisted === 0) return;
241
263
 
242
264
  let msg =
243
265
  'somi repo-awareness — this repository ships its own instructions/agents. Respect them as context:';
@@ -253,6 +275,9 @@ function main() {
253
275
  seen.add(f);
254
276
  msg += `\n - ${f}`;
255
277
  }
278
+ if (unlisted > 0) {
279
+ msg += `\n - ${unlisted} nested CLAUDE.md/AGENTS.md file(s) under folder names with unusual characters (not listed; find them with a file search)`;
280
+ }
256
281
  if (repoAgents) msg += `\n - ${repoAgents}`;
257
282
  msg += DIRECTIVE;
258
283
 
@@ -0,0 +1,121 @@
1
+ #!/usr/bin/env node
2
+ // hooks/session-start/ensure-default-config.mjs — SessionStart hook — create a default
3
+ // .somi/config.json when the project has none.
4
+ //
5
+ // Without a config every agent runs at the built-in default ceiling, so the agents built for the
6
+ // strongest tier (reviewers, designer, security-reviewer, ...) would silently run lower. The default
7
+ // file pins each agent to the highest tier it declares and sets the ceiling; see
8
+ // scripts/lib/cost-defaults.mjs for the table and the exact text this hook writes.
9
+ //
10
+ // Guarantees (a project's own files are untrusted, and a hook must never block a session):
11
+ // - Acts only when NOTHING exists at <root>/.somi/config.json (lstat ENOENT). An existing file of
12
+ // any kind — valid, invalid JSON, a symlink (even dangling), a directory — is left untouched.
13
+ // - `.somi` must be a real directory (lstat) or absent; a symlink or file there writes nothing.
14
+ // It is created with mode 0700 only when absent.
15
+ // - The file is created with O_CREAT|O_EXCL|O_NOFOLLOW, so a race or a planted link at the path
16
+ // can never be written through. Nothing else is written anywhere.
17
+ // - The content is a fixed constant, never derived from any existing file.
18
+ // - Exit code is 0 on every path; no file content or error text is printed. On success it prints
19
+ // one short, fixed notice through the same SessionStart channel the sibling hook uses.
20
+ // - When a regular config file already exists, it is only READ (O_NOFOLLOW, at most 64 KiB): if it
21
+ // parses to an object with no own cost.agents["somi-security-reviewer"] tier, or one pinned below high,
22
+ // one fixed notice says so (a distinct text for each).
23
+ // Nothing from the file reaches the notice, and the file is never written.
24
+
25
+ import fs from 'node:fs';
26
+ import path from 'node:path';
27
+ import { fileURLToPath, pathToFileURL } from 'node:url';
28
+ import { projectRoot, contextOutput, runHook } from '../lib/common.mjs';
29
+
30
+ const DEFAULTS_LIB = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', '..', 'scripts', 'lib', 'cost-defaults.mjs');
31
+ const CREATE = fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL | (fs.constants.O_NOFOLLOW ?? 0);
32
+
33
+ const MAX_READ = 64 * 1024;
34
+ const READ = fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW ?? 0) | (fs.constants.O_NONBLOCK ?? 0);
35
+ const LOW_PIN_NOTICE = 'SoMi: .somi/config.json pins somi-security-reviewer below high; its security reviews run at that lower tier.';
36
+ const PIN_NOTICE = 'SoMi: .somi/config.json has no cost.agents pin for somi-security-reviewer, so it runs at the ceiling (below high by default). Pin it under cost.agents to keep the strong pass.';
37
+
38
+ function writeAll(fd, text) {
39
+ const buf = Buffer.from(text);
40
+ for (let off = 0; off < buf.length;) off += fs.writeSync(fd, buf, off, buf.length - off);
41
+ }
42
+
43
+ // For a config that parses to an object: 'missing' when it has no own, valid-tier
44
+ // cost.agents["somi-security-reviewer"], 'low' when that entry is below high, else null. Any doubt
45
+ // (symlink, not a regular file, oversize, unparsable) is null: the resolver reports those.
46
+ function securityPinState(file) {
47
+ let fd;
48
+ try {
49
+ fd = fs.openSync(file, READ);
50
+ if (!fs.fstatSync(fd).isFile()) return null;
51
+ const buf = Buffer.alloc(MAX_READ + 1);
52
+ let n = 0;
53
+ while (n < buf.length) {
54
+ const got = fs.readSync(fd, buf, n, buf.length - n, null);
55
+ if (got === 0) break;
56
+ n += got;
57
+ }
58
+ if (n > MAX_READ) return null;
59
+ const cfg = JSON.parse(buf.toString('utf8', 0, n));
60
+ if (cfg === null || typeof cfg !== 'object' || Array.isArray(cfg)) return null;
61
+ const agents = cfg.cost && typeof cfg.cost === 'object' ? cfg.cost.agents : undefined;
62
+ const tier = agents && typeof agents === 'object' && Object.hasOwn(agents, 'somi-security-reviewer') ? agents['somi-security-reviewer'] : undefined;
63
+ if (tier === 'low' || tier === 'medium') return 'low';
64
+ return tier === 'high' ? null : 'missing';
65
+ } catch {
66
+ return null;
67
+ } finally {
68
+ if (fd !== undefined) try { fs.closeSync(fd); } catch { /* already closed */ }
69
+ }
70
+ }
71
+
72
+ function lstatOrNull(p) {
73
+ try { return fs.lstatSync(p); } catch (e) { if (e.code === 'ENOENT') return null; throw e; }
74
+ }
75
+
76
+ async function main() {
77
+ try {
78
+ const root = projectRoot();
79
+ if (!fs.statSync(root).isDirectory()) return;
80
+ const somi = path.join(root, '.somi');
81
+ const file = path.join(somi, 'config.json');
82
+ const dir = lstatOrNull(somi);
83
+ if (dir && !dir.isDirectory()) return; // a symlink or a file: write nothing
84
+ const existing = dir ? lstatOrNull(file) : null;
85
+ if (existing) { // anything already there is left alone; a regular file is only read
86
+ const pin = existing.isFile() ? securityPinState(file) : null;
87
+ if (pin) contextOutput('SessionStart', pin === 'low' ? LOW_PIN_NOTICE : PIN_NOTICE);
88
+ return;
89
+ }
90
+ const { serializeDefaultConfig, buildDefaultConfig } = await import(pathToFileURL(DEFAULTS_LIB).href);
91
+ const text = serializeDefaultConfig();
92
+ const ceiling = buildDefaultConfig().cost.ceiling;
93
+ if (!dir) {
94
+ try {
95
+ fs.mkdirSync(somi, { mode: 0o700 });
96
+ } catch (e) {
97
+ if (e.code !== 'EEXIST') return;
98
+ if (!lstatOrNull(somi)?.isDirectory()) return; // lost a race to a link or a file
99
+ }
100
+ }
101
+ const fd = fs.openSync(file, CREATE, 0o644);
102
+ try {
103
+ writeAll(fd, text);
104
+ } catch {
105
+ // We created it a moment ago; do not leave half a file, but never remove a swapped path.
106
+ try {
107
+ const mine = fs.fstatSync(fd);
108
+ const now = lstatOrNull(file);
109
+ if (now && now.dev === mine.dev && now.ino === mine.ino) fs.rmSync(file, { force: true });
110
+ } catch { /* leave it */ }
111
+ fs.closeSync(fd);
112
+ return;
113
+ }
114
+ fs.closeSync(fd);
115
+ contextOutput('SessionStart', `SoMi created .somi/config.json with default cost settings: ceiling ${ceiling}, each agent pinned to its default tier. Run /somi-config, or edit "cost" in .somi/config.json, to change them.`);
116
+ } catch {
117
+ // Any failure (read-only directory, EEXIST race, missing plugin file) is a silent no-op.
118
+ }
119
+ }
120
+
121
+ runHook(() => main().then(() => { process.exitCode = 0; }));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@skathio/somi",
3
- "version": "3.1.0",
3
+ "version": "4.0.0",
4
4
  "scripts": {
5
5
  "test": "bash scripts/validate.sh",
6
6
  "eval:behavioral": "node tests/evals/run.mjs",
@@ -45,4 +45,4 @@ Prefer reversible actions. When asked to do something irreversible:
45
45
 
46
46
  Going fast is the **result** of getting (1)–(3) right, not a competing axis. Cutting maintainability to
47
47
  ship sooner usually slows the next ten changes. When you are tempted to take a shortcut, name it explicitly
48
- and let the human decide.
48
+ and let the human decide; one you keep in code carries a comment `shortcut: <the limit>, <when to upgrade>`.
@@ -79,5 +79,5 @@ Default to secure. Every change is reviewed through this lens, not just changes
79
79
 
80
80
  ## When in doubt
81
81
 
82
- Pause and invoke the **`security-reviewer`** agent before merging. Auth, crypto, input validation, file
82
+ Pause and invoke the **`somi-security-reviewer`** agent before merging. Auth, crypto, input validation, file
83
83
  uploads, deserialization, and template rendering are five areas where "I think it's fine" loses outages.
@@ -6,6 +6,9 @@ How to work with humans, and how agents hand off to each other inside SOMI.
6
6
 
7
7
  - **Match the question to the answer.** A yes/no question gets "yes" or "no" first, then the reasoning.
8
8
  - **Don't bury the lede.** If you blocked, broke, or skipped something, surface it in the first line.
9
+ - **End with what you didn't do.** A reply that did work ends with one or two lines: what you
10
+ skipped or did not check, and any risk the user must know. A summary that lists only what worked
11
+ reads as a clean bill it isn't.
9
12
  - **Show your evidence.** When you claim something exists, link to the file. When you claim
10
13
  something works, name the test or output. When you assume, mark the assumption.
11
14
  - **Challenge the premise, not just the architecture.** Restating a request is not endorsing it.
@@ -20,7 +23,7 @@ How to work with humans, and how agents hand off to each other inside SOMI.
20
23
  user proposes a custom option) and **Discover** (you ask narrowing questions to guide the
21
24
  choice). Record verified decisions in `decisions.md`. When you are running as a Tasked
22
25
  subagent that cannot reach the user, **return the decisions for the orchestrator to present**
23
- (the batch round-trip in `agents/planner.md`) — never answer them yourself and mark them
26
+ (the batch round-trip in `agents/somi-planner.md`) — never answer them yourself and mark them
24
27
  verified.
25
28
  - **Stop asking, start showing** when ambiguity is small. Don't ping the human for every
26
29
  micro-decision; pick the most reasonable default for non-architectural calls and call it out.
@@ -33,7 +36,7 @@ The workflows compose. Each one has a clean handoff shape — the build trio is
33
36
 
34
37
  ### Discovery → Planning
35
38
 
36
- Discovery (the [`discovery-analyst`](../agents/discovery-analyst.md), greenfield only) produces the
39
+ Discovery (the [`somi-discovery-analyst`](../agents/somi-discovery-analyst.md), greenfield only) produces the
37
40
  `.somi/rd/<slug>/` foundation: `research-report.md`, `brd.md`, `srs.md`, `frd.md`, `sdd.md`,
38
41
  `tdd.md`, plus `decisions.md`, `diary.md`, and a `README.md` index with a traceability map. The
39
42
  planner consumes it: the **SRS/FRD are the requirements source** (`spec.md` cites `FR-*`/`NFR-*`
@@ -78,10 +81,10 @@ plan-change protocol fires — don't patch symptoms in code when the plan needs
78
81
  ## When to escalate up the agent chain
79
82
 
80
83
  Coders escalate to:
81
- - **`security-reviewer`** before touching auth/crypto/input validation in a non-trivial way.
82
- - **`architecture-reviewer`** before introducing a new module, service, or contract boundary.
83
- - **`test-strategist`** when tests feel wrong-shaped (too many mocks, too slow, too flaky).
84
- - **`refactorer`** when the task is "patch around an antipattern" and the antipattern keeps
84
+ - **`somi-security-reviewer`** before touching auth/crypto/input validation in a non-trivial way.
85
+ - **`somi-architecture-reviewer`** before introducing a new module, service, or contract boundary.
86
+ - **`somi-test-strategist`** when tests feel wrong-shaped (too many mocks, too slow, too flaky).
87
+ - **`somi-refactorer`** when the task is "patch around an antipattern" and the antipattern keeps
85
88
  biting.
86
89
 
87
90
  Planners escalate when the request is **bigger than it looked**: stop, produce a scoping note,
package/rules/CLAUDE.md CHANGED
@@ -52,7 +52,8 @@ the full treatment; read that file when you **enter its domain** (see "How to lo
52
52
  the hooks would gate. ([`40`](./40-engineering-practices.md))
53
53
  - **Collaboration:** challenge the premise, not just the architecture; match the answer to the
54
54
  question; recommend with concrete options, the user decides direction; surface tradeoffs and
55
- blockers in the first line. ([`50`](./50-collaboration.md))
55
+ blockers in the first line; end with one or two lines: what you skipped or did not check, and any
56
+ risk the user must know. ([`50`](./50-collaboration.md))
56
57
  - **Reasoning craft:** before writing, parse trajectory (what will the reader do with this in 10
57
58
  minutes; answer the predictable next question now) → shape (choose the deliverable's form before
58
59
  the words; put the answer first) → verify (mark inference as inference; never trade "I confirmed"
@@ -154,15 +155,15 @@ See [docs/HOOKS.md](../docs/HOOKS.md) for the full list and how to extend it.
154
155
 
155
156
  SOMI provides specialized agents in `agents/`. Use them when the work matches their description:
156
157
 
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.
160
- - **`coder`** — to execute against an approved plan or do a constrained implementation task.
161
- - **`reviewer`** — before declaring work done; before merging; whenever you want a skeptical second opinion.
162
- - **`security-reviewer`** — auth, crypto, input handling, third-party data, file uploads, anything touching secrets.
163
- - **`architecture-reviewer`** — new modules, new services, contract changes, dependency direction changes.
164
- - **`test-strategist`** — flaky tests, missing coverage, deciding integration vs. unit, mocking decisions.
165
- - **`refactorer`** — when the right move is "untangle this first" rather than "patch around it".
158
+ - **`somi-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`.**
159
+ - **`somi-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`.**
160
+ - **`somi-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.
161
+ - **`somi-coder`** — to execute against an approved plan or do a constrained implementation task.
162
+ - **`somi-reviewer`** — before declaring work done; before merging; whenever you want a skeptical second opinion.
163
+ - **`somi-security-reviewer`** — auth, crypto, input handling, third-party data, file uploads, anything touching secrets.
164
+ - **`somi-architecture-reviewer`** — new modules, new services, contract changes, dependency direction changes.
165
+ - **`somi-test-strategist`** — flaky tests, missing coverage, deciding integration vs. unit, mocking decisions.
166
+ - **`somi-refactorer`** — when the right move is "untangle this first" rather than "patch around it".
166
167
 
167
168
  Full catalogue and escalation rules: [docs/AGENTS.md](../docs/AGENTS.md).
168
169
 
@@ -0,0 +1,85 @@
1
+ // agent-info.mjs — the read-only somi_agent_info lookup: the agent catalog, or one identifier (a
2
+ // canonical name or a registered alias) normalised through agent-registry.mjs and resolved through the
3
+ // shared dispatch resolver with persist:false, so a lookup reports what a dispatch would get right now
4
+ // and writes nothing (no ceiling argument is accepted, and an env ceiling is never remembered).
5
+ //
6
+ // Pure apart from the resolver's reads: the caller supplies the project root lookup (the MCP server's
7
+ // can be a roots/list round trip) and the install root, and turns {ok, ...} into its own surface.
8
+
9
+ import { buildRegistry, normalize, agentTypeFor, catalog, ORCHESTRATOR } from './agent-registry.mjs';
10
+ import { resolveDispatch, EXIT_USAGE, EXIT_UNKNOWN_AGENT } from './dispatch-resolver.mjs';
11
+
12
+ // Built once: an alias collision fails at import, before any lookup answers.
13
+ const REGISTRY = buildRegistry();
14
+ const HOST_RE = /^[a-z][a-z0-9-]{0,31}$/;
15
+
16
+ export const AGENT_INFO_TOOL = {
17
+ name: 'somi_agent_info',
18
+ description:
19
+ 'Read-only agent registry and dispatch lookup. Without `agent`: the catalog of every canonical ' +
20
+ 'SoMi agent with the aliases hosts actually register for it and its default tier. With `agent` ' +
21
+ '(a canonical name such as "somi-coder" or a registered alias such as "somi:somi-coder"): the ' +
22
+ 'canonical agent, the alias that matched, `agent_type` (the id to pass as the host subagent ' +
23
+ 'type), and the tier and model it would run at right now on `host` — from the same resolver as ' +
24
+ 'somi_resolve, but nothing is written: no ceiling is set or remembered. Failures: 64 invalid ' +
25
+ 'identifier or arguments, 65 unknown agent or alias (never routed to another agent), 67 ' +
26
+ 'project environment failure (as somi_resolve).',
27
+ inputSchema: {
28
+ type: 'object',
29
+ properties: {
30
+ agent: { type: 'string', description: 'canonical name or registered alias; omit for the catalog' },
31
+ host: { type: 'string', description: '"claude-code" or "copilot"; defaults to "claude-code"' },
32
+ project_dir: { type: 'string', description: 'absolute path of the consuming project, as for somi_resolve (lookup only)' },
33
+ },
34
+ },
35
+ };
36
+
37
+ const fail = (code, message) => ({ ok: false, code, message });
38
+
39
+ /**
40
+ * @param {{agent?: unknown, host?: unknown}} args
41
+ * @param {{resolveRoot: () => Promise<{ok: boolean, root?: string, code?: number, message?: string}>, installRoot: string}} env
42
+ * @returns {Promise<{ok: true, result: object} | {ok: false, code: number, message: string}>}
43
+ */
44
+ export async function agentInfo(args, { resolveRoot, installRoot }) {
45
+ const host = args?.host;
46
+ if (host !== undefined && (typeof host !== 'string' || !HOST_RE.test(host))) {
47
+ return fail(EXIT_USAGE, `host must be a lowercase host name, got ${JSON.stringify(host)}`);
48
+ }
49
+ if (args?.agent === undefined) return { ok: true, result: { agents: catalog(REGISTRY) } };
50
+ const n = normalize(REGISTRY, args.agent);
51
+ if (!n.ok) return fail(n.reason === 'invalid' ? EXIT_USAGE : EXIT_UNKNOWN_AGENT, n.message);
52
+ const HOST = host || 'claude-code';
53
+ const identity = {
54
+ requested_as: args.agent,
55
+ canonical_name: n.canonical,
56
+ matched_alias: n.matched_alias,
57
+ aliases: REGISTRY.aliasesOf.get(n.canonical).filter((a) => a !== n.matched_alias),
58
+ agent_type: agentTypeFor(REGISTRY, n.canonical, HOST),
59
+ host: HOST,
60
+ };
61
+ if (n.canonical === ORCHESTRATOR) {
62
+ return { ok: true, result: { ...identity, role: 'orchestrator', dispatch: null, reason: 'the front door is selected by the user, never dispatched; the host binds its model' } };
63
+ }
64
+ const root = await resolveRoot();
65
+ if (!root.ok) return fail(root.code, root.message);
66
+ const outcome = resolveDispatch({ agent: n.canonical, host: HOST, projectRoot: root.root, installRoot, persist: false });
67
+ if (!outcome.ok) return outcome;
68
+ const r = outcome.result;
69
+ return {
70
+ ok: true,
71
+ result: {
72
+ ...identity,
73
+ role: 'specialist',
74
+ session_ceiling: { value: r.ceiling, source: r.ceiling_source, origin: r.ceiling_origin },
75
+ default_tier: r.declared[0],
76
+ dispatch_tier: r.tier,
77
+ tier_source: r.tier_source,
78
+ degraded: r.degraded,
79
+ model: r.model,
80
+ ...(r.model_candidates ? { model_candidates: r.model_candidates } : {}),
81
+ enforced: r.enforced,
82
+ ...(r.reason ? { reason: r.reason } : {}),
83
+ },
84
+ };
85
+ }