fwdloop 0.36.0 → 0.37.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 (98) hide show
  1. package/README.md +1 -1
  2. package/bin/fwdloop +5 -2
  3. package/package.json +3 -3
  4. package/src/action-stop.js +1 -1
  5. package/src/auditchecks.js +41 -9
  6. package/src/authoring.js +74 -16
  7. package/src/blockasks.js +10 -12
  8. package/src/blockassemble.js +49 -43
  9. package/src/blockdraft.js +4 -2
  10. package/src/blockpick.js +10 -0
  11. package/src/canrun.js +2 -1
  12. package/src/cardlist.js +28 -5
  13. package/src/checkblock.js +610 -64
  14. package/src/checked.js +28 -33
  15. package/src/checklistsign.js +2 -1
  16. package/src/checklook.js +45 -0
  17. package/src/checkrows.js +202 -0
  18. package/src/cited-record.js +2 -2
  19. package/src/citedcheck.js +53 -12
  20. package/src/citedwords.js +7 -4
  21. package/src/closers.js +49 -2
  22. package/src/declaration.js +26 -4
  23. package/src/drafter.js +85 -61
  24. package/src/factwords.js +7 -4
  25. package/src/globprefix.js +26 -0
  26. package/src/model-step.js +22 -4
  27. package/src/pageask.js +0 -3
  28. package/src/pagedropwords.js +3 -11
  29. package/src/pagedry.js +75 -1
  30. package/src/pagefetch.js +11 -6
  31. package/src/pagelook.js +2 -1
  32. package/src/pagerules.js +8 -2
  33. package/src/panel/author.js +9 -3
  34. package/src/panel/data.js +3 -2
  35. package/src/panel/index.html +143 -33
  36. package/src/panel/result.js +34 -1
  37. package/src/pickrecord.js +14 -0
  38. package/src/planrebuild.js +55 -19
  39. package/src/ratelimit.js +117 -0
  40. package/src/report.js +14 -3
  41. package/src/rowresults.js +111 -0
  42. package/src/rubricstep.js +65 -2
  43. package/src/runner.js +38 -5
  44. package/src/shapebuild.js +281 -0
  45. package/src/shapelook.js +91 -0
  46. package/src/shapemenu.js +64 -0
  47. package/src/shaperesult.js +104 -0
  48. package/src/shaperows.js +263 -0
  49. package/src/shapewords.js +140 -0
  50. package/src/sheetbuild.js +41 -29
  51. package/src/sheetclaims.js +1 -1
  52. package/src/sheetrows.js +10 -64
  53. package/src/ticketrows.js +1 -1
  54. package/src/try-checks.js +39 -6
  55. package/src/types.js +1 -0
  56. package/src/whole-job.js +24 -8
  57. package/types/action-stop.d.ts +1 -1
  58. package/types/auditchecks.d.ts +13 -2
  59. package/types/authoring.d.ts +20 -2
  60. package/types/blockasks.d.ts +6 -10
  61. package/types/blockassemble.d.ts +13 -13
  62. package/types/blockdraft.d.ts +3 -2
  63. package/types/blockpick.d.ts +4 -0
  64. package/types/cardlist.d.ts +18 -2
  65. package/types/checkblock.d.ts +278 -28
  66. package/types/checked.d.ts +15 -6
  67. package/types/checklook.d.ts +36 -0
  68. package/types/checkrows.d.ts +119 -0
  69. package/types/citedcheck.d.ts +4 -2
  70. package/types/closers.d.ts +10 -1
  71. package/types/drafter.d.ts +8 -4
  72. package/types/globprefix.d.ts +5 -0
  73. package/types/model-step.d.ts +43 -2
  74. package/types/pageask.d.ts +0 -1
  75. package/types/pagedropwords.d.ts +0 -1
  76. package/types/pagedry.d.ts +27 -0
  77. package/types/pagefetch.d.ts +3 -2
  78. package/types/pagerules.d.ts +4 -0
  79. package/types/panel/result.d.ts +16 -1
  80. package/types/pickrecord.d.ts +10 -0
  81. package/types/ratelimit.d.ts +59 -0
  82. package/types/report.d.ts +2 -1
  83. package/types/rowresults.d.ts +28 -0
  84. package/types/rubricstep.d.ts +21 -0
  85. package/types/runner.d.ts +3 -1
  86. package/types/shapebuild.d.ts +97 -0
  87. package/types/shapelook.d.ts +76 -0
  88. package/types/shapemenu.d.ts +40 -0
  89. package/types/shaperesult.d.ts +40 -0
  90. package/types/shaperows.d.ts +102 -0
  91. package/types/shapewords.d.ts +43 -0
  92. package/types/sheetbuild.d.ts +31 -13
  93. package/types/sheetclaims.d.ts +1 -0
  94. package/types/sheetrows.d.ts +5 -36
  95. package/types/ticketrows.d.ts +1 -1
  96. package/types/try-checks.d.ts +2 -1
  97. package/types/types.d.ts +4 -0
  98. package/types/whole-job.d.ts +20 -4
