fwdloop 0.13.0 → 0.15.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.
@@ -13,9 +13,10 @@
13
13
  // child.log the child's stdout+stderr, mode 0600 (quoted to the page only after `scrub`)
14
14
  // pid.json { pid, procStart } written right after the spawn; the ONE liveness fact (`isFwdloopAlive`, M4c)
15
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 ...
16
+ // card-<n>.json the card as the human submitted it for revise <n> (M4e amendment 14 item 2), written by `revise`, write-once ('wx'), never a key
17
+ // prose-<n>.txt the prose file built from card-<n>.json (the ONE `cardToProse`); the model gets this card only, never the old plan
18
+ // draft-<n>/ the CLI's output for revise <n> (`fwdloop draft prose-<n>.txt --out draft-<n>`, a plain fresh draft): its own full draft dir;
19
+ // `revise-<n>.log` is that child's log. The plan to sign is the NEWEST of draft, draft-1, ... and only if it is green (`withRevises`).
19
20
  // abandoned.json written by Abandon, after the child is gone
20
21
  // signed.json written by `sign` (piece 2b) right after `signDraft` succeeds; the phase reader reads it
21
22
  //
@@ -27,13 +28,15 @@
27
28
  // write pid.json, no await between), so two requests that arrive together run one after the other and the second
28
29
  // sees the first's live child and is refused. A dead child never blocks (its pid is read, never assumed).
29
30
  import { randomBytes } from 'node:crypto';
30
- import { mkdirSync, realpathSync, writeFileSync } from 'node:fs';
31
+ import {
32
+ mkdirSync, realpathSync, rmSync, writeFileSync,
33
+ } from 'node:fs';
31
34
  import { userInfo } from 'node:os';
32
35
  import { dirname, join } from 'node:path';
33
36
  import { fileURLToPath } from 'node:url';
34
37
 
35
38
  import {
36
- PANEL_DRAFTS_DIR, readoutHeadIndexes, scrub, signDraft, textHasKey,
39
+ ANSWER_FILE, NOT_CHECKED_FILE, OPEN_QUESTION_SAY, PANEL_DRAFTS_DIR, readQuestions, readoutHeadIndexes, scrub, signDraft,
37
40
  } from '../authoring.js';
38
41
  import { nextRunId, readFileInside, readdirInside } from '../flow.js';
39
42
  import { isFwdloopAlive } from '../liveness.js';
@@ -41,20 +44,23 @@ import {
41
44
  checkMonthlyRoom, ConfigError, monthlyNote, monthlyRefusalText,
42
45
  } from '../monthly.js';
43
46
  import {
44
- capFloorText, capFloorUsd, cardFields, checkCard, checkInputRows, parseInputLines,
47
+ appendAnswersToJob, capFloorText, capFloorUsd, cardFields, checkCard, checkInputRows, parseInputLines, parseJobBox,
45
48
  } from './authorcard.js';
49
+ import { checkedLines, notCheckedBlock } from '../checked.js';
50
+ import { parseSignedText } from '../signed-text.js';
46
51
  import { leastResumeCapUsd } from './authorvalues.js';
47
52
  import { createFlowsDoor } from './authorflows.js';
48
53
  import { createResumeDoor } from './authorresume.js';
49
54
  import { createStarter } from './authorstart.js';
50
55
  import {
51
- childRunning, providerKeys, readJsonFile, spawnDetached, writePidFile,
56
+ childRunning as childRunningNow, providerKeys, readJsonFile, spawnDetached, writePidFile,
52
57
  } from './spawn.js';
53
58
 
54
59
  const HERE = dirname(fileURLToPath(import.meta.url));
55
60
  const BIN = join(HERE, '..', '..', 'bin', 'fwdloop');
56
61
 
57
62
  /** A draft id: `d-` + the start time in base 36 (so ids sort oldest to newest) + 4 random hex. */
63
+ const STARTED_OVER_FILE = 'started-over-from.json';
58
64
  const ID_RE = /^d-[0-9a-z]{10}-[0-9a-f]{4}$/;
59
65
  const newId = () => `d-${Date.now().toString(36).padStart(10, '0')}-${randomBytes(2).toString('hex')}`;
60
66
  /** 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). */
@@ -62,24 +68,29 @@ const FINISHED = new Set(['abandoned', 'signed']);
62
68
  const LOG_TAIL_CHARS = 1500;
63
69
  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
70
  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$/;
71
+ /** Up to 2 revises per draft (amendment 14 item 3); a revise is used once its `draft-<n>/` exists (a refusal at $0 makes none). */
72
+ export const MAX_REVISES = 2;
73
+ const CARD_RE = /^card-(\d+)\.json$/;
74
+ /** The phases in which a draft child is running (a first draft, a revise, or the redraft after the human's answers). */
75
+ const LIVE_PHASES = new Set(['drafting', 'revising', 'redrafting']);
76
+ const ANSWERS_NOT_DRAFTED_SAY = 'Your answers are saved, but the plan was not drafted again with them (the process did not start). Nothing was signed. Draft again from the card.';
77
+ const REDRAFT_RED_SAY = 'The plan drafted with your answers did not pass the checks. Nothing can be signed until a plan is green. Your answers are kept in the card: change it and draft again.';
78
+ const BLANK_ANSWER_SAY = 'Write an answer. A question can\'t be skipped; the plan waits for it.';
79
+ const ONE_LINE_ANSWER_SAY = 'Write the answer on one line. It is added to your job as one guardrail line.';
69
80
  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.';
