fwdloop 0.12.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.
Files changed (62) hide show
  1. package/bin/fwdloop +155 -27
  2. package/package.json +2 -2
  3. package/src/ask.js +3 -0
  4. package/src/authoring.js +135 -16
  5. package/src/books.js +23 -2
  6. package/src/canrun.js +106 -0
  7. package/src/catalogue.json +2 -2
  8. package/src/checked.js +50 -0
  9. package/src/closers.js +112 -91
  10. package/src/config.js +2 -1
  11. package/src/declaration.js +175 -3
  12. package/src/drafter.js +148 -10
  13. package/src/draftspend.js +70 -0
  14. package/src/flow.js +43 -0
  15. package/src/keysfile.js +4 -2
  16. package/src/liveness.js +1 -1
  17. package/src/model-step.js +31 -5
  18. package/src/monthly.js +195 -28
  19. package/src/panel/author.js +638 -0
  20. package/src/panel/authorcard.js +340 -0
  21. package/src/panel/authorflows.js +317 -0
  22. package/src/panel/authorresume.js +149 -0
  23. package/src/panel/authorstart.js +257 -0
  24. package/src/panel/authorvalues.js +110 -0
  25. package/src/panel/data.js +318 -99
  26. package/src/panel/index.html +2000 -330
  27. package/src/panel/resume.js +6 -8
  28. package/src/panel/server.js +122 -119
  29. package/src/panel/settings.js +8 -6
  30. package/src/panel/spawn.js +77 -0
  31. package/src/provider.js +12 -17
  32. package/src/runner.js +707 -104
  33. package/src/runvalues.js +178 -0
  34. package/src/send.js +10 -3
  35. package/src/setup.js +127 -0
  36. package/types/authoring.d.ts +56 -2
  37. package/types/books.d.ts +14 -2
  38. package/types/canrun.d.ts +64 -0
  39. package/types/checked.d.ts +23 -0
  40. package/types/closers.d.ts +47 -28
  41. package/types/config.d.ts +1 -0
  42. package/types/declaration.d.ts +23 -1
  43. package/types/drafter.d.ts +151 -2
  44. package/types/draftspend.d.ts +21 -0
  45. package/types/flow.d.ts +23 -0
  46. package/types/liveness.d.ts +2 -2
  47. package/types/model-step.d.ts +4 -7
  48. package/types/monthly.d.ts +46 -1
  49. package/types/panel/author.d.ts +316 -0
  50. package/types/panel/authorcard.d.ts +142 -0
  51. package/types/panel/authorflows.d.ts +175 -0
  52. package/types/panel/authorresume.d.ts +32 -0
  53. package/types/panel/authorstart.d.ts +115 -0
  54. package/types/panel/authorvalues.d.ts +62 -0
  55. package/types/panel/data.d.ts +105 -63
  56. package/types/panel/server.d.ts +11 -33
  57. package/types/panel/spawn.d.ts +30 -0
  58. package/types/provider.d.ts +6 -9
  59. package/types/runner.d.ts +129 -6
  60. package/types/runvalues.d.ts +97 -0
  61. package/types/send.d.ts +5 -1
  62. package/types/setup.d.ts +77 -0
package/bin/fwdloop CHANGED
@@ -15,18 +15,20 @@
15
15
  // from poc/, and poc/ is not part of the published package.
16
16
 
17
17
  import { parseArgs } from 'node:util';
18
- import { existsSync, realpathSync } from 'node:fs';
18
+ import {
19
+ existsSync, readdirSync, realpathSync, rmdirSync,
20
+ } from 'node:fs';
19
21
  import { extname, join, resolve } from 'node:path';
20
22
  import { pathToFileURL } from 'node:url';
21
- import { randomUUID } from 'node:crypto';
22
23
 
23
24
  import {
24
- readFlow, checkFlowName, resolveRunDir, listFlowNames, listRunIds, readFileInside,
25
+ readFlow, checkFlowName, resolveRunDir, listFlowNames, listRunIds, readFileInside, claimRunId,
25
26
  } from '../src/flow.js';
26
27
  import { loadCatalogue } from '../src/catalogue.js';
27
28
  import {
28
- runFlow, resumeRun, makeParkingAskStep, readAsk, readRunState,
29
+ runFlow, resumeRun, continueRun, auditSpend, makeParkingAskStep, readAsk, readRunState,
29
30
  } from '../src/runner.js';
31
+ import { applyRunValues, pickRunValues, dropUnstartedValues } from '../src/runvalues.js';
30
32
  import { makeLiveModelStep } from '../src/model-step.js';
31
33
  import { sendViaPrimitive } from '../src/send.js';
32
34
  import { resolvePrimitives } from '../src/primitives.js';
@@ -35,7 +37,7 @@ import {
35
37
  } from '../src/provider.js';
36
38
  import { configDoorHome } from '../src/config.js';
37
39
  import {
38
- claimHold, settleHold, monthlyRefusalText, ConfigError,
40
+ claimHold, settleHold, nameRunDir, monthlyRefusalText, ConfigError,
39
41
  } from '../src/monthly.js';
40
42
  import { keysForDoor } from '../src/keysfile.js';
