fwdloop 0.36.0 → 0.38.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 (107) hide show
  1. package/README.md +6 -20
  2. package/bin/fwdloop +35 -12
  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 -46
  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 +598 -61
  14. package/src/checked.js +27 -33
  15. package/src/checklistsign.js +3 -3
  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 +34 -10
  23. package/src/drafter.js +99 -74
  24. package/src/factwords.js +7 -4
  25. package/src/globprefix.js +26 -0
  26. package/src/isrec.js +2 -0
  27. package/src/line-checks.js +1 -2
  28. package/src/minrule.js +16 -0
  29. package/src/model-step.js +22 -4
  30. package/src/pageask.js +0 -3
  31. package/src/pagedropwords.js +3 -11
  32. package/src/pagedry.js +75 -1
  33. package/src/pagefetch.js +11 -6
  34. package/src/pagelook.js +2 -1
  35. package/src/pagerules.js +8 -2
  36. package/src/panel/author.js +33 -8
  37. package/src/panel/data.js +3 -2
  38. package/src/panel/index.html +177 -37
  39. package/src/panel/result.js +34 -1
  40. package/src/pickrecord.js +14 -0
  41. package/src/planrebuild.js +55 -19
  42. package/src/ratelimit.js +117 -0
  43. package/src/report.js +14 -2
  44. package/src/rowresults.js +111 -0
  45. package/src/rubricstep.js +65 -2
  46. package/src/runner.js +38 -5
  47. package/src/shapebuild.js +281 -0
  48. package/src/shapelook.js +91 -0
  49. package/src/shapemenu.js +64 -0
  50. package/src/shaperesult.js +104 -0
  51. package/src/shaperows.js +263 -0
  52. package/src/shapewords.js +140 -0
  53. package/src/sheet-record.js +1 -2
  54. package/src/sheetblock.js +1 -2
  55. package/src/sheetbuild.js +41 -29
  56. package/src/sheetchecks.js +1 -2
  57. package/src/sheetclaims.js +1 -2
  58. package/src/sheetoffer.js +1 -1
  59. package/src/sheetrows.js +10 -64
  60. package/src/sheetrun.js +1 -2
  61. package/src/ticketrows.js +2 -3
  62. package/src/try-checks.js +39 -6
  63. package/src/types.js +1 -0
  64. package/src/whole-job.js +24 -8
  65. package/types/action-stop.d.ts +1 -1
  66. package/types/auditchecks.d.ts +13 -2
  67. package/types/authoring.d.ts +21 -2
  68. package/types/blockasks.d.ts +6 -10
  69. package/types/blockassemble.d.ts +12 -13
  70. package/types/blockdraft.d.ts +3 -2
  71. package/types/blockpick.d.ts +4 -0
  72. package/types/cardlist.d.ts +18 -2
  73. package/types/checkblock.d.ts +276 -27
  74. package/types/checked.d.ts +15 -6
  75. package/types/checklook.d.ts +36 -0
  76. package/types/checkrows.d.ts +119 -0
  77. package/types/citedcheck.d.ts +4 -2
  78. package/types/closers.d.ts +10 -1
  79. package/types/drafter.d.ts +9 -4
  80. package/types/globprefix.d.ts +5 -0
  81. package/types/isrec.d.ts +1 -0
  82. package/types/minrule.d.ts +6 -0
  83. package/types/model-step.d.ts +43 -2
  84. package/types/pageask.d.ts +0 -1
  85. package/types/pagedropwords.d.ts +0 -1
  86. package/types/pagedry.d.ts +27 -0
  87. package/types/pagefetch.d.ts +3 -2
  88. package/types/pagerules.d.ts +4 -0
  89. package/types/panel/result.d.ts +16 -1
  90. package/types/pickrecord.d.ts +10 -0
  91. package/types/ratelimit.d.ts +59 -0
  92. package/types/report.d.ts +2 -1
  93. package/types/rowresults.d.ts +28 -0
  94. package/types/rubricstep.d.ts +21 -0
  95. package/types/runner.d.ts +3 -1
  96. package/types/shapebuild.d.ts +97 -0
  97. package/types/shapelook.d.ts +76 -0
  98. package/types/shapemenu.d.ts +40 -0
  99. package/types/shaperesult.d.ts +40 -0
  100. package/types/shaperows.d.ts +102 -0
  101. package/types/shapewords.d.ts +43 -0
  102. package/types/sheetbuild.d.ts +31 -13
  103. package/types/sheetrows.d.ts +5 -36
  104. package/types/ticketrows.d.ts +1 -1
  105. package/types/try-checks.d.ts +2 -1
  106. package/types/types.d.ts +4 -0
  107. package/types/whole-job.d.ts +20 -4
@@ -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 CHANGED
@@ -8,10 +8,11 @@ import { lstatSync } from 'node:fs';
8
8
  import { join } from 'node:path';
9
9
  import { sheetCheckSentence } from './sheetchecks.js';
10
10
  import { sheetTotalLines, ROW_MATH_OPS } from './sheetclaims.js';
11
+ import { isRec } from './isrec.js';
11
12
  import { lineRules } from './pagebits.js';
13
+ import { shapeResultModel, shapeMarkdown } from './shaperesult.js';
12
14
 
13
15
  const SCALAR = ['string', 'number', 'boolean'];
14
- const isRec = (/** @type {unknown} */ v) => v !== null && typeof v === 'object' && !Array.isArray(v);
15
16
 
16
17
  /** the words under a not-checked answer and a checked one (M15 am3 item 2) */
17
18
  export const NOT_CHECKED_HEADING = '### The AI\'s answer (not checked — you judge it at Accept)';
@@ -159,7 +160,7 @@ function stepSection({ artifact, checks, okIds, tables }) {
159
160
  /**
160
161
  * 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
162
  * 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
163
+ * @param {{n: number, kind: 'ask'|'work', text?: string, rules?: string[], artifact?: unknown, checks?: any[], okIds?: Set<string>|null, proseChecked?: boolean, shape?: any}[]} lines
163
164
  * @param {Record<string, any>} tables the frozen sheets by input name
164
165
  * @returns {string}
165
166
  */
@@ -168,6 +169,17 @@ export function renderReportBody(lines, tables) {
168
169
  const sections = [];
169
170
  for (const l of lines) {
170
171
  if (l.kind === 'ask') { sections.push(askLineWords(l.n)); continue; }
172
+ // borrowed-from: bareloop src/resultmd.js@v0.61.0 (the shape branch of renderRunMd)
173
+ // 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.
174
+ // 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.
175
+ if (isRec(l.shape)) {
176
+ const results = isRec(l.artifact) ? /** @type {Record<string, any>} */ (l.artifact).results : null;
177
+ if (!Array.isArray(results) || results.length === 0) continue;
178
+ const rules = lineRules({ rules: l.rules });
179
+ const head = [`## ${l.n}. ${l.text}`, ...rules.map((r) => `Rule: ${r}`)].join('\n');
180
+ sections.push([head, shapeMarkdown(shapeResultModel({ part: l.shape, results, rules }))].join('\n\n'));
181
+ continue;
182
+ }
171
183
  const sec = stepSection({ artifact: l.artifact, checks: l.checks ?? [], okIds: l.okIds ?? null, tables });
172
184
  if (sec === null) continue;
173
185
  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
+ }