fwdloop 0.10.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.
package/src/runner.js CHANGED
@@ -49,13 +49,13 @@ import {
49
49
  readFlow, resolveRunDir, readFileInside, resolveInside,
50
50
  } from './flow.js';
51
51
  import {
52
- writeAskArchive, readAcceptedHashesByEmits, serializeArtifact, normalizeDecision, answerTiming,
52
+ writeAskArchive, readAcceptedHashesByEmits, serializeArtifact, normalizeDecision, answerTiming, effectiveExpiresAt, withReopen,
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
57
  import {
58
- readResumeLock, recordPid, writeLockHolder, LOCK_NO_HOLDER,
58
+ readResumeLock, recordPid, writeLockHolder, procStartOf, LOCK_NO_HOLDER,
59
59
  } from './liveness.js';
60
60
 
61
61
  const __dirname = dirname(fileURLToPath(import.meta.url));
@@ -631,8 +631,19 @@ async function runStepRalph({
631
631
  // never retried (M2 scope item 8) — both are the caller's own
632
632
  // `modelStep`'s job to distinguish; this loop only ever retries the
633
633
  // `transport: true` shape, exactly once.
634
+ const first = result;
634
635
  // eslint-disable-next-line no-await-in-loop
635
636
  result = await modelStep(executorContext, grantedTools, stepMeta);
637
+ // The first call's gate refusals and tool tally belong to this attempt's
638
+ // audit row too (the retry's collector starts empty). Only refused /
639
+ // tools / ungranted are merged — cost is never touched here.
640
+ if (result && typeof result === 'object') {
641
+ const refused = [...(first.refused ?? []), ...(result.refused ?? [])];
642
+ const tools = first.tools || result.tools ? { ...(first.tools ?? {}) } : null;
643
+ if (tools) for (const [k, v] of Object.entries(result.tools ?? {})) tools[k] = (tools[k] ?? 0) + v;
644
+ const ungranted = [...new Set([...(first.ungranted ?? []), ...(result.ungranted ?? [])])].sort();
645
+ result = { ...result, refused, tools, ...(ungranted.length > 0 ? { ungranted } : {}) };
646
+ }
636
647
  }
637
648
  const wallMs = Date.now() - startedAt;
638
649
 
@@ -1480,6 +1491,15 @@ function sumAuditUsd(runDir) {
1480
1491
  return { ok: true, total };
1481
1492
  }
1482
1493
 
1494
+ /** Unlink `resume.lock` only when its recorded holder is still THIS process (`readResumeLock`'s holder pid + start
1495
+ * time against our own). A lock a later taker made in its place is never touched. */
1496
+ function releaseResumeLock(runDir, lockPath) {
1497
+ const lock = readResumeLock(runDir);
1498
+ if (lock.pid === process.pid && lock.procStart === procStartOf('self')) {
1499
+ try { unlinkSync(lockPath); } catch { /* already gone */ }
1500
+ }
1501
+ }
1502
+
1483
1503
  /**
1484
1504
  * M4c amendment 2 (d): create `resume.lock` with `wx` and write the holder into it.
1485
1505
  * An existing lock is read: holder alive (or cannot be told) -> refuse by name
@@ -1493,8 +1513,10 @@ async function takeResumeLock(runDir, runId, lockPath) {
1493
1513
  try {
1494
1514
  const lockFd = openSync(lockPath, 'wx');
1495
1515
  try { writeLockHolder(lockFd); } catch (err) {
1516
+ // This call's own `wx` just created the file and no holder is in it yet, so it is ours to remove
1517
+ // (`releaseResumeLock` would skip it: it unlinks only a lock whose holder names this process).
1518
+ try { unlinkSync(lockPath); } catch { /* already gone */ }
1496
1519
  try { closeSync(lockFd); } catch { /* ignore */ }
1497
- try { unlinkSync(lockPath); } catch { /* ignore */ }
1498
1520
  return { ok: false, red: `resume: could not record the lock holder in ${lockPath} — ${err.message}` };
1499
1521
  }
1500
1522
  return { ok: true, lockFd };