@@ -0,0 +1,117 @@
1
+ // borrowed-from: bareloop src/ratelimit.js@v0.61.0 (fc56e1f3) -- copied unchanged (the 429 wait the shape look uses; fwd had no home for it)
2
+ // PRD item 28's parked (a/b) ruling, hamr's verbatim call: "do a/b as a
3
+ // fallback, and verify/validate + no regression." A vendor HTTP 429 is a
4
+ // response — the provider answered, unlike src/transport.js's no-response
5
+ // class — but unlike every other status this repo already declines to retry
6
+ // (4xx/5xx generally, F115's own boundary), a 429 carries the ONE piece of
7
+ // information that turns "retry blindly" into "retry honestly": the vendor's
8
+ // own stated wait. This module is transport.js's SIBLING, not an extension
9
+ // of it — `isTransportFailure` must keep returning FALSE for anything
10
+ // carrying an HTTP status (429 included), and nothing here widens that.
11
+ //
12
+ // This is a FALLBACK, not the primary answer. The primary answer (F139,
13
+ // measured 2026-09-08) is picking a worker model with adequate rate
14
+ // headroom: a 30,000 TPM model (429s deterministically on our workload,
15
+ // 2 of 2 runs), a 200,000 TPM model and a 500,000 TPM model do not.
16
+ // One bounded retry only softens the failure mode when that primary answer
17
+ // was not followed (or headroom was still exceeded); it does not replace it.
18
+
19
+ /** The fixed retry budget: ONE extra attempt after a 429. Never read from a
20
+ * job spec or CLI flag — raising it is arbiter territory, mirroring
21
+ * transport.js's TRANSPORT_RETRIES exactly (tighten-only doctrine). */
22
+ export const RATE_LIMIT_RETRIES = 1;
23
+
24
+ /** bare-agent's `Retry.call` (if ever used) counts ATTEMPTS, not retries;
25
+ * this module's own hand-rolled ladder (src/planrun.js) does the same for
26
+ * symmetry with TRANSPORT_MAX_ATTEMPTS. */
27
+ export const RATE_LIMIT_MAX_ATTEMPTS = RATE_LIMIT_RETRIES + 1;
28
+
29
+ /** The hard cap on how long we will ever wait for a vendor-stated 429 delay.
30
+ * A vendor asking for longer than this is not honoured — we do not retry at
31
+ * all in that case. Waiting that long is the operator's decision, not ours
32
+ * (arbiter territory: nothing here escalates the wait past what hamr set). */
33
+ export const RATE_LIMIT_MAX_WAIT_MS = 60_000;
34
+
35
+ /** Used only when the vendor's message carries no parseable delay at all. */
36
+ export const RATE_LIMIT_DEFAULT_WAIT_MS = 5_000;
37
+
38
+ /** A parsed delay is the EARLIEST moment the vendor's own window resets, not
39
+ * a safe one to fire on the dot — this margin is added to any PARSED value
40
+ * (never to the default) so the retry lands just after the window, not on
41
+ * its leading edge. Never allowed to push a parsed value over the cap. */
42
+ const PARSED_DELAY_MARGIN_MS = 250;
43
+
44
+ /**
45
+ * Is `err` an HTTP 429 (rate-limited) response? True ONLY for an explicit
46
+ * status of 429 on the error itself. Nothing else qualifies — not message
47
+ * text (a message merely containing "429" is not this), not `retryable`,
48
+ * not any other status. Symmetric with `isTransportFailure`'s own status
49
+ * check (src/transport.js), just reading the opposite branch of it.
50
+ * @param {any} err
51
+ * @returns {boolean}
52
+ */
53
+ export function isRateLimited(err) {
54
+ if (err == null) return false;
55
+ const status = err.status ?? err.statusCode;
56
+ return status === 429;
57
+ }
58
+
59
+ /**
60
+ * The vendor's RAW stated wait, in milliseconds, parsed straight from the
61
+ * error message — no default, no margin, no cap. `null` when nothing in the
62
+ * message matches a known shape. Exported separately from `rateLimitWaitMs`
63
+ * so a caller that wants to report the vendor's own number on the spine
64
+ * (`statedMs`) never has to re-derive it from the margin-adjusted figure.
65
+ *
66
+ * bare-agent does not expose the vendor's `retry-after` /
67
+ * `x-ratelimit-reset-*` response headers on the thrown error (BA-26) — the
68
+ * delay exists only in the vendor's English message text, so this parses
69
+ * that text. Verified real shape (a hosted provider, run `8ev2sdkn`, 2026-09-08):
70
+ * "Please try again in 11.996s." This also supports "try again in 1.5
71
+ * seconds", "try again in 20ms", "retry after 30s", and "retry after 30
72
+ * seconds" — case-insensitive.
73
+ * @param {any} err
74
+ * @returns {number|null}
75
+ */
76
+ export function statedWaitMs(err) {
77
+ const message = String(err?.message ?? err ?? '');
78
+ const match = message.match(/(?:try again in|retry after)\s*([\d.]+)\s*(ms|milliseconds?|s|seconds?)?/i);
79
+ if (!match) return null;
80
+
81
+ const value = Number(match[1]);
82
+ if (!Number.isFinite(value) || value < 0) return null;
83
+
84
+ const unit = (match[2] ?? 's').toLowerCase();
85
+ const isMs = unit === 'ms' || unit.startsWith('millisecond');
86
+ return isMs ? value : value * 1000;
87
+ }
88
+
89
+ /**
90
+ * How long to wait before retrying a 429, in milliseconds — or `null`
91
+ * meaning "do not retry at all" (either the parsed wait exceeds
92
+ * `RATE_LIMIT_MAX_WAIT_MS`, in which case waiting that long is the
93
+ * operator's decision, not ours).
94
+ *
95
+ * A parsed value gets `PARSED_DELAY_MARGIN_MS` added (the vendor's stated
96
+ * number is the earliest moment its window resets, not a safe one to fire
97
+ * on), capped so the margin itself can never push a parsed value over
98
+ * `RATE_LIMIT_MAX_WAIT_MS`. When nothing parses, `RATE_LIMIT_DEFAULT_WAIT_MS`
99
+ * is returned as-is, with no margin added (there is nothing to add margin
100
+ * to — it is already a conservative guess, not an earliest-moment reading).
101
+ * @param {any} err
102
+ * @returns {number|null}
103
+ */
104
+ export function rateLimitWaitMs(err) {
105
+ const parsedMs = statedWaitMs(err);
106
+ if (parsedMs === null) {
107
+ return RATE_LIMIT_DEFAULT_WAIT_MS <= RATE_LIMIT_MAX_WAIT_MS ? RATE_LIMIT_DEFAULT_WAIT_MS : null;
108
+ }
109
+
110
+ // The RAW parsed value is what is judged against the cap ("a vendor asking
111
+ // for longer than this is not honoured") — the margin is added only AFTER
112
+ // that gate, and clamped so it can never itself push the result past the
113
+ // cap, but it never turns an already-honoured wait into a refusal.
114
+ if (parsedMs > RATE_LIMIT_MAX_WAIT_MS) return null;
115
+ if (parsedMs === 0) return 0;
116
+ return Math.min(parsedMs + PARSED_DELAY_MARGIN_MS, RATE_LIMIT_MAX_WAIT_MS);
117
+ }
package/src/report.js CHANGED
@@ -7,11 +7,11 @@
7
7
  import { lstatSync } from 'node:fs';
8
8
  import { join } from 'node:path';