81
+ const REVISE_RED_SAY = 'The revised plan did not pass the checks. Nothing can be signed until a plan is green. Your edits are kept: change the card and draft again.';
71
82
  const KILL_WAIT_MS = 3000;
72
83
  const KILL_HARD_WAIT_MS = 2000;
73
84
  const sleep = (ms) => new Promise((r) => { setTimeout(r, ms); });
74
85
 
75
86
  /**
76
- * @param {{ root: string, home?: string, skipMonthly?: boolean, loadEnv: () => { ok: boolean, env: Record<string, string|undefined>, refusal: string|null }, bin?: string }} opts
87
+ * @param {{ root: string, home?: string, skipMonthly?: boolean, loadEnv: () => { ok: boolean, env: Record<string, string|undefined>, refusal: string|null }, bin?: string, childRunning?: (dir: string) => boolean }} opts
77
88
  * `loadEnv` is the keys-file door (`keysForDoor`): called before EVERY spawn and every reply that quotes a log, so editing
78
89
  * the file needs no restart. Its `env` is BOTH the child's spawn env AND the scrub list (POC (a), M4d wiring rule).
79
90
  */
80
91
  export function createAuthor(opts) {
81
92
  const {
82
- root, loadEnv, home, skipMonthly = false, bin = BIN,
93
+ root, loadEnv, home, skipMonthly = false, bin = BIN, childRunning = childRunningNow,
83
94
  } = opts;
84
95
  // the ONE run-start path (sign and run both end in `starter.start`) and the Run-a-signed-flow door built on it
85
96
  const starter = createStarter({ root, bin });
@@ -123,11 +134,15 @@ export function createAuthor(opts) {
123
134
  const signed = readJson(dir, 'signed.json');
124
135
  if (signed) return { ...base, phase: 'signed' };
125
136
 
137
+ // C9: ask "is it still running" FIRST, then read the result. A child that finishes between the two reads is then seen as finished
138
+ // with its result on disk; the other order could see no result, then no child, and call a finished draft stopped.
139
+ const running = childRunning(dir);
126
140
  const first = resultOf(dir, 'draft', keys);
127
- if (first && first.phase === 'green') return withChanges(base, dir, first, keys);
141
+ // a first plan that asked questions (green or red) is read by `withRevises` too: it is the ONE function that decides the phase of every plan
142
+ if (first && (first.phase === 'green' || readQuestions(join(dir, 'draft')).questions.length > 0)) return withRevises(base, dir, first, keys);
128
143
  if (first) return { ...base, ...first };
129
144
  // no result yet: the child is the only thing that can still produce one
130
- if (childRunning(dir)) return { ...base, phase: 'drafting' };
145
+ if (running) return { ...base, phase: 'drafting' };
131
146
  return { ...base, phase: 'stopped', say: logTail(dir, 'child.log', keys) || STOPPED_SAY };
132
147
  }
133
148
 
@@ -160,29 +175,72 @@ export function createAuthor(opts) {
160
175
  }
161
176
 
162
177
  /**
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
178
+ * A first plan (green, or red with questions), plus its revises and answer redrafts (amendments 14, 24). The ONE function that decides
179
+ * what is signable and what phase a draft is in: the plan to look at is the NEWEST of `draft`, `draft-1`, ...; it is signable ONLY if it is
180
+ * green AND has no question open. A newest plan with an unanswered question is `questions-open` (nothing is signable, a reload keeps it open).
181
+ * A red or stopped newest plan means nothing is signable (an older green plan was drafted from a different card), and the card shown is the one
182
+ * last submitted. `phase` is `revising` / `redrafting` only while the newest plan's child runs. A revise uses one of the 2; an answer redraft
183
+ * (marked by `redraft-<n>.json`) uses none. One reader of every such fact: each `card-<n>.json`, its folder and log, its questions and answers.
184
+ * @param {any} base @param {string} dir @param {any} first the first plan's result (green, or red that asked questions) @param {string[]} keys
167
185
  */
168
- function withChanges(base, dir, first, keys) {
186
+ function withRevises(base, dir, first, keys) {
169
187
  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) : '' };
188
+ const ns = names.map((n) => CARD_RE.exec(n)?.[1]).filter((x) => x !== undefined).map(Number).sort((a, b) => a - b);
189
+ const redrafts = new Set(ns.filter((n) => readJson(dir, `redraft-${n}.json`) !== null));
190
+ const used = names.filter((n) => PLAN_DIR_RE.test(n) && !redrafts.has(Number(PLAN_DIR_RE.exec(n)?.[1]))).length;
191
+ const revisesLeft = Math.max(0, MAX_REVISES - used);
192
+ const newest = ns.length > 0 ? ns[ns.length - 1] : 0;
193
+ const card = newest > 0 ? (readJson(dir, `card-${newest}.json`) ?? base.card) : base.card;
194
+ const revises = ns.map((n) => {
195
+ const kind = redrafts.has(n) ? 'answers' : 'revise';
196
+ const running = n === newest && childRunning(dir); // C9: running first, then the result
177
197
  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 };
198
+ if (res && res.phase === 'green') return { n, kind, phase: 'green', hash: res.hash };
199
+ if (res) return { n, kind, phase: 'red', reds: res.reds, say: kind === 'answers' ? REDRAFT_RED_SAY : REVISE_RED_SAY };
200
+ if (running) return { n, kind, phase: 'running' };
201
+ return { n, kind, phase: 'stopped', say: logTail(dir, `${kind === 'answers' ? 'redraft' : 'revise'}-${n}.log`, keys) || STOPPED_SAY };
182
202
  });
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
- };
203
+ const cur = /** @type {{ phase: string, kind: string, say?: string }} */ (newest > 0 ? revises[revises.length - 1] : { phase: first.phase, kind: 'first' });
204
+ const shared = { ...base, card, revises, revisesLeft };
205
+ const rel = newest > 0 ? `draft-${newest}` : 'draft';
206
+ if (cur.phase === 'running') return { ...shared, phase: cur.kind === 'answers' ? 'redrafting' : 'revising' };
207
+ if (cur.phase === 'stopped') return { ...shared, phase: 'stopped', say: cur.say };
208
+ const res = newest > 0 ? resultOf(dir, rel, keys) : first;
209
+ // the plan's questions: any open one makes the phase `questions-open`, whatever colour the plan is (the answers are what it was waiting for)
210
+ const q = readQuestions(join(dir, rel));
211
+ if (q.open.length > 0) {
212
+ const lineText = (line) => parseJobBox(typeof card?.job === 'string' ? card.job : '').steps[line - 1]?.text ?? null;
213
+ 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 }));
214
+ return { ...shared, phase: 'questions-open', plan: rel, questions, openK: q.open[0].k, total: q.questions.length };
215
+ }
216
+ if (q.questions.length > 0) return { ...shared, phase: 'stopped', say: ANSWERS_NOT_DRAFTED_SAY };
217
+ if (res.phase === 'green') {
218
+ const answers = newest > 0 && redrafts.has(newest) ? answersOf(dir, newest, keys) : [];
219
+ return { ...shared, phase: 'green', hash: res.hash, readout: res.readout, readoutHeads: res.readoutHeads, plan: rel, answers, ...planChecks(dir, rel) };
220
+ }
221
+ return { ...shared, phase: 'red', reds: res.reds, say: newest === 0 ? RED_SAY : cur.say };
222
+ }
223
+
224
+ /**
225
+ * What the human is shown beside a green plan at sign: "Checked" (built by `checkedLines` from the plan's typed closes, never model text) and
226
+ * "Not checked" (the drafter's own list, always with its label). Read-only; neither is signed or in the hash. @param {string} dir @param {string} rel
227
+ */
228
+ function planChecks(dir, rel) {
229
+ const decl = readJson(dir, `${rel}/declaration.json`);
230
+ const prose = readFileInside(dir, `${rel}/prose.txt`);
231
+ const parsed = prose.ok ? parseSignedText(prose.text) : null;
232
+ const opts = parsed?.ok === true ? { askLines: parsed.arbiter.asks.map((x) => x.line) } : { hasAsk: true };
233
+ return { checked: checkedLines(decl, opts), notChecked: notCheckedBlock(readJson(dir, `${rel}/${NOT_CHECKED_FILE}`)?.notChecked) };
234
+ }
235
+
236
+ /** The answers an answer-redraft was drafted with, as the marker recorded them: `[{ line, lineText, question, answer }]` (scrubbed). @param {string} dir @param {number} n @param {string[]} keys */
237
+ function answersOf(dir, n, keys) {
238
+ const rec = readJson(dir, `redraft-${n}.json`);
239
+ const card = readJson(dir, `card-${n}.json`);
240
+ const steps = parseJobBox(typeof card?.job === 'string' ? card.job : '').steps;
241
+ return (Array.isArray(rec?.answers) ? rec.answers : []).map((a) => ({
242
+ line: a.line, lineText: steps[a.line - 1]?.text ?? null, question: scrub(String(a.question), keys), answer: scrub(String(a.answer), keys),
243
+ }));
186
244
  }
