fwdloop 0.13.0 → 0.14.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.
- package/bin/fwdloop +25 -12
- package/package.json +2 -2
- package/src/authoring.js +68 -37
- package/src/canrun.js +71 -1
- package/src/catalogue.json +2 -2
- package/src/checked.js +50 -0
- package/src/closers.js +112 -91
- package/src/declaration.js +113 -11
- package/src/drafter.js +139 -39
- package/src/keysfile.js +4 -2
- package/src/model-step.js +1 -1
- package/src/monthly.js +139 -17
- package/src/panel/author.js +219 -63
- package/src/panel/authorcard.js +44 -1
- package/src/panel/authorflows.js +12 -7
- package/src/panel/data.js +96 -71
- package/src/panel/index.html +355 -303
- package/src/panel/server.js +4 -1
- package/src/panel/settings.js +1 -1
- package/src/runner.js +96 -47
- package/src/setup.js +21 -14
- package/types/authoring.d.ts +41 -9
- package/types/canrun.d.ts +33 -1
- package/types/checked.d.ts +23 -0
- package/types/closers.d.ts +47 -28
- package/types/declaration.d.ts +16 -2
- package/types/drafter.d.ts +146 -11
- package/types/model-step.d.ts +1 -6
- package/types/monthly.d.ts +25 -1
- package/types/panel/author.d.ts +21 -40
- package/types/panel/authorcard.d.ts +22 -0
- package/types/panel/data.d.ts +5 -54
- package/types/runner.d.ts +11 -3
- package/types/setup.d.ts +6 -12
package/src/panel/author.js
CHANGED
|
@@ -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
|
-
//
|
|
17
|
-
//
|
|
18
|
-
//
|
|
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 {
|
|
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,
|
|
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
|
|
66
|
-
export const
|
|
67
|
-
const
|
|
68
|
-
|
|
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
|
|
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
|
-
|
|
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 (
|
|
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
|
|
164
|
-
*
|
|
165
|
-
*
|
|
166
|
-
*
|
|
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
|
|
186
|
+
function withRevises(base, dir, first, keys) {
|
|
169
187
|
const names = readdirInside(dir, '.');
|
|
170
|
-
const
|
|
171
|
-
const
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
const
|
|
175
|
-
|
|
176
|
-
|
|
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')
|
|
179
|
-
if (res) return {
|
|
180
|
-
if (
|
|
181
|
-
return {
|
|
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
|
-
|
|
184
|
-
|
|
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 hasAsk = parsed?.ok === true ? parsed.arbiter.asks.length > 0 : true;
|
|
233
|
+
return { checked: checkedLines(decl, { hasAsk }), 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
|
|
273
|
-
|
|
274
|
-
|
|
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
|
|
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
|
-
|
|
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
|
},
|
|
@@ -368,54 +446,132 @@ export function createAuthor(opts) {
|
|
|
368
446
|
},
|
|
369
447
|
|
|
370
448
|
/**
|
|
371
|
-
* `POST /api/author/:id/revise` body
|
|
372
|
-
* plan -> $0 checks
|
|
373
|
-
*
|
|
374
|
-
* draft;
|
|
449
|
+
* `POST /api/author/:id/revise` body = the card fields, as `POST /api/author/draft` takes them (M4e amendment 14): the human's edited
|
|
450
|
+
* 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)
|
|
451
|
+
* -> one detached plain `fwdloop draft prose-<n>.txt --out draft-<n>` -> 202. The model gets the card only. Up to MAX_REVISES per
|
|
452
|
+
* draft; a refusal makes no model call and writes nothing. A body carrying a note (`text`/`note`) is refused: nothing the human types
|
|
453
|
+
* goes to the model as a note. Synchronous, like `start`.
|
|
375
454
|
* @param {string} id @param {any} body
|
|
376
455
|
*/
|
|
377
456
|
revise(id, body) {
|
|
378
457
|
const { loaded, keys } = keysNow();
|
|
379
458
|
if (!loaded.ok) return { status: 409, body: { ok: false, refused: 'keys-file', say: String(loaded.refusal) } };
|
|
380
459
|
if (!ID_RE.test(id)) return { status: 404, body: { ok: false, refused: 'no-such-draft' } };
|
|
460
|
+
if (body && typeof body === 'object' && ('text' in body || 'note' in body)) {
|
|
461
|
+
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.' } };
|
|
462
|
+
}
|
|
381
463
|
const dd = draftsDir();
|
|
382
464
|
const dir = dd === null ? null : join(dd, id);
|
|
383
465
|
const v = dir === null ? null : /** @type {any} */ (readDraft(dir, id, keys));
|
|
384
466
|
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
|
|
386
|
-
if (v.phase
|
|
387
|
-
|
|
467
|
+
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.' } };
|
|
468
|
+
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.' } };
|
|
469
|
+
// only a draft whose first plan was green has revises (`withRevises` is the one reader that sets them)
|
|
470
|
+
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.` } };
|
|
471
|
+
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
472
|
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
|
|
390
|
-
if (
|
|
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.' } };
|
|
473
|
+
const vet = vetCard(body, loaded);
|
|
474
|
+
if (!vet.ok) return vet.reply;
|
|
393
475
|
for (const other of listIds()) {
|
|
394
476
|
if (other === id) continue;
|
|
395
477
|
const ov = view(other, keys);
|
|
396
|
-
if (ov && (ov.phase
|
|
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
|
|
478
|
+
if (ov && LIVE_PHASES.has(ov.phase)) {
|
|
479
|
+
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
480
|
}
|
|
399
481
|
}
|
|
400
|
-
const n = Math.max(0, ...v.
|
|
401
|
-
const
|
|
402
|
-
writeFileSync(
|
|
482
|
+
const n = Math.max(0, ...v.revises.map((x) => x.n)) + 1;
|
|
483
|
+
const proseFile = join(dir, `prose-${n}.txt`);
|
|
484
|
+
writeFileSync(join(dir, `card-${n}.json`), `${JSON.stringify(vet.card, null, 2)}\n`, { mode: 0o600, flag: 'wx' });
|
|
485
|
+
writeFileSync(proseFile, vet.prose, { mode: 0o600, flag: 'wx' });
|
|
403
486
|
let child;
|
|
404
487
|
try {
|
|
405
488
|
child = spawnDetached({
|
|
406
489
|
bin,
|
|
407
|
-
argv: ['draft',
|
|
490
|
+
argv: ['draft', proseFile, '--out', join(dir, `draft-${n}`), '--root', realpathSync(root), '--name', vet.card.flowName],
|
|
408
491
|
env: loaded.env,
|
|
409
492
|
logPath: join(dir, `revise-${n}.log`),
|
|
410
493
|
});
|
|
411
494
|
} catch (e) {
|
|
412
|
-
return { status: 500, body: { ok: false, refused: 'spawn', say: `The
|
|
495
|
+
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
496
|
}
|
|
414
497
|
child.on('error', () => {});
|
|
415
498
|
writePidFile(dir, child);
|
|
416
499
|
return { status: 202, body: { ok: true, draftId: id, n } };
|
|
417
500
|
},
|
|
418
501
|
|
|
502
|
+
/**
|
|
503
|
+
* `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.
|
|
504
|
+
* 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
|
|
505
|
+
* 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
|
|
506
|
+
* each answer added word for word as a `~` guardrail under its line (the one `appendAnswersToJob`, then the one `cardToProse`). It is booked as
|
|
507
|
+
* an answer redraft (`redraft-<n>.json`), not a revise: it uses none of the 2. Synchronous, like `revise`; a refusal at $0 writes nothing.
|
|
508
|
+
* @param {string} id @param {any} body
|
|
509
|
+
*/
|
|
510
|
+
answer(id, body) {
|
|
511
|
+
const { loaded, keys } = keysNow();
|
|
512
|
+
if (!loaded.ok) return { status: 409, body: { ok: false, refused: 'keys-file', say: String(loaded.refusal) } };
|
|
513
|
+
if (!ID_RE.test(id)) return { status: 404, body: { ok: false, refused: 'no-such-draft' } };
|
|
514
|
+
const dd = draftsDir();
|
|
515
|
+
const dir = dd === null ? null : join(dd, id);
|
|
516
|
+
const v = dir === null ? null : /** @type {any} */ (readDraft(dir, id, keys));
|
|
517
|
+
if (dir === null || v === null || v.card === null) return { status: 404, body: { ok: false, refused: 'no-such-draft' } };
|
|
518
|
+
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.' } };
|
|
519
|
+
const b = body && typeof body === 'object' ? body : {};
|
|
520
|
+
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.' } };
|
|
521
|
+
const answer = typeof b.answer === 'string' ? b.answer.trim() : '';
|
|
522
|
+
if (answer === '') return { status: 400, body: { ok: false, refused: 'blank-answer', say: BLANK_ANSWER_SAY } };
|
|
523
|
+
if (/[\r\n]/.test(answer)) return { status: 400, body: { ok: false, refused: 'one-line', say: ONE_LINE_ANSWER_SAY } };
|
|
524
|
+
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.' } };
|
|
525
|
+
if (childRunning(dir)) return { status: 409, body: { ok: false, refused: 'draft-live', say: 'The draft process is still finishing. Try again in a moment.' } };
|
|
526
|
+
const planDir = join(dir, v.plan);
|
|
527
|
+
const q = v.questions.find((x) => x.k === v.openK);
|
|
528
|
+
const last = v.questions.filter((x) => !x.answered).length === 1;
|
|
529
|
+
const answerFile = join(planDir, ANSWER_FILE(v.openK));
|
|
530
|
+
// the whole redraft is checked at $0 BEFORE the answer is written, so a refusal leaves the question open and nothing on disk
|
|
531
|
+
/** @type {any} */
|
|
532
|
+
let redraft = null;
|
|
533
|
+
if (last) {
|
|
534
|
+
const all = readQuestions(planDir).questions.map((x) => ({ line: x.line, question: x.question, answer: x.k === v.openK ? answer : x.answer }));
|
|
535
|
+
const grown = appendAnswersToJob(typeof v.card.job === 'string' ? v.card.job : '', /** @type {{line:number, answer:string}[]} */ (all));
|
|
536
|
+
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.' } };
|
|
537
|
+
const vet = vetCard({ ...v.card, job: grown.job }, loaded);
|
|
538
|
+
if (!vet.ok) return vet.reply;
|
|
539
|
+
for (const other of listIds()) {
|
|
540
|
+
if (other === id) continue;
|
|
541
|
+
const ov = view(other, keys);
|
|
542
|
+
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.' } };
|
|
543
|
+
}
|
|
544
|
+
redraft = { vet, all };
|
|
545
|
+
}
|
|
546
|
+
try {
|
|
547
|
+
writeFileSync(answerFile, `${JSON.stringify({ k: v.openK, line: q.line, question: q.question, answer, at: new Date().toISOString() })}\n`, { mode: 0o600, flag: 'wx' });
|
|
548
|
+
} catch (e) {
|
|
549
|
+
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.' } };
|
|
550
|
+
}
|
|
551
|
+
if (!last) return { status: 200, body: { ok: true, draftId: id, next: v.openK + 1 } };
|
|
552
|
+
const n = Math.max(0, ...v.revises.map((x) => x.n)) + 1;
|
|
553
|
+
const files = [`card-${n}.json`, `prose-${n}.txt`, `redraft-${n}.json`].map((f) => join(dir, f));
|
|
554
|
+
const undo = () => { for (const f of [...files, answerFile]) rmSync(f, { force: true }); };
|
|
555
|
+
let child;
|
|
556
|
+
try {
|
|
557
|
+
writeFileSync(files[0], `${JSON.stringify(redraft.vet.card, null, 2)}\n`, { mode: 0o600, flag: 'wx' });
|
|
558
|
+
writeFileSync(files[1], redraft.vet.prose, { mode: 0o600, flag: 'wx' });
|
|
559
|
+
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' });
|
|
560
|
+
child = spawnDetached({
|
|
561
|
+
bin,
|
|
562
|
+
argv: ['draft', files[1], '--out', join(dir, `draft-${n}`), '--root', realpathSync(root), '--name', redraft.vet.card.flowName, '--no-questions'],
|
|
563
|
+
env: loaded.env,
|
|
564
|
+
logPath: join(dir, `redraft-${n}.log`),
|
|
565
|
+
});
|
|
566
|
+
} catch (e) {
|
|
567
|
+
undo();
|
|
568
|
+
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 } };
|
|
569
|
+
}
|
|
570
|
+
child.on('error', () => {});
|
|
571
|
+
writePidFile(dir, child);
|
|
572
|
+
return { status: 202, body: { ok: true, draftId: id, n, redrafting: true } };
|
|
573
|
+
},
|
|
574
|
+
|
|
419
575
|
/**
|
|
420
576
|
* `GET /api/author/live`: the newest draft that is not abandoned or signed, and the newest panel start the human has not cleared
|
|
421
577
|
* (`starting` or `refused`; a `started` one is in Runs) — read from files, never memory.
|
package/src/panel/authorcard.js
CHANGED
|
@@ -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
|
-
|
|
134
|
+
if (s.guardrails.length > 0) out.push(` guardrail: ${joinGuardrails(s.guardrails)}`);
|
|
92
135
|
}
|
|
93
136
|
return out;
|
|
94
137
|
}
|
package/src/panel/authorflows.js
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
// run starts only through `authorstart.js`'s one `start`. Reads the disk; writes nothing.
|
|
4
4
|
//
|
|
5
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
|
|
6
|
+
// (the one function shared with the run's own preflight: an unwired verb is not listed; amendment 22) and that have at least one
|
|
7
7
|
// passed run (amendment 7 item 7; Run again reaches the rest), each with its signed
|
|
8
8
|
// cap, its declared source roles, the source paths the NEWEST run of that flow used (its `inputs.json`
|
|
9
9
|
// manifest `source` field; blank when none) and what is left this month (a courtesy: the CLI's own monthly
|
|
@@ -15,7 +15,7 @@ import { join } from 'node:path';
|
|
|
15
15
|
|
|
16
16
|
import { scrub } from '../authoring.js';
|
|
17
17
|
import { endRow, readHistory } from '../books.js';
|
|
18
|
-
import { canFlowRun } from '../canrun.js';
|
|
18
|
+
import { canFlowRun, willNotRunSay } from '../canrun.js';
|
|
19
19
|
import { loadCatalogue } from '../catalogue.js';
|
|
20
20
|
import { ConfigError, readConfig } from '../config.js';
|
|
21
21
|
import {
|
|
@@ -171,6 +171,11 @@ export function createFlowsDoor(opts) {
|
|
|
171
171
|
if (!read.ok) {
|
|
172
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
173
|
}
|
|
174
|
+
const can = canFlowRun(read); // amendment 21 item 1: a flow the list shows refused is refused here too, in the same sentence
|
|
175
|
+
if (!can.ok) {
|
|
176
|
+
const red = scrub(String(can.red), keys);
|
|
177
|
+
return reply(409, { refused: 'flow', say: willNotRunSay(flow, red), refusals: [{ field: 'flow', say: willNotRunSay(flow, red) }] });
|
|
178
|
+
}
|
|
174
179
|
const checked = checkValues({
|
|
175
180
|
allowedKeys: RUN_KEYS, body, base: flowValues(read.arbiter), realRoot, capOnly: false, floorUsd: formFacts(read).capFloorUsd, monthlyClaim,
|
|
176
181
|
});
|
|
@@ -223,7 +228,7 @@ export function createFlowsDoor(opts) {
|
|
|
223
228
|
const flows = [];
|
|
224
229
|
for (const name of listFlowNames(realRoot)) {
|
|
225
230
|
const read = readSigned(realRoot, name);
|
|
226
|
-
if (!canFlowRun(read).ok) continue;
|
|
231
|
+
if (!canFlowRun(read).ok) continue; // a refused flow (unreadable, unwired verb, unbuildable check) is never listed
|
|
227
232
|
const entry = entryFor(realRoot, name, read, left);
|
|
228
233
|
if (entry.runs.length === 0) continue; // amendment 7 item 7: only a flow with a passed run is listed
|
|
229
234
|
flows.push(entry);
|
|
@@ -249,13 +254,13 @@ export function createFlowsDoor(opts) {
|
|
|
249
254
|
const rr = resolveRunDir(join(realRoot, flow), runId);
|
|
250
255
|
if (!rr.ok) return no(400, `${rr.red}.`);
|
|
251
256
|
if (!listRunIds(join(realRoot, flow)).includes(runId)) return no(404, `"${flow}" has no run "${runId}".`);
|
|
252
|
-
const
|
|
253
|
-
const can = canFlowRun(
|
|
257
|
+
const readRaw = readSigned(realRoot, flow);
|
|
258
|
+
const can = canFlowRun(readRaw);
|
|
254
259
|
if (!can.ok) {
|
|
255
260
|
const red = scrub(String(can.red), providerKeys(loadEnv().env));
|
|
256
|
-
return no(409,
|
|
261
|
+
return no(409, willNotRunSay(flow, red), { red });
|
|
257
262
|
}
|
|
258
|
-
|
|
263
|
+
const read = /** @type {Extract<typeof readRaw, { ok: true }>} */ (readRaw); // canFlowRun refuses every failed read above
|
|
259
264
|
const roles = (read.arbiter.sources ?? []).map((s) => s.role);
|
|
260
265
|
return {
|
|
261
266
|
status: 200,
|