bareloop 0.4.0 → 0.5.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/src/plan.js ADDED
@@ -0,0 +1,237 @@
1
+ // plan-v1 validator — the AGENT-authored half of the two-doc story (Layer 2,
2
+ // design record 2026-07-21; PRD v1.12). The plan is the ONLY document the
3
+ // emergent middle authors: an ordered list of bounded steps, each with a tool
4
+ // grant, a rounds bound, a deliverable target, and a form-check exit. This
5
+ // validator gates it before tokens burn, against the SIGNED job spec:
6
+ //
7
+ // verbs ⊆ the spec's tool ceiling → `verb-escape` (the ceiling
8
+ // exists and the plan overreached — distinct from the operator-side
9
+ // `request-red`, which is admission demand against the product menu)
10
+ // bounds ≤ the shell caps → `bounds`
11
+ // scopes/targets inside the signed fence → `scope-escape` / `invalid-value`
12
+ // exits from the closed menu only → `exit-illegal` (arbiter
13
+ // inexpressibility: an exit is declarative data the shell evaluates with
14
+ // its own fixed code — `run` cannot be laundered through it)
15
+ // check references resolve against the SIGNED checks menu → `check-unknown`
16
+ // (decision 1: a check the spec doesn't sign does not exist)
17
+ //
18
+ // Like its siblings (validate.js, job.js) it never throws on JSON text or
19
+ // plain parsed data; every failure is a named {code, path, detail} red.
20
+
21
+ import { TOOL_MENU, LOCKED_TOOLS } from './job.js';
22
+ import { globToPrefix, scopeContained, isObj, isNonEmptyString, sweepSecretLiterals } from './validate.js';
23
+
24
+ /** the closed exit menu (PRD v1.12 §3 + decision 1's `check-passes`): the
25
+ * shell evaluates every form with its own fixed code, never a command — the
26
+ * same both-directions inexpressibility guard as the two-validator split */
27
+ export const EXIT_TYPES = Object.freeze(['artifact-written', 'tree-changed', 'json-valid', 'check-passes']);
28
+ /** decision 8: AND-only conjunction, bounded — no OR (a weak arm would
29
+ * launder the exit), no NOT */
30
+ export const MAX_EXITS_PER_STEP = 2;
31
+ /** plan size bound — per-step rounds bound the spend, but an unbounded step
32
+ * COUNT is still an unbounded claim on the wallet; same 8 as loop.maxIterations */
33
+ export const MAX_PLAN_STEPS = 8;
34
+ /** the write-class verbs (BA-13: `edit` is judged by the same fence as
35
+ * `write`) — a step granting one is a WRITE step for the F17 pairing rule
36
+ * and the v1.18 target requirement */
37
+ export const WRITE_VERBS = Object.freeze(['write', 'edit']);
38
+ const PLAN_FIELDS = ['schema', 'steps'];
39
+ // decision 7: NO dependsOn — v1 is strictly sequential, array order IS the
40
+ // order; a field nothing consumes is a live-looking knob with zero effect
41
+ // (the F16 inert-op class). The arbiter's own vocabulary (close, budget,
42
+ // fence) is absent by construction — unknown-field at every depth.
43
+ const STEP_FIELDS = ['id', 'action', 'tools', 'rounds', 'target', 'exit'];
44
+ const EXIT_FIELDS = {
45
+ 'artifact-written': ['type', 'path', 'pattern'],
46
+ 'tree-changed': ['type', 'scope'],
47
+ 'json-valid': ['type', 'path'],
48
+ 'check-passes': ['type', 'name'],
49
+ };
50
+ const SLUG_RE = /^[a-z0-9][a-z0-9-]*$/;
51
+
52
+ /** @typedef {{code: string, path: string, detail?: string, verb?: string}} Red */
53
+
54
+ /**
55
+ * Validate an agent-authored plan (`schema: "plan-v1"`) against the SIGNED
56
+ * job spec. Never throws on JSON text or plain parsed data; every failure is
57
+ * a named red. Returns the parsed plan on ok (single parse), null on any red.
58
+ * @param {object|string} input parsed plan, or raw JSON text (parse failures are a red)
59
+ * @param {{ job?: any, maxStepRounds?: number }} [opts] `job`: the
60
+ * validateJob-GREEN four-field spec (the ceiling, the fence, and the checks
61
+ * menu all come from it — a missing or non-plan-shape job fails CLOSED);
62
+ * `maxStepRounds`: the shell's per-step rounds ceiling (interpret's
63
+ * tool-mode TURNS_PER_ATTEMPT) — a step may tighten it, never exceed it.
64
+ * @returns {{ ok: boolean, reds: Red[], plan: object|null }}
65
+ */
66
+ export function validatePlan(input, { job, maxStepRounds = 40 } = {}) {
67
+ /** @type {Red[]} */
68
+ const reds = [];
69
+ /** @type {(code: string, path: string, detail?: string) => void} */
70
+ const red = (code, path, detail) => { reds.push(detail ? { code, path, detail } : { code, path }); };
71
+
72
+ // The signed side, fail-CLOSED (the validate.js fence-invalid pattern): the
73
+ // ceiling/fence/menu are meaningless without a plan-shape spec, and an open
74
+ // gate on a malformed one would validate a plan against nothing.
75
+ if (!isObj(job) || !isNonEmptyString(/** @type {any} */ (job).goal) || !Array.isArray(/** @type {any} */ (job).writeScope)) {
76
+ return { ok: false, reds: [{ code: 'job-invalid', path: 'job', detail: 'a plan validates only against a validateJob-green plan shape spec (goal/verdictType/close/checks[]) — validate the job first' }], plan: null };
77
+ }
78
+ const spec = /** @type {Record<string, any>} */ (job);
79
+ /** the signed tool ceiling — validateJob permits omission, meaning the full menu */
80
+ const ceiling = Array.isArray(spec.tools) ? spec.tools : [...TOOL_MENU];
81
+ const fence = spec.writeScope.map(globToPrefix);
82
+ const insideFence = (/** @type {string} */ p) => fence.some((f) => p === f || p.startsWith(f + '/'));
83
+ const checkNames = Array.isArray(spec.checks) ? spec.checks.map((/** @type {any} */ c) => c?.name).filter(isNonEmptyString) : [];
84
+
85
+ let p = input;
86
+ if (typeof p === 'string') {
87
+ try { p = JSON.parse(p); } catch (e) {
88
+ return { ok: false, reds: [{ code: 'parse-error', path: '$', detail: String(/** @type {Error} */ (e).message) }], plan: null };
89
+ }
90
+ }
91
+ if (!isObj(p)) return { ok: false, reds: [{ code: 'parse-error', path: '$', detail: 'plan must be a JSON object' }], plan: null };
92
+ const plan = /** @type {Record<string, any>} */ (p);
93
+
94
+ // 1. shape — unknown top-level fields red (a smuggled close/checks/budget
95
+ // lands here: the arbiter is inexpressible in the plan vocabulary)
96
+ for (const key of Object.keys(plan)) {
97
+ if (!PLAN_FIELDS.includes(key)) red('unknown-field', key, 'the plan vocabulary is steps only — the arbiter (close/budget/fence/checks) is signed, never planned');
98
+ }
99
+ if (plan.schema === undefined) red('missing-required', 'schema');
100
+ else if (plan.schema !== 'plan-v1') red('invalid-value', 'schema', `expected "plan-v1", got ${JSON.stringify(plan.schema)}`);
101
+
102
+ // 2. steps — ordered array (decision 7: order IS the order), bounded count
103
+ if (!Array.isArray(plan.steps) || plan.steps.length === 0) {
104
+ red('missing-required', 'steps', 'non-empty ordered array — v1 executes strictly sequentially, array order is the order');
105
+ } else if (plan.steps.length > MAX_PLAN_STEPS) {
106
+ red('bounds', 'steps', `max ${MAX_PLAN_STEPS} steps — per-step rounds bound the spend, the step count bounds the claim on the wallet`);
107
+ } else {
108
+ const seen = new Set();
109
+ plan.steps.forEach((/** @type {any} */ s, /** @type {number} */ i) => {
110
+ const at = `steps.${i}`;
111
+ if (!isObj(s)) { red('invalid-value', at, 'step must be an object'); return; }
112
+ for (const key of Object.keys(s)) {
113
+ if (!STEP_FIELDS.includes(key)) red('unknown-field', `${at}.${key}`, key === 'dependsOn' ? 'no dependsOn in v1 — strictly sequential, array order is the order (an inert knob is a fake contrast lever)' : 'not a step field — the arbiter is inexpressible here');
114
+ }
115
+ if (!isNonEmptyString(s.id) || !SLUG_RE.test(s.id)) red('invalid-value', `${at}.id`, 'kebab-case slug');
116
+ else if (seen.has(s.id)) red('duplicate-id', `${at}.id`, s.id);
117
+ else seen.add(s.id);
118
+
119
+ if (!isNonEmptyString(s.action)) red('missing-required', `${at}.action`, 'the step\'s task text — a step without one is an unaimed worker');
120
+
121
+ // tools ⊆ the SIGNED ceiling: a verb beyond it is verb-escape with the
122
+ // verb as structured data (the ledger counts overreach per verb) — an
123
+ // unknown string stays a typo (invalid-value), never an escape
124
+ let writeStep = false;
125
+ if (s.tools === undefined) red('missing-required', `${at}.tools`, 'every step declares its grant — the narrowed menu is the step boundary');
126
+ else if (!(Array.isArray(s.tools) && s.tools.length > 0
127
+ && s.tools.every((/** @type {unknown} */ t) => typeof t === 'string')
128
+ && new Set(s.tools).size === s.tools.length)) {
129
+ red('invalid-value', `${at}.tools`, `non-empty unique subset of the spec ceiling [${ceiling.join(', ')}]`);
130
+ } else {
131
+ // three disjoint classes: a LOCKED verb (run — never in any ceiling) is
132
+ // an escape the ledger must never bury as a typo; a menu verb outside
133
+ // the SIGNED ceiling is an escape too (overreach, not admission demand);
134
+ // a string in neither list is a typo (invalid-value)
135
+ const unknown = s.tools.filter((/** @type {string} */ t) => !TOOL_MENU.includes(t) && !LOCKED_TOOLS.includes(t));
136
+ if (unknown.length) red('invalid-value', `${at}.tools`, `unknown tool(s) ${unknown.join(', ')} — menu: ${TOOL_MENU.join('|')}`);
137
+ for (const t of s.tools.filter((/** @type {string} */ t) => LOCKED_TOOLS.includes(t))) {
138
+ reds.push({ code: 'verb-escape', path: `${at}.tools`, verb: t, detail: `"${t}" is locked at every layer — a worker that can run commands can run its own close` });
139
+ }
140
+ for (const t of s.tools.filter((/** @type {string} */ t) => TOOL_MENU.includes(t) && !ceiling.includes(t))) {
141
+ reds.push({ code: 'verb-escape', path: `${at}.tools`, verb: t, detail: `"${t}" is outside the signed ceiling [${ceiling.join(', ')}] — the plan may narrow the grant, never widen it` });
142
+ }
143
+ writeStep = s.tools.some((/** @type {string} */ t) => WRITE_VERBS.includes(t));
144
+ }
145
+
146
+ // rounds ≤ the shell cap (cap-not-estimate; the step bound IS maxTurns)
147
+ if (!(Number.isInteger(s.rounds) && s.rounds >= 1 && s.rounds <= maxStepRounds)) {
148
+ red('bounds', `${at}.rounds`, `integer 1..${maxStepRounds} — the step bound is the Gate's maxTurns, it may tighten the shell cap, never exceed it`);
149
+ }
150
+
151
+ // target (v1.18): the per-step deliverable — required on write steps,
152
+ // always inside the signed fence when present
153
+ if (s.target === undefined || s.target === '') {
154
+ if (writeStep) red('missing-required', `${at}.target`, 'a write-granted step declares its deliverable path (v1.18) — an untargeted write step is unattributable');
155
+ } else if (!isNonEmptyString(s.target) || !scopeContained(s.target)) {
156
+ red('invalid-value', `${at}.target`, 'a relative path inside the run dir — no absolute paths, no ".." segments');
157
+ } else if (!insideFence(globToPrefix(s.target))) {
158
+ red('scope-escape', `${at}.target`, `"${s.target}" is outside the signed fence [${spec.writeScope.join(', ')}]`);
159
+ }
160
+
161
+ validateExit(s, at, red, { checkNames, fence: spec.writeScope, insideFence, writeStep });
162
+ });
163
+ }
164
+
165
+ // 3. secrets sweep — the agent-authored document is the riskier entry point
166
+ sweepSecretLiterals(plan, red);
167
+
168
+ return { ok: reds.length === 0, reds, plan: reds.length === 0 ? plan : null };
169
+ }
170
+
171
+ /**
172
+ * A step's exit: AND-only conjunction from the closed menu, max 2 (decision
173
+ * 8). Every form is declarative data the shell evaluates with its own fixed
174
+ * code — `exit-illegal` is the arbiter-inexpressibility red.
175
+ * @param {Record<string, any>} s the step
176
+ * @param {string} at step path prefix
177
+ * @param {(code: string, path: string, detail?: string) => void} red
178
+ * @param {{ checkNames: string[], fence: string[], insideFence: (p: string) => boolean, writeStep: boolean }} ctx
179
+ */
180
+ function validateExit(s, at, red, { checkNames, fence, insideFence, writeStep }) {
181
+ if (!Array.isArray(s.exit) || s.exit.length === 0) {
182
+ red('missing-required', `${at}.exit`, `non-empty array from the closed menu ${EXIT_TYPES.join('|')} — ALL listed exits must pass (AND-only); a step without an exit has no progress gate`);
183
+ return;
184
+ }
185
+ if (s.exit.length > MAX_EXITS_PER_STEP) {
186
+ red('exit-illegal', `${at}.exit`, `max ${MAX_EXITS_PER_STEP} exits — AND-only conjunction, bounded (decision 8)`);
187
+ return;
188
+ }
189
+ let hasTreeChanged = false;
190
+ let hasCheck = false;
191
+ s.exit.forEach((/** @type {any} */ e, /** @type {number} */ i) => {
192
+ const eAt = `${at}.exit.${i}`;
193
+ if (!isObj(e) || !EXIT_TYPES.includes(e.type)) {
194
+ red('exit-illegal', eAt, `menu: ${EXIT_TYPES.join('|')} — an exit is declarative data the shell evaluates with its own fixed code, never a command`);
195
+ return;
196
+ }
197
+ for (const key of Object.keys(e)) {
198
+ if (!EXIT_FIELDS[e.type].includes(key)) red('unknown-field', `${eAt}.${key}`, `not a ${e.type} field (commands and script bodies land here)`);
199
+ }
200
+ if (e.type === 'check-passes') {
201
+ hasCheck = true;
202
+ if (!isNonEmptyString(e.name)) red('invalid-value', `${eAt}.name`, 'the signed check\'s name');
203
+ else if (!checkNames.includes(e.name)) {
204
+ // decision 1: a check the spec doesn't sign DOES NOT EXIST — and the
205
+ // detail names the signed menu so the replan can aim, not guess
206
+ red('check-unknown', eAt, `"${e.name}" is not a signed check — the agent references checks, never authors them; signed menu: [${checkNames.join(', ') || 'none'}]`);
207
+ }
208
+ } else if (e.type === 'tree-changed') {
209
+ hasTreeChanged = true;
210
+ if (!isNonEmptyString(e.scope) || !scopeContained(e.scope) || globToPrefix(e.scope).includes('*')) {
211
+ red('invalid-value', `${eAt}.scope`, 'a contained scope (trailing /** or /* only, no ".." or absolute)');
212
+ } else if (!insideFence(globToPrefix(e.scope))) {
213
+ red('scope-escape', `${eAt}.scope`, `"${e.scope}" is outside the signed fence [${fence.join(', ')}]`);
214
+ }
215
+ } else { // artifact-written | json-valid — a named file path inside the fence
216
+ if (!isNonEmptyString(e.path) || !scopeContained(e.path)) {
217
+ red('invalid-value', `${eAt}.path`, 'a relative file path inside the run dir — no absolute paths, no ".." segments');
218
+ } else if (!insideFence(globToPrefix(e.path))) {
219
+ red('scope-escape', `${eAt}.path`, `"${e.path}" is outside the signed fence [${fence.join(', ')}]`);
220
+ }
221
+ if (e.type === 'artifact-written' && e.pattern !== undefined) {
222
+ if (!isNonEmptyString(e.pattern)) red('invalid-value', `${eAt}.pattern`, 'regex source string');
223
+ else {
224
+ try { new RegExp(e.pattern, 'm'); }
225
+ catch { red('invalid-value', `${eAt}.pattern`, 'must compile as a RegExp'); }
226
+ }
227
+ }
228
+ }
229
+ });
230
+ // The F17 pairing rule: the seed tree is green, so a lone check-passes on a
231
+ // write-granted step would pass on the UNTOUCHED repo — an unearned exit.
232
+ // The POC's changed-from-seed stage existed for exactly this; here it is a
233
+ // validation law, stated in the plan itself (never hardwired shell code).
234
+ if (writeStep && hasCheck && !hasTreeChanged) {
235
+ red('exit-illegal', `${at}.exit`, 'check-passes on a write-granted step requires the tree-changed conjunct — the seed tree is green, so a lone check would pass on the untouched repo (F17/F46 already-green trap)');
236
+ }
237
+ }