fwdloop 0.13.0 → 0.14.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.
@@ -287,6 +287,7 @@ async function stopRoute(res, body, root) {
287
287
  root, name: flow, runId, catalogue: loaded.primitives,
288
288
  });
289
289
  if (stopped.outcome === 'stopped') { sendJson(res, 202, { ok: true, stopping: false, stopped: true }); return; }
290
+ if (stopped.outcome === 'stop-failed') { sendJson(res, 500, { ok: false, refused: 'stop-failed', say: stopped.red }); return; }
290
291
  // not parked after all (a resume took its answer) or a resume still closing: the request stays for the runner's own seam
291
292
  }
292
293
  sendJson(res, 202, { ok: true, stopping: true, already: written === 'exists' });
@@ -318,7 +319,7 @@ function resumeRoute(res, body, root, resumer) {
318
319
  }
319
320
 
320
321
  /**
321
- * `POST /api/author/{draft,run,resume-prepare,resume,<id>/sign-prepare,<id>/sign,<id>/revise,<id>/abandon,start/<id>/clear}` — run after the same gates as every other POST.
322
+ * `POST /api/author/{draft,run,resume-prepare,resume,<id>/sign-prepare,<id>/sign,<id>/revise,<id>/answer,<id>/abandon,start/<id>/clear}` — run after the same gates as every other POST.
322
323
  * Anything else under `/api/author/` is a 404 by name.
323
324
  * @param {any} res @param {string} url @param {any} body @param {ReturnType<typeof createAuthor>} author
324
325
  */