41
43
  import {
@@ -43,7 +45,7 @@ import {
43
45
  } from '../src/ask.js';
44
46
  import { panelMain } from '../src/panel/server.js';
45
47
  import { isInteractive, confirmTypedName, NEEDS_TTY } from '../src/sign-confirm.js';
46
- import { draftToDir, signDraft, SIGN_LINE, costText } from '../src/authoring.js';
48
+ import { draftToDir, draftKeyRefusal, signDraft, SIGN_LINE, costText, questionsRefusal } from '../src/authoring.js';
47
49
  import { userInfo } from 'node:os';
48
50
 
49
51
  // The baseline model (project rule, CLAUDE.md/AGENT_RULES: "deepseek-flash
@@ -71,7 +73,7 @@ function keyedEnv() {
71
73
  * that does not fit refuses at $0 with the one refusal text. A hold that fits is given back when this
72
74
  * process ends or parks (the `exit` hook runs on every exit path; a SIGKILL leaves it for the next check,
73
75
  * which settles it as "process gone").
74
- * @returns {{ addRunDir: (d: string) => void }}
76
+ * @returns {{ addRunDir: (d: string) => void, nameRunDir: (d: string) => void }}
75
77
  */
76
78
  function takeMonthlyHold({ what, flow, runId, runDir, holdUsd, spentAtHold = 0 }) {
77
79
  const door = configDoorHome();
@@ -84,7 +86,7 @@ function takeMonthlyHold({ what, flow, runId, runDir, holdUsd, spentAtHold = 0 }
84
86
  if (!(process.env.NODE_ENV === 'test' && process.env[hook])) {
85
87
  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
88
  }
87
- return { addRunDir: () => {} };
89
+ return { addRunDir: () => {}, nameRunDir: () => {} };
88
90
  }
89
91
  let claim;
90
92
  try {
@@ -101,13 +103,17 @@ function takeMonthlyHold({ what, flow, runId, runDir, holdUsd, spentAtHold = 0 }
101
103
  holdId: claim.holdId, why: process.exitCode ? 'ended (red)' : 'ended or parked', home, alsoRunDirs: also,
102
104
  }));
103
105
  }
104
- return { addRunDir: (d) => also.push(d) };
106
+ return {
107
+ addRunDir: (d) => also.push(d),
108
+ // C2: a rerun's new run dir is named in the money record the moment it starts.
109
+ nameRunDir: (d) => { also.push(d); nameRunDir({ holdId: claim.holdId, runDir: d, home }); },
110
+ };
105
111
  }
106
112
 
107
113
  /** The new runs a `rerun` chain started in this process — their spend belongs to this hold's month too. */
108
114
  function rerunDirs(result, flowDir) {
109
115
  const dirs = [];
110
- for (let r = result; r && r.outcome === 'rerun'; r = r.newRun) dirs.push(join(flowDir, r.newRunId));
116
+ for (let r = result; r && r.outcome === 'rerun'; r = r.newRun) dirs.push(join(flowDir, 'runs', r.newRunId));
111
117
  return dirs;
112
118
  }
113
119
 
@@ -219,6 +225,10 @@ function reportRunResult(result, { rootArg }) {
219
225
  reportRunResult(result.newRun, { rootArg });
220
226
  return;
221
227
  }
