@skathio/somi 3.1.1 → 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.
- package/.claude/settings.json +13 -0
- package/.claude-plugin/marketplace.json +2 -2
- package/.claude-plugin/plugin.json +1 -1
- package/.copilot-extension/extension.json +1 -1
- package/.copilot-extension/marketplace.json +2 -2
- package/README.md +28 -23
- package/VERSION +1 -1
- package/agents/{architecture-reviewer.md → somi-architecture-reviewer.md} +10 -11
- package/agents/{atlas.md → somi-atlas.md} +3 -5
- package/agents/{coder.md → somi-coder.md} +26 -23
- package/agents/{designer.md → somi-designer.md} +9 -11
- package/agents/{discovery-analyst.md → somi-discovery-analyst.md} +7 -9
- package/agents/{impact.md → somi-impact.md} +6 -8
- package/agents/{incident.md → somi-incident.md} +2 -4
- package/agents/{plan-reviewer.md → somi-plan-reviewer.md} +9 -11
- package/agents/{planner.md → somi-planner.md} +16 -24
- package/agents/{pr.md → somi-pr.md} +2 -4
- package/agents/{refactor-designer.md → somi-refactor-designer.md} +14 -15
- package/agents/{refactorer.md → somi-refactorer.md} +11 -12
- package/agents/{reviewer.md → somi-reviewer.md} +8 -7
- package/agents/{sdlc-reviewer.md → somi-sdlc-reviewer.md} +8 -10
- package/agents/{security-reviewer.md → somi-security-reviewer.md} +8 -8
- package/agents/{test-strategist.md → somi-test-strategist.md} +4 -6
- package/agents/somi.md +25 -12
- package/commands/adopt.md +9 -10
- package/commands/architecture-review.md +4 -5
- package/commands/atlas.md +3 -3
- package/commands/code-loop.md +38 -14
- package/commands/code-parallel.md +4 -4
- package/commands/code.md +24 -15
- package/commands/debug.md +8 -9
- package/commands/design.md +14 -15
- package/commands/discover.md +11 -12
- package/commands/impact.md +2 -2
- package/commands/incident.md +3 -4
- package/commands/plan-loop.md +16 -12
- package/commands/plan.md +15 -16
- package/commands/pr.md +2 -2
- package/commands/refactor-design.md +10 -11
- package/commands/refactor.md +7 -8
- package/commands/release-readiness.md +6 -7
- package/commands/review-panel.md +24 -23
- package/commands/review.md +14 -14
- package/commands/security-review.md +8 -7
- package/commands/ship-loop.md +107 -28
- package/commands/ship.md +6 -6
- package/commands/somi-config.md +131 -0
- package/commands/test-strategy.md +3 -4
- package/commands/upgrade.md +4 -5
- package/examples/code-review-example.md +1 -1
- package/examples/discovery-example.md +1 -1
- package/examples/feature-plan-example.md +2 -2
- package/hooks/hooks.json +14 -1
- package/hooks/lib/common.mjs +64 -1
- package/hooks/post-tool/audit-log.mjs +3 -2
- package/hooks/pre-tool/block-secret-writes.mjs +12 -11
- package/hooks/pre-tool/guard-cost-lowering.mjs +177 -0
- package/hooks/pre-tool/guard-protected-paths.mjs +13 -3
- package/hooks/session-start/detect-repo-instructions.mjs +27 -2
- package/hooks/session-start/ensure-default-config.mjs +121 -0
- package/package.json +1 -1
- package/rules/00-priorities.md +1 -1
- package/rules/30-security-owasp.md +1 -1
- package/rules/50-collaboration.md +9 -6
- package/rules/CLAUDE.md +11 -10
- package/scripts/lib/agent-info.mjs +85 -0
- package/scripts/lib/agent-registry.mjs +92 -0
- package/scripts/lib/cost-ceiling.mjs +175 -171
- package/scripts/lib/cost-config-edit.mjs +102 -0
- package/scripts/lib/cost-config.mjs +64 -0
- package/scripts/lib/cost-defaults.mjs +51 -0
- package/scripts/lib/cost-lowering.mjs +89 -0
- package/scripts/lib/cost-model.mjs +37 -22
- package/scripts/lib/dispatch-resolver.mjs +59 -50
- package/scripts/lib/loop-diff.mjs +96 -0
- package/scripts/lib/loop-dispatch.mjs +19 -0
- package/scripts/lib/loop-review.mjs +52 -0
- package/scripts/lib/run-budget.mjs +28 -0
- package/scripts/lib/size-tier.mjs +184 -0
- package/scripts/lib/tier-record.mjs +82 -0
- package/scripts/size-budget-overrides.json +7 -15
- package/scripts/somi-config.mjs +358 -0
- package/scripts/somi-dispatch.mjs +1 -1
- package/scripts/somi-loop.mjs +71 -96
- package/scripts/somi-mcp.mjs +135 -14
- package/scripts/somi-tier.mjs +393 -0
- package/scripts/validate.sh +37 -215
- package/skills/api-design/SKILL.md +1 -1
- package/skills/clean-code/SKILL.md +1 -1
- package/skills/market-research/SKILL.md +2 -2
- package/skills/owasp-defense/SKILL.md +2 -2
- package/skills/plan-review/SKILL.md +5 -1
- package/skills/reasoning-craft/SKILL.md +1 -1
- package/skills/requirements-engineering/SKILL.md +3 -3
- package/skills/solid-principles/SKILL.md +1 -1
- package/skills/somi-dispatch/SKILL.md +104 -109
- package/skills/somi-routing/SKILL.md +88 -1
- package/skills/testing-playbook/SKILL.md +2 -2
- package/skills/threat-modeling/SKILL.md +3 -3
- package/templates/BRIEF.md.tmpl +2 -2
- package/templates/DESIGN.md.tmpl +1 -1
- package/templates/DOD.md.tmpl +2 -2
- package/templates/PHASE.md.tmpl +2 -2
- package/templates/RCA.md.tmpl +1 -1
- package/templates/REVIEW.md.tmpl +3 -2
- package/templates/SDD.md.tmpl +1 -1
- package/templates/SPEC.md.tmpl +1 -1
- package/templates/TDD.md.tmpl +1 -1
- package/tests/hooks/cases/block-secret-writes.json +130 -17
- package/tests/hooks/cases/detect-repo-instructions.json +22 -1
- package/tests/hooks/cases/guard-protected-paths.json +175 -25
- package/tests/scripts/agent-model-frontmatter.sh +38 -0
- package/tests/scripts/agent-names.sh +77 -0
- package/tests/scripts/check-frontmatter.sh +1 -1
- package/tests/scripts/checkpoint-gate.sh +44 -3
- package/tests/scripts/convergence-runner.sh +10 -6
- package/tests/scripts/cost-ceiling.sh +127 -215
- package/tests/scripts/cost-defaults.sh +128 -0
- package/tests/scripts/cost-hardcap.sh +329 -0
- package/tests/scripts/cost-lowering.sh +261 -0
- package/tests/scripts/cost-model.sh +18 -14
- package/tests/scripts/dispatch-guard.sh +7 -7
- package/tests/scripts/dispatch-line-gate.sh +61 -0
- package/tests/scripts/dispatch-reference-gate.sh +13 -13
- package/tests/scripts/ensure-default-config.sh +162 -0
- package/tests/scripts/eval-runner.sh +9 -9
- package/tests/scripts/evals-packaging.sh +127 -20
- package/tests/scripts/fixtures/size-tier-cases.json +87 -0
- package/tests/scripts/goldens/loop-state-done.json +1 -1
- package/tests/scripts/goldens/somi-loop.json +3 -3
- package/tests/scripts/lib/agent-registry-tests.mjs +95 -0
- package/tests/scripts/lib/brief-only-guard.mjs +27 -0
- package/tests/scripts/lib/checkpoint-gate.mjs +40 -3
- package/tests/scripts/lib/dispatch-reference-gate.mjs +5 -5
- package/tests/scripts/lib/retirement-gate.mjs +7 -2
- package/tests/scripts/lib/ship-loop-sizing-guard.mjs +52 -0
- package/tests/scripts/lib/size-tier-drift.mjs +74 -0
- package/tests/scripts/lib/somi-mcp-config-tests.mjs +92 -0
- package/tests/scripts/lib/somi-mcp-tests.mjs +66 -28
- package/tests/scripts/lib/somi-mcp-tier-tests.mjs +64 -0
- package/tests/scripts/retirement-gate.sh +19 -0
- package/tests/scripts/review-panel-seats.sh +2 -2
- package/tests/scripts/run.sh +95 -0
- package/tests/scripts/size-tier.sh +562 -0
- package/tests/scripts/somi-agent-dispatch-contract.sh +20 -11
- package/tests/scripts/somi-config.sh +281 -0
- package/tests/scripts/somi-dispatch.sh +150 -98
- package/tests/scripts/somi-mcp.sh +2 -0
|
@@ -1,36 +1,38 @@
|
|
|
1
|
-
// cost-ceiling.mjs — the session cost ceiling:
|
|
2
|
-
//
|
|
1
|
+
// cost-ceiling.mjs — the session cost ceiling: the tier every dispatch runs at unless an agent has
|
|
2
|
+
// its own override in .somi/config.json.
|
|
3
3
|
//
|
|
4
|
-
//
|
|
5
|
-
//
|
|
6
|
-
//
|
|
7
|
-
//
|
|
8
|
-
//
|
|
9
|
-
//
|
|
10
|
-
//
|
|
4
|
+
// The ceiling is re-resolved on every call, nothing is frozen once. Precedence, highest first:
|
|
5
|
+
// 1. a value given THIS call: an argument the caller parsed itself (a CLI flag) or SOMI_COST_CEILING
|
|
6
|
+
// 2. `cost.ceiling` in .somi/config.json, read live on every call
|
|
7
|
+
// 3. a ceiling persisted by an earlier call, but only one that call took from a CLI flag or the env
|
|
8
|
+
// var (a ceiling someone explicitly set), and only when the config sets none
|
|
9
|
+
// 4. DEFAULT_CEILING
|
|
10
|
+
// So a bare edit to .somi/config.json moves the ceiling on the very next dispatch. That reverses the
|
|
11
|
+
// older rule (and the loop-cap precedent in scripts/somi-loop.mjs) under which a config edit could
|
|
12
|
+
// not move a ceiling already in force. A persisted ceiling that was itself taken from the config,
|
|
13
|
+
// the default, or from before origins were recorded never outranks 2 or 4 -- it yields, so it can
|
|
14
|
+
// not pin a stale value after a config fix or a change of default.
|
|
15
|
+
//
|
|
16
|
+
// Only a CLI/env value is ever written to disk. Every value that reaches validateCeiling() is
|
|
17
|
+
// rejected outright if it isn't one of VALID_COSTS -- never coerced -- so a malformed value dies
|
|
18
|
+
// loudly instead of quietly disabling the ceiling.
|
|
11
19
|
//
|
|
12
20
|
// State is deliberately NOT keyed by slug (unlike loop state): the ceiling bounds an operator's
|
|
13
21
|
// spend for the whole session, not one slice of work, so one file covers every dispatch.
|
|
14
|
-
// Callers pass `root` explicitly rather than this module sniffing CLAUDE_PROJECT_DIR itself
|
|
22
|
+
// Callers pass `root` explicitly rather than this module sniffing CLAUDE_PROJECT_DIR itself --
|
|
15
23
|
// keeps the module a pure library over explicit inputs, testable without env-var setup.
|
|
16
24
|
//
|
|
17
|
-
// Every raise is appended to `ceiling_overrides`, shaped {field, from, to, source, at}
|
|
25
|
+
// Every raise is appended to `ceiling_overrides`, shaped {field, from, to, source, at} -- the same
|
|
18
26
|
// shape somi-loop.mjs's `cap_overrides` uses, so an override record looks the same wherever it's
|
|
19
27
|
// read from. Created lazily, only on the first real override.
|
|
20
|
-
//
|
|
21
|
-
// The ceiling not moving on a bare config edit (above) means `ceiling_origin: "config"` can go
|
|
22
|
-
// stale: config can change to a DIFFERENT value after state already exists, without moving what's
|
|
23
|
-
// in force. `resolveCeiling` detects this and reports `"config-stale"` instead — never persisted,
|
|
24
|
-
// since nothing about the value in force actually changed, only the honesty of naming why. A state
|
|
25
|
-
// file written before `ceiling_origin` shipped (no hard failure -- reported as `"unknown"`) is the
|
|
26
|
-
// other non-canonical value `resolveCeiling` can return; see LEGACY_ORIGIN below.
|
|
27
28
|
|
|
28
29
|
import fs from 'node:fs';
|
|
29
30
|
import path from 'node:path';
|
|
30
31
|
import { resolveModel, VALID_COSTS } from './cost-model.mjs';
|
|
32
|
+
import { validateCostConfig, quote } from './cost-config.mjs';
|
|
31
33
|
|
|
32
34
|
export const CEILING_ENV = 'SOMI_COST_CEILING';
|
|
33
|
-
export const DEFAULT_CEILING = '
|
|
35
|
+
export const DEFAULT_CEILING = 'medium';
|
|
34
36
|
export const ACTIONS = Object.freeze(['allow']);
|
|
35
37
|
|
|
36
38
|
const ORDER = Object.freeze(Object.fromEntries(VALID_COSTS.map((c, i) => [c, i])));
|
|
@@ -43,11 +45,51 @@ function nowIso() {
|
|
|
43
45
|
return new Date().toISOString().replace(/\.\d{3}Z$/, 'Z');
|
|
44
46
|
}
|
|
45
47
|
|
|
46
|
-
|
|
48
|
+
// A committed config is untrusted input, read whole into memory and into the model's reach; a file
|
|
49
|
+
// this large is not a config, so it is refused rather than parsed.
|
|
50
|
+
export const MAX_CONFIG_BYTES = 64 * 1024;
|
|
51
|
+
|
|
52
|
+
// Opened with O_NOFOLLOW (a committed symlink -- say to /dev/zero -- is refused, never followed) and
|
|
53
|
+
// O_NONBLOCK (a FIFO cannot hang the open), then checked on the open descriptor, not the path, so
|
|
54
|
+
// there is no stat-then-read race. At most MAX_CONFIG_BYTES+1 bytes are ever read.
|
|
55
|
+
const OPEN_FLAGS = fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW ?? 0) | (fs.constants.O_NONBLOCK ?? 0);
|
|
56
|
+
|
|
57
|
+
export function readTextFile(file) {
|
|
58
|
+
let fd;
|
|
59
|
+
try {
|
|
60
|
+
fd = fs.openSync(file, OPEN_FLAGS);
|
|
61
|
+
} catch (e) {
|
|
62
|
+
if (e.code === 'ELOOP') throw new Error(`cost-ceiling: ${file} is a symlink; refusing to follow it`);
|
|
63
|
+
throw e;
|
|
64
|
+
}
|
|
65
|
+
try {
|
|
66
|
+
if (!fs.fstatSync(fd).isFile()) throw new Error(`cost-ceiling: ${file} is not a regular file`);
|
|
67
|
+
const buf = Buffer.alloc(MAX_CONFIG_BYTES + 1);
|
|
68
|
+
let n = 0;
|
|
69
|
+
while (n < buf.length) {
|
|
70
|
+
const got = fs.readSync(fd, buf, n, buf.length - n, null);
|
|
71
|
+
if (got === 0) break;
|
|
72
|
+
n += got;
|
|
73
|
+
}
|
|
74
|
+
if (n > MAX_CONFIG_BYTES) throw new Error(`cost-ceiling: ${file} is over the ${MAX_CONFIG_BYTES}-byte limit`);
|
|
75
|
+
return buf.toString('utf8', 0, n);
|
|
76
|
+
} finally {
|
|
77
|
+
fs.closeSync(fd);
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
// The parser's own message quotes file text (untrusted, and it reaches the model), so only its error
|
|
82
|
+
// name and numeric position are reported.
|
|
83
|
+
function parseFailure(file, e) {
|
|
84
|
+
const pos = /position (\d+)/.exec(String(e.message))?.[1];
|
|
85
|
+
return new Error(`cost-ceiling: ${file} is not valid JSON (${JSON.stringify(e.name)}${pos ? ` at position ${pos}` : ''})`);
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
export function readConfig(root) {
|
|
47
89
|
const file = path.join(root, '.somi', 'config.json');
|
|
48
90
|
let raw;
|
|
49
91
|
try {
|
|
50
|
-
raw =
|
|
92
|
+
raw = readTextFile(file);
|
|
51
93
|
} catch (e) {
|
|
52
94
|
if (e.code === 'ENOENT') return {}; // no config committed: nothing configured, defaults apply
|
|
53
95
|
throw e;
|
|
@@ -57,13 +99,11 @@ function readConfig(root) {
|
|
|
57
99
|
} catch (e) {
|
|
58
100
|
// A committed config that fails to PARSE is not "unconfigured" -- silently returning {} here
|
|
59
101
|
// would bootstrap DEFAULT_CEILING and PERSIST it, inverting a team's `low` policy until
|
|
60
|
-
// someone notices, and outliving the typo once fixed. Dies loudly
|
|
61
|
-
throw
|
|
102
|
+
// someone notices, and outliving the typo once fixed. Dies loudly, naming the file.
|
|
103
|
+
throw parseFailure(file, e);
|
|
62
104
|
}
|
|
63
105
|
}
|
|
64
106
|
|
|
65
|
-
const COST_CONFIG_KEYS = new Set(['ceiling', 'mapping']);
|
|
66
|
-
|
|
67
107
|
// A `cost` that isn't an object, has an unrecognized key (a typo), or a `ceiling` misplaced at
|
|
68
108
|
// the top level all die loudly here instead of silently resolving to "not configured".
|
|
69
109
|
//
|
|
@@ -75,42 +115,25 @@ export function readCostConfig(root) {
|
|
|
75
115
|
if (cfg.ceiling !== undefined) {
|
|
76
116
|
throw new Error('cost-ceiling: "ceiling" in .somi/config.json belongs under "cost.ceiling"');
|
|
77
117
|
}
|
|
78
|
-
|
|
79
|
-
if (cost === undefined || cost === null) return {};
|
|
80
|
-
if (typeof cost !== 'object' || Array.isArray(cost)) {
|
|
81
|
-
throw new Error(`cost-ceiling: cost in .somi/config.json expected an object, got ${JSON.stringify(cost)}`);
|
|
82
|
-
}
|
|
83
|
-
for (const key of Object.keys(cost)) {
|
|
84
|
-
if (!COST_CONFIG_KEYS.has(key)) {
|
|
85
|
-
throw new Error(`cost-ceiling: cost in .somi/config.json has an unrecognized key "${key}"`);
|
|
86
|
-
}
|
|
87
|
-
}
|
|
88
|
-
return cost;
|
|
118
|
+
return validateCostConfig(cfg.cost);
|
|
89
119
|
}
|
|
90
120
|
|
|
91
121
|
function validateCeiling(raw, label) {
|
|
92
122
|
if (!VALID_COSTS.includes(raw)) {
|
|
93
|
-
throw new Error(`cost-ceiling: ${label} expected one of ${VALID_COSTS.join('|')}, got
|
|
123
|
+
throw new Error(`cost-ceiling: ${label} expected one of ${VALID_COSTS.join('|')}, got ${quote(raw)}`);
|
|
94
124
|
}
|
|
95
125
|
return raw;
|
|
96
126
|
}
|
|
97
127
|
|
|
98
|
-
// What produced
|
|
99
|
-
// what
|
|
100
|
-
//
|
|
101
|
-
// session") instead of only "it's saved state" -- see resolveCeiling's own doc comment.
|
|
128
|
+
// What produced a persisted ceiling. Only `cli` and `env` are ever written now; `config` and `default`
|
|
129
|
+
// are what earlier versions wrote, and are accepted (never rewritten) so an old state file still
|
|
130
|
+
// loads. A state file with no origin at all (one written before origins were recorded) is legacy: it yields.
|
|
102
131
|
const VALID_ORIGINS = Object.freeze(['config', 'cli', 'env', 'default']);
|
|
103
|
-
|
|
104
|
-
// Reported (never persisted) origin for a state file written before `ceiling_origin` existed --
|
|
105
|
-
// this repo's own checked-in .somi/somi-state/ceiling.json is exactly that shape. There is no way
|
|
106
|
-
// to recover which of config/cli/env/default actually produced the value, so this is the honest
|
|
107
|
-
// answer rather than a guess. Distinct from a PRESENT-but-invalid value (a typo, a stale removed
|
|
108
|
-
// value), which still dies loudly in loadOrInitState below -- absence is legacy, corruption isn't.
|
|
109
|
-
const LEGACY_ORIGIN = 'unknown';
|
|
132
|
+
const EXPLICIT_ORIGINS = Object.freeze(['cli', 'env']);
|
|
110
133
|
|
|
111
134
|
function validateOrigin(raw, label) {
|
|
112
135
|
if (!VALID_ORIGINS.includes(raw)) {
|
|
113
|
-
throw new Error(`cost-ceiling: ${label} expected one of ${VALID_ORIGINS.join('|')}, got
|
|
136
|
+
throw new Error(`cost-ceiling: ${label} expected one of ${VALID_ORIGINS.join('|')}, got ${quote(raw)}`);
|
|
114
137
|
}
|
|
115
138
|
return raw;
|
|
116
139
|
}
|
|
@@ -118,130 +141,115 @@ function validateOrigin(raw, label) {
|
|
|
118
141
|
function saveState(root, state) {
|
|
119
142
|
const file = ceilingStatePath(root);
|
|
120
143
|
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
121
|
-
|
|
144
|
+
// Written to a fresh exclusive temp file (O_NOFOLLOW) and renamed over the target: the rename
|
|
145
|
+
// replaces a symlink planted at ceiling.json instead of writing through it, and a reader never
|
|
146
|
+
// sees a half-written file.
|
|
147
|
+
const tmp = `${file}.${process.pid}.tmp`;
|
|
148
|
+
const flags = fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL | (fs.constants.O_NOFOLLOW ?? 0);
|
|
149
|
+
try {
|
|
150
|
+
const fd = fs.openSync(tmp, flags, 0o666);
|
|
151
|
+
try { fs.writeSync(fd, JSON.stringify(state)); } finally { fs.closeSync(fd); }
|
|
152
|
+
fs.renameSync(tmp, file);
|
|
153
|
+
} catch (e) {
|
|
154
|
+
fs.rmSync(tmp, { force: true });
|
|
155
|
+
throw e;
|
|
156
|
+
}
|
|
122
157
|
}
|
|
123
158
|
|
|
124
|
-
//
|
|
125
|
-
//
|
|
126
|
-
//
|
|
127
|
-
|
|
128
|
-
//
|
|
129
|
-
// Returns `{state, bootstrapSource}` — `bootstrapSource` is `'config'` or `'default'` when this
|
|
130
|
-
// call just bootstrapped a fresh state file, or `'state'` when an existing one was loaded. This is
|
|
131
|
-
// what lets resolveCeiling() report where a ceiling came from even on a call that overrides
|
|
132
|
-
// nothing — a dispatcher can then announce a `low` ceiling honestly, by its real source, not just
|
|
133
|
-
// by its bare value.
|
|
134
|
-
function loadOrInitState(root) {
|
|
159
|
+
// Returns the persisted state, or undefined when there is none. A PRESENT but corrupt file is not
|
|
160
|
+
// silently treated as missing -- it throws, same "malformed dies loudly" discipline as a bad
|
|
161
|
+
// CLI/env value. Read with the same no-follow, regular-file, size-bounded helper as the config.
|
|
162
|
+
export function loadState(root) {
|
|
135
163
|
const file = ceilingStatePath(root);
|
|
136
164
|
let raw;
|
|
137
165
|
try {
|
|
138
|
-
raw =
|
|
166
|
+
raw = readTextFile(file);
|
|
139
167
|
} catch (e) {
|
|
140
|
-
if (e.code
|
|
141
|
-
|
|
142
|
-
const isConfigured = !(configured === undefined || configured === null || configured === '');
|
|
143
|
-
const ceiling = isConfigured
|
|
144
|
-
? validateCeiling(configured, 'cost.ceiling in .somi/config.json')
|
|
145
|
-
: DEFAULT_CEILING;
|
|
146
|
-
const bootstrapSource = isConfigured ? 'config' : 'default';
|
|
147
|
-
const state = { ceiling, ceiling_origin: bootstrapSource };
|
|
148
|
-
saveState(root, state);
|
|
149
|
-
return { state, bootstrapSource };
|
|
168
|
+
if (e.code === 'ENOENT') return undefined;
|
|
169
|
+
throw e;
|
|
150
170
|
}
|
|
151
|
-
// An unparsable state file
|
|
152
|
-
//
|
|
153
|
-
// caller (or a project-environment-failure classifier) no path to report which file is corrupt.
|
|
171
|
+
// An unparsable state file must still name the file in its error -- a bare JSON.parse throw would
|
|
172
|
+
// surface as an unattributed SyntaxError, leaving a caller no path to report which file is corrupt.
|
|
154
173
|
let state;
|
|
155
174
|
try {
|
|
156
175
|
state = JSON.parse(raw);
|
|
157
176
|
} catch (e) {
|
|
158
|
-
throw
|
|
177
|
+
throw parseFailure(file, e);
|
|
159
178
|
}
|
|
160
179
|
if (state === null || typeof state !== 'object' || Array.isArray(state)) {
|
|
161
180
|
throw new Error(`cost-ceiling: ${file} is not a valid state object`);
|
|
162
181
|
}
|
|
163
182
|
state.ceiling = validateCeiling(state.ceiling, `ceiling in ${file}`);
|
|
164
|
-
// Absent entirely (
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
// persisted value.
|
|
168
|
-
state.ceiling_origin = state.ceiling_origin === undefined
|
|
169
|
-
? LEGACY_ORIGIN
|
|
170
|
-
: validateOrigin(state.ceiling_origin, `ceiling_origin in ${file}`);
|
|
171
|
-
return { state, bootstrapSource: 'state' };
|
|
172
|
-
}
|
|
173
|
-
|
|
174
|
-
// `ceiling_origin: "config"` is a claim -- "a committed project policy produced this value" --
|
|
175
|
-
// that a later, DIFFERENT `.somi/config.json` edit silently falsifies. By design (see this file's
|
|
176
|
-
// own header) an edit after state already exists does not move the ceiling already in force, so
|
|
177
|
-
// reporting the origin unchanged would keep asserting a policy that no longer matches what's
|
|
178
|
-
// committed. Detected only when the origin currently on disk still claims 'config' (once a cli/env
|
|
179
|
-
// override has moved it, the origin already reflects THAT, correctly) and only against a call that
|
|
180
|
-
// LOADED existing state rather than bootstrapping fresh this same call (a fresh bootstrap read
|
|
181
|
-
// config and set state from it in this same call, so it cannot yet be stale). Never persisted --
|
|
182
|
-
// this changes only what THIS call reports, not the state file itself.
|
|
183
|
-
function reportedOrigin(root, state, bootstrapSource) {
|
|
184
|
-
if (bootstrapSource !== 'state' || state.ceiling_origin !== 'config') return state.ceiling_origin;
|
|
185
|
-
const configured = readCostConfig(root).ceiling;
|
|
186
|
-
const unset = configured === undefined || configured === null || configured === '';
|
|
187
|
-
return (unset || configured !== state.ceiling) ? 'config-stale' : state.ceiling_origin;
|
|
183
|
+
// Absent entirely is legacy (it yields), not corruption; present but wrong is rejected.
|
|
184
|
+
if (state.ceiling_origin !== undefined) validateOrigin(state.ceiling_origin, `ceiling_origin in ${file}`);
|
|
185
|
+
return state;
|
|
188
186
|
}
|
|
189
187
|
|
|
190
188
|
/**
|
|
191
189
|
* Re-resolves the session ceiling for one dispatch. `explicitArg` is a value the caller already
|
|
192
|
-
* extracted THIS invocation (e.g. a parsed CLI flag)
|
|
193
|
-
* Precedence
|
|
194
|
-
*
|
|
195
|
-
*
|
|
196
|
-
*
|
|
197
|
-
*
|
|
198
|
-
*
|
|
199
|
-
*
|
|
200
|
-
* `ceiling_origin` is what actually produced the value now in force — `config`/`cli`/`env`/`default`
|
|
201
|
-
* — and, unlike `source`, it survives every later bare call. `source: "state"` alone only tells a
|
|
202
|
-
* caller a ceiling was already on disk; `ceiling_origin` is what lets an announcement say WHY (a
|
|
203
|
-
* committed team policy, or an explicit `cli`/`env` set in an earlier session) instead of only
|
|
204
|
-
* "it's saved state". Two further values it can report, neither ever persisted: `config-stale` —
|
|
205
|
-
* the value was bootstrapped from `.somi/config.json`, but that file's `cost.ceiling` has since
|
|
206
|
-
* changed to something else (or been removed) — and `unknown` — a state file written before this
|
|
207
|
-
* field existed (this repo's own committed state is exactly that shape).
|
|
190
|
+
* extracted THIS invocation (e.g. a parsed CLI flag) -- distinct from SOMI_COST_CEILING, read here.
|
|
191
|
+
* Precedence is in this file's header: explicit (arg, then env) > config > persisted CLI/env > default.
|
|
192
|
+
* `source` names where THIS call's effective ceiling came from: `cli`, `env`, `config`, `state` (a
|
|
193
|
+
* ceiling persisted by an earlier CLI/env call) or `default`. `ceiling_origin` is what produced the
|
|
194
|
+
* value: the same, except a `state` ceiling reports the `cli`/`env` that originally set it.
|
|
195
|
+
* A CLI/env value that differs from what is persisted is saved (with an override record); that is the
|
|
196
|
+
* only write this function makes, and `{persist: false}` skips it (a read-only lookup such as
|
|
197
|
+
* somi_agent_info reports the same answer without remembering anything).
|
|
208
198
|
* @returns {{ceiling: string, overridden: boolean, source: string, ceiling_origin: string, override?: object}}
|
|
209
199
|
*/
|
|
210
|
-
export function resolveCeiling(root, explicitArg) {
|
|
211
|
-
const
|
|
200
|
+
export function resolveCeiling(root, explicitArg, { persist = true } = {}) {
|
|
201
|
+
const state = loadState(root);
|
|
202
|
+
const configured = readCostConfig(root).ceiling;
|
|
203
|
+
const isConfigured = !(configured === undefined || configured === null || configured === '');
|
|
212
204
|
const isCli = explicitArg !== undefined && explicitArg !== '';
|
|
213
205
|
const envVal = process.env[CEILING_ENV];
|
|
214
206
|
const explicit = isCli ? explicitArg : (envVal === undefined || envVal === '' ? undefined : envVal);
|
|
207
|
+
|
|
215
208
|
if (explicit === undefined) {
|
|
216
|
-
|
|
209
|
+
if (isConfigured) {
|
|
210
|
+
const ceiling = validateCeiling(configured, 'cost.ceiling in .somi/config.json');
|
|
211
|
+
return { ceiling, overridden: false, source: 'config', ceiling_origin: 'config' };
|
|
212
|
+
}
|
|
213
|
+
if (state && EXPLICIT_ORIGINS.includes(state.ceiling_origin)) {
|
|
214
|
+
return { ceiling: state.ceiling, overridden: false, source: 'state', ceiling_origin: state.ceiling_origin };
|
|
215
|
+
}
|
|
216
|
+
return { ceiling: DEFAULT_CEILING, overridden: false, source: 'default', ceiling_origin: 'default' };
|
|
217
217
|
}
|
|
218
|
+
|
|
219
|
+
// A config that sets a ceiling is validated even when a CLI/env value outranks it: a typo there
|
|
220
|
+
// should surface now, not on the later call that lacks the flag.
|
|
221
|
+
if (isConfigured) validateCeiling(configured, 'cost.ceiling in .somi/config.json');
|
|
218
222
|
const source = isCli ? 'cli' : 'env';
|
|
219
223
|
const validated = validateCeiling(explicit, isCli ? '--ceiling' : CEILING_ENV);
|
|
220
|
-
|
|
221
|
-
|
|
224
|
+
const persisted = state && EXPLICIT_ORIGINS.includes(state.ceiling_origin) ? state : undefined;
|
|
225
|
+
// Nothing to do only when the stored value already matches AND no differing config is being raised
|
|
226
|
+
// over (then the effective ceiling changes and the raise is recorded below).
|
|
227
|
+
const configDiffers = isConfigured && configured !== validated;
|
|
228
|
+
if (persisted && persisted.ceiling === validated && persisted.ceiling_origin === source && !configDiffers) {
|
|
229
|
+
return { ceiling: validated, overridden: false, source, ceiling_origin: source };
|
|
230
|
+
}
|
|
231
|
+
const next = state ?? {};
|
|
232
|
+
// The override record's `from` is the ceiling that was in force before this call.
|
|
233
|
+
const from = isConfigured ? configured : (persisted ? persisted.ceiling : DEFAULT_CEILING);
|
|
234
|
+
next.ceiling = validated;
|
|
235
|
+
next.ceiling_origin = source;
|
|
236
|
+
if (from === validated) {
|
|
237
|
+
if (persist) saveState(root, next);
|
|
238
|
+
return { ceiling: validated, overridden: false, source, ceiling_origin: source };
|
|
222
239
|
}
|
|
223
|
-
const override = {
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
};
|
|
230
|
-
state.ceiling = validated;
|
|
231
|
-
// The value now in force was produced by THIS override, not by whatever bootstrapped the file --
|
|
232
|
-
// ceiling_origin tracks the origin of the CURRENT value, so it must move with it.
|
|
233
|
-
state.ceiling_origin = source;
|
|
234
|
-
if (!Array.isArray(state.ceiling_overrides)) state.ceiling_overrides = [];
|
|
235
|
-
state.ceiling_overrides.push(override);
|
|
236
|
-
saveState(root, state);
|
|
237
|
-
return { ceiling: state.ceiling, overridden: true, source, ceiling_origin: state.ceiling_origin, override };
|
|
240
|
+
const override = { field: 'ceiling', from, to: validated, source, at: nowIso() };
|
|
241
|
+
if (!Array.isArray(next.ceiling_overrides)) next.ceiling_overrides = [];
|
|
242
|
+
// A repeat of the identical raise (same flag every call, config unchanged) is not a new event.
|
|
243
|
+
const last = next.ceiling_overrides[next.ceiling_overrides.length - 1];
|
|
244
|
+
if (!(last && last.from === from && last.to === validated && last.source === source)) next.ceiling_overrides.push(override);
|
|
245
|
+
if (persist) saveState(root, next);
|
|
246
|
+
return { ceiling: validated, overridden: true, source, ceiling_origin: source, override };
|
|
238
247
|
}
|
|
239
248
|
|
|
240
|
-
//
|
|
241
|
-
//
|
|
242
|
-
//
|
|
243
|
-
//
|
|
244
|
-
// on a frontmatter declaration, re-checked here rather than trusted: this is a library over
|
|
249
|
+
// The `costs` argument is a tier set in ascending order; the resolver passes the agent's single
|
|
250
|
+
// default tier. Accepts a bare string too, as a one-member set, so a single-tier caller needs no
|
|
251
|
+
// special-casing. Always returns a frozen array in ascending order, re-checked here rather than
|
|
252
|
+
// trusted: this is a library over
|
|
245
253
|
// explicit inputs, and a malformed set must die loudly rather than be silently coerced into
|
|
246
254
|
// something valid -- the same discipline validateCeiling() above applies to the ceiling value.
|
|
247
255
|
function normalizeCostSet(costs, label) {
|
|
@@ -264,48 +272,44 @@ function normalizeCostSet(costs, label) {
|
|
|
264
272
|
}
|
|
265
273
|
|
|
266
274
|
/**
|
|
267
|
-
* Selects the tier a dispatch
|
|
268
|
-
* `ceiling`. `costs` is a single cost string or an ascending, duplicate-free array/list of them.
|
|
269
|
-
* Always allows, and always runs at a tier the unit itself declared:
|
|
275
|
+
* Selects the tier a dispatch runs at. The ceiling is a HARD cap with one escape hatch:
|
|
270
276
|
*
|
|
271
|
-
* -
|
|
272
|
-
*
|
|
273
|
-
*
|
|
274
|
-
*
|
|
275
|
-
* unit whose cheapest declared tier is already above the ceiling has no cheaper mode to fall
|
|
276
|
-
* back to -- it is intrinsically that expensive, so blocking it would not be a saving, only a
|
|
277
|
-
* stoppage. It runs at its own declared floor rather than not at all.
|
|
277
|
+
* - `override` given (the agent's `cost.agents.<name>` from config) -> `selected` is the override,
|
|
278
|
+
* even above the ceiling. `tier_source` is `"override"`.
|
|
279
|
+
* - no override -> `selected` is the CEILING tier itself, whatever the unit's default tier is (not that
|
|
280
|
+
* default, not a min() of the two). `tier_source` is `"ceiling"`.
|
|
278
281
|
*
|
|
279
|
-
* `
|
|
280
|
-
*
|
|
281
|
-
*
|
|
282
|
+
* `costs` (the unit's default tier set, a string or an ascending duplicate-free array) is
|
|
283
|
+
* read only to report: `supported` echoes it, and `degraded` is true when `selected` ranks below
|
|
284
|
+
* its highest member. It never changes `selected`: declaring a tier never lowers or raises the run.
|
|
285
|
+
*
|
|
286
|
+
* Pure and deterministic; the result is frozen so a caller can't rewrite the selection.
|
|
282
287
|
*/
|
|
283
|
-
export function decideDispatch(costs, ceiling) {
|
|
284
|
-
const supported = normalizeCostSet(costs, '
|
|
288
|
+
export function decideDispatch(costs, ceiling, override) {
|
|
289
|
+
const supported = normalizeCostSet(costs, 'default tier');
|
|
285
290
|
if (!VALID_COSTS.includes(ceiling)) {
|
|
286
291
|
throw new Error(`cost-ceiling: unrecognized ceiling "${ceiling}" (expected one of ${VALID_COSTS.join('|')})`);
|
|
287
292
|
}
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
// in as a documented guard, not a bug: it makes "take the highest permitted member" true by
|
|
291
|
-
// construction even if that invariant were ever relaxed, rather than by iteration order alone.
|
|
292
|
-
let selected = null;
|
|
293
|
-
for (const c of supported) {
|
|
294
|
-
if (ORDER[c] <= ORDER[ceiling] && (selected === null || ORDER[c] > ORDER[selected])) {
|
|
295
|
-
selected = c;
|
|
296
|
-
}
|
|
293
|
+
if (override !== undefined && !VALID_COSTS.includes(override)) {
|
|
294
|
+
throw new Error(`cost-ceiling: unrecognized override "${override}" (expected one of ${VALID_COSTS.join('|')})`);
|
|
297
295
|
}
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
296
|
+
const selected = override === undefined ? ceiling : override;
|
|
297
|
+
const degraded = ORDER[selected] < ORDER[supported[supported.length - 1]];
|
|
298
|
+
return Object.freeze({
|
|
299
|
+
action: 'allow',
|
|
300
|
+
selected,
|
|
301
|
+
supported,
|
|
302
|
+
ceiling,
|
|
303
|
+
degraded,
|
|
304
|
+
tier_source: override === undefined ? 'ceiling' : 'override',
|
|
305
|
+
});
|
|
302
306
|
}
|
|
303
307
|
|
|
304
308
|
/**
|
|
305
309
|
* The only sanctioned way to turn a decideDispatch() result into a model. `decideDispatch` always
|
|
306
310
|
* returns "allow" now, so this guard is unreachable by construction -- kept anyway as the
|
|
307
|
-
* structural closer
|
|
308
|
-
*
|
|
311
|
+
* structural closer: nothing can hand this function a decision that wasn't produced by
|
|
312
|
+
* `decideDispatch`'s own selection and expect a model back.
|
|
309
313
|
*/
|
|
310
314
|
export function modelForDispatch(decision, host, mapping) {
|
|
311
315
|
if (!decision || decision.action !== 'allow') {
|
|
@@ -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
|
+
}
|