fwdloop 0.29.0 → 0.30.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.
package/src/drafter.js CHANGED
@@ -19,6 +19,7 @@ import { Loop, HaltError } from 'bare-agent';
19
19
  import { capTooSmallText, usdText } from './draftspend.js';
20
20
  import { parseSignedText, unsignedAskTtls } from './signed-text.js';
21
21
  import { validateDeclaration, checkGuardrailSums, checkSendLineGuardrail } from './declaration.js';
22
+ import { readEveryStep } from './whole-job.js';
22
23
  import { loadCatalogue } from './catalogue.js';
23
24
  import { findMcpPlanRed } from './canrun.js';
24
25
  import { WIRED_VERBS, wiredMenu } from './primitives.js';
@@ -30,12 +31,14 @@ import { lookAtPage, pageInfoLines } from './pagelook.js';
30
31
  import { lookAtSheet, sheetPrompt } from './sheetlook.js';
31
32
  import { leftRuleLine, dropRows, dropLine, dropSentence, pickNoteLine } from './pagedropwords.js';
32
33
  import {
33
- scopedRules, rowsFromAnswer, checkAsks, settleRules, applyPicks, SUGGEST_SYSTEM, SUGGEST_TOOL, SUGGEST_SCHEMA, suggestUserText,
34
+ offerRules, rowsFromAnswer, checkAsks, settleRules, applyPicks, retentionOf, SUGGEST_SYSTEM, SUGGEST_TOOL, SUGGEST_SCHEMA, suggestUserText,
34
35
  } from './checkpick.js';
35
36
  import { matchRecord, entriesFromAnswers, sameWords, KEPT_WORDS } from './pickrecord.js';
36
37
  import { MAP_SYSTEM, mapPrompt } from './pagemap.js';
37
38
  import { askableFromLook, tooManyAsksText, MAX_LOOK_ASKS } from './pageask.js';
38
39
  import { lineRules } from './pagebits.js';
40
+ import { isCountGuardrail } from './declaration.js';
41
+ import { repairDeclaration } from './repairs.js';
39
42
  import path from 'node:path';
40
43
  import { isCellsPath } from './closers.js';
41
44
  import { parseCsv, sheetTable } from './csv.js';
@@ -291,11 +294,29 @@ function cleanNotChecked(raw) {
291
294
  return Array.isArray(raw) ? raw.filter((x) => typeof x === 'string' && x.trim() !== '').map((x) => x.trim()) : [];
292
295
  }
293
296
 
297
+ // M10 am27 (1): at draft time a count guardrail is hidden from the AI (the page look and the drafter); code keeps the ORIGINAL rule numbers and text.
298
+ const shownRules = (/** @type {string} */ guardrail) => lineRules({ rule: guardrail }).filter((r) => !isCountGuardrail(r)).join('; ');
299
+
300
+ /**
301
+ * The job lines as the page look may see them (no count rule), and `toOriginal`, which takes a look fact's / dropped entry's visible rule number back to the guardrail's own number.
302
+ * @param {{n: number, text: string, rule?: string}[]} jobLines
303
+ */
304
+ export function hideCounts(jobLines) {
305
+ const seenLines = jobLines.map((l) => { const kept = lineRules(l).filter((r) => !isCountGuardrail(r)); return { n: l.n, text: l.text, ...(kept.length ? { rule: kept.join('; ') } : {}) }; });
306
+ const ruleMap = (/** @type {number} */ line, /** @type {number|undefined} */ vis) => {
307
+ if (vis === undefined) return undefined;
308
+ const orig = lineRules(jobLines.find((x) => x.n === line)).map((r, i) => ({ r, no: i + 1 })).filter((x) => !isCountGuardrail(x.r));
309
+ return orig[vis - 1]?.no ?? vis;
310
+ };
311
+ const toOriginal = (/** @type {any} */ f) => (f.forRule !== undefined ? { ...f, forRule: ruleMap(f.line, f.forRule) } : f.rule !== undefined ? { ...f, rule: ruleMap(f.line, f.rule) } : f);
312
+ return { seenLines, toOriginal };
313
+ }
314
+
294
315
  function jobLinesText(lines, asks) {
295
316
  const askLines = new Set(asks.map((a) => a.line));
296
317
  return lines
297
318
  .map((l) => `${l.n}. ${l.text}${askLines.has(l.n) ? ' [SIGNED ASK — a human stop]' : ''}`
298
- + `${l.guardrail ? ` [guardrail: ${l.guardrail}]` : ' [no guardrail]'}`)
319
+ + `${l.guardrail && shownRules(l.guardrail) ? ` [guardrail: ${shownRules(l.guardrail)}]` : ' [no guardrail]'}`)
299
320
  .join('\n');
300
321
  }
301
322
 
@@ -348,8 +369,8 @@ function whenToUse(menu) {
348
369
  function sheetRuleNumbers(lines, arbiter) {
349
370
  const csvRoles = (arbiter.sources ?? []).filter((s) => s.kind === 'file' && isCellsPath(s.path));
350
371
  if (csvRoles.length === 0) return [];
351
- const rows = lines.map((l) => ({ n: l.n, rules: lineRules(l.guardrail ? { rule: l.guardrail } : {}) })).filter((x) => x.rules.length > 0);
352
- return rows.length === 0 ? [] : ['', 'The guardrail rules by number (what "covers" counts):', ...rows.map((x) => `- line ${x.n}: ${x.rules.map((r, i) => `${i + 1}) ${r}`).join(' ')}`)];
372
+ const rows = lines.map((l) => ({ n: l.n, rules: lineRules(l.guardrail ? { rule: l.guardrail } : {}).map((r, i) => ({ r, no: i + 1 })).filter((x) => !isCountGuardrail(x.r)) })).filter((x) => x.rules.length > 0);
373
+ return rows.length === 0 ? [] : ['', 'The guardrail rules by number (what "covers" counts):', ...rows.map((x) => `- line ${x.n}: ${x.rules.map((q) => `${q.no}) ${q.r}`).join(' ')}`)];
353
374
  }
354
375
 
