fwdloop 0.13.0 → 0.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/closers.js CHANGED
@@ -37,18 +37,19 @@
37
37
  // casualty, never a red — bareloop F17); an internal error while
38
38
  // resolving is `crash`.
39
39
  //
40
- // SOFTGREEN (compose) step artifact: `{ text: string, lines?: string[] }`
41
- // - `text` is the whole composed text; `maxWords`/`sections` (F38's
42
- // `closeWordsAndSections`) run over it directly.
40
+ // SOFTGREEN (compose) step artifact: `{ text: string }`
41
+ // - `text` is the whole composed text; `maxWords`/`sections`/`wordsPerSection` run over it directly. Since M4e amendment 18 these
42
+ // soft checks run on bareguard's rubric (`softgreenSpec`), reported in our own words (`renderSoftgreenGaps`).
43
43
  // - `linesPerInvoice`/`mustCarry` (new here, M0 had no equivalent —
44
44
  // M0's own `closeCompose` checked citations+brackets, which M2's
45
45
  // `green` class already covers; this piece's `mustCarry` check is
46
46
  // the text-shape half only) group `text`'s own non-empty lines into
47
47
  // blocks of `linesPerInvoice` lines and require every `mustCarry`
48
48
  // string to appear (case-insensitive substring) in each block.
49
- // - What this LEAVES OUT (named, not silently assumed): the optional
50
- // `lines` field is never cross-checked against `text` itself, and
51
- // `mustCarry` is a substring match on the block's own words, never a
49
+ // - Any key besides `text` (done/blocker are stripped before the close)
50
+ // is refused red by name: the check reads `text` only, so an answer
51
+ // placed elsewhere must never pass or hide.
52
+ // - What this LEAVES OUT (named, not silently assumed): `mustCarry` is a substring match on the block's own words, never a
52
53
  // citation-level check that the carried figure is the RIGHT figure —
53
54
  // that grounding is `green`'s job, on a different step, per the
54
55
  // signed scope ("close by declared class, one closer per class").
@@ -61,6 +62,8 @@
61
62
  // reading, flagged there as an interpretation call, not a rule from the
62
63
  // signed text).
63
64
 
65
+ import { createRubric, checkStep } from 'bareguard';
66
+
64
67
  /** @typedef {import('./types.js').CloseVerdict} CloseVerdict */
65
68
 
