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
@@ -0,0 +1,482 @@
1
+ // borrowed-from: bareloop src/panel/authorroutes.js@524a244 (the one-at-a-time rule `hasLiveSession` + terminal phases,
2
+ // the `/api/author/{live,start,:id,:id/abandon}` route set, the monthly/keys refusals before any spawn) and
3
+ // bareloop src/panel/authorsession.js@524a244 (the state's `card` field, kept so a refresh re-attaches).
4
+ // M4e piece 2a (docs/wiki/the-module-ladder.md, "M4e", scope 5, 6, 7, 11, 12): the DRAFT side of the panel's backend.
5
+ //
6
+ // Differences from bareloop, all signed: fwdloop's draft is a DETACHED CLI CHILD (`fwdloop draft <prose> --out <dir>
7
+ // --root <root> --name <flow>`), not an in-memory session, so every fact lives in FILES under
8
+ // `<root>/.drafts/<draftId>/` and the panel's memory holds NOTHING a restart would lose. No scouting, repo copy,
9
+ // install pause, revise menu or questions (fwdloop's drafter is one forced call with no questions back).
10
+ //
11
+ // card.json the typed card fields (what the human typed; never a key — checkCard refuses one)
12
+ // prose.txt the prose file `fwdloop draft` reads, built from the card by `cardToProse` (src/panel/authorcard.js)
13
+ // child.log the child's stdout+stderr, mode 0600 (quoted to the page only after `scrub`)
14
+ // pid.json { pid, procStart } written right after the spawn; the ONE liveness fact (`isFwdloopAlive`, M4c)
15
+ // draft/ the CLI's own output (spec.hash, readout.txt, log.json, spend.jsonl, draft-spend.json ...)
16
+ // note-<n>.txt the human's note for change <n> (M4e amendment 3 item 3), written by `revise`, write-once ('wx'), never a key
17
+ // draft-<n>/ the CLI's output for change <n> (`fwdloop draft --revise-from <plan> --note note-<n>.txt`): its own full draft dir, with
18
+ // note.txt beside spec.hash; `revise-<n>.log` is that child's log. The plan to sign is the NEWEST green of draft, draft-1 ...
19
+ // abandoned.json written by Abandon, after the child is gone
20
+ // signed.json written by `sign` (piece 2b) right after `signDraft` succeeds; the phase reader reads it
21
+ //
22
+ // ONE WRITER PER FIELD: `start` writes card.json, prose.txt, pid.json (and, through the one spawn helper, child.log);
23
+ // `abandon` writes abandoned.json; `sign` writes signed.json; the CLI child writes everything under draft/. The phase is never stored — it is
24
+ // READ from those files each time (`readDraft`), so a refresh or a panel restart cannot disagree with the disk.
25
+ //
26
+ // One at a time with no lock table: `start` is fully synchronous (check live -> create the folder -> spawn ->
27
+ // write pid.json, no await between), so two requests that arrive together run one after the other and the second
28
+ // sees the first's live child and is refused. A dead child never blocks (its pid is read, never assumed).
29
+ import { randomBytes } from 'node:crypto';
30
+ import { mkdirSync, realpathSync, writeFileSync } from 'node:fs';
31
+ import { userInfo } from 'node:os';
32
+ import { dirname, join } from 'node:path';
33
+ import { fileURLToPath } from 'node:url';
34
+
35
+ import {
36
+ PANEL_DRAFTS_DIR, readoutHeadIndexes, scrub, signDraft, textHasKey,
37
+ } from '../authoring.js';
38
+ import { nextRunId, readFileInside, readdirInside } from '../flow.js';
39
+ import { isFwdloopAlive } from '../liveness.js';
40
+ import {
41
+ checkMonthlyRoom, ConfigError, monthlyNote, monthlyRefusalText,
42
+ } from '../monthly.js';
43
+ import {
44
+ capFloorText, capFloorUsd, cardFields, checkCard, checkInputRows, parseInputLines,
45
+ } from './authorcard.js';
46
+ import { leastResumeCapUsd } from './authorvalues.js';
47
+ import { createFlowsDoor } from './authorflows.js';
48
+ import { createResumeDoor } from './authorresume.js';
49
+ import { createStarter } from './authorstart.js';
50
+ import {
51
+ childRunning, providerKeys, readJsonFile, spawnDetached, writePidFile,
52
+ } from './spawn.js';
53
+
54
+ const HERE = dirname(fileURLToPath(import.meta.url));
55
+ const BIN = join(HERE, '..', '..', 'bin', 'fwdloop');
56
+
57
+ /** A draft id: `d-` + the start time in base 36 (so ids sort oldest to newest) + 4 random hex. */
58
+ const ID_RE = /^d-[0-9a-z]{10}-[0-9a-f]{4}$/;
59
+ const newId = () => `d-${Date.now().toString(36).padStart(10, '0')}-${randomBytes(2).toString('hex')}`;
60
+ /** 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). */
61
+ const FINISHED = new Set(['abandoned', 'signed']);
62
+ const LOG_TAIL_CHARS = 1500;
63
+ const STOPPED_SAY = 'The draft process ended before it finished (it was stopped from outside). Nothing was signed and nothing was sent. Draft again.';
64
+ const RED_SAY = 'The drafter\'s plan did not pass the checks. Nothing was signed and nothing was sent. Fix the job and draft again; this draft is kept on disk and is never reused.';
65
+ /** Up to 2 changes per draft (amendment 3 item 3); a change is used once its `draft-<n>/` exists (a refusal at $0 makes none). */
66
+ export const MAX_CHANGES = 2;
67
+ const NOTE_MAX_CHARS = 2000;
68
+ const NOTE_RE = /^note-(\d+)\.txt$/;
69
+ const PLAN_DIR_RE = /^draft-(\d+)$/;
70
+ const CHANGE_RED_SAY = 'The change did not pass the checks. The plan above is unchanged and still the one to sign.';
71
+ const KILL_WAIT_MS = 3000;
72
+ const KILL_HARD_WAIT_MS = 2000;
73
+ const sleep = (ms) => new Promise((r) => { setTimeout(r, ms); });
74
+
75
+ /**
76
+ * @param {{ root: string, home?: string, skipMonthly?: boolean, loadEnv: () => { ok: boolean, env: Record<string, string|undefined>, refusal: string|null }, bin?: string }} opts
77
+ * `loadEnv` is the keys-file door (`keysForDoor`): called before EVERY spawn and every reply that quotes a log, so editing
78
+ * the file needs no restart. Its `env` is BOTH the child's spawn env AND the scrub list (POC (a), M4d wiring rule).
79
+ */
80
+ export function createAuthor(opts) {
81
+ const {
82
+ root, loadEnv, home, skipMonthly = false, bin = BIN,
83
+ } = opts;
84
+ // the ONE run-start path (sign and run both end in `starter.start`) and the Run-a-signed-flow door built on it
85
+ const starter = createStarter({ root, bin });
86
+ const flowsDoor = createFlowsDoor({
87
+ root, home, skipMonthly, loadEnv, starter, monthlyClaim: (usd) => monthlyClaim(usd),
88
+ });
89
+
90
+ /** The ONE monthly check, defined below (a function declaration, so the doors above may take it now). */
91
+ const resumeDoor = createResumeDoor({
92
+ root, loadEnv, monthlyClaim: (usd) => monthlyClaim(usd), starter,
93
+ });
94
+
95
+ /** The drafts folder's real path, or null when the flows root does not exist. */
96
+ const draftsDir = () => {
97
+ try { return join(realpathSync(root), PANEL_DRAFTS_DIR); } catch { return null; }
98
+ };
99
+
100
+ const readJson = readJsonFile;
101
+
102
+ /**
103
+ * The monthly room for a cap, from the ONE read-only check the CLI's door also decides on (`checkMonthlyRoom`, src/monthly.js).
104
+ * `null` when this process has no config home (the CLI skips its check there too); `{ problem }` when config.json cannot be read.
105
+ * @param {number} capUsd
106
+ */
107
+ function monthlyClaim(capUsd) {
108
+ if (skipMonthly) return null;
109
+ try { return checkMonthlyRoom({ capUsd, home }); } catch (e) {
110
+ if (e instanceof ConfigError) return { problem: e.message };
111
+ throw e;
112
+ }
113
+ }
114
+
115
+ /**
116
+ * The draft's state, READ from its files. `keys` = the provider key values to scrub from anything quoted.
117
+ * @param {string} dir the draft folder @param {string} id @param {string[]} keys
118
+ */
119
+ function readDraft(dir, id, keys) {
120
+ const card = readJson(dir, 'card.json');
121
+ const base = { draftId: id, card };
122
+ if (readJson(dir, 'abandoned.json')) return { ...base, phase: 'abandoned' };
123
+ const signed = readJson(dir, 'signed.json');
124
+ if (signed) return { ...base, phase: 'signed' };
125
+
126
+ const first = resultOf(dir, 'draft', keys);
127
+ if (first && first.phase === 'green') return withChanges(base, dir, first, keys);
128
+ if (first) return { ...base, ...first };
129
+ // no result yet: the child is the only thing that can still produce one
130
+ if (childRunning(dir)) return { ...base, phase: 'drafting' };
131
+ return { ...base, phase: 'stopped', say: logTail(dir, 'child.log', keys) || STOPPED_SAY };
132
+ }
133
+
134
+ /** The tail of a child's log, scrubbed and without its `fwdloop: ` prefix; '' when there is none. */
135
+ function logTail(dir, rel, keys) {
136
+ const logText = readFileInside(dir, rel);
137
+ return logText.ok ? scrub(logText.text, keys).trim().slice(-LOG_TAIL_CHARS).replace(/^fwdloop: /, '') : '';
138
+ }
139
+
140
+ /**
141
+ * One plan folder's result, READ from its files: green (spec.hash), red (a log that says not ok, or a leak marker), or null (no result yet).
142
+ * @param {string} dir the draft folder @param {string} rel `draft` or `draft-<n>` @param {string[]} keys
143
+ * @returns {any}
144
+ */
145
+ function resultOf(dir, rel, keys) {
146
+ const hashFile = readFileInside(dir, `${rel}/spec.hash`);
147
+ if (hashFile.ok && hashFile.text.trim() !== '') {
148
+ const readout = readFileInside(dir, `${rel}/readout.txt`);
149
+ const text = readout.ok ? scrub(readout.text, keys) : '';
150
+ return { phase: 'green', hash: hashFile.text.trim(), readout: text, readoutHeads: readoutHeadIndexes(text) };
151
+ }
152
+ const leak = readFileInside(dir, `${rel}/scrub-leak.red`);
153
+ const log = readJson(dir, `${rel}/log.json`);
154
+ if (leak.ok || (log && log.ok === false)) {
155
+ const reds = Array.isArray(log?.reds) ? log.reds.map((r) => scrub(String(r), keys)) : [];
156
+ if (leak.ok) reds.push(scrub(leak.text.trim(), keys));
157
+ return { phase: 'red', reds, say: RED_SAY };
158
+ }
159
+ return null;
160
+ }
161
+
162
+ /**
163
+ * A green first plan, plus its changes (amendment 3 item 3): the plan to sign is the NEWEST green of `draft`, `draft-1`, ...; a
164
+ * red or stopped change never replaces it. `phase` is `revising` only while the newest change's child runs. One reader of every
165
+ * change fact: the notes (`note-<n>.txt`), each change's own folder and log, and how many changes are used (their folders).
166
+ * @param {any} base @param {string} dir @param {{ hash: string, readout: string, readoutHeads?: number[] }} first @param {string[]} keys
167
+ */
168
+ function withChanges(base, dir, first, keys) {
169
+ const names = readdirInside(dir, '.');
170
+ const noteNs = names.map((n) => NOTE_RE.exec(n)?.[1]).filter((x) => x !== undefined).map(Number).sort((a, b) => a - b);
171
+ const used = names.filter((n) => PLAN_DIR_RE.test(n)).length;
172
+ let plan = { rel: 'draft', ...first };
173
+ let running = false;
174
+ const notes = noteNs.map((n, i) => {
175
+ const text = readFileInside(dir, `note-${n}.txt`);
176
+ const entry = { n, text: text.ok ? scrub(text.text, keys) : '' };
177
+ const res = resultOf(dir, `draft-${n}`, keys);
178
+ if (res && res.phase === 'green') { plan = { rel: `draft-${n}`, ...res }; return { ...entry, phase: 'green', hash: res.hash, left: Math.max(0, MAX_CHANGES - (i + 1)) }; }
179
+ if (res) return { ...entry, phase: 'red', reds: res.reds, say: CHANGE_RED_SAY };
180
+ if (i === noteNs.length - 1 && childRunning(dir)) { running = true; return { ...entry, phase: 'running' }; }
181
+ return { ...entry, phase: 'stopped', say: logTail(dir, `revise-${n}.log`, keys) || STOPPED_SAY };
182
+ });
183
+ return {
184
+ ...base, phase: running ? 'revising' : 'green', hash: plan.hash, readout: plan.readout, readoutHeads: plan.readoutHeads, plan: plan.rel, changesLeft: Math.max(0, MAX_CHANGES - used), notes,
185
+ };
186
+ }
187
+
188
+ /** Draft ids, newest first. */
189
+ const listIds = () => {
190
+ const d = draftsDir();
191
+ return d === null ? [] : readdirInside(d, '.').filter((n) => ID_RE.test(n)).sort().reverse();
192
+ };
193
+
194
+ const view = (id, keys) => {
195
+ const d = draftsDir();
196
+ return d === null ? null : readDraft(join(d, id), id, keys);
197
+ };
198
+
199
+ /** The one request-time read of the keys door: the merged env (scrub list + child env) or null on its refusal. */
200
+ const keysNow = () => {
201
+ const loaded = loadEnv();
202
+ return { loaded, keys: providerKeys(loaded.env) };
203
+ };
204
+
205
+ /**
206
+ * The one reader both sign calls share: a well-formed id, a readable draft, phase `green` (so not abandoned, signed, red,
207
+ * drafting or stopped), and the flow name from its own `target.json`.
208
+ * @param {string} id
209
+ */
210
+ function greenDraft(id) {
211
+ const no = (status, refused, say) => ({ ok: false, reply: { status, body: { ok: false, refused, ...(say ? { say } : {}) } } });
212
+ if (!ID_RE.test(id)) return no(404, 'no-such-draft');
213
+ const dd = draftsDir();
214
+ const dir = dd === null ? null : join(dd, id);
215
+ const v = dir === null ? null : readDraft(dir, id, keysNow().keys);
216
+ if (dir === null || v === null || v.card === null) return no(404, 'no-such-draft');
217
+ if (v.phase !== 'green') return no(409, 'not-green', `This draft is ${v.phase}, not a finished plan, so it cannot be signed.`);
218
+ const name = readJson(dir, `${v.plan}/target.json`)?.name;
219
+ if (typeof name !== 'string') return no(409, 'no-name', 'The draft has no readable flow name. Nothing was signed.');
220
+ return {
221
+ ok: true, v: /** @type {any} */ (v), name, dir,
222
+ };
223
+ }
224
+
225
+ return {
226
+ flows: flowsDoor.flows,
227
+ runAgain: flowsDoor.runAgain,
228
+ run: flowsDoor.run,
229
+ runPrepare: flowsDoor.runPrepare,
230
+ resumePrepare: resumeDoor.prepare,
231
+ resumeForm: resumeDoor.form,
232
+ resume: resumeDoor.resume,
233
+
234
+ /**
235
+ * `GET /api/author/monthly-check?cap=<usd>`: the note under Cap, one read-only check. `{ text, red }` is what to show (red =
236
+ * the cap does not fit this month); `floorUsd` is the smallest cap that funds one round of a model step, for the page's
237
+ * `needs at least $X per run` line. A cap that is not a number above 0 gets no note. Never spends, never writes.
238
+ * @param {unknown} cap @param {string|null} [spent] what a resumed run has already spent (amendment 4 item 4)
239
+ */
240
+ monthlyCheck(cap, spent = null) {
241
+ const n = Number(cap);
242
+ const floorUsd = capFloorUsd('x');
243
+ if (typeof cap !== 'string' || cap.trim() === '' || !Number.isFinite(n) || n <= 0) return { status: 200, body: { ok: true, text: '', red: false, floorUsd, floorText: capFloorText(floorUsd) } };
244
+ // 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
245
+ // what is spent says so in the door's own words (red)
246
+ const spentUsd = typeof spent === 'string' && spent.trim() !== '' && Number.isFinite(Number(spent)) && Number(spent) > 0 ? Number(spent) : 0;
247
+ if (spentUsd > 0 && n <= spentUsd + 1e-9) {
248
+ 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) } };
249
+ }
250
+ const claim = monthlyClaim(n - spentUsd);
251
+ if (claim === null || 'problem' in claim) return { status: 200, body: { ok: true, text: '', red: false, floorUsd, floorText: capFloorText(floorUsd) } };
252
+ return { status: 200, body: { ok: true, ...monthlyNote(claim), floorUsd, floorText: capFloorText(floorUsd) } };
253
+ },
254
+
255
+ /** `GET /api/author/start/:startId`: the start's phase, read from its files. @param {string} id */
256
+ startGet(id) { return starter.get(id, keysNow().keys); },
257
+
258
+ /** `POST /api/author/start/:startId/clear`: dismiss a refused start. @param {string} id */
259
+ startClear(id) { return starter.clear(id, keysNow().keys); },
260
+
261
+ /**
262
+ * `POST /api/author/draft`: card -> $0 checks -> one detached `fwdloop draft` -> 202 { draftId }. Nothing is created
263
+ * on a refusal. Synchronous on purpose (see the file header).
264
+ * @param {any} body
265
+ * @returns {{ status: number, body: any }}
266
+ */
267
+ start(body) {
268
+ const { loaded, keys } = keysNow();
269
+ if (!loaded.ok) return { status: 409, body: { ok: false, refused: 'keys-file', say: String(loaded.refusal) } };
270
+ const dd = draftsDir();
271
+ if (dd === null) return { status: 400, body: { ok: false, refused: 'root', say: 'The flows folder this panel serves does not exist.' } };
272
+ const card = cardFields(body);
273
+ const checked = checkCard(card, { root: realpathSync(root), env: loaded.env });
274
+ if (!checked.ok) return { status: 400, body: { ok: false, refused: 'card', refusals: checked.refusals } };
275
+ // 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)
276
+ const claim = monthlyClaim(Number(card.capUsd));
277
+ if (claim && 'problem' in claim) return { status: 409, body: { ok: false, refused: 'monthly', say: `${claim.problem} — refusing rather than guess the monthly limit. Nothing spent.` } };
278
+ if (claim && !claim.ok) return { status: 400, body: { ok: false, refused: 'card', refusals: [{ field: 'capUsd', say: monthlyRefusalText(claim.room) }] } };
279
+ for (const id of listIds()) {
280
+ const v = view(id, keys);
281
+ if (v && (v.phase === 'drafting' || v.phase === 'revising')) {
282
+ return { status: 409, body: { ok: false, refused: 'draft-live', draftId: id, say: 'A draft is already running. Wait for it, or abandon it, before starting another.' } };
283
+ }
284
+ }
285
+ const id = newId();
286
+ const dir = join(dd, id);
287
+ mkdirSync(dd, { recursive: true, mode: 0o700 });
288
+ mkdirSync(dir, { mode: 0o700 });
289
+ const proseFile = join(dir, 'prose.txt');
290
+ writeFileSync(join(dir, 'card.json'), `${JSON.stringify(card, null, 2)}\n`, { mode: 0o600 });
291
+ writeFileSync(proseFile, checked.prose, { mode: 0o600 });
292
+ let child;
293
+ try {
294
+ child = spawnDetached({
295
+ bin, argv: ['draft', proseFile, '--out', join(dir, 'draft'), '--root', realpathSync(root), '--name', card.flowName], env: loaded.env, logPath: join(dir, 'child.log'),
296
+ });
297
+ } catch (e) {
298
+ return { status: 500, body: { ok: false, refused: 'spawn', say: `The draft could not be started (${/** @type {any} */ (e)?.code ?? 'error'}). Nothing was spent.`, draftId: id } };
299
+ }
300
+ child.on('error', () => {}); // a later spawn failure leaves no pid-backed child: the draft then reads as stopped
301
+ writePidFile(dir, child);
302
+ return { status: 202, body: { ok: true, draftId: id } };
303
+ },
304
+
305
+ /**
306
+ * `POST /api/author/:id/sign-prepare` (the first click of "Sign & run"): what the human is about to sign — the readout, the
307
+ * hash, the flow name, the cap. GREEN drafts only. Writes nothing: the page holds the hash it was shown, and `sign`
308
+ * re-reads everything from disk.
309
+ * @param {string} id
310
+ */
311
+ signPrepare(id) {
312
+ const seen = greenDraft(id);
313
+ if (!seen.ok) return seen.reply;
314
+ return {
315
+ status: 200,
316
+ body: {
317
+ ok: true, draftId: id, hash: seen.v.hash, flowName: seen.name, capUsd: seen.v.card.capUsd, readout: seen.v.readout, runId: nextRunId(join(root, seen.name)),
318
+ },
319
+ };
320
+ },
321
+
322
+ /**
323
+ * `POST /api/author/:id/sign` body `{ hash, runId? }`: sign and start the run — only when the draft is green and
324
+ * not abandoned/signed and the hash is the one on disk (M4e amendment 2: the second click, no typed name). Then the SAME `signDraft` as `fwdloop sign`, `signed.json`, and the ONE run start. Any mismatch
325
+ * refuses by name, signs nothing, writes nothing, spends nothing. Fully synchronous (no await between the checks and the
326
+ * writes), so two sign POSTs together sign once: the second reads the first's `signed.json` and is refused.
327
+ * @param {string} id @param {any} body
328
+ */
329
+ sign(id, body) {
330
+ const { loaded } = keysNow();
331
+ if (!loaded.ok) return { status: 409, body: { ok: false, refused: 'keys-file', say: String(loaded.refusal) } };
332
+ const seen = greenDraft(id);
333
+ if (!seen.ok) return seen.reply;
334
+ const { v, name, dir } = seen;
335
+ const b = body && typeof body === 'object' ? body : {};
336
+ // 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)
337
+ const floor = capFloorUsd(typeof v.card.job === 'string' ? v.card.job : '');
338
+ if (Number(v.card.capUsd) < floor) return { status: 400, body: { ok: false, refused: 'cap-too-small', say: capFloorText(floor) } };
339
+ if (typeof b.hash !== 'string' || b.hash !== v.hash) {
340
+ 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.' } };
341
+ }
342
+ // everything the run needs is checked BEFORE signing, so a refusal never leaves a signed flow with no run
343
+ const inputs = parseInputLines(typeof v.card.inputs === 'string' ? v.card.inputs : '');
344
+ const bad = checkInputRows(inputs);
345
+ if (bad.length > 0) return { status: 400, body: { ok: false, refused: 'inputs', refusals: bad } };
346
+ // '' = no typed id: the start claims the next `run-<n>` (M4e amendment 3); a typed one is checked here, before signing
347
+ const runId = typeof b.runId === 'string' ? b.runId : '';
348
+ if (runId !== '') {
349
+ const run = starter.checkRun(name, runId);
350
+ if (!run.ok) return { status: 400, body: { ok: false, refused: 'run-id', say: run.say } };
351
+ }
352
+ const signedBy = userInfo().username;
353
+ const result = signDraft({
354
+ dir: join(dir, v.plan), approve: v.hash, signedBy, env: loaded.env, sessionDir: dir,
355
+ });
356
+ if (!result.ok) {
357
+ const keys = providerKeys(loaded.env);
358
+ return { status: 409, body: { ok: false, refused: 'sign-refused', say: 'The draft did not pass the signing checks. Nothing was signed.', reds: result.reds.map((r) => scrub(String(r), keys)) } };
359
+ }
360
+ writeFileSync(join(dir, 'signed.json'), `${JSON.stringify({
361
+ at: new Date().toISOString(), signedBy, hash: v.hash, flow: name, runId: runId === '' ? null : runId,
362
+ })}\n`, { mode: 0o600 });
363
+ const started = starter.start({
364
+ kind: 'sign', flow: name, runId, sources: inputs.map((r) => ({ role: r.role, path: r.path })),
365
+ }, loaded.env);
366
+ 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".` } };
367
+ return { status: 202, body: { ...started.body, signed: true } };
368
+ },
369
+
370
+ /**
371
+ * `POST /api/author/:id/revise` body `{ text }` (M4e amendment 3 item 3, bareloop's "Ask for a change"): the human's note on a GREEN
372
+ * plan -> $0 checks -> one detached `fwdloop draft --revise-from <current plan> --note note-<n>.txt --out draft-<n>` -> 202. Up to
373
+ * MAX_CHANGES per draft; a refusal makes no model call and writes nothing. The new plan is read back from `draft-<n>/` like any
374
+ * draft; the old plan stays signable until a newer green one exists. Synchronous, like `start`.
375
+ * @param {string} id @param {any} body
376
+ */
377
+ revise(id, body) {
378
+ const { loaded, keys } = keysNow();
379
+ if (!loaded.ok) return { status: 409, body: { ok: false, refused: 'keys-file', say: String(loaded.refusal) } };
380
+ if (!ID_RE.test(id)) return { status: 404, body: { ok: false, refused: 'no-such-draft' } };
381
+ const dd = draftsDir();
382
+ const dir = dd === null ? null : join(dd, id);
383
+ const v = dir === null ? null : /** @type {any} */ (readDraft(dir, id, keys));
384
+ if (dir === null || v === null || v.card === null) return { status: 404, body: { ok: false, refused: 'no-such-draft' } };
385
+ if (v.phase === 'revising') return { status: 409, body: { ok: false, refused: 'draft-live', say: 'A change is already being drafted. Wait for it.' } };
386
+ if (v.phase !== 'green') return { status: 409, body: { ok: false, refused: 'not-green', say: `This draft is ${v.phase}, not a finished plan, so it cannot be changed.` } };
387
+ if (v.changesLeft <= 0) return { status: 409, body: { ok: false, refused: 'no-changes-left', say: `This draft has used its ${MAX_CHANGES} changes. Sign it, abandon it, or edit the card and draft again.` } };
388
+ if (childRunning(dir)) return { status: 409, body: { ok: false, refused: 'draft-live', say: 'The draft process is still finishing. Try again in a moment.' } };
389
+ const text = body && typeof body.text === 'string' ? body.text.trim() : '';
390
+ if (text === '') return { status: 400, body: { ok: false, refused: 'note-empty', say: 'Write what you want changed first. Nothing was sent.' } };
391
+ if (text.length > NOTE_MAX_CHARS) return { status: 400, body: { ok: false, refused: 'note-long', say: `The note is longer than ${NOTE_MAX_CHARS} characters. Shorten it. Nothing was sent.` } };
392
+ if (textHasKey(text, loaded.env)) return { status: 400, body: { ok: false, refused: 'note-key', say: 'This note contains an API key. Keys go in Settings only. Nothing was saved or sent.' } };
393
+ for (const other of listIds()) {
394
+ if (other === id) continue;
395
+ const ov = view(other, keys);
396
+ if (ov && (ov.phase === 'drafting' || ov.phase === 'revising')) {
397
+ return { status: 409, body: { ok: false, refused: 'draft-live', draftId: other, say: 'A draft is already running. Wait for it, or abandon it, before asking for a change.' } };
398
+ }
399
+ }
400
+ const n = Math.max(0, ...v.notes.map((x) => x.n)) + 1;
401
+ const noteFile = join(dir, `note-${n}.txt`);
402
+ writeFileSync(noteFile, `${text}\n`, { mode: 0o600, flag: 'wx' });
403
+ let child;
404
+ try {
405
+ child = spawnDetached({
406
+ bin,
407
+ argv: ['draft', join(dir, 'prose.txt'), '--out', join(dir, `draft-${n}`), '--root', dirname(/** @type {string} */ (dd)), '--name', v.card.flowName, '--revise-from', join(dir, v.plan), '--note', noteFile],
408
+ env: loaded.env,
409
+ logPath: join(dir, `revise-${n}.log`),
410
+ });
411
+ } catch (e) {
412
+ return { status: 500, body: { ok: false, refused: 'spawn', say: `The change could not be started (${/** @type {any} */ (e)?.code ?? 'error'}). Nothing was spent.`, draftId: id } };
413
+ }
414
+ child.on('error', () => {});
415
+ writePidFile(dir, child);
416
+ return { status: 202, body: { ok: true, draftId: id, n } };
417
+ },
418
+
419
+ /**
420
+ * `GET /api/author/live`: the newest draft that is not abandoned or signed, and the newest panel start the human has not cleared
421
+ * (`starting` or `refused`; a `started` one is in Runs) — read from files, never memory.
422
+ */
423
+ live() {
424
+ const { keys } = keysNow();
425
+ /** @type {any} */
426
+ let draft = null;
427
+ for (const id of listIds()) {
428
+ const v = view(id, keys);
429
+ if (v && !FINISHED.has(v.phase)) draft = v;
430
+ break; // only the NEWEST draft can be the card's: an older one was replaced by it
431
+ }
432
+ return { status: 200, body: { ok: true, draft, start: starter.newestOpen(keys) } };
433
+ },
434
+
435
+ /** `GET /api/author/:id`. @param {string} id */
436
+ get(id) {
437
+ if (!ID_RE.test(id)) return { status: 404, body: { ok: false, refused: 'no-such-draft' } };
438
+ const { keys } = keysNow();
439
+ const v = view(id, keys);
440
+ if (v === null || v.card === null) return { status: 404, body: { ok: false, refused: 'no-such-draft' } };
441
+ return { status: 200, body: { ok: true, ...v } };
442
+ },
443
+
444
+ /**
445
+ * `POST /api/author/:id/abandon`: stop the child (by its recorded pid, only after `isFwdloopAlive` says it is ours),
446
+ * confirm it is gone, then write `abandoned.json`. No further model call; the spend already booked stays booked.
447
+ * @param {string} id
448
+ */
449
+ async abandon(id) {
450
+ if (!ID_RE.test(id)) return { status: 404, body: { ok: false, refused: 'no-such-draft' } };
451
+ const dd = draftsDir();
452
+ const dir = dd === null ? null : join(dd, id);
453
+ const { keys } = keysNow();
454
+ const v = dir === null ? null : readDraft(dir, id, keys);
455
+ if (dir === null || v === null || v.card === null) return { status: 404, body: { ok: false, refused: 'no-such-draft' } };
456
+ if (FINISHED.has(v.phase)) return { status: 409, body: { ok: false, refused: 'not-abandonable', say: `This draft is already ${v.phase}.` } };
457
+ const pid = readJson(dir, 'pid.json');
458
+ let killed = false;
459
+ if (pid && Number.isInteger(pid.pid)) {
460
+ const procStart = typeof pid.procStart === 'string' ? pid.procStart : null;
461
+ const alive = isFwdloopAlive(pid.pid, procStart);
462
+ if (alive === null) return { status: 409, body: { ok: false, refused: 'cannot-tell', say: 'The panel cannot tell whether the draft process is still running, so it did not stop anything.' } };
463
+ if (alive === true) {
464
+ // the child leads its own process group (detached), so one signal to the group reaches it and nothing else
465
+ for (const { sig, wait } of [{ sig: 'SIGTERM', wait: KILL_WAIT_MS }, { sig: 'SIGKILL', wait: KILL_HARD_WAIT_MS }]) {
466
+ try { process.kill(-pid.pid, /** @type {NodeJS.Signals} */ (sig)); } catch { /* already gone */ }
467
+ const t0 = Date.now();
468
+ // eslint-disable-next-line no-await-in-loop
469
+ while (isFwdloopAlive(pid.pid, procStart) === true && Date.now() - t0 < wait) await sleep(25);
470
+ if (isFwdloopAlive(pid.pid, procStart) !== true) break;
471
+ }
472
+ if (isFwdloopAlive(pid.pid, procStart) === true) {
473
+ return { status: 500, body: { ok: false, refused: 'still-running', say: 'The draft process did not stop. Nothing was marked abandoned.' } };
474
+ }
475
+ killed = true;
476
+ }
477
+ }
478
+ writeFileSync(join(dir, 'abandoned.json'), `${JSON.stringify({ at: new Date().toISOString(), killed, phaseWas: v.phase })}\n`, { mode: 0o600 });
479
+ return { status: 200, body: { ok: true, phase: 'abandoned', stopped: killed } };
480
+ },
481
+ };
482
+ }