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
package/src/drafter.js CHANGED
@@ -33,6 +33,8 @@ import { freezePage } from './runner.js';
33
33
  import { removeFrozenPages } from './flow.js';
34
34
  import { lookAtPage, pageInfoLines } from './pagelook.js';
35
35
  import { lookAtSheet, sheetPrompt } from './sheetlook.js';
36
+ import { lookAtShape, SHAPE_SYSTEM, SHAPE_CALL_LABEL } from './shapelook.js';
37
+ import { buildShapes } from './shapebuild.js';
36
38
  import { leftRuleLine, dropRows, dropLine } from './pagedropwords.js';
37
39
  import {
38
40
  offerRules, rowsFromAnswer, retentionOf, SUGGEST_SYSTEM, SUGGEST_TOOL, SUGGEST_SCHEMA, suggestUserText, codeScope,
@@ -41,7 +43,8 @@ import {
41
43
  import { blockJobLines } from './blocklines.js';
42
44
  import { setUpBlock, ticketLeaveOut, pickEdits, ledgerEdits, repairedEditsReadable, editRecord, renderRejectBlock, buildFaultWords, isBuildFault } from './blockdraft.js';
43
45
  import { assembleFromBlock, closeUnbuiltSheetSteps } from './blockassemble.js';
44
- import { cardOfBlock } from './cardlist.js';
46
+ import { cardOfBlock, cardOfPlanBlock } from './cardlist.js';
47
+ import { ledgerRowsOf } from './checkrows.js';
45
48
  import { questionsOfBlock } from './blockasks.js';
46
49
  import { NOTE_KIND, NOTE_TOOL, NOTE_SYSTEM, NOTE_SCHEMA, notePrompt, noteAnswers } from './noteask.js';
47
50
  import { ledgerRecord, LEDGER_SYSTEM, LEDGER_SCHEMA, LEDGER_TOOL, ledgerUserText } from './checklist.js';
@@ -56,8 +59,8 @@ import { isCellsPath } from './closers.js';
56
59
  import { parseCsv, sheetTable } from './csv.js';
57
60
  import { sheetSuggestProp, sheetOfferRules, agreedColumnWords } from './sheetoffer.js';
58
61
  import { uncoveredRules, csvRolesOf } from './sheetblock.js';
59
- import { withSheetRows, withSheetCard, sheetChoice, keyOfSameCheck } from './sheetrows.js';
60
- import { buildSheetChecks } from './sheetbuild.js';
62
+ import { withSheetRows, withSheetCard } from './sheetrows.js';
63
+ import { buildSheetChecks, unbuiltSheetLines } from './sheetbuild.js';
61
64
  import { TICKET_FIELDS, ticketRuleField, proposalReds, withTicketRows } from './ticketrows.js';
62
65
  import {
63
66
  makeProvider, ModelRefusal, sumMeterings, ceilingCostUsd, priceRecord,
@@ -359,7 +362,7 @@ function isPlainObject(v) { return !!v && typeof v === 'object' && !Array.isArra
359
362
  * @returns {Promise<{ok:boolean, declaration:object|null, reds:string[], rounds:number, calls:number, spendComplete:boolean,
360
363
  * costUsd:number|null, modelReturned:string|null, modelId?:string, price?:object|null, tokens?:object|null, structureRetries:number, revisions:number, stop:string|null, log:object[],
361
364
  * questions?:{line:number, question:string}[], proseText?:string, action?:{line:number, by?:'agent'|'you', dropped?:true}|null, droppedQuestions?:object[], notChecked?:string[], thinking?:{asked:string, status:string|null, say:string|null}, inputs?:{role:string, detail:string}[],
362
- * checkCard?:ReturnType<typeof cardOfBlock>, notCheckedBy?:Record<string,'you'|'agent'|'default'>, look?:{facts:any[], dropped:any[]}, pageLooks?:{role:string, address:string, sha256:string, bytes:number, frozen:string, attempts:number, mapping:any}[], sheetLooks?:any[]}>}
365
+ * checkCard?:ReturnType<typeof cardOfPlanBlock>, sheetBuilt?:Awaited<ReturnType<typeof buildSheetChecks>>, notCheckedBy?:Record<string,'you'|'agent'|'default'>, look?:{facts:any[], dropped:any[]}, pageLooks?:{role:string, address:string, sha256:string, bytes:number, frozen:string, attempts:number, mapping:any}[], sheetLooks?:any[], box?:string}>}
363
366
  * `learnHints` (M8 item 5a): the earlier runs' notes block (src/learnstore.js hintsForRun), appended to the drafter's system prompt; null = nothing.
364
367
  * `look` / `pageLooks` (M10 item 3) are there when the job signs a web page: the kept facts (with their `reading`, the input a later ask reads), every drop, and per page its address, sha256 and the AI's map. Each drop is also a line in `notChecked`.
365
368
  */
@@ -369,7 +372,7 @@ export async function draft({
369
372
  draftDir = /** @type {string|null} */ (null), fetchPage = undefined, leftRules = /** @type {{line: number, rule: number}[]} */ ([]), columnAnswers = /** @type {{line: number, word: string, column: string}[]} */ ([]), carriedColumns = /** @type {any[]} */ ([]), onColumns = /** @type {(rec: any[]) => void} */ (() => {}),
370
373
  checkPicks = /** @type {import('./checkpick.js').Pick[]} */ ([]),
371
374
  // M10 am17/am18: the picks of the plan this one follows (src/pickrecord.js entries), and a callback that is handed this draft's record (kept + newly answered) for the one writer
372
- carriedPicks = /** @type {import('./pickrecord.js').Entry[]} */ ([]), carriedChoices = /** @type {any[]|null} */ (null), carriedSheetDropped = /** @type {any[]} */ ([]), onSheetDropped = /** @type {(rec: any[]) => void} */ (() => {}), onChoices = /** @type {(rec: any[]) => void} */ (() => {}), onPickRecord = /** @type {((r: {picks: import('./pickrecord.js').Entry[], kept: {line: number, rule: number, ruleText: string, check: Record<string, any>|null}[]}) => void)|null} */ (null),
375
+ carriedPicks = /** @type {import('./pickrecord.js').Entry[]} */ ([]), carriedChoices = /** @type {any[]|null} */ (null), carriedSheetDropped = /** @type {any[]} */ ([]), onSheetDropped = /** @type {(rec: any[]) => void} */ (() => {}), carriedShapeDropped = /** @type {any[]} */ ([]), onShapeDropped = /** @type {(rec: any[]) => void} */ (() => {}), onChoices = /** @type {(rec: any[]) => void} */ (() => {}), onPickRecord = /** @type {((r: {picks: import('./pickrecord.js').Entry[], kept: {line: number, rule: number, ruleText: string, check: Record<string, any>|null}[]}) => void)|null} */ (null),
373
376
  learnHints = /** @type {{text: string, ids: string[]}|null} */ (null),
374
377
  mcpServers = /** @type {string[]|undefined} */ (undefined),
375
378
  // M13 piece 4: the job's flow type and its MCP pick (`mcpPickFor`: `{ok, server, tools}`), both set by code from the card; the drafter is told them, never asked for them
@@ -383,7 +386,7 @@ export async function draft({
383
386
  const status = worstThinkingStatus(log.map((e) => e.thinkingStatus));
384
387
  return { asked: draftThinking, status, say: thinkingSay(status) };
385
388
  };
386
- const fail = (reds, extra = {}) => ({
389
+ const fail = (reds, extra = /** @type {{box?: string}} */ ({})) => ({
387
390
  ok: false, declaration: null, reds, rounds: 0, calls: 0, spendComplete: true, costUsd: 0, modelReturned: null, structureRetries: 0, revisions: 0, stop: 'pre-flight', log: [], ...extra,
388
391
  });
389
392
 
@@ -392,28 +395,29 @@ export async function draft({
392
395
  if (draftThinking !== 'on' && draftThinking !== 'off') return fail([`config: draftThinking must be on | off, got ${JSON.stringify(draftThinking)}`]);
393
396
  if (actionMode !== null && actionMode !== 'check' && actionMode !== 'known') return fail([`config: actionMode must be check | known, got ${JSON.stringify(actionMode)}`]);
394
397
  const parsed = parseSignedText(proseText);
395
- if (!parsed.ok) return fail(parsed.reds.map((r) => `signed-text: ${r}`));
398
+ if (!parsed.ok) return fail(parsed.reds.map((r) => `signed-text: ${r}`), { box: 'job' });
396
399
  const { lines } = parsed;
397
400
  let { arbiter } = parsed;
398
401
  const ttlReds = unsignedAskTtls(arbiter);
399
- if (ttlReds.length) return fail(ttlReds);
402
+ if (ttlReds.length) return fail(ttlReds, { box: 'job' });
400
403
  // M4e amendment 15 item 2: a guardrail that fights itself on words is red at $0, before any provider is built or called.
401
404
  const sumReds = checkGuardrailSums(lines);
402
- if (sumReds.length) return fail(sumReds);
405
+ if (sumReds.length) return fail(sumReds, { box: 'job' });
403
406
  // M10 amendment 14 item 1: a guardrail on the send line is refused at $0 (the card says it first; a prose file straight to `fwdloop draft` is caught here).
404
407
  // M13 am11: with an actionMode the send is the card's tentative one; the refusal is made after the AI says whether the last line is the action (below)
405
408
  const sendReds = actionMode === null ? checkSendLineGuardrail(lines, arbiter) : [];
406
- if (sendReds.length) return fail(sendReds);
409
+ if (sendReds.length) return fail(sendReds, { box: 'job' });
407
410
  const menu = wiredMenu(skills);
408
411
  // The file inputs are read first, at $0, before a provider is built (a page input is fetched only after the price and cap gates, below).
409
412
  const fileFacts = readInputFacts((arbiter.sources ?? []).filter((s) => s.kind !== 'page'));
410
- if (!fileFacts.ok) return fail(fileFacts.reds);
413
+ if (!fileFacts.ok) return fail(fileFacts.reds, { box: 'inputs' });
411
414
  // M13 piece 4: with flow type Tickets, a GitHub issues list is a ticket role, not a page: never fetched at draft; the drafter is told it exists and may suggest a label filter.
412
415
  // The job's flow type and MCP (server + every tool of its newest OK check) come from the card; the refusals are at $0, before any provider is built.
413
416
  const ticketSources = flowType === 'tickets' ? ticketSourcesOf(arbiter.sources) : [];
414
417
  const servers = flowType === 'plain' ? [] : (mcpServers ?? userMcpServers());
415
418
  const flowReds = ticketReds({ flowType, ticketSources, pick: mcp, servers });
416
- if (flowReds.length) return fail(flowReds);
419
+ // M19 am14b: the Tickets list address is an Inputs line; every other flow red is about the picked MCP
420
+ if (flowReds.length) return fail(flowReds, { box: flowType === 'tickets' && ticketSources.length === 0 ? 'inputs' : 'mcp' });
417
421
 
418
422
  let { provider, rates, modelId } = { provider: injected, rates: injectedRates, modelId: injectedModelId };
419
423
  let prices = null; // the one price lookup's result (live provider only); the cap check below uses the SAME price
@@ -423,7 +427,7 @@ export async function draft({
423
427
  provider, rates, modelId, prices = null,
424
428
  } = makeProviderFn(slot, { model, env, ...LIVE_PROVIDER_OPTIONS }));
425
429
  } catch (err) {
426
- return fail([err instanceof ModelRefusal ? err.message : `${err instanceof ConfigError ? 'config' : 'key'}: ${err.message}`]);
430
+ return fail([err instanceof ModelRefusal ? err.message : `${err instanceof ConfigError ? 'config' : 'key'}: ${err.message}`], { box: 'model' });
427
431
  }
428
432
  }
429
433
 
@@ -433,7 +437,7 @@ export async function draft({
433
437
  if (!cat.ok) return fail([`catalogue: ${cat.reds.join('; ')}`]);
434
438
  const validationCatalogue = cat.primitives;
435
439
  // The hold: the picked model's own Settings prices (or the rates a test injected) times the token bounds - never a table.
436
- if (!rates) return fail(['price: this round has no price to hold - tick a model in Settings > Providers with both prices first']);
440
+ if (!rates) return fail(['price: this round has no price to hold - tick a model in Settings > Providers with both prices first'], { box: 'model' });
437
441
  const roundCeiling = ceilingCostUsd(rates);
438
442
  // M4d am13: the draft is capped by the card's Cap $ (the cap signed in the prose), the same number the run is capped at.
439
443
  // One round at its ceiling must fit that cap, or refuse at $0 before any provider call.
@@ -444,7 +448,7 @@ export async function draft({
444
448
  const tooSmall = (ceiling) => (priorUsd > 0
445
449
  ? `Cap ${usdText(arbiter.capUsd)} less ${usdText(priorUsd)} already spent on drafting leaves ${usdText(Math.max(0, budgetUsd))}, below one drafting round's worst case for ${modelId}, $${ceiling.toFixed(4)}. Raise Cap $ or pick another model.`
446
450
  : capTooSmallText('drafting', arbiter.capUsd, ceiling, modelId));
447
- if (roundCeiling > budgetUsd) return fail([tooSmall(roundCeiling)]);
451
+ if (roundCeiling > budgetUsd) return fail([tooSmall(roundCeiling)], { box: 'capUsd' });
448
452
 
449
453
  const meterings = [];
450
454
  const log = [];
@@ -501,7 +505,7 @@ export async function draft({
501
505
  for (let attempt = 1; attempt <= attempts; attempt += 1) {
502
506
  const spentBefore = meterings.reduce((sum, ev) => sum + (ev.costUsd ?? roundCeiling), 0);
503
507
  if (spentBefore + ceilingCostUsd(rates, sys.length + messages.reduce((n, m) => n + m.content.length, 0) + JSON.stringify(spec.schema).length) > budgetUsd) {
504
- if (meterings.length === 0 && calls === 0) { removeFrozenPages(/** @type {string} */ (draftDir), Object.values(pages).map((q) => q.entry.frozen)); return { early: fail([tooSmall(roundCeiling)]) }; }
508
+ if (meterings.length === 0 && calls === 0) { removeFrozenPages(/** @type {string} */ (draftDir), Object.values(pages).map((q) => q.entry.frozen)); return { early: fail([tooSmall(roundCeiling)], { box: 'capUsd' }) }; }
505
509
  return { early: earlyStop(['the draft budget is spent'], 'budget') };
506
510
  }
507
511
  /** @type {any} */
@@ -602,9 +606,9 @@ export async function draft({
602
606
  const { seenLines, toOriginal } = hideCounts(jobLines, !sheetPath ? new Set(lineNums.filter((n) => !askOrSend.has(n))) : new Set());
603
607
  const pageInfo = [];
604
608
  /** one map call (a page's or a sheet's): its hold, its metering and its book are the drafting round's own (the `kind` names it in the round log) */
605
- const makeCallModel = (kind) => async (content, attempt) => {
609
+ const makeCallModel = (kind, system = MAP_SYSTEM) => async (content, attempt) => {
606
610
  const spentSoFar = meterings.reduce((sum, ev) => sum + (ev.costUsd ?? roundCeiling), 0);
607
- if (spentSoFar + ceilingCostUsd(rates, content.length + MAP_SYSTEM.length) > budgetUsd) { mapCut = 'budget'; return { error: 'the draft budget is spent' }; }
611
+ if (spentSoFar + ceilingCostUsd(rates, content.length + system.length) > budgetUsd) { mapCut = 'budget'; return { error: 'the draft budget is spent', budget: true }; }
608
612
  const roundEvents = [];
609
613
  const mapLoop = new Loop({ provider, rates, onLlmResult: async (ev) => { roundEvents.push(ev); meterings.push(ev); } });
610
614
  calls += 1;
@@ -612,7 +616,7 @@ export async function draft({
612
616
  let res;
613
617
  let threw = null;
614
618
  try {
615
- res = await mapLoop.run([{ role: 'system', content: MAP_SYSTEM }, { role: 'user', content }], [], { maxTokens: DRAFT_MAX_TOKENS, thinkingMode: attempt === 1 ? draftThinking : 'on' });
619
+ res = await mapLoop.run([{ role: 'system', content: system }, { role: 'user', content }], [], { maxTokens: DRAFT_MAX_TOKENS, thinkingMode: attempt === 1 ? draftThinking : 'on' });
616
620
  } catch (err) {
617
621
  threw = err;
618
622
  if (roundEvents.length === 0) unmetered += 1;
@@ -621,9 +625,10 @@ export async function draft({
621
625
  const entry = { round: log.length + 1, kind };
622
626
  if (res?.thinkingApplied !== undefined) entry.thinkingApplied = res.thinkingApplied;
623
627
  if (res?.thinkingStatus !== undefined) entry.thinkingStatus = res.thinkingStatus;
624
- if (threw) { entry.outcome = `provider-red: ${threw.message}`; log.push(entry); mapCut = 'provider-red'; return { error: threw.message }; }
628
+ if (threw) { entry.outcome = `provider-red: ${threw.message}`; log.push(entry); mapCut = 'provider-red'; return { error: threw.message, threw }; }
625
629
  const cutOff = res?.stopReason === 'max_tokens';
626
630
  entry.outcome = cutOff ? 'truncated' : 'answered';
631
+ if (kind === SHAPE_CALL_LABEL && typeof res?.text === 'string' && res.text !== '') entry.rawText = res.text;
627
632
  log.push(entry);
628
633
  if (res?.error && !cutOff) return { error: String(res.error) };
629
634
  return { text: res?.text ?? '', cutOff };
@@ -634,7 +639,7 @@ export async function draft({
634
639
  const mapCeiling = ceilingCostUsd(rates, mapPrompt({ jobLines: seenLines, label: s.role, text: pg.text }).length + MAP_SYSTEM.length);
635
640
  const spentBefore = meterings.reduce((sum, ev) => sum + (ev.costUsd ?? roundCeiling), 0);
636
641
  if (spentBefore + mapCeiling > budgetUsd) {
637
- if (meterings.length === 0 && calls === 0) { removeFrozenPages(/** @type {string} */ (draftDir), Object.values(pages).map((q) => q.entry.frozen)); return fail([tooSmall(mapCeiling)]); }
642
+ if (meterings.length === 0 && calls === 0) { removeFrozenPages(/** @type {string} */ (draftDir), Object.values(pages).map((q) => q.entry.frozen)); return fail([tooSmall(mapCeiling)], { box: 'capUsd' }); }
638
643
  }
639
644
  const callModel = makeCallModel('page-map');
640
645
  const got0 = await lookAtPage({ label: s.role, text: pg.text, jobLines: seenLines, callModel });
@@ -694,7 +699,7 @@ export async function draft({
694
699
  const text = headings === undefined ? facts.sheets[role] : '';
695
700
  const spentBefore = meterings.reduce((sum, ev) => sum + (ev.costUsd ?? roundCeiling), 0);
696
701
  const hold = ceilingCostUsd(rates, sheetPrompt({ jobLines: sheetJobLines, label: role, text, headings }).length + MAP_SYSTEM.length);
697
- if (spentBefore + hold > budgetUsd && meterings.length === 0 && calls === 0) { removeFrozenPages(/** @type {string} */ (draftDir), Object.values(pages).map((q) => q.entry.frozen)); return fail([tooSmall(hold)]); }
702
+ if (spentBefore + hold > budgetUsd && meterings.length === 0 && calls === 0) { removeFrozenPages(/** @type {string} */ (draftDir), Object.values(pages).map((q) => q.entry.frozen)); return fail([tooSmall(hold)], { box: 'capUsd' }); }
698
703
  const got = await lookAtSheet({ label: role, text, headings, jobLines: sheetJobLines, callModel: makeCallModel('sheet-map') });
699
704
  if (!got.ok) {
700
705
  const m = sumMeterings(meterings);
@@ -728,6 +733,12 @@ export async function draft({
728
733
  const blockPlan = blockJobLines(proseText, undefined, [...new Set([...sheetFacts.filter((f) => f.forRule !== undefined), ...sheetAsks, ...sheetLooks.flatMap((l) => l.dropped)].map((x) => x.line)), ...csvRuleLines]);
729
734
  if (blockPlan && !blockPlan.ok) return fail(blockPlan.reds.map((r) => `signed-text: ${r}`));
730
735
  const blockLineNums = new Set(blockPlan ? blockPlan.jobLines.map((l) => l.n) : []);
736
+ // M19 S3: the sheet lines (a CSV input and a line with `~` rules that the list's own rows do not take) are the check block's too: it holds their rules and their sheet checks (src/checkblock.js `setSheet`), the AI names a sheet line by its job number
737
+ const sheetTables = Object.keys(facts.sheets ?? {}).length ? Object.fromEntries(Object.entries(facts.sheets).map(([role, t]) => [role, sheetTable(parseCsv(t))])) : undefined;
738
+ const sheetRoleList = sheetTables ? Object.keys(sheetTables) : [];
739
+ const sendLines = new Set(arbiter.sends.map((x) => x.line));
740
+ const sheetLineNums = sheetRoleList.length > 0 ? jobLines.filter((l) => !askLines.has(l.n) && !sendLines.has(l.n) && !blockLineNums.has(l.n) && lineRules(l).length > 0).map((l) => l.n) : [];
741
+ const sheetTurn = sheetLineNums.length > 0;
731
742
  // M17 am4 (A3, B5): the list is the one place a shape rule is asked and picked; a line the list is not given (a sheet line) has no pick path of its own
732
743
  const allShape = shapeEverywhere.filter((r) => blockLineNums.has(r.line));
733
744
  // M10 am17/am18: a guardrail whose pick is kept from the last draft skips the suggestion call and the asks; only the rest is suggested and asked. The model never sees a pick.
@@ -740,10 +751,13 @@ export async function draft({
740
751
  let block = null;
741
752
  if (blockPlan?.ok) {
742
753
  const inBlock = (/** @type {{line: number}} */ x) => blockLineNums.has(x.line);
754
+ const sheetBlockLines = sheetTurn ? (() => { const all = blockJobLines(proseText); return all.ok ? all.jobLines.filter((l) => sheetLineNums.includes(l.n)) : []; })() : [];
755
+ // the page look is about the page inputs: its facts and drops on a sheet line are not rows of the block
756
+ const notSheet = (/** @type {{line: number}} */ x) => !sheetLineNums.includes(x.line);
743
757
  block = setUpBlock({
744
- texts: { ...(facts.docs ?? {}), ...Object.fromEntries(Object.entries(pages).map(([role, pg]) => [role, pg.text])) }, jobLines: blockPlan.jobLines, look,
758
+ texts: { ...(facts.docs ?? {}), ...Object.fromEntries(Object.entries(pages).map(([role, pg]) => [role, pg.text])) }, jobLines: [...blockPlan.jobLines, ...sheetBlockLines].sort((a, b) => a.n - b.n), look: { facts: look.facts.filter(notSheet), dropped: look.dropped.filter(notSheet) },
745
759
  kept: { picks: carried.picks.filter(inBlock), left: carried.left.filter(inBlock), askRules: carried.askRules.filter(inBlock) },
746
- fresh: { picks: checkPicks.filter(inBlock), left: leftRules.filter(inBlock) }, asks: offerQuestions, countScope: (t) => codeScope(arbiter.sources, t) === 'in', leaveOut: ticketLeaveOut(flowType, blockPlan.jobLines),
760
+ fresh: { picks: checkPicks.filter(inBlock), left: leftRules.filter(inBlock) }, asks: offerQuestions, countScope: (t) => codeScope(arbiter.sources, t) === 'in', leaveOut: ticketLeaveOut(flowType, blockPlan.jobLines), sheetLines: sheetLineNums,
747
761
  });
748
762
  }
749
763
  if (askRules.length && offerQuestions) {
@@ -766,16 +780,16 @@ export async function draft({
766
780
  // a Revise keeps the last draft's Drop/Add choices (the suggestions exist now); code still judges every one when the list is reconciled
767
781
  if (block && Array.isArray(carriedChoices)) { block.carryChoices(carriedChoices); onChoices(block.choicesRecord()); block.reconcile(); }
768
782
  /** the questions of the block, merged below with the sheet's and the look's own, under one cap (M16 S3) */
769
- const blockAsks = block && offerQuestions ? questionsOfBlock(block, allShape) : [];
770
- if (block) pageExtras.checkRows = ledgerRecord(/** @type {any} */ (block.rows));
783
+ const blockAsks = block && offerQuestions ? questionsOfBlock(block) : [];
784
+ if (block) pageExtras.checkRows = ledgerRecord(/** @type {any} */ (block.rows.filter((r) => !block.isSheetLine(r.line))));
771
785
  // M10 piece 3 (item 4, am1, am2): CODE decides the early asks from the look, after the one map call and BEFORE any drafting round. A signed ask line's own
772
786
  // guardrail is a human stop, not a page check, so it is not asked. More than MAX_LOOK_ASKS is a job to rewrite: nothing is asked, nothing more is spent.
773
787
  // The redraft after the answers (offerQuestions false) never asks. A sheet's offers are reading asks: they come first with the page's, in line order.
774
788
  if ((sheetAsks.length || blockAsks.length || actionAsk !== null) && offerQuestions) {
775
789
  // M17 am4 (A1): a question comes from the list (questionsOfBlock) or is the sheet's column offer (M17 am1 1(a)); no question is asked outside the list
776
- const lookAsks = [...[...sheetAsks, ...blockAsks.filter((a) => a.ask === 'reading')].sort((a, b) => a.line - b.line), ...blockAsks.filter((a) => a.ask === 'cant-check')];
790
+ const lookAsks = [...[...sheetAsks, ...blockAsks.filter((a) => a.ask === 'reading')].sort((a, b) => a.line - b.line)];
777
791
  // am16 (3): a shape guardrail's ask follows, in line order. (5): a proposal is not an ask under am1; only a `can't check` ask counts toward the cap (the 4th stops drafting at $0).
778
- const blockShape = blockAsks.filter((a) => a.ask === 'no-check' || a.ask === 'check');
792
+ const blockShape = blockAsks.filter((a) => a.ask === 'check');
779
793
  const asks = [...lookAsks, ...blockShape, ...(actionAsk === null ? [] : [actionAsk])];
780
794
  if (asks.length > 0) {
781
795
  const m = sumMeterings(meterings);
@@ -794,20 +808,35 @@ export async function draft({
794
808
  }
795
809
  // the record this draft hands on: what it kept plus what the person just answered (numbered on this card)
796
810
  onPickRecord?.({ picks: [...carried.kept.map((k) => k.entry), ...entriesFromAnswers(lines, allShape, checkPicks, leftRules)], kept: keptView });
811
+ // borrowed-from: bareloop src/authorjob.js@v0.61.0 (fc56e1f3) (:788-813, the shape look after the page look, the sheet look, the asks and the person's answers)
812
+ // SHAPE JOBS: the shape look is asked ONLY about the `~` rules still Not checked once every truth check, the answers and the asks are settled (`shapeCandidates`, code decides). No candidate = no call, and the draft is byte-identical.
813
+ // The AI only suggests; code builds or refuses each field (src/shapebuild.js). A look that fails, is unreadable or is capped never stops the draft: its spend stays booked, one draft-log line says so, and it goes on without a shape.
814
+ if (block && blockPlan?.ok) {
815
+ const left = block.shapeCandidates();
816
+ if (left.length > 0) {
817
+ const lineNums = [...new Set(left.map((x) => x.line))].sort((a, b) => a - b);
818
+ const got = await lookAtShape({
819
+ texts: block.texts, jobLines: blockPlan.jobLines, lineNums, left: lineNums.map((n) => ({ line: n, rules: left.filter((x) => x.line === n).map((x) => x.rule) })), ceilingUsd: arbiter.capUsd,
820
+ callModel: makeCallModel(SHAPE_CALL_LABEL, SHAPE_SYSTEM),
821
+ });
822
+ if (!got.ok) log.push({ round: log.length + 1, kind: 'shape-skipped', reason: got.reason, line: `the shape look did not complete: ${got.reason}; going on without a shape` });
823
+ else if (got.shapes.length > 0) {
824
+ block.setShape(buildShapes({ lines: blockPlan.jobLines.filter((l) => lineRules(l).length > 0 && !block.isSheetLine(l.n)), labels: block.labels, suggestions: got.shapes }));
825
+ block.carryShapeDropped(carriedShapeDropped);
826
+ }
827
+ block.reconcile();
828
+ }
829
+ }
797
830
  // M16 S2 + S4: the AI's two helpers send edits to the list, then the row-edit turn; code judges every edit alone (src/checkblock.js). The declaration path below runs as before (S5 assembles from the rows).
798
831
  // a line with nothing to check (no `~` rule of the person's, no input text for a `!` row to be built from) has no list to edit: no turn is paid for it (M16 item 2, "every job line with checks")
799
- // M10b piece 3: the drafting copy's table of each CSV input - the header the AI may pick from in its suggestions, the table bareguard's build and sign-time tests run over
800
- const sheetTables = Object.keys(facts.sheets ?? {}).length ? Object.fromEntries(Object.entries(facts.sheets).map(([role, t]) => [role, sheetTable(parseCsv(t))])) : undefined;
832
+ // M10b piece 3: the drafting copy's table of each CSV input (`sheetTables`, above) - the header the AI may pick from in its suggestions, the table bareguard's build and sign-time tests run over
801
833
  /** M17 am2: the sheet checks the AI suggested on the row-edit reply (typed, each with its job line); code builds or refuses each (src/sheetbuild.js) @type {any[]} */
802
834
  let sheetSuggested = [];
835
+ /** @type {Awaited<ReturnType<typeof buildSheetChecks>>|null} */
836
+ let sheetBuilt = null;
803
837
  /** M17 am6: the Tickets filter and watch the AI suggested as an edit of the list: the last legal value of each, and what was refused (code proves each, src/ticketrows.js) @type {{ticketFilter?: any, ticketWatch?: any, refused: Record<string, string>}} */
804
838
  const ticketProposal = { refused: {} };
805
839
  const ticketRuleOnJob = flowType === 'tickets' && blockPlan?.ok === true && blockPlan.jobLines.some((l) => (l.rules ?? []).some((t) => ticketRuleField(t) !== null));
806
- const sheetRoleList = sheetTables ? Object.keys(sheetTables) : [];
807
- // the sheet lines: a line with `~` rules the list's own rows do not take (and no ask or send line); the AI names a sheet line by its job number, and only one of these
808
- const sendLines = new Set(arbiter.sends.map((x) => x.line));
809
- const sheetLineNums = sheetRoleList.length > 0 ? jobLines.filter((l) => !askLines.has(l.n) && !sendLines.has(l.n) && !blockLineNums.has(l.n) && lineRules(l).length > 0).map((l) => l.n) : [];
810
- const sheetTurn = sheetLineNums.length > 0;
811
840
  if (block && blockPlan?.ok && (blockPlan.jobLines.length > 0 || sheetTurn) && (Object.keys(block.texts).length > 0 || block.rows.some((r) => r.kind === 'rule') || ticketRuleOnJob || sheetTurn)) {
812
841
  // M17 am2: with a CSV input the turn also shows the sheet lines and the sheets; the sheet checks come back as typed suggestions
813
842
  const texts = { ...block.texts, ...(facts.sheets ?? {}) };
@@ -837,7 +866,18 @@ export async function draft({
837
866
  if (refused.length === 0 || rev >= MAX_REVISIONS) break;
838
867
  turn = [...turn, { role: 'assistant', content: JSON.stringify(got.args) }, { role: 'user', content: `${renderRejectBlock(refused.map((e) => `edit ${String(e?.op)}: ${String(e.refusedBecause)}`))}\n\n${ROW_EDIT_REVISE}` }];
839
868
  }
840
- pageExtras.checkRows = ledgerRecord(/** @type {any} */ (block.rows));
869
+ // M19 S3 (bareloop's order): the sheet checks code built from the reply's suggestions become the block's own rows after the AI's edits; a Revise keeps a Drop of the very same check
870
+ if (sheetTurn && sheetTables) {
871
+ sheetBuilt = await buildSheetChecks({ lines: lines.filter((l) => sheetLineNums.includes(l.n)), tables: sheetTables, suggestions: sheetSuggested });
872
+ block.setSheet(sheetBuilt);
873
+ block.carrySheetDropped(carriedSheetDropped);
874
+ onSheetDropped(block.sheetDroppedRecord());
875
+ pageExtras.sheetBuilt = sheetBuilt;
876
+ }
877
+ // shape jobs: a Revise keeps a Drop of the very same shape field (the block's own record, beside the sheet's)
878
+ if (carriedShapeDropped.length) block.carryShapeDropped(carriedShapeDropped);
879
+ onShapeDropped(block.shapeDroppedRecord());
880
+ pageExtras.checkRows = ledgerRecord(/** @type {any} */ (block.rows.filter((r) => !block.isSheetLine(r.line))));
841
881
  }
842
882
  // M17 am1 1(e): the note question, ONE forced turn, only when a line of the list is facts-only after the AI's edits (src/noteask.js). The typed answer goes to the block; code decides what it means.
843
883
  // The answers ride the turn's log entry (`notes`), the one place the replay (src/planrebuild.js) reads them from, a failed turn included.
@@ -850,7 +890,7 @@ export async function draft({
850
890
  const answers = noteAnswers(asked, nq.args, askedLines);
851
891
  nq.entry.notes = answers;
852
892
  block.setNotes(answers);
853
- pageExtras.checkRows = ledgerRecord(/** @type {any} */ (block.rows));
893
+ pageExtras.checkRows = ledgerRecord(/** @type {any} */ (block.rows.filter((r) => !block.isSheetLine(r.line))));
854
894
  }
855
895
  }
856
896
  // The page lines go on the drafter's list of inputs: the first line of a page's block replaces the plain line readInputFacts wrote for it.
@@ -996,7 +1036,7 @@ export async function draft({
996
1036
  if (Array.isArray(declaration.steps)) {
997
1037
  declaration.steps = declaration.steps.map((st) => (isPlainObject(st) ? { ...st, goal: goalForLine(st.fromLine, lines) } : st));
998
1038
  }
999
- // M13 am9 item 4: the last Ask before the added `write it out` reads every step; code sets it, whatever the model sent
1039
+ // M13 am9 item 4: the last Ask before the action reads every step; code sets it, whatever the model sent
1000
1040
  if (Array.isArray(declaration.steps)) declaration.steps = readEveryStep(declaration.steps, arbiter);
1001
1041
  // M10 am16 (4): the drafter writes no check. Whatever `close.shape` it sent (the schema offers none) is dropped here; a check reaches the plan only from the list's built rows (assembleFromBlock).
1002
1042
  delete declaration.unjudgeable; // M17 am4 (C8): the hidden can't-judge record is gone; a line's Not checked reasons are the list's rows
@@ -1011,54 +1051,37 @@ export async function draft({
1011
1051
  }
1012
1052
  // M16 S6: the checks of the block's lines are the block's built parts; whatever the AI wrote for them is gone, and the list that proves it is signed with the plan
1013
1053
  delete declaration.checkList;
1054
+ // M17 am2 item 2: the AI writes no sheet check: a declaration that carries `close.sheet` is refused (a red naming the field, no check run). The checks are the block's own (M19 S3: `setSheet`, from the row-edit reply's
1055
+ // suggestions, which code refused or built on bareguard, src/sheetbuild.js); the assembly below writes them into the step that reads the sheet
1056
+ let carriedSheet = false;
1057
+ if (sheetTables) {
1058
+ declaration.steps = (Array.isArray(declaration.steps) ? declaration.steps : []).map((/** @type {any} */ st) => {
1059
+ if (!isPlainObject(st) || !isPlainObject(st.close)) return st;
1060
+ const { sheet: carried, ...close } = st.close;
1061
+ if (carried !== undefined) carriedSheet = true;
1062
+ return { ...st, close };
1063
+ });
1064
+ }
1014
1065
  let assembled = null;
1015
1066
  if (block && blockPlan?.ok) {
1016
- assembled = assembleFromBlock({ declaration, block, lines, lineSet: blockLineNums, askLines });
1067
+ assembled = assembleFromBlock({ declaration, block, lines, lineSet: blockLineNums, askLines, sheetRoles: sheetRoleList });
1017
1068
  Object.assign(declaration, assembled.declaration);
1018
1069
  if (assembled.declaration.pickedLines === undefined) delete declaration.pickedLines;
1019
1070
  }
1020
- // M17 am2: the AI writes no sheet check. What it sent as `close.sheet` is a typed suggestion; code refuses or builds each one on bareguard (src/sheetbuild.js) and writes the checks, with its own ids
1021
- /** @type {Awaited<ReturnType<typeof buildSheetChecks>>|null} */
1022
- let sheetBuilt = null;
1023
- let carriedSheet = false;
1024
1071
  /** @type {ReturnType<typeof closeUnbuiltSheetSteps>|null} */
1025
1072
  let sheetHitl = null;
1026
1073
  if (sheetTables) {
1027
- // M17 am2 item 2: a declaration that carries `close.sheet` is refused (a red naming the field, no check run); the suggestions are the row-edit reply's, put on the step that reads the sheet by code
1028
- const roles = Object.keys(sheetTables);
1029
- const given = new Set();
1030
- declaration.steps = (Array.isArray(declaration.steps) ? declaration.steps : []).map((/** @type {any} */ st) => {
1031
- if (!isPlainObject(st) || !isPlainObject(st.close)) return st;
1032
- const { sheet: carried, ...close } = st.close;
1033
- if (carried !== undefined) carriedSheet = true;
1034
- const mine = close.class === 'green' && Array.isArray(st.reads) && st.reads.some((/** @type {string} */ r) => roles.includes(r)) && !given.has(st.fromLine) ? sheetSuggested.filter((x) => x.line === st.fromLine).map(({ line: _l, ...x }) => x) : [];
1035
- if (mine.length) given.add(st.fromLine);
1036
- return { ...st, close: mine.length ? { ...close, sheet: mine } : close };
1037
- });
1038
- const unplaced = sheetSuggested.filter((x) => !given.has(x.line)).map((x) => ({ line: x.line, helper: 'line', why: `line ${String(x.line)} has no green step that reads a sheet` }));
1039
- sheetBuilt = await buildSheetChecks({ declaration, lines, tables: sheetTables });
1040
- Object.assign(declaration, { steps: sheetBuilt.declaration.steps });
1074
+ // a suggestion for a line with no green step that reads a sheet has nowhere to go (recorded, as before)
1075
+ const placedLines = new Set((Array.isArray(declaration.steps) ? declaration.steps : []).filter((/** @type {any} */ st) => isPlainObject(st) && isPlainObject(st.close) && st.close.class === 'green' && Array.isArray(st.reads) && st.reads.some((/** @type {string} */ r) => sheetRoleList.includes(r))).map((/** @type {any} */ st) => st.fromLine));
1076
+ const unplaced = sheetSuggested.filter((x) => !placedLines.has(x.line)).map((x) => ({ line: x.line, helper: 'line', why: `line ${String(x.line)} has no green step that reads a sheet` }));
1041
1077
  // M17 am5 / P5: a sheet step the builder built no check for is closed here (its class is the assembly's decision), its rules Not checked below
1042
- const closed = closeUnbuiltSheetSteps(declaration, sheetBuilt.unbuilt);
1078
+ const closed = closeUnbuiltSheetSteps(declaration, unbuiltSheetLines({ declaration, lines, roles: sheetRoleList, notChecked: sheetBuilt?.notChecked ?? {} }));
1043
1079
  Object.assign(declaration, closed.declaration);
1044
1080
  sheetHitl = closed;
1045
- if (sheetBuilt.refused.length || unplaced.length) entry.sheetRefused = [...unplaced, ...sheetBuilt.refused];
1081
+ if ((sheetBuilt?.refused.length ?? 0) > 0 || unplaced.length) entry.sheetRefused = [...unplaced, ...(sheetBuilt?.refused ?? [])];
1046
1082
  }
1047
- // M16 am4 (2): a sheet line's checks are rows on the same list (code builds them, src/sheetbuild.js; src/sheetrows.js reads them as rows)
1083
+ // M16 am4 (2): a sheet line's checks are rows on the same list (the block holds them, src/checkblock.js; src/sheetrows.js reads them as rows)
1048
1084
  let sheetOnList = null;
1049
- /** @type {any[]} */
1050
- let sheetDroppedNow = [];
1051
- if (block) {
1052
- // hamr 2026-11-14: a Revise keeps a sheet Drop - a new check with the id of a carried dropped one starts dropped again (only an `[agent]` row can be dropped; one that now covers a `~` rule stays)
1053
- for (const d of carriedSheetDropped) {
1054
- // M17 am3: code names every check, so the Drop is kept for the very same check (its typed fields), never for an id that may name another one now
1055
- const key = keyOfSameCheck(declaration, d);
1056
- if (key === null) continue;
1057
- const r = sheetChoice({ declaration, lines, csvRoles: csvRolesOf(arbiter), op: 'drop', key, dropped: sheetDroppedNow });
1058
- if (r.ok) { Object.assign(declaration, { steps: r.declaration.steps }); sheetDroppedNow = r.dropped; }
1059
- }
1060
- onSheetDropped(sheetDroppedNow);
1061
- }
1062
1085
  /** @type {ReturnType<typeof withTicketRows>['tickets']|null} */
1063
1086
  let ticketOnList = null;
1064
1087
  if (block && flowType === 'tickets') { const w = withTicketRows({ declaration, lines }); ticketOnList = w.tickets; if (w.tickets.signed.length) Object.assign(declaration, { checkList: w.declaration.checkList }); }
@@ -1117,9 +1140,11 @@ export async function draft({
1117
1140
  if (verdict.ok) {
1118
1141
  entry.outcome = 'valid';
1119
1142
  log.push(entry);
1143
+ // M19 am8 item 1, am9 item 5: the draft's ledger rows, one per Not checked row, in its own log (no new file); a row's words are the build's name for it
1144
+ if (block) log.push(...ledgerRowsOf(declaration, lines, Object.fromEntries(block.rows.filter((r) => r.kind !== 'rule').map((r) => [r.key, r.name ? [r.name] : r.words ?? []]))));
1120
1145
  const m = sumMeterings(meterings);
1121
1146
  return withAction({
1122
- ok: true, declaration, reds: [], rounds: m.rounds, calls, spendComplete: unmetered === 0 && m.costUsd !== null, costUsd: m.costUsd, modelReturned: m.model, modelId, price: priceRecord(prices, rates), tokens: m.tokens, structureRetries, revisions, stop: null, log, thinking: thinkingOf(), inputs: facts.list, ...extras, ...pageExtras, ...(block ? { checkCard: (() => { const c = sheetOnList ? withSheetCard(cardOfBlock(block), sheetOnList, sheetDroppedNow) : cardOfBlock(block); return ticketOnList?.card.length ? withSheetCard(c, { card: ticketOnList.card }) : c; })() } : {}),
1147
+ ok: true, declaration, reds: [], rounds: m.rounds, calls, spendComplete: unmetered === 0 && m.costUsd !== null, costUsd: m.costUsd, modelReturned: m.model, modelId, price: priceRecord(prices, rates), tokens: m.tokens, structureRetries, revisions, stop: null, log, thinking: thinkingOf(), inputs: facts.list, ...extras, ...pageExtras, ...(block ? { checkCard: (() => { const c = sheetOnList ? withSheetCard(cardOfBlock(block), sheetOnList) : cardOfBlock(block); return cardOfPlanBlock(block, ticketOnList?.card.length ? withSheetCard(c, { card: ticketOnList.card }) : c, { declaration, lines, csvRoles: csvRolesOf(arbiter), log }); })() } : {}),
1123
1148
  });
1124
1149
  }
1125
1150
  lastReds = [...verdict.reds];
package/src/factwords.js CHANGED
@@ -91,14 +91,17 @@ export function checkFactWords({ part, text, line, scan = scanLabels(text), kept
91
91
  }
92
92
  if (f.until !== undefined) dropRed('closing label', f.until);
93
93
  if (f.until !== undefined && countExact(text, f.until) < 1) red('rubric-fact-word-missing', `${who}: ${JSON.stringify(f.until)} is not in the input "${src}". Copy the closing words from the input, or leave them out.`);
94
- if (f.shape === 'phrase' && typeof f.phrase === 'string') {
95
- const seen = countPhrase(text, f.phrase);
96
- if (seen < 1) red('rubric-fact-word-missing', `${who}: ${JSON.stringify(f.phrase)} is not in the input "${src}". Copy the words the input really uses, or remove the check.`);
94
+ // M19 am5: a several-word phrase fact (anyOf) holds when the page says ANY of its words; the count of results is the words' counts together
95
+ const phraseOf = f.shape === 'phrase' ? (Array.isArray(f.anyOf) ? f.anyOf : typeof f.phrase === 'string' ? [f.phrase] : null) : null;
96
+ if (phraseOf) {
97
+ const shown = Array.isArray(f.anyOf) ? phraseOf.map((/** @type {string} */ x) => JSON.stringify(x)).join(', ') : JSON.stringify(f.phrase);
98
+ const seen = phraseOf.reduce((/** @type {number} */ n, /** @type {string} */ x) => n + countPhrase(text, x), 0);
99
+ if (seen < 1) red('rubric-fact-word-missing', `${who}: ${shown} is not in the input "${src}". Copy the words the input really uses, or remove the check.`);
97
100
  else if (Number.isInteger(part.count?.min) && seen < part.count.min) {
98
101
  // M4: the words each result's quote must say must repeat as often as results were asked for; page-header words (counted
99
102
  // once or twice) are in no result, so no one-result quote can say them
100
103
  const n = part.count.min;
101
- red('rubric-fact-phrase-rare', `${who}: the words ${JSON.stringify(f.phrase)} are in the input "${src}" only ${seen} time${seen === 1 ? '' : 's'}, but this line asks for ${n} results - each result's own quote must say them. Pick words every result says, or drop this check.`);
104
+ red('rubric-fact-phrase-rare', `${who}: the words ${shown} are in the input "${src}" only ${seen} time${seen === 1 ? '' : 's'}, but this line asks for ${n} results - each result's own quote must say them. Pick words every result says, or drop this check.`);
102
105
  }
103
106
  }
104
107
  // a unit (one string, or every one of a list) must be found as whole words; a currency sign (each of a list) must be found as written
@@ -0,0 +1,26 @@
1
+ // borrowed-from: bareloop src/validate.js@v0.60.0 (globToPrefix only; the rest of that file is bareloop's job validator and is not wanted here)
2
+ // The one canonical spelling of a scope's path prefix. The check block's repo rows (src/checkblock.js `inScope`) read it; fwd has no repo job and never sets the block's `repo` option, so nothing in fwd calls it.
3
+
4
+ /**
5
+ * @param {string} scope
6
+ * @returns {string}
7
+ */
8
+ export function globToPrefix(scope) {
9
+ // One canonical spelling for equivalent paths — leading "./", interior "/./",
10
+ // doubled "//", trailing "/" all collapse — so the legality rule, the fence
11
+ // comparison, and bareguard enforcement agree on what a scope NAMES. Without
12
+ // this, a validateJob-green fence like "src/" would reject every workflow
13
+ // scope inside it (the F9 red-class across two documents).
14
+ //
15
+ // Order is load-bearing: "//" collapses and interior "/./" drops BEFORE the
16
+ // leading "./" strip, so ".//src" → "src" and never "/src". Stripping first
17
+ // would MINT an absolute prefix from a relative scope — a design-law-#1
18
+ // containment escape (resolve(workdir, "/src") ignores workdir entirely).
19
+ //
20
+ // Deliberately NOT path.posix.normalize: it resolves ".." segments
21
+ // (normalize("src/../etc") === "etc"), which must stay VISIBLE so
22
+ // scopeContained can reject them — the whole point of the containment law.
23
+ let p = scope.replace(/\/\*\*?$/, '');
24
+ p = p.replace(/\/{2,}/g, '/').replace(/\/\.(?=\/|$)/g, '').replace(/^(?:\.\/)+/, '').replace(/\/+$/, '');
25
+ return p;
26
+ }
package/src/isrec.js ADDED
@@ -0,0 +1,2 @@
1
+ // one owner for the plain-object predicate (fwd's own files; borrowed copies keep theirs)
2
+ export const isRec = (/** @type {unknown} */ v) => v !== null && typeof v === 'object' && !Array.isArray(v);
@@ -5,14 +5,13 @@
5
5
  import { writeFileSync, renameSync } from 'node:fs';
6
6
  import { join } from 'node:path';
7
7
  import { readFileInside } from './flow.js';
8
+ import { isRec } from './isrec.js';
8
9
 
9
10
  /** the record's name in the run's own folder */
10
11
  export const LINE_CHECKS_FILE = 'line-checks.json';
11
12
 
12
13
  /** @typedef {'cited'|'sheet'} LineSection */
13
14
 
14
- const isRec = (/** @type {unknown} */ v) => v !== null && typeof v === 'object' && !Array.isArray(v);
15
-
16
15
  /** The whole file as parsed, or why not. @param {string} runDir @returns {{ok: true, rec: Record<string, any>}|{ok: false, missing: boolean, red: string}} */
17
16
  function readWhole(runDir) {
18
17
  const r = readFileInside(runDir, LINE_CHECKS_FILE);
package/src/minrule.js ADDED
@@ -0,0 +1,16 @@
1
+ // M19 amendment 13: a job needs at least one `~` rule of the person's. The ONE writer of the refusal words; the ONE count is the drafter's own reader
2
+ // (parseSignedText) with the block's own splitter (rulesOfLine). `!` and `$` rows are never in the prose, so only typed `~` lines count.
3
+ import { parseSignedText } from './signed-text.js';
4
+ import { rulesOfLine } from './sheetblock.js';
5
+
6
+ export const MIN_RULE_REFUSAL = 'Add at least one rule (~) for this job — for example what the result must include, or what must stay true.';
7
+
8
+ /**
9
+ * @param {string} prose the job prose `fwdloop draft` reads
10
+ * @returns {string|null} the refusal words, or null when the prose carries at least one `~` rule. Prose the reader cannot parse is not this gate's to refuse (the drafter's own red wins).
11
+ */
12
+ export function minRuleRefusal(prose) {
13
+ const p = parseSignedText(prose);
14
+ if (!p.ok) return null;
15
+ return p.lines.reduce((n, l) => n + rulesOfLine(l).length, 0) === 0 ? MIN_RULE_REFUSAL : null;
16
+ }
package/src/model-step.js CHANGED
@@ -31,11 +31,14 @@ import { appendCall, appendTool, nextRound } from './diary.js';
31
31
  import { ConfigError } from './config.js';
32
32
  import { worstThinkingStatus } from './thinking.js';
33
33
  import { citedBrief, toldPicks } from './citedcheck.js';
34
+ import { shapeBriefOf, shapeLineBrief } from './rubricstep.js';
35
+
34
36
  import { sheetAnswerProps, sheetBrief } from './sheetclaims.js';
35
37
 
36
38
  import {
37
39
  makeProvider, ModelRefusal, sumMeterings, appendSpendRow, classifyModelId, priceRecord,
38
40
  } from './provider.js';
41
+ import { isRec } from './isrec.js';
39
42
 
40
43
  // F27: a provider's `chat/completions` can send HTTP 200 + headers + one byte
41
44
  // then nothing — a "zombie stream" that `timeoutMs`'s idle bound never
@@ -138,14 +141,27 @@ const CITED_SCHEMA = Object.freeze({
138
141
  additionalProperties: false,
139
142
  });
140
143
 
144
+ // M19 S5: a step whose line is a list of items and nothing else (its close carries `itemShape` and no `cited`) answers `{results: [...]}`, one object per item; the check (src/closers.js closeItemShape, bareguard's `itemShape`)
145
+ // reads the fields, so the schema asks only for the list
146
+ const LIST_SCHEMA = Object.freeze({
147
+ type: 'object',
148
+ properties: {
149
+ results: { type: 'array', items: { type: 'object' } },
150
+ ...DONE_PROPS,
151
+ },
152
+ required: ['results', 'done'],
153
+ additionalProperties: false,
154
+ });
155
+
141
156
  /**
142
157
  * Build the `emit_artifact` tool schema from a step's declared close CLASS
143
158
  * only (plus, for a green step that quotes a saved page, the form of its answer).
144
159
  * `stepClass` is `'green' | 'softgreen' | 'hitl' | null | undefined`; `cited` is true for that green step.
145
160
  */
146
161
  /** @param {string|null|undefined} stepClass @param {boolean} [cited] @param {any[]|null} [sheet] M10b piece 2: the step's `close.sheet` (its claim boxes become the answer) @param {boolean} [withText] M10 am22: a fact step with the person's picks also answers in `text` (the picks read it) */
147
- export function buildEmitArtifactSchema(stepClass, cited = false, sheet = null, withText = false) {
162
+ export function buildEmitArtifactSchema(stepClass, cited = false, sheet = null, withText = false, items = false) {
148
163
  const text = withText ? { text: { type: 'string' } } : {};
164
+ if (items && !cited && (stepClass === 'green' || stepClass === 'softgreen')) return { ...LIST_SCHEMA, properties: { ...LIST_SCHEMA.properties, ...text }, required: [...LIST_SCHEMA.required.slice(0, 1), ...(withText ? ['text'] : []), 'done'] };
149
165
  if (stepClass === 'green' && Array.isArray(sheet)) {
150
166
  // M10b piece 2: a step that reads a sheet answers in one typed box per claim (bareguard's shapes), never a cite
151
167
  const { properties, required } = sheetAnswerProps(sheet);
@@ -334,7 +350,7 @@ function stoppedResult(cumulative, modelId, modelMatch) {
334
350
  * @param {{in:number,out:number}} [opts.rates]
335
351
  * @param {string} [opts.modelId]
336
352
  * @param {Record<string,string|undefined>} [opts.env] - the merged shell+keys-file env the key is read from (default process.env).
337
- * @returns {(executorContext:object, grantedTools:Record<string,any>, stepMeta?:{class?:string, attempt?:number, step?:string|null, cited?:any, sheet?:any[]|null, withText?:boolean, picked?:any[]|null, thinkingMode?:'on'|'off'}, seam?:{stopRequested?:() => boolean}) => Promise<any>}
353
+ * @returns {(executorContext:object, grantedTools:Record<string,any>, stepMeta?:{class?:string, attempt?:number, step?:string|null, cited?:any, sheet?:any[]|null, withText?:boolean, itemShape?:any, line?:number|null, picked?:any[]|null, thinkingMode?:'on'|'off'}, seam?:{stopRequested?:() => boolean}) => Promise<any>}
338
354
  */
339
355
  export function makeLiveModelStep({
340
356
  slot, model, spendPath, provider: injectedProvider, rates: injectedRates, modelId: injectedModelId, env,
@@ -375,7 +391,7 @@ export function makeLiveModelStep({
375
391
  const runDir = dirname(spendPath);
376
392
  const diaryStep = stepMeta.step ?? null;
377
393
  const diaryTry = typeof stepMeta.attempt === 'number' ? stepMeta.attempt : null;
378
- const toolSchema = buildEmitArtifactSchema(stepMeta.class, stepMeta.class === 'green' && Boolean(stepMeta.cited), stepMeta.class === 'green' && Array.isArray(stepMeta.sheet) ? stepMeta.sheet : null, stepMeta.class === 'green' && stepMeta.withText === true);
394
+ const toolSchema = buildEmitArtifactSchema(stepMeta.class, stepMeta.class === 'green' && Boolean(stepMeta.cited), stepMeta.class === 'green' && Array.isArray(stepMeta.sheet) ? stepMeta.sheet : null, stepMeta.class === 'green' && stepMeta.withText === true, isRec(stepMeta.itemShape));
379
395
  const thinkingMode = stepMeta.thinkingMode === 'on' || stepMeta.thinkingMode === 'off' ? stepMeta.thinkingMode : null;
380
396
  const systemPrompt = 'You are executing one step of a signed, human-authored automation. '
381
397
  + 'Call emit_artifact exactly once with this step\'s result. Ground every value in the '
@@ -389,9 +405,11 @@ export function makeLiveModelStep({
389
405
  // M14 item 2: what happened so far in this run (src/memo.js), whole, on every try that has any; absent = nothing has happened yet. Text only, it leans the model, the close alone judges
390
406
  ...(typeof executorContext.memo === 'string' && executorContext.memo !== '' ? { fromThisRun: executorContext.memo } : {}),
391
407
  // M10 am7 item 3: a step that quotes a saved page is told the form of its answer and what each result must hold; M10 am28: and each pick on its line (values only)
392
- ...(stepMeta.class === 'green' && stepMeta.cited ? { quoting: { ...citedBrief(stepMeta.cited), ...(Array.isArray(stepMeta.picked) && stepMeta.picked.length > 0 ? { yourTextHas: toldPicks(stepMeta.picked) } : {}) } } : {}),
408
+ ...(stepMeta.class === 'green' && stepMeta.cited ? { quoting: { ...citedBrief(stepMeta.cited), ...(isRec(stepMeta.itemShape) ? { eachResultAlso: shapeBriefOf(stepMeta.itemShape, stepMeta.cited) } : {}), ...(Array.isArray(stepMeta.picked) && stepMeta.picked.length > 0 ? { yourTextHas: toldPicks(stepMeta.picked) } : {}) } } : {}),
393
409
  // M10b piece 2: a step that reads a sheet is told the shape of each claim box (bareguard's worked example), never the check
394
410
  ...(stepMeta.class === 'green' && Array.isArray(stepMeta.sheet) ? { answering: sheetBrief(stepMeta.sheet) } : {}),
411
+ // M19 S5 (amendment B, the third brief exception): a step whose line is a list of items is told the answer, each field in plain words and one example item, all written by code; never a verdict, never its other guardrails
412
+ ...(isRec(stepMeta.itemShape) && !stepMeta.cited ? { answering: shapeLineBrief(stepMeta.line ?? 0, stepMeta.itemShape, stepMeta.withText === true) } : {}),
395
413
  // M10 am22: a fact step whose line carries the person's picks also writes the answer the job line asks for, in "text" (their sizes are in the job line)
396
414
  ...(stepMeta.class === 'green' && stepMeta.withText === true ? { alsoWrite: 'Also give "text": the written answer the goal asks for, in your own words, grounded in what you found. Never leave it empty.' } : {}),
397
415
  });
package/src/pageask.js CHANGED
@@ -69,9 +69,6 @@ const readingRest = (n) => `, or type your own reading (your answer replaces tha
69
69
  const cantCheckTail = (n) => ` Answer "${DROP_IT}", or type how to check it (your answer replaces that ~ rule on line ${n}).`;
70
70
  /** @param {number} n @param {string} rule @param {string} reading @returns {string} */
71
71
  export const readingQuestion = (n, rule, reading) => `Your line ${n} says "${rule}".${READING_HEAD}${reading}${READING_TAIL}${readingRest(n)}`;
72
- // borrowed-from: bareloop src/pagemap.js@v0.56.0 (3383cce) (cantCheckQuestion; readingQuestion above is exported for the block's asks)
73
- /** @param {number} n @param {string} rule @returns {string} the can't-check ask in its one spelling */
74
- export const cantCheckQuestion = (n, rule) => `Your line ${n} says "${rule}". I can't check this on the page. Drop it?${cantCheckTail(n)}`;
75
72
  /** @param {unknown} q a recorded question @returns {string|null} the reading a reading ask proposed, or null when it was another kind of question */
76
73
  export function readingOfQuestion(q) {
77
74
  const s = String(q ?? '');