fwdloop 0.10.0 → 0.12.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
@@ -25,13 +25,22 @@ import {
25
25
  } from '../src/flow.js';
26
26
  import { loadCatalogue } from '../src/catalogue.js';
27
27
  import {
28
- runFlow, resumeRun, makeParkingAskStep, readAsk,
28
+ runFlow, resumeRun, makeParkingAskStep, readAsk, readRunState,
29
29
  } from '../src/runner.js';
30
30
  import { makeLiveModelStep } from '../src/model-step.js';
31
31
  import { sendViaPrimitive } from '../src/send.js';
32
32
  import { resolvePrimitives } from '../src/primitives.js';
33
- import { checkKeyPreflight } from '../src/provider.js';
34
- import { answerAsk, readAskEvidence, normalizeDecision } from '../src/ask.js';
33
+ import {
34
+ checkKeyPreflight, resolveSlot, resolvePrices, readPriceConfig, ceilingCostUsd,
35
+ } from '../src/provider.js';
36
+ import { configDoorHome } from '../src/config.js';
37
+ import {
38
+ claimHold, settleHold, monthlyRefusalText, ConfigError,
39
+ } from '../src/monthly.js';
40
+ import { keysForDoor } from '../src/keysfile.js';
41
+ import {
42
+ answerAsk, readAskEvidence, normalizeDecision, stripControl, withReopen,
43
+ } from '../src/ask.js';
35
44
  import { panelMain } from '../src/panel/server.js';
36
45
  import { isInteractive, confirmTypedName, NEEDS_TTY } from '../src/sign-confirm.js';
37
46
  import { draftToDir, signDraft, SIGN_LINE, costText } from '../src/authoring.js';
@@ -43,6 +52,65 @@ import { userInfo } from 'node:os';
43
52
  // never reads a key any other way and never prints it.
44
53
  const MODEL_SLOT = 'deepseek';
45
54
 