187
245
 
188
246
  /** Draft ids, newest first. */
@@ -214,6 +272,8 @@ export function createAuthor(opts) {
214
272
  const dir = dd === null ? null : join(dd, id);
215
273
  const v = dir === null ? null : readDraft(dir, id, keysNow().keys);
216
274
  if (dir === null || v === null || v.card === null) return no(404, 'no-such-draft');
275
+ // amendments 24/25: a plan with a question open is never signed from here; signDraft refuses it again from the plan folder (the same check)
276
+ if (v.phase === 'questions-open') return no(409, 'question-open', OPEN_QUESTION_SAY);
217
277
  if (v.phase !== 'green') return no(409, 'not-green', `This draft is ${v.phase}, not a finished plan, so it cannot be signed.`);
218
278
  const name = readJson(dir, `${v.plan}/target.json`)?.name;
219
279
  if (typeof name !== 'string') return no(409, 'no-name', 'The draft has no readable flow name. Nothing was signed.');
@@ -222,6 +282,23 @@ export function createAuthor(opts) {
222
282
  };
223
283
  }
224
284
 
285
+ /**
286
+ * 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,
287
+ * every field), then the monthly room for its cap. `{ ok: true, card, prose }` or `{ ok: false, reply }`. Writes nothing.
288
+ * @param {any} body @param {{ ok: boolean, env: Record<string, string|undefined> }} loaded
289
+ * @returns {{ ok: true, card: any, prose: string }|{ ok: false, reply: { status: number, body: any } }}
290
+ */
291
+ function vetCard(body, loaded) {
292
+ const card = cardFields(body);
293
+ const checked = checkCard(card, { root: realpathSync(root), env: loaded.env });
294
+ if (!checked.ok) return { ok: false, reply: { status: 400, body: { ok: false, refused: 'card', refusals: checked.refusals } } };
295
+ // 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)
296
+ const claim = monthlyClaim(Number(card.capUsd));
297
+ 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.` } } };
298
+ if (claim && !claim.ok) return { ok: false, reply: { status: 400, body: { ok: false, refused: 'card', refusals: [{ field: 'capUsd', say: monthlyRefusalText(claim.room) }] } } };
299
+ return { ok: true, card, prose: checked.prose };
300
+ }
301
+
225
302
  return {
226
303
  flows: flowsDoor.flows,
227
304
  runAgain: flowsDoor.runAgain,
@@ -269,16 +346,12 @@ export function createAuthor(opts) {
269
346
  if (!loaded.ok) return { status: 409, body: { ok: false, refused: 'keys-file', say: String(loaded.refusal) } };
270
347
  const dd = draftsDir();
271
348
  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) }] } };
349
+ const vet = vetCard(body, loaded);
350
+ if (!vet.ok) return vet.reply;
351
+ const { card } = vet;
279
352
  for (const id of listIds()) {
280
353
  const v = view(id, keys);
281
- if (v && (v.phase === 'drafting' || v.phase === 'revising')) {
354
+ if (v && LIVE_PHASES.has(v.phase)) {
282
355
  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
356
  }
284
357
  }
@@ -288,7 +361,12 @@ export function createAuthor(opts) {
288
361
  mkdirSync(dir, { mode: 0o700 });
289
362
  const proseFile = join(dir, 'prose.txt');
290
363
  writeFileSync(join(dir, 'card.json'), `${JSON.stringify(card, null, 2)}\n`, { mode: 0o600 });
291
- writeFileSync(proseFile, checked.prose, { mode: 0o600 });
364
+ // amendment 14 item 6: a Start over names the draft it started over from; write-once, here only. An id that is not one of this panel's drafts is ignored.
365
+ const from = body?.startedOverFrom;
366
+ if (typeof from === 'string' && ID_RE.test(from) && listIds().includes(from)) {
367
+ writeFileSync(join(dir, STARTED_OVER_FILE), `${JSON.stringify({ startedOverFrom: from })}\n`, { mode: 0o600, flag: 'wx' });
368
+ }
369
+ writeFileSync(proseFile, vet.prose, { mode: 0o600 });
292
370
  let child;
293
371
  try {
294
372
  child = spawnDetached({
@@ -314,7 +392,7 @@ export function createAuthor(opts) {
314
392
  return {
315
393
  status: 200,
316
394
  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)),
395
+ 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)),
318
396
  },
319
397
  };
320
398
  },
@@ -350,8 +428,14 @@ export function createAuthor(opts) {
350
428
  if (!run.ok) return { status: 400, body: { ok: false, refused: 'run-id', say: run.say } };
351
429
  }
352
430
  const signedBy = userInfo().username;
431
+ // M6: a card that edits a signed job signs as a REPLACEMENT of that job, only at the signature hash it was opened at (the writer re-checks it)
432
+ const editOf = v.card.editOf && typeof v.card.editOf === 'object' ? v.card.editOf : null;
433
+ if (editOf !== null && editOf.flow !== name) return { status: 409, body: { ok: false, refused: 'edit-name', say: 'This draft edits another job than the name it was drafted under. Nothing was signed.' } };
434
+ // M6 amendments 1 and 3: a replacing sign is refused while a run of the job is running, waiting at its ask or starting (a stale page cannot get round the greyed button)
435
+ const editBlock = editOf !== null ? flowsDoor.editBlock(name) : null;
436
+ if (editBlock !== null) return { status: 409, body: { ok: false, refused: 'run-live', say: editBlock } };
353
437
  const result = signDraft({
354
- dir: join(dir, v.plan), approve: v.hash, signedBy, env: loaded.env, sessionDir: dir,
438
+ dir: join(dir, v.plan), approve: v.hash, signedBy, env: loaded.env, sessionDir: dir, replaces: editOf !== null ? { flowHash: String(editOf.flowHash) } : undefined,
355
439
  });
356
440
  if (!result.ok) {
357
441
  const keys = providerKeys(loaded.env);
@@ -368,54 +452,132 @@ export function createAuthor(opts) {
368
452
  },
369
453
 
370
454
  /**
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`.
455
+ * `POST /api/author/:id/revise` body = the card fields, as `POST /api/author/draft` takes them (M4e amendment 14): the human's edited
456
+ * card on a draft whose first plan was green -> the same $0 checks as a first draft -> `card-<n>.json` + `prose-<n>.txt` (write-once)
457
+ * -> one detached plain `fwdloop draft prose-<n>.txt --out draft-<n>` -> 202. The model gets the card only. Up to MAX_REVISES per
458
+ * draft; a refusal makes no model call and writes nothing. A body carrying a note (`text`/`note`) is refused: nothing the human types
459
+ * goes to the model as a note. Synchronous, like `start`.
375
460
  * @param {string} id @param {any} body
376
461
  */
377
462
  revise(id, body) {
378
463
  const { loaded, keys } = keysNow();
379
464
  if (!loaded.ok) return { status: 409, body: { ok: false, refused: 'keys-file', say: String(loaded.refusal) } };
380
465
  if (!ID_RE.test(id)) return { status: 404, body: { ok: false, refused: 'no-such-draft' } };
466
+ if (body && typeof body === 'object' && ('text' in body || 'note' in body)) {
467
+ return { status: 400, body: { ok: false, refused: 'note', say: 'A revise takes the card only; a note is not accepted. Edit the card fields and draft again. Nothing was sent.' } };
468
+ }
381
469
  const dd = draftsDir();
382
470
  const dir = dd === null ? null : join(dd, id);
383
471
  const v = dir === null ? null : /** @type {any} */ (readDraft(dir, id, keys));
384
472
  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.` } };
473
+ if (v.phase === 'revising' || v.phase === 'redrafting') return { status: 409, body: { ok: false, refused: 'draft-live', say: 'A plan is already being drafted. Wait for it.' } };
474
+ if (v.phase === 'questions-open') return { status: 409, body: { ok: false, refused: 'question-open', say: 'A question the plan raised is still open. Answer it first; it is not a revise.' } };
475
+ // only a draft whose first plan was green has revises (`withRevises` is the one reader that sets them)
476
+ 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.` } };
477
+ 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.` } };
388
478
  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.' } };
479
+ const vet = vetCard(body, loaded);
480
+ if (!vet.ok) return vet.reply;
393
481
  for (const other of listIds()) {
394
482
  if (other === id) continue;
395
483
  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.' } };
484
+ if (ov && LIVE_PHASES.has(ov.phase)) {
485
+ return { status: 409, body: { ok: false, refused: 'draft-live', draftId: other, say: 'A draft is already running. Wait for it, or abandon it, before revising.' } };
398
486
  }
399
487
  }
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' });
488
+ const n = Math.max(0, ...v.revises.map((x) => x.n)) + 1;
489
+ const proseFile = join(dir, `prose-${n}.txt`);
490
+ writeFileSync(join(dir, `card-${n}.json`), `${JSON.stringify(vet.card, null, 2)}\n`, { mode: 0o600, flag: 'wx' });
491
+ writeFileSync(proseFile, vet.prose, { mode: 0o600, flag: 'wx' });
403
492
  let child;
404
493
  try {
405
494
  child = spawnDetached({
406
495
  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],
496
+ argv: ['draft', proseFile, '--out', join(dir, `draft-${n}`), '--root', realpathSync(root), '--name', vet.card.flowName],
408
497
  env: loaded.env,
409
498
  logPath: join(dir, `revise-${n}.log`),
410
499
  });
411
500
  } 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 } };
501
+ return { status: 500, body: { ok: false, refused: 'spawn', say: `The revise could not be started (${/** @type {any} */ (e)?.code ?? 'error'}). Nothing was spent.`, draftId: id } };
413
502
  }
414
503
  child.on('error', () => {});
415
504
  writePidFile(dir, child);
416
505
  return { status: 202, body: { ok: true, draftId: id, n } };
417
506
  },
418
507
 
508
+ /**
509
+ * `POST /api/author/:id/answer` body `{ k, answer }` (M4e amendments 24, 25): the human's answer to the plan's question `k` of `n`, one at a time.
510
+ * A blank answer is refused and the question stays open; there is no skip. The answer is written ONCE ('wx') as `<plan>/answer-<k>.json`. After
511
+ * the LAST answer the plan is drafted again as a fresh plain `fwdloop draft --no-questions` child (it never asks), from the submitted card with
512
+ * each answer added word for word as a `~` guardrail under its line (the one `appendAnswersToJob`, then the one `cardToProse`). It is booked as
513
+ * an answer redraft (`redraft-<n>.json`), not a revise: it uses none of the 2. Synchronous, like `revise`; a refusal at $0 writes nothing.
514
+ * @param {string} id @param {any} body
515
+ */
516
+ answer(id, body) {
517
+ const { loaded, keys } = keysNow();
518
+ if (!loaded.ok) return { status: 409, body: { ok: false, refused: 'keys-file', say: String(loaded.refusal) } };
519
+ if (!ID_RE.test(id)) return { status: 404, body: { ok: false, refused: 'no-such-draft' } };
520
+ const dd = draftsDir();
521
+ const dir = dd === null ? null : join(dd, id);
522
+ const v = dir === null ? null : /** @type {any} */ (readDraft(dir, id, keys));
523
+ if (dir === null || v === null || v.card === null) return { status: 404, body: { ok: false, refused: 'no-such-draft' } };
524
+ if (v.phase !== 'questions-open') return { status: 409, body: { ok: false, refused: 'no-question-open', say: 'This draft has no question waiting for an answer.' } };
525
+ const b = body && typeof body === 'object' ? body : {};
526
+ if (b.k !== v.openK) return { status: 409, body: { ok: false, refused: 'stale-question', say: 'That is not the question now open. Reload and answer the one shown.' } };
527
+ const answer = typeof b.answer === 'string' ? b.answer.trim() : '';
528
+ if (answer === '') return { status: 400, body: { ok: false, refused: 'blank-answer', say: BLANK_ANSWER_SAY } };
529
+ if (/[\r\n]/.test(answer)) return { status: 400, body: { ok: false, refused: 'one-line', say: ONE_LINE_ANSWER_SAY } };
530
+ if (keys.some((k) => k.length >= 8 && answer.includes(k))) return { status: 400, body: { ok: false, refused: 'key', say: 'This answer contains an API key. Keys go in Settings only. Nothing was saved.' } };
531
+ if (childRunning(dir)) return { status: 409, body: { ok: false, refused: 'draft-live', say: 'The draft process is still finishing. Try again in a moment.' } };
532
+ const planDir = join(dir, v.plan);
533
+ const q = v.questions.find((x) => x.k === v.openK);
534
+ const last = v.questions.filter((x) => !x.answered).length === 1;
535
+ const answerFile = join(planDir, ANSWER_FILE(v.openK));
536
+ // the whole redraft is checked at $0 BEFORE the answer is written, so a refusal leaves the question open and nothing on disk
537
+ /** @type {any} */
538
+ let redraft = null;
539
+ if (last) {
540
+ const all = readQuestions(planDir).questions.map((x) => ({ line: x.line, question: x.question, answer: x.k === v.openK ? answer : x.answer }));
541
+ const grown = appendAnswersToJob(typeof v.card.job === 'string' ? v.card.job : '', /** @type {{line:number, answer:string}[]} */ (all));
542
+ 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.' } };
543
+ const vet = vetCard({ ...v.card, job: grown.job }, loaded);
544
+ if (!vet.ok) return vet.reply;
545
+ for (const other of listIds()) {
546
+ if (other === id) continue;
547
+ const ov = view(other, keys);
548
+ if (ov && LIVE_PHASES.has(ov.phase)) return { status: 409, body: { ok: false, refused: 'draft-live', draftId: other, say: 'A draft is already running. Wait for it, or abandon it, before answering.' } };
549
+ }
550
+ redraft = { vet, all };
551
+ }
552
+ try {
553
+ writeFileSync(answerFile, `${JSON.stringify({ k: v.openK, line: q.line, question: q.question, answer, at: new Date().toISOString() })}\n`, { mode: 0o600, flag: 'wx' });
554
+ } catch (e) {
555
+ return { status: 409, body: { ok: false, refused: 'already-answered', say: /** @type {any} */ (e)?.code === 'EEXIST' ? 'That question already has an answer.' : 'The answer could not be saved. Nothing was sent.' } };
556
+ }
557
+ if (!last) return { status: 200, body: { ok: true, draftId: id, next: v.openK + 1 } };
558
+ const n = Math.max(0, ...v.revises.map((x) => x.n)) + 1;
559
+ const files = [`card-${n}.json`, `prose-${n}.txt`, `redraft-${n}.json`].map((f) => join(dir, f));
560
+ const undo = () => { for (const f of [...files, answerFile]) rmSync(f, { force: true }); };
561
+ let child;
562
+ try {
563
+ writeFileSync(files[0], `${JSON.stringify(redraft.vet.card, null, 2)}\n`, { mode: 0o600, flag: 'wx' });
564
+ writeFileSync(files[1], redraft.vet.prose, { mode: 0o600, flag: 'wx' });
565
+ writeFileSync(files[2], `${JSON.stringify({ fromPlan: v.plan, answers: redraft.all.map((x) => ({ line: x.line, question: x.question, answer: x.answer })) })}\n`, { mode: 0o600, flag: 'wx' });
566
+ child = spawnDetached({
567
+ bin,
568
+ argv: ['draft', files[1], '--out', join(dir, `draft-${n}`), '--root', realpathSync(root), '--name', redraft.vet.card.flowName, '--no-questions'],
569
+ env: loaded.env,
570
+ logPath: join(dir, `redraft-${n}.log`),
571
+ });
572
+ } catch (e) {
573
+ undo();
574
+ return { status: 500, body: { ok: false, refused: 'spawn', say: `The plan could not be drafted again (${/** @type {any} */ (e)?.code ?? 'error'}). Your answer was not kept; answer again. Nothing was spent.`, draftId: id } };
575
+ }
576
+ child.on('error', () => {});
577
+ writePidFile(dir, child);
578
+ return { status: 202, body: { ok: true, draftId: id, n, redrafting: true } };
579
+ },
580
+
419
581
  /**
420
582
  * `GET /api/author/live`: the newest draft that is not abandoned or signed, and the newest panel start the human has not cleared
421
583
  * (`starting` or `refused`; a `started` one is in Runs) — read from files, never memory.
@@ -14,7 +14,7 @@ import {
14
14
  } from 'node:fs';
15
15
  import { isAbsolute, join } from 'node:path';
16
16
 
17
- import { checkFlowName } from '../flow.js';
17
+ import { checkFlowName, signedHashOf } from '../flow.js';
18
18
  import { checkSendDestination, resolveCeilingUsd } from '../runner.js';
19
19
  import { parseSignedText } from '../signed-text.js';
20
20
  import { PROVIDER_SLOTS } from '../provider.js';
@@ -82,13 +82,56 @@ export function parseJobBox(text) {
82
82
  return { steps, refusals };
83
83
  }
84
84
 
85
+ /**
86
+ * M4e amendment 24 item 3: the submitted job box with each answer added WORD FOR WORD as a `~` line under the job line it is about, after
87
+ * that line's own `~` lines (several answers for one line keep their order). The job box's own lines are untouched; the card -> prose path
88
+ * (`cardToProse`) then writes the answer as that line's guardrail, so it reaches the signed text and the hash. Pure. An answer for a line
89
+ * the box does not have is NOT added (the caller sees the count).
90
+ * @param {string} job @param {{ line: number, answer: string }[]} answers
91
+ * @returns {{ job: string, added: number }}
92
+ */
93
+ export function appendAnswersToJob(job, answers) {
94
+ const raw = String(job).split('\n');
95
+ /** @type {Map<number, number>} the index of the last non-empty box line that belongs to each step (its own line or a `~` under it) */
96
+ const lastOf = new Map();
97
+ let step = 0;
98
+ raw.forEach((l, i) => {
99
+ const t = l.trim();
100
+ if (t === '') return;
101
+ if (!t.startsWith('~')) step += 1;
102
+ if (step > 0) lastOf.set(step, i);
103
+ });
104
+ /** @type {Map<number, string[]>} */
105
+ const after = new Map();
106
+ let added = 0;
107
+ for (const a of answers) {
108
+ if (!lastOf.has(a.line)) continue;
109
+ const at = /** @type {number} */ (lastOf.get(a.line));
110
+ after.set(at, [...(after.get(at) ?? []), `~ ${a.answer}`]);
111
+ added += 1;
112
+ }
113
+ const out = [];
114
+ raw.forEach((l, i) => { out.push(l); for (const g of after.get(i) ?? []) out.push(g); });
115
+ return { job: out.join('\n'), added };
116
+ }
117
+
118
+ /**
119
+ * THE one place a step's `~` lines become its guardrail: several `~` lines under one step are ONE continuous guardrail (hamr ruling 2026-10-09),
120
+ * each part verbatim (trimmed), in typed order, joined by "; ". An answer (am24) is one more `~` line, so it joins here too. The signed-text parser
121
+ * stays strict 1-for-1 because the job file never carries more than one `guardrail:` per line.
122
+ * @param {string[]} parts
123
+ */
124
+ export function joinGuardrails(parts) {
125
+ return parts.map((g) => g.trim()).join('; ');
126
+ }
127
+
85
128
  /** 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
129
  export function jobFileLines(steps, askWait) {
87
130
  /** @type {string[]} */
88
131
  const out = [];
89
132
  for (const s of steps) {
90
133
  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}`);
