fwdloop 0.12.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 +155 -27
- package/package.json +2 -2
- package/src/ask.js +3 -0
- package/src/authoring.js +135 -16
- package/src/books.js +23 -2
- package/src/canrun.js +106 -0
- package/src/catalogue.json +2 -2
- package/src/checked.js +50 -0
- package/src/closers.js +112 -91
- package/src/config.js +2 -1
- package/src/declaration.js +175 -3
- package/src/drafter.js +148 -10
- package/src/draftspend.js +70 -0
- package/src/flow.js +43 -0
- package/src/keysfile.js +4 -2
- package/src/liveness.js +1 -1
- package/src/model-step.js +31 -5
- package/src/monthly.js +195 -28
- package/src/panel/author.js +638 -0
- package/src/panel/authorcard.js +340 -0
- package/src/panel/authorflows.js +317 -0
- package/src/panel/authorresume.js +149 -0
- package/src/panel/authorstart.js +257 -0
- package/src/panel/authorvalues.js +110 -0
- package/src/panel/data.js +318 -99
- package/src/panel/index.html +2000 -330
- package/src/panel/resume.js +6 -8
- package/src/panel/server.js +122 -119
- package/src/panel/settings.js +8 -6
- package/src/panel/spawn.js +77 -0
- package/src/provider.js +12 -17
- package/src/runner.js +707 -104
- package/src/runvalues.js +178 -0
- package/src/send.js +10 -3
- package/src/setup.js +127 -0
- package/types/authoring.d.ts +56 -2
- package/types/books.d.ts +14 -2
- package/types/canrun.d.ts +64 -0
- package/types/checked.d.ts +23 -0
- package/types/closers.d.ts +47 -28
- package/types/config.d.ts +1 -0
- package/types/declaration.d.ts +23 -1
- package/types/drafter.d.ts +151 -2
- package/types/draftspend.d.ts +21 -0
- package/types/flow.d.ts +23 -0
- package/types/liveness.d.ts +2 -2
- package/types/model-step.d.ts +4 -7
- package/types/monthly.d.ts +46 -1
- package/types/panel/author.d.ts +316 -0
- package/types/panel/authorcard.d.ts +142 -0
- package/types/panel/authorflows.d.ts +175 -0
- package/types/panel/authorresume.d.ts +32 -0
- package/types/panel/authorstart.d.ts +115 -0
- package/types/panel/authorvalues.d.ts +62 -0
- package/types/panel/data.d.ts +105 -63
- package/types/panel/server.d.ts +11 -33
- package/types/panel/spawn.d.ts +30 -0
- package/types/provider.d.ts +6 -9
- package/types/runner.d.ts +129 -6
- package/types/runvalues.d.ts +97 -0
- package/types/send.d.ts +5 -1
- package/types/setup.d.ts +77 -0
|
@@ -0,0 +1,638 @@
|
|
|
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
|
+
// 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`).
|
|
20
|
+
// abandoned.json written by Abandon, after the child is gone
|
|
21
|
+
// signed.json written by `sign` (piece 2b) right after `signDraft` succeeds; the phase reader reads it
|
|
22
|
+
//
|
|
23
|
+
// ONE WRITER PER FIELD: `start` writes card.json, prose.txt, pid.json (and, through the one spawn helper, child.log);
|
|
24
|
+
// `abandon` writes abandoned.json; `sign` writes signed.json; the CLI child writes everything under draft/. The phase is never stored — it is
|
|
25
|
+
// READ from those files each time (`readDraft`), so a refresh or a panel restart cannot disagree with the disk.
|
|
26
|
+
//
|
|
27
|
+
// One at a time with no lock table: `start` is fully synchronous (check live -> create the folder -> spawn ->
|
|
28
|
+
// write pid.json, no await between), so two requests that arrive together run one after the other and the second
|
|
29
|
+
// sees the first's live child and is refused. A dead child never blocks (its pid is read, never assumed).
|
|
30
|
+
import { randomBytes } from 'node:crypto';
|
|
31
|
+
import {
|
|
32
|
+
mkdirSync, realpathSync, rmSync, writeFileSync,
|
|
33
|
+
} from 'node:fs';
|
|
34
|
+
import { userInfo } from 'node:os';
|
|
35
|
+
import { dirname, join } from 'node:path';
|
|
36
|
+
import { fileURLToPath } from 'node:url';
|
|
37
|
+
|
|
38
|
+
import {
|
|
39
|
+
ANSWER_FILE, NOT_CHECKED_FILE, OPEN_QUESTION_SAY, PANEL_DRAFTS_DIR, readQuestions, readoutHeadIndexes, scrub, signDraft,
|
|
40
|
+
} from '../authoring.js';
|
|
41
|
+
import { nextRunId, readFileInside, readdirInside } from '../flow.js';
|
|
42
|
+
import { isFwdloopAlive } from '../liveness.js';
|
|
43
|
+
import {
|
|
44
|
+
checkMonthlyRoom, ConfigError, monthlyNote, monthlyRefusalText,
|
|
45
|
+
} from '../monthly.js';
|
|
46
|
+
import {
|
|
47
|
+
appendAnswersToJob, capFloorText, capFloorUsd, cardFields, checkCard, checkInputRows, parseInputLines, parseJobBox,
|
|
48
|
+
} from './authorcard.js';
|
|
49
|
+
import { checkedLines, notCheckedBlock } from '../checked.js';
|
|
50
|
+
import { parseSignedText } from '../signed-text.js';
|
|
51
|
+
import { leastResumeCapUsd } from './authorvalues.js';
|
|
52
|
+
import { createFlowsDoor } from './authorflows.js';
|
|
53
|
+
import { createResumeDoor } from './authorresume.js';
|
|
54
|
+
import { createStarter } from './authorstart.js';
|
|
55
|
+
import {
|
|
56
|
+
childRunning as childRunningNow, providerKeys, readJsonFile, spawnDetached, writePidFile,
|
|
57
|
+
} from './spawn.js';
|
|
58
|
+
|
|
59
|
+
const HERE = dirname(fileURLToPath(import.meta.url));
|
|
60
|
+
const BIN = join(HERE, '..', '..', 'bin', 'fwdloop');
|
|
61
|
+
|
|
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';
|
|
64
|
+
const ID_RE = /^d-[0-9a-z]{10}-[0-9a-f]{4}$/;
|
|
65
|
+
const newId = () => `d-${Date.now().toString(36).padStart(10, '0')}-${randomBytes(2).toString('hex')}`;
|
|
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). */
|
|
67
|
+
const FINISHED = new Set(['abandoned', 'signed']);
|
|
68
|
+
const LOG_TAIL_CHARS = 1500;
|
|
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.';
|
|
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.';
|
|
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.';
|
|
80
|
+
const PLAN_DIR_RE = /^draft-(\d+)$/;
|
|
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.';
|
|
82
|
+
const KILL_WAIT_MS = 3000;
|
|
83
|
+
const KILL_HARD_WAIT_MS = 2000;
|
|
84
|
+
const sleep = (ms) => new Promise((r) => { setTimeout(r, ms); });
|
|
85
|
+
|
|
86
|
+
/**
|
|
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
|
|
88
|
+
* `loadEnv` is the keys-file door (`keysForDoor`): called before EVERY spawn and every reply that quotes a log, so editing
|
|
89
|
+
* the file needs no restart. Its `env` is BOTH the child's spawn env AND the scrub list (POC (a), M4d wiring rule).
|
|
90
|
+
*/
|
|
91
|
+
export function createAuthor(opts) {
|
|
92
|
+
const {
|
|
93
|
+
root, loadEnv, home, skipMonthly = false, bin = BIN, childRunning = childRunningNow,
|
|
94
|
+
} = opts;
|
|
95
|
+
// the ONE run-start path (sign and run both end in `starter.start`) and the Run-a-signed-flow door built on it
|
|
96
|
+
const starter = createStarter({ root, bin });
|
|
97
|
+
const flowsDoor = createFlowsDoor({
|
|
98
|
+
root, home, skipMonthly, loadEnv, starter, monthlyClaim: (usd) => monthlyClaim(usd),
|
|
99
|
+
});
|
|
100
|
+
|
|
101
|
+
/** The ONE monthly check, defined below (a function declaration, so the doors above may take it now). */
|
|
102
|
+
const resumeDoor = createResumeDoor({
|
|
103
|
+
root, loadEnv, monthlyClaim: (usd) => monthlyClaim(usd), starter,
|
|
104
|
+
});
|
|
105
|
+
|
|
106
|
+
/** The drafts folder's real path, or null when the flows root does not exist. */
|
|
107
|
+
const draftsDir = () => {
|
|
108
|
+
try { return join(realpathSync(root), PANEL_DRAFTS_DIR); } catch { return null; }
|
|
109
|
+
};
|
|
110
|
+
|
|
111
|
+
const readJson = readJsonFile;
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* The monthly room for a cap, from the ONE read-only check the CLI's door also decides on (`checkMonthlyRoom`, src/monthly.js).
|
|
115
|
+
* `null` when this process has no config home (the CLI skips its check there too); `{ problem }` when config.json cannot be read.
|
|
116
|
+
* @param {number} capUsd
|
|
117
|
+
*/
|
|
118
|
+
function monthlyClaim(capUsd) {
|
|
119
|
+
if (skipMonthly) return null;
|
|
120
|
+
try { return checkMonthlyRoom({ capUsd, home }); } catch (e) {
|
|
121
|
+
if (e instanceof ConfigError) return { problem: e.message };
|
|
122
|
+
throw e;
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/**
|
|
127
|
+
* The draft's state, READ from its files. `keys` = the provider key values to scrub from anything quoted.
|
|
128
|
+
* @param {string} dir the draft folder @param {string} id @param {string[]} keys
|
|
129
|
+
*/
|
|
130
|
+
function readDraft(dir, id, keys) {
|
|
131
|
+
const card = readJson(dir, 'card.json');
|
|
132
|
+
const base = { draftId: id, card };
|
|
133
|
+
if (readJson(dir, 'abandoned.json')) return { ...base, phase: 'abandoned' };
|
|
134
|
+
const signed = readJson(dir, 'signed.json');
|
|
135
|
+
if (signed) return { ...base, phase: 'signed' };
|
|
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);
|
|
140
|
+
const first = resultOf(dir, 'draft', 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);
|
|
143
|
+
if (first) return { ...base, ...first };
|
|
144
|
+
// no result yet: the child is the only thing that can still produce one
|
|
145
|
+
if (running) return { ...base, phase: 'drafting' };
|
|
146
|
+
return { ...base, phase: 'stopped', say: logTail(dir, 'child.log', keys) || STOPPED_SAY };
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/** The tail of a child's log, scrubbed and without its `fwdloop: ` prefix; '' when there is none. */
|
|
150
|
+
function logTail(dir, rel, keys) {
|
|
151
|
+
const logText = readFileInside(dir, rel);
|
|
152
|
+
return logText.ok ? scrub(logText.text, keys).trim().slice(-LOG_TAIL_CHARS).replace(/^fwdloop: /, '') : '';
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/**
|
|
156
|
+
* 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).
|
|
157
|
+
* @param {string} dir the draft folder @param {string} rel `draft` or `draft-<n>` @param {string[]} keys
|
|
158
|
+
* @returns {any}
|
|
159
|
+
*/
|
|
160
|
+
function resultOf(dir, rel, keys) {
|
|
161
|
+
const hashFile = readFileInside(dir, `${rel}/spec.hash`);
|
|
162
|
+
if (hashFile.ok && hashFile.text.trim() !== '') {
|
|
163
|
+
const readout = readFileInside(dir, `${rel}/readout.txt`);
|
|
164
|
+
const text = readout.ok ? scrub(readout.text, keys) : '';
|
|
165
|
+
return { phase: 'green', hash: hashFile.text.trim(), readout: text, readoutHeads: readoutHeadIndexes(text) };
|
|
166
|
+
}
|
|
167
|
+
const leak = readFileInside(dir, `${rel}/scrub-leak.red`);
|
|
168
|
+
const log = readJson(dir, `${rel}/log.json`);
|
|
169
|
+
if (leak.ok || (log && log.ok === false)) {
|
|
170
|
+
const reds = Array.isArray(log?.reds) ? log.reds.map((r) => scrub(String(r), keys)) : [];
|
|
171
|
+
if (leak.ok) reds.push(scrub(leak.text.trim(), keys));
|
|
172
|
+
return { phase: 'red', reds, say: RED_SAY };
|
|
173
|
+
}
|
|
174
|
+
return null;
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/**
|
|
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
|
|
185
|
+
*/
|
|
186
|
+
function withRevises(base, dir, first, keys) {
|
|
187
|
+
const names = readdirInside(dir, '.');
|
|
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
|
|
197
|
+
const res = resultOf(dir, `draft-${n}`, keys);
|
|
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 };
|
|
202
|
+
});
|
|
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
|
+
}));
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
/** Draft ids, newest first. */
|
|
247
|
+
const listIds = () => {
|
|
248
|
+
const d = draftsDir();
|
|
249
|
+
return d === null ? [] : readdirInside(d, '.').filter((n) => ID_RE.test(n)).sort().reverse();
|
|
250
|
+
};
|
|
251
|
+
|
|
252
|
+
const view = (id, keys) => {
|
|
253
|
+
const d = draftsDir();
|
|
254
|
+
return d === null ? null : readDraft(join(d, id), id, keys);
|
|
255
|
+
};
|
|
256
|
+
|
|
257
|
+
/** The one request-time read of the keys door: the merged env (scrub list + child env) or null on its refusal. */
|
|
258
|
+
const keysNow = () => {
|
|
259
|
+
const loaded = loadEnv();
|
|
260
|
+
return { loaded, keys: providerKeys(loaded.env) };
|
|
261
|
+
};
|
|
262
|
+
|
|
263
|
+
/**
|
|
264
|
+
* The one reader both sign calls share: a well-formed id, a readable draft, phase `green` (so not abandoned, signed, red,
|
|
265
|
+
* drafting or stopped), and the flow name from its own `target.json`.
|
|
266
|
+
* @param {string} id
|
|
267
|
+
*/
|
|
268
|
+
function greenDraft(id) {
|
|
269
|
+
const no = (status, refused, say) => ({ ok: false, reply: { status, body: { ok: false, refused, ...(say ? { say } : {}) } } });
|
|
270
|
+
if (!ID_RE.test(id)) return no(404, 'no-such-draft');
|
|
271
|
+
const dd = draftsDir();
|
|
272
|
+
const dir = dd === null ? null : join(dd, id);
|
|
273
|
+
const v = dir === null ? null : readDraft(dir, id, keysNow().keys);
|
|
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);
|
|
277
|
+
if (v.phase !== 'green') return no(409, 'not-green', `This draft is ${v.phase}, not a finished plan, so it cannot be signed.`);
|
|
278
|
+
const name = readJson(dir, `${v.plan}/target.json`)?.name;
|
|
279
|
+
if (typeof name !== 'string') return no(409, 'no-name', 'The draft has no readable flow name. Nothing was signed.');
|
|
280
|
+
return {
|
|
281
|
+
ok: true, v: /** @type {any} */ (v), name, dir,
|
|
282
|
+
};
|
|
283
|
+
}
|
|
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
|
+
|
|
302
|
+
return {
|
|
303
|
+
flows: flowsDoor.flows,
|
|
304
|
+
runAgain: flowsDoor.runAgain,
|
|
305
|
+
run: flowsDoor.run,
|
|
306
|
+
runPrepare: flowsDoor.runPrepare,
|
|
307
|
+
resumePrepare: resumeDoor.prepare,
|
|
308
|
+
resumeForm: resumeDoor.form,
|
|
309
|
+
resume: resumeDoor.resume,
|
|
310
|
+
|
|
311
|
+
/**
|
|
312
|
+
* `GET /api/author/monthly-check?cap=<usd>`: the note under Cap, one read-only check. `{ text, red }` is what to show (red =
|
|
313
|
+
* the cap does not fit this month); `floorUsd` is the smallest cap that funds one round of a model step, for the page's
|
|
314
|
+
* `needs at least $X per run` line. A cap that is not a number above 0 gets no note. Never spends, never writes.
|
|
315
|
+
* @param {unknown} cap @param {string|null} [spent] what a resumed run has already spent (amendment 4 item 4)
|
|
316
|
+
*/
|
|
317
|
+
monthlyCheck(cap, spent = null) {
|
|
318
|
+
const n = Number(cap);
|
|
319
|
+
const floorUsd = capFloorUsd('x');
|
|
320
|
+
if (typeof cap !== 'string' || cap.trim() === '' || !Number.isFinite(n) || n <= 0) return { status: 200, body: { ok: true, text: '', red: false, floorUsd, floorText: capFloorText(floorUsd) } };
|
|
321
|
+
// 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
|
|
322
|
+
// what is spent says so in the door's own words (red)
|
|
323
|
+
const spentUsd = typeof spent === 'string' && spent.trim() !== '' && Number.isFinite(Number(spent)) && Number(spent) > 0 ? Number(spent) : 0;
|
|
324
|
+
if (spentUsd > 0 && n <= spentUsd + 1e-9) {
|
|
325
|
+
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) } };
|
|
326
|
+
}
|
|
327
|
+
const claim = monthlyClaim(n - spentUsd);
|
|
328
|
+
if (claim === null || 'problem' in claim) return { status: 200, body: { ok: true, text: '', red: false, floorUsd, floorText: capFloorText(floorUsd) } };
|
|
329
|
+
return { status: 200, body: { ok: true, ...monthlyNote(claim), floorUsd, floorText: capFloorText(floorUsd) } };
|
|
330
|
+
},
|
|
331
|
+
|
|
332
|
+
/** `GET /api/author/start/:startId`: the start's phase, read from its files. @param {string} id */
|
|
333
|
+
startGet(id) { return starter.get(id, keysNow().keys); },
|
|
334
|
+
|
|
335
|
+
/** `POST /api/author/start/:startId/clear`: dismiss a refused start. @param {string} id */
|
|
336
|
+
startClear(id) { return starter.clear(id, keysNow().keys); },
|
|
337
|
+
|
|
338
|
+
/**
|
|
339
|
+
* `POST /api/author/draft`: card -> $0 checks -> one detached `fwdloop draft` -> 202 { draftId }. Nothing is created
|
|
340
|
+
* on a refusal. Synchronous on purpose (see the file header).
|
|
341
|
+
* @param {any} body
|
|
342
|
+
* @returns {{ status: number, body: any }}
|
|
343
|
+
*/
|
|
344
|
+
start(body) {
|
|
345
|
+
const { loaded, keys } = keysNow();
|
|
346
|
+
if (!loaded.ok) return { status: 409, body: { ok: false, refused: 'keys-file', say: String(loaded.refusal) } };
|
|
347
|
+
const dd = draftsDir();
|
|
348
|
+
if (dd === null) return { status: 400, body: { ok: false, refused: 'root', say: 'The flows folder this panel serves does not exist.' } };
|
|
349
|
+
const vet = vetCard(body, loaded);
|
|
350
|
+
if (!vet.ok) return vet.reply;
|
|
351
|
+
const { card } = vet;
|
|
352
|
+
for (const id of listIds()) {
|
|
353
|
+
const v = view(id, keys);
|
|
354
|
+
if (v && LIVE_PHASES.has(v.phase)) {
|
|
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.' } };
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
const id = newId();
|
|
359
|
+
const dir = join(dd, id);
|
|
360
|
+
mkdirSync(dd, { recursive: true, mode: 0o700 });
|
|
361
|
+
mkdirSync(dir, { mode: 0o700 });
|
|
362
|
+
const proseFile = join(dir, 'prose.txt');
|
|
363
|
+
writeFileSync(join(dir, 'card.json'), `${JSON.stringify(card, null, 2)}\n`, { 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 });
|
|
370
|
+
let child;
|
|
371
|
+
try {
|
|
372
|
+
child = spawnDetached({
|
|
373
|
+
bin, argv: ['draft', proseFile, '--out', join(dir, 'draft'), '--root', realpathSync(root), '--name', card.flowName], env: loaded.env, logPath: join(dir, 'child.log'),
|
|
374
|
+
});
|
|
375
|
+
} catch (e) {
|
|
376
|
+
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 } };
|
|
377
|
+
}
|
|
378
|
+
child.on('error', () => {}); // a later spawn failure leaves no pid-backed child: the draft then reads as stopped
|
|
379
|
+
writePidFile(dir, child);
|
|
380
|
+
return { status: 202, body: { ok: true, draftId: id } };
|
|
381
|
+
},
|
|
382
|
+
|
|
383
|
+
/**
|
|
384
|
+
* `POST /api/author/:id/sign-prepare` (the first click of "Sign & run"): what the human is about to sign — the readout, the
|
|
385
|
+
* hash, the flow name, the cap. GREEN drafts only. Writes nothing: the page holds the hash it was shown, and `sign`
|
|
386
|
+
* re-reads everything from disk.
|
|
387
|
+
* @param {string} id
|
|
388
|
+
*/
|
|
389
|
+
signPrepare(id) {
|
|
390
|
+
const seen = greenDraft(id);
|
|
391
|
+
if (!seen.ok) return seen.reply;
|
|
392
|
+
return {
|
|
393
|
+
status: 200,
|
|
394
|
+
body: {
|
|
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)),
|
|
396
|
+
},
|
|
397
|
+
};
|
|
398
|
+
},
|
|
399
|
+
|
|
400
|
+
/**
|
|
401
|
+
* `POST /api/author/:id/sign` body `{ hash, runId? }`: sign and start the run — only when the draft is green and
|
|
402
|
+
* 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
|
|
403
|
+
* refuses by name, signs nothing, writes nothing, spends nothing. Fully synchronous (no await between the checks and the
|
|
404
|
+
* writes), so two sign POSTs together sign once: the second reads the first's `signed.json` and is refused.
|
|
405
|
+
* @param {string} id @param {any} body
|
|
406
|
+
*/
|
|
407
|
+
sign(id, body) {
|
|
408
|
+
const { loaded } = keysNow();
|
|
409
|
+
if (!loaded.ok) return { status: 409, body: { ok: false, refused: 'keys-file', say: String(loaded.refusal) } };
|
|
410
|
+
const seen = greenDraft(id);
|
|
411
|
+
if (!seen.ok) return seen.reply;
|
|
412
|
+
const { v, name, dir } = seen;
|
|
413
|
+
const b = body && typeof body === 'object' ? body : {};
|
|
414
|
+
// 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)
|
|
415
|
+
const floor = capFloorUsd(typeof v.card.job === 'string' ? v.card.job : '');
|
|
416
|
+
if (Number(v.card.capUsd) < floor) return { status: 400, body: { ok: false, refused: 'cap-too-small', say: capFloorText(floor) } };
|
|
417
|
+
if (typeof b.hash !== 'string' || b.hash !== v.hash) {
|
|
418
|
+
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.' } };
|
|
419
|
+
}
|
|
420
|
+
// everything the run needs is checked BEFORE signing, so a refusal never leaves a signed flow with no run
|
|
421
|
+
const inputs = parseInputLines(typeof v.card.inputs === 'string' ? v.card.inputs : '');
|
|
422
|
+
const bad = checkInputRows(inputs);
|
|
423
|
+
if (bad.length > 0) return { status: 400, body: { ok: false, refused: 'inputs', refusals: bad } };
|
|
424
|
+
// '' = no typed id: the start claims the next `run-<n>` (M4e amendment 3); a typed one is checked here, before signing
|
|
425
|
+
const runId = typeof b.runId === 'string' ? b.runId : '';
|
|
426
|
+
if (runId !== '') {
|
|
427
|
+
const run = starter.checkRun(name, runId);
|
|
428
|
+
if (!run.ok) return { status: 400, body: { ok: false, refused: 'run-id', say: run.say } };
|
|
429
|
+
}
|
|
430
|
+
const signedBy = userInfo().username;
|
|
431
|
+
const result = signDraft({
|
|
432
|
+
dir: join(dir, v.plan), approve: v.hash, signedBy, env: loaded.env, sessionDir: dir,
|
|
433
|
+
});
|
|
434
|
+
if (!result.ok) {
|
|
435
|
+
const keys = providerKeys(loaded.env);
|
|
436
|
+
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)) } };
|
|
437
|
+
}
|
|
438
|
+
writeFileSync(join(dir, 'signed.json'), `${JSON.stringify({
|
|
439
|
+
at: new Date().toISOString(), signedBy, hash: v.hash, flow: name, runId: runId === '' ? null : runId,
|
|
440
|
+
})}\n`, { mode: 0o600 });
|
|
441
|
+
const started = starter.start({
|
|
442
|
+
kind: 'sign', flow: name, runId, sources: inputs.map((r) => ({ role: r.role, path: r.path })),
|
|
443
|
+
}, loaded.env);
|
|
444
|
+
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".` } };
|
|
445
|
+
return { status: 202, body: { ...started.body, signed: true } };
|
|
446
|
+
},
|
|
447
|
+
|
|
448
|
+
/**
|
|
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`.
|
|
454
|
+
* @param {string} id @param {any} body
|
|
455
|
+
*/
|
|
456
|
+
revise(id, body) {
|
|
457
|
+
const { loaded, keys } = keysNow();
|
|
458
|
+
if (!loaded.ok) return { status: 409, body: { ok: false, refused: 'keys-file', say: String(loaded.refusal) } };
|
|
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
|
+
}
|
|
463
|
+
const dd = draftsDir();
|
|
464
|
+
const dir = dd === null ? null : join(dd, id);
|
|
465
|
+
const v = dir === null ? null : /** @type {any} */ (readDraft(dir, id, keys));
|
|
466
|
+
if (dir === null || v === null || v.card === null) return { status: 404, body: { ok: false, refused: 'no-such-draft' } };
|
|
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.` } };
|
|
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.' } };
|
|
473
|
+
const vet = vetCard(body, loaded);
|
|
474
|
+
if (!vet.ok) return vet.reply;
|
|
475
|
+
for (const other of listIds()) {
|
|
476
|
+
if (other === id) continue;
|
|
477
|
+
const ov = view(other, keys);
|
|
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.' } };
|
|
480
|
+
}
|
|
481
|
+
}
|
|
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' });
|
|
486
|
+
let child;
|
|
487
|
+
try {
|
|
488
|
+
child = spawnDetached({
|
|
489
|
+
bin,
|
|
490
|
+
argv: ['draft', proseFile, '--out', join(dir, `draft-${n}`), '--root', realpathSync(root), '--name', vet.card.flowName],
|
|
491
|
+
env: loaded.env,
|
|
492
|
+
logPath: join(dir, `revise-${n}.log`),
|
|
493
|
+
});
|
|
494
|
+
} catch (e) {
|
|
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 } };
|
|
496
|
+
}
|
|
497
|
+
child.on('error', () => {});
|
|
498
|
+
writePidFile(dir, child);
|
|
499
|
+
return { status: 202, body: { ok: true, draftId: id, n } };
|
|
500
|
+
},
|
|
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
|
+
|
|
575
|
+
/**
|
|
576
|
+
* `GET /api/author/live`: the newest draft that is not abandoned or signed, and the newest panel start the human has not cleared
|
|
577
|
+
* (`starting` or `refused`; a `started` one is in Runs) — read from files, never memory.
|
|
578
|
+
*/
|
|
579
|
+
live() {
|
|
580
|
+
const { keys } = keysNow();
|
|
581
|
+
/** @type {any} */
|
|
582
|
+
let draft = null;
|
|
583
|
+
for (const id of listIds()) {
|
|
584
|
+
const v = view(id, keys);
|
|
585
|
+
if (v && !FINISHED.has(v.phase)) draft = v;
|
|
586
|
+
break; // only the NEWEST draft can be the card's: an older one was replaced by it
|
|
587
|
+
}
|
|
588
|
+
return { status: 200, body: { ok: true, draft, start: starter.newestOpen(keys) } };
|
|
589
|
+
},
|
|
590
|
+
|
|
591
|
+
/** `GET /api/author/:id`. @param {string} id */
|
|
592
|
+
get(id) {
|
|
593
|
+
if (!ID_RE.test(id)) return { status: 404, body: { ok: false, refused: 'no-such-draft' } };
|
|
594
|
+
const { keys } = keysNow();
|
|
595
|
+
const v = view(id, keys);
|
|
596
|
+
if (v === null || v.card === null) return { status: 404, body: { ok: false, refused: 'no-such-draft' } };
|
|
597
|
+
return { status: 200, body: { ok: true, ...v } };
|
|
598
|
+
},
|
|
599
|
+
|
|
600
|
+
/**
|
|
601
|
+
* `POST /api/author/:id/abandon`: stop the child (by its recorded pid, only after `isFwdloopAlive` says it is ours),
|
|
602
|
+
* confirm it is gone, then write `abandoned.json`. No further model call; the spend already booked stays booked.
|
|
603
|
+
* @param {string} id
|
|
604
|
+
*/
|
|
605
|
+
async abandon(id) {
|
|
606
|
+
if (!ID_RE.test(id)) return { status: 404, body: { ok: false, refused: 'no-such-draft' } };
|
|
607
|
+
const dd = draftsDir();
|
|
608
|
+
const dir = dd === null ? null : join(dd, id);
|
|
609
|
+
const { keys } = keysNow();
|
|
610
|
+
const v = dir === null ? null : readDraft(dir, id, keys);
|
|
611
|
+
if (dir === null || v === null || v.card === null) return { status: 404, body: { ok: false, refused: 'no-such-draft' } };
|
|
612
|
+
if (FINISHED.has(v.phase)) return { status: 409, body: { ok: false, refused: 'not-abandonable', say: `This draft is already ${v.phase}.` } };
|
|
613
|
+
const pid = readJson(dir, 'pid.json');
|
|
614
|
+
let killed = false;
|
|
615
|
+
if (pid && Number.isInteger(pid.pid)) {
|
|
616
|
+
const procStart = typeof pid.procStart === 'string' ? pid.procStart : null;
|
|
617
|
+
const alive = isFwdloopAlive(pid.pid, procStart);
|
|
618
|
+
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.' } };
|
|
619
|
+
if (alive === true) {
|
|
620
|
+
// the child leads its own process group (detached), so one signal to the group reaches it and nothing else
|
|
621
|
+
for (const { sig, wait } of [{ sig: 'SIGTERM', wait: KILL_WAIT_MS }, { sig: 'SIGKILL', wait: KILL_HARD_WAIT_MS }]) {
|
|
622
|
+
try { process.kill(-pid.pid, /** @type {NodeJS.Signals} */ (sig)); } catch { /* already gone */ }
|
|
623
|
+
const t0 = Date.now();
|
|
624
|
+
// eslint-disable-next-line no-await-in-loop
|
|
625
|
+
while (isFwdloopAlive(pid.pid, procStart) === true && Date.now() - t0 < wait) await sleep(25);
|
|
626
|
+
if (isFwdloopAlive(pid.pid, procStart) !== true) break;
|
|
627
|
+
}
|
|
628
|
+
if (isFwdloopAlive(pid.pid, procStart) === true) {
|
|
629
|
+
return { status: 500, body: { ok: false, refused: 'still-running', say: 'The draft process did not stop. Nothing was marked abandoned.' } };
|
|
630
|
+
}
|
|
631
|
+
killed = true;
|
|
632
|
+
}
|
|
633
|
+
}
|
|
634
|
+
writeFileSync(join(dir, 'abandoned.json'), `${JSON.stringify({ at: new Date().toISOString(), killed, phaseWas: v.phase })}\n`, { mode: 0o600 });
|
|
635
|
+
return { status: 200, body: { ok: true, phase: 'abandoned', stopped: killed } };
|
|
636
|
+
},
|
|
637
|
+
};
|
|
638
|
+
}
|