@@ -335,6 +336,8 @@ function authorPost(res, url, body, author) {
335
336
  if (sg) { send(author.sign(sg[1], body)); return; }
336
337
  const rv = /^\/api\/author\/([^/]+)\/revise$/.exec(url);
337
338
  if (rv) { send(author.revise(rv[1], body)); return; }
339
+ const an = /^\/api\/author\/([^/]+)\/answer$/.exec(url);
340
+ if (an) { send(author.answer(an[1], body)); return; }
338
341
  const sc = /^\/api\/author\/start\/([^/]+)\/clear$/.exec(url);
339
342
  if (sc) { send(author.startClear(sc[1])); return; }
340
343
  const m = /^\/api\/author\/([^/]+)\/abandon$/.exec(url);
@@ -1,7 +1,7 @@
1
1
  // borrowed-from: bareloop src/panel/settingsroutes.js@2b101d5 — ADAPTED for fwdloop.
2
2
  // M4d piece 4 (docs/wiki/the-module-ladder.md, "M4d", scope items 2-3): the Settings routes under
3
3
  // `/api/settings/`, dispatched by `src/panel/server.js` AFTER the same gates as every other route
4
- // (Host, cookie, and for a POST: Origin + the 8 KiB body cap). This file only decides what a settings
4
+ // (Host, and for a POST: Origin + the 8 KiB body cap). This file only decides what a settings
5
5
  // request means.
6
6
  //
7
7
  // What it never does (negatives (i) (ii) (ix) (xiv)):
package/src/runner.js CHANGED
@@ -51,7 +51,9 @@ import {
51
51
  import {
52
52
  writeAskArchive, readAcceptedHashesByEmits, serializeArtifact, normalizeDecision, answerTiming, effectiveExpiresAt, withReopen, setAsideAnswer,
53
53
  } from './ask.js';
54
- import { findUnwiredVerbStep, unwiredRed } from './canrun.js'; // M4e am7 item 7: the ONE decider (F46 refusal lives there)
54
+ import {
55
+ findUnwiredVerbStep, unwiredRed, findUnbuildableCheckStep, unbuildableRed,
56
+ } from './canrun.js'; // M4e am7 item 7: the ONE decider (F46 refusal lives there)
55
57
  import { configHome, configDoorHome } from './config.js';
56
58
  import { closeByClass } from './closers.js';
57
59
  import {
@@ -114,11 +116,22 @@ export function requestStop(runDir) {
114
116
  }
115
117
  }
116
118
 
117
- /** The ONE reader of the stop request: `{at}` (when it was asked; null if unreadable) or `null` when none is pending. @param {string} runDir */
118
- export function readStopRequest(runDir) {
119
+ /**
120
+ * The ONE reader of the stop request: `{at}` (when it was asked) or `null` when none is pending. Amendment 16 C11 / amendment 17 2A: a
121
+ * time that is not a real date (a non-date string, a number, a missing or empty time, a torn file) is treated as made "now" (`now`,
122
+ * when given), one rule for all, so the stop completes with every record and the ask is never lost. Without `now` (a pending check)
123
+ * such a request reads `{at:null}`.
124
+ * @param {string} runDir @param {() => string} [now]
125
+ */
126
+ export function readStopRequest(runDir, now) {
119
127
  const r = readFileInside(runDir, STOP_FILE);
120
128
  if (!r.ok) return null;
121
- try { const at = JSON.parse(r.text)?.at; return { at: typeof at === 'string' ? at : null }; } catch { return { at: null }; }
129
+ let at = null;
130
+ try {
131
+ const t = JSON.parse(r.text)?.at;
132
+ if (typeof t === 'string' && !Number.isNaN(Date.parse(t))) at = t;
133
+ } catch { /* a torn file: no time */ }
134
+ return { at: at ?? (typeof now === 'function' ? now() : null) };
122
135
  }
123
136
 
124
137
  /** Is a stop pending for this run? (read-only) @param {string} runDir */
@@ -143,7 +156,7 @@ export function stopPending(runDir) {
143
156
  function settleStop({
144
157
  runDir, now, outcome, stop = null,
145
158
  }) {
146
- const req = readStopRequest(runDir);
159
+ const req = readStopRequest(runDir, now);
147
160
  if (!req && !stop) return;
148
161
  const lastStep = () => readAudit(runDir).map((r) => r.step).filter((s) => typeof s === 'string' && s.length > 0).pop() ?? null;
149
162
  const step = stop ? (stop.step ?? stop.book?.step ?? null) : lastStep();
@@ -873,7 +886,7 @@ async function runStepRalph({
873
886
  continue;
874
887
  }
875
888
 
876
- const closed = closeByClass(step, artifact, { reads: readsMap, businessDate });
889
+ const closed = await closeByClass(step, artifact, { reads: readsMap, businessDate });
877
890
 
878
891
  if (closed.verdict === 'green' || closed.verdict === 'hitl') {
879
892
  recordAudit(makeAuditRow({
@@ -1011,6 +1024,14 @@ export async function runFlow({
1011
1024
  });
1012
1025
  }
1013
1026
 
1027
+ // M4e amendment 19 4: every softgreen check is built before the first model call; one that cannot be built is refused at $0, by step name
1028
+ const unbuildable = findUnbuildableCheckStep(declaration);
1029
+ if (unbuildable) {
1030
+ return haltRun({
1031
+ flowDir, runDir, runId, capUsd, startedAt, now, nowMs: getNowMs, signatureHash: signature.flow, outcome: 'preflight-red', red: unbuildableRed(unbuildable), detail: unbuildable.why, spent: { value: 0 },
1032
+ });
1033
+ }
1034
+
1014
1035
  if (primitiveReds?.length) {
1015
1036
  return haltRun({
1016
1037
  flowDir, runDir, runId, capUsd, startedAt, now, nowMs: getNowMs, signatureHash: signature.flow, outcome: 'preflight-red', red: primitiveReds[0], spent: { value: 0 },
@@ -1307,7 +1328,7 @@ async function runAskSlot({
1307
1328
  flowDir, runDir, runId, capUsd, startedAt: runStartedAt, now, signatureHash, spent, spendComplete: spendComplete.value, attempts: attemptsLog, artifacts,
1308
1329
  stepIndex, stepEmits: step.emits ?? step.goal ?? null, flowRoot, flowName, inputsManifest, unjudged: evidenceUnjudged, redone, parkedAskId: askId,
1309
1330
  });
1310
- if (stopped) return { type: 'stopped', result: stopped };
1331
+ if (stopped && stopped.outcome !== 'stop-failed') return { type: 'stopped', result: stopped };
1311
1332
  }
1312
1333
  return {
1313
1334
  type: 'paused',
@@ -1658,14 +1679,18 @@ async function foldFromStep({
1658
1679
  // run really was sitting there waiting on a human, so it belongs in
1659
1680
  // "how long did this run take", not carved out of it.
1660
1681
  const wallMs = nowMs() - runStartedAt;
1661
- appendHistory(flowDir, {
1662
- runId, at: now(), outcome: 'complete', spentUsd: spent.value, spendComplete: spendComplete.value, capUsd, wallMs, signatureHash,
1663
- });
1664
- recordLateAnswerIfAny(runDir, now);
1665
- writeLog(runDir, {
1666
- runId, outcome: 'complete', attempts: attemptsLog, artifacts,
1667
- });
1668
- settleStop({ runDir, now, outcome: 'complete' });
1682
+ try {
1683
+ recordLateAnswerIfAny(runDir, now);
1684
+ writeLog(runDir, {
1685
+ runId, outcome: 'complete', attempts: attemptsLog, artifacts,
1686
+ });
1687
+ settleStop({ runDir, now, outcome: 'complete' });
1688
+ } finally {
1689
+ // Amendment 16 C6/C7: the history end row is written last, and always.
1690
+ appendHistory(flowDir, {
1691
+ runId, at: now(), outcome: 'complete', spentUsd: spent.value, spendComplete: spendComplete.value, capUsd, wallMs, signatureHash,
1692
+ });
1693
+ }
1669
1694
  return {
1670
1695
  outcome: 'complete', runDir, artifacts, spentUsd: spent.value,
1671
1696
  };
@@ -1804,12 +1829,15 @@ function sameRoot(recorded, requested) {
1804
1829
  * @param {string} opts.businessDate
1805
1830
  * @param {number} [opts.ceilingUsd]
1806
1831
  * @param {() => number} [opts.nowMs] - F45 finding 3; see `runFlow`'s own.
1832
+ * @param {(newRunDir:string) => void} [opts.onRerunStart] - amendment 16 C2: called with the new run's folder just before a `rerun` starts it.
1807
1833
  */
1808
1834
  export async function resumeRun({
1809
1835
  root, name, runId, catalogue, modelStep, sendStep, primitives, primitiveReds, clock, businessDate, ceilingUsd,
1810
1836
  // F45 finding 3 (see `runFlow`'s own `nowMs`): additive, defaults to the
1811
1837
  // real `Date.now` for every existing caller.
1812
1838
  nowMs,
1839
+ // Amendment 16 C2: called with the new run's folder just before a `rerun` starts it, so the caller can name it in the money records.
1840
+ onRerunStart,
1813
1841
  }) {
1814
1842
  const now = typeof clock === 'function' ? clock : () => new Date().toISOString();
1815
1843
  const getNowMs = typeof nowMs === 'function' ? nowMs : Date.now;
@@ -1841,6 +1869,8 @@ export async function resumeRun({
1841
1869
  red: unwiredRed(unwiredVerb),
1842
1870
  };
1843
1871
  }
1872
+ const unbuildable = findUnbuildableCheckStep(preflightRead.declaration);
1873
+ if (unbuildable) return { outcome: 'refused', red: unbuildableRed(unbuildable), detail: unbuildable.why };
1844
1874
  }
1845
1875
 
1846
1876
  if (primitiveReds?.length) return { outcome: 'refused', red: primitiveReds[0] };
@@ -2037,10 +2067,9 @@ export async function resumeRun({
2037
2067
  // park, before the Stop door could act). The run is stopped AT the ask and the answer to it is not used. A Stop asked at the same
2038
2068
  // instant as the answer, or after it, belongs to the apply that follows: the fold's own seam reads it and stops before the next
2039
2069
  // step. On a tie the ANSWER WINS (hamr's ruling, 2026-10-07: a fast CI gave both the same millisecond). A Stop with no readable
2040
- // time is stopped at the ask: conservative, stated here so it never falls out of a NaN comparison.
2041
- const stopReq = readStopRequest(runDir);
2042
- const stopMs = stopReq ? Date.parse(stopReq.at ?? '') : NaN;
2043
- const stopFirst = Number.isNaN(stopMs) || stopMs < Date.parse(answer.answeredAt);
2070
+ // time is read as made "now" by `readStopRequest` (amendment 17 2A, one rule), which is after the answer: the answer wins.
2071
+ const stopReq = readStopRequest(runDir, now);
2072
+ const stopFirst = stopReq !== null && Date.parse(/** @type {string} */ (stopReq.at)) < Date.parse(answer.answeredAt);
2044
2073
  if (stopReq && stopFirst) {
2045
2074
  const prev = readLog(runDir);
2046
2075
  return stopAtAsk({
@@ -2102,11 +2131,15 @@ export async function resumeRun({
2102
2131
  for (let i = 0; i < state.stepIndex; i += 1) {
2103
2132
  priorArtifactsForLog[steps[i].emits] = readArtifact(runDir, steps[i].emits);
2104
2133
  }
2105
- appendHistory(flowDir, {
2106
- runId, at: now(), outcome: 'rerun', spentUsd: spent.value, spendComplete: spendComplete.value, capUsd: arbiter.capUsd ?? null, wallMs: getNowMs() - runStartedAt, signatureHash: state.signatureHash,
2107
- });
2108
- recordLateAnswerIfAny(runDir, now);
2109
- writeLog(runDir, { runId, outcome: 'rerun', attempts: [], artifacts: priorArtifactsForLog });
2134
+ try {
2135
+ recordLateAnswerIfAny(runDir, now);
2136
+ writeLog(runDir, { runId, outcome: 'rerun', attempts: [], artifacts: priorArtifactsForLog });
2137
+ } finally {
2138
+ // Amendment 16 C6/C7: the history end row is written last, and always.
2139
+ appendHistory(flowDir, {
2140
+ runId, at: now(), outcome: 'rerun', spentUsd: spent.value, spendComplete: spendComplete.value, capUsd: arbiter.capUsd ?? null, wallMs: getNowMs() - runStartedAt, signatureHash: state.signatureHash,
2141
+ });
2142
+ }
2110
2143
 
2111
2144
  // Deterministic derived id (M3 scope item 7) — refused by name, never
2112
2145
  // silently renumbered, if it already exists.
@@ -2125,6 +2158,7 @@ export async function resumeRun({
2125
2158
  // they aren't already" — they already are, via this field).
2126
2159
  const rerunSources = (state.inputsManifest ?? []).map((entry) => ({ id: entry.id, path: entry.source }));
2127
2160
 
2161
+ if (typeof onRerunStart === 'function') onRerunStart(newRunDir);
2128
2162
  const newRun = await runFlow({
2129
2163
  root,
2130
2164
  name,
@@ -2344,7 +2378,7 @@ export async function continueRun({
2344
2378
  const getNowMs = typeof nowMs === 'function' ? nowMs : Date.now;
2345
2379
  const flowDir = join(root, name);
2346
2380
  const startedAt = getNowMs();
2347
- const refused = (red) => ({ outcome: 'refused', red: `continue: ${red}` });
2381
+ const refused = (red, detail) => ({ outcome: 'refused', red: `continue: ${red}`, ...(detail ? { detail } : {}) });
2348
2382
 
2349
2383
  const runIdCheck = resolveRunDir(flowDir, runId);
2350
2384
  if (!runIdCheck.ok) return { outcome: 'refused', red: runIdCheck.red };
@@ -2354,6 +2388,8 @@ export async function continueRun({
2354
2388
  if (preflightRead.ok) {
2355
2389
  const unwiredVerb = findUnwiredVerbStep(preflightRead.declaration);
2356
2390
  if (unwiredVerb) return refused(unwiredRed(unwiredVerb));
2391
+ const unbuildable = findUnbuildableCheckStep(preflightRead.declaration);
2392
+ if (unbuildable) return refused(unbuildableRed(unbuildable), unbuildable.why);
2357
2393
  }
2358
2394
  if (primitiveReds?.length) return refused(primitiveReds[0]);
2359
2395
 
@@ -2520,8 +2556,11 @@ function stopAtAsk(o) {
2520
2556
  } = o;
2521
2557
  const red = `stopped by you at the ask of step ${stepIndex + 1}`;
2522
2558
  if (parkedAskId !== null) {
2523
- try { renameSync(join(runDir, 'ask.json'), join(runDir, `ask.${parkedAskId}.stopped.json`)); } catch {
2524
- return { outcome: 'stopped', red, spentUsd: spent.value }; // another stopper won the rename: it writes the rows
2559
+ try { renameSync(join(runDir, 'ask.json'), join(runDir, `ask.${parkedAskId}.stopped.json`)); } catch (err) {
2560
+ // Amendment 16 C8: only "file not found" means another stopper won the rename (it writes the rows). Any other error is a failed
2561
+ // stop: said plainly with the error named, nothing written, the run left as it was.
2562
+ if (err?.code === 'ENOENT') return { outcome: 'stopped', red, spentUsd: spent.value };
2563
+ return { outcome: 'stop-failed', red: `the stop failed: could not set the ask aside (${err?.code ?? 'error'}: ${err?.message ?? err})`, spentUsd: spent.value };
2525
2564
  }
2526
2565
  try { renameSync(join(runDir, 'state.json'), join(runDir, `state.${parkedAskId}.stopped.json`)); } catch { /* no state: nothing to set aside */ }
2527
2566
  if (existsSync(join(runDir, 'answer.json'))) setAsideAnswer(runDir, parkedAskId, 'late');
@@ -2654,6 +2693,7 @@ export function readAsk(runDir) {
2654
2693
  * @param {() => number} [opts.nowMs] - F45 finding 3; defaults to `Date.now`.
2655
2694
  * @param {string} opts.outcome
2656
2695
  * @param {string} [opts.red]
2696
+ * @param {string|null} [opts.detail] - amendment 23: bareguard's raw reason, recorded beside `red` (never the sentence).
2657
2697
  * @param {{ value: number }} opts.spent
2658
2698
  * @param {any[]} [opts.attempts]
2659
2699
  * @param {Record<string, any>} [opts.artifacts]
@@ -2674,7 +2714,7 @@ export function readAsk(runDir) {
2674
2714
  */
2675
2715
  function haltRun({
2676
2716
  flowDir, runDir, runId, capUsd, startedAt, now, nowMs = Date.now, outcome, red, spent, attempts = [], artifacts = {}, signatureHash = null,
2677
- priorSpendComplete = true, resumeAt = null, stop = null,
2717
+ priorSpendComplete = true, resumeAt = null, stop = null, detail = null,
2678
2718
  }) {
2679
2719
  // F45 finding 3: `startedAt` here is always the RUN's start (every caller
2680
2720
  // now passes `runStartedAt` under this key — see call sites), so `wallMs`
@@ -2683,24 +2723,33 @@ function haltRun({
2683
2723
  const spendComplete = priorSpendComplete
2684
2724
  && outcome !== 'provider-red' && outcome !== 'pricing-red' && outcome !== 'cap-halt';
2685
2725
  mkdirSync(flowDir, { recursive: true });
2686
- if (existsSync(runDir)) {
2687
- recordLateAnswerIfAny(runDir, now);
2688
- writeLog(runDir, {
2689
- runId, outcome, red, attempts, artifacts,
2690
- });
2691
- // M4e amendment 4 item 4: a cap-halted or stopped run leaves the one record Resume continues from (its only writer).
2692
- if (resumeAt && HALT_OUTCOMES.includes(outcome)) {
2693
- writeFileSync(join(runDir, HALT_FILE), `${JSON.stringify({
2694
- runId, outcome, at: now(), flow: { root: resumeAt.flowRoot, name: resumeAt.flowName }, signatureHash, inputsManifest: resumeAt.inputsManifest,
2695
- stepIndex: resumeAt.stepIndex, startedAt, unjudged: resumeAt.unjudged ?? [],
2696
- ...(Number.isInteger(resumeAt.redone) ? { redone: resumeAt.redone } : {}),
2697
- }, null, 2)}\n`, { flag: 'wx' });
2698
- }
2699
- settleStop({ runDir, now, outcome, stop }); // amendment 7 item 8: every Stop leaves its rows
2726
+ try {
2727
+ if (existsSync(runDir)) {
2728
+ recordLateAnswerIfAny(runDir, now);
2729
+ writeLog(runDir, {
2730
+ runId, outcome, red, ...(detail ? { detail } : {}), attempts, artifacts,
2731
+ });
2732
+ // M4e amendment 4 item 4: a cap-halted or stopped run leaves the one record Resume continues from (its only writer).
2733
+ if (resumeAt && HALT_OUTCOMES.includes(outcome)) {
2734
+ writeFileSync(join(runDir, HALT_FILE), `${JSON.stringify({
2735
+ runId, outcome, at: now(), flow: { root: resumeAt.flowRoot, name: resumeAt.flowName }, signatureHash, inputsManifest: resumeAt.inputsManifest,
2736
+ stepIndex: resumeAt.stepIndex, startedAt, unjudged: resumeAt.unjudged ?? [],
2737
+ ...(Number.isInteger(resumeAt.redone) ? { redone: resumeAt.redone } : {}),
2738
+ }, null, 2)}\n`, { flag: 'wx' });
2739
+ }
2740
+ settleStop({ runDir, now, outcome, stop }); // amendment 7 item 8: every Stop leaves its rows
2741
+ }
2742
+ } finally {
2743
+ // The history end row is the LAST write and is always written (amendment 16 C7): a reader that sees it finds the run settled, and a
2744
+ // failed log, halt.json or settle row above never costs the row its real signature hash or the run's spend.
2745
+ // The one exception is the earlier rule (test/m4e-halt-write-order.test.js): a `stopped` row with no halt.json would read "stopped" with
2746
+ // no Resume offered, so a Stop whose halt record failed leaves no end row. C7 names the cap-halt, which always gets its row.
2747
+ const stoppedWithoutHaltRecord = outcome === 'stopped' && resumeAt && !readHaltRecord(runDir).ok;
2748
+ if (!stoppedWithoutHaltRecord) {
2749
+ appendHistory(flowDir, {
2750
+ runId, at: now(), outcome, spentUsd: spent.value, spendComplete, capUsd: capUsd ?? null, wallMs, signatureHash, ...(detail ? { detail } : {}), // amendment 23: bareguard's raw reason, never the sentence
2751
+ });
2752
+ }
2700
2753
  }
2701
- // The history end row is the LAST write: a reader that sees it finds the run fully settled (halt.json, log.json, stop rows).
2702
- appendHistory(flowDir, {
2703
- runId, at: now(), outcome, spentUsd: spent.value, spendComplete, capUsd: capUsd ?? null, wallMs, signatureHash,
2704
- });
2705
- return { outcome, red, spentUsd: spent.value };
2754
+ return { outcome, red, ...(detail ? { detail } : {}), spentUsd: spent.value };
2706
2755
  }
package/src/setup.js CHANGED
@@ -1,21 +1,23 @@
1
1
  // M4e amendment 6 item 4 (docs/wiki/the-module-ladder.md, "M4e", "Amendment 6"): the SETUP record. At sign, the draft folder's own
2
- // record (the card, each draft and change with its model, cost and verdict, each note in the human's words, and the sign) is copied once
2
+ // record (the card, each draft and revise with its model, cost and verdict, and the sign) is copied once
3
3
  // into the flow folder as `setup.jsonl`. It sits outside the three signed files (`FLOW_FILES`), so `readFlow` and the signature never see
4
4
  // it. ONE writer (`writeSetup`, called from `signDraft`, which the CLI and the panel both use) and ONE reader (`readSetup`).
5
5
  //
6
- // What each row throws away: a draft/change row keeps model, cost, calls, time, verdict, plan hash and its first red, NOT the plan itself (the signed
7
- // declaration is the plan) nor the model's tokens/rounds; a card row keeps the card's own typed fields; a note keeps its text verbatim.
6
+ // What each row throws away: a draft/revise row keeps model, cost, calls, time, verdict, plan hash and its first red, NOT the plan itself (the signed
7
+ // declaration is the plan) nor the model's tokens/rounds; a card row keeps the card's own typed fields. Rows written before amendment 14 may
8
+ // carry `note` / `change` kinds; they are only ever READ back, from the flow's own setup.jsonl.
8
9
  // Third outcomes: a draft with no result is `stopped`; a cost nobody booked is `null` (shown "unknown", never $0).
9
10
  import { lstatSync, writeFileSync } from 'node:fs';
10
11
  import { join } from 'node:path';
11
12
 
12
13
  import { scrub } from './authoring.js';
14
+ import { notCheckedBlock } from './checked.js';
13
15
  import { readDraftSpend } from './draftspend.js';
14
16
  import { readFileInside, readdirInside } from './flow.js';
15
17
  import { readSpendRows } from './provider.js';
16
18
 
17
19
  export const SETUP_FILE = 'setup.jsonl';
18
- const NOTE_RE = /^note-(\d+)\.txt$/;
20
+ const CARD_RE = /^card-(\d+)\.json$/;
19
21
 
20
22
  const readJson = (dir, rel) => {
21
23
  const r = readFileInside(dir, rel);
@@ -54,7 +56,7 @@ function planRow(sessionDir, rel, kind, n) {
54
56
  }
55
57
 
56
58
  /**
57
- * The rows of a draft's record, oldest first. `sessionDir` is the panel's draft folder (card.json, draft/, note-<n>.txt, draft-<n>/); a CLI
59
+ * The rows of a draft's record, oldest first. `sessionDir` is the panel's draft folder (card.json, draft/, card-<n>.json, draft-<n>/); a CLI
58
60
  * draft has none, so its record is its one plan folder (`planDir`, read as `draft`) plus the sign.
59
61
  * @param {{ sessionDir?: string, planDir: string, hash: string, signedBy: string, signedAt: string, flowHash?: string }} a
60
62
  */
@@ -65,21 +67,26 @@ export function buildSetupRows({
65
67
  if (sessionDir) {
66
68
  const card = readJson(sessionDir, 'card.json');
67
69
  if (card) rows.push({ kind: 'card', n: 0, at: mtimeIso(sessionDir, 'card.json'), card });
68
- rows.push(planRow(sessionDir, 'draft', 'draft', 0));
69
- const notes = readdirInside(sessionDir, '.').map((f) => NOTE_RE.exec(f)?.[1]).filter((x) => x !== undefined).map(Number).sort((a, b) => a - b);
70
- for (const n of notes) {
71
- const t = readFileInside(sessionDir, `note-${n}.txt`);
72
- rows.push({
73
- kind: 'note', n, at: mtimeIso(sessionDir, `note-${n}.txt`), text: t.ok ? t.text.replace(/\n$/, '') : '',
74
- });
75
- rows.push(planRow(sessionDir, `draft-${n}`, 'change', n));
70
+ // amendment 14 item 6: a draft begun by Start over says so (written once by the panel's start); its row reads `start over`
71
+ const so = readJson(sessionDir, 'started-over-from.json');
72
+ rows.push(planRow(sessionDir, 'draft', typeof so?.startedOverFrom === 'string' ? 'startover' : 'draft', 0));
73
+ // amendment 14 item 6: each revise is the card as submitted, then its plan row (model, cost, verdict, hash); there is no note row
74
+ const ns = readdirInside(sessionDir, '.').map((f) => CARD_RE.exec(f)?.[1]).filter((x) => x !== undefined).map(Number).sort((a, b) => a - b);
75
+ for (const n of ns) {
76
+ const card = readJson(sessionDir, `card-${n}.json`);
77
+ if (card) rows.push({ kind: 'card', n, at: mtimeIso(sessionDir, `card-${n}.json`), card });
78
+ // M4e amendment 24 item 4: a plan drafted again after the human's answers is booked as `redraft`, not `revise` (it uses none of the 2 revises)
79
+ rows.push(planRow(sessionDir, `draft-${n}`, readJson(sessionDir, `redraft-${n}.json`) ? 'redraft' : 'revise', n));
76
80
  }
77
81
  } else {
78
82
  const r = planRow(planDir, '.', 'draft', 0);
79
83
  rows.push(r);
80
84
  }
85
+ // M4e amendment 36: the drafter's own "Not checked" list (the green plan folder's not-checked.json), kept word for word with its label. Not signed,
86
+ // not in any hash. An unreadable or missing file is an empty list (a plan from before amendment 25 has none).
87
+ const notChecked = notCheckedBlock(readJson(planDir, 'not-checked.json')?.notChecked);
81
88
  rows.push({
82
- kind: 'sign', n: 0, at: signedAt, signedBy, hash, flowHash: flowHash ?? null,
89
+ kind: 'sign', n: 0, at: signedAt, signedBy, hash, flowHash: flowHash ?? null, notChecked,
83
90
  });
84
91
  return rows;
85
92
  }
@@ -17,14 +17,31 @@ export function specHash({ proseText, declarationText, inputFactsText, readoutTe
17
17
  ok: false;
18
18
  red: string;
19
19
  };
20
- /** Literal (never RegExp) key scrub; a secret under 8 chars is skipped so it can't blank ordinary text. */
21
- export function scrub(text: any, secrets: any): any;
22
20
  /**
23
- * Does `text` carry any provider key VALUE in `env` (every slot, 8+ chars, literal)? The one test for a human's free text
24
- * (the revise note) — the same literal rule `scrub` and `sweepForSecrets` use.
25
- * @param {string} text @param {Record<string, string|undefined>} env
21
+ * The questions a plan folder raised and the answers on disk, READ from its files — the ONE reader (the panel's phase reader, the sign
22
+ * checks and the page all use it). `questions` = [{ k, line, question, answer|null }], `open` = those with no answer. A blank or unreadable
23
+ * answer file counts as no answer. No questions file = `{ questions: [], open: [] }`.
24
+ * @param {string} planDir
25
+ * @returns {{ questions: {k:number, line:number, question:string, answer:string|null}[], open: {k:number, line:number, question:string, answer:null}[] }}
26
26
  */
27
- export function textHasKey(text: string, env: Record<string, string | undefined>): boolean;
27
+ export function readQuestions(planDir: string): {
28
+ questions: {
29
+ k: number;
30
+ line: number;
31
+ question: string;
32
+ answer: string | null;
33
+ }[];
34
+ open: {
35
+ k: number;
36
+ line: number;
37
+ question: string;
38
+ answer: null;
39
+ }[];
40
+ };
41
+ /** The ONE check that a plan folder with questions is not signable (CLI sign, the page's sign route and signDraft all call it). null = fine. @param {string} planDir */
42
+ export function questionsRefusal(planDir: string): "A question the plan raised is still open. Answer it in the panel (fwdloop panel), then sign the plan it drafts after your answers. Nothing was signed." | "This plan raised questions, and your answers went into a newer plan. Sign the newest plan, not this one. Nothing was signed." | null;
43
+ /** Literal (never RegExp) key scrub; a secret under 8 chars is skipped so it can't blank ordinary text. */
44
+ export function scrub(text: any, secrets: any): any;
28
45
  /** Count files directly inside `dir` that contain a secret literally. */
29
46
  export function sweepForSecrets(dir: any, secrets: any): number;
30
47
  /** Exact signed TTL with its unit, never rounded: 2h / 30m / 20s / 1500ms (the largest unit that divides it exactly). */
@@ -53,6 +70,13 @@ export function readProseFile(file: any): {
53
70
  text: string;
54
71
  red?: undefined;
55
72
  };
73
+ /**
74
+ * The ONE check of a draft's API key, at $0 before any ledger write (C3, amendment 16): `bin/fwdloop draft` and `draftToDir` both call
75
+ * it, so both refuse with the same sentence. null = the key is fine; else the sentence (never the key's value).
76
+ * @param {string} slot @param {Record<string,string|undefined>} env
77
+ * @returns {string|null}
78
+ */
79
+ export function draftKeyRefusal(slot: string, env: Record<string, string | undefined>): string | null;
56
80
  /**
57
81
  * Draft into `dir`. $0 refusals (return {ok:false, wrote:false}, nothing on disk): bad key,
58
82
  * unreadable/blank prose, prose that contains the key, missing inputs / bad signed text, dir
@@ -62,7 +86,7 @@ export function readProseFile(file: any): {
62
86
  *
63
87
  * Test seam: `provider`/`rates`/`modelId` are injected; without them a live provider is built.
64
88
  */
65
- export function draftToDir({ proseFile, dir, root, name, slot, model, budgetUsd, env, provider, rates, modelId, reviseFrom, noteFile, }: {
89
+ export function draftToDir({ proseFile, dir, root, name, slot, model, budgetUsd, env, provider, rates, modelId, noQuestions, }: {
66
90
  proseFile: any;
67
91
  dir: any;
68
92
  root: any;
@@ -74,8 +98,7 @@ export function draftToDir({ proseFile, dir, root, name, slot, model, budgetUsd,
74
98
  provider: any;
75
99
  rates: any;
76
100
  modelId: any;
77
- reviseFrom: any;
78
- noteFile: any;
101
+ noQuestions?: boolean | undefined;
79
102
  }): Promise<{
80
103
  ok: boolean;
81
104
  wrote: boolean;
@@ -101,6 +124,7 @@ export function draftToDir({ proseFile, dir, root, name, slot, model, budgetUsd,
101
124
  leaks: number;
102
125
  dir?: undefined;
103
126
  hash?: undefined;
127
+ questions?: undefined;
104
128
  stop?: undefined;
105
129
  rounds?: undefined;
106
130
  calls?: undefined;
@@ -109,6 +133,7 @@ export function draftToDir({ proseFile, dir, root, name, slot, model, budgetUsd,
109
133
  wrote: boolean;
110
134
  dir: any;
111
135
  hash: string | null;
136
+ questions: number;
112
137
  reds: any;
113
138
  costUsd: number | null;
114
139
  spendComplete: boolean;
@@ -151,5 +176,12 @@ export const SPEC_HASH_FILE: "spec.hash";
151
176
  export const PANEL_DRAFTS_DIR: ".drafts";
152
177
  /** Written when the end sweep finds a key in the draft dir; sign refuses a dir that has it. */
153
178
  export const LEAK_MARKER_FILE: "scrub-leak.red";
179
+ /** M4e amendments 24/25: the drafter's questions (written once by `fwdloop draft`), each human answer (`answer-<k>.json`, written once by the panel),
180
+ * and the drafter's own "not checked" reading (information only; never in the readout, so never in the hash). */
181
+ export const QUESTIONS_FILE: "questions.json";
182
+ export const NOT_CHECKED_FILE: "not-checked.json";
183
+ export function ANSWER_FILE(k: any): string;
154
184
  export function SIGN_LINE(dir: any, hash: any): string;
185
+ export const OPEN_QUESTION_SAY: "A question the plan raised is still open. Answer it in the panel (fwdloop panel), then sign the plan it drafts after your answers. Nothing was signed.";
186
+ export const ANSWERED_QUESTION_SAY: "This plan raised questions, and your answers went into a newer plan. Sign the newest plan, not this one. Nothing was signed.";
155
187
  export function costText(n: any, spendComplete?: boolean): string;
package/types/canrun.d.ts CHANGED
@@ -19,14 +19,46 @@ export function unwiredRed(found: {
19
19
  };
20
20
  verb: string;
21
21
  }): string;
22
+ /**
23
+ * M4e amendment 23: the ONE function that turns "this step's check cannot be built" into a plain sentence. It reads the shape, never
24
+ * bareguard's wording, so no `spec.` path or `checks[` index can reach a human. The steps are numbered by the job line they came from
25
+ * ("line 3" elsewhere), so "step 3" is job line 3. What it throws away: the raw reason (kept apart as `detail`) and any second problem
26
+ * in the same shape (the first one found is the one said). A shape it cannot classify gets the generic sentence.
27
+ * @param {number|undefined} n the step's job line
28
+ * @param {Record<string, any>} shape
29
+ * @returns {string}
30
+ */
31
+ export function unbuildableSay(n: number | undefined, shape: Record<string, any>): string;
32
+ /**
33
+ * M4e amendment 19 4: the first softgreen step whose check bareguard cannot build (a flow signed before amendment 18 may hold one), or null.
34
+ * Built with the same `buildSoftgreenRubric` the close uses, so a step that passes here never crashes at its close for want of a check.
35
+ * `why` is bareguard's raw reason, for the record only (amendment 23); `say` is the plain sentence.
36
+ * @param {Record<string, any>} declaration `readFlow`'s declaration
37
+ * @returns {{step: {emits: string, fromLine: number}, why: string, say: string}|null}
38
+ */
39
+ export function findUnbuildableCheckStep(declaration: Record<string, any>): {
40
+ step: {
41
+ emits: string;
42
+ fromLine: number;
43
+ };
44
+ why: string;
45
+ say: string;
46
+ } | null;
47
+ /** The preflight refusal sentence for a check that cannot be built: plain words, never bareguard's (that is `found.why`). @param {{say: string}} found */
48
+ export function unbuildableRed(found: {
49
+ say: string;
50
+ }): string;
22
51
  /**
23
52
  * Can this flow run? `read` is `readFlow`'s result (a failed read — signature, tampering, missing files — is a refusal with its own reds).
24
53
  * @param {any} read
25
- * @returns {{ok: true} | {ok: false, red: string}}
54
+ * @returns {{ok: true} | {ok: false, red: string, detail?: string}} `detail` is the raw reason, for the record, never the sentence
26
55
  */
27
56
  export function canFlowRun(read: any): {
28
57
  ok: true;
29
58
  } | {
30
59
  ok: false;
31
60
  red: string;
61
+ detail?: string;
32
62
  };
63
+ /** The one sentence for a signed flow that will not run: the panel's run door (the POST /api/author/run 409) and Run again say the same words. The Signed list no longer shows a refused flow. @param {string} flow @param {string} red */
64
+ export function willNotRunSay(flow: string, red: string): string;
@@ -0,0 +1,23 @@
1
+ /**
2
+ * One entry per step, in plan order: the plain sentences for what its typed close checks.
3
+ * @param {{ steps?: any[] }} declaration @param {{ hasAsk?: boolean }} [opts] hasAsk = the job has a signed ask line (so "you check it at the ask" is true)
4
+ * @returns {{ step: number, line: number|null, goal: string, class: string, sentences: string[] }[]}
5
+ */
6
+ export function checkedLines(declaration: {
7
+ steps?: any[];
8
+ }, { hasAsk }?: {
9
+ hasAsk?: boolean;
10
+ }): {
11
+ step: number;
12
+ line: number | null;
13
+ goal: string;
14
+ class: string;
15
+ sentences: string[];
16
+ }[];
17
+ /** The "Not checked" block the page shows: always the label, then the drafter's items (an empty list says the drafter listed nothing). @param {unknown} items */
18
+ export function notCheckedBlock(items: unknown): {
19
+ label: string;
20
+ items: any[];
21
+ };
22
+ /** The label that always sits with the "Not checked" list. */
23
+ export const NOT_CHECKED_LABEL: "the drafter's own reading, not a guarantee";