134
+ if (s.guardrails.length > 0) out.push(` guardrail: ${joinGuardrails(s.guardrails)}`);
92
135
  }
93
136
  return out;
94
137
  }
@@ -127,6 +170,8 @@ export function cardFields(body) {
127
170
  inputs: str(b.inputs).replace(/\r\n?/g, '\n'),
128
171
  capUsd: typeof b.capUsd === 'string' && b.capUsd.trim() !== '' ? Number(b.capUsd) : b.capUsd,
129
172
  askWait: str(b.askWait).trim(),
173
+ // M6: present only when this card EDITS a signed job: which job, and the signature hash it was opened at
174
+ ...(typeof b.editOf?.flow === 'string' && typeof b.editOf?.flowHash === 'string' && b.editOf.flowHash !== '' ? { editOf: { flow: b.editOf.flow, flowHash: b.editOf.flowHash } } : {}),
130
175
  };
131
176
  }
132
177
 
@@ -150,6 +195,51 @@ export function cardToProse(card) {
150
195
  return `${out.join('\n')}\n`;
151
196
  }
152
197
 
198
+ /** An ask wait in ms as the card spells it (`30m`, `2h`), or null when it is not a whole number of minutes. @param {number} ms */
199
+ function waitText(ms) {
200
+ if (!Number.isInteger(ms) || ms <= 0 || ms % 60000 !== 0) return null;
201
+ return ms % 3600000 === 0 ? `${ms / 3600000}h` : `${ms / 60000}m`;
202
+ }
203
+
204
+ /**
205
+ * M6: a signed job turned back into the card's fields (the job box, inputs box, destination, cap, ask wait), from `parseSignedText`'s `lines` and
206
+ * `arbiter`. The ONE rule of fidelity is mechanical: the card is offered only if writing it again (`cardToProse` -> `parseSignedText`) gives back the
207
+ * SAME lines and the SAME arbiter (an old unsigned `ask:` wait is the one thing allowed to differ: it comes back signed at its 30m). A setting the
208
+ * card has no box for (a redo cap, a second send, a send off the last line, a wait in seconds) makes the answer `{ok:false, say}`; nothing is dropped.
209
+ * @param {{ lines: {n: number, text: string, guardrail: string}[], arbiter: any }} signed
210
+ * @returns {{ ok: true, card: { job: string, inputs: string, destination: string, capUsd: string, askWait: string } } | { ok: false, say: string }}
211
+ */
212
+ export function cardFromSigned({ lines, arbiter }) {
213
+ const no = () => ({ ok: /** @type {false} */ (false), say: 'This job has a setting the card has no box for, so it cannot be opened for editing here.' });
214
+ const asks = new Map((arbiter.asks ?? []).map((a) => [a.line, a]));
215
+ const jobLines = [];
216
+ let firstWait = null;
217
+ for (const l of lines) {
218
+ const ak = asks.get(l.n);
219
+ if (ak) {
220
+ const w = waitText(ak.ttlMs);
221
+ if (w === null) return no();
222
+ firstWait ??= w;
223
+ jobLines.push(`Ask ${w}: ${l.text}`);
224
+ } else jobLines.push(l.text);
225
+ if (typeof l.guardrail === 'string' && l.guardrail !== '') jobLines.push(`~ ${l.guardrail}`);
226
+ }
227
+ const sends = arbiter.sends ?? [];
228
+ if (sends.length > 1 || (sends.length === 1 && sends[0].target?.kind !== 'file')) return no();
229
+ const card = {
230
+ job: jobLines.join('\n'),
231
+ inputs: (arbiter.sources ?? []).map((x) => `${x.role}: ${x.path}`).join('\n'),
232
+ destination: sends.length === 1 ? sends[0].target.path : '',
233
+ capUsd: capText(Number(arbiter.capUsd)),
234
+ askWait: firstWait ?? '1h',
235
+ };
236
+ const again = parseSignedText(cardToProse(cardFields({ ...card, flowName: 'x' })));
237
+ const norm = (a) => JSON.stringify({ ...a, asks: (a.asks ?? []).map(({ ttlSigned, ...rest }) => rest) });
238
+ const sameLines = again.ok && JSON.stringify(again.lines) === JSON.stringify(lines);
239
+ if (!sameLines || norm(again.arbiter) !== norm(arbiter)) return no();
240
+ return { ok: true, card };
241
+ }
242
+
153
243
  /** The refusal for a path that does not name a readable regular file (realpath at the click). @param {string} p */
