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/bin/fwdloop CHANGED
@@ -31,7 +31,7 @@ import { makeLiveModelStep } from '../src/model-step.js';
31
31
  import { sendViaPrimitive } from '../src/send.js';
32
32
  import { resolvePrimitives } from '../src/primitives.js';
33
33
  import { checkKeyPreflight } from '../src/provider.js';
34
- import { answerAsk, readAskEvidence } from '../src/ask.js';
34
+ import { answerAsk, readAskEvidence, normalizeDecision } from '../src/ask.js';
35
35
  import { panelMain } from '../src/panel/server.js';
36
36
  import { isInteractive, confirmTypedName, NEEDS_TTY } from '../src/sign-confirm.js';
37
37
  import { draftToDir, signDraft, SIGN_LINE, costText } from '../src/authoring.js';
@@ -139,7 +139,7 @@ function findRunDirByAskId(root, askId) {
139
139
  function reportRunResult(result, { rootArg }) {
140
140
  if (result.outcome === 'paused') {
141
141
  process.stdout.write(`parked: askId=${result.askId} expiresAt=${result.expiresAt} spentUsd=${result.spentUsd}\n`);
142
- process.stdout.write(`fwdloop answer ${result.askId} accept|reject "<reason>"|rerun "<reason>" --root ${rootArg}\n`);
142
+ process.stdout.write(`fwdloop answer ${result.askId} accept|redo "<reason>"|rerun "<reason>" --root ${rootArg}\n`);
143
143
  return;
144
144
  }
145
145
  if (result.outcome === 'complete') {
@@ -414,8 +414,8 @@ function cmdAnswer(rest) {
414
414
  allowPositionals: true,
415
415
  });
416
416
  const [askId, decision, reason] = positionals;
417
- if (!askId) fail('answer: an askId is required — fwdloop answer <askId> accept|reject "<reason>"|rerun "<reason>"');
418
- if (!decision) fail(`answer: a decision (accept|reject|rerun) is required for askId "${askId}"`);
417
+ if (!askId) fail('answer: an askId is required — fwdloop answer <askId> accept|redo "<reason>"|rerun "<reason>"');
418
+ if (!decision) fail(`answer: a decision (accept|redo|rerun) is required for askId "${askId}"`);
419
419
 
420
420
  const root = resolveRoot('answer', values.root ?? '.');
421
421
  const runDir = findRunDirByAskId(root, askId);
@@ -426,7 +426,7 @@ function cmdAnswer(rest) {
426
426
  });
427
427
  if (!result.ok) fail(result.red);
428
428
 
429
- process.stdout.write(`answered: askId=${askId} decision=${decision}\n`);
429
+ process.stdout.write(`answered: askId=${askId} decision=${normalizeDecision(decision)}\n`);
430
430
  }
431
431
 
432
432
  // ---------------------------------------------------------------------------
@@ -513,9 +513,11 @@ async function cmdResume(rest) {
513
513
  }
514
514
 
515
515
  // ---------------------------------------------------------------------------
516
- // panel — M4a piece 2 (docs/wiki/the-module-ladder.md, "M4a — read-only
517
- // panel — SIGNED"): `fwdloop panel [--port 4800] [--root <dir>]`. Read-only,
518
- // GET/HEAD only, bound to 127.0.0.1 only (src/panel/server.js). Never picks
516
+ // panel — M4a piece 2 + M4b (docs/wiki/the-module-ladder.md, "M4a — read-only
517
+ // panel" and "M4b — inputs"): `fwdloop panel [--port 4800] [--root <dir>]`.
518
+ // Reads are GET/HEAD; the only writes are POST /api/answer and POST
519
+ // /api/resume (src/panel/server.js), each gated by Origin/Host + a per-process
520
+ // token. Bound to 127.0.0.1 only. Never picks
519
521
  // a different port on collision — a taken port is a loud, non-zero-exit
520
522
  // failure.
521
523
  // ---------------------------------------------------------------------------
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "fwdloop",
3
- "version": "0.8.1",
3
+ "version": "0.10.0",
4
4
  "description": "Describe a job as steps and guardrails; an agent builds the workflow, pauses for humans where you said, checks every step happened, and reruns it under budgets it cannot touch.",
5
5
  "type": "module",
6
6
  "main": "./src/index.js",