228
+ if (result.outcome === 'stopped') {
229
+ process.stdout.write(`stopped: spentUsd=${result.spentUsd} — ${result.red}\n`);
230
+ return;
231
+ }
222
232
  if (result.outcome === 'ask-expired') {
223
233
  process.stderr.write(`fwdloop: ask-expired — run cancelled, spentUsd=${result.spentUsd}\n`);
224
234
  process.exitCode = 1;
@@ -258,7 +268,7 @@ async function cmdRun(rest) {
258
268
 
259
269
  const read = readFlow({ root, name: flowName, catalogue });
260
270
  if (!read.ok) fail(`flow "${flowName}": ${read.reds.join('; ')}`);
261
- const { arbiter, declaration } = read;
271
+ const { declaration } = read;
262
272
 
263
273
  let parsedSources;
264
274
  try {
@@ -267,7 +277,7 @@ async function cmdRun(rest) {
267
277
  fail(`run: ${err.message}`);
268
278
  return;
269
279
  }
270
- const declaredRoles = (arbiter.sources ?? []).map((s) => s.role);
280
+ const declaredRoles = (read.arbiter.sources ?? []).map((s) => s.role);
271
281
  for (const role of declaredRoles) {
272
282
  if (!Object.hasOwn(parsedSources, role)) {
273
283
  fail(`run: flow "${flowName}" declares source role "${role}" — pass --source ${role}=<path>`);
@@ -283,11 +293,29 @@ async function cmdRun(rest) {
283
293
  if (!existsSync(src.path)) fail(`run: source "${src.id}" is unreadable at ${src.path}`);
284
294
  }
285
295
 
286
- const runId = values['run-id'] ?? `run-${Date.now().toString(36)}-${randomUUID().slice(0, 8)}`;
287
- const runIdCheck = resolveRunDir(join(root, flowName), runId);
288
- if (!runIdCheck.ok) fail(runIdCheck.red);
289
- const { runDir } = runIdCheck;
290
- if (existsSync(runDir)) fail(`run: run dir "${runDir}" already exists — use a new --run-id`);
296
+ // M4e amendment 3: no --run-id -> the ONE claim (`run-<n>`, the folder created exclusively). A typed id is checked as before; its
297
+ // folder may already exist ONLY if empty — that is a name the panel just claimed for this very start, it holds no run.
298
+ let runId = values['run-id'];
299
+ /** @type {string} */
300
+ let runDir;
301
+ if (runId === undefined) {
302
+ const claimed = claimRunId(join(root, flowName));
303
+ if (!claimed.ok) fail(claimed.red);
304
+ runId = claimed.runId;
305
+ runDir = claimed.runDir;
306
+ } else {
307
+ const runIdCheck = resolveRunDir(join(root, flowName), runId);
308
+ if (!runIdCheck.ok) fail(runIdCheck.red);
309
+ runDir = runIdCheck.runDir;
310
+ // M4e amendment 5: the panel's Sign & run puts the run's signed values in the folder BEFORE the start; that one file is not "a run".
311
+ if (existsSync(runDir) && readdirSync(runDir).filter((n) => n !== 'signed-values.json').length > 0) fail(`run: run dir "${runDir}" already exists — use a new --run-id`);
312
+ }
313
+ // M4e amendment 5 item 3: the cap this run was signed with (its own values file, else the flow's) is what the monthly hold is for.
314
+ const applied = applyRunValues(read.arbiter, flowName, read.signature.flow, pickRunValues(runDir));
315
+ if (!applied.ok) fail(`run: ${applied.red}`);
316
+ const { arbiter } = applied;
317
+ // a refusal before the run starts must not leave the claimed empty folder behind (rmdir only ever removes an EMPTY folder)
318
+ process.on('exit', () => { dropUnstartedValues(runDir); try { rmdirSync(runDir); } catch { /* not empty, or gone: nothing to undo */ } });
291
319
 
292
320
  // The key preflight (item A: "refuses at $0 BEFORE any book write") runs
293
321
  // here — before ANY directory for this run is created.
@@ -533,12 +561,16 @@ async function cmdResume(rest) {
533
561
 
534
562
  const read = readFlow({ root, name: flowName, catalogue });
535
563
  if (!read.ok) fail(`flow "${flowName}": ${read.reds.join('; ')}`);
536
- const { declaration, arbiter } = read;
564
+ const { declaration } = read;
537
565
 
538
566
  const runIdCheck = resolveRunDir(join(root, flowName), runId);
539
567
  if (!runIdCheck.ok) fail(runIdCheck.red);
540
568
  const { runDir } = runIdCheck;
541
569
  if (!existsSync(runDir)) fail(`resume: no run dir for runId "${runId}" under flow "${flowName}"`);
570
+ // M4e amendment 5 item 3: the cap this run was signed with (its own values file, else the flow's)
571
+ const applied = applyRunValues(read.arbiter, flowName, read.signature.flow, pickRunValues(runDir));
572
+ if (!applied.ok) fail(`resume: ${applied.red}`);
573
+ const { arbiter } = applied;
542
574
 
543
575
  const spendPath = join(runDir, 'spend.jsonl');
544
576
  let modelStep;
@@ -591,6 +623,93 @@ async function cmdResume(rest) {
591
623
  primitives,
592
624
  primitiveReds,
593
625
  businessDate: today(),
626
+ onRerunStart: (d) => hold.nameRunDir(d),
627
+ });
628
+
629
+ for (const d of rerunDirs(result, join(root, flowName))) hold.addRunDir(d);
630
+ reportRunResult(result, { rootArg: values.root });
631
+ }
632
+
633
+ // ---------------------------------------------------------------------------
634
+ // continue — M4e amendment 4 items 4 and 6: Resume of a STOPPED or CAP-HALTED run (the same run id), under the run's highest signed
635
+ // values version (the human's new cap). `fwdloop continue <runId> --flow <name> --root <dir>`. The panel's "Sign & resume" writes
636
+ // the new signed version first and then starts this; run by hand it continues under whatever version is on disk.
637
+ // ---------------------------------------------------------------------------
638
+
639
+ async function cmdContinue(rest) {
640
+ const { values, positionals } = parseArgs({
641
+ args: rest,
642
+ options: {
643
+ flow: { type: 'string' },
644
+ root: { type: 'string' },
645
+ },
646
+ allowPositionals: true,
647
+ });
648
+ const env = keyedEnv();
649
+ const runId = positionals[0];
650
+ if (!runId) fail('continue: a runId is required — fwdloop continue <runId> --flow <name> --root <dir>');
651
+ if (!values.flow) fail('continue: --flow <name> is required');
652
+ if (!values.root) fail('continue: --root <dir> is required');
653
+
654
+ const root = resolveRoot('continue', values.root);
655
+ const flowName = values.flow;
656
+
657
+ const loaded = loadCatalogue();
658
+ if (!loaded.ok) fail(`catalogue: ${loaded.reds.join('; ')}`);
659
+ const catalogue = loaded.primitives;
660
+
661
+ const read = readFlow({ root, name: flowName, catalogue });
662
+ if (!read.ok) fail(`flow "${flowName}": ${read.reds.join('; ')}`);
663
+ const { declaration } = read;
664
+
665
+ const runIdCheck = resolveRunDir(join(root, flowName), runId);
666
+ if (!runIdCheck.ok) fail(runIdCheck.red);
667
+ const { runDir } = runIdCheck;
668
+ if (!existsSync(runDir)) fail(`continue: no run dir for runId "${runId}" under flow "${flowName}"`);
669
+ const applied = applyRunValues(read.arbiter, flowName, read.signature.flow, pickRunValues(runDir));
670
+ if (!applied.ok) fail(`continue: ${applied.red}`);
671
+
672
+ const spendPath = join(runDir, 'spend.jsonl');
673
+ let modelStep;
674
+ try {
675
+ modelStep = await resolveModelStep(spendPath, env);
676
+ } catch (err) {
677
+ fail(err.message);
678
+ return;
679
+ }
680
+
681
+ // The monthly check: the hold is the cap in force minus what the run's own books say it has spent (never less than 0).
682
+ const spentSoFar = auditSpend(runDir);
683
+ if (!spentSoFar.ok) fail(`continue: run "${runId}" ${spentSoFar.red}`);
684
+ const hold = takeMonthlyHold({
685
+ what: 'resume', flow: flowName, runId, runDir, holdUsd: Math.max(0, applied.arbiter.capUsd - spentSoFar.total), spentAtHold: spentSoFar.total,
686
+ });
687
+
688
+ const inputsManifestRead = readFileInside(runDir, 'inputs.json');
689
+ let inputsManifest = [];
690
+ if (inputsManifestRead.ok) {
691
+ try {
692
+ inputsManifest = JSON.parse(inputsManifestRead.text);
693
+ } catch (err) {
694
+ fail(`continue: inputs.json for run "${runId}" is not valid JSON — ${err.message}`);
695
+ return;
696
+ }
697
+ }
698
+ const allVerbs = [...new Set(declaration.steps.flatMap((s) => s.primitives ?? []))];
699
+ const { tools: primitives, reds: primitiveReds } = resolvePrimitives(catalogue, allVerbs, {
700
+ runDir, inputs: inputsManifest.map((m) => ({ id: m.id, frozen: m.frozen })),
701
+ });
702
+
703
+ const result = await continueRun({
704
+ root,
705
+ name: flowName,
706
+ runId,
707
+ catalogue,
708
+ modelStep,
709
+ sendStep: sendViaPrimitive,
710
+ primitives,
711
+ primitiveReds,
712
+ businessDate: today(),
594
713
  });
595
714
 
596
715
  for (const d of rerunDirs(result, join(root, flowName))) hold.addRunDir(d);
@@ -601,11 +720,9 @@ async function cmdResume(rest) {
601
720
  // panel — M4a piece 2 + M4b (docs/wiki/the-module-ladder.md, "M4a — read-only
602
721
  // panel" and "M4b — inputs"): `fwdloop panel [--port 4800] [--root <dir>]`.
603
722
  // Reads are GET/HEAD; the only writes are POST /api/answer and POST
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
608
- // a different port on collision — a taken port is a loud, non-zero-exit
723
+ // /api/resume (src/panel/server.js), each gated by Origin/Host. No token, no
724
+ // cookie (M4e amendment 4 item 8): `fwdloop panel` prints `http://127.0.0.1:<port>/`.
725
+ // Bound to 127.0.0.1 only. Never picks a different port on collision — a taken port is a loud, non-zero-exit
609
726
  // failure.
610
727
  // ---------------------------------------------------------------------------
611
728
 
@@ -643,6 +760,8 @@ async function cmdDraft(rest) {
643
760
  args: rest,
644
761
  options: {
645
762
  out: { type: 'string' }, root: { type: 'string' }, name: { type: 'string' }, budget: { type: 'string' },
763
+ // M4e amendment 24 item 4: the redraft after the human's answers never asks (the panel passes this; a plain draft may ask on try 3)
764
+ 'no-questions': { type: 'boolean' },
646
765
  },
647
766
  allowPositionals: true,
648
767
  });
@@ -658,8 +777,8 @@ async function cmdDraft(rest) {
658
777
  }
659
778
  // The key preflight comes first (draftToDir repeats it), so an unset key keeps its own message ahead of the NODE_ENV refusal.
660
779
  if (injected.provider == null) {
661
- const keyCheck = checkKeyPreflight('deepseek', env);
662
- if (!keyCheck.ok) fail(`draft refused at $0 — ${keyCheck.message}`);
780
+ const refusal = draftKeyRefusal(MODEL_SLOT, env);
781
+ if (refusal !== null) fail(`draft refused at $0 — ${refusal}`);
663
782
  }
664
783
  // M4d piece 3: the monthly check — a draft has no signed cap, so it holds one ceiling round, priced by the
665
784
  // ONE price lookup (an injected test provider carries its own rates).
@@ -682,6 +801,7 @@ async function cmdDraft(rest) {
682
801
  root: resolve(values.root),
683
802
  name: values.name,
684
803
  budgetUsd: values.budget === undefined ? undefined : Number(values.budget),
804
+ noQuestions: values['no-questions'] === true,
685
805
  env,
686
806
  ...injected,
687
807
  });
@@ -697,6 +817,10 @@ async function cmdDraft(rest) {
697
817
  process.exitCode = 1;
698
818
  return;
699
819
  }
820
+ if (result.questions > 0) {
821
+ process.stdout.write('DRAFTED — NOT SIGNABLE YET: the plan raised a question. Answer it in the panel (fwdloop panel); the panel drafts again with your answers.\n');
822
+ return;
823
+ }
700
824
  process.stdout.write(`${SIGN_LINE(resolve(values.out), result.hash)}\n`);
701
825
  }
702
826
 
@@ -709,6 +833,9 @@ async function cmdSign(rest) {
709
833
  const env = keyedEnv(); // sign takes no key, but its leak sweep must know the file's keys too
710
834
  const dir = positionals[0];
711
835
  if (!dir) fail('sign: a draft dir is required — fwdloop sign <dir> --approve <hash>');
836
+ // M4e amendments 24/25: a plan with a question is not signed from here — the answers are taken in the panel. One check, also run again inside signDraft.
837
+ const openQuestion = questionsRefusal(resolve(dir));
838
+ if (openQuestion !== null) fail(`sign refused — ${openQuestion}`);
712
839
  // Amendment 2: a person at a keyboard. TTY check first (cheapest), then the typed flow name; only then
713
840
  // signDraft's own $0 checks (hash, wired, goals, TTL, sources, send, leak). signDraft writes only on success.
714
841
  if (!isInteractive()) fail(`sign refused — ${NEEDS_TTY}`);
@@ -729,7 +856,7 @@ async function cmdSign(rest) {
729
856
 
730
857
  async function main() {
731
858
  const [verb, ...rest] = process.argv.slice(2);
732
- if (!verb) fail('usage: fwdloop draft|sign|run|inbox|show|answer|resume|panel ...');
859
+ if (!verb) fail('usage: fwdloop draft|sign|run|inbox|show|answer|resume|continue|panel ...');
733
860
 
734
861
  if (verb === 'draft') return cmdDraft(rest);
735
862
  if (verb === 'sign') return cmdSign(rest);
@@ -738,8 +865,9 @@ async function main() {
738
865
  if (verb === 'show') return cmdShow(rest);
739
866
  if (verb === 'answer') return cmdAnswer(rest);
740
867
  if (verb === 'resume') return cmdResume(rest);
868
+ if (verb === 'continue') return cmdContinue(rest);
741
869
  if (verb === 'panel') return cmdPanel(rest);
742
- fail(`unknown verb "${verb}" — expected draft | sign | run | inbox | show | answer | resume | panel`);
870
+ fail(`unknown verb "${verb}" — expected draft | sign | run | inbox | show | answer | resume | continue | panel`);
743
871
  return undefined;
744
872
  }
745
873
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "fwdloop",
3
- "version": "0.12.0",
3
+ "version": "0.14.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",
@@ -50,7 +50,7 @@
50
50
  ],
51
51
  "dependencies": {
52
52
  "bare-agent": "^0.49.0",
53
- "bareguard": "^0.19.2",
53
+ "bareguard": "^0.21.2",
54
54
  "litectx": "^0.32.0"
55
55
  },
56
56
  "devDependencies": {
package/src/ask.js CHANGED
@@ -736,6 +736,9 @@ export function listArchivedAsks(runDir) {
736
736
  } catch (err) {
737
737
  answer = { status: 'open', why: `${join(runDir, consumedRelPath)} is not valid JSON — ${err.message}` };
738
738
  }
739
+ } else if (readFileInside(runDir, `ask.${askId}.stopped.json`).ok) {
740
+ // M4e amendment 13: a human stopped the run at this ask; no wait can expire on it.
741
+ answer = { status: 'stopped' };
739
742
  } else if (typeof ask.expiresAt === 'string' && !Number.isNaN(Date.parse(ask.expiresAt))
740
743
  && Date.now() > Date.parse(effectiveExpiresAt(runDir, askId, ask.expiresAt))) {
741
744
  answer = { status: 'expired' };
package/src/authoring.js CHANGED
@@ -28,11 +28,20 @@ import { canonicalBytes } from './signature.js';
28
28
  import { writeFlow, readFileInside, readdirInside, checkFlowName } from './flow.js';
29
29
  import { checkSendDestination } from './runner.js';
30
30
  import { PROVIDER_SLOTS, checkKeyPreflight, appendSpendRow } from './provider.js';
31
+ import { writeDraftSpend } from './draftspend.js';
32
+ import { writeSetup } from './setup.js';
31
33
 
32
34
  export const DRAFT_BUDGET_USD = 0.10;
33
35
  export const SPEC_HASH_FILE = 'spec.hash';
36
+ /** The one folder under the flows root where the panel keeps its draft folders (M4e). Starts with a dot, so it is never a flow name. */
37
+ export const PANEL_DRAFTS_DIR = '.drafts';
34
38
  /** Written when the end sweep finds a key in the draft dir; sign refuses a dir that has it. */
35
39
  export const LEAK_MARKER_FILE = 'scrub-leak.red';
40
+ /** M4e amendments 24/25: the drafter's questions (written once by `fwdloop draft`), each human answer (`answer-<k>.json`, written once by the panel),
41
+ * and the drafter's own "not checked" reading (information only; never in the readout, so never in the hash). */
42
+ export const QUESTIONS_FILE = 'questions.json';
43
+ export const NOT_CHECKED_FILE = 'not-checked.json';
44
+ export const ANSWER_FILE = (k) => `answer-${k}.json`;
36
45
  export const SIGN_LINE = (dir, hash) => `DRAFTED — NOT SIGNED. To sign: fwdloop sign ${dir} --approve ${hash}`;
37
46
 
38
47
  const sha = (bytes) => createHash('sha256').update(bytes).digest('hex');
@@ -61,6 +70,40 @@ export function specHash({
61
70
  return { ok: true, hash: sha(Buffer.from(framed, 'utf8')) };
62
71
  }
63
72
 
73
+ /**
74
+ * 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
75
+ * checks and the page all use it). `questions` = [{ k, line, question, answer|null }], `open` = those with no answer. A blank or unreadable
76
+ * answer file counts as no answer. No questions file = `{ questions: [], open: [] }`.
77
+ * @param {string} planDir
78
+ * @returns {{ questions: {k:number, line:number, question:string, answer:string|null}[], open: {k:number, line:number, question:string, answer:null}[] }}
79
+ */
80
+ export function readQuestions(planDir) {
81
+ const none = { questions: [], open: [] };
82
+ const f = readFileInside(planDir, QUESTIONS_FILE);
83
+ if (!f.ok) return none;
84
+ let list;
85
+ try { list = JSON.parse(f.text)?.questions; } catch { return none; }
86
+ if (!Array.isArray(list)) return none;
87
+ const questions = list.map((q, i) => {
88
+ const k = i + 1;
89
+ const a = readFileInside(planDir, ANSWER_FILE(k));
90
+ let answer = null;
91
+ if (a.ok) { try { const t = JSON.parse(a.text)?.answer; if (typeof t === 'string' && t.trim() !== '') answer = t; } catch { /* unreadable = unanswered */ } }
92
+ return { k, line: q.line, question: String(q.question), answer };
93
+ });
94
+ return { questions, open: /** @type {any} */ (questions.filter((q) => q.answer === null)) };
95
+ }
96
+
97
+ 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.';
98
+ 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.';
99
+
100
+ /** 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 */
101
+ export function questionsRefusal(planDir) {
102
+ const q = readQuestions(planDir);
103
+ if (q.questions.length === 0) return null;
104
+ return q.open.length > 0 ? OPEN_QUESTION_SAY : ANSWERED_QUESTION_SAY;
105
+ }
106
+
64
107
  /** Literal (never RegExp) key scrub; a secret under 8 chars is skipped so it can't blank ordinary text. */
65
108
  export function scrub(text, secrets) {
66
109
  let out = text;
@@ -96,6 +139,24 @@ export const costText = (n, spendComplete = true) => {
96
139
  };
97
140
  const usd = costText;
98
141
 
142
+ /** The readout's section headings: the ONE list. buildReadout writes them from here and `readoutHeadIndexes` finds them by it,
143
+ * so the panel's bold and the template cannot drift (M4e amendment 7 item 3). */
144
+ const READOUT_HEADS = {
145
+ inputs: 'INPUTS',
146
+ steps: 'STEPS',
147
+ asks: 'ASKS (human stops)',
148
+ sends: 'SEND TARGET (nothing leaves before an accepted ask)',
149
+ refused: 'REFUSED LINES',
150
+ jobLines: 'JOB LINES',
151
+ };
152
+ /** Zero-based indexes of the heading lines in a readout's text (split on "\n"): the panel renders those bold. */
153
+ export function readoutHeadIndexes(text) {
154
+ const heads = new Set(Object.values(READOUT_HEADS));
155
+ const idx = [];
156
+ String(text).split('\n').forEach((l, i) => { if (heads.has(l)) idx.push(i); });
157
+ return idx;
158
+ }
159
+
99
160
  /** Plain-text readout of what the human is about to sign. Pure. */
100
161
  export function buildReadout({
101
162
  declaration, arbiter, lines, name, modelId, costUsd, rounds, spendComplete, root,
@@ -105,29 +166,40 @@ export function buildReadout({
105
166
  out.push(`Drafted by: ${modelId ?? '?'} in ${rounds} round(s), cost ${usd(costUsd, spendComplete)}`);
106
167
  if (typeof root === 'string') out.push(`Flows root: ${root} (the flow is written to <flows root>/${name} when you sign)`);
107
168
  out.push(`Cap per run (signed by you in the prose): $${arbiter.capUsd}`, '');
108
- out.push('INPUTS');
169
+ out.push(READOUT_HEADS.inputs);
109
170
  for (const s of arbiter.sources) {
110
171
  const h = declaration.inputFacts?.[s.role];
111
172
  out.push(` ${s.role} = ${s.path}${h ? ` [headings: ${h.join(' | ') || 'none'}]` : ''}`);
112
173
  }
113
- out.push('', 'STEPS');
174
+ out.push('', READOUT_HEADS.steps);
114
175
  declaration.steps.forEach((st, i) => {
115
176
  out.push(` ${i + 1}. (line ${st.fromLine}) ${st.goal}`);
116
177
  out.push(` grants: ${st.primitives?.length ? st.primitives.join(', ') : 'none (pure stop)'}`
117
178
  + ` | reads: ${st.reads?.length ? st.reads.join(', ') : '-'} | emits: ${st.emits} | check: ${st.close?.class}`);
179
+ // M4e amendment 14 item 5: the check's sections in its order (+ word limit); fixed text from typed fields, never model prose.
180
+ const shape = st.close?.shape;
181
+ if (Array.isArray(shape?.sections) && shape.sections.length > 0) {
182
+ const per = Number.isInteger(shape.wordsPerSection) ? ` · about ${shape.wordsPerSection} words each` : '';
183
+ const lim = Number.isInteger(shape.maxWords) ? ` · under ${shape.maxWords} words` : '';
184
+ out.push(` sections: ${shape.sections.join(' · ')}${per}${lim}`);
185
+ }
118
186
  });
119
- out.push('', 'ASKS (human stops)');
187
+ out.push('', READOUT_HEADS.asks);
120
188
  for (const a of arbiter.asks) out.push(` line ${a.line}: "${a.question}" (ttl ${fmtTtl(a.ttlMs)})`);
121
189
  if (arbiter.asks.length === 0) out.push(' none');
122
- out.push('', 'SEND TARGET (nothing leaves before an accepted ask)');
190
+ out.push('', READOUT_HEADS.sends);
123
191
  for (const s of arbiter.sends) out.push(` line ${s.line} -> ${s.target.kind}:${s.target.path}`);
124
192
  if (arbiter.sends.length === 0) out.push(' none');
125
193
  const refused = declaration.refused ?? [];
126
194
  if (refused.length) {
127
- out.push('', 'REFUSED LINES');
195
+ out.push('', READOUT_HEADS.refused);
128
196
  for (const r of refused) out.push(` line ${r.line}: ${r.reason}`);
129
197
  }
130
- out.push('', 'JOB LINES', ...lines.map((l) => ` ${l.n}. ${l.text}`));
198
+ out.push('', READOUT_HEADS.jobLines);
199
+ for (const l of lines) {
200
+ out.push(` ${l.n}. ${l.text}`);
201
+ if (typeof l.guardrail === 'string' && l.guardrail.trim() !== '') out.push(` ~ ${l.guardrail}`);
202
+ }
131
203
  return `${out.join('\n')}\n`;
132
204
  }
133
205
 
@@ -153,6 +225,17 @@ export function readProseFile(file) {
153
225
  return { ok: true, text };
154
226
  }
155
227
 
228
+ /**
229
+ * 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
230
+ * it, so both refuse with the same sentence. null = the key is fine; else the sentence (never the key's value).
231
+ * @param {string} slot @param {Record<string,string|undefined>} env
232
+ * @returns {string|null}
233
+ */
234
+ export function draftKeyRefusal(slot, env) {
235
+ const key = checkKeyPreflight(slot, env);
236
+ return key.ok ? null : String(key.message);
237
+ }
238
+
156
239
  /**
157
240
  * Draft into `dir`. $0 refusals (return {ok:false, wrote:false}, nothing on disk): bad key,
158
241
  * unreadable/blank prose, prose that contains the key, missing inputs / bad signed text, dir
@@ -163,7 +246,7 @@ export function readProseFile(file) {
163
246
  * Test seam: `provider`/`rates`/`modelId` are injected; without them a live provider is built.
164
247
  */
165
248
  export async function draftToDir({
166
- proseFile, dir, root, name, slot = 'deepseek', model, budgetUsd = DRAFT_BUDGET_USD, env = process.env, provider, rates, modelId,
249
+ proseFile, dir, root, name, slot = 'deepseek', model, budgetUsd = DRAFT_BUDGET_USD, env = process.env, provider, rates, modelId, noQuestions = false,
167
250
  }) {
168
251
  const refuse = (reds) => ({ ok: false, wrote: false, reds, costUsd: 0 });
169
252
  const nameCheck = checkFlowName(name);
@@ -174,7 +257,10 @@ export async function draftToDir({
174
257
  const realRoot = realpathOfNew(root);
175
258
  const realDir = realpathOfNew(dir);
176
259
  const rel = path.relative(realRoot, realDir);
177
- if (rel === '' || (rel !== '..' && !rel.startsWith(`..${path.sep}`) && !path.isAbsolute(rel))) {
260
+ // M4e piece 2: the panel's own draft folders live at exactly `<root>/.drafts/<id>/...` (a dot-name is never a flow:
261
+ // `checkFlowName` refuses it, so `listFlowNames`/`readFlow` never list it). Nothing else under the root is allowed.
262
+ const panelDrafts = rel.startsWith(`${PANEL_DRAFTS_DIR}${path.sep}`) && !path.isAbsolute(rel);
263
+ if (!panelDrafts && (rel === '' || (rel !== '..' && !rel.startsWith(`..${path.sep}`) && !path.isAbsolute(rel)))) {
178
264
  return refuse([`draft: "${dir}" is inside the flows root "${root}" — an unsigned draft would show as a flow; use a --out outside the flows root`]);
179
265
  }
180
266
  const read = readProseFile(proseFile);
@@ -183,8 +269,8 @@ export async function draftToDir({
183
269
  const injected = provider != null;
184
270
  const secretVar = PROVIDER_SLOTS[slot]?.envVar;
185
271
  if (!injected) {
186
- const key = checkKeyPreflight(slot, env);
187
- if (!key.ok) return refuse([key.message]);
272
+ const refusal = draftKeyRefusal(slot, env);
273
+ if (refusal !== null) return refuse([refusal]);
188
274
  }
189
275
  const secrets = secretVar && env[secretVar] ? [env[secretVar]] : [];
190
276
  if (secrets.some((s) => s.length >= 8 && prose.text.includes(s))) return refuse(['prose: contains an API key value — refused']);
@@ -200,8 +286,26 @@ export async function draftToDir({
200
286
  return e.code === 'EEXIST' ? exists() : refuse([`draft: cannot create "${dir}": ${e.code ?? e.message}`]);
201
287
  }
202
288
 
289
+ // Spend is booked per call into `<dir>/draft-spend.json` (src/draftspend.js), so a draft stopped between rounds
290
+ // keeps what it paid. The first write is the mark that a call is in flight: if that cannot be written, the call is not made.
291
+ let startedAt = null;
292
+ const onBook = ({
293
+ inFlight, calls, unmetered, metered, modelId: usedModel, price,
294
+ }) => {
295
+ const now = new Date().toISOString();
296
+ startedAt ??= now;
297
+ try {
298
+ writeDraftSpend(dir, {
299
+ kind: 'draft-live', provider: slot, model: usedModel ?? modelId ?? null, price: price ?? null, tokens: metered.tokens, costUsd: metered.costUsd, rounds: metered.rounds,
300
+ calls, spendComplete: !inFlight && unmetered === 0 && metered.costUsd !== null, inFlight, at: startedAt, startedAt, updatedAt: now,
301
+ });
302
+ } catch (e) {
303
+ if (inFlight) throw new Error(`draft: cannot book the spend before the call (${e.code ?? e.message}) — nothing was spent`);
304
+ // after a call the cost is already in the file as "one call in flight" (a ceiling): the honest direction, so no throw
305
+ }
306
+ };
203
307
  const result = await draft({
204
- proseText: prose.text, slot, model, budgetUsd, provider, rates, modelId, env,
308
+ proseText: prose.text, slot, model, budgetUsd, provider, rates, modelId, env, onBook, offerQuestions: !noQuestions,
205
309
  });
206
310
  if (result.stop === 'pre-flight') {
207
311
  try { rmdirSync(dir); } catch { /* the claimed dir is still empty; leave it rather than mask the refusal */ }
@@ -219,6 +323,10 @@ export async function draftToDir({
219
323
  files['prose.txt'] = prose.text; // verbatim
220
324
  const targetText = dj({ root, name });
221
325
  files['target.json'] = targetText;
326
+ // Amendments 24/25: the questions and the drafter's own "not checked" reading are written BEFORE log.json/spec.hash (the panel reads those
327
+ // two as "the draft finished"), as their own files: never in the readout, so never in the hash.
328
+ if (result.questions?.length) files[QUESTIONS_FILE] = scrub(dj({ questions: result.questions }), secrets);
329
+ files[NOT_CHECKED_FILE] = scrub(dj({ notChecked: result.notChecked ?? [] }), secrets);
222
330
  files['log.json'] = scrub(dj({
223
331
  ok: result.ok, stop: result.stop, reds: result.reds, rounds: result.rounds, calls: result.calls, costUsd: result.costUsd, spendComplete: result.spendComplete,
224
332
  modelId: result.modelId, modelReturned: result.modelReturned, structureRetries: result.structureRetries,
@@ -259,6 +367,9 @@ export async function draftToDir({
259
367
  spendComplete: result.spendComplete,
260
368
  stop: result.stop,
261
369
  budgetUsd,
370
+ // the draft's own time (amendment 7 item 2: the Draft's total time adds up from these); null when no call was booked
371
+ startedAt,
372
+ wallMs: startedAt === null ? null : Math.max(0, Date.now() - Date.parse(startedAt)),
262
373
  });
263
374
  for (const [f, text] of Object.entries(files)) writeFileSync(path.join(dir, f), text);
264
375
  leaks = sweepForSecrets(dir, secrets);
@@ -272,19 +383,22 @@ export async function draftToDir({
272
383
  return paidFail(`write failed after the paid round (${e.code ?? e.message}); the draft dir is incomplete and never signable`);
273
384
  }
274
385
  return {
275
- ok: result.ok, wrote: true, dir, hash, reds: cleanReds(result.reds), costUsd: result.costUsd, spendComplete: result.spendComplete, stop: result.stop, rounds: result.rounds, calls: result.calls, leaks: 0,
386
+ ok: result.ok, wrote: true, dir, hash, questions: result.questions?.length ?? 0, reds: cleanReds(result.reds), costUsd: result.costUsd, spendComplete: result.spendComplete, stop: result.stop, rounds: result.rounds, calls: result.calls, leaks: 0,
276
387
  };
277
388
  }
278
389
 
279
390
  /**
280
391
  * The human step, $0. Every refusal returns reds and writes NO flow.
281
392
  * `signedBy` must come from the human's own invocation (the CLI's --signed-by/username).
393
+ * `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.
282
394
  */
283
395
  export function signDraft({
284
- dir, approve, signedBy, signedAt = new Date().toISOString(), env = process.env,
396
+ dir, approve, signedBy, signedAt = new Date().toISOString(), env = process.env, sessionDir,
285
397
  }) {
286
398
  const refuse = (...reds) => ({ ok: false, reds });
287
399
  if (readFileInside(dir, LEAK_MARKER_FILE).ok) return refuse(`sign: "${dir}" carries a key-leak marker (${LEAK_MARKER_FILE}) — never signed`);
400
+ const openQuestion = questionsRefusal(dir);
401
+ if (openQuestion !== null) return refuse(`sign: ${openQuestion}`);
288
402
  // Sign is $0 and takes no key, so it can only sweep for keys present in ITS env (any provider slot's).
289
403
  // With none set the sweep is skipped: the marker above and the missing spec.hash are then the guard.
290
404
  const keys = Object.values(PROVIDER_SLOTS).map((p) => env[p.envVar]).filter(Boolean);
@@ -319,7 +433,7 @@ export function signDraft({
319
433
  const cat = loadCatalogue();
320
434
  if (!cat.ok) return refuse(`sign: catalogue: ${cat.reds.join('; ')}`);
321
435
  const verdict = validateDeclaration(declaration, {
322
- arbiter: signed.arbiter, lines: signed.lines, catalogue: cat.primitives, wired: WIRED_VERBS, verbatimGoals: true,
436
+ arbiter: signed.arbiter, lines: signed.lines, catalogue: cat.primitives, wired: WIRED_VERBS, verbatimGoals: true, fitJobLine: true,
323
437
  });
324
438
  if (!verdict.ok) return { ok: false, reds: verdict.reds };
325
439
 
@@ -328,7 +442,7 @@ export function signDraft({
328
442
  if (s.kind === 'file' && !existsSync(s.path)) reds.push(`sign: input source "${s.role}" is missing at ${s.path}`);
329
443
  }
330
444
  for (const s of signed.arbiter.sends) {
331
- const d = checkSendDestination(`${s.target.kind}:${s.target.path}`);
445
+ const d = checkSendDestination(`${s.target.kind}:${s.target.path}`, { root: target.root });
332
446
  if (!d.ok) reds.push(`sign: ${d.red}`);
333
447
  }
334
448
  if (reds.length) return { ok: false, reds };
@@ -337,5 +451,10 @@ export function signDraft({
337
451
  root: target.root, name: target.name, proseText: parts['prose.txt'], declaration, signedBy, signedAt, catalogue: cat.primitives,
338
452
  });
339
453
  if (!written.ok) return { ok: false, reds: written.reds };
340
- return { ok: true, flowDir: written.dir, signature: written.signature };
454
+ // M4e amendment 6 item 4: the draft's record goes into the flow folder once, outside the three signed files. The flow IS signed by now, so a
455
+ // failure to write it never un-signs: it is returned (`setup.ok:false`) for the caller to say, and the audit reads "no setup record".
456
+ const setup = writeSetup({
457
+ flowDir: written.dir, sessionDir, planDir: dir, hash: h.hash, signedBy, signedAt, flowHash: written.signature?.flow, secrets: /** @type {string[]} */ (keys.filter((k) => typeof k === 'string' && k.length >= 8)),
458
+ });
459
+ return { ok: true, flowDir: written.dir, signature: written.signature, setup };
341
460
  }