@skathio/somi 4.0.1 → 4.1.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 +1 -1
- package/.claude-plugin/marketplace.json +1 -1
- package/.claude-plugin/plugin.json +1 -1
- package/.copilot-extension/extension.json +1 -1
- package/.copilot-extension/marketplace.json +1 -1
- package/README.md +5 -4
- package/VERSION +1 -1
- package/agents/somi-coder.md +4 -228
- package/agents/somi-designer.md +4 -160
- package/agents/somi-discovery-analyst.md +4 -276
- package/agents/somi-flow.md +47 -0
- package/agents/somi-general.md +36 -0
- package/agents/somi-planner.md +4 -341
- package/agents/somi-reviewer.md +4 -199
- package/agents/somi.md +81 -253
- package/commands/adopt.md +6 -84
- package/commands/architecture-review.md +11 -86
- package/commands/atlas.md +10 -25
- package/commands/code-loop.md +10 -221
- package/commands/code-parallel.md +10 -151
- package/commands/code.md +9 -157
- package/commands/debug.md +9 -131
- package/commands/design.md +9 -160
- package/commands/discover.md +9 -194
- package/commands/impact.md +9 -25
- package/commands/incident.md +9 -39
- package/commands/plan-loop.md +9 -181
- package/commands/plan.md +9 -244
- package/commands/pr.md +10 -25
- package/commands/refactor-design.md +11 -89
- package/commands/refactor.md +11 -50
- package/commands/release-readiness.md +11 -70
- package/commands/review-panel.md +10 -141
- package/commands/review.md +11 -181
- package/commands/security-review.md +11 -75
- package/commands/ship-loop.md +9 -260
- package/commands/ship.md +9 -115
- package/commands/somi-config.md +11 -130
- package/commands/test-strategy.md +11 -75
- package/commands/upgrade.md +9 -72
- package/hooks/hooks.json +1 -1
- package/hooks/lib/common.mjs +8 -5
- package/hooks/pre-tool/block-dangerous-bash.mjs +1 -1
- package/hooks/pre-tool/block-secret-writes.mjs +5 -7
- package/hooks/pre-tool/guard-protected-paths.mjs +54 -34
- package/package.json +1 -1
- package/scripts/lib/cost-defaults.mjs +2 -0
- package/scripts/lib/escalation-facts.mjs +146 -0
- package/scripts/lib/escalation.mjs +129 -0
- package/scripts/lib/findings-ledger.mjs +241 -0
- package/scripts/lib/install-text.mjs +97 -0
- package/scripts/lib/loop-caps.mjs +140 -0
- package/scripts/lib/loop-diff.mjs +12 -70
- package/scripts/lib/loop-engine.mjs +226 -0
- package/scripts/lib/loop-escalate.mjs +49 -0
- package/scripts/lib/loop-exit.mjs +47 -0
- package/scripts/lib/loop-notes-compact.mjs +72 -0
- package/scripts/lib/loop-notes.mjs +278 -0
- package/scripts/lib/loop-review.mjs +355 -12
- package/scripts/lib/loop-state.mjs +44 -0
- package/scripts/lib/loop-step-close.mjs +75 -0
- package/scripts/lib/loop-step-kit.mjs +179 -0
- package/scripts/lib/loop-step-review.mjs +140 -0
- package/scripts/lib/loop-step-tool.mjs +89 -0
- package/scripts/lib/loop-step.mjs +301 -0
- package/scripts/lib/mcp-project-root.mjs +18 -7
- package/scripts/lib/path-facts.mjs +187 -0
- package/scripts/lib/path-safety.mjs +171 -0
- package/scripts/lib/run-card.mjs +73 -0
- package/scripts/size-budget-overrides.json +5 -13
- package/scripts/somi-card.mjs +39 -0
- package/scripts/somi-findings.mjs +56 -271
- package/scripts/somi-loop.mjs +77 -447
- package/scripts/somi-mcp.mjs +26 -95
- package/scripts/validate.sh +75 -57
- package/skills/flow-adopt/SKILL.md +92 -0
- package/skills/flow-architecture-review/SKILL.md +94 -0
- package/skills/flow-atlas/SKILL.md +34 -0
- package/skills/flow-code/SKILL.md +167 -0
- package/skills/flow-code-loop/SKILL.md +263 -0
- package/skills/flow-code-parallel/SKILL.md +160 -0
- package/skills/flow-debug/SKILL.md +141 -0
- package/skills/flow-design/SKILL.md +170 -0
- package/skills/flow-discover/SKILL.md +204 -0
- package/skills/flow-impact/SKILL.md +35 -0
- package/skills/flow-incident/SKILL.md +49 -0
- package/skills/flow-plan/SKILL.md +254 -0
- package/skills/flow-plan-loop/SKILL.md +254 -0
- package/skills/flow-pr/SKILL.md +34 -0
- package/skills/flow-refactor/SKILL.md +58 -0
- package/skills/flow-refactor-design/SKILL.md +97 -0
- package/skills/flow-release-readiness/SKILL.md +82 -0
- package/skills/flow-review/SKILL.md +193 -0
- package/skills/flow-review-panel/SKILL.md +154 -0
- package/skills/flow-security-review/SKILL.md +83 -0
- package/skills/flow-ship/SKILL.md +125 -0
- package/skills/flow-ship-loop/SKILL.md +274 -0
- package/skills/flow-somi-config/SKILL.md +142 -0
- package/skills/flow-status/SKILL.md +43 -0
- package/skills/flow-test-strategy/SKILL.md +83 -0
- package/skills/flow-upgrade/SKILL.md +82 -0
- package/skills/role-coder/SKILL.md +247 -0
- package/skills/role-designer/SKILL.md +172 -0
- package/skills/role-discovery-analyst/SKILL.md +288 -0
- package/skills/role-planner/SKILL.md +353 -0
- package/skills/role-reviewer/SKILL.md +218 -0
- package/skills/somi-checkpoint/SKILL.md +95 -0
- package/skills/somi-dispatch/SKILL.md +14 -14
- package/skills/somi-routing/SKILL.md +6 -2
- package/tests/hooks/cases/block-secret-writes.json +6 -1
- package/tests/hooks/cases/guard-protected-paths.json +44 -2
- package/tests/hooks/run.sh +21 -0
- package/tests/scripts/checkpoint-gate.sh +2 -2
- package/tests/scripts/cost-defaults.sh +2 -0
- package/tests/scripts/dispatch-line-gate.sh +4 -4
- package/tests/scripts/dispatch-reference-gate.sh +14 -14
- package/tests/scripts/escalation.sh +409 -0
- package/tests/scripts/eval-runner.sh +8 -7
- package/tests/scripts/fact-sheet.sh +296 -0
- package/tests/scripts/goldens/somi-loop.json +2 -2
- package/tests/scripts/lib/dispatch-reference-gate.mjs +14 -5
- package/tests/scripts/lib/escalation-facts-tests.mjs +140 -0
- package/tests/scripts/lib/escalation-tests.mjs +154 -0
- package/tests/scripts/lib/findings-ledger-tests.mjs +118 -0
- package/tests/scripts/lib/loop-engine-tests.mjs +287 -0
- package/tests/scripts/lib/loop-escalate-tests.mjs +356 -0
- package/tests/scripts/lib/loop-flow-gate.mjs +173 -0
- package/tests/scripts/lib/loop-notes-tests.mjs +371 -0
- package/tests/scripts/lib/loop-step-cli-tests.mjs +141 -0
- package/tests/scripts/lib/loop-step-close-tests.mjs +351 -0
- package/tests/scripts/lib/loop-step-lenient-tests.mjs +114 -0
- package/tests/scripts/lib/loop-step-state-tests.mjs +127 -0
- package/tests/scripts/lib/loop-step-tests.mjs +499 -0
- package/tests/scripts/lib/loop-step-unwritten-tests.mjs +55 -0
- package/tests/scripts/lib/path-facts-tests.mjs +198 -0
- package/tests/scripts/lib/path-safety-tests.mjs +201 -0
- package/tests/scripts/lib/run-suites.mjs +139 -0
- package/tests/scripts/lib/sizing-score-tests.mjs +210 -0
- package/tests/scripts/lib/sizing-set-tests.mjs +131 -0
- package/tests/scripts/lib/somi-mcp-loop-tests.mjs +226 -0
- package/tests/scripts/lib/somi-mcp-tests.mjs +21 -1
- package/tests/scripts/loop-engine.sh +22 -0
- package/tests/scripts/loop-flow-gate.sh +11 -0
- package/tests/scripts/review-panel-seats.sh +4 -4
- package/tests/scripts/run-card.sh +57 -0
- package/tests/scripts/run-suites.sh +74 -0
- package/tests/scripts/run.sh +11 -0
- package/tests/scripts/size-tier.sh +3 -3
- package/tests/scripts/somi-agent-dispatch-contract.sh +23 -3
- package/tests/scripts/somi-mcp.sh +1 -0
- package/tests/scripts/suite-plan.json +20 -0
|
@@ -0,0 +1,226 @@
|
|
|
1
|
+
// loop-engine.mjs -- the handlers of the loop engine: the lifecycle (init, resume, pass, finish), the measuring
|
|
2
|
+
// ones (check-diff, review-scope) and the recording ones (run-start, record-dispatch, record-pass).
|
|
3
|
+
// A handler takes a context ({root, env, stateDir, installRoot}, optional `now` clock) and the parsed arguments
|
|
4
|
+
// and returns a result ({out, code, message}, see loop-exit.mjs); it never prints or exits, and it reads the
|
|
5
|
+
// environment only from ctx.env (the one inheritance of the process env is the git subprocess in loop-review.mjs's snapshotTree).
|
|
6
|
+
|
|
7
|
+
import fs from 'node:fs';
|
|
8
|
+
import path from 'node:path';
|
|
9
|
+
import { verifyBriefOnly } from './tier-record.mjs';
|
|
10
|
+
import { REVIEW_SCOPES, headCommit, ignoredSnapshot, refuseSubmodules, reviewMinFor, reviewScope as scopeOf, snapshotTree } from './loop-review.mjs';
|
|
11
|
+
import { computeDiff } from './loop-diff.mjs';
|
|
12
|
+
import { dispatchEntry } from './loop-dispatch.mjs';
|
|
13
|
+
import { checkRun, startRun } from './run-budget.mjs';
|
|
14
|
+
import { loadConfig } from './config-files.mjs';
|
|
15
|
+
import { EXIT_DIFF_CAP, EXIT_MAX_PASSES, EXIT_TIME_BUDGET, LoopExit, PROG, ok, refuse, usageError } from './loop-exit.mjs';
|
|
16
|
+
import { applyCapOverride, configVal, firstDefined, resolveInitCap, reresolveCap, validateCap } from './loop-caps.mjs';
|
|
17
|
+
import { loadState, nowIso, requireState, saveState, stateFile } from './loop-state.mjs';
|
|
18
|
+
import { SEVERITIES } from './findings-ledger.mjs';
|
|
19
|
+
|
|
20
|
+
// The effective config; an unreadable or invalid file reads as unconfigured, so the defaults apply.
|
|
21
|
+
export function readConfig(root, env) {
|
|
22
|
+
try {
|
|
23
|
+
return loadConfig(root, env).config;
|
|
24
|
+
} catch {
|
|
25
|
+
return {};
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
// A thrown LoopExit reaches the caller as the result it stands for.
|
|
30
|
+
function guarded(body) {
|
|
31
|
+
return (ctx, args) => {
|
|
32
|
+
try {
|
|
33
|
+
return body(ctx, args);
|
|
34
|
+
} catch (e) {
|
|
35
|
+
if (e instanceof LoopExit) return refuse(e.code, e.message);
|
|
36
|
+
throw e;
|
|
37
|
+
}
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
const withReviewMin = (state) => (state.review_min ? { review_min: state.review_min } : {});
|
|
42
|
+
|
|
43
|
+
export const init = guarded(({ env, root, stateDir, now = nowIso }, args) => {
|
|
44
|
+
const { slug, loop, iteration, force } = args;
|
|
45
|
+
const sf = stateFile(stateDir, slug, iteration);
|
|
46
|
+
if (fs.existsSync(sf) && !force) {
|
|
47
|
+
let status;
|
|
48
|
+
try {
|
|
49
|
+
status = loadState(sf).status;
|
|
50
|
+
} catch {
|
|
51
|
+
status = undefined;
|
|
52
|
+
}
|
|
53
|
+
if (status === 'running') {
|
|
54
|
+
throw usageError(`loop state already running at ${sf} — use 'resume' to continue it, or 'init --force' to discard`);
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
// A brief-only work item (a plan directory with no phases/) exists only for the sized, human-
|
|
59
|
+
// approved small tier of /ship-loop: refuse it without the tier record's approval stamp.
|
|
60
|
+
const planDir = path.join(root, '.somi', 'plans', slug);
|
|
61
|
+
if (loop === 'code' && fs.existsSync(planDir) && !fs.existsSync(path.join(planDir, 'phases'))) {
|
|
62
|
+
const v = verifyBriefOnly(root, slug);
|
|
63
|
+
if (!v.ok) throw usageError(`brief-only work item refused: ${v.reason}; use /plan or /ship-loop`);
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
// Cap resolution: CLI > env > config > default, validated (see loop-caps.mjs).
|
|
67
|
+
const config = readConfig(root, env);
|
|
68
|
+
const plan = loop === 'plan';
|
|
69
|
+
const maxPasses = resolveInitCap(env, config, plan ? 'plan' : 'code', 'max_passes', args.maxPasses);
|
|
70
|
+
const sevFloor = firstDefined(
|
|
71
|
+
args.severity,
|
|
72
|
+
plan ? env.SOMI_PLAN_LOOP_SEVERITY_FLOOR : env.SOMI_CODE_LOOP_SEVERITY_FLOOR,
|
|
73
|
+
configVal(config, [plan ? 'plan_loop' : 'code_loop', 'severity_floor']),
|
|
74
|
+
'Major',
|
|
75
|
+
);
|
|
76
|
+
if (!SEVERITIES.includes(sevFloor)) throw usageError(`severity_floor: ${sevFloor} must be one of ${SEVERITIES.join('|')}`);
|
|
77
|
+
const diffCap = plan ? 0 : resolveInitCap(env, config, 'code', 'diff_cap_lines', args.diffCap); // plan loops have no diff cap
|
|
78
|
+
|
|
79
|
+
if (!plan) refuseSubmodules(root); // a repository the diff gate cannot measure is refused before any coder pass
|
|
80
|
+
const baseline = headCommit(root);
|
|
81
|
+
|
|
82
|
+
const state = {
|
|
83
|
+
slug,
|
|
84
|
+
loop,
|
|
85
|
+
iteration,
|
|
86
|
+
baseline_sha: baseline,
|
|
87
|
+
started: now(),
|
|
88
|
+
status: 'running',
|
|
89
|
+
caps: { max_passes: maxPasses, diff_cap_lines: diffCap, severity_floor: sevFloor },
|
|
90
|
+
iteration_files: args.files.split(' ').filter((s) => s.length > 0),
|
|
91
|
+
pass: 0,
|
|
92
|
+
history: [],
|
|
93
|
+
};
|
|
94
|
+
if (loop === 'code') state.review_min = reviewMinFor(root, slug) ?? undefined; // undefined: not serialised
|
|
95
|
+
if (loop === 'code') state.ignored_guarded = ignoredSnapshot(root); // the ignored files under the policy paths now; the escalation raises any that is new or changed later
|
|
96
|
+
fs.mkdirSync(stateDir, { recursive: true }); // only now: a refused init leaves no directory behind
|
|
97
|
+
saveState(sf, state);
|
|
98
|
+
return ok({ baseline_sha: state.baseline_sha, caps: state.caps, state_file: sf, ...withReviewMin(state) });
|
|
99
|
+
});
|
|
100
|
+
|
|
101
|
+
export const resume = guarded(({ stateDir }, { slug, iteration }) => {
|
|
102
|
+
const sf = stateFile(stateDir, slug, iteration);
|
|
103
|
+
requireState(sf);
|
|
104
|
+
return ok(loadState(sf));
|
|
105
|
+
});
|
|
106
|
+
|
|
107
|
+
export const pass = guarded(({ env, stateDir, now = nowIso }, args) => {
|
|
108
|
+
const sf = stateFile(stateDir, args.slug, args.iteration);
|
|
109
|
+
requireState(sf);
|
|
110
|
+
const state = loadState(sf);
|
|
111
|
+
const { resolved: max, override } = reresolveCap(env, state, 'max_passes', args.maxPasses, now());
|
|
112
|
+
if (override) {
|
|
113
|
+
applyCapOverride(state, override);
|
|
114
|
+
saveState(sf, state); // persist the raise even if the gate below still fails
|
|
115
|
+
}
|
|
116
|
+
const cur = state.pass;
|
|
117
|
+
if (cur + 1 > max) throw new LoopExit(EXIT_MAX_PASSES, `max-passes-exceeded: pass ${cur + 1} > cap ${max}`);
|
|
118
|
+
const run = checkRun(path.dirname(stateDir), args.slug, Date.parse(now()));
|
|
119
|
+
if (run?.over) throw new LoopExit(EXIT_TIME_BUDGET, `time-budget-exceeded: ${run.elapsed_minutes} of ${run.max_minutes} minutes used by this run`);
|
|
120
|
+
state.pass = cur + 1;
|
|
121
|
+
saveState(sf, state);
|
|
122
|
+
return ok({ pass: state.pass, max_passes: max, ...withReviewMin(state) });
|
|
123
|
+
});
|
|
124
|
+
|
|
125
|
+
// The reasons a stopped loop is closed with (`stopped-<reason>`): the code loop's documented stops, plus the time budget `open` reports.
|
|
126
|
+
export const STOP_REASONS = Object.freeze(['max-passes-exceeded', 'diff-cap-exceeded', 'scope-expansion', 'circuit-breaker', 'user-stop', 'time-budget']);
|
|
127
|
+
export const documentedStatus = (s) => s === 'done' || (typeof s === 'string' && s.startsWith('stopped-') && STOP_REASONS.includes(s.slice(8)));
|
|
128
|
+
|
|
129
|
+
// Ends a running loop: the status and the time it ended, and the summary `finish` prints. Shared by `finish` and the `close` step.
|
|
130
|
+
// A loop that is already over is refused, so a second finish cannot rewrite how the first ended.
|
|
131
|
+
export function endLoop(state, status, at) {
|
|
132
|
+
if (state.status !== 'running') throw usageError(`the loop is not running (status ${JSON.stringify(String(state.status).slice(0, 40))}); it cannot be finished again`);
|
|
133
|
+
state.status = status;
|
|
134
|
+
state.finished = at;
|
|
135
|
+
return {
|
|
136
|
+
status,
|
|
137
|
+
pass: state.pass,
|
|
138
|
+
history: state.history.length,
|
|
139
|
+
cap_overrides: state.cap_overrides || [],
|
|
140
|
+
...(state.dispatches ? { dispatches: state.dispatches } : {}),
|
|
141
|
+
};
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
export const finish = guarded(({ stateDir, now = nowIso }, args) => {
|
|
145
|
+
const sf = stateFile(stateDir, args.slug, args.iteration);
|
|
146
|
+
requireState(sf);
|
|
147
|
+
if (!args.status) throw usageError('finish requires --status');
|
|
148
|
+
const state = loadState(sf);
|
|
149
|
+
const summary = endLoop(state, args.status, now());
|
|
150
|
+
saveState(sf, state);
|
|
151
|
+
return ok(summary);
|
|
152
|
+
});
|
|
153
|
+
|
|
154
|
+
export const runStart = guarded(({ env, root, stateDir }, args) => {
|
|
155
|
+
const raw = firstDefined(args.maxMinutes, env.SOMI_SHIP_LOOP_MAX_MINUTES, configVal(readConfig(root, env), ['ship_loop', 'max_minutes']));
|
|
156
|
+
const max = raw === undefined ? null : validateCap(raw, 'max_minutes');
|
|
157
|
+
if (max === 0) throw usageError('max_minutes: 0 would disable the budget; leave it unset instead');
|
|
158
|
+
return ok(startRun(path.dirname(stateDir), args.slug, max, { force: args.force }));
|
|
159
|
+
});
|
|
160
|
+
|
|
161
|
+
// Over the cap it is a refusal that still carries its JSON: the CLI prints stdout, then the stderr line.
|
|
162
|
+
export const checkDiff = guarded(({ env, root, stateDir, now = nowIso }, args) => {
|
|
163
|
+
const sf = stateFile(stateDir, args.slug, args.iteration);
|
|
164
|
+
requireState(sf);
|
|
165
|
+
const state = loadState(sf);
|
|
166
|
+
const { resolved: cap, override } = reresolveCap(env, state, 'diff_cap_lines', args.diffCap, now());
|
|
167
|
+
if (override) {
|
|
168
|
+
applyCapOverride(state, override);
|
|
169
|
+
saveState(sf, state); // persist the raise even if the gate below still fails
|
|
170
|
+
}
|
|
171
|
+
const { total, weighted, outOfScope } = computeDiff(root, state.baseline_sha, state.iteration_files);
|
|
172
|
+
const out = { diff_lines: total, weighted_lines: weighted, cap, out_of_scope: outOfScope };
|
|
173
|
+
if (cap > 0 && weighted > cap) return refuse(EXIT_DIFF_CAP, `diff-cap-exceeded: weighted ${weighted} > cap ${cap} (out-of-scope counts double)`, out);
|
|
174
|
+
return ok(out);
|
|
175
|
+
});
|
|
176
|
+
|
|
177
|
+
export const reviewScope = guarded(({ env, root, stateDir }, args) => {
|
|
178
|
+
const sf = stateFile(stateDir, args.slug, args.iteration);
|
|
179
|
+
requireState(sf);
|
|
180
|
+
const state = loadState(sf);
|
|
181
|
+
const setting = firstDefined(env.SOMI_CODE_LOOP_REVIEW_SCOPE, configVal(readConfig(root, env), ['code_loop', 'review_scope']), 'delta');
|
|
182
|
+
if (!REVIEW_SCOPES.includes(setting)) throw usageError(`review scope must be one of ${REVIEW_SCOPES.join('|')}, got ${JSON.stringify(setting)}`);
|
|
183
|
+
return ok({ ...scopeOf(root, state, setting), ...withReviewMin(state) });
|
|
184
|
+
});
|
|
185
|
+
|
|
186
|
+
export const recordDispatch = guarded(({ root, installRoot, stateDir }, args) => {
|
|
187
|
+
const sf = stateFile(stateDir, args.slug, args.iteration);
|
|
188
|
+
requireState(sf);
|
|
189
|
+
if (!args.agent) throw usageError('record-dispatch requires --agent');
|
|
190
|
+
const state = loadState(sf);
|
|
191
|
+
const d = dispatchEntry({ root, installRoot, agent: args.agent, host: args.host, pass: state.pass });
|
|
192
|
+
if (!d.ok) return refuse(d.code, `${PROG}: ${d.message}`);
|
|
193
|
+
(state.dispatches ??= []).push(d.entry);
|
|
194
|
+
saveState(sf, state);
|
|
195
|
+
return ok(d.entry);
|
|
196
|
+
});
|
|
197
|
+
|
|
198
|
+
// A pass entry the step reads back: a short verdict without control characters, counts that are numbers (null: unrecorded).
|
|
199
|
+
export const entryOk = (h) => typeof h.verdict === 'string' && h.verdict.length <= 60 && !/\p{Cc}/u.test(h.verdict) && [h.blockers, h.majors].every((n) => n == null || (Number.isFinite(n) && n >= 0));
|
|
200
|
+
// The history entry of the pass in progress: the verdict and counts as given, the cumulative diff and the tree reviewed
|
|
201
|
+
// (the next pass's delta starts there). Shared by `record-pass` and the composite steps, which store it under their cursor.
|
|
202
|
+
export function passEntry(root, state, args, at) {
|
|
203
|
+
const { total } = computeDiff(root, state.baseline_sha, state.iteration_files);
|
|
204
|
+
const entry = {
|
|
205
|
+
pass: state.pass,
|
|
206
|
+
verdict: args.verdict,
|
|
207
|
+
blockers: Number(args.blockers),
|
|
208
|
+
majors: Number(args.majors),
|
|
209
|
+
diff_lines: total,
|
|
210
|
+
tree: snapshotTree(root) ?? undefined,
|
|
211
|
+
at,
|
|
212
|
+
};
|
|
213
|
+
if (!entryOk(entry)) throw usageError('verdict must be at most 60 characters without control characters, and --blockers and --majors non-negative numbers');
|
|
214
|
+
return entry;
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
export const recordPass = guarded(({ root, stateDir, now = nowIso }, args) => {
|
|
218
|
+
const sf = stateFile(stateDir, args.slug, args.iteration);
|
|
219
|
+
requireState(sf);
|
|
220
|
+
if (!args.verdict) throw usageError('record-pass requires --verdict');
|
|
221
|
+
const state = loadState(sf);
|
|
222
|
+
const entry = passEntry(root, state, args, now());
|
|
223
|
+
state.history.push(entry);
|
|
224
|
+
saveState(sf, state);
|
|
225
|
+
return ok(entry);
|
|
226
|
+
});
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
// loop-escalate.mjs -- the code loop's report of what its own cumulative diff warrants. Glue between the diff rows, the facts
|
|
2
|
+
// adapter (escalation-facts.mjs) and the pure rules (escalation.mjs), so loop-step.mjs stays small. It reports only: nothing
|
|
3
|
+
// here changes a review mode, a cap or a stop.
|
|
4
|
+
//
|
|
5
|
+
// escalate(root, env, rows, baseline, ignoredBefore) -> { ran: true, reasons, size_flag, tests_weakened, hard_surface, notes } or { ran: false }.
|
|
6
|
+
// `rows` are the measured diff's rows ({file, added, deleted, status}); the folders the measurement excludes (.claude, and the
|
|
7
|
+
// two .somi paths that carry policy) are listed here and added, because a change there is the one an injected coder would make
|
|
8
|
+
// to loosen its own limits. Everything the object carries is an id from a closed list; a path or file text never goes in. Any
|
|
9
|
+
// failure (a config file that cannot be read, which would drop the user's own sensitive paths; a git call that fails; an id of an
|
|
10
|
+
// unexpected shape) is `{ ran: false }`: the response says the escalation did not run, it is never skipped silently.
|
|
11
|
+
import { loadConfig } from './config-files.mjs';
|
|
12
|
+
import { diffFacts } from './escalation-facts.mjs';
|
|
13
|
+
import { escalation } from './escalation.mjs';
|
|
14
|
+
import { guardedRows } from './loop-review.mjs';
|
|
15
|
+
|
|
16
|
+
const ID = /^[a-z_]{1,32}(:[a-z_]{1,32})?$/;
|
|
17
|
+
const MAX_IDS = 24;
|
|
18
|
+
const ids = (list) => {
|
|
19
|
+
if (!Array.isArray(list) || list.length > MAX_IDS || !list.every((x) => typeof x === 'string' && ID.test(x))) throw new TypeError('not an id list');
|
|
20
|
+
return list;
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
export function escalate(root, env, rows, baseline, ignoredBefore) {
|
|
24
|
+
try {
|
|
25
|
+
const all = [...rows, ...guardedRows(root, baseline, ignoredBefore)];
|
|
26
|
+
const { facts, notes } = diffFacts(all, { config: loadConfig(root, env) }); // its {global, project}, never the merged `.config`
|
|
27
|
+
const e = escalation(facts);
|
|
28
|
+
return { ran: true, reasons: ids(e.reasons), size_flag: e.size_flag === true, tests_weakened: e.tests_weakened === true, hard_surface: ids(e.hard_surface), notes: ids(notes) };
|
|
29
|
+
} catch {
|
|
30
|
+
return { ran: false };
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
// What a step response carries: the object only when it has something to say.
|
|
35
|
+
export const reported = (e) => (e.ran === false || e.reasons.length > 0 || e.size_flag || e.tests_weakened || e.hard_surface.length > 0 || e.notes.length > 0
|
|
36
|
+
? { escalation: { ran: e.ran, ...(e.ran ? { reasons: e.reasons, size_flag: e.size_flag, tests_weakened: e.tests_weakened, hard_surface: e.hard_surface, ...(e.notes.length ? { notes: e.notes } : {}) } : {}) } }
|
|
37
|
+
: {});
|
|
38
|
+
|
|
39
|
+
// The pass's diary text from a stored response's escalation; stored state is read as untrusted, so only ids of the closed shape pass.
|
|
40
|
+
export function diaryText(e) {
|
|
41
|
+
if (e === null || typeof e !== 'object') return '';
|
|
42
|
+
if (e.ran === false) return '; escalation did not run';
|
|
43
|
+
try {
|
|
44
|
+
const parts = [...ids(e.reasons), ...ids(e.hard_surface).map((h) => `hard:${h}`), ...(e.size_flag === true ? ['size_flag'] : []), ...(e.notes === undefined ? [] : ids(e.notes).map((n) => `note:${n}`))];
|
|
45
|
+
return parts.length ? `; escalation: ${parts.join(', ')}` : '';
|
|
46
|
+
} catch {
|
|
47
|
+
return '; escalation unreadable';
|
|
48
|
+
}
|
|
49
|
+
}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
// loop-exit.mjs -- the exit model of the loop engine, as data. A handler never prints or exits: it returns a
|
|
2
|
+
// result ({out, code, message}) or throws a LoopExit, and the caller (the CLI today, a tool later) decides
|
|
3
|
+
// how to deliver it. `message` is the exact stderr text, without the trailing newline. It also owns the words a step
|
|
4
|
+
// response is built from: the gate exits, and the `next` and unwritten `kind` tokens a caller branches on.
|
|
5
|
+
|
|
6
|
+
export const PROG = 'somi-loop';
|
|
7
|
+
|
|
8
|
+
// The exits that are an outcome of a gate, not a refusal (each is a normal result of a step); any other nonzero exit is a
|
|
9
|
+
// refusal. 70 is an internal error: the step did not complete and nothing of the error is echoed.
|
|
10
|
+
export const EXIT_MAX_PASSES = 2;
|
|
11
|
+
export const EXIT_DIFF_CAP = 3;
|
|
12
|
+
export const EXIT_TIME_BUDGET = 4;
|
|
13
|
+
export const EXIT_CIRCUIT_BREAKER = 5;
|
|
14
|
+
export const EXIT_INTERNAL = 70;
|
|
15
|
+
export const GATE_STOPS = Object.freeze([EXIT_MAX_PASSES, EXIT_DIFF_CAP, EXIT_TIME_BUDGET, EXIT_CIRCUIT_BREAKER]);
|
|
16
|
+
|
|
17
|
+
// What a response's `next` may be (null when a step names none) and what an unwritten item's `kind` may be. A record kind is
|
|
18
|
+
// something the caller writes into the file the item names; `notice` is only reported, never written. `reason` and a
|
|
19
|
+
// response's `stop_reason` are text for a person: a flow branches on `next` and `exit` only. Every `next` a step emits is a
|
|
20
|
+
// member of NEXT, never a literal (a test scans the step files).
|
|
21
|
+
export const NEXT = Object.freeze({ taskCoder: 'task-coder', taskPlanner: 'task-planner', taskReviewer: 'task-reviewer', taskReviewers: 'task-reviewers', taskPanel: 'task-panel', open: 'open', close: 'close', summarise: 'summarise', askUser: 'ask-user' });
|
|
22
|
+
export const NEXTS = Object.freeze(Object.values(NEXT));
|
|
23
|
+
export const KIND = Object.freeze({ diaryEntry: 'diary-entry', iterationRow: 'iteration-row', lastActivity: 'last-activity', statusLine: 'status-line', notice: 'notice' });
|
|
24
|
+
export const KINDS = Object.freeze(Object.values(KIND));
|
|
25
|
+
|
|
26
|
+
// Thrown to unwind out of a handler with an exit code and the stderr line that goes with it.
|
|
27
|
+
export class LoopExit extends Error {
|
|
28
|
+
constructor(code, message) {
|
|
29
|
+
super(message);
|
|
30
|
+
this.code = code;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
// Exit 64: a usage or environment error, prefixed with the program name as the CLI always printed it.
|
|
35
|
+
export function usageError(msg) {
|
|
36
|
+
return new LoopExit(64, `${PROG}: ${msg}`);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
// A handler's success: `out` is the one JSON-serialisable object it prints.
|
|
40
|
+
export function ok(out) {
|
|
41
|
+
return { out, code: 0, message: '' };
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
// A handler's refusal: no stdout, a code and a stderr line. Pass `out` when the CLI printed before failing.
|
|
45
|
+
export function refuse(code, message, out) {
|
|
46
|
+
return out === undefined ? { out: undefined, code, message } : { out, code, message };
|
|
47
|
+
}
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
// loop-notes-compact.mjs -- the text half of the diary writer: one entry's shape, where it goes, and the 40/15
|
|
2
|
+
// compaction rule of templates/DIARY.md.tmpl. Pure string functions, no file access (loop-notes.mjs does the IO
|
|
3
|
+
// and the path confinement). Callers pass already-sanitised one-line fields; nothing here reads the environment.
|
|
4
|
+
|
|
5
|
+
export const CATEGORIES = ['plan-change', 'blocker', 'unblock', 'discovery', 'decision-change', 'note', 'review-feedback'];
|
|
6
|
+
const MOVABLE = new Set(['note', 'discovery', 'unblock', 'blocker', 'review-feedback']);
|
|
7
|
+
export const MAX_ENTRIES = 40;
|
|
8
|
+
export const KEEP_NEWEST = 15;
|
|
9
|
+
|
|
10
|
+
// An entry starts at a line beginning `## `; text before the first one is the file's preamble.
|
|
11
|
+
const SPLIT = /^(?=## )/m;
|
|
12
|
+
const withNewline = (s) => (s.endsWith('\n') ? s : `${s}\n`);
|
|
13
|
+
|
|
14
|
+
// A diary or archive in template shape: a `# ` title first, and no carriage returns (a CRLF file is not ours).
|
|
15
|
+
export const archiveShape = (text) => text.startsWith('# ') && !text.includes('\r');
|
|
16
|
+
export const diaryShape = (text) => archiveShape(text) && text.split(SPLIT).length > 1;
|
|
17
|
+
|
|
18
|
+
export const archiveHead = (slug) => `# Diary archive — ${slug}\n\n> Entries moved out of [\`diary.md\`](./diary.md) by compaction, verbatim: batches oldest first, newest first within a batch.\n\n`;
|
|
19
|
+
|
|
20
|
+
export function formatEntry({ stamp, title, category, phase, body }) {
|
|
21
|
+
return `## ${stamp} — ${title}\n\n**Category**: \`${category}\`\n**Phase**: ${phase}\n\n${body ? `${body}\n\n` : ''}---\n\n`;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
// Newest first: the new entry goes in front of the first existing one. Null when the file is not a diary.
|
|
25
|
+
export function insertEntry(text, entry) {
|
|
26
|
+
if (!diaryShape(text)) return null;
|
|
27
|
+
const at = text.search(/^## /m);
|
|
28
|
+
return text.slice(0, at) + entry + text.slice(at);
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
// Replay guard: the newest entry is, text for text, the one about to be written (stamp, title, category, phase, body).
|
|
32
|
+
export const isReplay = (text, entry) => text.split(SPLIT)[1]?.trimEnd() === entry.trimEnd();
|
|
33
|
+
|
|
34
|
+
// A title that reads as a running summary is reserved: only compactDiary writes one.
|
|
35
|
+
export const isSummaryTitle = (title) => /^\s*compacted\s*:/i.test(title);
|
|
36
|
+
|
|
37
|
+
// Category lives in the first lines under the heading; an entry whose category cannot be read is never moved.
|
|
38
|
+
const categoryOf = (chunk) => /^\*\*Category\*\*: `?([a-z-]+)`?/m.exec(chunk.split('\n').slice(1, 6).join('\n'))?.[1];
|
|
39
|
+
const summaryEntry = (stamp, from, to, count) => formatEntry({
|
|
40
|
+
stamp, title: `Compacted: ${from} .. ${to}`, category: 'note', phase: 'work-item-wide',
|
|
41
|
+
body: `${count} older entries moved verbatim to [\`diary-archive.md\`](./diary-archive.md); decision-change and plan-change entries stay here.`,
|
|
42
|
+
});
|
|
43
|
+
const escapeRe = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
44
|
+
// A prior summary is one whose whole chunk is what summaryEntry emits (so a hand-made or forged entry is never
|
|
45
|
+
// "ours"), with a count of at most six digits (always a safe integer). Groups: 1 = from, 2 = to, 3 = count.
|
|
46
|
+
const RUNNING = new RegExp(`^${escapeRe(summaryEntry('<stamp>', '<from>', '<to>', '<count>').trimEnd())}\\s*$`
|
|
47
|
+
.replace('<stamp>', '\\d{4}-\\d\\d-\\d\\d \\d\\d:\\d\\d').replace('<from>', '(\\d{4}-\\d\\d-\\d\\d)')
|
|
48
|
+
.replace('<to>', '(\\d{4}-\\d\\d-\\d\\d)').replace('<count>', '(\\d{1,6})'));
|
|
49
|
+
// An undated heading has no place in the summary's span.
|
|
50
|
+
const dateOf = (chunk) => /^## (\d{4}-\d{2}-\d{2})/.exec(chunk)?.[1];
|
|
51
|
+
|
|
52
|
+
// More than MAX_ENTRIES entries: every movable entry older than the newest KEEP_NEWEST leaves, and one `Compacted:`
|
|
53
|
+
// entry takes the place of the newest of them -- or, when an earlier Compacted entry of our own shape exists, replaces
|
|
54
|
+
// it with the date span widened and the count summed, so the diary keeps one running summary. An entry that only
|
|
55
|
+
// resembles a summary is not ours and is left alone. decision-change, plan-change and Compacted entries never move.
|
|
56
|
+
// Null when the diary is within bounds or nothing is movable; else { diary, archived } where `archived` is the moved
|
|
57
|
+
// text, verbatim.
|
|
58
|
+
export function compactDiary(text, stamp) {
|
|
59
|
+
const [head, ...chunks] = text.split(SPLIT);
|
|
60
|
+
if (chunks.length <= MAX_ENTRIES) return null;
|
|
61
|
+
const moves = chunks.map((c, i) => i >= KEEP_NEWEST && MOVABLE.has(categoryOf(c)) && !/^## [\d-]+ [\d:]+ — Compacted: /.test(c));
|
|
62
|
+
const moved = chunks.filter((_, i) => moves[i]);
|
|
63
|
+
if (moved.length === 0) return null;
|
|
64
|
+
const prior = chunks.findIndex((c) => RUNNING.test(c));
|
|
65
|
+
const before = prior < 0 ? null : RUNNING.exec(chunks[prior]);
|
|
66
|
+
const dates = moved.map(dateOf).filter(Boolean).concat(before ? [before[1], before[2]] : []).sort();
|
|
67
|
+
if (dates.length === 0) dates.push(stamp.slice(0, 10)); // every moved heading undated: the summary's own day
|
|
68
|
+
const summary = summaryEntry(stamp, dates[0], dates[dates.length - 1], moved.length + (before ? Number(before[3]) : 0));
|
|
69
|
+
const at = before ? prior : moves.indexOf(true);
|
|
70
|
+
const kept = chunks.flatMap((c, i) => (i === at ? [summary] : moves[i] ? [] : [withNewline(c)]));
|
|
71
|
+
return { diary: head + kept.join(''), archived: moved.map(withNewline).join('') };
|
|
72
|
+
}
|