fwdloop 0.7.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/bin/fwdloop CHANGED
@@ -33,6 +33,9 @@ import { resolvePrimitives } from '../src/primitives.js';
33
33
  import { checkKeyPreflight } from '../src/provider.js';
34
34
  import { answerAsk, readAskEvidence } from '../src/ask.js';
35
35
  import { panelMain } from '../src/panel/server.js';
36
+ import { isInteractive, confirmTypedName, NEEDS_TTY } from '../src/sign-confirm.js';
37
+ import { draftToDir, signDraft, SIGN_LINE, costText } from '../src/authoring.js';
38
+ import { userInfo } from 'node:os';
36
39
 
37
40
  // The baseline model (project rule, CLAUDE.md/AGENT_RULES: "deepseek-flash
38
41
  // ... Never Claude for fwdloop's own runs") — the ONE provider slot this CLI
@@ -537,19 +540,94 @@ async function cmdPanel(rest) {
537
540
  process.exitCode = code;
538
541
  }
539
542
 
543
+ // ---------------------------------------------------------------------------
544
+ // draft / sign — M6a (docs/wiki/the-module-ladder.md, "M6a — authoring
545
+ // backend", scope items 4-5). `draft` is the one paid step and never writes a
546
+ // flow; `sign` is the human step ($0) and the only path that writes one.
547
+ // Test-only escape hatch for draft, same two-gate shape as resolveModelStep:
548
+ // NODE_ENV=test AND FWDLOOP_TEST_DRAFT_PROVIDER (a module whose default export
549
+ // returns { provider, rates, modelId }).
550
+ // ---------------------------------------------------------------------------
551
+
552
+ async function cmdDraft(rest) {
553
+ const { values, positionals } = parseArgs({
554
+ args: rest,
555
+ options: {
556
+ out: { type: 'string' }, root: { type: 'string' }, name: { type: 'string' }, budget: { type: 'string' },
557
+ },
558
+ allowPositionals: true,
559
+ });
560
+ const proseFile = positionals[0];
561
+ if (!proseFile) fail('draft: a prose file is required — fwdloop draft <prose.txt> --out <draftDir> --root <flowsDir> --name <flow> [--budget <usd>]');
562
+ for (const req of ['out', 'root', 'name']) if (!values[req]) fail(`draft: --${req} is required`);
563
+
564
+ let injected = {};
565
+ if (process.env.NODE_ENV === 'test' && process.env.FWDLOOP_TEST_DRAFT_PROVIDER) {
566
+ const mod = await import(pathToFileURL(resolve(process.env.FWDLOOP_TEST_DRAFT_PROVIDER)).href);
567
+ injected = await mod.default();
568
+ }
569
+ const result = await draftToDir({
570
+ proseFile: resolve(proseFile),
571
+ dir: resolve(values.out),
572
+ root: resolve(values.root),
573
+ name: values.name,
574
+ budgetUsd: values.budget === undefined ? undefined : Number(values.budget),
575
+ ...injected,
576
+ });
577
+ const cost = result.costUsd === null ? 'UNKNOWN' : costText(Number(result.costUsd), result.spendComplete);
578
+ if (!result.wrote) {
579
+ process.stderr.write(`fwdloop: draft refused at $0 — ${result.reds.join('; ')}\n`);
580
+ process.exitCode = 1;
581
+ return;
582
+ }
583
+ process.stdout.write(`draft dir: ${resolve(values.out)} cost: ${cost}\n`);
584
+ if (!result.ok) {
585
+ process.stderr.write(`fwdloop: draft RED (${result.stop ?? 'scrub'}) — ${result.reds.join('; ')}\n`);
586
+ process.exitCode = 1;
587
+ return;
588
+ }
589
+ process.stdout.write(`${SIGN_LINE(resolve(values.out), result.hash)}\n`);
590
+ }
591
+
592
+ async function cmdSign(rest) {
593
+ const { values, positionals } = parseArgs({
594
+ args: rest,
595
+ options: { approve: { type: 'string' }, 'signed-by': { type: 'string' } },
596
+ allowPositionals: true,
597
+ });
598
+ const dir = positionals[0];
599
+ if (!dir) fail('sign: a draft dir is required — fwdloop sign <dir> --approve <hash>');
600
+ // Amendment 2: a person at a keyboard. TTY check first (cheapest), then the typed flow name; only then
601
+ // signDraft's own $0 checks (hash, wired, goals, TTL, sources, send, leak). signDraft writes only on success.
602
+ if (!isInteractive()) fail(`sign refused — ${NEEDS_TTY}`);
603
+ let flowName;
604
+ const tj = readFileInside(resolve(dir), 'target.json');
605
+ try { flowName = tj.ok ? JSON.parse(tj.text).name : undefined; } catch { flowName = undefined; }
606
+ if (typeof flowName !== 'string' || flowName === '') fail('sign refused — the draft has no readable target.json name');
607
+ const typed = await confirmTypedName({ name: flowName });
608
+ if (!typed.ok) fail(`sign refused — ${typed.red}`);
609
+ const result = signDraft({
610
+ dir: resolve(dir), approve: values.approve, signedBy: values['signed-by'] ?? userInfo().username,
611
+ });
612
+ if (!result.ok) fail(`sign refused — ${result.reds.join('; ')}`);
613
+ process.stdout.write(`signed: ${result.flowDir} (by ${result.signature.signedBy})\n`);
614
+ }
615
+
540
616
  // ---------------------------------------------------------------------------
