fwdloop 0.8.1 → 0.10.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,10 +48,15 @@ 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, answerTiming,
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';
57
+ import {
58
+ readResumeLock, recordPid, writeLockHolder, LOCK_NO_HOLDER,
59
+ } from './liveness.js';
55
60
 
56
61
  const __dirname = dirname(fileURLToPath(import.meta.url));
57
62
  const REPO_ROOT = resolve(__dirname, '..');
@@ -386,7 +391,7 @@ export function writeArtifact(runDir, id, artifact, { overwrite = false } = {})
386
391
  if (existsSync(target) && !overwrite) {
387
392
  throw new Error(`writeArtifact: artifact "${id}" already exists in this run (${target}) — refused`);
388
393
  }
389
- writeFileSync(target, JSON.stringify(artifact, null, 2));
394
+ writeFileSync(target, serializeArtifact(artifact));
390
395
  }
391
396
 
392
397
  /**
@@ -751,8 +756,8 @@ async function runStepRalph({
751
756
  * @param {Array<{id:string, path:string}>} opts.sources - the real files to freeze for this run.
752
757
  * @param {unknown} opts.catalogue - passed straight through to `readFlow`.
753
758
  * @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
754
- * @param {(opts:{question:string, evidence:unknown, runDir:string}) => Promise<{decision:'accept'|'reject'|'rerun'|'timeout'|'park', reason?:string}>} opts.askStep
755
- * @param {(target:string, filename:string, content:unknown) => Promise<{ok:boolean, red?:string, bytes?:number}>} opts.sendStep
759
+ * @param {(opts:{question:string, evidence:unknown, runDir:string}) => Promise<{decision:'accept'|'redo'|'rerun'|'timeout'|'park', reason?:string, artifactSha256?:string}>} opts.askStep
760
+ * @param {(target:string, filename:string, content:unknown, acceptedSha256?:string|null) => Promise<{ok:boolean, red?:string, bytes?:number}>} opts.sendStep
756
761
  * @param {Record<string, any>} [opts.primitives] - injected primitive implementations, keyed by catalogue verb.
757
762
  * @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.
758
763
  * @param {() => string} [opts.clock] - returns the current ISO timestamp; defaults to the wall clock.
@@ -854,6 +859,8 @@ export async function runFlow({
854
859
  flowDir, runDir, runId, capUsd, startedAt, now, nowMs: getNowMs, signatureHash: signature.flow, outcome: 'preflight-red', red: frozen.red, spent: { value: 0 },
855
860
  });
856
861
  }
862
+ // M4c: every guard above has passed — this process records itself (pid row) before its first step.
863
+ recordPid(runDir, 'run', now());
857
864
 
858
865
  const artifacts = {};
859
866
  const auditRows = [];
@@ -902,7 +909,9 @@ export async function runFlow({
902
909
  const askStepEmits = new Set(steps.filter((s) => askLines.has(s.fromLine)).map((s) => s.emits));
903
910
  // Tracks which specific ask emits were accepted THIS run (acceptedThisRun
904
911
  // above stays run-wide, for the "reached with no accept this run" gate).
905
- const acceptedAskEmitsThisRun = new Set();
912
+ // M4b piece 3: Map emits -> the sha256 the human's accept recorded for that
913
+ // ask's artifact (`null` = none recorded in THIS process; send refuses).
914
+ const acceptedAskEmitsThisRun = new Map();
906
915
 
907
916
  const result = await foldFromStep({
908
917
  i0: 0,
@@ -980,16 +989,16 @@ export function makeParkingAskStep() {
980
989
 
981
990
  /** `resumeRun`'s own askStep: yields the human's already-consumed decision
982
991
  * exactly once (for the ask it was built for), then — if that decision was
983
- * a reject and the ask loops back around to ask again — parks under a NEW
992
+ * a redo and the ask loops back around to ask again — parks under a NEW
984
993
  * askId, exactly like a fresh ask would. This is what turns "redo, then
985
994
  * ask again" into "redo, then re-park" for a resumed run, with no second
986
995
  * code path. */
