fwdloop 0.12.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 (56) hide show
  1. package/bin/fwdloop +136 -21
  2. package/package.json +1 -1
  3. package/src/ask.js +3 -0
  4. package/src/authoring.js +101 -13
  5. package/src/books.js +23 -2
  6. package/src/canrun.js +36 -0
  7. package/src/config.js +2 -1
  8. package/src/declaration.js +72 -2
  9. package/src/drafter.js +41 -3
  10. package/src/draftspend.js +70 -0
  11. package/src/flow.js +43 -0
  12. package/src/liveness.js +1 -1
  13. package/src/model-step.js +30 -4
  14. package/src/monthly.js +58 -13
  15. package/src/panel/author.js +482 -0
  16. package/src/panel/authorcard.js +297 -0
  17. package/src/panel/authorflows.js +312 -0
  18. package/src/panel/authorresume.js +149 -0
  19. package/src/panel/authorstart.js +257 -0
  20. package/src/panel/authorvalues.js +110 -0
  21. package/src/panel/data.js +228 -34
  22. package/src/panel/index.html +1745 -127
  23. package/src/panel/resume.js +6 -8
  24. package/src/panel/server.js +119 -119
  25. package/src/panel/settings.js +7 -5
  26. package/src/panel/spawn.js +77 -0
  27. package/src/provider.js +12 -17
  28. package/src/runner.js +639 -85
  29. package/src/runvalues.js +178 -0
  30. package/src/send.js +10 -3
  31. package/src/setup.js +120 -0
  32. package/types/authoring.d.ts +24 -2
  33. package/types/books.d.ts +14 -2
  34. package/types/canrun.d.ts +32 -0
  35. package/types/config.d.ts +1 -0
  36. package/types/declaration.d.ts +9 -1
  37. package/types/drafter.d.ts +15 -1
  38. package/types/draftspend.d.ts +21 -0
  39. package/types/flow.d.ts +23 -0
  40. package/types/liveness.d.ts +2 -2
  41. package/types/model-step.d.ts +3 -1
  42. package/types/monthly.d.ts +21 -0
  43. package/types/panel/author.d.ts +335 -0
  44. package/types/panel/authorcard.d.ts +120 -0
  45. package/types/panel/authorflows.d.ts +175 -0
  46. package/types/panel/authorresume.d.ts +32 -0
  47. package/types/panel/authorstart.d.ts +115 -0
  48. package/types/panel/authorvalues.d.ts +62 -0
  49. package/types/panel/data.d.ts +103 -12
  50. package/types/panel/server.d.ts +11 -33
  51. package/types/panel/spawn.d.ts +30 -0
  52. package/types/provider.d.ts +6 -9
  53. package/types/runner.d.ts +120 -5
  54. package/types/runvalues.d.ts +97 -0
  55. package/types/send.d.ts +5 -1
  56. package/types/setup.d.ts +83 -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';
@@ -219,6 +221,10 @@ function reportRunResult(result, { rootArg }) {
219
221
  reportRunResult(result.newRun, { rootArg });
220
222
  return;
221
223
  }
