fwdloop 0.16.0 → 0.18.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 (64) hide show
  1. package/README.md +2 -0
  2. package/bin/fwdloop +10 -7
  3. package/package.json +1 -1
  4. package/src/authoring.js +6 -6
  5. package/src/books.js +6 -1
  6. package/src/catalogue.json +9 -3
  7. package/src/ctx-tools.js +245 -0
  8. package/src/draft-steps.js +89 -30
  9. package/src/drafter.js +28 -4
  10. package/src/draftspend.js +109 -3
  11. package/src/liveness.js +34 -10
  12. package/src/panel/author.js +125 -37
  13. package/src/panel/authorcard.js +15 -10
  14. package/src/panel/authorflows.js +9 -3
  15. package/src/panel/authorresume.js +5 -4
  16. package/src/panel/authorstart.js +21 -9
  17. package/src/panel/authortrigger.js +384 -0
  18. package/src/panel/authorvalues.js +5 -3
  19. package/src/panel/data.js +104 -16
  20. package/src/panel/index.html +257 -44
  21. package/src/panel/scheduler.js +125 -0
  22. package/src/panel/server.js +24 -10
  23. package/src/panel/settings.js +2 -2
  24. package/src/plain-checks.js +51 -0
  25. package/src/primitives.js +34 -3
  26. package/src/provider.js +17 -8
  27. package/src/run-store.js +47 -0
  28. package/src/runner.js +2 -0
  29. package/src/runvalues.js +5 -3
  30. package/src/setup.js +24 -0
  31. package/src/signed-text.js +26 -0
  32. package/src/summary-words.js +155 -0
  33. package/src/trigger-clock.js +142 -0
  34. package/src/trigger-files.js +212 -0
  35. package/src/trigger-line.js +86 -0
  36. package/src/types.js +1 -0
  37. package/src/version.js +13 -0
  38. package/types/authoring.d.ts +1 -3
  39. package/types/ctx-tools.d.ts +18 -0
  40. package/types/draft-steps.d.ts +38 -5
  41. package/types/drafter.d.ts +3 -3
  42. package/types/draftspend.d.ts +56 -0
  43. package/types/liveness.d.ts +7 -1
  44. package/types/panel/author.d.ts +149 -146
  45. package/types/panel/authorcard.d.ts +12 -2
  46. package/types/panel/authorflows.d.ts +11 -3
  47. package/types/panel/authorstart.d.ts +7 -4
  48. package/types/panel/authortrigger.d.ts +210 -0
  49. package/types/panel/authorvalues.d.ts +3 -1
  50. package/types/panel/data.d.ts +14 -7
  51. package/types/panel/scheduler.d.ts +15 -0
  52. package/types/panel/server.d.ts +11 -3
  53. package/types/plain-checks.d.ts +22 -0
  54. package/types/primitives.d.ts +0 -6
  55. package/types/provider.d.ts +7 -1
  56. package/types/run-store.d.ts +11 -0
  57. package/types/runvalues.d.ts +1 -1
  58. package/types/setup.d.ts +27 -0
  59. package/types/summary-words.d.ts +53 -0
  60. package/types/trigger-clock.d.ts +60 -0
  61. package/types/trigger-files.d.ts +90 -0
  62. package/types/trigger-line.d.ts +44 -0
  63. package/types/types.d.ts +4 -0
  64. package/types/version.d.ts +2 -0
package/src/drafter.js CHANGED
@@ -16,6 +16,7 @@
16
16
  // prices an unpriced round at the ceiling.
17
17
 
18
18
  import { Loop, HaltError } from 'bare-agent';
19
+ import { capTooSmallText, usdText } from './draftspend.js';
19
20
  import { parseSignedText, unsignedAskTtls } from './signed-text.js';
20
21
  import { validateDeclaration, SHAPE_KEYS, checkGuardrailSums, guardrailWordsPerSection } from './declaration.js';
21
22
  import { loadCatalogue } from './catalogue.js';
@@ -227,6 +228,21 @@ function greenReadRule(sources) {
227
228
  : `${rule} This job signs no CSV input, so a guardrail that needs cited cells cannot be classed green here: class it "hitl".`];
228
229
  }
229
230
 
