fwdloop 0.19.1 → 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.
Files changed (68) hide show
  1. package/README.md +2 -0
  2. package/bin/fwdloop +22 -13
  3. package/package.json +1 -1
  4. package/src/audit-fold.js +177 -0
  5. package/src/authoring.js +24 -4
  6. package/src/books.js +4 -3
  7. package/src/closers.js +49 -2
  8. package/src/ctx-tools.js +1 -1
  9. package/src/diary.js +49 -0
  10. package/src/flow.js +218 -2
  11. package/src/flowmodel.js +42 -5
  12. package/src/jobkey.js +25 -0
  13. package/src/jsonl-append.js +29 -0
  14. package/src/model-step.js +103 -5
  15. package/src/monthly.js +3 -2
  16. package/src/panel/author.js +44 -18
  17. package/src/panel/authorcard.js +7 -13
  18. package/src/panel/authorflows.js +118 -24
  19. package/src/panel/authorresume.js +8 -4
  20. package/src/panel/authorstart.js +63 -18
  21. package/src/panel/authortrigger.js +250 -125
  22. package/src/panel/authorvalues.js +13 -2
  23. package/src/panel/data.js +279 -43
  24. package/src/panel/index.html +547 -150
  25. package/src/panel/needsyou.js +29 -0
  26. package/src/panel/scheduler.js +21 -22
  27. package/src/panel/server.js +30 -6
  28. package/src/primitives.js +44 -2
  29. package/src/provider.js +3 -2
  30. package/src/runner.js +58 -22
  31. package/src/runvalues.js +10 -2
  32. package/src/schedule.js +135 -0
  33. package/src/setup.js +0 -21
  34. package/src/summary-words.js +180 -7
  35. package/src/thinking.js +39 -0
  36. package/src/trigger-clock.js +18 -16
  37. package/src/trigger-files.js +37 -24
  38. package/src/trigger-line.js +6 -15
  39. package/src/try-checks.js +62 -0
  40. package/src/types.js +2 -1
  41. package/types/audit-fold.d.ts +54 -0
  42. package/types/authoring.d.ts +33 -2
  43. package/types/books.d.ts +17 -0
  44. package/types/ctx-tools.d.ts +1 -0
  45. package/types/diary.d.ts +57 -0
  46. package/types/flow.d.ts +106 -0
  47. package/types/flowmodel.d.ts +25 -3
  48. package/types/jobkey.d.ts +11 -0
  49. package/types/jsonl-append.d.ts +6 -0
  50. package/types/model-step.d.ts +4 -1
  51. package/types/panel/author.d.ts +47 -17
  52. package/types/panel/authorcard.d.ts +3 -6
  53. package/types/panel/authorflows.d.ts +38 -10
  54. package/types/panel/authorstart.d.ts +15 -2
  55. package/types/panel/authortrigger.d.ts +73 -41
  56. package/types/panel/authorvalues.d.ts +6 -0
  57. package/types/panel/data.d.ts +101 -19
  58. package/types/panel/needsyou.d.ts +20 -0
  59. package/types/runvalues.d.ts +5 -0
  60. package/types/schedule.d.ts +69 -0
  61. package/types/setup.d.ts +0 -19
  62. package/types/summary-words.d.ts +105 -2
  63. package/types/thinking.d.ts +31 -0
  64. package/types/trigger-clock.d.ts +8 -7
  65. package/types/trigger-files.d.ts +17 -10
  66. package/types/trigger-line.d.ts +16 -8
  67. package/types/try-checks.d.ts +55 -0
  68. package/types/types.d.ts +10 -1
package/src/runner.js CHANGED
@@ -48,7 +48,7 @@ import { resetRunStore } from './run-store.js';
48
48
  import { fileURLToPath } from 'node:url';
49
49
 
50
50
  import {
51
- readFlow, resolveRunDir, readFileInside, readdirInside, resolveInside, FLOW_FILES, PANEL_STARTS_DIR, writeRunJobCopy,
51
+ readPlan, readRunPlan, runOwnsPlan, resolveRunDir, readFileInside, readdirInside, resolveInside, FLOW_FILES, PANEL_STARTS_DIR, writeRunJobCopy,
52
52
  } from './flow.js';
