fwdloop 0.11.0 → 0.13.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 +248 -27
  2. package/package.json +1 -1
  3. package/src/ask.js +3 -0
  4. package/src/authoring.js +103 -13
  5. package/src/books.js +23 -2
  6. package/src/canrun.js +36 -0
  7. package/src/config.js +256 -0
  8. package/src/declaration.js +72 -2
  9. package/src/drafter.js +53 -11
  10. package/src/draftspend.js +70 -0
  11. package/src/flow.js +43 -0
  12. package/src/keysfile.js +180 -0
  13. package/src/liveness.js +1 -1
  14. package/src/model-step.js +43 -8
  15. package/src/monthly.js +276 -0
  16. package/src/panel/author.js +482 -0
  17. package/src/panel/authorcard.js +297 -0
  18. package/src/panel/authorflows.js +312 -0
  19. package/src/panel/authorresume.js +149 -0
  20. package/src/panel/authorstart.js +257 -0
  21. package/src/panel/authorvalues.js +110 -0
  22. package/src/panel/data.js +228 -34
  23. package/src/panel/index.html +2073 -124
  24. package/src/panel/resume.js +14 -11
  25. package/src/panel/server.js +150 -117
  26. package/src/panel/settings.js +270 -0
  27. package/src/panel/spawn.js +77 -0
  28. package/src/provider.js +189 -43
  29. package/src/providershapes.js +19 -0
  30. package/src/runner.js +639 -85
  31. package/src/runvalues.js +178 -0
  32. package/src/send.js +10 -3
  33. package/src/setup.js +120 -0
  34. package/types/authoring.d.ts +24 -2
  35. package/types/books.d.ts +14 -2
  36. package/types/canrun.d.ts +32 -0
  37. package/types/config.d.ts +52 -0
  38. package/types/declaration.d.ts +9 -1
  39. package/types/drafter.d.ts +18 -2
  40. package/types/draftspend.d.ts +21 -0
  41. package/types/flow.d.ts +23 -0
  42. package/types/keysfile.d.ts +90 -0
  43. package/types/liveness.d.ts +2 -2
  44. package/types/model-step.d.ts +6 -2
  45. package/types/monthly.d.ts +130 -0
  46. package/types/panel/author.d.ts +335 -0
  47. package/types/panel/authorcard.d.ts +120 -0
  48. package/types/panel/authorflows.d.ts +175 -0
  49. package/types/panel/authorresume.d.ts +32 -0
  50. package/types/panel/authorstart.d.ts +115 -0
  51. package/types/panel/authorvalues.d.ts +62 -0
  52. package/types/panel/data.d.ts +103 -12
  53. package/types/panel/resume.d.ts +8 -1
  54. package/types/panel/server.d.ts +19 -33
  55. package/types/panel/settings.d.ts +23 -0
  56. package/types/panel/spawn.d.ts +30 -0
  57. package/types/provider.d.ts +123 -70
  58. package/types/providershapes.d.ts +11 -0
  59. package/types/runner.d.ts +120 -5
  60. package/types/runvalues.d.ts +97 -0
  61. package/types/send.d.ts +5 -1
  62. package/types/setup.d.ts +83 -0
package/bin/fwdloop CHANGED
@@ -15,22 +15,31 @@
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,
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';
33
- import { checkKeyPreflight } from '../src/provider.js';
35
+ import {
36
+ checkKeyPreflight, resolveSlot, resolvePrices, readPriceConfig, ceilingCostUsd,
37
+ } from '../src/provider.js';
38
+ import { configDoorHome } from '../src/config.js';
39
+ import {
40
+ claimHold, settleHold, monthlyRefusalText, ConfigError,
41
+ } from '../src/monthly.js';
42
+ import { keysForDoor } from '../src/keysfile.js';
34
43
  import {
35
44
  answerAsk, readAskEvidence, normalizeDecision, stripControl, withReopen,
36
45
  } from '../src/ask.js';
@@ -45,6 +54,65 @@ import { userInfo } from 'node:os';
45
54
  // never reads a key any other way and never prints it.
46
55
  const MODEL_SLOT = 'deepseek';
