@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
@@ -0,0 +1,102 @@
1
+ // cost-config-edit.mjs — the pure edit step shared by scripts/somi-config.mjs, the cost-lowering
2
+ // PreToolUse hook and the tests: parse a key, check a tier, and apply set/unset/init to an
3
+ // already-parsed config. No I/O. Only cost.ceiling and cost.agents.<name> can be edited.
4
+
5
+ import { validateCostConfig, quote } from './cost-config.mjs';
6
+ import { VALID_COSTS, MODEL_ID_RE, MAX_MODEL_CANDIDATES, mergeHostMapping, resolveModelCandidates } from './cost-model.mjs';
7
+ import { buildDefaultConfig } from './cost-defaults.mjs';
8
+
9
+ // A caller mistake (bad key, tier or name), as opposed to a problem with the project's files.
10
+ export class EditError extends Error {}
11
+
12
+ const KEY_RE = /^cost\.(ceiling|agents\.([a-z][a-z0-9-]*)|mapping\.([a-z][a-z0-9-]{0,31})(?:\.(low|medium|high))?)$/;
13
+
14
+ /**
15
+ * -> {kind:'ceiling'} | {kind:'agent', name} | {kind:'mapping', host, tier?}; throws EditError for any
16
+ * other key. `cost.mapping.<host>.<tier>` is set; `cost.mapping.<host>` (the whole host map) is unset.
17
+ */
18
+ export function parseKey(key) {
19
+ const m = KEY_RE.exec(key);
20
+ if (!m) throw new EditError(`only cost.ceiling, cost.agents.<name> and cost.mapping.<host>[.<tier>] can be used, not ${quote(key)}`);
21
+ if (m[1] === 'ceiling') return { kind: 'ceiling' };
22
+ if (m[2] !== undefined) return { kind: 'agent', name: m[2] };
23
+ return { kind: 'mapping', host: m[3], tier: m[4] };
24
+ }
25
+
26
+ /** A model value: one id, or a comma-separated preference list (#35) -> a string or an array. */
27
+ export function parseModels(v) {
28
+ const list = typeof v === 'string' ? v.split(',').map((x) => x.trim()) : [];
29
+ if (list.length === 0 || list.length > MAX_MODEL_CANDIDATES || list.some((x) => !MODEL_ID_RE.test(x)) || new Set(list).size !== list.length) {
30
+ throw new EditError(`the value must be a model id or up to ${MAX_MODEL_CANDIDATES} distinct comma-separated ids, got ${quote(v)}`);
31
+ }
32
+ return list.length === 1 ? list[0] : list;
33
+ }
34
+
35
+ /** The tiers a named host's map still lacks (a host in cost.mapping replaces its whole tier map). */
36
+ export function missingMappingTiers(cost, host) {
37
+ const tiers = cost?.mapping?.[host];
38
+ return tiers ? VALID_COSTS.filter((t) => !Object.hasOwn(tiers, t)) : [];
39
+ }
40
+
41
+ export function parseTier(v) {
42
+ if (!VALID_COSTS.includes(v)) throw new EditError(`the tier must be one of ${VALID_COSTS.join('|')}, got ${quote(v)}`);
43
+ return v;
44
+ }
45
+
46
+ /** Throws unless the whole cost block is legal (keys, agent names, tiers, ceiling value). */
47
+ export function validateCostBlock(cost) {
48
+ validateCostConfig(cost);
49
+ if (cost && cost.mapping !== undefined) {
50
+ const merged = mergeHostMapping({}, cost.mapping);
51
+ for (const host of Object.keys(merged)) for (const tier of Object.keys(merged[host])) resolveModelCandidates(tier, host, merged);
52
+ }
53
+ if (cost && cost.ceiling !== undefined && !VALID_COSTS.includes(cost.ceiling)) {
54
+ throw new Error(`cost-ceiling: cost.ceiling expected one of ${VALID_COSTS.join('|')}, got ${quote(cost.ceiling)}`);
55
+ }
56
+ }
57
+
58
+ /**
59
+ * Applies one edit to `cfg` (a parsed config object, or null for an absent file) IN PLACE where it
60
+ * can, and returns {next, changed}. `action` is set|unset|init. A set or init on an absent file
61
+ * starts from the default config; an unset of an absent file or entry changes nothing. The result is
62
+ * not validated here: callers run validateCostBlock(next.cost) so each can report it its own way.
63
+ */
64
+ export function applyEdit(cfg, { action, key, value }) {
65
+ const absent = cfg === null || cfg === undefined;
66
+ if (action === 'init') return absent ? { next: buildDefaultConfig(), changed: true } : { next: cfg, changed: false };
67
+ const k = parseKey(key);
68
+ if (action === 'unset') {
69
+ if (k.kind === 'mapping' && k.tier === undefined) {
70
+ if (absent || !(cfg.cost?.mapping && Object.hasOwn(cfg.cost.mapping, k.host))) return { next: cfg ?? {}, changed: false };
71
+ delete cfg.cost.mapping[k.host];
72
+ if (Object.keys(cfg.cost.mapping).length === 0) delete cfg.cost.mapping;
73
+ return { next: cfg, changed: true };
74
+ }
75
+ if (k.kind !== 'agent') throw new EditError('only cost.agents.<name> and cost.mapping.<host> can be unset');
76
+ if (absent || !(cfg.cost?.agents && Object.hasOwn(cfg.cost.agents, k.name))) return { next: cfg ?? {}, changed: false };
77
+ delete cfg.cost.agents[k.name];
78
+ return { next: cfg, changed: true };
79
+ }
80
+ if (action !== 'set') throw new EditError('the action must be set, unset or init');
81
+ if (k.kind === 'mapping') {
82
+ if (k.tier === undefined) throw new EditError('set one tier at a time: cost.mapping.<host>.<low|medium|high>');
83
+ const models = parseModels(value);
84
+ const base = absent ? buildDefaultConfig() : cfg;
85
+ const before = JSON.stringify(base.cost ?? null);
86
+ if (base.cost === undefined || base.cost === null) base.cost = {};
87
+ if (base.cost.mapping === undefined) base.cost.mapping = {};
88
+ if (base.cost.mapping[k.host] === undefined) base.cost.mapping[k.host] = {};
89
+ base.cost.mapping[k.host][k.tier] = models;
90
+ return { next: base, changed: absent || JSON.stringify(base.cost) !== before };
91
+ }
92
+ const tier = parseTier(value);
93
+ const next = absent ? buildDefaultConfig() : cfg;
94
+ const before = JSON.stringify(next.cost ?? null);
95
+ if (next.cost === undefined || next.cost === null) next.cost = {};
96
+ if (k.kind === 'ceiling') next.cost.ceiling = tier;
97
+ else {
98
+ if (next.cost.agents === undefined) next.cost.agents = {};
99
+ next.cost.agents[k.name] = tier;
100
+ }
101
+ return { next, changed: absent || JSON.stringify(next.cost) !== before };
102
+ }
@@ -0,0 +1,64 @@
1
+ // cost-config.mjs — the one validator for the `cost.*` block of .somi/config.json.
2
+ //
3
+ // The block is committed, cloned input (untrusted), so every consumer must agree on which keys
4
+ // and values are legal; keeping that decision here stops readers from drifting apart. Errors keep
5
+ // the `cost-ceiling:` prefix so existing callers' config-problem mapping is unchanged.
6
+
7
+ import { VALID_COSTS } from './cost-model.mjs';
8
+
9
+ export const COST_CONFIG_KEYS = Object.freeze(['ceiling', 'mapping', 'agents']);
10
+
11
+ // The one agent-name pattern; dispatch-resolver.mjs re-exports it (that module imports this one, so
12
+ // the dependency runs one way).
13
+ export const AGENT_NAME_RE = /^[a-z][a-z0-9-]*$/;
14
+
15
+ // "constructor" and "prototype" satisfy AGENT_NAME_RE, so the name pattern alone does not keep them
16
+ // out of a map that later code may index with a plain lookup.
17
+ const FORBIDDEN_KEYS = Object.freeze(['__proto__', 'constructor', 'prototype']);
18
+
19
+ const where = 'cost in .somi/config.json';
20
+
21
+ // Committed config reaches the model's context through these messages: quote every echoed value and
22
+ // bound its length so a hostile key cannot inject lines or escape sequences.
23
+ export const quote = (v) => {
24
+ const q = JSON.stringify(v) ?? String(v);
25
+ return q.length > 80 ? `${q.slice(0, 80)}...` : q;
26
+ };
27
+
28
+ // -> a frozen null-prototype copy, so a plain lookup of a missing name ("constructor") finds nothing.
29
+ function validateAgents(agents) {
30
+ if (agents === null || typeof agents !== 'object' || Array.isArray(agents)) {
31
+ throw new Error(`cost-ceiling: cost.agents in .somi/config.json expected an object, got ${quote(agents)}`);
32
+ }
33
+ for (const [name, tier] of Object.entries(agents)) {
34
+ if (FORBIDDEN_KEYS.includes(name)) {
35
+ throw new Error(`cost-ceiling: cost.agents in .somi/config.json has a forbidden agent name ${quote(name)}`);
36
+ }
37
+ if (!AGENT_NAME_RE.test(name)) {
38
+ throw new Error(`cost-ceiling: cost.agents in .somi/config.json has an invalid agent name ${quote(name)} (expected ${AGENT_NAME_RE})`);
39
+ }
40
+ if (!VALID_COSTS.includes(tier)) {
41
+ throw new Error(`cost-ceiling: cost.agents.${name} expected one of ${VALID_COSTS.join('|')}, got ${quote(tier)}`);
42
+ }
43
+ }
44
+ return Object.freeze(Object.assign(Object.create(null), agents));
45
+ }
46
+
47
+ /**
48
+ * Validates a parsed `cost` value and returns it (with `agents` as a frozen null-prototype map). `undefined`/`null` mean unconfigured.
49
+ * `ceiling` and `mapping` values are checked where they are used (validateCeiling, resolveModel);
50
+ * this decides only which keys are legal and that `agents` is a name-to-tier map.
51
+ */
52
+ export function validateCostConfig(cost) {
53
+ if (cost === undefined || cost === null) return {};
54
+ if (typeof cost !== 'object' || Array.isArray(cost)) {
55
+ throw new Error(`cost-ceiling: ${where} expected an object, got ${quote(cost)}`);
56
+ }
57
+ for (const key of Object.keys(cost)) {
58
+ if (!COST_CONFIG_KEYS.includes(key)) {
59
+ throw new Error(`cost-ceiling: ${where} has an unrecognized key ${quote(key)}`);
60
+ }
61
+ }
62
+ if (cost.agents === undefined) return cost;
63
+ return { ...cost, agents: validateAgents(cost.agents) };
64
+ }
@@ -0,0 +1,51 @@
1
+ // cost-defaults.mjs — the default .somi/config.json `cost` block a project with no config gets.
2
+ //
3
+ // The table is the one source of each agent's default tier (agent files carry no tier of their own).
4
+ // It is literal data, not read from agents/ at runtime: the code that writes the file runs in a
5
+ // consuming project where only the plugin install exists. tests/scripts/cost-defaults.sh keeps its
6
+ // keys equal to agents/*.md minus the front-door `somi` agent, which is exempt from cost resolution
7
+ // (the host binds its model).
8
+ // Tier names only; which model a tier means is cost.mapping's job.
9
+
10
+ import { DEFAULT_CEILING } from './cost-ceiling.mjs';
11
+ import { validateCostConfig } from './cost-config.mjs';
12
+
13
+ export const DEFAULT_CEILING_TIER = DEFAULT_CEILING;
14
+
15
+ // Null-prototype and frozen: a plain lookup of "constructor" finds nothing, and nothing can edit it.
16
+ export const AGENT_DEFAULT_TIERS = Object.freeze(Object.assign(Object.create(null), {
17
+ 'somi-architecture-reviewer': 'high',
18
+ 'somi-atlas': 'high',
19
+ 'somi-coder': 'medium',
20
+ 'somi-designer': 'high',
21
+ 'somi-discovery-analyst': 'high',
22
+ 'somi-impact': 'medium',
23
+ 'somi-incident': 'medium',
24
+ 'somi-plan-reviewer': 'high',
25
+ 'somi-planner': 'medium',
26
+ 'somi-pr': 'medium',
27
+ 'somi-refactor-designer': 'high',
28
+ 'somi-refactorer': 'medium',
29
+ 'somi-reviewer': 'high',
30
+ 'somi-sdlc-reviewer': 'high',
31
+ 'somi-security-reviewer': 'high',
32
+ 'somi-test-strategist': 'high',
33
+ }));
34
+
35
+ /**
36
+ * The exact object a fresh .somi/config.json holds: `{cost: {ceiling, agents}}`, agents sorted by
37
+ * name so the bytes are stable. `table` is overridable for tests. Throws if the shared validator
38
+ * rejects it.
39
+ */
40
+ export function buildDefaultConfig(table = AGENT_DEFAULT_TIERS) {
41
+ const agents = {};
42
+ for (const name of Object.keys(table).sort()) agents[name] = table[name];
43
+ const cost = { ceiling: DEFAULT_CEILING_TIER, agents };
44
+ validateCostConfig(cost);
45
+ return { cost };
46
+ }
47
+
48
+ /** The file text: JSON, 2-space indent, trailing newline. The one serialization every writer uses. */
49
+ export function serializeDefaultConfig(table = AGENT_DEFAULT_TIERS) {
50
+ return `${JSON.stringify(buildDefaultConfig(table), null, 2)}\n`;
51
+ }
@@ -0,0 +1,89 @@
1
+ // cost-lowering.mjs — does moving from one config to another LOWER any agent's tier?
2
+ //
3
+ // Pure. Compares EFFECTIVE tiers (the agent's cost.agents entry, else the ceiling: the resolver's own
4
+ // rule, via decideDispatch) for every agent in the default table and any named in either config. It
5
+ // answers one question for the PreToolUse hook and the CLI's --refuse-lowering: does this change need
6
+ // the user? Reasons are fixed strings; nothing from either config is ever echoed.
7
+ //
8
+ // A change lowers when any of these holds:
9
+ // - security-reviewer would run below high (flagged even if unchanged from before, so an explicit low
10
+ // pin is always flagged; an identical before and after is a no-op and never lowers)
11
+ // - the ceiling is lower than before
12
+ // - an agent's effective tier is lower than before; when that is a removed pin above the ceiling
13
+ // the reason says so
14
+ // - cost.mapping changes in any way (which model a tier means cannot be ranked here)
15
+ // - the new config is not an object, or its cost block is not valid
16
+ // Whether a state file appears later cannot change a verdict: a config that has NO cost.ceiling after the
17
+ // change is judged against the worst case, so deleting cost.ceiling (or unpinning an agent in a config
18
+ // without one) is a lowering unless the removed value was already `low`. Otherwise a model could delete the
19
+ // ceiling first and plant a persisted low ceiling afterwards.
20
+ // The ceiling an absent cost.ceiling falls back to is the resolver's: a ceiling an earlier --ceiling or
21
+ // env call persisted (origin cli/env), else the default. `root` (the project) is needed to read that
22
+ // state, read-only; it is applied on BOTH sides of the comparison, so deleting cost.ceiling is judged by
23
+ // the value that takes over. SOMI_COST_CEILING of the session is not known here and is not considered.
24
+ // Raises and no-ops never lower. Both arguments are parsed config objects ({} or null for an absent
25
+ // file); `after` may also be anything unparsed (null, a string, an array), which counts as invalid.
26
+
27
+ import { decideDispatch, DEFAULT_CEILING, loadState } from './cost-ceiling.mjs';
28
+ import { VALID_COSTS } from './cost-model.mjs';
29
+ import { AGENT_DEFAULT_TIERS } from './cost-defaults.mjs';
30
+ import { validateCostBlock } from './cost-config-edit.mjs';
31
+
32
+ export const REASONS = Object.freeze({
33
+ security: 'security-reviewer would run below high',
34
+ ceiling: 'the ceiling would be lowered',
35
+ agent: 'an agent tier would be lowered',
36
+ pin: 'a pin above the ceiling would be removed',
37
+ invalid: 'the new config is not valid',
38
+ mapping: 'a tier would be mapped to a different model',
39
+ });
40
+
41
+ const rank = (t) => VALID_COSTS.indexOf(t);
42
+ const isObj = (x) => x !== null && typeof x === 'object' && !Array.isArray(x);
43
+
44
+ // The persisted ceiling that would take over when cost.ceiling is absent, or undefined.
45
+ function stateCeiling(root) {
46
+ if (!root) return undefined;
47
+ try {
48
+ const st = loadState(root);
49
+ return st && ['cli', 'env'].includes(st.ceiling_origin) ? st.ceiling : undefined;
50
+ } catch {
51
+ return undefined; // an unreadable state file is the resolver's error to report, not a reason here
52
+ }
53
+ }
54
+
55
+ // Tolerant on purpose: a bad value in `before` must not make the comparison throw.
56
+ function view(cfg, fallback) {
57
+ const cost = isObj(cfg) && isObj(cfg.cost) ? cfg.cost : {};
58
+ const ceiling = VALID_COSTS.includes(cost.ceiling) ? cost.ceiling : fallback;
59
+ const agents = isObj(cost.agents) ? cost.agents : {};
60
+ const pin = (name) => (Object.hasOwn(agents, name) && VALID_COSTS.includes(agents[name]) ? agents[name] : undefined);
61
+ const tier = (name) => decideDispatch(AGENT_DEFAULT_TIERS[name] ?? ceiling, ceiling, pin(name)).selected;
62
+ return { ceiling, pin, tier, names: Object.keys(agents), json: JSON.stringify(cost), mapping: JSON.stringify(cost.mapping ?? null) };
63
+ }
64
+
65
+ /** @returns {{lowers: boolean, reasons: string[]}}; `root` is the project directory (for the persisted ceiling). */
66
+ export function lowers(before, after, root) {
67
+ if (!isObj(after)) return { lowers: true, reasons: [REASONS.invalid] };
68
+ try { validateCostBlock(after.cost); } catch { return { lowers: true, reasons: [REASONS.invalid] }; }
69
+ const fallback = stateCeiling(root) ?? DEFAULT_CEILING;
70
+ const b = view(before, fallback);
71
+ const a = view(after, fallback);
72
+ const ceilingGone = isObj(before?.cost) && VALID_COSTS.includes(before.cost.ceiling) && !(isObj(after.cost) && VALID_COSTS.includes(after.cost.ceiling));
73
+ const worst = (name) => decideDispatch(AGENT_DEFAULT_TIERS[name] ?? 'low', 'low', undefined).selected;
74
+ if (a.json === b.json) return { lowers: false, reasons: [] };
75
+ const reasons = new Set();
76
+ // Which model a tier means is not comparable here (no prices), so any mapping change needs the user:
77
+ // pointing `high` at a cheap model is a lowering this function could not otherwise see.
78
+ if (a.mapping !== b.mapping) reasons.add(REASONS.mapping);
79
+ if (rank(a.tier('somi-security-reviewer')) < rank('high')) reasons.add(REASONS.security);
80
+ if (rank(a.ceiling) < rank(b.ceiling) || (ceilingGone && rank(b.ceiling) > rank('low'))) reasons.add(REASONS.ceiling);
81
+ const noCeiling = !(isObj(after.cost) && VALID_COSTS.includes(after.cost.ceiling));
82
+ for (const name of new Set([...Object.keys(AGENT_DEFAULT_TIERS), ...b.names, ...a.names])) {
83
+ const removedPin = b.pin(name) !== undefined && a.pin(name) === undefined;
84
+ const aTier = removedPin && noCeiling ? worst(name) : a.tier(name);
85
+ if (rank(aTier) >= rank(b.tier(name))) continue;
86
+ reasons.add(removedPin ? REASONS.pin : REASONS.agent);
87
+ }
88
+ return { lowers: reasons.size > 0, reasons: [...reasons] };
89
+ }
@@ -9,7 +9,7 @@ export const VALID_COSTS = Object.freeze(['low', 'medium', 'high']);
9
9
  // A mapped model can come from committed, cloned .somi/config.json -- untrusted input about to
