fwdloop 0.12.0 → 0.14.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.
Files changed (62) hide show
  1. package/bin/fwdloop +155 -27
  2. package/package.json +2 -2
  3. package/src/ask.js +3 -0
  4. package/src/authoring.js +135 -16
  5. package/src/books.js +23 -2
  6. package/src/canrun.js +106 -0
  7. package/src/catalogue.json +2 -2
  8. package/src/checked.js +50 -0
  9. package/src/closers.js +112 -91
  10. package/src/config.js +2 -1
  11. package/src/declaration.js +175 -3
  12. package/src/drafter.js +148 -10
  13. package/src/draftspend.js +70 -0
  14. package/src/flow.js +43 -0
  15. package/src/keysfile.js +4 -2
  16. package/src/liveness.js +1 -1
  17. package/src/model-step.js +31 -5
  18. package/src/monthly.js +195 -28
  19. package/src/panel/author.js +638 -0
  20. package/src/panel/authorcard.js +340 -0
  21. package/src/panel/authorflows.js +317 -0
  22. package/src/panel/authorresume.js +149 -0
  23. package/src/panel/authorstart.js +257 -0
  24. package/src/panel/authorvalues.js +110 -0
  25. package/src/panel/data.js +318 -99
  26. package/src/panel/index.html +2000 -330
  27. package/src/panel/resume.js +6 -8
  28. package/src/panel/server.js +122 -119
  29. package/src/panel/settings.js +8 -6
  30. package/src/panel/spawn.js +77 -0
  31. package/src/provider.js +12 -17
  32. package/src/runner.js +707 -104
  33. package/src/runvalues.js +178 -0
  34. package/src/send.js +10 -3
  35. package/src/setup.js +127 -0
  36. package/types/authoring.d.ts +56 -2
  37. package/types/books.d.ts +14 -2
  38. package/types/canrun.d.ts +64 -0
  39. package/types/checked.d.ts +23 -0
  40. package/types/closers.d.ts +47 -28
  41. package/types/config.d.ts +1 -0
  42. package/types/declaration.d.ts +23 -1
  43. package/types/drafter.d.ts +151 -2
  44. package/types/draftspend.d.ts +21 -0
  45. package/types/flow.d.ts +23 -0
  46. package/types/liveness.d.ts +2 -2
  47. package/types/model-step.d.ts +4 -7
  48. package/types/monthly.d.ts +46 -1
  49. package/types/panel/author.d.ts +316 -0
  50. package/types/panel/authorcard.d.ts +142 -0
  51. package/types/panel/authorflows.d.ts +175 -0
  52. package/types/panel/authorresume.d.ts +32 -0
  53. package/types/panel/authorstart.d.ts +115 -0
  54. package/types/panel/authorvalues.d.ts +62 -0
  55. package/types/panel/data.d.ts +105 -63
  56. package/types/panel/server.d.ts +11 -33
  57. package/types/panel/spawn.d.ts +30 -0
  58. package/types/provider.d.ts +6 -9
  59. package/types/runner.d.ts +129 -6
  60. package/types/runvalues.d.ts +97 -0
  61. package/types/send.d.ts +5 -1
  62. package/types/setup.d.ts +77 -0
package/src/books.js CHANGED
@@ -21,7 +21,7 @@
21
21
  import { appendFileSync, mkdirSync } from 'node:fs';
22
22
  import { dirname, join } from 'node:path';
23
23
 
24
- import { readFileInside } from './flow.js';
24
+ import { readFileInside, readdirInside } from './flow.js';
25
25
 
