fwdloop 0.23.0 → 0.24.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/runner.js CHANGED
@@ -65,13 +65,16 @@ import { writeSheetLine } from './sheet-record.js';
65
65
  import {
66
66
  appendAudit, appendHistory, readAudit, readHistory, endRow, HALT_OUTCOMES,
67
67
  } from './books.js';
68
+ import { learnAtRunEnd, NOT_A_RUN_END, hintsForRun, placeSpecOf } from './learnstore.js';
69
+ import { redactSecrets } from './redact.js';
70
+ import { appendRow } from './jsonl-append.js';
68
71
  import { applyRunValues, pickRunValues } from './runvalues.js';
69
- import { stepThinkingMode } from './thinking.js';
72
+ import { stepThinkingMode, stepHintsWanted } from './thinking.js';
70
73
  import { appendChecks, nextRound } from './diary.js';
71
74
  import {
72
75
  doneRecord, happenedRecord, outputRecord, closeRecords,
73
76
  } from './try-checks.js';
74
- import { readJobThinking, writeRunThinking, writeRunModel } from './flowmodel.js';
77
+ import { readJobThinking, writeRunThinking, writeRunModel, takeLearningsRecord } from './flowmodel.js';
75
78
  import { fetchPageText, isWebUrl } from './pagefetch.js';