355
376
  export function buildSystemPrompt({ menu, lines, arbiter, factsInfo }) {
@@ -541,6 +562,8 @@ export async function draft({
541
562
  const pageExtras = pageSources.length ? { look, pageLooks } : {};
542
563
  let mapCut = null;
543
564
  const jobLines = lines.map((l) => ({ n: l.n, text: l.text, ...(l.guardrail ? { rule: l.guardrail } : {}) }));
565
+ // M10 am27 (1): the page look sees only the non-count rules; `toOriginal` takes a visible rule number back to the original one
566
+ const { seenLines, toOriginal } = hideCounts(jobLines);
544
567
  const pageInfo = [];
545
568
  /** 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) */
546
569
  const makeCallModel = (kind) => async (content, attempt) => {
@@ -572,13 +595,14 @@ export async function draft({
572
595
  for (const s of pageSources) {
573
596
  const pg = pages[s.role];
574
597
  // The hold of the map call is sized from its own prompt (the saved page is in it): one that cannot fit what is left of the cap is refused here, at $0.
575
- const mapCeiling = ceilingCostUsd(rates, mapPrompt({ jobLines, label: s.role, text: pg.text }).length + MAP_SYSTEM.length);
598
+ const mapCeiling = ceilingCostUsd(rates, mapPrompt({ jobLines: seenLines, label: s.role, text: pg.text }).length + MAP_SYSTEM.length);
576
599
  const spentBefore = meterings.reduce((sum, ev) => sum + (ev.costUsd ?? roundCeiling), 0);
577
600
  if (spentBefore + mapCeiling > budgetUsd) {
578
601
  if (meterings.length === 0 && calls === 0) { removeFrozenPages(/** @type {string} */ (draftDir), Object.values(pages).map((q) => q.entry.frozen)); return fail([tooSmall(mapCeiling)]); }
579
602
  }
580
603
  const callModel = makeCallModel('page-map');
581
- const got = await lookAtPage({ label: s.role, text: pg.text, jobLines, callModel });
604
+ const got0 = await lookAtPage({ label: s.role, text: pg.text, jobLines: seenLines, callModel });
605
+ const got = got0.ok ? { ...got0, look: { ...got0.look, facts: got0.look.facts.map(toOriginal), dropped: got0.look.dropped.map(toOriginal) } } : got0;
582
606
  if (!got.ok) {
583
607
  const m = sumMeterings(meterings);
584
608
  return {
@@ -658,7 +682,7 @@ export async function draft({
658
682
  // per guardrail, or none; code keeps what passes keep-or-drop. The call is metered, held and booked as a drafting round (the same `meterings`). The redraft after the answers
659
683
  // (offerQuestions false) makes no call: it settles every rule against the person's picks instead.
660
684
  // a rule a kept page or sheet fact already serves (the look tied it: line + rule number) is settled by that fact and is not asked here
661
- const shapeRules = scopedRules(lines, arbiter).filter((r) => ![...look.facts, ...sheetFacts].some((f) => f.line === r.line && f.forRule === r.rule));
685
+ const shapeRules = offerRules(lines, arbiter, [...look.facts, ...sheetFacts]);
662
686
  // 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.
663
687
  const carried = matchRecord(carriedPicks, lines, shapeRules);
664
688
  const keptView = carried.kept.map((k) => ({ line: k.line, rule: k.rule, ruleText: k.entry.ruleText, check: k.entry.check, added: k.entry.added, left: k.entry.left }));
@@ -873,16 +897,24 @@ export async function draft({
873
897
  if (Array.isArray(declaration.steps)) {
874
898
  declaration.steps = declaration.steps.map((st) => (isPlainObject(st) ? { ...st, goal: goalForLine(st.fromLine, lines) } : st));
875
899
  }
900
+ // M13 am9 item 4: the last Ask before the added `write it out` reads every step; code sets it, whatever the model sent
901
+ if (Array.isArray(declaration.steps)) declaration.steps = readEveryStep(declaration.steps, arbiter);
876
902
  // 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 person's picks (applyPicks, next).
903
+ delete declaration.pickedLines; // the record of picked fact lines is code's too (applyPicks)
877
904
  if (Array.isArray(declaration.steps)) {
878
905
  declaration.steps = declaration.steps.map((st) => {
879
- if (!isPlainObject(st) || !isPlainObject(st.close) || st.close.shape === undefined) return st;
880
- const { shape: _drop, ...close } = st.close;
906
+ if (!isPlainObject(st) || !isPlainObject(st.close) || (st.close.shape === undefined && st.close.picked === undefined)) return st;
907
+ // M10 am22 (3): `close.picked` is code's from the person's picks (applyPicks, next); one the drafter sent is dropped here too
908
+ const { shape: _drop, picked: _dropPicked, ...close } = st.close;
881
909
  return { ...st, close };
882
910
  });
883
911
  }
884
912
  // M10 am16 (4): code sets the check of every line it settled, from the picks only; the drafter's own `close.shape` and class for such a line are gone
885
913
  if (settled) Object.assign(declaration, applyPicks(declaration, shapeRules, settled, (n) => dropSentence({ line: n.line, fact: '', reason: n.reason })));
914
+ // M10 am27 (2): the two mechanical plan mistakes (cited page not in reads; unjudgeable note on a green line) are repaired by code and logged on the round
915
+ { const fixed = repairDeclaration(declaration, arbiter); if (fixed.repaired.length) { Object.assign(declaration, fixed.declaration); entry.repaired = fixed.repaired; } }
916
+ // M10 am27 (4): what the drafter wrote vs what the final plan keeps, per job line (record only); drafted = the declaration as sent, before any code change
917
+ entry.retention = retentionOf(captured, declaration, jobLines, [...(settled?.checks.keys() ?? [])]);
886
918
  // M10b piece 4: `covers` (which ~ rules a check verifies) stays on the check and is signed; the validator checks it, the plan card shows it
887
919
  const verdict1 = validateDeclaration(declaration, {
888
920
  arbiter, lines, catalogue: validationCatalogue, wired: WIRED_VERBS, verbatimGoals: true, fitJobLine: true,
package/src/jobkey.js CHANGED
@@ -5,6 +5,7 @@
5
5
  // TWO producers, ONE canonical form: the signed flow (parseSignedText's lines + arbiter) and the card's job box (parseJobBox).
6
6
  import { createHash } from 'node:crypto';
7
7
 
8
+ import { typedLinesOf } from './added-end.js';
8
9
  import { joinGuardrails, parseJobBox } from './panel/authorcard.js';
9
10
 
10
11
  /** @param {{ask: boolean, text: string, guardrail: string}[]} steps */
@@ -21,5 +22,6 @@ export function jobKeyOfCard(job) {
21
22
  /** The key of a signed job. @param {{ lines: {n: number, text: string, guardrail: string}[], arbiter: any }} signed `parseSignedText`'s ok result */
22
23
  export function jobKeyOfSigned({ lines, arbiter }) {
23
24
  const asks = new Set((arbiter.asks ?? []).map((a) => a.line));
24
- return keyOf(lines.map((l) => ({ ask: asks.has(l.n), text: String(l.text).trim(), guardrail: String(l.guardrail ?? '').trim() })));
25
+ // M13 am8: the end code adds (and an old job's send line) is not part of the job the person typed
26
+ return keyOf(typedLinesOf(lines, arbiter).map((l) => ({ ask: asks.has(l.n), text: String(l.text).trim(), guardrail: String(l.guardrail ?? '').trim() })));
25
27
  }
package/src/model-step.js CHANGED
@@ -30,7 +30,7 @@ import { GateRefusal } from './primitives.js';
30
30
  import { appendCall, appendTool, nextRound } from './diary.js';
31
31
  import { ConfigError } from './config.js';
32
32
  import { worstThinkingStatus } from './thinking.js';
33
- import { citedBrief } from './citedcheck.js';
33
+ import { citedBrief, toldPicks } from './citedcheck.js';
34
34
  import { sheetAnswerProps, sheetBrief } from './sheetclaims.js';
35
35
 
36
36
  import {
@@ -143,12 +143,16 @@ const CITED_SCHEMA = Object.freeze({
143
143
  * only (plus, for a green step that quotes a saved page, the form of its answer).
144
144
  * `stepClass` is `'green' | 'softgreen' | 'hitl' | null | undefined`; `cited` is true for that green step.
145
145
  */
146
- /** @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) */
147
- export function buildEmitArtifactSchema(stepClass, cited = false, sheet = null) {
146
+ /** @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) {
148
+ const text = withText ? { text: { type: 'string' } } : {};
148
149
  if (stepClass === 'green' && Array.isArray(sheet)) {
149
150
  // M10b piece 2: a step that reads a sheet answers in one typed box per claim (bareguard's shapes), never a cite
150
151
  const { properties, required } = sheetAnswerProps(sheet);
151
- return { type: 'object', properties: { ...properties, ...DONE_PROPS }, required: [...required, 'done'], additionalProperties: false };
152
+ return { type: 'object', properties: { ...properties, ...text, ...DONE_PROPS }, required: [...required, ...(withText ? ['text'] : []), 'done'], additionalProperties: false };
153
+ }
154
+ if (stepClass === 'green' && cited && withText) {
155
+ return { ...CITED_SCHEMA, properties: { ...CITED_SCHEMA.properties, ...text }, required: ['results', 'text', 'done'] };
152
156
  }
153
157
  if (stepClass === 'green' && cited) return CITED_SCHEMA;
154
158
  if (stepClass === 'green') throw new Error('a green step answers in quotes (close.cited) or in claim boxes (close.sheet); the cell cite retired in M10b piece 5');
@@ -330,7 +334,7 @@ function stoppedResult(cumulative, modelId, modelMatch) {
330
334
  * @param {{in:number,out:number}} [opts.rates]
331
335
  * @param {string} [opts.modelId]
332
336
  * @param {Record<string,string|undefined>} [opts.env] - the merged shell+keys-file env the key is read from (default process.env).
333
- * @returns {(executorContext:object, grantedTools:Record<string,any>, stepMeta?:{class?:string, attempt?:number, step?:string|null, cited?:any, sheet?:any[]|null, thinkingMode?:'on'|'off'}, seam?:{stopRequested?:() => boolean}) => Promise<any>}
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>}
334
338
  */
335
339
  export function makeLiveModelStep({
336
340
  slot, model, spendPath, provider: injectedProvider, rates: injectedRates, modelId: injectedModelId, env,
@@ -371,7 +375,7 @@ export function makeLiveModelStep({
371
375
  const runDir = dirname(spendPath);
372
376
  const diaryStep = stepMeta.step ?? null;
373
377
  const diaryTry = typeof stepMeta.attempt === 'number' ? stepMeta.attempt : null;
374
- const toolSchema = buildEmitArtifactSchema(stepMeta.class, stepMeta.class === 'green' && Boolean(stepMeta.cited), stepMeta.class === 'green' && Array.isArray(stepMeta.sheet) ? stepMeta.sheet : 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);
375
379
  const thinkingMode = stepMeta.thinkingMode === 'on' || stepMeta.thinkingMode === 'off' ? stepMeta.thinkingMode : null;
376
380
  const systemPrompt = 'You are executing one step of a signed, human-authored automation. '
377
381
  + 'Call emit_artifact exactly once with this step\'s result. Ground every value in the '
@@ -384,10 +388,12 @@ export function makeLiveModelStep({
384
388
  ...(typeof executorContext.hints === 'string' && executorContext.hints !== '' ? { fromEarlierRuns: executorContext.hints } : {}),
385
389
  // 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
386
390
  ...(typeof executorContext.memo === 'string' && executorContext.memo !== '' ? { fromThisRun: executorContext.memo } : {}),
387
- // M10 am7 item 3: a step that quotes a saved page is told the form of its answer and what each result must hold
388
- ...(stepMeta.class === 'green' && stepMeta.cited ? { quoting: citedBrief(stepMeta.cited) } : {}),
391
+ // 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) } : {}) } } : {}),
389
393
  // M10b piece 2: a step that reads a sheet is told the shape of each claim box (bareguard's worked example), never the check
390
394
  ...(stepMeta.class === 'green' && Array.isArray(stepMeta.sheet) ? { answering: sheetBrief(stepMeta.sheet) } : {}),
395
+ // 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
+ ...(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.' } : {}),
391
397
  });
392
398
  /** @type {any[]} */
393
399
  let messages = [
package/src/pageask.js CHANGED
@@ -10,10 +10,12 @@
10
10
  // READING: a kept fact carries it with a `reading` (a limit the page cannot hold in words, e.g. "not a red-eye"). Asked only when a bound of the
11
11
  // reading is NOT in the words the person wrote; a bound they wrote themselves is theirs and nothing is asked.
12
12
  // CAN'T CHECK: no kept fact carries it.
13
+ // A COUNT guardrail (declaration.js isCountGuardrail) is none of these: it is asked once, as a pick (M10 am24).
13
14
  // Throws away: a fact's name, words and source (only its reading and the rule it serves are used).
14
15
  import { redactSecrets } from './redact.js';
15
16
  import { lineRules, boundInWords, wordsSaidOn } from './pagebits.js';
16
17
  import { validReading } from './pagerules.js';
18
+ import { isCountGuardrail } from './declaration.js';
17
19
 
18
20
  /** the most asks before drafting; more than this is a job to rewrite, not a questionnaire (am1) */
19
21
  export const MAX_LOOK_ASKS = 3;
@@ -97,6 +99,7 @@ export function askableFromLook(look, jobLines) {
97
99
  for (const l of Array.isArray(jobLines) ? jobLines : []) {
98
100
  lineRules(l).forEach((rule, k) => {
99
101
  const n = k + 1;
102
+ if (isCountGuardrail(rule)) return; // M10 am24: a count guardrail is asked only as a pick (src/checkpick.js), never as a page question; its look facts stay
100
103
  const key = `${l.n}\u0000${rule.trim().toLowerCase()}`;
101
104
  const tied = facts.filter((f) => f.line === l.n && f.forRule === n);
102
105
  if (tied.length > 0) {
@@ -749,7 +749,8 @@ export function createAuthor(opts) {
749
749
  // M10 piece 3 (am2): a question the page look raised takes bareloop's answer words. A blank answer gets bareloop's sentence; a newline is folded to a
750
750
  // space (one `~` line is one line) instead of refused. Every other question keeps its own gate (blank, one line).
751
751
  const look = q.source === 'look';
752
- const answer = typeof b.answer === 'string' ? (look ? b.answer.replace(/\s*\n\s*/g, ' ') : b.answer).trim() : '';
752
+ // hamr 2026-11-07 (ruling 2A): a leading `~` the person typed is dropped quietly (the job line adds its own); the ONE place, so a tilde-only answer is a blank answer
753
+ const answer = typeof b.answer === 'string' ? (look ? b.answer.replace(/\s*\n\s*/g, ' ') : b.answer).trim().replace(/^(?:~\s*)+/, '') : '';
753
754
  if (answer === '') return { status: 400, body: { ok: false, refused: 'blank-answer', say: look ? LOOK_BLANK_ANSWER_SAY : BLANK_ANSWER_SAY } };
754
755
  if (!look && /[\r\n]/.test(answer)) return { status: 400, body: { ok: false, refused: 'one-line', say: ONE_LINE_ANSWER_SAY } };
755
756
  if (keys.some((k) => k.length >= 8 && answer.includes(k))) return { status: 400, body: { ok: false, refused: 'key', say: 'This answer contains an API key. Keys go in Settings only. Nothing was saved.' } };
@@ -18,7 +18,7 @@ import { checkFlowName } from '../flow.js';
18
18
  import { isWebUrl } from '../pagefetch.js';
19
19
  import { checkSendDestination } from '../runner.js';
20
20
  import { parseSignedText } from '../signed-text.js';
21
- import { checkSendLineGuardrail } from '../declaration.js';
21
+ import { addEnd, typedLinesOf } from '../added-end.js';
22
22
  import { capTooSmallText } from '../draftspend.js';
23
23
  import { startableMcpServers, mcpConfigFor } from '../mcp-sources.js';
24
24
  import { mcpPickFor } from '../mcp-pick.js';
@@ -257,7 +257,7 @@ export function runInputRows(v) {
257
257
  * @returns {string}
258
258
  */
259
259
  export function cardToProse(card) {
260
- const { steps } = parseJobBox(card.job);
260
+ const { steps } = addEnd(parseJobBox(card.job).steps, card.destination); // M13 am8: the end is added by code
261
261
  const out = [...jobFileLines(steps, card.askWait), '', ARBITER_HEADING];
262
262
  out.push(`guardrail: cap $${capText(Number(card.capUsd))} per run`);
263
263
  if (card.destination !== '') out.push(`guardrail: send at line ${steps.length} to file:${card.destination}`);
@@ -284,14 +284,19 @@ export function cardFromSigned({ lines, arbiter }) {
284
284
  const asks = new Map((arbiter.asks ?? []).map((a) => [a.line, a]));
285
285
  const jobLines = [];
286
286
  let firstWait = null;
287
+ // M13 am8: the end is added by code (`cardToProse`), so the card's job leaves out the send line (the last line when it is the send) and an added Ask before it
288
+ const lastSend = (arbiter.sends ?? []).length === 1 && arbiter.sends[0].line === lines.length ? arbiter.sends[0].line : null;
289
+ const typed = new Set(typedLinesOf(lines, arbiter).map((l) => l.n));
287
290
  for (const l of lines) {
288
291
  const ak = asks.get(l.n);
289
292
  if (ak) {
290
293
  const w = waitText(ak.ttlMs);
291
294
  if (w === null) return no();
292
295
  firstWait ??= w;
293
- jobLines.push(`Ask ${w}: ${l.text}`);
294
- } else jobLines.push(l.text);
296
+ }
297
+ if (!typed.has(l.n)) continue;
298
+ if (ak) jobLines.push(`Ask ${waitText(ak.ttlMs)}: ${l.text}`);
299
+ else jobLines.push(l.text);
295
300
  if (typeof l.guardrail === 'string' && l.guardrail !== '') jobLines.push(`~ ${l.guardrail}`);
296
301
  }
297
302
  const sends = arbiter.sends ?? [];
@@ -306,7 +311,9 @@ export function cardFromSigned({ lines, arbiter }) {
306
311
  const again = parseSignedText(cardToProse(cardFields({ ...card, flowName: 'x' })));
307
312
  // M9 am1: the trigger is not a box on the card, and signing an Edit clears it (By hand again), so it is not part of the fidelity check
308
313
  const norm = (a) => JSON.stringify({ ...a, trigger: null, asks: (a.asks ?? []).map(({ ttlSigned, ...rest }) => rest) });
309
- const sameLines = again.ok && JSON.stringify(again.lines) === JSON.stringify(lines);
314
+ // a send line signed before am8 is the person's own words; the added one reads `write it out`: the words alone may differ there
315
+ const sendText = (/** @type {{n: number, text: string}[]} */ ls) => ls.map((l) => (l.n === lastSend ? { ...l, text: '' } : l));
316
+ const sameLines = again.ok && JSON.stringify(sendText(again.lines)) === JSON.stringify(sendText(lines));
310
317
  if (!sameLines || norm(again.arbiter) !== norm(arbiter)) return no();
311
318
  return { ok: true, card };
312
319
  }
@@ -493,8 +500,5 @@ export function checkCard(card, { root, keys = [], home, runOf }) {
493
500
  }
494
501
  return { ok: false, refusals };
495
502
  }
496
- // M10 am14 item 1: a guardrail on the send line is refused at $0, before drafting, naming the line
497
- for (const r of checkSendLineGuardrail(parsed.lines, parsed.arbiter)) no('job', r);
498
- if (refusals.length > 0) return { ok: false, refusals };
499
503
  return { ok: true, prose };
500
504
  }
package/src/panel/data.js CHANGED
@@ -23,7 +23,7 @@ import {
23
23
  existsSync, realpathSync,
24
24
  } from 'node:fs';
25
25
  import { createHash } from 'node:crypto';
26
- import { plainPlanCheck } from '../plain-checks.js';
26
+ import { plainPlanCheck, pickPlanRed } from '../plain-checks.js';
27
27
  import { compareNatural } from '../natural.js';
28
28
  import { join, sep } from 'node:path';
29
29
 
@@ -41,6 +41,7 @@ import { applyRunValues, parseWaitMs, pickRunValues, VALUES_FILE_RE } from '../r
41
41
  import { readSetup } from '../setup.js';
42
42
  import { parseHintBlock } from '../learn.js';
43
43
  import { checkedLines, notCheckedView, NOT_CHECKED_LABEL } from '../checked.js';
44
+ import { LABEL_PICKED } from '../checkwords.js';
44
45
  import { csvRolesOf, askSheetCard } from '../sheetblock.js';
45
46
  import { readSheetChecks } from '../sheet-record.js';
46
47
  import {
@@ -1911,7 +1912,7 @@ export function getDraftBlock(flowDir, runDir) {
1911
1912
  // The free retry after a broken reply reads `try N again`. A flow signed before am15 recorded no tries: nothing is added.
1912
1913
  const tryRows = (r, n) => (Array.isArray(r.tries) ? r.tries : []).map((t, k) => {
1913
1914
  const reds = Array.isArray(t.reds) ? t.reds.map(String) : [];
1914
- const gap = t.passed ? '' : (reds.length > 0 ? `${plainPlanCheck(reds[0]).reason}${reds.length > 1 ? ` (and ${reds.length - 1} more)` : ''}` : String(t.outcome ?? ''));
1915
+ const gap = t.passed ? '' : (reds.length > 0 ? `${plainPlanCheck(pickPlanRed(reds)).reason}${reds.length > 1 ? ` (and ${reds.length - 1} more)` : ''}` : String(t.outcome ?? ''));
1915
1916
  return {
1916
1917
  attempt: `${n}.${k + 1}`, step: 'drafting', class: null, verdict: t.passed ? 'green' : 'red', gap, at: r.at ?? null, setup: true, blocked: false,
1917
1918
  action: `${t.label} ${t.passed ? '✓' : '✗'}`, tryRow: true, tokensDisplay: { kind: 'no-model' },
@@ -1940,7 +1941,7 @@ export function getDraftBlock(flowDir, runDir) {
1940
1941
  rows.push(human(r, n, { action: 'card (you)', gap }));
1941
1942
  } else if (r.kind === 'note') rows.push(human(r, n, { action: 'note (you)', gap: String(r.text ?? '') }));
1942
1943
  // M10 am2 item 4: a question the page look raised and your answer, under the drafting step, in bareloop's words (`you were asked:` / `you said:`)
1943
- else if (r.kind === 'human') rows.push(human(r, n, { action: `you were asked: ${r.question}`, gap: `you said: ${r.answer}` }));
1944
+ else if (r.kind === 'human') rows.push(human(r, n, { action: `you were asked: ${r.question}`, gap: `you said: ${r.answer}${r.source === 'look' && typeof r.rule === 'string' && r.rule !== '' ? ` ${LABEL_PICKED}` : ''}` }));
1944
1945
  else if (r.kind === 'draft') { rows.push(model(r, n, 'draft')); rows.push(...tryRows(r, n)); }
1945
1946
  else if (r.kind === 'change') { rows.push(model(r, n, `change ${r.n}`)); rows.push(...tryRows(r, n)); }
1946
1947
  else if (r.kind === 'startover') { rows.push(model(r, n, 'start over')); rows.push(...tryRows(r, n)); }
@@ -226,6 +226,7 @@
226
226
  .badge.cyan{color:var(--cyan);}
227
227
 
228
228
  .hint{font-size:11px;color:var(--text-faint);margin-top:4px;}
229
+ .hint.jf-added{margin-top:2px;overflow-wrap:anywhere;}
229
230
  .hint.money-red{color:var(--red);}
230
231
  .btn{padding:8px 14px;min-height:44px;border:1px solid var(--border-strong);background:var(--panel2);color:var(--text);white-space:nowrap;flex:none;position:relative;}
231
232
  .btn::before{content:"[ ";color:var(--text-faint);}
@@ -1187,7 +1188,9 @@
1187
1188
  <div class="jf-gut" id="jf-job-gut" data-testid="jf-job-gut" aria-hidden="true"><div class="jf-gut-in"></div></div>
1188
1189
  <textarea class="jf-wrap" id="jf-job" rows="6" data-testid="jf-job" autocomplete="off" spellcheck="false" placeholder="Read my resume&#10;~keep it under 600 words&#10;Ask: check it with me&#10;Write it out"></textarea>
1189
1190
  </div>
1190
- <div class="hint">One step per line. A line starting with <code>~</code> is a guardrail of the step above it. <code>Ask:</code> stops for you; <code>Ask 2h:</code> sets that ask's own wait. The last line writes the result to the Destination.</div>
1191
+ <div class="hint jf-added" id="jf-added-ask" data-testid="jf-added-ask" hidden></div>
1192
+ <div class="hint jf-added" id="jf-added-write" data-testid="jf-added-write" hidden></div>
1193
+ <div class="hint">One step per line. A line starting with <code>~</code> is a guardrail of the step above it. <code>Ask:</code> stops for you; <code>Ask 2h:</code> sets that ask's own wait. fwdloop adds the last check and the write to your Destination.</div>
1191
1194
  <div class="jf-err" id="jf-err-job" data-testid="jf-err-job"></div>
1192
1195
  </div>
1193
1196
  <div class="field">
@@ -6163,7 +6166,18 @@
6163
6166
  clearBtn.textContent = b.text;
6164
6167
  clearBtn.disabled = b.disabled;
6165
6168
  }
6169
+ // M13 am8: the end code adds, in grey under the Job box (the server's `addEnd` is the one writer; this only shows it): an Ask unless the last step is already one, then the write.
6170
+ function paintAddedEnd(){
6171
+ var steps = jobEl.value.split("\n").map(function(l){ return l.trim(); }).filter(function(l){ return l !== "" && l.charAt(0) !== "~"; });
6172
+ var on = destEl.value.trim() !== "" && steps.length > 0;
6173
+ var needAsk = on && !/^ask[: ]/i.test(steps[steps.length - 1]);
6174
+ var askEl = byId("jf-added-ask"), writeEl = byId("jf-added-write");
6175
+ askEl.hidden = !needAsk; writeEl.hidden = !on;
6176
+ askEl.textContent = "+ Ask " + (askWaitEl.value.trim() || "1h") + ": check the result";
6177
+ writeEl.textContent = "+ Write to Destination";
6178
+ }
6166
6179
  function refreshStartEnabled(){
6180
+ paintAddedEnd();
6167
6181
  paintRequired();
6168
6182
  startOk = startReady();
6169
6183
  syncCardLock();
@@ -6,7 +6,7 @@
6
6
  // change (the job line, the guardrail, the inputs, the destination) or to Draft again when it is the AI's own form error; every rule has one (am15 item 3).
7
7
  // The first two rules' `say` already ends with their fix, as the page has always shown them.
8
8
 
9
- /** @type {ReadonlyArray<{re: RegExp, say: string|null, fix: string}>} `say` null = the checker's own sentence, as it is without its "declaration: " prefix */
9
+ /** @type {ReadonlyArray<{re: RegExp, say: string|null, fix: string, first?: boolean}>} `say` null = the checker's own sentence, as it is without its "declaration: " prefix */
10
10
  export const PLAN_CHECK_RULES = Object.freeze([
11
11
  { re: /which is not in the job line's words/, say: "A section name in the plan's check is not in your job line. Change the job line to use the section words you want.", fix: 'Change the job line to use the section words you want.' },
12
12
  { re: /the job line says .*; the check says/, say: "The sections in the plan's check come in a different order than your job line. Change the job line to change the order.", fix: 'Change the job line to change the order.' },
@@ -21,6 +21,8 @@ export const PLAN_CHECK_RULES = Object.freeze([
21
21
  { re: /not in the catalogue|not wired|which is not signed|checkpoint/, say: 'A step uses a tool that is not available for this job.', fix: 'Draft again; if it repeats, say in the job line what that step should do.' },
22
22
  { re: /reads artifact|is a duplicate|\.reads must|\.emits must/, say: 'The steps do not pass their results to each other in a workable order.', fix: 'Draft again.' },
23
23
  { re: /ask at line \d+|signed ask at line|ask slot/, say: 'The ask on one of your lines is not set up as a plain stop where you decide.', fix: 'Check the line that starts with Ask in your job, then Draft again.' },
24
+ // M4d am38 item 1: `first: true` = this red is the one explained whenever it is among the reds (pickPlanRed), not only when it comes first.
25
+ { re: /send at line \d+ .* is not granted a catalogue primitive of class "write"/, say: 'Your last line sends to your Destination, but your job puts other work on it. Make your last line the one that sends, or move that work above it, then Draft again.', fix: 'Make your last line the one that sends, or move that work above it, then Draft again.', first: true },
24
26
  { re: /send at line \d+|signed send at line|send slot/, say: 'The send step is not set up to follow your accept and write only to your destination.', fix: 'Check the Destination on the card, then Draft again.' },
25
27
  { re: /hitl after the last signed ask/, say: 'A step after your last ask would leave without your seeing it, so it is refused.', fix: 'Move the lines you want to check before your last Ask line, then Draft again.' },
26
28
  { re: /is a pause .* unsigned line/, say: 'A step pauses at a line you did not sign as an ask.', fix: 'Mark the line you want to stop at with Ask, then Draft again.' },
@@ -35,8 +37,18 @@ export const PLAN_CHECK_RULES = Object.freeze([
35
37
  export const GENERIC_SAY = 'One of the checks on the plan failed.';
36
38
  export const GENERIC_FIX = 'Draft again.';
37
39
 
38
- /** The rules as the page takes them: JSON, the regex as its source text. */
39
- export const pageRules = () => PLAN_CHECK_RULES.map((r) => ({ re: r.re.source, say: r.say }));
40
+ /** The rules as the page takes them: JSON, the regex as its source text. `first` rides along so a page that picks a red reads the same rule data. */
41
+ export const pageRules = () => PLAN_CHECK_RULES.map((r) => ({ re: r.re.source, say: r.say, ...(r.first === true ? { first: true } : {}) }));
42
+
43
+ /**
44
+ * M4d amendment 38 item 1: the ONE decision of which red is explained: the first red a `first` rule matches, else the first red (am15 item 3).
45
+ * @param {ReadonlyArray<string>} reds
46
+ * @returns {string|undefined}
47
+ */
48
+ export function pickPlanRed(reds) {
49
+ const list = Array.isArray(reds) ? reds : [];
50
+ return list.find((t) => PLAN_CHECK_RULES.some((r) => r.first === true && r.re.test(String(t)))) ?? list[0];
51
+ }
40
52
 
41
53
  /**
42
54
  * @param {unknown} raw one raw refusal text
package/src/provider.js CHANGED
@@ -41,7 +41,7 @@ import { OpenAI, Anthropic, Gemini } from 'bare-agent/providers';
41
41
  * marker on the instance (`this.lastMalformedToolCall`, reset at the top of
42
42
  * every `generate()` call) — the one channel `runModelStepOnPrimitives`
43
43
  * (same provider reference) can read after `loop.run()` returns. We require
44
- * bare-agent >=0.50 (package.json `^0.57.0`) and never patch around its
44
+ * bare-agent >=0.50 (package.json `^0.59.0`) and never patch around its
45
45
  * private response internals.
46
46
  */
47
47
  class MalformedToolCallTolerantOpenAI extends OpenAI {
package/src/repairs.js ADDED
@@ -0,0 +1,38 @@
1
+ // M10 am27 (2): code repairs of the two mechanical plan mistakes F169 found in 13 of 20 F168 drafts. Each repair is returned as a line of text and logged on the draft
2
+ // entry (`repaired`), so it is visible. Neither repair grants a primitive, changes a class, or writes a check.
3
+ // (1) a green step whose `close.cited.source` is a declared source role the step does not read: the role is added to its `reads`.
4
+ // (2) an `unjudgeable` entry for a line whose guardrailClasses says green: the entry is dropped and the line stays green.
5
+ // Throws away: the `unjudgeable` reason text of a dropped entry (kept only inside the `repaired` line).
6
+ /**
7
+ * @param {any} declaration the drafter's declaration (not changed) @param {{sources?: {role?: string, kind?: string}[]}} arbiter
8
+ * @returns {{declaration: any, repaired: string[]}}
9
+ */
10
+ export function repairDeclaration(declaration, arbiter) {
11
+ const isRec = (/** @type {unknown} */ v) => v !== null && typeof v === 'object' && !Array.isArray(v);
12
+ if (!isRec(declaration)) return { declaration, repaired: [] };
13
+ /** @type {string[]} */
14
+ const repaired = [];
15
+ const roles = new Set((arbiter?.sources ?? []).filter((s) => typeof s?.role === 'string').map((s) => /** @type {string} */ (s.role)));
16
+ let out = declaration;
17
+ if (Array.isArray(declaration.steps)) {
18
+ out = {
19
+ ...out,
20
+ steps: declaration.steps.map((/** @type {any} */ st, /** @type {number} */ i) => {
21
+ const src = isRec(st) && isRec(st.close) && st.close.class === 'green' && isRec(st.close.cited) ? st.close.cited.source : undefined;
22
+ if (typeof src !== 'string' || !roles.has(src) || !Array.isArray(st.reads) || st.reads.includes(src)) return st;
23
+ repaired.push(`steps[${i}].reads: added "${src}" (its cited check reads it)`);
24
+ return { ...st, reads: [...st.reads, src] };
25
+ }),
26
+ };
27
+ }
28
+ if (isRec(declaration.unjudgeable) && isRec(declaration.guardrailClasses)) {
29
+ const un = { ...declaration.unjudgeable };
30
+ for (const key of Object.keys(un)) {
31
+ if (declaration.guardrailClasses[key] !== 'green') continue;
32
+ repaired.push(`unjudgeable: dropped the entry for line ${key} (its class is green; reason was: ${String(un[key]).slice(0, 160)})`);
33
+ delete un[key];
34
+ }
35
+ out = { ...out, unjudgeable: un };
36
+ }
37
+ return { declaration: repaired.length ? out : declaration, repaired };
38
+ }
package/src/runner.js CHANGED
@@ -77,6 +77,7 @@ import {
77
77
  import { readJobThinking, readModelRecord, takeLearningsRecord } from './flowmodel.js';
78
78
  import { readRunInputs, writeRunStart } from './runfile.js';
79
79
  import { buildMemo } from './memo.js';
80
+ import { wholeJobAskIndex, wholeJobText } from './whole-job.js';
80
81
  import { fetchPageText, isWebUrl } from './pagefetch.js';
81
82
  import { readTicketMcp, configForServer, remoteRefusal, mcpStartOpts, startRefusal, firstLine } from './ticket-mcp.js';
82
83
  import { createMCPBridge, discoverServers } from 'bare-agent/mcp';
@@ -1004,7 +1005,7 @@ async function runStepTries({
1004
1005
  // M4d am25: `thinkingMode` is the ONE decision of what this try asks of thinking (`stepThinkingMode`); the model step only passes it on.
1005
1006
  // M10 am7 item 3: `cited` is the fact part of a green step that quotes a saved page - the form of its ANSWER ({results: [{quote, values}]}) and the facts it must hold,
1006
1007
  // told to the step in plain words by the model step. It is not the check: the quotes are checked by `closeCited` against the run's own copy.
1007
- const stepMeta = Object.freeze({ class: step.close?.class ?? null, cited: step.close?.class === 'green' && step.close.cited ? step.close.cited : null, sheet: step.close?.class === 'green' && Array.isArray(step.close.sheet) ? step.close.sheet : null, attempt, step: step?.emits ?? step?.goal ?? null, thinkingMode: stepThinkingMode({ boxOn: thinkingBox, attempt }) });
1008
+ const stepMeta = Object.freeze({ class: step.close?.class ?? null, cited: step.close?.class === 'green' && step.close.cited ? step.close.cited : null, sheet: step.close?.class === 'green' && Array.isArray(step.close.sheet) ? step.close.sheet : null, withText: step.close?.class === 'green' && Array.isArray(step.close.picked) && step.close.picked.length > 0, picked: step.close?.class === 'green' && Array.isArray(step.close.picked) ? step.close.picked : null, attempt, step: step?.emits ?? step?.goal ?? null, thinkingMode: stepThinkingMode({ boxOn: thinkingBox, attempt }) });
1008
1009
 
1009
1010
  const stopSeam = readStop ? Object.freeze({ stopRequested: readStop }) : undefined;
1010
1011
 
@@ -1398,19 +1399,19 @@ export async function runFlow({
1398
1399
 
1399
1400
  // M4d am25: the run keeps the job's "Thinking on" box as it is now (read by `readJobThinking` on every try and every resume); taken here, recorded in `run.json` once the inputs are frozen
1400
1401
  const thinkingBox = readModelRecord(flowDir)?.thinking === true;
1401
- // M8 item 6: the first run from a freshly signed flow takes the learnings its draft was handed (the Audit box); a run that kept its own plan already has its record; a failure never stops the run
1402
- if (!runOwnsPlan(runDir)) {
1403
- try { takeLearningsRecord(flowDir, runDir); } catch (/** @type {any} */ e) {
1404
- try { appendRow(join(runDir, LEARN_ERROR_FILE), { at: now(), error: redactSecrets(`learnings record: ${e?.message ?? e}`).split('\n')[0] }); } catch { /* best-effort */ }
1405
- }
1406
- }
1407
-
1408
1402
  const frozen = await freezeInputs(runDir, sources ?? [], { fetchPage, tableRoles: sheetRolesOf(declaration.steps), mcp: declaration.mcp, ticketFilter: declaration.ticketFilter });
1409
1403
  if (!frozen.ok) {
1410
1404
  return haltRun({
1411
1405
  flowDir, runDir, runId, capUsd, startedAt, now, nowMs: getNowMs, signatureHash: signature.flow, outcome: 'preflight-red', red: frozen.red, spent: { value: 0 },
1412
1406
  });
1413
1407
  }
1408
+ // M8 item 6: the first run from a freshly signed flow takes the learnings its draft was handed (the Audit box); a run that kept its own plan already has its record; taken only once the inputs froze, so a run refused at its inputs leaves it; a failure never stops the run
1409
+ if (!runOwnsPlan(runDir)) {
1410
+ try { takeLearningsRecord(flowDir, runDir); } catch (/** @type {any} */ e) {
1411
+ try { appendRow(join(runDir, LEARN_ERROR_FILE), { at: now(), error: redactSecrets(`learnings record: ${e?.message ?? e}`).split('\n')[0] }); } catch { /* best-effort */ }
1412
+ }
1413
+ }
1414
+
1414
1415
  // M8b item 1: the run's start record, written once: the model it started on (M4d am33), the "Thinking on" box (M4d am25) and the frozen inputs
1415
1416
  writeRunStart(runDir, { model: runModel ?? null, thinking: thinkingBox, inputs: /** @type {any[]} */ (frozen.manifest), rerun: rerunOf ?? null });
1416
1417
  // M12 piece 3 (item 9): a ticket the signed labels do not match, or a closed one, ends here: skipped, $0, nothing else runs
@@ -1605,6 +1606,8 @@ async function runAskSlot({
1605
1606
  runStartedAt,
1606
1607
  // M13 item 5: the job's signed `mcp.server`; a redo of the step before the ask runs it again with its signed MCP tools
1607
1608
  mcpServer = /** @type {string|null} */ (null),
1609
+ // M13 am9: set only for the Ask that shows the whole job; rebuilds `{text}` from the saved outputs after a redo changed one
1610
+ rebuildPrior = /** @type {null | (() => ({ok:true,value:any}|{ok:false,red:string}))} */ (null),
1608
1611
  }) {
1609
1612
  let redone = initialRedone;
1610
1613
  let currentPrior = priorArtifact;
@@ -1794,6 +1797,11 @@ async function runAskSlot({
1794
1797
  // case `writeArtifact` allows to overwrite on purpose.
1795
1798
  writeArtifact(runDir, priorId, currentPrior, { overwrite: true });
1796
1799
  artifacts[priorId] = currentPrior;
1800
+ if (rebuildPrior) {
1801
+ const whole = rebuildPrior();
1802
+ if (!whole.ok) return { type: 'halted', outcome: 'red', red: whole.red };
1803
+ currentPrior = whole.value;
1804
+ }
1797
1805
  // eslint-disable-next-line no-continue
1798
1806
  continue;
1799
1807
  }
@@ -1844,6 +1852,9 @@ async function foldFromStep({
1844
1852
  }) {
1845
1853
  let runAcceptedThisRun = acceptedThisRun;
1846
1854
  let runUnjudged = unjudgedSinceLastAsk;
1855
+ // M13 am9: the Ask that shows the whole job (-1 = none: a job signed before am8 is unchanged)
1856
+ const wholeIdx = wholeJobAskIndex({ steps, askLines, sendLines });
1857
+ const rebuildWhole = () => wholeJobText({ steps, askLines, lastAskIndex: wholeIdx, readResult: (id) => readArtifactResult(runDir, id) });
1847
1858
 
1848
1859
  for (let i = i0; i < steps.length; i += 1) {
1849
1860
  const step = steps[i];
@@ -1955,7 +1966,17 @@ async function foldFromStep({
1955
1966
  : `ask: prior artifact "${priorId}" for step "${step.goal}" — ${priorArtifactResult.red}`,
1956
1967
  });
1957
1968
  }
1958
- const priorArtifact = priorArtifactResult.value;
1969
+ let priorArtifact = priorArtifactResult.value;
1970
+ if (i === wholeIdx) {
1971
+ const whole = rebuildWhole();
1972
+ if (!whole.ok) {
1973
+ return haltRun({
1974
+ flowDir, runDir, runId, capUsd, startedAt: runStartedAt, now, nowMs, signatureHash, spent, priorSpendComplete: spendComplete.value, attempts: attemptsLog, artifacts,
1975
+ outcome: 'red', red: whole.red,
1976
+ });
1977
+ }
1978
+ priorArtifact = whole.value;
1979
+ }
1959
1980
 
1960
1981
  // M2 amendment 1 item 2: every hitl artifact carried since the
1961
1982
  // previous ask goes to THIS ask as evidence, alongside the ask step's
@@ -1976,6 +1997,7 @@ async function foldFromStep({
1976
1997
  priorStepNo: priorStepIndex + 1,
1977
1998
  priorPrevStepId: priorStepIndex > 0 ? (steps[priorStepIndex - 1].emits ?? null) : null,
1978
1999
  priorArtifact,
2000
+ rebuildPrior: i === wholeIdx ? rebuildWhole : null,
1979
2001
  redoCap,
1980
2002
  effectiveCeilingUsd,
1981
2003
  capUsd,
@@ -2636,7 +2658,21 @@ export async function resumeRun({
2636
2658
  // `priorId` names a step strictly earlier than the parked ask
2637
2659
  // (state.stepIndex), so i < state.stepIndex — already proven `ok` by the
2638
2660
  // "was this step already done" gate above; safe to collapse here.
2639
- const priorArtifact = readArtifact(runDir, priorId);
2661
+ let priorArtifact = readArtifact(runDir, priorId);
2662
+ // M13 am9: the Ask that shows the whole job rebuilds `{text}` from the saved outputs, as the first pass did
2663
+ const wholeIdx = wholeJobAskIndex({ steps, askLines, sendLines });
2664
+ const rebuildWhole = () => wholeJobText({ steps, askLines, lastAskIndex: wholeIdx, readResult: (id) => readArtifactResult(runDir, id) });
2665
+ if (state.stepIndex === wholeIdx) {
2666
+ const whole = rebuildWhole();
2667
+ if (!whole.ok) {
2668
+ return haltRun({
2669
+ flowDir, runDir, runId, capUsd, startedAt: runStartedAt, now, nowMs: getNowMs, signatureHash: state.signatureHash, spent, priorSpendComplete: spendComplete.value, attempts: attemptsLog, artifacts,
2670
+ outcome: 'red', red: whole.red,
2671
+ resumeAt: { stepIndex: state.stepIndex, flowRoot: root, flowName: name, inputsManifest: state.inputsManifest, unjudged: state.evidenceUnjudged ?? [], redone: typeof state.redone === 'number' ? state.redone : 0 },
2672
+ });
2673
+ }
2674
+ priorArtifact = whole.value;
2675
+ }
2640
2676
 
2641
2677
  const oneShotAskStep = makeOneShotThenParkAskStep({ decision: answer.decision, reason: answer.reason, artifactSha256: answer.artifactSha256 });
2642
2678
 
@@ -2650,6 +2686,7 @@ export async function resumeRun({
2650
2686
  priorStepNo: priorStepIndex + 1,
2651
2687
  priorPrevStepId: priorStepIndex > 0 ? (steps[priorStepIndex - 1].emits ?? null) : null,
2652
2688
  priorArtifact,
2689
+ rebuildPrior: state.stepIndex === wholeIdx ? rebuildWhole : null,
2653
2690
  redoCap,
2654
2691
  effectiveCeilingUsd,
2655
2692
  capUsd,
package/src/sheetblock.js CHANGED
@@ -7,6 +7,7 @@
7
7
  // A green "found" is the step's OWN claimed value in plain words (a number, or a count of rows / days / bands / groups); a string claim (a looked-up cell) is never
8
8
  // repeated, because it is cell text. A red "found" is bareguard's gap words (row numbers and counts), never a cell's text.
9
9
  // Third outcomes, named: a line the run never reached (no record) carries no verdict; a check the record lacks carries none (the page shows no mark).
10
+ import { labelled } from './checkwords.js';
10
11
  import { isDeepStrictEqual } from 'node:util';
11
12
  import { rubricVocabulary } from 'bareguard';
12
13
  import { lineRules } from './pagebits.js';
@@ -90,7 +91,7 @@ export function sheetLineBlocks({ declaration, lines, csvRoles = [], record }) {
90
91
  const words = sheetCheckSentence(c);
91
92
  const cw = coversWords(rules);
92
93
  /** @type {any} */
93
- const e = { id: typeof c.id === 'string' ? c.id : '', name, words, covers: rules, coversWords: cw, text: [name, ...(words === name ? [] : [words]), ...(cw ? [cw] : [])].join(' — ') };
94
+ const e = { id: typeof c.id === 'string' ? c.id : '', name, words, covers: rules, coversWords: cw, text: labelled([name, ...(words === name ? [] : [words]), ...(cw ? [cw] : [])].join(' — '), 'agent') }; // M10 am22 (4): the AI wrote every sheet check
94
95
  const res = newest && Array.isArray(newest.results) ? newest.results.find((/** @type {any} */ r) => isRec(r) && r.id === c.id) : undefined;
95
96
  if (isRec(res) && typeof res.ok === 'boolean') {
96
97
  e.ok = res.ok;