231
+ /** M7 piece 6 (signed scope item 1): a granted verb ships WITH the line that says when to reach for it, or the
232
+ * model keeps using the familiar one. Only these three get a line; each only when it is on the menu. No number
233
+ * (the tool itself tells a step its size limit). Borrowed in spirit from bareloop src/tools.js@dc06660 strategyFor. */
234
+ const WHEN_TO_USE = Object.freeze({
235
+ compress: '- Use compress when a step only needs what a function IS (its signature and doc) rather than how it works: it returns the head without the body, far cheaper than reading the file. Code only.',
236
+ stash: '- Use stash to park a bulky intermediate result under an id instead of carrying it from step to step; it lasts this run only and each parked item has a size limit.',
237
+ peek: '- Use peek to look at the start and end of something parked with stash without loading all of it.',
238
+ });
239
+
240
+ /** @param {Array<{verb: string}>} menu */
241
+ function whenToUse(menu) {
242
+ const on = new Set(menu.map((e) => e.verb));
243
+ return Object.entries(WHEN_TO_USE).filter(([verb]) => on.has(verb)).map(([, line]) => line);
244
+ }
245
+
230
246
  export function buildSystemPrompt({ menu, lines, arbiter, factsInfo }) {
231
247
  const askLines = arbiter.asks.map((a) => a.line);
232
248
  const sendLines = arbiter.sends.map((s) => s.line);
@@ -236,6 +252,7 @@ export function buildSystemPrompt({ menu, lines, arbiter, factsInfo }) {
236
252
  'Primitive menu (a grant list; a verb not listed does not exist):',
237
253
  ...menu.map((e) => `- ${e.verb}: ${e.desc} (class: ${e.class})`),
238
254
  '',
255
+ ...(whenToUse(menu).length ? ['When to use them:', ...whenToUse(menu), ''] : []),
239
256
  'Rules:',
240
257
  '- Steps share one artifact space. Each step: primitives (verbs it needs, [] if none), reads (artifact ids emitted by an EARLIER step, or the role of a CSV input listed under Inputs), emits (ONE new unique artifact id), fromLine (the ONE job line it serves), close. The machine fills each step\'s goal with that signed line, verbatim — you never write a goal.',
241
258
  '- Every numbered job line must be served by a step (fromLine = that line) or listed in "refused" with a reason.',
@@ -278,7 +295,7 @@ function isPlainObject(v) { return !!v && typeof v === 'object' && !Array.isArra
278
295
  /**
279
296
  * Draft one declaration. `provider`/`rates`/`modelId` may be injected (tests,
280
297
  * the batch); otherwise a live provider is built from `slot` (throws on a bad
281
- * key — the batch preflights first). `budgetUsd` is this draft's hard cap.
298
+ * key — the batch preflights first). The draft's hard cap is the cap signed in the prose (M4d am13); `priorSpend(ceilingUsd)` (am16) is what this job's earlier drafting already spent, so every round must fit what is LEFT of the cap.
282
299
  * `makeProviderFn` is a test seam: the live-provider factory (default `makeProvider`).
283
300
  * `onBook` (M4e piece 2a, scope 13): called right BEFORE each provider call (`inFlight: true`, the call counted in
284
301
  * `calls`) and right AFTER it (`inFlight: false`), with what is known so far, so the caller can book spend per call
@@ -291,7 +308,7 @@ function isPlainObject(v) { return !!v && typeof v === 'object' && !Array.isArra
291
308
  */
292
309
  export async function draft({
293
310
  proseText, slot, model, provider: injected, rates: injectedRates, modelId: injectedModelId, env,
294
- budgetUsd = 0.10, skills = DRAFT_SKILLS, makeProviderFn = makeProvider, onBook, offerQuestions = true, draftThinking = /** @type {'on'|'off'} */ ('off'),
311
+ priorSpend = /** @type {((ceilingUsd: number) => number)|null} */ (null), skills = DRAFT_SKILLS, makeProviderFn = makeProvider, onBook, offerQuestions = true, draftThinking = /** @type {'on'|'off'} */ ('off'),
295
312
  }) {
296
313
  // What was asked of thinking and the WORST status bareagent reported across the rounds (the page says it loudly unless 'applied'). Read from the round log, the one record.
297
314
  const thinkingOf = () => {
@@ -340,9 +357,16 @@ export async function draft({
340
357
  // The hold: the picked model's own Settings prices (or the rates a test injected) times the token bounds - never a table.
341
358
  if (!rates) return fail(['price: this round has no price to hold - tick a model in Settings > Providers with both prices first']);
342
359
  const roundCeiling = ceilingCostUsd(rates);
343
- // One round at its ceiling must fit the budget, or refuse at $0 before any provider call.
360
+ // M4d am13: the draft is capped by the card's Cap $ (the cap signed in the prose), the same number the run is capped at.
361
+ // One round at its ceiling must fit that cap, or refuse at $0 before any provider call.
362
+ // M4d am16 item 2: against the remaining money, not the whole cap. Spend by earlier drafts of this job (a revise, the redraft after answers) is taken off first.
363
+ const priorUsd = typeof priorSpend === 'function' ? priorSpend(roundCeiling) : 0;
364
+ const budgetUsd = arbiter.capUsd - priorUsd;
344
365
  if (roundCeiling > budgetUsd) {
345
- return fail([`budget: $${budgetUsd} is below one round's worst-case cost — the minimum budget is $${roundCeiling.toFixed(4)}`]);
366
+ const capText = usdText(arbiter.capUsd);
367
+ return fail([priorUsd > 0
368
+ ? `Cap ${capText} less ${usdText(priorUsd)} already spent on drafting leaves ${usdText(Math.max(0, budgetUsd))}, below one drafting round's worst case for ${modelId}, $${roundCeiling.toFixed(4)}. Raise Cap $ or pick another model.`
369
+ : capTooSmallText('drafting', arbiter.capUsd, roundCeiling, modelId)]);
346
370
  }
347
371
 
348
372
  const meterings = [];
package/src/draftspend.js CHANGED
@@ -17,10 +17,11 @@
17
17
  // { kind:'draft-live', provider, model, price, tokens, costUsd (metered floor, null when unpriced), rounds, calls,
18
18
  // spendComplete (false while a call is in flight or any call is unmetered/unpriced), inFlight, at, startedAt, updatedAt }
19
19
  import { renameSync, writeFileSync } from 'node:fs';
20
- import { join } from 'node:path';
20
+ import { basename, dirname, join, resolve } from 'node:path';
21
21
 
22
- import { readFileInside } from './flow.js';
23
- import { readSpendRows } from './provider.js';
22
+ import { readdirInside, readFileInside } from './flow.js';
23
+ import { readSpendRows, rowCeilingUsd, spendRowCost, unmeteredCalls } from './provider.js';
24
+ import { parseSignedText } from './signed-text.js';
24
25
 
25
26
  export const DRAFT_SPEND_FILE = 'draft-spend.json';
26
27
 
@@ -68,3 +69,108 @@ export function readDirSpendRows(dir) {
68
69
  const live = readDraftSpend(dir);
69
70
  return live ? [live] : [];
70
71
  }
72
+
73
+ const PLAN_DIR_RE = /^draft(?:-\d+)?$/;
74
+ /** M4d am21 item 2: the one sentence for a Start over (or revise, or sign) whose chain names an earlier draft that is gone. */
75
+ export const EARLIER_MISSING_SAY = "An earlier draft of this job is missing, so its spend can't be counted.";
76
+
77
+ /** The file a Start over's session folder carries to name the session it started over from (written once by src/panel/author.js). */
78
+ export const STARTED_OVER_FILE = 'started-over-from.json';
79
+ const SESSION_ID_RE = /^d-[0-9a-z]{10}-[0-9a-f]{4}$/;
80
+
81
+ /**
82
+ * M4d amendment 16 item 1: what ALL of a job's drafting spent — the one writer of that total. A panel draft's session folder holds one plan
83
+ * folder per draft (`draft/`, `draft-<n>/` for each revise and the redraft after answers); each is read by `readDirSpendRows` and priced by
84
+ * `spendRowCost`, the one cost rule. A round whose cost is not known counts at its WORST CASE (item 5): its own booked price's ceiling, else
85
+ * `ceilingUsd` (Settings prices x the fixed token limits), never $0; `notPriced` counts those rounds and `complete` is false.
86
+ * @param {string} sessionDir the panel's draft folder
87
+ * @param {{ ceilingUsd?: number, exclude?: string }} [o] `exclude` = a plan folder name to leave out (the one being written now)
88
+ * @returns {{ usd: number, notPriced: number, complete: boolean, missingEarlier: boolean }}
89
+ */
90
+ export function draftingSpent(sessionDir, { ceilingUsd = 0, exclude } = {}, seen = new Set()) {
91
+ seen.add(resolve(sessionDir));
92
+ let usd = 0;
93
+ let notPriced = 0;
94
+ let missingEarlier = false;
95
+ for (const name of readdirInside(sessionDir, '.')) {
96
+ if (!PLAN_DIR_RE.test(name) || name === exclude) continue;
97
+ for (const row of readDirSpendRows(join(sessionDir, name))) {
98
+ if (row.spendComplete === false) {
99
+ const n = unmeteredCalls(row);
100
+ const per = rowCeilingUsd(row) > 0 ? rowCeilingUsd(row) : ceilingUsd;
101
+ usd += (row.costUsd ?? 0) + n * per;
102
+ notPriced += n;
103
+ } else if (row.costUsd === null || row.costUsd === undefined) {
104
+ usd += rowCeilingUsd(row) > 0 ? rowCeilingUsd(row) : ceilingUsd;
105
+ notPriced += 1;
106
+ } else usd += spendRowCost(row).usd;
107
+ }
108
+ }
109
+ // M4d am19 item 3: a Start over opens a new session folder that names the one it started over from (`started-over-from.json`, written once by the panel):
110
+ // what the earlier session spent is still this job's drafting, so the chain is followed (a name that points back at a folder already counted is not).
111
+ const so = readFileInside(sessionDir, STARTED_OVER_FILE);
112
+ if (so.ok) {
113
+ let from = null;
114
+ try { from = JSON.parse(so.text)?.startedOverFrom; } catch { /* unreadable: no chain */ }
115
+ if (typeof from === 'string' && SESSION_ID_RE.test(from) && !seen.has(resolve(dirname(sessionDir), from))) {
116
+ const prev = join(dirname(sessionDir), from);
117
+ // M4d am21 item 2: a link naming a folder that is gone is NOT $0: what it spent cannot be counted (`missingEarlier`, never a clean figure)
118
+ if (!readFileInside(prev, 'card.json').ok) missingEarlier = true;
119
+ else {
120
+ const before = draftingSpent(prev, { ceilingUsd }, seen);
121
+ usd += before.usd;
122
+ notPriced += before.notPriced;
123
+ missingEarlier = before.missingEarlier;
124
+ }
125
+ } else if (typeof from === 'string' && !SESSION_ID_RE.test(from)) missingEarlier = true;
126
+ }
127
+ return { usd, notPriced, complete: notPriced === 0 && !missingEarlier, missingEarlier };
128
+ }
129
+
130
+ /** Money to 4 places, trailing zeros kept to 2 (`0.05`, `0.0016`). @param {number} n */
131
+ export const usdText = (n) => `$${String(Math.round(n * 1e4) / 1e4).replace(/^(\d+)$/, '$1.00').replace(/^(\d+\.\d)$/, '$10')}`;
132
+
133
+ /**
134
+ * M4d amendment 16 items 1, 3, 5: the split of the card's Cap $ at Sign & run. `leftUsd` is what the first run may spend, rounded DOWN to 4 places (never
135
+ * more than is left). `line` is the sentence the page shows.
136
+ * @param {number} capUsd @param {{ usd: number, notPriced: number }} spent
137
+ */
138
+ export function potSplit(capUsd, spent) {
139
+ const leftUsd = Math.max(0, Math.floor((capUsd - spent.usd) * 1e4 + 1e-6) / 1e4);
140
+ const drafting = spent.notPriced > 0
141
+ ? `drafting spent at most ${usdText(spent.usd)} (${spent.notPriced} round${spent.notPriced === 1 ? '' : 's'} not priced)`
142
+ : `drafting spent ${usdText(spent.usd)}`;
143
+ return { capUsd, spentUsd: spent.usd, notPriced: spent.notPriced, leftUsd, line: `Cap ${usdText(capUsd)} · ${drafting} · this run up to ${usdText(leftUsd)}` };
144
+ }
145
+
146
+ /**
147
+ * The drafter's `priorSpend` for the plan folder `dir`: when it sits in a panel session folder (a `card.json` beside it), what the session's earlier plans spent;
148
+ * null for a plain CLI draft (no session, nothing earlier). The folder being written is left out.
149
+ * @param {string} dir @returns {((ceilingUsd: number) => number)|null}
150
+ */
151
+ export function sessionPriorSpend(dir) {
152
+ const sessionDir = dirname(resolve(dir));
153
+ if (!readFileInside(sessionDir, 'card.json').ok) return null;
154
+ return (ceilingUsd) => draftingSpent(sessionDir, { ceilingUsd, exclude: basename(dir) }).usd;
155
+ }
156
+
157
+ /**
158
+ * M4d amendment 19 item 1: what a draft reserves against the monthly limit: what is LEFT of the cap in its prose (cap minus what this job's drafting already
159
+ * spent, `sessionPriorSpend`), not one round. A prose that does not parse falls back to one round: the draft itself refuses it at $0.
160
+ * @param {string} proseText @param {string} outDir the plan folder the draft will write @param {number} ceilingUsd one round at its worst case
161
+ */
162
+ export function draftHoldUsd(proseText, outDir, ceilingUsd) {
163
+ const parsed = parseSignedText(proseText);
164
+ if (!parsed.ok) return ceilingUsd;
165
+ const prior = sessionPriorSpend(outDir);
166
+ return Math.max(0, parsed.arbiter.capUsd - (prior === null ? 0 : prior(ceilingUsd)));
167
+ }
168
+
169
+ /**
170
+ * M4d amendment 19 item 5 / amendment 20: the ONE sentence for a cap that cannot pay for one round. `kind` is "drafting" (the Chat card, the drafter) or "run"
171
+ * (Run a signed flow, Resume); nothing else differs. `modelId` is the model the minimum was computed for, `minUsd` its worst-case round.
172
+ * @param {'drafting'|'run'} kind @param {number} capUsd @param {number} minUsd @param {string} modelId
173
+ */
174
+ export function capTooSmallText(kind, capUsd, minUsd, modelId) {
175
+ return `Cap ${usdText(capUsd)} is below one ${kind} round's worst case for ${modelId}, $${minUsd.toFixed(4)}. Raise Cap $ or pick another model.`;
176
+ }
package/src/liveness.js CHANGED
@@ -23,14 +23,28 @@ const NAME = 'fwdloop';
23
23
  * @returns {string|null}
24
24
  */
25
25
  export function procStartOf(pid) {
26
- try {
27
- const stat = readFileSync(`/proc/${pid}/stat`, 'utf8');
28
- const after = stat.slice(stat.lastIndexOf(')') + 2).split(' ');
29
- const v = after[19]; // field 3 is after[0], so field 22 is after[19]
30
- return v !== undefined && /^\d+$/.test(v) ? v : null;
31
- } catch { return null; }
26
+ try { return startFromStat(readFileSync(`/proc/${pid}/stat`, 'utf8')); } catch { return null; }
32
27
  }
33
28
 
29
+ /** Field 22 of a /proc/<pid>/stat text, or null. @param {string} stat */
30
+ function startFromStat(stat) {
31
+ const after = stat.slice(stat.lastIndexOf(')') + 2).split(' ');
32
+ const v = after[19]; // field 3 is after[0], so field 22 is after[19]
33
+ return v !== undefined && /^\d+$/.test(v) ? v : null;
34
+ }
35
+
36
+ /** Field 3 (state) of a /proc/<pid>/stat text. @param {string} stat */
37
+ const stateFromStat = (stat) => stat.slice(stat.lastIndexOf(')') + 2, stat.lastIndexOf(')') + 3);
38
+
39
+ /** Field 23 (vsize, bytes) of a /proc/<pid>/stat text: 0 for a task that has already released its memory (dying), > 0 for one that is alive (even in its exec window). @param {string} stat */
40
+ const vsizeFromStat = (stat) => Number(stat.slice(stat.lastIndexOf(')') + 2).split(' ')[20]);
41
+
42
+ /** The two /proc files this module reads, as one seam so a test can hand it a snapshot. */
43
+ const REAL_PROC = {
44
+ cmdline: (/** @type {number} */ pid) => readFileSync(`/proc/${pid}/cmdline`, 'utf8'),
45
+ stat: (/** @type {number} */ pid) => readFileSync(`/proc/${pid}/stat`, 'utf8'),
46
+ };
47
+
34
48
  /**
35
49
  * Is `pid` a live fwdloop process — and, when `procStart` is given, the SAME
36
50
  * process that recorded it?
@@ -39,16 +53,25 @@ export function procStartOf(pid) {
39
53
  * null - cannot tell (no /proc, or not ours to read): caller falls back to the 10-minute rule
40
54
  * @param {number} pid
41
55
  * @param {string|null} [procStart] the starttime recorded by the process itself; absent/null = not compared
56
+ * @param {typeof REAL_PROC} [proc] where /proc is read from (tests pass a snapshot)
42
57
  * @returns {boolean|null}
43
58
  */
44
- export function isFwdloopAlive(pid, procStart) {
59
+ export function isFwdloopAlive(pid, procStart, proc = REAL_PROC) {
45
60
  if (!Number.isInteger(pid) || pid <= 0) return false;
46
61
  try { process.kill(pid, 0); } catch (e) { if (e?.code !== 'EPERM') return false; /* EPERM: exists, not ours */ }
47
62
  let cmdline;
48
- try { cmdline = readFileSync(`/proc/${pid}/cmdline`, 'utf8'); } catch (e) {
63
+ try { cmdline = proc.cmdline(pid); } catch (e) {
49
64
  return e?.code === 'ENOENT' && process.platform === 'linux' && hasProc() ? false : null; // died between the two calls vs no /proc
50
65
  }
51
- if (cmdline === '') return false; // zombie (or kernel thread): not a runner
66
+ if (cmdline === '') {
67
+ // A zombie reads empty, but so does a LIVE child for a few ms after its exec (seen under load: state R, starttime equal, cmdline
68
+ // empty), which used to read as dead and showed a fresh draft as "stopped". Only a state of Z/X is dead; otherwise we cannot tell yet.
69
+ // A task that is exiting also reads empty (and R/D) for an instant, but it has already let go of its memory: vsize 0. That is dead, not "cannot tell".
70
+ let state = null;
71
+ let vsize = 0;
72
+ try { const st = proc.stat(pid); state = stateFromStat(st); vsize = vsizeFromStat(st); } catch { /* gone between the reads */ }
73
+ return state === 'Z' || state === 'X' || state === null || !(vsize > 0) ? false : null;
74
+ }
52
75
  const [argv0, ...rest] = cmdline.split('\0');
53
76
  let isFwdloop;
54
77
  if (basename(argv0) === NAME) isFwdloop = true; // direct exec of a renamed/compiled bin
@@ -60,7 +83,8 @@ export function isFwdloopAlive(pid, procStart) {
60
83
  }
61
84
  if (!isFwdloop) return false;
62
85
  if (typeof procStart === 'string') {
63
- const live = procStartOf(pid);
86
+ let live = null;
87
+ try { live = startFromStat(proc.stat(pid)); } catch { /* unreadable */ }
64
88
  if (live === null) return null; // cannot compare: never a silent true
65
89
  if (live !== procStart) return false; // a different fwdloop process reusing the pid
66
90
  }
@@ -45,7 +45,7 @@ import {
45
45
  checkMonthlyRoom, ConfigError, monthlyNote, monthlyRefusalText,
46
46
  } from '../monthly.js';
47
47
  import {
48
- appendAnswersToJob, capFloorText, capFloorUsd, cardFields, checkCard, checkInputRows, parseInputLines, parseJobBox,
48
+ appendAnswersToJob, capFloorFor, capFloorOf, capFloorUsd, cardFields, checkCard, checkInputRows, parseInputLines, parseJobBox,
49
49
  } from './authorcard.js';
50
50
  import { checkedLines, notCheckedBlock } from '../checked.js';
51
51
  import {
@@ -53,9 +53,14 @@ import {
53
53
  } from '../provider.js';
54
54
  import { thinkingSupport as bareagentThinkingSupport, THINKING_FIXED_SAY, THINKING_UNVERIFIED_SAY } from '../thinking.js';
55
55
  import { parseSignedText } from '../signed-text.js';
56
- import { draftStepList } from '../draft-steps.js';
56
+ import { draftStepList, reviseStepList } from '../draft-steps.js';
57
+ import {
58
+ capTooSmallText, draftingSpent, EARLIER_MISSING_SAY, potSplit, STARTED_OVER_FILE, usdText,
59
+ } from '../draftspend.js';
60
+ import { flowValues, valuesHash } from '../runvalues.js';
57
61
  import { leastResumeCapUsd } from './authorvalues.js';
58
62
  import { createFlowsDoor } from './authorflows.js';
63
+ import { createTriggerDoor } from './authortrigger.js';
59
64
  import { createResumeDoor } from './authorresume.js';
60
65
  import { createStarter } from './authorstart.js';
61
66
  import {
@@ -66,7 +71,6 @@ const HERE = dirname(fileURLToPath(import.meta.url));
66
71
  const BIN = join(HERE, '..', '..', 'bin', 'fwdloop');
67
72
 
68
73
  /** A draft id: `d-` + the start time in base 36 (so ids sort oldest to newest) + 4 random hex. */
69
- const STARTED_OVER_FILE = 'started-over-from.json';
70
74
  const ID_RE = /^d-[0-9a-z]{10}-[0-9a-f]{4}$/;
71
75
  const newId = () => `d-${Date.now().toString(36).padStart(10, '0')}-${randomBytes(2).toString('hex')}`;
72
76
  /** The phases that end a card's life: Abandon or a sign. Everything else is still on the card (to read, to sign, to retry). */
@@ -90,13 +94,13 @@ const KILL_HARD_WAIT_MS = 2000;
90
94
  const sleep = (ms) => new Promise((r) => { setTimeout(r, ms); });
91
95
 
92
96
  /**
93
- * @param {{ root: string, home?: string, skipMonthly?: boolean, loadEnv: () => { ok: boolean, env: Record<string, string|undefined>, refusal: string|null, keyNames?: string[] }, bin?: string, childRunning?: (dir: string) => boolean, thinkingSupport?: typeof bareagentThinkingSupport }} opts
97
+ * @param {{ root: string, home?: string, skipMonthly?: boolean, loadEnv: () => { ok: boolean, env: Record<string, string|undefined>, refusal: string|null, keyNames?: string[] }, bin?: string, childRunning?: (dir: string) => boolean, thinkingSupport?: typeof bareagentThinkingSupport, now?: () => number }} opts
94
98
  * `loadEnv` is the keys-file door (`keysForDoor`): called before EVERY spawn and every reply that quotes a log, so editing
95
99
  * the file needs no restart. Its `env` is BOTH the child's spawn env AND the scrub list (POC (a), M4d wiring rule).
96
100
  */
97
101
  export function createAuthor(opts) {
98
102
  const {
99
- root, loadEnv, home, skipMonthly = false, bin = BIN, childRunning = childRunningNow, thinkingSupport = bareagentThinkingSupport,
103
+ root, loadEnv, home, skipMonthly = false, bin = BIN, childRunning = childRunningNow, thinkingSupport = bareagentThinkingSupport, now = Date.now,
100
104
  } = opts;
101
105
  // the ONE run-start path (sign and run both end in `starter.start`) and the Run-a-signed-flow door built on it
102
106
  const starter = createStarter({ root, bin });
@@ -104,6 +108,11 @@ export function createAuthor(opts) {
104
108
  root, home, skipMonthly, loadEnv, starter, monthlyClaim: (usd) => monthlyClaim(usd), modelRefusal: (card, loaded) => modelRefusal(card, loaded),
105
109
  });
106
110
 
111
+ // M9: the trigger door (set the signed trigger, read it) and the one fire path the panel's scheduler calls
112
+ const triggerDoor = createTriggerDoor({
113
+ root, flowsDoor, starter, loadEnv, monthlyClaim: (usd) => monthlyClaim(usd), modelRefusal: (card, loaded) => modelRefusal(card, loaded), now,
114
+ });
115
+
107
116
  /** The ONE monthly check, defined below (a function declaration, so the doors above may take it now). */
108
117
  const resumeDoor = createResumeDoor({
109
118
  root, home, loadEnv, monthlyClaim: (usd) => monthlyClaim(usd), starter,
@@ -161,14 +170,36 @@ export function createAuthor(opts) {
161
170
  /**
162
171
  * M4d am10: the Chat list of what this plan's draft really did, READ from its log.json and declaration (never from the readout, which is signed text),
163
172
  * built by the ONE function `draftStepList`; every string scrubbed. `null` when the draft left no log (the page then lists what it always did).
164
- * @param {string} dir @param {string} rel @param {string[]} keys
173
+ * `questionOpen`: the plan asked a question and the draft has not ended (am15 item 3), so its plan-checks line is not red.
174
+ * @param {string} dir @param {string} rel @param {string[]} keys @param {boolean} [questionOpen]
165
175
  */
166
- function stepListOf(dir, rel, keys) {
176
+ function stepListOf(dir, rel, keys, questionOpen = false) {
167
177
  const declaration = readJson(dir, `${rel}/declaration.json`) ?? readJson(dir, `${rel}/declaration.rejected.json`);
168
- const list = draftStepList({ log: readJson(dir, `${rel}/log.json`), declaration });
178
+ const list = draftStepList({ log: readJson(dir, `${rel}/log.json`), declaration, questionOpen });
169
179
  if (list === null) return null;
170
180
  const sc = (x) => scrub(String(x), keys);
171
- return list.map((st) => ({ ...st, label: sc(st.label), details: st.details.map(sc), ...(st.reds ? { reds: st.reds.map(sc) } : {}) }));
181
+ return list.map((st) => ({ ...st, label: sc(st.label), details: st.details.map(sc) }));
182
+ }
183
+
184
+ /** M4d am19: what ALL of this job's drafting already spent (the session folder and any Start-over chain behind it), unpriced rounds at their worst case. @param {string} dir @param {any} card */
185
+ function draftedSoFar(dir, card) {
186
+ return draftingSpent(dir, { ceilingUsd: capFloorFor(true, home, card) }).usd;
187
+ }
188
+
189
+ /**
190
+ * M4d am16: the split of the card's Cap $ at Sign & run, from ALL of this job's drafting (the one writer of that total, `draftingSpent`). Unpriced rounds count at their
191
+ * worst case (the picked model's Settings ceiling). `refusal` = what is left cannot pay one run round at its worst case: refused at $0.
192
+ * @param {string} dir the draft folder @param {any} card
193
+ */
194
+ function potOf(dir, card) {
195
+ const ceilingUsd = capFloorFor(true, home, card);
196
+ const spentRead = draftingSpent(dir, { ceilingUsd });
197
+ const split = potSplit(Number(card.capUsd), spentRead);
198
+ const floorUsd = capFloorUsd(typeof card.job === 'string' ? card.job : '', home, card);
199
+ const refusal = spentRead.missingEarlier ? EARLIER_MISSING_SAY : split.leftUsd < floorUsd
200
+ ? `${split.line}: not enough for one run round at its worst case, ${usdText(floorUsd)}. Raise Cap $.`
201
+ : null;
202
+ return { split, refusal };
172
203
  }
173
204
 
174
205
  /**
@@ -210,17 +241,26 @@ export function createAuthor(opts) {
210
241
  const revisesLeft = Math.max(0, MAX_REVISES - used);
211
242
  const newest = ns.length > 0 ? ns[ns.length - 1] : 0;
212
243
  const card = newest > 0 ? (readJson(dir, `card-${newest}.json`) ?? base.card) : base.card;
244
+ let reviseNo = 0;
213
245
  const revises = ns.map((n) => {
214
246
  const kind = redrafts.has(n) ? 'answers' : 'revise';
247
+ if (kind === 'revise') reviseNo += 1;
248
+ // M4d am15 (every line of the list): this plan's own line, from its own log, built by `reviseStepList`; the try history is in the Audit Draft group
249
+ const name = kind === 'answers' ? 'drafted again with your answers' : `revise ${reviseNo}`;
215
250
  const running = n === newest && childRunning(dir); // C9: running first, then the result
251
+ // the result BEFORE the log: the child writes log.json first and the result (spec.hash, or the red log itself) after, so a result we see has its log already on disk
216
252
  const res = resultOf(dir, `draft-${n}`, keys);
217
- if (res && res.phase === 'green') return { n, kind, phase: 'green', hash: res.hash };
218
- if (res) return { n, kind, phase: 'red', reds: res.reds, say: kind === 'answers' ? REDRAFT_RED_SAY : REVISE_RED_SAY };
219
- if (running) return { n, kind, phase: 'running' };
220
- return { n, kind, phase: 'stopped', say: logTail(dir, `${kind === 'answers' ? 'redraft' : 'revise'}-${n}.log`, keys) || STOPPED_SAY };
253
+ const lines = reviseStepList({ log: readJson(dir, `draft-${n}/log.json`), name });
254
+ const scrubbed = lines === null ? null : lines.map((l) => ({ ...l, label: scrub(l.label, keys) }));
255
+ if (res && res.phase === 'green') return { n, kind, phase: 'green', hash: res.hash, name, lines: scrubbed };
256
+ if (res) return { n, kind, phase: 'red', reds: res.reds, say: kind === 'answers' ? REDRAFT_RED_SAY : REVISE_RED_SAY, name, lines: scrubbed };
257
+ if (running) return { n, kind, phase: 'running', name };
258
+ return { n, kind, name, phase: 'stopped', say: logTail(dir, `${kind === 'answers' ? 'redraft' : 'revise'}-${n}.log`, keys) || STOPPED_SAY };
221
259
  });
222
260
  const cur = /** @type {{ phase: string, kind: string, say?: string }} */ (newest > 0 ? revises[revises.length - 1] : { phase: first.phase, kind: 'first' });
223
- const shared = { ...base, card, revises, revisesLeft, stepList: first.stepList ?? null };
261
+ // a first plan that asked questions did not end red, it ended by asking (open or answered): its plan-checks line is never the red one (am15 item 3)
262
+ const asked = readQuestions(join(dir, 'draft')).questions.length > 0;
263
+ const shared = { ...base, card, revises, revisesLeft, stepList: asked ? stepListOf(dir, 'draft', keys, true) : (first.stepList ?? null) };
224
264
  const rel = newest > 0 ? `draft-${newest}` : 'draft';
225
265
  if (cur.phase === 'running') return { ...shared, phase: cur.kind === 'answers' ? 'redrafting' : 'revising' };
226
266
  if (cur.phase === 'stopped') return { ...shared, phase: 'stopped', say: cur.say };
@@ -230,7 +270,7 @@ export function createAuthor(opts) {
230
270
  if (q.open.length > 0) {
231
271
  const lineText = (line) => parseJobBox(typeof card?.job === 'string' ? card.job : '').steps[line - 1]?.text ?? null;
232
272
  const questions = q.questions.map((x) => ({ k: x.k, line: x.line, lineText: lineText(x.line), question: scrub(x.question, keys), answered: x.answer !== null }));
233
- return { ...shared, phase: 'questions-open', plan: rel, questions, openK: q.open[0].k, total: q.questions.length };
273
+ return { ...shared, stepList: stepListOf(dir, rel, keys, true), phase: 'questions-open', plan: rel, questions, openK: q.open[0].k, total: q.questions.length };
234
274
  }
235
275
  if (q.questions.length > 0) return { ...shared, phase: 'stopped', say: ANSWERS_NOT_DRAFTED_SAY };
236
276
  if (res.phase === 'green') {
@@ -325,26 +365,38 @@ export function createAuthor(opts) {
325
365
  /**
326
366
  * The $0 checks both a first draft and a revise run on the card as submitted: the card's own checks (a key value, the flow name,
327
367
  * every field), then the monthly room for its cap. `{ ok: true, card, prose }` or `{ ok: false, reply }`. Writes nothing.
328
- * @param {any} body @param {{ ok: boolean, env: Record<string, string|undefined>, keyNames?: string[] }} loaded
368
+ * M4d am19 items 2-3: `priorUsd` = what this job's drafting already spent; the month is checked for what is LEFT of the cap, not the whole cap again.
369
+ * @param {any} body @param {{ ok: boolean, env: Record<string, string|undefined>, keyNames?: string[] }} loaded @param {number} [priorUsd]
329
370
  * @returns {{ ok: true, card: any, prose: string }|{ ok: false, reply: { status: number, body: any } }}
330
371
  */
331
- function vetCard(body, loaded) {
372
+ function vetCard(body, loaded, priorUsd = 0) {
332
373
  const card = cardFields(body);
333
374
  const checked = checkCard(card, { root: realpathSync(root), keys: providerKeys(loaded), home });
334
375
  const modelSays = modelRefusal(card, loaded);
335
376
  if (!checked.ok || modelSays.length > 0) return { ok: false, reply: { status: 400, body: { ok: false, refused: 'card', refusals: [...(checked.ok ? [] : checked.refusals), ...modelSays] } } };
336
377
  // amendment 4 item 1: a cap that does not fit this month refuses here too, at $0, with the one refusal text (the page's red note is only a courtesy)
337
- const claim = monthlyClaim(Number(card.capUsd));
378
+ const claim = monthlyClaim(Math.max(0, Number(card.capUsd) - priorUsd));
338
379
  if (claim && 'problem' in claim) return { ok: false, reply: { status: 409, body: { ok: false, refused: 'monthly', say: `${claim.problem} — refusing rather than guess the monthly limit. Nothing spent.` } } };
339
380
  if (claim && !claim.ok) return { ok: false, reply: { status: 400, body: { ok: false, refused: 'card', refusals: [{ field: 'capUsd', say: monthlyRefusalText(claim.room) }] } } };
340
381
  return { ok: true, card, prose: checked.prose };
341
382
  }
342
383
 
343
384
  return {
344
- flows: flowsDoor.flows,
345
- runAgain: flowsDoor.runAgain,
385
+ /** `GET /api/author/flows`, each listed job carrying its trigger card (M9 piece 5): the typed trigger, its words, and why it cannot be set (no good run yet). */
386
+ flows() {
387
+ const r = flowsDoor.flows();
388
+ if (r.status !== 200 || !Array.isArray(r.body.flows)) return r;
389
+ return { ...r, body: { ...r.body, flows: r.body.flows.map((f) => ({ ...f, trigger: triggerDoor.card(f.flow) })) } };
390
+ },
391
+ /** `GET /api/author/run-again`, its flow entry carrying the trigger card like the list's entries do. @param {string|null} flow @param {string|null} runId */
392
+ runAgain(flow, runId) {
393
+ const r = /** @type {any} */ (flowsDoor.runAgain(flow, runId));
394
+ if (r.status !== 200 || !r.body.flow) return r;
395
+ return { ...r, body: { ...r.body, flow: { ...r.body.flow, trigger: triggerDoor.card(r.body.flow.flow) } } };
396
+ },
346
397
  run: flowsDoor.run,
347
398
  runPrepare: flowsDoor.runPrepare,
399
+ trigger: triggerDoor,
348
400
  resumePrepare: resumeDoor.prepare,
349
401
  resumeForm: resumeDoor.form,
350
402
  resume: resumeDoor.resume,
@@ -352,24 +404,31 @@ export function createAuthor(opts) {
352
404
  /**
353
405
  * `GET /api/author/monthly-check?cap=<usd>`: the note under Cap, one read-only check. `{ text, red }` is what to show (red =
354
406
  * the cap does not fit this month); `floorUsd` is the smallest cap that funds one round of a model step, for the page's
355
- * `needs at least $X per run` line. A cap that is not a number above 0 gets no note. Never spends, never writes.
356
- * @param {unknown} cap @param {string|null} [spent] what a resumed run has already spent (amendment 4 item 4) @param {{ provider?: string, model?: string, flow?: string }|null} [pick] the card's picked model, or (a Resume) the flow whose recorded model it is: its own prices are the floor (M4d am6)
407
+ * floor line (am20: `Cap $X is below one drafting|run round's worst case for <model>, $Y. …`, `kind` picks the word). A cap that is not a number above 0 gets no note. Never spends, never writes.
408
+ * @param {unknown} cap @param {string|null} [spent] what a resumed run has already spent (amendment 4 item 4) @param {{ provider?: string, model?: string, flow?: string }|null} [pick] the card's picked model, or (a Run / Resume) the flow whose recorded model it @param {string} [kind] 'run' for Run a signed flow and Resume, else the Chat card's 'drafting' is: its own prices are the floor (M4d am6)
357
409
  */
358
- monthlyCheck(cap, spent = null, pick = null) {
410
+ monthlyCheck(cap, spent = null, pick = null, kind = 'drafting', draftId = /** @type {string|null} */ (null)) {
359
411
  const n = Number(cap);
360
- // a Resume names its flow: the model recorded beside the signed job is the one whose prices are the floor
412
+ // a Resume / Run names its flow: the model recorded beside the signed job is the one whose prices are the floor
361
413
  const recorded = pick?.flow !== undefined && checkFlowName(pick.flow).ok ? readModelRecord(join(root, pick.flow)) : null;
362
- const floorUsd = capFloorUsd('x', home, recorded ?? pick);
363
- if (typeof cap !== 'string' || cap.trim() === '' || !Number.isFinite(n) || n <= 0) return { status: 200, body: { ok: true, text: '', red: false, floorUsd, floorText: capFloorText(floorUsd) } };
414
+ const floor = capFloorOf(true, home, recorded ?? pick);
415
+ const floorUsd = floor.usd;
416
+ // M4d am20: the sentence names the typed cap, so it is written here per cap (one writer, `capTooSmallText`); '' when the cap is not under the floor
417
+ const floorText = Number.isFinite(n) && n > 0 && n < floorUsd ? capTooSmallText(kind === 'run' ? 'run' : 'drafting', n, floorUsd, String(floor.model)) : '';
418
+ if (typeof cap !== 'string' || cap.trim() === '' || !Number.isFinite(n) || n <= 0) return { status: 200, body: { ok: true, text: '', red: false, floorUsd, floorText } };
364
419
  // a Resume (amendment 4 item 1): only what the run still has to spend is held, so the note asks for `cap - spent`; a cap not above
365
420
  // what is spent says so in the door's own words (red)
366
421
  const spentUsd = typeof spent === 'string' && spent.trim() !== '' && Number.isFinite(Number(spent)) && Number(spent) > 0 ? Number(spent) : 0;
367
422
  if (spentUsd > 0 && n <= spentUsd + 1e-9) {
368
- return { status: 200, body: { ok: true, text: `The cap must be above what is already spent (at least $${leastResumeCapUsd(spentUsd, floorUsd).toFixed(2)}).`, red: true, floorUsd, floorText: capFloorText(floorUsd) } };
423
+ return { status: 200, body: { ok: true, text: `The cap must be above what is already spent (at least $${leastResumeCapUsd(spentUsd, floorUsd).toFixed(2)}).`, red: true, floorUsd, floorText } };
369
424
  }
370
- const claim = monthlyClaim(n - spentUsd);
371
- if (claim === null || 'problem' in claim) return { status: 200, body: { ok: true, text: '', red: false, floorUsd, floorText: capFloorText(floorUsd) } };
372
- return { status: 200, body: { ok: true, ...monthlyNote(claim), floorUsd, floorText: capFloorText(floorUsd) } };
425
+ // M4d am21 item 1: a card that belongs to a draft (a revise, or the Start over about to be made) is checked for the pot LEFT, as the doors do
426
+ const dd = draftsDir();
427
+ const priorDir = typeof draftId === 'string' && ID_RE.test(draftId) && dd !== null && listIds().includes(draftId) ? join(dd, draftId) : null;
428
+ const priorUsd = priorDir === null ? 0 : draftingSpent(priorDir, { ceilingUsd: floorUsd }).usd;
429
+ const claim = monthlyClaim(Math.max(0, n - spentUsd - priorUsd));
430
+ if (claim === null || 'problem' in claim) return { status: 200, body: { ok: true, text: '', red: false, floorUsd, floorText } };
431
+ return { status: 200, body: { ok: true, ...monthlyNote(claim), floorUsd, floorText } };
373
432
  },
374
433
 
375
434
  /**
@@ -388,6 +447,9 @@ export function createAuthor(opts) {
388
447
  return { status: 200, body: { ok: true, lines, say: lines.length === 0 ? 'Tick a model in Settings > Providers.' : '' } };
389
448
  },
390
449
 
450
+ /** The starter's "this run's start is in phase `starting`" for the Runs list and a run's page (`startingFor`, the ONE rule). @param {string} flow @param {string} runId */
451
+ startingRun(flow, runId) { return starter.startingFor(flow, keysNow().keys, runId) !== null; },
452
+
391
453
  /** `GET /api/author/start/:startId`: the start's phase, read from its files. @param {string} id */
392
454
  startGet(id) { return starter.get(id, keysNow().keys); },
393
455
 
@@ -405,7 +467,17 @@ export function createAuthor(opts) {
405
467
  if (!loaded.ok) return { status: 409, body: { ok: false, refused: 'keys-file', say: String(loaded.refusal) } };
406
468
  const dd = draftsDir();
407
469
  if (dd === null) return { status: 400, body: { ok: false, refused: 'root', say: 'The flows folder this panel serves does not exist.' } };
408
- const vet = vetCard(body, loaded);
470
+ // M4d am19 item 3 / am21 items 1-2: a Start over keeps the pot. The month is checked for the cap LEFT after the earlier session's drafting (the chain behind it too);
471
+ // an earlier draft that is gone is never counted as $0: refused here, at $0, in words
472
+ const startedFrom = body?.startedOverFrom;
473
+ let priorUsd = 0;
474
+ if (typeof startedFrom === 'string' && startedFrom !== '') {
475
+ if (!ID_RE.test(startedFrom) || !listIds().includes(startedFrom)) return { status: 400, body: { ok: false, refused: 'earlier-missing', say: EARLIER_MISSING_SAY } };
476
+ const spent = draftingSpent(join(dd, startedFrom), { ceilingUsd: capFloorFor(true, home, cardFields(body)) });
477
+ if (spent.missingEarlier) return { status: 400, body: { ok: false, refused: 'earlier-missing', say: EARLIER_MISSING_SAY } };
478
+ priorUsd = spent.usd;
479
+ }
480
+ const vet = vetCard(body, loaded, priorUsd);
409
481
  if (!vet.ok) return vet.reply;
410
482
  const { card } = vet;
411
483
  for (const id of listIds()) {
@@ -448,10 +520,12 @@ export function createAuthor(opts) {
448
520
  signPrepare(id) {
449
521
  const seen = greenDraft(id);
450
522
  if (!seen.ok) return seen.reply;
523
+ const pot = potOf(seen.dir, seen.v.card);
524
+ if (pot.refusal !== null) return { status: 400, body: { ok: false, refused: 'pot-empty', say: pot.refusal, split: pot.split } };
451
525
  return {
452
526
  status: 200,
453
527
  body: {
454
- ok: true, draftId: id, hash: seen.v.hash, flowName: seen.name, capUsd: seen.v.card.capUsd, readout: seen.v.readout, answers: seen.v.answers, checked: seen.v.checked, notChecked: seen.v.notChecked, runId: nextRunId(join(root, seen.name)),
528
+ ok: true, split: pot.split, draftId: id, hash: seen.v.hash, flowName: seen.name, capUsd: seen.v.card.capUsd, readout: seen.v.readout, answers: seen.v.answers, checked: seen.v.checked, notChecked: seen.v.notChecked, runId: nextRunId(join(root, seen.name)),
455
529
  },
456
530
  };
457
531
  },
@@ -471,8 +545,10 @@ export function createAuthor(opts) {
471
545
  const { v, name, dir } = seen;
472
546
  const b = body && typeof body === 'object' ? body : {};
473
547
  // amendment 4 item 2: a cap that cannot fund one round of the first model step is never signed (it would cap-halt at $0 spent)
474
- const floor = capFloorUsd(typeof v.card.job === 'string' ? v.card.job : '', home, v.card);
475
- if (Number(v.card.capUsd) < floor) return { status: 400, body: { ok: false, refused: 'cap-too-small', say: capFloorText(floor) } };
548
+ const floor = capFloorOf(parseJobBox(typeof v.card.job === 'string' ? v.card.job : '').steps.some((s) => s.ask === null), home, v.card);
549
+ if (Number(v.card.capUsd) < floor.usd) return { status: 400, body: { ok: false, refused: 'cap-too-small', say: capTooSmallText('drafting', Number(v.card.capUsd), floor.usd, String(floor.model)) } };
550
+ const pot = potOf(dir, v.card);
551
+ if (pot.refusal !== null) return { status: 400, body: { ok: false, refused: 'pot-empty', say: pot.refusal, split: pot.split } };
476
552
  if (typeof b.hash !== 'string' || b.hash !== v.hash) {
477
553
  return { status: 409, body: { ok: false, refused: 'stale-hash', say: 'The plan on disk is not the one you were shown (its hash differs). Nothing was signed. Reload and read the plan again.' } };
478
554
  }
@@ -503,8 +579,19 @@ export function createAuthor(opts) {
503
579
  writeFileSync(join(dir, 'signed.json'), `${JSON.stringify({
504
580
  at: new Date().toISOString(), signedBy, hash: v.hash, flow: name, runId: runId === '' ? null : runId,
505
581
  })}\n`, { mode: 0o600 });
582
+ // M4d am16 item 1: the first run gets what is LEFT of the card's cap after drafting, as its own signed values (the flow stays signed at the card's cap, and
583
+ // every later run that does not draft gets the whole of it). Nothing spent on drafting = no values file = the whole cap.
584
+ let values = null;
585
+ if (pot.split.spentUsd > 0) {
586
+ const prose = readFileInside(join(dir, v.plan), 'prose.txt');
587
+ const parsed = prose.ok ? parseSignedText(prose.text) : null;
588
+ if (parsed && parsed.ok) {
589
+ const vals = { ...flowValues(parsed.arbiter), capUsd: pot.split.leftUsd };
590
+ values = { flow: name, flowSignatureHash: result.signature.flow, version: 0, values: vals, hash: valuesHash({ flow: name, flowSignatureHash: result.signature.flow, runId: null, version: 0, values: vals }), signedBy, at: new Date().toISOString() };
591
+ }
592
+ }
506
593
  const started = starter.start({
507
- kind: 'sign', flow: name, runId, sources: inputs.map((r) => ({ role: r.role, path: r.path })),
594
+ kind: 'sign', flow: name, runId, sources: inputs.map((r) => ({ role: r.role, path: r.path })), values,
508
595
  }, loaded);
509
596
  if (started.status !== 202) return { status: started.status, body: { ...started.body, signed: true, flow: name, say: `${started.body.say ?? 'The run did not start.'} The flow is signed; start it from "Run a signed flow".` } };
510
597
  return { status: 202, body: { ...started.body, signed: true } };
@@ -535,7 +622,8 @@ export function createAuthor(opts) {
535
622
  if (!Array.isArray(v.revises)) return { status: 409, body: { ok: false, refused: 'not-revisable', say: `This draft is ${v.phase}, so it cannot be revised. Draft again from the card.` } };
536
623
  if (v.revisesLeft <= 0) return { status: 409, body: { ok: false, refused: 'no-revises-left', say: `This draft has used its ${MAX_REVISES} revises. Start over: it keeps the fields and gives ${MAX_REVISES} new revises.` } };
537
624
  if (childRunning(dir)) return { status: 409, body: { ok: false, refused: 'draft-live', say: 'The draft process is still finishing. Try again in a moment.' } };
538
- const vet = vetCard(body, loaded);
625
+ if (draftingSpent(dir).missingEarlier) return { status: 400, body: { ok: false, refused: 'earlier-missing', say: EARLIER_MISSING_SAY } };
626
+ const vet = vetCard(body, loaded, draftedSoFar(dir, v.card));
539
627
  if (!vet.ok) return vet.reply;
540
628
  for (const other of listIds()) {
541
629
  if (other === id) continue;
@@ -599,7 +687,7 @@ export function createAuthor(opts) {
599
687
  const all = readQuestions(planDir).questions.map((x) => ({ line: x.line, question: x.question, answer: x.k === v.openK ? answer : x.answer }));
600
688
  const grown = appendAnswersToJob(typeof v.card.job === 'string' ? v.card.job : '', /** @type {{line:number, answer:string}[]} */ (all));
601
689
  if (grown.added !== all.length) return { status: 409, body: { ok: false, refused: 'no-such-line', say: 'An answer is about a job line the card no longer has. Draft again from the card. Nothing was signed.' } };
602
- const vet = vetCard({ ...v.card, job: grown.job }, loaded);
690
+ const vet = vetCard({ ...v.card, job: grown.job }, loaded, draftedSoFar(dir, v.card));
603
691
  if (!vet.ok) return vet.reply;
604
692
  for (const other of listIds()) {
605
693
  if (other === id) continue;