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.
Files changed (62) hide show
  1. package/bin/fwdloop +155 -27
  2. package/package.json +2 -2
  3. package/src/ask.js +3 -0
  4. package/src/authoring.js +135 -16
  5. package/src/books.js +23 -2
  6. package/src/canrun.js +106 -0
  7. package/src/catalogue.json +2 -2
  8. package/src/checked.js +50 -0
  9. package/src/closers.js +112 -91
  10. package/src/config.js +2 -1
  11. package/src/declaration.js +175 -3
  12. package/src/drafter.js +148 -10
  13. package/src/draftspend.js +70 -0
  14. package/src/flow.js +43 -0
  15. package/src/keysfile.js +4 -2
  16. package/src/liveness.js +1 -1
  17. package/src/model-step.js +31 -5
  18. package/src/monthly.js +195 -28
  19. package/src/panel/author.js +638 -0
  20. package/src/panel/authorcard.js +340 -0
  21. package/src/panel/authorflows.js +317 -0
  22. package/src/panel/authorresume.js +149 -0
  23. package/src/panel/authorstart.js +257 -0
  24. package/src/panel/authorvalues.js +110 -0
  25. package/src/panel/data.js +318 -99
  26. package/src/panel/index.html +2000 -330
  27. package/src/panel/resume.js +6 -8
  28. package/src/panel/server.js +122 -119
  29. package/src/panel/settings.js +8 -6
  30. package/src/panel/spawn.js +77 -0
  31. package/src/provider.js +12 -17
  32. package/src/runner.js +707 -104
  33. package/src/runvalues.js +178 -0
  34. package/src/send.js +10 -3
  35. package/src/setup.js +127 -0
  36. package/types/authoring.d.ts +56 -2
  37. package/types/books.d.ts +14 -2
  38. package/types/canrun.d.ts +64 -0
  39. package/types/checked.d.ts +23 -0
  40. package/types/closers.d.ts +47 -28
  41. package/types/config.d.ts +1 -0
  42. package/types/declaration.d.ts +23 -1
  43. package/types/drafter.d.ts +151 -2
  44. package/types/draftspend.d.ts +21 -0
  45. package/types/flow.d.ts +23 -0
  46. package/types/liveness.d.ts +2 -2
  47. package/types/model-step.d.ts +4 -7
  48. package/types/monthly.d.ts +46 -1
  49. package/types/panel/author.d.ts +316 -0
  50. package/types/panel/authorcard.d.ts +142 -0
  51. package/types/panel/authorflows.d.ts +175 -0
  52. package/types/panel/authorresume.d.ts +32 -0
  53. package/types/panel/authorstart.d.ts +115 -0
  54. package/types/panel/authorvalues.d.ts +62 -0
  55. package/types/panel/data.d.ts +105 -63
  56. package/types/panel/server.d.ts +11 -33
  57. package/types/panel/spawn.d.ts +30 -0
  58. package/types/provider.d.ts +6 -9
  59. package/types/runner.d.ts +129 -6
  60. package/types/runvalues.d.ts +97 -0
  61. package/types/send.d.ts +5 -1
  62. package/types/setup.d.ts +77 -0
