fwdloop 0.13.0 → 0.15.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);
@@ -503,7 +506,7 @@ export function handleRequest(req, res, opts) {
503
506
  }
504
507
 
505
508
  if (pathname === '/api/inbox') {
506
- const rows = listStops({ root: opts.root, resumeAttempt });
509
+ const rows = listStops({ root: opts.root, resumeAttempt, catalogue });
507
510
  send(200, { rows, openCount: inboxOpenCount(rows) });
508
511
  return;
509
512
  }
@@ -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
@@ -46,12 +46,14 @@ import {
46
46
  import { fileURLToPath } from 'node:url';
47
47
 
48
48
  import {
49
- readFlow, resolveRunDir, readFileInside, readdirInside, resolveInside, FLOW_FILES, PANEL_STARTS_DIR,
49
+ readFlow, resolveRunDir, readFileInside, readdirInside, resolveInside, FLOW_FILES, PANEL_STARTS_DIR, writeRunJobCopy,
50
50
  } from './flow.js';
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 },
@@ -1025,6 +1046,14 @@ export async function runFlow({
1025
1046
  }
1026
1047
  mkdirSync(runDir, { recursive: true });
1027
1048
 
1049
+ // M6: the run keeps a write-once copy of the job it runs, from before its first step (its Job tab shows this, not the flow's later versions)
1050
+ const jobCopy = writeRunJobCopy(flowDir, runDir, signature.flow);
1051
+ if (!jobCopy.ok) {
1052
+ return haltRun({
1053
+ flowDir, runDir, runId, capUsd, startedAt, now, nowMs: getNowMs, signatureHash: signature.flow, outcome: 'preflight-red', red: jobCopy.red, spent: { value: 0 },
1054
+ });
1055
+ }
1056
+
1028
1057
  const frozen = freezeInputs(runDir, sources ?? []);
1029
1058
  if (!frozen.ok) {
1030
1059
  return haltRun({
@@ -1307,7 +1336,7 @@ async function runAskSlot({
1307
1336
  flowDir, runDir, runId, capUsd, startedAt: runStartedAt, now, signatureHash, spent, spendComplete: spendComplete.value, attempts: attemptsLog, artifacts,
1308
1337
  stepIndex, stepEmits: step.emits ?? step.goal ?? null, flowRoot, flowName, inputsManifest, unjudged: evidenceUnjudged, redone, parkedAskId: askId,
1309
1338
  });
1310
- if (stopped) return { type: 'stopped', result: stopped };
1339
+ if (stopped && stopped.outcome !== 'stop-failed') return { type: 'stopped', result: stopped };
1311
1340
  }
1312
1341
  return {
1313
1342
  type: 'paused',
@@ -1658,14 +1687,18 @@ async function foldFromStep({
1658
1687
  // run really was sitting there waiting on a human, so it belongs in
1659
1688
  // "how long did this run take", not carved out of it.
1660
1689
  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' });
1690
+ try {
1691
+ recordLateAnswerIfAny(runDir, now);
1692
+ writeLog(runDir, {
1693
+ runId, outcome: 'complete', attempts: attemptsLog, artifacts,
1694
+ });
1695
+ settleStop({ runDir, now, outcome: 'complete' });
1696
+ } finally {
1697
+ // Amendment 16 C6/C7: the history end row is written last, and always.
1698
+ appendHistory(flowDir, {
1699
+ runId, at: now(), outcome: 'complete', spentUsd: spent.value, spendComplete: spendComplete.value, capUsd, wallMs, signatureHash,
1700
+ });
1701
+ }
1669
1702
  return {
1670
1703
  outcome: 'complete', runDir, artifacts, spentUsd: spent.value,
1671
1704
  };
@@ -1804,12 +1837,15 @@ function sameRoot(recorded, requested) {
1804
1837
  * @param {string} opts.businessDate
1805
1838
  * @param {number} [opts.ceilingUsd]
1806
1839
  * @param {() => number} [opts.nowMs] - F45 finding 3; see `runFlow`'s own.
1840
+ * @param {(newRunDir:string) => void} [opts.onRerunStart] - amendment 16 C2: called with the new run's folder just before a `rerun` starts it.
1807
1841
  */
1808
1842
  export async function resumeRun({
1809
1843
  root, name, runId, catalogue, modelStep, sendStep, primitives, primitiveReds, clock, businessDate, ceilingUsd,
1810
1844
  // F45 finding 3 (see `runFlow`'s own `nowMs`): additive, defaults to the
1811
1845
  // real `Date.now` for every existing caller.
1812
1846
  nowMs,
1847
+ // 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.
1848
+ onRerunStart,
1813
1849
  }) {
1814
1850
  const now = typeof clock === 'function' ? clock : () => new Date().toISOString();
1815
1851
  const getNowMs = typeof nowMs === 'function' ? nowMs : Date.now;
@@ -1841,6 +1877,8 @@ export async function resumeRun({
1841
1877
  red: unwiredRed(unwiredVerb),
1842
1878
  };
1843
1879
  }
1880
+ const unbuildable = findUnbuildableCheckStep(preflightRead.declaration);
1881
+ if (unbuildable) return { outcome: 'refused', red: unbuildableRed(unbuildable), detail: unbuildable.why };
1844
1882
  }
1845
1883
 
1846
1884
  if (primitiveReds?.length) return { outcome: 'refused', red: primitiveReds[0] };
@@ -2037,10 +2075,9 @@ export async function resumeRun({
2037
2075
  // 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
2076
  // 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
2077
  // 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);
2078
+ // time is read as made "now" by `readStopRequest` (amendment 17 2A, one rule), which is after the answer: the answer wins.
2079
+ const stopReq = readStopRequest(runDir, now);
2080
+ const stopFirst = stopReq !== null && Date.parse(/** @type {string} */ (stopReq.at)) < Date.parse(answer.answeredAt);
2044
2081
  if (stopReq && stopFirst) {
2045
2082
  const prev = readLog(runDir);
2046
2083
  return stopAtAsk({
@@ -2102,11 +2139,15 @@ export async function resumeRun({
2102
2139
  for (let i = 0; i < state.stepIndex; i += 1) {
2103
2140
  priorArtifactsForLog[steps[i].emits] = readArtifact(runDir, steps[i].emits);
2104
2141
  }
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 });
2142
+ try {
2143
+ recordLateAnswerIfAny(runDir, now);
2144
+ writeLog(runDir, { runId, outcome: 'rerun', attempts: [], artifacts: priorArtifactsForLog });
2145
+ } finally {
2146
+ // Amendment 16 C6/C7: the history end row is written last, and always.
2147
+ appendHistory(flowDir, {
2148
+ runId, at: now(), outcome: 'rerun', spentUsd: spent.value, spendComplete: spendComplete.value, capUsd: arbiter.capUsd ?? null, wallMs: getNowMs() - runStartedAt, signatureHash: state.signatureHash,
2149
+ });
2150
+ }
2110
2151
 
2111
2152
  // Deterministic derived id (M3 scope item 7) — refused by name, never
2112
2153
  // silently renumbered, if it already exists.
@@ -2125,6 +2166,7 @@ export async function resumeRun({
2125
2166
  // they aren't already" — they already are, via this field).
2126
2167
  const rerunSources = (state.inputsManifest ?? []).map((entry) => ({ id: entry.id, path: entry.source }));
2127
2168
 
2169
+ if (typeof onRerunStart === 'function') onRerunStart(newRunDir);
2128
2170
  const newRun = await runFlow({
2129
2171
  root,
2130
2172
  name,
@@ -2344,7 +2386,7 @@ export async function continueRun({
2344
2386
  const getNowMs = typeof nowMs === 'function' ? nowMs : Date.now;
2345
2387
  const flowDir = join(root, name);
2346
2388
  const startedAt = getNowMs();
2347
- const refused = (red) => ({ outcome: 'refused', red: `continue: ${red}` });
2389
+ const refused = (red, detail) => ({ outcome: 'refused', red: `continue: ${red}`, ...(detail ? { detail } : {}) });
2348
2390
 
2349
2391
  const runIdCheck = resolveRunDir(flowDir, runId);
2350
2392
  if (!runIdCheck.ok) return { outcome: 'refused', red: runIdCheck.red };
@@ -2354,6 +2396,8 @@ export async function continueRun({
2354
2396
  if (preflightRead.ok) {
2355
2397
  const unwiredVerb = findUnwiredVerbStep(preflightRead.declaration);
2356
2398
  if (unwiredVerb) return refused(unwiredRed(unwiredVerb));
2399
+ const unbuildable = findUnbuildableCheckStep(preflightRead.declaration);
2400
+ if (unbuildable) return refused(unbuildableRed(unbuildable), unbuildable.why);
2357
2401
  }
2358
2402
  if (primitiveReds?.length) return refused(primitiveReds[0]);
2359
2403
 
@@ -2520,8 +2564,11 @@ function stopAtAsk(o) {
2520
2564
  } = o;
2521
2565
  const red = `stopped by you at the ask of step ${stepIndex + 1}`;
2522
2566
  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
2567
+ try { renameSync(join(runDir, 'ask.json'), join(runDir, `ask.${parkedAskId}.stopped.json`)); } catch (err) {
2568
+ // Amendment 16 C8: only "file not found" means another stopper won the rename (it writes the rows). Any other error is a failed
2569
+ // stop: said plainly with the error named, nothing written, the run left as it was.
2570
+ if (err?.code === 'ENOENT') return { outcome: 'stopped', red, spentUsd: spent.value };
2571
+ return { outcome: 'stop-failed', red: `the stop failed: could not set the ask aside (${err?.code ?? 'error'}: ${err?.message ?? err})`, spentUsd: spent.value };
2525
2572
  }
2526
2573
  try { renameSync(join(runDir, 'state.json'), join(runDir, `state.${parkedAskId}.stopped.json`)); } catch { /* no state: nothing to set aside */ }
2527
2574
  if (existsSync(join(runDir, 'answer.json'))) setAsideAnswer(runDir, parkedAskId, 'late');
@@ -2654,6 +2701,7 @@ export function readAsk(runDir) {
2654
2701
  * @param {() => number} [opts.nowMs] - F45 finding 3; defaults to `Date.now`.
2655
2702
  * @param {string} opts.outcome
2656
2703
  * @param {string} [opts.red]
2704
+ * @param {string|null} [opts.detail] - amendment 23: bareguard's raw reason, recorded beside `red` (never the sentence).
2657
2705
  * @param {{ value: number }} opts.spent
2658
2706
  * @param {any[]} [opts.attempts]
2659
2707
  * @param {Record<string, any>} [opts.artifacts]
@@ -2674,7 +2722,7 @@ export function readAsk(runDir) {
2674
2722
  */
2675
2723
  function haltRun({
2676
2724
  flowDir, runDir, runId, capUsd, startedAt, now, nowMs = Date.now, outcome, red, spent, attempts = [], artifacts = {}, signatureHash = null,
2677
- priorSpendComplete = true, resumeAt = null, stop = null,
2725
+ priorSpendComplete = true, resumeAt = null, stop = null, detail = null,
2678
2726
  }) {
2679
2727
  // F45 finding 3: `startedAt` here is always the RUN's start (every caller
2680
2728
  // now passes `runStartedAt` under this key — see call sites), so `wallMs`
@@ -2683,24 +2731,33 @@ function haltRun({
2683
2731
  const spendComplete = priorSpendComplete
2684
2732
  && outcome !== 'provider-red' && outcome !== 'pricing-red' && outcome !== 'cap-halt';
2685
2733
  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
2734
+ try {
2735
+ if (existsSync(runDir)) {
2736
+ recordLateAnswerIfAny(runDir, now);
2737
+ writeLog(runDir, {
2738
+ runId, outcome, red, ...(detail ? { detail } : {}), attempts, artifacts,
2739
+ });
2740
+ // M4e amendment 4 item 4: a cap-halted or stopped run leaves the one record Resume continues from (its only writer).
2741
+ if (resumeAt && HALT_OUTCOMES.includes(outcome)) {
2742
+ writeFileSync(join(runDir, HALT_FILE), `${JSON.stringify({
2743
+ runId, outcome, at: now(), flow: { root: resumeAt.flowRoot, name: resumeAt.flowName }, signatureHash, inputsManifest: resumeAt.inputsManifest,
2744
+ stepIndex: resumeAt.stepIndex, startedAt, unjudged: resumeAt.unjudged ?? [],
2745
+ ...(Number.isInteger(resumeAt.redone) ? { redone: resumeAt.redone } : {}),
2746
+ }, null, 2)}\n`, { flag: 'wx' });
2747
+ }
2748
+ settleStop({ runDir, now, outcome, stop }); // amendment 7 item 8: every Stop leaves its rows
2749
+ }
2750
+ } finally {
2751
+ // 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
2752
+ // failed log, halt.json or settle row above never costs the row its real signature hash or the run's spend.
2753
+ // 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
2754
+ // no Resume offered, so a Stop whose halt record failed leaves no end row. C7 names the cap-halt, which always gets its row.
2755
+ const stoppedWithoutHaltRecord = outcome === 'stopped' && resumeAt && !readHaltRecord(runDir).ok;
2756
+ if (!stoppedWithoutHaltRecord) {
2757
+ appendHistory(flowDir, {
2758
+ runId, at: now(), outcome, spentUsd: spent.value, spendComplete, capUsd: capUsd ?? null, wallMs, signatureHash, ...(detail ? { detail } : {}), // amendment 23: bareguard's raw reason, never the sentence
2759
+ });
2760
+ }
2700
2761
  }
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 };
2762
+ return { outcome, red, ...(detail ? { detail } : {}), spentUsd: spent.value };
2706
2763
  }
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
  }
@@ -0,0 +1,71 @@
1
+ // M5 close / amendment 43: say what changed. Pure — no disk, no clock. Given the signed copy of the two signed files and what is on disk now,
2
+ // name each change in plain words ("line 3 changed", "line 3's guardrail changed", "the cap changed") instead of only the file name.
3
+ // What this throws away: the old and new values themselves (only that a thing changed, and for a number the two numbers); a prose edit
4
+ // that parses to the same lines and arbiter (spacing, blank lines) is named as "wording or spacing", never silently dropped.
5
+
6
+ import { parseSignedText } from './signed-text.js';
7
+
8
+ const same = (a, b) => JSON.stringify(a) === JSON.stringify(b);
9
+ const sec = (ms) => (ms % 3600000 === 0 ? `${ms / 3600000}h` : ms % 60000 === 0 ? `${ms / 60000}m` : `${ms / 1000}s`);
10
+
11
+ /**
12
+ * @param {{ oldProse: string, newProse: string, oldDecl: string, newDecl: string }} x the signed copy (old) and the files on disk (new)
13
+ * @returns {string[]} plain sentences; empty when nothing differs
14
+ */
15
+ export function describeChange({ oldProse, newProse, oldDecl, newDecl }) {
16
+ const out = [];
17
+ const a = parseSignedText(oldProse);
18
+ const b = parseSignedText(newProse);
19
+ if (oldProse.replace(/\r\n/g, '\n') !== newProse.replace(/\r\n/g, '\n')) {
20
+ if (!a.ok || !b.ok) {
21
+ out.push(b.ok ? 'the signed text could not be compared with the saved copy' : `prose.txt no longer reads as a signed job (${b.reds[0]})`);
22
+ } else {
23
+ const before = new Map(a.lines.map((l) => [l.n, l]));
24
+ const after = new Map(b.lines.map((l) => [l.n, l]));
25
+ for (const [n, l] of before) {
26
+ const m = after.get(n);
27
+ if (!m) { out.push(`line ${n} was removed`); continue; }
28
+ if (l.text !== m.text) out.push(`line ${n} changed`);
29
+ if (l.guardrail !== m.guardrail) out.push(`line ${n}'s guardrail changed`);
30
+ }
31
+ for (const n of after.keys()) if (!before.has(n)) out.push(`line ${n} was added`);
32
+ const x = a.arbiter;
33
+ const y = b.arbiter;
34
+ if (x.capUsd !== y.capUsd) out.push(`the cap changed (from $${x.capUsd} to $${y.capUsd})`);
35
+ if (x.redoCap !== y.redoCap) out.push(`the redo cap changed (from ${x.redoCap} to ${y.redoCap})`);
36
+ if (x.roundBudgetMs !== y.roundBudgetMs) out.push(`the round budget changed (from ${sec(x.roundBudgetMs)} to ${sec(y.roundBudgetMs)})`);
37
+ if (!same(x.skills, y.skills)) out.push('the skills changed');
38
+ for (const k of x.asks) {
39
+ const o = y.asks.find((s) => s.line === k.line);
40
+ if (!o) out.push(`the ask at line ${k.line} was removed`);
41
+ else if (o.ttlMs !== k.ttlMs) out.push(`the wait of the ask at line ${k.line} changed (from ${sec(k.ttlMs)} to ${sec(o.ttlMs)})`);
42
+ else if (o.question !== k.question) out.push(`the question of the ask at line ${k.line} changed`);
43
+ }
44
+ for (const k of y.asks) if (!x.asks.some((s) => s.line === k.line)) out.push(`an ask was added at line ${k.line}`);
45
+ for (const k of x.sends) {
46
+ const o = y.sends.find((s) => s.line === k.line);
47
+ if (!o) out.push(`the send at line ${k.line} was removed`);
48
+ else if (!same(o.target, k.target)) out.push(`the send destination at line ${k.line} changed`);
49
+ }
50
+ for (const k of y.sends) if (!x.sends.some((s) => s.line === k.line)) out.push(`a send was added at line ${k.line}`);
51
+ for (const k of x.sources) {
52
+ const o = y.sources.find((s) => s.role === k.role);
53
+ if (!o) out.push(`the input "${k.role}" was removed`);
54
+ else if (!same(o, k)) out.push(`the input "${k.role}" changed`);
55
+ }
56
+ for (const k of y.sources) if (!x.sources.some((s) => s.role === k.role)) out.push(`an input "${k.role}" was added`);
57
+ if (out.length === 0) out.push('prose.txt changed in wording or spacing (no job line, guardrail or arbiter value differs)');
58
+ }
59
+ }
60
+ let d1;
61
+ let d2;
62
+ try { d1 = JSON.stringify(sortDeep(JSON.parse(oldDecl))); d2 = JSON.stringify(sortDeep(JSON.parse(newDecl))); } catch { d1 = oldDecl; d2 = newDecl; }
63
+ if (d1 !== d2) out.push('the plan changed (declaration.json)');
64
+ return out;
65
+ }
66
+
67
+ function sortDeep(v) {
68
+ if (Array.isArray(v)) return v.map(sortDeep);
69
+ if (v && typeof v === 'object') return Object.fromEntries(Object.keys(v).sort().map((k) => [k, sortDeep(v[k])]));
70
+ return v;
71
+ }
@@ -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;
@@ -121,14 +146,20 @@ export function draftToDir({ proseFile, dir, root, name, slot, model, budgetUsd,
121
146
  * The human step, $0. Every refusal returns reds and writes NO flow.
122
147
  * `signedBy` must come from the human's own invocation (the CLI's --signed-by/username).
123
148
  * `sessionDir` (the panel's draft folder: card, notes, every change) widens the setup record; the CLI has none, so its record is the one plan folder.
149
+ * M6: `replaces: {flowHash}` (a draft opened from an existing signed job, carrying that job's signature hash) makes this sign REPLACE that job
150
+ * (`writeFlow` checks the hash is still the job's); without it a taken name is refused as ever.
151
+ * @param {{dir: any, approve?: any, signedBy: any, signedAt?: string, env?: Record<string, string|undefined>, sessionDir?: string, replaces?: {flowHash: string}}} a
124
152
  */
125
- export function signDraft({ dir, approve, signedBy, signedAt, env, sessionDir, }: {
153
+ export function signDraft({ dir, approve, signedBy, signedAt, env, sessionDir, replaces, }: {
126
154
  dir: any;
127
- approve: any;
155
+ approve?: any;
128
156
  signedBy: any;
129
- signedAt?: string | undefined;
130
- env?: NodeJS.ProcessEnv | undefined;
131
- sessionDir: any;
157
+ signedAt?: string;
158
+ env?: Record<string, string | undefined>;
159
+ sessionDir?: string;
160
+ replaces?: {
161
+ flowHash: string;
162
+ };
132
163
  }): {
133
164
  ok: boolean;
134
165
  reds: any[];
@@ -151,5 +182,12 @@ export const SPEC_HASH_FILE: "spec.hash";
151
182
  export const PANEL_DRAFTS_DIR: ".drafts";
152
183
  /** Written when the end sweep finds a key in the draft dir; sign refuses a dir that has it. */
153
184
  export const LEAK_MARKER_FILE: "scrub-leak.red";
185
+ /** M4e amendments 24/25: the drafter's questions (written once by `fwdloop draft`), each human answer (`answer-<k>.json`, written once by the panel),
186
+ * and the drafter's own "not checked" reading (information only; never in the readout, so never in the hash). */
187
+ export const QUESTIONS_FILE: "questions.json";
188
+ export const NOT_CHECKED_FILE: "not-checked.json";
189
+ export function ANSWER_FILE(k: any): string;
154
190
  export function SIGN_LINE(dir: any, hash: any): string;
191
+ 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.";
192
+ 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
193
  export function costText(n: any, spendComplete?: boolean): string;