fwdloop 0.9.0 → 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.
@@ -55,7 +55,7 @@ import { loadCatalogue } from '../catalogue.js';
55
55
  import { answerAsk, normalizeDecision } from '../ask.js';
56
56
  import { checkFlowName, resolveRunDir } from '../flow.js';
57
57
  import {
58
- listRuns, getRunDetail, getRunAudit, getRunJob, listStops, getRunAsks, readSavedAnswer,
58
+ listRuns, getRunDetail, getRunAudit, getRunJob, listStops, inboxOpenCount, getRunAsks, readSavedAnswer,
59
59
  } from './data.js';
60
60
  import { createResumer } from './resume.js';
61
61
 
@@ -274,7 +274,8 @@ export function handleRequest(req, res, opts) {
274
274
  }
275
275
 
276
276
  if (pathname === '/api/inbox') {
277
- send(200, { rows: listStops({ root: opts.root, resumeAttempt }) });
277
+ const rows = listStops({ root: opts.root, resumeAttempt });
278
+ send(200, { rows, openCount: inboxOpenCount(rows) });
278
279
  return;
279
280
  }
280
281
 
package/src/runner.js CHANGED
@@ -49,11 +49,14 @@ import {
49
49
  readFlow, resolveRunDir, readFileInside, resolveInside,
50
50
  } from './flow.js';
51
51
  import {
52
- writeAskArchive, readAcceptedHashesByEmits, serializeArtifact, normalizeDecision,
52
+ writeAskArchive, readAcceptedHashesByEmits, serializeArtifact, normalizeDecision, answerTiming,
53
53
  } from './ask.js';
54
54
  import { WIRED_VERBS } from './primitives.js';
55
55
  import { closeByClass } from './closers.js';
56
56
  import { appendAudit, appendHistory } from './books.js';
57
+ import {
58
+ readResumeLock, recordPid, writeLockHolder, LOCK_NO_HOLDER,
59
+ } from './liveness.js';
57
60
 
58
61
  const __dirname = dirname(fileURLToPath(import.meta.url));
59
62
  const REPO_ROOT = resolve(__dirname, '..');
@@ -856,6 +859,8 @@ export async function runFlow({
856
859
  flowDir, runDir, runId, capUsd, startedAt, now, nowMs: getNowMs, signatureHash: signature.flow, outcome: 'preflight-red', red: frozen.red, spent: { value: 0 },
857
860
  });
858
861
  }
862
+ // M4c: every guard above has passed — this process records itself (pid row) before its first step.
863
+ recordPid(runDir, 'run', now());
859
864
 
860
865
  const artifacts = {};
861
866
  const auditRows = [];
@@ -1475,11 +1480,59 @@ function sumAuditUsd(runDir) {
1475
1480
  return { ok: true, total };
1476
1481
  }
