fwdloop 0.35.2 → 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 (104) 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 +78 -20
  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 +86 -62
  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 +6 -4
  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 +20 -8
  34. package/src/panel/authorcard.js +3 -3
  35. package/src/panel/data.js +3 -2
  36. package/src/panel/index.html +176 -41
  37. package/src/panel/result.js +40 -3
  38. package/src/pickrecord.js +14 -0
  39. package/src/planrebuild.js +55 -19
  40. package/src/ratelimit.js +117 -0
  41. package/src/report.js +216 -0
  42. package/src/rowresults.js +111 -0
  43. package/src/rubricstep.js +65 -2
  44. package/src/runner.js +61 -9
  45. package/src/send.js +19 -82
  46. package/src/shapebuild.js +281 -0
  47. package/src/shapelook.js +91 -0
  48. package/src/shapemenu.js +64 -0
  49. package/src/shaperesult.js +104 -0
  50. package/src/shaperows.js +263 -0
  51. package/src/shapewords.js +140 -0
  52. package/src/sheetbuild.js +41 -29
  53. package/src/sheetclaims.js +49 -1
  54. package/src/sheetfind.js +8 -0
  55. package/src/sheetlook.js +11 -1
  56. package/src/sheetrows.js +10 -64
  57. package/src/ticketrows.js +1 -1
  58. package/src/try-checks.js +39 -6
  59. package/src/types.js +1 -0
  60. package/src/whole-job.js +108 -16
  61. package/types/action-stop.d.ts +1 -1
  62. package/types/auditchecks.d.ts +13 -2
  63. package/types/authoring.d.ts +24 -4
  64. package/types/blockasks.d.ts +6 -10
  65. package/types/blockassemble.d.ts +13 -13
  66. package/types/blockdraft.d.ts +3 -2
  67. package/types/blockpick.d.ts +4 -0
  68. package/types/cardlist.d.ts +18 -2
  69. package/types/checkblock.d.ts +278 -28
  70. package/types/checked.d.ts +15 -6
  71. package/types/checklook.d.ts +36 -0
  72. package/types/checkrows.d.ts +119 -0
  73. package/types/citedcheck.d.ts +4 -2
  74. package/types/closers.d.ts +10 -1
  75. package/types/drafter.d.ts +8 -4
  76. package/types/globprefix.d.ts +5 -0
  77. package/types/model-step.d.ts +43 -2
  78. package/types/pageask.d.ts +5 -3
  79. package/types/pagedropwords.d.ts +0 -1
  80. package/types/pagedry.d.ts +27 -0
  81. package/types/pagefetch.d.ts +3 -2
  82. package/types/pagerules.d.ts +4 -0
  83. package/types/panel/result.d.ts +19 -2
  84. package/types/pickrecord.d.ts +10 -0
  85. package/types/ratelimit.d.ts +59 -0
  86. package/types/report.d.ts +46 -0
  87. package/types/rowresults.d.ts +28 -0
  88. package/types/rubricstep.d.ts +21 -0
  89. package/types/runner.d.ts +3 -1
  90. package/types/send.d.ts +13 -12
  91. package/types/shapebuild.d.ts +97 -0
  92. package/types/shapelook.d.ts +76 -0
  93. package/types/shapemenu.d.ts +40 -0
  94. package/types/shaperesult.d.ts +40 -0
  95. package/types/shaperows.d.ts +102 -0
  96. package/types/shapewords.d.ts +43 -0
  97. package/types/sheetbuild.d.ts +31 -13
  98. package/types/sheetclaims.d.ts +16 -0
  99. package/types/sheetfind.d.ts +1 -0
  100. package/types/sheetrows.d.ts +5 -36
  101. package/types/ticketrows.d.ts +1 -1
  102. package/types/try-checks.d.ts +2 -1
  103. package/types/types.d.ts +4 -0
  104. package/types/whole-job.d.ts +69 -3
@@ -12,7 +12,8 @@ import { readInputFacts } from './input-facts.js';
12
12
  import { blockJobLines } from './blocklines.js';
13
13
  import { setUpBlock, ticketLeaveOut, pickEdits, ledgerEdits } from './blockdraft.js';
14
14
  import { assembleFromBlock } from './blockassemble.js';
15
- import { cardOfBlock } from './cardlist.js';
15
+ import { cardOfBlock, cardOfPlanBlock } from './cardlist.js';
16
+ import { ledgerRowsOf } from './checkrows.js';
16
17
  import { editsOf } from './rowedit.js';
17
18
  import { NOTE_KIND } from './noteask.js';
18
19
  import { offerRules, rowsFromAnswer, codeScope } from './checkpick.js';