package/src/ask.js CHANGED
@@ -1,7 +1,7 @@
1
1
  // M2 piece 2 (docs/wiki/the-module-ladder.md, "M2 — scope, exit, negative —
2
2
  // SIGNED", scope item 6): the file-checkpoint ask, in-process. Writes
3
3
  // `ask.json` (question + evidence + askedAt + attempt) into the run dir and
4
- // polls for `answer.json` (`{ decision: accept|reject|rerun, reason?,
4
+ // polls for `answer.json` (`{ decision: accept|redo|rerun, reason?,
5
5
  // answeredAt }`). Consumed exactly once (renamed away on read); a stale
6
6
  // answer — `answeredAt` older than THIS ask's `askedAt` — is quarantined
7
7
  // (renamed to `answer.stale.<n>.json`, audited `stale-answer-ignored`) and
@@ -20,11 +20,48 @@ import {
20
20
  existsSync, mkdirSync, readFileSync, renameSync, writeFileSync,
21
21
  } from 'node:fs';
22
22
  import { join } from 'node:path';
23
- import { randomUUID } from 'node:crypto';
23
+ import { createHash, randomUUID } from 'node:crypto';
24
24
 
25
25
  import { appendAudit } from './books.js';
26
26
  import { readFileInside, resolveInside, readdirInside } from './flow.js';
27
27
 
28
+ /**
29
+ * M4c amendment 3: the ONE rule for "was this answer saved in time" — the
30
+ * answer's own saved time (`answeredAt`, written by `answerAsk`) against the
31
+ * ask's deadline, never the clock at the moment a resume restarts.
32
+ * on-time - answeredAt parses and is not after expiresAt
33
+ * late - answeredAt parses and is after expiresAt
34
+ * unreadable - answeredAt or expiresAt missing/unparseable: never on time
35
+ * @param {unknown} answeredAt
36
+ * @param {unknown} expiresAt
37
+ * @returns {'on-time'|'late'|'unreadable'}
38
+ */
39
+ export function answerTiming(answeredAt, expiresAt) {
40
+ const a = typeof answeredAt === 'string' ? Date.parse(answeredAt) : NaN;
41
+ const e = typeof expiresAt === 'string' ? Date.parse(expiresAt) : NaN;
42
+ if (Number.isNaN(a) || Number.isNaN(e)) return 'unreadable';
43
+ return a > e ? 'late' : 'on-time';
44
+ }
45
+
46
+ /**
47
+ * M4b amendment 3 (SIGNED by hamr 2026-09-30): the ONE translation of a
48
+ * decision. The answer that was spelled `reject` is `redo`; `reject` is still
49
+ * understood (from the CLI, the library, or a file an older version wrote) and
50
+ * means `redo`. `accept`, `redo` and `rerun` pass. Anything else comes back
51
+ * unchanged, so each caller's existing "unrecognised decision" refusal still
52
+ * quotes what it was given. Every decision from outside, and every one read
53
+ * from disk, goes through here; nothing else may compare against the old word.
54
+ * @param {string} decision
55
+ * @returns {string}
56
+ */
57
+ export function normalizeDecision(decision) {
58
+ return decision === 'reject' ? 'redo' : decision;
59
+ }
60
+
61
+ /** The one decision -> status table, used by `listArchivedAsks` here and by the panel's legacy-ask rows.
62
+ * Look it up with `normalizeDecision(decision)`. */
63
+ export const DECISION_STATUS = { accept: 'accepted', redo: 'redo', rerun: 'reran' };
64
+
28
65
  function sleep(ms) {
29
66
  return new Promise((resolve) => { setTimeout(resolve, ms); });
30
67
  }
@@ -101,7 +138,7 @@ export function makeFileAskStep({
101
138
  // ask has been answered.
102
139
  } else {
103
140
  renameSync(answerPath, join(runDir, `answer.${safeStamp(askedAt)}.consumed.json`));
104
- return { decision: parsed.decision, reason: parsed.reason };
141
+ return { decision: normalizeDecision(parsed.decision), reason: parsed.reason, artifactSha256: parsed.artifactSha256 };
105
142
  }
106
143
  }
107
144
  }