55
+ /**
56
+ * M4d: the ONE place a keyed command gets its env — the shell env with the keys file
57
+ * (`~/.config/fwdloop/.env`) filling what the shell leaves unset, loaded once at command
58
+ * start. A file other users can read is refused here (ruling 1A), before any dir or ledger
59
+ * write, at $0. process.env is never mutated: the merged env is handed down by hand.
60
+ */
61
+ function keyedEnv() {
62
+ const loaded = keysForDoor();
63
+ if (!loaded.ok) fail(String(loaded.refusal));
64
+ return loaded.env;
65
+ }
66
+
67
+ /**
68
+ * M4d piece 3: the monthly check, at the ONE seam all three money doors (`run`, `resume`, `draft`) call,
69
+ * before any spend and before any ledger write. No limit set = a $0 hold row (so the run's spend is counted once a limit is set), no check;
70
+ * a test process with no config home = no row at all. A broken config.json or an unwritable record refuses by name, never "no limit". A hold
71
+ * that does not fit refuses at $0 with the one refusal text. A hold that fits is given back when this
72
+ * process ends or parks (the `exit` hook runs on every exit path; a SIGKILL leaves it for the next check,
73
+ * which settles it as "process gone").
74
+ * @returns {{ addRunDir: (d: string) => void }}
75
+ */
76
+ function takeMonthlyHold({ what, flow, runId, runDir, holdUsd, spentAtHold = 0 }) {
77
+ const door = configDoorHome();
78
+ const home = door.home;
79
+ const also = [];
80
+ if (door.skip) {
81
+ // A test process with no config home skips the money checks. Only an injected test hook may do that;
82
+ // a real provider call here would spend with no keys file, prices, limit or record.
83
+ const hook = what === 'draft' ? 'FWDLOOP_TEST_DRAFT_PROVIDER' : 'FWDLOOP_TEST_MODEL_STEP';
84
+ if (!(process.env.NODE_ENV === 'test' && process.env[hook])) {
85
+ fail('NODE_ENV=test is set without FWDLOOP_CONFIG_HOME, so the keys file, prices and monthly limit would be skipped. Nothing spent. Unset NODE_ENV, or set FWDLOOP_CONFIG_HOME.');
86
+ }
87
+ return { addRunDir: () => {} };
88
+ }
89
+ let claim;
90
+ try {
91
+ claim = claimHold({
92
+ what, flow, runId, runDir, holdUsd, spentAtHold, home,
93
+ });
94
+ } catch (err) {
95
+ if (!(err instanceof ConfigError)) throw err;
96
+ fail(`${err.message} — refusing to start rather than guess the monthly limit. Nothing spent.`);
97
+ }
98
+ if (!claim.ok) fail(monthlyRefusalText(claim.room));
99
+ if (claim.holdId !== null) {
100
+ process.on('exit', () => settleHold({
101
+ holdId: claim.holdId, why: process.exitCode ? 'ended (red)' : 'ended or parked', home, alsoRunDirs: also,
102
+ }));
103
+ }
104
+ return { addRunDir: (d) => also.push(d) };
105
+ }
106
+
107
+ /** The new runs a `rerun` chain started in this process — their spend belongs to this hold's month too. */
108
+ function rerunDirs(result, flowDir) {
109
+ const dirs = [];
110
+ for (let r = result; r && r.outcome === 'rerun'; r = r.newRun) dirs.push(join(flowDir, r.newRunId));
111
+ return dirs;
112
+ }
113
+
46
114
  function fail(message) {
47
115
  process.stderr.write(`fwdloop: ${message}\n`);
48
116
  process.exit(1);
@@ -82,7 +150,7 @@ function today() {
82
150
  * be hit by a user typing `--something`. This is how the test suite drives
83
151
  * every CLI scenario at $0 with zero chance of a real network call.
84
152
  */
85
- async function resolveModelStep(spendPath) {
153
+ async function resolveModelStep(spendPath, env) {
86
154
  if (process.env.NODE_ENV === 'test' && process.env.FWDLOOP_TEST_MODEL_STEP) {
87
155
  const modulePath = resolve(process.env.FWDLOOP_TEST_MODEL_STEP);
88
156
  const mod = await import(pathToFileURL(modulePath).href);
@@ -91,9 +159,9 @@ async function resolveModelStep(spendPath) {
91
159
  }
92
160
  return mod.default({ spendPath });
93
161
  }
94
- const keyCheck = checkKeyPreflight(MODEL_SLOT);
162
+ const keyCheck = checkKeyPreflight(MODEL_SLOT, env);
95
163
  if (!keyCheck.ok) throw new Error(keyCheck.message);
96
- return makeLiveModelStep({ slot: MODEL_SLOT, spendPath });
164
+ return makeLiveModelStep({ slot: MODEL_SLOT, spendPath, env });
97
165
  }
98
166
 
99
167
  function parseSourceFlags(list) {
@@ -174,6 +242,7 @@ async function cmdRun(rest) {
174
242
  },
175
243
  allowPositionals: true,
176
244
  });
245
+ const env = keyedEnv();
177
246
 
178
247
  const flowName = positionals[0];
179
248
  if (!flowName) fail('run: a flow name is required — fwdloop run <flow> --root <dir> --source <role>=<path> ...');
@@ -225,12 +294,18 @@ async function cmdRun(rest) {
225
294
  const spendPath = join(runDir, 'spend.jsonl');
226
295
  let modelStep;
227
296
  try {
228
- modelStep = await resolveModelStep(spendPath);
297
+ modelStep = await resolveModelStep(spendPath, env);
229
298
  } catch (err) {
230
299
  fail(err.message);
231
300
  return;
232
301
  }
233
302
 
303
+ // M4d piece 3: the monthly check — the hold is the flow's signed per-run cap. Before the run dir exists
304
+ // (runFlow makes it), so a refusal leaves only the refused rows in runs.jsonl.
305
+ const hold = takeMonthlyHold({
306
+ what: 'run', flow: flowName, runId, runDir, holdUsd: arbiter.capUsd,
307
+ });
308
+
234
309
  // Predict the frozen input paths `runFlow`'s own `freezeInputs` will use
235
310
  // (deterministic: `<runDir>/inputs/<id><ext>`) so the primitives map can
236
311
  // be built once, before `runFlow` itself freezes anything. Pure path
@@ -258,6 +333,7 @@ async function cmdRun(rest) {
258
333
  businessDate: today(),
259
334
  });
260
335
 
336
+ for (const d of rerunDirs(result, join(root, flowName))) hold.addRunDir(d);
261
337
  reportRunResult(result, { rootArg: values.root });
262
338
  }
263
339
 
@@ -288,7 +364,7 @@ function cmdInbox(rest) {
288
364
  if (!askRead.ok) continue; // eslint-disable-line no-continue -- missing (or refused) ask.json: nothing to show
289
365
  let ask;
290
366
  try {
291
- ask = JSON.parse(askRead.text);
367
+ ask = withReopen(runDir, JSON.parse(askRead.text)); // the effective deadline (a reopened ask's new one)
292
368
  } catch (err) {
293
369
  // A malformed/unparseable ask.json must never crash inbox — show it
294
370
  // naming the run as unreadable and move on to the next one.
@@ -342,11 +418,11 @@ function cmdInbox(rest) {
342
418
  continue;
343
419
  }
344
420
  if (row.status === 'legacy') {
345
- process.stdout.write(`flow=${row.flow} run=${row.runId} [legacy (not answerable)] — ${row.question}\n`);
421
+ process.stdout.write(`flow=${row.flow} run=${row.runId} [legacy (not answerable)] — ${stripControl(row.question)}\n`);
346
422
  continue;
347
423
  }
348
424
  const timeLeft = row.status === 'expired' ? 'expired' : `${Math.max(0, Math.round(row.timeLeftMs / 1000))}s left`;
349
- process.stdout.write(`${row.askId} flow=${row.flow} run=${row.runId} [${row.status}] ${timeLeft} — ${row.question}\n`);
425
+ process.stdout.write(`${row.askId} flow=${row.flow} run=${row.runId} [${row.status}] ${timeLeft} — ${stripControl(row.question)}\n`);
350
426
  }
351
427
  }
352
428
 
@@ -381,13 +457,13 @@ function cmdShow(rest) {
381
457
  }
382
458
  let ask;
383
459
  try {
384
- ask = JSON.parse(askRead.text);
460
+ ask = withReopen(runDir, JSON.parse(askRead.text)); // the effective deadline (a reopened ask's new one)
385
461
  } catch (err) {
386
462
  fail(`show: ask.json for askId "${askId}" is not valid JSON — ${err.message}`);
387
463
  return;
388
464
  }
389
465
 
390
- process.stdout.write(`question: ${ask.question}\n`);
466
+ process.stdout.write(`question: ${stripControl(ask.question)}\n`);
391
467
  process.stdout.write(`expiresAt: ${ask.expiresAt}\n`);
392
468
 
393
469
  const { draft, unjudged, why } = readAskEvidence(ask);
@@ -396,10 +472,10 @@ function cmdShow(rest) {
396
472
  return;
397
473
  }
398
474
  process.stdout.write('\n--- artifact under review ---\n');
399
- process.stdout.write(`${draft.text}\n`);
475
+ process.stdout.write(`${stripControl(draft.text)}\n`);
400
476
  for (const item of unjudged) {
401
- process.stdout.write(`\n--- unjudged: ${item.step} ---\n`);
402
- process.stdout.write(`${item.text}\n`);
477
+ process.stdout.write(`\n--- unjudged: ${stripControl(item.step)} ---\n`);
478
+ process.stdout.write(`${stripControl(item.text)}\n`);
403
479
  }
404
480
  }