@@ -20,12 +21,15 @@ import { matchRecord, readRowChoices, RECORD_FILE } from './pickrecord.js';
20
21
  import { listLinesOf, cardLinesOf } from './checklistsign.js';
21
22
  import { csvRolesOf } from './sheetblock.js';
22
23
  import { withTicketRows } from './ticketrows.js';
23
- import { isSheetKey, sheetChoice, withSheetRows, withSheetCard, droppedSheetOf } from './sheetrows.js';
24
+ import { isSheetKey, sheetRowsOf, withSheetRows, withSheetCard } from './sheetrows.js';
24
25
  import { validateDeclaration } from './declaration.js';
25
26
  import { loadCatalogue } from './catalogue.js';
26
27
  import { WIRED_VERBS } from './primitives.js';
27
28
  import { ticketSourcesOf } from './ticket-draft.js';
28
29
  import { docRolesOf } from './drafter.js';
30
+ import { buildShapes } from './shapebuild.js';
31
+ import { parseShapeAnswer, SHAPE_CALL_LABEL } from './shapelook.js';
32
+ import { lineRules } from './pagebits.js';
29
33
  import { buildReadout, specHash, PAGES_DIR, NOT_CHECKED_FILE } from './authoring.js';
30
34
 
31
35
  /** what a person is told when the saved inputs no longer give the saved list: nothing is written */