1477
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
+
1478
1530
  /**
1479
1531
  * M3 scope items 4-6: re-enter a parked run's SAME fold from a separate
1480
- * process. Takes an exclusive `resume.lock` (refuses by name if already
1481
- * held; a lock left behind by a killed resumer is a red naming it, never
1482
- * 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/
1483
1536
  * missing-artifact mismatch, consumes `answer.json` by atomic rename BEFORE
1484
1537
  * acting (F44), then either cancels an expired ask ($0, nothing sent) or
1485
1538
  * resolves it and folds on to `complete`/the next pause/a halt.
@@ -1540,15 +1593,9 @@ export async function resumeRun({
1540
1593
 
1541
1594
  const lockPath = join(runDir, 'resume.lock');
1542
1595
 
1543
- let lockFd;
1544
- try {
1545
- lockFd = openSync(lockPath, 'wx');
1546
- } catch (err) {
1547
- if (err.code === 'EEXIST') {
1548
- return { outcome: 'refused', red: `resume: run "${runId}" is locked by another resumer (${lockPath})` };
1549
- }
1550
- return { outcome: 'refused', red: `resume: could not create lock ${lockPath} — ${err.message}` };
1551
- }
1596
+ const took = await takeResumeLock(runDir, runId, lockPath);
1597
+ if (!took.ok) return { outcome: 'refused', red: took.red };
1598
+ const { lockFd } = took;
1552
1599
 
1553
1600
  try {
1554
1601
  const statePath = join(runDir, 'state.json');
@@ -1717,6 +1764,13 @@ export async function resumeRun({
1717
1764
  return { outcome: 'refused', red: `resume: answer askId "${answer.askId}" does not match open askId "${state.askId}" for run "${runId}"` };
1718
1765
  }
1719
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
+
1720
1774
  // M4b amendment 2: hashes recorded by earlier-process accepts, read back
1721
1775
  // from the archive + consumed markers. Refused BEFORE the consume below so
1722
1776
  // the answer stays replayable.
@@ -1727,12 +1781,12 @@ export async function resumeRun({
1727
1781
  // itself a one-winner gate, on top of the lock above.
1728
1782
  const consumedPath = join(runDir, `answer.${answer.askId}.consumed.json`);
1729
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());
1730
1786
 
1731
- // The run's own injected clock governs expiry, exactly like every other
1732
- // "now" in this module (never the bare wall clock) — the same fixed
1733
- // clock a test controls for `runFlow` also controls what "expired" means
1734
- // for `resumeRun`, with no real wait required to prove it.
1735
- 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') {
1736
1790
  // Negative (i): an answer arriving after expiry cancels the run —
1737
1791
  // adds NOTHING further, but the run's own already-spent total is
1738
1792
  // real money and must be reported, never coerced to 0 (orchestrator
package/types/ask.d.ts CHANGED
@@ -1,3 +1,15 @@
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";
1
13
  /**
2
14
  * M4b amendment 3 (SIGNED by hamr 2026-09-30): the ONE translation of a
3
15
  * decision. The answer that was spelled `reject` is `redo`; `reject` is still
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";
@@ -4,11 +4,12 @@
4
4
  * through `readFileInside` (a symlinked file is "none"). `null` when there is
5
5
  * none or it is unreadable/unparseable or names no askId.
6
6
  * @param {string} runDir
7
- * @returns {{askId: string, decision: string|null}|null}
7
+ * @returns {{askId: string, decision: string|null, answeredAt: string|null}|null}
8
8
  */
9
9
  export function readSavedAnswer(runDir: string): {
10
10
  askId: string;
11
11
  decision: string | null;
12
+ answeredAt: string | null;
12
13
  } | null;
13
14
  /**
14
15
  * M4b amendment 1 scope 2: the ONE derivation of "answer saved, resume not
@@ -16,15 +17,20 @@ export function readSavedAnswer(runDir: string): {
16
17
  * unconsumed. From the panel's in-memory attempt record (`attempt`, may be
17
18
  * null): whether a resume is still being started, and the resume's own refusal.
18
19
  * `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
+ * M4c amendment 3: `ask` (the run's open `ask.json`, may be null). A saved answer for that ask that was
21
+ * NOT saved in time (`answerTiming`) once the deadline has passed is not a resumable answer: it reads as
22
+ * none, so the run is `[!]` expired, the same as an ask nobody answered.
23
+ * @param {{savedAnswer: {askId:string, decision:string|null, answeredAt?:string|null}|null, attempt: any, ask?: any}} ctx
20
24
  * @returns {{state: 'starting'|'not-started'|'took-over', askId: string|null, tries: number|null, maxTries: number|null, reason: string|null, label: string}|null}
21
25
  */