405
481
 
@@ -442,6 +518,7 @@ async function cmdResume(rest) {
442
518
  },
443
519
  allowPositionals: true,
444
520
  });
521
+ const env = keyedEnv();
445
522
  const runId = positionals[0];
446
523
  if (!runId) fail('resume: a runId is required — fwdloop resume <runId> --flow <name> --root <dir>');
447
524
  if (!values.flow) fail('resume: --flow <name> is required');
@@ -456,7 +533,7 @@ async function cmdResume(rest) {
456
533
 
457
534
  const read = readFlow({ root, name: flowName, catalogue });
458
535
  if (!read.ok) fail(`flow "${flowName}": ${read.reds.join('; ')}`);
459
- const { declaration } = read;
536
+ const { declaration, arbiter } = read;
460
537
 
461
538
  const runIdCheck = resolveRunDir(join(root, flowName), runId);
462
539
  if (!runIdCheck.ok) fail(runIdCheck.red);
@@ -466,12 +543,19 @@ async function cmdResume(rest) {
466
543
  const spendPath = join(runDir, 'spend.jsonl');
467
544
  let modelStep;
468
545
  try {
469
- modelStep = await resolveModelStep(spendPath);
546
+ modelStep = await resolveModelStep(spendPath, env);
470
547
  } catch (err) {
471
548
  fail(err.message);
472
549
  return;
473
550
  }
474
551
 
552
+ // M4d piece 3: the monthly check — the hold is the signed cap minus what this run already spent (its own
553
+ // state.json; no readable figure = the whole cap, never less).
554
+ const priorSpent = Number.isFinite(readRunState(runDir)?.spent) ? readRunState(runDir).spent : 0;
555
+ const hold = takeMonthlyHold({
556
+ what: 'resume', flow: flowName, runId, runDir, holdUsd: Math.max(0, arbiter.capUsd - priorSpent), spentAtHold: priorSpent,
557
+ });
558
+
475
559
  // Resume never re-freezes inputs — the run's own `inputs.json` (written at
476
560
  // park by `freezeInputs`) is the one source of the already-frozen paths a
477
561
  // sandboxed primitive may read.
@@ -509,6 +593,7 @@ async function cmdResume(rest) {
509
593
  businessDate: today(),
510
594
  });
511
595
 
596
+ for (const d of rerunDirs(result, join(root, flowName))) hold.addRunDir(d);
512
597
  reportRunResult(result, { rootArg: values.root });
513
598
  }
514
599
 
