fwdloop 0.8.0 → 0.9.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
@@ -12,7 +12,7 @@
12
12
  // poc/m2/gapback.mjs@29caa83 (`buildExecutor`'s "no field but goal/
13
13
  // primitives/reads/gap" shape, `normaliseGap`, the strike-governed ralph
14
14
  // loop) and fwdloop poc/m0/askWithRedo@29caa83 (the ask-with-redo: consume-once,
15
- // a reason-less rerun refused and re-asked, a rejection redoes the step that
15
+ // a reason-less rerun refused and re-asked, a redo redoes the step that
16
16
  // emitted the artifact under review). Rewritten against M1's real
17
17
  // `readFlow`/`arbiter` shape (the POCs above ran on hand-rolled declarations
18
18
  // and a single hard-coded ask/send slot) — src/ never imports from poc/.
@@ -48,7 +48,9 @@ import { fileURLToPath } from 'node:url';
48
48
  import {
49
49
  readFlow, resolveRunDir, readFileInside, resolveInside,
50
50
  } from './flow.js';
51
- import { writeAskArchive } from './ask.js';
51
+ import {
52
+ writeAskArchive, readAcceptedHashesByEmits, serializeArtifact, normalizeDecision,
53
+ } from './ask.js';
52
54
  import { WIRED_VERBS } from './primitives.js';
53
55
  import { closeByClass } from './closers.js';
54
56
  import { appendAudit, appendHistory } from './books.js';
@@ -386,7 +388,7 @@ export function writeArtifact(runDir, id, artifact, { overwrite = false } = {})
386
388
  if (existsSync(target) && !overwrite) {
387
389
  throw new Error(`writeArtifact: artifact "${id}" already exists in this run (${target}) — refused`);
388
390
  }
389
- writeFileSync(target, JSON.stringify(artifact, null, 2));
391
+ writeFileSync(target, serializeArtifact(artifact));
390
392
  }
391
393
 
392
394
  /**
@@ -474,6 +476,7 @@ function recordLateAnswerIfAny(runDir, now = () => new Date().toISOString()) {
474
476
  at: now(),
475
477
  tokens: null,
476
478
  tools: null,
479
+ refused: [],
477
480
  kind: 'answer-after-run',
478
481
  file,
479
482
  });
@@ -750,8 +753,8 @@ async function runStepRalph({
750
753
  * @param {Array<{id:string, path:string}>} opts.sources - the real files to freeze for this run.
751
754
  * @param {unknown} opts.catalogue - passed straight through to `readFlow`.
752
755
  * @param {(executorContext:object, grantedTools:Record<string,any>, stepMeta?:{class:string|null}) => Promise<{ok:boolean, artifact?:unknown, costUsd:number|null, red?:string, transport?:boolean, model?:string, modelMatch?:boolean}>} opts.modelStep
753
- * @param {(opts:{question:string, evidence:unknown, runDir:string}) => Promise<{decision:'accept'|'reject'|'rerun'|'timeout'|'park', reason?:string}>} opts.askStep
754
- * @param {(target:string, filename:string, content:unknown) => Promise<{ok:boolean, red?:string, bytes?:number}>} opts.sendStep
756
+ * @param {(opts:{question:string, evidence:unknown, runDir:string}) => Promise<{decision:'accept'|'redo'|'rerun'|'timeout'|'park', reason?:string, artifactSha256?:string}>} opts.askStep
757
+ * @param {(target:string, filename:string, content:unknown, acceptedSha256?:string|null) => Promise<{ok:boolean, red?:string, bytes?:number}>} opts.sendStep
755
758
  * @param {Record<string, any>} [opts.primitives] - injected primitive implementations, keyed by catalogue verb.
756
759
  * @param {string[]} [opts.primitiveReds] - `resolvePrimitives`'s own `reds` (e.g. bareguard refusing a symlinked file scope); any entry refuses the run at $0 like an unwired verb, before the run dir exists.
757
760
  * @param {() => string} [opts.clock] - returns the current ISO timestamp; defaults to the wall clock.
@@ -901,7 +904,9 @@ export async function runFlow({
901
904
  const askStepEmits = new Set(steps.filter((s) => askLines.has(s.fromLine)).map((s) => s.emits));
902
905
  // Tracks which specific ask emits were accepted THIS run (acceptedThisRun
903
906
  // above stays run-wide, for the "reached with no accept this run" gate).
904
- const acceptedAskEmitsThisRun = new Set();
907
+ // M4b piece 3: Map emits -> the sha256 the human's accept recorded for that
908
+ // ask's artifact (`null` = none recorded in THIS process; send refuses).
909
+ const acceptedAskEmitsThisRun = new Map();
905
910
 
906
911
  const result = await foldFromStep({
907
912
  i0: 0,
@@ -979,16 +984,16 @@ export function makeParkingAskStep() {
979
984
 
980
985
  /** `resumeRun`'s own askStep: yields the human's already-consumed decision
981
986
  * exactly once (for the ask it was built for), then — if that decision was
982
- * a reject and the ask loops back around to ask again — parks under a NEW
987
+ * a redo and the ask loops back around to ask again — parks under a NEW
983
988
  * askId, exactly like a fresh ask would. This is what turns "redo, then
984
989
  * ask again" into "redo, then re-park" for a resumed run, with no second
985
990
  * code path. */