541
617
 
542
618
  async function main() {
543
619
  const [verb, ...rest] = process.argv.slice(2);
544
- if (!verb) fail('usage: fwdloop run|inbox|show|answer|resume|panel ...');
620
+ if (!verb) fail('usage: fwdloop draft|sign|run|inbox|show|answer|resume|panel ...');
545
621
 
622
+ if (verb === 'draft') return cmdDraft(rest);
623
+ if (verb === 'sign') return cmdSign(rest);
546
624
  if (verb === 'run') return cmdRun(rest);
547
625
  if (verb === 'inbox') return cmdInbox(rest);
548
626
  if (verb === 'show') return cmdShow(rest);
549
627
  if (verb === 'answer') return cmdAnswer(rest);
550
628
  if (verb === 'resume') return cmdResume(rest);
551
629
  if (verb === 'panel') return cmdPanel(rest);
552
- fail(`unknown verb "${verb}" — expected run | inbox | show | answer | resume | panel`);
630
+ fail(`unknown verb "${verb}" — expected draft | sign | run | inbox | show | answer | resume | panel`);
553
631
  return undefined;
554
632
  }
555
633
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "fwdloop",
3
- "version": "0.7.0",
3
+ "version": "0.8.0",
4
4
  "description": "Describe a job as steps and guardrails; an agent builds the workflow, pauses for humans where you said, checks every step happened, and reruns it under budgets it cannot touch.",
5
5
  "type": "module",
6
6
  "main": "./src/index.js",
@@ -49,12 +49,12 @@
49
49
  "NOTICE"
50
50
  ],
51
51
  "dependencies": {
52
- "bare-agent": "^0.48.0",
52
+ "bare-agent": "^0.49.0",
53
53
  "bareguard": "^0.19.2",
54
54
  "litectx": "^0.32.0"
55
55
  },
56
56
  "devDependencies": {
57
- "typescript": "^5.9.3",
58
- "@types/node": "^22.20.4"
57
+ "@types/node": "^22.20.4",
58
+ "typescript": "^5.9.3"
59
59
  }
60
60
  }
@@ -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
+ }
@@ -23,7 +23,7 @@
23
23
  "verb": "recent", "component": "select", "package": "litectx", "symbol": "LiteCtx", "method": "recentMemory", "class": "read", "skill": "core", "desc": "List the most recently saved notes, newest first."
24
24
  },
25
25
  {
26
- "verb": "compress", "component": "compress", "package": "litectx", "symbol": "compress", "class": "read", "skill": "core", "desc": "Shorten a piece of text to fit a small prompt (full, signature-only, or dropped)."
26
+ "verb": "compress", "component": "compress", "package": "litectx", "symbol": "compress", "class": "read", "skill": "core", "desc": "Shrink source code: keep each function header and its doc comment, drop the body (or reduce it to a name). Code only — prose and markdown come back unchanged."
27
27
  },