9
9
  import { sheetCheckSentence } from './sheetchecks.js';
10
- import { sheetTotalLines, ROW_MATH_OPS } from './sheetclaims.js';
10
+ import { sheetTotalLines, ROW_MATH_OPS, isRec } from './sheetclaims.js';
11
11
  import { lineRules } from './pagebits.js';
12
+ import { shapeResultModel, shapeMarkdown } from './shaperesult.js';
12
13
 
13
14
  const SCALAR = ['string', 'number', 'boolean'];
14
- const isRec = (/** @type {unknown} */ v) => v !== null && typeof v === 'object' && !Array.isArray(v);
15
15
 
16
16
  /** the words under a not-checked answer and a checked one (M15 am3 item 2) */
17
17
  export const NOT_CHECKED_HEADING = '### The AI\'s answer (not checked — you judge it at Accept)';
@@ -159,7 +159,7 @@ function stepSection({ artifact, checks, okIds, tables }) {
159
159
  /**
160
160
  * The body: every line before the send, in job order. A work line is `## <n>. <text>`, a `Rule:` per ~ rule, `### Checked by code` (bullets) and the AI's text under its heading; an Ask line is one line
161
161
  * in its place; a work line with nothing to write has no section. Pure.
162
- * @param {{n: number, kind: 'ask'|'work', text?: string, rules?: string[], artifact?: unknown, checks?: any[], okIds?: Set<string>|null, proseChecked?: boolean}[]} lines
162
+ * @param {{n: number, kind: 'ask'|'work', text?: string, rules?: string[], artifact?: unknown, checks?: any[], okIds?: Set<string>|null, proseChecked?: boolean, shape?: any}[]} lines
163
163
  * @param {Record<string, any>} tables the frozen sheets by input name
164
164
  * @returns {string}
165
165
  */
@@ -168,6 +168,17 @@ export function renderReportBody(lines, tables) {
168
168
  const sections = [];
169
169
  for (const l of lines) {
170
170
  if (l.kind === 'ask') { sections.push(askLineWords(l.n)); continue; }
171
+ // borrowed-from: bareloop src/resultmd.js@v0.61.0 (the shape branch of renderRunMd)
172
+ // a shape line (picked by the line's signed `itemShape`, never by the key `results`, which a facts line also uses): the shape section (M19 amendment C, C1): its heading, the Rule lines, the shape-checks line, the table, the Not checked line.
173
+ // A report is written for a green run only, so no item is red here. The one place a check mark may appear in a report is this table.
174
+ if (isRec(l.shape)) {
175
+ const results = isRec(l.artifact) ? /** @type {Record<string, any>} */ (l.artifact).results : null;
176
+ if (!Array.isArray(results) || results.length === 0) continue;
177
+ const rules = lineRules({ rules: l.rules });
178
+ const head = [`## ${l.n}. ${l.text}`, ...rules.map((r) => `Rule: ${r}`)].join('\n');
179
+ sections.push([head, shapeMarkdown(shapeResultModel({ part: l.shape, results, rules }))].join('\n\n'));
180
+ continue;
181
+ }
171
182
  const sec = stepSection({ artifact: l.artifact, checks: l.checks ?? [], okIds: l.okIds ?? null, tables });
172
183
  if (sec === null) continue;
173
184
  const parts = [[`## ${l.n}. ${l.text}`, ...lineRules({ rules: l.rules }).map((r) => `Rule: ${r}`)].join('\n')];
@@ -0,0 +1,111 @@
1
+ // borrowed-from: bareloop src/rowresults.js@v0.61.0 (fc56e1f3)
2
+ // fwd's imports: `plainFactItem` is in src/citedcheck.js. One change, marked below by whole-line comments (M19 am11 item 4): a count gap lands on the row of the rule that set the count.
3
+ // PER-ROW RESULTS of the one check list (Addendum 2026-11-14 (c) piece 4, hamr's pick b): each row of a rubric line gets its OWN pass or fail, from bareguard's own structured gaps for that line's step
4
+ // file, never a result shared by the line. Pure; no I/O. A gap is mapped to the ONE row that owns the check it names, by a rule that never guesses:
5
+ // p<part>-facts, item `#<r>:d<fact>:<reason>` -> the row(s) that built that fact (the signed row's `facts` names it)
6
+ // p<part>-count-min|max -> the count row that points at that part
7
+ // p<part>-<countable check> -> the row(s) that point at that part (a pick, the cited default, the numbers default, the note)
8
+ // text-present / happened -> the line's floor row
9
+ // the numbers tie (gradeStep's extra lines) -> the line's `$ numbers` row
10
+ // itemShape, item `#<i>:<field>:<reason>` -> the row of that field (a `~` rule row, or an `!` extra field's row); a whole-field gap, or an item with no field, the line's `$ shape` row
11
+ // A gap that names no single row (a quote-level gap of a fact part: the quote carries no fact index; a part with no results at all) is NEVER spread over rows: it is returned in `unclaimed`, in plain words,
12
+ // and the line shows it as its own item. When the file itself could not be read (the floor is red), the line's other rows were not looked at: they read `unread`, never passed.
13
+ import { plainFactItem } from './citedcheck.js';
14
+ import { plainStepGap } from './rubricstep.js';
15
+ import { plainShapeItem, itemFieldOf } from './shapewords.js';
16
+ import { shapePartOf, shapeRowKey, shapeDefaultKey } from './shaperows.js';
17
+
18
+ const isRec = (/** @type {unknown} */ v) => v !== null && typeof v === 'object' && !Array.isArray(v);
19
+
20
+ /** the check kinds a row may be, for the rows a step file is judged by */
21
+ const LINE_KINDS = ['rule', 'fact', 'phrase', 'count', 'cited', 'numbers', 'note', 'floor', 'sheet', 'shape'];
22
+
23
+ /**
24
+ * @typedef {{key: string, result: 'passed'|'failed'|'unread', why?: string}} RowResult
25
+ * @param {any[]|null|undefined} list the signed list (`closeDecl.list`) @param {{step: number, parts: any[]}} params the rubric-step stage's params
26
+ * @param {{verdict?: string, rawGaps?: any[], extraGaps?: string[], detail?: Record<string, any>, ruleCounts?: Record<number, {min?: number, max?: number}>}} graded `gradeStep`'s answer (`ruleCounts`: fwd's, the bounds of the rules that count items)
27
+ * @returns {{rows: RowResult[], unclaimed: string[], items?: string[]}}
28
+ */
29
+ export function rowResultsOf(list, params, graded) {
30
+ const n = params.step;
31
+ const rows = (Array.isArray(list) ? list : []).filter((/** @type {any} */ r) => isRec(r) && r.line === n && r.state === 'built' && LINE_KINDS.includes(r.kind));
32
+ /** @type {Map<string, string[]>} the plain reasons each red row has */
33
+ const red = new Map();
34
+ /** @type {string[]} */
35
+ const unclaimed = [];
36
+ const hit = (/** @type {any} */ r, /** @type {string} */ why) => red.set(r.key, [...(red.get(r.key) ?? []), why]);
37
+ const why0 = typeof graded.detail?.why === 'string' ? graded.detail.why : 'empty';
38
+ /** the rows that carry part `pi`: a row points at its part, or a `~` rule row is named in the part's own `rules` */
39
+ const rowsOfPart = (/** @type {number} */ pi) => rows.filter((r) => r.kind !== 'floor' && ((isRec(r.part) && r.part.part === pi) || (r.kind === 'rule' && Array.isArray(params.parts[pi]?.rules) && params.parts[pi].rules.includes(r.rule))));
40
+ /** shape jobs: the raw item reds (`#<i>:<path>:<reason>`, names and counts only) of the line's `itemShape` gaps: what the Result tab's grid reads to mark a cell @type {string[]} */
41
+ const items = [];
42
+ for (const g of graded.rawGaps ?? []) {
43
+ const id = String(g.id ?? g.check);
44
+ const plain = () => plainStepGap(n, why0, g, params).split('\n').join(' ');
45
+ if (id === 'text-present' || id === 'happened') { for (const r of rows.filter((x) => x.kind === 'floor')) hit(r, plain()); if (!rows.some((x) => x.kind === 'floor')) unclaimed.push(plain()); continue; }
46
+ // S4: a gap of a sheet check names the check by its own id (bareguard's `id`); it lands on the row that holds that check: the `[you]` rule row for a rule row's check, the `[agent]` row for an agent check, and the rules an agent row shows
47
+ const sheetCheck = (params.parts ?? []).flatMap((/** @type {any} */ p) => (isRec(p) && p.class === 'sheet' && Array.isArray(p.checks) ? p.checks : [])).find((/** @type {any} */ c) => isRec(c) && c.id === id);
48
+ if (sheetCheck) {
49
+ const covers = Array.isArray(sheetCheck.covers) ? sheetCheck.covers : [];
50
+ const owners = rows.filter((r) => (r.kind === 'sheet' && r.key === `L${n}.sheet.${id}`) || (r.kind === 'rule' && covers.includes(r.rule)));
51
+ if (owners.length === 0) unclaimed.push(plain()); else for (const r of owners) hit(r, plain());
52
+ continue;
53
+ }
54
+ // shape jobs (clause 8): an `itemShape` gap names an item and a field (`#<i>:<path>:<reason>`): the `[you]` rule row whose rule made that field, or the `[agent]` row of an extra field; a whole-field gap (no list, the
55
+ // count) or an item red with no field lands on the line's `[default]` row, the one that says "the answer is a list of items"
56
+ if (g.check === 'itemShape') {
57
+ const shape = shapePartOf(params);
58
+ const defaults = rows.filter((r) => r.kind === 'shape' && r.key === shapeDefaultKey(n));
59
+ const raw = g.kind === 'item-shape' && Array.isArray(g.items) ? g.items : null;
60
+ // fwd's change (M19 am11 item 4, loop takes it): a count gap (`count-under`, `count-over`) is on the row of the `~` rule that set that bound: a rule row that points at the shape part and is no field's rule. With several
61
+ // such rules the bound the gap names (`limit`) picks the one whose own bound it is (`graded.ruleCounts`, rule number -> {min?, max?}); a gap no rule owns is never put on a guessed row.
62
+ if (raw === null && (g.kind === 'count-under' || g.kind === 'count-over')) {
63
+ const si = Array.isArray(params.parts) ? params.parts.indexOf(shape) : -1;
64
+ const fieldRules = new Set((shape?.fields ?? []).map((/** @type {any} */ f) => f.rule));
65
+ const own = rows.filter((r) => r.kind === 'rule' && isRec(r.part) && r.part.part === si && !fieldRules.has(r.rule));
66
+ const bound = g.kind === 'count-under' ? 'min' : 'max';
67
+ const owners = own.length === 1 ? own : own.filter((r) => graded.ruleCounts?.[r.rule]?.[bound] === g.limit);
68
+ if (owners.length > 0) { for (const r of owners) hit(r, plain()); continue; }
69
+ }
70
+ if (raw === null) { if (defaults.length === 0) unclaimed.push(plain()); else for (const r of defaults) hit(r, plain()); continue; }
71
+ for (const it of raw) {
72
+ items.push(String(it));
73
+ const name = itemFieldOf(it);
74
+ const field = name === null ? null : (shape?.fields ?? []).find((/** @type {any} */ f) => isRec(f) && f.name === name);
75
+ const owners = field ? rows.filter((r) => (r.kind === 'shape' && r.key === shapeRowKey(n, name ?? '')) || (r.kind === 'rule' && field.row !== 'agent' && r.rule === field.rule)) : defaults;
76
+ if (owners.length === 0) unclaimed.push(plainShapeItem(it)); else for (const r of owners) hit(r, plainShapeItem(it));
77
+ }
78
+ continue;
79
+ }
80
+ const m = /^p(\d+)-(.+)$/.exec(id);
81
+ const pi = m ? Number(m[1]) - 1 : -1;
82
+ const part = params.parts[pi];
83
+ if (!m || !isRec(part)) { unclaimed.push(plain()); continue; }
84
+ if (part.class === 'fact' && m[2] === 'facts') {
85
+ const items = Array.isArray(g.items) ? g.items : [];
86
+ if (g.kind !== 'unsupported' || items.length === 0) { unclaimed.push(plain()); continue; }
87
+ for (const it of items) {
88
+ const im = /^#(\d+):d(\d+):/.exec(String(it));
89
+ const fname = im ? part.facts?.[Number(im[2])]?.name : undefined;
90
+ const owners = fname === undefined ? [] : rows.filter((r) => Array.isArray(r.facts) && r.facts.includes(fname));
91
+ if (owners.length === 0) { unclaimed.push(plainFactItem(String(it), part)); continue; }
92
+ for (const r of owners) hit(r, plainFactItem(String(it), part));
93
+ }
94
+ continue;
95
+ }
96
+ const owners = part.class === 'fact' ? rows.filter((r) => r.kind === 'count' && isRec(r.part) && r.part.part === pi) : rowsOfPart(pi);
97
+ if (owners.length === 0) { unclaimed.push(plain()); continue; }
98
+ for (const r of owners) hit(r, plain());
99
+ }
100
+ // the numbers tie of a text line (gradeStep's own lines): the line's `$ numbers` row owns it
101
+ for (const line of graded.extraGaps ?? []) {
102
+ const owner = rows.find((r) => r.kind === 'numbers');
103
+ if (owner) hit(owner, line); else unclaimed.push(line);
104
+ }
105
+ const unreadable = rows.some((r) => r.kind === 'floor' && red.has(r.key));
106
+ return {
107
+ rows: rows.map((r) => (red.has(r.key) ? { key: r.key, result: /** @type {const} */ ('failed'), why: /** @type {string[]} */ (red.get(r.key)).join(' ') } : { key: r.key, result: unreadable && r.kind !== 'floor' ? /** @type {const} */ ('unread') : /** @type {const} */ ('passed') })),
108
+ unclaimed,
109
+ ...(items.length ? { items } : {}),
110
+ };
111
+ }
package/src/rubricstep.js CHANGED
@@ -3,6 +3,13 @@
3
3
  // and the default cited text. The rest of the rubric step (building, grading and reading a step file) is not wanted here.
4
4
  import { lineRules } from './pagebits.js';
5
5
  import { factShapeReds } from './citedcheck.js';
6
+ import { shapeShapeReds, shapeFieldSentence, shapeExampleItem } from './shaperows.js';
7
+ import { plainShapeGap } from './shapewords.js';
8
+
9
+ // borrowed-from: bareloop src/rubricstep.js@v0.60.0 (the one spelling of the keys of a repo job's stage row, of a job-level guard row and of the write-fence row; fwd has no repo job, so only the block's repo rows read them)
10
+ export const stageKeyOf = (/** @type {string} */ name) => `S.${name}`;
11
+ export const guardKeyOf = (/** @type {string} */ name) => `J.$guard.${name}`;
12
+ export const FENCE_KEY = 'J.$fence';
6
13
 
7
14
  // ── the `rubric-step` stage: its parameters, and the rubric they build ───────────────────────────────────────────────
8
15
  //
@@ -17,7 +24,7 @@ import { factShapeReds } from './citedcheck.js';
17
24
  // (src/authoring.js `checkRubricParts`) so no signed stage ever carries one.
18
25
 
19
26
  /** the closed set of classes a part is sorted into; `none` = "I could not sort this one" (a red, in plain words, never a guess) */
20
- export const PART_CLASSES = Object.freeze(['countable', 'fact', 'judged', 'guard', 'none']);
27
+ export const PART_CLASSES = Object.freeze(['countable', 'fact', 'shape', 'judged', 'guard', 'none']);
21
28
 
22
29
  /**
23
30
  * The counted/quoted checks a `countable` part may name, with the fields each needs — read off bareguard's own rule table
@@ -49,7 +56,7 @@ export const COUNT_CHECKS = Object.freeze({
49
56
  });
50
57
 
51
58
  /** every field a part may carry, whatever its class */
52
- const PART_FIELDS = Object.freeze(['text', 'class', 'check', 'value', 'names', 'wordsPerSection', 'source', 'domains', 'phrases', 'size', 'covers', 'rules', 'from', 'record', 'facts', 'count', 'tested', 'sample']);
59
+ const PART_FIELDS = Object.freeze(['text', 'class', 'check', 'value', 'names', 'wordsPerSection', 'source', 'domains', 'phrases', 'size', 'covers', 'rules', 'from', 'record', 'facts', 'count', 'tested', 'sample', 'asSeen', 'fields', 'minItems', 'maxItems']);
53
60
 
54
61
  /** @typedef {{code: string, path: string, detail: string}} ShapeRed */
55
62
 
@@ -92,6 +99,9 @@ export function rubricStepShapeReds(p, at) {
92
99
  && part.rules.every((/** @type {unknown} */ x) => Number.isInteger(x) && /** @type {number} */ (x) >= 1))) {
93
100
  red('invalid-value', `${w}.rules`, 'the numbers of the line\'s ~ rules this part carries out (distinct integers, 1 or more)');
94
101
  }
102
+ if (Object.hasOwn(part, 'asSeen') && part.class !== 'fact') red('invalid-value', `${w}.asSeen`, 'only a fact part carries the as-seen example');
103
+ for (const k of ['fields', 'minItems', 'maxItems']) if (Object.hasOwn(part, k) && part.class !== 'shape') red('invalid-value', `${w}.${k}`, 'only a shape part carries the fields and the item count of a list of items');
104
+ if (part.class === 'shape') { shapeShapeReds(part, w, (c, path, d) => red(c, path, d), p.parts.find((/** @type {any} */ x) => isRec(x) && x.class === 'fact') ?? null); return; }
95
105
  if (part.class === 'fact') { factShapeReds(part, w, (c, path, d) => red(c, path, d)); return; }
96
106
  if (part.class === 'guard') {
97
107
  if (!nameList(part.domains)) red('invalid-value', `${w}.domains`, 'a non-empty array of web domains the rule is about');
@@ -113,6 +123,10 @@ export function rubricStepShapeReds(p, at) {
113
123
  }
114
124
  }
115
125
  });