53
53
  import {
54
54
  writeAskArchive, readAcceptedHashesByEmits, serializeArtifact, normalizeDecision, answerTiming, effectiveExpiresAt, withReopen, setAsideAnswer,
@@ -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}` };
@@ -993,7 +1026,7 @@ export async function runFlow({
993
1026
  return { outcome: 'refused', red: runIdCheck.red };
994
1027
  }
995
1028
 
996
- const read = readFlow({ root, name, catalogue });
1029
+ const read = readPlan({ root, name, catalogue, runDir: runIdCheck.runDir });
997
1030
  if (!read.ok) {
998
1031
  // Negative iv: a flow whose files don't hash to the signature (or is
999
1032
  // otherwise unreadable) is refused by name, at $0. No run dir exists to
@@ -1065,13 +1098,16 @@ export async function runFlow({
1065
1098
  mkdirSync(runDir, { recursive: true });
1066
1099
 
1067
1100
  // M6: the run keeps a write-once copy of the job it runs, from before its first step (its Job tab shows this, not the flow's later versions)
1068
- const jobCopy = writeRunJobCopy(flowDir, runDir, signature.flow);
1101
+ const jobCopy = runOwnsPlan(runDir) ? { ok: /** @type {true} */ (true) } : writeRunJobCopy(flowDir, runDir, signature.flow); // am9: a run that keeps its own plan already holds its verified copy
1069
1102
  if (!jobCopy.ok) {
1070
1103
  return haltRun({
1071
1104
  flowDir, runDir, runId, capUsd, startedAt, now, nowMs: getNowMs, signatureHash: signature.flow, outcome: 'preflight-red', red: jobCopy.red, spent: { value: 0 },
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) {
@@ -1886,7 +1922,7 @@ export async function resumeRun({
1886
1922
  // below (inside the lock): if this pre-read itself fails, that failure is
1887
1923
  // reported properly by the definitive read further down, under the lock,
1888
1924
  // exactly as before this check existed.
1889
- const preflightRead = readFlow({ root, name, catalogue });
1925
+ const preflightRead = readRunPlan({ root, name, catalogue, runDir });
1890
1926
  if (preflightRead.ok) {
1891
1927
  const unwiredVerb = findUnwiredVerbStep(preflightRead.declaration);
1892
1928
  if (unwiredVerb) {
@@ -1949,7 +1985,7 @@ export async function resumeRun({
1949
1985
  };
1950
1986
  }
1951
1987
 
1952
- const read = readFlow({ root, name, catalogue });
1988
+ const read = readRunPlan({ root, name, catalogue, runDir });
1953
1989
  if (!read.ok) {
1954
1990
  return { outcome: 'refused', red: `resume: flow re-read failed for run "${runId}": ${read.reds.join('; ')}` };
1955
1991
  }
@@ -1960,7 +1996,7 @@ export async function resumeRun({
1960
1996
  const { arbiter } = applied;
1961
1997
 
1962
1998
  if (signature.flow !== state.signatureHash) {
1963
- return { outcome: 'refused', red: `resume: signature mismatch for run "${runId}" — the flow changed while parked` };
1999
+ return { outcome: 'refused', red: `resume: signature mismatch for run "${runId}" — its saved copy of the job is not the job it was parked under` };
1964
2000
  }
1965
2001
 
1966
2002
  for (const entry of state.inputsManifest ?? []) {
@@ -2410,7 +2446,7 @@ export async function continueRun({
2410
2446
  if (!runIdCheck.ok) return { outcome: 'refused', red: runIdCheck.red };
2411
2447
  const runDir = runIdCheck.runDir;
2412
2448
 
2413
- const preflightRead = readFlow({ root, name, catalogue });
2449
+ const preflightRead = readRunPlan({ root, name, catalogue, runDir });
2414
2450
  if (preflightRead.ok) {
2415
2451
  const unwiredVerb = findUnwiredVerbStep(preflightRead.declaration);
2416
2452
  if (unwiredVerb) return refused(unwiredRed(unwiredVerb));
@@ -2437,10 +2473,10 @@ export async function continueRun({
2437
2473
  }
2438
2474
  if (!Number.isInteger(halt.stepIndex) || halt.stepIndex < 0) return refused(`run "${runId}" halt.json field "stepIndex" is not a step number`);
2439
2475
 
2440
- const read = readFlow({ root, name, catalogue });
2476
+ const read = readRunPlan({ root, name, catalogue, runDir });
2441
2477
  if (!read.ok) return refused(`flow re-read failed for run "${runId}": ${read.reds.join('; ')}`);
2442
2478
  const { declaration, signature } = read;
2443
- if (signature.flow !== halt.signatureHash) return refused(`signature mismatch for run "${runId}" — the flow changed while it was halted`);
2479
+ if (signature.flow !== halt.signatureHash) return refused(`signature mismatch for run "${runId}" — its saved copy of the job is not the job it was halted under`);
2444
2480
  // the human's signed values for this run (its highest version): the new cap is read from here, nowhere else
2445
2481
  const applied = applyRunValues(read.arbiter, name, signature.flow, pickRunValues(runDir));
2446
2482
  if (!applied.ok) return refused(`run "${runId}" — ${applied.red}`);
@@ -2638,7 +2674,7 @@ export async function stopParkedRun({
2638
2674
  const audit = auditSpend(runDir);
2639
2675
  if (!audit.ok) return refused(`run "${runId}" ${audit.red}`);
2640
2676
  requestStop(runDir); // 'exists' when the door (or a race) wrote it already
2641
- const read = readFlow({ root, name, catalogue });
2677
+ const read = readRunPlan({ root, name, catalogue, runDir });
2642
2678
  let capUsd = null;
2643
2679
  if (read.ok) {
2644
2680
  const applied = applyRunValues(read.arbiter, name, read.signature.flow, pickRunValues(runDir));
package/src/runvalues.js CHANGED
@@ -53,12 +53,14 @@ export function flowValues(arbiter) {
53
53
  return { capUsd: arbiter.capUsd, destination, askWaits };
54
54
  }
55
55
 
56
- /** @param {{capUsd: number, destination: string|null, askWaits: Record<string,string>}} v the values in canonical key order */
56
+ /** @param {{capUsd: number, destination: string|null, askWaits: Record<string,string>, model?: {slot: string, model: string}|null}} v the values in canonical key order */
57
57
  function canonValues(v) {
58
58
  return {
59
59
  capUsd: v.capUsd,
60
60
  destination: v.destination ?? null,
61
61
  askWaits: Object.fromEntries(Object.entries(v.askWaits ?? {}).sort(([a], [b]) => Number(a) - Number(b))),
62
+ // M6 am5/am6: the model THIS run uses, only when it differs from the flow's recorded one. Absent = no key at all, so every record signed before this keeps its hash.
63
+ ...(v.model ? { model: { slot: v.model.slot, model: v.model.model } } : {}),
62
64
  };
63
65
  }
64
66
 
@@ -79,6 +81,11 @@ export function sameValues(a, b) {
79
81
  return JSON.stringify(canonValues(a)) === JSON.stringify(canonValues(b));
80
82
  }
81
83
 
84
+ /** The model a run was signed to use instead of its flow's recorded one, or null (the flow's). The ONE reader. @param {ReturnType<typeof pickRunValues>} picked */
85
+ export function runModelOf(picked) {
86
+ return picked.ok && !picked.none && picked.record.values.model ? { slot: picked.record.values.model.slot, model: picked.record.values.model.model } : null;
87
+ }
88
+
82
89
  /** File name of a version. @param {number} version */
83
90
  export const valuesFileName = (version) => (version === 0 ? 'signed-values.json' : `signed-values-r${version}.json`);
84
91
 
@@ -126,7 +133,8 @@ export function pickRunValues(runDir) {
126
133
  const shaped = record && typeof record === 'object' && record.version === best.version && typeof record.flow === 'string' && typeof record.flowSignatureHash === 'string'
127
134
  && typeof record.hash === 'string' && v && typeof v === 'object' && Number.isFinite(v.capUsd) && v.capUsd > 0
128
135
  && (v.destination === null || (typeof v.destination === 'string' && v.destination !== ''))
129
- && v.askWaits && typeof v.askWaits === 'object' && Object.values(v.askWaits).every((w) => parseWaitMs(w) !== null);
136
+ && v.askWaits && typeof v.askWaits === 'object' && Object.values(v.askWaits).every((w) => parseWaitMs(w) !== null)
137
+ && (v.model === undefined || (v.model && typeof v.model.slot === 'string' && v.model.slot !== '' && typeof v.model.model === 'string' && v.model.model !== ''));
130
138
  if (!shaped) return { ok: false, red: `signed values: ${best.name} does not have the shape of a signed values record` };
131
139
  const want = valuesHash({
132
140
  flow: record.flow, flowSignatureHash: record.flowSignatureHash, runId: best.version === 0 ? null : (record.runId ?? null), version: best.version, values: v,
@@ -0,0 +1,135 @@
1
+ // M9 amendment 20 (docs/wiki/the-module-ladder.md, SIGNED 2026-10-16): a job's schedule lives in its OWN signed file, `<flow>/schedule.json`,
2
+ // and its queue in ONE file, `<flow>/schedule-ledger.jsonl`, for as long as the job exists. Setting, changing or cancelling a schedule never
3
+ // touches the job or its signature (prose.txt, declaration.json, signature.json are not opened here).
4
+ //
5
+ // borrowed-from: bareloop src/panel/schedules.js@73809db (readSchedule / writeSchedule / dropQueue / sameTarget / removeSchedule), adapted:
6
+ // fwdloop keeps a job's fire OUTCOMES in `triggers.jsonl` (the Audit's words are built from it), so this file's ledger holds only the clock and file rows.
7
+ //
8
+ // ONE WRITER PER FIELD: `writeSchedule` is the only function that writes `schedule.json` (temp + rename: a reader sees the old file or the new one,
9
+ // never half); `removeSchedule` the only one that removes it. `dropQueue` / `carryQueue` are the only places a waiting file leaves a queue because
10
+ // the schedule changed. The signing id (`sig`) is `sha256(bound + signedAt)`: the same schedule signed again after a Cancel is a NEW signing, so rows
11
+ // of the earlier one can never carry over. Every ledger row carries the `sig` that wrote it; "since this signing" is a filter on `sig`.
12
+ import { createHash } from 'node:crypto';
13
+ import { renameSync, rmSync, writeFileSync } from 'node:fs';
14
+ import { isAbsolute, join } from 'node:path';
15
+
16
+ import { readFileInside } from './flow.js';
17
+ import { appendRow } from './jsonl-append.js';
18
+ import { queueOf, readSeen, recordDropped } from './trigger-files.js';
19
+ import { readRows, validateSchedule } from './trigger-clock.js';
20
+ import { triggerHash } from './trigger-line.js';
21
+
22
+ /** @typedef {import('./trigger-line.js').Trigger} Trigger */
23
+ /**
24
+ * @typedef {{
25
+ * v: 1, flow: string, trigger: Trigger, flowSignatureHash: string, bound: string, sig: string, signedBy: string, signedAt: string,
26
+ * model: {slot: string, model: string}|null, destination: string|null, inputs: {role: string, path: string}[]|null,
27
+ * plan: {run: string, flowHash: string, declSha: string}|null, from: string|null,
28
+ * }} Schedule
29
+ */
30
+
31
+ export const SCHEDULE_FILE = 'schedule.json';
32
+ export const LEDGER_FILE = 'schedule-ledger.jsonl';
33
+ /** The words of the am16 row (also for a Cancel): signed text, M9 am16. @param {string} name */
34
+ export const droppedSay = (name) => `${name} was waiting when the schedule changed, so it will not run. Drop it in again to run it.`;
35
+
36
+ /** @param {string} flowDir */
37
+ export const scheduleFileOf = (flowDir) => join(flowDir, SCHEDULE_FILE);
38
+ /** @param {string} flowDir */
39
+ export const ledgerOf = (flowDir) => join(flowDir, LEDGER_FILE);
40
+
41
+ /** @param {string} bound @param {string} signedAt */
42
+ export const sigOf = (bound, signedAt) => createHash('sha256').update(`${bound}\n${signedAt}`).digest('hex');
43
+
44
+ const isFile = (/** @type {any} */ t) => t?.kind === 'new-file' || t?.kind === 'file-updated';
45
+ const str = (/** @type {unknown} */ v) => typeof v === 'string' && v !== '';
46
+
47
+ /** Is this a typed trigger of the five shapes? (the same shapes `trigger-line.js` parses; the schedule file never carries a line) @param {any} t */
48
+ function triggerOk(t) {
49
+ if (!t || typeof t !== 'object') return false;
50
+ if (isFile(t)) return str(t.role) && isAbsolute(String(t.kind === 'new-file' ? t.folder : t.path));
51
+ try { validateSchedule(t); return true; } catch { return false; }
52
+ }
53
+
54
+ /**
55
+ * The job's schedule, or null (no file, unreadable, not the shape, or a file whose own hashes do not check: it was changed after it was signed, so it
56
+ * is not the schedule a human signed and nothing acts on it). Read through the safe gateway.
57
+ * @param {string} flowDir @returns {Schedule|null}
58
+ */
59
+ export function readSchedule(flowDir) {
60
+ const f = readFileInside(flowDir, SCHEDULE_FILE);
61
+ if (!f.ok) return null;
62
+ let o;
63
+ try { o = JSON.parse(f.text); } catch { return null; }
64
+ if (!o || typeof o !== 'object' || o.v !== 1 || !str(o.flow) || !triggerOk(o.trigger) || !str(o.flowSignatureHash) || !str(o.bound) || !str(o.sig) || !str(o.signedBy) || !str(o.signedAt)) return null;
65
+ const optStr = (/** @type {unknown} */ v) => v === null || str(v);
66
+ if (!optStr(o.destination) || !optStr(o.from)) return null;
67
+ if (o.model !== null && !(o.model && str(o.model.slot) && str(o.model.model))) return null;
68
+ if (o.inputs !== null && !(Array.isArray(o.inputs) && o.inputs.every((/** @type {any} */ r) => str(r?.role) && str(r?.path)))) return null;
69
+ if (o.plan !== null && !(o.plan && str(o.plan.run) && str(o.plan.flowHash) && str(o.plan.declSha))) return null;
70
+ const want = triggerHash({
71
+ flow: o.flow, flowSignatureHash: o.flowSignatureHash, trigger: o.trigger, model: o.model, destination: o.destination, inputs: o.inputs, plan: o.plan,
72
+ });
73
+ if (want !== o.bound || sigOf(o.bound, o.signedAt) !== o.sig) return null;
74
+ return /** @type {Schedule} */ (o);
75
+ }
76
+
77
+ /** THE writer of `schedule.json`: atomic (temp file, then rename). @param {string} flowDir @param {Schedule} schedule */
78
+ export function writeSchedule(flowDir, schedule) {
79
+ const file = scheduleFileOf(flowDir);
80
+ const tmp = `${file}.${process.pid}.tmp`;
81
+ writeFileSync(tmp, `${JSON.stringify(schedule, null, 2)}\n`, { mode: 0o600 });
82
+ renameSync(tmp, file);
83
+ }
84
+
85
+ /** The only remover of `schedule.json`. @param {string} flowDir */
86
+ export function removeSchedule(flowDir) {
87
+ rmSync(scheduleFileOf(flowDir), { force: true });
88
+ }
89
+
90
+ /** Does a re-sign keep the same kind and the same folder/file (so the queue and the baseline stand)? @param {Trigger|null|undefined} cur @param {Trigger|null} next */
91
+ export function sameTarget(cur, next) {
92
+ if (!cur || !next || !isFile(cur) || !isFile(next) || cur.kind !== next.kind) return false;
93
+ return cur.kind === 'new-file' ? cur.folder === /** @type {any} */ (next).folder : /** @type {any} */ (cur).path === /** @type {any} */ (next).path;
94
+ }
95
+
96
+ /** Is this signing armed (its `armed` row is in the ledger)? @param {string} flowDir @param {string} sig */
97
+ export const isArmed = (flowDir, sig) => readRows(ledgerOf(flowDir), sig).some((r) => r.kind === 'armed');
98
+
99
+ /**
100
+ * Every file waiting under signing `sig` leaves its queue: one `dropped` row (under `sig`) and ONE row in the outcome file with am16's words. The drop is written
101
+ * BEFORE the row: a crash loses a row, never doubles one. @param {string} flowDir @param {string} sig
102
+ * @param {number} nowMs @param {(row: Record<string, any>) => void} note writes one outcome row
103
+ */
104
+ export function dropQueue(flowDir, sig, nowMs, note) {
105
+ const ledger = ledgerOf(flowDir);
106
+ for (const q of queueOf(readSeen(ledger, sig))) {
107
+ recordDropped(ledger, q, 'schedule-changed', nowMs, sig);
108
+ note({ outcome: 'schedule-changed', file: q.path, sha: q.sha, say: droppedSay(q.name) });
109
+ }
110
+ }
111
+
112
+ /**
113
+ * The folder is the same: signing `to` takes over everything `from` knew about the files (baseline, arrived, ran, dropped, in order), so the queue and
114
+ * the starting point stand. Written BEFORE the new `schedule.json`; the old signing's waiting files are marked `carried` after it (`finishCarry`).
115
+ * @param {string} flowDir @param {string} from @param {string} to
116
+ */
117
+ export function carryQueue(flowDir, from, to) {
118
+ const ledger = ledgerOf(flowDir);
119
+ for (const r of readSeen(ledger, from)) {
120
+ if (!['baseline', 'arrived', 'ran', 'dropped'].includes(r.kind)) continue;
121
+ const { sig: _old, ...row } = r;
122
+ appendRow(ledger, { ...row, sig: to });
123
+ }
124
+ }
125
+
126
+ /** The old signing's files that `carryQueue` copied are no longer its own to run. @param {string} flowDir @param {string} from @param {number} nowMs */
127
+ export function finishCarry(flowDir, from, nowMs) {
128
+ const ledger = ledgerOf(flowDir);
129
+ for (const q of queueOf(readSeen(ledger, from))) recordDropped(ledger, q, 'carried', nowMs, from);
130
+ }
131
+
132
+ /** Cancel's own row in the ledger. @param {string} flowDir @param {string} sig @param {number} nowMs */
133
+ export function recordCancelled(flowDir, sig, nowMs) {
134
+ appendRow(ledgerOf(flowDir), { id: `cancelled:${nowMs}`, kind: 'cancelled', sig, at: nowMs });
135
+ }
package/src/setup.js CHANGED
@@ -112,27 +112,6 @@ export function writeSetup({ flowDir, secrets = [], ...rest }) {
112
112
  }
113
113
  }
114
114
 
115
- /**
116
- * M9 item 2: a trigger-only re-sign signs the same plan under a new flow hash. The old `setup.jsonl` bytes are written back untouched (append-only)
117
- * and ONE row is added: kind `trigger-resign`, the record of the signing it continues (its plan hash and "Not checked" list, copied) under the new
118
- * `flowHash`, naming the old one in `resignOf`. A reader that wants this job's record looks for the row whose `flowHash` is the job's. Never throws.
119
- * @param {{ flowDir: string, oldText: string, oldFlowHash: string, newFlowHash: string, at: string }} a
120
- * @returns {{ ok: true } | { ok: false, red: string }}
121
- */
122
- export function carrySetup({ flowDir, oldText, oldFlowHash, newFlowHash, at }) {
123
- try {
124
- const rows = oldText.split('\n').filter(Boolean).map((l) => { try { return JSON.parse(l); } catch { return null; } }).filter(Boolean);
125
- const signs = rows.filter((r) => r.kind === 'sign' || r.kind === 'trigger-resign');
126
- const from = signs.findLast((r) => r.flowHash === oldFlowHash) ?? signs.at(-1);
127
- const keep = oldText.endsWith('\n') ? oldText : `${oldText}\n`;
128
- const extra = from ? `${JSON.stringify({ ...from, kind: 'trigger-resign', at, flowHash: newFlowHash, resignOf: oldFlowHash })}\n` : '';
129
- writeFileSync(join(flowDir, SETUP_FILE), keep + extra, { flag: 'wx', mode: 0o600 });
130
- return { ok: true };
131
- } catch (err) {
132
- return { ok: false, red: `setup: could not carry ${SETUP_FILE} over (${err.code ?? err.message})` };
133
- }
134
- }
135
-
136
115
  /**
137
116
  * The flow's setup rows, through the one safe gateway. `present:false` = a flow signed before amendment 6 (or a file that cannot be read).
138
117
  * @param {string} flowDir