22
- export function deriveResumeState({ savedAnswer, attempt }: {
26
+ export function deriveResumeState({ savedAnswer: saved, attempt, ask }: {
23
27
  savedAnswer: {
24
28
  askId: string;
25
29
  decision: string | null;
30
+ answeredAt?: string | null;
26
31
  } | null;
27
32
  attempt: any;
33
+ ask?: any;
28
34
  }): {
29
35
  state: "starting" | "not-started" | "took-over";
30
36
  askId: string | null;
@@ -33,6 +39,45 @@ export function deriveResumeState({ savedAnswer, attempt }: {
33
39
  reason: string | null;
34
40
  label: string;
35
41
  } | null;
42
+ /**
43
+ * M4c amendment 2 (a): the ONE rule for "stuck". The answer is saved and not yet
44
+ * taken (`resume.state === 'not-started'`: `answer.json` is on disk; the panel's
45
+ * transient 'starting' is not stuck) and nothing is carrying the run on: the
46
+ * newest pid row's process is not alive AND the resume lock is not held by a
47
+ * live process (`readResumeLock`, src/liveness.js). computeGlyph, the Inbox
48
+ * (`listStops`) and Runs (`listRuns`) all read this, never a second copy.
49
+ * @param {{resume?: any, liveness?: 'running'|'gone'|'unknown', lock?: string}} ctx
50
+ * @returns {boolean}
51
+ */
52
+ export function isStuck({ resume, liveness, lock }: {
53
+ resume?: any;
54
+ liveness?: "running" | "gone" | "unknown";
55
+ lock?: string;
56
+ }): boolean;
57
+ /**
58
+ * M4c amendment 3 (e): the ONE choice of the stuck label. After a "Try the resume again" the runner
59
+ * refused for a lock with no recorded holder (`LOCK_NO_HOLDER`, src/liveness.js) and that lock is
60
+ * still there unreadable (`lock === 'empty'`), trying again can never work: the label says to remove
61
+ * the file by hand. Every other stuck run keeps `STUCK_LABEL`.
62
+ * @param {{resume?: any, lock?: string}} ctx
63
+ * @returns {string}
64
+ */
65
+ export function stuckLabelFor({ resume, lock }: {
66
+ resume?: any;
67
+ lock?: string;
68
+ }): string;
69
+ /**
70
+ * M4c item 1: does this sign pulse? Only `[▶]` running and `[·]` WAITING ON YOU
71
+ * do, and `[II]` stuck (M4c amendment 2: it is not a final state). The other
72
+ * `[·]` states (answered not resumed, resume starting) are not waiting on the
73
+ * human, so they stay still. The one place that decides.
74
+ * @param {{glyph: string, label: string}} g a `computeGlyph` result
75
+ * @returns {boolean}
76
+ */
77
+ export function glyphPulses(g: {
78
+ glyph: string;
79
+ label: string;
80
+ }): boolean;
36
81
  /**
37
82
  * The glyph + human-words label for one run — ported verbatim (in spirit,
38
83
  * from real derivation, not a shortcut) from `poc/m4/panel-data.mjs`'s
@@ -54,24 +99,36 @@ export function deriveResumeState({ savedAnswer, attempt }: {
54
99
  * - `[·]` answered, not resumed yet — parked, a consumed answer exists, but
55
100
  * no history row yet (resume hasn't finished) — always in words, never
56
101
  * the same line as "waiting on you", never `[?]`.
57
- * - `[?]` died / unknown — no history row, no open ask, no consumed answer:
58
- * `resume.lock` carries no pid and nothing checks liveness (M4a's own
59
- * open POC question), so a crashed resumer and a live one look the same
60
- * on disk. Never guessed into `[✗]` or `[✓]`.
102
+ * - `[?]` died / unknown — no history row, no open ask, and either the
103
+ * pid row's process is gone (M4c), or there is no pid row / no /proc and
104
+ * the books are older than 10 minutes. Never guessed into `[✗]` or `[✓]`.
61
105
  * - `[·]` answer saved, resume not started / starting (M4b amendment 1) —
62
106
  * `answer.json` still on disk (`resume` = `deriveResumeState`): never
63
107
  * "waiting on you" (the human already answered) and never a success.
64
- * @param {{historyRow: any, askJson: any, consumedAnswerExists: boolean, hasStateJson: boolean, resume?: any}} ctx
65
- * @returns {{glyph: '[✓]'|'[✗]'|'[·]'|'[!]'|'[?]', label: string}}
108
+ * - `[▶]` running (M4c) — no end row, no open unanswered ask, and either the
109
+ * newest pid row's process is alive and is fwdloop (`liveness`, src/liveness.js)
110
+ * or (`liveness` unknown) the run's books changed in the last 10 minutes
111
+ * (`booksFresh`). A gone process is `[?]`. Absent `liveness`/`booksFresh`
112
+ * (a direct caller) reads as unknown / not fresh.
113
+ * - `[II]` stuck (M4c amendment 2, `isStuck`) — the answer is saved, not taken,
114
+ * and no live process (pid row or resume lock holder) carries the run on.
115
+ * A saved answer with a live process is `[▶]` working on your answer.
116
+ * - `[?]` crashed after taking your answer (amendment 2 (f)) — the answer was
117
+ * consumed, the process is gone, no end row: cannot be carried on.
118
+ * @param {{historyRow: any, askJson: any, consumedAnswerExists: boolean, hasStateJson: boolean, resume?: any, liveness?: 'running'|'gone'|'unknown', booksFresh?: boolean, lock?: string}} ctx
119
+ * @returns {{glyph: '[✓]'|'[✗]'|'[·]'|'[!]'|'[▶]'|'[?]'|'[II]', label: string}}
66
120
  */
67
- export function computeGlyph({ historyRow, askJson, consumedAnswerExists, hasStateJson, resume, }: {
121
+ export function computeGlyph({ historyRow, askJson, consumedAnswerExists, hasStateJson, resume, liveness, booksFresh, lock, }: {
68
122
  historyRow: any;
69
123
  askJson: any;
70
124
  consumedAnswerExists: boolean;
71
125
  hasStateJson: boolean;
72
126
  resume?: any;
127
+ liveness?: "running" | "gone" | "unknown";
128
+ booksFresh?: boolean;
129
+ lock?: string;
73
130
  }): {
74
- glyph: "[\u2713]" | "[\u2717]" | "[\u00B7]" | "[!]" | "[?]";
131
+ glyph: "[\u2713]" | "[\u2717]" | "[\u00B7]" | "[!]" | "[\u25B6]" | "[?]" | "[II]";
75
132
  label: string;
76
133
  };
77
134
  /**
@@ -282,9 +339,8 @@ export function summarizeSpendRows(spendRows: any[]): {
282
339
  * `GET /api/runs` — every flow under `root`, every run under each flow
283
340
  * (M4a scope item 2). A flow with zero runs still gets one row (`runId:
284
341
  * null`, an explicit `why`) — no flow is silently missing from the list.
285
- * Newest-first by history `at` where known; a row with no history row (died
286
- * or still parked) sorts after every row that has one, in flow/run order
287
- * (a real ordering, never `Date.now()` guessed in for a missing `at`).
342
+ * Ordered by `orderRuns` (waiting on you, running, then newest `at` first; a row
343
+ * with no `at` is never given a guessed one).
288
344
  * @param {{root: string, catalogue: any, resumeAttempt?: (flow: string, runId: string) => any}} opts
289
345
  * `resumeAttempt`: the panel's in-memory resume-attempt lookup (M4b piece 2); absent = none.
290
346
  * @returns {any[]}
@@ -294,6 +350,19 @@ export function listRuns({ root, catalogue, resumeAttempt }: {
294
350
  catalogue: any;
295
351
  resumeAttempt?: (flow: string, runId: string) => any;
296
352
  }): any[];
353
+ /**
354
+ * The ONE ordering of Runs — History and Workflows both render the list in the
355
+ * order given (M4c amendment 1 (c)); a flow's top row is therefore the first
356
+ * run of that flow here, so a waiting run is the parent with no second rule:
357
+ * 1 waiting on you — least time left first; a stuck run (`[II]`, amendment 2)
358
+ * after the ones with a timer;
359
+ * 2 running (`[▶]`, the glyph's own liveness rule);
360
+ * 3 everything else — finish time `at`, newest first.
361
+ * A row with no known time keeps input order at the end of its section.
362
+ * @param {any[]} rows
363
+ * @returns {any[]}
364
+ */
365
+ export function orderRuns(rows: any[]): any[];
297
366
  /**
298
367
  * `GET /api/runs/:flow/:runId` — the Run tab (M4a scope item 2): the step
299
368
  * map from `declaration.steps`, step cards -> attempts from `audit.jsonl`
@@ -428,6 +497,20 @@ export function deriveAskStepInfo(orderedAsks: any[], auditRows: any[], declStep
428
497
  line: number | null;
429
498
  why: string | null;
430
499
  }>;
500
+ /**
501
+ * M4c item 5 — the Ask tab's ONE grouping function: one block per signed ask
502
+ * line. Key = the archive's recorded `emits`, else the step the ask's own "paused" audit row names (`stepName`,
503
+ * `deriveAskStepInfo`); when the books cannot name a step (count mismatch, a
504
+ * pre-M4a-1 run) the key falls back to the question text, then to one shared
505
+ * "unknown" key — never a guessed pairing. Draft numbers are the ask's 1-based
506
+ * position within its own block (how many times this line has parked).
507
+ * `current` is the newest draft; `answers` is one row per draft that has a
508
+ * recorded decision (the newest draft only when it is not itself open),
509
+ * decision word via `DECISION_STATUS` (old `reject` files already read `redo`).
510
+ * @param {any[]} asks rows as built by `getRunAsks` (oldest first)
511
+ * @returns {any[]}
512
+ */
513
+ export function groupAskBlocks(asks: any[]): any[];
431
514
  /**
432
515
  * `GET /api/runs/:flow/:runId/asks` — the Ask tab (M4a-1 scope item 1):
433
516
  * every ask this run's books can name, in order, each carrying full
@@ -443,7 +526,7 @@ export function deriveAskStepInfo(orderedAsks: any[], auditRows: any[], declStep
443
526
  * detail carries, `null` for a finished run or nothing to say) so the Ask tab
444
527
  * can tell "open, answerable" from "answer saved" without a second fetch.
445
528
  * @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}
529
+ * @returns {{flow:string, runId:string, asks:any[], resume: any, blocks: any[]}|null}
447
530
  */
448
531
  export function getRunAsks({ root, flow, runId, catalogue, resumeAttempt, }: {
449
532
  root: string;
@@ -456,6 +539,7 @@ export function getRunAsks({ root, flow, runId, catalogue, resumeAttempt, }: {
456
539
  runId: string;
457
540
  asks: any[];
458
541
  resume: any;
542
+ blocks: any[];
459
543
  } | null;
460
544
  /**
461
545
  * `GET /api/inbox` — every stop (parked ask, open or past) across every
@@ -479,6 +563,33 @@ export function listStops({ root, resumeAttempt }: {
479
563
  root: string;
480
564
  resumeAttempt?: (flow: string, runId: string) => any;
481
565
  }): any[];
566
+ /**
567
+ * The ONE ordering of the Inbox (M4c item 4, hamr 2026-09-30); the page renders
568
+ * in the order given and stamps each row's `section`:
569
+ * 1 waiting on you — least time left first ("runs out first"); a stuck run
570
+ * (amendment 2: answer saved, nobody carrying it on) after the timed asks;
571
+ * 2 working on an answer you gave (`working`), or answer saved and resume not
572
+ * started (`resume`) — newest answer first;
573
+ * 3 answered and expired asks — newest first (answeredAt, else expiresAt).
574
+ * A row with no known time sorts last within its section, ties by input order.
575
+ * @param {any[]} rows
576
+ * @returns {any[]}
577
+ */
578
+ export function orderStops(rows: any[]): any[];
579
+ /**
580
+ * N for `Inbox (N)` (M4c item 3): asks open and not expired, across every flow
581
+ * and run, plus stuck runs (amendment 2: the human must act). An answered ask
582
+ * whose resume is carried on is not `waiting`, so not counted; a crashed one
583
+ * (answer taken, process gone) is not stuck and not counted;
584
+ * an expired ask is not `open`. The page only shows this number.
585
+ * @param {any[]} rows `listStops` rows
586
+ * @returns {number}
587
+ */
588
+ export function inboxOpenCount(rows: any[]): number;
482
589
  /** What the `resume` field says when the panel has no attempt record for a run
483
590
  * (it restarted since the answer was saved) — said so, never blank. */
484
591
  export const RESUME_REASON_UNKNOWN: "reason unknown: the panel restarted, so it has no record of the resume attempt";
592
+ export const WAITING_LABEL: "waiting on you (parked, unanswered)";
593
+ export const STUCK_LABEL: "stuck \u2014 answer saved, click try the resume again";
594
+ export const STUCK_LOCK_LABEL: "stuck \u2014 remove the old resume lock by hand, then try again";
595
+ export const CRASHED_LABEL: "crashed after taking your answer \u2014 start a fresh run";
package/types/runner.d.ts CHANGED
@@ -184,9 +184,10 @@ export function makeParkingAskStep(): (opts?: any) => Promise<{
184
184
  }>;
185
185
  /**
186
186
  * M3 scope items 4-6: re-enter a parked run's SAME fold from a separate
187
- * process. Takes an exclusive `resume.lock` (refuses by name if already
188
- * held; a lock left behind by a killed resumer is a red naming it, never
189
- * stolen), re-reads the flow, refuses by name at $0 on any signature/input/
187
+ * process. Takes an exclusive `resume.lock` that records its holder's
188
+ * `{pid, procStart}` (M4c amendment 2: refuses by name if the holder is alive
189
+ * or the lock has no readable holder; a lock whose holder is gone is cleared
190
+ * and retaken, losing cleanly on a race), re-reads the flow, refuses by name at $0 on any signature/input/
190
191
  * missing-artifact mismatch, consumes `answer.json` by atomic rename BEFORE
191
192
  * acting (F44), then either cancels an expired ask ($0, nothing sent) or
192
193
  * resolves it and folds on to `complete`/the next pause/a halt.