@@ -0,0 +1,178 @@
1
+ // M4e amendment 5 item 3 and amendment 4 item 6 (docs/wiki/the-module-ladder.md): the signed values ONE RUN uses when they differ from
2
+ // its flow's own, and the signed version a resumed run continues under.
3
+ //
4
+ // A run's folder may hold `signed-values.json` (version 0: written once by the human's two-click "Sign & run", before the run starts) and
5
+ // `signed-values-r<k>.json` (k >= 1: written once by the human's two-click "Sign & resume", one per Resume). Each file is the FULL set
6
+ // in force from then on (cap, destination, each ask's wait), never a patch, so the highest version wins whole. Write-once ('wx'): no
7
+ // version is ever overwritten, and the flow's own prose.txt / signature.json are never touched; the next plain run starts from the flow's
8
+ // signed values again. The agent, the chat notes and the drafter have no path to these files (the runner reads them; the panel's two
9
+ // doors are the only writers, and only on a hash the human's click carried).
10
+ //
11
+ // hash sha256 over the canonical {flow, flowSignatureHash, runId|null, version, values}: the page shows it at the first click and
12
+ // sends it back at the second; the record carries it and every reader recomputes it (a hand-edited file reads as a refusal).
13
+ //
14
+ // ONE function decides which version a run uses (`pickRunValues`) and ONE applies it (`applyRunValues`): the runner (fresh run,
15
+ // answer-resume, continue) and the CLI's monthly hold all call these, never the files directly.
16
+ import { createHash } from 'node:crypto';
17
+ import { unlinkSync, writeFileSync } from 'node:fs';
18
+ import { join } from 'node:path';
19
+
20
+ import { readFileInside, readdirInside } from './flow.js';
21
+
22
+ export const VALUES_FILE_RE = /^signed-values(?:-r(\d+))?\.json$/;
23
+
24
+ const WAIT_RE = /^(\d+)\s*([smh])$/i;
25
+ const UNIT_MS = { s: 1000, m: 60_000, h: 3_600_000 };
26
+
27
+ /** An ask wait as the signed text spells it (`<int>` then `s`, `m` or `h`), in ms; null when it is not that or not above 0. @param {unknown} text */
28
+ export function parseWaitMs(text) {
29
+ const m = typeof text === 'string' ? WAIT_RE.exec(text.trim()) : null;
30
+ if (m === null) return null;
31
+ const n = Number(m[1]);
32
+ return n > 0 && Number.isSafeInteger(n) ? n * UNIT_MS[m[2].toLowerCase()] : null;
33
+ }
34
+
35
+ /** The wait text for a ttl in ms (`2h`, `30m`, `45s`). @param {number} ms */
36
+ export function waitText(ms) {
37
+ if (ms % 3_600_000 === 0 && ms > 0) return `${ms / 3_600_000}h`;
38
+ if (ms % 60_000 === 0 && ms > 0) return `${ms / 60_000}m`;
39
+ return `${Math.round(ms / 1000)}s`;
40
+ }
41
+
42
+ /**
43
+ * The values a flow's own signature gives: the cap, the ONE send's destination folder (null when the flow has no single file send, so a
44
+ * destination cannot be added or changed), and each ask's wait by its line number.
45
+ * @param {any} arbiter `readFlow`'s arbiter
46
+ * @returns {{ capUsd: number, destination: string|null, askWaits: Record<string, string> }}
47
+ */
48
+ export function flowValues(arbiter) {
49
+ const sends = arbiter.sends ?? [];
50
+ const destination = sends.length === 1 && sends[0].target?.kind === 'file' ? String(sends[0].target.path) : null;
51
+ const askWaits = Object.fromEntries((arbiter.asks ?? []).map((a) => [String(a.line), waitText(a.ttlMs)]));
52
+ return { capUsd: arbiter.capUsd, destination, askWaits };
53
+ }
54
+
55
+ /** @param {{capUsd: number, destination: string|null, askWaits: Record<string,string>}} v the values in canonical key order */
56
+ function canonValues(v) {
57
+ return {
58
+ capUsd: v.capUsd,
59
+ destination: v.destination ?? null,
60
+ askWaits: Object.fromEntries(Object.entries(v.askWaits ?? {}).sort(([a], [b]) => Number(a) - Number(b))),
61
+ };
62
+ }
63
+
64
+ /**
65
+ * The hash the human's click is bound to.
66
+ * @param {{ flow: string, flowSignatureHash: string, runId?: string|null, version: number, values: {capUsd: number, destination: string|null, askWaits: Record<string,string>} }} a
67
+ */
68
+ export function valuesHash({
69
+ flow, flowSignatureHash, runId = null, version, values,
70
+ }) {
71
+ return createHash('sha256').update(JSON.stringify({
72
+ flow, flowSignatureHash, runId, version, values: canonValues(values),
73
+ })).digest('hex');
74
+ }
75
+
76
+ /** True when `a` and `b` are the same values (cap, destination, every wait). */
77
+ export function sameValues(a, b) {
78
+ return JSON.stringify(canonValues(a)) === JSON.stringify(canonValues(b));
79
+ }
80
+
81
+ /** File name of a version. @param {number} version */
82
+ export const valuesFileName = (version) => (version === 0 ? 'signed-values.json' : `signed-values-r${version}.json`);
83
+
84
+ /**
85
+ * The ONE writer of a version file: write-once (`wx`), mode 0600. Refuses a record whose hash does not match its own fields.
86
+ * @param {string} runDir
87
+ * @param {{ flow: string, flowSignatureHash: string, runId: string, version: number, values: any, hash: string, signedBy: string, at: string }} record
88
+ * @returns {{ok: true, file: string} | {ok: false, red: string}}
89
+ */
90
+ export function writeRunValues(runDir, record) {
91
+ const want = valuesHash({
92
+ flow: record.flow, flowSignatureHash: record.flowSignatureHash, runId: record.version === 0 ? null : record.runId, version: record.version, values: record.values,
93
+ });
94
+ if (want !== record.hash) return { ok: false, red: 'signed values: the hash does not match the values — nothing written' };
95
+ const file = join(runDir, valuesFileName(record.version));
96
+ try {
97
+ writeFileSync(file, `${JSON.stringify({ ...record, values: canonValues(record.values) }, null, 2)}\n`, { flag: 'wx', mode: 0o600 });
98
+ } catch (err) {
99
+ return { ok: false, red: err.code === 'EEXIST' ? `signed values: version ${record.version} of this run already exists — never overwritten` : `signed values: could not write ${valuesFileName(record.version)} (${err.code ?? err.message})` };
100
+ }
101
+ return { ok: true, file };
102
+ }
103
+
104
+ /**
105
+ * The ONE decision "which signed version does this run use": the highest version file in the run folder.
106
+ * `{ok:true, none:true}` = the flow's own values; `{ok:true, version, record}`; `{ok:false, red}` = a file that cannot be trusted
107
+ * (unreadable, not JSON, wrong shape, a hash that does not match its fields, a name that disagrees with its version).
108
+ * @param {string} runDir
109
+ * @returns {{ok: true, none: true} | {ok: true, none?: false, version: number, record: any} | {ok: false, red: string}}
110
+ */
111
+ export function pickRunValues(runDir) {
112
+ let best = null;
113
+ for (const name of readdirInside(runDir, '.')) {
114
+ const m = VALUES_FILE_RE.exec(name);
115
+ if (m === null) continue;
116
+ const version = m[1] === undefined ? 0 : Number(m[1]);
117
+ if (best === null || version > best.version) best = { version, name };
118
+ }
119
+ if (best === null) return { ok: true, none: true };
120
+ const f = readFileInside(runDir, best.name);
121
+ if (!f.ok) return { ok: false, red: `signed values: ${best.name} — ${f.missing ? 'unreadable' : f.red}` };
122
+ let record;
123
+ try { record = JSON.parse(f.text); } catch (err) { return { ok: false, red: `signed values: ${best.name} is not valid JSON — ${err.message}` }; }
124
+ const v = record?.values;
125
+ const shaped = record && typeof record === 'object' && record.version === best.version && typeof record.flow === 'string' && typeof record.flowSignatureHash === 'string'
126
+ && typeof record.hash === 'string' && v && typeof v === 'object' && Number.isFinite(v.capUsd) && v.capUsd > 0
127
+ && (v.destination === null || (typeof v.destination === 'string' && v.destination !== ''))
128
+ && v.askWaits && typeof v.askWaits === 'object' && Object.values(v.askWaits).every((w) => parseWaitMs(w) !== null);
129
+ if (!shaped) return { ok: false, red: `signed values: ${best.name} does not have the shape of a signed values record` };
130
+ const want = valuesHash({
131
+ flow: record.flow, flowSignatureHash: record.flowSignatureHash, runId: best.version === 0 ? null : (record.runId ?? null), version: best.version, values: v,
132
+ });
133
+ if (want !== record.hash) return { ok: false, red: `signed values: ${best.name} does not match its own hash — it was changed after it was signed` };
134
+ return { ok: true, version: best.version, record };
135
+ }
136
+
137
+ /**
138
+ * The arbiter a run executes under: the flow's own, with the picked record's cap, send folder and ask waits laid over it. The flow's
139
+ * arbiter object is never mutated. A record for another flow or a changed flow signature is refused; so is a record that names a send
140
+ * or an ask the flow does not have.
141
+ * @param {any} arbiter `readFlow`'s arbiter @param {string} flow @param {string} flowSignatureHash
142
+ * @param {ReturnType<typeof pickRunValues>} picked
143
+ * @returns {{ok: true, arbiter: any, version: number|null} | {ok: false, red: string}}
144
+ */
145
+ export function applyRunValues(arbiter, flow, flowSignatureHash, picked) {
146
+ if (!picked.ok) return { ok: false, red: picked.red };
147
+ if (picked.none) return { ok: true, arbiter, version: null };
148
+ const { record } = picked;
149
+ if (record.flow !== flow || record.flowSignatureHash !== flowSignatureHash) {
150
+ return { ok: false, red: `signed values: ${valuesFileName(picked.version)} was signed for another flow or another signature of this flow — refusing` };
151
+ }
152
+ const own = flowValues(arbiter);
153
+ const v = record.values;
154
+ if ((v.destination === null) !== (own.destination === null)) return { ok: false, red: 'signed values: the destination does not fit this flow (it has no single send folder to change) — refusing' };
155
+ const lines = Object.keys(own.askWaits).sort().join(',');
156
+ if (Object.keys(v.askWaits).sort().join(',') !== lines) return { ok: false, red: 'signed values: the ask waits do not name this flow\'s asks — refusing' };
157
+ return {
158
+ ok: true,
159
+ version: picked.version,
160
+ arbiter: {
161
+ ...arbiter,
162
+ capUsd: v.capUsd,
163
+ sends: (arbiter.sends ?? []).map((s) => (v.destination === null ? s : { ...s, target: { ...s.target, path: v.destination } })),
164
+ asks: (arbiter.asks ?? []).map((a) => ({ ...a, ttlMs: parseWaitMs(v.askWaits[String(a.line)]), ttlSigned: true })),
165
+ },
166
+ };
167
+ }
168
+
169
+ /**
170
+ * A start that refused before the run began (monthly limit, empty key ...) leaves a run folder holding nothing but its signed values
171
+ * file: remove that one file so the folder can be removed too and the run name is not burned. Never touches a folder with anything else.
172
+ * @param {string} runDir @returns {boolean} true when the file was removed
173
+ */
174
+ export function dropUnstartedValues(runDir) {
175
+ const names = readdirInside(runDir, '.');
176
+ if (names.length !== 1 || names[0] !== valuesFileName(0)) return false;
177
+ try { unlinkSync(join(runDir, names[0])); return true; } catch { return false; }
178
+ }
package/src/send.js CHANGED
@@ -11,7 +11,7 @@
11
11
  // in-memory content handed in — so a write that silently truncates to 0
