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
@@ -0,0 +1,297 @@
1
+ // M4e piece 2a, items 1-2 (docs/wiki/the-module-ladder.md, "M4e", scope 2 and 6): the job card -> the prose file
2
+ // `fwdloop draft` reads, and the $0 checks that run before any spawn. Pure of the panel: no HTTP, no spawn, no
3
+ // writes — it reads the disk only to check the card's paths (realpathSync at the click, as the signed text says).
4
+ //
5
+ // The card writes EXACTLY the shape `flows/<flow>/prose.txt` has: the job box's lines turned into the job file (`N. text`,
6
+ // ` guardrail: text`, `N. ask <wait>: question` — M4e amendment 2), then the "Arbiter guardrails" block built ONLY from the card's
7
+ // typed fields — cap, send at the LAST step to the folder, one `source <role> = file:<path>` per input line. The drafter never writes
8
+ // any of it (hard line); this file is the only place the block is built.
9
+ //
10
+ // Every refusal is `{ field, say }`: the box it names and a plain sentence. A refusal spends $0 and creates
11
+ // nothing — this module writes nothing at all.
12
+ import {
13
+ accessSync, constants as fsConstants, lstatSync, realpathSync, statSync,
14
+ } from 'node:fs';
15
+ import { isAbsolute, join } from 'node:path';
16
+
17
+ import { checkFlowName } from '../flow.js';
18
+ import { checkSendDestination, resolveCeilingUsd } from '../runner.js';
19
+ import { parseSignedText } from '../signed-text.js';
20
+ import { PROVIDER_SLOTS } from '../provider.js';
21
+
22
+ /** The heading line the prose files use (flows/job2-m6a-3/prose.txt); the parser matches `/^arbiter guardrails\b/i`. */
23
+ export const ARBITER_HEADING = 'Arbiter guardrails (belong to no line; human-signed, tighten-only — never authored or claimed by the drafter):';
24
+
25
+ /** The role shape the signed-text parser accepts (src/signed-text.js SOURCE_RE). */
26
+ const ROLE_RE = /^[a-z][a-z0-9_-]*$/;
27
+ /** A tab is allowed in the job text; every other control character (a newline in a path, NUL) is not. */
28
+ // eslint-disable-next-line no-control-regex
29
+ const CONTROL_RE = /[\u0000-\u001f\u007f]/;
30
+
31
+ /** A cap as the signed-text grammar spells it: a plain decimal, never an exponent. @param {number} n */
32
+ function capText(n) {
33
+ const s = String(n);
34
+ return /^\d+(?:\.\d+)?$/.test(s) ? s : n.toFixed(20).replace(/0+$/, '').replace(/\.$/, '');
35
+ }
36
+
37
+ const str = (v) => (typeof v === 'string' ? v : '');
38
+
39
+ /** The ask wait the card takes (amendment 2 item 5): a whole number above 0 with `m` or `h`, nothing else. */
40
+ const WAIT_RE = /^(\d+)([mh])$/i;
41
+ /** @param {string} t @returns {boolean} */
42
+ export const isAskWait = (t) => { const m = WAIT_RE.exec(t); return m !== null && Number(m[1]) > 0; };
43
+
44
+ /** The first 40 characters of a line, for a refusal sentence. @param {string} t */
45
+ const snip = (t) => (t.length > 40 ? `${t.slice(0, 40)}…` : t);
46
+
47
+ /**
48
+ * The job box (M4e amendment 2 item 1), a pure function of its text. One non-empty line is one step; a line starting with `~` is a
49
+ * guardrail of the step above; `Ask:` / `Ask 2h:` (case-insensitive) is an ask with the card's wait / its own wait; empty lines are
50
+ * dropped. A refusal is `{ line, say }`, `line` = the 1-based line of the box (blank lines count, so the human can find it).
51
+ * @param {string} text
52
+ * @returns {{ steps: { n: number, text: string, ask: null | { wait: string|null, question: string }, guardrails: string[] }[], refusals: { line: number, say: string }[] }}
53
+ */
54
+ export function parseJobBox(text) {
55
+ /** @type {{ n: number, text: string, ask: null | { wait: string|null, question: string }, guardrails: string[] }[]} */
56
+ const steps = [];
57
+ /** @type {{ line: number, say: string }[]} */
58
+ const refusals = [];
59
+ String(text).split('\n').forEach((raw, i) => {
60
+ const t = raw.trim();
61
+ if (t === '') return;
62
+ const at = i + 1;
63
+ const no = (say) => refusals.push({ line: at, say: `Line ${at} ("${snip(t)}") ${say}` });
64
+ if (t.startsWith('~')) {
65
+ const g = t.slice(1).trim();
66
+ if (steps.length === 0) no('starts with ~ but no step is above it. A ~ line belongs to the step above, so put a step first.');
67
+ else if (g === '') no('is only a ~. Write the guardrail after it.');
68
+ else steps[steps.length - 1].guardrails.push(g);
69
+ return;
70
+ }
71
+ const n = steps.length + 1;
72
+ if (/^ask[: ]/i.test(t)) {
73
+ const m = /^ask(?:\s+(\d+)\s*([mh]))?\s*:\s*(.*)$/i.exec(t);
74
+ if (!m) no('is not an ask. Write it as "Ask: question" or "Ask 2h: question" (m for minutes, h for hours).');
75
+ else if (m[1] !== undefined && Number(m[1]) <= 0) no('has an ask wait of 0. The wait must be above 0.');
76
+ else if (m[3] === '') no('is an ask with no question after the colon.');
77
+ else steps.push({ n, text: t, ask: { wait: m[1] === undefined ? null : `${Number(m[1])}${m[2].toLowerCase()}`, question: m[3] }, guardrails: [] });
78
+ return;
79
+ }
80
+ steps.push({ n, text: t, ask: null, guardrails: [] });
81
+ });
82
+ return { steps, refusals };
83
+ }
84
+
85
+ /** The job file lines (`N. text`, ` guardrail: text`, `N. ask <wait>: question`) for parsed steps; the wait is ALWAYS written out. @param {ReturnType<typeof parseJobBox>['steps']} steps @param {string} askWait */
86
+ export function jobFileLines(steps, askWait) {
87
+ /** @type {string[]} */
88
+ const out = [];
89
+ for (const s of steps) {
90
+ out.push(s.ask ? `${s.n}. ask ${s.ask.wait ?? askWait.toLowerCase()}: ${s.ask.question}` : `${s.n}. ${s.text}`);
91
+ for (const g of s.guardrails) out.push(` guardrail: ${g}`);
92
+ }
93
+ return out;
94
+ }
95
+
96
+ /**
97
+ * The inputs box (amendment 2 item 2): one `name: path` per non-empty line, split at the FIRST colon. `line` is the line's own number
98
+ * as the box shows it (empty lines are skipped and not numbered). A line with no colon is flagged `noColon`.
99
+ * @param {string} text
100
+ * @returns {{ line: number, role: string, path: string, noColon?: true }[]}
101
+ */
102
+ export function parseInputLines(text) {
103
+ /** @type {{ line: number, role: string, path: string, noColon?: true }[]} */
104
+ const rows = [];
105
+ for (const raw of String(text).split('\n')) {
106
+ const t = raw.trim();
107
+ if (t === '') continue;
108
+ const line = rows.length + 1;
109
+ const c = t.indexOf(':');
110
+ if (c === -1) rows.push({ line, role: t, path: '', noColon: true });
111
+ else rows.push({ line, role: t.slice(0, c).trim(), path: t.slice(c + 1).trim() });
112
+ }
113
+ return rows;
114
+ }
115
+
116
+ /**
117
+ * Normalise what the page sent into the typed card (one reader of the request body's shape). Unknown fields are
118
+ * dropped; nothing here judges a value. `inputs` is the inputs box's TEXT (`name: path` per line); `destination` is the folder.
119
+ * @param {any} body
120
+ */
121
+ export function cardFields(body) {
122
+ const b = body && typeof body === 'object' ? body : {};
123
+ return {
124
+ flowName: str(b.flowName).trim(),
125
+ job: str(b.job).replace(/\r\n?/g, '\n'),
126
+ destination: str(b.destination).trim(),
127
+ inputs: str(b.inputs).replace(/\r\n?/g, '\n'),
128
+ capUsd: typeof b.capUsd === 'string' && b.capUsd.trim() !== '' ? Number(b.capUsd) : b.capUsd,
129
+ askWait: str(b.askWait).trim(),
130
+ };
131
+ }
132
+
133
+ /** The Run-a-signed-flow door's rows (a role is fixed by the signed flow): what the page sent, as `{role, path}`. @param {any} v */
134
+ export function runInputRows(v) {
135
+ return (Array.isArray(v) ? v : []).map((r) => ({ role: str(r?.role).trim(), path: str(r?.path).trim() }));
136
+ }
137
+
138
+ /**
139
+ * The prose file text for a card whose fields already passed {@link checkCard}. The job lines come first (the job box's steps as the
140
+ * job file); the arbiter block is built only from the card's own fields. The ONE card -> prose function.
141
+ * @param {ReturnType<typeof cardFields>} card
142
+ * @returns {string}
143
+ */
144
+ export function cardToProse(card) {
145
+ const { steps } = parseJobBox(card.job);
146
+ const out = [...jobFileLines(steps, card.askWait), '', ARBITER_HEADING];
147
+ out.push(`guardrail: cap $${capText(Number(card.capUsd))} per run`);
148
+ if (card.destination !== '') out.push(`guardrail: send at line ${steps.length} to file:${card.destination}`);
149
+ for (const i of parseInputLines(card.inputs)) out.push(`guardrail: source ${i.role} = file:${i.path}`);
150
+ return `${out.join('\n')}\n`;
151
+ }
152
+
153
+ /** The refusal for a path that does not name a readable regular file (realpath at the click). @param {string} p */
154
+ function fileProblem(p) {
155
+ let real;
156
+ try { real = realpathSync(p); } catch (/** @type {any} */ e) {
157
+ return e?.code === 'ENOENT' || e?.code === 'ENOTDIR' || e?.code === 'ELOOP'
158
+ ? 'is not there (no file at that path, or a link that points at nothing).' : `cannot be looked at (${e?.code ?? 'error'}).`;
159
+ }
160
+ let st;
161
+ try { st = statSync(real); } catch (/** @type {any} */ e) { return `cannot be looked at (${e?.code ?? 'error'}).`; }
162
+ if (!st.isFile()) return 'is a folder or something that is not a plain file — type the path of one file.';
163
+ try { accessSync(real, fsConstants.R_OK); } catch { return 'is a file this panel is not allowed to read.'; }
164
+ return null;
165
+ }
166
+
167
+ /**
168
+ * The $0 check of the input rows, shared by the card (draft door) and the Run-a-signed-flow door: a role and a path on every row,
169
+ * a role shape the signed-text parser accepts and used once, each path a full path to a readable regular file (realpath at the
170
+ * click). Never reads a file's contents. A row from the card's inputs box carries its `line`: its refusal is field `inputs` and its
171
+ * sentence starts "Line N:". A Run-door row has no line: its refusal is field `inputs.<n>`.
172
+ * @param {{role: string, path: string, line?: number, noColon?: true}[]} rows
173
+ * @returns {{field: string, say: string}[]} one refusal per bad row
174
+ */
175
+ export function checkInputRows(rows) {
176
+ /** @type {{field: string, say: string}[]} */
177
+ const refusals = [];
178
+ const seen = new Set();
179
+ rows.forEach((row, n) => {
180
+ const no = (say) => refusals.push(row.line === undefined ? { field: `inputs.${n}`, say } : { field: 'inputs', say: `Line ${row.line}: ${say}` });
181
+ if (row.noColon) { no('write it as name: path (for example resume: /home/me/resume.md).'); return; }
182
+ if (row.role === '' && row.path === '') { no('This input row is empty. Fill it in or remove it.'); return; }
183
+ if (row.role === '') { no('This input has a path but no role. Give it a name such as "resume".'); return; }
184
+ if (!ROLE_RE.test(row.role)) { no(`The role "${row.role}" must be lowercase letters, digits, "-" or "_", starting with a letter.`); return; }
185
+ if (seen.has(row.role)) { no(`The role "${row.role}" is used twice. Each input needs its own role.`); return; }
186
+ seen.add(row.role);
187
+ if (row.path === '') { no(`The input "${row.role}" has a role but no path.`); return; }
188
+ if (CONTROL_RE.test(row.path)) { no(`The path for "${row.role}" has a character that cannot be in a path.`); return; }
189
+ if (!isAbsolute(row.path)) { no(`The path for "${row.role}" must be a full path starting with "/".`); return; }
190
+ const why = fileProblem(row.path);
191
+ if (why) no(`The path for "${row.role}" ${why}`);
192
+ });
193
+ return refusals;
194
+ }
195
+
196
+ /**
197
+ * M4e amendment 4 item 2: the smallest per-run cap that funds ONE round of the first model step. The runner halts a step when
198
+ * `spent + ceiling > cap` (`runStepRalph`), and every ordinary (non-ask) step is a model step, so the floor is the runner's own
199
+ * per-round ceiling (`resolveCeilingUsd`) as soon as the job has one such line; a job of only asks spends nothing before its stop.
200
+ * ONE function: the card's Draft check, Sign, and the page's note all read it. Returns 0 when no step needs a round.
201
+ * @param {string} jobText
202
+ */
203
+ export function capFloorUsd(jobText) {
204
+ return capFloorFor(parseJobBox(jobText).steps.some((s) => s.ask === null));
205
+ }
206
+
207
+ /** The floor itself, for a caller that already knows whether the job has a step that is not an ask (a signed flow: any step off an ask line). @param {boolean} hasRoundStep */
208
+ export function capFloorFor(hasRoundStep) {
209
+ return hasRoundStep ? resolveCeilingUsd(null) : 0;
210
+ }
211
+
212
+ /** The one sentence for a cap under the floor (red under Cap, and the Draft / sign refusal). @param {number} floorUsd */
213
+ export function capFloorText(floorUsd) {
214
+ return `needs at least $${(Math.ceil(floorUsd * 100 - 1e-6) / 100).toFixed(2)} per run`;
215
+ }
216
+
217
+ /**
218
+ * Amendment 1's destination checks, in ONE place: the New job card and the per-run destination of amendment 5 both ask it. `null` = fine,
219
+ * else the sentence (a folder that is the run folder, a flow folder, the root, `.drafts`, `.starts`, the config folder, a file, a missing
220
+ * folder, a path with a control character). Never overwrite is the send's own rule at write time.
221
+ * @param {string} dest the folder as typed @param {string} root the flows root
222
+ * @returns {string|null}
223
+ */
224
+ export function destinationRefusal(dest, root) {
225
+ if (CONTROL_RE.test(dest)) return 'The destination folder has a character that cannot be in a path.';
226
+ const d = checkSendDestination(`file:${dest}`, { root });
227
+ return d.ok ? null : `${d.red.replace(/^destination: /, '')}.`;
228
+ }
229
+
230
+ /**
231
+ * Every $0 check on the card, before any spawn (scope 6). Collects all refusals so the page can name every box.
232
+ * @param {ReturnType<typeof cardFields>} card
233
+ * @param {{ root: string, env?: Record<string, string|undefined> }} ctx `env` = the merged keys env: a key value typed into any box is refused
234
+ * @returns {{ ok: true, prose: string }|{ ok: false, refusals: {field: string, say: string}[] }}
235
+ */
236
+ export function checkCard(card, { root, env = {} }) {
237
+ /** @type {{field: string, say: string}[]} */
238
+ const refusals = [];
239
+ const no = (field, say) => refusals.push({ field, say });
240
+
241
+ // flow name: the CLI's own check, and not an existing flow
242
+ const name = checkFlowName(card.flowName);
243
+ if (!name.ok) no('flowName', `${name.red}. Use lowercase letters, digits, "-" or "_".`);
244
+ else {
245
+ let there = true;
246
+ try { lstatSync(join(root, card.flowName)); } catch { there = false; }
247
+ if (there) no('flowName', `There is already a flow named "${card.flowName}" here. Pick a name that is not used yet.`);
248
+ }
249
+
250
+ // job
251
+ if (card.job.trim() === '') no('job', 'The job is empty. Write one step per line.');
252
+ else if (/^\s*arbiter guardrails\b/im.test(card.job)) {
253
+ no('job', 'The job contains an "Arbiter guardrails" heading. The cap, the destination and the inputs go in their own boxes, not in the job text.');
254
+ } else for (const r of parseJobBox(card.job).refusals) no('job', r.say);
255
+
256
+ // ask wait: a number with m or h (it is written out on every ask line)
257
+ if (!isAskWait(card.askWait)) no('askWait', 'The ask wait must be a number with m or h, such as 30m or 1h.');
258
+
259
+ // cap
260
+ if (typeof card.capUsd === 'string' || typeof card.capUsd === 'number') {
261
+ if (!(Number.isFinite(Number(card.capUsd)) && Number(card.capUsd) > 0)) no('capUsd', 'The cap must be a number above 0 (dollars per run).');
262
+ else if (Number(card.capUsd) < capFloorUsd(card.job)) no('capUsd', capFloorText(capFloorUsd(card.job)));
263
+ } else no('capUsd', 'The cap must be a number above 0 (dollars per run).');
264
+
265
+ // destination: one folder, or empty for no send (it is sent at the last step)
266
+ const dest = card.destination;
267
+ if (dest !== '') {
268
+ const why = destinationRefusal(dest, root);
269
+ if (why !== null) no('destination', why);
270
+ }
271
+
272
+ // inputs: one `name: path` per line; a role and a path on every line, no repeated role; each path a readable regular file (realpath)
273
+ refusals.push(...checkInputRows(parseInputLines(card.inputs)));
274
+
275
+ // a provider key typed into any box never reaches a file
276
+ /** @type {string[]} */
277
+ const keys = [];
278
+ for (const p of Object.values(PROVIDER_SLOTS)) { const k = env[p.envVar]; if (typeof k === 'string' && k.length >= 8) keys.push(k); }
279
+ if (keys.length > 0) {
280
+ const boxes = [['job', card.job], ['flowName', card.flowName], ['destination', dest], ['inputs', card.inputs]];
281
+ for (const [field, text] of boxes) if (keys.some((k) => String(text).includes(k))) no(String(field), 'This box contains an API key. Keys go in Settings only. Nothing was saved.');
282
+ }
283
+
284
+ if (refusals.length > 0) return { ok: false, refusals };
285
+
286
+ // the parser has the last word on the job lines and the block (a send line that is not a job line, a bad ask mark)
287
+ const prose = cardToProse(card);
288
+ const parsed = parseSignedText(prose);
289
+ if (!parsed.ok) {
290
+ for (const red of parsed.reds) {
291
+ const field = /field "sends"/.test(red) ? 'destination' : /field "capUsd"/.test(red) ? 'capUsd' : /field "sources"/.test(red) ? 'inputs' : 'job';
292
+ no(field, `${red.replace(/^(signed-text|arbiter): /, '')}.`);
293
+ }
294
+ return { ok: false, refusals };
295
+ }
296
+ return { ok: true, prose };
297
+ }
@@ -0,0 +1,312 @@
1
+ // M4e piece 2b (docs/wiki/the-module-ladder.md, "M4e", scope 3 "Run a signed flow", 6, 9; negatives (iii) (iv) (v) (x)): the
2
+ // RUN-A-SIGNED-FLOW door of the panel's backend — `GET /api/author/flows` and `POST /api/author/run`. No spawn of its own: a
3
+ // run starts only through `authorstart.js`'s one `start`. Reads the disk; writes nothing.
4
+ //
5
+ // flows() only flows whose `readFlow` passes (a missing, unsigned or tampered flow is never listed), that `canFlowRun` accepts
6
+ // (the one function shared with the run's own preflight: an unwired verb is not listed) and that have at least one
7
+ // passed run (amendment 7 item 7; Run again reaches the rest), each with its signed
8
+ // cap, its declared source roles, the source paths the NEWEST run of that flow used (its `inputs.json`
9
+ // manifest `source` field; blank when none) and what is left this month (a courtesy: the CLI's own monthly
10
+ // check is what refuses).
11
+ // run(body) { flow, inputs: [{role, path}], runId } -> the SAME $0 input checks as the card (`checkInputRows`), the role set
12
+ // must equal the flow's declared roles exactly, the run id the CLI's own check and no such run yet — then `start`.
13
+ import { lstatSync, realpathSync } from 'node:fs';
14
+ import { join } from 'node:path';
15
+
16
+ import { scrub } from '../authoring.js';
17
+ import { endRow, readHistory } from '../books.js';
18
+ import { canFlowRun } from '../canrun.js';
19
+ import { loadCatalogue } from '../catalogue.js';
20
+ import { ConfigError, readConfig } from '../config.js';
21
+ import {
22
+ checkFlowName, listFlowNames, listRunIds, nextRunId, readFileInside, readFlow, resolveRunDir,
23
+ } from '../flow.js';
24
+ import { spendSummary } from '../monthly.js';
25
+ import { userInfo } from 'node:os';
26
+ import {
27
+ applyRunValues, flowValues, pickRunValues, valuesHash,
28
+ } from '../runvalues.js';
29
+ import {
30
+ capFloorFor, capFloorText, checkInputRows, runInputRows,
31
+ } from './authorcard.js';
32
+ import { checkValues } from './authorvalues.js';
33
+ import { providerKeys } from './spawn.js';
34
+
35
+ const NO_LIMIT = 'no monthly limit set';
36
+ /** The body keys a run start takes (amendment 5 item 2): the open boxes plus the hash of the second click. Any other key is refused by name. */
37
+ const RUN_KEYS = ['flow', 'inputs', 'runId', 'destination', 'capUsd', 'askWaits', 'hash'];
38
+
39
+ /**
40
+ * What the Run / Resume forms show of a signed flow (read from its own files, never from a model): the job lines as the signed text has them
41
+ * (an ask line carries its question and its wait), the values the open boxes start from, and the cap floor. Amendment 5 item 2: all the rest is dimmed.
42
+ * @param {any} read `readFlow`'s ok result
43
+ */
44
+ export function formFacts(read) {
45
+ const asks = new Map((read.arbiter.asks ?? []).map((a) => [a.line, a]));
46
+ const values = flowValues(read.arbiter);
47
+ const jobLines = read.lines.map((l) => ({
48
+ n: l.n, text: l.text, guardrail: l.guardrail || null, ask: asks.has(l.n) ? { wait: values.askWaits[String(l.n)] } : null,
49
+ }));
50
+ const hasRound = read.declaration.steps.some((st) => !asks.has(st.fromLine));
51
+ return {
52
+ values, jobLines, hasSend: values.destination !== null, capFloorUsd: capFloorFor(hasRound), floorText: capFloorText(capFloorFor(hasRound)),
53
+ };
54
+ }
55
+
56
+ /**
57
+ * @param {{ root: string, home?: string, skipMonthly?: boolean, loadEnv: () => { ok: boolean, env: Record<string, string|undefined>, refusal: string|null }, starter: ReturnType<typeof import('./authorstart.js').createStarter>, monthlyClaim: (usd: number) => any }} opts
58
+ */
59
+ export function createFlowsDoor(opts) {
60
+ const {
61
+ root, home, skipMonthly = false, loadEnv, starter, monthlyClaim,
62
+ } = opts;
63
+
64
+ /** What is left of the monthly limit, as a courtesy line: the limit minus this month's counted spend (holds are the CLI's business). */
65
+ function leftThisMonth() {
66
+ // a test process with no config home: the CLI skips its monthly check, so there is no limit to read (and no real home to touch)
67
+ if (skipMonthly) return { limitUsd: null, leftUsd: null, atLeast: false, say: NO_LIMIT };
68
+ let limit;
69
+ try { limit = readConfig({ home }).monthlyLimitUsd ?? null; } catch (e) {
70
+ return { limitUsd: null, leftUsd: null, atLeast: false, say: e instanceof ConfigError ? 'The Settings file cannot be read.' : 'The monthly limit cannot be read.' };
71
+ }
72
+ if (limit === null) return { limitUsd: null, leftUsd: null, atLeast: false, say: NO_LIMIT };
73
+ const month = spendSummary({ home }).month;
74
+ const left = Math.max(0, Math.floor((limit - month.usd) * 100 + 1e-6) / 100);
75
+ return {
76
+ limitUsd: limit, leftUsd: left, atLeast: month.atLeast, say: `${month.atLeast ? 'at most ' : ''}$${left.toFixed(2)} left this month`,
77
+ };
78
+ }
79
+
80
+ /** The source paths one run froze: role -> path, from that run's `inputs.json`. Blank = none. @param {string} runDir @param {string[]} roles */
81
+ function sourcesOf(runDir, roles) {
82
+ /** @type {Record<string, string>} */
83
+ const out = Object.fromEntries(roles.map((r) => [r, '']));
84
+ if (runDir === '') return out;
85
+ const f = readFileInside(runDir, 'inputs.json');
86
+ let rows = [];
87
+ try { rows = f.ok ? JSON.parse(f.text) : []; } catch { rows = []; }
88
+ for (const row of Array.isArray(rows) ? rows : []) {
89
+ if (row && typeof row.id === 'string' && roles.includes(row.id) && typeof row.source === 'string') out[row.id] = row.source;
90
+ }
91
+ return out;
92
+ }
93
+
94
+ /** The source paths the newest run of this flow used: role -> path, from that run's `inputs.json`. Blank = none. @param {string} flowDir @param {string[]} roles */
95
+ function lastSources(flowDir, roles) {
96
+ let newest = null;
97
+ for (const id of listRunIds(flowDir)) {
98
+ const r = resolveRunDir(flowDir, id);
99
+ if (!r.ok) continue;
100
+ let t;
101
+ try { t = lstatSync(join(r.runDir, 'inputs.json')).mtimeMs; } catch { continue; }
102
+ if (newest === null || t > newest.t || (t === newest.t && id > newest.id)) newest = { t, id, runDir: r.runDir };
103
+ }
104
+ if (newest === null) return { runId: null, sources: sourcesOf('', roles) };
105
+ return { runId: newest.id, sources: sourcesOf(newest.runDir, roles) };
106
+ }
107
+
108
+ /** The values one run ran with: the flow's own, with the run's newest signed version laid over (`applyRunValues`). Unreadable = the flow's own. @param {any} read @param {string} name @param {string} runDir */
109
+ function runValuesOf(read, name, runDir) {
110
+ const applied = applyRunValues(read.arbiter, name, read.signature.flow, pickRunValues(runDir));
111
+ return { values: flowValues(applied.ok ? applied.arbiter : read.arbiter) };
112
+ }
113
+
114
+ /**
115
+ * What the Signed flow list shows of a flow's runs, read from its books: the passed runs (each with the values and input paths it
116
+ * ran with, so picking a run fills them in) and the track record (bareloop's reuse-estimate shape). An average reads only figures that
117
+ * are exact: a run with an unpriced spend or no wall time is left out of it, never counted as $0 or 0 min (unknown is never zero).
118
+ * @param {string} flowDir @param {string} name @param {any} read @param {string[]} roles
119
+ */
120
+ function runsOf(flowDir, name, read, roles) {
121
+ const history = readHistory(flowDir);
122
+ const passed = [];
123
+ let green = 0; let notGreen = 0; let spendSum = 0; let spendN = 0; let wallSum = 0; let wallN = 0;
124
+ for (const id of listRunIds(flowDir)) {
125
+ const r = resolveRunDir(flowDir, id);
126
+ if (!r.ok) continue;
127
+ const end = endRow(history, r.runDir, id);
128
+ if (end === null) continue; // not ended (running, parked, died): neither green nor not green
129
+ if (end.outcome === 'complete') {
130
+ green += 1;
131
+ passed.push({ runId: id, ...runValuesOf(read, name, r.runDir), sources: sourcesOf(r.runDir, roles) });
132
+ } else notGreen += 1;
133
+ if (end.spendComplete === true && Number.isFinite(end.spentUsd) && end.spentUsd >= 0) { spendSum += end.spentUsd; spendN += 1; }
134
+ if (Number.isFinite(end.wallMs) && end.wallMs > 0) { wallSum += end.wallMs; wallN += 1; }
135
+ }
136
+ const asks = new Set((read.arbiter.asks ?? []).map((a) => a.line));
137
+ return {
138
+ passed,
139
+ stats: {
140
+ steps: read.declaration.steps.filter((st) => !asks.has(st.fromLine)).length, asks: asks.size, green, notGreen,
141
+ avgSpendUsd: spendN > 0 ? spendSum / spendN : null, avgWallMs: wallN > 0 ? wallSum / wallN : null,
142
+ },
143
+ };
144
+ }
145
+
146
+ /** The real path of the flows folder this panel serves, or null when it is not there — the one place `root` is resolved. */
147
+ function realRootOrNull() {
148
+ try { return realpathSync(root); } catch { return null; }
149
+ }
150
+
151
+ /** Read one flow the way the CLI will (`readFlow`: signature verified). @param {string} realRoot @param {string} name */
152
+ function readSigned(realRoot, name) {
153
+ const cat = loadCatalogue();
154
+ if (!cat.ok) return { ok: /** @type {false} */ (false), reds: [`catalogue: ${cat.reds.join('; ')}`] };
155
+ return readFlow({ root: realRoot, name, catalogue: cat.primitives });
156
+ }
157
+
158
+ /**
159
+ * Every $0 check of a run start, shared by `runPrepare` (the first click) and `run`. `{ok:false, reply}` or the facts a start needs.
160
+ * Amendment 5 items 2-4: the open boxes are Inputs, Destination, Cap $ and each ask's wait; anything else in the body is refused by name.
161
+ * @param {any} body
162
+ */
163
+ function inspect(body, keys) {
164
+ const reply = (status, b) => ({ ok: /** @type {false} */ (false), reply: { status, body: { ok: false, ...b } } });
165
+ const realRoot = realRootOrNull();
166
+ if (realRoot === null) return reply(400, { refused: 'root', say: 'The flows folder this panel serves does not exist.' });
167
+ const flow = typeof body?.flow === 'string' ? body.flow : '';
168
+ const named = checkFlowName(flow);
169
+ if (!named.ok) return reply(400, { refused: 'flow', refusals: [{ field: 'flow', say: `${named.red}.` }] });
170
+ const read = readSigned(realRoot, flow);
171
+ if (!read.ok) {
172
+ return reply(400, { refused: 'flow', refusals: [{ field: 'flow', say: `"${flow}" is not a signed flow that passes its checks, so it will not run.` }], reds: read.reds.map((r) => scrub(String(r), keys)) });
173
+ }
174
+ const checked = checkValues({
175
+ allowedKeys: RUN_KEYS, body, base: flowValues(read.arbiter), realRoot, capOnly: false, floorUsd: formFacts(read).capFloorUsd, monthlyClaim,
176
+ });
177
+ if (!checked.ok && checked.refused) return reply(checked.status, { refused: checked.refused, say: checked.say, refusals: checked.refusals });
178
+ /** @type {{field: string, say: string}[]} */
179
+ const refusals = checked.ok ? [] : [...checked.refusals];
180
+ if (!checked.ok && checked.status === 409) return reply(409, { refused: 'monthly', say: checked.say });
181
+ const rows = runInputRows(body?.inputs);
182
+ refusals.push(...checkInputRows(rows));
183
+ const declared = (read.arbiter.sources ?? []).map((s) => s.role);
184
+ for (const role of declared) {
185
+ if (!rows.some((r) => r.role === role)) refusals.push({ field: 'inputs', say: `This flow needs an input named "${role}". Add it.` });
186
+ }
187
+ rows.forEach((r, n) => {
188
+ if (r.role !== '' && !declared.includes(r.role)) refusals.push({ field: `inputs.${n}`, say: `This flow has no input named "${r.role}" (it takes: ${declared.join(', ') || 'none'}).` });
189
+ });
190
+ const runId = typeof body?.runId === 'string' ? body.runId.trim() : '';
191
+ if (runId !== '') {
192
+ const run = starter.checkRun(flow, runId);
193
+ if (!run.ok) refusals.push({ field: 'runId', say: String(run.say) });
194
+ }
195
+ if (refusals.length > 0 || !checked.ok) return reply(400, { refused: 'run', refusals });
196
+ const hash = valuesHash({
197
+ flow, flowSignatureHash: read.signature.flow, runId: null, version: 0, values: checked.values,
198
+ });
199
+ return {
200
+ ok: /** @type {true} */ (true), flow, read, declared, rows, runId, values: checked.values, differs: checked.differs, hash,
201
+ };
202
+ }
203
+
204
+ /** One flow's record for the page: its signed values and facts, its last run's inputs, its passed runs and its track record. @param {string} realRoot @param {string} name @param {any} read @param {any} left */
205
+ function entryFor(realRoot, name, read, left) {
206
+ const roles = (read.arbiter.sources ?? []).map((s) => s.role);
207
+ const flowDir = join(realRoot, name);
208
+ const last = lastSources(flowDir, roles);
209
+ const { passed, stats } = runsOf(flowDir, name, read, roles);
210
+ return {
211
+ flow: name, capUsd: read.arbiter.capUsd, roles, nextRunId: nextRunId(flowDir), lastRunId: last.runId, lastSources: last.sources, leftThisMonth: left,
212
+ runs: passed, stats,
213
+ ...formFacts(read),
214
+ };
215
+ }
216
+
217
+ return {
218
+ /** `GET /api/author/flows`. */
219
+ flows() {
220
+ const realRoot = realRootOrNull();
221
+ if (realRoot === null) return { status: 200, body: { ok: true, flows: [] } };
222
+ const left = leftThisMonth();
223
+ const flows = [];
224
+ for (const name of listFlowNames(realRoot)) {
225
+ const read = readSigned(realRoot, name);
226
+ if (!canFlowRun(read).ok) continue;
227
+ const entry = entryFor(realRoot, name, read, left);
228
+ if (entry.runs.length === 0) continue; // amendment 7 item 7: only a flow with a passed run is listed
229
+ flows.push(entry);
230
+ }
231
+ return { status: 200, body: { ok: true, flows, leftThisMonth: left } };
232
+ },
233
+
234
+ /**
235
+ * `GET /api/author/run-again?flow=&runId=` (amendment 7 item 6): the Signed flow form for ONE run of a signed flow, any outcome, with that
236
+ * run's values and input paths as `pick`. The list's rule (passed run, preflight accepts) does not apply here; a flow the run's own
237
+ * preflight would refuse says why, in the preflight's words. Reads only.
238
+ * @param {string|null} flow @param {string|null} runId
239
+ */
240
+ runAgain(flow, runId) {
241
+ const no = (status, say, extra = {}) => ({ status, body: { ok: false, refused: 'run-again', say, ...extra } });
242
+ const realRoot = realRootOrNull();
243
+ if (realRoot === null) return no(400, 'The flows folder this panel serves does not exist.');
244
+ // a missing query value is refused by name, never passed on as null
245
+ if (typeof flow !== 'string' || flow === '') return no(400, 'Say which flow to run again.');
246
+ if (typeof runId !== 'string' || runId === '') return no(400, 'Say which run to run again.');
247
+ const named = checkFlowName(flow);
248
+ if (!named.ok) return no(400, `${named.red}.`);
249
+ const rr = resolveRunDir(join(realRoot, flow), runId);
250
+ if (!rr.ok) return no(400, `${rr.red}.`);
251
+ if (!listRunIds(join(realRoot, flow)).includes(runId)) return no(404, `"${flow}" has no run "${runId}".`);
252
+ const read = readSigned(realRoot, flow);
253
+ const can = canFlowRun(read);
254
+ if (!can.ok) {
255
+ const red = scrub(String(can.red), providerKeys(loadEnv().env));
256
+ return no(409, `"${flow}" will not run: ${red}`, { red });
257
+ }
258
+ if (!read.ok) return no(409, `"${flow}" will not run: it does not read.`); // narrows the type; canFlowRun has already refused this
259
+ const roles = (read.arbiter.sources ?? []).map((s) => s.role);
260
+ return {
261
+ status: 200,
262
+ body: {
263
+ ok: true, flow: entryFor(realRoot, flow, read, leftThisMonth()), pick: { runId, ...runValuesOf(read, flow, rr.runDir), sources: sourcesOf(rr.runDir, roles) },
264
+ },
265
+ };
266
+ },
267
+
268
+ /**
269
+ * `POST /api/author/run-prepare` (the first click of "Sign & run"): the same $0 checks as `run`, never starts anything and writes nothing.
270
+ * `needsSign` = the Destination, Cap $ or an ask wait differs from the flow's signed value, so the start needs the human's second click
271
+ * carrying `hash` (amendment 5 item 3); false = a plain Run (one click).
272
+ * @param {any} body
273
+ */
274
+ runPrepare(body) {
275
+ const s = inspect(body, providerKeys(loadEnv().env));
276
+ if (!s.ok) return s.reply;
277
+ return {
278
+ status: 200, body: {
279
+ ok: true, flow: s.flow, needsSign: s.differs, hash: s.differs ? s.hash : null, values: s.values, capUsd: s.values.capUsd,
280
+ },
281
+ };
282
+ },
283
+
284
+ /**
285
+ * `POST /api/author/run`: $0 checks -> the one start. A refusal names the box, spends $0 and creates nothing. A run whose Destination, Cap $
286
+ * or ask wait differs from the flow's signed values starts only with the `hash` of those values (the human's second click, like page
287
+ * sign): none or a stale one signs nothing and starts nothing. The signed values are written once into the run's own folder first.
288
+ * @param {any} body
289
+ */
290
+ run(body) {
291
+ const loaded = loadEnv();
292
+ if (!loaded.ok) return { status: 409, body: { ok: false, refused: 'keys-file', say: String(loaded.refusal) } };
293
+ const s = inspect(body, providerKeys(loaded.env));
294
+ if (!s.ok) return s.reply;
295
+ let values = null;
296
+ if (s.differs) {
297
+ if (typeof body.hash !== 'string' || body.hash === '') {
298
+ return { status: 409, body: { ok: false, refused: 'needs-sign', say: 'This run changes the destination, the cap or an ask wait, so it has to be signed: use Sign & run (two clicks). Nothing was started.' } };
299
+ }
300
+ if (body.hash !== s.hash) {
301
+ return { status: 409, body: { ok: false, refused: 'stale-hash', say: 'What you were shown is not what is on the card now (its hash differs). Nothing was signed. Look again, then sign.' } };
302
+ }
303
+ values = {
304
+ flow: s.flow, flowSignatureHash: s.read.signature.flow, version: 0, values: s.values, hash: s.hash, signedBy: userInfo().username, at: new Date().toISOString(),
305
+ };
306
+ }
307
+ return starter.start({
308
+ kind: 'run', flow: s.flow, runId: s.runId, sources: s.declared.map((role) => ({ role, path: /** @type {{path: string}} */ (s.rows.find((r) => r.role === role)).path })), values,
309
+ }, loaded.env);
310
+ },
311
+ };
312
+ }