47
56
 
57
+ /**
58
+ * M4d: the ONE place a keyed command gets its env — the shell env with the keys file
59
+ * (`~/.config/fwdloop/.env`) filling what the shell leaves unset, loaded once at command
60
+ * start. A file other users can read is refused here (ruling 1A), before any dir or ledger
61
+ * write, at $0. process.env is never mutated: the merged env is handed down by hand.
62
+ */
63
+ function keyedEnv() {
64
+ const loaded = keysForDoor();
65
+ if (!loaded.ok) fail(String(loaded.refusal));
66
+ return loaded.env;
67
+ }
68
+
69
+ /**
70
+ * M4d piece 3: the monthly check, at the ONE seam all three money doors (`run`, `resume`, `draft`) call,
71
+ * before any spend and before any ledger write. No limit set = a $0 hold row (so the run's spend is counted once a limit is set), no check;
72
+ * a test process with no config home = no row at all. A broken config.json or an unwritable record refuses by name, never "no limit". A hold
73
+ * that does not fit refuses at $0 with the one refusal text. A hold that fits is given back when this
74
+ * process ends or parks (the `exit` hook runs on every exit path; a SIGKILL leaves it for the next check,
75
+ * which settles it as "process gone").
76
+ * @returns {{ addRunDir: (d: string) => void }}
77
+ */
78
+ function takeMonthlyHold({ what, flow, runId, runDir, holdUsd, spentAtHold = 0 }) {
79
+ const door = configDoorHome();
80
+ const home = door.home;
81
+ const also = [];
82
+ if (door.skip) {
83
+ // A test process with no config home skips the money checks. Only an injected test hook may do that;
84
+ // a real provider call here would spend with no keys file, prices, limit or record.
85
+ const hook = what === 'draft' ? 'FWDLOOP_TEST_DRAFT_PROVIDER' : 'FWDLOOP_TEST_MODEL_STEP';
86
+ if (!(process.env.NODE_ENV === 'test' && process.env[hook])) {
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.');
88
+ }
89
+ return { addRunDir: () => {} };
90
+ }
91
+ let claim;
92
+ try {
93
+ claim = claimHold({
94
+ what, flow, runId, runDir, holdUsd, spentAtHold, home,
95
+ });
96
+ } catch (err) {
97
+ if (!(err instanceof ConfigError)) throw err;
98
+ fail(`${err.message} — refusing to start rather than guess the monthly limit. Nothing spent.`);
99
+ }
100
+ if (!claim.ok) fail(monthlyRefusalText(claim.room));
101
+ if (claim.holdId !== null) {
102
+ process.on('exit', () => settleHold({
103
+ holdId: claim.holdId, why: process.exitCode ? 'ended (red)' : 'ended or parked', home, alsoRunDirs: also,
104
+ }));
105
+ }
106
+ return { addRunDir: (d) => also.push(d) };
107
+ }
108
+
109
+ /** The new runs a `rerun` chain started in this process — their spend belongs to this hold's month too. */
110
+ function rerunDirs(result, flowDir) {
111
+ const dirs = [];
112
+ for (let r = result; r && r.outcome === 'rerun'; r = r.newRun) dirs.push(join(flowDir, r.newRunId));
113
+ return dirs;
114
+ }
115
+
48
116
  function fail(message) {
49
117
  process.stderr.write(`fwdloop: ${message}\n`);
50
118
  process.exit(1);
@@ -84,7 +152,7 @@ function today() {
84
152
  * be hit by a user typing `--something`. This is how the test suite drives
85
153
  * every CLI scenario at $0 with zero chance of a real network call.
86
154
  */
87
- async function resolveModelStep(spendPath) {
155
+ async function resolveModelStep(spendPath, env) {
88
156
  if (process.env.NODE_ENV === 'test' && process.env.FWDLOOP_TEST_MODEL_STEP) {
89
157
  const modulePath = resolve(process.env.FWDLOOP_TEST_MODEL_STEP);
90
158
  const mod = await import(pathToFileURL(modulePath).href);
@@ -93,9 +161,9 @@ async function resolveModelStep(spendPath) {
93
161
  }
94
162
  return mod.default({ spendPath });
95
163
  }
96
- const keyCheck = checkKeyPreflight(MODEL_SLOT);
164
+ const keyCheck = checkKeyPreflight(MODEL_SLOT, env);
97
165
  if (!keyCheck.ok) throw new Error(keyCheck.message);
98
- return makeLiveModelStep({ slot: MODEL_SLOT, spendPath });
166
+ return makeLiveModelStep({ slot: MODEL_SLOT, spendPath, env });
99
167
  }
100
168
 
101
169
  function parseSourceFlags(list) {
@@ -153,6 +221,10 @@ function reportRunResult(result, { rootArg }) {
153
221
  reportRunResult(result.newRun, { rootArg });
154
222
  return;
155
223
  }
224
+ if (result.outcome === 'stopped') {
225
+ process.stdout.write(`stopped: spentUsd=${result.spentUsd} — ${result.red}\n`);
226
+ return;
227
+ }
156
228
  if (result.outcome === 'ask-expired') {
157
229
  process.stderr.write(`fwdloop: ask-expired — run cancelled, spentUsd=${result.spentUsd}\n`);
158
230
  process.exitCode = 1;
@@ -176,6 +248,7 @@ async function cmdRun(rest) {
176
248
  },
177
249
  allowPositionals: true,
178
250
  });
251
+ const env = keyedEnv();
179
252
 
180
253
  const flowName = positionals[0];
181
254
  if (!flowName) fail('run: a flow name is required — fwdloop run <flow> --root <dir> --source <role>=<path> ...');
@@ -191,7 +264,7 @@ async function cmdRun(rest) {
191
264
 
192
265
  const read = readFlow({ root, name: flowName, catalogue });
193
266
  if (!read.ok) fail(`flow "${flowName}": ${read.reds.join('; ')}`);
194
- const { arbiter, declaration } = read;
267
+ const { declaration } = read;
195
268
 
196
269
  let parsedSources;
197
270
  try {
@@ -200,7 +273,7 @@ async function cmdRun(rest) {
200
273
  fail(`run: ${err.message}`);
201
274
  return;
202
275
  }
203
- const declaredRoles = (arbiter.sources ?? []).map((s) => s.role);
276
+ const declaredRoles = (read.arbiter.sources ?? []).map((s) => s.role);
204
277
  for (const role of declaredRoles) {
205
278
  if (!Object.hasOwn(parsedSources, role)) {
206
279
  fail(`run: flow "${flowName}" declares source role "${role}" — pass --source ${role}=<path>`);
@@ -216,23 +289,47 @@ async function cmdRun(rest) {
216
289
  if (!existsSync(src.path)) fail(`run: source "${src.id}" is unreadable at ${src.path}`);
217
290
  }
218
291
 
219
- const runId = values['run-id'] ?? `run-${Date.now().toString(36)}-${randomUUID().slice(0, 8)}`;
220
- const runIdCheck = resolveRunDir(join(root, flowName), runId);
221
- if (!runIdCheck.ok) fail(runIdCheck.red);
222
- const { runDir } = runIdCheck;
223
- if (existsSync(runDir)) fail(`run: run dir "${runDir}" already exists — use a new --run-id`);
292
+ // M4e amendment 3: no --run-id -> the ONE claim (`run-<n>`, the folder created exclusively). A typed id is checked as before; its
293
+ // folder may already exist ONLY if empty — that is a name the panel just claimed for this very start, it holds no run.
294
+ let runId = values['run-id'];
295
+ /** @type {string} */
296
+ let runDir;
297
+ if (runId === undefined) {
298
+ const claimed = claimRunId(join(root, flowName));
299
+ if (!claimed.ok) fail(claimed.red);
300
+ runId = claimed.runId;
301
+ runDir = claimed.runDir;
302
+ } else {
303
+ const runIdCheck = resolveRunDir(join(root, flowName), runId);
304
+ if (!runIdCheck.ok) fail(runIdCheck.red);
305
+ runDir = runIdCheck.runDir;
306
+ // 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".
307
+ 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`);
308
+ }
309
+ // 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.
310
+ const applied = applyRunValues(read.arbiter, flowName, read.signature.flow, pickRunValues(runDir));
311
+ if (!applied.ok) fail(`run: ${applied.red}`);
312
+ const { arbiter } = applied;
313
+ // a refusal before the run starts must not leave the claimed empty folder behind (rmdir only ever removes an EMPTY folder)
314
+ process.on('exit', () => { dropUnstartedValues(runDir); try { rmdirSync(runDir); } catch { /* not empty, or gone: nothing to undo */ } });
224
315
 
225
316
  // The key preflight (item A: "refuses at $0 BEFORE any book write") runs
226
317
  // here — before ANY directory for this run is created.
227
318
  const spendPath = join(runDir, 'spend.jsonl');
228
319
  let modelStep;
229
320
  try {
230
- modelStep = await resolveModelStep(spendPath);
321
+ modelStep = await resolveModelStep(spendPath, env);
231
322
  } catch (err) {
232
323
  fail(err.message);
233
324
  return;
234
325
  }
235
326
 
327
+ // M4d piece 3: the monthly check — the hold is the flow's signed per-run cap. Before the run dir exists
328
+ // (runFlow makes it), so a refusal leaves only the refused rows in runs.jsonl.
329
+ const hold = takeMonthlyHold({
330
+ what: 'run', flow: flowName, runId, runDir, holdUsd: arbiter.capUsd,
331
+ });
332
+
236
333
  // Predict the frozen input paths `runFlow`'s own `freezeInputs` will use
237
334
  // (deterministic: `<runDir>/inputs/<id><ext>`) so the primitives map can
238
335
  // be built once, before `runFlow` itself freezes anything. Pure path
@@ -260,6 +357,7 @@ async function cmdRun(rest) {
260
357
  businessDate: today(),
261
358
  });
262
359
 
360
+ for (const d of rerunDirs(result, join(root, flowName))) hold.addRunDir(d);
263
361
  reportRunResult(result, { rootArg: values.root });
264
362
  }
265
363
 
@@ -444,6 +542,7 @@ async function cmdResume(rest) {
444
542
  },
445
543
  allowPositionals: true,
446
544
  });
545
+ const env = keyedEnv();
447
546
  const runId = positionals[0];
448
547
  if (!runId) fail('resume: a runId is required — fwdloop resume <runId> --flow <name> --root <dir>');
449
548
  if (!values.flow) fail('resume: --flow <name> is required');
@@ -464,16 +563,27 @@ async function cmdResume(rest) {
464
563
  if (!runIdCheck.ok) fail(runIdCheck.red);
465
564
  const { runDir } = runIdCheck;
466
565
  if (!existsSync(runDir)) fail(`resume: no run dir for runId "${runId}" under flow "${flowName}"`);
566
+ // M4e amendment 5 item 3: the cap this run was signed with (its own values file, else the flow's)
567
+ const applied = applyRunValues(read.arbiter, flowName, read.signature.flow, pickRunValues(runDir));
568
+ if (!applied.ok) fail(`resume: ${applied.red}`);
569
+ const { arbiter } = applied;
467
570
 
468
571
  const spendPath = join(runDir, 'spend.jsonl');
469
572
  let modelStep;
470
573
  try {
471
- modelStep = await resolveModelStep(spendPath);
574
+ modelStep = await resolveModelStep(spendPath, env);
472
575
  } catch (err) {
473
576
  fail(err.message);
474
577
  return;
475
578
  }
476
579
 
580
+ // M4d piece 3: the monthly check — the hold is the signed cap minus what this run already spent (its own
581
+ // state.json; no readable figure = the whole cap, never less).
582
+ const priorSpent = Number.isFinite(readRunState(runDir)?.spent) ? readRunState(runDir).spent : 0;
583
+ const hold = takeMonthlyHold({
584
+ what: 'resume', flow: flowName, runId, runDir, holdUsd: Math.max(0, arbiter.capUsd - priorSpent), spentAtHold: priorSpent,
585
+ });
586
+
477
587
  // Resume never re-freezes inputs — the run's own `inputs.json` (written at
478
588
  // park by `freezeInputs`) is the one source of the already-frozen paths a
479
589
  // sandboxed primitive may read.
@@ -511,6 +621,93 @@ async function cmdResume(rest) {
511
621
  businessDate: today(),
512
622
  });
513
623
 
624
+ for (const d of rerunDirs(result, join(root, flowName))) hold.addRunDir(d);
625
+ reportRunResult(result, { rootArg: values.root });
626
+ }
627
+
628
+ // ---------------------------------------------------------------------------
629
+ // 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
630
+ // values version (the human's new cap). `fwdloop continue <runId> --flow <name> --root <dir>`. The panel's "Sign & resume" writes
631
+ // the new signed version first and then starts this; run by hand it continues under whatever version is on disk.
632
+ // ---------------------------------------------------------------------------
633
+
634
+ async function cmdContinue(rest) {
635
+ const { values, positionals } = parseArgs({
636
+ args: rest,
637
+ options: {
638
+ flow: { type: 'string' },
639
+ root: { type: 'string' },
640
+ },
641
+ allowPositionals: true,
642
+ });
643
+ const env = keyedEnv();
644
+ const runId = positionals[0];
645
+ if (!runId) fail('continue: a runId is required — fwdloop continue <runId> --flow <name> --root <dir>');
646
+ if (!values.flow) fail('continue: --flow <name> is required');
647
+ if (!values.root) fail('continue: --root <dir> is required');
648
+
649
+ const root = resolveRoot('continue', values.root);
650
+ const flowName = values.flow;
651
+
652
+ const loaded = loadCatalogue();
653
+ if (!loaded.ok) fail(`catalogue: ${loaded.reds.join('; ')}`);
654
+ const catalogue = loaded.primitives;
655
+
656
+ const read = readFlow({ root, name: flowName, catalogue });
657
+ if (!read.ok) fail(`flow "${flowName}": ${read.reds.join('; ')}`);
658
+ const { declaration } = read;
659
+
660
+ const runIdCheck = resolveRunDir(join(root, flowName), runId);
661
+ if (!runIdCheck.ok) fail(runIdCheck.red);
662
+ const { runDir } = runIdCheck;
663
+ if (!existsSync(runDir)) fail(`continue: no run dir for runId "${runId}" under flow "${flowName}"`);
664
+ const applied = applyRunValues(read.arbiter, flowName, read.signature.flow, pickRunValues(runDir));
665
+ if (!applied.ok) fail(`continue: ${applied.red}`);
666
+
667
+ const spendPath = join(runDir, 'spend.jsonl');
668
+ let modelStep;
669
+ try {
670
+ modelStep = await resolveModelStep(spendPath, env);
671
+ } catch (err) {
672
+ fail(err.message);
673
+ return;
674
+ }
675
+
676
+ // 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).
677
+ const spentSoFar = auditSpend(runDir);
678
+ if (!spentSoFar.ok) fail(`continue: run "${runId}" ${spentSoFar.red}`);
679
+ const hold = takeMonthlyHold({
680
+ what: 'resume', flow: flowName, runId, runDir, holdUsd: Math.max(0, applied.arbiter.capUsd - spentSoFar.total), spentAtHold: spentSoFar.total,
681
+ });
682
+
683
+ const inputsManifestRead = readFileInside(runDir, 'inputs.json');
684
+ let inputsManifest = [];
685
+ if (inputsManifestRead.ok) {
686
+ try {
687
+ inputsManifest = JSON.parse(inputsManifestRead.text);
688
+ } catch (err) {
689
+ fail(`continue: inputs.json for run "${runId}" is not valid JSON — ${err.message}`);
690
+ return;
691
+ }
692
+ }
693
+ const allVerbs = [...new Set(declaration.steps.flatMap((s) => s.primitives ?? []))];
694
+ const { tools: primitives, reds: primitiveReds } = resolvePrimitives(catalogue, allVerbs, {
695
+ runDir, inputs: inputsManifest.map((m) => ({ id: m.id, frozen: m.frozen })),
696
+ });
697
+
698
+ const result = await continueRun({
699
+ root,
700
+ name: flowName,
701
+ runId,
702
+ catalogue,
703
+ modelStep,
704
+ sendStep: sendViaPrimitive,
705
+ primitives,
706
+ primitiveReds,
707
+ businessDate: today(),
708
+ });
709
+
710
+ for (const d of rerunDirs(result, join(root, flowName))) hold.addRunDir(d);
514
711
  reportRunResult(result, { rootArg: values.root });
515
712
  }
516
713
 
@@ -518,11 +715,9 @@ async function cmdResume(rest) {
518
715
  // panel — M4a piece 2 + M4b (docs/wiki/the-module-ladder.md, "M4a — read-only
519
716
  // panel" and "M4b — inputs"): `fwdloop panel [--port 4800] [--root <dir>]`.
520
717
  // Reads are GET/HEAD; the only writes are POST /api/answer and POST
521
- // /api/resume (src/panel/server.js), each gated by Origin/Host + the panel's
522
- // cookie. `fwdloop panel` writes its token to a 0600 file ($XDG_RUNTIME_DIR/fwdloop/
523
- // panel-<port>.token, else ~/.cache/fwdloop/; reused across restarts while that file is 0600) and prints `http://127.0.0.1:<port>/?t=<token>` —
524
- // open that link (it sets the cookie); every request needs it. Bound to 127.0.0.1 only. Never picks
525
- // a different port on collision — a taken port is a loud, non-zero-exit
718
+ // /api/resume (src/panel/server.js), each gated by Origin/Host. No token, no
719
+ // cookie (M4e amendment 4 item 8): `fwdloop panel` prints `http://127.0.0.1:<port>/`.
720
+ // Bound to 127.0.0.1 only. Never picks a different port on collision — a taken port is a loud, non-zero-exit
526
721
  // failure.
527
722
  // ---------------------------------------------------------------------------
528
723
 
@@ -559,12 +754,13 @@ async function cmdDraft(rest) {
559
754
  const { values, positionals } = parseArgs({
560
755
  args: rest,
561
756
  options: {
562
- out: { type: 'string' }, root: { type: 'string' }, name: { type: 'string' }, budget: { type: 'string' },
757
+ out: { type: 'string' }, root: { type: 'string' }, name: { type: 'string' }, budget: { type: 'string' }, 'revise-from': { type: 'string' }, note: { type: 'string' },
563
758
  },
564
759
  allowPositionals: true,
565
760
  });
761
+ const env = keyedEnv();
566
762
  const proseFile = positionals[0];
567
- if (!proseFile) fail('draft: a prose file is required — fwdloop draft <prose.txt> --out <draftDir> --root <flowsDir> --name <flow> [--budget <usd>]');
763
+ if (!proseFile) fail('draft: a prose file is required — fwdloop draft <prose.txt> --out <draftDir> --root <flowsDir> --name <flow> [--budget <usd>] [--revise-from <planDir> --note <file>]');
568
764
  for (const req of ['out', 'root', 'name']) if (!values[req]) fail(`draft: --${req} is required`);
569
765
 
570
766
  let injected = {};
@@ -572,12 +768,35 @@ async function cmdDraft(rest) {
572
768
  const mod = await import(pathToFileURL(resolve(process.env.FWDLOOP_TEST_DRAFT_PROVIDER)).href);
573
769
  injected = await mod.default();
574
770
  }
771
+ // The key preflight comes first (draftToDir repeats it), so an unset key keeps its own message ahead of the NODE_ENV refusal.
772
+ if (injected.provider == null) {
773
+ const keyCheck = checkKeyPreflight('deepseek', env);
774
+ if (!keyCheck.ok) fail(`draft refused at $0 — ${keyCheck.message}`);
775
+ }
776
+ // M4d piece 3: the monthly check — a draft has no signed cap, so it holds one ceiling round, priced by the
777
+ // ONE price lookup (an injected test provider carries its own rates).
778
+ let ceiling;
779
+ try {
780
+ const priceConfig = readPriceConfig();
781
+ const modelId = injected.modelId ?? resolveSlot('deepseek', { config: priceConfig }).model;
782
+ const prices = injected.rates ? { rates: injected.rates } : resolvePrices(modelId, { slot: 'deepseek', config: priceConfig });
783
+ ceiling = ceilingCostUsd(modelId, undefined, { prices });
784
+ } catch (err) {
785
+ if (!(err instanceof ConfigError)) throw err;
786
+ fail(`${err.message} — refusing to draft rather than guess the price. Nothing spent.`);
787
+ }
788
+ takeMonthlyHold({
789
+ what: 'draft', flow: values.name, runId: null, runDir: resolve(values.out), holdUsd: ceiling,
790
+ });
575
791
  const result = await draftToDir({
576
792
  proseFile: resolve(proseFile),
577
793
  dir: resolve(values.out),
578
794
  root: resolve(values.root),
579
795
  name: values.name,
580
796
  budgetUsd: values.budget === undefined ? undefined : Number(values.budget),
797
+ reviseFrom: values['revise-from'] === undefined ? undefined : resolve(values['revise-from']),
798
+ noteFile: values.note === undefined ? undefined : resolve(values.note),
799
+ env,
581
800
  ...injected,
582
801
  });
583
802
  const cost = result.costUsd === null ? 'UNKNOWN' : costText(Number(result.costUsd), result.spendComplete);
@@ -601,6 +820,7 @@ async function cmdSign(rest) {
601
820
  options: { approve: { type: 'string' }, 'signed-by': { type: 'string' } },
602
821
  allowPositionals: true,
603
822
  });
823
+ const env = keyedEnv(); // sign takes no key, but its leak sweep must know the file's keys too
604
824
  const dir = positionals[0];
605
825
  if (!dir) fail('sign: a draft dir is required — fwdloop sign <dir> --approve <hash>');
606
826
  // Amendment 2: a person at a keyboard. TTY check first (cheapest), then the typed flow name; only then
@@ -613,7 +833,7 @@ async function cmdSign(rest) {
613
833
  const typed = await confirmTypedName({ name: flowName });
614
834
  if (!typed.ok) fail(`sign refused — ${typed.red}`);
615
835
  const result = signDraft({
616
- dir: resolve(dir), approve: values.approve, signedBy: values['signed-by'] ?? userInfo().username,
836
+ dir: resolve(dir), approve: values.approve, signedBy: values['signed-by'] ?? userInfo().username, env,
617
837
  });
618
838
  if (!result.ok) fail(`sign refused — ${result.reds.join('; ')}`);
619
839
  process.stdout.write(`signed: ${result.flowDir} (by ${result.signature.signedBy})\n`);
@@ -623,7 +843,7 @@ async function cmdSign(rest) {
623
843
 
624
844
  async function main() {
625
845
  const [verb, ...rest] = process.argv.slice(2);
626
- if (!verb) fail('usage: fwdloop draft|sign|run|inbox|show|answer|resume|panel ...');
846
+ if (!verb) fail('usage: fwdloop draft|sign|run|inbox|show|answer|resume|continue|panel ...');
627
847
 
628
848
  if (verb === 'draft') return cmdDraft(rest);
629
849
  if (verb === 'sign') return cmdSign(rest);
@@ -632,8 +852,9 @@ async function main() {
632
852
  if (verb === 'show') return cmdShow(rest);
633
853
  if (verb === 'answer') return cmdAnswer(rest);
634
854
  if (verb === 'resume') return cmdResume(rest);
855
+ if (verb === 'continue') return cmdContinue(rest);
635
856
  if (verb === 'panel') return cmdPanel(rest);
636
- fail(`unknown verb "${verb}" — expected draft | sign | run | inbox | show | answer | resume | panel`);
857
+ fail(`unknown verb "${verb}" — expected draft | sign | run | inbox | show | answer | resume | continue | panel`);
637
858
  return undefined;
638
859
  }
639
860
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "fwdloop",
3
- "version": "0.11.0",
3
+ "version": "0.13.0",
4
4
  "description": "Describe a job as steps and guardrails; an agent builds the workflow, pauses for humans where you said, checks every step happened, and reruns it under budgets it cannot touch.",
5
5
  "type": "module",
6
6
  "main": "./src/index.js",
package/src/ask.js CHANGED
@@ -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' };