28
28
  {
29
29
  "verb": "peek", "component": "compress", "package": "litectx", "symbol": "LiteCtx", "method": "peek", "class": "read", "skill": "core", "desc": "Preview a parked item's start and end without loading all of it."
@@ -249,11 +249,15 @@ function deriveFromLine(fromLine, lines, guardrailClasses) {
249
249
  * exception.
250
250
  *
251
251
  * @param {unknown} declaration
252
- * @param {{ arbiter?: unknown, lines?: unknown, catalogue?: unknown }} [context]
252
+ * `wired` (optional Set of verbs): when given, a granted verb outside it is a red
253
+ * by name, even if the catalogue lists it. Omitted = no wired check (existing callers).
254
+ * `verbatimGoals` (optional boolean; M6a amendment 1): when true, a step naming a signed line must carry that line's
255
+ * text as its goal, exactly. Off by default so already-signed flows keep running; draft and sign turn it on.
256
+ * @param {{ arbiter?: unknown, lines?: unknown, catalogue?: unknown, wired?: Set<string>, verbatimGoals?: boolean }} [context]
253
257
  * @returns {ValidateDeclarationResult}
254
258
  */
255
259
  export function validateDeclaration(declaration, context = {}) {
256
- const { arbiter, lines, catalogue } = context;
260
+ const { arbiter, lines, catalogue, wired, verbatimGoals } = context;
257
261
  const reds = [];
258
262
 
259
263
  if (!isPlainObject(declaration)) {
@@ -413,6 +417,12 @@ export function validateDeclaration(declaration, context = {}) {
413
417
  if (typeof step.goal !== 'string' || step.goal.length === 0) {
414
418
  reds.push(`declaration: ${label}.goal must be a non-empty string`);
415
419
  }
420
+ if (verbatimGoals === true && typeof step.goal === 'string' && Number.isInteger(step.fromLine)) {
421
+ const own = safeLines.find((l) => l.n === step.fromLine);
422
+ if (own && step.goal !== own.text) {
423
+ reds.push(`declaration: ${label}.goal is not its signed line ${own.n} verbatim (expected ${JSON.stringify(own.text)}, got ${JSON.stringify(step.goal)}) — the goal is the human's line, never reworded`);
424
+ }
425
+ }
416
426
 
417
427
  // primitives
418
428
  const primitives = Array.isArray(step.primitives) ? step.primitives : null;
@@ -425,6 +435,10 @@ export function validateDeclaration(declaration, context = {}) {
425
435
  reds.push(`declaration: ${label}.primitives names "${verb}", which is not in the catalogue`);
426
436
  continue;
427
437
  }
438
+ if (wired && !wired.has(verb)) {
439
+ reds.push(`declaration: ${label}.primitives "${verb}" is in the catalogue but not wired (no implementation yet)`);
440
+ continue;
441
+ }
428
442
  if (!skills.includes(entry.skill)) {
429
443
  reds.push(`declaration: ${label}.primitives "${verb}" needs skill "${entry.skill}", which is not signed (skills: ${skills.join(', ') || 'none'})`);
430
444
  }
package/src/docx.js CHANGED
@@ -127,8 +127,9 @@ function extractText(xml) {
127
127
  return { text: paragraphs.map(paragraphText).join('\n'), paragraphs: paragraphs.length };
128
128
  }
129
129
 
130
- /** @param {string} path @returns {{ok:true,text:string,paragraphs:number}|{ok:false,red:string}} */
131
- export function readDocxText(path) {
130
+ /** One reader for word/document.xml: the file, the zip entry, the bounded inflate.
131
+ * @param {string} path @returns {{ok:true,xml:string}|{ok:false,red:string}} */
132
+ function loadDocumentXml(path) {
132
133
  let buf;
133
134
  try {
134
135
  buf = readFileSync(path);
@@ -139,7 +140,35 @@ export function readDocxText(path) {
139
140
  if (entry.red) return { ok: false, red: entry.red };
140
141
  const read = readEntryBytes(buf, entry);
141
142
  if (read.red || !read.data) return { ok: false, red: read.red ?? 'no data decoded' };
142
- const xml = read.data.toString('utf8');
143
- const { text, paragraphs } = extractText(xml);
143
+ return { ok: true, xml: read.data.toString('utf8') };
144
+ }
145
+
146
+ /** @param {string} path @returns {{ok:true,text:string,paragraphs:number}|{ok:false,red:string}} */
147
+ export function readDocxText(path) {
148
+ const doc = loadDocumentXml(path);
149
+ if (!doc.ok) return doc;
150
+ const { text, paragraphs } = extractText(doc.xml);
144
151
  return { ok: true, text, paragraphs };
145
152
  }
153
+
154
+ // Heading paragraphs: <w:pStyle w:val="Heading1"/> .. HeadingN, or Title. The
155
+ // style ID is matched, not styles.xml's display name — Word writes the ID
156
+ // "Heading1" for the built-in "heading 1"; a custom-named heading style is
157
+ // not seen (declared loss). Text is the paragraph's runs, whitespace-trimmed;
158
+ // an empty heading paragraph is dropped.
159
+ const HEADING_STYLE_RE = /<w:pStyle\s+w:val="(?:Heading\d+|Title)"\s*\/?>/i;
160
+
161
+ function extractHeadings(xml) {
162
+ const paragraphs = xml.match(/<w:p[ >][\s\S]*?<\/w:p>/g) || [];
163
+ return paragraphs
164
+ .filter((p) => HEADING_STYLE_RE.test(p))
165
+ .map((p) => paragraphText(p).replace(/\s+/g, ' ').trim())
166
+ .filter((t) => t !== '');
167
+ }
168
+
169
+ /** @param {string} path @returns {{ok:true,headings:string[]}|{ok:false,red:string}} */
170
+ export function readDocxHeadings(path) {
171
+ const doc = loadDocumentXml(path);
172
+ if (!doc.ok) return doc;
173
+ return { ok: true, headings: extractHeadings(doc.xml) };
174
+ }