@@ -1516,10 +1538,11 @@ async function takeResumeLock(runDir, runId, lockPath) {
1516
1538
  }
1517
1539
  if (lock.state === 'dead') {
1518
1540
  // 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.
1541
+ // already, and must not lose its fresh lock. Same holder (pid and start time) as judged dead.
1542
+ // The window left is one syscall wide, and the answer's rename-to-consume (F44) still lets only
1543
+ // one resume act on the answer.
1521
1544
  const again = readResumeLock(runDir);
1522
- if (again.state === 'dead' && again.pid === lock.pid) {
1545
+ if (again.state === 'dead' && again.pid === lock.pid && again.procStart === lock.procStart) {
1523
1546
  try { unlinkSync(lockPath); } catch { /* another taker already cleared it: retry wx */ }
1524
1547
  }
1525
1548
  }
@@ -1527,6 +1550,15 @@ async function takeResumeLock(runDir, runId, lockPath) {
1527
1550
  return { ok: false, red: `resume: run "${runId}" is locked by another resumer (${lockPath})` };
1528
1551
  }
1529
1552
 
1553
+ /** Two roots are the same flow location when their real paths agree: a run parked through a symlinked `--root`
1554
+ * recorded the typed link path, and a resume (or a CLI that realpaths its root) names the real one. A path that
1555
+ * cannot be resolved is compared as typed. */
1556
+ function sameRoot(recorded, requested) {
1557
+ if (typeof recorded !== 'string' || typeof requested !== 'string') return false;
1558
+ const real = (p) => { try { return realpathSync(p); } catch { return p; } };
1559
+ return recorded === requested || real(recorded) === real(requested);
1560
+ }
1561
+
1530
1562
  /**
1531
1563
  * M3 scope items 4-6: re-enter a parked run's SAME fold from a separate
1532
1564
  * process. Takes an exclusive `resume.lock` that records its holder's
@@ -1631,7 +1663,7 @@ export async function resumeRun({
1631
1663
  // parked run whose recorded flow location disagrees with what THIS call
1632
1664
  // was asked to resume is refused by name, never re-read from wherever
1633
1665
  // the state file happens to point.
1634
- if (state.flow?.root !== root || state.flow?.name !== name) {
1666
+ if (!sameRoot(state.flow?.root, root) || state.flow?.name !== name) {
1635
1667
  return {
1636
1668
  outcome: 'refused',
1637
1669
  red: `resume: run "${runId}" was parked against flow "${state.flow?.root}/${state.flow?.name}", `
@@ -1757,6 +1789,10 @@ export async function resumeRun({
1757
1789
  } catch (err) {
1758
1790
  return { outcome: 'refused', red: `resume: answer.json for run "${runId}" is not valid JSON — ${err.message}` };
1759
1791
  }
1792
+ // Valid JSON that is not an object (`null`, a number, a string, an array) has no askId to read: refused by name.
1793
+ if (answer === null || typeof answer !== 'object' || Array.isArray(answer)) {
1794
+ return { outcome: 'refused', red: `resume: answer.json for run "${runId}" is not a JSON object (it holds ${answer === null ? 'null' : Array.isArray(answer) ? 'an array' : `a ${typeof answer}`})` };
1795
+ }
1760
1796
  // M4b amendment 3: a consumed/saved answer that says `reject` (an older
1761
1797
  // version's file) is read as `redo`; the file on disk is never rewritten.
1762
1798
  answer = { ...answer, decision: normalizeDecision(answer.decision) };
@@ -1766,7 +1802,7 @@ export async function resumeRun({
1766
1802
 
1767
1803
  // M4c amendment 3: an answer's saved time, never the restart's clock, says whether it was on time. A missing or
1768
1804
  // unreadable one is refused by name here, before the consume, so the answer stays replayable.
1769
- const timing = answerTiming(answer.answeredAt, state.expiresAt);
1805
+ const timing = answerTiming(answer.answeredAt, effectiveExpiresAt(runDir, state.askId, state.expiresAt));
1770
1806
  if (timing === 'unreadable') {
1771
1807
  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
1808
  }
@@ -2013,8 +2049,8 @@ export async function resumeRun({
2013
2049
  if (result.outcome === 'complete') return { ...result, auditRows };
2014
2050
  return result;
2015
2051
  } finally {
2052
+ releaseResumeLock(runDir, lockPath);
2016
2053
  try { closeSync(lockFd); } catch { /* already closed */ }