@@ -73,6 +77,12 @@ export function rebuildBlock({ planDir, asks }) {
73
77
  if (!plan.ok) return no('This plan could not be read. Nothing was changed.');
74
78
  const blockLineNums = new Set(plan.jobLines.map((l) => l.n));
75
79
  const inBlock = (/** @type {{line: number}} */ x) => blockLineNums.has(x.line);
80
+ // M19 S3: a sheet line is the block's too; the draft saved what code built from the AI's sheet suggestions (log.json `sheetBuilt`), so the block holds its sheet rows again without a call. A plan that has sheet checks
81
+ // and no such record was drafted before this and cannot be rebuilt: the same sentence as an input that changed
82
+ const sheetBuilt = isRec(log?.sheetBuilt) && isRec(log.sheetBuilt.built) ? log.sheetBuilt : null;
83
+ if (sheetBuilt === null && (declaration.steps ?? []).some((/** @type {any} */ st) => isRec(st?.close) && Array.isArray(st.close.sheet))) return no(REBUILD_CHANGED_SAY);
84
+ const sheetLineNums = sheetBuilt === null ? [] : Object.keys(sheetBuilt.built).map(Number).filter((n) => tied.includes(n));
85
+ const notSheet = (/** @type {{line: number}} */ x) => !sheetLineNums.includes(x.line);
76
86
  const lines = parsed.lines;
77
87
  const allShape = offerRules(lines, parsed.arbiter, look.facts);
78
88
  const matched = matchRecord(Array.isArray(record.picks) ? record.picks : [], lines, allShape);
@@ -83,16 +93,28 @@ export function rebuildBlock({ planDir, asks }) {
83
93
  const leftSaved = look.dropped.filter((/** @type {any} */ d) => d?.reason === 'person-left' && Number.isInteger(d.line) && Number.isInteger(d.rule)).map((/** @type {any} */ d) => ({ line: d.line, rule: d.rule }));
84
94
  const leftFresh = [...matched.left.filter((x) => !isKept(x)), ...leftSaved.filter((x) => !matched.left.some((m) => m.line === x.line && m.rule === x.rule))].filter(inBlock);
85
95
  const block = setUpBlock({
86
- texts, jobLines: plan.jobLines, look,
96
+ texts, jobLines: [...plan.jobLines, ...all.jobLines.filter((l) => sheetLineNums.includes(l.n))].sort((a, b) => a.n - b.n), look: { facts: look.facts.filter(notSheet), dropped: look.dropped.filter(notSheet) },
87
97
  kept: { picks: matched.picks.filter(inBlock).filter(isKept), left: matched.left.filter(inBlock).filter(isKept), askRules: matched.askRules.filter(inBlock) },
88
98
  fresh: { picks: matched.picks.filter(inBlock).filter((x) => !isKept(x)), left: leftFresh },
89
- asks, countScope: (t) => codeScope(parsed.arbiter.sources, t) === 'in', leaveOut: ticketLeaveOut(declaration.flowType, plan.jobLines),
99
+ asks, countScope: (t) => codeScope(parsed.arbiter.sources, t) === 'in', leaveOut: ticketLeaveOut(declaration.flowType, plan.jobLines), sheetLines: sheetLineNums,
90
100
  });
91
101
  // the AI's replies, in the order the draft took them (log.json keeps each reply as sent)
92
102
  const askRules = allShape.filter((r) => !isKept(r));
103
+ let shapeSet = false;
93
104
  for (const e of Array.isArray(log?.log) ? log.log : []) {
94
105
  // the note question's answers ride its entry, a failed turn's too (a `failed` answer is a Not checked row, so it must replay)
95
106
  if (isRec(e) && e.kind === NOTE_KIND) { block.setNotes(notesOfEntry(e)); continue; }
107
+ // M19 S9: the shape look's answer, as the draft saved it (log.json keeps the raw text of the one call it made). It is read again through the same parser and the same builder, so the block holds its shape rows
108
+ // without a call; the first answer that reads is the one the draft used (an unreadable first answer was asked once more). A plan with shape rows and no such entry does not rebuild (the list differs below)
109
+ if (isRec(e) && e.kind === SHAPE_CALL_LABEL) {
110
+ const got = e.outcome === 'answered' && typeof e.rawText === 'string' && !shapeSet ? parseShapeAnswer(e.rawText) : null;
111
+ if (got !== null && got.ok && got.shapes.length > 0) {
112
+ shapeSet = true;
113
+ block.setShape(buildShapes({ lines: plan.jobLines.filter((l) => lineRules(l).length > 0 && !block.isSheetLine(l.n)), labels: block.labels, suggestions: got.shapes }));
114
+ block.reconcile();
115
+ }
116
+ continue;
117
+ }
96
118
  if (!isRec(e) || e.outcome !== 'answered' || !isRec(e.args)) continue;
97
119
  if (e.kind === 'check-suggest') block.applyDelta({ label: 'pre:check-suggest', pre: true, edits: pickEdits(rowsFromAnswer(askRules, e.args), blockLineNums) });
98
120
  else if (e.kind === 'ledger-suggest') block.applyDelta({ label: 'pre:ledger-suggest', pre: true, edits: ledgerEdits(e.args.extra) });
@@ -103,6 +125,9 @@ export function rebuildBlock({ planDir, asks }) {
103
125
  // the choices the plan was made with (a Drop or an Add of an earlier edit), judged by the block again
104
126
  const choices = readRowChoices(path.join(planDir, RECORD_FILE));
105
127
  if (choices) block.carryChoices(choices);
128
+ // the sheet checks the draft built, in the draft's own order (after the AI's edits), and the Drops the plan was made with
129
+ if (sheetBuilt !== null) { block.setSheet(sheetBuilt); block.carrySheetDropped(Array.isArray(record.sheetDropped) ? record.sheetDropped : []); }
130
+ if (Array.isArray(record.shapeDropped) && record.shapeDropped.length) block.carryShapeDropped(record.shapeDropped);
106
131
  block.reconcile();
107
132
  return { ok: true, block, declaration, lines, lineSet, parsed, texts, look, record, log, proseText: prose.text };
108
133
  }
@@ -120,7 +145,7 @@ function assembleAgain(b, from = b.declaration) {
120
145
  const src = b.lineSet.has(st?.fromLine) && isRec(st.close) && isRec(st.close.cited) ? st.close.cited.source : undefined;
121
146
  return typeof src === 'string' && docs.has(src) && Array.isArray(st.reads) ? { ...st, reads: st.reads.filter((/** @type {string} */ r) => r !== src) } : st;
122
147
  }) };
123
- const built = assembleFromBlock({ declaration: rest, block: b.block, lines: b.lines, lineSet: b.lineSet, askLines: new Set(b.parsed.arbiter.asks.map((/** @type {any} */ a) => a.line)) });
148
+ const built = assembleFromBlock({ declaration: rest, block: b.block, lines: b.lines, lineSet: b.lineSet, askLines: new Set(b.parsed.arbiter.asks.map((/** @type {any} */ a) => a.line)), sheetRoles: csvRolesOf(b.parsed.arbiter) });
124
149
  // M16 am4: the sheet checks are rows on the list too, read from the steps the same way the draft read them
125
150
  const withSheet = withSheetRows({ declaration: built.declaration, lines: b.lines, csvRoles: csvRolesOf(b.parsed.arbiter) });
126
151
  // M17 am6: the Tickets filter and watch are rows on the list too, read from the declaration's fields the same way the draft read them
@@ -154,16 +179,22 @@ const fingerprint = (d) => JSON.stringify([d.checkList ?? null, (d.steps ?? []).
154
179
  export function rowEditPlan({ planDir, op, key, asks = true }) {
155
180
  const b = rebuildBlock({ planDir, asks });
156
181
  if (!b.ok) return { ok: false, say: b.say, refused: 'no-list' };
157
- const dropped = droppedSheetOf(b.record);
158
182
  const before = assembleAgain(b);
159
183
  if (!before.ok) return { ok: false, say: before.say, refused: 'rebuild' };
160
184
  if (fingerprint(before.declaration) !== fingerprint(b.declaration)) return { ok: false, say: REBUILD_CHANGED_SAY, refused: 'changed' };
161
- // a sheet row is a check of the AI's own sheet step: its Drop or Add changes `close.sheet` (src/sheetrows.js); any other row is the block's
162
- const sheetDone = isSheetKey(key) ? sheetChoice({ declaration: b.declaration, lines: b.lines, csvRoles: csvRolesOf(b.parsed.arbiter), op, key, dropped }) : null;
163
- const done = sheetDone ?? b.block.rowChoice(key, op);
185
+ // M19 S3: a sheet check is a row of the block like any other (its Drop or Add is the block's `rowChoice`). A `[you]` sheet row is drawn with the key of its check (src/sheetrows.js), which is no row of the block: the
186
+ // refusals for it are the words the plan card has always given
187
+ /** @type {string|null} */
188
+ let sheetKeyWhy = null;
189
+ if (isSheetKey(key) && !b.block.rows.some((r) => r.key === key)) {
190
+ const card = sheetRowsOf({ declaration: b.declaration, lines: b.lines, csvRoles: csvRolesOf(b.parsed.arbiter) }).card.find((r) => r.key === key);
191
+ sheetKeyWhy = op === 'drop' ? (card?.by === 'you' ? 'that check comes from a rule you wrote; edit the job to change it' : 'there is no such check on the list') : 'only a suggested check can be added';
192
+ }
193
+ const done = sheetKeyWhy !== null ? { ok: /** @type {const} */ (false), why: sheetKeyWhy } : b.block.rowChoice(key, op);
164
194
  if (!done.ok) return { ok: false, say: `${done.why[0].toUpperCase()}${done.why.slice(1)}${/[.!?]$/.test(done.why) ? '' : '.'} Nothing was changed.`, refused: 'bad-row' };
165
- const droppedNow = sheetDone && sheetDone.ok ? sheetDone.dropped : dropped;
166
- const after = assembleAgain(b, sheetDone && sheetDone.ok ? sheetDone.declaration : b.declaration);
195
+ const droppedNow = b.block.sheetDroppedRecord();
196
+ const shapeDroppedNow = b.block.shapeDroppedRecord();
197
+ const after = assembleAgain(b);
167
198
  if (!after.ok) return { ok: false, say: after.say, refused: 'rebuild' };
168
199
  const target = readJson(planDir, 'target.json');
169
200
  const inputFactsText = readFileInside(planDir, 'input-facts.json');
@@ -171,11 +202,6 @@ export function rowEditPlan({ planDir, op, key, asks = true }) {
171
202
  if (!targetText.ok || !inputFactsText.ok || !isRec(target)) return { ok: false, say: 'This plan could not be read. Nothing was changed.', refused: 'rebuild' };
172
203
  const dj = (/** @type {unknown} */ o) => `${JSON.stringify(o, null, 2)}\n`;
173
204
  const declarationText = dj(after.declaration);
174
- const readoutText = buildReadout({
175
- declaration: after.declaration, arbiter: b.parsed.arbiter, lines: b.lines, name: target.name, modelId: b.log?.modelId, costUsd: b.log?.costUsd ?? null, rounds: b.log?.rounds ?? 0, spendComplete: b.log?.spendComplete !== false, root: target.root,
176
- });
177
- const h = specHash({ proseText: b.proseText, declarationText, inputFactsText: inputFactsText.text, readoutText, targetText: targetText.text });
178
- if (!h.ok) return { ok: false, say: 'The changed plan could not be hashed. Nothing was changed.', refused: 'rebuild' };
179
205
  // the "Not checked" list: what the old plan listed, less what the old list made, plus what the changed list makes (the AI's own list stays)
180
206
  const oldNc = readJson(planDir, NOT_CHECKED_FILE)?.notChecked;
181
207
  const oldList = Array.isArray(oldNc) ? oldNc.filter((x) => typeof x === 'string') : [];
@@ -183,7 +209,17 @@ export function rowEditPlan({ planDir, op, key, asks = true }) {
183
209
  const notChecked = [...new Set([...oldList.filter((x) => !was.has(x)), ...after.notChecked])];
184
210
  const oldBy = isRec(readJson(planDir, NOT_CHECKED_FILE)?.by) ? readJson(planDir, NOT_CHECKED_FILE).by : {};
185
211
  const by = { ...Object.fromEntries(Object.entries(oldBy).filter(([t]) => !was.has(t))), ...after.notCheckedBy };
186
- const { sheetDropped: _sd, ...record } = isRec(b.record) ? b.record : {};
212
+ // M19 am4: the plan card the new plan saves is the one its readout reads (one model)
213
+ // M19 am8 item 1, am9 item 5: the new plan's ledger rows, one per Not checked row, in its own log; the card is read from the new plan (am6)
214
+ const ledger = ledgerRowsOf(after.declaration, b.lines, Object.fromEntries(b.block.rows.filter((/** @type {any} */ r) => r.kind !== 'rule').map((/** @type {any} */ r) => [r.key, r.name ? [r.name] : r.words ?? []])));
215
+ const card = (() => { const c = withSheetCard(cardOfBlock(b.block), after.sheet); return cardOfPlanBlock(b.block, after.tickets.card.length ? withSheetCard(c, { card: after.tickets.card }) : c, { declaration: after.declaration, lines: b.lines, csvRoles: csvRolesOf(b.parsed.arbiter), log: [...(Array.isArray(b.log?.log) ? b.log.log : []), ...ledger] }); })();
216
+ const readoutText = buildReadout({
217
+ declaration: after.declaration, arbiter: b.parsed.arbiter, lines: b.lines, name: target.name, modelId: b.log?.modelId, costUsd: b.log?.costUsd ?? null, rounds: b.log?.rounds ?? 0, spendComplete: b.log?.spendComplete !== false, root: target.root,
218
+ notChecked, notCheckedBy: by, suggested: card.suggested, checkCard: card,
219
+ });
220
+ const h = specHash({ proseText: b.proseText, declarationText, inputFactsText: inputFactsText.text, readoutText, targetText: targetText.text });
221
+ if (!h.ok) return { ok: false, say: 'The changed plan could not be hashed. Nothing was changed.', refused: 'rebuild' };
222
+ const { sheetDropped: _sd, shapeDropped: _shd, ...record } = isRec(b.record) ? b.record : {};
187
223
  const logRow = { round: (Array.isArray(b.log?.log) ? b.log.log.length : 0) + 1, kind: 'row-edit-human', op, key, outcome: 'answered', at: new Date().toISOString() };
188
224
  // the files the new plan keeps as they were (read through the gateway), then the ones it changes; `spec.hash` last, so a folder with one is whole
189
225
  /** @type {Record<string, string>} */
@@ -208,8 +244,8 @@ export function rowEditPlan({ planDir, op, key, asks = true }) {
208
244
  'declaration.json': declarationText,
209
245
  'readout.txt': readoutText,
210
246
  [NOT_CHECKED_FILE]: dj({ notChecked, ...(Object.keys(by).length ? { by } : {}) }),
211
- [RECORD_FILE]: dj({ ...record, rowChoices: b.block.choicesRecord(), ...(droppedNow.length ? { sheetDropped: droppedNow } : {}) }),
212
- 'log.json': dj({ ...(isRec(b.log) ? b.log : {}), log: [...(Array.isArray(b.log?.log) ? b.log.log : []), logRow], checkCard: (() => { const c = withSheetCard(cardOfBlock(b.block), after.sheet, droppedNow); return after.tickets.card.length ? withSheetCard(c, { card: after.tickets.card }) : c; })() }),
247
+ [RECORD_FILE]: dj({ ...record, rowChoices: b.block.choicesRecord(), ...(droppedNow.length ? { sheetDropped: droppedNow } : {}), ...(shapeDroppedNow.length ? { shapeDropped: shapeDroppedNow } : {}) }),
248
+ 'log.json': dj({ ...(isRec(b.log) ? b.log : {}), log: [...(Array.isArray(b.log?.log) ? b.log.log : []), logRow, ...ledger], checkCard: card }),
213
249
  'spec.hash': `${h.hash}\n`,
214
250
  },
215
251
  };
@@ -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 ADDED
@@ -0,0 +1,216 @@
1
+ // M15 am3 (docs/wiki/the-module-ladder.md, "M15 am3 - one markdown report per run"): the ONE writer of the report's words. The body (every line's section, in job order) is built by code at the last
2
+ // Ask (`wholeJobText`, src/whole-job.js) and is what the person accepts; the send step adds the title and the `Passed` line after the accept (`reportFileText`) and picks the file's name (`nextFreeName`).
3
+ // borrowed-from: bareloop src/resultmd.js@v0.60.0 (leaves, words, friendlyName, blockLines, isResultList, claimLines, reportBullet, plainDate, stepSection, the section writer of renderRunMd) and src/source.js@v0.60.0 (pickDelivery, the name clean-up).
4
+ // Adapted to fwd's run data: one JSON artifact per step, a sheet step's claim boxes at the top of its artifact, the close from the signed declaration.
5
+ // What this throws away: a result's keys other than `quote` and `values`; a claim box no check of the line carries; an artifact key that is neither text, results nor a claim; the AI's own count and total (code's are written).
6
+ // Third outcomes: a line whose artifact holds neither text, results nor a written claim has no section (as bareloop: nothing to write is not a heading alone); an artifact that is not an object has no section.
7
+ import { lstatSync } from 'node:fs';
8
+ import { join } from 'node:path';
9
+ import { sheetCheckSentence } from './sheetchecks.js';
10
+ import { sheetTotalLines, ROW_MATH_OPS, isRec } from './sheetclaims.js';
11
+ import { lineRules } from './pagebits.js';
12
+ import { shapeResultModel, shapeMarkdown } from './shaperesult.js';
13
+
14
+ const SCALAR = ['string', 'number', 'boolean'];
15
+
16
+ /** the words under a not-checked answer and a checked one (M15 am3 item 2) */
17
+ export const NOT_CHECKED_HEADING = '### The AI\'s answer (not checked — you judge it at Accept)';
18
+ export const CHECKED_HEADING = '### The answer';
19
+ /** an Ask line, in M13 am9's words */
20
+ export const askLineWords = (/** @type {number} */ n) => `Line ${n}: you accepted this at the Ask.`;
21
+ /** the Result tab's note for a report saved under a new name (code-owned; the page types no words) @param {string} taken */
22
+ export const REPORT_RENAMED = (taken) => `saved under a new name because ${taken} was already taken`;
23
+
24
+ /** one value as leaf lines `{parts, text}`: parts are the names on the way in; a string as it is, a number or boolean written out; a list of plain values joined by ", "; null as empty */
25
+ /** @param {string[]} parts @param {any} v @returns {{parts: string[], text: string}[]} */
26
+ function leaves(parts, v) {
27
+ if (v === null || v === undefined) return [{ parts, text: '' }];
28
+ if (SCALAR.includes(typeof v)) return [{ parts, text: `${v}` }];
29
+ if (Array.isArray(v) && v.every((x) => x === null || SCALAR.includes(typeof x))) return [{ parts, text: v.join(', ') }];
30
+ if (Array.isArray(v)) return v.flatMap((x, i) => leaves([...parts, `${i + 1}`], x));
31
+ return Object.entries(v).flatMap(([k, x]) => leaves([...parts, k], x));
32
+ }
33
+
34
+ /** @param {string} name split only at a lowercase-to-capital boundary, `_`, `-` and spaces, so `ID` stays one word */
35
+ const words = (name) => name.replace(/([a-z0-9])([A-Z])/g, '$1 $2').split(/[_\-\s]+/).filter(Boolean);
36
+
37
+ /** the names as plain words (M15 am2 (1)); a last name of `value` or `rows` is left out; the first letter capital, the later words lowercase @param {string[]} parts */
38
+ function friendlyName(parts) {
39
+ const p = parts.length > 1 && (parts[parts.length - 1] === 'value' || parts[parts.length - 1] === 'rows') ? parts.slice(0, -1) : parts;
40
+ const w = p.flatMap(words).map((x) => x.toLowerCase());
41
+ if (!w.length) return parts.join('.');
42
+ return w[0][0].toUpperCase() + w[0].slice(1) + (w.length > 1 ? ` ${w.slice(1).join(' ')}` : '');
43
+ }
44
+
45
+ /** the lines of one block, each a bullet; two lines with the same words both keep the `a.b` form @param {{parts: string[], text: string}[]} ls */
46
+ function blockLines(ls) {
47
+ const f = ls.map((l) => friendlyName(l.parts));
48
+ /** @type {Record<string, number>} */
49
+ const n = {};
50
+ for (const x of f) n[x] = (n[x] || 0) + 1;
51
+ return ls.map((l, i) => `- ${n[f[i]] > 1 ? l.parts.join('.') : f[i]}: ${l.text}`);
52
+ }
53
+
54
+ /** a list of results: every item an object holding a `values` object @param {any} v */
55
+ const isResultList = (v) => Array.isArray(v) && v.length > 0 && v.every((r) => isRec(r) && isRec(r.values));
56
+
57
+ /** the box keys that only say what the box holds: left out of a line's name */
58
+ const BOX_KEYS = ['value', 'rows', 'keys', 'values', 'totals'];
59
+ /** a box that maps a row number to its value */
60
+ const ROW_MAPS = ['days', 'bands'];
61
+ const cap = (/** @type {string} */ s) => (s ? s[0].toUpperCase() + s.slice(1) : s);
62
+
63
+ /**
64
+ * The claim bullets of a sheet step. A claim id is named with the plain sentence of the first passed check that carries it and is not a sumIf / countIf; a claim only sumIf / countIf carry is null (code computes it, the AI's
65
+ * number is never written); a box no check carries is left out. A map of rows (`days`, `bands`) writes one bullet per row.
66
+ * @param {Record<string, any>} claims @param {Record<string, string|null>} claimWords @returns {string[]}
67
+ */
68
+ function claimLines(claims, claimWords) {
69
+ /** @type {string[]} */
70
+ const out = [];
71
+ for (const [id, box] of Object.entries(claims)) {
72
+ if (!Object.hasOwn(claimWords, id) || claimWords[id] === null) continue;
73
+ const label = cap(/** @type {string} */ (claimWords[id]));
74
+ for (const l of leaves([], box)) {
75
+ let p = l.parts;
76
+ if (p.length === 2 && ROW_MAPS.includes(p[0])) { out.push(`- ${label}, row ${p[1]}: ${l.text}`); continue; }
77
+ if (p.length > 0 && BOX_KEYS.includes(p[p.length - 1])) p = p.slice(0, -1);
78
+ out.push(`- ${p.length ? `${label}, ${p.flatMap(words).map((x) => x.toLowerCase()).join(' ')}` : label}: ${l.text}`);
79
+ }
80
+ }
81
+ return out;
82
+ }
83
+
84
+ const COMPUTED = ' (computed by code from the rows named)';
85
+
86
+ /** code's own line (`Count of rows 3, 5: 2 (computed by code from the rows named)`) as a bullet `- Count: 2` / `- Total: 1,234.50` @param {string} line */
87
+ function reportBullet(line) {
88
+ const m = /^(Count|Total) of [^:]*: (.*)$/.exec(line);
89
+ const rest = (m ? m[2] : line).endsWith(COMPUTED) ? (m ? m[2] : line).slice(0, -COMPUTED.length) : (m ? m[2] : line);
90
+ return m ? `- ${m[1]}: ${rest}` : `- ${rest}`;
91
+ }
92
+
93
+ /**
94
+ * claim id -> the sentence of the first passed non-sumIf/countIf check carrying it; a claim only sumIf/countIf carry is null. `okIds` = the ids of the checks that passed, or null = no record (all count).
95
+ * @param {any[]} checks @param {Set<string>|null} okIds @returns {Record<string, string|null>}
96
+ */
97
+ export function claimWordsOf(checks, okIds) {
98
+ /** @type {Record<string, string|null>} */
99
+ const out = {};
100
+ /** @type {Set<string>} */
101
+ const seen = new Set();
102
+ for (const c of checks) {
103
+ if (!isRec(c) || typeof c.claim !== 'string') continue;
104
+ seen.add(c.claim);
105
+ if (c.rule === 'cells' && ROW_MATH_OPS.includes(c.op)) continue;
106
+ if (okIds && !okIds.has(c.id)) continue;
107
+ if (typeof out[c.claim] !== 'string') out[c.claim] = sheetCheckSentence(c);
108
+ }
109
+ for (const id of seen) if (!Object.hasOwn(out, id)) out[id] = null;
110
+ return out;
111
+ }
112
+
113
+ /** the date as plain words, `18 Nov 2026`, in the machine's local day (the day the dated file names use) @param {Date} d */
114
+ export function plainDate(d) {
115
+ return `${d.getDate()} ${['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'][d.getMonth()]} ${d.getFullYear()}`;
116
+ }
117
+
118
+ /** the run number when the run id reads `run-N`, else null (a rerun id `run-1-rerun-1` has none) @param {string} runId @returns {number|null} */
119
+ export function runNumberOf(runId) {
120
+ const m = /^run-(\d+)$/.exec(String(runId));
121
+ return m ? Number(m[1]) : null;
122
+ }
123
+
124
+ /** the title and the `Passed` line, written by the send step (M15 am3 item 2) @param {string} job @param {number|null} runNo @param {Date} now */
125
+ export const reportHead = (job, runNo, now) => `# ${job}${runNo === null ? '' : ` — run-${runNo}`}\nPassed · ${plainDate(now)}`;
126
+
127
+ /** the whole file: the title and the Passed line, then the accepted body @param {string} job @param {number|null} runNo @param {Date} now @param {string} body */
128
+ export const reportFileText = (job, runNo, now, body) => `${reportHead(job, runNo, now)}\n\n${body}\n`;
129
+
130
+ /**
131
+ * One line's section parts: `checked` blocks (`#### Result k` blocks and the bullets) and `answer`, the AI's own text, or null.
132
+ * @param {{artifact: unknown, checks: any[], okIds: Set<string>|null, tables: Record<string, any>}} o
133
+ * @returns {{checked: string[], answer: string|null}|null}
134
+ */
135
+ function stepSection({ artifact, checks, okIds, tables }) {
136
+ if (!isRec(artifact)) return null;
137
+ const a = /** @type {Record<string, any>} */ (artifact);
138
+ const hasText = typeof a.text === 'string';
139
+ /** @type {string[]} */
140
+ const checked = [];
141
+ if (isResultList(a.results)) {
142
+ a.results.forEach((/** @type {any} */ r, /** @type {number} */ i) => {
143
+ const lines = blockLines(Object.entries(r.values).flatMap(([n, x]) => leaves([n], x)));
144
+ checked.push([`#### Result ${i + 1}`, ...lines, ...(typeof r.quote === 'string' ? ['', `from the page: "${r.quote}"`] : [])].join('\n'));
145
+ });
146
+ }
147
+ const sheet = checks.filter((c) => isRec(c) && c.rule === 'cells');
148
+ // a sheet step's boxes are its artifact's keys named by a check's claim; nothing else of the artifact is a claim
149
+ const claimIds = new Set(sheet.map((c) => c.claim).filter((x) => typeof x === 'string'));
150
+ const claims = Object.fromEntries(Object.entries(a).filter(([k]) => claimIds.has(k)));
151
+ // Count then Total, whatever the order of the signed checks
152
+ const counted = sheetTotalLines(sheet, claims, tables).sort((x, y) => Number(y.startsWith('Count of')) - Number(x.startsWith('Count of')));
153
+ const bullets = [...claimLines(claims, claimWordsOf(sheet, okIds)), ...counted.map(reportBullet)];
154
+ if (bullets.length) checked.push(bullets.join('\n'));
155
+ const answer = hasText && /** @type {string} */ (a.text).trim() !== '' ? /** @type {string} */ (a.text) : null;
156
+ return checked.length === 0 && answer === null ? null : { checked, answer };
157
+ }
158
+
159
+ /**
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
+ * 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, shape?: any}[]} lines
163
+ * @param {Record<string, any>} tables the frozen sheets by input name
164
+ * @returns {string}
165
+ */
166
+ export function renderReportBody(lines, tables) {
167
+ /** @type {string[]} */
168
+ const sections = [];
169
+ for (const l of lines) {
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
+ }
182
+ const sec = stepSection({ artifact: l.artifact, checks: l.checks ?? [], okIds: l.okIds ?? null, tables });
183
+ if (sec === null) continue;
184
+ const parts = [[`## ${l.n}. ${l.text}`, ...lineRules({ rules: l.rules }).map((r) => `Rule: ${r}`)].join('\n')];
185
+ if (sec.checked.length) parts.push(['### Checked by code', sec.checked.join('\n\n')].join('\n'));
186
+ if (sec.answer !== null) parts.push([l.proseChecked ? CHECKED_HEADING : NOT_CHECKED_HEADING, sec.answer].join('\n'));
187
+ sections.push(parts.join('\n\n'));
188
+ }
189
+ return sections.join('\n\n');
190
+ }
191
+
192
+ /** is anything at this path (lstat: a dangling symlink counts as present) @param {string} p */
193
+ function present(p) {
194
+ try { lstatSync(p); return true; } catch (err) { return /** @type {any} */ (err).code !== 'ENOENT'; }
195
+ }
196
+
197
+ /** the most same-day names tried before the send stops (bareloop's MAX_SAME_DAY) */
198
+ export const MAX_SAME_DAY = 99;
199
+
200
+ /**
201
+ * The file name for a report: `<job>-YYYY-MM-DD.md`, then `<job>-YYYY-MM-DD-2.md`, `-3`, ... the first one that is free in `dir` (the machine's local day). Never a taken name. `taken` = the first choice
202
+ * when it was not free (the Result tab's note names it), else null. `name` = null when every name up to -99 is taken.
203
+ * @param {string} dir the Destination folder @param {string} job @param {Date} now
204
+ * @returns {{name: string|null, taken: string|null}}
205
+ */
206
+ export function nextFreeName(dir, job, now) {
207
+ const clean = String(job).replace(/[/\\\0]/g, '-').replace(/^\.+/, '') || 'report';
208
+ const pad = (/** @type {number} */ n) => String(n).padStart(2, '0');
209
+ const base = `${clean}-${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())}`;
210
+ const first = `${base}.md`;
211
+ for (let n = 1; n <= MAX_SAME_DAY; n += 1) {
212
+ const name = n === 1 ? first : `${base}-${n}.md`;
213
+ if (!present(join(dir, name))) return { name, taken: n === 1 ? null : first };
214
+ }
215
+ return { name: null, taken: first };
216
+ }
@@ -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
+ }