154
244
  function fileProblem(p) {
155
245
  let real;
@@ -238,10 +328,15 @@ export function checkCard(card, { root, env = {} }) {
238
328
  const refusals = [];
239
329
  const no = (field, say) => refusals.push({ field, say });
240
330
 
241
- // flow name: the CLI's own check, and not an existing flow
331
+ // flow name: the CLI's own check, and not an existing flow (M6: unless this card edits that very job, still at the hash it was opened at)
242
332
  const name = checkFlowName(card.flowName);
243
333
  if (!name.ok) no('flowName', `${name.red}. Use lowercase letters, digits, "-" or "_".`);
244
- else {
334
+ else if (card.editOf) {
335
+ const was = signedHashOf(join(root, card.editOf.flow));
336
+ if (card.flowName !== card.editOf.flow) no('flowName', `The name of a job being edited cannot change. It stays "${card.editOf.flow}".`);
337
+ else if (was === null) no('flowName', `The job "${card.editOf.flow}" is no longer here, so it cannot be edited. Clear the card and start a new job.`);
338
+ else if (was !== card.editOf.flowHash) no('flowName', `"${card.editOf.flow}" was signed again since you opened it for editing. Open it again to edit the new version. Nothing was changed.`);
339
+ } else {
245
340
  let there = true;
246
341
  try { lstatSync(join(root, card.flowName)); } catch { there = false; }
247
342
  if (there) no('flowName', `There is already a flow named "${card.flowName}" here. Pick a name that is not used yet.`);