10
10
  // reach a prompt and possibly a host CLI -- so it must look like a model identifier, not just be
11
11
  // a non-empty string.
12
- const MODEL_ID_RE = /^[A-Za-z0-9][A-Za-z0-9._:/@\[\]-]{0,127}$/;
12
+ export const MODEL_ID_RE = /^[A-Za-z0-9][A-Za-z0-9._:/@\[\]-]{0,127}$/;
13
13
 
14
14
  // Hosts with a verified model identifier for each tier. Add an entry to opt a new host into
15
15
  // explicit model selection; leave a host out to keep it on its own default.
@@ -20,40 +20,55 @@ export const HOST_MODELS = Object.freeze({
20
20
  'claude-code': Object.freeze({ low: 'haiku', medium: 'sonnet', high: 'opus' }),
21
21
  });
22
22
 
23
+ export const MAX_MODEL_CANDIDATES = 8;
24
+
23
25
  /**
24
- * Resolves a declared cost tier to a concrete model for the given host.
25
- * @returns {string|null} the mapped model, or null when the host is absent from the mapping
26
- * (no override for that host — the caller omits the model argument and its own default applies).
26
+ * Resolves a declared cost tier to its ordered model candidates for the given host (#35). A mapping
27
+ * entry is one model id, or a non-empty list of up to MAX_MODEL_CANDIDATES distinct ids in preference
28
+ * order: plans and editors expose different model ids, so the caller passes the first one its host
29
+ * actually offers. The resolver cannot see the host's model list; it only validates and orders.
30
+ * @returns {string[]|null} the candidates (length >= 1), or null when the host is absent from the
31
+ * mapping (no override for that host — the caller omits the model argument and its own default applies).
27
32
  */
