fwdloop 0.3.0 → 0.4.1

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,665 @@
1
+ // ported-from: poc/m0/validator.mjs@288cb8a (parseLines/resolveGuardrailClass/
2
+ // deriveFromLine/validate — the walkable chain, the fromLine/class
3
+ // derivation, the listing rule, and THE SEND LOCK block around lines
4
+ // 573-634) and poc/m0/artifacts.mjs@deae3da (ArtifactSpace/unwalkableReads —
5
+ // the declared-before check) and poc/m1/slots.mjs@92313d7 (checkAskSlots —
6
+ // the ask slot mechanism, incl. the "a pause is zero primitives AND hitl"
7
+ // fix). Rewritten for the M1 schema, never imported — src must not import
8
+ // from poc (CLAUDE.md: "borrow, never import"; complete separation between
9
+ // poc/ and src/).
10
+ //
11
+ // The send lock is a mechanism, not wording (F21/F24: a lock is typed
12
+ // grants/checks, never prompt phrasing). Generalised from M0b's single ask
13
+ // slot / single send slot to M1's arrays (`arbiter.asks[]`,
14
+ // `arbiter.sends[]`, M1 scope item 3 widened to "however many a human
15
+ // signs"): every signed ask and send line is checked, not just the last one
16
+ // seen. Unlike M0, which hard-coded the verb "write", rule (d) below checks
17
+ // the CATALOGUE's `class` field for the primitive instead — the send lock
18
+ // should not be tied to one verb's name.
19
+ //
20
+ // M1 piece 3 (docs/wiki/the-module-ladder.md, "M1 — scope, exit,
21
+ // negative — SIGNED", scope item 2): "the drafter's half is a schema with
22
+ // no arbiter fields in it." This module validates `declaration.json`
23
+ // against that closed schema, given the ALREADY-PARSED `arbiter`/`lines`
24
+ // from `parseSignedText` (src/signed-text.js) — it never parses prose
25
+ // itself, and it never imports the catalogue: the caller passes it as
26
+ // data (piece 4 makes it a data file; piece 3 only takes it as a param).
27
+ //
28
+ // `inputFacts`/`picks` replace M0's old per-input listing fields — the
29
+ // harness-supplied mechanical listing for one input, generalised from "one
30
+ // spreadsheet header" to "one input per signed source role" (M1 §10, sources as typed
31
+ // arbiter lines). The listing rule itself (M0a exit criterion, F17) is
32
+ // unchanged in spirit: every name a step picks must appear verbatim in the
33
+ // real, harness-supplied listing for that role — never derived from goal
34
+ // prose, never skipped when it cannot be checked.
35
+ //
36
+ // No `new RegExp` anywhere in this file — a test in test/signed-text.test.js
37
+ // greps all of src/ for that, and it must keep passing with this file added.
38
+
39
+ /** @typedef {import('./types.js').Arbiter} Arbiter */
40
+ /** @typedef {import('./types.js').SignedLine} SignedLine */
41
+ /** @typedef {import('./types.js').CatalogueEntry} CatalogueEntry */
42
+ /** @typedef {import('./types.js').ValidateDeclarationResult} ValidateDeclarationResult */
43
+
44
+ /** Every top-level, step-level and close-level field this schema defines —
45
+ * kept in sync with the checks below so a mutation suite can assert it
46
+ * tested every one of them (same trick as ARBITER_FIELDS/SIGNATURE_FIELDS). */
47
+ export const DECLARATION_FIELDS = Object.freeze([
48
+ // top level
49
+ 'steps',
50
+ 'guardrailClasses',
51
+ 'unjudgeable',
52
+ 'refused',
53
+ 'inputFacts',
54
+ // step level
55
+ 'goal',
56
+ 'primitives',
57
+ 'reads',
58
+ 'emits',
59
+ 'fromLine',
60
+ 'close',
61
+ 'picks',
62
+ // close level
63
+ 'class',
64
+ 'shape',
65
+ ]);
66
+
67
+ const VALID_CLASSES = Object.freeze(['green', 'softgreen', 'hitl']);
68
+
69
+ // The arbiter's own vocabulary — refused at any depth in a declaration, in
70
+ // any position, because the drafter never authors these (CLAUDE.md hard
71
+ // line: "the agent authors steps; it never authors the trigger, the cap,
72
+ // an ask's position, an ask's TTL, the egress allow-list...").
73
+ const ARBITER_KEYS = Object.freeze(['cap', 'ask', 'ttl', 'send', 'source', 'trigger', 'skills']);
74
+
75
+ const TOP_LEVEL_ALLOWED = Object.freeze(['steps', 'guardrailClasses', 'unjudgeable', 'refused', 'inputFacts']);
76
+ const STEP_ALLOWED = Object.freeze(['goal', 'primitives', 'reads', 'emits', 'fromLine', 'close', 'picks']);
77
+ const CLOSE_ALLOWED = Object.freeze(['class', 'shape']);
78
+
79
+ /** @returns {value is Record<string, any>} */
80
+ function isPlainObject(value) {
81
+ return !!value && typeof value === 'object' && !Array.isArray(value);
82
+ }
83
+
84
+ /** Unknown-key + arbiter-key refusal for one object's OWN keys (not
85
+ * recursive) — arbiter words get their own, distinguishable red wording so
86
+ * it can never be mistaken for a plain unknown key. */
87
+ function checkOwnKeys(obj, allowed, path, reds) {
88
+ for (const key of Object.keys(obj)) {
89
+ if (ARBITER_KEYS.includes(key)) {
90
+ reds.push(`declaration: arbiter field "${key}" at ${path}.${key} — the drafter cannot author it`);
91
+ } else if (!allowed.includes(key)) {
92
+ reds.push(`declaration: unknown key "${key}" at ${path}.${key}`);
93
+ }
94
+ }
95
+ }
96
+
97
+ /** The typed `close.shape` vocabulary, signed by hamr 2026-09-23 (v1):
98
+ * exactly these four top-level keys. Anything else inside `shape` reds by
99
+ * name. */
100
+ export const SHAPE_KEYS = Object.freeze(['maxWords', 'sections', 'linesPerInvoice', 'mustCarry']);
101
+
102
+ const SHAPE_TYPE_CHECKS = Object.freeze({
103
+ maxWords: {
104
+ expected: 'a positive integer',
105
+ check: (v) => Number.isInteger(v) && v > 0,
106
+ },
107
+ linesPerInvoice: {
108
+ expected: 'a positive integer',
109
+ check: (v) => Number.isInteger(v) && v > 0,
110
+ },
111
+ sections: {
112
+ expected: 'a non-empty array of non-empty strings',
113
+ check: (v) => Array.isArray(v) && v.length > 0 && v.every((s) => typeof s === 'string' && s.length > 0),
114
+ },
115
+ mustCarry: {
116
+ expected: 'a non-empty array of non-empty strings',
117
+ check: (v) => Array.isArray(v) && v.length > 0 && v.every((s) => typeof s === 'string' && s.length > 0),
118
+ },
119
+ });
120
+
121
+ /** Arbiter-key refusal recursively through a `close.shape` value — any
122
+ * depth, any key named after the arbiter's vocabulary, in an object or
123
+ * nested inside an array (e.g. inside a `sections` array entry that turns
124
+ * out to be an object). */
125
+ function scanForArbiterKeys(value, path, reds) {
126
+ if (Array.isArray(value)) {
127
+ value.forEach((entry, i) => scanForArbiterKeys(entry, `${path}[${i}]`, reds));
128
+ return;
129
+ }
130
+ if (isPlainObject(value)) {
131
+ for (const key of Object.keys(value)) {
132
+ const childPath = `${path}.${key}`;
133
+ if (ARBITER_KEYS.includes(key)) {
134
+ reds.push(`declaration: arbiter field "${key}" at ${childPath} — the drafter cannot author it`);
135
+ }
136
+ scanForArbiterKeys(value[key], childPath, reds);
137
+ }
138
+ }
139
+ }
140
+
141
+ /** `close.shape`'s own top-level keys must each be in SHAPE_KEYS (the signed
142
+ * v1 vocabulary) — an arbiter key gets the existing arbiter-red wording, any
143
+ * other unknown key reds by name, and a known key is type-checked. Nested
144
+ * arbiter-key refusal still applies at any depth inside a shape value. */
145
+ function checkShapeKeys(shape, path, reds) {
146
+ for (const key of Object.keys(shape)) {
147
+ const childPath = `${path}.${key}`;
148
+ const value = shape[key];
149
+ if (ARBITER_KEYS.includes(key)) {
150
+ reds.push(`declaration: arbiter field "${key}" at ${childPath} — the drafter cannot author it`);
151
+ } else if (!SHAPE_KEYS.includes(key)) {
152
+ reds.push(`declaration: unknown shape key "${key}" at ${childPath}`);
153
+ } else {
154
+ const typeCheck = SHAPE_TYPE_CHECKS[key];
155
+ if (!typeCheck.check(value)) {
156
+ reds.push(`declaration: shape key "${key}" at ${childPath} must be ${typeCheck.expected}`);
157
+ }
158
+ }
159
+ scanForArbiterKeys(value, childPath, reds);
160
+ }
161
+ }
162
+
163
+ /**
164
+ * A small, pure walker over `declaration.steps` for callers that only want
165
+ * the shape-key verdict (e.g. poc/m1/slot-batch.mjs's `shape` column) —
166
+ * never a substitute for `validateDeclaration`, which is still the one
167
+ * check that decides pass/fail for a real declaration. Reuses the same
168
+ * `checkShapeKeys` `validateDeclaration` calls, so the two can never drift
169
+ * apart on what counts as a known shape key.
170
+ *
171
+ * A non-array `declaration.steps` (or a non-object `declaration` at all)
172
+ * reds `'no steps array'` rather than throwing. `shapedSteps` counts every
173
+ * step whose `close` carries a `shape` key at all — a step that TRIED to
174
+ * carry a shape, known-key or not, plain-object or not. A `shape` that
175
+ * isn't a plain object (array, string, number, null) reds
176
+ * `"... .close.shape must be an object"`, matching `validateDeclaration`'s
177
+ * own red for the same malformed input.
178
+ */
179
+ export function checkShapes(declaration) {
180
+ const steps = isPlainObject(declaration) && Array.isArray(declaration.steps) ? declaration.steps : null;
181
+ if (steps === null) {
182
+ return { verdict: 'red', reds: ['no steps array'], shapedSteps: 0 };
183
+ }
184
+ const reds = [];
185
+ let shapedSteps = 0;
186
+ steps.forEach((step, i) => {
187
+ if (!isPlainObject(step?.close) || !('shape' in step.close)) return;
188
+ const shape = step.close.shape;
189
+ shapedSteps += 1;
190
+ if (isPlainObject(shape)) {
191
+ checkShapeKeys(shape, `declaration.steps[${i}].close.shape`, reds);
192
+ } else {
193
+ reds.push(`declaration.steps[${i}].close.shape must be an object`);
194
+ }
195
+ });
196
+ return { verdict: reds.length > 0 ? 'red' : 'green', reds, shapedSteps };
197
+ }
198
+
199
+ /**
200
+ * Resolve one line's class from `guardrailClasses`, exactly as
201
+ * poc/m0/validator.mjs's `resolveGuardrailClass` does: blank guardrail is
202
+ * always hitl; no proposal for a non-blank guardrail is hitl (silence is
203
+ * safe); an invented proposal is a red, never normalised to hitl.
204
+ * Returns `{ ok: true, class }` or `{ ok: false, error }`.
205
+ */
206
+ function resolveGuardrailClass(line, guardrailClasses) {
207
+ if (!line || !line.guardrail) {
208
+ return { ok: true, class: 'hitl' };
209
+ }
210
+ const key = String(line.n);
211
+ if (!Object.prototype.hasOwnProperty.call(guardrailClasses, key)) {
212
+ return { ok: true, class: 'hitl' };
213
+ }
214
+ const proposed = guardrailClasses[key];
215
+ if (VALID_CLASSES.includes(proposed)) {
216
+ return { ok: true, class: proposed };
217
+ }
218
+ return {
219
+ ok: false,
220
+ error: `guardrailClasses line ${line.n} proposes class "${proposed}", which is not one of `
221
+ + `${VALID_CLASSES.join(', ')} (an invented proposal, never normalised to hitl)`,
222
+ };
223
+ }
224
+
225
+ /** Same shape as poc/m0/validator.mjs's `deriveFromLine`: a step with no
226
+ * `fromLine` is silence -> hitl; a malformed or non-existent `fromLine` is
227
+ * a red; otherwise the class derives from that line's guardrail proposal. */
228
+ function deriveFromLine(fromLine, lines, guardrailClasses) {
229
+ if (fromLine === null || fromLine === undefined) {
230
+ return { ok: true, class: 'hitl', line: null };
231
+ }
232
+ if (!Number.isInteger(fromLine)) {
233
+ return { ok: false, error: `fromLine ${JSON.stringify(fromLine)} must be an integer` };
234
+ }
235
+ const line = lines.find((l) => l.n === fromLine);
236
+ if (!line) {
237
+ return { ok: false, error: `fromLine ${fromLine} does not name any of the signed numbered lines` };
238
+ }
239
+ const resolved = resolveGuardrailClass(line, guardrailClasses);
240
+ if (!resolved.ok) return { ok: false, error: resolved.error };
241
+ return { ok: true, class: resolved.class, line };
242
+ }
243
+
244
+ /**
245
+ * Validate a drafter declaration against the M1 closed schema. `arbiter`
246
+ * and `lines` are `parseSignedText`'s output; `catalogue` is a plain array
247
+ * of `{ verb, skill, class }`. Never throws — a bad declaration, a bad
248
+ * arbiter, a bad lines array, or a bad catalogue is a red, never an
249
+ * exception.
250
+ *
251
+ * @param {unknown} declaration
252
+ * @param {{ arbiter?: unknown, lines?: unknown, catalogue?: unknown }} [context]
253
+ * @returns {ValidateDeclarationResult}
254
+ */
255
+ export function validateDeclaration(declaration, context = {}) {
256
+ const { arbiter, lines, catalogue } = context;
257
+ const reds = [];
258
+
259
+ if (!isPlainObject(declaration)) {
260
+ return deepFreeze({ ok: false, reds: ['declaration: must be an object'] });
261
+ }
262
+ if (!isPlainObject(arbiter)) {
263
+ reds.push('declaration: caller-supplied "arbiter" must be an object (parseSignedText output)');
264
+ }
265
+ if (!Array.isArray(lines)) {
266
+ reds.push('declaration: caller-supplied "lines" must be an array (parseSignedText output)');
267
+ }
268
+ if (!Array.isArray(catalogue)) {
269
+ reds.push('declaration: caller-supplied "catalogue" must be an array of {verb, skill, class}');
270
+ }
271
+ if (reds.length > 0) return deepFreeze({ ok: false, reds });
272
+
273
+ const safeLines = /** @type {SignedLine[]} */ (lines);
274
+ const safeArbiter = /** @type {Arbiter} */ (arbiter);
275
+ const skills = Array.isArray(safeArbiter.skills) ? safeArbiter.skills : [];
276
+ const sourceRoles = Array.isArray(safeArbiter.sources) ? safeArbiter.sources.map((s) => s?.role) : [];
277
+ const asks = Array.isArray(safeArbiter.asks) ? safeArbiter.asks : [];
278
+ const askLines = asks.map((a) => a.line);
279
+ const sends = Array.isArray(safeArbiter.sends) ? safeArbiter.sends : [];
280
+ const sendLines = sends.map((s) => s.line);
281
+
282
+ const catalogueByVerb = new Map();
283
+ for (const entry of /** @type {CatalogueEntry[]} */ (catalogue)) {
284
+ if (entry && typeof entry.verb === 'string') catalogueByVerb.set(entry.verb, entry);
285
+ }
286
+
287
+ // --- top level: unknown / arbiter keys -----------------------------------
288
+ checkOwnKeys(declaration, TOP_LEVEL_ALLOWED, 'declaration', reds);
289
+
290
+ // --- steps: must be a non-empty array, or nothing else here is meaningful
291
+ if (!Array.isArray(declaration.steps) || declaration.steps.length === 0) {
292
+ reds.push('declaration: "steps" must be a non-empty array');
293
+ return deepFreeze({ ok: false, reds });
294
+ }
295
+ const { steps } = declaration;
296
+
297
+ // --- guardrailClasses (REQUIRED — the harness always writes it; empty {}
298
+ // is fine, missing entirely is not) ------------------------------------
299
+ let guardrailClasses = {};
300
+ if (!Object.prototype.hasOwnProperty.call(declaration, 'guardrailClasses')) {
301
+ reds.push('declaration: "guardrailClasses" is required (an object keyed by line number; {} is fine)');
302
+ } else if (isPlainObject(declaration.guardrailClasses)) {
303
+ guardrailClasses = declaration.guardrailClasses;
304
+ for (const key of Object.keys(guardrailClasses)) {
305
+ const n = Number(key);
306
+ const line = Number.isInteger(n) ? safeLines.find((l) => l.n === n) : undefined;
307
+ if (!line || !line.guardrail) {
308
+ reds.push(`declaration: guardrailClasses key "${key}" does not name a signed line with a guardrail`);
309
+ continue;
310
+ }
311
+ const value = guardrailClasses[key];
312
+ if (!VALID_CLASSES.includes(value)) {
313
+ reds.push(`declaration: guardrailClasses line ${key} value ${JSON.stringify(value)} is not one of ${VALID_CLASSES.join(', ')}`);
314
+ }
315
+ }
316
+ } else {
317
+ reds.push('declaration: "guardrailClasses" must be an object keyed by line number');
318
+ }
319
+
320
+ // --- unjudgeable (REQUIRED; {} is fine) ------------------------------------
321
+ let unjudgeable = {};
322
+ if (!Object.prototype.hasOwnProperty.call(declaration, 'unjudgeable')) {
323
+ reds.push('declaration: "unjudgeable" is required (an object keyed by line number; {} is fine)');
324
+ } else if (isPlainObject(declaration.unjudgeable)) {
325
+ unjudgeable = declaration.unjudgeable;
326
+ for (const [key, reason] of Object.entries(unjudgeable)) {
327
+ const n = Number(key);
328
+ if (!Number.isInteger(n)) {
329
+ reds.push(`declaration: unjudgeable key "${key}" must be an integer line number`);
330
+ continue;
331
+ }
332
+ if (typeof reason !== 'string' || reason.length === 0) {
333
+ reds.push(`declaration: unjudgeable reason for line ${n} must be a non-empty string`);
334
+ continue;
335
+ }
336
+ const line = safeLines.find((l) => l.n === n);
337
+ if (!line || !line.guardrail) {
338
+ reds.push(`declaration: unjudgeable names line ${n}, which has no guardrail to be unjudgeable about`);
339
+ continue;
340
+ }
341
+ const proposed = isPlainObject(declaration.guardrailClasses) ? declaration.guardrailClasses[key] : undefined;
342
+ if (proposed !== undefined && proposed !== 'hitl') {
343
+ reds.push(`declaration: line ${n} is marked unjudgeable but guardrailClasses proposes "${proposed}" `
344
+ + '— unjudgeable never upgrades or downgrades the class, it can only explain a hitl');
345
+ }
346
+ }
347
+ } else {
348
+ reds.push('declaration: "unjudgeable" must be an object keyed by line number');
349
+ }
350
+
351
+ // --- refused (REQUIRED; [] is fine) ----------------------------------------
352
+ let refused = [];
353
+ if (!Object.prototype.hasOwnProperty.call(declaration, 'refused')) {
354
+ reds.push('declaration: "refused" is required (an array of {line, reason}; [] is fine)');
355
+ } else if (Array.isArray(declaration.refused)) {
356
+ refused = declaration.refused;
357
+ refused.forEach((entry, i) => {
358
+ if (!isPlainObject(entry)) {
359
+ reds.push(`declaration: refused[${i}] must be an object {line, reason}`);
360
+ return;
361
+ }
362
+ if (!Number.isInteger(entry.line)) {
363
+ reds.push(`declaration: refused[${i}].line must be an integer line number`);
364
+ } else if (!safeLines.some((l) => l.n === entry.line)) {
365
+ reds.push(`declaration: refused[${i}].line ${entry.line} does not name any signed numbered line`);
366
+ }
367
+ if (typeof entry.reason !== 'string' || entry.reason.length === 0) {
368
+ reds.push(`declaration: refused[${i}].reason must be a non-empty string`);
369
+ }
370
+ });
371
+ } else {
372
+ reds.push('declaration: "refused" must be an array of {line, reason}');
373
+ }
374
+ const refusedLines = new Set(refused.map((r) => r?.line).filter((n) => Number.isInteger(n)));
375
+
376
+ // --- inputFacts (REQUIRED; {} is fine) -------------------------------------
377
+ let inputFacts = {};
378
+ if (!Object.prototype.hasOwnProperty.call(declaration, 'inputFacts')) {
379
+ reds.push('declaration: "inputFacts" is required (an object keyed by source role; {} is fine)');
380
+ } else if (isPlainObject(declaration.inputFacts)) {
381
+ inputFacts = declaration.inputFacts;
382
+ for (const [role, listing] of Object.entries(inputFacts)) {
383
+ if (!sourceRoles.includes(role)) {
384
+ reds.push(`declaration: inputFacts role "${role}" is not one of the signed source roles`);
385
+ }
386
+ if (!Array.isArray(listing) || listing.some((v) => typeof v !== 'string')) {
387
+ reds.push(`declaration: inputFacts["${role}"] must be an array of strings`);
388
+ }
389
+ }
390
+ } else {
391
+ reds.push('declaration: "inputFacts" must be an object keyed by source role');
392
+ }
393
+
394
+ // --- steps ------------------------------------------------------------------
395
+ const emitSeen = new Set();
396
+ const declaredEmits = new Set();
397
+ /** @type {Array<{ emits: string|null, effectiveClass: string, fromLine: number|null, primitives: string[], reads: string[] }>} */
398
+ const stepInfo = [];
399
+
400
+ steps.forEach((step, i) => {
401
+ const label = `steps[${i}]`;
402
+ if (!isPlainObject(step)) {
403
+ reds.push(`declaration: ${label} must be an object`);
404
+ stepInfo.push({
405
+ emits: null, effectiveClass: 'hitl', fromLine: null, primitives: [], reads: [],
406
+ });
407
+ return;
408
+ }
409
+
410
+ checkOwnKeys(step, STEP_ALLOWED, `declaration.${label}`, reds);
411
+
412
+ // goal
413
+ if (typeof step.goal !== 'string' || step.goal.length === 0) {
414
+ reds.push(`declaration: ${label}.goal must be a non-empty string`);
415
+ }
416
+
417
+ // primitives
418
+ const primitives = Array.isArray(step.primitives) ? step.primitives : null;
419
+ if (primitives === null) {
420
+ reds.push(`declaration: ${label}.primitives must be an array of catalogue verbs`);
421
+ } else {
422
+ for (const verb of primitives) {
423
+ const entry = typeof verb === 'string' ? catalogueByVerb.get(verb) : undefined;
424
+ if (!entry) {
425
+ reds.push(`declaration: ${label}.primitives names "${verb}", which is not in the catalogue`);
426
+ continue;
427
+ }
428
+ if (!skills.includes(entry.skill)) {
429
+ reds.push(`declaration: ${label}.primitives "${verb}" needs skill "${entry.skill}", which is not signed (skills: ${skills.join(', ') || 'none'})`);
430
+ }
431
+ }
432
+ }
433
+
434
+ // reads
435
+ const reads = Array.isArray(step.reads) ? step.reads : null;
436
+ if (reads === null) {
437
+ reds.push(`declaration: ${label}.reads must be an array of artifact ids`);
438
+ }
439
+
440
+ // emits
441
+ let emits = null;
442
+ if (typeof step.emits !== 'string' || step.emits.length === 0) {
443
+ reds.push(`declaration: ${label}.emits must be a non-empty string`);
444
+ } else {
445
+ emits = step.emits;
446
+ if (emitSeen.has(emits)) {
447
+ reds.push(`declaration: ${label}.emits "${emits}" is a duplicate — one writer per artifact`);
448
+ }
449
+ emitSeen.add(emits);
450
+ }
451
+
452
+ // walkable chain — every read must have been emitted by an EARLIER step
453
+ if (reads !== null && emits !== null) {
454
+ for (const readId of reads) {
455
+ if (readId === emits || !declaredEmits.has(readId)) {
456
+ reds.push(`declaration: ${label} reads artifact "${readId}" that no earlier step declared`);
457
+ }
458
+ }
459
+ }
460
+ if (emits !== null) declaredEmits.add(emits);
461
+
462
+ // fromLine + class derivation — the key itself is required (value may be
463
+ // null, meaning "no line"; the key being entirely absent is not the same
464
+ // thing and is its own red).
465
+ let effectiveClass = 'hitl';
466
+ let fromLine = null;
467
+ if (!Object.prototype.hasOwnProperty.call(step, 'fromLine')) {
468
+ reds.push(`declaration: ${label}.fromLine is required (an integer naming a real line, or null)`);
469
+ } else {
470
+ fromLine = step.fromLine;
471
+ if (fromLine !== null && typeof fromLine !== 'number') {
472
+ reds.push(`declaration: ${label}.fromLine must be an integer or null`);
473
+ } else {
474
+ const resolved = deriveFromLine(fromLine, safeLines, guardrailClasses);
475
+ if (!resolved.ok) {
476
+ reds.push(`declaration: ${label} ${resolved.error}`);
477
+ } else {
478
+ effectiveClass = resolved.class;
479
+ }
480
+ }
481
+ }
482
+
483
+ // close
484
+ if (step.close !== undefined && step.close !== null) {
485
+ if (!isPlainObject(step.close)) {
486
+ reds.push(`declaration: ${label}.close must be an object`);
487
+ } else {
488
+ checkOwnKeys(step.close, CLOSE_ALLOWED, `declaration.${label}.close`, reds);
489
+ const declaredClass = step.close.class;
490
+ if (declaredClass !== undefined) {
491
+ if (!VALID_CLASSES.includes(declaredClass)) {
492
+ reds.push(`declaration: ${label}.close.class ${JSON.stringify(declaredClass)} is not one of ${VALID_CLASSES.join(', ')}`);
493
+ } else if (declaredClass !== effectiveClass) {
494
+ reds.push(`declaration: ${label}.close.class "${declaredClass}" does not match "${effectiveClass}", `
495
+ + 'which is what fromLine derives to — a step cannot claim a class its own guardrail does not produce');
496
+ }
497
+ }
498
+ if (step.close.shape !== undefined && step.close.shape !== null) {
499
+ if (!isPlainObject(step.close.shape)) {
500
+ reds.push(`declaration: ${label}.close.shape must be an object`);
501
+ } else {
502
+ checkShapeKeys(step.close.shape, `declaration.${label}.close.shape`, reds);
503
+ }
504
+ }
505
+ }
506
+ }
507
+
508
+ // picks — the listing rule, generalised
509
+ if (step.picks !== undefined) {
510
+ if (!isPlainObject(step.picks)) {
511
+ reds.push(`declaration: ${label}.picks must be an object keyed by source role`);
512
+ } else {
513
+ for (const [role, names] of Object.entries(step.picks)) {
514
+ const listing = Object.prototype.hasOwnProperty.call(inputFacts, role) ? inputFacts[role] : undefined;
515
+ if (listing === undefined) {
516
+ reds.push(`declaration: ${label}.picks names role "${role}", which is missing from declaration.inputFacts`);
517
+ continue;
518
+ }
519
+ if (!Array.isArray(names)) {
520
+ reds.push(`declaration: ${label}.picks["${role}"] must be an array of strings`);
521
+ continue;
522
+ }
523
+ for (const name of names) {
524
+ if (typeof name !== 'string' || !listing.includes(name)) {
525
+ reds.push(`declaration: ${label}.picks["${role}"] names "${name}" — invented name, not in `
526
+ + `declaration.inputFacts["${role}"] (${listing.join(', ')})`);
527
+ }
528
+ }
529
+ }
530
+ }
531
+ }
532
+
533
+ stepInfo.push({
534
+ emits,
535
+ effectiveClass,
536
+ fromLine: fromLine ?? null,
537
+ primitives: primitives ?? [],
538
+ reads: reads ?? [],
539
+ });
540
+ });
541
+
542
+ // --- ask slots (ported from poc/m1/slots.mjs's checkAskSlots) --------------
543
+ // (a) exactly one hitl step bound to each signed ask line.
544
+ for (const n of askLines) {
545
+ const matches = stepInfo.filter((st) => st.fromLine === n);
546
+ if (matches.length === 0) {
547
+ reds.push(`declaration: ask at line ${n} has no step bound to it`);
548
+ } else if (matches.length >= 2) {
549
+ reds.push(`declaration: ask at line ${n} has ${matches.length} steps bound to it — exactly 1 required`);
550
+ } else if (matches[0].effectiveClass !== 'hitl') {
551
+ reds.push(`declaration: ask at line ${n} step's effective class is "${matches[0].effectiveClass}" — must be "hitl"`);
552
+ }
553
+ // (a2) M1 amendment 3 item 4: a marked line is ONLY the stop — the one
554
+ // step bound to it grants no primitive. Independent of (and collected
555
+ // alongside) the class check above: a step can be both the wrong class
556
+ // AND carrying work, and both reds should surface.
557
+ if (matches.length === 1 && matches[0].primitives.length > 0) {
558
+ const stepIdx = stepInfo.indexOf(matches[0]);
559
+ reds.push(`declaration: ask at line ${n} (steps[${stepIdx}]) is a stop only — granting primitive(s) `
560
+ + `[${matches[0].primitives.join(', ')}] is work, which belongs on its own line`);
561
+ }
562
+ }
563
+ // (b) no step, anywhere, grants "checkpoint" — that belongs to the runner.
564
+ stepInfo.forEach((st, i) => {
565
+ if (st.primitives.includes('checkpoint')) {
566
+ reds.push(`declaration: steps[${i}] (line ${st.fromLine}) grants "checkpoint" — the pause belongs to the runner, never the drafter`);
567
+ }
568
+ });
569
+ // (c) no pause (zero primitives AND effective class hitl) at an unsigned line.
570
+ const signedAskLines = new Set(askLines);
571
+ stepInfo.forEach((st, i) => {
572
+ const isSignedAskLine = st.fromLine !== null && signedAskLines.has(st.fromLine);
573
+ if (st.primitives.length === 0 && st.effectiveClass === 'hitl' && !isSignedAskLine) {
574
+ reds.push(`declaration: steps[${i}] (line ${st.fromLine}) is a pause (no primitives, hitl) at an unsigned line`);
575
+ }
576
+ });
577
+
578
+ // --- THE SEND LOCK (ported from poc/m0/validator.mjs@288cb8a, the block
579
+ // "THE SEND LOCK (M0b Part 1...)" around lines 573-634) — a mechanism, not
580
+ // wording (F21/F24: a lock is typed grants, never wording). Generalised
581
+ // from M0b's single ask/send slot to M1's arrays (`arbiter.asks[]`,
582
+ // `arbiter.sends[]`): every signed slot is checked, not just the last one.
583
+ //
584
+ // (a) every signed ask/send line must be a real numbered line. Redundant
585
+ // with what parseSignedText already guarantees on its own arbiter — this
586
+ // validator does not trust its caller either, same discipline as the rest
587
+ // of this file.
588
+ const lineNumbers = new Set(safeLines.map((l) => l.n));
589
+ for (const n of askLines) {
590
+ if (!lineNumbers.has(n)) reds.push(`declaration: signed ask at line ${n} does not name a real numbered line`);
591
+ }
592
+ for (const n of sendLines) {
593
+ if (!lineNumbers.has(n)) reds.push(`declaration: signed send at line ${n} does not name a real numbered line`);
594
+ }
595
+
596
+ // (b) a signed ask or send line can never be refused.
597
+ for (const n of askLines) {
598
+ if (refusedLines.has(n)) reds.push(`declaration: line ${n} is the signed ask slot and cannot be refused`);
599
+ }
600
+ for (const n of sendLines) {
601
+ if (refusedLines.has(n)) reds.push(`declaration: line ${n} is the signed send slot and cannot be refused`);
602
+ }
603
+
604
+ // (c)-(e) — the send step itself: exactly one step bound to it, granted a
605
+ // catalogue primitive of class "write" (not hard-coded to the verb
606
+ // "write" itself, per the coordinator's note — a catalogue is exactly the
607
+ // place that vocabulary belongs), and reading the `emits` of at least one
608
+ // ask step at a strictly earlier signed ask line.
609
+ for (const n of sendLines) {
610
+ const matches = stepInfo.map((st, i) => ({ st, i })).filter((x) => x.st.fromLine === n);
611
+ if (matches.length === 0) {
612
+ reds.push(`declaration: send at line ${n} has no step bound to it`);
613
+ continue;
614
+ }
615
+ if (matches.length >= 2) {
616
+ reds.push(`declaration: send at line ${n} has ${matches.length} steps bound to it (steps[${matches.map((m) => m.i).join(', ')}]) — exactly 1 required`);
617
+ continue;
618
+ }
619
+ const { st: sendStep, i: sendIdx } = matches[0];
620
+
621
+ const hasWrite = sendStep.primitives.some((verb) => catalogueByVerb.get(verb)?.class === 'write');
622
+ if (!hasWrite) {
623
+ reds.push(`declaration: send at line ${n} (steps[${sendIdx}]) is not granted a catalogue primitive of class "write"`);
624
+ }
625
+
626
+ const earlierAskLines = askLines.filter((a) => a < n);
627
+ if (earlierAskLines.length === 0) {
628
+ reds.push(`declaration: send at line ${n} (steps[${sendIdx}]) has no signed ask at an earlier line to read from`);
629
+ } else {
630
+ const earlierAskEmits = earlierAskLines
631
+ .map((a) => stepInfo.find((st) => st.fromLine === a))
632
+ .filter((st) => st !== undefined)
633
+ .map((st) => st.emits);
634
+ const readsAnAsk = earlierAskEmits.some((emits) => emits !== null && sendStep.reads.includes(emits));
635
+ if (!readsAnAsk) {
636
+ reds.push(`declaration: send at line ${n} (steps[${sendIdx}]) does not read the emits of any earlier signed `
637
+ + `ask step (asks at lines ${earlierAskLines.join(', ')})`);
638
+ }
639
+ }
640
+ }
641
+
642
+ // --- check 6: every numbered line must be served or refused, never dropped
643
+ const claimedLines = new Set(stepInfo.map((st) => st.fromLine).filter((n) => Number.isInteger(n)));
644
+ for (const line of safeLines) {
645
+ if (!claimedLines.has(line.n) && !refusedLines.has(line.n)) {
646
+ reds.push(`declaration: job line ${line.n} ("${line.text}") is neither served by any step's fromLine nor refused with a reason`);
647
+ }
648
+ }
649
+
650
+ if (reds.length > 0) return deepFreeze({ ok: false, reds });
651
+
652
+ const classes = {};
653
+ stepInfo.forEach((st) => {
654
+ if (st.emits !== null) classes[st.emits] = st.effectiveClass;
655
+ });
656
+ return deepFreeze({ ok: true, classes });
657
+ }
658
+
659
+ function deepFreeze(value) {
660
+ if (value && typeof value === 'object' && !Object.isFrozen(value)) {
661
+ Object.freeze(value);
662
+ for (const key of Object.keys(value)) deepFreeze(value[key]);
663
+ }
664
+ return value;
665
+ }