fwdloop 0.9.0 → 0.11.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.
@@ -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, procStart: string|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, procStart: null, path }; }
127
+ if (!st.isFile()) return { state: 'empty', pid: null, procStart: null, path };
128
+ let h;
129
+ try { h = JSON.parse(readFileSync(path, 'utf8')); } catch { return { state: 'empty', pid: null, procStart: null, path }; }
130
+ if (!h || !Number.isInteger(h.pid) || h.pid <= 0) return { state: 'empty', pid: null, procStart: 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, procStart, path };
135
+ const alive = isFwdloopAlive(h.pid, procStart);
136
+ return { state: alive === true ? 'live' : alive === false ? 'dead' : 'unknown', pid: h.pid, procStart, 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
+ }
package/src/model-step.js CHANGED
@@ -251,11 +251,12 @@ export function makeLiveModelStep({
251
251
  ({ provider, rates, modelId } = makeProvider(slot, { model, ...LIVE_PROVIDER_OPTIONS }));
252
252
  } catch (err) {
253
253
  // No provider was ever built, so no round could possibly have run —
254
- // `tokens: null` (and `tools: null`, M4a-3) here is the one honest
254
+ // `model: null`, `tokens: null` and `tools: null` (M4a-3) here are the one honest
255
255
  // "no model call at all" case (never a zeroed object standing in for
256
- // a call that never happened).
256
+ // a call that never happened). A row that names a model must carry its
257
+ // tokens (appendAudit refuses it otherwise), so the model is not named.
257
258
  return {
258
- ok: false, red: `key: ${err.message}`, costUsd: null, model: model ?? null, tokens: null, tools: null,
259
+ ok: false, red: `key: ${err.message}`, costUsd: null, model: null, tokens: null, tools: null,
259
260
  };
260
261
  }
261
262
  }