76
79
  import {
77
80
  readResumeLock, recordPid, writeLockHolder, procStartOf, LOCK_NO_HOLDER,
@@ -218,9 +221,9 @@ const holdOf = (ceilingUsd) => (Number.isFinite(ceilingUsd) && /** @type {number
218
221
  // WITHOUT the cap (M2 scope item 3, the load-bearing invariant).
219
222
  // ---------------------------------------------------------------------------
220
223
 
221
- const EXECUTOR_FIELDS = Object.freeze(['goal', 'primitives', 'reads', 'gap']);
224
+ const EXECUTOR_FIELDS = Object.freeze(['goal', 'primitives', 'reads', 'gap', 'hints']);
222
225
 
223
- /** @param {{goal:string, primitives?:string[], reads?:Record<string,any>, gap?:string|null}} opts */
226
+ /** @param {{goal:string, primitives?:string[], reads?:Record<string,any>, gap?:string|null, hints?:string|null}} opts `hints` (M8 am7): the earlier runs' block, text only, for a retry / redo / rerun try */
224
227
  export function buildExecutorContext(opts) {
225
228
  for (const key of Object.keys(opts ?? {})) {
226
229
  if (!EXECUTOR_FIELDS.includes(key)) {
@@ -228,13 +231,14 @@ export function buildExecutorContext(opts) {
228
231
  }
229
232
  }
230
233
  const {
231
- goal, primitives = [], reads = {}, gap = null,
234
+ goal, primitives = [], reads = {}, gap = null, hints = null,
232
235
  } = opts ?? {};
233
236
  return Object.freeze({
234
237
  goal,
235
238
  primitives: Object.freeze([...primitives]),
236
239
  reads: Object.freeze({ ...reads }),
237
240
  gap: gap ?? null,
241
+ hints: hints ?? null,
238
242
  });
239
243
  }
240
244
 
@@ -681,6 +685,59 @@ function recordLateAnswerIfAny(runDir, now = () => new Date().toISOString()) {
681
685
  });
682
686
  }
683
687
 
688
+ // ---------------------------------------------------------------------------
689
+ // M8 items 2 and 4 (item 4 replaced by am4): the run-end tally of cross-run learnings ($0, code only, no model call). ONE call per run
690
+ // exit, from the three callers of `foldFromStep` (runFlow, resumeRun, continueRun), the expired-ask exit and the rerun exit. A record,
691
+ // never a verdict: it can never change a run's outcome, result, spend or books. It runs whether `learningHints` is on or off.
692
+ // - M8 am4: every run's notes COUNT when the run ends, FIXED and NEVER FIXED alike, whatever the ending and whether or not its asks
693
+ // were accepted. No hold, no release (bareloop's ruling for both repos, 2026-10-24).
694
+ // - A run waiting at an ask has not ended ('paused', or a Stop whose set-aside failed): no note yet. A Stop or a cap-halt HAS ended
695
+ // the leg, as in bareloop: its notes are made then, and a later resume folds the whole run again (the ledger counts a run once per row).
696
+ // - Noise runs (provider red, a crashed check) make no note: buildCards reads them off the escalation events eventsOfRun builds.
697
+ // Under a test process with no FWDLOOP_CONFIG_HOME nothing is written (`configDoorHome`), as for every config read.
698
+ // borrowed-from: bareloop src/userrun.js@v0.46.0:2035 (the call site, in its own try/catch)
699
+ // ---------------------------------------------------------------------------
700
+
701
+ /** where a failure of learnings work that must not stop the run is recorded (one appended row, in the run's own folder): the run-end tally (`recordRunNotes`) and the take of the draft's learnings record (`takeLearningsRecord`, in runFlow). The run itself is unaffected */
702
+ export const LEARN_ERROR_FILE = 'learn-error.jsonl';
703
+
704
+ /**
705
+ * @param {{flowName: string, runId: string, runDir: string, outcome: string, specHash: string|null, now: () => string}} o
706
+ */
707
+ function recordRunNotes({
708
+ flowName, runId, runDir, outcome, specHash, now,
709
+ }) {
710
+ if (NOT_A_RUN_END.has(outcome)) return;
711
+ const door = configDoorHome();
712
+ if (door.skip) return;
713
+ try {
714
+ const r = learnAtRunEnd({
715
+ home: door.home, workflow: flowName, runId, runDir, specHash, now: new Date(now()),
716
+ });
717
+ if (r.problem) throw new Error(r.problem);
718
+ } catch (/** @type {any} */ e) {
719
+ try {
720
+ appendRow(join(runDir, LEARN_ERROR_FILE), { at: now(), error: redactSecrets(String(e?.message ?? e)).split('\n')[0] });
721
+ } catch { /* the record of the failure is itself best-effort */ }
722
+ }
723
+ }
724
+
725
+ /**
726
+ * M8 am7 item 1: the step's side of "one block". `hintsForRun` (src/learnstore.js) is the ONE function that makes the block the drafter is handed; a step's try
727
+ * calls that same function, with the run's own workflow name, first input source and clock, and a null specHash exactly as the drafter does (so no second filter by job version), and takes its answer whole (no second render, no filter).
728
+ * Returns null when `learningHints` is off, when there is no ledger or nothing readable, or in a test process with no config home. A ledger problem THROWS (the caller
729
+ * hands nothing and records why as `hintsError` on the try's audit row, never a failed step).
730
+ * @param {{flowName: string, source: string|null, now: () => string}} o
731
+ * @returns {() => {text: string, ids: string[]}|null}
732
+ */
733
+ function stepHintsReader({ flowName, source, now }) {
734
+ return () => {
735
+ const door = configDoorHome();
736
+ if (door.skip) return null;
737
+ return hintsForRun({ home: door.home, spec: placeSpecOf(flowName, source), specHash: null, now: new Date(now()) });
738
+ };
739
+ }
740
+
684
741
  // ---------------------------------------------------------------------------
685
742
  // The ralph loop with strikes (M2 scope item 5) for ONE step.
686
743
  // ---------------------------------------------------------------------------
@@ -722,6 +779,10 @@ function sumKnownUsd(...values) {
722
779
  function makeAuditRow({
723
780
  step, attempt, verdict, gap, usd, spendComplete, wallMs, model = null, modelMatch = null, strike, at, tokens = null, tools = null, ungranted = /** @type {string[]|undefined} */ (undefined), refused = /** @type {Array<{verb:string,path:string,rule:string}>} */ ([]),
724
781
  thinking = /** @type {{asked:string, status:string|null}|undefined} */ (undefined),
782
+ hints = /** @type {number|undefined} */ (undefined),
783
+ hintsText = /** @type {string|undefined} */ (undefined),
784
+ hintIds = /** @type {string[]|undefined} */ (undefined),
785
+ hintsError = /** @type {string|undefined} */ (undefined),
725
786
  }) {
726
787
  const row = {
727
788
  step: step?.emits ?? step?.goal ?? null,
@@ -743,6 +804,10 @@ function makeAuditRow({
743
804
  if (ungranted !== undefined && ungranted.length > 0) row.ungranted = ungranted;
744
805
  // M4d am25 item 4: the thinking this model call asked for and what bareagent reported back; the ONE writer of the field. A row with no model call has none.
745
806
  if (thinking !== undefined) row.thinking = thinking;
807
+ // M8 am7 item 4: how many hints from earlier runs this try was handed, the exact text and the ids; the keys are absent when none were. The ONE place the handed text is kept
808
+ // (this row, written after the call from what the try held in memory); a failed ask for the block is `hintsError`, the first line, secrets redacted.
809
+ if (hints !== undefined) { row.hints = hints; row.hintsText = hintsText; row.hintIds = hintIds; }
810
+ if (hintsError !== undefined) row.hintsError = hintsError;
746
811
  return row;
747
812
  }
748
813
 
@@ -765,6 +830,7 @@ function makeAuditRow({
765
830
  * @param {(row: any, modelOutput?: any) => void} opts.recordAudit
766
831
  * @param {string|null} [opts.initialGap]
767
832
  * @param {number} [opts.attemptOffset]
833
+ * @param {(() => {text: string, ids: string[]}|null)|null} [opts.learnHints] - M8 am7: `stepHintsReader`'s closure (the drafter's one block function); asked only on a retry, redo or rerun try
768
834
  * @param {boolean} [opts.thinkingBox] - M4d am25: the job's "Thinking on" box as this run's copy keeps it (default off)
769
835
  * @param {() => string} [opts.now] - M4a-2: stamps each audit row's `at`;
770
836
  * defaults to the real wall clock.
@@ -779,6 +845,7 @@ export async function runStepRalph({
779
845
  step, primitivesMap, readsMap, businessDate, modelStep, spent, capUsd, ceilingUsd, recordAudit, initialGap = null, attemptOffset = 0,
780
846
  // M4d am25: the job's "Thinking on" box as the run's own copy keeps it; read once by the caller (`readJobThinking`), decided per try below by `stepThinkingMode`.
781
847
  thinkingBox = false,
848
+ learnHints = null,
782
849
  // M4a-2: the run's own injected clock (never the bare wall clock) —
783
850
  // stamps every audit row's `at` with this attempt's finish time. Defaults
784
851
  // to the real wall clock so a caller that doesn't inject one (there are
@@ -835,8 +902,29 @@ export async function runStepRalph({
835
902
  }
836
903
 
837
904
  const grantedTools = Object.fromEntries((step.primitives ?? []).map((verb) => [verb, primitivesMap?.[verb]]));
905
+ // M8 am7: the earlier runs' block for THIS try only - a retry, a redo or a rerun (`stepHintsWanted`; the Chat box never decides it). It is the drafter's one block
906
+ // function asked again now. What it handed is kept in memory and rides EVERY audit row this try writes (the row is written after the call, so the record exists once the
907
+ // try's row does); any failure hands nothing and rides the row as `hintsError`.
908
+ /** @type {{text: string, ids: string[]}|null} */
909
+ let handed = null;
910
+ /** @type {string|undefined} */
911
+ let handedError;
912
+ if (learnHints !== null && stepHintsWanted({ attempt, rerunReason: n === 1 ? initialGap : null })) {
913
+ try {
914
+ handed = learnHints();
915
+ } catch (/** @type {any} */ e) {
916
+ handed = null;
917
+ handedError = redactSecrets(String(e?.message ?? e)).split('\n')[0];
918
+ }
919
+ }
920
+ // every row this try writes from here on carries how many hints it was handed, which, and what (none handed = no field)
921
+ const rowOf = (/** @type {any} */ a) => makeAuditRow({
922
+ ...a,
923
+ ...(handed !== null ? { hints: handed.ids.length, hintsText: handed.text, hintIds: handed.ids } : {}),
924
+ ...(handedError !== undefined ? { hintsError: handedError } : {}),
925
+ });
838
926
  const executorContext = buildExecutorContext({
839
- goal: step.goal, primitives: step.primitives ?? [], reads: readsMap, gap,
927
+ goal: step.goal, primitives: step.primitives ?? [], reads: readsMap, gap, hints: handed === null ? null : handed.text,
840
928
  });
841
929
 
842
930
  // `stepMeta` is a SEPARATE argument from `executorContext` — never a
@@ -892,7 +980,7 @@ export async function runStepRalph({
892
980
  if (typeof result.costUsd === 'number') spent.value += result.costUsd;
893
981
  const usd = sumKnownUsd(attemptFloorUsd, result.costUsd);
894
982
  const ranCalls = (turns ?? 0) > 0 || attemptFloorUsd !== null;
895
- return stopped(stopWords(ranCalls ? attempt : attempt - 1, turns ?? 0), makeAuditRow({
983
+ return stopped(stopWords(ranCalls ? attempt : attempt - 1, turns ?? 0), rowOf({
896
984
  step, attempt: ranCalls ? attempt : null, verdict: 'stopped', gap: null, usd, spendComplete: usd !== null, wallMs, model: result.model, modelMatch: result.modelMatch, strike: false, at: now(), tokens: result.tokens ?? null, tools: result.tools ?? null, ungranted: result.ungranted, refused: result.refused, thinking: result.thinking,
897
985
  }));
898
986
  }
@@ -903,7 +991,7 @@ export async function runStepRalph({
903
991
  // already added to `spent.value` above (never double-added here); a
904
992
  // null second cost never zeroes out a known first floor.
905
993
  const usd = sumKnownUsd(attemptFloorUsd, result.costUsd);
906
- recordAudit(makeAuditRow({
994
+ recordAudit(rowOf({
907
995
  step, attempt, verdict: 'provider-red', gap, usd, spendComplete: false, wallMs, model: result.model, modelMatch: result.modelMatch, strike: false, at: now(), tokens: result.tokens ?? null, tools: result.tools ?? null, ungranted: result.ungranted, refused: result.refused, thinking: result.thinking,
908
996
  }), result.red ?? 'transport fault twice');
909
997
  return { ok: false, outcome: 'provider-red', red: `provider-red: step "${step.goal}" attempt ${attempt}: ${result.red ?? 'transport fault twice'}` };
@@ -923,7 +1011,7 @@ export async function runStepRalph({
923
1011
  seenGaps.add(normalised);
924
1012
  if (strike) strikes += 1;
925
1013
  const usd = sumKnownUsd(attemptFloorUsd, result?.costUsd);
926
- recordAudit(makeAuditRow({
1014
+ recordAudit(rowOf({
927
1015
  step, attempt, verdict: 'red', gap: red, usd, spendComplete: usd !== null, wallMs, model: result?.model, modelMatch: result?.modelMatch, strike, at: now(), tokens: result?.tokens ?? null, tools: result?.tools ?? null, ungranted: result?.ungranted, refused: result?.refused, thinking: result?.thinking,
928
1016
  }), red);
929
1017
  if (n === maxN) return { ok: false, outcome: 'attempt-fallback', red: `attempt-fallback: step "${step.goal}" — ${red}` };
@@ -934,7 +1022,7 @@ export async function runStepRalph({
934
1022
  }
935
1023
 
936
1024
  if (result.costUsd === null || result.costUsd === undefined) {
937
- recordAudit(makeAuditRow({
1025
+ recordAudit(rowOf({
938
1026
  step, attempt, verdict: 'pricing-red', gap, usd: attemptFloorUsd, spendComplete: false, wallMs, model: result.model, modelMatch: result.modelMatch, strike: false, at: now(), tokens: result.tokens ?? null, tools: result.tools ?? null, ungranted: result.ungranted, refused: result.refused, thinking: result.thinking,
939
1027
  }), result.artifact ?? null);
940
1028
  return { ok: false, outcome: 'pricing-red', red: `pricing-red: step "${step.goal}" attempt ${attempt} returned no cost (never "?? 0")` };
@@ -961,7 +1049,7 @@ export async function runStepRalph({
961
1049
  tryChecks.push(doneRecord(doneCheck, result.artifact));
962
1050
  if (doneCheck.verdict === 'not-done') {
963
1051
  saveTry();
964
- recordAudit(makeAuditRow({
1052
+ recordAudit(rowOf({
965
1053
  step, attempt, verdict: 'not-done', gap: doneCheck.red, usd: attemptUsd, spendComplete: true, wallMs, model: result.model, modelMatch: result.modelMatch, strike: false, at: now(), tokens: result.tokens ?? null, tools: result.tools ?? null, ungranted: result.ungranted, refused: result.refused, thinking: result.thinking,
966
1054
  }), result.artifact ?? null);
967
1055
  return { ok: false, outcome: 'not-done', red: doneCheck.red };
@@ -977,7 +1065,7 @@ export async function runStepRalph({
977
1065
  // (never gated by novelty — an empty artifact is always the same
978
1066
  // failure) — matches poc/m2/gapback.mjs's own rule exactly.
979
1067
  strikes += 1;
980
- recordAudit(makeAuditRow({
1068
+ recordAudit(rowOf({
981
1069
  step, attempt, verdict: 'red', gap: happened.red, usd: attemptUsd, spendComplete: true, wallMs, model: result.model, modelMatch: result.modelMatch, strike: true, at: now(), tokens: result.tokens ?? null, tools: result.tools ?? null, ungranted: result.ungranted, refused: result.refused, thinking: result.thinking,
982
1070
  }), result.artifact ?? null);
983
1071
  if (n === maxN) return { ok: false, outcome: 'attempt-fallback', red: `attempt-fallback: ${happened.red}` };
@@ -1006,7 +1094,7 @@ export async function runStepRalph({
1006
1094
  saveTry();
1007
1095
 
1008
1096
  if (closed.verdict === 'green' || closed.verdict === 'hitl') {
1009
- recordAudit(makeAuditRow({
1097
+ recordAudit(rowOf({
1010
1098
  step, attempt, verdict: closed.verdict, gap: null, usd: attemptUsd, spendComplete: true, wallMs, model: result.model, modelMatch: result.modelMatch, strike: false, at: now(), tokens: result.tokens ?? null, tools: result.tools ?? null, ungranted: result.ungranted, refused: result.refused, thinking: result.thinking,
1011
1099
  }), result.artifact);
1012
1100
  return {
@@ -1017,7 +1105,7 @@ export async function runStepRalph({
1017
1105
  if (closed.verdict !== 'red') {
1018
1106
  // A closer that renders no judgment ('unparseable'/'crash') is a
1019
1107
  // CASUALTY, never a red and never a strike (bareloop F17).
1020
- recordAudit(makeAuditRow({
1108
+ recordAudit(rowOf({
1021
1109
  step, attempt, verdict: 'close-casualty', gap: closed.red, usd: attemptUsd, spendComplete: true, wallMs, model: result.model, modelMatch: result.modelMatch, strike: false, at: now(), tokens: result.tokens ?? null, tools: result.tools ?? null, ungranted: result.ungranted, refused: result.refused, thinking: result.thinking,
1022
1110
  }), result.artifact);
1023
1111
  return { ok: false, outcome: 'close-casualty', red: `close-casualty: step "${step.goal}" — ${closed.red} (${closed.verdict})` };
@@ -1027,7 +1115,7 @@ export async function runStepRalph({
1027
1115
  const strike = seenGaps.has(normalised);
1028
1116
  seenGaps.add(normalised);
1029
1117
  if (strike) strikes += 1;
1030
- recordAudit(makeAuditRow({
1118
+ recordAudit(rowOf({
1031
1119
  step, attempt, verdict: 'red', gap: closed.red, usd: attemptUsd, spendComplete: true, wallMs, model: result.model, modelMatch: result.modelMatch, strike, at: now(), tokens: result.tokens ?? null, tools: result.tools ?? null, ungranted: result.ungranted, refused: result.refused, thinking: result.thinking,
1032
1120
  }), result.artifact);
1033
1121
 
@@ -1179,6 +1267,12 @@ export async function runFlow({
1179
1267
  // M4d am25: the run keeps the job's "Thinking on" box as it is now (read by `readJobThinking` on every try and every resume)
1180
1268
  writeRunThinking(flowDir, runDir);
1181
1269
  if (runModel) writeRunModel(runDir, runModel); // M4d am33: the one record of the model this run started on
1270
+ // 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
1271
+ if (!runOwnsPlan(runDir)) {
1272
+ try { takeLearningsRecord(flowDir, runDir); } catch (/** @type {any} */ e) {
1273
+ try { appendRow(join(runDir, LEARN_ERROR_FILE), { at: now(), error: redactSecrets(`learnings record: ${e?.message ?? e}`).split('\n')[0] }); } catch { /* best-effort */ }
1274
+ }
1275
+ }
1182
1276
 
1183
1277
  const frozen = await freezeInputs(runDir, sources ?? [], { fetchPage, tableRoles: sheetRolesOf(declaration.steps) });
1184
1278
  if (!frozen.ok) {
@@ -1281,6 +1375,9 @@ export async function runFlow({
1281
1375
  attemptsLog,
1282
1376
  firstStepGap: initialGap ?? null,
1283
1377
  });
1378
+ recordRunNotes({
1379
+ flowName: name, runId, runDir, outcome: result.outcome, specHash: signature.flow, now,
1380
+ });
1284
1381
 
1285
1382
  if (result.outcome === 'complete') return { ...result, auditRows };
1286
1383
  return result;
@@ -1544,7 +1641,7 @@ async function runAskSlot({
1544
1641
  }
1545
1642
  // eslint-disable-next-line no-await-in-loop
1546
1643
  const redoResult = await runStepRalph({
1547
- step: priorStep, primitivesMap: primitives, readsMap: priorReadsResult.map, businessDate, modelStep, spent, capUsd, ceilingUsd: effectiveCeilingUsd, recordAudit, initialGap: reason, attemptOffset: lastTryNumber(runDir, priorStep.emits ?? priorStep.goal ?? null), thinkingBox: readJobThinking(flowDir, runDir), now, runDir,
1644
+ step: priorStep, primitivesMap: primitives, readsMap: priorReadsResult.map, businessDate, modelStep, spent, capUsd, ceilingUsd: effectiveCeilingUsd, recordAudit, initialGap: reason, attemptOffset: lastTryNumber(runDir, priorStep.emits ?? priorStep.goal ?? null), thinkingBox: readJobThinking(flowDir, runDir), learnHints: stepHintsReader({ flowName, source: inputsManifest?.[0]?.source ?? null, now }), now, runDir,
1548
1645
  readStop: () => stopPending(runDir), stepNo: priorStepNo, prevStepId: priorPrevStepId,
1549
1646
  });
1550
1647
  if (!redoResult.ok) {
@@ -1799,7 +1896,7 @@ async function foldFromStep({
1799
1896
  // redo's `initialGap` above.
1800
1897
  // eslint-disable-next-line no-await-in-loop
1801
1898
  const stepResult = await runStepRalph({
1802
- step, primitivesMap: primitives, readsMap, businessDate, modelStep, spent, capUsd, ceilingUsd: effectiveCeilingUsd, recordAudit, initialGap: i === i0 ? firstStepGap : null, thinkingBox: readJobThinking(flowDir, runDir), now, runDir,
1899
+ step, primitivesMap: primitives, readsMap, businessDate, modelStep, spent, capUsd, ceilingUsd: effectiveCeilingUsd, recordAudit, initialGap: i === i0 ? firstStepGap : null, thinkingBox: readJobThinking(flowDir, runDir), learnHints: stepHintsReader({ flowName, source: inputsManifest?.[0]?.source ?? null, now }), now, runDir,
1803
1900
  readStop: () => stopPending(runDir), stepNo: i + 1, prevStepId: i > 0 ? (steps[i - 1].emits ?? steps[i - 1].goal ?? null) : null, attemptOffset: i === i0 ? resumeTries.numbered : 0, triesDone: i === i0 ? resumeTries.done : 0,
1804
1901
  });
1805
1902
  if (!stepResult.ok) {
@@ -2256,6 +2353,9 @@ export async function resumeRun({
2256
2353
  appendHistory(flowDir, {
2257
2354
  runId, at: now(), outcome: 'ask-expired', spentUsd: spent.value, spendComplete: spendComplete.value, capUsd: arbiter.capUsd ?? null, wallMs: getNowMs() - runStartedAt, signatureHash: state.signatureHash,
2258
2355
  });
2356
+ recordRunNotes({
2357
+ flowName: name, runId, runDir, outcome: 'ask-expired', specHash: state.signatureHash, now,
2358
+ });
2259
2359
  return { outcome: 'ask-expired', runDir, spentUsd: spent.value };
2260
2360
  }
2261
2361
 
@@ -2289,6 +2389,10 @@ export async function resumeRun({
2289
2389
  runId, at: now(), outcome: 'rerun', spentUsd: spent.value, spendComplete: spendComplete.value, capUsd: arbiter.capUsd ?? null, wallMs: getNowMs() - runStartedAt, signatureHash: state.signatureHash,
2290
2390
  });
2291
2391
  }
2392
+ // M8 am4: a rerun ends THIS run, so its notes count now (the new run, started below, makes its own).
2393
+ recordRunNotes({
2394
+ flowName: name, runId, runDir, outcome: 'rerun', specHash: state.signatureHash, now,
2395
+ });
2292
2396
 
2293
2397
  // Deterministic derived id (M3 scope item 7) — refused by name, never
2294
2398
  // silently renumbered, if it already exists.
@@ -2479,6 +2583,9 @@ export async function resumeRun({
2479
2583
  recordAudit,
2480
2584
  attemptsLog,
2481
2585
  });
2586
+ recordRunNotes({
2587
+ flowName: name, runId, runDir, outcome: result.outcome, specHash: state.signatureHash, now,
2588
+ });
2482
2589
 
2483
2590
  if (result.outcome === 'complete') return { ...result, auditRows };
2484
2591
  return result;
@@ -2681,6 +2788,9 @@ export async function continueRun({
2681
2788
  recordAudit,
2682
2789
  attemptsLog,
2683
2790
  });
2791
+ recordRunNotes({
2792
+ flowName: name, runId, runDir, outcome: result.outcome, specHash: halt.signatureHash, now,
2793
+ });
2684
2794
  if (result.outcome === 'complete') return { ...result, auditRows };
2685
2795
  return result;
2686
2796
  } finally {
package/src/thinking.js CHANGED
@@ -92,3 +92,14 @@ export function thinkingRuleWords(boxOn) {
92
92
  export function stepThinkingMode({ boxOn, attempt }) {
93
93
  return boxOn === true || (Number.isInteger(attempt) && attempt >= 2) ? 'on' : 'off';
94
94
  }
95
+
96
+ /**
97
+ * M8 am7 item 2: the ONE owner of whether a step's try is handed the earlier runs' block. The places thinking switches on, but NOT the Chat "Thinking on" box:
98
+ * a retry (2nd or later try), a redo at an ask (numbered after the step's last try, so 2nd or later), and a rerun (the fresh run's first step, which starts
99
+ * from the human's rerun reason). A step's plain first try never gets it, whatever the box says.
100
+ * @param {{attempt: number, rerunReason: string|null}} a `rerunReason`: the reason this try starts from when it is a fresh run's first try, else null
101
+ * @returns {boolean}
102
+ */
103
+ export function stepHintsWanted({ attempt, rerunReason }) {
104
+ return (Number.isInteger(attempt) && attempt >= 2) || (typeof rerunReason === 'string' && rerunReason !== '');
105
+ }
package/types/ask.d.ts CHANGED
@@ -51,7 +51,7 @@ export function makeFileAskStep({ timeoutMs, pollMs, clock, writeLine, }?: {
51
51
  * @param {any} ask the parsed ask.json object (or its `evidence` field's
52
52
  * container — pass the whole ask so a missing `evidence` key is itself a
53
53
  * handled case, not the caller's problem).
54
- * @returns {{ draft: {step?: string, text: string} | null, unjudged: Array<{step: string, emits?: string, text: string}>, why?: string, claims?: Record<string, any> }}
54
+ * @returns {{ draft: {step?: string, text: string} | null, unjudged: Array<{step: string, emits?: string, text?: string, cells?: Record<string, unknown>}>, why?: string, claims?: Record<string, any>, results?: Array<{quote: string, values: Record<string, unknown>}> }}
55
55
  */
56
56
  export function readAskEvidence(ask: any): {
57
57
  draft: {
@@ -61,10 +61,15 @@ export function readAskEvidence(ask: any): {
61
61
  unjudged: Array<{
62
62
  step: string;
63
63
  emits?: string;
64
- text: string;
64
+ text?: string;
65
+ cells?: Record<string, unknown>;
65
66
  }>;
66
67
  why?: string;
67
68
  claims?: Record<string, any>;
69
+ results?: Array<{
70
+ quote: string;
71
+ values: Record<string, unknown>;
72
+ }>;
68
73
  };
69
74
  /**
70
75
  * M4b piece 3: the ONE serialisation of an artifact's bytes — what
@@ -0,0 +1,38 @@
1
+ /**
2
+ * Cut `text` to at most `max` bytes at a LINE boundary (never mid-line).
3
+ * @param {string} text @param {number} max
4
+ * @returns {{text: string, truncated: boolean, cutLines: number}}
5
+ */
6
+ export function cutAtLine(text: string, max: number): {
7
+ text: string;
8
+ truncated: boolean;
9
+ cutLines: number;
10
+ };
11
+ /**
12
+ * Begin recording one worker try. Call BEFORE the worker's turn; call `finish()` after
13
+ * (in a `finally`). Never throws.
14
+ * @param {{workdir: string, fence: string[], redact?: (s: string) => string}} o
15
+ * `fence` = the ABSOLUTE write-scope prefixes the gate enforces for this try.
16
+ * @returns {Promise<{finish: () => Promise<null | {files: {path: string, diff: string, truncated: boolean, cutLines: number}[], binary: string[], truncated: boolean, gitError?: string}>}>}
17
+ * `finish()` resolves null when the try changed nothing in scope.
18
+ */
19
+ export function startAttemptDiff({ workdir, fence, redact }: {
20
+ workdir: string;
21
+ fence: string[];
22
+ redact?: (s: string) => string;
23
+ }): Promise<{
24
+ finish: () => Promise<null | {
25
+ files: {
26
+ path: string;
27
+ diff: string;
28
+ truncated: boolean;
29
+ cutLines: number;
30
+ }[];
31
+ binary: string[];
32
+ truncated: boolean;
33
+ gitError?: string;
34
+ }>;
35
+ }>;
36
+ /** per-file and per-event byte caps for the recorded diff text */
37
+ export const ATTEMPT_DIFF_FILE_MAX: 4096;
38
+ export const ATTEMPT_DIFF_EVENT_MAX: 16384;
@@ -76,6 +76,20 @@ export function placeReds({ part, line, look }: {
76
76
  facts?: any[];
77
77
  } | null | undefined;
78
78
  }): WordRed[];
79
+ /**
80
+ * A limit the page look read from a guardrail ("under $40" -> price under 40, `reading` on a kept fact, src/pagerules.js) must be carried by a fact of the part,
81
+ * with the same kind, op and bound. A plan that leaves it out would pass a result the guardrail forbids ($48 under "under $40"). Only a reading code accepts
82
+ * (validReading) whose bounds are in the person's own words on the line is demanded; a bound that is not said gets its ask (src/pageask.js), never a refusal.
83
+ * @param {{part: any, line: number, jobLine: any, look: {facts?: any[]}|null|undefined}} o @returns {WordRed[]}
84
+ */
85
+ export function boundReds({ part, line, jobLine, look, }: {
86
+ part: any;
87
+ line: number;
88
+ jobLine: any;
89
+ look: {
90
+ facts?: any[];
91
+ } | null | undefined;
92
+ }): WordRed[];
79
93
  /**
80
94
  * Every word red for one cited part, in the order a person fixes them.
81
95
  * @param {{part: any, text: string|undefined, line: number, jobLine: any, look: {facts?: any[], dropped?: any[]}|null|undefined, doc?: boolean}} o @returns {WordRed[]}
@@ -489,9 +489,10 @@ export function goalForLine(fromLine: any, lines: any): any;
489
489
  * costUsd:number|null, modelReturned:string|null, modelId?:string, price?:object|null, tokens?:object|null, structureRetries:number, revisions:number, stop:string|null, log:object[],
490
490
  * questions?:{line:number, question:string}[], droppedQuestions?:object[], notChecked?:string[], thinking?:{asked:string, status:string|null, say:string|null}, inputs?:{role:string, detail:string}[],
491
491
  * look?:{facts:any[], dropped:any[]}, pageLooks?:{role:string, address:string, sha256:string, bytes:number, frozen:string, attempts:number, mapping:any}[], sheetLooks?:any[]}>}
492
+ * `learnHints` (M8 item 5a): the earlier runs' notes block (src/learnstore.js hintsForRun), appended to the drafter's system prompt; null = nothing.
492
493
  * `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`.
493
494
  */
494
- export function draft({ proseText, slot, model, provider: injected, rates: injectedRates, modelId: injectedModelId, env, priorSpend, skills, makeProviderFn, onBook, offerQuestions, draftThinking, draftDir, fetchPage, leftRules, }: {
495
+ export function draft({ proseText, slot, model, provider: injected, rates: injectedRates, modelId: injectedModelId, env, priorSpend, skills, makeProviderFn, onBook, offerQuestions, draftThinking, draftDir, fetchPage, leftRules, learnHints, }: {
495
496
  proseText: any;
496
497
  slot: any;
497
498
  model: any;
@@ -511,6 +512,10 @@ export function draft({ proseText, slot, model, provider: injected, rates: injec
511
512
  line: number;
512
513
  rule: number;
513
514
  }[] | undefined;
515
+ learnHints?: {
516
+ text: string;
517
+ ids: string[];
518
+ } | null | undefined;
514
519
  }): Promise<{
515
520
  ok: boolean;
516
521
  declaration: object | null;
@@ -46,8 +46,44 @@ export function writeRunModel(runDir: string, { slot, model }: {
46
46
  slot: string;
47
47
  model: string;
48
48
  }): void;
49
+ /** @param {string} dir @param {{text: string, ids: string[]}} hints */
50
+ export function writeLearningsRecord(dir: string, { text, ids }: {
51
+ text: string;
52
+ ids: string[];
53
+ }): void;
54
+ /**
55
+ * The drafter's failed ask for the block (or failed record write) rides the same record: nothing handed (`text: ''`, no ids), and `error` (first line, secrets redacted).
56
+ * `readLearningsRecord` reads an empty text as no record, so the Audit box stays hidden and `copyLearningsRecord` copies nothing.
57
+ * @param {string} dir @param {string} error
58
+ */
59
+ export function writeLearningsError(dir: string, error: string): void;
60
+ /**
61
+ * M8 item 6: the Audit box reads the record in the RUN's folder. It reaches the run the way `model.json` does: a draft's record is copied (write-once) into the folder it is signed
62
+ * into (`copyLearningsRecord`: the flow folder at a new job's sign, the new run's folder at a red run's redraft), and the first run that starts from a flow folder TAKES it
63
+ * (`takeLearningsRecord`: a rename, so it moves once and a second run of the same job never shows it). A run that reused its plan has no draft, so it has none.
64
+ * @param {string} fromDir a draft folder @param {string} toDir a flow folder or a run folder @returns {boolean} true when a record was copied
65
+ */
66
+ export function copyLearningsRecord(fromDir: string, toDir: string): boolean;
67
+ /** @param {string} flowDir @param {string} runDir @returns {boolean} true when the flow's record moved into the run (it is no longer in the flow folder) */
68
+ export function takeLearningsRecord(flowDir: string, runDir: string): boolean;
69
+ /**
70
+ * The ONE reader of a run's record. null = no record, or one that is not `{phase, text, ids, chars}` (the box is then hidden, never guessed).
71
+ * @param {string} runDir @returns {{phase: string, text: string, ids: string[], chars: number}|null}
72
+ */
73
+ export function readLearningsRecord(runDir: string): {
74
+ phase: string;
75
+ text: string;
76
+ ids: string[];
77
+ chars: number;
78
+ } | null;
49
79
  export const MODEL_FILE: "model.json";
50
80
  /** M4d am25: the file in a run's folder that keeps the box as the run started with it (outside `job/`, which holds the three signed files only). */
51
81
  export const RUN_THINKING_FILE: "thinking.json";
52
82
  /** M4d am33: the file in a run's folder that records the model the run STARTED on (write-once; every continue path keeps it). */
53
83
  export const RUN_MODEL_FILE: "run-model.json";
84
+ /**
85
+ * M8 item 5a: the file that keeps EXACTLY what the drafter was handed from earlier runs (the Audit box of item 6 reads it). Bareloop's
86
+ * `learnings` spine record shape, `{phase, text, ids, chars}`. Write-once (never over an existing record); written with something handed, or by `writeLearningsError` with an empty `text`
87
+ * (a failed ask: nothing handed, why in `error`); a reader treats empty text as no record, so no file or empty text = nothing handed = no box. Borrowed-from: bareloop src/planrun.js@v0.46.0:3092 (emit('learnings', ...)).
88
+ */
89
+ export const LEARNINGS_FILE: "learnings.json";