2017
- try { unlinkSync(lockPath); } catch { /* already gone */ }
2018
2054
  }
2019
2055
  }
2020
2056
 
@@ -2063,7 +2099,8 @@ export function readRunState(runDir) {
2063
2099
  export function readAsk(runDir) {
2064
2100
  const result = readFileInside(runDir, 'ask.json');
2065
2101
  if (!result.ok) return null;
2066
- try { return JSON.parse(result.text); } catch { return null; }
2102
+ // The deadline every reader sees is the effective one (`withReopen`: a reopened ask's new deadline).
2103
+ try { return withReopen(runDir, JSON.parse(result.text)); } catch { return null; }
2067
2104
  }
2068
2105
 
2069
2106
  /**
package/types/ask.d.ts CHANGED
@@ -22,6 +22,13 @@ export function answerTiming(answeredAt: unknown, expiresAt: unknown): "on-time"
22
22
  * @returns {string}
23
23
  */
24
24
  export function normalizeDecision(decision: string): string;
25
+ /** Terminal control codes out of text a model wrote, before it reaches a terminal: C0 (incl. ESC, which starts
26
+ * every CSI/OSC sequence), DEL and C1 (incl. the one-byte CSI, U+009B). Keeps \n and \t. A stripped ESC leaves the
27
+ * sequence's printable tail ("[2J") visible, which is inert. */
28
+ export function stripControl(text: any): string;
29
+ /** The status for a decision word read from disk, or undefined for anything that is not one of the table's OWN
30
+ * entries ("constructor", "toString" and the rest of Object.prototype read as unrecognised). */
31
+ export function decisionStatus(decision: any): any;
25
32
  /**
26
33
  * @param {{ timeoutMs?: number, pollMs?: number, clock?: () => string, writeLine?: (line:string) => void }} [opts]
27
34
  * @returns {(opts:{question:string, evidence:unknown, runDir:string, ttlMs?: number}) => Promise<{decision:string, reason?:string}>}
@@ -73,9 +80,70 @@ export function serializeArtifact(artifact: unknown): string;
73
80
  * @returns {string}
74
81
  */
75
82
  export function sha256Hex(serialised: string): string;
83
+ /**
84
+ * M4c-fix amendment 1 (a): why a saved `answer.json` is not a usable answer for the open ask `openAskId`, or `null`
85
+ * when it is usable. The resume refuses each of these by name before it consumes the file, so without a way aside
86
+ * the file would block every new answer (`answerAsk`'s exclusive create).
87
+ * @param {string} text the file's text @param {string} openAskId
88
+ * @returns {string|null}
89
+ */
90
+ export function brokenAnswerWhy(text: string, openAskId: string): string | null;
91
+ /**
92
+ * Move `answer.json` aside as a record: `answer.<askId>.<kind>.<n>.json`, `n` the first free number. Write-once:
93
+ * the new name is created with a hard link (`EEXIST` = taken, try the next), then the old name is removed — never
94
+ * a rename, which would overwrite; never a delete of the content. A symlinked `answer.json` is refused, not followed.
95
+ * @param {string} runDir @param {string} askId @param {'broken'|'late'} kind
96
+ * @returns {{ ok: true, name: string } | { ok: false, red: string }}
97
+ */
98
+ export function setAsideAnswer(runDir: string, askId: string, kind: "broken" | "late"): {
99
+ ok: true;
100
+ name: string;
101
+ } | {
102
+ ok: false;
103
+ red: string;
104
+ };
105
+ /**
106
+ * The deadline an ask is judged against: the newest valid reopen record's `expiresAt`, else `original`.
107
+ * A record that is unreadable, names another ask, or holds no parseable `expiresAt` is ignored.
108
+ * @param {string} runDir @param {string} askId @param {string} original the ask's own `expiresAt`
109
+ * @returns {string}
110
+ */
111
+ export function effectiveExpiresAt(runDir: string, askId: string, original: string): string;
112
+ /**
113
+ * An `ask.json`-shaped object as every reader should see it: `expiresAt` is the effective deadline, and `waitMs`
114
+ * is the signed wait the ask was parked with (its own `expiresAt` minus `askedAt`, written from the signed ttl),
115
+ * which a reopen repeats. `waitMs` is `null` when either time cannot be read.
116
+ * @param {string} runDir @param {any} ask
117
+ * @returns {any}
118
+ */
119
+ export function withReopen(runDir: string, ask: any): any;
120
+ /**
121
+ * Reopen an expired ask: a fresh window of the same signed length, starting now, on the same ask (the same draft;
122
+ * nothing about the run changes). Human only — the caller names who (`by`); no runner, agent or resume path calls this.
123
+ * Refused, by name, when: there is no such open ask, its answer was already taken, it has not expired, or a saved
124
+ * answer made in time is waiting (that one is resumed, not reopened). A late or broken saved answer is moved aside
125
+ * as a record (`answer.<askId>.late.<n>.json`, never deleted). Two clicks race on the record's exclusive create:
126
+ * the loser is refused "already reopened", so a double click opens one window, not two.
127
+ * @param {{ runDir: string, askId: string, by: string, clock?: () => string }} opts
128
+ * @returns {{ ok: true, expiresAt: string, n: number, setAside: string|null } | { ok: false, red: string }}
129
+ */
130
+ export function reopenAsk({ runDir, askId, by, clock, }: {
131
+ runDir: string;
132
+ askId: string;
133
+ by: string;
134
+ clock?: () => string;
135
+ }): {
136
+ ok: true;
137
+ expiresAt: string;
138
+ n: number;
139
+ setAside: string | null;
140
+ } | {
141
+ ok: false;
142
+ red: string;
143
+ };
76
144
  /**
77
145
  * @param {{ runDir: string, askId: string, decision: 'accept'|'redo'|'reject'|'rerun', reason?: string, clock?: () => string }} opts
78
- * @returns {{ ok: true } | { ok: false, red: string }}
146
+ * @returns {{ ok: true, setAside: string|null } | { ok: false, red: string }}
79
147
  */
80
148
  export function answerAsk({ runDir, askId, decision: givenDecision, reason, clock, }: {
81
149
  runDir: string;
@@ -85,6 +153,7 @@ export function answerAsk({ runDir, askId, decision: givenDecision, reason, cloc
85
153
  clock?: () => string;
86
154
  }): {
87
155
  ok: true;
156
+ setAside: string | null;
88
157
  } | {
89
158
  ok: false;
90
159
  red: string;
@@ -24,7 +24,7 @@ export function sweepForSecrets(dir: any, secrets: any): number;
24
24
  /** Exact signed TTL with its unit, never rounded: 2h / 30m / 20s / 1500ms (the largest unit that divides it exactly). */
25
25
  export function fmtTtl(ms: any): string;
26
26
  /** Plain-text readout of what the human is about to sign. Pure. */
27
- export function buildReadout({ declaration, arbiter, lines, name, modelId, costUsd, rounds, spendComplete }: {
27
+ export function buildReadout({ declaration, arbiter, lines, name, modelId, costUsd, rounds, spendComplete, root, }: {
28
28
  declaration: any;
29
29
  arbiter: any;
30
30
  lines: any;
@@ -33,6 +33,7 @@ export function buildReadout({ declaration, arbiter, lines, name, modelId, costU
33
33
  costUsd: any;
34
34
  rounds: any;
35
35
  spendComplete: any;
36
+ root: any;
36
37
  }): string;
37
38
  /** Read the prose file. Refuses (a red, never a throw) on unreadable or blank. */
38
39
  export function readProseFile(file: any): {
@@ -98,7 +99,7 @@ export function draftToDir({ proseFile, dir, root, name, slot, model, budgetUsd,
98
99
  wrote: boolean;
99
100
  dir: any;
100
101
  hash: string | null;
101
- reds: string[];
102
+ reds: any;
102
103
  costUsd: number | null;
103
104
  spendComplete: boolean;
104
105
  stop: string | null;
@@ -48,11 +48,12 @@ export function writeLockHolder(fd: number): void;
48
48
  * unknown - liveness cannot be told (no /proc): never treated as dead
49
49
  * empty - a lock with no readable holder (pre-amendment resumer, torn write)
50
50
  * @param {string} runDir
51
- * @returns {{state: 'none'|'live'|'dead'|'unknown'|'empty', pid: number|null, path: string}}
51
+ * @returns {{state: 'none'|'live'|'dead'|'unknown'|'empty', pid: number|null, procStart: string|null, path: string}}
52
52
  */
53
53
  export function readResumeLock(runDir: string): {
54
54
  state: "none" | "live" | "dead" | "unknown" | "empty";
55
55
  pid: number | null;
56
+ procStart: string | null;
56
57
  path: string;
57
58
  };
58
59
  /**
@@ -1,3 +1,44 @@
1
+ /**
2
+ * Resolve `<root>/<flowName>` safely — `checkFlowName` first (never a raw
3
+ * string joined into a path). `checkFlowName` rules out a flowName that
4
+ * escapes `root` lexically (no `/`, `\`, `..`), but a flow directory named
5
+ * by URL is not required to have come from `listFlowNames` first — a
6
+ * request can name a flow directly. So if `<root>/<flowName>` actually
7
+ * exists, it is re-checked with `realpathSync`: it must resolve inside the
8
+ * real `root`, same class of hole `resolveRunDir` closes for a run dir one
9
+ * level down (a symlinked flow directory would never show up in a
10
+ * `listFlowNames` listing, since a symlink dirent never reports
11
+ * `isDirectory()`, but a direct request naming it by its allow-list-legal
12
+ * name must still be refused). A not-yet-existing flow directory has
13
+ * nothing to realpath, so only the lexical result applies to it.
14
+ * Returns the flow directory, or a refusal.
15
+ * @param {string} root
16
+ * @param {string} flowName
17
+ * @returns {{ok:true, flowDir:string}|{ok:false, red:string, why?:'outside-root'}}
18
+ */
19
+ export function resolveFlowDir(root: string, flowName: string): {
20
+ ok: true;
21
+ flowDir: string;
22
+ } | {
23
+ ok: false;
24
+ red: string;
25
+ why?: "outside-root";
26
+ };
27
+ /**
28
+ * A consumed-answer marker exists for THIS ask (`askId`) — `answerAsk`'s own write
29
+ * (`src/ask.js`) renames to `answer.<askId>.consumed.json` on accept, and
30
+ * `resumeRun` (`src/runner.js`) does the same when it consumes an in-place
31
+ * `answer.json`. A directory-naming-convention check, not a "book" with its
32
+ * own single-row shape, so it lives here rather than growing a one-off
33
+ * reader in either writer's module. Per the signed rule (ladder M4a scope
34
+ * item 4) it is per the OPEN ask's askId: after redo -> re-park the old
35
+ * ask's marker stays on disk and must not answer the new ask. An ask with no
36
+ * askId (pre-M3) can be paired with no marker: false.
37
+ * @param {string} runDir
38
+ * @param {string|null} askId the open ask's own askId
39
+ * @returns {boolean}
40
+ */
41
+ export function hasConsumedAnswer(runDir: string, askId: string | null): boolean;
1
42
  /**
2
43
  * M4b piece 2: a SAVED, not-yet-consumed answer — `answer.json` (what
3
44
  * `answerAsk` writes; the resume consumes it by renaming it away, F44). Read
@@ -13,15 +54,16 @@ export function readSavedAnswer(runDir: string): {
13
54
  } | null;
14
55
  /**
15
56
  * M4b amendment 1 scope 2: the ONE derivation of "answer saved, resume not
16
- * started". From the books: an answer saved (`answer.json` present) and so
17
- * unconsumed. From the panel's in-memory attempt record (`attempt`, may be
57
+ * started" (now worded "your answer is saved; the run stopped before using it" — M4c-fix amendment 3 (c)).
58
+ * From the books: an answer saved (`answer.json` present) and so unconsumed. From the panel's in-memory attempt record (`attempt`, may be
18
59
  * null): whether a resume is still being started, and the resume's own refusal.
19
60
  * `null` when there is nothing to say (no saved answer and no attempt).
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.
61
+ * M4c amendment 3: `ask` (the run's open `ask.json`, may be null; its `expiresAt` is the effective deadline). A saved
62
+ * answer for that ask that was NOT saved in time, once the deadline has passed, is not a resumable answer: it reads
63
+ * as none, so the ask is expired and offers the reopen (M4c-fix amendment 1 (b)). One with no readable time, before
64
+ * the deadline, reads `broken` (amendment 1 (a)).
23
65
  * @param {{savedAnswer: {askId:string, decision:string|null, answeredAt?:string|null}|null, attempt: any, ask?: any}} ctx
24
- * @returns {{state: 'starting'|'not-started'|'took-over', askId: string|null, tries: number|null, maxTries: number|null, reason: string|null, label: string}|null}
66
+ * @returns {{state: 'starting'|'not-started'|'broken'|'took-over', askId: string|null, tries: number|null, maxTries: number|null, reason: string|null, label: string}|null}
25
67
  */
26
68
  export function deriveResumeState({ savedAnswer: saved, attempt, ask }: {
27
69
  savedAnswer: {
@@ -32,7 +74,7 @@ export function deriveResumeState({ savedAnswer: saved, attempt, ask }: {
32
74
  attempt: any;
33
75
  ask?: any;
34
76
  }): {
35
- state: "starting" | "not-started" | "took-over";
77
+ state: "starting" | "not-started" | "broken" | "took-over";
36
78
  askId: string | null;
37
79
  tries: number | null;
38
80
  maxTries: number | null;
@@ -40,32 +82,49 @@ export function deriveResumeState({ savedAnswer: saved, attempt, ask }: {
40
82
  label: string;
41
83
  } | null;
42
84
  /**
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.
85
+ * The sign's word and the plain line after the dash. The existing plain line is kept as is; only a line that already
86
+ * opens with the word ("stuck — …") or is the word itself ("passed") loses that repeat, so it is never said twice.
87
+ * `noWord`: a run the human ended on purpose with rerun wears `[✗]` but is never called "failed" (M4b amendment 3),
88
+ * so it shows its plain line alone.
89
+ * @param {string} glyph a `computeGlyph` sign @param {string} label its plain line @param {boolean} [noWord]
90
+ * @returns {{word: string|null, line: string|null}}
91
+ */
92
+ export function signParts(glyph: string, label: string, noWord?: boolean): {
93
+ word: string | null;
94
+ line: string | null;
95
+ };
96
+ /**
97
+ * The ONE decision "is this run stuck, why, and what does it say" (M4c amendment 2 (a), amendment 3 (e), M4c-fix 15,
98
+ * 16). The answer is saved and not yet taken (`resume.state === 'not-started'`: `answer.json` is on disk; the
99
+ * panel's transient 'starting' and the `late` state are not stuck) and nothing is carrying the run on: the newest
100
+ * pid row's process is not alive AND the resume lock is not held by a live process, nor by one whose liveness
101
+ * cannot be told (`unknown`: never called stuck). The reason is typed, derived from the lock file and the saved
102
+ * answer themselves — never from a refusal string, so it is the same after a panel restart. Everything that shows
103
+ * "stuck" (computeGlyph, the Inbox, Runs, the Ask tab) reads this.
49
104
  * @param {{resume?: any, liveness?: 'running'|'gone'|'unknown', lock?: string}} ctx
50
- * @returns {boolean}
105
+ * @returns {{stuck: false, reason: null, label: null, why: null}|{stuck: true, reason: 'retry'|'lock-no-holder', label: string, why: string|null}}
51
106
  */
52
- export function isStuck({ resume, liveness, lock }: {
107
+ export function stuckState({ resume, liveness, lock }: {
53
108
  resume?: any;
54
109
  liveness?: "running" | "gone" | "unknown";
55
110
  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 }: {
111
+ }): {
112
+ stuck: false;
113
+ reason: null;
114
+ label: null;
115
+ why: null;
116
+ } | {
117
+ stuck: true;
118
+ reason: "retry" | "lock-no-holder";
119
+ label: string;
120
+ why: string | null;
121
+ };
122
+ /** @param {{resume?: any, liveness?: 'running'|'gone'|'unknown', lock?: string}} ctx @returns {boolean} */
123
+ export function isStuck(ctx: {
66
124
  resume?: any;
125
+ liveness?: "running" | "gone" | "unknown";
67
126
  lock?: string;
68
- }): string;
127
+ }): boolean;
69
128
  /**
70
129
  * M4c item 1: does this sign pulse? Only `[▶]` running and `[·]` WAITING ON YOU
71
130
  * do, and `[II]` stuck (M4c amendment 2: it is not a final state). The other
@@ -102,7 +161,7 @@ export function glyphPulses(g: {
102
161
  * - `[?]` died / unknown — no history row, no open ask, and either the
103
162
  * pid row's process is gone (M4c), or there is no pid row / no /proc and
104
163
  * the books are older than 10 minutes. Never guessed into `[✗]` or `[✓]`.
105
- * - `[·]` answer saved, resume not started / starting (M4b amendment 1) —
164
+ * - `[·]` your answer is saved; the run stopped before using it / starting (M4b amendment 1) —
106
165
  * `answer.json` still on disk (`resume` = `deriveResumeState`): never
107
166
  * "waiting on you" (the human already answered) and never a success.
108
167
  * - `[▶]` running (M4c) — no end row, no open unanswered ask, and either the
@@ -590,6 +649,26 @@ export function inboxOpenCount(rows: any[]): number;
590
649
  * (it restarted since the answer was saved) — said so, never blank. */
591
650
  export const RESUME_REASON_UNKNOWN: "reason unknown: the panel restarted, so it has no record of the resume attempt";
592
651
  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";
652
+ export const STUCK_LABEL: "stuck \u2014 your answer is saved; the run stopped before using it";
653
+ export const STUCK_LOCK_LABEL: "stuck \u2014 an old resume lock is in the way";
654
+ export const BROKEN_LABEL: "Your saved answer could not be read.";
655
+ export const BROKEN_ANSWER_WHY: "Please answer again; the broken one is kept aside.";
595
656
  export const CRASHED_LABEL: "crashed after taking your answer \u2014 start a fresh run";
657
+ /**
658
+ * M4c-fix amendment 2 (g): the ONE table from a sign to its bold word. Runs, the Inbox and the run header all show
659
+ * the word this table gives (the server stamps it on every row; the page never invents one).
660
+ * @type {Record<string, string>}
661
+ */
662
+ export const SIGN_WORDS: Record<string, string>;
663
+ /** The typed reasons a stuck run can have. `retry`: nothing is wrong that the books name, so trying again is the
664
+ * action. `lock-no-holder`: the resume lock has no recorded holder, so trying again can never work. */
665
+ export const STUCK_REASONS: {
666
+ retry: {
667
+ label: string;
668
+ why: null;
669
+ };
670
+ 'lock-no-holder': {
671
+ label: string;
672
+ why: string;
673
+ };
674
+ };
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Remove `<runDir>/resume.lock`, only if at THIS moment it has no recorded holder (`readResumeLock` -> `empty`;
3
+ * a live, dead or unknowable holder is never touched), and only if the lock file really sits inside this run dir
4
+ * (realpath of the run dir against realpath of `--root` at use time; a symlinked lock is unlinked as the link itself,
5
+ * never followed).
6
+ * Then one audit row through the one audit writer, shaped like the `ask-reopened` row (a pure note: cost 0, no model).
7
+ * @param {{root: string, runDir: string, nowIso?: string}} a
8
+ * @returns {{ok: true, at: string}|{ok: false, refused: 'no-lock'|'lock-has-holder'|'lock-outside-run', red: string}}
9
+ */
10
+ export function removeOldLock({ root, runDir, nowIso }: {
11
+ root: string;
12
+ runDir: string;
13
+ nowIso?: string;
14
+ }): {
15
+ ok: true;
16
+ at: string;
17
+ } | {
18
+ ok: false;
19
+ refused: "no-lock" | "lock-has-holder" | "lock-outside-run";
20
+ red: string;
21
+ };
@@ -40,6 +40,10 @@ export function createResumer(opts: {
40
40
  logPath: null;
41
41
  superseded: boolean;
42
42
  };
43
+ /** True while this run is already resuming: a resume child of this panel is alive for it, or its
44
+ * latest attempt is still starting (between tries). Routes refuse a second resume while true.
45
+ * @param {string} flow @param {string} runId */
46
+ busy(flow: string, runId: string): boolean;
43
47
  /** A copy of the run's attempt record, or null (none yet, or the panel restarted).
44
48
  * @param {string} flow @param {string} runId */
45
49
  get(flow: string, runId: string): any;
@@ -1,3 +1,29 @@
1
+ /**
2
+ * hamr's 2026-10-03 ruling "1A": the panel token is REUSED across restarts, so a bookmark of
3
+ * `http://127.0.0.1:<port>/` keeps working once the link was opened. Reads the token file (same path
4
+ * `writeTokenFile` writes); a new token only when the file is missing, unreadable, not a regular file,
5
+ * not mode 0600, not ours, or not 64 hex chars (the caller then rewrites it 0600).
6
+ * @param {{ port: number, dir?: string, env?: Record<string, string|undefined> }} a
7
+ * @returns {string}
8
+ */
9
+ export function loadOrMakeToken({ port, dir, env }: {
10
+ port: number;
11
+ dir?: string;
12
+ env?: Record<string, string | undefined>;
13
+ }): string;
14
+ /**
15
+ * M4c-fix item 2: the token's one on-disk home — `<dir>/panel-<port>.token`, dir 0700, file 0600,
16
+ * `dir` = `$XDG_RUNTIME_DIR/fwdloop`, else `~/.cache/fwdloop`. Refuses a dir that is a symlink or
17
+ * not ours. The file is replaced (unlink, then exclusive create at 0600), never rewritten in place,
18
+ * so it never exists with a looser mode. Returns the file's path.
19
+ * @param {{ port: number, token: string, dir?: string, env?: Record<string, string|undefined> }} a
20
+ */
21
+ export function writeTokenFile({ port, token, dir, env, }: {
22
+ port: number;
23
+ token: string;
24
+ dir?: string;
25
+ env?: Record<string, string | undefined>;
26
+ }): string;
1
27
  /**
2
28
  * Handle one request against the API + the page. Exported
3
29
  * separately from {@link createPanelServer} so tests can drive it without a
@@ -18,13 +44,14 @@ export function handleRequest(req: import("node:http").IncomingMessage, res: imp
18
44
  * header). Resolves once actually listening; rejects on a bind error
19
45
  * (including `EADDRINUSE`) with a `.port` field on the error for the
20
46
  * caller's message.
21
- * @param {{ port?: number, root: string, resume?: { env?: Record<string,string|undefined>, bin?: string, logDir?: string, maxTries?: number, windowMs?: number, slotMs?: number } }} opts
47
+ * @param {{ port?: number, root: string, token?: string, resume?: { env?: Record<string,string|undefined>, bin?: string, logDir?: string, maxTries?: number, windowMs?: number, slotMs?: number } }} opts
22
48
  * `resume` is for tests only (a fake env/bin, a short retry window); the CLI passes none.
23
- * @returns {Promise<{ server: import('node:http').Server, port: number, close: () => Promise<void> }>}
49
+ * @returns {Promise<{ server: import('node:http').Server, port: number, token: string, close: () => Promise<void> }>}
24
50
  */
25
51
  export function createPanelServer(opts: {
26
52
  port?: number;
27
53
  root: string;
54
+ token?: string;
28
55
  resume?: {
29
56
  env?: Record<string, string | undefined>;
30
57
  bin?: string;
@@ -36,6 +63,7 @@ export function createPanelServer(opts: {
36
63
  }): Promise<{
37
64
  server: import("node:http").Server;
38
65
  port: number;
66
+ token: string;
39
67
  close: () => Promise<void>;
40
68
  }>;
41
69
  /**