126
+ // shape jobs: a line is a shape line, a sheet line or a facts line, never two of them, and a shape part holds its place beside the line's fact part (facts+shape: one `results` list) and its picks
127
+ const shapeParts = p.parts.filter((/** @type {any} */ x) => isRec(x) && x.class === 'shape');
128
+ if (shapeParts.length > 1) red('invalid-value', `${at}.parts`, 'one shape part per step: the fields of a list of items all go in one');
129
+ if (p.parts.some((/** @type {any} */ x) => isRec(x) && x.class === 'sheet') && shapeParts.length > 0) red('invalid-value', `${at}.parts`, 'a sheet line holds sheet checks: a shape part is not allowed beside them');
116
130
  return reds;
117
131
  }
118
132
 
@@ -270,3 +284,52 @@ export function listMatchesClose(closeDecl) {
270
284
  if (bare.length) parts.push(`a check in the close has no row: line ${bare.map(({ n, i }) => `${n} part ${i + 1}`).join('; ')}`);
271
285
  return { ok: false, error: `The list of checks does not match the signed close (${parts.join(' | ')}). Nothing was signed — draft again.` };
272
286
  }
287
+
288
+ // borrowed-from: bareloop src/rubricstep.js@v0.61.0 (fc56e1f3) (shapeBriefOf and the LIST-line brief of lineBriefs: the lines are the tag's, written by code from the signed shape; the first line of a shape-only or text+list line is fwd's adapted
289
+ // line, docs/wiki/the-module-ladder.md M19 section 3.6, because fwd's step answers through emit_artifact with done and blocker, not a step file)
290
+ /**
291
+ * FACTS + SHAPE: the extra lines of a fact line's brief when its close also carries an itemShape part (code-written, never model-written): each result also carries the shape fields, in plain words, with ONE example result
292
+ * built by code (the quote and values placeholders, then a legal value for each shape field). Nothing is added for a line with no shape part.
293
+ * @param {any} shape the line's shape part ({fields, minItems?, maxItems?}) @param {any} fp the fact part @returns {string[]}
294
+ */
295
+ export function shapeBriefOf(shape, fp) {
296
+ if (!isRec(shape) || !Array.isArray(shape.fields)) return [];
297
+ const fields = shape.fields.filter(isRec);
298
+ const values = Object.fromEntries(fp.facts.map((/** @type {any} */ f) => [f.name, '<as the quote writes it>']));
299
+ return [
300
+ ' Each result ALSO carries these fields (named exactly as written; a field marked optional may be left out when it does not apply):',
301
+ ...fields.map((/** @type {any} */ f) => ` - ${f.name}: ${shapeFieldSentence(f.spec)}${f.spec.required === true ? '' : ' (optional)'}`),
302
+ ` One example result: ${JSON.stringify({ quote: '<words copied from the page>', values, ...shapeExampleItem(/** @type {any} */ (fields)) })}`,
303
+ ];
304
+ }
305
+
306
+ /**
307
+ * A SHAPE line's brief (no fact part): the answer is a list of items, each field in plain words (the signed bounds, in the person's own form) and ONE worked example item, all written by code from the signed shape.
308
+ * `alsoText` = the line also carries the person's picks (its answer has `text` too).
309
+ * @param {number} n the job line @param {any} shape the line's shape part @param {boolean} [alsoText] @returns {string}
310
+ */
311
+ export function shapeLineBrief(n, shape, alsoText = false) {
312
+ const fields = shape.fields.filter(isRec);
313
+ // M19 am11 item 3: the count as it is signed (`exactly N items`, `at least N items`, `at most N items`)
314
+ const lo = Number.isInteger(shape.minItems) ? shape.minItems : null; const hi = Number.isInteger(shape.maxItems) ? shape.maxItems : null;
315
+ const s = (/** @type {number} */ k) => `${k} item${k === 1 ? '' : 's'}`;
316
+ const count = lo !== null && lo === hi ? `exactly ${s(lo)}` : lo !== null || hi !== null ? [...(lo !== null ? [`at least ${s(lo)}`] : []), ...(hi !== null ? [`at most ${s(hi)}`] : [])].join(' and ') : 'one item for every one you find';
317
+ return [
318
+ alsoText
319
+ ? `Job line ${n} is a TEXT line AND a LIST line. Call emit_artifact exactly once with this step's result: {"text": "...", "results": [{...}, {...}]}: "text" as for any text line, and "results" is the list of items. One object per item: ${count}.`
320
+ : `Job line ${n} is a LIST line. Call emit_artifact exactly once with this step's result: {"results": [{...}, {...}]} — no "text", no "cites". One object per item: ${count}.`,
321
+ ' Every item has these fields, named exactly as written (a field marked optional may be left out when it does not apply):',
322
+ ...fields.map((/** @type {any} */ f) => ` - ${f.name}: ${shapeFieldSentence(f.spec)}${f.spec.required === true ? '' : ' (optional)'}`),
323
+ ` One example item: ${JSON.stringify(shapeExampleItem(fields))}`,
324
+ ' Write each value as plain text or a plain number or yes/no (true or false) as the field says, never as a sentence about the value.',
325
+ ].join('\n');
326
+ }
327
+
328
+ /**
329
+ * The plain sentence of a bareguard gap of one line's answer, as the tag's `plainStepGap` takes it (step, why, gap, params). fwd's step has no file, so an itemShape gap's file is `the answer` (src/closers.js); only an itemShape gap
330
+ * is worded here (fwd's other gaps keep their own words in src/closers.js and src/citedcheck.js).
331
+ * @param {number} step the job line @param {string} _why @param {any} g a bareguard gap @param {any} [_params] @returns {string}
332
+ */
333
+ export function plainStepGap(step, _why, g, _params = null) {
334
+ return plainShapeGap({ at: `line ${step}`, file: 'the answer' }, g);
335
+ }
package/src/runner.js CHANGED
@@ -933,6 +933,7 @@ function makeAuditRow({
933
933
  * @param {number} [opts.triesDone] - tries a Stop already closed on this step (they count against its limit)
934
934
  * @param {string|null} [opts.runDir] - M4d am29 item 2: the run's folder, where each try saves its checks
935
935
  * @param {any[]} [opts.checkList] - M16 item 5: the plan's signed list; a list line's checks carry the row's `by`
936
+ * @param {any[]} [opts.jobLines] - M19 am11 item 4: the signed job lines; the words of a list line's rows read the person's rule
936
937
  * @param {Record<string, any>} [opts.mcpGranted] - M13 item 5: this step's signed MCP tools, already bound to its bridge (`runStepRalph` builds them); handed to the model with the verbs
937
938
  * @returns {Promise<{ok:true, artifact:any, attempts:number, hitl?:boolean} | {ok:false, outcome:string, red:string, stop?:{where:string, book:Record<string, any>, step?:string|null}}>}
938
939
  */
@@ -959,6 +960,8 @@ async function runStepTries({
959
960
  mcpGranted = {},
960
961
  // M16 item 5: the signed list (declaration.checkList), so a check of a list line is tagged by its row in the Audit
961
962
  checkList = undefined,
963
+ // M19 am11 item 4: the signed job lines (the words of a list line's rows)
964
+ jobLines = undefined,
962
965
  }) {
963
966
  /** @type {string|null} */
964
967
  let gap = initialGap ?? null;
@@ -1047,7 +1050,7 @@ async function runStepTries({
1047
1050
  // M4d am25: `thinkingMode` is the ONE decision of what this try asks of thinking (`stepThinkingMode`); the model step only passes it on.
1048
1051
  // M10 am7 item 3: `cited` is the fact part of a green step that quotes a saved page - the form of its ANSWER ({results: [{quote, values}]}) and the facts it must hold,
1049
1052
  // told to the step in plain words by the model step. It is not the check: the quotes are checked by `closeCited` against the run's own copy.
1050
- const stepMeta = Object.freeze({ class: step.close?.class ?? null, cited: step.close?.class === 'green' && step.close.cited ? step.close.cited : null, sheet: step.close?.class === 'green' && Array.isArray(step.close.sheet) ? step.close.sheet : null, withText: step.close?.class === 'green' && Array.isArray(step.close.picked) && step.close.picked.length > 0, picked: step.close?.class === 'green' && Array.isArray(step.close.picked) ? step.close.picked : null, attempt, step: step?.emits ?? step?.goal ?? null, thinkingMode: stepThinkingMode({ boxOn: thinkingBox, attempt }) });
1053
+ const stepMeta = Object.freeze({ class: step.close?.class ?? null, cited: step.close?.class === 'green' && step.close.cited ? step.close.cited : null, sheet: step.close?.class === 'green' && Array.isArray(step.close.sheet) ? step.close.sheet : null, withText: step.close?.class === 'green' && Array.isArray(step.close.picked) && step.close.picked.length > 0, picked: step.close?.class === 'green' && Array.isArray(step.close.picked) ? step.close.picked : null, attempt, itemShape: step.close?.itemShape && typeof step.close.itemShape === 'object' ? step.close.itemShape : null, line: step.fromLine ?? null, step: step?.emits ?? step?.goal ?? null, thinkingMode: stepThinkingMode({ boxOn: thinkingBox, attempt }) });
1051
1054
 
1052
1055
  const stopSeam = readStop ? Object.freeze({ stopRequested: readStop }) : undefined;
1053
1056
 
@@ -1210,7 +1213,7 @@ async function runStepTries({
1210
1213
  n: step.fromLine, part: closed.cited.part, results: closed.cited.results, check: closed.cited.check,
1211
1214
  }));
1212
1215
  }
1213
- tryChecks.push(...closeRecords(step, artifact, closed, checkList));
1216
+ tryChecks.push(...closeRecords(step, artifact, closed, checkList, jobLines));
1214
1217
  saveTry();
1215
1218
 
1216
1219
  if (closed.verdict === 'green' || closed.verdict === 'hitl') {
@@ -1663,6 +1666,8 @@ async function runAskSlot({
1663
1666
  rebuildPrior = /** @type {null | (() => ({ok:true,value:any}|{ok:false,red:string}))} */ (null),
1664
1667
  // M16 item 5: the signed list, handed on to a redo's tries
1665
1668
  checkList = /** @type {any[]|undefined} */ (undefined),
1669
+ // M19 am11 item 4: the signed job lines, handed on to a redo's tries with the list
1670
+ jobLines = /** @type {any[]|undefined} */ (undefined),
1666
1671
  }) {
1667
1672
  let redone = initialRedone;
1668
1673
  let currentPrior = priorArtifact;
@@ -1839,7 +1844,7 @@ async function runAskSlot({
1839
1844
  }
1840
1845
  // eslint-disable-next-line no-await-in-loop
1841
1846
  const redoResult = await runStepRalph({
1842
- step: priorStep, primitivesMap: primitives, readsMap: priorReadsResult.map, businessDate, modelStep, spent, capUsd, ceilingUsd: effectiveCeilingUsd, recordAudit, mcpServer, checkList, initialGap: reason, attemptOffset: lastTryNumber(runDir, priorStep.emits ?? priorStep.goal ?? null), thinkingBox: readJobThinking(flowDir, runDir), learnHints: stepHintsReader({ flowName, source: inputsManifest?.[0]?.source ?? null, now }), now, runDir,
1847
+ step: priorStep, primitivesMap: primitives, readsMap: priorReadsResult.map, businessDate, modelStep, spent, capUsd, ceilingUsd: effectiveCeilingUsd, recordAudit, mcpServer, checkList, jobLines, initialGap: reason, attemptOffset: lastTryNumber(runDir, priorStep.emits ?? priorStep.goal ?? null), thinkingBox: readJobThinking(flowDir, runDir), learnHints: stepHintsReader({ flowName, source: inputsManifest?.[0]?.source ?? null, now }), now, runDir,
1843
1848
  readStop: () => stopPending(runDir), stepNo: priorStepNo, prevStepId: priorPrevStepId,
1844
1849
  });
1845
1850
  if (!redoResult.ok) {
@@ -1969,6 +1974,19 @@ async function foldFromStep({
1969
1974
  });
1970
1975
  }
1971
1976
  let content = contentResult.value;
1977
+ // M15 am4: a job with no signed Ask shows and binds the WHOLE body (every work line, in line order) at the stop, so what is accepted is what is written. It is built before the stop, from the saved outputs.
1978
+ const noAsk = askLines.size === 0 && wholeIdx < 0;
1979
+ let noAskBody = /** @type {{ ok: true, body: string } | null} */ (null);
1980
+ if (noAsk) {
1981
+ const built = sendBodyOf({ content, wholeIdx, steps, sendIndex: i, askLines, context: reportContextOf({ runDir, steps, jobLines, checkList }), readResult: (id) => readArtifactResult(runDir, id) });
1982
+ if (!built.ok) {
1983
+ return haltRun({
1984
+ flowDir, runDir, runId, capUsd, startedAt: runStartedAt, now, nowMs, signatureHash, spent, priorSpendComplete: spendComplete.value, attempts: attemptsLog, artifacts, outcome: 'red', red: built.red,
1985
+ });
1986
+ }
1987
+ noAskBody = built;
1988
+ content = { text: built.body };
1989
+ }
1972
1990
  const decided = decideAction({ acceptedSha: lastAcceptedSha(steps, i, acceptedAskEmitsThisRun), outgoing: content });
1973
1991
  let shaToSend = decided.outgoingSha;
1974
1992
  if (!decided.go) {
@@ -1980,6 +1998,7 @@ async function foldFromStep({
1980
1998
  const stop = await runAskSlot({
1981
1999
  mcpServer,
1982
2000
  checkList,
2001
+ jobLines,
1983
2002
  step,
1984
2003
  stepIndex: i,
1985
2004
  askSlot: { question: decided.question, ttlMs: stopWaitMs(steps, i, askLines, sendSlot.waitMs), kind: ACTION_STOP_KIND },
@@ -2027,7 +2046,7 @@ async function foldFromStep({
2027
2046
  }
2028
2047
  }
2029
2048
  // M15 am3 item 6: what is written is the accepted body (the whole-job text built at the last Ask) under the title and the Passed line the send adds; the hash check stays on `content`
2030
- const sendBody = sendBodyOf({ content, wholeIdx, steps, sendIndex: i, askLines, context: reportContextOf({ runDir, steps, jobLines, checkList }) });
2049
+ const sendBody = noAskBody ?? sendBodyOf({ content, wholeIdx, steps, sendIndex: i, askLines, context: reportContextOf({ runDir, steps, jobLines, checkList }) });
2031
2050
  if (!sendBody.ok) {
2032
2051
  return haltRun({
2033
2052
  flowDir, runDir, runId, capUsd, startedAt: runStartedAt, now, nowMs, signatureHash, spent, priorSpendComplete: spendComplete.value, attempts: attemptsLog, artifacts, outcome: 'red', red: sendBody.red,
@@ -2097,6 +2116,7 @@ async function foldFromStep({
2097
2116
  const askResult = await runAskSlot({
2098
2117
  mcpServer,
2099
2118
  checkList,
2119
+ jobLines,
2100
2120
  step,
2101
2121
  stepIndex: i,
2102
2122
  askSlot,
@@ -2170,7 +2190,7 @@ async function foldFromStep({
2170
2190
  // redo's `initialGap` above.
2171
2191
  // eslint-disable-next-line no-await-in-loop
2172
2192
  const stepResult = await runStepRalph({
2173
- step, primitivesMap: primitives, readsMap, businessDate, modelStep, spent, capUsd, ceilingUsd: effectiveCeilingUsd, recordAudit, mcpServer, checkList, initialGap: i === i0 ? firstStepGap : null, thinkingBox: readJobThinking(flowDir, runDir), learnHints: stepHintsReader({ flowName, source: inputsManifest?.[0]?.source ?? null, now }), now, runDir,
2193
+ step, primitivesMap: primitives, readsMap, businessDate, modelStep, spent, capUsd, ceilingUsd: effectiveCeilingUsd, recordAudit, mcpServer, checkList, jobLines, initialGap: i === i0 ? firstStepGap : null, thinkingBox: readJobThinking(flowDir, runDir), learnHints: stepHintsReader({ flowName, source: inputsManifest?.[0]?.source ?? null, now }), now, runDir,
2174
2194
  readStop: () => stopPending(runDir), stepNo: i + 1, prevStepId: i > 0 ? (steps[i - 1].emits ?? steps[i - 1].goal ?? null) : null, attemptOffset: i === i0 ? resumeTries.numbered : 0, triesDone: i === i0 ? resumeTries.done : 0,
2175
2195
  });
2176
2196
  if (!stepResult.ok) {
@@ -2773,6 +2793,18 @@ export async function resumeRun({
2773
2793
  let priorArtifact = readArtifact(runDir, priorId);
2774
2794
  // M13 am9: the Ask that shows the whole job rebuilds `{text}` from the saved outputs, as the first pass did
2775
2795
  const wholeIdx = wholeJobAskIndex({ steps, askLines, sendLines });
2796
+ if (isStop && askLines.size === 0 && wholeIdx < 0) {
2797
+ // M15 am4: the stop of a job with no Ask shows the whole body, rebuilt as the first pass built it (the answer's hash is of this text)
2798
+ const built = sendBodyOf({ content: priorArtifact, wholeIdx, steps, sendIndex: state.stepIndex, askLines, context: reportContextOf({ runDir, steps, jobLines: read.lines, checkList: declaration.checkList }), readResult: (id) => readArtifactResult(runDir, id) });
2799
+ if (!built.ok) {
2800
+ return haltRun({
2801
+ flowDir, runDir, runId, capUsd, startedAt: runStartedAt, now, nowMs: getNowMs, signatureHash: state.signatureHash, spent, priorSpendComplete: spendComplete.value, attempts: attemptsLog, artifacts,
2802
+ outcome: 'red', red: built.red,
2803
+ resumeAt: { stepIndex: state.stepIndex, flowRoot: root, flowName: name, inputsManifest: state.inputsManifest, unjudged: state.evidenceUnjudged ?? [], redone: typeof state.redone === 'number' ? state.redone : 0 },
2804
+ });
2805
+ }
2806
+ priorArtifact = { text: built.body };
2807
+ }
2776
2808
  const rebuildWhole = () => wholeJobText({ steps, askLines, lastAskIndex: wholeIdx, readResult: (id) => readArtifactResult(runDir, id), context: reportContextOf({ runDir, steps, jobLines: read.lines, checkList: declaration.checkList }) });
2777
2809
  if (state.stepIndex === wholeIdx) {
2778
2810
  const whole = rebuildWhole();
@@ -2791,6 +2823,7 @@ export async function resumeRun({
2791
2823
  const askResult = await runAskSlot({
2792
2824
  mcpServer: declaration.mcp?.server ?? null,
2793
2825
  checkList: declaration.checkList,
2826
+ jobLines: read.lines,
2794
2827
  step,
2795
2828
  stepIndex: state.stepIndex,
2796
2829
  askSlot,