987
- function makeOneShotThenParkAskStep({ decision, reason }) {
996
+ function makeOneShotThenParkAskStep({ decision, reason, artifactSha256 }) {
988
997
  let used = false;
989
998
  return async function resumeAskStep() {
990
999
  if (!used) {
991
1000
  used = true;
992
- return { decision, reason };
1001
+ return { decision, reason, artifactSha256 };
993
1002
  }
994
1003
  return { decision: 'park' };
995
1004
  };
@@ -1026,9 +1035,11 @@ async function runAskSlot({
1026
1035
  for (;;) {
1027
1036
  const evidence = { artifact: currentPrior, unjudged: evidenceUnjudged };
1028
1037
  // eslint-disable-next-line no-await-in-loop
1029
- const answer = await askStep({
1038
+ const rawAnswer = await askStep({
1030
1039
  question: askSlot?.question ?? step.goal, evidence, runDir, ttlMs: askSlot?.ttlMs, stepIndex,
1031
1040
  });
1041
+ // M4b amendment 3: a decision from any askStep is translated once, here.
1042
+ const answer = { ...rawAnswer, decision: normalizeDecision(rawAnswer.decision) };
1032
1043
 
1033
1044
  if (answer.decision === 'park') {
1034
1045
  // M3 scope item 1 (fixes F43): the wait is ALWAYS the signed ttlMs —
@@ -1040,7 +1051,7 @@ async function runAskSlot({
1040
1051
  // human sees in-process (`makeFileAskStep`'s `{ artifact, unjudged }`)
1041
1052
  // — the draft under review and the unjudged evidence, never just the
1042
1053
  // question. `evidence` above is already recomputed at the top of every
1043
- // loop iteration (including a re-park after a reject, where
1054
+ // loop iteration (including a re-park after a redo, where
1044
1055
  // `currentPrior` is the just-redrafted artifact), so this write always
1045
1056
  // carries the CURRENT evidence, not a stale first-park copy.
1046
1057
  writeFileSync(join(runDir, 'ask.json'), JSON.stringify({
@@ -1058,7 +1069,7 @@ async function runAskSlot({
1058
1069
  // is a genuine invariant violation, not a race to recover from — it
1059
1070
  // halts the run rather than silently dropping the archive duty.
1060
1071
  const archived = writeAskArchive({
1061
- runDir, askId, question: askSlot?.question ?? step.goal, askedAt, expiresAt, evidence,
1072
+ runDir, askId, question: askSlot?.question ?? step.goal, askedAt, expiresAt, evidence, emits: step.emits,
1062
1073
  });
1063
1074
  if (!archived.ok) {
1064
1075
  throw new Error(archived.red);
@@ -1127,12 +1138,12 @@ async function runAskSlot({
1127
1138
  };
1128
1139
  }
1129
1140
 
1130
- const isRedo = answer.decision === 'reject' || answer.decision === 'rerun';
1141
+ const isRedo = answer.decision === 'redo' || answer.decision === 'rerun';
1131
1142
  const reason = typeof answer.reason === 'string' ? answer.reason.trim() : '';
1132
1143
 
1133
1144
  if (isRedo && reason.length === 0) {
1134
1145
  recordAudit(makeAuditRow({
1135
- step, attempt: redone + 1, verdict: 'refused', gap: 'a rejection/rerun needs a reason', usd: 0, spendComplete: true, wallMs: 0, strike: false, at: now(),
1146
+ step, attempt: redone + 1, verdict: 'refused', gap: 'a redo/rerun needs a reason', usd: 0, spendComplete: true, wallMs: 0, strike: false, at: now(),
1136
1147
  }), undefined, unjudgedCount);
1137
1148
  // Refused, re-asked for the SAME attempt — never re-runs the step.
1138
1149
  // eslint-disable-next-line no-continue
@@ -1143,7 +1154,11 @@ async function runAskSlot({
1143
1154
  recordAudit(makeAuditRow({
1144
1155
  step, attempt: redone + 1, verdict: 'green', gap: null, usd: 0, spendComplete: true, wallMs: 0, strike: false, at: now(),
1145
1156
  }), undefined, unjudgedCount);
1146
- return { type: 'accepted', artifact: currentPrior };
1157
+ return {
1158
+ type: 'accepted',
1159
+ artifact: currentPrior,
1160
+ acceptedSha256: typeof answer.artifactSha256 === 'string' ? answer.artifactSha256 : null,
1161
+ };
1147
1162
  }
1148
1163
 
1149
1164
  if (isRedo) {
@@ -1155,7 +1170,7 @@ async function runAskSlot({
1155
1170
  return {
1156
1171
  type: 'halted',
1157
1172
  outcome: 'redo-halt',
1158
- red: `redo cap ${redoCap} reached at step "${step.goal}" after ${redone} rejections`,
1173
+ red: `redo cap ${redoCap} reached at step "${step.goal}" after ${redone} redos`,
1159
1174
  };
1160
1175
  }
1161
1176
  // F48 round 4: every id in `priorStep.reads` names a STILL EARLIER step
@@ -1278,7 +1293,7 @@ async function foldFromStep({
1278
1293
  const content = contentResult.value;
1279
1294
  const filename = `${runId}-${step.emits}.json`;
1280
1295
  // eslint-disable-next-line no-await-in-loop
1281
- const sendResult = await sendStep(target, filename, content);
1296
+ const sendResult = await sendStep(target, filename, content, acceptedAskEmitsThisRun.get(askArtifactId));
1282
1297
  const sendRow = makeAuditRow({
1283
1298
  step, attempt: 1, verdict: sendResult.ok ? 'green' : 'red', gap: sendResult.ok ? null : sendResult.red, usd: 0, spendComplete: true, wallMs: 0, strike: false, at: now(),
1284
1299
  });
@@ -1369,7 +1384,7 @@ async function foldFromStep({
1369
1384
  writeArtifact(runDir, step.emits, askResult.artifact);
1370
1385
  artifacts[step.emits] = askResult.artifact;
1371
1386
  runAcceptedThisRun = true;
1372
- acceptedAskEmitsThisRun.add(step.emits);
1387
+ acceptedAskEmitsThisRun.set(step.emits, askResult.acceptedSha256 ?? null);
1373
1388
  // eslint-disable-next-line no-continue
1374
1389
  continue;
1375
1390
  }
@@ -1465,11 +1480,59 @@ function sumAuditUsd(runDir) {
1465
1480
  return { ok: true, total };
1466
1481
  }
1467
1482
 
1483
+ /**
1484
+ * M4c amendment 2 (d): create `resume.lock` with `wx` and write the holder into it.
1485
+ * An existing lock is read: holder alive (or cannot be told) -> refuse by name
1486
+ * ("locked by another resumer", the panel's one retried refusal); no readable
1487
+ * holder -> refuse by name with the lock path; holder gone -> unlink and retake
1488
+ * with `wx` once (a racing second taker loses cleanly on EEXIST).
1489
+ * @returns {Promise<{ok:true, lockFd:number}|{ok:false, red:string}>}
1490
+ */
1491
+ async function takeResumeLock(runDir, runId, lockPath) {
1492
+ for (let attempt = 0; attempt < 2; attempt += 1) {
1493
+ try {
1494
+ const lockFd = openSync(lockPath, 'wx');
1495
+ try { writeLockHolder(lockFd); } catch (err) {
1496
+ try { closeSync(lockFd); } catch { /* ignore */ }
1497
+ try { unlinkSync(lockPath); } catch { /* ignore */ }
1498
+ return { ok: false, red: `resume: could not record the lock holder in ${lockPath} — ${err.message}` };
1499
+ }
1500
+ return { ok: true, lockFd };
1501
+ } catch (err) {
1502
+ if (err.code !== 'EEXIST') return { ok: false, red: `resume: could not create lock ${lockPath} — ${err.message}` };
1503
+ }
1504
+ let lock = readResumeLock(runDir);
1505
+ if (lock.state === 'empty') {
1506
+ // A taker between its `wx` create and its holder write looks empty for an instant.
1507
+ // eslint-disable-next-line no-await-in-loop
1508
+ await new Promise((r) => { setTimeout(r, 150); });
1509
+ lock = readResumeLock(runDir);
1510
+ }
1511
+ if (lock.state === 'live' || lock.state === 'unknown') {
1512
+ return { ok: false, red: `resume: run "${runId}" is locked by another resumer (pid ${lock.pid}, ${lockPath})` };
1513
+ }
1514
+ if (lock.state === 'empty') {
1515
+ return { ok: false, red: `resume: run "${runId}" has a resume lock ${LOCK_NO_HOLDER} (${lockPath}) — it predates the holder record, so it cannot be told apart from a live resume; remove that file by hand if no resume is running` };
1516
+ }
1517
+ if (lock.state === 'dead') {
1518
+ // Re-read right before the unlink: a racing taker may have cleared this lock and retaken it
1519
+ // already, and must not lose its fresh lock. The window left is one syscall wide, and the
1520
+ // answer's rename-to-consume (F44) still lets only one resume act on the answer.
1521
+ const again = readResumeLock(runDir);
1522
+ if (again.state === 'dead' && again.pid === lock.pid) {
1523
+ try { unlinkSync(lockPath); } catch { /* another taker already cleared it: retry wx */ }
1524
+ }
1525
+ }
1526
+ }
1527
+ return { ok: false, red: `resume: run "${runId}" is locked by another resumer (${lockPath})` };
1528
+ }
1529
+
1468
1530
  /**
1469
1531
  * M3 scope items 4-6: re-enter a parked run's SAME fold from a separate
1470
- * process. Takes an exclusive `resume.lock` (refuses by name if already
1471
- * held; a lock left behind by a killed resumer is a red naming it, never
1472
- * stolen), re-reads the flow, refuses by name at $0 on any signature/input/
1532
+ * process. Takes an exclusive `resume.lock` that records its holder's
1533
+ * `{pid, procStart}` (M4c amendment 2: refuses by name if the holder is alive
1534
+ * or the lock has no readable holder; a lock whose holder is gone is cleared
1535
+ * and retaken, losing cleanly on a race), re-reads the flow, refuses by name at $0 on any signature/input/
1473
1536
  * missing-artifact mismatch, consumes `answer.json` by atomic rename BEFORE
1474
1537
  * acting (F44), then either cancels an expired ask ($0, nothing sent) or
1475
1538
  * resolves it and folds on to `complete`/the next pause/a halt.
@@ -1530,15 +1593,9 @@ export async function resumeRun({
1530
1593
 
1531
1594
  const lockPath = join(runDir, 'resume.lock');
1532
1595
 
1533
- let lockFd;
1534
- try {
1535
- lockFd = openSync(lockPath, 'wx');
1536
- } catch (err) {
1537
- if (err.code === 'EEXIST') {
1538
- return { outcome: 'refused', red: `resume: run "${runId}" is locked by another resumer (${lockPath})` };
1539
- }
1540
- return { outcome: 'refused', red: `resume: could not create lock ${lockPath} — ${err.message}` };
1541
- }
1596
+ const took = await takeResumeLock(runDir, runId, lockPath);
1597
+ if (!took.ok) return { outcome: 'refused', red: took.red };
1598
+ const { lockFd } = took;
1542
1599
 
1543
1600
  try {
1544
1601
  const statePath = join(runDir, 'state.json');
@@ -1700,20 +1757,36 @@ export async function resumeRun({
1700
1757
  } catch (err) {
1701
1758
  return { outcome: 'refused', red: `resume: answer.json for run "${runId}" is not valid JSON — ${err.message}` };
1702
1759
  }
1760
+ // M4b amendment 3: a consumed/saved answer that says `reject` (an older
1761
+ // version's file) is read as `redo`; the file on disk is never rewritten.
1762
+ answer = { ...answer, decision: normalizeDecision(answer.decision) };
1703
1763
  if (answer.askId !== state.askId) {
1704
1764
  return { outcome: 'refused', red: `resume: answer askId "${answer.askId}" does not match open askId "${state.askId}" for run "${runId}"` };
1705
1765
  }
1706
1766
 
1767
+ // M4c amendment 3: an answer's saved time, never the restart's clock, says whether it was on time. A missing or
1768
+ // unreadable one is refused by name here, before the consume, so the answer stays replayable.
1769
+ const timing = answerTiming(answer.answeredAt, state.expiresAt);
1770
+ if (timing === 'unreadable') {
1771
+ return { outcome: 'refused', red: `resume: answer.json for run "${runId}" has a missing or unreadable answeredAt ("${answer.answeredAt}") — refusing rather than treating it as on time` };
1772
+ }
1773
+
1774
+ // M4b amendment 2: hashes recorded by earlier-process accepts, read back
1775
+ // from the archive + consumed markers. Refused BEFORE the consume below so
1776
+ // the answer stays replayable.
1777
+ const recordedHashes = readAcceptedHashesByEmits(runDir);
1778
+ if (!recordedHashes.ok) return { outcome: 'refused', red: recordedHashes.red };
1779
+
1707
1780
  // Consume-once, BEFORE acting on the decision (F44) — the rename is
1708
1781
  // itself a one-winner gate, on top of the lock above.
1709
1782
  const consumedPath = join(runDir, `answer.${answer.askId}.consumed.json`);
1710
1783
  renameSync(answerPath, consumedPath);
1784
+ // M4c: the answer is ours and every guard has passed — record this resume process before its first step.
1785
+ recordPid(runDir, 'resume', now());
1711
1786
 
1712
- // The run's own injected clock governs expiry, exactly like every other
1713
- // "now" in this module (never the bare wall clock) — the same fixed
1714
- // clock a test controls for `runFlow` also controls what "expired" means
1715
- // for `resumeRun`, with no real wait required to prove it.
1716
- if (Date.parse(now()) > Date.parse(state.expiresAt)) {
1787
+ // M4c amendment 3: expiry is when the answer was SAVED against the deadline (`timing`, above),
1788
+ // not this process's clock at restart.
1789
+ if (timing === 'late') {
1717
1790
  // Negative (i): an answer arriving after expiry cancels the run —
1718
1791
  // adds NOTHING further, but the run's own already-spent total is
1719
1792
  // real money and must be reported, never coerced to 0 (orchestrator
@@ -1797,7 +1870,7 @@ export async function resumeRun({
1797
1870
  };
1798
1871
  }
1799
1872
 
1800
- if (answer.decision !== 'accept' && answer.decision !== 'reject') {
1873
+ if (answer.decision !== 'accept' && answer.decision !== 'redo') {
1801
1874
  return { outcome: 'refused', red: `resume: unrecognised decision "${answer.decision}" for run "${runId}"` };
1802
1875
  }
1803
1876
 
@@ -1813,11 +1886,13 @@ export async function resumeRun({
1813
1886
  const askLines = new Map((arbiter.asks ?? []).map((a) => [a.line, a]));
1814
1887
  const sendLines = new Map((arbiter.sends ?? []).map((s) => [s.line, s]));
1815
1888
  const askStepEmits = new Set(steps.filter((s) => askLines.has(s.fromLine)).map((s) => s.emits));
1816
- const acceptedAskEmitsThisRun = new Set();
1889
+ // M4b piece 3: Map emits -> the sha256 the human's accept recorded for that
1890
+ // ask's artifact (`null` = none recorded in THIS process; send refuses).
1891
+ const acceptedAskEmitsThisRun = new Map();
1817
1892
  for (const emits of askStepEmits) {
1818
1893
  const idx = steps.findIndex((s) => s.emits === emits);
1819
1894
  if (idx !== -1 && idx < state.stepIndex && readArtifact(runDir, emits) !== undefined) {
1820
- acceptedAskEmitsThisRun.add(emits);
1895
+ acceptedAskEmitsThisRun.set(emits, recordedHashes.byEmits.get(emits) ?? null);
1821
1896
  }
1822
1897
  }
1823
1898
 
@@ -1848,7 +1923,7 @@ export async function resumeRun({
1848
1923
  // "was this step already done" gate above; safe to collapse here.
1849
1924
  const priorArtifact = readArtifact(runDir, priorId);
1850
1925
 
1851
- const oneShotAskStep = makeOneShotThenParkAskStep({ decision: answer.decision, reason: answer.reason });
1926
+ const oneShotAskStep = makeOneShotThenParkAskStep({ decision: answer.decision, reason: answer.reason, artifactSha256: answer.artifactSha256 });
1852
1927
 
1853
1928
  const askResult = await runAskSlot({
1854
1929
  step,
@@ -1896,7 +1971,7 @@ export async function resumeRun({
1896
1971
  // send/step path completes exactly as `runFlow` would have, in-process).
1897
1972
  writeArtifact(runDir, step.emits, askResult.artifact);
1898
1973
  artifacts[step.emits] = askResult.artifact;
1899
- acceptedAskEmitsThisRun.add(step.emits);
1974
+ acceptedAskEmitsThisRun.set(step.emits, askResult.acceptedSha256 ?? null);
1900
1975
 
1901
1976
  const result = await foldFromStep({
1902
1977
  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/types/ask.d.ts CHANGED
@@ -1,3 +1,27 @@
1
+ /**
2
+ * M4c amendment 3: the ONE rule for "was this answer saved in time" — the
3
+ * answer's own saved time (`answeredAt`, written by `answerAsk`) against the
4
+ * ask's deadline, never the clock at the moment a resume restarts.
5
+ * on-time - answeredAt parses and is not after expiresAt
6
+ * late - answeredAt parses and is after expiresAt
7
+ * unreadable - answeredAt or expiresAt missing/unparseable: never on time
8
+ * @param {unknown} answeredAt
9
+ * @param {unknown} expiresAt
10
+ * @returns {'on-time'|'late'|'unreadable'}
11
+ */
12
+ export function answerTiming(answeredAt: unknown, expiresAt: unknown): "on-time" | "late" | "unreadable";
13
+ /**
14
+ * M4b amendment 3 (SIGNED by hamr 2026-09-30): the ONE translation of a
15
+ * decision. The answer that was spelled `reject` is `redo`; `reject` is still
16
+ * understood (from the CLI, the library, or a file an older version wrote) and
17
+ * means `redo`. `accept`, `redo` and `rerun` pass. Anything else comes back
18
+ * unchanged, so each caller's existing "unrecognised decision" refusal still
19
+ * quotes what it was given. Every decision from outside, and every one read
20
+ * from disk, goes through here; nothing else may compare against the old word.
21
+ * @param {string} decision
22
+ * @returns {string}
23
+ */
24
+ export function normalizeDecision(decision: string): string;
1
25
  /**
2
26
  * @param {{ timeoutMs?: number, pollMs?: number, clock?: () => string, writeLine?: (line:string) => void }} [opts]
3
27
  * @returns {(opts:{question:string, evidence:unknown, runDir:string, ttlMs?: number}) => Promise<{decision:string, reason?:string}>}
@@ -35,13 +59,28 @@ export function readAskEvidence(ask: any): {
35
59
  why?: string;
36
60
  };
37
61
  /**
38
- * @param {{ runDir: string, askId: string, decision: 'accept'|'reject'|'rerun', reason?: string, clock?: () => string }} opts
62
+ * M4b piece 3: the ONE serialisation of an artifact's bytes — what
63
+ * `writeArtifact` (`src/runner.js`) puts on disk and what `sendViaPrimitive`
64
+ * (`src/send.js`) ships. The accept hash and the send-time re-hash are both
65
+ * over exactly this string, so they can only differ if the content does.
66
+ * @param {unknown} artifact
67
+ * @returns {string}
68
+ */
69
+ export function serializeArtifact(artifact: unknown): string;
70
+ /**
71
+ * sha256 (hex) of the bytes `serializeArtifact` yields.
72
+ * @param {string} serialised
73
+ * @returns {string}
74
+ */
75
+ export function sha256Hex(serialised: string): string;
76
+ /**
77
+ * @param {{ runDir: string, askId: string, decision: 'accept'|'redo'|'reject'|'rerun', reason?: string, clock?: () => string }} opts
39
78
  * @returns {{ ok: true } | { ok: false, red: string }}
40
79
  */
41
- export function answerAsk({ runDir, askId, decision, reason, clock, }: {
80
+ export function answerAsk({ runDir, askId, decision: givenDecision, reason, clock, }: {
42
81
  runDir: string;
43
82
  askId: string;
44
- decision: "accept" | "reject" | "rerun";
83
+ decision: "accept" | "redo" | "reject" | "rerun";
45
84
  reason?: string;
46
85
  clock?: () => string;
47
86
  }): {
@@ -68,22 +107,48 @@ export function answerAsk({ runDir, askId, decision, reason, clock, }: {
68
107
  * what is actually on disk); it is never treated as "before M4a-1" (that
69
108
  * `why` is reserved for a run with NO `asks/` directory at all).
70
109
  *
71
- * @param {{ runDir: string, askId: string, question: string, askedAt: string, expiresAt: string, evidence: unknown }} opts
110
+ * M4b amendment 2 (SIGNED by hamr 2026-09-30, F52): the record also carries
111
+ * `emits`, the step output this ask is about, so a later process can join
112
+ * the ask to its consumed answer's recorded hash (`readAcceptedHashesByEmits`).
113
+ * Written once with the rest of the record; an existing archive is never
114
+ * rewritten to add it (the `wx` create refuses).
115
+ *
116
+ * @param {{ runDir: string, askId: string, question: string, askedAt: string, expiresAt: string, evidence: unknown, emits?: string }} opts
72
117
  * @returns {{ ok: true } | { ok: false, red: string }}
73
118
  */
74
- export function writeAskArchive({ runDir, askId, question, askedAt, expiresAt, evidence, }: {
119
+ export function writeAskArchive({ runDir, askId, question, askedAt, expiresAt, evidence, emits, }: {
75
120
  runDir: string;
76
121
  askId: string;
77
122
  question: string;
78
123
  askedAt: string;
79
124
  expiresAt: string;
80
125
  evidence: unknown;
126
+ emits?: string;
81
127
  }): {
82
128
  ok: true;
83
129
  } | {
84
130
  ok: false;
85
131
  red: string;
86
132
  };
133
+ /**
134
+ * M4b amendment 2: for each archived ask that carries `emits`, joins it BY
135
+ * askId to its consumed answer and returns the recorded `artifactSha256` of
136
+ * an ACCEPT. Only `decision: accept` with a string hash counts; never
137
+ * recomputed from any file. No `emits` (old run), no marker, bad JSON, a
138
+ * redo/rerun, or a symlinked/unreadable entry contributes nothing, so the
139
+ * emits stays unrecorded and send refuses by name. Two accepts for one
140
+ * `emits` should be impossible; if seen, the result is a red, never a guess.
141
+ *
142
+ * @param {string} runDir
143
+ * @returns {{ ok: true, byEmits: Map<string, string> } | { ok: false, red: string }}
144
+ */
145
+ export function readAcceptedHashesByEmits(runDir: string): {
146
+ ok: true;
147
+ byEmits: Map<string, string>;
148
+ } | {
149
+ ok: false;
150
+ red: string;
151
+ };
87
152
  /**
88
153
  * @param {string} runDir
89
154
  * @returns {{ archived: true, asks: Array<{ askId: string, question?: string, askedAt?: string, expiresAt?: string,
@@ -109,3 +174,8 @@ export function listArchivedAsks(runDir: string): {
109
174
  archived: false;
110
175
  why: string;
111
176
  };
177
+ export namespace DECISION_STATUS {
178
+ let accept: string;
179
+ let redo: string;
180
+ let rerun: string;
181
+ }
package/types/books.d.ts CHANGED
@@ -1,3 +1,22 @@
1
+ /**
2
+ * M4c piece 1: the ONE writer of a run dir's `pids.jsonl` — append-only, never
3
+ * rewritten, not a book the arbiter reads. One row per process that works on
4
+ * the run (`src/liveness.js` `recordPid` builds the row).
5
+ * @param {string} runDir
6
+ * @param {{pid: number, startedAt: string, procStart: string|null, leg: 'run'|'resume'}} row
7
+ */
8
+ export function appendPidRow(runDir: string, row: {
9
+ pid: number;
10
+ startedAt: string;
11
+ procStart: string | null;
12
+ leg: "run" | "resume";
13
+ }): void;
14
+ /**
15
+ * The one reader of `pids.jsonl` (same tolerant `readLines` every book uses).
16
+ * @param {string} runDir
17
+ * @returns {any[]}
18
+ */
19
+ export function readPidRows(runDir: string): any[];
1
20
  /**
2
21
  * One row per attempt (also used for one row per ask and one row per send —
3
22
  * M2 scope item 9). `row` shape: `{ step, attempt, class, verdict, gap, usd,
@@ -0,0 +1,69 @@
1
+ /**
2
+ * Field 22 (`starttime`, clock ticks since boot) of /proc/<pid>/stat, as a
3
+ * string; `null` when unreadable. The comm field (2) may contain spaces and
4
+ * parens, so fields are counted from the LAST ')'.
5
+ * @param {number|'self'} pid
6
+ * @returns {string|null}
7
+ */
8
+ export function procStartOf(pid: number | "self"): string | null;
9
+ /**
10
+ * Is `pid` a live fwdloop process — and, when `procStart` is given, the SAME
11
+ * process that recorded it?
12
+ * true - exists AND its command line is fwdloop (AND its starttime matches)
13
+ * false - gone, a zombie, alive but something else, or a different process on a recycled pid
14
+ * null - cannot tell (no /proc, or not ours to read): caller falls back to the 10-minute rule
15
+ * @param {number} pid
16
+ * @param {string|null} [procStart] the starttime recorded by the process itself; absent/null = not compared
17
+ * @returns {boolean|null}
18
+ */
19
+ export function isFwdloopAlive(pid: number, procStart?: string | null): boolean | null;
20
+ /**
21
+ * The one writer call: this process records itself in the run dir's
22
+ * `pids.jsonl`, before its first step.
23
+ * @param {string} runDir
24
+ * @param {'run'|'resume'} leg
25
+ * @param {string} at ISO timestamp from the run's own clock
26
+ */
27
+ export function recordPid(runDir: string, leg: "run" | "resume", at: string): void;
28
+ /**
29
+ * Is the process that last worked on this run still alive? Reads the newest
30
+ * `pids.jsonl` row (the one reader, `readPidRows`).
31
+ * `unknown` = no row (a pre-M4c run), a malformed row, or the check said `null`.
32
+ * @param {string} runDir
33
+ * @returns {'running'|'gone'|'unknown'}
34
+ */
35
+ export function runLiveness(runDir: string): "running" | "gone" | "unknown";
36
+ /**
37
+ * M4c amendment 2 (d): the resume lock records who holds it. The one writer:
38
+ * `resumeRun` calls this on the fd it just created with `wx`.
39
+ * @param {number} fd
40
+ */
41
+ export function writeLockHolder(fd: number): void;
42
+ /**
43
+ * The one reader of `resume.lock`. Through `lstat` (a symlinked lock is read as
44
+ * `empty`, never followed).
45
+ * none - no lock file
46
+ * live - the holder is a live fwdloop process (same rule as `[▶]`)
47
+ * dead - the holder is gone (or a different process on a recycled pid)
48
+ * unknown - liveness cannot be told (no /proc): never treated as dead
49
+ * empty - a lock with no readable holder (pre-amendment resumer, torn write)
50
+ * @param {string} runDir
51
+ * @returns {{state: 'none'|'live'|'dead'|'unknown'|'empty', pid: number|null, path: string}}
52
+ */
53
+ export function readResumeLock(runDir: string): {
54
+ state: "none" | "live" | "dead" | "unknown" | "empty";
55
+ pid: number | null;
56
+ path: string;
57
+ };
58
+ /**
59
+ * bareloop's fallback (signed M4c scope item 2): when liveness is `unknown`
60
+ * (a pre-M4c run with no pid row, or /proc unreadable), a run with no end row
61
+ * whose books changed in the last 10 minutes is still working; older is not.
62
+ * Symlinked files are skipped (lstat), never followed.
63
+ * @param {string} runDir
64
+ * @param {number} [nowMs]
65
+ * @returns {boolean}
66
+ */
67
+ export function booksFresh(runDir: string, nowMs?: number): boolean;
68
+ /** The words the runner's refusal uses for a lock it cannot clear; the panel reads the same constant (M4c amendment 3 (e)). */
69
+ export const LOCK_NO_HOLDER: "with no recorded holder";