224
+ if (result.outcome === 'stopped') {
225
+ process.stdout.write(`stopped: spentUsd=${result.spentUsd} — ${result.red}\n`);
226
+ return;
227
+ }
222
228
  if (result.outcome === 'ask-expired') {
223
229
  process.stderr.write(`fwdloop: ask-expired — run cancelled, spentUsd=${result.spentUsd}\n`);
224
230
  process.exitCode = 1;
@@ -258,7 +264,7 @@ async function cmdRun(rest) {
258
264
 
259
265
  const read = readFlow({ root, name: flowName, catalogue });
260
266
  if (!read.ok) fail(`flow "${flowName}": ${read.reds.join('; ')}`);
261
- const { arbiter, declaration } = read;
267
+ const { declaration } = read;
262
268
 
263
269
  let parsedSources;
264
270
  try {
@@ -267,7 +273,7 @@ async function cmdRun(rest) {
267
273
  fail(`run: ${err.message}`);
268
274
  return;
269
275
  }
270
- const declaredRoles = (arbiter.sources ?? []).map((s) => s.role);
276
+ const declaredRoles = (read.arbiter.sources ?? []).map((s) => s.role);
271
277
  for (const role of declaredRoles) {
272
278
  if (!Object.hasOwn(parsedSources, role)) {
273
279
  fail(`run: flow "${flowName}" declares source role "${role}" — pass --source ${role}=<path>`);
@@ -283,11 +289,29 @@ async function cmdRun(rest) {
283
289
  if (!existsSync(src.path)) fail(`run: source "${src.id}" is unreadable at ${src.path}`);
284
290
  }
285
291
 
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`);
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 */ } });
291
315
 
292
316
  // The key preflight (item A: "refuses at $0 BEFORE any book write") runs
293
317
  // here — before ANY directory for this run is created.
@@ -533,12 +557,16 @@ async function cmdResume(rest) {
533
557
 
534
558
  const read = readFlow({ root, name: flowName, catalogue });
535
559
  if (!read.ok) fail(`flow "${flowName}": ${read.reds.join('; ')}`);
536
- const { declaration, arbiter } = read;
560
+ const { declaration } = read;
537
561
 
538
562
  const runIdCheck = resolveRunDir(join(root, flowName), runId);
539
563
  if (!runIdCheck.ok) fail(runIdCheck.red);
540
564
  const { runDir } = runIdCheck;
541
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;
542
570
 
543
571
  const spendPath = join(runDir, 'spend.jsonl');
544
572
  let modelStep;
@@ -597,15 +625,99 @@ async function cmdResume(rest) {
597
625
  reportRunResult(result, { rootArg: values.root });
598
626
  }
599
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);
711
+ reportRunResult(result, { rootArg: values.root });
712
+ }
713
+
600
714
  // ---------------------------------------------------------------------------
601
715
  // panel — M4a piece 2 + M4b (docs/wiki/the-module-ladder.md, "M4a — read-only
602
716
  // panel" and "M4b — inputs"): `fwdloop panel [--port 4800] [--root <dir>]`.
603
717
  // 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
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
609
721
  // failure.
610
722
  // ---------------------------------------------------------------------------
611
723
 
@@ -642,13 +754,13 @@ async function cmdDraft(rest) {
642
754
  const { values, positionals } = parseArgs({
643
755
  args: rest,
644
756
  options: {
645
- 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' },
646
758
  },
647
759
  allowPositionals: true,
648
760
  });
649
761
  const env = keyedEnv();
650
762
  const proseFile = positionals[0];
651
- 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>]');
652
764
  for (const req of ['out', 'root', 'name']) if (!values[req]) fail(`draft: --${req} is required`);
653
765
 
654
766
  let injected = {};
@@ -682,6 +794,8 @@ async function cmdDraft(rest) {
682
794
  root: resolve(values.root),
683
795
  name: values.name,
684
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),
685
799
  env,
686
800
  ...injected,
687
801
  });
@@ -729,7 +843,7 @@ async function cmdSign(rest) {
729
843
 
730
844
  async function main() {
731
845
  const [verb, ...rest] = process.argv.slice(2);
732
- 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 ...');
733
847
 
734
848
  if (verb === 'draft') return cmdDraft(rest);
735
849
  if (verb === 'sign') return cmdSign(rest);
@@ -738,8 +852,9 @@ async function main() {
738
852
  if (verb === 'show') return cmdShow(rest);
739
853
  if (verb === 'answer') return cmdAnswer(rest);
740
854
  if (verb === 'resume') return cmdResume(rest);
855
+ if (verb === 'continue') return cmdContinue(rest);
741
856
  if (verb === 'panel') return cmdPanel(rest);
742
- 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`);
743
858
  return undefined;
744
859
  }
745
860
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "fwdloop",
3
- "version": "0.12.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' };
package/src/authoring.js CHANGED
@@ -28,9 +28,13 @@ 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';
36
40
  export const SIGN_LINE = (dir, hash) => `DRAFTED — NOT SIGNED. To sign: fwdloop sign ${dir} --approve ${hash}`;
@@ -68,6 +72,15 @@ export function scrub(text, secrets) {
68
72
  return out;
69
73
  }
70
74
 
75
+ /**
76
+ * Does `text` carry any provider key VALUE in `env` (every slot, 8+ chars, literal)? The one test for a human's free text
77
+ * (the revise note) — the same literal rule `scrub` and `sweepForSecrets` use.
78
+ * @param {string} text @param {Record<string, string|undefined>} env
79
+ */
80
+ export function textHasKey(text, env) {
81
+ return Object.values(PROVIDER_SLOTS).some((p) => { const k = env[p.envVar]; return typeof k === 'string' && k.length >= 8 && text.includes(k); });
82
+ }
83
+
71
84
  /** Count files directly inside `dir` that contain a secret literally. */
72
85
  export function sweepForSecrets(dir, secrets) {
73
86
  const live = secrets.filter((s) => typeof s === 'string' && s.length >= 8);
@@ -96,6 +109,24 @@ export const costText = (n, spendComplete = true) => {
96
109
  };
97
110
  const usd = costText;
98
111
 
112
+ /** The readout's section headings: the ONE list. buildReadout writes them from here and `readoutHeadIndexes` finds them by it,
113
+ * so the panel's bold and the template cannot drift (M4e amendment 7 item 3). */
114
+ const READOUT_HEADS = {
115
+ inputs: 'INPUTS',
116
+ steps: 'STEPS',
117
+ asks: 'ASKS (human stops)',
118
+ sends: 'SEND TARGET (nothing leaves before an accepted ask)',
119
+ refused: 'REFUSED LINES',
120
+ jobLines: 'JOB LINES',
121
+ };
122
+ /** Zero-based indexes of the heading lines in a readout's text (split on "\n"): the panel renders those bold. */
123
+ export function readoutHeadIndexes(text) {
124
+ const heads = new Set(Object.values(READOUT_HEADS));
125
+ const idx = [];
126
+ String(text).split('\n').forEach((l, i) => { if (heads.has(l)) idx.push(i); });
127
+ return idx;
128
+ }
129
+
99
130
  /** Plain-text readout of what the human is about to sign. Pure. */
100
131
  export function buildReadout({
101
132
  declaration, arbiter, lines, name, modelId, costUsd, rounds, spendComplete, root,
@@ -105,29 +136,33 @@ export function buildReadout({
105
136
  out.push(`Drafted by: ${modelId ?? '?'} in ${rounds} round(s), cost ${usd(costUsd, spendComplete)}`);
106
137
  if (typeof root === 'string') out.push(`Flows root: ${root} (the flow is written to <flows root>/${name} when you sign)`);
107
138
  out.push(`Cap per run (signed by you in the prose): $${arbiter.capUsd}`, '');
108
- out.push('INPUTS');
139
+ out.push(READOUT_HEADS.inputs);
109
140
  for (const s of arbiter.sources) {
110
141
  const h = declaration.inputFacts?.[s.role];
111
142
  out.push(` ${s.role} = ${s.path}${h ? ` [headings: ${h.join(' | ') || 'none'}]` : ''}`);
112
143
  }
113
- out.push('', 'STEPS');
144
+ out.push('', READOUT_HEADS.steps);
114
145
  declaration.steps.forEach((st, i) => {
115
146
  out.push(` ${i + 1}. (line ${st.fromLine}) ${st.goal}`);
116
147
  out.push(` grants: ${st.primitives?.length ? st.primitives.join(', ') : 'none (pure stop)'}`
117
148
  + ` | reads: ${st.reads?.length ? st.reads.join(', ') : '-'} | emits: ${st.emits} | check: ${st.close?.class}`);
118
149
  });
119
- out.push('', 'ASKS (human stops)');
150
+ out.push('', READOUT_HEADS.asks);
120
151
  for (const a of arbiter.asks) out.push(` line ${a.line}: "${a.question}" (ttl ${fmtTtl(a.ttlMs)})`);
121
152
  if (arbiter.asks.length === 0) out.push(' none');
122
- out.push('', 'SEND TARGET (nothing leaves before an accepted ask)');
153
+ out.push('', READOUT_HEADS.sends);
123
154
  for (const s of arbiter.sends) out.push(` line ${s.line} -> ${s.target.kind}:${s.target.path}`);
124
155
  if (arbiter.sends.length === 0) out.push(' none');
125
156
  const refused = declaration.refused ?? [];
126
157
  if (refused.length) {
127
- out.push('', 'REFUSED LINES');
158
+ out.push('', READOUT_HEADS.refused);
128
159
  for (const r of refused) out.push(` line ${r.line}: ${r.reason}`);
129
160
  }
130
- out.push('', 'JOB LINES', ...lines.map((l) => ` ${l.n}. ${l.text}`));
161
+ out.push('', READOUT_HEADS.jobLines);
162
+ for (const l of lines) {
163
+ out.push(` ${l.n}. ${l.text}`);
164
+ if (typeof l.guardrail === 'string' && l.guardrail.trim() !== '') out.push(` ~ ${l.guardrail}`);
165
+ }
131
166
  return `${out.join('\n')}\n`;
132
167
  }
133
168
 
@@ -163,7 +198,7 @@ export function readProseFile(file) {
163
198
  * Test seam: `provider`/`rates`/`modelId` are injected; without them a live provider is built.
164
199
  */
165
200
  export async function draftToDir({
166
- proseFile, dir, root, name, slot = 'deepseek', model, budgetUsd = DRAFT_BUDGET_USD, env = process.env, provider, rates, modelId,
201
+ proseFile, dir, root, name, slot = 'deepseek', model, budgetUsd = DRAFT_BUDGET_USD, env = process.env, provider, rates, modelId, reviseFrom, noteFile,
167
202
  }) {
168
203
  const refuse = (reds) => ({ ok: false, wrote: false, reds, costUsd: 0 });
169
204
  const nameCheck = checkFlowName(name);
@@ -174,7 +209,10 @@ export async function draftToDir({
174
209
  const realRoot = realpathOfNew(root);
175
210
  const realDir = realpathOfNew(dir);
176
211
  const rel = path.relative(realRoot, realDir);
177
- if (rel === '' || (rel !== '..' && !rel.startsWith(`..${path.sep}`) && !path.isAbsolute(rel))) {
212
+ // M4e piece 2: the panel's own draft folders live at exactly `<root>/.drafts/<id>/...` (a dot-name is never a flow:
213
+ // `checkFlowName` refuses it, so `listFlowNames`/`readFlow` never list it). Nothing else under the root is allowed.
214
+ const panelDrafts = rel.startsWith(`${PANEL_DRAFTS_DIR}${path.sep}`) && !path.isAbsolute(rel);
215
+ if (!panelDrafts && (rel === '' || (rel !== '..' && !rel.startsWith(`..${path.sep}`) && !path.isAbsolute(rel)))) {
178
216
  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
217
  }
180
218
  const read = readProseFile(proseFile);
@@ -188,6 +226,28 @@ export async function draftToDir({
188
226
  }
189
227
  const secrets = secretVar && env[secretVar] ? [env[secretVar]] : [];
190
228
  if (secrets.some((s) => s.length >= 8 && prose.text.includes(s))) return refuse(['prose: contains an API key value — refused']);
229
+ // M4e amendment 3 item 3: a revise starts from the current green plan's dir plus the human's note, and nothing else. All $0, before the dir is claimed.
230
+ /** @type {{ plan: any, note: string }|undefined} */
231
+ let revise;
232
+ if ((reviseFrom === undefined) !== (noteFile === undefined)) return refuse(['draft: --revise-from and --note go together']);
233
+ if (reviseFrom !== undefined && noteFile !== undefined) {
234
+ const prev = {};
235
+ for (const f of ['prose.txt', 'declaration.json', SPEC_HASH_FILE]) {
236
+ const r = readFileInside(reviseFrom, f);
237
+ if (!r.ok) return refuse([`revise: "${reviseFrom}" is not a green draft — ${f} ${r.missing ? 'is missing' : `is refused (${r.red})`}`]);
238
+ prev[f] = r.text;
239
+ }
240
+ // the card's fields come only from the card: a revise carries the SAME prose, byte for byte, as the plan it revises
241
+ if (prev['prose.txt'] !== prose.text) return refuse(['revise: the prose differs from the plan being revised — a revise never changes the card']);
242
+ const noteRead = readFileInside(path.dirname(noteFile), path.basename(noteFile));
243
+ if (!noteRead.ok) return refuse([`revise: cannot read the note "${noteFile}": ${noteRead.missing ? 'missing' : noteRead.red}`]);
244
+ const note = noteRead.text;
245
+ if (note.trim() === '') return refuse(['revise: the note is empty']);
246
+ if (textHasKey(note, env)) return refuse(['note: contains an API key value — refused']);
247
+ let plan;
248
+ try { plan = JSON.parse(prev['declaration.json']); } catch { return refuse(['revise: the plan being revised is not valid JSON']); }
249
+ revise = { plan, note };
250
+ }
191
251
  // Red messages can echo what a provider's error body echoed (a key): scrubbed like every file, before anything prints them.
192
252
  const cleanReds = (reds) => (reds ?? []).map((r) => scrub(String(r), secrets));
193
253
  // Claim the dir BEFORE the paid round (exclusive mkdir: a race or an existing path refuses at $0).
@@ -200,8 +260,26 @@ export async function draftToDir({
200
260
  return e.code === 'EEXIST' ? exists() : refuse([`draft: cannot create "${dir}": ${e.code ?? e.message}`]);
201
261
  }
202
262
 
263
+ // Spend is booked per call into `<dir>/draft-spend.json` (src/draftspend.js), so a draft stopped between rounds
264
+ // 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.
265
+ let startedAt = null;
266
+ const onBook = ({
267
+ inFlight, calls, unmetered, metered, modelId: usedModel, price,
268
+ }) => {
269
+ const now = new Date().toISOString();
270
+ startedAt ??= now;
271
+ try {
272
+ writeDraftSpend(dir, {
273
+ kind: 'draft-live', provider: slot, model: usedModel ?? modelId ?? null, price: price ?? null, tokens: metered.tokens, costUsd: metered.costUsd, rounds: metered.rounds,
274
+ calls, spendComplete: !inFlight && unmetered === 0 && metered.costUsd !== null, inFlight, at: startedAt, startedAt, updatedAt: now,
275
+ });
276
+ } catch (e) {
277
+ if (inFlight) throw new Error(`draft: cannot book the spend before the call (${e.code ?? e.message}) — nothing was spent`);
278
+ // after a call the cost is already in the file as "one call in flight" (a ceiling): the honest direction, so no throw
279
+ }
280
+ };
203
281
  const result = await draft({
204
- proseText: prose.text, slot, model, budgetUsd, provider, rates, modelId, env,
282
+ proseText: prose.text, slot, model, budgetUsd, provider, rates, modelId, env, onBook, revise,
205
283
  });
206
284
  if (result.stop === 'pre-flight') {
207
285
  try { rmdirSync(dir); } catch { /* the claimed dir is still empty; leave it rather than mask the refusal */ }
@@ -219,6 +297,7 @@ export async function draftToDir({
219
297
  files['prose.txt'] = prose.text; // verbatim
220
298
  const targetText = dj({ root, name });
221
299
  files['target.json'] = targetText;
300
+ if (revise) files['note.txt'] = revise.note; // kept with the draft it made (write-once: the dir is exclusive)
222
301
  files['log.json'] = scrub(dj({
223
302
  ok: result.ok, stop: result.stop, reds: result.reds, rounds: result.rounds, calls: result.calls, costUsd: result.costUsd, spendComplete: result.spendComplete,
224
303
  modelId: result.modelId, modelReturned: result.modelReturned, structureRetries: result.structureRetries,
@@ -259,6 +338,9 @@ export async function draftToDir({
259
338
  spendComplete: result.spendComplete,
260
339
  stop: result.stop,
261
340
  budgetUsd,
341
+ // the draft's own time (amendment 7 item 2: the Draft's total time adds up from these); null when no call was booked
342
+ startedAt,
343
+ wallMs: startedAt === null ? null : Math.max(0, Date.now() - Date.parse(startedAt)),
262
344
  });
263
345
  for (const [f, text] of Object.entries(files)) writeFileSync(path.join(dir, f), text);
264
346
  leaks = sweepForSecrets(dir, secrets);
@@ -279,9 +361,10 @@ export async function draftToDir({
279
361
  /**
280
362
  * The human step, $0. Every refusal returns reds and writes NO flow.
281
363
  * `signedBy` must come from the human's own invocation (the CLI's --signed-by/username).
364
+ * `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
365
  */
283
366
  export function signDraft({
284
- dir, approve, signedBy, signedAt = new Date().toISOString(), env = process.env,
367
+ dir, approve, signedBy, signedAt = new Date().toISOString(), env = process.env, sessionDir,
285
368
  }) {
286
369
  const refuse = (...reds) => ({ ok: false, reds });
287
370
  if (readFileInside(dir, LEAK_MARKER_FILE).ok) return refuse(`sign: "${dir}" carries a key-leak marker (${LEAK_MARKER_FILE}) — never signed`);
@@ -319,7 +402,7 @@ export function signDraft({
319
402
  const cat = loadCatalogue();
320
403
  if (!cat.ok) return refuse(`sign: catalogue: ${cat.reds.join('; ')}`);
321
404
  const verdict = validateDeclaration(declaration, {
322
- arbiter: signed.arbiter, lines: signed.lines, catalogue: cat.primitives, wired: WIRED_VERBS, verbatimGoals: true,
405
+ arbiter: signed.arbiter, lines: signed.lines, catalogue: cat.primitives, wired: WIRED_VERBS, verbatimGoals: true, fitJobLine: true,
323
406
  });
324
407
  if (!verdict.ok) return { ok: false, reds: verdict.reds };
325
408
 
@@ -328,7 +411,7 @@ export function signDraft({
328
411
  if (s.kind === 'file' && !existsSync(s.path)) reds.push(`sign: input source "${s.role}" is missing at ${s.path}`);
329
412
  }
330
413
  for (const s of signed.arbiter.sends) {
331
- const d = checkSendDestination(`${s.target.kind}:${s.target.path}`);
414
+ const d = checkSendDestination(`${s.target.kind}:${s.target.path}`, { root: target.root });
332
415
  if (!d.ok) reds.push(`sign: ${d.red}`);
333
416
  }
334
417
  if (reds.length) return { ok: false, reds };
@@ -337,5 +420,10 @@ export function signDraft({
337
420
  root: target.root, name: target.name, proseText: parts['prose.txt'], declaration, signedBy, signedAt, catalogue: cat.primitives,
338
421
  });
339
422
  if (!written.ok) return { ok: false, reds: written.reds };
340
- return { ok: true, flowDir: written.dir, signature: written.signature };
423
+ // 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
424
+ // 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".
425
+ const setup = writeSetup({
426
+ 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)),
427
+ });
428
+ return { ok: true, flowDir: written.dir, signature: written.signature, setup };
341
429
  }
package/src/books.js CHANGED
@@ -21,7 +21,7 @@
21
21
  import { appendFileSync, mkdirSync } from 'node:fs';
22
22
  import { dirname, join } from 'node:path';
23
23
 
24
- import { readFileInside } from './flow.js';
24
+ import { readFileInside, readdirInside } from './flow.js';
25
25
 
26
26
  function appendLine(filePath, row) {
27
27
  mkdirSync(dirname(filePath), { recursive: true });
@@ -33,7 +33,7 @@ function appendLine(filePath, row) {
33
33
  * rewritten, not a book the arbiter reads. One row per process that works on
34
34
  * the run (`src/liveness.js` `recordPid` builds the row).
35
35
  * @param {string} runDir
36
- * @param {{pid: number, startedAt: string, procStart: string|null, leg: 'run'|'resume'}} row
36
+ * @param {{pid: number, startedAt: string, procStart: string|null, leg: 'run'|'resume'|'continue'}} row
37
37
  */
38
38
  export function appendPidRow(runDir, row) {
39
39
  appendLine(join(runDir, 'pids.jsonl'), row);
@@ -301,3 +301,24 @@ export function appendHistory(flowDir, row) {
301
301
  export function readHistory(flowDir) {
302
302
  return readLines(flowDir, 'history.jsonl');
303
303
  }
304
+
305
+ /** The two outcomes a run can be continued from (M4e amendment 4 item 4): the runner leaves `halt.json` for them. */
306
+ export const HALT_OUTCOMES = Object.freeze(['cap-halt', 'stopped']);
307
+
308
+ /**
309
+ * The ONE rule for "how did this run end": the LAST history row of the run (a run that was stopped or cap-halted and
310
+ * continued has one row per leg; history stays append-only). `null` when the run has no row yet, and also while a
311
+ * continue is in flight: the last row is a halt row, `halt.json` is gone (the continue consumed it by rename to
312
+ * `halt.<n>.consumed.json`) — an older halt row is then not the run's end. A run halted before halt records existed has
313
+ * no consumed file, so its halt row stays final.
314
+ * @param {any[]} historyRows `readHistory`'s rows @param {string} runDir @param {string} runId
315
+ * @returns {any|null}
316
+ */
317
+ export function endRow(historyRows, runDir, runId) {
318
+ let last = null;
319
+ for (const r of historyRows) if (r && r.runId === runId) last = r;
320
+ if (last === null || !HALT_OUTCOMES.includes(last.outcome)) return last;
321
+ const names = readdirInside(runDir, '.');
322
+ const continuing = !names.includes('halt.json') && names.some((n) => /^halt\.\d+\.consumed\.json$/.test(n));
323
+ return continuing ? null : last;
324
+ }
package/src/canrun.js ADDED
@@ -0,0 +1,36 @@
1
+ // M4e amendment 7 item 7: the ONE function that decides "can this flow run" — the panel's Signed flow list reads it, and the run's own
2
+ // preflight refusal says the same words. A flow the run would refuse at preflight (a signature that does not check out; a step granting a
3
+ // verb with no wired implementation) is not offered. Reads only; writes nothing. `WIRED_VERBS` stays the one list (src/primitives.js).
4
+ import { WIRED_VERBS } from './primitives.js';
5
+
6
+ /**
7
+ * The first step granting a verb that has no wired implementation, or null. (A verb absent from the catalogue entirely is caught earlier,
8
+ * at declaration validation inside `readFlow`.)
9
+ * @param {Record<string, any>} declaration `readFlow`'s declaration
10
+ * @returns {{step: {emits: string, fromLine: number}, verb: string}|null}
11
+ */
12
+ export function findUnwiredVerbStep(declaration) {
13
+ for (const step of declaration.steps) {
14
+ for (const verb of step.primitives ?? []) {
15
+ if (!WIRED_VERBS.has(verb)) return { step, verb };
16
+ }
17
+ }
18
+ return null;
19
+ }
20
+
21
+ /** The preflight refusal sentence for an unwired verb, in the words the run's own preflight uses. @param {{step: {emits: string, fromLine: number}, verb: string}} found */
22
+ export function unwiredRed(found) {
23
+ return `preflight: step "${found.step.emits}" (line ${found.step.fromLine}) grants verb "${found.verb}", which has no wired implementation`;
24
+ }
25
+
26
+ /**
27
+ * Can this flow run? `read` is `readFlow`'s result (a failed read — signature, tampering, missing files — is a refusal with its own reds).
28
+ * @param {any} read
29
+ * @returns {{ok: true} | {ok: false, red: string}}
30
+ */
31
+ export function canFlowRun(read) {
32
+ if (!read || read.ok !== true) return { ok: false, red: String(read?.reds?.[0] ?? 'the flow does not read') };
33
+ const unwired = findUnwiredVerbStep(read.declaration);
34
+ if (unwired) return { ok: false, red: unwiredRed(unwired) };
35
+ return { ok: true };
36
+ }
package/src/config.js CHANGED
@@ -3,7 +3,7 @@
3
3
  //
4
4
  // Shape (unknown top-level fields are kept, never dropped):
5
5
  // { "monthlyLimitUsd": <number > 0>, // absent = no limit (piece 3 reads it)
6
- // "prices": { "<slot>": { "inPerM": n, "cachedInPerM": n, "outPerM": n } }, // USD per 1M tokens, each optional
6
+ // "prices": { "<slot>": { "inPerM": n, "cachedInPerM": n, "outPerM": n } }, // USD per 1M tokens, each optional; a saved "cachedInPerM" is tolerated, never read (M4d amendment 2)
7
7
  // "providers": { "<slot>": { "model": "<id>", "shape": "<shape id>", "baseUrl": "" | "http(s)://…" } } } // each optional (M4d amendment 1)
8
8
  // A price is a finite number above 0; 0, a negative, NaN, Infinity or text is a ConfigError
9
9
  // naming the slot and field — on write AND on read, so a hand-edited 0 can never price a call at $0.
@@ -53,6 +53,7 @@ export function configDoorHome() {
53
53
  return { skip: home === undefined, home };
54
54
  }
55
55
 
56
+ /** Fields a config file may hold; `cachedInPerM` stays so an older file still loads, but nothing prices from it. */
56
57
  export const PRICE_FIELDS = Object.freeze(['inPerM', 'cachedInPerM', 'outPerM']);
57
58
  const SLOT_RE = /^[A-Za-z0-9_-]{1,64}$/;
58
59