fwdloop 0.23.0 → 0.25.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 (71) hide show
  1. package/bin/fwdloop +62 -32
  2. package/package.json +1 -1
  3. package/src/ask.js +15 -1
  4. package/src/attemptdiff.js +118 -0
  5. package/src/audit-fold.js +2 -0
  6. package/src/authoring.js +32 -2
  7. package/src/cited-record.js +3 -22
  8. package/src/cited-source.js +5 -6
  9. package/src/citedwords.js +36 -2
  10. package/src/config.js +5 -1
  11. package/src/diary.js +21 -17
  12. package/src/drafter.js +6 -2
  13. package/src/flowmodel.js +52 -28
  14. package/src/keysfile.js +1 -1
  15. package/src/launcher.js +552 -0
  16. package/src/learn.js +952 -0
  17. package/src/learnstore.js +348 -0
  18. package/src/line-checks.js +55 -0
  19. package/src/model-step.js +2 -0
  20. package/src/opener.js +33 -0
  21. package/src/pagedry.js +3 -4
  22. package/src/pagefetch.js +9 -2
  23. package/src/pagerules.js +28 -5
  24. package/src/panel/author.js +2 -0
  25. package/src/panel/authorflows.js +9 -9
  26. package/src/panel/authorresume.js +4 -3
  27. package/src/panel/data.js +63 -14
  28. package/src/panel/index.html +162 -16
  29. package/src/panel/result.js +7 -12
  30. package/src/panel/server.js +53 -5
  31. package/src/panel/settings.js +4 -18
  32. package/src/panel/spawn.js +0 -9
  33. package/src/prompts.js +33 -0
  34. package/src/redact.js +6 -6
  35. package/src/runfile.js +60 -0
  36. package/src/runner.js +144 -33
  37. package/src/sheet-record.js +15 -35
  38. package/src/sheetblock.js +3 -3
  39. package/src/sheetrun.js +6 -6
  40. package/src/summary-words.js +13 -5
  41. package/src/thinking.js +11 -0
  42. package/src/tty-colour.js +29 -0
  43. package/types/ask.d.ts +7 -2
  44. package/types/attemptdiff.d.ts +38 -0
  45. package/types/cited-record.d.ts +0 -2
  46. package/types/citedwords.d.ts +14 -0
  47. package/types/diary.d.ts +2 -5
  48. package/types/drafter.d.ts +6 -1
  49. package/types/flowmodel.d.ts +37 -20
  50. package/types/keysfile.d.ts +7 -0
  51. package/types/launcher.d.ts +307 -0
  52. package/types/learn.d.ts +576 -0
  53. package/types/learnstore.d.ts +168 -0
  54. package/types/line-checks.d.ts +26 -0
  55. package/types/opener.d.ts +12 -0
  56. package/types/pagerules.d.ts +7 -0
  57. package/types/panel/author.d.ts +2 -0
  58. package/types/panel/data.d.ts +2 -1
  59. package/types/panel/result.d.ts +2 -4
  60. package/types/panel/server.d.ts +24 -3
  61. package/types/panel/settings.d.ts +2 -2
  62. package/types/panel/spawn.d.ts +0 -6
  63. package/types/prompts.d.ts +14 -0
  64. package/types/runfile.d.ts +48 -0
  65. package/types/runner.d.ts +14 -5
  66. package/types/sheet-record.d.ts +0 -2
  67. package/types/sheetblock.d.ts +2 -2
  68. package/types/sheetrun.d.ts +1 -1
  69. package/types/summary-words.d.ts +2 -1
  70. package/types/thinking.d.ts +11 -0
  71. package/types/tty-colour.d.ts +33 -0
package/src/runner.js CHANGED
@@ -65,13 +65,17 @@ 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, readModelRecord, takeLearningsRecord } from './flowmodel.js';
78
+ import { readRunInputs, writeRunStart } from './runfile.js';
75
79
  import { fetchPageText, isWebUrl } from './pagefetch.js';