28
- export function resolveModel(cost, host, mapping = HOST_MODELS) {
33
+ export function resolveModelCandidates(cost, host, mapping = HOST_MODELS) {
29
34
  if (!VALID_COSTS.includes(cost)) {
30
35
  throw new Error(`cost-model: unrecognized cost "${cost}" (expected one of ${VALID_COSTS.join('|')})`);
31
36
  }
32
37
  if (!Object.hasOwn(mapping, host)) return null; // unmapped host: no override, its own default applies
33
38
  const models = mapping[host];
34
- const model = models[cost];
35
- if (model === undefined) {
39
+ const entry = models[cost];
40
+ if (entry === undefined) {
36
41
  throw new Error(`cost-model: host "${host}" has no "${cost}" entry in its mapping`);
37
42
  }
38
- // A user-supplied mapping (.somi/config.json's cost.mapping) can name a tier with a non-string
39
- // value (a number, an object, an empty string) -- that must die loudly here, at the one place
40
- // every mapping (shipped or overridden) is read, rather than silently handing a caller something
41
- // that prints into JSON as a "model" no host can actually run.
42
- if (typeof model !== 'string' || model === '') {
43
- throw new Error(`cost-model: host "${host}"'s "${cost}" entry must be a non-empty string, got ${JSON.stringify(model)}`);
43
+ // A user-supplied mapping (.somi/config.json's cost.mapping) can name a tier with a value of the
44
+ // wrong shape -- that must die loudly here, at the one place every mapping (shipped or overridden)
45
+ // is read, rather than hand a caller something that prints into JSON as a "model" no host can run.
46
+ const list = Array.isArray(entry) ? entry : [entry];
47
+ if (list.length === 0 || list.length > MAX_MODEL_CANDIDATES) {
48
+ throw new Error(`cost-model: host "${host}"'s "${cost}" entry must be a model id or a list of 1 to ${MAX_MODEL_CANDIDATES} ids, got ${list.length}`);
49
+ }
50
+ for (const model of list) {
51
+ if (typeof model !== 'string' || model === '') {
52
+ throw new Error(`cost-model: host "${host}"'s "${cost}" entry must be a non-empty string, got ${JSON.stringify(model)}`);
53
+ }
54
+ if (!MODEL_ID_RE.test(model)) {
55
+ throw new Error(`cost-model: host "${host}"'s "${cost}" entry "${model}" is not a valid model identifier`);
56
+ }
44
57
  }
45
- if (!MODEL_ID_RE.test(model)) {
46
- throw new Error(`cost-model: host "${host}"'s "${cost}" entry "${model}" is not a valid model identifier`);
58
+ if (new Set(list).size !== list.length) {
59
+ throw new Error(`cost-model: host "${host}"'s "${cost}" list names the same model twice`);
47
60
  }
48
- return model;
61
+ return [...list];
62
+ }
63
+
64
+ /**
65
+ * Resolves a declared cost tier to its preferred model for the given host: the first candidate.
66
+ * @returns {string|null} the mapped model, or null when the host is absent from the mapping.
67
+ */
68
+ export function resolveModel(cost, host, mapping = HOST_MODELS) {
69
+ return resolveModelCandidates(cost, host, mapping)?.[0] ?? null;
49
70
  }
50
71
 
51
- // JSON.parse gives a "__proto__" key in parsed text a genuine OWN enumerable property (unlike
52
- // object-literal syntax, which would set the prototype instead) — Object.keys/for-in sees it like
53
- // any other key. A naive `{...defaults, ...override}` spread is safe against the accessor-setter
54
- // gadget (spread uses DefineOwnProperty, not Set), but a config-sourced override is exactly the
55
- // input a merge helper should not trust blindly, so disallowed keys are rejected outright rather
56
- // than silently absorbed as an inert host entry.
57
72
  const FORBIDDEN_HOST_KEYS = new Set(['__proto__', 'constructor', 'prototype']);
58
73
 
59
74
  /**
@@ -7,12 +7,12 @@
7
7
  // Each caller turns the returned {ok, ...} shape into its own surface — the CLI: exit code +
8
8
  // stdout JSON, or a stderr message; the MCP server: a tool result. Composition (never inline the
9
9
  // pieces yourself; this is the one sanctioned call site for it):
10
- // resolveCeiling(projectRoot, ceiling) -> decideDispatch(declaredCost, ceiling)
10
+ // resolveCeiling(projectRoot, ceiling) -> decideDispatch([default tier], ceiling, cost.agents[agent])
11
11
  // -> modelForDispatch(decision, host, mergeHostMapping(HOST_MODELS, cost.mapping))
12
12
  //
13
- // `cost.mapping` is read from the project's .somi/config.json on EVERY call, unlike the ceiling
14
- // (re-read only at bootstrap — see cost-ceiling.mjs's header): the mapping is a lookup table, not
15
- // a gate, so a mid-session config fix taking effect on the very next dispatch is correct.
13
+ // `cost.mapping`, `cost.agents` and `cost.ceiling` are all read from the project's
14
+ // .somi/config.json on EVERY call, so a mid-session config fix takes effect on the very next
15
+ // dispatch (see cost-ceiling.mjs's header for the ceiling's precedence).
16
16
  //
17
17
  // `agent` is validated against a strict allowlist before any path is built — it may come from a
18
18
  // prompt carrying untrusted text (and, via the MCP server, from a model-supplied tool argument).
@@ -23,7 +23,7 @@
23
23
  // the same bad input produces the same code through either surface, checked before either
24
24
  // surface's own project-root lookup (the MCP server's own can be a 2s `roots/list` round trip)
25
25
  // 65 unknown agent (no agents/<name>.md at the install root)
26
- // 66 malformed declaration (no cost:, or an invalid/unordered/duplicated cost set) — OR the
26
+ // 66 no tier source (the exempt `somi` agent, or an agent file with no default-tier-table entry) — OR the
27
27
  // merged mapping's own resolution for the selected tier failing WHEN the project's own
28
28
  // cost.mapping never named that host at all (a bug in the shipped HOST_MODELS table, not a
29
29
  // broken project file)
@@ -39,9 +39,15 @@
39
39
  import fs from 'node:fs';
40
40
  import path from 'node:path';
41
41
  import { resolveCeiling, decideDispatch, modelForDispatch, readCostConfig, CEILING_ENV } from './cost-ceiling.mjs';
42
- import { HOST_MODELS, mergeHostMapping, VALID_COSTS } from './cost-model.mjs';
42
+ import { AGENT_NAME_RE } from './cost-config.mjs';
43
+ import { HOST_MODELS, mergeHostMapping, resolveModelCandidates, VALID_COSTS } from './cost-model.mjs';
44
+ import { AGENT_DEFAULT_TIERS } from './cost-defaults.mjs';
45
+ import { buildRegistry, agentTypeFor } from './agent-registry.mjs';
43
46
 
44
- export const AGENT_NAME_RE = /^[a-z][a-z0-9-]*$/;
47
+ // Built once: an alias collision fails the import, so no surface can start on an ambiguous registry.
48
+ const REGISTRY = buildRegistry();
49
+
50
+ export { AGENT_NAME_RE };
45
51
 
46
52
  export const EXIT_USAGE = 64;
47
53
  export const EXIT_UNKNOWN_AGENT = 65;
@@ -52,26 +58,6 @@ function err(code, message) {
52
58
  return { ok: false, code, message };
53
59
  }
54
60
 
55
- // Extracts one field's raw value from the frontmatter block (the lines between the first two
56
- // literal `---` delimiters) — same block scripts/validate.sh's cost_of()/model_of() awk parses.
57
- // Splits on CRLF too: a Windows checkout with core.autocrlf turns `---` into `---\r` (#28).
58
- function frontmatterField(content, field) {
59
- const re = new RegExp(`^${field}:\\s*(.*)$`);
60
- let dashes = 0;
61
- for (const line of content.split(/\r?\n/)) {
62
- if (line === '---') {
63
- dashes++;
64
- if (dashes >= 2) break;
65
- continue;
66
- }
67
- if (dashes === 1) {
68
- const m = re.exec(line);
69
- if (m) return m[1].trim();
70
- }
71
- }
72
- return undefined;
73
- }
74
-
75
61
  // The ONE validation order both surfaces run, over the SAME three fields, producing the SAME code
76
62
  // for the SAME bad input. scripts/somi-dispatch.mjs and scripts/somi-mcp.mjs each call this
77
63
  // directly before either does its own project-root lookup (the MCP server's can be a 2s
@@ -97,9 +83,8 @@ export function validateDispatchArgs({ agent, host, ceiling } = {}) {
97
83
  if (host !== undefined && (typeof host !== 'string' || host === '')) {
98
84
  return err(EXIT_USAGE, `--host requires a non-empty string, got ${JSON.stringify(host)}`);
99
85
  }
100
- // Validated here, before resolveCeiling() ever touches disk: a bad ceiling used to reach
101
- // loadOrInitState() first, which bootstraps (and WRITES) the state file before the value is
102
- // checked, so a rejected argument still left a state file behind.
86
+ // Validated here, before resolveCeiling() ever touches disk, so a rejected argument can never
87
+ // leave a persisted state file behind.
103
88
  if (ceiling !== undefined) {
104
89
  if (typeof ceiling !== 'string' || ceiling === '') {
105
90
  return err(EXIT_USAGE, `--ceiling requires a non-empty string, got ${JSON.stringify(ceiling)}`);
@@ -123,10 +108,13 @@ export function validateDispatchArgs({ agent, host, ceiling } = {}) {
123
108
  * `ceiling`, when given, is this call's explicit override. Both, and `agent`, are validated by
124
109
  * `validateDispatchArgs` above. `projectRoot`/`installRoot` are plain strings the caller resolves
125
110
  * itself (the CLI's own convention differs from the MCP server's — see mcp-project-root.mjs).
111
+ * `persist: false` makes the call read-only: an explicit or env ceiling is used but never remembered.
112
+ * The result's `agent_type` is the id the host's subagent tool takes for this agent (`somi:<agent>`
113
+ * on both shipped hosts), or null for a host with no registration (see agent-registry.mjs).
126
114
  *
127
115
  * @returns {{ok: true, result: object} | {ok: false, code: number, message: string}}
128
116
  */
129
- export function resolveDispatch({ agent, host, ceiling, projectRoot, installRoot }) {
117
+ export function resolveDispatch({ agent, host, ceiling, projectRoot, installRoot, persist = true }) {
130
118
  const validated = validateDispatchArgs({ agent, host, ceiling });
131
119
  if (!validated.ok) return validated;
132
120
  const HOST = host || 'claude-code';
@@ -140,45 +128,58 @@ export function resolveDispatch({ agent, host, ceiling, projectRoot, installRoot
140
128
  throw e;
141
129
  }
142
130
 
143
- const rawCost = frontmatterField(content, 'cost');
144
- if (!rawCost) {
145
- if (agent === 'somi') {
146
- return err(
147
- EXIT_MALFORMED,
148
- `agent "somi" is exempt from cost: — the host binds its model when the user selects it ` +
149
- `in the host's own UI, so there is nothing for this resolver to compute`,
150
- );
151
- }
152
- return err(EXIT_MALFORMED, `agent "${agent}" declares no cost: in its frontmatter`);
131
+ // The agent's own tier comes from the shipped default table, never from the agent file: a
132
+ // leftover `cost:` line in the file is ignored. `somi` is the one agent with no table entry on
133
+ // purpose; any other agent file the table doesn't know is a gap in the plugin itself (66).
134
+ if (agent === 'somi') {
135
+ return err(
136
+ EXIT_MALFORMED,
137
+ `agent "somi" is exempt from cost: — the host binds its model when the user selects it ` +
138
+ `in the host's own UI, so there is nothing for this resolver to compute`,
139
+ );
140
+ }
141
+ const defaultTier = AGENT_DEFAULT_TIERS[agent];
142
+ if (defaultTier === undefined) {
143
+ return err(EXIT_MALFORMED, `agent "${agent}" has no entry in the default tier table (scripts/lib/cost-defaults.mjs)`);
153
144
  }
154
- const declaredCost = rawCost.split(',').map((s) => s.trim());
145
+ const declaredCost = [defaultTier];
155
146
 
156
147
  // Both --ceiling and SOMI_COST_CEILING were already syntax-checked above, before any disk write —
157
148
  // so anything resolveCeiling() throws now is the PROJECT's own persisted state, not this call's
158
149
  // arguments: an unparsable .somi/config.json, or a corrupt .somi/somi-state/ceiling.json.
159
150
  let ceilingResult;
160
151
  try {
161
- ceilingResult = resolveCeiling(projectRoot, ceiling || undefined);
152
+ ceilingResult = resolveCeiling(projectRoot, ceiling || undefined, { persist });
162
153
  } catch (e) {
163
154
  return err(EXIT_PROJECT_ENV, e.message);
164
155
  }
165
156
 
166
- // Read fresh per call, not per-bootstrap (see this file's header): this is how a project on a
157
+ // Read fresh per call (see this file's header): this is how a project on a
167
158
  // host SoMi doesn't ship a mapping for (e.g. Copilot) tells SoMi which of ITS models counts as
168
159
  // low/medium/high. Captured once, before the merge, and kept around past it: modelForDispatch's
169
160
  // own catch below needs to know whether the PROJECT's mapping named this specific host at all,
170
161
  // to attribute a later resolution failure correctly.
171
162
  let projectMapping;
163
+ let override;
172
164
  try {
173
- projectMapping = readCostConfig(projectRoot).mapping;
165
+ const costConfig = readCostConfig(projectRoot);
166
+ projectMapping = costConfig.mapping;
167
+ // hasOwn, not a plain lookup: the map is null-prototype already, but this keeps "no entry"
168
+ // meaning "follows the ceiling" for any name, including ones like "constructor".
169
+ if (costConfig.agents && Object.hasOwn(costConfig.agents, agent)) override = costConfig.agents[agent];
174
170
  } catch (e) {
175
171
  return err(EXIT_PROJECT_ENV, e.message);
176
172
  }
173
+ // readCostConfig already validated it; re-checked here so an invalid override can only ever be the
174
+ // project's file (67), never reach decideDispatch's agent-declaration error path (66).
175
+ if (override !== undefined && !VALID_COSTS.includes(override)) {
176
+ return err(EXIT_PROJECT_ENV, `cost.agents.${agent} expected one of ${VALID_COSTS.join('|')}, got ${JSON.stringify(override)}`);
177
+ }
177
178
 
178
179
  // mergeHostMapping rejects a __proto__/constructor/prototype key, a non-object per-host value,
179
180
  // and a tier key outside low|medium|high outright — kept in its own try/catch, distinct from
180
181
  // decideDispatch/modelForDispatch below: this fails only on the PROJECT's own persisted
181
- // .somi/config.json being structurally broken, never on this agent's own `cost:` frontmatter.
182
+ // .somi/config.json being structurally broken, never on this agent's own default tier.
182
183
  let mapping;
183
184
  try {
184
185
  mapping = mergeHostMapping(HOST_MODELS, projectMapping);
@@ -186,23 +187,25 @@ export function resolveDispatch({ agent, host, ceiling, projectRoot, installRoot
186
187
  return err(EXIT_PROJECT_ENV, e.message);
187
188
  }
188
189
 
189
- // decideDispatch failing is always this AGENT's own cost: declaration (66) — unrelated to the
190
- // mapping, so it stays in its own try/catch rather than sharing modelForDispatch's below.
190
+ // The override and ceiling are validated by now, so decideDispatch failing is this AGENT's own
191
+ // default tier (66) -- unrelated to the mapping, so it stays in its own try/catch.
191
192
  let decision;
192
193
  try {
193
- decision = decideDispatch(declaredCost, ceilingResult.ceiling);
194
+ decision = decideDispatch(declaredCost, ceilingResult.ceiling, override);
194
195
  } catch (e) {
195
196
  return err(EXIT_MALFORMED, e.message);
196
197
  }
197
198
 
198
199
  // modelForDispatch failing here means the MERGED mapping is shape-valid but incomplete or wrong
199
- // for the tier this call actually selected. Whose fault that is turns on whether the project's
200
+ // for the tier this call actually selected (the ceiling, or the agent's override). Whose fault that is turns on whether the project's
200
201
  // OWN cost.mapping named this host at all: if it did, the gap is the project's own file (67),
201
202
  // and the message says so explicitly. Only a host the project's mapping never mentioned failing
202
203
  // this way would point at a bug in the shipped HOST_MODELS table itself, which stays 66.
203
204
  let model;
205
+ let candidates;
204
206
  try {
205
207
  model = modelForDispatch(decision, HOST, mapping);
208
+ candidates = resolveModelCandidates(decision.selected, HOST, mapping);
206
209
  } catch (e) {
207
210
  if (projectMapping && Object.hasOwn(projectMapping, HOST)) {
208
211
  return err(EXIT_PROJECT_ENV, `${e.message} (in .somi/config.json cost.mapping)`);
@@ -210,13 +213,28 @@ export function resolveDispatch({ agent, host, ceiling, projectRoot, installRoot
210
213
  return err(EXIT_MALFORMED, e.message);
211
214
  }
212
215
 
216
+ // `enforced` is true only when a concrete model id came out of the merged mapping (shipped table
217
+ // or the project's cost.mapping). A null model means nothing pins the tier on this host: the
218
+ // agent runs on whatever the host picks, so a caller must not report the tier as "dispatched".
219
+ const enforced = model !== null;
220
+ const modelFields = enforced
221
+ ? { enforced }
222
+ : { enforced, reason: `no model mapping for host ${HOST} (set cost.mapping.${HOST} with low, medium and high in .somi/config.json)` };
223
+
213
224
  return {
214
225
  ok: true,
215
226
  result: {
216
227
  agent,
228
+ agent_type: agentTypeFor(REGISTRY, agent, HOST),
217
229
  supported: decision.supported,
230
+ declared: decision.supported,
218
231
  tier: decision.selected,
232
+ degraded: decision.degraded,
233
+ tier_source: decision.tier_source,
219
234
  model,
235
+ // Only for a preference list (#35): pass the first candidate the host offers; `model` is the first.
236
+ ...(candidates && candidates.length > 1 ? { model_candidates: candidates } : {}),
237
+ ...modelFields,
220
238
  ceiling: ceilingResult.ceiling,
221
239
  ceiling_source: ceilingResult.source,
222
240
  ceiling_origin: ceilingResult.ceiling_origin,