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/books.js CHANGED
@@ -21,11 +21,41 @@
21
21
  import { appendFileSync, mkdirSync } from 'node:fs';
22
22
  import { dirname, join } from 'node:path';
23
23
 
24
+ import { readFileInside } from './flow.js';
25
+
24
26
  function appendLine(filePath, row) {
25
27
  mkdirSync(dirname(filePath), { recursive: true });
26
28
  appendFileSync(filePath, `${JSON.stringify(row)}\n`);
27
29
  }
28
30
 
31
+ /**
32
+ * Raw read-back of one JSONL book, one writer's own sibling reader (M4a
33
+ * piece 2, docs/wiki/the-module-ladder.md M4a scope item 2: "one reader per
34
+ * book"). Never throws on a missing file (`[]`) or a malformed line (that
35
+ * one line is skipped, never crashes the whole read) — the panel and any
36
+ * other reader need an honest best-effort array, not a hard failure over one
37
+ * bad byte someone else wrote.
38
+ *
39
+ * F48 round 3: goes through `readFileInside` (`src/flow.js`) — a book file
40
+ * that is itself a symlink, or that sits behind a symlinked ancestor
41
+ * directory, resolving outside `baseDir` reads as `[]`, same as a missing
42
+ * file, never as the outside target's content.
43
+ * @param {string} baseDir - the run dir (audit.jsonl) or flow dir (history.jsonl)
44
+ * @param {string} relPath - the book's own file name, relative to baseDir
45
+ * @returns {any[]}
46
+ */
47
+ function readLines(baseDir, relPath) {
48
+ const result = readFileInside(baseDir, relPath);
49
+ if (!result.ok) return [];
50
+ const rows = [];
51
+ for (const line of result.text.split('\n')) {
52
+ const trimmed = line.trim();
53
+ if (trimmed.length === 0) continue;
54
+ try { rows.push(JSON.parse(trimmed)); } catch { /* malformed line: skip, never crash the read */ }
55
+ }
56
+ return rows;
57
+ }
58
+
29
59
  /**
30
60
  * Refuse (throw) a row whose cost field is `undefined` (never `?? 0` — the
31
61
  * caller must say `null` on purpose for "unknown"), or whose cost field is
@@ -49,20 +79,186 @@ function checkCostField(row, field, label) {
49
79
  }
50
80
  }
51
81
 
82
+ /**
83
+ * Refuse (throw) a row whose `at` is not a valid ISO timestamp string
84
+ * (Amendment M4a-2, docs/wiki/the-module-ladder.md "M4a" section: "every
85
+ * new row carries a valid `at`"). Never coerced/defaulted here — the caller
86
+ * (the runner's own injected clock) must supply it, so a test's fixed clock
87
+ * governs `at` exactly like it governs every other timestamp this module
88
+ * writes.
89
+ */
90
+ function checkAtField(row, label) {
91
+ const value = row.at;
92
+ if (typeof value !== 'string' || Number.isNaN(Date.parse(value))) {
93
+ throw new Error(`${label}: "at" must be a valid ISO timestamp string, got ${JSON.stringify(value)}`);
94
+ }
95
+ }
96
+
97
+ /**
98
+ * Refuse (throw) a row whose `tokens` is `undefined` (never silently
99
+ * omitted — say `null` on purpose), or whose `tokens` is `null` while
100
+ * `model` is not `null` (Amendment M4a-2: "a model-call audit row written
101
+ * without tokens is refused at write time"), or whose non-null `tokens` is
102
+ * not an object of three non-negative integers
103
+ * (`inputTokens`/`outputTokens`/`cacheReadTokens`). A row with no model
104
+ * call (`model: null`) may carry `tokens: null` — that is the one honest
105
+ * "nothing to sum" case, never a zeroed object standing in for a call that
106
+ * never happened.
107
+ */
108
+ function checkTokensField(row, label) {
109
+ const value = row.tokens;
110
+ if (value === undefined) {
111
+ throw new Error(`${label}: "tokens" must not be undefined — pass null (no model call) or a {inputTokens,outputTokens,cacheReadTokens} object`);
112
+ }
113
+ if (value === null) {
114
+ if (row.model !== null && row.model !== undefined) {
115
+ throw new Error(`${label}: "tokens" is null but "model" is "${row.model}" — a model-call row must carry its tokens`);
116
+ }
117
+ return;
118
+ }
119
+ if (typeof value !== 'object' || Array.isArray(value)) {
120
+ throw new Error(`${label}: "tokens" must be null or an object, got ${JSON.stringify(value)}`);
121
+ }
122
+ for (const key of ['inputTokens', 'outputTokens', 'cacheReadTokens']) {
123
+ const v = value[key];
124
+ if (typeof v !== 'number' || !Number.isInteger(v) || v < 0) {
125
+ throw new Error(`${label}: "tokens.${key}" must be a non-negative integer, got ${JSON.stringify(v)}`);
126
+ }
127
+ }
128
+ }
129
+
130
+ /**
131
+ * Refuse (throw) a row whose `tools` is `undefined` (never silently omitted
132
+ * — say `null` on purpose), or whose `tools` is `null` while `model` is not
133
+ * `null` (Amendment M4a-3, docs/wiki/the-module-ladder.md "M4a" section: a
134
+ * model-call row must carry its tool tally — mirrors `checkTokensField`'s
135
+ * discipline exactly), or whose non-null `tools` is not a plain object of
136
+ * non-negative integer counts. A row with no model call (`model: null`) may
137
+ * carry `tools: null` — the one honest "no model call, so no tool call
138
+ * either" case; a model-call row that made zero tool calls carries `tools:
139
+ * {}`, never `null`.
140
+ */
141
+ function checkToolsField(row, label) {
142
+ const value = row.tools;
143
+ if (value === undefined) {
144
+ throw new Error(`${label}: "tools" must not be undefined — pass null (no model call) or a {toolName: count} object`);
145
+ }
146
+ if (value === null) {
147
+ if (row.model !== null && row.model !== undefined) {
148
+ throw new Error(`${label}: "tools" is null but "model" is "${row.model}" — a model-call row must carry its tool tally`);
149
+ }
150
+ return;
151
+ }
152
+ if (typeof value !== 'object' || Array.isArray(value)) {
153
+ throw new Error(`${label}: "tools" must be null or an object, got ${JSON.stringify(value)}`);
154
+ }
155
+ for (const [name, count] of Object.entries(value)) {
156
+ if (typeof count !== 'number' || !Number.isInteger(count) || count < 0) {
157
+ throw new Error(`${label}: "tools.${name}" must be a non-negative integer, got ${JSON.stringify(count)}`);
158
+ }
159
+ }
160
+ }
161
+
162
+ /**
163
+ * Refuse (throw) a row whose `ungranted` key is present but is not an array
164
+ * of strings (Amendment M4a-3: "ungranted absent or an array of strings").
165
+ * `ungranted` itself is optional — a row with nothing ungranted simply omits
166
+ * the key, never carries an empty array as noise (the caller's own choice;
167
+ * this check only refuses a WRONG shape, never requires the key).
168
+ */
169
+ function checkUngrantedField(row, label) {
170
+ if (!Object.prototype.hasOwnProperty.call(row, 'ungranted')) return;
171
+ const value = row.ungranted;
172
+ if (!Array.isArray(value) || !value.every((v) => typeof v === 'string')) {
173
+ throw new Error(`${label}: "ungranted" must be an array of strings when present, got ${JSON.stringify(value)}`);
174
+ }
175
+ }
176
+
52
177
  /**
53
178
  * One row per attempt (also used for one row per ask and one row per send —
54
179
  * M2 scope item 9). `row` shape: `{ step, attempt, class, verdict, gap, usd,
55
- * spendComplete, wallMs, model, modelMatch, strike }`. Append-only, one
56
- * writer.
180
+ * spendComplete, wallMs, model, modelMatch, strike, at, tokens }` (`at`/
181
+ * `tokens` added by Amendment M4a-2 — every row appended from here on must
182
+ * carry both; a pre-M4a-2 row already on disk simply lacks them, read back
183
+ * as-is by `readAudit`). Append-only, one writer.
57
184
  *
58
185
  * @param {string} runDir
59
186
  * @param {Record<string, any>} row
60
187
  */