76
80
  import {
77
81
  readResumeLock, recordPid, writeLockHolder, procStartOf, LOCK_NO_HOLDER,
@@ -218,9 +222,9 @@ const holdOf = (ceilingUsd) => (Number.isFinite(ceilingUsd) && /** @type {number
218
222
  // WITHOUT the cap (M2 scope item 3, the load-bearing invariant).
219
223
  // ---------------------------------------------------------------------------
220
224
 
221
- const EXECUTOR_FIELDS = Object.freeze(['goal', 'primitives', 'reads', 'gap']);
225
+ const EXECUTOR_FIELDS = Object.freeze(['goal', 'primitives', 'reads', 'gap', 'hints']);
222
226
 
223
- /** @param {{goal:string, primitives?:string[], reads?:Record<string,any>, gap?:string|null}} opts */
227
+ /** @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
228
  export function buildExecutorContext(opts) {
225
229
  for (const key of Object.keys(opts ?? {})) {
226
230
  if (!EXECUTOR_FIELDS.includes(key)) {
@@ -228,13 +232,14 @@ export function buildExecutorContext(opts) {
228
232
  }
229
233
  }
230
234
  const {
231
- goal, primitives = [], reads = {}, gap = null,
235
+ goal, primitives = [], reads = {}, gap = null, hints = null,
232
236
  } = opts ?? {};
233
237
  return Object.freeze({
234
238
  goal,
235
239
  primitives: Object.freeze([...primitives]),
236
240
  reads: Object.freeze({ ...reads }),
237
241
  gap: gap ?? null,
242
+ hints: hints ?? null,
238
243
  });
239
244
  }
240
245
 
@@ -411,7 +416,7 @@ export async function freezePage(dir, id, url, { fetchPage = fetchPageText } = {
411
416
  }
412
417
 
413
418
  /** Copy each named source into `<runDir>/inputs/`, hash the FROZEN copy
414
- * (never the original again after this), write `inputs.json`. An
419
+ * (never the original again after this) and return the manifest, which `runFlow` records as the `inputs` of `run.json` (M8b). An
415
420
  * unreadable source refuses by name. A source that is a web address
416
421
  * (M10 item 1) is fetched and frozen by `freezePage`, in the same manifest.
417
422
  * @param {string} runDir @param {Array<{id: string, path: string}>} sources
@@ -448,7 +453,6 @@ export async function freezeInputs(runDir, sources, { fetchPage, tableRoles = []
448
453
  }
449
454
  manifest.push(entry);
450
455
  }
451
- writeFileSync(join(runDir, 'inputs.json'), JSON.stringify(manifest, null, 2));
452
456
  return { ok: true, manifest };
453
457
  }
454
458
 
@@ -638,11 +642,9 @@ const citedRolesOf = (step) => (step?.close?.class === 'green' && typeof step.cl
638
642
  /** A frozen CSV input as `{kind:'cells', header, rows}` (the shape `addressCells` gives), checked against the sha256 recorded at freeze.
639
643
  * Same three outcomes as `readArtifactResult`: not an input of this run (`missing`), refused (`red`), or the cells. */
640
644
  function readInputCells(runDir, id) {
641
- const manifest = readFileInside(runDir, 'inputs.json');
642
- if (!manifest.ok) return manifest.missing ? { ok: false, missing: true } : { ok: false, missing: false, red: manifest.red };
643
- let entries;
644
- try { entries = JSON.parse(manifest.text); } catch (err) { return { ok: false, missing: false, red: `inputs.json is not valid JSON — ${err.message}` }; }
645
- const entry = Array.isArray(entries) ? entries.find((e) => e?.id === id) : undefined;
645
+ const manifest = readRunInputs(runDir);
646
+ if (!manifest.ok) return manifest.code === 'missing' ? { ok: false, missing: true } : { ok: false, missing: false, red: manifest.red };
647
+ const entry = manifest.entries.find((e) => e?.id === id);
646
648
  if (!entry || !isCellsPath(entry.frozen)) return { ok: false, missing: true };
647
649
  const file = readFileInside(runDir, `inputs/${basename(entry.frozen)}`);
648
650
  if (!file.ok) return file.missing ? { ok: false, missing: false, red: 'the frozen copy is missing' } : { ok: false, missing: false, red: file.red };
@@ -681,6 +683,59 @@ function recordLateAnswerIfAny(runDir, now = () => new Date().toISOString()) {
681
683
  });
682
684
  }
683
685
 
686
+ // ---------------------------------------------------------------------------
687
+ // 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
688
+ // exit, from the three callers of `foldFromStep` (runFlow, resumeRun, continueRun), the expired-ask exit and the rerun exit. A record,
689
+ // never a verdict: it can never change a run's outcome, result, spend or books. It runs whether `learningHints` is on or off.
690
+ // - 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
691
+ // were accepted. No hold, no release (bareloop's ruling for both repos, 2026-10-24).
692
+ // - 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
693
+ // 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).
694
+ // - Noise runs (provider red, a crashed check) make no note: buildCards reads them off the escalation events eventsOfRun builds.
695
+ // Under a test process with no FWDLOOP_CONFIG_HOME nothing is written (`configDoorHome`), as for every config read.
696
+ // borrowed-from: bareloop src/userrun.js@v0.46.0:2035 (the call site, in its own try/catch)
697
+ // ---------------------------------------------------------------------------
698
+
699
+ /** 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 */
700
+ export const LEARN_ERROR_FILE = 'learn-error.jsonl';
701
+
702
+ /**
703
+ * @param {{flowName: string, runId: string, runDir: string, outcome: string, specHash: string|null, now: () => string}} o
704
+ */
705
+ function recordRunNotes({
706
+ flowName, runId, runDir, outcome, specHash, now,
707
+ }) {
708
+ if (NOT_A_RUN_END.has(outcome)) return;
709
+ const door = configDoorHome();
710
+ if (door.skip) return;
711
+ try {
712
+ const r = learnAtRunEnd({
713
+ home: door.home, workflow: flowName, runId, runDir, specHash, now: new Date(now()),
714
+ });
715
+ if (r.problem) throw new Error(r.problem);
716
+ } catch (/** @type {any} */ e) {
717
+ try {
718
+ appendRow(join(runDir, LEARN_ERROR_FILE), { at: now(), error: redactSecrets(String(e?.message ?? e)).split('\n')[0] });
719
+ } catch { /* the record of the failure is itself best-effort */ }
720
+ }
721
+ }
722
+
723
+ /**
724
+ * 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
725
+ * 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).
726
+ * 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
727
+ * hands nothing and records why as `hintsError` on the try's audit row, never a failed step).
728
+ * @param {{flowName: string, source: string|null, now: () => string}} o
729
+ * @returns {() => {text: string, ids: string[]}|null}
730
+ */
731
+ function stepHintsReader({ flowName, source, now }) {
732
+ return () => {
733
+ const door = configDoorHome();
734
+ if (door.skip) return null;
735
+ return hintsForRun({ home: door.home, spec: placeSpecOf(flowName, source), specHash: null, now: new Date(now()) });
736
+ };
737
+ }
738
+
684
739
  // ---------------------------------------------------------------------------
685
740
  // The ralph loop with strikes (M2 scope item 5) for ONE step.
686
741
  // ---------------------------------------------------------------------------
@@ -722,6 +777,10 @@ function sumKnownUsd(...values) {
722
777
  function makeAuditRow({
723
778
  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
779
  thinking = /** @type {{asked:string, status:string|null}|undefined} */ (undefined),
780
+ hints = /** @type {number|undefined} */ (undefined),
781
+ hintsText = /** @type {string|undefined} */ (undefined),
782
+ hintIds = /** @type {string[]|undefined} */ (undefined),
783
+ hintsError = /** @type {string|undefined} */ (undefined),
725
784
  }) {
726
785
  const row = {
727
786
  step: step?.emits ?? step?.goal ?? null,
@@ -743,6 +802,10 @@ function makeAuditRow({
743
802
  if (ungranted !== undefined && ungranted.length > 0) row.ungranted = ungranted;
744
803
  // 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
804
  if (thinking !== undefined) row.thinking = thinking;
805
+ // 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
806
+ // (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.
807
+ if (hints !== undefined) { row.hints = hints; row.hintsText = hintsText; row.hintIds = hintIds; }
808
+ if (hintsError !== undefined) row.hintsError = hintsError;
746
809
  return row;
747
810
  }
748
811
 
@@ -765,6 +828,7 @@ function makeAuditRow({
765
828
  * @param {(row: any, modelOutput?: any) => void} opts.recordAudit
766
829
  * @param {string|null} [opts.initialGap]
767
830
  * @param {number} [opts.attemptOffset]
831
+ * @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
832
  * @param {boolean} [opts.thinkingBox] - M4d am25: the job's "Thinking on" box as this run's copy keeps it (default off)
769
833
  * @param {() => string} [opts.now] - M4a-2: stamps each audit row's `at`;
770
834
  * defaults to the real wall clock.
@@ -779,6 +843,7 @@ export async function runStepRalph({
779
843
  step, primitivesMap, readsMap, businessDate, modelStep, spent, capUsd, ceilingUsd, recordAudit, initialGap = null, attemptOffset = 0,
780
844
  // 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
845
  thinkingBox = false,
846
+ learnHints = null,
782
847
  // M4a-2: the run's own injected clock (never the bare wall clock) —
783
848
  // stamps every audit row's `at` with this attempt's finish time. Defaults
784
849
  // to the real wall clock so a caller that doesn't inject one (there are
@@ -790,7 +855,7 @@ export async function runStepRalph({
790
855
  // cut this step short of (their numbering is in `attemptOffset`; a try the Stop cut mid-way is replaced by the new one, never counted
791
856
  // against the limit, so Resume always gets at least one new try).
792
857
  readStop = null, stepNo = 0, triesDone = 0,
793
- // M4d am29 item 2: the run's folder, where each try saves its checks (`checks.jsonl`, src/diary.js)
858
+ // M4d am29 item 2: the run's folder, where each try saves its checks (`diary.jsonl`, kind checks, src/diary.js)
794
859
  runDir = null,
795
860
  // the id of step stepNo-1 (null for step 1): a Stop before this step's first call words itself "after step N-1" and is filed under that step
796
861
  prevStepId = null,
@@ -835,8 +900,29 @@ export async function runStepRalph({
835
900
  }
836
901
 
837
902
  const grantedTools = Object.fromEntries((step.primitives ?? []).map((verb) => [verb, primitivesMap?.[verb]]));
903
+ // 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
904
+ // 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
905
+ // try's row does); any failure hands nothing and rides the row as `hintsError`.
906
+ /** @type {{text: string, ids: string[]}|null} */
907
+ let handed = null;
908
+ /** @type {string|undefined} */
909
+ let handedError;
910
+ if (learnHints !== null && stepHintsWanted({ attempt, rerunReason: n === 1 ? initialGap : null })) {
911
+ try {
912
+ handed = learnHints();
913
+ } catch (/** @type {any} */ e) {
914
+ handed = null;
915
+ handedError = redactSecrets(String(e?.message ?? e)).split('\n')[0];
916
+ }
917
+ }
918
+ // every row this try writes from here on carries how many hints it was handed, which, and what (none handed = no field)
919
+ const rowOf = (/** @type {any} */ a) => makeAuditRow({
920
+ ...a,
921
+ ...(handed !== null ? { hints: handed.ids.length, hintsText: handed.text, hintIds: handed.ids } : {}),
922
+ ...(handedError !== undefined ? { hintsError: handedError } : {}),
923
+ });
838
924
  const executorContext = buildExecutorContext({
839
- goal: step.goal, primitives: step.primitives ?? [], reads: readsMap, gap,
925
+ goal: step.goal, primitives: step.primitives ?? [], reads: readsMap, gap, hints: handed === null ? null : handed.text,
840
926
  });
841
927
 
842
928
  // `stepMeta` is a SEPARATE argument from `executorContext` — never a
@@ -892,7 +978,7 @@ export async function runStepRalph({
892
978
  if (typeof result.costUsd === 'number') spent.value += result.costUsd;
893
979
  const usd = sumKnownUsd(attemptFloorUsd, result.costUsd);
894
980
  const ranCalls = (turns ?? 0) > 0 || attemptFloorUsd !== null;
895
- return stopped(stopWords(ranCalls ? attempt : attempt - 1, turns ?? 0), makeAuditRow({
981
+ return stopped(stopWords(ranCalls ? attempt : attempt - 1, turns ?? 0), rowOf({
896
982
  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
983
  }));
898
984
  }
@@ -903,7 +989,7 @@ export async function runStepRalph({
903
989
  // already added to `spent.value` above (never double-added here); a
904
990
  // null second cost never zeroes out a known first floor.
905
991
  const usd = sumKnownUsd(attemptFloorUsd, result.costUsd);
906
- recordAudit(makeAuditRow({
992
+ recordAudit(rowOf({
907
993
  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
994
  }), result.red ?? 'transport fault twice');
909
995
  return { ok: false, outcome: 'provider-red', red: `provider-red: step "${step.goal}" attempt ${attempt}: ${result.red ?? 'transport fault twice'}` };
@@ -923,7 +1009,7 @@ export async function runStepRalph({
923
1009
  seenGaps.add(normalised);
924
1010
  if (strike) strikes += 1;
925
1011
  const usd = sumKnownUsd(attemptFloorUsd, result?.costUsd);
926
- recordAudit(makeAuditRow({
1012
+ recordAudit(rowOf({
927
1013
  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
1014
  }), red);
929
1015
  if (n === maxN) return { ok: false, outcome: 'attempt-fallback', red: `attempt-fallback: step "${step.goal}" — ${red}` };
@@ -934,7 +1020,7 @@ export async function runStepRalph({
934
1020
  }
935
1021
 
936
1022
  if (result.costUsd === null || result.costUsd === undefined) {
937
- recordAudit(makeAuditRow({
1023
+ recordAudit(rowOf({
938
1024
  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
1025
  }), result.artifact ?? null);
940
1026
  return { ok: false, outcome: 'pricing-red', red: `pricing-red: step "${step.goal}" attempt ${attempt} returned no cost (never "?? 0")` };
@@ -961,7 +1047,7 @@ export async function runStepRalph({
961
1047
  tryChecks.push(doneRecord(doneCheck, result.artifact));
962
1048
  if (doneCheck.verdict === 'not-done') {
963
1049
  saveTry();
964
- recordAudit(makeAuditRow({
1050
+ recordAudit(rowOf({
965
1051
  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
1052
  }), result.artifact ?? null);
967
1053
  return { ok: false, outcome: 'not-done', red: doneCheck.red };
@@ -977,7 +1063,7 @@ export async function runStepRalph({
977
1063
  // (never gated by novelty — an empty artifact is always the same
978
1064
  // failure) — matches poc/m2/gapback.mjs's own rule exactly.
979
1065
  strikes += 1;
980
- recordAudit(makeAuditRow({
1066
+ recordAudit(rowOf({
981
1067
  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
1068
  }), result.artifact ?? null);
983
1069
  if (n === maxN) return { ok: false, outcome: 'attempt-fallback', red: `attempt-fallback: ${happened.red}` };
@@ -1006,7 +1092,7 @@ export async function runStepRalph({
1006
1092
  saveTry();
1007
1093
 
1008
1094
  if (closed.verdict === 'green' || closed.verdict === 'hitl') {
1009
- recordAudit(makeAuditRow({
1095
+ recordAudit(rowOf({
1010
1096
  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
1097
  }), result.artifact);
1012
1098
  return {
@@ -1017,7 +1103,7 @@ export async function runStepRalph({
1017
1103
  if (closed.verdict !== 'red') {
1018
1104
  // A closer that renders no judgment ('unparseable'/'crash') is a
1019
1105
  // CASUALTY, never a red and never a strike (bareloop F17).
1020
- recordAudit(makeAuditRow({
1106
+ recordAudit(rowOf({
1021
1107
  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
1108
  }), result.artifact);
1023
1109
  return { ok: false, outcome: 'close-casualty', red: `close-casualty: step "${step.goal}" — ${closed.red} (${closed.verdict})` };
@@ -1027,7 +1113,7 @@ export async function runStepRalph({
1027
1113
  const strike = seenGaps.has(normalised);
1028
1114
  seenGaps.add(normalised);
1029
1115
  if (strike) strikes += 1;
1030
- recordAudit(makeAuditRow({
1116
+ recordAudit(rowOf({
1031
1117
  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
1118
  }), result.artifact);
1033
1119
 
@@ -1058,7 +1144,7 @@ export async function runStepRalph({
1058
1144
  * @param {() => string} [opts.clock] - returns the current ISO timestamp; defaults to the wall clock.
1059
1145
  * @param {string} opts.businessDate - the run's explicit "as of today", never the wall clock.
1060
1146
  * @param {number} [opts.ceilingUsd] - per-attempt ceiling override; the model's hold from Settings prices (`ceilingCostUsd`); absent = no hold.
1061
- * @param {{slot: string, model: string}} [opts.runModel] - M4d am33: the model this run started on; recorded once in the run folder (run-model.json) and kept by every resume/continue.
1147
+ * @param {{slot: string, model: string}} [opts.runModel] - M4d am33: the model this run started on; recorded once in the run folder (run.json) and kept by every resume/continue.
1062
1148
  * @param {string|null} [opts.initialGap] - M3 scope item 7 (rerun as a fresh
1063
1149
  * run): a human's rerun reason, carried as the FIRST ordinary step's
1064
1150
  * starting gap. Never used by a plain `runFlow` call outside `resumeRun`'s
@@ -1176,9 +1262,14 @@ export async function runFlow({
1176
1262
  });
1177
1263
  }
1178
1264
 
1179
- // 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
- writeRunThinking(flowDir, runDir);
1181
- if (runModel) writeRunModel(runDir, runModel); // M4d am33: the one record of the model this run started on
1265
+ // 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
1266
+ const thinkingBox = readModelRecord(flowDir)?.thinking === true;
1267
+ // 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
1268
+ if (!runOwnsPlan(runDir)) {
1269
+ try { takeLearningsRecord(flowDir, runDir); } catch (/** @type {any} */ e) {
1270
+ try { appendRow(join(runDir, LEARN_ERROR_FILE), { at: now(), error: redactSecrets(`learnings record: ${e?.message ?? e}`).split('\n')[0] }); } catch { /* best-effort */ }
1271
+ }
1272
+ }
1182
1273
 
1183
1274
  const frozen = await freezeInputs(runDir, sources ?? [], { fetchPage, tableRoles: sheetRolesOf(declaration.steps) });
1184
1275
  if (!frozen.ok) {
@@ -1186,6 +1277,8 @@ export async function runFlow({
1186
1277
  flowDir, runDir, runId, capUsd, startedAt, now, nowMs: getNowMs, signatureHash: signature.flow, outcome: 'preflight-red', red: frozen.red, spent: { value: 0 },
1187
1278
  });
1188
1279
  }
1280
+ // 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
1281
+ writeRunStart(runDir, { model: runModel ?? null, thinking: thinkingBox, inputs: /** @type {any[]} */ (frozen.manifest) });
1189
1282
  // M4c: every guard above has passed — this process records itself (pid row) before its first step.
1190
1283
  recordPid(runDir, 'run', now());
1191
1284
 
@@ -1281,6 +1374,9 @@ export async function runFlow({
1281
1374
  attemptsLog,
1282
1375
  firstStepGap: initialGap ?? null,
1283
1376
  });
1377
+ recordRunNotes({
1378
+ flowName: name, runId, runDir, outcome: result.outcome, specHash: signature.flow, now,
1379
+ });
1284
1380
 
1285
1381
  if (result.outcome === 'complete') return { ...result, auditRows };
1286
1382
  return result;
@@ -1544,7 +1640,7 @@ async function runAskSlot({
1544
1640
  }
1545
1641
  // eslint-disable-next-line no-await-in-loop
1546
1642
  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,
1643
+ 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
1644
  readStop: () => stopPending(runDir), stepNo: priorStepNo, prevStepId: priorPrevStepId,
1549
1645
  });
1550
1646
  if (!redoResult.ok) {
@@ -1799,7 +1895,7 @@ async function foldFromStep({
1799
1895
  // redo's `initialGap` above.
1800
1896
  // eslint-disable-next-line no-await-in-loop
1801
1897
  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,
1898
+ 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
1899
  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
1900
  });
1805
1901
  if (!stepResult.ok) {
@@ -1975,7 +2071,7 @@ function sameRoot(recorded, requested) {
1975
2071
  * @param {() => string} [opts.clock]
1976
2072
  * @param {string} opts.businessDate
1977
2073
  * @param {number} [opts.ceilingUsd]
1978
- * @param {{slot: string, model: string}} [opts.runModel] - M4d am33: the model this run started on; recorded once in the run folder (run-model.json) and kept by every resume/continue.
2074
+ * @param {{slot: string, model: string}} [opts.runModel] - M4d am33: the model this run started on; recorded once in the run folder (run.json) and kept by every resume/continue.
1979
2075
  * @param {() => number} [opts.nowMs] - F45 finding 3; see `runFlow`'s own.
1980
2076
  * @param {(newRunDir:string) => void} [opts.onRerunStart] - amendment 16 C2: called with the new run's folder just before a `rerun` starts it.
1981
2077
  */
@@ -2256,6 +2352,9 @@ export async function resumeRun({
2256
2352
  appendHistory(flowDir, {
2257
2353
  runId, at: now(), outcome: 'ask-expired', spentUsd: spent.value, spendComplete: spendComplete.value, capUsd: arbiter.capUsd ?? null, wallMs: getNowMs() - runStartedAt, signatureHash: state.signatureHash,
2258
2354
  });
2355
+ recordRunNotes({
2356
+ flowName: name, runId, runDir, outcome: 'ask-expired', specHash: state.signatureHash, now,
2357
+ });
2259
2358
  return { outcome: 'ask-expired', runDir, spentUsd: spent.value };
2260
2359
  }
2261
2360
 
@@ -2282,13 +2381,17 @@ export async function resumeRun({
2282
2381
  }
2283
2382
  try {
2284
2383
  recordLateAnswerIfAny(runDir, now);
2285
- writeLog(runDir, { runId, outcome: 'rerun', attempts: [], artifacts: priorArtifactsForLog });
2384
+ writeLog(runDir, { runId, outcome: 'rerun', attempts: Array.isArray(readLog(runDir)?.attempts) ? readLog(runDir).attempts : [], artifacts: priorArtifactsForLog }); // F83: keep the earlier legs' tries
2286
2385
  } finally {
2287
2386
  // Amendment 16 C6/C7: the history end row is written last, and always.
2288
2387
  appendHistory(flowDir, {
2289
2388
  runId, at: now(), outcome: 'rerun', spentUsd: spent.value, spendComplete: spendComplete.value, capUsd: arbiter.capUsd ?? null, wallMs: getNowMs() - runStartedAt, signatureHash: state.signatureHash,
2290
2389
  });
2291
2390
  }
2391
+ // M8 am4: a rerun ends THIS run, so its notes count now (the new run, started below, makes its own).
2392
+ recordRunNotes({
2393
+ flowName: name, runId, runDir, outcome: 'rerun', specHash: state.signatureHash, now,
2394
+ });
2292
2395
 
2293
2396
  // Deterministic derived id (M3 scope item 7) — refused by name, never
2294
2397
  // silently renumbered, if it already exists.
@@ -2360,7 +2463,8 @@ export async function resumeRun({
2360
2463
  }
2361
2464
  }
2362
2465
 
2363
- const attemptsLog = [];
2466
+ // F83: log.json has one writer and it replaces the file, so this leg starts from the tries the earlier legs wrote (the pause's write)
2467
+ const attemptsLog = Array.isArray(readLog(runDir)?.attempts) ? [...readLog(runDir).attempts] : [];
2364
2468
  const auditRows = [];
2365
2469
  const recordAudit = (row, modelOutput, unjudgedCount) => {
2366
2470
  const fullRow = unjudgedCount === undefined ? row : { ...row, unjudgedCount };
@@ -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;
@@ -2619,7 +2726,8 @@ export async function continueRun({
2619
2726
  acceptedAskEmitsThisRun.set(emits, recordedHashes.byEmits.get(emits) ?? null);
2620
2727
  }
2621
2728
  }
2622
- const attemptsLog = [];
2729
+ // F83: log.json has one writer and it replaces the file, so this leg starts from the tries the earlier legs wrote (the pause's write)
2730
+ const attemptsLog = Array.isArray(readLog(runDir)?.attempts) ? [...readLog(runDir).attempts] : [];
2623
2731
  const auditRows = [];
2624
2732
  const recordAudit = (row, modelOutput, unjudgedCount) => {
2625
2733
  const fullRow = unjudgedCount === undefined ? row : { ...row, unjudgedCount };
@@ -2681,6 +2789,9 @@ export async function continueRun({
2681
2789
  recordAudit,
2682
2790
  attemptsLog,
2683
2791
  });
2792
+ recordRunNotes({
2793
+ flowName: name, runId, runDir, outcome: result.outcome, specHash: halt.signatureHash, now,
2794
+ });
2684
2795
  if (result.outcome === 'complete') return { ...result, auditRows };
2685
2796
  return result;
2686
2797
  } finally {
@@ -1,13 +1,8 @@
1
- // M10b piece 2: the ONE writer of `<run>/sheet-checks.json`, the record of what each sheet check said in this run, for the separate checker that re-runs a run's
1
+ // M10b piece 2 / M8b item 3: the writer of the `sheet` section of `<run>/line-checks.json` (the file's one writer is `writeLineSection`, src/line-checks.js), the record of what each sheet check said in this run, for the separate checker that re-runs a run's
2
2
  // signed checks against its saved sheet (M10b "Done when"). Append-only: one entry per (job line, try), written the moment that try's check has run, never replaced.
3
3
  // Shape: { lines: [ { n, try, passed, tables: [{name, tableSha}], checks: [the signed check objects], claims: <the step's answer>, results: [{id, text, ok, result}], red } ] }.
4
- // `tables[].tableSha` is the one recorded at the run's start (inputs.json), the one the check used. Throws away: nothing the check saw; no cell text is kept here.
5
- import { writeFileSync, renameSync } from 'node:fs';
6
- import { join } from 'node:path';
7
- import { readFileInside } from './flow.js';
8
-
9
- /** the record's name in the run's own folder */
10
- export const SHEET_CHECKS_FILE = 'sheet-checks.json';
4
+ // `tables[].tableSha` is the one recorded at the run's start (run.json), the one the check used. Throws away: nothing the check saw; no cell text is kept here.
5
+ import { readLineSection, writeLineSection } from './line-checks.js';
11
6
 
12
7
  const isRec = (/** @type {unknown} */ v) => v !== null && typeof v === 'object' && !Array.isArray(v);
13
8
 
@@ -18,28 +13,17 @@ const isRec = (/** @type {unknown} */ v) => v !== null && typeof v === 'object'
18
13
  export function writeSheetLine(runDir, { n, try: attempt, checks, closed }) {
19
14
  const rec = closed.sheetRecord;
20
15
  if (!rec) return;
21
- /** @type {any[]} */
22
- let lines = [];
23
- const had = readFileInside(runDir, SHEET_CHECKS_FILE);
24
- if (had.ok) {
25
- try {
26
- const parsed = JSON.parse(had.text);
27
- if (isRec(parsed) && Array.isArray(parsed.lines)) lines = parsed.lines;
28
- } catch { lines = []; }
29
- }
30
- if (lines.some((l) => isRec(l) && l.n === n && l.try === attempt)) return;
31
- lines.push({
32
- n, try: attempt, passed: closed.verdict === 'green',
33
- tables: rec.inputs.map((/** @type {any} */ i) => ({ name: i.name, tableSha: i.sha256 })),
34
- checks: JSON.parse(JSON.stringify(checks)),
35
- claims: rec.claims,
36
- results: rec.checks,
37
- red: closed.verdict === 'green' ? null : (closed.red ?? null),
16
+ writeLineSection(runDir, 'sheet', (had) => {
17
+ if (had.some((l) => isRec(l) && l.n === n && l.try === attempt)) return null;
18
+ return [...had, {
19
+ n, try: attempt, passed: closed.verdict === 'green',
20
+ tables: rec.inputs.map((/** @type {any} */ i) => ({ name: i.name, tableSha: i.sha256 })),
21
+ checks: JSON.parse(JSON.stringify(checks)),
22
+ claims: rec.claims,
23
+ results: rec.checks,
24
+ red: closed.verdict === 'green' ? null : (closed.red ?? null),
25
+ }];
38
26
  });
39
- const file = join(runDir, SHEET_CHECKS_FILE);
40
- const tmp = `${file}.tmp`;
41
- writeFileSync(tmp, `${JSON.stringify({ lines }, null, 2)}\n`);
42
- renameSync(tmp, file);
43
27
  }
44
28
 
45
29
  /**
@@ -48,10 +32,6 @@ export function writeSheetLine(runDir, { n, try: attempt, checks, closed }) {
48
32
  * @param {string} runDir @returns {{lines: any[]}|null}
49
33
  */
50
34
  export function readSheetChecks(runDir) {
51
- const got = readFileInside(runDir, SHEET_CHECKS_FILE);
52
- if (!got.ok) return null;
53
- try {
54
- const parsed = JSON.parse(got.text);
55
- return isRec(parsed) && Array.isArray(parsed.lines) ? { lines: parsed.lines } : null;
56
- } catch { return null; }
35
+ const got = readLineSection(runDir, 'sheet');
36
+ return got.ok ? { lines: got.lines } : null;
57
37
  }
package/src/sheetblock.js CHANGED
@@ -1,7 +1,7 @@
1
1
  // M10b piece 4 (docs/wiki/the-module-ladder.md "M10b amendment 2", items 4 and 7): the ONE builder of what a job line that reads a sheet shows -
2
2
  // { guardrails, checked: [{id, name, words, covers, text}], notChecked: [guardrail, ...] | 'none' }
3
3
  // from the signed declaration (the step's `close.sheet`, each check's `covers` tag) and the job line's own `~` rules. After a run, `record` (the
4
- // `sheet-checks.json` lines, src/sheet-record.js) adds to each check its verdict and what was found: `{ok, found}`. Every surface (the Chat plan card, the Job tab, the
4
+ // the `sheet` section of `line-checks.json`, lines, src/sheet-record.js) adds to each check its verdict and what was found: `{ok, found}`. Every surface (the Chat plan card, the Job tab, the
5
5
  // Result tab, the Audit's check rows) shows this block's strings; none of them words a check itself.
6
6
  // Throws away: the check's id, claim, range and the other typed fields that do not change what it says (src/sheetchecks.js `sheetCheckSentence` drops them too).
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
@@ -65,7 +65,7 @@ export const coversWords = (rules) => rules.map((r) => `covers "${r}"`).join('
65
65
  * The block of every job line whose step reads a sheet. A line qualifies when its green step carries `close.sheet`, or (with `csvRoles`) reads a CSV input and carries no
66
66
  * older `close.columns` / `close.cited` check (then every guardrail is Not checked).
67
67
  * @param {{declaration: any, lines: Array<{n: number, rules?: string[], guardrail?: string, rule?: string}>, csvRoles?: string[], record?: any}} o
68
- * `record` = the parsed `sheet-checks.json` (`{lines: [...]}`), only after a run
68
+ * `record` = the `sheet` section of `line-checks.json` (`{lines: [...]}`), only after a run
69
69
  * @returns {Array<{line: number, guardrails: string[], checked: Array<{id: string, name: string, words: string, covers: string[], coversWords: string, text: string, ok?: boolean, found?: string}>, notChecked: string[]|'none'}>}
70
70
  */
71
71
  export function sheetLineBlocks({ declaration, lines, csvRoles = [], record }) {
@@ -155,7 +155,7 @@ export function claimLines(claims) {
155
155
  }
156
156
 
157
157
  /**
158
- * M10b am4: what an ask card shows for the claim boxes it was given. The step is the sheet step whose saved try (`sheet-checks.json`) holds exactly these claims; its block is
158
+ * M10b am4: what an ask card shows for the claim boxes it was given. The step is the sheet step whose saved try (the `sheet` section of `line-checks.json`) holds exactly these claims; its block is
159
159
  * the Result tab's own (`sheetLineBlocks`, that try's verdicts), and `answer` is the claims value by value. Null when no saved try matches: the caller then keeps the old line.
160
160
  * @param {{claims: unknown, declaration: any, lines: Array<{n: number, rules?: string[], guardrail?: string, rule?: string}>, csvRoles?: string[], record?: any}} o
161
161
  * @returns {{block: ReturnType<typeof sheetLineBlocks>[number], answer: string[]}|null}
package/src/sheetrun.js CHANGED
@@ -1,6 +1,6 @@
1
1
  // M10b piece 2 (docs/wiki/the-module-ladder.md "M10b scope" items 5-6 and amendment 1): a sheet check at RUN time.
2
2
  // - the lock: at run start each CSV input a step's `close.sheet` names gets its `tableSha` (bareguard's fingerprint of the table made from the run's frozen copy)
3
- // written down once with that run's inputs (`freezeInputs` is the one writer of inputs.json and calls `tableShaOfFile`); here is how it is read back;
3
+ // written down once with that run's inputs (`freezeInputs` makes the manifest, `runFlow` records it in run.json, and it calls `tableShaOfFile`); here is how it is read back;
4
4
  // - the judge: `closeSheet` hands the signed checks, the step's typed answer and the run's table to bareguard's `checkStep`. No model grades.
5
5
  // Third outcomes, each named, never green: a sheet the run recorded no fingerprint for, a frozen copy that is missing, a table that no longer gives the recorded
6
6
  // `tableSha` (bareguard stops the check; the red names the input), any other stopped check.
@@ -9,6 +9,7 @@ import { basename } from 'node:path';
9
9
  import { createRubric, checkStep, renderGaps, tableSha } from 'bareguard';
10
10
  import { parseCsv, sheetTable } from './csv.js';
11
11
  import { readFileInside } from './flow.js';
12
+ import { readRunInputs } from './runfile.js';
12
13
  import { sheetCheckSentence, bareguardChecks } from './sheetchecks.js';
13
14
  import { sheetCheckName, sheetFoundWords } from './sheetblock.js';
14
15
 
@@ -37,16 +38,15 @@ export function tableShaOfFrozen(runDir, name) {
37
38
  const SHA_RE = /^[0-9a-f]{64}$/;
38
39
 
39
40
  /**
40
- * What a sheet check reads in a run: the run's OWN frozen copy of each sheet its checks name, as bareguard's table, and the `tableSha` recorded in `inputs.json` at
41
+ * What a sheet check reads in a run: the run's OWN frozen copy of each sheet its checks name, as bareguard's table, and the `tableSha` recorded in `run.json` (inputs) at
41
42
  * the run's start. The table is NOT compared here: bareguard compares it to the recorded sha when it checks (and stops if it differs).
42
43
  * @param {string} runDir @param {any[]} checks the step's `close.sheet`
43
44
  * @returns {{ok: true, tables: Record<string, {header: string[], rows: any[]}>, inputs: Array<{name: string, sha256: string}>}|{ok: false, red: string}}
44
45
  */
45
46
  export function readRunSheets(runDir, checks) {
46
- const manifest = readFileInside(runDir, 'inputs.json');
47
- if (!manifest.ok) return { ok: false, red: manifest.missing ? 'this run has no frozen inputs' : `inputs.json: ${manifest.red}` };
48
- let entries;
49
- try { entries = JSON.parse(manifest.text); } catch (err) { return { ok: false, red: `inputs.json is not valid JSON - ${/** @type {any} */ (err).message}` }; }
47
+ const manifest = readRunInputs(runDir);
48
+ if (!manifest.ok) return { ok: false, red: manifest.code === 'missing' ? 'this run has no frozen inputs' : manifest.red };
49
+ const { entries } = manifest;
50
50
  /** @type {Record<string, any>} */
51
51
  const tables = {};
52
52
  const inputs = [];
@@ -110,11 +110,19 @@ const stoppedAt = (line, rest) => (line === null ? `Stopped: ${rest}` : `Stopped
110
110
 
111
111
  const RERUN_NEXT = 'Run it again from the Chat card.';
112
112
 
113
+ /**
114
+ * M9 am24: a NEXT with more than one instruction is `rows` of [label, instruction], one per line (label muted, instruction in a second column).
115
+ * `next` stays the one string every other reader gets: the rows joined "label instruction", one per line. The only writer of both.
116
+ * @param {Array<[string, string]>} rows
117
+ * @returns {{next: string, rows: Array<[string, string]>}}
118
+ */
119
+ const splitNext = (rows) => ({ next: rows.map(([l, t]) => `${l} ${t}`).join('\n'), rows });
120
+
113
121
  /**
114
122
  * ENDED / NEXT of a finished run. Every outcome the history row can hold has a fixed sentence; an unknown one gets an honest fixed fallback
115
123
  * that names the code and guesses nothing. `null` when there is no ending (still running, waiting, or no history row and not died).
116
124
  * @param {{outcome: string|null, died?: boolean, line: number|null, destination: string|null, canResume: boolean, home?: string}} f
117
- * @returns {{reason: string, next: string}|null}
125
+ * @returns {{reason: string, next: string, rows?: Array<[string, string]>}|null}
118
126
  */
119
127
  export function endedWords(f) {
120
128
  const {
@@ -129,12 +137,12 @@ export function endedWords(f) {
129
137
  case 'stopped':
130
138
  return { reason: 'Stopped by you.', next: resumeOrAgain };
131
139
  case 'cap-halt':
132
- return { reason: stoppedAt(line, 'the next try could not fit under the money cap.'), next: canResume ? 'Raise the cap and Resume from the Chat card.' : RERUN_NEXT };
140
+ return { reason: stoppedAt(line, 'the next try could not fit under the money cap.'), ...(canResume ? splitNext([['raise the cap:', 'Cap $ on the Chat card'], ['then:', 'Resume from the Chat card']]) : { next: RERUN_NEXT }) };
133
141
  case 'redo-halt':
134
142
  return { reason: stoppedAt(line, 'you rejected it.'), next: RERUN_NEXT };
135
143
  case 'ask-expired':
136
144
  case 'ask-timeout':
137
- return { reason: stoppedAt(line, 'nobody answered in time.'), next: 'Reopen it from the Ask tab, or run it again from the Chat card.' };
145
+ return { reason: stoppedAt(line, 'nobody answered in time.'), ...splitNext([['reopen it:', 'from the Ask tab'], ['or run it again:', 'from the Chat card']]) };
138
146
  case 'not-done':
139
147
  return { reason: stoppedAt(line, 'the step said it did not finish.'), next: RERUN_NEXT };
140
148
  case 'struck-out':
@@ -152,9 +160,9 @@ export function endedWords(f) {
152
160
  case 'rerun':
153
161
  return { reason: 'You ended this run on purpose; a fresh run was started.', next: 'Look at the newest run of this job.' };
154
162
  case 'preflight-red':
155
- return { reason: 'It did not start: the job could not pass its pre-run checks. Nothing was spent.', next: 'Fix what the Audit / logs tab names, then run it again from the Chat card.' };
163
+ return { reason: 'It did not start: the job could not pass its pre-run checks. Nothing was spent.', ...splitNext([['fix it:', 'what the Audit / logs tab names'], ['then:', 'run it again from the Chat card']]) };
156
164
  case 'refused':
157
- return { reason: 'It did not start: the run was refused. Nothing was spent.', next: 'The Audit / logs tab says why. Fix that, then run it again from the Chat card.' };
165
+ return { reason: 'It did not start: the run was refused. Nothing was spent.', ...splitNext([['see why:', 'the Audit / logs tab'], ['then:', 'fix that and run it again from the Chat card']]) };
158
166
  default: {
159
167
  // an unknown code: say so, name the code (from the books, capped), guess nothing
160
168
  const code = String(outcome).replace(/[^\w-]/g, '').slice(0, 40);
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
+ }