986
- function makeOneShotThenParkAskStep({ decision, reason }) {
991
+ function makeOneShotThenParkAskStep({ decision, reason, artifactSha256 }) {
987
992
  let used = false;
988
993
  return async function resumeAskStep() {
989
994
  if (!used) {
990
995
  used = true;
991
- return { decision, reason };
996
+ return { decision, reason, artifactSha256 };
992
997
  }
993
998
  return { decision: 'park' };
994
999
  };
@@ -1025,9 +1030,11 @@ async function runAskSlot({
1025
1030
  for (;;) {
1026
1031
  const evidence = { artifact: currentPrior, unjudged: evidenceUnjudged };
1027
1032
  // eslint-disable-next-line no-await-in-loop
1028
- const answer = await askStep({
1033
+ const rawAnswer = await askStep({
1029
1034
  question: askSlot?.question ?? step.goal, evidence, runDir, ttlMs: askSlot?.ttlMs, stepIndex,
1030
1035
  });
1036
+ // M4b amendment 3: a decision from any askStep is translated once, here.
1037
+ const answer = { ...rawAnswer, decision: normalizeDecision(rawAnswer.decision) };
1031
1038
 
1032
1039
  if (answer.decision === 'park') {
1033
1040
  // M3 scope item 1 (fixes F43): the wait is ALWAYS the signed ttlMs —
@@ -1039,7 +1046,7 @@ async function runAskSlot({
1039
1046
  // human sees in-process (`makeFileAskStep`'s `{ artifact, unjudged }`)
1040
1047
  // — the draft under review and the unjudged evidence, never just the
1041
1048
  // question. `evidence` above is already recomputed at the top of every
1042
- // loop iteration (including a re-park after a reject, where
1049
+ // loop iteration (including a re-park after a redo, where
1043
1050
  // `currentPrior` is the just-redrafted artifact), so this write always
1044
1051
  // carries the CURRENT evidence, not a stale first-park copy.
1045
1052
  writeFileSync(join(runDir, 'ask.json'), JSON.stringify({
@@ -1057,7 +1064,7 @@ async function runAskSlot({
1057
1064
  // is a genuine invariant violation, not a race to recover from — it
1058
1065
  // halts the run rather than silently dropping the archive duty.
1059
1066
  const archived = writeAskArchive({
1060
- runDir, askId, question: askSlot?.question ?? step.goal, askedAt, expiresAt, evidence,
1067
+ runDir, askId, question: askSlot?.question ?? step.goal, askedAt, expiresAt, evidence, emits: step.emits,
1061
1068
  });
1062
1069
  if (!archived.ok) {
1063
1070
  throw new Error(archived.red);
@@ -1126,12 +1133,12 @@ async function runAskSlot({
1126
1133
  };
1127
1134
  }
1128
1135
 
1129
- const isRedo = answer.decision === 'reject' || answer.decision === 'rerun';
1136
+ const isRedo = answer.decision === 'redo' || answer.decision === 'rerun';
1130
1137
  const reason = typeof answer.reason === 'string' ? answer.reason.trim() : '';
1131
1138
 
1132
1139
  if (isRedo && reason.length === 0) {
1133
1140
  recordAudit(makeAuditRow({
1134
- step, attempt: redone + 1, verdict: 'refused', gap: 'a rejection/rerun needs a reason', usd: 0, spendComplete: true, wallMs: 0, strike: false, at: now(),
1141
+ step, attempt: redone + 1, verdict: 'refused', gap: 'a redo/rerun needs a reason', usd: 0, spendComplete: true, wallMs: 0, strike: false, at: now(),
1135
1142
  }), undefined, unjudgedCount);
1136
1143
  // Refused, re-asked for the SAME attempt — never re-runs the step.
1137
1144
  // eslint-disable-next-line no-continue
@@ -1142,7 +1149,11 @@ async function runAskSlot({
1142
1149
  recordAudit(makeAuditRow({
1143
1150
  step, attempt: redone + 1, verdict: 'green', gap: null, usd: 0, spendComplete: true, wallMs: 0, strike: false, at: now(),
1144
1151
  }), undefined, unjudgedCount);
1145
- return { type: 'accepted', artifact: currentPrior };
1152
+ return {
1153
+ type: 'accepted',
1154
+ artifact: currentPrior,
1155
+ acceptedSha256: typeof answer.artifactSha256 === 'string' ? answer.artifactSha256 : null,
1156
+ };
1146
1157
  }
1147
1158
 
1148
1159
  if (isRedo) {
@@ -1154,7 +1165,7 @@ async function runAskSlot({
1154
1165
  return {
1155
1166
  type: 'halted',
1156
1167
  outcome: 'redo-halt',
1157
- red: `redo cap ${redoCap} reached at step "${step.goal}" after ${redone} rejections`,
1168
+ red: `redo cap ${redoCap} reached at step "${step.goal}" after ${redone} redos`,
1158
1169
  };
1159
1170
  }
1160
1171
  // F48 round 4: every id in `priorStep.reads` names a STILL EARLIER step
@@ -1277,7 +1288,7 @@ async function foldFromStep({
1277
1288
  const content = contentResult.value;
1278
1289
  const filename = `${runId}-${step.emits}.json`;
1279
1290
  // eslint-disable-next-line no-await-in-loop
1280
- const sendResult = await sendStep(target, filename, content);
1291
+ const sendResult = await sendStep(target, filename, content, acceptedAskEmitsThisRun.get(askArtifactId));
1281
1292
  const sendRow = makeAuditRow({
1282
1293
  step, attempt: 1, verdict: sendResult.ok ? 'green' : 'red', gap: sendResult.ok ? null : sendResult.red, usd: 0, spendComplete: true, wallMs: 0, strike: false, at: now(),
1283
1294
  });
@@ -1368,7 +1379,7 @@ async function foldFromStep({
1368
1379
  writeArtifact(runDir, step.emits, askResult.artifact);
1369
1380
  artifacts[step.emits] = askResult.artifact;
1370
1381
  runAcceptedThisRun = true;
1371
- acceptedAskEmitsThisRun.add(step.emits);
1382
+ acceptedAskEmitsThisRun.set(step.emits, askResult.acceptedSha256 ?? null);
1372
1383
  // eslint-disable-next-line no-continue
1373
1384
  continue;
1374
1385
  }
@@ -1699,10 +1710,19 @@ export async function resumeRun({
1699
1710
  } catch (err) {
1700
1711
  return { outcome: 'refused', red: `resume: answer.json for run "${runId}" is not valid JSON — ${err.message}` };
1701
1712
  }
1713
+ // M4b amendment 3: a consumed/saved answer that says `reject` (an older
1714
+ // version's file) is read as `redo`; the file on disk is never rewritten.
1715
+ answer = { ...answer, decision: normalizeDecision(answer.decision) };
1702
1716
  if (answer.askId !== state.askId) {
1703
1717
  return { outcome: 'refused', red: `resume: answer askId "${answer.askId}" does not match open askId "${state.askId}" for run "${runId}"` };
1704
1718
  }
1705
1719
 
1720
+ // M4b amendment 2: hashes recorded by earlier-process accepts, read back
1721
+ // from the archive + consumed markers. Refused BEFORE the consume below so
1722
+ // the answer stays replayable.
1723
+ const recordedHashes = readAcceptedHashesByEmits(runDir);
1724
+ if (!recordedHashes.ok) return { outcome: 'refused', red: recordedHashes.red };
1725
+
1706
1726
  // Consume-once, BEFORE acting on the decision (F44) — the rename is
1707
1727
  // itself a one-winner gate, on top of the lock above.
1708
1728
  const consumedPath = join(runDir, `answer.${answer.askId}.consumed.json`);
@@ -1719,7 +1739,7 @@ export async function resumeRun({
1719
1739
  // review fix 2: "a pause spends nothing" means the pause adds
1720
1740
  // nothing, not that the run's total resets).
1721
1741
  appendAudit(runDir, {
1722
- step: null, attempt: null, class: null, verdict: 'ask-expired', gap: null, usd: 0, spendComplete: true, wallMs: 0, model: null, modelMatch: null, strike: false, at: now(), tokens: null, tools: null,
1742
+ step: null, attempt: null, class: null, verdict: 'ask-expired', gap: null, usd: 0, spendComplete: true, wallMs: 0, model: null, modelMatch: null, strike: false, at: now(), tokens: null, tools: null, refused: [],
1723
1743
  });
1724
1744
  appendHistory(flowDir, {
1725
1745
  runId, at: now(), outcome: 'ask-expired', spentUsd: spent.value, spendComplete: spendComplete.value, capUsd: arbiter.capUsd ?? null, wallMs: getNowMs() - runStartedAt, signatureHash: state.signatureHash,
@@ -1796,7 +1816,7 @@ export async function resumeRun({
1796
1816
  };
1797
1817
  }
1798
1818
 
1799
- if (answer.decision !== 'accept' && answer.decision !== 'reject') {
1819
+ if (answer.decision !== 'accept' && answer.decision !== 'redo') {
1800
1820
  return { outcome: 'refused', red: `resume: unrecognised decision "${answer.decision}" for run "${runId}"` };
1801
1821
  }
1802
1822
 
@@ -1812,11 +1832,13 @@ export async function resumeRun({
1812
1832
  const askLines = new Map((arbiter.asks ?? []).map((a) => [a.line, a]));
1813
1833
  const sendLines = new Map((arbiter.sends ?? []).map((s) => [s.line, s]));
1814
1834
  const askStepEmits = new Set(steps.filter((s) => askLines.has(s.fromLine)).map((s) => s.emits));
1815
- const acceptedAskEmitsThisRun = new Set();
1835
+ // M4b piece 3: Map emits -> the sha256 the human's accept recorded for that
1836
+ // ask's artifact (`null` = none recorded in THIS process; send refuses).
1837
+ const acceptedAskEmitsThisRun = new Map();
1816
1838
  for (const emits of askStepEmits) {
1817
1839
  const idx = steps.findIndex((s) => s.emits === emits);
1818
1840
  if (idx !== -1 && idx < state.stepIndex && readArtifact(runDir, emits) !== undefined) {
1819
- acceptedAskEmitsThisRun.add(emits);
1841
+ acceptedAskEmitsThisRun.set(emits, recordedHashes.byEmits.get(emits) ?? null);
1820
1842
  }
1821
1843
  }
1822
1844
 
@@ -1847,7 +1869,7 @@ export async function resumeRun({
1847
1869
  // "was this step already done" gate above; safe to collapse here.
1848
1870
  const priorArtifact = readArtifact(runDir, priorId);
1849
1871
 
1850
- const oneShotAskStep = makeOneShotThenParkAskStep({ decision: answer.decision, reason: answer.reason });
1872
+ const oneShotAskStep = makeOneShotThenParkAskStep({ decision: answer.decision, reason: answer.reason, artifactSha256: answer.artifactSha256 });
1851
1873
 
1852
1874
  const askResult = await runAskSlot({
1853
1875
  step,
@@ -1895,7 +1917,7 @@ export async function resumeRun({
1895
1917
  // send/step path completes exactly as `runFlow` would have, in-process).
1896
1918
  writeArtifact(runDir, step.emits, askResult.artifact);
1897
1919
  artifacts[step.emits] = askResult.artifact;
1898
- acceptedAskEmitsThisRun.add(step.emits);
1920
+ acceptedAskEmitsThisRun.set(step.emits, askResult.acceptedSha256 ?? null);
1899
1921
 
1900
1922
  const result = await foldFromStep({
1901
1923
  i0: state.stepIndex + 1,
package/src/send.js CHANGED
@@ -16,6 +16,7 @@ import { join } from 'node:path';
16
16
  import { createShellTools } from 'bare-agent/tools';
17
17
 
18
18
  import { checkSendDestination } from './runner.js';
19
+ import { serializeArtifact, sha256Hex } from './ask.js';
19
20
 
20
21
  const { tools: SHELL_TOOLS } = createShellTools();
21
22
  const FOUND_WRITE_TOOL = SHELL_TOOLS.find((t) => t.name === 'shell_write');
@@ -26,9 +27,12 @@ const WRITE_TOOL = FOUND_WRITE_TOOL;
26
27
  * @param {string} target - a signed arbiter target, e.g. `file:poc/m0/out`.
27
28
  * @param {string} filename
28
29
  * @param {unknown} content - JSON-serialised before writing.
30
+ * @param {string|null} [acceptedSha256] - the sha256 the human's accept recorded
31
+ * (`answerAsk`, M4b piece 3). Required: none recorded (an answer written by an
32
+ * older version, or no accept in this process) refuses by name.
29
33
  * @returns {Promise<{ok:true, path:string, bytes:number} | {ok:false, red:string}>}
30
34
  */
31
- export async function sendViaPrimitive(target, filename, content) {
35
+ export async function sendViaPrimitive(target, filename, content, acceptedSha256) {
32
36
  const destination = checkSendDestination(target);
33
37
  if (!destination.ok) return { ok: false, red: destination.red };
34
38
 
@@ -51,8 +55,21 @@ export async function sendViaPrimitive(target, filename, content) {
51
55
  return { ok: false, red: `send: content is not an artifact object (got ${JSON.stringify(content)}) — refused` };
52
56
  }
53
57
 
58
+ // M4b scope item 4 (F48 finding C): at use time, AFTER the destination
59
+ // re-checks above, hash the exact string about to be written and compare it
60
+ // to the hash the human's accept recorded. No hash recorded, or a mismatch
61
+ // (the accepted artifact changed after accept) refuses by name, before
62
+ // anything is written to the destination.
63
+ const serialised = serializeArtifact(content);
64
+ if (typeof acceptedSha256 !== 'string' || acceptedSha256.length === 0) {
65
+ return { ok: false, red: 'send: no accepted-artifact hash was recorded for this accept — refused (nothing shipped)' };
66
+ }
67
+ const actualSha256 = sha256Hex(serialised);
68
+ if (actualSha256 !== acceptedSha256) {
69
+ return { ok: false, red: `send: the artifact changed after it was accepted (accepted sha256 ${acceptedSha256}, about to send ${actualSha256}) — refused (nothing shipped)` };
70
+ }
71
+
54
72
  const path = join(destination.dir, filename);
55
- const serialised = JSON.stringify(content, null, 2);
56
73
  await WRITE_TOOL.execute({ path, content: serialised });
57
74
 
58
75
  const bytes = readFileSync(path);
package/src/types.js CHANGED
@@ -292,8 +292,8 @@
292
292
  * @property {string[]} [ungranted] - tool names the model called that this
293
293
  * step never granted; absent when empty, never an invented empty array.
294
294
  * @property {Array<{verb:string, path:string, rule:string}>} [refused] - bareguard
295
- * fs-gate refusals during this attempt; `[]` (never omitted) on every row
296
- * written by a model attempt, absent on rows with no model call.
295
+ * fs-gate refusals during this attempt; `[]` (never omitted) on every row,
296
+ * including rows with no model call (paused, cap-halt, ask, send).
297
297
  */
298
298
 
299
299
  /**
package/types/ask.d.ts CHANGED
@@ -1,3 +1,15 @@
1
+ /**
2
+ * M4b amendment 3 (SIGNED by hamr 2026-09-30): the ONE translation of a
3
+ * decision. The answer that was spelled `reject` is `redo`; `reject` is still
4
+ * understood (from the CLI, the library, or a file an older version wrote) and
5
+ * means `redo`. `accept`, `redo` and `rerun` pass. Anything else comes back
6
+ * unchanged, so each caller's existing "unrecognised decision" refusal still
7
+ * quotes what it was given. Every decision from outside, and every one read
8
+ * from disk, goes through here; nothing else may compare against the old word.
9
+ * @param {string} decision
10
+ * @returns {string}
11
+ */
12
+ export function normalizeDecision(decision: string): string;
1
13
  /**
2
14
  * @param {{ timeoutMs?: number, pollMs?: number, clock?: () => string, writeLine?: (line:string) => void }} [opts]
3
15
  * @returns {(opts:{question:string, evidence:unknown, runDir:string, ttlMs?: number}) => Promise<{decision:string, reason?:string}>}
@@ -35,13 +47,28 @@ export function readAskEvidence(ask: any): {
35
47
  why?: string;
36
48
  };
37
49
  /**
38
- * @param {{ runDir: string, askId: string, decision: 'accept'|'reject'|'rerun', reason?: string, clock?: () => string }} opts
50
+ * M4b piece 3: the ONE serialisation of an artifact's bytes — what
51
+ * `writeArtifact` (`src/runner.js`) puts on disk and what `sendViaPrimitive`
52
+ * (`src/send.js`) ships. The accept hash and the send-time re-hash are both
53
+ * over exactly this string, so they can only differ if the content does.
54
+ * @param {unknown} artifact
55
+ * @returns {string}
56
+ */
57
+ export function serializeArtifact(artifact: unknown): string;
58
+ /**
59
+ * sha256 (hex) of the bytes `serializeArtifact` yields.
60
+ * @param {string} serialised
61
+ * @returns {string}
62
+ */
63
+ export function sha256Hex(serialised: string): string;
64
+ /**
65
+ * @param {{ runDir: string, askId: string, decision: 'accept'|'redo'|'reject'|'rerun', reason?: string, clock?: () => string }} opts
39
66
  * @returns {{ ok: true } | { ok: false, red: string }}
40
67
  */
41
- export function answerAsk({ runDir, askId, decision, reason, clock, }: {
68
+ export function answerAsk({ runDir, askId, decision: givenDecision, reason, clock, }: {
42
69
  runDir: string;
43
70
  askId: string;
44
- decision: "accept" | "reject" | "rerun";
71
+ decision: "accept" | "redo" | "reject" | "rerun";
45
72
  reason?: string;
46
73
  clock?: () => string;
47
74
  }): {
@@ -68,22 +95,48 @@ export function answerAsk({ runDir, askId, decision, reason, clock, }: {
68
95
  * what is actually on disk); it is never treated as "before M4a-1" (that
69
96
  * `why` is reserved for a run with NO `asks/` directory at all).
70
97
  *
71
- * @param {{ runDir: string, askId: string, question: string, askedAt: string, expiresAt: string, evidence: unknown }} opts
98
+ * M4b amendment 2 (SIGNED by hamr 2026-09-30, F52): the record also carries
99
+ * `emits`, the step output this ask is about, so a later process can join
100
+ * the ask to its consumed answer's recorded hash (`readAcceptedHashesByEmits`).
101
+ * Written once with the rest of the record; an existing archive is never
102
+ * rewritten to add it (the `wx` create refuses).
103
+ *
104
+ * @param {{ runDir: string, askId: string, question: string, askedAt: string, expiresAt: string, evidence: unknown, emits?: string }} opts
72
105
  * @returns {{ ok: true } | { ok: false, red: string }}
73
106
  */
74
- export function writeAskArchive({ runDir, askId, question, askedAt, expiresAt, evidence, }: {
107
+ export function writeAskArchive({ runDir, askId, question, askedAt, expiresAt, evidence, emits, }: {
75
108
  runDir: string;
76
109
  askId: string;
77
110
  question: string;
78
111
  askedAt: string;
79
112
  expiresAt: string;
80
113
  evidence: unknown;
114
+ emits?: string;
81
115
  }): {
82
116
  ok: true;
83
117
  } | {
84
118
  ok: false;
85
119
  red: string;
86
120
  };
121
+ /**
122
+ * M4b amendment 2: for each archived ask that carries `emits`, joins it BY
123
+ * askId to its consumed answer and returns the recorded `artifactSha256` of
124
+ * an ACCEPT. Only `decision: accept` with a string hash counts; never
125
+ * recomputed from any file. No `emits` (old run), no marker, bad JSON, a
126
+ * redo/rerun, or a symlinked/unreadable entry contributes nothing, so the
127
+ * emits stays unrecorded and send refuses by name. Two accepts for one
128
+ * `emits` should be impossible; if seen, the result is a red, never a guess.
129
+ *
130
+ * @param {string} runDir
131
+ * @returns {{ ok: true, byEmits: Map<string, string> } | { ok: false, red: string }}
132
+ */
133
+ export function readAcceptedHashesByEmits(runDir: string): {
134
+ ok: true;
135
+ byEmits: Map<string, string>;
136
+ } | {
137
+ ok: false;
138
+ red: string;
139
+ };
87
140
  /**
88
141
  * @param {string} runDir
89
142
  * @returns {{ archived: true, asks: Array<{ askId: string, question?: string, askedAt?: string, expiresAt?: string,
@@ -109,3 +162,8 @@ export function listArchivedAsks(runDir: string): {
109
162
  archived: false;
110
163
  why: string;
111
164
  };
165
+ export namespace DECISION_STATUS {
166
+ let accept: string;
167
+ let redo: string;
168
+ let rerun: string;
169
+ }
@@ -1,3 +1,38 @@
1
+ /**
2
+ * M4b piece 2: a SAVED, not-yet-consumed answer — `answer.json` (what
3
+ * `answerAsk` writes; the resume consumes it by renaming it away, F44). Read
4
+ * through `readFileInside` (a symlinked file is "none"). `null` when there is
5
+ * none or it is unreadable/unparseable or names no askId.
6
+ * @param {string} runDir
7
+ * @returns {{askId: string, decision: string|null}|null}
8
+ */
9
+ export function readSavedAnswer(runDir: string): {
10
+ askId: string;
11
+ decision: string | null;
12
+ } | null;
13
+ /**
14
+ * M4b amendment 1 scope 2: the ONE derivation of "answer saved, resume not
15
+ * started". From the books: an answer saved (`answer.json` present) and so
16
+ * unconsumed. From the panel's in-memory attempt record (`attempt`, may be
17
+ * null): whether a resume is still being started, and the resume's own refusal.
18
+ * `null` when there is nothing to say (no saved answer and no attempt).
19
+ * @param {{savedAnswer: {askId:string, decision:string|null}|null, attempt: any}} ctx
20
+ * @returns {{state: 'starting'|'not-started'|'took-over', askId: string|null, tries: number|null, maxTries: number|null, reason: string|null, label: string}|null}
21
+ */
22
+ export function deriveResumeState({ savedAnswer, attempt }: {
23
+ savedAnswer: {
24
+ askId: string;
25
+ decision: string | null;
26
+ } | null;
27
+ attempt: any;
28
+ }): {
29
+ state: "starting" | "not-started" | "took-over";
30
+ askId: string | null;
31
+ tries: number | null;
32
+ maxTries: number | null;
33
+ reason: string | null;
34
+ label: string;
35
+ } | null;
1
36
  /**
2
37
  * The glyph + human-words label for one run — ported verbatim (in spirit,
3
38
  * from real derivation, not a shortcut) from `poc/m4/panel-data.mjs`'s
@@ -23,14 +58,18 @@
23
58
  * `resume.lock` carries no pid and nothing checks liveness (M4a's own
24
59
  * open POC question), so a crashed resumer and a live one look the same
25
60
  * on disk. Never guessed into `[✗]` or `[✓]`.
26
- * @param {{historyRow: any, askJson: any, consumedAnswerExists: boolean, hasStateJson: boolean}} ctx
61
+ * - `[·]` answer saved, resume not started / starting (M4b amendment 1) —
62
+ * `answer.json` still on disk (`resume` = `deriveResumeState`): never
63
+ * "waiting on you" (the human already answered) and never a success.
64
+ * @param {{historyRow: any, askJson: any, consumedAnswerExists: boolean, hasStateJson: boolean, resume?: any}} ctx
27
65
  * @returns {{glyph: '[✓]'|'[✗]'|'[·]'|'[!]'|'[?]', label: string}}
28
66
  */
29
- export function computeGlyph({ historyRow, askJson, consumedAnswerExists, hasStateJson, }: {
67
+ export function computeGlyph({ historyRow, askJson, consumedAnswerExists, hasStateJson, resume, }: {
30
68
  historyRow: any;
31
69
  askJson: any;
32
70
  consumedAnswerExists: boolean;
33
71
  hasStateJson: boolean;
72
+ resume?: any;
34
73
  }): {
35
74
  glyph: "[\u2713]" | "[\u2717]" | "[\u00B7]" | "[!]" | "[?]";
36
75
  label: string;
@@ -85,7 +124,7 @@ export function deriveRunModel(auditRows: any[]): string | null;
85
124
  * place that ever passes a third argument (`unjudgedCount`) into
86
125
  * `recordAudit`, so `Object.prototype.hasOwnProperty.call(row,
87
126
  * 'unjudgedCount')` is true for exactly that step's own rows (paused,
88
- * and the human's own accept/reject/rerun/refused answers) and false for
127
+ * and the human's own accept/redo/rerun/refused answers) and false for
89
128
  * every other row shape in the book — a real, always-present marker
90
129
  * (`unjudgedCount` is a number, 0 included, never omitted on an ask row),
91
130
  * never the step's close class (a NON-ask hitl step, e.g. a plain write
@@ -246,12 +285,14 @@ export function summarizeSpendRows(spendRows: any[]): {
246
285
  * Newest-first by history `at` where known; a row with no history row (died
247
286
  * or still parked) sorts after every row that has one, in flow/run order
248
287
  * (a real ordering, never `Date.now()` guessed in for a missing `at`).
249
- * @param {{root: string, catalogue: any}} opts
288
+ * @param {{root: string, catalogue: any, resumeAttempt?: (flow: string, runId: string) => any}} opts
289
+ * `resumeAttempt`: the panel's in-memory resume-attempt lookup (M4b piece 2); absent = none.
250
290
  * @returns {any[]}
251
291
  */
252
- export function listRuns({ root, catalogue }: {
292
+ export function listRuns({ root, catalogue, resumeAttempt }: {
253
293
  root: string;
254
294
  catalogue: any;
295
+ resumeAttempt?: (flow: string, runId: string) => any;
255
296
  }): any[];
256
297
  /**
257
298
  * `GET /api/runs/:flow/:runId` — the Run tab (M4a scope item 2): the step
@@ -260,14 +301,15 @@ export function listRuns({ root, catalogue }: {
260
301
  * `log.json`. `null` when the flow/runId doesn't resolve to a real run
261
302
  * directory at all (caller renders 404); a `red` field names why a
262
303
  * sub-derivation couldn't fill (never invented).
263
- * @param {{root: string, flow: string, runId: string, catalogue: any}} opts
304
+ * @param {{root: string, flow: string, runId: string, catalogue: any, resumeAttempt?: (flow: string, runId: string) => any}} opts
264
305
  * @returns {any|null}
265
306
  */
266
- export function getRunDetail({ root, flow, runId, catalogue, }: {
307
+ export function getRunDetail({ root, flow, runId, catalogue, resumeAttempt, }: {
267
308
  root: string;
268
309
  flow: string;
269
310
  runId: string;
270
311
  catalogue: any;
312
+ resumeAttempt?: (flow: string, runId: string) => any;
271
313
  }): any | null;
272
314
  /**
273
315
  * `GET /api/runs/:flow/:runId/audit` — the Audit/logs tab (M4a scope item
@@ -397,18 +439,23 @@ export function deriveAskStepInfo(orderedAsks: any[], auditRows: any[], declStep
397
439
  * 3" — a plain array position, not derived from any book) and `stepName`/
398
440
  * `stepLine`/`stepWhy` (`deriveAskStepInfo`) so the Ask tab's header can
399
441
  * name which ask is open without the client re-deriving any of it.
400
- * @param {{root: string, flow: string, runId: string, catalogue: any}} opts
401
- * @returns {{flow:string, runId:string, asks:any[]}|null}
442
+ * M4b piece 4: also carries `resume` (the SAME `deriveResumeState` the run
443
+ * detail carries, `null` for a finished run or nothing to say) so the Ask tab
444
+ * can tell "open, answerable" from "answer saved" without a second fetch.
445
+ * @param {{root: string, flow: string, runId: string, catalogue: any, resumeAttempt?: (flow: string, runId: string) => any}} opts
446
+ * @returns {{flow:string, runId:string, asks:any[], resume: any}|null}
402
447
  */
403
- export function getRunAsks({ root, flow, runId, catalogue, }: {
448
+ export function getRunAsks({ root, flow, runId, catalogue, resumeAttempt, }: {
404
449
  root: string;
405
450
  flow: string;
406
451
  runId: string;
407
452
  catalogue: any;
453
+ resumeAttempt?: (flow: string, runId: string) => any;
408
454
  }): {
409
455
  flow: string;
410
456
  runId: string;
411
457
  asks: any[];
458
+ resume: any;
412
459
  } | null;
413
460
  /**
414
461
  * `GET /api/inbox` — every stop (parked ask, open or past) across every
@@ -425,9 +472,13 @@ export function getRunAsks({ root, flow, runId, catalogue, }: {
425
472
  * force-`false` here as a second, independent check (belt-and-braces on the
426
473
  * one thing the brief calls out by name: "the Inbox tab's open count counts
427
474
  * only truly open asks — parked run, no history row, unexpired, unanswered").
428
- * @param {{root: string}} opts
475
+ * @param {{root: string, resumeAttempt?: (flow: string, runId: string) => any}} opts
429
476
  * @returns {any[]}
430
477
  */
431
- export function listStops({ root }: {
478
+ export function listStops({ root, resumeAttempt }: {
432
479
  root: string;
480
+ resumeAttempt?: (flow: string, runId: string) => any;
433
481
  }): any[];
482
+ /** What the `resume` field says when the panel has no attempt record for a run
483
+ * (it restarted since the answer was saved) — said so, never blank. */
484
+ export const RESUME_REASON_UNKNOWN: "reason unknown: the panel restarted, so it has no record of the resume attempt";
@@ -0,0 +1,51 @@
1
+ /**
2
+ * @param {{ root: string, env?: Record<string, string|undefined>, bin?: string, logDir?: string,
3
+ * maxTries?: number, windowMs?: number, slotMs?: number }} opts
4
+ * `env`/`bin`/`logDir`/`maxTries`/`windowMs`/`slotMs` are injectable so tests neither sleep 10 s
5
+ * nor need a live key; production passes none of them. `slotMs` (default `windowMs / maxTries`,
6
+ * i.e. 2000 ms) is only the spacing between tries: a test sets it small and `windowMs` (the
7
+ * per-try "did it take over" deadline) large, so CPU load cannot turn a slow child start into a
8
+ * false "stuck".
9
+ */
10
+ export function createResumer(opts: {
11
+ root: string;
12
+ env?: Record<string, string | undefined>;
13
+ bin?: string;
14
+ logDir?: string;
15
+ maxTries?: number;
16
+ windowMs?: number;
17
+ slotMs?: number;
18
+ }): {
19
+ /**
20
+ * Start the detached resume for a saved answer and return at once with the
21
+ * attempt record (a copy); the verify/retry loop runs in the background.
22
+ * @param {{ flow: string, runId: string, runDir: string, askId: string }} a
23
+ */
24
+ start({ flow, runId, runDir, askId, }: {
25
+ flow: string;
26
+ runId: string;
27
+ runDir: string;
28
+ askId: string;
29
+ }): {
30
+ flow: string;
31
+ runId: string;
32
+ askId: string;
33
+ state: string;
34
+ tries: number;
35
+ maxTries: number;
36
+ windowMs: number;
37
+ refusal: null;
38
+ startedAt: number;
39
+ endedAt: null;
40
+ logPath: null;
41
+ superseded: boolean;
42
+ };
43
+ /** A copy of the run's attempt record, or null (none yet, or the panel restarted).
44
+ * @param {string} flow @param {string} runId */
45
+ get(flow: string, runId: string): any;
46
+ /** Every log file this resumer has written (for tests and hygiene checks). */
47
+ logPaths(): any[];
48
+ };
49
+ /** Signed with M4b amendment 1, scope 1: up to 5 tries within 10 seconds. */
50
+ export const RESUME_MAX_TRIES: 5;
51
+ export const RESUME_WINDOW_MS: 10000;
@@ -1,14 +1,16 @@
1
1
  /**
2
- * Handle one request against the read-only API + the page. Exported
2
+ * Handle one request against the API + the page. Exported
3
3
  * separately from {@link createPanelServer} so tests can drive it without a
4
4
  * real listening socket where that is simpler.
5
5
  * @param {import('node:http').IncomingMessage} req
6
6
  * @param {import('node:http').ServerResponse} res
7
- * @param {{ root: string, port: number }} opts
7
+ * @param {{ root: string, port: number, token: string, resumer: ReturnType<typeof createResumer> }} opts
8
8
  */
9
9
  export function handleRequest(req: import("node:http").IncomingMessage, res: import("node:http").ServerResponse, opts: {
10
10
  root: string;
11
11
  port: number;
12
+ token: string;
13
+ resumer: ReturnType<typeof createResumer>;
12
14
  }): void;
13
15
  /**
14
16
  * Start the panel server. Binds `127.0.0.1` ONLY. A taken port is a LOUD,
@@ -16,12 +18,21 @@ export function handleRequest(req: import("node:http").IncomingMessage, res: imp
16
18
  * header). Resolves once actually listening; rejects on a bind error
17
19
  * (including `EADDRINUSE`) with a `.port` field on the error for the
18
20
  * caller's message.
19
- * @param {{ port?: number, root: string }} opts
21
+ * @param {{ port?: number, root: string, resume?: { env?: Record<string,string|undefined>, bin?: string, logDir?: string, maxTries?: number, windowMs?: number, slotMs?: number } }} opts
22
+ * `resume` is for tests only (a fake env/bin, a short retry window); the CLI passes none.
20
23
  * @returns {Promise<{ server: import('node:http').Server, port: number, close: () => Promise<void> }>}
21
24
  */
22
25
  export function createPanelServer(opts: {
23
26
  port?: number;
24
27
  root: string;
28
+ resume?: {
29
+ env?: Record<string, string | undefined>;
30
+ bin?: string;
31
+ logDir?: string;
32
+ maxTries?: number;
33
+ windowMs?: number;
34
+ slotMs?: number;
35
+ };
25
36
  }): Promise<{
26
37
  server: import("node:http").Server;
27
38
  port: number;
@@ -43,3 +54,4 @@ export function panelMain(argv: string[], ctx: {
43
54
  * is 4800 — bareloop owns 4700, and the two panels must be able to run
44
55
  * side by side. */
45
56
  export const DEFAULT_PORT: 4800;
57
+ import { createResumer } from './resume.js';