fwdloop 0.20.0 → 0.21.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
@@ -62,6 +62,12 @@ import {
62
62
  appendAudit, appendHistory, readAudit, readHistory, endRow, HALT_OUTCOMES,
63
63
  } from './books.js';
64
64
  import { applyRunValues, pickRunValues } from './runvalues.js';
65
+ import { stepThinkingMode } from './thinking.js';
66
+ import { appendChecks, nextRound } from './diary.js';
67
+ import {
68
+ doneRecord, happenedRecord, outputRecord, closeRecords,
69
+ } from './try-checks.js';
70
+ import { readJobThinking, writeRunThinking } from './flowmodel.js';
65
71
  import {
66
72
  readResumeLock, recordPid, writeLockHolder, procStartOf, LOCK_NO_HOLDER,
67
73
  } from './liveness.js';
@@ -667,6 +673,7 @@ function sumKnownUsd(...values) {
667
673
  // unchanged.
668
674
  function makeAuditRow({
669
675
  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}>} */ ([]),
676
+ thinking = /** @type {{asked:string, status:string|null}|undefined} */ (undefined),
670
677
  }) {
671
678
  const row = {
672
679
  step: step?.emits ?? step?.goal ?? null,
@@ -686,6 +693,8 @@ function makeAuditRow({
686
693
  refused,
687
694
  };
688
695
  if (ungranted !== undefined && ungranted.length > 0) row.ungranted = ungranted;
696
+ // 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.
697
+ if (thinking !== undefined) row.thinking = thinking;
689
698
  return row;
690
699
  }
691
700
 
@@ -708,16 +717,20 @@ function makeAuditRow({
708
717
  * @param {(row: any, modelOutput?: any) => void} opts.recordAudit
709
718
  * @param {string|null} [opts.initialGap]
710
719
  * @param {number} [opts.attemptOffset]
720
+ * @param {boolean} [opts.thinkingBox] - M4d am25: the job's "Thinking on" box as this run's copy keeps it (default off)
711
721
  * @param {() => string} [opts.now] - M4a-2: stamps each audit row's `at`;
712
722
  * defaults to the real wall clock.
713
723
  * @param {(() => boolean)|null} [opts.readStop] - amendment 7 item 8: the run's stop reader, asked before every try and (via modelStep's seam) every model call
714
724
  * @param {number} [opts.stepNo] - this step's 1-based number, for the words of a stop row
715
725
  * @param {string|null} [opts.prevStepId] - the id of step stepNo-1 (null for step 1): the step a "stopped after step N-1" row is filed under
716
726
  * @param {number} [opts.triesDone] - tries a Stop already closed on this step (they count against its limit)
727
+ * @param {string|null} [opts.runDir] - M4d am29 item 2: the run's folder, where each try saves its checks
717
728
  * @returns {Promise<{ok:true, artifact:any, attempts:number, hitl?:boolean} | {ok:false, outcome:string, red:string, stop?:{where:string, book:Record<string, any>, step?:string|null}}>}
718
729
  */
719
730
  async function runStepRalph({
720
731
  step, primitivesMap, readsMap, businessDate, modelStep, spent, capUsd, ceilingUsd, recordAudit, initialGap = null, attemptOffset = 0,
732
+ // 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`.
733
+ thinkingBox = false,
721
734
  // M4a-2: the run's own injected clock (never the bare wall clock) —
722
735
  // stamps every audit row's `at` with this attempt's finish time. Defaults
723
736
  // to the real wall clock so a caller that doesn't inject one (there are
@@ -729,6 +742,8 @@ async function runStepRalph({
729
742
  // 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
730
743
  // against the limit, so Resume always gets at least one new try).
731
744
  readStop = null, stepNo = 0, triesDone = 0,
745
+ // M4d am29 item 2: the run's folder, where each try saves its checks (`checks.jsonl`, src/diary.js)
746
+ runDir = null,
732
747
  // 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
733
748
  prevStepId = null,
734
749
  }) {
@@ -782,7 +797,8 @@ async function runStepRalph({
782
797
  // schema without the executor context ever needing to carry one (M2
783
798
  // scope item 3's own invariant: the schema is class-only, and the
784
799
  // construction test below proves the context itself stays clean).
785
- const stepMeta = Object.freeze({ class: step.close?.class ?? null });
800
+ // M4d am25: `thinkingMode` is the ONE decision of what this try asks of thinking (`stepThinkingMode`); the model step only passes it on.
801
+ const stepMeta = Object.freeze({ class: step.close?.class ?? null, attempt, step: step?.emits ?? step?.goal ?? null, thinkingMode: stepThinkingMode({ boxOn: thinkingBox, attempt }) });
786
802
 
787
803
  const stopSeam = readStop ? Object.freeze({ stopRequested: readStop }) : undefined;
788
804
 
@@ -827,7 +843,7 @@ async function runStepRalph({
827
843
  const usd = sumKnownUsd(attemptFloorUsd, result.costUsd);
828
844
  const ranCalls = (turns ?? 0) > 0 || attemptFloorUsd !== null;
829
845
  return stopped(stopWords(ranCalls ? attempt : attempt - 1, turns ?? 0), makeAuditRow({
830
- 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,
846
+ 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,
831
847
  }));
832
848
  }
833
849
 
@@ -838,7 +854,7 @@ async function runStepRalph({
838
854
  // null second cost never zeroes out a known first floor.
839
855
  const usd = sumKnownUsd(attemptFloorUsd, result.costUsd);
840
856
  recordAudit(makeAuditRow({
841
- 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,
857
+ 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,
842
858
  }), result.red ?? 'transport fault twice');
843
859
  return { ok: false, outcome: 'provider-red', red: `provider-red: step "${step.goal}" attempt ${attempt}: ${result.red ?? 'transport fault twice'}` };
844
860
  }
@@ -855,7 +871,7 @@ async function runStepRalph({
855
871
  if (strike) strikes += 1;
856
872
  const usd = sumKnownUsd(attemptFloorUsd, result?.costUsd);
857
873
  recordAudit(makeAuditRow({
858
- 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,
874
+ 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,
859
875
  }), red);
860
876
  if (n === maxN) return { ok: false, outcome: 'attempt-fallback', red: `attempt-fallback: step "${step.goal}" — ${red}` };
861
877
  if (strikes >= STRIKE_LIMIT) return { ok: false, outcome: 'struck-out', red: `struck-out: step "${step.goal}" — ${red}` };
@@ -866,35 +882,50 @@ async function runStepRalph({
866
882
 
867
883
  if (result.costUsd === null || result.costUsd === undefined) {
868
884
  recordAudit(makeAuditRow({
869
- 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,
885
+ 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,
870
886
  }), result.artifact ?? null);
871
887
  return { ok: false, outcome: 'pricing-red', red: `pricing-red: step "${step.goal}" attempt ${attempt} returned no cost (never "?? 0")` };
872
888
  }
873
889
  spent.value += result.costUsd;
874
890
  const attemptUsd = sumKnownUsd(attemptFloorUsd, result.costUsd);
875
891
 
892
+ // M4d am29 item 2: this try's checks, in the order they run; `saveTry` writes them (and the output they judged) once, just before the try's audit row
893
+ const tryChecks = /** @type {any[]} */ ([]);
894
+ let judged = null;
895
+ const saveTry = () => {
896
+ if (runDir === null) return;
897
+ appendChecks(runDir, {
898
+ step: step?.emits ?? step?.goal ?? null, try: attempt, at: now(), lastRound: nextRound(runDir, step?.emits ?? step?.goal ?? null) - 1, checks: [...tryChecks].sort((a, b) => a.n - b.n), output: judged,
899
+ });
900
+ };
901
+
876
902
  // The model's own word, taken at face value — before the happened check,
877
903
  // before any close, no exception (M2 amendment 1 item 1). A halt, not a
878
904
  // strike, not a retry: `recordAudit`'s modelOutput arg keeps the RAW
879
905
  // `result.artifact` (done/blocker included) for log.json; everything
880
906
  // downstream of a `done: true` gets the STRIPPED artifact.
881
907
  const doneCheck = checkDoneBlocker(step, result.artifact);
908
+ tryChecks.push(doneRecord(doneCheck, result.artifact));
882
909
  if (doneCheck.verdict === 'not-done') {
910
+ saveTry();
883
911
  recordAudit(makeAuditRow({
884
- 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,
912
+ 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,
885
913
  }), result.artifact ?? null);
886
914
  return { ok: false, outcome: 'not-done', red: doneCheck.red };
887
915
  }
888
916
  const artifact = stripDoneBlocker(result.artifact);
889
917
 
890
918
  const happened = checkArtifactHappened(step, artifact);
919
+ tryChecks.push(happenedRecord(happened, artifact));
920
+ judged = outputRecord(step, artifact);
891
921
  if (happened.verdict === 'red') {
922
+ saveTry();
892
923
  // Item 5: "or wrote no artifact" strikes unconditionally, every time
893
924
  // (never gated by novelty — an empty artifact is always the same
894
925
  // failure) — matches poc/m2/gapback.mjs's own rule exactly.
895
926
  strikes += 1;
896
927
  recordAudit(makeAuditRow({
897
- 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,
928
+ 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,
898
929
  }), result.artifact ?? null);
899
930
  if (n === maxN) return { ok: false, outcome: 'attempt-fallback', red: `attempt-fallback: ${happened.red}` };
900
931
  if (strikes >= STRIKE_LIMIT) return { ok: false, outcome: 'struck-out', red: `struck-out: ${happened.red}` };
@@ -904,10 +935,12 @@ async function runStepRalph({
904
935
  }
905
936
 
906
937
  const closed = await closeByClass(step, artifact, { reads: readsMap, businessDate });
938
+ tryChecks.push(...closeRecords(step, artifact, closed));
939
+ saveTry();
907
940
 
908
941
  if (closed.verdict === 'green' || closed.verdict === 'hitl') {
909
942
  recordAudit(makeAuditRow({
910
- 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,
943
+ 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,
911
944
  }), result.artifact);
912
945
  return {
913
946
  ok: true, artifact, attempts: attempt, hitl: closed.verdict === 'hitl',
@@ -918,7 +951,7 @@ async function runStepRalph({
918
951
  // A closer that renders no judgment ('unparseable'/'crash') is a
919
952
  // CASUALTY, never a red and never a strike (bareloop F17).
920
953
  recordAudit(makeAuditRow({
921
- 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,
954
+ 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,
922
955
  }), result.artifact);
923
956
  return { ok: false, outcome: 'close-casualty', red: `close-casualty: step "${step.goal}" — ${closed.red} (${closed.verdict})` };
924
957
  }
@@ -928,7 +961,7 @@ async function runStepRalph({
928
961
  seenGaps.add(normalised);
929
962
  if (strike) strikes += 1;
930
963
  recordAudit(makeAuditRow({
931
- 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,
964
+ 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,
932
965
  }), result.artifact);
933
966
 
934
967
  if (n === maxN) return { ok: false, outcome: 'attempt-fallback', red: `attempt-fallback: step "${step.goal}" — ${closed.red}` };
@@ -1072,6 +1105,9 @@ export async function runFlow({
1072
1105
  });
1073
1106
  }
1074
1107
 
1108
+ // M4d am25: the run keeps the job's "Thinking on" box as it is now (read by `readJobThinking` on every try and every resume)
1109
+ writeRunThinking(flowDir, runDir);
1110
+
1075
1111
  const frozen = freezeInputs(runDir, sources ?? []);
1076
1112
  if (!frozen.ok) {
1077
1113
  return haltRun({
@@ -1423,7 +1459,7 @@ async function runAskSlot({
1423
1459
  }
1424
1460
  // eslint-disable-next-line no-await-in-loop
1425
1461
  const redoResult = await runStepRalph({
1426
- step: priorStep, primitivesMap: primitives, readsMap: priorReadsResult.map, businessDate, modelStep, spent, capUsd, ceilingUsd: effectiveCeilingUsd, recordAudit, initialGap: reason, attemptOffset: redone, now,
1462
+ step: priorStep, primitivesMap: primitives, readsMap: priorReadsResult.map, businessDate, modelStep, spent, capUsd, ceilingUsd: effectiveCeilingUsd, recordAudit, initialGap: reason, attemptOffset: redone, thinkingBox: readJobThinking(flowDir, runDir), now, runDir,
1427
1463
  readStop: () => stopPending(runDir), stepNo: priorStepNo, prevStepId: priorPrevStepId,
1428
1464
  });
1429
1465
  if (!redoResult.ok) {
@@ -1678,7 +1714,7 @@ async function foldFromStep({
1678
1714
  // redo's `initialGap` above.
1679
1715
  // eslint-disable-next-line no-await-in-loop
1680
1716
  const stepResult = await runStepRalph({
1681
- step, primitivesMap: primitives, readsMap, businessDate, modelStep, spent, capUsd, ceilingUsd: effectiveCeilingUsd, recordAudit, initialGap: i === i0 ? firstStepGap : null, now,
1717
+ step, primitivesMap: primitives, readsMap, businessDate, modelStep, spent, capUsd, ceilingUsd: effectiveCeilingUsd, recordAudit, initialGap: i === i0 ? firstStepGap : null, thinkingBox: readJobThinking(flowDir, runDir), now, runDir,
1682
1718
  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,
1683
1719
  });
1684
1720
  if (!stepResult.ok) {
package/src/thinking.js CHANGED
@@ -53,3 +53,42 @@ export function thinkingSay(status) {
53
53
  if (status === 'unknown') return 'thinking off (not confirmed)';
54
54
  return null;
55
55
  }
56
+
57
+ /**
58
+ * M4d am26 items 1-2: the words after a try line in the Audit, from that try's audit-row `thinking` {asked, status} (am25). bareagent confirmed it
59
+ * ('applied'): `thinking on` / `thinking off`. Any other status: `thinkingSay`'s words above, the same ones Chat uses. A row with no `thinking` (before am25,
60
+ * or no model call) has no words: nothing is guessed.
61
+ * M4d am27: a row with a `thinking` record but no status (the model sent no reply: an error, the time limit, a Stop before the first reply) reads
62
+ * `thinking <asked> (no reply)`, from what was ASKED; the words never say thinking happened. Nothing asked (asked null) has no words.
63
+ * @param {{asked?: unknown, status?: unknown}|null|undefined} thinking @returns {string|null}
64
+ */
65
+ export function thinkingTryWords(thinking) {
66
+ if (thinking === null || typeof thinking !== 'object') return null;
67
+ const status = typeof thinking.status === 'string' ? thinking.status : null;
68
+ if (status === null) return thinking.asked === 'on' || thinking.asked === 'off' ? `thinking ${thinking.asked} (no reply)` : null;
69
+ if (status === 'applied') return thinking.asked === 'on' || thinking.asked === 'off' ? `thinking ${thinking.asked}` : null;
70
+ return thinkingSay(status);
71
+ }
72
+
73
+ /**
74
+ * M4d am28 items 2-4 (replaces am26 item 3's words and the hidden row): the Job tab's Thinking value, from the run's own record
75
+ * (`boxOn` = the Chat "Thinking on" box as the run started). A run with no record (before am25) is `null` and reads `—`, never a guess from model.json.
76
+ * Words: bareloop's `thinkingJobText`.
77
+ * // borrowed-from: bareloop src/thinking.js@b79e7d9
78
+ * @param {boolean|null} boxOn
79
+ */
80
+ export function thinkingRuleWords(boxOn) {
81
+ if (boxOn === null) return '—';
82
+ return boxOn ? 'always on' : 'on retries';
83
+ }
84
+
85
+ /**
86
+ * M4d am25 item 1/2: the ONE owner of what thinking a step's model call asks for. Code decides, never the model.
87
+ * Box ticked (the job's Chat "Thinking on" box, kept with the job): every try 'on'. Box off: the 1st try 'off'; the 2nd and later tries 'on'.
88
+ * A step redone after a human Redo is numbered from its redo count (the runner's `attemptOffset`), so it is always a 2nd-or-later try and thinks 'on'.
89
+ * @param {{boxOn: boolean, attempt: number}} a the runner's 1-based attempt number for this step
90
+ * @returns {'on'|'off'}
91
+ */
92
+ export function stepThinkingMode({ boxOn, attempt }) {
93
+ return boxOn === true || (Number.isInteger(attempt) && attempt >= 2) ? 'on' : 'off';
94
+ }
@@ -0,0 +1,62 @@
1
+ // M4d am29 item 2: what one try saves about its checks. The runner runs the checks (done, happened, the close); this module only words them
2
+ // and records the output they judged. Numbers are identities, not run order: #1 the output exists, #2 the model said done, #3 and up the close's
3
+ // checks. A check that did not run (the done check halts before the others) is not listed. A hitl close has no mechanical check, so it adds none.
4
+ import { createHash } from 'node:crypto';
5
+ import { serializeArtifact } from './ask.js';
6
+
7
+ export const EVERY_STEP = 'every step';
8
+
9
+ /** The size words of a byte count: `412 B`, `7.9 KB`, `1.2 MB`. @param {number} n */
10
+ export function sizeWords(n) {
11
+ if (n < 1024) return `${n} B`;
12
+ if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)} KB`;
13
+ return `${(n / 1024 / 1024).toFixed(1)} MB`;
14
+ }
15
+
16
+ /** Where a guardrail check comes from: the job line it belongs to (guardrail n belongs to job line n). @param {{fromLine?: unknown}} step */
17
+ export const lineSource = (step) => (Number.isInteger(step?.fromLine) ? `line ${step.fromLine} ~` : 'the step\'s guardrail');
18
+
19
+ /** #2, the model's own `done`. @param {{verdict: 'done'|'not-done'}} doneCheck @param {unknown} artifact */
20
+ export function doneRecord(doneCheck, artifact) {
21
+ const said = /** @type {any} */ (artifact)?.done;
22
+ return {
23
+ n: 2, text: 'the model said done: true', ok: doneCheck.verdict === 'done', result: doneCheck.verdict === 'done' ? null : (typeof said === 'boolean' ? 'it said done: false' : 'no true/false done'), source: EVERY_STEP,
24
+ };
25
+ }
26
+
27
+ /** #1, the happened check: the output exists and is not empty. @param {{verdict: string, red?: string}} happened @param {unknown} artifact */
28
+ export function happenedRecord(happened, artifact) {
29
+ const ok = happened.verdict !== 'red';
30
+ return {
31
+ n: 1, text: 'the output exists and isn\'t empty', ok, result: ok ? sizeWords(Buffer.byteLength(serializeArtifact(artifact), 'utf8')) : String(happened.red ?? '').replace(/^.*? produced /, ''), source: EVERY_STEP,
32
+ };
33
+ }
34
+
35
+ /** The output a try judged: the file it is saved as when the step closes, with the size and sha256 of those exact bytes. Never its content. @param {{emits?: string}} step @param {unknown} artifact */
36
+ export function outputRecord(step, artifact) {
37
+ const bytes = serializeArtifact(artifact);
38
+ return { file: `artifacts/${step?.emits ?? 'step'}.json`, bytes: Buffer.byteLength(bytes, 'utf8'), sha256: createHash('sha256').update(Buffer.from(bytes, 'utf8')).digest('hex') };
39
+ }
40
+
41
+ /**
42
+ * #3 and up: the close's own checks. A softgreen close carries each of its checks; a green close is one check over all its cited fields; a close that
43
+ * judged nothing (`unparseable`, `crash`) is one check that could not run, with that third outcome as its result.
44
+ * @param {any} step @param {any} artifact @param {{verdict: string, red?: string|null, checks?: Array<{text:string, ok:boolean, result:string|null}>}} closed
45
+ */
46
+ export function closeRecords(step, artifact, closed) {
47
+ const source = lineSource(step);
48
+ if (closed.verdict === 'unparseable' || closed.verdict === 'crash') {
49
+ return [{
50
+ n: 3, text: 'the close could run', ok: false, result: closed.verdict, source,
51
+ }];
52
+ }
53
+ if (step?.close?.class === 'green') {
54
+ const n = Object.keys(artifact?.fields ?? {}).length;
55
+ return [{
56
+ n: 3, text: 'every cited field matches its source', ok: closed.verdict === 'green', result: `${n} field${n === 1 ? '' : 's'}`, source,
57
+ }];
58
+ }
59
+ return (closed.checks ?? []).map((c, i) => ({
60
+ n: 3 + i, text: c.text, ok: c.ok, result: c.result, source,
61
+ }));
62
+ }
package/src/types.js CHANGED
@@ -261,6 +261,7 @@
261
261
  * @property {'green'|'red'|'hitl'|'unparseable'|'crash'} verdict
262
262
  * @property {string|null} [red]
263
263
  * @property {string[]} [reds]
264
+ * @property {Array<{id:string, text:string, ok:boolean, result:string|null}>} [checks] a softgreen close: every check it ran (M4d am29 item 2)
264
265
  */
265
266
 
266
267
  /**
@@ -0,0 +1,54 @@
1
+ /** A Stop's notes are not tries: the asked/not-honoured rows, and a `stopped` row that cut no try (no attempt number). @param {any} r */
2
+ export function isTryRow(r: any): boolean;
3
+ /** @param {string} runDir */
4
+ export function loadDiaries(runDir: string): {
5
+ present: boolean;
6
+ calls: any[];
7
+ tools: any[];
8
+ checks: any[];
9
+ };
10
+ /** What the human did, in the signed words, from the ask step's own audit row; `null` for a row that is not an answer. @param {any} r */
11
+ export function humanWords(r: any): string | null;
12
+ /**
13
+ * The fold of one step, or `null` for a step with nothing new to show (an old run, or a step that is neither a model step with records nor an ask).
14
+ * @param {{rows:any[], tryMarks:string[], closeClass:string|null}} group `deriveAuditGroups`' group for the step
15
+ * @param {ReturnType<typeof loadDiaries>} d
16
+ * @param {{about?: string|null}} [info] `about`: the file an ask is about
17
+ */
18
+ export function deriveFold(group: {
19
+ rows: any[];
20
+ tryMarks: string[];
21
+ closeClass: string | null;
22
+ }, d: ReturnType<typeof loadDiaries>, info?: {
23
+ about?: string | null;
24
+ }): {
25
+ who: string;
26
+ tally: string | null;
27
+ tries: any[];
28
+ rows: any[];
29
+ counts: {
30
+ rounds: number;
31
+ tools: number;
32
+ denied: number;
33
+ checksRun: any;
34
+ checksFailed: any;
35
+ lastTry: {
36
+ run: any;
37
+ passed: any;
38
+ } | null;
39
+ };
40
+ lastAnswer: {
41
+ words: string | null;
42
+ at: any;
43
+ } | null;
44
+ } | null;
45
+ /** The step card's one new line (item 6) minus the human step's time (the page formats that); `—` when there is no record. @param {ReturnType<typeof deriveFold>} fold */
46
+ export function cardLine(fold: ReturnType<typeof deriveFold>): string;
47
+ /**
48
+ * The Run summary's two new lines (item 5), from the same diary rows the folds read; `—` for a run with no diaries.
49
+ * @param {ReturnType<typeof loadDiaries>} d
50
+ */
51
+ export function summaryLines(d: ReturnType<typeof loadDiaries>): {
52
+ calls: string;
53
+ checks: string;
54
+ };
@@ -191,6 +191,7 @@ export function signDraft({ dir, approve, signedBy, signedAt, env, keyNames, ses
191
191
  modelPick: {
192
192
  slot: string;
193
193
  model: string;
194
+ thinking?: true;
194
195
  } | null;
195
196
  } | {
196
197
  ok: boolean;
package/types/books.d.ts CHANGED
@@ -17,6 +17,23 @@ export function appendPidRow(runDir: string, row: {
17
17
  * @returns {any[]}
18
18
  */
19
19
  export function readPidRows(runDir: string): any[];
20
+ /**
21
+ * Raw read-back of one JSONL book, one writer's own sibling reader (M4a
22
+ * piece 2, docs/wiki/the-module-ladder.md M4a scope item 2: "one reader per
23
+ * book"). Never throws on a missing file (`[]`) or a malformed line (that
24
+ * one line is skipped, never crashes the whole read) — the panel and any
25
+ * other reader need an honest best-effort array, not a hard failure over one
26
+ * bad byte someone else wrote.
27
+ *
28
+ * F48 round 3: goes through `readFileInside` (`src/flow.js`) — a book file
29
+ * that is itself a symlink, or that sits behind a symlinked ancestor
30
+ * directory, resolving outside `baseDir` reads as `[]`, same as a missing
31
+ * file, never as the outside target's content.
32
+ * @param {string} baseDir - the run dir (audit.jsonl) or flow dir (history.jsonl)
33
+ * @param {string} relPath - the book's own file name, relative to baseDir
34
+ * @returns {any[]}
35
+ */
36
+ export function readLines(baseDir: string, relPath: string): any[];
20
37
  /**
21
38
  * One row per attempt (also used for one row per ask and one row per send —
22
39
  * M2 scope item 9). `row` shape: `{ step, attempt, class, verdict, gap, usd,
@@ -16,3 +16,4 @@ export function makeCtxTools({ runDir, gatePath }: {
16
16
  /** One stashed item holds at most this many bytes (measured after secrets are masked,
17
17
  * because that is what enters the store). Bareloop's number, signed in M7 item 3. */
18
18
  export const ISOLATE_MAX_BYTES: 65536;
19
+ export function redactSecrets(raw: unknown): string;
@@ -0,0 +1,57 @@
1
+ export const DIARY_FILES: Readonly<{
2
+ calls: "calls.jsonl";
3
+ tools: "tools.jsonl";
4
+ checks: "checks.jsonl";
5
+ }>;
6
+ export function diaryPaths(runDir: string): string[];
7
+ export function appendCall(runDir: string, row: {
8
+ step: string | null;
9
+ try: number | null;
10
+ round: number;
11
+ at: string;
12
+ model: string | null;
13
+ costUsd: number | null;
14
+ tokens: {
15
+ in: number;
16
+ out: number;
17
+ cache: number;
18
+ } | null;
19
+ ms: number | null;
20
+ stopReason: string | null;
21
+ thinking: {
22
+ asked: string | null;
23
+ status: string | null;
24
+ };
25
+ }): void;
26
+ export function appendTool(runDir: string, row: {
27
+ step: string | null;
28
+ try: number | null;
29
+ round: number;
30
+ at: string;
31
+ tool: string;
32
+ path: string | null;
33
+ decision: "allow" | "deny" | "no check";
34
+ rule: string | null;
35
+ }): void;
36
+ export function appendChecks(runDir: string, row: {
37
+ step: string | null;
38
+ try: number;
39
+ at: string;
40
+ lastRound: number;
41
+ checks: Array<{
42
+ n: number;
43
+ text: string;
44
+ ok: boolean;
45
+ result: string | null;
46
+ source: string;
47
+ }>;
48
+ output: {
49
+ file: string;
50
+ bytes: number;
51
+ sha256: string;
52
+ } | null;
53
+ }): void;
54
+ export function readCalls(runDir: string): any[];
55
+ export function readTools(runDir: string): any[];
56
+ export function readChecks(runDir: string): any[];
57
+ export function nextRound(runDir: string, step: string | null): any;
@@ -1,16 +1,38 @@
1
1
  /**
2
2
  * @param {string} dir a draft folder or a flow folder
3
- * @returns {{ slot: string, model: string }|null} null when there is no usable record (missing, unreadable, or not a name and a model id)
3
+ * M4d am25: `thinking: true` is the Chat "Thinking on" box as it was when the job was signed; the key is absent when the box was off.
4
+ * @returns {{ slot: string, model: string, thinking?: true }|null} null when there is no usable record (missing, unreadable, or not a name and a model id)
4
5
  */
5
6
  export function readModelRecord(dir: string): {
6
7
  slot: string;
7
8
  model: string;
9
+ thinking?: true;
8
10
  } | null;
9
11
  /**
10
- * Write the record once (never over an existing one). @param {string} dir @param {{ slot: string, model: string }} pick
12
+ * Write the record once (never over an existing one). @param {string} dir @param {{ slot: string, model: string, thinking?: boolean }} pick
11
13
  */
12
- export function writeModelRecord(dir: string, { slot, model }: {
14
+ export function writeModelRecord(dir: string, { slot, model, thinking }: {
13
15
  slot: string;
14
16
  model: string;
17
+ thinking?: boolean;
15
18
  }): void;
19
+ /**
20
+ * M4d am25: the ONE reader of the job's "Thinking on" box for a run. A run reads its OWN record (`<run>/thinking.json`, written once when the run
21
+ * started) when it has one; otherwise the flow folder's `model.json`. No record, an unreadable one, or one without `thinking` is box OFF: a job
22
+ * signed before am25 stored nothing, and it must not start thinking on every try.
23
+ * @param {string} flowDir @param {string|null} runDir @returns {boolean}
24
+ */
25
+ export function readJobThinking(flowDir: string, runDir: string | null): boolean;
26
+ /**
27
+ * M4d am26: the run's OWN record of the box (`<run>/thinking.json`) and nothing else: `true`/`false`, or `null` when the run has none (a run from before am25).
28
+ * An unreadable record is box off, as `readJobThinking` has always read it. @param {string|null} runDir @returns {boolean|null}
29
+ */
30
+ export function readRunThinking(runDir: string | null): boolean | null;
31
+ /**
32
+ * M4d am25: a run keeps the box as the job had it when the run started (write-once, so an Edit of the job never changes a run already going).
33
+ * Written for every fresh run, ticked or not. @param {string} flowDir @param {string} runDir
34
+ */
35
+ export function writeRunThinking(flowDir: string, runDir: string): void;
16
36
  export const MODEL_FILE: "model.json";
37
+ /** 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). */
38
+ export const RUN_THINKING_FILE: "thinking.json";
@@ -87,7 +87,7 @@ export function buildEmitArtifactSchema(stepClass: any): Readonly<{
87
87
  * @param {{in:number,out:number}} [opts.rates]
88
88
  * @param {string} [opts.modelId]
89
89
  * @param {Record<string,string|undefined>} [opts.env] - the merged shell+keys-file env the key is read from (default process.env).
90
- * @returns {(executorContext:object, grantedTools:Record<string,any>, stepMeta?:{class?:string}, seam?:{stopRequested?:() => boolean}) => Promise<any>}
90
+ * @returns {(executorContext:object, grantedTools:Record<string,any>, stepMeta?:{class?:string, attempt?:number, step?:string|null, thinkingMode?:'on'|'off'}, seam?:{stopRequested?:() => boolean}) => Promise<any>}
91
91
  */
92
92
  export function makeLiveModelStep({ slot, model, spendPath, provider: injectedProvider, rates: injectedRates, modelId: injectedModelId, env, }: {
93
93
  slot?: string | undefined;
@@ -102,6 +102,9 @@ export function makeLiveModelStep({ slot, model, spendPath, provider: injectedPr
102
102
  env?: Record<string, string | undefined> | undefined;
103
103
  }): (executorContext: object, grantedTools: Record<string, any>, stepMeta?: {
104
104
  class?: string;
105
+ attempt?: number;
106
+ step?: string | null;
107
+ thinkingMode?: "on" | "off";
105
108
  }, seam?: {
106
109
  stopRequested?: () => boolean;
107
110
  }) => Promise<any>;
@@ -19,6 +19,37 @@ export function worstThinkingStatus(statuses: Array<string | null | undefined>):
19
19
  * @param {string|null} status @returns {string|null}
20
20
  */
21
21
  export function thinkingSay(status: string | null): string | null;
22
+ /**
23
+ * M4d am26 items 1-2: the words after a try line in the Audit, from that try's audit-row `thinking` {asked, status} (am25). bareagent confirmed it
24
+ * ('applied'): `thinking on` / `thinking off`. Any other status: `thinkingSay`'s words above, the same ones Chat uses. A row with no `thinking` (before am25,
25
+ * or no model call) has no words: nothing is guessed.
26
+ * M4d am27: a row with a `thinking` record but no status (the model sent no reply: an error, the time limit, a Stop before the first reply) reads
27
+ * `thinking <asked> (no reply)`, from what was ASKED; the words never say thinking happened. Nothing asked (asked null) has no words.
28
+ * @param {{asked?: unknown, status?: unknown}|null|undefined} thinking @returns {string|null}
29
+ */
30
+ export function thinkingTryWords(thinking: {
31
+ asked?: unknown;
32
+ status?: unknown;
33
+ } | null | undefined): string | null;
34
+ /**
35
+ * M4d am28 items 2-4 (replaces am26 item 3's words and the hidden row): the Job tab's Thinking value, from the run's own record
36
+ * (`boxOn` = the Chat "Thinking on" box as the run started). A run with no record (before am25) is `null` and reads `—`, never a guess from model.json.
37
+ * Words: bareloop's `thinkingJobText`.
38
+ * // borrowed-from: bareloop src/thinking.js@b79e7d9
39
+ * @param {boolean|null} boxOn
40
+ */
41
+ export function thinkingRuleWords(boxOn: boolean | null): "—" | "always on" | "on retries";
42
+ /**
43
+ * M4d am25 item 1/2: the ONE owner of what thinking a step's model call asks for. Code decides, never the model.
44
+ * Box ticked (the job's Chat "Thinking on" box, kept with the job): every try 'on'. Box off: the 1st try 'off'; the 2nd and later tries 'on'.
45
+ * A step redone after a human Redo is numbered from its redo count (the runner's `attemptOffset`), so it is always a 2nd-or-later try and thinks 'on'.
46
+ * @param {{boxOn: boolean, attempt: number}} a the runner's 1-based attempt number for this step
47
+ * @returns {'on'|'off'}
48
+ */
49
+ export function stepThinkingMode({ boxOn, attempt }: {
50
+ boxOn: boolean;
51
+ attempt: number;
52
+ }): "on" | "off";
22
53
  /** The sentence under a greyed "Thinking on" box (amendment 7 item 2). */
23
54
  export const THINKING_FIXED_SAY: "can't change this for this model";
24
55
  /** The note beside the Chat "Thinking on" box, before any draft, for a model bareagent has not checked (M4d am11 item 2). */
@@ -0,0 +1,55 @@
1
+ /** The size words of a byte count: `412 B`, `7.9 KB`, `1.2 MB`. @param {number} n */
2
+ export function sizeWords(n: number): string;
3
+ /** #2, the model's own `done`. @param {{verdict: 'done'|'not-done'}} doneCheck @param {unknown} artifact */
4
+ export function doneRecord(doneCheck: {
5
+ verdict: "done" | "not-done";
6
+ }, artifact: unknown): {
7
+ n: number;
8
+ text: string;
9
+ ok: boolean;
10
+ result: string | null;
11
+ source: string;
12
+ };
13
+ /** #1, the happened check: the output exists and is not empty. @param {{verdict: string, red?: string}} happened @param {unknown} artifact */
14
+ export function happenedRecord(happened: {
15
+ verdict: string;
16
+ red?: string;
17
+ }, artifact: unknown): {
18
+ n: number;
19
+ text: string;
20
+ ok: boolean;
21
+ result: string;
22
+ source: string;
23
+ };
24
+ /** The output a try judged: the file it is saved as when the step closes, with the size and sha256 of those exact bytes. Never its content. @param {{emits?: string}} step @param {unknown} artifact */
25
+ export function outputRecord(step: {
26
+ emits?: string;
27
+ }, artifact: unknown): {
28
+ file: string;
29
+ bytes: number;
30
+ sha256: string;
31
+ };
32
+ /**
33
+ * #3 and up: the close's own checks. A softgreen close carries each of its checks; a green close is one check over all its cited fields; a close that
34
+ * judged nothing (`unparseable`, `crash`) is one check that could not run, with that third outcome as its result.
35
+ * @param {any} step @param {any} artifact @param {{verdict: string, red?: string|null, checks?: Array<{text:string, ok:boolean, result:string|null}>}} closed
36
+ */
37
+ export function closeRecords(step: any, artifact: any, closed: {
38
+ verdict: string;
39
+ red?: string | null;
40
+ checks?: Array<{
41
+ text: string;
42
+ ok: boolean;
43
+ result: string | null;
44
+ }>;
45
+ }): {
46
+ n: number;
47
+ text: string;
48
+ ok: boolean;
49
+ result: string | null;
50
+ source: string;
51
+ }[];
52
+ export const EVERY_STEP: "every step";
53
+ export function lineSource(step: {
54
+ fromLine?: unknown;
55
+ }): string;