fwdloop 0.6.0 → 0.8.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/src/ask.js CHANGED
@@ -23,6 +23,7 @@ import { join } from 'node:path';
23
23
  import { randomUUID } from 'node:crypto';
24
24
 
25
25
  import { appendAudit } from './books.js';
26
+ import { readFileInside, resolveInside, readdirInside } from './flow.js';
26
27
 
27
28
  function sleep(ms) {
28
29
  return new Promise((resolve) => { setTimeout(resolve, ms); });
@@ -73,7 +74,13 @@ export function makeFileAskStep({
73
74
  let staleCount = 0;
74
75
 
75
76
  for (;;) {
76
- if (existsSync(answerPath)) {
77
+ // F48 round 3: `answer.json` is checked with `resolveInside`
78
+ // (`src/flow.js`) before it is ever read — a symlinked answer file (or
79
+ // a symlinked run-dir ancestor) is treated exactly like "no answer
80
+ // yet" (kept polling), never read through to an outside file's
81
+ // content standing in for the human's real decision.
82
+ const answerResolved = resolveInside(runDir, 'answer.json');
83
+ if (answerResolved.ok) {
77
84
  let raw = null;
78
85
  try { raw = readFileSync(answerPath, 'utf8'); } catch { raw = null; }
79
86
  let parsed = null;
@@ -88,7 +95,7 @@ export function makeFileAskStep({
88
95
  while (existsSync(staleName)) { staleCount += 1; staleName = join(runDir, `answer.stale.${staleCount}.json`); }
89
96
  renameSync(answerPath, staleName);
90
97
  appendAudit(runDir, {
91
- step: 'ask', attempt, class: null, verdict: 'stale-answer-ignored', gap: `answeredAt ${answeredAt} predates this ask's askedAt ${askedAt}`, usd: 0, spendComplete: true, wallMs: 0, model: null, modelMatch: null, strike: false,
98
+ step: 'ask', attempt, class: null, verdict: 'stale-answer-ignored', gap: `answeredAt ${answeredAt} predates this ask's askedAt ${askedAt}`, usd: 0, spendComplete: true, wallMs: 0, model: null, modelMatch: null, strike: false, at: clock(), tokens: null, tools: null,
92
99
  });
93
100
  // Keep polling — a stale file quarantined does not mean THIS
94
101
  // ask has been answered.
@@ -108,6 +115,86 @@ export function makeFileAskStep({
108
115
  };
109
116
  }
110
117
 
118
+ // ---------------------------------------------------------------------------
119
+ // F47 fix (docs/logs/FINDINGS.md F47, M4a ladder item 1): the ONE shared
120
+ // reader for ask.json's `evidence` field, across every real shape on disk —
121
+ // M3 (`evidence.artifact.text` + `evidence.unjudged[].artifact.text`), M2
122
+ // (`evidence.text`/`evidence.lines`, no unjudged concept), and none (parked
123
+ // before F45 finding 2 landed the evidence-carry fix, so no `evidence` key
124
+ // at all). `bin/fwdloop`'s `artifactText()`/`cmdShow` and `poc/m4/panel-
125
+ // data.mjs` both read ask.json evidence ad hoc today; this is the one
126
+ // place, per "one writer/one reader" (AGENT_RULES.md), that normalises it.
127
+ // Never returns "undefined"/""/0 standing in for missing data — an
128
+ // unparseable shape is a named `why`, never a crash, never silently empty.
129
+ // ---------------------------------------------------------------------------
130
+
131
+ /**
132
+ * @param {any} ask the parsed ask.json object (or its `evidence` field's
133
+ * container — pass the whole ask so a missing `evidence` key is itself a
134
+ * handled case, not the caller's problem).
135
+ * @returns {{ draft: {step?: string, text: string} | null, unjudged: Array<{step: string, emits?: string, text: string}>, why?: string }}
136
+ */
137
+ export function readAskEvidence(ask) {
138
+ const evidence = ask && typeof ask === 'object' ? ask.evidence : undefined;
139
+
140
+ if (evidence === undefined || evidence === null) {
141
+ return {
142
+ draft: null,
143
+ unjudged: [],
144
+ why: 'this ask was parked before evidence was recorded (pre-F45 finding 2)',
145
+ };
146
+ }
147
+
148
+ if (typeof evidence !== 'object') {
149
+ return {
150
+ draft: null,
151
+ unjudged: [],
152
+ why: `ask.json "evidence" is neither an object nor absent — unrecognised shape: ${typeof evidence}`,
153
+ };
154
+ }
155
+
156
+ // M3 shape: evidence.artifact.text (+ evidence.unjudged[]).
157
+ if (evidence.artifact && typeof evidence.artifact === 'object' && typeof evidence.artifact.text === 'string') {
158
+ const rawUnjudged = Array.isArray(evidence.unjudged) ? evidence.unjudged : [];
159
+ const unjudged = [];
160
+ for (const item of rawUnjudged) {
161
+ // `step` (an ask.json unjudged entry's own field name) actually
162
+ // carries the step's GOAL text, not its id — `emits` (when present) is
163
+ // the real step id (e.g. "resume-text"), dropped by the ONLY earlier
164
+ // version of this reader (hamr's review #9, 2026-09-27: the panel's
165
+ // Inbox was labelling by goal text because this function never
166
+ // returned `emits` at all). Both are kept honestly: `step` falls back
167
+ // to `emits` only when the entry names no goal text of its own,
168
+ // `emits` is included ONLY when the entry actually names one — a
169
+ // caller must never assume `emits` is present (an M2/no-`emits`
170
+ // fixture omits it, never a guessed value).
171
+ const step = item && (item.step ?? item.emits);
172
+ const emits = item && typeof item.emits === 'string' ? item.emits : undefined;
173
+ const text = item && item.artifact && typeof item.artifact.text === 'string' ? item.artifact.text : undefined;
174
+ if (typeof step === 'string' && typeof text === 'string') {
175
+ unjudged.push(emits ? { step, emits, text } : { step, text });
176
+ }
177
+ // An unjudged entry with neither a nameable step nor readable text is
178
+ // dropped rather than shown as a blank row — the draft itself is
179
+ // never lost by a malformed sibling entry.
180
+ }
181
+ return { draft: { text: evidence.artifact.text }, unjudged };
182
+ }
183
+
184
+ // M2 shape: evidence.text (+ evidence.lines) — no unjudged concept.
185
+ if (typeof evidence.text === 'string') {
186
+ return { draft: { text: evidence.text }, unjudged: [] };
187
+ }
188
+
189
+ // Present but neither recognised shape — never fall through to
190
+ // `undefined`/`JSON.stringify(undefined)` ("undefined" the string).
191
+ return {
192
+ draft: null,
193
+ unjudged: [],
194
+ why: `ask.json "evidence" has neither ".artifact.text" (M3) nor ".text" (M2) — unrecognised shape: keys ${JSON.stringify(Object.keys(evidence))}`,
195
+ };
196
+ }
197
+
111
198
  // ---------------------------------------------------------------------------
112
199
  // M3 piece 1 (docs/wiki/the-module-ladder.md, "M3 — scope, exit, negative —
113
200
  // SIGNED", scope item 3, the function only — the CLI is piece 2): a separate
@@ -136,13 +223,19 @@ export function answerAsk({
136
223
  return { ok: false, red: `answerAsk: unrecognised decision "${decision}"` };
137
224
  }
138
225
 
139
- const askPath = join(runDir, 'ask.json');
140
- if (!existsSync(askPath)) {
141
- return { ok: false, red: `answerAsk: no open ask for run ${runDir}` };
226
+ // F48 round 3: routed through `readFileInside` — a symlinked `ask.json`
227
+ // (or a symlinked run-dir ancestor) reads as "no open ask", never as some
228
+ // outside file's content.
229
+ const askRead = readFileInside(runDir, 'ask.json');
230
+ if (!askRead.ok) {
231
+ if (askRead.missing) {
232
+ return { ok: false, red: `answerAsk: no open ask for run ${runDir}` };
233
+ }
234
+ return { ok: false, red: `answerAsk: ask.json for run ${runDir} — ${askRead.red}` };
142
235
  }
143
236
  let ask;
144
237
  try {
145
- ask = JSON.parse(readFileSync(askPath, 'utf8'));
238
+ ask = JSON.parse(askRead.text);
146
239
  } catch (err) {
147
240
  return { ok: false, red: `answerAsk: ask.json for run ${runDir} is not valid JSON — ${err.message}` };
148
241
  }
@@ -194,3 +287,164 @@ export function answerAsk({
194
287
  }
195
288
  return { ok: true };
196
289
  }
290
+
291
+ // ---------------------------------------------------------------------------
292
+ // M4a Amendment M4a-1 — SIGNED by hamr 2026-09-27 ("sign m4a1")
293
+ // (docs/wiki/the-module-ladder.md, "M4a" section): every park writes a
294
+ // PERMANENT copy of that ask into `asks/<askId>.json` alongside the
295
+ // (mutable, single-slot) `ask.json`. `ask.json` keeps its current role
296
+ // unchanged — this is a second, append-only record, one file per askId,
297
+ // never overwritten, never deleted (not by resume, not by answer
298
+ // consumption, not by rerun — a rerun always gets a fresh run dir, so it
299
+ // never revisits an old askId). Write-once is a MECHANISM (exclusive
300
+ // create, `{ flag: 'wx' }'), not a check-then-write race: a second write
301
+ // for the same askId is refused, by name, and the first file on disk is
302
+ // left byte-identical.
303
+ // ---------------------------------------------------------------------------
304
+
305
+ /**
306
+ * Writes `asks/<askId>.json` in `runDir`, creating the `asks/` directory if
307
+ * needed. Called by `src/runner.js` right after it writes `ask.json` for a
308
+ * fresh park (same `askId`/`question`/`askedAt`/`expiresAt`/`evidence` — the
309
+ * archive is a permanent copy of the SAME content, not a second source of
310
+ * truth). Exclusive-create: a second call for an already-archived `askId`
311
+ * is refused (a red naming the file) rather than silently overwriting it —
312
+ * proven by the write itself failing (`EEXIST`), not by a separate
313
+ * existence check that a concurrent writer could race past.
314
+ *
315
+ * Crash-order note: this is called AFTER `ask.json` is written, so a crash
316
+ * between the two writes leaves `ask.json` present and `asks/<askId>.json`
317
+ * missing — the run is still correctly parked and resumable (ask.json/
318
+ * state.json govern resume, unchanged), just without its archive entry for
319
+ * that one askId. `listArchivedAsks` below tolerates this (it only reports
320
+ * what is actually on disk); it is never treated as "before M4a-1" (that
321
+ * `why` is reserved for a run with NO `asks/` directory at all).
322
+ *
323
+ * @param {{ runDir: string, askId: string, question: string, askedAt: string, expiresAt: string, evidence: unknown }} opts
324
+ * @returns {{ ok: true } | { ok: false, red: string }}
325
+ */
326
+ export function writeAskArchive({
327
+ runDir, askId, question, askedAt, expiresAt, evidence,
328
+ }) {
329
+ if (typeof runDir !== 'string' || runDir.length === 0) {
330
+ return { ok: false, red: 'writeAskArchive: "runDir" must be a non-empty string' };
331
+ }
332
+ if (typeof askId !== 'string' || askId.length === 0) {
333
+ return { ok: false, red: 'writeAskArchive: "askId" must be a non-empty string' };
334
+ }
335
+ const asksDir = join(runDir, 'asks');
336
+ mkdirSync(asksDir, { recursive: true });
337
+ const archivePath = join(asksDir, `${askId}.json`);
338
+ const payload = {
339
+ askId, question, askedAt, expiresAt, evidence,
340
+ };
341
+ try {
342
+ writeFileSync(archivePath, JSON.stringify(payload, null, 2), { flag: 'wx' });
343
+ } catch (err) {
344
+ if (err.code === 'EEXIST') {
345
+ return { ok: false, red: `writeAskArchive: "${archivePath}" already exists — refusing to overwrite an archived ask` };
346
+ }
347
+ return { ok: false, red: `writeAskArchive: could not write ${archivePath} — ${err.message}` };
348
+ }
349
+ return { ok: true };
350
+ }
351
+
352
+ // ---------------------------------------------------------------------------
353
+ // M4a Amendment M4a-1 reader: pairs each archived ask (`asks/<askId>.json`)
354
+ // with its consumed answer (`answer.<askId>.consumed.json`), by askId only —
355
+ // never by position/order, so the reader is correct even if archives and
356
+ // consumed-answer files land out of step with each other. A run with no
357
+ // `asks/` directory at all predates M4a-1: its asks are not lost, they were
358
+ // simply never kept — reported with a named `why`, never an invented entry.
359
+ // ---------------------------------------------------------------------------
360
+
361
+ /**
362
+ * @param {string} runDir
363
+ * @returns {{ archived: true, asks: Array<{ askId: string, question?: string, askedAt?: string, expiresAt?: string,
364
+ * evidence: ReturnType<typeof readAskEvidence>,
365
+ * answer: { status: string, reason?: string, answeredAt?: string, why?: string } }> } | { archived: false, why: string }}
366
+ */
367
+ export function listArchivedAsks(runDir) {
368
+ // F48 round 3: the `asks/` directory itself — and every entry inside it —
369
+ // is checked with `resolveInside`/`readFileInside` (`src/flow.js`), so a
370
+ // symlinked `asks/` (the exact shape F48's live plant used one level up,
371
+ // for `runs/`) is refused here rather than followed to list an outside
372
+ // directory, and any individual entry that is itself a symlink is skipped
373
+ // before this loop ever sees its name.
374
+ const asksDirResolved = resolveInside(runDir, 'asks');
375
+ if (!asksDirResolved.ok) {
376
+ if (asksDirResolved.missing) {
377
+ return { archived: false, why: 'draft not kept (before M4a-1)' };
378
+ }
379
+ return { archived: false, why: `listArchivedAsks: ${asksDirResolved.red}` };
380
+ }
381
+
382
+ const entries = readdirInside(runDir, 'asks');
383
+
384
+ const asks = [];
385
+ for (const entry of entries.sort()) {
386
+ if (!entry.endsWith('.json')) continue; // eslint-disable-line no-continue
387
+ const askId = entry.slice(0, -'.json'.length);
388
+ const archivePath = join(runDir, 'asks', entry);
389
+ const archiveRead = readFileInside(runDir, join('asks', entry));
390
+ let ask;
391
+ if (!archiveRead.ok) {
392
+ asks.push({
393
+ askId, question: undefined, askedAt: undefined, expiresAt: undefined,
394
+ evidence: {
395
+ draft: null,
396
+ unjudged: [],
397
+ why: archiveRead.missing
398
+ ? `${archivePath} is missing`
399
+ : `${archivePath} — ${archiveRead.red}`,
400
+ },
401
+ answer: { status: 'open' },
402
+ });
403
+ continue; // eslint-disable-line no-continue
404
+ }
405
+ try {
406
+ ask = JSON.parse(archiveRead.text);
407
+ } catch (err) {
408
+ asks.push({
409
+ askId, question: undefined, askedAt: undefined, expiresAt: undefined,
410
+ evidence: { draft: null, unjudged: [], why: `${archivePath} is not valid JSON — ${err.message}` },
411
+ answer: { status: 'open' },
412
+ });
413
+ continue; // eslint-disable-line no-continue
414
+ }
415
+
416
+ const consumedRelPath = `answer.${askId}.consumed.json`;
417
+ const consumedRead = readFileInside(runDir, consumedRelPath);
418
+ let answer = { status: 'open' };
419
+ if (consumedRead.ok) {
420
+ let parsed;
421
+ try {
422
+ parsed = JSON.parse(consumedRead.text);
423
+ const decisionToStatus = { accept: 'accepted', reject: 'rejected', rerun: 'reran' };
424
+ answer = {
425
+ status: decisionToStatus[parsed.decision] ?? `unrecognised: ${parsed.decision}`,
426
+ answeredAt: parsed.answeredAt,
427
+ };
428
+ if (typeof parsed.reason === 'string') answer.reason = parsed.reason;
429
+ } catch (err) {
430
+ answer = { status: 'open', why: `${join(runDir, consumedRelPath)} is not valid JSON — ${err.message}` };
431
+ }
432
+ } else if (typeof ask.expiresAt === 'string' && !Number.isNaN(Date.parse(ask.expiresAt))
433
+ && Date.now() > Date.parse(ask.expiresAt)) {
434
+ answer = { status: 'expired' };
435
+ } else {
436
+ answer = { status: 'unanswered' };
437
+ }
438
+
439
+ asks.push({
440
+ askId,
441
+ question: ask.question,
442
+ askedAt: ask.askedAt,
443
+ expiresAt: ask.expiresAt,
444
+ evidence: readAskEvidence(ask),
445
+ answer,
446
+ });
447
+ }
448
+
449
+ return { archived: true, asks };
450
+ }
@@ -0,0 +1,313 @@
1
+ // M6a — authoring backend: `fwdloop draft` and `fwdloop sign` (docs/wiki/the-module-ladder.md,
2
+ // "M6a — authoring backend", scope items 4 and 5).
3
+ //
4
+ // borrowed-from: fwdloop poc/m6a/batch.mjs@867c25b (literal key scrub + end-of-run sweep).
5
+ //
6
+ // draftToDir — paid step: run the drafter, write a draft dir. Never writes a flow.
7
+ // signDraft — the human step, $0: re-check, then writeFlow with a human `signedBy`.
8
+ //
9
+ // The spec hash (`specHash`, the ONE function; draft prints it, sign recomputes it) covers
10
+ // exactly what the human reads and signs: prose + declaration + input facts + readout, each
11
+ // canonicalised (signature.js canonicalBytes: CRLF -> LF for text, sorted-key JSON).
12
+ // target.json (root + name: where the flow lands) is covered too, so editing it after draft
13
+ // cannot sign under a different name/dir than the readout showed. It does NOT cover log.json /
14
+ // spend.jsonl (a record of how the draft was made, not of what is signed).
15
+
16
+ import { createHash } from 'node:crypto';
17
+ import {
18
+ existsSync, mkdirSync, readFileSync, rmdirSync, writeFileSync,
19
+ } from 'node:fs';
20
+ import path from 'node:path';
21
+
22
+ import { draft } from './drafter.js';
23
+ import { parseSignedText, unsignedAskTtls } from './signed-text.js';
24
+ import { validateDeclaration } from './declaration.js';
25
+ import { loadCatalogue } from './catalogue.js';
26
+ import { WIRED_VERBS } from './primitives.js';
27
+ import { canonicalBytes } from './signature.js';
28
+ import { writeFlow, readFileInside, readdirInside, checkFlowName } from './flow.js';
29
+ import { checkSendDestination } from './runner.js';
30
+ import { PROVIDER_SLOTS, checkKeyPreflight, appendSpendRow } from './provider.js';
31
+
32
+ export const DRAFT_BUDGET_USD = 0.10;
33
+ export const SPEC_HASH_FILE = 'spec.hash';
34
+ /** Written when the end sweep finds a key in the draft dir; sign refuses a dir that has it. */
35
+ export const LEAK_MARKER_FILE = 'scrub-leak.red';
36
+ export const SIGN_LINE = (dir, hash) => `DRAFTED — NOT SIGNED. To sign: fwdloop sign ${dir} --approve ${hash}`;
37
+
38
+ const sha = (bytes) => createHash('sha256').update(bytes).digest('hex');
39
+
40
+ /**
41
+ * The one spec hash. sha256 over the four canonical parts, JSON-array framed so no part can
42
+ * bleed into the next. Never throws.
43
+ * @param {{proseText:string, declarationText:string, inputFactsText:string, readoutText:string, targetText:string}} p
44
+ * @returns {{ok:true, hash:string}|{ok:false, red:string}}
45
+ */
46
+ export function specHash({
47
+ proseText, declarationText, inputFactsText, readoutText, targetText,
48
+ }) {
49
+ const prose = canonicalBytes('prose.txt', proseText);
50
+ if (!prose.ok) return { ok: false, red: prose.red };
51
+ const decl = canonicalBytes('declaration.json', declarationText);
52
+ if (!decl.ok) return { ok: false, red: decl.red };
53
+ // canonicalBytes' 'declaration.json' kind is the generic sorted-key JSON canonicaliser.
54
+ const facts = canonicalBytes('declaration.json', inputFactsText);
55
+ if (!facts.ok) return { ok: false, red: 'input-facts.json: is not valid JSON' };
56
+ const readout = canonicalBytes('prose.txt', readoutText);
57
+ if (!readout.ok) return { ok: false, red: readout.red };
58
+ const target = canonicalBytes('declaration.json', targetText);
59
+ if (!target.ok) return { ok: false, red: 'target.json: is not valid JSON' };
60
+ const framed = JSON.stringify([sha(prose.bytes), sha(decl.bytes), sha(facts.bytes), sha(readout.bytes), sha(target.bytes)]);
61
+ return { ok: true, hash: sha(Buffer.from(framed, 'utf8')) };
62
+ }
63
+
64
+ /** Literal (never RegExp) key scrub; a secret under 8 chars is skipped so it can't blank ordinary text. */
65
+ export function scrub(text, secrets) {
66
+ let out = text;
67
+ for (const s of secrets) if (typeof s === 'string' && s.length >= 8) out = out.split(s).join('[redacted-key]');
68
+ return out;
69
+ }
70
+
71
+ /** Count files directly inside `dir` that contain a secret literally. */
72
+ export function sweepForSecrets(dir, secrets) {
73
+ const live = secrets.filter((s) => typeof s === 'string' && s.length >= 8);
74
+ if (live.length === 0) return 0;
75
+ let leaks = 0;
76
+ for (const name of readdirInside(dir, '.')) {
77
+ const r = readFileInside(dir, name);
78
+ if (r.ok && live.some((s) => r.text.includes(s))) leaks += 1;
79
+ }
80
+ return leaks;
81
+ }
82
+
83
+ /** Exact signed TTL with its unit, never rounded: 2h / 30m / 20s / 1500ms (the largest unit that divides it exactly). */
84
+ export function fmtTtl(ms) {
85
+ if (!Number.isFinite(ms)) return String(ms);
86
+ if (ms % 3600000 === 0 && ms > 0) return `${ms / 3600000}h`;
87
+ if (ms % 60000 === 0 && ms > 0) return `${ms / 60000}m`;
88
+ if (ms % 1000 === 0) return `${ms / 1000}s`;
89
+ return `${ms}ms`;
90
+ }
91
+
92
+ /** One cost renderer: an incomplete total is "at least", never a bare number. */
93
+ export const costText = (n, spendComplete = true) => {
94
+ if (n == null) return 'UNKNOWN (unpriced round)';
95
+ return spendComplete === false ? `at least $${n.toFixed(4)} (incomplete: a provider call is unpriced)` : `$${n.toFixed(4)}`;
96
+ };
97
+ const usd = costText;
98
+
99
+ /** Plain-text readout of what the human is about to sign. Pure. */
100
+ export function buildReadout({ declaration, arbiter, lines, name, modelId, costUsd, rounds, spendComplete }) {
101
+ const out = [];
102
+ out.push(`DRAFT READOUT — NOT SIGNED — flow "${name}"`, '');
103
+ out.push(`Drafted by: ${modelId ?? '?'} in ${rounds} round(s), cost ${usd(costUsd, spendComplete)}`);
104
+ out.push(`Cap per run (signed by you in the prose): $${arbiter.capUsd}`, '');
105
+ out.push('INPUTS');
106
+ for (const s of arbiter.sources) {
107
+ const h = declaration.inputFacts?.[s.role];
108
+ out.push(` ${s.role} = ${s.path}${h ? ` [headings: ${h.join(' | ') || 'none'}]` : ''}`);
109
+ }
110
+ out.push('', 'STEPS');
111
+ declaration.steps.forEach((st, i) => {
112
+ out.push(` ${i + 1}. (line ${st.fromLine}) ${st.goal}`);
113
+ out.push(` grants: ${st.primitives?.length ? st.primitives.join(', ') : 'none (pure stop)'}`
114
+ + ` | reads: ${st.reads?.length ? st.reads.join(', ') : '-'} | emits: ${st.emits} | check: ${st.close?.class}`);
115
+ });
116
+ out.push('', 'ASKS (human stops)');
117
+ for (const a of arbiter.asks) out.push(` line ${a.line}: "${a.question}" (ttl ${fmtTtl(a.ttlMs)})`);
118
+ if (arbiter.asks.length === 0) out.push(' none');
119
+ out.push('', 'SEND TARGET (nothing leaves before an accepted ask)');
120
+ for (const s of arbiter.sends) out.push(` line ${s.line} -> ${s.target.kind}:${s.target.path}`);
121
+ if (arbiter.sends.length === 0) out.push(' none');
122
+ const refused = declaration.refused ?? [];
123
+ if (refused.length) {
124
+ out.push('', 'REFUSED LINES');
125
+ for (const r of refused) out.push(` line ${r.line}: ${r.reason}`);
126
+ }
127
+ out.push('', 'JOB LINES', ...lines.map((l) => ` ${l.n}. ${l.text}`));
128
+ return `${out.join('\n')}\n`;
129
+ }
130
+
131
+ /** Read the prose file. Refuses (a red, never a throw) on unreadable or blank. */
132
+ export function readProseFile(file) {
133
+ let text;
134
+ try { text = readFileSync(file, 'utf8'); } catch (e) { return { ok: false, red: `prose: cannot read "${file}": ${e.code ?? e.message}` }; }
135
+ if (text.trim() === '') return { ok: false, red: `prose: "${file}" is empty` };
136
+ return { ok: true, text };
137
+ }
138
+
139
+ /**
140
+ * Draft into `dir`. $0 refusals (return {ok:false, wrote:false}, nothing on disk): bad key,
141
+ * unreadable/blank prose, prose that contains the key, missing inputs / bad signed text, dir
142
+ * already exists. After a paid round the dir is ALWAYS written — green (spec.hash present) or
143
+ * red (reds, no spec.hash). Spend is booked in `<dir>/spend.jsonl` with the runner's own
144
+ * writer (appendSpendRow); an unpriced round books null, never 0.
145
+ *
146
+ * Test seam: `provider`/`rates`/`modelId` are injected; without them a live provider is built.
147
+ */
148
+ export async function draftToDir({
149
+ proseFile, dir, root, name, slot = 'deepseek', model, budgetUsd = DRAFT_BUDGET_USD, env = process.env, provider, rates, modelId,
150
+ }) {
151
+ const refuse = (reds) => ({ ok: false, wrote: false, reds, costUsd: 0 });
152
+ const nameCheck = checkFlowName(name);
153
+ if (!nameCheck.ok) return refuse([nameCheck.red]);
154
+ if (typeof root !== 'string' || root === '') return refuse(['draft: --root <flows dir> is required']);
155
+ if (!(budgetUsd > 0)) return refuse(['draft: budget must be a positive number']);
156
+ const read = readProseFile(proseFile);
157
+ if (!read.ok) return refuse([String(read.red)]);
158
+ const prose = { text: String(read.text) };
159
+ const injected = provider != null;
160
+ const secretVar = PROVIDER_SLOTS[slot]?.envVar;
161
+ if (!injected) {
162
+ const key = checkKeyPreflight(slot, env);
163
+ if (!key.ok) return refuse([key.message]);
164
+ }
165
+ const secrets = secretVar && env[secretVar] ? [env[secretVar]] : [];
166
+ if (secrets.some((s) => s.length >= 8 && prose.text.includes(s))) return refuse(['prose: contains an API key value — refused']);
167
+ // Claim the dir BEFORE the paid round (exclusive mkdir: a race or an existing path refuses at $0).
168
+ const exists = () => refuse([`draft: "${dir}" already exists — never overwritten, use a new dir`]);
169
+ if (existsSync(dir)) return exists();
170
+ try {
171
+ mkdirSync(path.dirname(path.resolve(dir)), { recursive: true });
172
+ mkdirSync(dir);
173
+ } catch (e) {
174
+ return e.code === 'EEXIST' ? exists() : refuse([`draft: cannot create "${dir}": ${e.code ?? e.message}`]);
175
+ }
176
+
177
+ const result = await draft({
178
+ proseText: prose.text, slot, model, budgetUsd, provider, rates, modelId,
179
+ });
180
+ if (result.stop === 'pre-flight') {
181
+ try { rmdirSync(dir); } catch { /* the claimed dir is still empty; leave it rather than mask the refusal */ }
182
+ return refuse(result.reds);
183
+ }
184
+
185
+ // After a paid round: never a silent throw. The cost is returned so the caller prints it; the dir is claimed and stays.
186
+ const paidFail = (red) => ({
187
+ ok: false, wrote: true, dir, reds: [red], costUsd: result.costUsd, spendComplete: result.spendComplete, stop: 'write', rounds: result.rounds, calls: result.calls, leaks: 0,
188
+ });
189
+ const parsed = parseSignedText(prose.text); // the drafter already proved it parses
190
+ if (!parsed.ok) return paidFail(`parse: ${parsed.reds.join('; ')}`);
191
+ const dj = (o) => `${JSON.stringify(o, null, 2)}\n`;
192
+ const files = {};
193
+ files['prose.txt'] = prose.text; // verbatim
194
+ const targetText = dj({ root, name });
195
+ files['target.json'] = targetText;
196
+ files['log.json'] = scrub(dj({
197
+ ok: result.ok, stop: result.stop, reds: result.reds, rounds: result.rounds, calls: result.calls, costUsd: result.costUsd, spendComplete: result.spendComplete,
198
+ modelId: result.modelId, modelReturned: result.modelReturned, structureRetries: result.structureRetries,
199
+ revisions: result.revisions, log: result.log,
200
+ }), secrets);
201
+ let hash = null;
202
+ if (result.ok) {
203
+ const declarationText = scrub(dj(result.declaration), secrets);
204
+ const inputFactsText = scrub(dj(result.declaration.inputFacts), secrets);
205
+ const readoutText = scrub(buildReadout({
206
+ declaration: result.declaration, arbiter: parsed.arbiter, lines: parsed.lines, name, modelId: result.modelId, costUsd: result.costUsd, rounds: result.rounds, spendComplete: result.spendComplete,
207
+ }), secrets);
208
+ files['declaration.json'] = declarationText;
209
+ files['input-facts.json'] = inputFactsText;
210
+ files['readout.txt'] = readoutText;
211
+ const h = specHash({
212
+ proseText: prose.text, declarationText, inputFactsText, readoutText, targetText,
213
+ });
214
+ if (!h.ok) return paidFail(`hash: ${h.red}`);
215
+ hash = h.hash; // spec.hash is written only after a clean sweep, below
216
+ } else if (result.declaration) {
217
+ files['declaration.rejected.json'] = scrub(dj(result.declaration), secrets);
218
+ }
219
+
220
+ // The spend is booked FIRST, so a later write failure cannot leave a paid round unbooked.
221
+ let leaks;
222
+ try {
223
+ appendSpendRow(path.join(dir, 'spend.jsonl'), {
224
+ kind: 'draft',
225
+ model: result.modelId ?? modelId ?? null,
226
+ modelReturned: result.modelReturned,
227
+ tokens: result.tokens ?? null,
228
+ costUsd: result.costUsd, // null when any round was unpriced — never 0
229
+ rounds: result.rounds,
230
+ calls: result.calls,
231
+ spendComplete: result.spendComplete,
232
+ stop: result.stop,
233
+ budgetUsd,
234
+ });
235
+ for (const [f, text] of Object.entries(files)) writeFileSync(path.join(dir, f), text);
236
+ leaks = sweepForSecrets(dir, secrets);
237
+ if (leaks > 0) {
238
+ const red = `scrub: ${leaks} file(s) in the draft dir contain a key value`;
239
+ writeFileSync(path.join(dir, LEAK_MARKER_FILE), `${red}\n`); // no spec.hash; sign also refuses on this marker
240
+ return { ok: false, wrote: true, reds: [red], costUsd: result.costUsd, spendComplete: result.spendComplete, leaks };
241
+ }
242
+ if (hash) writeFileSync(path.join(dir, SPEC_HASH_FILE), `${hash}\n`);
243
+ } catch (e) {
244
+ return paidFail(`write failed after the paid round (${e.code ?? e.message}); the draft dir is incomplete and never signable`);
245
+ }
246
+ return {
247
+ ok: result.ok, wrote: true, dir, hash, reds: result.reds, costUsd: result.costUsd, spendComplete: result.spendComplete, stop: result.stop, rounds: result.rounds, calls: result.calls, leaks: 0,
248
+ };
249
+ }
250
+
251
+ /**
252
+ * The human step, $0. Every refusal returns reds and writes NO flow.
253
+ * `signedBy` must come from the human's own invocation (the CLI's --signed-by/username).
254
+ */
255
+ export function signDraft({
256
+ dir, approve, signedBy, signedAt = new Date().toISOString(), env = process.env,
257
+ }) {
258
+ const refuse = (...reds) => ({ ok: false, reds });
259
+ if (readFileInside(dir, LEAK_MARKER_FILE).ok) return refuse(`sign: "${dir}" carries a key-leak marker (${LEAK_MARKER_FILE}) — never signed`);
260
+ // Sign is $0 and takes no key, so it can only sweep for keys present in ITS env (any provider slot's).
261
+ // With none set the sweep is skipped: the marker above and the missing spec.hash are then the guard.
262
+ const keys = Object.values(PROVIDER_SLOTS).map((p) => env[p.envVar]).filter(Boolean);
263
+ if (sweepForSecrets(dir, keys) > 0) return refuse(`sign: "${dir}" contains a key value — nothing signed`);
264
+ if (typeof approve !== 'string' || approve === '') return refuse('sign: --approve <hash> is required');
265
+ const read = (f) => readFileInside(dir, f);
266
+ const parts = {};
267
+ for (const f of ['prose.txt', 'declaration.json', 'input-facts.json', 'readout.txt', SPEC_HASH_FILE, 'target.json']) {
268
+ const r = read(f);
269
+ if (!r.ok) return refuse(`sign: "${dir}" is not a green draft — ${f} ${r.missing ? 'is missing' : `is refused (${r.red})`}`);
270
+ parts[f] = r.text;
271
+ }
272
+ const h = specHash({
273
+ proseText: parts['prose.txt'], declarationText: parts['declaration.json'], inputFactsText: parts['input-facts.json'], readoutText: parts['readout.txt'], targetText: parts['target.json'],
274
+ });
275
+ if (!h.ok) return refuse(`sign: ${h.red}`);
276
+ if (approve !== h.hash) return refuse('sign: --approve does not match the draft as it is now (edited since it was drafted, or the wrong hash) — nothing signed');
277
+ if (parts[SPEC_HASH_FILE].trim() !== h.hash) return refuse('sign: spec.hash was not written by the draft for these files — nothing signed');
278
+
279
+ let target;
280
+ let declaration;
281
+ try {
282
+ target = JSON.parse(parts['target.json']);
283
+ declaration = JSON.parse(parts['declaration.json']);
284
+ } catch (e) {
285
+ return refuse(`sign: draft file is not valid JSON — ${e.message}`);
286
+ }
287
+ const signed = parseSignedText(parts['prose.txt']);
288
+ if (!signed.ok) return { ok: false, reds: signed.reds };
289
+ const ttlReds = unsignedAskTtls(signed.arbiter);
290
+ if (ttlReds.length) return { ok: false, reds: ttlReds };
291
+ const cat = loadCatalogue();
292
+ if (!cat.ok) return refuse(`sign: catalogue: ${cat.reds.join('; ')}`);
293
+ const verdict = validateDeclaration(declaration, {
294
+ arbiter: signed.arbiter, lines: signed.lines, catalogue: cat.primitives, wired: WIRED_VERBS, verbatimGoals: true,
295
+ });
296
+ if (!verdict.ok) return { ok: false, reds: verdict.reds };
297
+
298
+ const reds = [];
299
+ for (const s of signed.arbiter.sources) {
300
+ if (s.kind === 'file' && !existsSync(s.path)) reds.push(`sign: input source "${s.role}" is missing at ${s.path}`);
301
+ }
302
+ for (const s of signed.arbiter.sends) {
303
+ const d = checkSendDestination(`${s.target.kind}:${s.target.path}`);
304
+ if (!d.ok) reds.push(`sign: ${d.red}`);
305
+ }
306
+ if (reds.length) return { ok: false, reds };
307
+
308
+ const written = writeFlow({
309
+ root: target.root, name: target.name, proseText: parts['prose.txt'], declaration, signedBy, signedAt, catalogue: cat.primitives,
310
+ });
311
+ if (!written.ok) return { ok: false, reds: written.reds };
312
+ return { ok: true, flowDir: written.dir, signature: written.signature };
313
+ }