26
26
  function appendLine(filePath, row) {
27
27
  mkdirSync(dirname(filePath), { recursive: true });
@@ -33,7 +33,7 @@ function appendLine(filePath, row) {
33
33
  * rewritten, not a book the arbiter reads. One row per process that works on
34
34
  * the run (`src/liveness.js` `recordPid` builds the row).
35
35
  * @param {string} runDir
36
- * @param {{pid: number, startedAt: string, procStart: string|null, leg: 'run'|'resume'}} row
36
+ * @param {{pid: number, startedAt: string, procStart: string|null, leg: 'run'|'resume'|'continue'}} row
37
37
  */
38
38
  export function appendPidRow(runDir, row) {
39
39
  appendLine(join(runDir, 'pids.jsonl'), row);
@@ -301,3 +301,24 @@ export function appendHistory(flowDir, row) {
301
301
  export function readHistory(flowDir) {
302
302
  return readLines(flowDir, 'history.jsonl');
303
303
  }
304
+
305
+ /** The two outcomes a run can be continued from (M4e amendment 4 item 4): the runner leaves `halt.json` for them. */
306
+ export const HALT_OUTCOMES = Object.freeze(['cap-halt', 'stopped']);
307
+
308
+ /**
309
+ * The ONE rule for "how did this run end": the LAST history row of the run (a run that was stopped or cap-halted and
310
+ * continued has one row per leg; history stays append-only). `null` when the run has no row yet, and also while a
311
+ * continue is in flight: the last row is a halt row, `halt.json` is gone (the continue consumed it by rename to
312
+ * `halt.<n>.consumed.json`) — an older halt row is then not the run's end. A run halted before halt records existed has
313
+ * no consumed file, so its halt row stays final.
314
+ * @param {any[]} historyRows `readHistory`'s rows @param {string} runDir @param {string} runId
315
+ * @returns {any|null}
316
+ */
317
+ export function endRow(historyRows, runDir, runId) {
318
+ let last = null;
319
+ for (const r of historyRows) if (r && r.runId === runId) last = r;
320
+ if (last === null || !HALT_OUTCOMES.includes(last.outcome)) return last;
321
+ const names = readdirInside(runDir, '.');
322
+ const continuing = !names.includes('halt.json') && names.some((n) => /^halt\.\d+\.consumed\.json$/.test(n));
323
+ return continuing ? null : last;
324
+ }
package/src/canrun.js ADDED
@@ -0,0 +1,106 @@
1
+ // M4e amendment 7 item 7: the ONE function that decides "can this flow run" — the panel's Signed flow list reads it, and the run's own
2
+ // preflight refusal says the same words. A flow the run would refuse at preflight (a signature that does not check out; a step granting a
3
+ // verb with no wired implementation) is not offered. Reads only; writes nothing. `WIRED_VERBS` stays the one list (src/primitives.js).
4
+ import { WIRED_VERBS } from './primitives.js';
5
+ import { buildSoftgreenRubric } from './closers.js';
6
+
7
+ /**
8
+ * The first step granting a verb that has no wired implementation, or null. (A verb absent from the catalogue entirely is caught earlier,
9
+ * at declaration validation inside `readFlow`.)
10
+ * @param {Record<string, any>} declaration `readFlow`'s declaration
11
+ * @returns {{step: {emits: string, fromLine: number}, verb: string}|null}
12
+ */
13
+ export function findUnwiredVerbStep(declaration) {
14
+ for (const step of declaration.steps) {
15
+ for (const verb of step.primitives ?? []) {
16
+ if (!WIRED_VERBS.has(verb)) return { step, verb };
17
+ }
18
+ }
19
+ return null;
20
+ }
21
+
22
+ /** The preflight refusal sentence for an unwired verb, in the words the run's own preflight uses. @param {{step: {emits: string, fromLine: number}, verb: string}} found */
23
+ export function unwiredRed(found) {
24
+ return `preflight: step "${found.step.emits}" (line ${found.step.fromLine}) grants verb "${found.verb}", which has no wired implementation`;
25
+ }
26
+
27
+ /** bareguard refuses a signed name or phrase past this many characters (rubric MAX_SIGNED_LEN). */
28
+ const MAX_ENTRY_CHARS = 1000;
29
+ const SIGN_AGAIN = 'and sign the job again';
30
+ const clipText = (t, n = 40) => (t.length > n ? `${t.slice(0, n)}...` : t);
31
+
32
+ /**
33
+ * M4e amendment 23: the ONE function that turns "this step's check cannot be built" into a plain sentence. It reads the shape, never
34
+ * bareguard's wording, so no `spec.` path or `checks[` index can reach a human. The steps are numbered by the job line they came from
35
+ * ("line 3" elsewhere), so "step 3" is job line 3. What it throws away: the raw reason (kept apart as `detail`) and any second problem
36
+ * in the same shape (the first one found is the one said). A shape it cannot classify gets the generic sentence.
37
+ * @param {number|undefined} n the step's job line
38
+ * @param {Record<string, any>} shape
39
+ * @returns {string}
40
+ */
41
+ export function unbuildableSay(n, shape) {
42
+ const head = `This flow will not run: step ${n}'s`;
43
+ const lists = [['sections', 'section name', 'section list'], ['mustCarry', 'required phrase', 'required-phrase list']];
44
+ for (const [key, one, whole] of lists) {
45
+ const list = shape[key];
46
+ if (!Array.isArray(list)) continue;
47
+ if (list.length === 0) return `${head} ${whole} is empty. Name at least one, or remove the list, ${SIGN_AGAIN}.`;
48
+ for (const entry of list) {
49
+ if (typeof entry !== 'string') continue;
50
+ if (entry.trim() === '') return `${head} ${one} is blank. Fill it in or remove it, ${SIGN_AGAIN}.`;
51
+ if (entry.length > MAX_ENTRY_CHARS) return `${head} ${one} "${clipText(entry)}" is ${entry.length} characters, and the most one may be is ${MAX_ENTRY_CHARS}. Shorten it ${SIGN_AGAIN}.`;
52
+ if (key === 'sections' && entry.trim().endsWith(':')) return `${head} ${one} "${entry}" ends in ':'. Remove the ':' ${SIGN_AGAIN}.`;
53
+ }
54
+ }
55
+ const noSections = !Array.isArray(shape.sections) || shape.sections.length === 0;
56
+ if (shape.wordsPerSection !== undefined && noSections) return `${head} check sets a size for each section but names no sections. Name the sections or remove the size, ${SIGN_AGAIN}.`;
57
+ if ((shape.linesPerInvoice === undefined) !== (shape.mustCarry === undefined)) {
58
+ const have = shape.linesPerInvoice === undefined ? 'the words each invoice must carry' : 'the lines in each invoice';
59
+ return `${head} invoice check has ${have} but not the other half. Add the missing half or remove this one, ${SIGN_AGAIN}.`;
60
+ }
61
+ return `This flow will not run: step ${n}'s check cannot be built. Draft the job again.`;
62
+ }
63
+
64
+ /**
65
+ * M4e amendment 19 4: the first softgreen step whose check bareguard cannot build (a flow signed before amendment 18 may hold one), or null.
66
+ * Built with the same `buildSoftgreenRubric` the close uses, so a step that passes here never crashes at its close for want of a check.
67
+ * `why` is bareguard's raw reason, for the record only (amendment 23); `say` is the plain sentence.
68
+ * @param {Record<string, any>} declaration `readFlow`'s declaration
69
+ * @returns {{step: {emits: string, fromLine: number}, why: string, say: string}|null}
70
+ */
71
+ export function findUnbuildableCheckStep(declaration) {
72
+ for (const step of declaration.steps) {
73
+ if (step.close?.class !== 'softgreen') continue;
74
+ try {
75
+ buildSoftgreenRubric(step.close.shape ?? {});
76
+ } catch (err) {
77
+ return { step, why: String(err.message).replace(/^invalid rubric: /, ''), say: unbuildableSay(step.fromLine, step.close.shape ?? {}) };
78
+ }
79
+ }
80
+ return null;
81
+ }
82
+
83
+ /** The preflight refusal sentence for a check that cannot be built: plain words, never bareguard's (that is `found.why`). @param {{say: string}} found */
84
+ export function unbuildableRed(found) {
85
+ return found.say;
86
+ }
87
+
88
+ /**
89
+ * Can this flow run? `read` is `readFlow`'s result (a failed read — signature, tampering, missing files — is a refusal with its own reds).
90
+ * @param {any} read
91
+ * @returns {{ok: true} | {ok: false, red: string, detail?: string}} `detail` is the raw reason, for the record, never the sentence
92
+ */
93
+ export function canFlowRun(read) {
94
+ if (!read || read.ok !== true) return { ok: false, red: String(read?.reds?.[0] ?? 'the flow does not read') };
95
+ const unwired = findUnwiredVerbStep(read.declaration);
96
+ if (unwired) return { ok: false, red: unwiredRed(unwired) };
97
+ const unbuildable = findUnbuildableCheckStep(read.declaration);
98
+ if (unbuildable) return { ok: false, red: unbuildableRed(unbuildable), detail: unbuildable.why };
99
+ return { ok: true };
100
+ }
101
+
102
+ /** The one sentence for a signed flow that will not run: the panel's run door (the POST /api/author/run 409) and Run again say the same words. The Signed list no longer shows a refused flow. @param {string} flow @param {string} red */
103
+ export function willNotRunSay(flow, red) {
104
+ if (red.startsWith('This flow will not run:')) return red; // amendment 23: already a whole sentence
105
+ return `"${flow}" will not run: ${red}`;
106
+ }
@@ -2,10 +2,10 @@
2
2
  "version": 1,
3
3
  "primitives": [
4
4
  {
5
- "verb": "write", "component": "write", "package": "bare-agent/tools", "symbol": "createShellTools", "tool": "shell_write", "class": "write", "skill": "core", "desc": "Create or overwrite a file with given contents."
5
+ "verb": "write", "component": "write", "package": "bare-agent/tools", "symbol": "createShellTools", "tool": "shell_write", "class": "write", "skill": "core", "desc": "Create or overwrite a file with given contents. Never granted to a step whose check reads its reply (softgreen)."
6
6
  },
7
7
  {
8
- "verb": "edit", "component": "write", "package": "bare-agent/tools", "symbol": "createShellTools", "tool": "shell_edit", "class": "write", "skill": "core", "desc": "Change part of an existing file in place."
8
+ "verb": "edit", "component": "write", "package": "bare-agent/tools", "symbol": "createShellTools", "tool": "shell_edit", "class": "write", "skill": "core", "desc": "Change part of an existing file in place. Never granted to a step whose check reads its reply (softgreen)."
9
9
  },
10
10
  {
11
11
  "verb": "read", "component": "select", "package": "bare-agent/tools", "symbol": "createShellTools", "tool": "shell_read", "class": "read", "skill": "core", "desc": "Read a file's text."
package/src/checked.js ADDED
@@ -0,0 +1,50 @@
1
+ // M4e amendments 24 item 6, 25: "Checked" and "Not checked" at sign.
2
+ //
3
+ // CHECKED is built here, by code, from the plan's TYPED closes (`close.class` and `close.shape`) — never from model text. It says only what a
4
+ // typed check really does (src/closers.js): `green` recomputes a cited figure; `softgreen` runs the declared shape (headings in order, word
5
+ // ceilings, lines per invoice and the fields each block carries); `hitl` has no content check — a human reads it at the ask. A shape key that is
6
+ // not in SHAPE_KEYS has no sentence, so a key the closers do not run can never be listed as checked.
7
+ //
8
+ // NOT CHECKED is the drafter's own reading (a list of short phrases it wrote in the same call). It is information only: shown with its label,
9
+ // never signed, never in the readout, never in the spec hash. What this throws away: anything the drafter did not list; the list is not complete.
10
+
11
+ /** The label that always sits with the "Not checked" list. */
12
+ export const NOT_CHECKED_LABEL = "the drafter's own reading, not a guarantee";
13
+
14
+ const list = (xs) => xs.join(', ');
15
+
16
+ /**
17
+ * One entry per step, in plan order: the plain sentences for what its typed close checks.
18
+ * @param {{ steps?: any[] }} declaration @param {{ hasAsk?: boolean }} [opts] hasAsk = the job has a signed ask line (so "you check it at the ask" is true)
19
+ * @returns {{ step: number, line: number|null, goal: string, class: string, sentences: string[] }[]}
20
+ */
21
+ export function checkedLines(declaration, { hasAsk = true } = {}) {
22
+ const steps = Array.isArray(declaration?.steps) ? declaration.steps : [];
23
+ return steps.map((st, i) => {
24
+ const cls = st?.close?.class;
25
+ const shape = st?.close?.shape && typeof st.close.shape === 'object' ? st.close.shape : {};
26
+ /** @type {string[]} */
27
+ const out = [];
28
+ if (cls === 'green') {
29
+ out.push('Every figure must cite its source cell, or a formula over cells, and the machine recomputes it and compares it with its source.');
30
+ } else if (cls === 'softgreen') {
31
+ out.push('The reply is checked as plain text only.');
32
+ if (Number.isInteger(shape.maxWords)) out.push(`The whole output is under ${shape.maxWords} words.`);
33
+ if (Array.isArray(shape.sections) && shape.sections.length > 0) out.push(`These section headings are there, in this order: ${list(shape.sections)}.`);
34
+ if (Number.isInteger(shape.wordsPerSection) && Array.isArray(shape.sections) && shape.sections.length > 0) out.push(`Each of those sections is about ${shape.wordsPerSection} words.`);
35
+ if (Number.isInteger(shape.linesPerInvoice)) out.push(`The output comes in blocks of ${shape.linesPerInvoice} lines.`);
36
+ if (Array.isArray(shape.mustCarry) && shape.mustCarry.length > 0) out.push(`Every block carries: ${list(shape.mustCarry)}.`);
37
+ } else {
38
+ out.push(hasAsk ? 'No machine check of the content: you check it at the ask.' : 'No machine check of the content; the machine checks only that the step happened.');
39
+ }
40
+ return {
41
+ step: i + 1, line: Number.isInteger(st?.fromLine) ? st.fromLine : null, goal: typeof st?.goal === 'string' ? st.goal : '', class: String(cls), sentences: out,
42
+ };
43
+ });
44
+ }
45
+
46
+ /** The "Not checked" block the page shows: always the label, then the drafter's items (an empty list says the drafter listed nothing). @param {unknown} items */
47
+ export function notCheckedBlock(items) {
48
+ const clean = Array.isArray(items) ? items.filter((x) => typeof x === 'string' && x.trim() !== '').map((x) => x.trim()) : [];
49
+ return { label: NOT_CHECKED_LABEL, items: clean };
50
+ }
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
  }
package/src/config.js CHANGED
@@ -3,7 +3,7 @@
3
3
  //
4
4
  // Shape (unknown top-level fields are kept, never dropped):
5
5
  // { "monthlyLimitUsd": <number > 0>, // absent = no limit (piece 3 reads it)
6
- // "prices": { "<slot>": { "inPerM": n, "cachedInPerM": n, "outPerM": n } }, // USD per 1M tokens, each optional
6
+ // "prices": { "<slot>": { "inPerM": n, "cachedInPerM": n, "outPerM": n } }, // USD per 1M tokens, each optional; a saved "cachedInPerM" is tolerated, never read (M4d amendment 2)
7
7
  // "providers": { "<slot>": { "model": "<id>", "shape": "<shape id>", "baseUrl": "" | "http(s)://…" } } } // each optional (M4d amendment 1)
8
8
  // A price is a finite number above 0; 0, a negative, NaN, Infinity or text is a ConfigError
9
9
  // naming the slot and field — on write AND on read, so a hand-edited 0 can never price a call at $0.
@@ -53,6 +53,7 @@ export function configDoorHome() {
53
53
  return { skip: home === undefined, home };
54
54
  }
55
55
 
56
+ /** Fields a config file may hold; `cachedInPerM` stays so an older file still loads, but nothing prices from it. */
56
57
  export const PRICE_FIELDS = Object.freeze(['inPerM', 'cachedInPerM', 'outPerM']);
57
58
  const SLOT_RE = /^[A-Za-z0-9_-]{1,64}$/;
58
59