@@ -516,8 +601,10 @@ async function cmdResume(rest) {
516
601
  // panel — M4a piece 2 + M4b (docs/wiki/the-module-ladder.md, "M4a — read-only
517
602
  // panel" and "M4b — inputs"): `fwdloop panel [--port 4800] [--root <dir>]`.
518
603
  // 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
604
+ // /api/resume (src/panel/server.js), each gated by Origin/Host + the panel's
605
+ // cookie. `fwdloop panel` writes its token to a 0600 file ($XDG_RUNTIME_DIR/fwdloop/
606
+ // panel-<port>.token, else ~/.cache/fwdloop/; reused across restarts while that file is 0600) and prints `http://127.0.0.1:<port>/?t=<token>` —
607
+ // open that link (it sets the cookie); every request needs it. Bound to 127.0.0.1 only. Never picks
521
608
  // a different port on collision — a taken port is a loud, non-zero-exit
522
609
  // failure.
523
610
  // ---------------------------------------------------------------------------
@@ -559,6 +646,7 @@ async function cmdDraft(rest) {
559
646
  },
560
647
  allowPositionals: true,
561
648
  });
649
+ const env = keyedEnv();
562
650
  const proseFile = positionals[0];
563
651
  if (!proseFile) fail('draft: a prose file is required — fwdloop draft <prose.txt> --out <draftDir> --root <flowsDir> --name <flow> [--budget <usd>]');
564
652
  for (const req of ['out', 'root', 'name']) if (!values[req]) fail(`draft: --${req} is required`);
@@ -568,12 +656,33 @@ async function cmdDraft(rest) {
568
656
  const mod = await import(pathToFileURL(resolve(process.env.FWDLOOP_TEST_DRAFT_PROVIDER)).href);
569
657
  injected = await mod.default();
570
658
  }
659
+ // The key preflight comes first (draftToDir repeats it), so an unset key keeps its own message ahead of the NODE_ENV refusal.
660
+ if (injected.provider == null) {
661
+ const keyCheck = checkKeyPreflight('deepseek', env);
662
+ if (!keyCheck.ok) fail(`draft refused at $0 — ${keyCheck.message}`);
663
+ }
664
+ // M4d piece 3: the monthly check — a draft has no signed cap, so it holds one ceiling round, priced by the
665
+ // ONE price lookup (an injected test provider carries its own rates).
666
+ let ceiling;
667
+ try {
668
+ const priceConfig = readPriceConfig();
669
+ const modelId = injected.modelId ?? resolveSlot('deepseek', { config: priceConfig }).model;
670
+ const prices = injected.rates ? { rates: injected.rates } : resolvePrices(modelId, { slot: 'deepseek', config: priceConfig });
671
+ ceiling = ceilingCostUsd(modelId, undefined, { prices });
672
+ } catch (err) {
673
+ if (!(err instanceof ConfigError)) throw err;
674
+ fail(`${err.message} — refusing to draft rather than guess the price. Nothing spent.`);
675
+ }
676
+ takeMonthlyHold({
677
+ what: 'draft', flow: values.name, runId: null, runDir: resolve(values.out), holdUsd: ceiling,
678
+ });
571
679
  const result = await draftToDir({
572
680
  proseFile: resolve(proseFile),
573
681
  dir: resolve(values.out),
574
682
  root: resolve(values.root),
575
683
  name: values.name,
576
684
  budgetUsd: values.budget === undefined ? undefined : Number(values.budget),
685
+ env,
577
686
  ...injected,
578
687
  });
579
688
  const cost = result.costUsd === null ? 'UNKNOWN' : costText(Number(result.costUsd), result.spendComplete);
@@ -597,6 +706,7 @@ async function cmdSign(rest) {
597
706
  options: { approve: { type: 'string' }, 'signed-by': { type: 'string' } },
598
707
  allowPositionals: true,
599
708
  });
709
+ const env = keyedEnv(); // sign takes no key, but its leak sweep must know the file's keys too
600
710
  const dir = positionals[0];
601
711
  if (!dir) fail('sign: a draft dir is required — fwdloop sign <dir> --approve <hash>');
602
712
  // Amendment 2: a person at a keyboard. TTY check first (cheapest), then the typed flow name; only then