61
188
  export function appendAudit(runDir, row) {
62
189
  checkCostField(row, 'usd', 'appendAudit');
190
+ checkAtField(row, 'appendAudit');
191
+ checkTokensField(row, 'appendAudit');
192
+ checkToolsField(row, 'appendAudit');
193
+ checkUngrantedField(row, 'appendAudit');
63
194
  appendLine(join(runDir, 'audit.jsonl'), row);
64
195
  }
65
196
 
197
+ /**
198
+ * Amendment M4a-2's own reader helper: the honest reading of one audit
199
+ * row's `tokens`, whether or not it was written before M4a-2 landed. A row
200
+ * that never had a `tokens` key at all (any row appended before this
201
+ * amendment) reads as "not recorded", never as `null` standing in for a
202
+ * genuine zero-token model call and never an invented number. A row that
203
+ * does carry the key (including a post-M4a-2 `tokens: null` no-model-call
204
+ * row) reads back exactly what was written.
205
+ *
206
+ * @param {Record<string, any>} row
207
+ * @returns {{tokens: {inputTokens:number, outputTokens:number, cacheReadTokens:number} | null, why?: string}}
208
+ */
209
+ export function auditRowTokens(row) {
210
+ if (!row || !Object.prototype.hasOwnProperty.call(row, 'tokens')) {
211
+ return { tokens: null, why: 'not recorded (before M4a-2)' };
212
+ }
213
+ return { tokens: row.tokens };
214
+ }
215
+
216
+ /**
217
+ * Amendment M4a-3's own reader helper, the same honest-read shape as
218
+ * `auditRowTokens`/`auditRowAt`: a row written before M4a-3 never had a
219
+ * `tools` key at all, and reads as "not recorded", never as an invented
220
+ * empty tally. A row that does carry the key reads back exactly what was
221
+ * written — `tools` (object or `null`) and `ungranted` (defaulted to `[]`
222
+ * when the writer left it out, never `undefined`).
223
+ *
224
+ * @param {Record<string, any>} row
225
+ * @returns {{tools: Record<string, number> | null, ungranted: string[], why?: string}}
226
+ */
227
+ export function auditRowTools(row) {
228
+ if (!row || !Object.prototype.hasOwnProperty.call(row, 'tools')) {
229
+ return { tools: null, ungranted: [], why: 'not recorded (before M4a-3)' };
230
+ }
231
+ return { tools: row.tools, ungranted: row.ungranted ?? [] };
232
+ }
233
+
234
+ /**
235
+ * Amendment M4a-2's own reader helper for `at`, the same honest-read shape
236
+ * as `auditRowTokens`: a row written before M4a-2 (any row appended before
237
+ * this amendment, or a raw/legacy line on disk) never had an `at` key at
238
+ * all, and reads as "not recorded", never as `undefined` silently rendered
239
+ * blank. A row that does carry the key reads back exactly what was written.
240
+ *
241
+ * @param {Record<string, any>} row
242
+ * @returns {{at: string|null, why?: string}}
243
+ */
244
+ export function auditRowAt(row) {
245
+ if (!row || !Object.prototype.hasOwnProperty.call(row, 'at')) {
246
+ return { at: null, why: 'not recorded (before M4a-2)' };
247
+ }
248
+ return { at: row.at };
249
+ }
250
+
251
+ /**
252
+ * Read back every row `appendAudit` has written for one run, in file order
253
+ * (append order — never re-sorted). `[]` when the file doesn't exist yet
254
+ * (a run that hasn't made an attempt), never a thrown error.
255
+ * @param {string} runDir
256
+ * @returns {any[]}
257
+ */
258
+ export function readAudit(runDir) {
259
+ return readLines(runDir, 'audit.jsonl');
260
+ }
261
+
66
262
  /**
67
263
  * One row per run. `row` shape: `{ runId, at, outcome, spentUsd,
68
264
  * spendComplete, capUsd, wallMs, signatureHash }`. Append-only, one writer.
@@ -74,3 +270,14 @@ export function appendHistory(flowDir, row) {
74
270
  checkCostField(row, 'spentUsd', 'appendHistory');
75
271
  appendLine(join(flowDir, 'history.jsonl'), row);
76
272
  }
273
+
274
+ /**
275
+ * Read back every row `appendHistory` has written for one flow, in file
276
+ * order. `[]` when the file doesn't exist yet (a flow with no completed/
277
+ * halted run), never a thrown error.
278
+ * @param {string} flowDir
279
+ * @returns {any[]}
280
+ */
281
+ export function readHistory(flowDir) {
282
+ return readLines(flowDir, 'history.jsonl');
283
+ }
@@ -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
+ }
package/src/drafter.js ADDED
@@ -0,0 +1,324 @@
1
+ // borrowed-from: fwdloop poc/m6a/schema.mjs + poc/m6a/draft.mjs@867c25b (M6a POC, bar met 20/20).
2
+ //
3
+ // M6a — the drafter. One forced tool call (`emit_declaration`, toolChoice by
4
+ // name) whose schema is derived from the wired menu (src/primitives.js
5
+ // wiredMenu, over src/catalogue.json) and src/declaration.js SHAPE_KEYS. The
6
+ // model's args, plus the harness's mechanical `inputFacts`, ARE the src
7
+ // declaration — no converter. validateDeclaration decides pass/fail, with the
8
+ // full catalogue and the WIRED_VERBS set, so an unwired verb reds by name.
9
+ //
10
+ // Rounds: 1 first draft + up to MAX_STRUCTURE_RETRIES when the round gave no
11
+ // usable tool call (malformed JSON, text instead, truncation) + up to
12
+ // MAX_REVISIONS when the validator reds (the reds are fed back verbatim).
13
+ // Every round is metered through Loop's onLlmResult; the tool body throws
14
+ // HaltError after capturing so no second (paid) "wrap-up" round happens.
15
+ // Unknown cost is never 0: sumMeterings gives null, and the budget check
16
+ // prices an unpriced round at the ceiling.
17
+
18
+ import { Loop, HaltError } from 'bare-agent';
19
+ import { parseSignedText, unsignedAskTtls } from './signed-text.js';
20
+ import { validateDeclaration, SHAPE_KEYS } from './declaration.js';
21
+ import { loadCatalogue } from './catalogue.js';
22
+ import { WIRED_VERBS, wiredMenu } from './primitives.js';
23
+ import { readInputFacts } from './input-facts.js';
24
+ import { makeProvider, sumMeterings, ceilingCostUsd } from './provider.js';
25
+ import { LIVE_PROVIDER_OPTIONS } from './model-step.js';
26
+
27
+ export const MAX_STRUCTURE_RETRIES = 2;
28
+ export const MAX_REVISIONS = 2;
29
+ export const DRAFT_MAX_TOKENS = 16000;
30
+ export const DRAFT_SKILLS = Object.freeze(['core']);
31
+
32
+ export const CLASSES = Object.freeze(['green', 'softgreen', 'hitl']);
33
+
34
+ const SHAPE_PROPS = Object.freeze({
35
+ maxWords: { type: 'integer', minimum: 1, description: "the whole output's word ceiling" },
36
+ sections: { type: 'array', minItems: 1, items: { type: 'string', minLength: 1 }, description: 'required section headings, in order' },
37
+ linesPerInvoice: { type: 'integer', minimum: 1, description: 'lines the output must carry per invoice' },
38
+ mustCarry: { type: 'array', minItems: 1, items: { type: 'string', minLength: 1 }, description: 'named fields every line must carry' },
39
+ });
40
+
41
+ /** The forced tool's parameter schema. `menu` = wiredMenu(). */
42
+ export function buildDeclarationSchema(menu) {
43
+ const shapeProps = {};
44
+ for (const key of SHAPE_KEYS) {
45
+ if (!SHAPE_PROPS[key]) throw new Error(`schema: SHAPE_KEYS gained "${key}" — add its type to SHAPE_PROPS`);
46
+ shapeProps[key] = SHAPE_PROPS[key];
47
+ }
48
+ return {
49
+ type: 'object',
50
+ properties: {
51
+ steps: {
52
+ type: 'array',
53
+ minItems: 1,
54
+ items: {
55
+ type: 'object',
56
+ properties: {
57
+ primitives: {
58
+ type: 'array',
59
+ items: { type: 'string', enum: menu.map((e) => e.verb) },
60
+ description: 'verbs this step is granted, from the menu only; [] for a pure stop',
61
+ },
62
+ reads: { type: 'array', items: { type: 'string' }, description: 'artifact ids emitted by EARLIER steps only' },
63
+ emits: { type: 'string', minLength: 1, description: 'the ONE new artifact id this step declares (unique)' },
64
+ fromLine: { type: ['integer', 'null'], description: 'the ONE numbered job line this step serves' },
65
+ picks: {
66
+ type: 'object',
67
+ additionalProperties: { type: 'array', items: { type: 'string' } },
68
+ description: 'optional: source role -> heading names this step uses, each copied verbatim from that role\'s headings listed under Inputs; omit when the step names none',
69
+ },
70
+ close: {
71
+ type: 'object',
72
+ properties: {
73
+ class: { type: 'string', enum: [...CLASSES], description: "MUST equal the class of fromLine's guardrail in guardrailClasses; hitl when that line has no guardrail" },
74
+ shape: {
75
+ type: 'object',
76
+ properties: shapeProps,
77
+ additionalProperties: false,
78
+ description: `only when class is softgreen; keys limited to ${SHAPE_KEYS.join(', ')}`,
79
+ },
80
+ },
81
+ required: ['class'],
82
+ additionalProperties: false,
83
+ },
84
+ },
85
+ required: ['primitives', 'reads', 'emits', 'fromLine', 'close'],
86
+ additionalProperties: false,
87
+ },
88
+ },
89
+ guardrailClasses: {
90
+ type: 'object',
91
+ additionalProperties: { type: 'string', enum: [...CLASSES] },
92
+ description: 'one class per job line that HAS a guardrail, keyed by line number as a string',
93
+ },
94
+ unjudgeable: {
95
+ type: 'object',
96
+ additionalProperties: { type: 'string' },
97
+ description: 'line number -> reason, only for a guardrail whose wording resisted judgment (its class stays hitl); {} if none',
98
+ },
99
+ refused: {
100
+ type: 'array',
101
+ items: {
102
+ type: 'object',
103
+ properties: { line: { type: 'integer' }, reason: { type: 'string', minLength: 1 } },
104
+ required: ['line', 'reason'],
105
+ additionalProperties: false,
106
+ },
107
+ description: 'job lines that cannot be served at all, with a reason; [] if none',
108
+ },
109
+ },
110
+ required: ['steps', 'guardrailClasses', 'unjudgeable', 'refused'],
111
+ additionalProperties: false,
112
+ };
113
+ }
114
+
115
+ const TOOL = 'emit_declaration';
116
+
117
+ function jobLinesText(lines, asks) {
118
+ const askLines = new Set(asks.map((a) => a.line));
119
+ return lines
120
+ .map((l) => `${l.n}. ${l.text}${askLines.has(l.n) ? ' [SIGNED ASK — a human stop]' : ''}`
121
+ + `${l.guardrail ? ` [guardrail: ${l.guardrail}]` : ' [no guardrail]'}`)
122
+ .join('\n');
123
+ }
124
+
125
+ export function buildSystemPrompt({ menu, lines, arbiter, factsInfo }) {
126
+ const askLines = arbiter.asks.map((a) => a.line);
127
+ const sendLines = arbiter.sends.map((s) => s.line);
128
+ return [
129
+ `You are the fwdloop drafter. Answer ONLY by calling ${TOOL} — never plain text. You author steps only.`,
130
+ '',
131
+ 'Primitive menu (a grant list; a verb not listed does not exist):',
132
+ ...menu.map((e) => `- ${e.verb}: ${e.desc} (class: ${e.class})`),
133
+ '',
134
+ 'Rules:',
135
+ '- Steps share one artifact space. Each step: primitives (verbs it needs, [] if none), reads (artifact ids emitted by an EARLIER step only), emits (ONE new unique artifact id), fromLine (the ONE job line it serves), close. The machine fills each step\'s goal with that signed line, verbatim — you never write a goal.',
136
+ '- Every numbered job line must be served by a step (fromLine = that line) or listed in "refused" with a reason.',
137
+ '- guardrailClasses: for each job line that HAS a guardrail, classify its wording once: "green" (every figure must cite its source cell), "softgreen" (the human declared a SHAPE the output must take), "hitl" (an ask/accept/review gate, or anything you are not sure of). When unsure, "hitl".',
138
+ '- close.class MUST equal the class of the guardrail on that step\'s fromLine (guardrailClasses[fromLine]); a line with no guardrail is "hitl". A step cannot claim a class its own line does not earn.',
139
+ '- close.shape only on a softgreen step; it is the human\'s declared shape in structured form.',
140
+ `- Signed ask line(s): ${askLines.length ? askLines.join(', ') : 'none'}. For each, emit EXACTLY ONE step: fromLine = that line, close.class "hitl", primitives []. It is a stop only — never grant a primitive on it, and never emit a pause at any other line.`,
141
+ `- Signed send line(s): ${sendLines.length ? sendLines.join(', ') : 'none'}. That step is drafted like any other: grant the write primitive and read the artifact of the ask step that comes before it. Its target and position are signed, not yours.`,
142
+ '- Nothing hitl may come after the last signed ask except the send step.',
143
+ '- You never author a trigger, cap, ask position or TTL, allow-list, send target, or what "done" means.',
144
+ '',
145
+ 'Inputs, mechanically read (facts, not guesses):',
146
+ ...(factsInfo.length ? factsInfo : ['- (none)']),
147
+ '',
148
+ 'The numbered job lines:',
149
+ jobLinesText(lines, arbiter.asks),
150
+ ].join('\n');
151
+ }
152
+
153
+ /**
154
+ * A step's goal = its signed line's text, exactly as parseSignedText's `lines` gives it: the words after
155
+ * "N. " (trailing comma kept; on an ask line the mark is stripped, leaving the question). Continuation
156
+ * lines do not exist in the grammar. A step naming no signed line gets a fixed placeholder, never model prose.
157
+ */
158
+ export function goalForLine(fromLine, lines) {
159
+ const line = Number.isInteger(fromLine) ? lines.find((l) => l.n === fromLine) : undefined;
160
+ return line ? line.text : '(no signed line)';
161
+ }
162
+
163
+ function reviseMessage(reds) {
164
+ return 'The declaration you just emitted was REFUSED by the validator. Fix every one of these and call '
165
+ + `${TOOL} again with the complete corrected declaration:\n${reds.map((r) => `- ${r}`).join('\n')}`;
166
+ }
167
+
168
+ function isPlainObject(v) { return !!v && typeof v === 'object' && !Array.isArray(v); }
169
+
170
+ // F49: deepseek-flash 400s on a forced tool_choice in thinking mode; the drafter forces its tool, so disable thinking.
171
+ export const DRAFT_PROVIDER_OPTIONS = Object.freeze({ ...LIVE_PROVIDER_OPTIONS, thinking: Object.freeze({ type: 'disabled' }) });
172
+
173
+ /**
174
+ * Draft one declaration. `provider`/`rates`/`modelId` may be injected (tests,
175
+ * the batch); otherwise a live provider is built from `slot` (throws on a bad
176
+ * key — the batch preflights first). `budgetUsd` is this draft's hard cap.
177
+ * `makeProviderFn` is a test seam: the live-provider factory (default `makeProvider`).
178
+ *
179
+ * @returns {Promise<{ok:boolean, declaration:object|null, reds:string[], rounds:number, calls:number, spendComplete:boolean,
180
+ * costUsd:number|null, modelReturned:string|null, modelId?:string, tokens?:object|null, structureRetries:number, revisions:number, stop:string|null, log:object[]}>}
181
+ */
182
+ export async function draft({
183
+ proseText, slot = 'deepseek', model, provider: injected, rates: injectedRates, modelId: injectedModelId,
184
+ budgetUsd = 0.10, skills = DRAFT_SKILLS, makeProviderFn = makeProvider,
185
+ }) {
186
+ const fail = (reds, extra = {}) => ({
187
+ ok: false, declaration: null, reds, rounds: 0, calls: 0, spendComplete: true, costUsd: 0, modelReturned: null, structureRetries: 0, revisions: 0, stop: 'pre-flight', log: [], ...extra,
188
+ });
189
+
190
+ // ---- $0 gates, before any provider is built -------------------------------
191
+ const parsed = parseSignedText(proseText);
192
+ if (!parsed.ok) return fail(parsed.reds.map((r) => `signed-text: ${r}`));
193
+ const { lines, arbiter } = parsed;
194
+ const ttlReds = unsignedAskTtls(arbiter);
195
+ if (ttlReds.length) return fail(ttlReds);
196
+ const menu = wiredMenu(skills);
197
+ const facts = readInputFacts(arbiter.sources);
198
+ if (!facts.ok) return fail(facts.reds);
199
+
200
+ let { provider, rates, modelId } = { provider: injected, rates: injectedRates, modelId: injectedModelId };
201
+ if (provider == null) {
202
+ try {
203
+ ({ provider, rates, modelId } = makeProviderFn(slot, { model, ...DRAFT_PROVIDER_OPTIONS }));
204
+ } catch (err) {
205
+ return fail([`key: ${err.message}`]);
206
+ }
207
+ }
208
+
209
+ const schema = buildDeclarationSchema(menu);
210
+ const system = buildSystemPrompt({ menu, lines, arbiter, factsInfo: facts.info });
211
+ // Full catalogue + the wired set: an unwired verb reds "not wired" by name; an unsigned skill reds by skill.
212
+ const cat = loadCatalogue();
213
+ if (!cat.ok) return fail([`catalogue: ${cat.reds.join('; ')}`]);
214
+ const validationCatalogue = cat.primitives;
215
+ const roundCeiling = ceilingCostUsd(modelId);
216
+ // One round at its ceiling must fit the budget, or refuse at $0 before any provider call.
217
+ if (roundCeiling > budgetUsd) {
218
+ return fail([`budget: $${budgetUsd} is below one round's worst-case cost — the minimum budget is $${roundCeiling.toFixed(4)}`]);
219
+ }
220
+
221
+ const meterings = [];
222
+ const log = [];
223
+ let structureRetries = 0;
224
+ let revisions = 0;
225
+ let lastReds = [];
226
+ let lastDecl = null;
227
+ let userText = `Call ${TOOL} now.`;
228
+ let nextKind = 'first'; // what the round about to run actually is
229
+ let validatorReds = []; // the last validator refusal; a structure retry after a revision must not drop it
230
+ let stop = null;
231
+ let calls = 0; // provider calls made (a call that threw before metering is in `calls`, not in `rounds`)
232
+ let unmetered = 0; // calls that failed with no metering: their cost is unknown
233
+
234
+ for (;;) {
235
+ // Budget: spend so far (an unpriced round counts at its ceiling) + one more
236
+ // round at its ceiling must fit, or we stop here, booked.
237
+ const spent = meterings.reduce((sum, ev) => sum + (ev.costUsd ?? roundCeiling), 0);
238
+ if (spent + roundCeiling > budgetUsd) { stop = 'budget'; break; }
239
+
240
+ let captured;
241
+ const tool = {
242
+ name: TOOL,
243
+ description: 'Emit the flow declaration over the granted primitives, or refuse lines you cannot serve.',
244
+ parameters: schema,
245
+ execute: async (args) => { captured = args; throw new HaltError('declaration captured', { rule: 'captured' }); },
246
+ };
247
+ const roundEvents = [];
248
+ const loop = new Loop({
249
+ provider, rates, onLlmResult: async (ev) => { roundEvents.push(ev); meterings.push(ev); },
250
+ });
251
+ let result;
252
+ let threw = null;
253
+ calls += 1;
254
+ try {
255
+ result = await loop.run(
256
+ [{ role: 'system', content: system }, { role: 'user', content: userText }],
257
+ [tool],
258
+ { maxTokens: DRAFT_MAX_TOKENS, toolChoice: { name: TOOL } },
259
+ );
260
+ } catch (err) {
261
+ threw = err;
262
+ if (roundEvents.length === 0) unmetered += 1;
263
+ }
264
+ const entry = { round: log.length + 1, kind: nextKind };
265
+
266
+ if (threw) {
267
+ entry.outcome = `provider-red: ${threw.message}`;
268
+ log.push(entry);
269
+ stop = 'provider-red';
270
+ lastReds = [`provider-red: ${threw.message}`];
271
+ break;
272
+ }
273
+
274
+ if (!isPlainObject(captured)) {
275
+ const malformed = provider?.lastMalformedToolCall ?? null;
276
+ const why = result?.stopReason === 'max_tokens' ? 'truncated: the round hit the output cap with no completed tool call'
277
+ : malformed ? `the tool call's arguments were not valid JSON (${malformed.error})`
278
+ : 'no usable tool call (text instead of the tool)';
279
+ entry.outcome = `structure: ${why}`;
280
+ log.push(entry);
281
+ lastReds = [why];
282
+ if (structureRetries >= MAX_STRUCTURE_RETRIES) { stop = 'structure'; break; }
283
+ structureRetries += 1;
284
+ nextKind = 'structure-retry';
285
+ userText = `Your last reply was not a usable tool call (${why}). Call ${TOOL} now with a complete, valid JSON declaration.`;
286
+ if (validatorReds.length) userText += `\n\nThe last declaration you emitted was still refused by the validator; keep fixing these too:\n${validatorReds.map((r) => `- ${r}`).join('\n')}`;
287
+ continue;
288
+ }
289
+
290
+ const declaration = { .../** @type {object} */ (captured), inputFacts: facts.inputFacts };
291
+ // M6a amendment 1 (F50): the goal is the signed line, set by the machine; whatever the model sent is overwritten.
292
+ if (Array.isArray(declaration.steps)) {
293
+ declaration.steps = declaration.steps.map((st) => (isPlainObject(st) ? { ...st, goal: goalForLine(st.fromLine, lines) } : st));
294
+ }
295
+ const verdict = validateDeclaration(declaration, {
296
+ arbiter, lines, catalogue: validationCatalogue, wired: WIRED_VERBS, verbatimGoals: true,
297
+ });
298
+ lastDecl = declaration;
299
+ if (verdict.ok) {
300
+ entry.outcome = 'valid';
301
+ log.push(entry);
302
+ const m = sumMeterings(meterings);
303
+ return {
304
+ ok: true, declaration, reds: [], rounds: m.rounds, calls, spendComplete: unmetered === 0 && m.costUsd !== null, costUsd: m.costUsd, modelReturned: m.model, modelId, tokens: m.tokens, structureRetries, revisions, stop: null, log,
305
+ };
306
+ }
307
+ lastReds = [...verdict.reds];
308
+ entry.outcome = `validator: ${verdict.reds.length} red(s)`;
309
+ entry.reds = lastReds;
310
+ log.push(entry);
311
+ if (revisions >= MAX_REVISIONS) { stop = 'validator'; break; }
312
+ revisions += 1;
313
+ validatorReds = lastReds;
314
+ nextKind = 'revision';
315
+ userText = reviseMessage(lastReds);
316
+ }
317
+
318
+ const m = sumMeterings(meterings);
319
+ // Runner convention: `costUsd` is the priced floor (null when nothing priced), and `spendComplete:false` marks a
320
+ // call that failed unmetered or a round left unpriced — the number is then "at least", never the whole.
321
+ return {
322
+ ok: false, declaration: lastDecl, reds: lastReds, rounds: m.rounds, calls, spendComplete: unmetered === 0 && m.costUsd !== null, costUsd: m.costUsd, modelReturned: m.model, modelId, tokens: m.tokens, structureRetries, revisions, stop, log,
323
+ };
324
+ }