@@ -199,18 +236,40 @@ export function readAskEvidence(ask) {
199
236
  // M3 piece 1 (docs/wiki/the-module-ladder.md, "M3 — scope, exit, negative —
200
237
  // SIGNED", scope item 3, the function only — the CLI is piece 2): a separate
201
238
  // process's half of the park protocol. Writes `answer.json` exactly once,
202
- // refusing (never throwing) a blank reason on reject/rerun, an unknown
239
+ // refusing (never throwing) a blank reason on redo/rerun, an unknown
203
240
  // askId, an expired askId, or a second answer to an already-answered ask —
204
241
  // each by name, so an answer for ask A can never be consumed by ask B.
205
242
  // ---------------------------------------------------------------------------
206
243
 
207
244
  /**
208
- * @param {{ runDir: string, askId: string, decision: 'accept'|'reject'|'rerun', reason?: string, clock?: () => string }} opts
245
+ * M4b piece 3: the ONE serialisation of an artifact's bytes — what
246
+ * `writeArtifact` (`src/runner.js`) puts on disk and what `sendViaPrimitive`
247
+ * (`src/send.js`) ships. The accept hash and the send-time re-hash are both
248
+ * over exactly this string, so they can only differ if the content does.
249
+ * @param {unknown} artifact
250
+ * @returns {string}
251
+ */
252
+ export function serializeArtifact(artifact) {
253
+ return JSON.stringify(artifact, null, 2);
254
+ }
255
+
256
+ /**
257
+ * sha256 (hex) of the bytes `serializeArtifact` yields.
258
+ * @param {string} serialised
259
+ * @returns {string}
260
+ */
261
+ export function sha256Hex(serialised) {
262
+ return createHash('sha256').update(Buffer.from(serialised, 'utf8')).digest('hex');
263
+ }
264
+
265
+ /**
266
+ * @param {{ runDir: string, askId: string, decision: 'accept'|'redo'|'reject'|'rerun', reason?: string, clock?: () => string }} opts
209
267
  * @returns {{ ok: true } | { ok: false, red: string }}
210
268
  */
211
269
  export function answerAsk({
212
- runDir, askId, decision, reason, clock,
270
+ runDir, askId, decision: givenDecision, reason, clock,
213
271
  }) {
272
+ const decision = normalizeDecision(givenDecision);
214
273
  const now = typeof clock === 'function' ? clock : () => new Date().toISOString();
215
274
 
216
275
  if (typeof runDir !== 'string' || runDir.length === 0) {
@@ -219,8 +278,8 @@ export function answerAsk({
219
278
  if (typeof askId !== 'string' || askId.length === 0) {
220
279
  return { ok: false, red: 'answerAsk: "askId" must be a non-empty string' };
221
280
  }
222
- if (decision !== 'accept' && decision !== 'reject' && decision !== 'rerun') {
223
- return { ok: false, red: `answerAsk: unrecognised decision "${decision}"` };
281
+ if (decision !== 'accept' && decision !== 'redo' && decision !== 'rerun') {
282
+ return { ok: false, red: `answerAsk: unrecognised decision "${givenDecision}"` };
224
283
  }
225
284
 
226
285
  // F48 round 3: routed through `readFileInside` — a symlinked `ask.json`
@@ -264,12 +323,25 @@ export function answerAsk({
264
323
  }
265
324
 
266
325
  const trimmedReason = typeof reason === 'string' ? reason.trim() : '';
267
- if ((decision === 'reject' || decision === 'rerun') && trimmedReason.length === 0) {
326
+ if ((decision === 'redo' || decision === 'rerun') && trimmedReason.length === 0) {
268
327
  return { ok: false, red: `answerAsk: askId "${askId}" needs a non-blank reason to ${decision}` };
269
328
  }
270
329
 
271
330
  const payload = { askId, decision, answeredAt: nowIso };
272
331
  if (trimmedReason.length > 0) payload.reason = trimmedReason;
332
+ // M4b scope item 4 (F48 finding C): an accept records the sha256 of the
333
+ // artifact the human was shown — `ask.json`'s `evidence.artifact`, the one
334
+ // draft this ask is about — so `send` can prove the bytes it ships are the
335
+ // bytes that were accepted. An accept whose artifact cannot be read from
336
+ // the ask is refused by name and nothing is written. redo/rerun record
337
+ // none (nothing is shipped on them).
338
+ if (decision === 'accept') {
339
+ const artifact = ask.evidence && typeof ask.evidence === 'object' ? ask.evidence.artifact : undefined;
340
+ if (artifact === null || typeof artifact !== 'object' || Array.isArray(artifact)) {
341
+ return { ok: false, red: `answerAsk: askId "${askId}" cannot be accepted — ask.json carries no readable artifact (evidence.artifact) to hash for run ${runDir}` };
342
+ }
343
+ payload.artifactSha256 = sha256Hex(serializeArtifact(artifact));
344
+ }
273
345
  // Orchestrator review fix (5): a plain `existsSync` check followed by a
274
346
  // separate `writeFileSync` is a check-then-act race — two concurrent
275
347
  // answers can both pass the check before either writes, and the second
@@ -320,11 +392,17 @@ export function answerAsk({
320
392
  * what is actually on disk); it is never treated as "before M4a-1" (that
321
393
  * `why` is reserved for a run with NO `asks/` directory at all).
322
394
  *
323
- * @param {{ runDir: string, askId: string, question: string, askedAt: string, expiresAt: string, evidence: unknown }} opts
395
+ * M4b amendment 2 (SIGNED by hamr 2026-09-30, F52): the record also carries
396
+ * `emits`, the step output this ask is about, so a later process can join
397
+ * the ask to its consumed answer's recorded hash (`readAcceptedHashesByEmits`).
398
+ * Written once with the rest of the record; an existing archive is never
399
+ * rewritten to add it (the `wx` create refuses).
400
+ *
401
+ * @param {{ runDir: string, askId: string, question: string, askedAt: string, expiresAt: string, evidence: unknown, emits?: string }} opts
324
402
  * @returns {{ ok: true } | { ok: false, red: string }}
325
403
  */
326
404
  export function writeAskArchive({
327
- runDir, askId, question, askedAt, expiresAt, evidence,
405
+ runDir, askId, question, askedAt, expiresAt, evidence, emits,
328
406
  }) {
329
407
  if (typeof runDir !== 'string' || runDir.length === 0) {
330
408
  return { ok: false, red: 'writeAskArchive: "runDir" must be a non-empty string' };
@@ -338,6 +416,7 @@ export function writeAskArchive({
338
416
  const payload = {
339
417
  askId, question, askedAt, expiresAt, evidence,
340
418
  };
419
+ if (typeof emits === 'string' && emits.length > 0) payload.emits = emits;
341
420
  try {
342
421
  writeFileSync(archivePath, JSON.stringify(payload, null, 2), { flag: 'wx' });
343
422
  } catch (err) {
@@ -349,6 +428,44 @@ export function writeAskArchive({
349
428
  return { ok: true };
350
429
  }
351
430
 
431
+ /**
432
+ * M4b amendment 2: for each archived ask that carries `emits`, joins it BY
433
+ * askId to its consumed answer and returns the recorded `artifactSha256` of
434
+ * an ACCEPT. Only `decision: accept` with a string hash counts; never
435
+ * recomputed from any file. No `emits` (old run), no marker, bad JSON, a
436
+ * redo/rerun, or a symlinked/unreadable entry contributes nothing, so the
437
+ * emits stays unrecorded and send refuses by name. Two accepts for one
438
+ * `emits` should be impossible; if seen, the result is a red, never a guess.
439
+ *
440
+ * @param {string} runDir
441
+ * @returns {{ ok: true, byEmits: Map<string, string> } | { ok: false, red: string }}
442
+ */
443
+ export function readAcceptedHashesByEmits(runDir) {
444
+ const byEmits = new Map();
445
+ if (!resolveInside(runDir, 'asks').ok) return { ok: true, byEmits };
446
+ const accepted = new Map(); // emits -> [askId]
447
+ for (const entry of readdirInside(runDir, 'asks').sort()) {
448
+ if (!entry.endsWith('.json')) continue; // eslint-disable-line no-continue
449
+ const askId = entry.slice(0, -'.json'.length);
450
+ const archiveRead = readFileInside(runDir, join('asks', entry));
451
+ if (!archiveRead.ok) continue; // eslint-disable-line no-continue
452
+ let emits;
453
+ try { emits = JSON.parse(archiveRead.text)?.emits; } catch { continue; } // eslint-disable-line no-continue
454
+ if (typeof emits !== 'string' || emits.length === 0) continue; // eslint-disable-line no-continue
455
+ const markerRead = readFileInside(runDir, `answer.${askId}.consumed.json`);
456
+ if (!markerRead.ok) continue; // eslint-disable-line no-continue
457
+ let marker;
458
+ try { marker = JSON.parse(markerRead.text); } catch { continue; } // eslint-disable-line no-continue
459
+ if (marker?.decision !== 'accept' || typeof marker.artifactSha256 !== 'string' || marker.artifactSha256.length === 0) continue; // eslint-disable-line no-continue
460
+ if (accepted.has(emits)) {
461
+ return { ok: false, red: `resume: more than one accepted ask (${accepted.get(emits)}, ${askId}) for step output "${emits}" — refusing to guess which hash applies` };
462
+ }
463
+ accepted.set(emits, askId);
464
+ byEmits.set(emits, marker.artifactSha256);
465
+ }
466
+ return { ok: true, byEmits };
467
+ }
468
+
352
469
  // ---------------------------------------------------------------------------
353
470
  // M4a Amendment M4a-1 reader: pairs each archived ask (`asks/<askId>.json`)
354
471
  // with its consumed answer (`answer.<askId>.consumed.json`), by askId only —
@@ -420,9 +537,8 @@ export function listArchivedAsks(runDir) {
420
537
  let parsed;
421
538
  try {
422
539
  parsed = JSON.parse(consumedRead.text);
423
- const decisionToStatus = { accept: 'accepted', reject: 'rejected', rerun: 'reran' };
424
540
  answer = {
425
- status: decisionToStatus[parsed.decision] ?? `unrecognised: ${parsed.decision}`,
541
+ status: DECISION_STATUS[normalizeDecision(parsed.decision)] ?? `unrecognised: ${parsed.decision}`,
426
542
  answeredAt: parsed.answeredAt,
427
543
  };
428
544
  if (typeof parsed.reason === 'string') answer.reason = parsed.reason;
@@ -443,6 +559,7 @@ export function listArchivedAsks(runDir) {
443
559
  expiresAt: ask.expiresAt,
444
560
  evidence: readAskEvidence(ask),
445
561
  answer,
562
+ ...(typeof ask.emits === 'string' ? { emits: ask.emits } : {}),
446
563
  });
447
564
  }
448
565
 
package/src/books.js CHANGED
@@ -28,6 +28,26 @@ function appendLine(filePath, row) {
28
28
  appendFileSync(filePath, `${JSON.stringify(row)}\n`);
29
29
  }
30
30
 
31
+ /**
32
+ * M4c piece 1: the ONE writer of a run dir's `pids.jsonl` — append-only, never
33
+ * rewritten, not a book the arbiter reads. One row per process that works on
34
+ * the run (`src/liveness.js` `recordPid` builds the row).
35
+ * @param {string} runDir
36
+ * @param {{pid: number, startedAt: string, procStart: string|null, leg: 'run'|'resume'}} row
37
+ */
38
+ export function appendPidRow(runDir, row) {
39
+ appendLine(join(runDir, 'pids.jsonl'), row);
40
+ }
41
+
42
+ /**
43
+ * The one reader of `pids.jsonl` (same tolerant `readLines` every book uses).
44
+ * @param {string} runDir
45
+ * @returns {any[]}
46
+ */
47
+ export function readPidRows(runDir) {
48
+ return readLines(runDir, 'pids.jsonl');
49
+ }
50
+
31
51
  /**
32
52
  * Raw read-back of one JSONL book, one writer's own sibling reader (M4a
33
53
  * piece 2, docs/wiki/the-module-ladder.md M4a scope item 2: "one reader per
@@ -0,0 +1,160 @@
1
+ // M4c piece 1: "is this run's process alive?" — the ONE rule. The panel's `[▶]`
2
+ // and (M4d) the money hold both call `isFwdloopAlive`/`runLiveness`, so the two
3
+ // never disagree (bareloop's own open inconsistency). No panel imports here.
4
+ // borrowed-from: bareloop src/runlist.js@00b2b75
5
+ // fwdloop tightened bareloop's rule: bareloop matched `fwdloop` in ANY argv
6
+ // position after node; here only the SCRIPT (first non-option arg) may name it
7
+ // (the panel's own resume spawn passes `--root <dir>`, and a root whose last
8
+ // segment is `fwdloop` would otherwise read as a fwdloop process). And it adds
9
+ // `procStart` (field 22 of /proc/<pid>/stat) to close a recycled pid that is
10
+ // itself a DIFFERENT fwdloop process. Proof: poc/m4c/README.md.
11
+ import { lstatSync, readFileSync, writeSync } from 'node:fs';
12
+ import { basename, join } from 'node:path';
13
+
14
+ import { appendPidRow, readPidRows } from './books.js';
15
+
16
+ const NAME = 'fwdloop';
17
+
18
+ /**
19
+ * Field 22 (`starttime`, clock ticks since boot) of /proc/<pid>/stat, as a
20
+ * string; `null` when unreadable. The comm field (2) may contain spaces and
21
+ * parens, so fields are counted from the LAST ')'.
22
+ * @param {number|'self'} pid
23
+ * @returns {string|null}
24
+ */
25
+ export function procStartOf(pid) {
26
+ try {
27
+ const stat = readFileSync(`/proc/${pid}/stat`, 'utf8');
28
+ const after = stat.slice(stat.lastIndexOf(')') + 2).split(' ');
29
+ const v = after[19]; // field 3 is after[0], so field 22 is after[19]
30
+ return v !== undefined && /^\d+$/.test(v) ? v : null;
31
+ } catch { return null; }
32
+ }
33
+
34
+ /**
35
+ * Is `pid` a live fwdloop process — and, when `procStart` is given, the SAME
36
+ * process that recorded it?
37
+ * true - exists AND its command line is fwdloop (AND its starttime matches)
38
+ * false - gone, a zombie, alive but something else, or a different process on a recycled pid
39
+ * null - cannot tell (no /proc, or not ours to read): caller falls back to the 10-minute rule
40
+ * @param {number} pid
41
+ * @param {string|null} [procStart] the starttime recorded by the process itself; absent/null = not compared
42
+ * @returns {boolean|null}
43
+ */
44
+ export function isFwdloopAlive(pid, procStart) {
45
+ if (!Number.isInteger(pid) || pid <= 0) return false;
46
+ try { process.kill(pid, 0); } catch (e) { if (e?.code !== 'EPERM') return false; /* EPERM: exists, not ours */ }
47
+ let cmdline;
48
+ try { cmdline = readFileSync(`/proc/${pid}/cmdline`, 'utf8'); } catch (e) {
49
+ return e?.code === 'ENOENT' && process.platform === 'linux' && hasProc() ? false : null; // died between the two calls vs no /proc
50
+ }
51
+ if (cmdline === '') return false; // zombie (or kernel thread): not a runner
52
+ const [argv0, ...rest] = cmdline.split('\0');
53
+ let isFwdloop;
54
+ if (basename(argv0) === NAME) isFwdloop = true; // direct exec of a renamed/compiled bin
55
+ else if (!basename(argv0).startsWith('node')) isFwdloop = false;
56
+ else {
57
+ // node <script> ...: only the SCRIPT (first non-option arg) may name fwdloop.
58
+ const script = rest.find((a) => a !== '' && !a.startsWith('-'));
59
+ isFwdloop = script !== undefined && basename(script) === NAME;
60
+ }
61
+ if (!isFwdloop) return false;
62
+ if (typeof procStart === 'string') {
63
+ const live = procStartOf(pid);
64
+ if (live === null) return null; // cannot compare: never a silent true
65
+ if (live !== procStart) return false; // a different fwdloop process reusing the pid
66
+ }
67
+ return true;
68
+ }
69
+
70
+ function hasProc() {
71
+ try { readFileSync('/proc/self/cmdline'); return true; } catch { return false; }
72
+ }
73
+
74
+ /**
75
+ * The one writer call: this process records itself in the run dir's
76
+ * `pids.jsonl`, before its first step.
77
+ * @param {string} runDir
78
+ * @param {'run'|'resume'} leg
79
+ * @param {string} at ISO timestamp from the run's own clock
80
+ */
81
+ export function recordPid(runDir, leg, at) {
82
+ appendPidRow(runDir, { pid: process.pid, startedAt: at, procStart: procStartOf('self'), leg });
83
+ }
84
+
85
+ /**
86
+ * Is the process that last worked on this run still alive? Reads the newest
87
+ * `pids.jsonl` row (the one reader, `readPidRows`).
88
+ * `unknown` = no row (a pre-M4c run), a malformed row, or the check said `null`.
89
+ * @param {string} runDir
90
+ * @returns {'running'|'gone'|'unknown'}
91
+ */
92
+ export function runLiveness(runDir) {
93
+ const rows = readPidRows(runDir);
94
+ const row = rows[rows.length - 1];
95
+ if (!row || !Number.isInteger(row.pid)) return 'unknown';
96
+ const alive = isFwdloopAlive(row.pid, typeof row.procStart === 'string' ? row.procStart : null);
97
+ return alive === true ? 'running' : alive === false ? 'gone' : 'unknown';
98
+ }
99
+
100
+ /**
101
+ * M4c amendment 2 (d): the resume lock records who holds it. The one writer:
102
+ * `resumeRun` calls this on the fd it just created with `wx`.
103
+ * @param {number} fd
104
+ */
105
+ export function writeLockHolder(fd) {
106
+ writeSync(fd, JSON.stringify({ pid: process.pid, procStart: procStartOf('self') }));
107
+ }
108
+
109
+ /** The words the runner's refusal uses for a lock it cannot clear; the panel reads the same constant (M4c amendment 3 (e)). */
110
+ export const LOCK_NO_HOLDER = 'with no recorded holder';
111
+
112
+ /**
113
+ * The one reader of `resume.lock`. Through `lstat` (a symlinked lock is read as
114
+ * `empty`, never followed).
115
+ * none - no lock file
116
+ * live - the holder is a live fwdloop process (same rule as `[▶]`)
117
+ * dead - the holder is gone (or a different process on a recycled pid)
118
+ * unknown - liveness cannot be told (no /proc): never treated as dead
119
+ * empty - a lock with no readable holder (pre-amendment resumer, torn write)
120
+ * @param {string} runDir
121
+ * @returns {{state: 'none'|'live'|'dead'|'unknown'|'empty', pid: number|null, path: string}}
122
+ */
123
+ export function readResumeLock(runDir) {
124
+ const path = join(runDir, 'resume.lock');
125
+ let st;
126
+ try { st = lstatSync(path); } catch { return { state: 'none', pid: null, path }; }
127
+ if (!st.isFile()) return { state: 'empty', pid: null, path };
128
+ let h;
129
+ try { h = JSON.parse(readFileSync(path, 'utf8')); } catch { return { state: 'empty', pid: null, path }; }
130
+ if (!h || !Number.isInteger(h.pid) || h.pid <= 0) return { state: 'empty', pid: null, path };
131
+ const procStart = typeof h.procStart === 'string' ? h.procStart : null;
132
+ // This very process holds it (two resumeRun calls in one process): alive by definition,
133
+ // whatever its command line says.
134
+ if (h.pid === process.pid && procStart === procStartOf('self')) return { state: 'live', pid: h.pid, path };
135
+ const alive = isFwdloopAlive(h.pid, procStart);
136
+ return { state: alive === true ? 'live' : alive === false ? 'dead' : 'unknown', pid: h.pid, path };
137
+ }
138
+
139
+ /** The run's books, for the 10-minute fallback: state, audit, model log, spend ledger, and the pid file itself. */
140
+ const BOOK_FILES = ['state.json', 'audit.jsonl', 'log.json', 'spend.jsonl', 'pids.jsonl'];
141
+ const FRESH_MS = 10 * 60 * 1000;
142
+
143
+ /**
144
+ * bareloop's fallback (signed M4c scope item 2): when liveness is `unknown`
145
+ * (a pre-M4c run with no pid row, or /proc unreadable), a run with no end row
146
+ * whose books changed in the last 10 minutes is still working; older is not.
147
+ * Symlinked files are skipped (lstat), never followed.
148
+ * @param {string} runDir
149
+ * @param {number} [nowMs]
150
+ * @returns {boolean}
151
+ */
152
+ export function booksFresh(runDir, nowMs = Date.now()) {
153
+ for (const f of BOOK_FILES) {
154
+ try {
155
+ const st = lstatSync(join(runDir, f));
156
+ if (st.isFile() && nowMs - st.mtimeMs <= FRESH_MS) return true;
157
+ } catch { /* missing file: not evidence of freshness */ }
158
+ }
159
+ return false;
160
+ }