@@ -609,7 +719,7 @@ async function cmdSign(rest) {
609
719
  const typed = await confirmTypedName({ name: flowName });
610
720
  if (!typed.ok) fail(`sign refused — ${typed.red}`);
611
721
  const result = signDraft({
612
- dir: resolve(dir), approve: values.approve, signedBy: values['signed-by'] ?? userInfo().username,
722
+ dir: resolve(dir), approve: values.approve, signedBy: values['signed-by'] ?? userInfo().username, env,
613
723
  });
614
724
  if (!result.ok) fail(`sign refused — ${result.reds.join('; ')}`);
615
725
  process.stdout.write(`signed: ${result.flowDir} (by ${result.signature.signedBy})\n`);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "fwdloop",
3
- "version": "0.10.0",
3
+ "version": "0.12.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
@@ -17,7 +17,7 @@
17
17
  // not a second Checkpoint instance layered on top of the same file protocol.
18
18
 
19
19
  import {
20
- existsSync, mkdirSync, readFileSync, renameSync, writeFileSync,
20
+ existsSync, linkSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync,
21
21
  } from 'node:fs';
22
22
  import { join } from 'node:path';
23
23
  import { createHash, randomUUID } from 'node:crypto';
@@ -58,10 +58,25 @@ export function normalizeDecision(decision) {
58
58
  return decision === 'reject' ? 'redo' : decision;
59
59
  }
60
60
 
61
+ /** Terminal control codes out of text a model wrote, before it reaches a terminal: C0 (incl. ESC, which starts
62
+ * every CSI/OSC sequence), DEL and C1 (incl. the one-byte CSI, U+009B). Keeps \n and \t. A stripped ESC leaves the
63
+ * sequence's printable tail ("[2J") visible, which is inert. */
64
+ export function stripControl(text) {
65
+ // eslint-disable-next-line no-control-regex
66
+ return String(text).replace(/[\x00-\x08\x0B-\x1F\x7F-\x9F]/g, '');
67
+ }
68
+
61
69
  /** The one decision -> status table, used by `listArchivedAsks` here and by the panel's legacy-ask rows.
62
70
  * Look it up with `normalizeDecision(decision)`. */
63
71
  export const DECISION_STATUS = { accept: 'accepted', redo: 'redo', rerun: 'reran' };
64
72
 
73
+ /** The status for a decision word read from disk, or undefined for anything that is not one of the table's OWN
74
+ * entries ("constructor", "toString" and the rest of Object.prototype read as unrecognised). */
75
+ export function decisionStatus(decision) {
76
+ const word = normalizeDecision(decision);
77
+ return typeof word === 'string' && Object.hasOwn(DECISION_STATUS, word) ? DECISION_STATUS[word] : undefined;
78
+ }
79
+
65
80
  function sleep(ms) {
66
81
  return new Promise((resolve) => { setTimeout(resolve, ms); });
67
82
  }
@@ -262,9 +277,171 @@ export function sha256Hex(serialised) {
262
277
  return createHash('sha256').update(Buffer.from(serialised, 'utf8')).digest('hex');
263
278
  }
264
279
 
280
+ /**
281
+ * M4c-fix amendment 1 (a): why a saved `answer.json` is not a usable answer for the open ask `openAskId`, or `null`
282
+ * when it is usable. The resume refuses each of these by name before it consumes the file, so without a way aside
283
+ * the file would block every new answer (`answerAsk`'s exclusive create).
284
+ * @param {string} text the file's text @param {string} openAskId
285
+ * @returns {string|null}
286
+ */
287
+ export function brokenAnswerWhy(text, openAskId) {
288
+ let a;
289
+ try { a = JSON.parse(text); } catch { return 'it is not valid JSON'; }
290
+ if (a === null || typeof a !== 'object' || Array.isArray(a)) return 'it is not a JSON object';
291
+ if (a.askId !== openAskId) return `it names another ask ("${a.askId}")`;
292
+ if (Number.isNaN(Date.parse(typeof a.answeredAt === 'string' ? a.answeredAt : ''))) return 'it carries no readable saved time';
293
+ return null;
294
+ }
295
+
296
+ /**
297
+ * Move `answer.json` aside as a record: `answer.<askId>.<kind>.<n>.json`, `n` the first free number. Write-once:
298
+ * the new name is created with a hard link (`EEXIST` = taken, try the next), then the old name is removed — never
299
+ * a rename, which would overwrite; never a delete of the content. A symlinked `answer.json` is refused, not followed.
300
+ * @param {string} runDir @param {string} askId @param {'broken'|'late'} kind
301
+ * @returns {{ ok: true, name: string } | { ok: false, red: string }}
302
+ */
303
+ export function setAsideAnswer(runDir, askId, kind) {
304
+ const resolved = resolveInside(runDir, 'answer.json');
305
+ if (!resolved.ok) return { ok: false, red: `answer.json cannot be set aside — ${'red' in resolved ? resolved.red : 'it is missing'}` };
306
+ for (let n = 1; n < 1000; n += 1) {
307
+ const name = `answer.${askId}.${kind}.${n}.json`;
308
+ try {
309
+ linkSync(resolved.full, join(runDir, name));
310
+ } catch (err) {
311
+ if (err.code === 'EEXIST') continue; // eslint-disable-line no-continue
312
+ return { ok: false, red: `answer.json could not be set aside — ${err.message}` };
313
+ }
314
+ try { unlinkSync(resolved.full); } catch { /* already moved by another process: the record exists either way */ }
315
+ return { ok: true, name };
316
+ }
317
+ return { ok: false, red: 'answer.json could not be set aside — no free record name' };
318
+ }
319
+
320
+ // ---------------------------------------------------------------------------
321
+ // M4c-fix amendment 1 (b): an expired ask can be reopened — by a human only. A reopen never rewrites `ask.json`,
322
+ // `state.json` or the archive (nothing existing is rewritten): it is a new write-once record,
323
+ // `reopen.<askId>.<n>.json` (`wx`, `n` = the next free number), holding who/when/the new deadline. The deadline of
324
+ // an ask is read in ONE place, `effectiveExpiresAt`: the newest reopen record for that askId, else the ask's own
325
+ // `expiresAt`. Every reader of a deadline (answerAsk, the resume, the panel, the CLI) goes through it.
326
+ // ---------------------------------------------------------------------------
327
+
328
+ const REOPEN_RE = /^reopen\.(.+)\.(\d+)\.json$/;
329
+
330
+ /**
331
+ * The deadline an ask is judged against: the newest valid reopen record's `expiresAt`, else `original`.
332
+ * A record that is unreadable, names another ask, or holds no parseable `expiresAt` is ignored.
333
+ * @param {string} runDir @param {string} askId @param {string} original the ask's own `expiresAt`
334
+ * @returns {string}
335
+ */
336
+ export function effectiveExpiresAt(runDir, askId, original) {
337
+ let best = null;
338
+ for (const name of readdirInside(runDir, '.')) {
339
+ const m = REOPEN_RE.exec(name);
340
+ if (!m || m[1] !== askId) continue; // eslint-disable-line no-continue
341
+ const n = Number(m[2]);
342
+ if (best && best.n >= n) continue; // eslint-disable-line no-continue
343
+ const r = readFileInside(runDir, name);
344
+ if (!r.ok) continue; // eslint-disable-line no-continue
345
+ let rec;
346
+ try { rec = JSON.parse(r.text); } catch { continue; } // eslint-disable-line no-continue
347
+ if (rec === null || typeof rec !== 'object' || rec.askId !== askId || typeof rec.expiresAt !== 'string' || Number.isNaN(Date.parse(rec.expiresAt))) continue; // eslint-disable-line no-continue
348
+ best = { n, expiresAt: rec.expiresAt };
349
+ }
350
+ return best ? best.expiresAt : original;
351
+ }
352
+
353
+ /**
354
+ * An `ask.json`-shaped object as every reader should see it: `expiresAt` is the effective deadline, and `waitMs`
355
+ * is the signed wait the ask was parked with (its own `expiresAt` minus `askedAt`, written from the signed ttl),
356
+ * which a reopen repeats. `waitMs` is `null` when either time cannot be read.
357
+ * @param {string} runDir @param {any} ask
358
+ * @returns {any}
359
+ */
360
+ export function withReopen(runDir, ask) {
361
+ if (ask === null || typeof ask !== 'object' || typeof ask.askId !== 'string') return ask;
362
+ const waitMs = Date.parse(ask.expiresAt) - Date.parse(ask.askedAt);
363
+ return {
364
+ ...ask,
365
+ expiresAt: typeof ask.expiresAt === 'string' ? effectiveExpiresAt(runDir, ask.askId, ask.expiresAt) : ask.expiresAt,
366
+ waitMs: Number.isFinite(waitMs) && waitMs > 0 ? waitMs : null,
367
+ };
368
+ }
369
+
370
+ /**
371
+ * Reopen an expired ask: a fresh window of the same signed length, starting now, on the same ask (the same draft;
372
+ * nothing about the run changes). Human only — the caller names who (`by`); no runner, agent or resume path calls this.
373
+ * Refused, by name, when: there is no such open ask, its answer was already taken, it has not expired, or a saved
374
+ * answer made in time is waiting (that one is resumed, not reopened). A late or broken saved answer is moved aside
375
+ * as a record (`answer.<askId>.late.<n>.json`, never deleted). Two clicks race on the record's exclusive create:
376
+ * the loser is refused "already reopened", so a double click opens one window, not two.
377
+ * @param {{ runDir: string, askId: string, by: string, clock?: () => string }} opts
378
+ * @returns {{ ok: true, expiresAt: string, n: number, setAside: string|null } | { ok: false, red: string }}
379
+ */
380
+ export function reopenAsk({
381
+ runDir, askId, by, clock,
382
+ }) {
383
+ const nowIso = (typeof clock === 'function' ? clock : () => new Date().toISOString())();
384
+ if (typeof runDir !== 'string' || runDir.length === 0) return { ok: false, red: 'reopenAsk: "runDir" must be a non-empty string' };
385
+ if (typeof askId !== 'string' || askId.length === 0) return { ok: false, red: 'reopenAsk: "askId" must be a non-empty string' };
386
+ if (typeof by !== 'string' || by.length === 0) return { ok: false, red: 'reopenAsk: "by" must name who reopened it' };
387
+ const askRead = readFileInside(runDir, 'ask.json');
388
+ if (!askRead.ok) return { ok: false, red: `reopenAsk: no open ask for run ${runDir}` };
389
+ let raw;
390
+ try { raw = JSON.parse(askRead.text); } catch (err) { return { ok: false, red: `reopenAsk: ask.json for run ${runDir} is not valid JSON — ${err.message}` }; }
391
+ if (raw === null || typeof raw !== 'object' || raw.askId !== askId) return { ok: false, red: `reopenAsk: askId "${askId}" is unknown for run ${runDir}` };
392
+ const ask = withReopen(runDir, raw);
393
+ if (Number.isNaN(Date.parse(ask.expiresAt))) return { ok: false, red: `reopenAsk: askId "${askId}" has an unparseable expiresAt — refusing` };
394
+ if (ask.waitMs === null) return { ok: false, red: `reopenAsk: askId "${askId}" carries no readable wait (askedAt/expiresAt) to repeat — refusing` };
395
+ if (existsSync(join(runDir, `answer.${askId}.consumed.json`))) return { ok: false, red: `reopenAsk: askId "${askId}" already answered for run ${runDir}` };
396
+ if (Date.parse(nowIso) <= Date.parse(ask.expiresAt)) return { ok: false, red: `reopenAsk: askId "${askId}" has not expired (it runs until ${ask.expiresAt})` };
397
+ const saved = readFileInside(runDir, 'answer.json');
398
+ let timing = null;
399
+ if (saved.ok) {
400
+ let a = null;
401
+ try { a = JSON.parse(saved.text); } catch { /* broken: set aside below */ }
402
+ timing = a !== null && typeof a === 'object' && a.askId === askId ? answerTiming(a.answeredAt, ask.expiresAt) : 'unreadable';
403
+ if (timing === 'on-time') return { ok: false, red: `reopenAsk: askId "${askId}" has an answer saved in time — resume it, it is not expired` };
404
+ }
405
+ // Amendment 3 (b): the stale answer is moved aside FIRST. If that fails nothing is written (no record, no audit
406
+ // row, the clock stays), so a stale answer can never count as fresh under a new deadline. If the record write then
407
+ // fails, the answer stays set aside: it was late or broken anyway, and the ask is simply still expired.
408
+ let setAside = null;
409
+ if (saved.ok) {
410
+ const moved = setAsideAnswer(runDir, askId, timing === 'late' ? 'late' : 'broken');
411
+ if (!moved.ok) return { ok: false, red: 'Could not clear the late answer; nothing was reopened.' };
412
+ setAside = moved.name;
413
+ }
414
+ // The record: write-once, keyed by askId and its number. The exclusive create is the one gate.
415
+ let n = 1;
416
+ for (const name of readdirInside(runDir, '.')) {
417
+ const m = REOPEN_RE.exec(name);
418
+ if (m && m[1] === askId) n = Math.max(n, Number(m[2]) + 1);
419
+ }
420
+ const expiresAt = new Date(Date.parse(nowIso) + ask.waitMs).toISOString();
421
+ const record = {
422
+ askId, n, by, at: nowIso, previousExpiresAt: ask.expiresAt, expiresAt, waitMs: ask.waitMs,
423
+ };
424
+ try {
425
+ writeFileSync(join(runDir, `reopen.${askId}.${n}.json`), JSON.stringify(record, null, 2), { flag: 'wx' });
426
+ } catch (err) {
427
+ if (err.code === 'EEXIST') return { ok: false, red: `reopenAsk: askId "${askId}" was already reopened (record ${n} exists)` };
428
+ return { ok: false, red: `reopenAsk: could not write the reopen record — ${err.message}` };
429
+ }
430
+ // The run's audit book names the reopen too (amendment 1 (b): "the audit records who reopened it and when"),
431
+ // through the one audit writer; a pure note (cost 0, no model), shaped like the stale-answer row.
432
+ appendAudit(runDir, {
433
+ step: 'ask', attempt: raw.attempt ?? null, class: null, verdict: 'ask-reopened',
434
+ gap: `reopened by ${by} at ${nowIso} (ask ${askId}); deadline ${ask.expiresAt} -> ${expiresAt}`,
435
+ usd: 0, spendComplete: true, wallMs: 0, model: null, modelMatch: null, strike: false, at: nowIso, tokens: null, tools: null, refused: [],
436
+ });
437
+ return {
438
+ ok: true, expiresAt, n, setAside,
439
+ };
440
+ }
441
+
265
442
  /**
266
443
  * @param {{ runDir: string, askId: string, decision: 'accept'|'redo'|'reject'|'rerun', reason?: string, clock?: () => string }} opts
267
- * @returns {{ ok: true } | { ok: false, red: string }}
444
+ * @returns {{ ok: true, setAside: string|null } | { ok: false, red: string }}
268
445
  */
269
446
  export function answerAsk({
270
447
  runDir, askId, decision: givenDecision, reason, clock,
@@ -310,8 +487,10 @@ export function answerAsk({
310
487
  if (Number.isNaN(Date.parse(ask.expiresAt))) {
311
488
  return { ok: false, red: `answerAsk: askId "${askId}" has an unparseable expiresAt "${ask.expiresAt}" for run ${runDir} — refusing rather than treating it as not-expired` };
312
489
  }
313
- if (Date.parse(nowIso) > Date.parse(ask.expiresAt)) {
314
- return { ok: false, red: `answerAsk: askId "${askId}" expired at ${ask.expiresAt} for run ${runDir}` };
490
+ // The deadline is the reopened one when the ask was reopened (`effectiveExpiresAt`, the one reader).
491
+ const expiresAt = effectiveExpiresAt(runDir, askId, ask.expiresAt);
492
+ if (Date.parse(nowIso) > Date.parse(expiresAt)) {
493
+ return { ok: false, red: `answerAsk: askId "${askId}" expired at ${expiresAt} for run ${runDir}` };
315
494
  }
316
495
 
317
496
  const answerPath = join(runDir, 'answer.json');
@@ -349,6 +528,18 @@ export function answerAsk({
349
528
  // the exclusive gate (fails EEXIST if the file already exists), so there
350
529
  // is no window between "is it answered" and "answer it" for a second
351
530
  // caller to land in.
531
+ // M4c-fix amendment 1 (a): a saved answer that is broken (not JSON, not an object, names another ask, no readable
532
+ // time) would block this write for good — it is moved aside as a record first (never deleted). Only a broken one.
533
+ let setAside = null;
534
+ const savedRead = readFileInside(runDir, 'answer.json');
535
+ if (savedRead.ok) {
536
+ const why = brokenAnswerWhy(savedRead.text, askId);
537
+ if (why !== null) {
538
+ const moved = setAsideAnswer(runDir, askId, 'broken');
539
+ if (!moved.ok) return { ok: false, red: `answerAsk: askId "${askId}" — a broken saved answer (${why}) is in the way — ${moved.red}` };
540
+ setAside = moved.name;
541
+ }
542
+ }
352
543
  try {
353
544
  writeFileSync(answerPath, JSON.stringify(payload, null, 2), { flag: 'wx' });
354
545
  } catch (err) {
@@ -357,7 +548,7 @@ export function answerAsk({
357
548
  }
358
549
  return { ok: false, red: `answerAsk: could not write ${answerPath} — ${err.message}` };
359
550
  }
360
- return { ok: true };
551
+ return { ok: true, setAside };
361
552
  }
362
553
 
363
554
  // ---------------------------------------------------------------------------
@@ -538,7 +729,7 @@ export function listArchivedAsks(runDir) {
538
729
  try {
539
730
  parsed = JSON.parse(consumedRead.text);
540
731
  answer = {
541
- status: DECISION_STATUS[normalizeDecision(parsed.decision)] ?? `unrecognised: ${parsed.decision}`,
732
+ status: decisionStatus(parsed.decision) ?? `unrecognised: ${parsed.decision}`,
542
733
  answeredAt: parsed.answeredAt,
543
734
  };
544
735
  if (typeof parsed.reason === 'string') answer.reason = parsed.reason;
@@ -546,7 +737,7 @@ export function listArchivedAsks(runDir) {
546
737
  answer = { status: 'open', why: `${join(runDir, consumedRelPath)} is not valid JSON — ${err.message}` };
547
738
  }
548
739
  } else if (typeof ask.expiresAt === 'string' && !Number.isNaN(Date.parse(ask.expiresAt))
549
- && Date.now() > Date.parse(ask.expiresAt)) {
740
+ && Date.now() > Date.parse(effectiveExpiresAt(runDir, askId, ask.expiresAt))) {
550
741
  answer = { status: 'expired' };
551
742
  } else {
552
743
  answer = { status: 'unanswered' };
@@ -556,7 +747,8 @@ export function listArchivedAsks(runDir) {
556
747
  askId,
557
748
  question: ask.question,
558
749
  askedAt: ask.askedAt,
559
- expiresAt: ask.expiresAt,
750
+ expiresAt: typeof ask.expiresAt === 'string' ? effectiveExpiresAt(runDir, askId, ask.expiresAt) : ask.expiresAt,
751
+ waitMs: withReopen(runDir, ask).waitMs ?? null,
560
752
  evidence: readAskEvidence(ask),
561
753
  answer,
562
754
  ...(typeof ask.emits === 'string' ? { emits: ask.emits } : {}),