66
69
  const FORMULAS = Object.freeze({
@@ -244,109 +247,127 @@ export function closeGreen(artifact, ctx) {
244
247
  }
245
248
 
246
249
  /**
247
- * The declared-shape word-cap + ordered-sections check, F38 version (every
248
- * failing check reported, not just the first). Identical rules to
249
- * poc/m0/shape.mjs's own `closeWordsAndSections`.
250
+ * M4e amendment 18: the soft checks run on bareguard 0.21.0. `softgreenSpec(shape)` is the ONE place a declared shape
251
+ * becomes a rubric spec (signing and the run both build through `buildSoftgreenRubric`, so a shape that signs is a shape
252
+ * that builds). The checks are in this fixed order, which is the order their sentences read in:
253
+ * allowedKeys, maxWords, sectionOrder, sectionWords, blockLines.
254
+ * A key that is declared at all gets its check built, so a half-declared shape (wordsPerSection with no sections, one of
255
+ * linesPerInvoice/mustCarry) cannot build and is a crash at run time, never silently skipped.
250
256
  *
251
- * @param {unknown} text
252
- * @param {{ maxWords: number, sections: string[] }} declared
253
- * @returns {CloseVerdict}
257
+ * @param {Record<string, any>} shape
254
258
  */
255
- export function closeWordsAndSections(text, { maxWords, sections }) {
256
- if (typeof text !== 'string') {
257
- return { verdict: 'unparseable', red: `expected string text, got ${text === null ? 'null' : typeof text}` };
258
- }
259
-
260
- const lines = text.split(/\r?\n/);
261
- const reds = /** @type {string[]} */ ([]);
262
-
263
- let wordCount = 0;
264
- for (const line of lines) {
265
- const stripped = line.replace(/^#+\s*/, '');
266
- const words = stripped.split(/\s+/).filter((w) => w.length > 0);
267
- wordCount += words.length;
268
- }
269
- if (Number.isFinite(maxWords) && wordCount > maxWords) {
270
- reds.push(`${wordCount} words, limit ${maxWords}`);
271
- }
272
-
273
- const headingLines = lines
274
- .map((line) => line.replace(/^#+\s*/, '').replace(/:\s*$/, '').trim().toLowerCase())
275
- .filter((l) => l.length > 0);
276
-
277
- let searchFrom = 0;
278
- for (const section of sections ?? []) {
279
- const want = section.trim().toLowerCase();
280
- const foundAt = headingLines.indexOf(want, searchFrom);
281
- if (foundAt === -1) {
282
- const anywhere = headingLines.indexOf(want);
283
- if (anywhere === -1) {
284
- reds.push(`no line is exactly the heading "${section}" (a heading is a line that is only that text, optionally after #)`);
285
- } else {
286
- reds.push(`section heading "${section}" is out of order`);
287
- }
288
- } else {
289
- searchFrom = foundAt + 1;
290
- }
259
+ export function softgreenSpec(shape) {
260
+ /** @type {Record<string, any>[]} */
261
+ const checks = [{ id: 'keys', rule: 'allowedKeys', keys: ['text'] }];
262
+ if (shape.maxWords !== undefined) checks.push({ id: 'words', rule: 'maxWords', field: 'text', value: shape.maxWords });
263
+ if (shape.sections !== undefined) checks.push({ id: 'sections', rule: 'sectionOrder', field: 'text', names: shape.sections });
264
+ if (shape.wordsPerSection !== undefined) checks.push({ id: 'perSection', rule: 'sectionWords', field: 'text', names: shape.sections, wordsPerSection: shape.wordsPerSection });
265
+ if (shape.linesPerInvoice !== undefined || shape.mustCarry !== undefined) {
266
+ checks.push({ id: 'lines', rule: 'blockLines', field: 'text', size: shape.linesPerInvoice, phrases: shape.mustCarry });
291
267
  }
268
+ return { schema: 1, goal: 'softgreen', checkpoints: { close: { gating: true, checks } } };
269
+ }
292
270
 
293
- if (reds.length > 0) return { verdict: 'red', red: reds.join('; '), reds };
294
- return { verdict: 'green', reds: [] };
271
+ /** Throws bareguard's `invalid rubric: ...` for a shape it cannot build. @param {Record<string, any>} shape @returns {ReturnType<typeof createRubric>} */
272
+ export function buildSoftgreenRubric(shape) {
273
+ return createRubric(softgreenSpec(shape));
295
274
  }
296
275
 
276
+ const partAfter = (item) => item.slice(item.indexOf(':') + 1);
277
+
297
278
  /**
298
- * `linesPerInvoice`/`mustCarry`: group `text`'s own non-empty lines into
299
- * blocks of `linesPerInvoice` lines; every `mustCarry` string must appear
300
- * (case-insensitive substring) somewhere in each block. Returns an array of
301
- * red strings (empty when clean) — the caller folds these into its own
302
- * `reds` list alongside `closeWordsAndSections`'s.
279
+ * The ONE render function (amendment 18 item 4A): bareguard's typed gaps in, fwdloop's plain-English sentences out, byte for byte
280
+ * what the hand-written checks said before the switch (test/m4e-am18-parity.test.js proves it on 142 inputs); past bareguard's own
281
+ * offender-list bound the "N more" tail is ours (amendment 19 2), derived from each gap's `itemsTotal` and list length, never a number.
282
+ * What it throws away: bareguard bounds every offender list; past that the sentence says how many more there were.
283
+ * A gap it has no sentence for is still a red, worded generically, never dropped.
284
+ *
285
+ * @param {any[]} gaps
286
+ * @param {{ linesPerInvoice?: number, mustCarry?: string[] }} shape
287
+ * @returns {{ red: string, reds: string[] }}
303
288
  */
304
- export function closeLinesAndCarry(text, { linesPerInvoice, mustCarry }) {
305
- const lines = text.split(/\r?\n/).filter((l) => l.trim().length > 0);
306
- const reds = [];
307
- if (lines.length === 0) {
308
- reds.push('text has no non-empty lines to check against linesPerInvoice');
309
- return reds;
289
+ export function renderSoftgreenGaps(gaps, shape) {
290
+ const extra = gaps.find((g) => g.check === 'allowedKeys');
291
+ if (extra) {
292
+ // The answer sits in the wrong place: nothing else is judged until it is in "text".
293
+ const keys = extra.keys ?? [];
294
+ const moreKeys = (extra.itemsTotal ?? keys.length) - keys.length;
295
+ return {
296
+ red: `softgreen artifact has key(s) ${keys.map((k) => `"${k}"`).join(', ')}${moreKeys > 0 ? ` and ${moreKeys} more` : ''} besides "text"; the check reads "text" only, so put the whole answer in "text"`,
297
+ reds: [`extra key(s): ${keys.join(', ')}${moreKeys > 0 ? ` and ${moreKeys} more` : ''}`],
298
+ };
310
299
  }
311
- if (lines.length % linesPerInvoice !== 0) {
312
- reds.push(`text has ${lines.length} non-empty line(s), not a multiple of linesPerInvoice ${linesPerInvoice}`);
313
- }
314
- for (let i = 0; i < lines.length; i += linesPerInvoice) {
315
- const block = lines.slice(i, i + linesPerInvoice).join(' ');
316
- for (const must of mustCarry ?? []) {
317
- if (!block.toLowerCase().includes(String(must).toLowerCase())) {
318
- reds.push(`invoice block starting at line ${i + 1} is missing "${must}"`);
300
+ const reds = [];
301
+ let moreSections = 0;
302
+ const sectionWordGaps = gaps.filter((g) => g.check === 'sectionWords');
303
+ for (const g of gaps) {
304
+ const kinds = String(g.kind ?? '').split(',');
305
+ if (g.check === 'maxWords') {
306
+ reds.push(`${g.measured} words, limit ${g.limit}`);
307
+ } else if (g.check === 'sectionOrder' && Array.isArray(g.items)) {
308
+ for (const it of g.items) {
309
+ const name = partAfter(it);
310
+ reds.push(it.startsWith('missing:')
311
+ ? `no line is exactly the heading "${name}" (a heading is a line that is only that text, optionally after #)`
312
+ : `section heading "${name}" is out of order`);
319
313
  }
314
+ if (g.itemsTotal) reds.push(`${g.itemsTotal - g.items.length} more section(s) are missing or out of order`);
315
+ } else if (g.check === 'sectionWords') {
316
+ reds.push(`${g.section}: ${g.words} words, about ${g.asked} asked (${g.lo}-${g.hi})`);
317
+ moreSections = Math.max(moreSections, (g.itemsTotal ?? 0) - sectionWordGaps.length);
318
+ } else if (g.check === 'blockLines') {
319
+ if (kinds.includes('zero-lines')) reds.push('text has no non-empty lines to check against linesPerInvoice');
320
+ if (kinds.includes('not-multiple')) reds.push(`text has ${g.measured} non-empty line(s), not a multiple of linesPerInvoice ${g.limit}`);
321
+ for (const it of g.items ?? []) {
322
+ const block = Number(/^block (\d+):/.exec(it)?.[1]);
323
+ reds.push(`invoice block starting at line ${(block - 1) * (shape.linesPerInvoice ?? 1) + 1} is missing "${partAfter(it)}"`);
324
+ }
325
+ // bareguard lists (block, word) misses and bounds the list; the tail counts the missing words it left out (amendment 20)
326
+ const moreWords = (g.itemsTotal ?? 0) - (g.items?.length ?? 0);
327
+ if (moreWords > 0) reds.push(`${moreWords} more missing word(s)`);
328
+ } else {
329
+ reds.push(`the ${g.check} check failed (${g.kind ?? 'no detail'})`);
320
330
  }
321
331
  }
322
- return reds;
332
+ if (moreSections > 0) reds.push(`${moreSections} more section(s) are outside the range`);
333
+ return { red: reds.join('; '), reds };
334
+ }
335
+
336
+ /** What the artifact looks like in a message, without ever throwing on a hostile object. */
337
+ function describeArtifact(artifact) {
338
+ try { return JSON.stringify(artifact); } catch { return '[an object that cannot be read]'; }
323
339
  }
324
340
 
325
341
  /**
326
- * `softgreen` close: dispatches to `closeWordsAndSections` (when the shape
327
- * declares `maxWords`/`sections`) and/or `closeLinesAndCarry` (when it
328
- * declares `linesPerInvoice`/`mustCarry`) and reports every failing check
329
- * from both, one sentence each (F38's rule, never widened to first-red-only).
342
+ * `softgreen` close: the declared shape (`maxWords`, `sections`, `wordsPerSection`, `linesPerInvoice` + `mustCarry`, and the
343
+ * one-key rule) is checked by bareguard's rubric (amendment 18 item 1) and every failing check is reported, one sentence each
344
+ * (F38's rule, never widened to first-red-only). Our front door stays: an answer that is not `{text: string}` is `unparseable`
345
+ * before bareguard sees it. A shape that cannot be built, or a check that stopped, is `crash`: never green.
346
+ * Async because bareguard's `checkStep` is.
330
347
  *
331
348
  * @param {any} artifact
332
- * @param {{ maxWords?: number, sections?: string[], linesPerInvoice?: number, mustCarry?: string[] }} shape
333
- * @returns {CloseVerdict}
349
+ * @param {{ maxWords?: number, sections?: string[], wordsPerSection?: number, linesPerInvoice?: number, mustCarry?: string[] }} shape
350
+ * @returns {Promise<CloseVerdict>}
334
351
  */
335
- export function closeSoftgreen(artifact, shape) {
336
- if (!artifact || typeof artifact !== 'object' || typeof artifact.text !== 'string') {
337
- return /** @type {CloseVerdict} */ ({ verdict: 'unparseable', red: `softgreen artifact must be an object shaped {text: string}, got ${JSON.stringify(artifact)}` });
352
+ export async function closeSoftgreen(artifact, shape) {
353
+ let text;
354
+ try {
355
+ text = artifact && typeof artifact === 'object' ? artifact.text : undefined;
356
+ } catch {
357
+ text = undefined;
358
+ }
359
+ if (typeof text !== 'string') {
360
+ return /** @type {CloseVerdict} */ ({ verdict: 'unparseable', red: `softgreen artifact must be an object shaped {text: string}, got ${describeArtifact(artifact)}` });
338
361
  }
339
362
  try {
340
- const reds = /** @type {string[]} */ ([]);
341
- if (shape.maxWords !== undefined || shape.sections !== undefined) {
342
- const wc = closeWordsAndSections(artifact.text, { maxWords: shape.maxWords ?? Infinity, sections: shape.sections ?? [] });
343
- if (wc.verdict === 'unparseable') return /** @type {CloseVerdict} */ (wc);
344
- reds.push(...(wc.reds ?? []));
345
- }
346
- if (shape.linesPerInvoice !== undefined && shape.mustCarry !== undefined) {
347
- reds.push(...closeLinesAndCarry(artifact.text, { linesPerInvoice: shape.linesPerInvoice, mustCarry: shape.mustCarry }));
363
+ const rubric = buildSoftgreenRubric(shape);
364
+ const res = await checkStep(rubric, 'close', artifact);
365
+ if (res.verdict === 'stopped') {
366
+ // bareguard's StepResult carries the first fault whenever the verdict is 'stopped' (rubric.js: "the first fault, when stopped").
367
+ const fault = /** @type {NonNullable<typeof res.fault>} */ (res.fault);
368
+ return { verdict: 'crash', red: `softgreen close crashed: the ${fault.id} check stopped (${fault.kind}${fault.detail ? `: ${fault.detail}` : ''})` };
348
369
  }
349
- if (reds.length > 0) return { verdict: 'red', red: reds.join('; '), reds };
370
+ if (res.verdict === 'red') return { verdict: 'red', ...renderSoftgreenGaps(res.gaps, shape) };
350
371
  return { verdict: 'green', red: null, reds: [] };
351
372
  } catch (err) {
352
373
  return { verdict: 'crash', red: `softgreen close crashed: ${err.message}` };
@@ -359,12 +380,12 @@ export function closeSoftgreen(artifact, shape) {
359
380
  * @param {{ close?: { class?: string, shape?: Record<string, any> } }} step
360
381
  * @param {unknown} artifact
361
382
  * @param {{ reads: Record<string, any>, businessDate: string }} ctx
362
- * @returns {CloseVerdict}
383
+ * @returns {Promise<CloseVerdict>}
363
384
  */
364
- export function closeByClass(step, artifact, ctx) {
385
+ export async function closeByClass(step, artifact, ctx) {
365
386
  const cls = step?.close?.class;
366
387
  if (cls === 'green') return closeGreen(artifact, ctx);
367
- if (cls === 'softgreen') return closeSoftgreen(artifact, step?.close?.shape ?? {});
388
+ if (cls === 'softgreen') return await closeSoftgreen(artifact, step?.close?.shape ?? {});
368
389
  if (cls === 'hitl') return { verdict: 'hitl', red: null };
369
390
  return { verdict: 'crash', red: `closeByClass: unknown close class ${JSON.stringify(cls)}` };
370
391
  }
@@ -36,6 +36,8 @@
36
36
  // No `new RegExp` anywhere in this file — a test in test/signed-text.test.js
37
37
  // greps all of src/ for that, and it must keep passing with this file added.
38
38
 
39
+ import { buildSoftgreenRubric } from './closers.js';
40
+
39
41
  /** @typedef {import('./types.js').Arbiter} Arbiter */
40
42
  /** @typedef {import('./types.js').SignedLine} SignedLine */
41
43
  /** @typedef {import('./types.js').CatalogueEntry} CatalogueEntry */
@@ -99,7 +101,14 @@ function checkOwnKeys(obj, allowed, path, reds) {
99
101
  * name. */
100
102
  export const SHAPE_KEYS = Object.freeze(['maxWords', 'sections', 'linesPerInvoice', 'mustCarry']);
101
103
 
104
+ /** Shape keys only the MACHINE sets (M4e amendment 15): read from the line's guardrail, never offered to the drafter's model. */
105
+ export const MACHINE_SHAPE_KEYS = Object.freeze(['wordsPerSection']);
106
+
102
107
  const SHAPE_TYPE_CHECKS = Object.freeze({
108
+ wordsPerSection: {
109
+ expected: 'a positive integer',
110
+ check: (v) => Number.isInteger(v) && v > 0,
111
+ },
103
112
  maxWords: {
104
113
  expected: 'a positive integer',
105
114
  check: (v) => Number.isInteger(v) && v > 0,
@@ -148,7 +157,7 @@ function checkShapeKeys(shape, path, reds) {
148
157
  const value = shape[key];
149
158
  if (ARBITER_KEYS.includes(key)) {
150
159
  reds.push(`declaration: arbiter field "${key}" at ${childPath} — the drafter cannot author it`);
151
- } else if (!SHAPE_KEYS.includes(key)) {
160
+ } else if (!SHAPE_KEYS.includes(key) && !MACHINE_SHAPE_KEYS.includes(key)) {
152
161
  reds.push(`declaration: unknown shape key "${key}" at ${childPath}`);
153
162
  } else {
154
163
  const typeCheck = SHAPE_TYPE_CHECKS[key];
@@ -241,30 +250,64 @@ function deriveFromLine(fromLine, lines, guardrailClasses) {
241
250
  return { ok: true, class: resolved.class, line };
242
251
  }
243
252
 
244
- /** The first "<n> words" in a guardrail ("3 sections, all under 600 words" -> 600), or null. */
245
- function guardrailWordLimit(guardrail) {
246
- const m = typeof guardrail === 'string' ? /(\d+)\s*words?\b/i.exec(guardrail) : null;
247
- return m ? Number(m[1]) : null;
253
+ /** M4e amendment 16 C14: a guardrail number, with or without thousands separators ("1,000" -> 1000). Commas must group by exactly three
254
+ * ("1,00" and "1,0000" match nothing), and the number cannot start in the middle of another one. */
255
+ const readNumber = (t) => Number(t.replace(/,/g, ''));
256
+
257
+ /** Every whole-output word number in a guardrail ("3 sections, under 600 words, each heading at most 3 words" -> [600, 3]), in order; [] when
258
+ * there is none. Code does not decide which one is the limit: the AI picks `maxWords` and the validator checks the pick is one of these
259
+ * (M4e amendments 28 + 29). A "<n> words each" / "<n> words per section" is the per-section size (amendment 15), never listed here. */
260
+ export function guardrailWordNumbers(guardrail) {
261
+ if (typeof guardrail !== 'string') return [];
262
+ return [...guardrail.matchAll(/(?<![\d,])(\d{1,3}(?:,\d{3})+|\d+)\s*words?\b(?!\s*(?:each|per\s+section)\b)/gi)].map((m) => readNumber(m[1]));
263
+ }
264
+
265
+ /** M4e amendment 15 item 1: the "<n> words each" / "<n> words per section" size in a guardrail ("about 250 words each", "250ish each" -> 250), or null. */
266
+ export function guardrailWordsPerSection(guardrail) {
267
+ const m = typeof guardrail === 'string' ? /(?<![\d,])(\d{1,3}(?:,\d{3})+|\d+)(?:\s*words?|ish(?:\s+words?)?)\s+(?:each|per\s+section)\b/i.exec(guardrail) : null;
268
+ return m ? readNumber(m[1]) : null;
248
269
  }
249
270
 
250
271
  const NUMBER_WORDS = { one: 1, two: 2, three: 3, four: 4, five: 5, six: 6, seven: 7, eight: 8, nine: 9, ten: 10 };
251
272
  /** M4e amendment 7 item 1: the first "<N> sections" in a guardrail (N digits, or the words one..ten), or null. */
252
- function guardrailSectionCount(guardrail) {
273
+ export function guardrailSectionCount(guardrail) {
253
274
  const m = typeof guardrail === 'string' ? /\b(\d+|one|two|three|four|five|six|seven|eight|nine|ten)\s+(?:\w+\s+)?sections?\b/i.exec(guardrail) : null;
254
275
  if (!m) return null;
255
276
  return /^\d+$/.test(m[1]) ? Number(m[1]) : NUMBER_WORDS[m[1].toLowerCase()];
256
277
  }
278
+
279
+ /** M4e amendment 15 item 2: for each line whose guardrail gives a size for each section, a section count AND a word number,
280
+ * size x count more than the LARGEST word number (no possible pick fits) is a red naming the line and the numbers. $0; run before any model
281
+ * call, when there is no AI pick yet (amendment 29). After the draft the AI's `maxWords` is checked in checkShapeFitsJobLine. */
282
+ export function checkGuardrailSums(lines) {
283
+ const reds = [];
284
+ for (const l of Array.isArray(lines) ? lines : []) {
285
+ const per = guardrailWordsPerSection(l?.guardrail);
286
+ const count = guardrailSectionCount(l?.guardrail);
287
+ const nums = guardrailWordNumbers(l?.guardrail);
288
+ const limit = nums.length > 0 ? Math.max(...nums) : null;
289
+ // M4e amendment 16 C13: a size for each section with no number of sections can never be checked.
290
+ if (per !== null && count === null) {
291
+ reds.push(`line ${l.n}'s guardrail gives ${per} words for each section but not how many sections. Say the number of sections in the guardrail.`);
292
+ }
293
+ if (per !== null && count !== null && limit !== null && per * count > limit) {
294
+ reds.push(`line ${l.n}'s guardrail asks about ${per} words for each of ${count} sections (${per * count}) but under ${limit} words in total. Change the guardrail.`);
295
+ }
296
+ }
297
+ return reds;
298
+ }
257
299
  const MAX_SECTION_NAME_WORDS = 8;
258
300
  const MAX_SECTION_SHARE_OF_LINE = 0.6;
259
301
  const wordCount = (t) => t.trim().split(/\s+/).filter(Boolean).length;
260
302
 
261
303
  /** M4e amendment 6 item 1 (+ amendment 7 item 1): a step's check cannot fight its own job line. Sections must be found in the line's words
262
- * (case-insensitive substring of the goal, first occurrence) and in the line's order; `maxWords` must equal the line's
263
- * own guardrail limit when that guardrail states one. A shape key a note may still change (mustCarry, linesPerInvoice)
304
+ * (case-insensitive substring of the goal, first occurrence) and in the line's order; `maxWords` (the AI's pick, amendment 29) must be one
305
+ * of the line's guardrail word numbers when that guardrail has any. A shape key a note may still change (mustCarry, linesPerInvoice)
264
306
  * is untouched. Pushes reds naming the step and both orders/values. */
265
307
  export function checkShapeFitsJobLine(step, i, lines, reds) {
266
308
  const { shape } = step.close;
267
309
  const label = `steps[${i}]`;
310
+ const redsBefore = reds.length;
268
311
  const line = Number.isInteger(step.fromLine) ? lines.find((l) => l.n === step.fromLine) : undefined;
269
312
  if (Array.isArray(shape.sections) && shape.sections.every((n) => typeof n === 'string' && n.length > 0) && typeof step.goal === 'string') {
270
313
  const goal = step.goal.toLowerCase().replace(/\s+/g, ' ');
@@ -302,9 +345,61 @@ export function checkShapeFitsJobLine(step, i, lines, reds) {
302
345
  if (x !== y && a.includes(b)) reds.push(`declaration: ${label}.close.shape.sections "${names[x]}" contains "${names[y]}" — one section name may not contain another`);
303
346
  }));
304
347
  }
305
- const limit = guardrailWordLimit(line?.guardrail);
306
- if (limit !== null && shape.maxWords !== undefined && shape.maxWords !== limit) {
307
- reds.push(`declaration: ${label} the job line's guardrail says ${limit} words; the check says ${shape.maxWords} — change the guardrail on the card to change the limit`);
348
+ // M4e amendment 15 item 1: wordsPerSection is the guardrail's number, set by the machine; it never differs from it.
349
+ const wantPer = guardrailWordsPerSection(line?.guardrail);
350
+ if (shape.wordsPerSection !== undefined && shape.wordsPerSection !== wantPer) {
351
+ reds.push(`declaration: ${label} the check has wordsPerSection ${shape.wordsPerSection}; the guardrail says ${wantPer === null ? 'no size for each section' : `${wantPer} words each`} — change the guardrail on the card to change it`);
352
+ } else if (shape.wordsPerSection === undefined && wantPer !== null) {
353
+ reds.push(`declaration: ${label} the guardrail says ${wantPer} words each; the check has no wordsPerSection`);
354
+ }
355
+ // M4e amendment 16 C13: a size for each section needs the section names to be checked against.
356
+ if (shape.wordsPerSection !== undefined && !(Array.isArray(shape.sections) && shape.sections.length > 0)) {
357
+ reds.push(`declaration: ${label}.close.shape has wordsPerSection but no sections — it needs the section names to check each one`);
358
+ }
359
+ // M4e amendment 16 C12: linesPerInvoice and mustCarry only work as a pair.
360
+ if ((shape.linesPerInvoice === undefined) !== (shape.mustCarry === undefined)) {
361
+ const have = shape.linesPerInvoice === undefined ? 'mustCarry' : 'linesPerInvoice';
362
+ const miss = shape.linesPerInvoice === undefined ? 'linesPerInvoice' : 'mustCarry';
363
+ reds.push(`declaration: ${label}.close.shape has ${have} but no ${miss} — they work as a pair, so the check needs both`);
364
+ }
365
+ // M4e amendments 28 + 29: maxWords is the AI's pick; it must be one of the guardrail's whole-output word numbers, or it is invented.
366
+ const nums = guardrailWordNumbers(line?.guardrail);
367
+ if (nums.length > 0 && shape.maxWords !== undefined && !nums.includes(shape.maxWords)) {
368
+ reds.push(`declaration: line ${line.n}'s check says ${shape.maxWords} words; the guardrail has no ${shape.maxWords}.`);
369
+ } else if (wantPer !== null && shape.maxWords !== undefined && Array.isArray(shape.sections) && shape.sections.length > 0 && wantPer * shape.sections.length > shape.maxWords) {
370
+ // am29: after the draft the sum uses the AI's pick (the $0 check before the draft can only use the largest candidate).
371
+ reds.push(`declaration: line ${line.n}'s guardrail asks about ${wantPer} words for each of ${shape.sections.length} sections (${wantPer * shape.sections.length}) but the check says ${shape.maxWords} words in total. Change the guardrail.`);
372
+ }
373
+ // M4e amendment 18 item 3: a shape bareguard will not build is red here, by name, not a crash at run time.
374
+ checkShapeBuilds(shape, label, reds, redsBefore);
375
+ }
376
+
377
+ /** bareguard refuses a signed name or phrase past this many characters (rubric MAX_SIGNED_LEN). */
378
+ const MAX_SIGNED_ENTRY = 1000;
379
+
380
+ /** What bareguard's rubric builder refuses that the type checks above let through: blank or over-long entries and a section
381
+ * name ending in ":" (a heading's ":" is dropped from the line, never from the name, so it could never match). Anything it
382
+ * still refuses is caught by trying the real builder, `buildSoftgreenRubric` (the same one the run uses), when nothing else
383
+ * was red for this step: so a shape that passes here always builds at run time. */
384
+ function checkShapeBuilds(shape, label, reds, redsBefore) {
385
+ for (const key of ['sections', 'mustCarry']) {
386
+ if (!Array.isArray(shape[key])) continue;
387
+ shape[key].forEach((entry, k) => {
388
+ if (typeof entry !== 'string' || entry.length === 0) return; // the type check already reds these
389
+ const at = `${label}.close.shape.${key}[${k}]`;
390
+ if (entry.trim() === '') reds.push(`declaration: ${at} is blank — every entry needs real text`);
391
+ else if (entry.length > MAX_SIGNED_ENTRY) reds.push(`declaration: ${at} is ${entry.length} characters; the most one entry may be is ${MAX_SIGNED_ENTRY}`);
392
+ else if (key === 'sections' && entry.trim().endsWith(':')) {
393
+ reds.push(`declaration: ${at} names "${entry}", which ends in ":" and can never match a heading (the ":" is dropped from the heading line, not from the name) — drop the ":"`);
394
+ }
395
+ });
396
+ }
397
+ const typesOk = Object.keys(shape).every((k) => SHAPE_TYPE_CHECKS[k]?.check(shape[k]) === true);
398
+ if (reds.length !== redsBefore || !typesOk) return;
399
+ try {
400
+ buildSoftgreenRubric(shape);
401
+ } catch (err) {
402
+ reds.push(`declaration: ${label}.close.shape cannot be built into a check — ${String(err.message).replace(/^invalid rubric: /, '')}`);
308
403
  }
309
404
  }
310
405
 
@@ -366,6 +461,7 @@ export function validateDeclaration(declaration, context = {}) {
366
461
  return deepFreeze({ ok: false, reds });
367
462
  }
368
463
  const { steps } = declaration;
464
+ if (fitJobLine === true) reds.push(...checkGuardrailSums(safeLines).map((r) => `declaration: ${r}`));
369
465
 
370
466
  // --- guardrailClasses (REQUIRED — the harness always writes it; empty {}
371
467
  // is fine, missing entirely is not) ------------------------------------
@@ -394,6 +490,8 @@ export function validateDeclaration(declaration, context = {}) {
394
490
  let unjudgeable = {};
395
491
  if (!Object.prototype.hasOwnProperty.call(declaration, 'unjudgeable')) {
396
492
  reds.push('declaration: "unjudgeable" is required (an object keyed by line number; {} is fine)');
493
+ } else if (Array.isArray(declaration.unjudgeable) && declaration.unjudgeable.length === 0) {
494
+ // am41 item 1 (F63): an empty list carries no data; it counts as {}. A non-empty list falls to the red below.
397
495
  } else if (isPlainObject(declaration.unjudgeable)) {
398
496
  unjudgeable = declaration.unjudgeable;
399
497
  for (const [key, reason] of Object.entries(unjudgeable)) {
@@ -589,6 +687,12 @@ export function validateDeclaration(declaration, context = {}) {
589
687
  }
590
688
  }
591
689
 
690
+ // M4e amendment 15 item 5: a step whose check reads its reply (softgreen) gets no `write` — the answer would land in a file the check never reads.
691
+ if (fitJobLine === true && effectiveClass === 'softgreen' && primitives !== null
692
+ && primitives.some((v) => typeof v === 'string' && catalogueByVerb.get(v)?.class === 'write')) {
693
+ reds.push(`declaration: step ${i + 1}'s check reads its reply, so it can't write files. The send step writes the result out.`);
694
+ }
695
+
592
696
  // picks — the listing rule, generalised
593
697
  if (step.picks !== undefined) {
594
698
  if (!isPlainObject(step.picks)) {