12
12
  // bytes reds here, not upstream).
13
13
 
14
- import { readFileSync } from 'node:fs';
14
+ import { lstatSync, readFileSync } from 'node:fs';
15
15
  import { join } from 'node:path';
16
16
  import { createShellTools } from 'bare-agent/tools';
17
17
 
@@ -30,10 +30,11 @@ const WRITE_TOOL = FOUND_WRITE_TOOL;
30
30
  * @param {string|null} [acceptedSha256] - the sha256 the human's accept recorded
31
31
  * (`answerAsk`, M4b piece 3). Required: none recorded (an answer written by an
32
32
  * older version, or no accept in this process) refuses by name.
33
+ * @param {{root?: string, runDir?: string}} [ctx] the flow root and this run's folder, for the destination refusals
33
34
  * @returns {Promise<{ok:true, path:string, bytes:number} | {ok:false, red:string}>}
34
35
  */
35
- export async function sendViaPrimitive(target, filename, content, acceptedSha256) {
36
- const destination = checkSendDestination(target);
36
+ export async function sendViaPrimitive(target, filename, content, acceptedSha256, ctx = {}) {
37
+ const destination = checkSendDestination(target, ctx);
37
38
  if (!destination.ok) return { ok: false, red: destination.red };
38
39
 
39
40
  // F48 round 4 (redesign) defense in depth: `src/runner.js`'s send slot
@@ -70,6 +71,12 @@ export async function sendViaPrimitive(target, filename, content, acceptedSha256
70
71
  }
71
72
 
72
73
  const path = join(destination.dir, filename);
74
+ // M4e amendment 1: never overwrite. `shell_write` has no exclusive-create mode, so this is an
75
+ // existence check immediately before the write (lstat: a dangling symlink at the name counts as
76
+ // present). A file created in the instants between this check and the write is still overwritten.
77
+ let present = true;
78
+ try { lstatSync(path); } catch (err) { if (err.code === 'ENOENT') present = false; }
79
+ if (present) return { ok: false, red: `send: "${path}" already exists — never overwritten (nothing shipped)` };
73
80
  await WRITE_TOOL.execute({ path, content: serialised });
74
81
 
75
82
  const bytes = readFileSync(path);
package/src/setup.js ADDED
@@ -0,0 +1,127 @@
1
+ // M4e amendment 6 item 4 (docs/wiki/the-module-ladder.md, "M4e", "Amendment 6"): the SETUP record. At sign, the draft folder's own
2
+ // record (the card, each draft and revise with its model, cost and verdict, and the sign) is copied once
3
+ // into the flow folder as `setup.jsonl`. It sits outside the three signed files (`FLOW_FILES`), so `readFlow` and the signature never see
4
+ // it. ONE writer (`writeSetup`, called from `signDraft`, which the CLI and the panel both use) and ONE reader (`readSetup`).
5
+ //
6
+ // What each row throws away: a draft/revise row keeps model, cost, calls, time, verdict, plan hash and its first red, NOT the plan itself (the signed
7
+ // declaration is the plan) nor the model's tokens/rounds; a card row keeps the card's own typed fields. Rows written before amendment 14 may
8
+ // carry `note` / `change` kinds; they are only ever READ back, from the flow's own setup.jsonl.
9
+ // Third outcomes: a draft with no result is `stopped`; a cost nobody booked is `null` (shown "unknown", never $0).
10
+ import { lstatSync, writeFileSync } from 'node:fs';
11
+ import { join } from 'node:path';
12
+
13
+ import { scrub } from './authoring.js';
14
+ import { notCheckedBlock } from './checked.js';
15
+ import { readDraftSpend } from './draftspend.js';
16
+ import { readFileInside, readdirInside } from './flow.js';
17
+ import { readSpendRows } from './provider.js';
18
+
19
+ export const SETUP_FILE = 'setup.jsonl';
20
+ const CARD_RE = /^card-(\d+)\.json$/;
21
+
22
+ const readJson = (dir, rel) => {
23
+ const r = readFileInside(dir, rel);
24
+ if (!r.ok) return null;
25
+ try { return JSON.parse(r.text); } catch { return null; }
26
+ };
27
+ const mtimeIso = (dir, rel) => {
28
+ try { return lstatSync(join(dir, rel)).mtime.toISOString(); } catch { return null; }
29
+ };
30
+
31
+ /** One plan folder's row: model, cost, verdict (green / red / stopped), plan hash, first red. @param {string} sessionDir @param {string} rel `draft` or `draft-<n>` */
32
+ function planRow(sessionDir, rel, kind, n) {
33
+ const hashFile = readFileInside(sessionDir, `${rel}/spec.hash`);
34
+ const hash = hashFile.ok && hashFile.text.trim() !== '' ? hashFile.text.trim() : null;
35
+ const log = readJson(sessionDir, `${rel}/log.json`);
36
+ const leak = readFileInside(sessionDir, `${rel}/scrub-leak.red`);
37
+ const spent = readSpendRows(join(sessionDir, rel, 'spend.jsonl')).filter((r) => r && r.kind === 'draft').pop() ?? readDraftSpend(join(sessionDir, rel));
38
+ let verdict = 'stopped';
39
+ /** @type {string|null} */
40
+ let gap = 'no result was recorded';
41
+ if (hash) { verdict = 'green'; gap = null; } else if (leak.ok || (log && log.ok === false)) {
42
+ verdict = 'red';
43
+ const reds = Array.isArray(log?.reds) ? log.reds.map(String) : [];
44
+ if (leak.ok) reds.push(leak.text.trim());
45
+ gap = reds.join('; ') || 'the plan did not pass the checks';
46
+ }
47
+ return {
48
+ kind, n, at: typeof spent?.at === 'string' ? spent.at : null, model: spent?.model ?? log?.modelId ?? null,
49
+ costUsd: typeof spent?.costUsd === 'number' ? spent.costUsd : null, spendComplete: spent ? spent.spendComplete !== false && typeof spent.costUsd === 'number' : false,
50
+ // calls and time as the draft booked them; null = not recorded (never 0)
51
+ calls: Number.isInteger(spent?.calls) ? spent.calls : null, wallMs: typeof spent?.wallMs === 'number' ? spent.wallMs : null,
52
+ // retries the drafter spent on structure (log.json); null = not recorded (a plan from before it), never 0
53
+ structureRetries: Number.isInteger(log?.structureRetries) ? log.structureRetries : null,
54
+ verdict, hash, gap,
55
+ };
56
+ }
57
+
58
+ /**
59
+ * The rows of a draft's record, oldest first. `sessionDir` is the panel's draft folder (card.json, draft/, card-<n>.json, draft-<n>/); a CLI
60
+ * draft has none, so its record is its one plan folder (`planDir`, read as `draft`) plus the sign.
61
+ * @param {{ sessionDir?: string, planDir: string, hash: string, signedBy: string, signedAt: string, flowHash?: string }} a
62
+ */
63
+ export function buildSetupRows({
64
+ sessionDir, planDir, hash, signedBy, signedAt, flowHash,
65
+ }) {
66
+ const rows = [];
67
+ if (sessionDir) {
68
+ const card = readJson(sessionDir, 'card.json');
69
+ if (card) rows.push({ kind: 'card', n: 0, at: mtimeIso(sessionDir, 'card.json'), card });
70
+ // amendment 14 item 6: a draft begun by Start over says so (written once by the panel's start); its row reads `start over`
71
+ const so = readJson(sessionDir, 'started-over-from.json');
72
+ rows.push(planRow(sessionDir, 'draft', typeof so?.startedOverFrom === 'string' ? 'startover' : 'draft', 0));
73
+ // amendment 14 item 6: each revise is the card as submitted, then its plan row (model, cost, verdict, hash); there is no note row
74
+ const ns = readdirInside(sessionDir, '.').map((f) => CARD_RE.exec(f)?.[1]).filter((x) => x !== undefined).map(Number).sort((a, b) => a - b);
75
+ for (const n of ns) {
76
+ const card = readJson(sessionDir, `card-${n}.json`);
77
+ if (card) rows.push({ kind: 'card', n, at: mtimeIso(sessionDir, `card-${n}.json`), card });
78
+ // M4e amendment 24 item 4: a plan drafted again after the human's answers is booked as `redraft`, not `revise` (it uses none of the 2 revises)
79
+ rows.push(planRow(sessionDir, `draft-${n}`, readJson(sessionDir, `redraft-${n}.json`) ? 'redraft' : 'revise', n));
80
+ }
81
+ } else {
82
+ const r = planRow(planDir, '.', 'draft', 0);
83
+ rows.push(r);
84
+ }
85
+ // M4e amendment 36: the drafter's own "Not checked" list (the green plan folder's not-checked.json), kept word for word with its label. Not signed,
86
+ // not in any hash. An unreadable or missing file is an empty list (a plan from before amendment 25 has none).
87
+ const notChecked = notCheckedBlock(readJson(planDir, 'not-checked.json')?.notChecked);
88
+ rows.push({
89
+ kind: 'sign', n: 0, at: signedAt, signedBy, hash, flowHash: flowHash ?? null, notChecked,
90
+ });
91
+ return rows;
92
+ }
93
+
94
+ /**
95
+ * Write `<flowDir>/setup.jsonl` ONCE ('wx': a second write is refused, never merged or replaced), mode 0600, every row scrubbed of the
96
+ * given key values. Never throws.
97
+ * @param {{ flowDir: string, secrets?: string[] } & Parameters<typeof buildSetupRows>[0]} a
98
+ * @returns {{ ok: true, file: string, rows: number } | { ok: false, red: string }}
99
+ */
100
+ export function writeSetup({ flowDir, secrets = [], ...rest }) {
101
+ const file = join(flowDir, SETUP_FILE);
102
+ try {
103
+ const rows = buildSetupRows(rest);
104
+ const text = rows.map((r) => scrub(JSON.stringify(r), secrets)).join('\n');
105
+ writeFileSync(file, `${text}\n`, { flag: 'wx', mode: 0o600 });
106
+ return { ok: true, file, rows: rows.length };
107
+ } catch (err) {
108
+ return { ok: false, red: err.code === 'EEXIST' ? `setup: ${SETUP_FILE} already exists — never overwritten` : `setup: could not write ${SETUP_FILE} (${err.code ?? err.message})` };
109
+ }
110
+ }
111
+
112
+ /**
113
+ * The flow's setup rows, through the one safe gateway. `present:false` = a flow signed before amendment 6 (or a file that cannot be read).
114
+ * @param {string} flowDir
115
+ * @returns {{ present: false } | { present: true, rows: any[], unreadable: number }}
116
+ */
117
+ export function readSetup(flowDir) {
118
+ const r = readFileInside(flowDir, SETUP_FILE);
119
+ if (!r.ok) return { present: false };
120
+ const rows = [];
121
+ let unreadable = 0;
122
+ for (const line of r.text.split('\n')) {
123
+ if (line.trim() === '') continue;
124
+ try { const row = JSON.parse(line); if (row && typeof row === 'object' && typeof row.kind === 'string') rows.push(row); else unreadable += 1; } catch { unreadable += 1; }
125
+ }
126
+ return { present: true, rows, unreadable };
127
+ }
@@ -17,12 +17,37 @@ export function specHash({ proseText, declarationText, inputFactsText, readoutTe
17
17
  ok: false;
18
18
  red: string;
19
19
  };
20
+ /**
21
+ * The questions a plan folder raised and the answers on disk, READ from its files — the ONE reader (the panel's phase reader, the sign
22
+ * checks and the page all use it). `questions` = [{ k, line, question, answer|null }], `open` = those with no answer. A blank or unreadable
23
+ * answer file counts as no answer. No questions file = `{ questions: [], open: [] }`.
24
+ * @param {string} planDir
25
+ * @returns {{ questions: {k:number, line:number, question:string, answer:string|null}[], open: {k:number, line:number, question:string, answer:null}[] }}
26
+ */
27
+ export function readQuestions(planDir: string): {
28
+ questions: {
29
+ k: number;
30
+ line: number;
31
+ question: string;
32
+ answer: string | null;
33
+ }[];
34
+ open: {
35
+ k: number;
36
+ line: number;
37
+ question: string;
38
+ answer: null;
39
+ }[];
40
+ };
41
+ /** The ONE check that a plan folder with questions is not signable (CLI sign, the page's sign route and signDraft all call it). null = fine. @param {string} planDir */
42
+ export function questionsRefusal(planDir: string): "A question the plan raised is still open. Answer it in the panel (fwdloop panel), then sign the plan it drafts after your answers. Nothing was signed." | "This plan raised questions, and your answers went into a newer plan. Sign the newest plan, not this one. Nothing was signed." | null;
20
43
  /** Literal (never RegExp) key scrub; a secret under 8 chars is skipped so it can't blank ordinary text. */
21
44
  export function scrub(text: any, secrets: any): any;
22
45
  /** Count files directly inside `dir` that contain a secret literally. */
23
46
  export function sweepForSecrets(dir: any, secrets: any): number;
24
47
  /** Exact signed TTL with its unit, never rounded: 2h / 30m / 20s / 1500ms (the largest unit that divides it exactly). */
25
48
  export function fmtTtl(ms: any): string;
49
+ /** Zero-based indexes of the heading lines in a readout's text (split on "\n"): the panel renders those bold. */
50
+ export function readoutHeadIndexes(text: any): any[];
26
51
  /** Plain-text readout of what the human is about to sign. Pure. */
27
52
  export function buildReadout({ declaration, arbiter, lines, name, modelId, costUsd, rounds, spendComplete, root, }: {
28
53
  declaration: any;
@@ -45,6 +70,13 @@ export function readProseFile(file: any): {
45
70
  text: string;
46
71
  red?: undefined;
47
72
  };
73
+ /**
74
+ * The ONE check of a draft's API key, at $0 before any ledger write (C3, amendment 16): `bin/fwdloop draft` and `draftToDir` both call
75
+ * it, so both refuse with the same sentence. null = the key is fine; else the sentence (never the key's value).
76
+ * @param {string} slot @param {Record<string,string|undefined>} env
77
+ * @returns {string|null}
78
+ */
79
+ export function draftKeyRefusal(slot: string, env: Record<string, string | undefined>): string | null;
48
80
  /**
49
81
  * Draft into `dir`. $0 refusals (return {ok:false, wrote:false}, nothing on disk): bad key,
50
82
  * unreadable/blank prose, prose that contains the key, missing inputs / bad signed text, dir
@@ -54,7 +86,7 @@ export function readProseFile(file: any): {
54
86
  *
55
87
  * Test seam: `provider`/`rates`/`modelId` are injected; without them a live provider is built.
56
88
  */
57
- export function draftToDir({ proseFile, dir, root, name, slot, model, budgetUsd, env, provider, rates, modelId, }: {
89
+ export function draftToDir({ proseFile, dir, root, name, slot, model, budgetUsd, env, provider, rates, modelId, noQuestions, }: {
58
90
  proseFile: any;
59
91
  dir: any;
60
92
  root: any;
@@ -66,6 +98,7 @@ export function draftToDir({ proseFile, dir, root, name, slot, model, budgetUsd,
66
98
  provider: any;
67
99
  rates: any;
68
100
  modelId: any;
101
+ noQuestions?: boolean | undefined;
69
102
  }): Promise<{
70
103
  ok: boolean;
71
104
  wrote: boolean;
@@ -91,6 +124,7 @@ export function draftToDir({ proseFile, dir, root, name, slot, model, budgetUsd,
91
124
  leaks: number;
92
125
  dir?: undefined;
93
126
  hash?: undefined;
127
+ questions?: undefined;
94
128
  stop?: undefined;
95
129
  rounds?: undefined;
96
130
  calls?: undefined;
@@ -99,6 +133,7 @@ export function draftToDir({ proseFile, dir, root, name, slot, model, budgetUsd,
99
133
  wrote: boolean;
100
134
  dir: any;
101
135
  hash: string | null;
136
+ questions: number;
102
137
  reds: any;
103
138
  costUsd: number | null;
104
139
  spendComplete: boolean;
@@ -110,13 +145,15 @@ export function draftToDir({ proseFile, dir, root, name, slot, model, budgetUsd,
110
145
  /**
111
146
  * The human step, $0. Every refusal returns reds and writes NO flow.
112
147
  * `signedBy` must come from the human's own invocation (the CLI's --signed-by/username).
148
+ * `sessionDir` (the panel's draft folder: card, notes, every change) widens the setup record; the CLI has none, so its record is the one plan folder.
113
149
  */
114
- export function signDraft({ dir, approve, signedBy, signedAt, env, }: {
150
+ export function signDraft({ dir, approve, signedBy, signedAt, env, sessionDir, }: {
115
151
  dir: any;
116
152
  approve: any;
117
153
  signedBy: any;
118
154
  signedAt?: string | undefined;
119
155
  env?: NodeJS.ProcessEnv | undefined;
156
+ sessionDir: any;
120
157
  }): {
121
158
  ok: boolean;
122
159
  reds: any[];
@@ -124,10 +161,27 @@ export function signDraft({ dir, approve, signedBy, signedAt, env, }: {
124
161
  ok: boolean;
125
162
  flowDir: string;
126
163
  signature: import("./types.js").Signature;
164
+ setup: {
165
+ ok: true;
166
+ file: string;
167
+ rows: number;
168
+ } | {
169
+ ok: false;
170
+ red: string;
171
+ };
127
172
  };
128
173
  export const DRAFT_BUDGET_USD: 0.1;
129
174
  export const SPEC_HASH_FILE: "spec.hash";
175
+ /** The one folder under the flows root where the panel keeps its draft folders (M4e). Starts with a dot, so it is never a flow name. */
176
+ export const PANEL_DRAFTS_DIR: ".drafts";
130
177
  /** Written when the end sweep finds a key in the draft dir; sign refuses a dir that has it. */
131
178
  export const LEAK_MARKER_FILE: "scrub-leak.red";
179
+ /** M4e amendments 24/25: the drafter's questions (written once by `fwdloop draft`), each human answer (`answer-<k>.json`, written once by the panel),
180
+ * and the drafter's own "not checked" reading (information only; never in the readout, so never in the hash). */
181
+ export const QUESTIONS_FILE: "questions.json";
182
+ export const NOT_CHECKED_FILE: "not-checked.json";
183
+ export function ANSWER_FILE(k: any): string;
132
184
  export function SIGN_LINE(dir: any, hash: any): string;
185
+ export const OPEN_QUESTION_SAY: "A question the plan raised is still open. Answer it in the panel (fwdloop panel), then sign the plan it drafts after your answers. Nothing was signed.";
186
+ export const ANSWERED_QUESTION_SAY: "This plan raised questions, and your answers went into a newer plan. Sign the newest plan, not this one. Nothing was signed.";
133
187
  export function costText(n: any, spendComplete?: boolean): string;
package/types/books.d.ts CHANGED
@@ -3,13 +3,13 @@
3
3
  * rewritten, not a book the arbiter reads. One row per process that works on
4
4
  * the run (`src/liveness.js` `recordPid` builds the row).
5
5
  * @param {string} runDir
6
- * @param {{pid: number, startedAt: string, procStart: string|null, leg: 'run'|'resume'}} row
6
+ * @param {{pid: number, startedAt: string, procStart: string|null, leg: 'run'|'resume'|'continue'}} row
7
7
  */
8
8
  export function appendPidRow(runDir: string, row: {
9
9
  pid: number;
10
10
  startedAt: string;
11
11
  procStart: string | null;
12
- leg: "run" | "resume";
12
+ leg: "run" | "resume" | "continue";
13
13
  }): void;
14
14
  /**
15
15
  * The one reader of `pids.jsonl` (same tolerant `readLines` every book uses).
@@ -103,3 +103,15 @@ export function appendHistory(flowDir: string, row: Record<string, any>): void;
103
103
  * @returns {any[]}
104
104
  */
105
105
  export function readHistory(flowDir: string): any[];
106
+ /**
107
+ * The ONE rule for "how did this run end": the LAST history row of the run (a run that was stopped or cap-halted and
108
+ * continued has one row per leg; history stays append-only). `null` when the run has no row yet, and also while a
109
+ * continue is in flight: the last row is a halt row, `halt.json` is gone (the continue consumed it by rename to
110
+ * `halt.<n>.consumed.json`) — an older halt row is then not the run's end. A run halted before halt records existed has
111
+ * no consumed file, so its halt row stays final.
112
+ * @param {any[]} historyRows `readHistory`'s rows @param {string} runDir @param {string} runId
113
+ * @returns {any|null}
114
+ */
115
+ export function endRow(historyRows: any[], runDir: string, runId: string): any | null;
116
+ /** The two outcomes a run can be continued from (M4e amendment 4 item 4): the runner leaves `halt.json` for them. */
117
+ export const HALT_OUTCOMES: readonly string[];
@@ -0,0 +1,64 @@
1
+ /**
2
+ * The first step granting a verb that has no wired implementation, or null. (A verb absent from the catalogue entirely is caught earlier,
3
+ * at declaration validation inside `readFlow`.)
4
+ * @param {Record<string, any>} declaration `readFlow`'s declaration
5
+ * @returns {{step: {emits: string, fromLine: number}, verb: string}|null}
6
+ */
7
+ export function findUnwiredVerbStep(declaration: Record<string, any>): {
8
+ step: {
9
+ emits: string;
10
+ fromLine: number;
11
+ };
12
+ verb: string;
13
+ } | null;
14
+ /** The preflight refusal sentence for an unwired verb, in the words the run's own preflight uses. @param {{step: {emits: string, fromLine: number}, verb: string}} found */
15
+ export function unwiredRed(found: {
16
+ step: {
17
+ emits: string;
18
+ fromLine: number;
19
+ };
20
+ verb: string;
21
+ }): string;
22
+ /**
23
+ * M4e amendment 23: the ONE function that turns "this step's check cannot be built" into a plain sentence. It reads the shape, never
24
+ * bareguard's wording, so no `spec.` path or `checks[` index can reach a human. The steps are numbered by the job line they came from
25
+ * ("line 3" elsewhere), so "step 3" is job line 3. What it throws away: the raw reason (kept apart as `detail`) and any second problem
26
+ * in the same shape (the first one found is the one said). A shape it cannot classify gets the generic sentence.
27
+ * @param {number|undefined} n the step's job line
28
+ * @param {Record<string, any>} shape
29
+ * @returns {string}
30
+ */
31
+ export function unbuildableSay(n: number | undefined, shape: Record<string, any>): string;
32
+ /**
33
+ * M4e amendment 19 4: the first softgreen step whose check bareguard cannot build (a flow signed before amendment 18 may hold one), or null.
34
+ * Built with the same `buildSoftgreenRubric` the close uses, so a step that passes here never crashes at its close for want of a check.
35
+ * `why` is bareguard's raw reason, for the record only (amendment 23); `say` is the plain sentence.
36
+ * @param {Record<string, any>} declaration `readFlow`'s declaration
37
+ * @returns {{step: {emits: string, fromLine: number}, why: string, say: string}|null}
38
+ */
39
+ export function findUnbuildableCheckStep(declaration: Record<string, any>): {
40
+ step: {
41
+ emits: string;
42
+ fromLine: number;
43
+ };
44
+ why: string;
45
+ say: string;
46
+ } | null;
47
+ /** The preflight refusal sentence for a check that cannot be built: plain words, never bareguard's (that is `found.why`). @param {{say: string}} found */
48
+ export function unbuildableRed(found: {
49
+ say: string;
50
+ }): string;
51
+ /**
52
+ * Can this flow run? `read` is `readFlow`'s result (a failed read — signature, tampering, missing files — is a refusal with its own reds).
53
+ * @param {any} read
54
+ * @returns {{ok: true} | {ok: false, red: string, detail?: string}} `detail` is the raw reason, for the record, never the sentence
55
+ */
56
+ export function canFlowRun(read: any): {
57
+ ok: true;
58
+ } | {
59
+ ok: false;
60
+ red: string;
61
+ detail?: string;
62
+ };
63
+ /** The one sentence for a signed flow that will not run: the panel's run door (the POST /api/author/run 409) and Run again say the same words. The Signed list no longer shows a refused flow. @param {string} flow @param {string} red */
64
+ export function willNotRunSay(flow: string, red: string): string;
@@ -0,0 +1,23 @@
1
+ /**
2
+ * One entry per step, in plan order: the plain sentences for what its typed close checks.
3
+ * @param {{ steps?: any[] }} declaration @param {{ hasAsk?: boolean }} [opts] hasAsk = the job has a signed ask line (so "you check it at the ask" is true)
4
+ * @returns {{ step: number, line: number|null, goal: string, class: string, sentences: string[] }[]}
5
+ */
6
+ export function checkedLines(declaration: {
7
+ steps?: any[];
8
+ }, { hasAsk }?: {
9
+ hasAsk?: boolean;
10
+ }): {
11
+ step: number;
12
+ line: number | null;
13
+ goal: string;
14
+ class: string;
15
+ sentences: string[];
16
+ }[];
17
+ /** The "Not checked" block the page shows: always the label, then the drafter's items (an empty list says the drafter listed nothing). @param {unknown} items */
18
+ export function notCheckedBlock(items: unknown): {
19
+ label: string;
20
+ items: any[];
21
+ };
22
+ /** The label that always sits with the "Not checked" list. */
23
+ export const NOT_CHECKED_LABEL: "the drafter's own reading, not a guarantee";