bareloop 0.8.0 → 0.10.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.
@@ -0,0 +1,1486 @@
1
+ // THE AUTHORING SURFACE — close-authoring v1, module M2 (design record
2
+ // 2026-08-07, FROZEN; gate-2 POC closed 2026-08-08).
3
+ //
4
+ // M1 owns what a stage DOES. This module owns what a declaration may SAY, and
5
+ // whether a given declaration said it legally. Three things live here and they
6
+ // belong together because they are one contract read from three sides:
7
+ //
8
+ // 1. THE KIND CATALOGUE — the entire vocabulary an authoring call has. It
9
+ // parameterises kinds whose implementations we own; a script body, a shell
10
+ // fragment and a new kind are not rejected late, they are INEXPRESSIBLE
11
+ // (D2/D3, the `check-passes(name)` move). `judged-floor` and
12
+ // `human-confirms` are LOCKED MENU ENTRIES: declaring one is a distinct
13
+ // `locked-kind` red at VALIDATION, before any tokens, carrying counted
14
+ // demand (the LOCKED_VERDICTS pattern, src/job.js:520). `harness-loop` is
15
+ // ABSENT — no entry at all, so declaring it is an unknown-kind typo, which
16
+ // is the honest reading of a kind that is out of v1 (gate 1, Result 2).
17
+ //
18
+ // 2. THE TYPES GENRE — the one genre v1 admits (D13). Its template is FROZEN
19
+ // TEXT, byte-identical to the prereg's addendum 3, and its two guard
20
+ // batteries are OURS. D5 is the load-bearing decision of the whole design:
21
+ // the close carries guards the user did not ask for and cannot remove,
22
+ // because the stage that forecloses the easy win is exactly the stage an
23
+ // LLM asked "what would done look like" will not write well (F87 + the RSI
24
+ // rubric-close gotcha). Gate-2 round 1 measured the failure mode precisely:
25
+ // the guard-stripped arm DID invent a guard-SHAPED stage — with 2 of its 4
26
+ // patterns dead letters and both live suppression channels of that patient
27
+ // missed. The shape is cheap; the battery is what was paid for.
28
+ //
29
+ // Round 3 added the two residues addendum 6 hands to this build, and both
30
+ // are OURS TO INJECT, never model-filled:
31
+ // - guard SCOPE. The suppression scan covers EVERY changed file of the
32
+ // genre's extensions. Round 3's arm A narrowed it to the two target
33
+ // files, which reads stricter and is not: a suppression added in a NEW
34
+ // helper file walks straight through a target-file filter.
35
+ // - genre ENV. `MYPYPATH` on a Python patient is the Result-5 fact no
36
+ // user could supply and no model found (round 2 authored `src`, which
37
+ // is wrong). It is expressed HERE as genre data and applied by the flow
38
+ // (M3); a declaration that authors it itself is a red.
39
+ //
40
+ // 3. THE DECLARATION VALIDATOR — the first of D9's three mechanical gates.
41
+ // Schema, kinds, params, the F84 one-population law, F49's static regex
42
+ // reject, the D5 guard equality, and hamr's listing rule: every path the
43
+ // model wrote down must SELECT from the real seed listing. Round 2's arm A
44
+ // invented `src/alertEmail.js` from the user's prose ("the alert email
45
+ // one") and silently reclassified 15 real errors into the wrong
46
+ // population. A path is not a judgment call — it either names something in
47
+ // the tree or it does not.
48
+ //
49
+ // What this module deliberately does NOT do:
50
+ // - it never judges QUALITY. Nothing here asks whether the close is a GOOD
51
+ // close; D9's other two gates (the precheck and the seed-verdict read) plus
52
+ // the user's signature do that, and no LLM validates another LLM's close.
53
+ // - it never enforces the genre's stage SKELETON. The template states it to
54
+ // the author; a close with no work stage is caught by the seed-verdict read
55
+ // (nothing red at seed = nothing to do), which is where round 2's arm B
56
+ // died. A validator that demanded named stages would be authoring them.
57
+ // - it never inspects command ARGS for paths. hamr's rule enumerates path
58
+ // PARAMS; an arg list carries flags, module names and config paths, and a
59
+ // `path-not-in-listing` red on `--strict` would be nonsense. The named
60
+ // consequence, not smoothed: an invented path can still ride in `args`, and
61
+ // the seed-verdict read is what catches it (it did, in round 2).
62
+ //
63
+ // One spelling of everything shared: `normalizeParser` and `regexGroups` are
64
+ // M1's, imported, never re-spelled — the validator and the executor must agree
65
+ // on what a parser MEANS or the one that grades is the one nobody validated.
66
+ // `hasNestedQuantifier` and `globToPrefix` are the shipped primitives from
67
+ // src/validate.js for the same reason (F49 is monotonic-only doctrine and the
68
+ // detector is never touched from here; globToPrefix's collapse order is fence
69
+ // territory, F9).
70
+ //
71
+ // NOTE for M4 wiring: nothing here is exported from src/index.js yet. M1
72
+ // flagged a `runClose` naming collision between the kind executor and
73
+ // src/ralph.js; the public surface is settled once at M4, not piecemeal.
74
+
75
+ import { normalizeParser } from './kinds.js';
76
+ import { isObj, isNonEmptyString, hasNestedQuantifier, globToPrefix } from './validate.js';
77
+
78
+ /** @typedef {{code: string, path: string, detail: string, [k: string]: any}} Red */
79
+ /** @typedef {{required: readonly string[], optional: readonly string[], pathParams: readonly string[], locked?: true, verdictClass: string, shape: string, asserts: string}} KindSpec */
80
+
81
+ // ── 0. THE VERDICT CLASSES ───────────────────────────────────────────────────
82
+ //
83
+ // The user's own answer (PRD v1.57 §1, restoring the 2026-07-21 radio and
84
+ // superseding D4): is your *done* machine-checkable, does it need judgment, or
85
+ // does it need a person. It is a CLOSED SET handed over enumerated, never a
86
+ // prose rule about what a legal answer would look like.
87
+ //
88
+ // TWO COPIES, PINNED BY THE SUITE RATHER THAN IMPORTED. `src/job.js` owns the
89
+ // same menu as the spec's radio (`VERDICT_TYPES`) and imports this module
90
+ // transitively (job → declaredclose → authoring), so importing it back would
91
+ // close a cycle and hand this module a TDZ-undefined constant at load. The suite
92
+ // asserts the two lists are identical, which is the same treatment
93
+ // `CATALOGUE_LIVE_KINDS` and the executor's `LIVE_KINDS` already get.
94
+
95
+ /** the whole menu, in ascending order of what it takes to render the verdict */
96
+ export const VERDICT_CLASSES = Object.freeze(['green', 'soft-green', 'hitl']);
97
+ /** declared-but-locked: selecting one is COUNTED demand, never an admission */
98
+ export const LOCKED_CLASSES = Object.freeze(['soft-green', 'hitl']);
99
+ /** the classes v1 actually builds — exactly one */
100
+ export const LIVE_CLASSES = Object.freeze(VERDICT_CLASSES.filter((c) => !LOCKED_CLASSES.includes(c)));
101
+
102
+ /** the hierarchy as a comparable number. `green` is the FLOOR: a mechanical
103
+ * measurement is the cheapest honest verdict, a judge is above it, a person is
104
+ * above that. Read by the ceiling rule and by nothing else. */
105
+ const CLASS_RANK = Object.freeze({ green: 0, 'soft-green': 1, hitl: 2 });
106
+
107
+ /**
108
+ * THE CEILING (hamr, 2026-08-08, *"yes to both, go"*): the picked class is a
109
+ * PROMISE, and this is what the composition actually demands.
110
+ *
111
+ * Every kind carries the class of verdict it can honestly render, so a
112
+ * declaration's ceiling is the HIGHEST class any of its stages needs. A pick
113
+ * below that ceiling is a silent UPGRADE — a judgment ruler running under a
114
+ * green promise, which is exactly the fake-hard verdict `CLASS_BY_CLOSE` and
115
+ * `CLASS_BY_VERDICT` exist to stop, defeated from ABOVE by never letting the
116
+ * illegal pair be formed.
117
+ *
118
+ * INERT IN v1 BY CONSTRUCTION, which is why it is cheap now: every LIVE kind is
119
+ * mechanical, so no declaration a v1 catalogue can express reaches above green.
120
+ * It is written before the second class exists so the first soft-green kind is
121
+ * not the thing that discovers the question.
122
+ *
123
+ * A kind the catalogue does not know contributes NOTHING — it already carries an
124
+ * `unknown-kind` red, and guessing a class for it would be deriving the promise
125
+ * from a typo. A catalogue entry with no class at all THROWS: the catalogue is
126
+ * OURS, and failing loudly beats weighing a kind whose honesty nobody stated.
127
+ * @param {any} declaration
128
+ * @param {Record<string, KindSpec>} [catalogue]
129
+ * @returns {{class: string, kind: string, stage: string|null, locked: boolean}|null}
130
+ */
131
+ export function closeCeiling(declaration, catalogue = KIND_CATALOGUE) {
132
+ const stages = Array.isArray(declaration?.stages) ? declaration.stages : [];
133
+ /** @type {{class: string, kind: string, stage: string|null, locked: boolean}|null} */
134
+ let top = null;
135
+ for (const s of stages) {
136
+ if (!isObj(s) || !isNonEmptyString(s.kind)) continue;
137
+ const spec = catalogue[s.kind];
138
+ if (!spec) continue;
139
+ if (!Object.hasOwn(CLASS_RANK, spec.verdictClass)) {
140
+ throw new Error(`[authoring] catalogue kind "${s.kind}" declares no verdict class — every kind states the class `
141
+ + `of verdict it can honestly render (one of ${VERDICT_CLASSES.join(', ')})`);
142
+ }
143
+ if (top === null || CLASS_RANK[spec.verdictClass] > CLASS_RANK[top.class]) {
144
+ top = {
145
+ class: spec.verdictClass,
146
+ kind: s.kind,
147
+ stage: isNonEmptyString(s.name) ? s.name : null,
148
+ locked: spec.locked === true,
149
+ };
150
+ }
151
+ }
152
+ return top;
153
+ }
154
+
155
+ // ── 1. THE KIND CATALOGUE ────────────────────────────────────────────────────
156
+
157
+ /**
158
+ * The whole vocabulary, as DATA. `shape` and `asserts` are the strings the
159
+ * authoring prompt renders (M3) — the prompt and this validator must judge the
160
+ * same facts, so they read one catalogue rather than two (the drift class
161
+ * SECRET_PATTERNS exists to prevent, one layer up).
162
+ *
163
+ * `pathParams` names every param that carries a repository path, in dotted
164
+ * form. It is data rather than a switch so hamr's listing rule reaches a new
165
+ * path-bearing param the day one is added, instead of the day someone
166
+ * remembers to widen a condition.
167
+ *
168
+ * `verdictClass` is the class of verdict this kind can HONESTLY render, and it
169
+ * is what makes the user's pick a promise the composer must keep (PRD v1.57 §1).
170
+ * Every live kind is `green` — a command's measurement is the truth — so the
171
+ * ceiling rule is inert in v1 by construction; the two locked kinds carry the
172
+ * classes they belong to so the rule is already correct the day one goes live.
173
+ *
174
+ * Optionality is read off the prereg §5 table, with ONE deliberate divergence
175
+ * from the gate-2 POC validator, named because it reverses a POC behaviour:
176
+ * `pattern-absent-in-diff.scope` is OPTIONAL here and the guard ships without
177
+ * it. Under addendum 6 the guard's scope is GENRE property and the answer is
178
+ * "every changed file of these extensions" — an absent scope is exactly that
179
+ * (M1's `inScope` admits everything when no scope object is present). The POC
180
+ * required it, and required it filled, which is how round 3's arm A came to
181
+ * narrow the scan and call it stricter.
182
+ * @type {Record<string, KindSpec>}
183
+ */
184
+ export const KIND_CATALOGUE = Object.freeze({
185
+ 'command-exit': Object.freeze({
186
+ verdictClass: 'green',
187
+ required: Object.freeze(['cmd', 'args', 'expectExit']),
188
+ optional: Object.freeze(['timeoutMs', 'env']),
189
+ pathParams: Object.freeze([]),
190
+ shape: 'cmd: string, args: string[], expectExit: integer, timeoutMs?: integer, env?: {NAME: value}',
191
+ asserts: 'run cmd/args in the repository; the exit code must equal expectExit.',
192
+ }),
193
+ 'count-not-worse': Object.freeze({
194
+ verdictClass: 'green',
195
+ required: Object.freeze(['cmd', 'args', 'parser', 'scope', 'direction', 'baseline']),
196
+ optional: Object.freeze(['timeoutMs', 'env']),
197
+ pathParams: Object.freeze(['scope.includePrefixes', 'scope.excludePrefixes']),
198
+ shape: 'cmd: string, args: string[], '
199
+ + 'parser: {terms: [{lineMatch: regex-string, capture?: integer, sign: 1 | -1, '
200
+ + 'aggregate: "first" | "sum", region: "whole-output" | {anchor: regex-string, capture: integer}}]} '
201
+ + '— or the short form {lineMatch: regex-string, capture?: integer}, '
202
+ + 'scope: {includePrefixes?: string[], excludePrefixes?: string[]}, '
203
+ + 'direction: "lower-is-better" | "higher-is-better", baseline: "seed" | 0, timeoutMs?: integer, env?: {NAME: value}',
204
+ asserts: 'run cmd/args; read a NUMBER out of the output with parser, keep only what scope selects, and '
205
+ + 'require that number to be not-worse than baseline in the stated direction. baseline "seed" is the same '
206
+ + 'number taken from this run\'s own starting point, measured every run; baseline 0 is literally zero. '
207
+ + 'You never write a number you measured yourself — you write the rule. '
208
+ + 'If the tool exits NON-ZERO and its output matches none of your parser\'s terms, the stage stops as a broken '
209
+ + 'instrument rather than recording zero: a crashed checker reporting nothing is unknown, not clean. Name a '
210
+ + 'tool that prints its count on a clean run.',
211
+ }),
212
+ 'pattern-absent-in-diff': Object.freeze({
213
+ verdictClass: 'green',
214
+ required: Object.freeze(['patterns', 'extensions']),
215
+ optional: Object.freeze(['scope']),
216
+ pathParams: Object.freeze(['scope.includePrefixes', 'scope.excludePrefixes']),
217
+ shape: 'patterns: [{id: string, regex: regex-string}], extensions: string[], '
218
+ + 'scope?: {includePrefixes?: string[], excludePrefixes?: string[]}',
219
+ asserts: 'none of the patterns may appear in any line this run ADDED, across every file this run changed '
220
+ + 'with one of the named extensions.',
221
+ }),
222
+ 'files-changed': Object.freeze({
223
+ verdictClass: 'green',
224
+ required: Object.freeze(['allowPrefixes', 'requireNonEmpty']),
225
+ optional: Object.freeze([]),
226
+ pathParams: Object.freeze(['allowPrefixes']),
227
+ shape: 'allowPrefixes: string[], requireNonEmpty: true',
228
+ asserts: 'the set of files this run changed must be non-empty and must lie wholly inside allowPrefixes.',
229
+ }),
230
+ // LOCKED: named so declaring one is COUNTED DEMAND rather than an unknown-kind
231
+ // typo (D13 forward-compat point 2). Disclosure is not admission — these do
232
+ // not run in v1, and `close[]` on disk stays predicate-only and shape-enforced
233
+ // (src/job.js:442), so the inexpressibility that is already free stays free.
234
+ 'judged-floor': Object.freeze({
235
+ verdictClass: 'soft-green',
236
+ required: Object.freeze([]), optional: Object.freeze([]), pathParams: Object.freeze([]), locked: true,
237
+ shape: 'LOCKED — not available in v1',
238
+ asserts: 'a judged score must clear a floor. Declaring it is recorded as demand; it will not run.',
239
+ }),
240
+ 'human-confirms': Object.freeze({
241
+ verdictClass: 'hitl',
242
+ required: Object.freeze([]), optional: Object.freeze([]), pathParams: Object.freeze([]), locked: true,
243
+ shape: 'LOCKED — not available in v1',
244
+ asserts: 'a person renders the verdict. Declaring it is recorded as demand; it will not run.',
245
+ }),
246
+ });
247
+
248
+ /**
249
+ * Which kinds can carry an environment at all, read off the CATALOGUE rather
250
+ * than a hand-kept list. ONE spelling, because two consumers must agree
251
+ * EXACTLY: `applyGenreEnv` injects the genre's variable into these stages and
252
+ * nowhere else, and the validator's completeness rule demands it on these
253
+ * stages and nowhere else. A second copy that drifted either way is a hole —
254
+ * stages injected but unchecked, or stages checked for what nothing injects.
255
+ * @param {string} kind @param {Record<string, KindSpec>} [catalogue]
256
+ */
257
+ export function envCapableKind(kind, catalogue = KIND_CATALOGUE) {
258
+ const spec = catalogue[kind];
259
+ return !!spec && !spec.locked && [...spec.required, ...spec.optional].includes('env');
260
+ }
261
+
262
+ export const CATALOGUE_KINDS = Object.freeze(Object.keys(KIND_CATALOGUE));
263
+ export const LOCKED_KINDS = Object.freeze(CATALOGUE_KINDS.filter((k) => KIND_CATALOGUE[k].locked));
264
+ /** the catalogue's live half — asserted EQUAL to the executor's own LIVE_KINDS
265
+ * by the suite, both directions: a kind the catalogue offers and the executor
266
+ * cannot run is a close that stops at runtime, and a kind the executor runs
267
+ * that the catalogue never names is a capability nothing can reach. */
268
+ export const CATALOGUE_LIVE_KINDS = Object.freeze(CATALOGUE_KINDS.filter((k) => !KIND_CATALOGUE[k].locked));
269
+
270
+ export const DIRECTIONS = Object.freeze(['lower-is-better', 'higher-is-better']);
271
+ /** D12: the close stores the COUNTING RULE, never the number. "seed" is measured
272
+ * at this run's own seed every run; 0 is literally zero. A frozen constant (the
273
+ * hand-written closes' `SEED_ERRORS 63`) is exactly what this menu retires. */
274
+ export const BASELINES = Object.freeze(['seed', 0]);
275
+ /** a runaway stage list is a red, not a bill — the sibling of M1's MAX_TERMS */
276
+ export const MAX_STAGES = 12;
277
+
278
+ const NAME_RE = /^[a-z][a-z0-9-]{1,48}$/;
279
+
280
+ /**
281
+ * THE DENY FLOOR under a declared command (hamr's ruling, PRD v1.57 §3: *"there
282
+ * should be a floor of all dangerous things… straight out block… no one wants
283
+ * `rm -rf` allowed either ways"*).
284
+ *
285
+ * Four families, and each one is here for a different reason:
286
+ * - SHELL INTERPRETERS. A shell runs anything, so admitting one makes every
287
+ * other entry decoration — the D3 line ("the danger is in the ACTIONS, not
288
+ * the SYNTAX") reappearing at the close's own spawn.
289
+ * - DESTRUCTIVE / SYSTEM commands. The `rm -rf` class the ruling names, plus
290
+ * the machine-level siblings (`dd`, the `mkfs` FAMILY, shutdown/reboot) and
291
+ * privilege escalation.
292
+ * - FETCH-AND-RUN vectors (`curl`, `wget`). A close that downloads its own
293
+ * instrument is a close nobody signed.
294
+ * - INDIRECTION (`env`, `eval`, `exec`, `xargs`). They run a program the
295
+ * declaration never names, which defeats every entry above by construction.
296
+ *
297
+ * It is a FLOOR, and MONOTONIC: names are only ever ADDED, never removed or
298
+ * narrowed (the F49 precedent — closing a false negative is the allowed
299
+ * direction; chasing a false positive is not). A legitimate runner refused here
300
+ * is fixed by declaring the runner, never by shrinking the floor.
301
+ *
302
+ * It is NOT A SANDBOX, and nothing here claims to be one. The local-trust model
303
+ * of v1.41 stands intact and its limitations are written out in PRD v1.57 §3:
304
+ * close children keep the operator's OS user, network egress and file access;
305
+ * `args` are not inspected (`node -e <anything>` is reachable and always was);
306
+ * resource use is bounded by liveness checks, not quotas. The floor narrows
307
+ * blast radius; it does not promise containment.
308
+ */
309
+ export const DENIED_COMMANDS = Object.freeze([
310
+ // shell interpreters
311
+ 'sh', 'bash', 'zsh', 'dash', 'ksh', 'csh', 'tcsh', 'fish',
312
+ // destructive / system
313
+ 'rm', 'rmdir', 'dd', 'mkfs', 'shutdown', 'reboot', 'halt', 'poweroff',
314
+ 'sudo', 'su', 'chmod', 'chown', 'kill', 'killall', 'pkill',
315
+ // fetch-and-run
316
+ 'curl', 'wget',
317
+ // indirection — a program the declaration never named
318
+ 'env', 'eval', 'exec', 'xargs',
319
+ ]);
320
+
321
+ /**
322
+ * The floor's decision for one declared `cmd`, as a reason or null.
323
+ *
324
+ * NORMALISATION FIRST, because that is where the dodge lives: `/usr/bin/rm`
325
+ * carries the same program as `rm` and only a basename read taken AFTER
326
+ * splitting the path can see it. Case is folded for the same reason.
327
+ *
328
+ * A cmd naming a program OUTSIDE the repository — an absolute path, or one that
329
+ * climbs out with `..` — is refused whatever its basename says. Two reasons, and
330
+ * both are the fail-safe direction: the validator has no repository in hand at
331
+ * every call site (the job validator judges a signed spec with no tree), so
332
+ * "outside" cannot be decided per-machine; and a machine-absolute path inside a
333
+ * SIGNED artefact grades a different machine than the one it was signed on.
334
+ * @param {string} cmd @returns {string|null}
335
+ */
336
+ export function deniedCommandReason(cmd) {
337
+ const raw = String(cmd ?? '').trim();
338
+ if (raw === '') return null; // shape is the schema walk's business, not the floor's
339
+ const segments = raw.split(/[\\/]/);
340
+ // `/^[a-zA-Z]:/` is the DRIVE-ABSOLUTE spelling, and it is here because
341
+ // `scopeContained` (src/validate.js) already counts it as an escape: two
342
+ // path-escape readings in one codebase that disagree are two instruments, and
343
+ // this was the one that let `C:\Windows\System32\evil.bat` through to the
344
+ // basename floor, which had never heard of it. MONOTONIC — this only ever adds
345
+ // a rejection, which is the direction F49's precedent licenses.
346
+ if (raw.startsWith('/') || raw.startsWith('\\') || /^[a-zA-Z]:/.test(raw) || segments.includes('..')) {
347
+ return `"${raw}" names a program outside the repository — a declared close runs the patient's own tools, `
348
+ + 'reached relatively or through the project\'s runner, never an absolute path (which grades a different '
349
+ + 'machine than the one that signed it)';
350
+ }
351
+ const base = /** @type {string} */ (segments.at(-1)).toLowerCase();
352
+ const denied = DENIED_COMMANDS.includes(base) || base.startsWith('mkfs.');
353
+ if (!denied) return null;
354
+ return `"${raw}" resolves to "${base}", which is on the deny floor — shells, destructive and system commands, `
355
+ + 'fetch-and-run vectors and program indirection are blocked outright (PRD v1.57 §3). A close names the '
356
+ + 'patient\'s own instrument; it never names a program that can undo the patient';
357
+ }
358
+
359
+ // ── 2. THE TYPES GENRE ───────────────────────────────────────────────────────
360
+
361
+ /**
362
+ * THE FROZEN TYPES GENRE TEMPLATE — prereg addendum 3's six policy points,
363
+ * VERBATIM. The suite reads the prereg and compares BYTES, so a paraphrase here
364
+ * fails the build rather than quietly changing what every future close is
365
+ * authored against. It deliberately carries no repo-specific command, path, env
366
+ * value or regex: round 2 measured that stating the LAW still leaves the model
367
+ * to find the VALUE, and that is the axis the build must keep live.
368
+ */
369
+ export const TYPES_GENRE_TEMPLATE = `1. The graded instrument is the STRICT form of the language's type checker, regardless of what
370
+ the repo's own scripts run. If the repo's script omits strictness, the close adds it.
371
+ 2. Tools are invoked so their binaries actually resolve — through the project's own package
372
+ runner or language module runner, never a bare binary name.
373
+ 3. The stage skeleton, in first-red-wins order: changed-from-seed (guard) → typecheck (error
374
+ count IN the target scope, baseline 0, lower-is-better) → typecheck-outside (error count
375
+ OUTSIDE the target scope, baseline measured at seed, a ceiling — required whenever the job
376
+ scopes to a subset of the tree; omitted only for whole-tree jobs) → tests-kept (a floor on
377
+ tests that actually EXECUTED, baseline at seed, higher-is-better; a skipped or deselected
378
+ test did not run and must not count) → suite-green (the suite exits clean AND reports zero
379
+ failing tests — two assertions) → no-suppressions (guard).
380
+ 4. One population per stage — two structurally different counts never share a stage.
381
+ 5. The checker must judge the PATIENT's own tree: if imports could resolve to an installed or
382
+ editable copy elsewhere, the environment is set so they resolve inside the patient.
383
+ 6. A number the tool did not report is unknown, never zero.`;
384
+
385
+ export const GENRE_LANGUAGES = Object.freeze(['js', 'python']);
386
+
387
+ /**
388
+ * THE GENRE, as data. The suppression batteries are the hand-written closes'
389
+ * own `SUPPRESSIONS` tables (`scripts/u-pulselog-close.mjs:35`,
390
+ * `scripts/u-spawner-close.mjs:34`) — operator-owned genre knowledge, minted by
391
+ * paying for live runs. `unknown` is deliberately NOT a JS suppression and not
392
+ * a Python one: it forces narrowing at the use site, which is real typing work.
393
+ *
394
+ * `env` is the addendum-6 residue expressed as data. Python's `MYPYPATH` is
395
+ * load-bearing and was found by probe, never by reading: the aurora patient sets
396
+ * `explicit_package_bases`, so without it a sibling import falls through to an
397
+ * editable install pointing at a DIFFERENT checkout and a cross-module fix is
398
+ * graded against unedited source. It moves no seed number, which is why no
399
+ * seed-verdict read can ever catch its absence — the only place it can live is
400
+ * here, in genre data, injected by the flow.
401
+ */
402
+ export const TYPES_GENRE = Object.freeze({
403
+ name: 'TYPES',
404
+ template: TYPES_GENRE_TEMPLATE,
405
+ languages: Object.freeze({
406
+ js: Object.freeze({
407
+ suppressions: Object.freeze([
408
+ Object.freeze({ id: 'ts-ignore', regex: '@ts-ignore' }),
409
+ Object.freeze({ id: 'ts-expect-error', regex: '@ts-expect-error' }),
410
+ Object.freeze({ id: 'ts-nocheck', regex: '@ts-nocheck' }),
411
+ Object.freeze({ id: 'eslint-disable', regex: 'eslint-disable' }),
412
+ Object.freeze({ id: 'any', regex: '(?:[{<|(\\[:,]|\\bas)\\s*any\\b|\\bany\\[\\]' }),
413
+ Object.freeze({ id: 'any-star', regex: '@\\w+\\s*\\{\\s*[*?]\\s*\\}' }),
414
+ Object.freeze({ id: 'cast', regex: '@type\\s*\\{.*\\}\\s*\\*\\/\\s*\\(' }),
415
+ ]),
416
+ extensions: Object.freeze(['.js', '.mjs', '.cjs']),
417
+ /** no import-resolution hazard on this runner — an EMPTY list, declared,
418
+ * never an absent field that would read as "not looked into" (F59) */
419
+ env: Object.freeze([]),
420
+ instruments: Object.freeze([
421
+ Object.freeze({
422
+ id: 'tsc-error-line',
423
+ what: 'one type error, as the TypeScript checker prints it',
424
+ lineMatch: 'error TS\\d+',
425
+ capture: null,
426
+ // REAL, from the captured `npm run typecheck -- --strict` of the pulselog
427
+ // patient (2026-08-09): 67 error lines, every one in this shape.
428
+ example: 'src/backup.js(21,19): error TS7006: Parameter \'now\' implicitly has an \'any\' type.',
429
+ why: 'tsc prints a DIFFERENT shape on a terminal (`src/backup.js:21:19 - error TS7006:`) than through a '
430
+ + 'pipe, and a close only ever reads the piped one. Run msmbpjk6 composed the terminal shape: it matched '
431
+ + '0 of 67 real error lines while the tool exited 2, so the stage read a crashed instrument. This pattern '
432
+ + 'is anchored on the CODE, not on the path spelling, so it reads both shapes and cannot lose that flip.',
433
+ }),
434
+ // ── node --test, the SAME pipe-vs-terminal trap, MEASURED ──────────────
435
+ //
436
+ // PROVENANCE, two independent halves.
437
+ //
438
+ // (1) REAL CAPTURED OUTPUT. The mailproof job-#2 battery's own spines carry
439
+ // whole `npm test` → `node --test` captures inside their `close-precheck`
440
+ // gap: `bareloop-patients/mailproof-job2-bareloop/battery-P1-mrm7gk25.jsonl`
441
+ // (`# tests 317` / `# pass 312` / `# fail 5`, five `not ok` lines) and
442
+ // `battery-P2-mrm7gk25.jsonl` (`# pass 316` / `# fail 1`). Nothing there was
443
+ // written to match a pattern — it is what the runner printed down the close's
444
+ // pipe, months before this table existed.
445
+ //
446
+ // (2) A SHIPPED, LIVE-FIRED SPELLING. `jobs/pulselog-author-types.json`
447
+ // already grades `^# pass (\d+)$` and `^# fail (\d+)$` (stages `tests-kept`
448
+ // and `test-suite-zero-failures`), and run msoc6t8v graded green through it.
449
+ // The table is not minting a new ruler; it is HANDING OVER the one the tree
450
+ // already grades with, the way the tsc term does.
451
+ //
452
+ // WHY IT IS THE TSC TRAP AGAIN, measured on this machine (node v22.22.2,
453
+ // one test file, identical args, 2026-08-13): through a PIPE the runner
454
+ // prints TAP — `TAP version 13`, `# pass 1`, `not ok 2 - b`; on a real pty it
455
+ // prints the spec reporter — `ℹ pass 1`, no `#`, no TAP at all. A close only
456
+ // ever reads the piped half, and a pattern composed against the pretty half
457
+ // matches nothing while the suite runs fine. Exactly what cost run msmbpjk6
458
+ // its authoring pass on tsc, waiting behind a second tool.
459
+ Object.freeze({
460
+ id: 'node-test-total-count',
461
+ what: 'how many tests the runner EXECUTED, off the TAP summary',
462
+ lineMatch: '^# tests (\\d+)$',
463
+ capture: 1,
464
+ example: '# tests 317',
465
+ why: 'the EXECUTED count is the honest denominator: a passed-count floor is satisfiable by a suite that '
466
+ + 'stopped running, so a stage asking "is the suite still whole?" counts this, not passes. Anchored '
467
+ + 'both ends because the runner prefixes ordinary chatter with the same `# ` (`# Subtest: <name>`), and '
468
+ + 'an unanchored `# tests` would count test NAMES.',
469
+ }),
470
+ Object.freeze({
471
+ id: 'node-test-pass-count',
472
+ what: 'how many tests passed, off the TAP summary',
473
+ lineMatch: '^# pass (\\d+)$',
474
+ capture: 1,
475
+ example: '# pass 316',
476
+ why: 'the spelling `jobs/pulselog-author-types.json` already grades with, green through run msoc6t8v. '
477
+ + 'The runner prints this line on a green run too, so a zero here is a REPORTED zero.',
478
+ }),
479
+ Object.freeze({
480
+ id: 'node-test-fail-count',
481
+ what: 'how many tests failed, off the TAP summary',
482
+ lineMatch: '^# fail (\\d+)$',
483
+ capture: 1,
484
+ example: '# fail 1',
485
+ why: 'this runner prints every counter on every run — a fully green suite still prints `# fail 0` '
486
+ + '(measured), so reading the figure cannot confuse "no failures" with "never reported". Its pytest '
487
+ + 'counterpart has no such guarantee, which is why python has no fail-COUNT term.',
488
+ }),
489
+ Object.freeze({
490
+ id: 'node-test-failed-line',
491
+ what: 'one failing test, as the TAP reporter names it',
492
+ lineMatch: '^not ok \\d+ ',
493
+ capture: null,
494
+ example: 'not ok 7 - edit-renotify: a non-participant edit, and edits on a pending event, ping no one',
495
+ why: 'one line per failing test, so it TALLIES and no match is a genuine counted zero. The trailing '
496
+ + 'space and the `^` both carry weight: every passing test prints `ok 7 - …`, and without the anchor '
497
+ + 'each of those would count as a failure.',
498
+ }),
499
+ ]),
500
+ }),
501
+ python: Object.freeze({
502
+ suppressions: Object.freeze([
503
+ Object.freeze({ id: 'ignore', regex: '#\\s*type:\\s*ignore' }),
504
+ Object.freeze({ id: 'any', regex: '\\bAny\\b' }),
505
+ Object.freeze({ id: 'cast', regex: '\\bcast\\s*\\(' }),
506
+ Object.freeze({ id: 'noqa', regex: '#\\s*noqa' }),
507
+ Object.freeze({ id: 'mypy-disable', regex: '#\\s*mypy:\\s*disable' }),
508
+ ]),
509
+ extensions: Object.freeze(['.py']),
510
+ env: Object.freeze([
511
+ Object.freeze({
512
+ name: 'MYPYPATH',
513
+ from: 'sourcePrefixes',
514
+ join: ':',
515
+ why: 'mypy must name the PATIENT\'s modules: without it a sibling import resolves through an editable '
516
+ + 'install to a different checkout, and a cross-module fix is graded against unedited source (Result 5, '
517
+ + 'found by probe). It moves no seed number, so no seed-verdict read can see its absence.',
518
+ }),
519
+ ]),
520
+ instruments: Object.freeze([
521
+ Object.freeze({
522
+ id: 'mypy-error-line',
523
+ what: 'one type error, as mypy prints it',
524
+ lineMatch: ' error: ',
525
+ capture: null,
526
+ // REAL, from a live aurora run's own spine
527
+ // (bareloop-patients/aurora-u-bareloop/u-ms2c0ls7.jsonl).
528
+ example: 'packages/spawner/src/aurora_spawner/timeout_policy.py:89: error: Statement is unreachable [unreachable]',
529
+ why: 'the operator\'s own hand-written close reads mypy this way (scripts/u-spawner-close.mjs:133), minted '
530
+ + 'by paid live runs. It is anchored on the SEVERITY word, not on the path spelling, so a relative or '
531
+ + 'absolute path, a package prefix or a config-driven root all read the same.',
532
+ }),
533
+ // ── pytest, from the aurora battery's own captured runs ────────────────
534
+ //
535
+ // PROVENANCE: six `close-precheck` gaps in
536
+ // `bareloop-patients/aurora-soar-bareloop/battery-A{1..4}-*.jsonl` carry the
537
+ // whole captured pytest run of the aurora patient (pytest 9.1.1, python
538
+ // 3.14.6, the patient's own `pytest.ini` addopts, which include `-ra`) —
539
+ // 2,690-odd tests, the `short test summary info` section and the final counts
540
+ // line. Real, uncrafted, paid for.
541
+ //
542
+ // WHAT IS NOT ANCHORED, and why. Every archived counts line arrives padded
543
+ // with `=` on both sides, and the padding WIDTH is terminal-derived: the
544
+ // archived long line gets exactly one `=` per side, a short local run gets
545
+ // twenty-five (measured, pytest 9.0.2, 2026-08-13). Under `-q` the padding is
546
+ // absent entirely. So the term anchors on the WORD and its number, never on
547
+ // the decoration — the same discipline as anchoring tsc on the code rather
548
+ // than the path.
549
+ Object.freeze({
550
+ id: 'pytest-pass-count',
551
+ what: 'how many tests passed, off pytest\'s final counts line',
552
+ lineMatch: '(\\d+) passed',
553
+ capture: 1,
554
+ example: '= 1 failed, 2690 passed, 3 skipped, 18 deselected, 1775 warnings in 326.12s (0:05:26) =',
555
+ why: 'the ONE segment of this line pytest prints whether the run was green or red, so it is the only '
556
+ + 'count on it that can be read as a figure without risking "never reported". The other segments '
557
+ + '(failed, skipped, deselected) are omitted when their count is zero — a green run prints just '
558
+ + '`1 passed in 0.04s` (measured) — so a term reading THOSE would go silent exactly when the news is '
559
+ + 'good, and a silent figure term is a broken instrument, not a zero.',
560
+ }),
561
+ Object.freeze({
562
+ id: 'pytest-failed-line',
563
+ what: 'one failing test, as pytest\'s short summary names it',
564
+ lineMatch: '^FAILED ',
565
+ capture: null,
566
+ example: 'FAILED packages/soar/tests/test_agent_registry_deprecation.py::TestAgentRegistryDeprecation::test_registry_and_discovery_equivalent_results',
567
+ why: 'this is how you count pytest FAILURES: exactly one line per failing test (measured under both `-ra` '
568
+ + 'and `-q`), so it TALLIES and no match at all is a legitimate counted zero rather than an unreported '
569
+ + 'number. It needs pytest\'s short summary section, which the patient\'s own config must not suppress.',
570
+ }),
571
+ ]),
572
+ }),
573
+ }),
574
+ });
575
+
576
+ /** @param {string} lang */
577
+ function language(lang) {
578
+ const l = TYPES_GENRE.languages[/** @type {'js'|'python'} */ (lang)];
579
+ // An unknown language THROWS rather than returning an empty battery: a genre
580
+ // we have not admitted must not read as "this genre needs no guards" (F59's
581
+ // shape — `{}` meaning "the scout did not complete", never "no facts needed").
582
+ if (!l) throw new Error(`no TYPES genre data for language "${lang}" — one of ${GENRE_LANGUAGES.join(', ')}`);
583
+ return l;
584
+ }
585
+
586
+ /**
587
+ * THE GUARD BATTERY, KEYED BY VERDICT CLASS (hamr's ruling, PRD v1.57 §2).
588
+ *
589
+ * D5's battery was genre-keyed data. Under class-keyed interviews it has no
590
+ * genre to hang from, and the ruling gives it the same home the interview took:
591
+ * **the battery attaches to the verdict class the user picked** — not to a
592
+ * problem-genre label, and not per catalogue KIND.
593
+ *
594
+ * WHY THE CLASS. What a battery is FOR is the class of dishonesty the class of
595
+ * VERDICT admits. A green job is a job whose *done* is claimed to be
596
+ * machine-checkable, so it carries the green battery whatever problem it came
597
+ * from — that is the anti-suppression obligation the F87 genre earned, and it
598
+ * must not travel with a label the interview no longer asks for.
599
+ *
600
+ * ATTACHMENT POINT vs CONTENTS, and the split is the whole implementation:
601
+ * - the battery's STRUCTURE and its un-removability key off the CLASS. That
602
+ * is this table: which guards exist, what they assert, which slot is the
603
+ * model's (`fill`), and which params are ours.
604
+ * - the battery's CONTENTS fill in at COMPOSITION (`compose`), because a
605
+ * suppression pattern, a file extension and a checker's escape hatch belong
606
+ * to the TOOL the declaration names, and nothing before composition knows
607
+ * that tool. `classGuards` resolves them from the language data below.
608
+ *
609
+ * A LOCKED class carries `guards: null`, not `[]`. Absent is never empty (F59):
610
+ * `[]` would read as "this class needs no guards", which is exactly the sentence
611
+ * D5 exists to make unsayable. Nothing ever reaches it — admission refuses a
612
+ * locked class before its battery is asked for — and `classGuards` throws rather
613
+ * than hand back nothing if anything ever does.
614
+ * @type {Record<string, {locked: boolean, guards: readonly any[]|null}>}
615
+ */
616
+ export const CLASS_BATTERIES = Object.freeze({
617
+ green: Object.freeze({
618
+ locked: false,
619
+ guards: Object.freeze([
620
+ Object.freeze({
621
+ name: 'changed-from-seed',
622
+ kind: 'files-changed',
623
+ params: Object.freeze({ requireNonEmpty: true }),
624
+ compose: Object.freeze([]),
625
+ fill: Object.freeze(['allowPrefixes']),
626
+ }),
627
+ Object.freeze({
628
+ name: 'no-suppressions',
629
+ kind: 'pattern-absent-in-diff',
630
+ // NO scope: the scan covers every changed file of these extensions. A
631
+ // narrowing here is the round-3 arm A defect and is a red, not a taste.
632
+ params: Object.freeze({}),
633
+ compose: Object.freeze(['patterns', 'extensions']),
634
+ fill: Object.freeze([]),
635
+ }),
636
+ ]),
637
+ }),
638
+ 'soft-green': Object.freeze({ locked: true, guards: null }),
639
+ hitl: Object.freeze({ locked: true, guards: null }),
640
+ });
641
+
642
+ /**
643
+ * How each COMPOSED param resolves from the tool the declaration names. One
644
+ * entry per composable param name, so a battery that grows a slot fails loudly
645
+ * here rather than shipping an unresolved one.
646
+ * @type {Record<string, (l: any) => any>}
647
+ */
648
+ const COMPOSE_FROM_TOOL = Object.freeze({
649
+ patterns: (/** @type {any} */ l) => l.suppressions.map((/** @type {any} */ p) => ({ ...p })),
650
+ extensions: (/** @type {any} */ l) => [...l.extensions],
651
+ });
652
+
653
+ /**
654
+ * The picked class's mandatory guards, FULLY ENUMERATED (D13 forward-compat
655
+ * point 3: an omittable-with-a-default field is the omitted-`tools` shape, where
656
+ * widening changes what runs without changing what was signed — so the guards
657
+ * are stored spelled out, and the hash is taken over the resolved form).
658
+ *
659
+ * `fill` names the ONLY slot the model supplies. `changed-from-seed`'s
660
+ * allowPrefixes is the job's own target scope and cannot be ours; everything
661
+ * else — including `no-suppressions`' absent scope — is.
662
+ *
663
+ * AN EMPTY BATTERY IS IMPOSSIBLE for a known class and a known language, and
664
+ * that is enforced rather than asserted: an unknown class, a locked class, an
665
+ * unknown language, a battery that resolved to nothing, and a composed param
666
+ * that resolved to nothing all THROW. F59's shape at the load-bearing decision
667
+ * of the design — a suppression scan with no patterns reads clean exactly like
668
+ * one that scanned correctly, and it lands in a SIGNED artefact.
669
+ *
670
+ * Returns a fresh deep copy each call: a frozen constant handed to a caller that
671
+ * edits it is one shared battery away from a silently weakened guard.
672
+ * @param {{verdictType: string, lang: string}} o
673
+ * @returns {{name: string, kind: string, params: Record<string, any>, compose: string[], fill: string[]}[]}
674
+ */
675
+ export function classGuards({ verdictType, lang }) {
676
+ const battery = Object.hasOwn(CLASS_BATTERIES, String(verdictType)) ? CLASS_BATTERIES[String(verdictType)] : null;
677
+ if (!battery) {
678
+ throw new Error(`no guard battery for verdict class "${verdictType}" — one of ${VERDICT_CLASSES.join(', ')}`);
679
+ }
680
+ if (battery.locked || battery.guards === null) {
681
+ throw new Error(`the "${verdictType}" guard battery is LOCKED — that class is declared-but-locked in v1 and `
682
+ + 'admission refuses it before any battery is built; a locked class must never resolve to an empty one');
683
+ }
684
+ const l = language(lang);
685
+ const guards = battery.guards.map((g) => {
686
+ /** @type {Record<string, any>} */
687
+ const params = structuredClone(g.params);
688
+ for (const p of g.compose) {
689
+ const resolve = COMPOSE_FROM_TOOL[p];
690
+ if (!resolve) throw new Error(`the "${g.name}" guard composes "${p}", which nothing knows how to resolve from a tool`);
691
+ const value = resolve(l);
692
+ if (!Array.isArray(value) || value.length === 0) {
693
+ throw new Error(`the "${g.name}" guard's "${p}" resolved EMPTY for language "${lang}" — a guard that checks `
694
+ + 'nothing reads clean exactly like one that checked correctly, and this one is about to be signed');
695
+ }
696
+ params[p] = value;
697
+ }
698
+ return { name: g.name, kind: g.kind, params, compose: [...g.compose], fill: [...g.fill] };
699
+ });
700
+ if (guards.length === 0) {
701
+ throw new Error(`the "${verdictType}" battery resolved to NO guards — D5 is the load-bearing decision of this `
702
+ + 'design and an empty battery is never a legal answer');
703
+ }
704
+ return guards;
705
+ }
706
+
707
+ /**
708
+ * The genre's environment for this patient — ours to inject at execution (M3),
709
+ * never model-authored. An entry with no value produces NO VARIABLE: an empty
710
+ * `MYPYPATH` is not the same instruction as an unset one, and shipping `''`
711
+ * would silently change how mypy resolves.
712
+ * @param {string} lang
713
+ * @param {{sourcePrefixes?: string[]}} [o]
714
+ * @returns {Record<string, string>}
715
+ */
716
+ export function genreEnv(lang, { sourcePrefixes = [] } = {}) {
717
+ const l = language(lang);
718
+ /** @type {Record<string, string>} */
719
+ const env = {};
720
+ for (const spec of l.env) {
721
+ const parts = (spec.from === 'sourcePrefixes' ? sourcePrefixes : []).filter(isNonEmptyString);
722
+ if (parts.length) env[spec.name] = parts.join(spec.join);
723
+ }
724
+ return env;
725
+ }
726
+
727
+ /** The names the genre OWNS — the validator refuses a declaration that authors
728
+ * one of them, because ownership is only real if it is mechanical.
729
+ * @param {string} lang @returns {string[]} */
730
+ export function genreOwnedEnvNames(lang) {
731
+ return language(lang).env.map((/** @type {any} */ e) => e.name);
732
+ }
733
+
734
+ /**
735
+ * HOW THE GENRE'S OWN TOOLS PRINT — genre property, like the suppression battery
736
+ * and like `MYPYPATH`, and for the same reason: it is a FACT ABOUT AN INSTRUMENT
737
+ * WE ALREADY OWN, not a composition choice. Seven hand-written closes read tsc
738
+ * with the identical `/error TS\d+/` (`scripts/u-pulselog-close.mjs:122`,
739
+ * `u-bareguard-close.mjs:123`, `u-bareagent-close.mjs:123`,
740
+ * `u-baremobile-close.mjs:122`, `u-litectx-close.mjs:140`, `types-close.mjs:190`,
741
+ * `types-check.mjs:60`) and one reads mypy with `' error: '`
742
+ * (`u-spawner-close.mjs:133`) — the same provenance the SUPPRESSIONS table has:
743
+ * operator knowledge minted by paying for live runs.
744
+ *
745
+ * WHY IT BECAME GENRE DATA (run msmbpjk6, 2026-08-09, $0.43). Left to the model,
746
+ * the parser for a known tool is a DRAFT-TIME LOTTERY on a fact nobody needed to
747
+ * guess: that run composed tsc's TTY-only pretty shape
748
+ * (`^\S+\.js:\d+:\d+ - error TS\d+:`), which matched 0 of the 67 real error lines
749
+ * the piped run actually printed, while the tool exited 2. The gates held — the
750
+ * stage read as a crashed instrument and signing was refused, correctly — but the
751
+ * refusal cost a whole authoring run to learn something the tree already knew. An
752
+ * earlier run (mslwbkz7) happened to roll the right shape. A coin-flip on an
753
+ * owned fact is not a capability question.
754
+ *
755
+ * WHAT THIS IS NOT: it does not close the parser. A stage counting something we
756
+ * have NOT measured still writes its own pattern, and that remains a real gap —
757
+ * named, not smoothed. This table is where a measured instrument fact lands, one
758
+ * at a time, with its provenance.
759
+ *
760
+ * THE TEST-COUNT FACTS (2026-08-13) landed under exactly that rule, and closed
761
+ * two of the three gaps the paragraph above used to name by hand: the executed
762
+ * count and the failure line, for both runners, are now measured facts rather
763
+ * than draft-time lotteries. Provenance rides on each entry.
764
+ *
765
+ * WHAT STAYED OUT, deliberately, because no evidence covers it:
766
+ * - a pytest FAIL-COUNT figure. A green pytest run omits the segment entirely
767
+ * (`1 passed in 0.04s`), so a figure term over it reports "never reported" on
768
+ * precisely the runs that went well. Failures are counted with the `^FAILED `
769
+ * tally instead, where no match IS zero.
770
+ * - a pytest EXECUTED count. `collected N items` is printed under `-ra` and NOT
771
+ * under `-q` (measured both ways), so no single spelling survives the modes a
772
+ * patient may configure; a stage needing it still composes its own and says so.
773
+ *
774
+ * Returns a fresh copy per call, for the reason `classGuards` does: a frozen
775
+ * constant handed to a caller that edits it is one shared table away from a
776
+ * silently changed ruler.
777
+ * @param {string} lang
778
+ * @returns {{id: string, what: string, lineMatch: string, capture: number|null, example: string, why: string}[]}
779
+ */
780
+ export function genreInstruments(lang) {
781
+ const instruments = language(lang).instruments ?? [];
782
+ // F59's shape at a table that feeds a RULER: an empty list would read as "this
783
+ // language's tools need no stated format", which is exactly the sentence that
784
+ // put the pretty-format regex into a signed-close candidate.
785
+ if (!instruments.length) {
786
+ throw new Error(`no known-instrument formats for language "${lang}" — a language the genre admits states how its `
787
+ + 'own checker prints, or the model is back to guessing a fact we already own');
788
+ }
789
+ return instruments.map((/** @type {any} */ i) => ({ ...i }));
790
+ }
791
+
792
+ /**
793
+ * GROUNDING for a RECORDED genre environment — the provenance half of the
794
+ * owned-env rule, and the reason the by-value comparison is worth anything.
795
+ *
796
+ * The value check proves the envelope's `genreEnv` and the stage's `params.env`
797
+ * AGREE. Both copies live in the same hand-editable spec, so agreement is
798
+ * something a forger gets for free: a spec carrying
799
+ * `MYPYPATH=/tmp/attacker-stubs` in both places is perfectly self-consistent and
800
+ * would point the checker at a tree nobody signed. Agreement is not provenance.
801
+ *
802
+ * What a forger does NOT own is the repository at the seed. Every value the
803
+ * arbiter can build is `genreEnv`'s join of `sourcePrefixes`, and those prefixes
804
+ * were already filtered against the seed listing before the join — so each
805
+ * ELEMENT of a genuine value is a path the listing SELECTS, exactly like hamr's
806
+ * listing rule for a declared path. Grounding therefore accepts precisely what
807
+ * `applyGenreEnv` produces and refuses everything else, without needing a second
808
+ * spelling of what "ours" means.
809
+ *
810
+ * Element-wise, never whole-value: a joined list is as strong as its weakest
811
+ * element, and one real prefix must not launder the rest. A root spelling is
812
+ * ungrounded here rather than waved through the way `checkPaths` waves it —
813
+ * `genreEnv` filters those out before joining, so the arbiter can never produce
814
+ * one, and a validator that admits what its own producer cannot emit is a gap.
815
+ *
816
+ * Callers that hold a listing only; the deferred job-spec gate cannot run this
817
+ * and does not pretend to (see `validateCloseDecl`).
818
+ * @param {string} lang
819
+ * @param {Record<string, string>} recorded what the envelope claims the arbiter injected
820
+ * @param {string[]} listing repo-relative paths at the seed
821
+ * @returns {{name: string, value: string, element: string, resolved: string}[]} one row per ungrounded element
822
+ */
823
+ export function ungroundedGenreEnv(lang, recorded, listing) {
824
+ const idx = indexListing((Array.isArray(listing) ? listing : []).filter(isNonEmptyString));
825
+ /** @type {{name: string, value: string, element: string, resolved: string}[]} */
826
+ const out = [];
827
+ // driven by the GENRE's own specs, not by the recorded keys: the join is genre
828
+ // knowledge, and a key the genre does not own is the envelope's red, not this
829
+ // function's business
830
+ for (const spec of language(lang).env) {
831
+ const value = recorded?.[spec.name];
832
+ if (!isNonEmptyString(value)) continue; // shape is the envelope's own check
833
+ for (const element of String(value).split(spec.join)) {
834
+ const resolved = normPrefix(element);
835
+ if (!isRoot(resolved) && (idx.files.has(resolved) || idx.dirs.has(resolved))) continue;
836
+ out.push({ name: spec.name, value, element, resolved });
837
+ }
838
+ }
839
+ return out;
840
+ }
841
+
842
+ // ── 3. THE DECLARATION VALIDATOR ─────────────────────────────────────────────
843
+
844
+ /** one prefix spelling, the SHIPPED one — `globToPrefix`'s collapse order is
845
+ * fence territory (F9) and is never re-spelled here. `''`, `'.'` and `'/'` all
846
+ * mean the repository root. */
847
+ const normPrefix = (/** @type {string} */ p) => globToPrefix(String(p)).replace(/^\.\//, '');
848
+ const isRoot = (/** @type {string} */ p) => p === '' || p === '.' || p === '/';
849
+
850
+ /**
851
+ * The seed listing, indexed once: the files that exist, and every directory
852
+ * that contains one. A path SELECTS when it is one of them.
853
+ * @param {string[]} listing
854
+ */
855
+ function indexListing(listing) {
856
+ const files = new Set(listing.map((f) => normPrefix(f)).filter((f) => f !== ''));
857
+ /** @type {Set<string>} */
858
+ const dirs = new Set();
859
+ for (const f of files) {
860
+ const segs = f.split('/');
861
+ for (let i = 1; i < segs.length; i++) dirs.add(segs.slice(0, i).join('/'));
862
+ }
863
+ return { files, dirs };
864
+ }
865
+
866
+ /**
867
+ * Is this a SCOPED job? Mechanically, from the GENRE'S OWN containment guard
868
+ * against the REAL listing — never from the operator's reading of the interview,
869
+ * and never from whichever `files-changed` stage happens to come first.
870
+ *
871
+ * WHICH STAGE IS READ IS LOAD-BEARING. The candidate set is the genre's guards,
872
+ * matched BY NAME (the guard battery's own `changed-from-seed`), because that is
873
+ * the one stage `checkGuards` pins byte-for-byte with `allowPrefixes` as its only
874
+ * model-filled slot — so its prefixes ARE the job's declared target scope. Read
875
+ * first-of-kind instead and a declaration carrying a legally-shaped decoy
876
+ * `files-changed` stage (`allowPrefixes: ['.']`) DECLARED EARLIER reads as
877
+ * whole-tree, and the F84 one-population law switches itself off silently: the
878
+ * count stages stop having to say which population they count. Measured, not
879
+ * imagined — with the decoy the whole declaration validated with zero reds.
880
+ *
881
+ * The guard NAMES come from the caller's own `guards` array rather than a literal
882
+ * here: one spelling, and a genre that renames or adds a containment guard is
883
+ * covered the day it lands instead of the day someone remembers this function.
884
+ * No guards in hand means no derivation — `guards-absent` is already a red, and
885
+ * guessing the job's scope from an unpinned stage is exactly what this fixes.
886
+ *
887
+ * A whole-tree job is genuinely unscoped — there is nothing outside — and the
888
+ * law must not red it (template rule 3 says the outside ceiling is omitted
889
+ * exactly there).
890
+ * @param {any} declaration @param {{files: Set<string>, dirs: Set<string>}} idx
891
+ * @param {any[]|null} guards the picked class's injected guards (`classGuards`)
892
+ */
893
+ function scopeOfJob(declaration, idx, guards) {
894
+ const stages = Array.isArray(declaration?.stages) ? declaration.stages : [];
895
+ const scopeGuards = (Array.isArray(guards) ? guards : [])
896
+ .filter((g) => isObj(g) && g.kind === 'files-changed' && isNonEmptyString(g.name));
897
+ for (const g of scopeGuards) {
898
+ const s = stages.find((/** @type {any} */ x) => isObj(x) && x.name === g.name && x.kind === 'files-changed');
899
+ if (!s) continue;
900
+ const pre = s?.params?.allowPrefixes;
901
+ if (!Array.isArray(pre) || pre.length === 0 || !pre.every(isNonEmptyString)) continue;
902
+ const norm = pre.map(normPrefix);
903
+ if (norm.some(isRoot)) continue; // this guard covers the whole tree
904
+ const uncovered = [...idx.files].some((f) => !norm.some((p) => f === p || f.startsWith(`${p}/`)));
905
+ if (uncovered) return { scoped: true, via: `${s.name}.allowPrefixes` };
906
+ }
907
+ return { scoped: false, via: null };
908
+ }
909
+
910
+ /**
911
+ * Kinds a declaration may carry AT MOST ONCE, as data beside the catalogue.
912
+ *
913
+ * `files-changed` is the whole list and the reason is the catalogue's own
914
+ * semantics, not taste. The kind asserts "every changed file lies inside
915
+ * allowPrefixes"; two of them assert it twice, and stages are ANDed, so the
916
+ * effective constraint is the INTERSECTION of the two prefix sets — which is
917
+ * itself a prefix set, and is therefore already expressible as one stage's
918
+ * `allowPrefixes`. A second containment stage adds no reach whatsoever, so
919
+ * refusing it costs the author nothing.
920
+ *
921
+ * What it does cost to admit is measurable: a second `files-changed` stage is a
922
+ * second answer to "what is this job's scope", which is the ambiguity
923
+ * `scopeOfJob` had to be pinned to the guard to survive. This is the same shape
924
+ * as `count-not-worse`'s `duplicate-population` rule — one population is one
925
+ * stage — applied to the one population that decides whether the law fires at
926
+ * all.
927
+ */
928
+ const AT_MOST_ONCE_KINDS = Object.freeze(['files-changed']);
929
+
930
+ /** @param {any} v */
931
+ const strArray = (v) => Array.isArray(v) && v.length > 0 && v.every(isNonEmptyString);
932
+
933
+ /** read a dotted param path off a params object, or undefined @param {any} p @param {string} dotted */
934
+ function readPath(p, dotted) {
935
+ let node = p;
936
+ for (const seg of dotted.split('.')) {
937
+ if (!isObj(node)) return undefined;
938
+ node = node[seg];
939
+ }
940
+ return node;
941
+ }
942
+
943
+ /**
944
+ * Validate an authored close DECLARATION. Never throws on model output — every
945
+ * failure is a named red, in the shipped `{ok, reds, <parsed>}` shape, and the
946
+ * parsed value is the RESOLVED declaration (every short-form parser expanded),
947
+ * because that is the form the executor runs and the signature covers.
948
+ *
949
+ * `listing`, `guards` and `envOwned` are REQUIRED, and their absence is a red
950
+ * rather than a skipped check — all three guard the SAME failure: a validator
951
+ * that silently stops checking when handed nothing to check against reports a
952
+ * clean declaration it never examined. v1 only admits a job with a runnable
953
+ * patient and a git seed (D13), so the listing always exists, and D5's guards
954
+ * exist by construction. `envOwned` is separated into absent-vs-empty for
955
+ * F59's reason exactly: `[]` is a genre that owns no variables (JS), and
956
+ * `undefined` is a caller that never asked — the two must not read alike.
957
+ *
958
+ * The CATALOGUE is ours, not model input: a malformed one is a bareloop bug and
959
+ * is allowed to throw, because failing loudly beats a validator that quietly
960
+ * stops enforcing a rule it was configured out of.
961
+ *
962
+ * `deferListing: true` is the ONE way to run without a listing, and it must be
963
+ * spelled literally. It exists for exactly one caller — the job-spec validator,
964
+ * which judges a signed `closeDecl` with no repository in hand — and it does NOT
965
+ * make the listing optional: it moves that half of the gate to the runner, which
966
+ * re-validates GROUNDED against the real seed before any stage runs. Two checks
967
+ * ride on the listing and both are named here rather than discovered later: the
968
+ * path rule (a path SELECTS or it does not exist), and the SCOPED-job derivation
969
+ * that arms the F84 one-population law. With the listing deferred, neither
970
+ * fires, and `grounded: false` on the result is how a caller knows.
971
+ *
972
+ * `verdictType` is REQUIRED for the same reason: it is the PROMISE the ceiling
973
+ * rule checks the composition against, and a validator with no pick in hand
974
+ * cannot check it. Absent or unknown is `class-absent`, naming the closed set.
975
+ *
976
+ * @param {any} declaration the parsed model output
977
+ * @param {{catalogue?: Record<string, KindSpec>, listing?: string[]|null,
978
+ * guards?: {name: string, kind: string, params: Record<string, any>, fill: string[]}[]|null,
979
+ * envOwned?: string[]|null, envInjected?: Record<string, string>|null, deferListing?: boolean,
980
+ * verdictType?: string|null}} [opts]
981
+ * `listing` — repo-relative paths at the seed (`git ls-tree -r --name-only`).
982
+ * `guards` — the picked class's injected guards (`classGuards`).
983
+ * `verdictType` — the class the USER picked (`VERDICT_CLASSES`).
984
+ * `envOwned` — env names the genre injects (`genreOwnedEnvNames`), `[]` when it owns none.
985
+ * `envInjected` — the env the ARBITER itself injected (`genreEnv`'s output), for a
986
+ * POST-injection re-validation. Omitted is the PRE-injection form: every owned name
987
+ * is the model's and reds. Supplied, an owned name is accepted only when its value is
988
+ * EXACTLY the injected one — a wrong value is the model's guess or corruption.
989
+ * `deferListing` — literally `true` to run the tree-independent half only.
990
+ * @returns {{ok: boolean, reds: Red[], declaration: any, grounded: boolean,
991
+ * scoped: {scoped: boolean, via: string|null},
992
+ * ceiling: {class: string, kind: string, stage: string|null, locked: boolean}|null}}
993
+ */
994
+ export function validateDeclaration(declaration, opts = {}) {
995
+ const {
996
+ catalogue = KIND_CATALOGUE, listing = null, guards = null, envOwned = null, envInjected = null,
997
+ verdictType = null,
998
+ } = opts;
999
+ const deferListing = opts.deferListing === true;
1000
+ /** @type {Red[]} */
1001
+ const reds = [];
1002
+ /** @type {(code: string, path: string, detail: string, extra?: object) => void} */
1003
+ const red = (code, path, detail, extra = {}) => { reds.push({ code, path, detail, ...extra }); };
1004
+
1005
+ const lockedKinds = Object.keys(catalogue).filter((k) => catalogue[k].locked);
1006
+ const kindNames = Object.keys(catalogue).join(' | ');
1007
+
1008
+ const haveListing = Array.isArray(listing) && listing.length > 0 && listing.every(isNonEmptyString);
1009
+ if (!haveListing && !deferListing) {
1010
+ red('listing-absent', 'listing', 'a non-empty seed file listing (git ls-tree -r --name-only <seed>) — '
1011
+ + 'without it nothing can tell a real path from an invented one, and a validator that skips that check '
1012
+ + 'reports a declaration it never examined');
1013
+ }
1014
+ if (haveListing && deferListing) {
1015
+ red('listing-conflict', 'listing', 'deferListing was declared AND a listing was supplied — a caller that both '
1016
+ + 'defers the tree-grounded half and hands over a tree does not know which gate it is running');
1017
+ }
1018
+ const idx = indexListing(haveListing ? /** @type {string[]} */ (listing) : []);
1019
+
1020
+ const haveGuards = Array.isArray(guards) && guards.length > 0;
1021
+ if (!haveGuards) {
1022
+ red('guards-absent', 'guards', 'the picked class\'s mandatory guards (classGuards) — D5 is the load-bearing '
1023
+ + 'decision of this design and it cannot be validated away by handing the validator nothing to check against');
1024
+ }
1025
+
1026
+ // THE PICK, and it is required for the same reason the guards are: it is the
1027
+ // promise the ceiling rule measures the composition against, and a validator
1028
+ // handed no pick reports a promise it never checked. A closed set, handed over
1029
+ // enumerated — never a prose rule about what a legal class would look like.
1030
+ const picked = VERDICT_CLASSES.includes(String(verdictType)) ? String(verdictType) : null;
1031
+ if (picked === null) {
1032
+ red('class-absent', 'verdictType', `the verdict class the user picked — one of ${VERDICT_CLASSES.join(' | ')}. `
1033
+ + 'It is what a composition promises to stay at or below, and nothing derives it from the declaration');
1034
+ }
1035
+
1036
+ // absent is not empty: `[]` is a genre that owns no environment (JS), and a
1037
+ // caller that never asked is a caller whose declarations are unchecked on the
1038
+ // axis round 2's arm B failed (F59's distinction, in the shape it bites here)
1039
+ const owned = Array.isArray(envOwned) ? envOwned : null;
1040
+ if (owned === null) {
1041
+ red('env-ownership-absent', 'envOwned', 'the env names this genre injects (genreOwnedEnvNames) — pass [] for a '
1042
+ + 'genre that owns none; omitting it leaves a model-authored MYPYPATH-class variable unexamined');
1043
+ }
1044
+ // The arbiter's OWN injection, when this is a POST-injection re-validation.
1045
+ // ABSENT (the default) is the PRE-injection form the authoring loop validates,
1046
+ // where every owned name is the model's and reds — so the loop's gate keeps
1047
+ // exactly the behaviour it had, and only a caller that can state what the
1048
+ // arbiter injected gets to have it accepted.
1049
+ const injected = isObj(envInjected) ? /** @type {Record<string, string>} */ (envInjected) : {};
1050
+
1051
+ if (!isObj(declaration)) {
1052
+ red('invalid-value', '', 'the declaration is an object carrying an ordered stages array');
1053
+ return { ok: false, reds, declaration: null, grounded: haveListing, scoped: { scoped: false, via: null }, ceiling: null };
1054
+ }
1055
+ // NOTES, checked HERE rather than only at the signing gate. The field is the
1056
+ // model's own ("anything you could not express"), it travels verbatim into the
1057
+ // signed `closeDecl`, and `validateCloseDecl` refuses an empty one — so a rule
1058
+ // that lives only there is a rule the authoring loop cannot feed back: the run
1059
+ // pays for a close, accepts it, and dies at signing on a defect the model was
1060
+ // never shown. One spelling of the rule, at the gate that can still revise it.
1061
+ if (declaration.notes !== undefined
1062
+ && !(Array.isArray(declaration.notes) && declaration.notes.every(isNonEmptyString))) {
1063
+ red('invalid-value', 'notes', 'an array of non-empty strings — what the author could not express, kept with '
1064
+ + 'the artefact it is about');
1065
+ }
1066
+
1067
+ const stages = declaration.stages;
1068
+ if (!Array.isArray(stages) || stages.length === 0) {
1069
+ red('missing-field', 'stages', 'a non-empty ORDERED array of stages — they run in the order you declare them');
1070
+ return { ok: false, reds, declaration: null, grounded: haveListing, scoped: { scoped: false, via: null }, ceiling: null };
1071
+ }
1072
+ if (stages.length > MAX_STAGES) {
1073
+ red('invalid-value', 'stages', `${stages.length} stages exceeds the ceiling of ${MAX_STAGES}`);
1074
+ }
1075
+
1076
+ const scoped = scopeOfJob(declaration, idx, guards);
1077
+ // Computed over the WHOLE declaration and REPORTED whatever it says, so a
1078
+ // composition that sits BELOW the pick is visible rather than silent — the
1079
+ // other half of the ruling ("never a silent downgrade"). Only EXCEEDING it is
1080
+ // a red, and that red is raised per offending stage inside the loop.
1081
+ const ceiling = closeCeiling(declaration, catalogue);
1082
+ /** @type {Set<string>} */
1083
+ const seen = new Set();
1084
+ /** @type {Map<string, string>} population key → the stage that already owns it */
1085
+ const populations = new Map();
1086
+ /** @type {Map<string, string>} at-most-once kind → the stage that already owns it */
1087
+ const kindOwners = new Map();
1088
+
1089
+ stages.forEach((/** @type {any} */ s, i) => {
1090
+ const at = `stages[${i}]`;
1091
+ if (!isObj(s)) { red('invalid-value', at, 'a stage is an object {name, kind, params}'); return; }
1092
+
1093
+ if (!isNonEmptyString(s.name)) red('missing-field', `${at}.name`, 'a non-empty stage name');
1094
+ else if (!NAME_RE.test(s.name)) red('invalid-value', `${at}.name`, `"${s.name}" is not a lowercase-hyphenated slug`);
1095
+ else if (seen.has(s.name)) {
1096
+ red('duplicate-name', `${at}.name`, `stage name "${s.name}" is declared twice — two stages under one name are `
1097
+ + 'one trend series over two populations (F84)');
1098
+ } else seen.add(s.name);
1099
+ const label = isNonEmptyString(s.name) ? s.name : at;
1100
+
1101
+ if (!isNonEmptyString(s.kind)) { red('missing-field', `${at}.kind`, `a kind: ${kindNames}`); return; }
1102
+ if (lockedKinds.includes(s.kind)) {
1103
+ // A DISTINCT red carrying counted demand. `verb`/`lib` are the structured
1104
+ // fields the ledger keys admission on, never prose, and `lib` is stamped
1105
+ // HERE at the emit site (the typed-lib rule): a locked KIND is demand
1106
+ // against bareloop's own catalogue, and filing it against a bare-suite
1107
+ // package is the BA-2 misattribution that rule exists to prevent.
1108
+ red('locked-kind', `${at}.kind`, `"${s.kind}" is a named but LOCKED kind — declaring it is recorded demand, `
1109
+ + 'never an admission; it does not run in v1', { kind: s.kind, verb: s.kind, lib: 'bareloop', stage: label });
1110
+ return;
1111
+ }
1112
+ const spec = catalogue[s.kind];
1113
+ if (!spec) {
1114
+ red('unknown-kind', `${at}.kind`, `"${s.kind}" is not in the catalogue — kinds: ${kindNames}`, { kind: s.kind });
1115
+ return;
1116
+ }
1117
+ // THE CEILING (PRD v1.57 §1): composition may only use kinds AT OR BELOW the
1118
+ // picked class. A LOCKED kind never reaches here — it already carries its own
1119
+ // counted-demand red and returned — so a kind refused as unavailable is never
1120
+ // ALSO redded for its class: one problem, one red, in one vocabulary.
1121
+ if (picked !== null && CLASS_RANK[spec.verdictClass] > CLASS_RANK[picked]) {
1122
+ red('class-ceiling', `${at}.kind`, `stage "${label}" uses "${s.kind}", which can only render a `
1123
+ + `${spec.verdictClass} verdict, and this job is declared ${picked}. The class the user picked is a PROMISE: a `
1124
+ + 'composition may use kinds at or below it and never above it, because a judgment ruler running under a '
1125
+ + 'machine-checkable promise is a fake-hard verdict — refused here rather than upgraded silently',
1126
+ { kind: s.kind, stage: label, kindClass: spec.verdictClass, picked });
1127
+ }
1128
+ if (AT_MOST_ONCE_KINDS.includes(s.kind)) {
1129
+ const owner = kindOwners.get(s.kind);
1130
+ if (owner !== undefined) {
1131
+ red('duplicate-kind', `${at}.kind`, `stage "${label}" is a second ${s.kind} stage — "${owner}" already declares `
1132
+ + 'which files this job may change. Stages are ANDed, so two of them mean the intersection of two prefix sets, '
1133
+ + 'which is itself a prefix set and already says the same thing in one stage; what a second one does add is a '
1134
+ + 'second answer to what this job\'s scope IS', { kind: s.kind, stage: label, twin: owner });
1135
+ } else kindOwners.set(s.kind, label);
1136
+ }
1137
+
1138
+ const p = s.params;
1139
+ if (!isObj(p)) { red('missing-field', `${at}.params`, `an object carrying: ${spec.required.join(', ')}`); return; }
1140
+ for (const k of spec.required) {
1141
+ if (!Object.hasOwn(p, k) || p[k] === null || p[k] === undefined) {
1142
+ red('missing-field', `${at}.params.${k}`, `${s.kind} requires ${k} (${spec.shape})`);
1143
+ }
1144
+ }
1145
+ for (const k of Object.keys(p)) {
1146
+ if (!spec.required.includes(k) && !spec.optional.includes(k)) {
1147
+ red('invalid-value', `${at}.params.${k}`, `"${k}" is not a parameter of ${s.kind} — the catalogue is the `
1148
+ + 'only source of parameter names');
1149
+ }
1150
+ }
1151
+
1152
+ checkKind({ kind: s.kind, params: p, at, red, scoped, label, populations, envOwned: owned ?? [], envInjected: injected });
1153
+ checkEnvComplete({ params: p, at, red, kind: s.kind, catalogue, envInjected: injected });
1154
+ checkPaths({ spec, params: p, at, red, idx, haveListing });
1155
+ });
1156
+
1157
+ if (haveGuards) checkGuards({ declaration, guards: /** @type {any[]} */ (guards), red });
1158
+
1159
+ const ok = reds.length === 0;
1160
+ return { ok, reds, declaration: ok ? normalizeDeclaration(declaration) : null, grounded: haveListing, scoped, ceiling };
1161
+ }
1162
+
1163
+ /**
1164
+ * COMPLETENESS — the deletion half of the owned-env rule, and the half a
1165
+ * by-VALUE comparison structurally cannot cover.
1166
+ *
1167
+ * `genre-owned-env` catches a CHANGED variable: a value that is not the one the
1168
+ * arbiter builds. Nothing caught a DELETED one. Drop the key from a stage — or
1169
+ * drop `params.env` outright — and there is no value left to compare, so a
1170
+ * hand-edited spec validates clean and mypy resolves through an editable install
1171
+ * to a DIFFERENT checkout while the close reports a number. That is the Result-5
1172
+ * hazard exactly, arriving through the one door the value check leaves open, and
1173
+ * it is silent by construction: the variable moves no number the close can see.
1174
+ *
1175
+ * So an injection is a fact about EVERY stage the injector touches, not about
1176
+ * the stages that happen to still carry it. The set is read from the same
1177
+ * catalogue predicate `applyGenreEnv` injects by (`envCapableKind`), so the rule
1178
+ * can never demand a variable on a stage nothing would inject into, nor let one
1179
+ * off a stage that was injected.
1180
+ *
1181
+ * Runs only on a POST-injection re-validation: with nothing recorded there is
1182
+ * nothing to be complete about, and the authoring loop must not ask the model
1183
+ * for the variable it is forbidden to author.
1184
+ * @param {{params: any, at: string, red: (c: string, p: string, d: string, e?: object) => void,
1185
+ * kind: string, catalogue: Record<string, KindSpec>, envInjected: Record<string, string>}} o
1186
+ */
1187
+ function checkEnvComplete({ params: p, at, red, kind, catalogue, envInjected }) {
1188
+ const names = Object.keys(envInjected);
1189
+ if (names.length === 0 || !envCapableKind(kind, catalogue)) return;
1190
+ // a malformed `env` already has its own shape red; saying it twice in two
1191
+ // vocabularies tells the reader there are two problems
1192
+ if (Object.hasOwn(p, 'env') && !isObj(p.env)) return;
1193
+ for (const name of names) {
1194
+ if (isObj(p.env) && Object.hasOwn(p.env, name)) continue;
1195
+ red('genre-env-missing', `${at}.params.env.${name}`, `${name} is recorded as the genre's own injection and this `
1196
+ + 'stage spawns a process, so it must carry it — the arbiter injects into every env-capable stage, and a stage '
1197
+ + 'that comes back without it grades whatever the ambient environment resolves to, silently and with no number '
1198
+ + 'that moves', { name, expected: envInjected[name] });
1199
+ }
1200
+ }
1201
+
1202
+ /**
1203
+ * The per-kind parameter checks, plus the two halves of the one-population law.
1204
+ * @param {{kind: string, params: any, at: string, red: (c: string, p: string, d: string, e?: object) => void,
1205
+ * scoped: {scoped: boolean, via: string|null}, label: string, populations: Map<string, string>,
1206
+ * envOwned: string[], envInjected: Record<string, string>}} o
1207
+ */
1208
+ function checkKind({ kind, params: p, at, red, scoped, label, populations, envOwned, envInjected }) {
1209
+ /** F49 — the static nested-quantifier reject, at the gate, before the pattern
1210
+ * ever runs. MEASURED: `(a+)+$` did not finish on a 33-char body in 120s, so
1211
+ * input-bounding is theatre and a static reject is not. The detector itself is
1212
+ * never touched from here (monotonic-only doctrine). */
1213
+ const regex = (/** @type {any} */ v, /** @type {string} */ path) => {
1214
+ if (!isNonEmptyString(v)) { red('invalid-value', path, 'a regular expression, as a string'); return; }
1215
+ if (hasNestedQuantifier(v)) {
1216
+ red('invalid-value', path, `/${v}/ carries a nested quantifier — rejected statically (F49); rewrite it without one`);
1217
+ return;
1218
+ }
1219
+ try { new RegExp(v); } catch (e) {
1220
+ red('invalid-value', path, `/${v}/ is not a valid regular expression: ${String(/** @type {any} */ (e)?.message ?? e)}`);
1221
+ }
1222
+ };
1223
+ const command = () => {
1224
+ if (!isNonEmptyString(p.cmd)) red('invalid-value', `${at}.params.cmd`, 'a non-empty executable name');
1225
+ else {
1226
+ // THE DENY FLOOR (PRD v1.57 §3), at the validation gate, before any token
1227
+ // and before any spawn. A FLOOR, not a sandbox — see DENIED_COMMANDS.
1228
+ const denied = deniedCommandReason(p.cmd);
1229
+ if (denied) red('cmd-denied', `${at}.params.cmd`, denied, { cmd: p.cmd });
1230
+ }
1231
+ if (Object.hasOwn(p, 'args') && !(Array.isArray(p.args) && p.args.every((/** @type {any} */ x) => typeof x === 'string'))) {
1232
+ red('invalid-value', `${at}.params.args`, 'an array of strings (may be empty)');
1233
+ }
1234
+ if (Object.hasOwn(p, 'timeoutMs') && !(Number.isInteger(p.timeoutMs) && p.timeoutMs > 0)) {
1235
+ red('invalid-value', `${at}.params.timeoutMs`, 'a positive integer');
1236
+ }
1237
+ if (Object.hasOwn(p, 'env')) {
1238
+ if (!(isObj(p.env) && Object.values(p.env).every((v) => typeof v === 'string'))) {
1239
+ red('invalid-value', `${at}.params.env`, 'an object of string values');
1240
+ } else {
1241
+ for (const name of Object.keys(p.env)) {
1242
+ if (!envOwned.includes(name)) continue;
1243
+ // The arbiter's OWN injection reaches this check on every re-validation
1244
+ // after the flow applied it (M3's applyGenreEnv), so the split is by
1245
+ // VALUE and never by presence — exactly how `checkGuards` tells a genre
1246
+ // guard from a weakened copy. Presence-flagging here would red the
1247
+ // arbiter's own artefact and no python close could be signed, validated
1248
+ // or run.
1249
+ const injected = Object.hasOwn(envInjected, name);
1250
+ if (injected && p.env[name] === envInjected[name]) continue;
1251
+ // Round 2's arm B authored MYPYPATH itself and authored it WRONG; the
1252
+ // flow sets it from genre data. A value that is not the one the arbiter
1253
+ // builds is the model's guess or a corrupted artefact, either way a red.
1254
+ red('genre-owned-env', `${at}.params.env.${name}`, injected
1255
+ ? `${name} is the genre's own variable and its value is fixed by the genre, not by the declaration: `
1256
+ + `expected ${JSON.stringify(envInjected[name])}, declared ${JSON.stringify(p.env[name])}`
1257
+ : `${name} is set by the genre, not by the declaration — this is a fact the interview cannot supply `
1258
+ + 'and the repository does not state',
1259
+ { name, ...(injected ? { expected: envInjected[name], declared: p.env[name] } : {}) });
1260
+ }
1261
+ }
1262
+ }
1263
+ };
1264
+ /** the one-population law's first half (F84): a count over a scoped job must
1265
+ * say WHICH population it counts, or an in-scope 29 and an outside 4 land in
1266
+ * one trend series and a run that swapped walls reads as converging. */
1267
+ const populationNamed = (/** @type {string} */ path) => {
1268
+ const sc = p.scope;
1269
+ if (!isObj(sc)) { red('missing-field', path, 'a scope object naming this stage\'s population'); return; }
1270
+ const inc = Object.hasOwn(sc, 'includePrefixes') ? sc.includePrefixes : null;
1271
+ const exc = Object.hasOwn(sc, 'excludePrefixes') ? sc.excludePrefixes : null;
1272
+ if (inc !== null && !strArray(inc)) red('invalid-value', `${path}.includePrefixes`, 'a non-empty array of path prefixes');
1273
+ if (exc !== null && !strArray(exc)) red('invalid-value', `${path}.excludePrefixes`, 'a non-empty array of path prefixes');
1274
+ for (const k of Object.keys(sc)) {
1275
+ if (k !== 'includePrefixes' && k !== 'excludePrefixes') red('invalid-value', `${path}.${k}`, 'a scope takes includePrefixes and excludePrefixes only');
1276
+ }
1277
+ if (inc === null && exc === null && scoped.scoped) {
1278
+ red('one-population', path, `stage "${label}" counts over a scoped job (${scoped.via}) with no include/exclude `
1279
+ + 'filter — that mixes the job\'s own population with everything else under one stage name, and the two land '
1280
+ + 'in one trend series (F84)', { rule: 'unnamed-population', stage: label });
1281
+ }
1282
+ };
1283
+
1284
+ switch (kind) {
1285
+ case 'command-exit':
1286
+ command();
1287
+ if (!Number.isInteger(p.expectExit)) red('invalid-value', `${at}.params.expectExit`, 'an integer exit code');
1288
+ break;
1289
+ case 'count-not-worse': {
1290
+ command();
1291
+ // ONE normalisation, the EXECUTOR's own (src/kinds.js). Short form and long
1292
+ // form both land here, so the validator and the grader can never disagree
1293
+ // about what a parser means.
1294
+ const norm = normalizeParser(p.parser, `${at}.params.parser`);
1295
+ for (const r of norm.reds) red(r.code, r.path, r.detail);
1296
+ for (const t of norm.terms ?? []) {
1297
+ regex(t.lineMatch, `${at}.params.parser (lineMatch /${t.lineMatch}/)`);
1298
+ // a region anchor runs over the whole output, so it is exactly as
1299
+ // exposed to F49 as lineMatch is
1300
+ if (isObj(t.region)) regex(t.region.anchor, `${at}.params.parser (region anchor /${t.region.anchor}/)`);
1301
+ }
1302
+ if (!DIRECTIONS.includes(p.direction)) red('invalid-value', `${at}.params.direction`, `one of ${DIRECTIONS.join(' | ')}`);
1303
+ if (!BASELINES.includes(p.baseline)) {
1304
+ red('invalid-value', `${at}.params.baseline`, `one of ${BASELINES.map((b) => JSON.stringify(b)).join(' | ')} — `
1305
+ + 'the close stores the counting rule, never a number you measured (D12)');
1306
+ }
1307
+ populationNamed(`${at}.params.scope`);
1308
+ // the law's second half: the SAME command, parser and scope declared twice
1309
+ // is one population measured twice, wearing two stage names
1310
+ if (norm.ok) {
1311
+ const key = JSON.stringify([p.cmd, p.args ?? [], norm.terms, canonicalScope(p.scope)]);
1312
+ const owner = populations.get(key);
1313
+ if (owner !== undefined) {
1314
+ red('one-population', `${at}.params`, `stage "${label}" measures the same population as "${owner}" — same `
1315
+ + 'command, same parser, same scope. One population is one stage (F84); two names over one number are two '
1316
+ + 'trend series that can never disagree', { rule: 'duplicate-population', stage: label, twin: owner });
1317
+ } else populations.set(key, label);
1318
+ }
1319
+ break;
1320
+ }
1321
+ case 'pattern-absent-in-diff':
1322
+ if (!Array.isArray(p.patterns) || p.patterns.length === 0) {
1323
+ red('invalid-value', `${at}.params.patterns`, 'a non-empty array of {id, regex}');
1324
+ } else {
1325
+ p.patterns.forEach((/** @type {any} */ q, /** @type {number} */ j) => {
1326
+ if (!isObj(q)) { red('invalid-value', `${at}.params.patterns[${j}]`, '{id, regex}'); return; }
1327
+ if (!isNonEmptyString(q.id)) red('invalid-value', `${at}.params.patterns[${j}].id`, 'a non-empty id');
1328
+ regex(q.regex, `${at}.params.patterns[${j}].regex`);
1329
+ });
1330
+ }
1331
+ if (!strArray(p.extensions)) red('invalid-value', `${at}.params.extensions`, 'a non-empty array of file extensions');
1332
+ // scope is OPTIONAL here and absent on the genre guard: the scan covers
1333
+ // every changed file of these extensions. When a declaration does carry
1334
+ // one it is still shape-checked — but a missing scope is not a red.
1335
+ if (Object.hasOwn(p, 'scope')) populationNamed(`${at}.params.scope`);
1336
+ break;
1337
+ case 'files-changed':
1338
+ if (!strArray(p.allowPrefixes)) red('invalid-value', `${at}.params.allowPrefixes`, 'a non-empty array of path prefixes');
1339
+ if (p.requireNonEmpty !== true) red('invalid-value', `${at}.params.requireNonEmpty`, 'literally true');
1340
+ break;
1341
+ default:
1342
+ red('unknown-kind', `${at}.kind`, `"${kind}" is in the catalogue but has no checker`, { kind });
1343
+ }
1344
+ }
1345
+
1346
+ /** the scope as a comparable value — key order must not decide whether two
1347
+ * stages count the same population @param {any} sc */
1348
+ function canonicalScope(sc) {
1349
+ if (!isObj(sc)) return null;
1350
+ const norm = (/** @type {any} */ v) => (Array.isArray(v) ? [...v].map(normPrefix).sort() : null);
1351
+ return { include: norm(sc.includePrefixes), exclude: norm(sc.excludePrefixes) };
1352
+ }
1353
+
1354
+ /**
1355
+ * HAMR'S LISTING RULE: every path-like param must SELECT from the seed listing.
1356
+ * A path matching nothing is a distinct red, never a judgment call — round 2's
1357
+ * arm A derived `src/alertEmail.js` from the user's prose and reclassified 15
1358
+ * real errors into the wrong population, and no amount of reading the
1359
+ * declaration would have caught it.
1360
+ *
1361
+ * A trailing-slash (or `/**`) spelling ASSERTS a directory, so it must name one;
1362
+ * a bare path may name either. The repository root, however spelled, always
1363
+ * selects — it names the whole tree, which exists.
1364
+ * @param {{spec: KindSpec, params: any, at: string,
1365
+ * red: (c: string, p: string, d: string, e?: object) => void,
1366
+ * idx: {files: Set<string>, dirs: Set<string>}, haveListing: boolean}} o
1367
+ */
1368
+ function checkPaths({ spec, params: p, at, red, idx, haveListing }) {
1369
+ if (!haveListing) return; // already redded once, at the top; not twice per path
1370
+ for (const dotted of spec.pathParams) {
1371
+ const value = readPath(p, dotted);
1372
+ if (!Array.isArray(value)) continue; // shape is the schema walk's business
1373
+ value.forEach((raw, i) => {
1374
+ if (!isNonEmptyString(raw)) return;
1375
+ const wantsDir = /(?:\/|\/\*\*?)$/.test(raw.trim());
1376
+ const norm = normPrefix(raw);
1377
+ if (isRoot(norm)) return;
1378
+ const path = `${at}.params.${dotted}[${i}]`;
1379
+ const isFile = idx.files.has(norm);
1380
+ const isDir = idx.dirs.has(norm);
1381
+ if (isDir) return;
1382
+ if (isFile && wantsDir) {
1383
+ red('path-not-in-listing', path, `"${raw}" is spelled as a directory but the seed tree says ${norm} is a file`,
1384
+ { declared: raw, resolved: norm, found: 'file', wanted: 'directory' });
1385
+ return;
1386
+ }
1387
+ if (isFile) return;
1388
+ red('path-not-in-listing', path, `"${raw}" matches nothing in the seed tree${nearby(norm, idx)} — a path is `
1389
+ + 'read off the repository, never derived from what a file sounds like it should be called',
1390
+ { declared: raw, resolved: norm, found: null, wanted: wantsDir ? 'directory' : 'any' });
1391
+ });
1392
+ }
1393
+ }
1394
+
1395
+ /** the mechanical half of the gap: what DOES exist beside the invented path.
1396
+ * Named items, counts, capped — never a paragraph (F38/F39).
1397
+ * @param {string} norm @param {{files: Set<string>, dirs: Set<string>}} idx */
1398
+ function nearby(norm, idx) {
1399
+ const parent = norm.includes('/') ? norm.slice(0, norm.lastIndexOf('/')) : '';
1400
+ const under = [...idx.files, ...idx.dirs]
1401
+ .filter((f) => (parent === '' ? !f.includes('/') : f.startsWith(`${parent}/`) && !f.slice(parent.length + 1).includes('/')))
1402
+ .sort();
1403
+ if (under.length === 0) return '';
1404
+ const shown = under.slice(0, 8);
1405
+ const tail = under.length > shown.length ? `, and ${under.length - shown.length} more` : '';
1406
+ return ` (under ${parent === '' ? 'the repository root' : parent} the seed tree has: ${shown.join(', ')}${tail})`;
1407
+ }
1408
+
1409
+ /**
1410
+ * THE D5 LINE. Every injected guard must be PRESENT, of the right kind, and
1411
+ * byte-equal to the genre's own parameters. Only the guard's declared `fill`
1412
+ * slots are the model's, and a parameter the guard does not carry at all is a
1413
+ * NARROWING — which is how round 3's arm A scoped the suppression scan to two
1414
+ * files and made a weaker guard look stricter.
1415
+ * @param {{declaration: any, guards: any[], red: (c: string, p: string, d: string, e?: object) => void}} o
1416
+ */
1417
+ function checkGuards({ declaration, guards, red }) {
1418
+ const stages = Array.isArray(declaration?.stages) ? declaration.stages : [];
1419
+ for (const g of guards) {
1420
+ const i = stages.findIndex((/** @type {any} */ s) => isObj(s) && s.name === g.name);
1421
+ if (i === -1) {
1422
+ red('guard-missing', 'stages', `the genre's "${g.name}" guard is not in the declaration — mandatory guards are `
1423
+ + 'shown to the user and cannot be removed (D5)', { guard: g.name, kind: g.kind });
1424
+ continue;
1425
+ }
1426
+ const s = stages[i];
1427
+ const at = `stages[${i}]`;
1428
+ if (s.kind !== g.kind) {
1429
+ red('guard-weakened', `${at}.kind`, `the "${g.name}" guard is a ${g.kind}; this declares ${String(s.kind)}`,
1430
+ { guard: g.name, param: 'kind' });
1431
+ continue;
1432
+ }
1433
+ const params = isObj(s.params) ? s.params : {};
1434
+ for (const [k, want] of Object.entries(g.params)) {
1435
+ if (!deepEqual(params[k], want)) {
1436
+ red('guard-weakened', `${at}.params.${k}`, `the "${g.name}" guard's ${k} is genre property and is fixed: `
1437
+ + `expected ${JSON.stringify(want)}`, { guard: g.name, param: k, expected: want, declared: params[k] });
1438
+ }
1439
+ }
1440
+ for (const k of Object.keys(params)) {
1441
+ if (Object.hasOwn(g.params, k) || g.fill.includes(k)) continue;
1442
+ red('guard-weakened', `${at}.params.${k}`, `the "${g.name}" guard does not take ${k} — adding one narrows what `
1443
+ + 'the guard covers, and a guard that covers less is not a stricter guard', { guard: g.name, param: k, declared: params[k] });
1444
+ }
1445
+ }
1446
+ }
1447
+
1448
+ /** structural equality over plain JSON data (the shapes a declaration carries)
1449
+ * @param {any} a @param {any} b */
1450
+ function deepEqual(a, b) {
1451
+ if (a === b) return true;
1452
+ if (Array.isArray(a) || Array.isArray(b)) {
1453
+ if (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length) return false;
1454
+ return a.every((v, i) => deepEqual(v, b[i]));
1455
+ }
1456
+ if (isObj(a) && isObj(b)) {
1457
+ const ka = Object.keys(a);
1458
+ const kb = Object.keys(b);
1459
+ if (ka.length !== kb.length) return false;
1460
+ return ka.every((k) => Object.hasOwn(b, k) && deepEqual(a[k], b[k]));
1461
+ }
1462
+ return false;
1463
+ }
1464
+
1465
+ /**
1466
+ * The declaration the EXECUTOR sees and the SIGNATURE covers: every
1467
+ * `count-not-worse` parser resolved to `{terms: [...]}`, so the short form stops
1468
+ * existing at this boundary and there is exactly one shape downstream (D13
1469
+ * forward-compat point 3 — the hash is taken over the RESOLVED form, or an
1470
+ * omittable-with-a-default field changes what runs without changing what was
1471
+ * signed).
1472
+ *
1473
+ * A parser that would not normalise is left VERBATIM: it already carries a red,
1474
+ * and rewriting it would hide what the model actually wrote.
1475
+ * @param {any} declaration
1476
+ */
1477
+ export function normalizeDeclaration(declaration) {
1478
+ if (!isObj(declaration) || !Array.isArray(declaration.stages)) return declaration;
1479
+ const out = structuredClone(declaration);
1480
+ for (const s of out.stages) {
1481
+ if (!isObj(s) || s.kind !== 'count-not-worse' || !isObj(s.params)) continue;
1482
+ const n = normalizeParser(s.params.parser, 'parser');
1483
+ if (n.ok) s.params.parser = { terms: n.terms };
1484
+ }
1485
+ return out;
1486
+ }