fwdloop 0.12.0 → 0.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/bin/fwdloop +155 -27
  2. package/package.json +2 -2
  3. package/src/ask.js +3 -0
  4. package/src/authoring.js +135 -16
  5. package/src/books.js +23 -2
  6. package/src/canrun.js +106 -0
  7. package/src/catalogue.json +2 -2
  8. package/src/checked.js +50 -0
  9. package/src/closers.js +112 -91
  10. package/src/config.js +2 -1
  11. package/src/declaration.js +175 -3
  12. package/src/drafter.js +148 -10
  13. package/src/draftspend.js +70 -0
  14. package/src/flow.js +43 -0
  15. package/src/keysfile.js +4 -2
  16. package/src/liveness.js +1 -1
  17. package/src/model-step.js +31 -5
  18. package/src/monthly.js +195 -28
  19. package/src/panel/author.js +638 -0
  20. package/src/panel/authorcard.js +340 -0
  21. package/src/panel/authorflows.js +317 -0
  22. package/src/panel/authorresume.js +149 -0
  23. package/src/panel/authorstart.js +257 -0
  24. package/src/panel/authorvalues.js +110 -0
  25. package/src/panel/data.js +318 -99
  26. package/src/panel/index.html +2000 -330
  27. package/src/panel/resume.js +6 -8
  28. package/src/panel/server.js +122 -119
  29. package/src/panel/settings.js +8 -6
  30. package/src/panel/spawn.js +77 -0
  31. package/src/provider.js +12 -17
  32. package/src/runner.js +707 -104
  33. package/src/runvalues.js +178 -0
  34. package/src/send.js +10 -3
  35. package/src/setup.js +127 -0
  36. package/types/authoring.d.ts +56 -2
  37. package/types/books.d.ts +14 -2
  38. package/types/canrun.d.ts +64 -0
  39. package/types/checked.d.ts +23 -0
  40. package/types/closers.d.ts +47 -28
  41. package/types/config.d.ts +1 -0
  42. package/types/declaration.d.ts +23 -1
  43. package/types/drafter.d.ts +151 -2
  44. package/types/draftspend.d.ts +21 -0
  45. package/types/flow.d.ts +23 -0
  46. package/types/liveness.d.ts +2 -2
  47. package/types/model-step.d.ts +4 -7
  48. package/types/monthly.d.ts +46 -1
  49. package/types/panel/author.d.ts +316 -0
  50. package/types/panel/authorcard.d.ts +142 -0
  51. package/types/panel/authorflows.d.ts +175 -0
  52. package/types/panel/authorresume.d.ts +32 -0
  53. package/types/panel/authorstart.d.ts +115 -0
  54. package/types/panel/authorvalues.d.ts +62 -0
  55. package/types/panel/data.d.ts +105 -63
  56. package/types/panel/server.d.ts +11 -33
  57. package/types/panel/spawn.d.ts +30 -0
  58. package/types/provider.d.ts +6 -9
  59. package/types/runner.d.ts +129 -6
  60. package/types/runvalues.d.ts +97 -0
  61. package/types/send.d.ts +5 -1
  62. package/types/setup.d.ts +77 -0
@@ -36,6 +36,8 @@
36
36
  // No `new RegExp` anywhere in this file — a test in test/signed-text.test.js
37
37
  // greps all of src/ for that, and it must keep passing with this file added.
38
38
 
39
+ import { buildSoftgreenRubric } from './closers.js';
40
+
39
41
  /** @typedef {import('./types.js').Arbiter} Arbiter */
40
42
  /** @typedef {import('./types.js').SignedLine} SignedLine */
41
43
  /** @typedef {import('./types.js').CatalogueEntry} CatalogueEntry */
@@ -99,7 +101,14 @@ function checkOwnKeys(obj, allowed, path, reds) {
99
101
  * name. */
100
102
  export const SHAPE_KEYS = Object.freeze(['maxWords', 'sections', 'linesPerInvoice', 'mustCarry']);
101
103
 
104
+ /** Shape keys only the MACHINE sets (M4e amendment 15): read from the line's guardrail, never offered to the drafter's model. */
105
+ export const MACHINE_SHAPE_KEYS = Object.freeze(['wordsPerSection']);
106
+
102
107
  const SHAPE_TYPE_CHECKS = Object.freeze({
108
+ wordsPerSection: {
109
+ expected: 'a positive integer',
110
+ check: (v) => Number.isInteger(v) && v > 0,
111
+ },
103
112
  maxWords: {
104
113
  expected: 'a positive integer',
105
114
  check: (v) => Number.isInteger(v) && v > 0,
@@ -148,7 +157,7 @@ function checkShapeKeys(shape, path, reds) {
148
157
  const value = shape[key];
149
158
  if (ARBITER_KEYS.includes(key)) {
150
159
  reds.push(`declaration: arbiter field "${key}" at ${childPath} — the drafter cannot author it`);
151
- } else if (!SHAPE_KEYS.includes(key)) {
160
+ } else if (!SHAPE_KEYS.includes(key) && !MACHINE_SHAPE_KEYS.includes(key)) {
152
161
  reds.push(`declaration: unknown shape key "${key}" at ${childPath}`);
153
162
  } else {
154
163
  const typeCheck = SHAPE_TYPE_CHECKS[key];
@@ -241,6 +250,159 @@ function deriveFromLine(fromLine, lines, guardrailClasses) {
241
250
  return { ok: true, class: resolved.class, line };
242
251
  }
243
252
 
253
+ /** M4e amendment 16 C14: a guardrail number, with or without thousands separators ("1,000" -> 1000). Commas must group by exactly three
254
+ * ("1,00" and "1,0000" match nothing), and the number cannot start in the middle of another one. */
255
+ const readNumber = (t) => Number(t.replace(/,/g, ''));
256
+
257
+ /** Every whole-output word number in a guardrail ("3 sections, under 600 words, each heading at most 3 words" -> [600, 3]), in order; [] when
258
+ * there is none. Code does not decide which one is the limit: the AI picks `maxWords` and the validator checks the pick is one of these
259
+ * (M4e amendments 28 + 29). A "<n> words each" / "<n> words per section" is the per-section size (amendment 15), never listed here. */
260
+ export function guardrailWordNumbers(guardrail) {
261
+ if (typeof guardrail !== 'string') return [];
262
+ return [...guardrail.matchAll(/(?<![\d,])(\d{1,3}(?:,\d{3})+|\d+)\s*words?\b(?!\s*(?:each|per\s+section)\b)/gi)].map((m) => readNumber(m[1]));
263
+ }
264
+
265
+ /** M4e amendment 15 item 1: the "<n> words each" / "<n> words per section" size in a guardrail ("about 250 words each", "250ish each" -> 250), or null. */
266
+ export function guardrailWordsPerSection(guardrail) {
267
+ const m = typeof guardrail === 'string' ? /(?<![\d,])(\d{1,3}(?:,\d{3})+|\d+)(?:\s*words?|ish(?:\s+words?)?)\s+(?:each|per\s+section)\b/i.exec(guardrail) : null;
268
+ return m ? readNumber(m[1]) : null;
269
+ }
270
+
271
+ const NUMBER_WORDS = { one: 1, two: 2, three: 3, four: 4, five: 5, six: 6, seven: 7, eight: 8, nine: 9, ten: 10 };
272
+ /** M4e amendment 7 item 1: the first "<N> sections" in a guardrail (N digits, or the words one..ten), or null. */
273
+ export function guardrailSectionCount(guardrail) {
274
+ const m = typeof guardrail === 'string' ? /\b(\d+|one|two|three|four|five|six|seven|eight|nine|ten)\s+(?:\w+\s+)?sections?\b/i.exec(guardrail) : null;
275
+ if (!m) return null;
276
+ return /^\d+$/.test(m[1]) ? Number(m[1]) : NUMBER_WORDS[m[1].toLowerCase()];
277
+ }
278
+
279
+ /** M4e amendment 15 item 2: for each line whose guardrail gives a size for each section, a section count AND a word number,
280
+ * size x count more than the LARGEST word number (no possible pick fits) is a red naming the line and the numbers. $0; run before any model
281
+ * call, when there is no AI pick yet (amendment 29). After the draft the AI's `maxWords` is checked in checkShapeFitsJobLine. */
282
+ export function checkGuardrailSums(lines) {
283
+ const reds = [];
284
+ for (const l of Array.isArray(lines) ? lines : []) {
285
+ const per = guardrailWordsPerSection(l?.guardrail);
286
+ const count = guardrailSectionCount(l?.guardrail);
287
+ const nums = guardrailWordNumbers(l?.guardrail);
288
+ const limit = nums.length > 0 ? Math.max(...nums) : null;
289
+ // M4e amendment 16 C13: a size for each section with no number of sections can never be checked.
290
+ if (per !== null && count === null) {
291
+ reds.push(`line ${l.n}'s guardrail gives ${per} words for each section but not how many sections. Say the number of sections in the guardrail.`);
292
+ }
293
+ if (per !== null && count !== null && limit !== null && per * count > limit) {
294
+ reds.push(`line ${l.n}'s guardrail asks about ${per} words for each of ${count} sections (${per * count}) but under ${limit} words in total. Change the guardrail.`);
295
+ }
296
+ }
297
+ return reds;
298
+ }
299
+ const MAX_SECTION_NAME_WORDS = 8;
300
+ const MAX_SECTION_SHARE_OF_LINE = 0.6;
301
+ const wordCount = (t) => t.trim().split(/\s+/).filter(Boolean).length;
302
+
303
+ /** M4e amendment 6 item 1 (+ amendment 7 item 1): a step's check cannot fight its own job line. Sections must be found in the line's words
304
+ * (case-insensitive substring of the goal, first occurrence) and in the line's order; `maxWords` (the AI's pick, amendment 29) must be one
305
+ * of the line's guardrail word numbers when that guardrail has any. A shape key a note may still change (mustCarry, linesPerInvoice)
306
+ * is untouched. Pushes reds naming the step and both orders/values. */
307
+ export function checkShapeFitsJobLine(step, i, lines, reds) {
308
+ const { shape } = step.close;
309
+ const label = `steps[${i}]`;
310
+ const redsBefore = reds.length;
311
+ const line = Number.isInteger(step.fromLine) ? lines.find((l) => l.n === step.fromLine) : undefined;
312
+ if (Array.isArray(shape.sections) && shape.sections.every((n) => typeof n === 'string' && n.length > 0) && typeof step.goal === 'string') {
313
+ const goal = step.goal.toLowerCase().replace(/\s+/g, ' ');
314
+ const found = [];
315
+ for (const name of shape.sections) {
316
+ const at = goal.indexOf(name.toLowerCase().replace(/\s+/g, ' ').trim());
317
+ if (at < 0) {
318
+ reds.push(`declaration: ${label}.close.shape.sections names "${name}", which is not in the job line's words — change the job line on the card to change what it names`);
319
+ } else found.push({ name, at });
320
+ }
321
+ if (found.length === shape.sections.length) {
322
+ const jobOrder = [...found].sort((a, b) => a.at - b.at).map((f) => f.name);
323
+ if (jobOrder.some((n, k) => n !== shape.sections[k])) {
324
+ reds.push(`declaration: ${label} the job line says ${jobOrder.join(', then ')}; the check says ${shape.sections.join(', then ')} — change the job line on the card to change the order`);
325
+ }
326
+ }
327
+ }
328
+ const wantSections = guardrailSectionCount(line?.guardrail);
329
+ if (Array.isArray(shape.sections)) {
330
+ if (wantSections !== null && shape.sections.length !== wantSections) {
331
+ reds.push(`declaration: ${label} the guardrail says ${wantSections} sections; the check has ${shape.sections.length}`);
332
+ }
333
+ const goalWords = typeof step.goal === 'string' ? wordCount(step.goal) : 0;
334
+ const names = shape.sections.filter((n) => typeof n === 'string' && n.trim().length > 0);
335
+ for (const name of names) {
336
+ const n = wordCount(name);
337
+ if (n > MAX_SECTION_NAME_WORDS) {
338
+ reds.push(`declaration: ${label}.close.shape.sections names "${name}" (${n} words) — a section name is a short phrase from the job line, at most ${MAX_SECTION_NAME_WORDS} words`);
339
+ } else if (goalWords > 0 && n / goalWords >= MAX_SECTION_SHARE_OF_LINE) {
340
+ reds.push(`declaration: ${label}.close.shape.sections names "${name}", which is the job line or most of it — a section name is a short phrase from the line`);
341
+ }
342
+ }
343
+ const norm = names.map((n) => n.toLowerCase().replace(/\s+/g, ' ').trim());
344
+ norm.forEach((a, x) => norm.forEach((b, y) => {
345
+ if (x !== y && a.includes(b)) reds.push(`declaration: ${label}.close.shape.sections "${names[x]}" contains "${names[y]}" — one section name may not contain another`);
346
+ }));
347
+ }
348
+ // M4e amendment 15 item 1: wordsPerSection is the guardrail's number, set by the machine; it never differs from it.
349
+ const wantPer = guardrailWordsPerSection(line?.guardrail);
350
+ if (shape.wordsPerSection !== undefined && shape.wordsPerSection !== wantPer) {
351
+ reds.push(`declaration: ${label} the check has wordsPerSection ${shape.wordsPerSection}; the guardrail says ${wantPer === null ? 'no size for each section' : `${wantPer} words each`} — change the guardrail on the card to change it`);
352
+ } else if (shape.wordsPerSection === undefined && wantPer !== null) {
353
+ reds.push(`declaration: ${label} the guardrail says ${wantPer} words each; the check has no wordsPerSection`);
354
+ }
355
+ // M4e amendment 16 C13: a size for each section needs the section names to be checked against.
356
+ if (shape.wordsPerSection !== undefined && !(Array.isArray(shape.sections) && shape.sections.length > 0)) {
357
+ reds.push(`declaration: ${label}.close.shape has wordsPerSection but no sections — it needs the section names to check each one`);
358
+ }
359
+ // M4e amendment 16 C12: linesPerInvoice and mustCarry only work as a pair.
360
+ if ((shape.linesPerInvoice === undefined) !== (shape.mustCarry === undefined)) {
361
+ const have = shape.linesPerInvoice === undefined ? 'mustCarry' : 'linesPerInvoice';
362
+ const miss = shape.linesPerInvoice === undefined ? 'linesPerInvoice' : 'mustCarry';
363
+ reds.push(`declaration: ${label}.close.shape has ${have} but no ${miss} — they work as a pair, so the check needs both`);
364
+ }
365
+ // M4e amendments 28 + 29: maxWords is the AI's pick; it must be one of the guardrail's whole-output word numbers, or it is invented.
366
+ const nums = guardrailWordNumbers(line?.guardrail);
367
+ if (nums.length > 0 && shape.maxWords !== undefined && !nums.includes(shape.maxWords)) {
368
+ reds.push(`declaration: line ${line.n}'s check says ${shape.maxWords} words; the guardrail has no ${shape.maxWords}.`);
369
+ } else if (wantPer !== null && shape.maxWords !== undefined && Array.isArray(shape.sections) && shape.sections.length > 0 && wantPer * shape.sections.length > shape.maxWords) {
370
+ // am29: after the draft the sum uses the AI's pick (the $0 check before the draft can only use the largest candidate).
371
+ reds.push(`declaration: line ${line.n}'s guardrail asks about ${wantPer} words for each of ${shape.sections.length} sections (${wantPer * shape.sections.length}) but the check says ${shape.maxWords} words in total. Change the guardrail.`);
372
+ }
373
+ // M4e amendment 18 item 3: a shape bareguard will not build is red here, by name, not a crash at run time.
374
+ checkShapeBuilds(shape, label, reds, redsBefore);
375
+ }
376
+
377
+ /** bareguard refuses a signed name or phrase past this many characters (rubric MAX_SIGNED_LEN). */
378
+ const MAX_SIGNED_ENTRY = 1000;
379
+
380
+ /** What bareguard's rubric builder refuses that the type checks above let through: blank or over-long entries and a section
381
+ * name ending in ":" (a heading's ":" is dropped from the line, never from the name, so it could never match). Anything it
382
+ * still refuses is caught by trying the real builder, `buildSoftgreenRubric` (the same one the run uses), when nothing else
383
+ * was red for this step: so a shape that passes here always builds at run time. */
384
+ function checkShapeBuilds(shape, label, reds, redsBefore) {
385
+ for (const key of ['sections', 'mustCarry']) {
386
+ if (!Array.isArray(shape[key])) continue;
387
+ shape[key].forEach((entry, k) => {
388
+ if (typeof entry !== 'string' || entry.length === 0) return; // the type check already reds these
389
+ const at = `${label}.close.shape.${key}[${k}]`;
390
+ if (entry.trim() === '') reds.push(`declaration: ${at} is blank — every entry needs real text`);
391
+ else if (entry.length > MAX_SIGNED_ENTRY) reds.push(`declaration: ${at} is ${entry.length} characters; the most one entry may be is ${MAX_SIGNED_ENTRY}`);
392
+ else if (key === 'sections' && entry.trim().endsWith(':')) {
393
+ reds.push(`declaration: ${at} names "${entry}", which ends in ":" and can never match a heading (the ":" is dropped from the heading line, not from the name) — drop the ":"`);
394
+ }
395
+ });
396
+ }
397
+ const typesOk = Object.keys(shape).every((k) => SHAPE_TYPE_CHECKS[k]?.check(shape[k]) === true);
398
+ if (reds.length !== redsBefore || !typesOk) return;
399
+ try {
400
+ buildSoftgreenRubric(shape);
401
+ } catch (err) {
402
+ reds.push(`declaration: ${label}.close.shape cannot be built into a check — ${String(err.message).replace(/^invalid rubric: /, '')}`);
403
+ }
404
+ }
405
+
244
406
  /**
245
407
  * Validate a drafter declaration against the M1 closed schema. `arbiter`
246
408
  * and `lines` are `parseSignedText`'s output; `catalogue` is a plain array
@@ -253,11 +415,13 @@ function deriveFromLine(fromLine, lines, guardrailClasses) {
253
415
  * by name, even if the catalogue lists it. Omitted = no wired check (existing callers).
254
416
  * `verbatimGoals` (optional boolean; M6a amendment 1): when true, a step naming a signed line must carry that line's
255
417
  * 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]
418
+ * `fitJobLine` (optional boolean; M4e amendment 6): when true, a `close.shape` whose sections/maxWords fight the step's job
419
+ * line or its guardrail is a red. Draft, change and sign turn it on; readFlow does not (signed flows keep running).
420
+ * @param {{ arbiter?: unknown, lines?: unknown, catalogue?: unknown, wired?: Set<string>, verbatimGoals?: boolean, fitJobLine?: boolean }} [context]
257
421
  * @returns {ValidateDeclarationResult}
258
422
  */
259
423
  export function validateDeclaration(declaration, context = {}) {
260
- const { arbiter, lines, catalogue, wired, verbatimGoals } = context;
424
+ const { arbiter, lines, catalogue, wired, verbatimGoals, fitJobLine } = context;
261
425
  const reds = [];
262
426
 
263
427
  if (!isPlainObject(declaration)) {
@@ -297,6 +461,7 @@ export function validateDeclaration(declaration, context = {}) {
297
461
  return deepFreeze({ ok: false, reds });
298
462
  }
299
463
  const { steps } = declaration;
464
+ if (fitJobLine === true) reds.push(...checkGuardrailSums(safeLines).map((r) => `declaration: ${r}`));
300
465
 
301
466
  // --- guardrailClasses (REQUIRED — the harness always writes it; empty {}
302
467
  // is fine, missing entirely is not) ------------------------------------
@@ -514,11 +679,18 @@ export function validateDeclaration(declaration, context = {}) {
514
679
  reds.push(`declaration: ${label}.close.shape must be an object`);
515
680
  } else {
516
681
  checkShapeKeys(step.close.shape, `declaration.${label}.close.shape`, reds);
682
+ if (fitJobLine === true) checkShapeFitsJobLine(step, i, safeLines, reds);
517
683
  }
518
684
  }
519
685
  }
520
686
  }
521
687
 
688
+ // M4e amendment 15 item 5: a step whose check reads its reply (softgreen) gets no `write` — the answer would land in a file the check never reads.
689
+ if (fitJobLine === true && effectiveClass === 'softgreen' && primitives !== null
690
+ && primitives.some((v) => typeof v === 'string' && catalogueByVerb.get(v)?.class === 'write')) {
691
+ reds.push(`declaration: step ${i + 1}'s check reads its reply, so it can't write files. The send step writes the result out.`);
692
+ }
693
+
522
694
  // picks — the listing rule, generalised
523
695
  if (step.picks !== undefined) {
524
696
  if (!isPlainObject(step.picks)) {
package/src/drafter.js CHANGED
@@ -17,7 +17,7 @@
17
17
 
18
18
  import { Loop, HaltError } from 'bare-agent';
19
19
  import { parseSignedText, unsignedAskTtls } from './signed-text.js';
20
- import { validateDeclaration, SHAPE_KEYS } from './declaration.js';
20
+ import { validateDeclaration, SHAPE_KEYS, checkGuardrailSums, guardrailWordsPerSection } from './declaration.js';
21
21
  import { loadCatalogue } from './catalogue.js';
22
22
  import { WIRED_VERBS, wiredMenu } from './primitives.js';
23
23
  import { readInputFacts } from './input-facts.js';
@@ -32,8 +32,11 @@ export const DRAFT_SKILLS = Object.freeze(['core']);
32
32
 
33
33
  export const CLASSES = Object.freeze(['green', 'softgreen', 'hitl']);
34
34
 
35
+ /** The whole-output-ceiling rule, told once to the drafter (schema and prompt use this string). Amendment 29; no number words (am25). */
36
+ export const WHOLE_OUTPUT_CEILING_RULE = "use the guardrail's ceiling for the whole output";
37
+
35
38
  const SHAPE_PROPS = Object.freeze({
36
- maxWords: { type: 'integer', minimum: 1, description: "the whole output's word ceiling" },
39
+ maxWords: { type: 'integer', minimum: 1, description: `the whole output's word ceiling; ${WHOLE_OUTPUT_CEILING_RULE}` },
37
40
  sections: { type: 'array', minItems: 1, items: { type: 'string', minLength: 1 }, description: 'required section headings, in order' },
38
41
  linesPerInvoice: { type: 'integer', minimum: 1, description: 'lines the output must carry per invoice' },
39
42
  mustCarry: { type: 'array', minItems: 1, items: { type: 'string', minLength: 1 }, description: 'named fields every line must carry' },
@@ -115,6 +118,94 @@ export function buildDeclarationSchema(menu) {
115
118
 
116
119
  const TOOL = 'emit_declaration';
117
120
 
121
+ // ---- M4e amendments 24 + 25: questions (try 3 only) and "not checked" (every try) ---------------------------------
122
+ // borrowed-from: fwdloop poc/am24-questions/draft.mjs@dda0e0f (prompts, linesNamedByReds, normalizeQuestions), adjusted to the product drafter.
123
+ export const MAX_QUESTIONS = 2;
124
+
125
+ /** What fwdloop's typed checks can really check (bareloop F174: give the model the real list, or "Not checked" is invented). */
126
+ export const CHECKABLE = Object.freeze([
127
+ 'green: a figure cites its source cell or formula',
128
+ 'softgreen: the output carries named section headings (sections), in order',
129
+ `softgreen: a word ceiling for the whole output (maxWords; ${WHOLE_OUTPUT_CEILING_RULE}) and per section (wordsPerSection)`,
130
+ 'softgreen: a line count per invoice (linesPerInvoice) and fields every line must carry (mustCarry)',
131
+ 'hitl: a human accepts or reviews at a signed ask — the machine checks only that the step happened',
132
+ ]);
133
+
134
+ /** Offered on EVERY try (it is information, not asking). */
135
+ export const NOTCHECKED_PROMPT = [
136
+ 'notChecked (optional): a short list of things about the job that no check below will verify. These are the ONLY things fwdloop can check:',
137
+ ...CHECKABLE.map((c) => `- ${c}`),
138
+ 'Anything the job asks for beyond those (tone, correctness of prose, completeness, matching a taste) is NOT checked: list it in "notChecked", a plain short phrase each. [] or leave out if nothing.',
139
+ ].join('\n');
140
+
141
+ /** Try 3 only, and only after tries 1 and 2 both failed validation. No digit and no number word anywhere (a test greps this): the machine, not the prompt, bounds the count. */
142
+ export const QUESTIONS_PROMPT = [
143
+ 'You may add "questions" to this reply. Ask only about a job line named in the refusals above, and only if that line cannot be drafted without the answer',
144
+ '(an undefined size, format, destination, or what "done" means). Each question is {line, question}: "line" is the number of the job line it is about.',
145
+ 'If the refusals can be fixed without asking, fix them and leave "questions" out. Never ask about a trigger, cap, ask position or TTL, allow-list or send target (signed, not yours).',
146
+ 'Still emit the complete corrected declaration.',
147
+ ].join('\n');
148
+
149
+ /** The declaration schema plus the optional `notChecked` (every try) and, on try 3 only, `questions`. Neither is in `required`. */
150
+ export function buildRoundSchema(menu, { questions = false } = {}) {
151
+ const s = buildDeclarationSchema(menu);
152
+ const extra = { notChecked: { type: 'array', items: { type: 'string' }, description: 'what the job asks for that no typed check verifies' } };
153
+ if (questions) {
154
+ extra.questions = {
155
+ type: 'array',
156
+ items: {
157
+ type: 'object',
158
+ properties: { line: { type: 'integer' }, question: { type: 'string' } },
159
+ required: ['line', 'question'],
160
+ },
161
+ description: 'questions the job cannot be drafted without; each names the job line it is about',
162
+ };
163
+ }
164
+ return { ...s, properties: { ...s.properties, ...extra } };
165
+ }
166
+
167
+ /**
168
+ * Which job lines did these reds name? Reds name a line three ways: "line N" (also "ask at line N", "(line N)",
169
+ * "guardrailClasses key \"N\""), "steps[i]" (mapped through that declaration's steps[i].fromLine), and "step N's check"
170
+ * (1-based). A red naming none (a missing top-level key, an unknown key) names no line. Returns sorted real line numbers.
171
+ */
172
+ export function linesNamedByReds(reds, declaration, lineNums) {
173
+ const found = new Set();
174
+ const steps = Array.isArray(declaration?.steps) ? declaration.steps : [];
175
+ const stepLine = (i) => (isPlainObject(steps[i]) && Number.isInteger(steps[i].fromLine) ? steps[i].fromLine : null);
176
+ for (const red of reds) {
177
+ for (const m of red.matchAll(/\bline (\d+)\b/g)) found.add(Number(m[1]));
178
+ for (const m of red.matchAll(/guardrailClasses key "(\d+)"|unjudgeable key "(\d+)"/g)) found.add(Number(m[1] ?? m[2]));
179
+ for (const m of red.matchAll(/steps\[(\d+)\]/g)) { const n = stepLine(Number(m[1])); if (n !== null) found.add(n); }
180
+ for (const m of red.matchAll(/\bstep (\d+)'s check/g)) { const n = stepLine(Number(m[1]) - 1); if (n !== null) found.add(n); }
181
+ }
182
+ return [...found].filter((n) => lineNums.includes(n)).sort((x, y) => x - y);
183
+ }
184
+
185
+ /**
186
+ * Amendment 25: a question is kept only if its line is one try 2's reds named; no line, a blank question or a third question is
187
+ * dropped. Every drop comes back with its reason, for the draft's log. Returns {kept, dropped}.
188
+ */
189
+ export function normalizeQuestions(raw, failedLines) {
190
+ const kept = [];
191
+ const dropped = [];
192
+ if (raw === undefined || raw === null) return { kept, dropped };
193
+ if (!Array.isArray(raw)) return { kept, dropped: [{ reason: 'questions is not a list', raw }] };
194
+ for (const q of raw) {
195
+ if (!isPlainObject(q) || !Number.isInteger(q.line)) { dropped.push({ reason: 'no line', raw: q }); continue; }
196
+ if (!failedLines.includes(q.line)) { dropped.push({ reason: `line ${q.line} is not a line try 2's checks failed on`, raw: q }); continue; }
197
+ if (typeof q.question !== 'string' || q.question.trim() === '') { dropped.push({ reason: 'blank question', raw: q }); continue; }
198
+ if (kept.length >= MAX_QUESTIONS) { dropped.push({ reason: 'third question', raw: q }); continue; }
199
+ kept.push({ line: q.line, question: q.question.trim() });
200
+ }
201
+ return { kept, dropped };
202
+ }
203
+
204
+ /** `notChecked` as the model sent it: non-blank strings only, trimmed. Anything else is an empty list. */
205
+ function cleanNotChecked(raw) {
206
+ return Array.isArray(raw) ? raw.filter((x) => typeof x === 'string' && x.trim() !== '').map((x) => x.trim()) : [];
207
+ }
208
+
118
209
  function jobLinesText(lines, asks) {
119
210
  const askLines = new Set(asks.map((a) => a.line));
120
211
  return lines
@@ -138,6 +229,7 @@ export function buildSystemPrompt({ menu, lines, arbiter, factsInfo }) {
138
229
  '- 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".',
139
230
  '- 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.',
140
231
  '- close.shape only on a softgreen step; it is the human\'s declared shape in structured form.',
232
+ '- A step whose check reads its reply (softgreen) answers in its reply text and is never granted `write`, `edit` or any other write-class verb; only the send step at the end writes files out.',
141
233
  `- 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.`,
142
234
  `- 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.`,
143
235
  '- Nothing hitl may come after the last signed ask except the send step.',
@@ -176,13 +268,18 @@ export const DRAFT_PROVIDER_OPTIONS = Object.freeze({ ...LIVE_PROVIDER_OPTIONS,
176
268
  * the batch); otherwise a live provider is built from `slot` (throws on a bad
177
269
  * key — the batch preflights first). `budgetUsd` is this draft's hard cap.
178
270
  * `makeProviderFn` is a test seam: the live-provider factory (default `makeProvider`).
271
+ * `onBook` (M4e piece 2a, scope 13): called right BEFORE each provider call (`inFlight: true`, the call counted in
272
+ * `calls`) and right AFTER it (`inFlight: false`), with what is known so far, so the caller can book spend per call
273
+ * and a draft killed between rounds still has its paid rounds on disk. It may throw before a call (nothing is
274
+ * spent then and the draft stops); after a call it is the caller's to keep from throwing.
179
275
  *
180
276
  * @returns {Promise<{ok:boolean, declaration:object|null, reds:string[], rounds:number, calls:number, spendComplete:boolean,
181
- * costUsd:number|null, modelReturned:string|null, modelId?:string, price?:object|null, tokens?:object|null, structureRetries:number, revisions:number, stop:string|null, log:object[]}>}
277
+ * costUsd:number|null, modelReturned:string|null, modelId?:string, price?:object|null, tokens?:object|null, structureRetries:number, revisions:number, stop:string|null, log:object[],
278
+ * questions?:{line:number, question:string}[], droppedQuestions?:object[], notChecked?:string[]}>}
182
279
  */
183
280
  export async function draft({
184
281
  proseText, slot = 'deepseek', model, provider: injected, rates: injectedRates, modelId: injectedModelId, env,
185
- budgetUsd = 0.10, skills = DRAFT_SKILLS, makeProviderFn = makeProvider,
282
+ budgetUsd = 0.10, skills = DRAFT_SKILLS, makeProviderFn = makeProvider, onBook, offerQuestions = true,
186
283
  }) {
187
284
  const fail = (reds, extra = {}) => ({
188
285
  ok: false, declaration: null, reds, rounds: 0, calls: 0, spendComplete: true, costUsd: 0, modelReturned: null, structureRetries: 0, revisions: 0, stop: 'pre-flight', log: [], ...extra,
@@ -194,6 +291,9 @@ export async function draft({
194
291
  const { lines, arbiter } = parsed;
195
292
  const ttlReds = unsignedAskTtls(arbiter);
196
293
  if (ttlReds.length) return fail(ttlReds);
294
+ // M4e amendment 15 item 2: a guardrail that fights itself on words is red at $0, before any provider is built or called.
295
+ const sumReds = checkGuardrailSums(lines);
296
+ if (sumReds.length) return fail(sumReds);
197
297
  const menu = wiredMenu(skills);
198
298
  const facts = readInputFacts(arbiter.sources);
199
299
  if (!facts.ok) return fail(facts.reds);
@@ -210,8 +310,10 @@ export async function draft({
210
310
  }
211
311
  }
212
312
 
213
- const schema = buildDeclarationSchema(menu);
214
- const system = buildSystemPrompt({ menu, lines, arbiter, factsInfo: facts.info });
313
+ // `notChecked` is offered on every try (information, not asking); `questions` only on try 3 (below).
314
+ const baseSystem = buildSystemPrompt({ menu, lines, arbiter, factsInfo: facts.info });
315
+ const system = `${baseSystem}\n\n${NOTCHECKED_PROMPT}`;
316
+ const lineNums = lines.map((l) => l.n);
215
317
  // Full catalogue + the wired set: an unwired verb reds "not wired" by name; an unsigned skill reds by skill.
216
318
  const cat = loadCatalogue();
217
319
  if (!cat.ok) return fail([`catalogue: ${cat.reds.join('; ')}`]);
@@ -232,6 +334,9 @@ export async function draft({
232
334
  let nextKind = 'first'; // what the round about to run actually is
233
335
  let validatorReds = []; // the last validator refusal; a structure retry after a revision must not drop it
234
336
  let stop = null;
337
+ let failedLines = []; // the job lines try 2's reds named: a question is kept only about one of these (amendment 25)
338
+ /** @type {{questions:{line:number, question:string}[], droppedQuestions:object[], notChecked:string[]}} */
339
+ let extras = { questions: [], droppedQuestions: [], notChecked: [] }; // from the round that produced `lastDecl`, never an earlier one
235
340
  let calls = 0; // provider calls made (a call that threw before metering is in `calls`, not in `rounds`)
236
341
  let unmetered = 0; // calls that failed with no metering: their cost is unknown
237
342
 
@@ -241,7 +346,13 @@ export async function draft({
241
346
  const spent = meterings.reduce((sum, ev) => sum + (ev.costUsd ?? roundCeiling), 0);
242
347
  if (spent + roundCeiling > budgetUsd) { stop = 'budget'; break; }
243
348
 
349
+ // assigned inside the tool's execute callback, which TS cannot see
350
+ /** @type {any} */
244
351
  let captured;
352
+ // Amendment 25: a lock is a mechanism. Only try 3 of 3, and only when tries 1 and 2 BOTH failed validation (`revisions` counts the
353
+ // validator's refusals fed back), gets the `questions` property; the redraft after an answer passes offerQuestions:false and never does.
354
+ const askOpen = offerQuestions && revisions === MAX_REVISIONS;
355
+ const schema = buildRoundSchema(menu, { questions: askOpen });
245
356
  const tool = {
246
357
  name: TOOL,
247
358
  description: 'Emit the flow declaration over the granted primitives, or refuse lines you cannot serve.',
@@ -255,6 +366,10 @@ export async function draft({
255
366
  let result;
256
367
  let threw = null;
257
368
  calls += 1;
369
+ const book = (inFlight) => onBook?.({
370
+ inFlight, calls, unmetered, metered: sumMeterings(meterings), modelId, price: priceRecord(prices, rates),
371
+ });
372
+ book(true);
258
373
  try {
259
374
  result = await loop.run(
260
375
  [{ role: 'system', content: system }, { role: 'user', content: userText }],
@@ -265,6 +380,7 @@ export async function draft({
265
380
  threw = err;
266
381
  if (roundEvents.length === 0) unmetered += 1;
267
382
  }
383
+ book(false);
268
384
  const entry = { round: log.length + 1, kind: nextKind };
269
385
 
270
386
  if (threw) {
@@ -288,24 +404,42 @@ export async function draft({
288
404
  nextKind = 'structure-retry';
289
405
  userText = `Your last reply was not a usable tool call (${why}). Call ${TOOL} now with a complete, valid JSON declaration.`;
290
406
  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')}`;
407
+ if (askOpen) userText += `\n\n${QUESTIONS_PROMPT}`;
291
408
  continue;
292
409
  }
293
410
 
294
- const declaration = { .../** @type {object} */ (captured), inputFacts: facts.inputFacts };
411
+ // `notChecked` was offered on every try, so it is information and never reaches the validator. `questions` is stripped only where it was
412
+ // offered; sent when not offered it stays, and the validator reds it as an unknown key (a stray key, never a silent pass).
413
+ const { questions: rawQuestions, notChecked: rawNotChecked, ...captureRest } = /** @type {Record<string, any>} */ (captured);
414
+ /** @type {Record<string, any>} */
415
+ const declaration = { ...(askOpen ? captureRest : { ...captureRest, ...(rawQuestions === undefined ? {} : { questions: rawQuestions }) }), inputFacts: facts.inputFacts };
295
416
  // M6a amendment 1 (F50): the goal is the signed line, set by the machine; whatever the model sent is overwritten.
296
417
  if (Array.isArray(declaration.steps)) {
297
418
  declaration.steps = declaration.steps.map((st) => (isPlainObject(st) ? { ...st, goal: goalForLine(st.fromLine, lines) } : st));
298
419
  }
420
+ // M4e amendment 15 item 1: `wordsPerSection` is the guardrail's number, set by the machine. If the model sent one it is overwritten
421
+ // (or dropped when the guardrail gives none), so it can never differ from the guardrail.
422
+ if (Array.isArray(declaration.steps)) {
423
+ declaration.steps = declaration.steps.map((st) => {
424
+ if (!isPlainObject(st) || !isPlainObject(st.close) || !isPlainObject(st.close.shape)) return st;
425
+ const { wordsPerSection: _drop, ...shape } = st.close.shape;
426
+ const per = guardrailWordsPerSection(lines.find((l) => l.n === st.fromLine)?.guardrail);
427
+ return { ...st, close: { ...st.close, shape: per === null ? shape : { ...shape, wordsPerSection: per } } };
428
+ });
429
+ }
299
430
  const verdict = validateDeclaration(declaration, {
300
- arbiter, lines, catalogue: validationCatalogue, wired: WIRED_VERBS, verbatimGoals: true,
431
+ arbiter, lines, catalogue: validationCatalogue, wired: WIRED_VERBS, verbatimGoals: true, fitJobLine: true,
301
432
  });
302
433
  lastDecl = declaration;
434
+ const asked = askOpen ? normalizeQuestions(rawQuestions, failedLines) : { kept: [], dropped: [] };
435
+ extras = { questions: asked.kept, droppedQuestions: asked.dropped, notChecked: cleanNotChecked(rawNotChecked) };
436
+ if (asked.dropped.length) entry.droppedQuestions = asked.dropped;
303
437
  if (verdict.ok) {
304
438
  entry.outcome = 'valid';
305
439
  log.push(entry);
306
440
  const m = sumMeterings(meterings);
307
441
  return {
308
- ok: true, declaration, reds: [], rounds: m.rounds, calls, spendComplete: unmetered === 0 && m.costUsd !== null, costUsd: m.costUsd, modelReturned: m.model, modelId, price: priceRecord(prices, rates), tokens: m.tokens, structureRetries, revisions, stop: null, log,
442
+ ok: true, declaration, reds: [], rounds: m.rounds, calls, spendComplete: unmetered === 0 && m.costUsd !== null, costUsd: m.costUsd, modelReturned: m.model, modelId, price: priceRecord(prices, rates), tokens: m.tokens, structureRetries, revisions, stop: null, log, ...extras,
309
443
  };
310
444
  }
311
445
  lastReds = [...verdict.reds];
@@ -317,12 +451,16 @@ export async function draft({
317
451
  validatorReds = lastReds;
318
452
  nextKind = 'revision';
319
453
  userText = reviseMessage(lastReds);
454
+ if (offerQuestions && revisions === MAX_REVISIONS) {
455
+ failedLines = linesNamedByReds(lastReds, declaration, lineNums);
456
+ userText += `\n\n${QUESTIONS_PROMPT}`;
457
+ }
320
458
  }
321
459
 
322
460
  const m = sumMeterings(meterings);
323
461
  // Runner convention: `costUsd` is the priced sum (null when ANY round is unpriced, so the CLI prints UNKNOWN,
324
462
  // never a bare number), and `spendComplete:false` marks a call that failed unmetered or a round left unpriced.
325
463
  return {
326
- ok: false, declaration: lastDecl, reds: lastReds, rounds: m.rounds, calls, spendComplete: unmetered === 0 && m.costUsd !== null, costUsd: m.costUsd, modelReturned: m.model, modelId, price: priceRecord(prices, rates), tokens: m.tokens, structureRetries, revisions, stop, log,
464
+ ok: false, declaration: lastDecl, reds: lastReds, rounds: m.rounds, calls, spendComplete: unmetered === 0 && m.costUsd !== null, costUsd: m.costUsd, modelReturned: m.model, modelId, price: priceRecord(prices, rates), tokens: m.tokens, structureRetries, revisions, stop, log, ...extras,
327
465
  };
328
466
  }
@@ -0,0 +1,70 @@
1
+ // borrowed-from: bareloop src/draftspend.js@524a244 (writeDraftSpend: one file per draft folder, rewritten atomically
2
+ // after EVERY metered call; the money readers count it).
3
+ // M4e piece 2a, item 7 (docs/wiki/the-module-ladder.md, "M4e", scope 13): drafting spend that is booked per call.
4
+ //
5
+ // Before this, `draftToDir` booked ONE `spend.jsonl` row after the whole draft returned, so a draft killed
6
+ // mid-way (Abandon, a SIGKILL, a panel host reboot) booked nothing for the rounds already paid for. Now the
7
+ // drafter reports every call (`onBook`, src/drafter.js) and `draftToDir` rewrites `<draft dir>/draft-spend.json`
8
+ // from it: written BEFORE each provider call as "one call in flight" (unknown cost = one ceiling, never $0),
9
+ // rewritten AFTER it with the metered floor.
10
+ //
11
+ // ONE rule for what a draft dir costs (`readDirSpendRows`, the only reader, called by src/monthly.js): the final
12
+ // `spend.jsonl` row, once the draft finished, is the whole truth and SUPERSEDES this file; before that, this file
13
+ // is the dir's one spend row. So a finished draft is counted once, never as both. The run that follows a sign has
14
+ // its own dir and its own books — it never carries this spend (counted once, as scope 13 says).
15
+ //
16
+ // The record is shaped like a spend row, so `spendRowCost` (src/provider.js, the one cost rule) prices it:
17
+ // { kind:'draft-live', provider, model, price, tokens, costUsd (metered floor, null when unpriced), rounds, calls,
18
+ // spendComplete (false while a call is in flight or any call is unmetered/unpriced), inFlight, at, startedAt, updatedAt }
19
+ import { renameSync, writeFileSync } from 'node:fs';
20
+ import { join } from 'node:path';
21
+
22
+ import { readFileInside } from './flow.js';
23
+ import { readSpendRows } from './provider.js';
24
+
25
+ export const DRAFT_SPEND_FILE = 'draft-spend.json';
26
+
27
+ /**
28
+ * (Re)write `<dir>/draft-spend.json` atomically (tmp + rename), so a reader never sees a torn file.
29
+ * @param {string} dir the draft dir
30
+ * @param {Record<string, any>} rec
31
+ */
32
+ export function writeDraftSpend(dir, rec) {
33
+ const file = join(dir, DRAFT_SPEND_FILE);
34
+ const tmp = `${file}.tmp`;
35
+ writeFileSync(tmp, `${JSON.stringify(rec, null, 2)}\n`, { mode: 0o600 });
36
+ renameSync(tmp, file);
37
+ }
38
+
39
+ /**
40
+ * The draft dir's live spend record as a spend row, or null when the file is not there. A file that is there but
41
+ * cannot be read is unknown spend: one unmetered call (priced at the ceiling), never $0 and never skipped.
42
+ * @param {string} dir
43
+ * @returns {Record<string, any>|null}
44
+ */
45
+ export function readDraftSpend(dir) {
46
+ const r = readFileInside(dir, DRAFT_SPEND_FILE);
47
+ if (!r.ok) return r.missing ? null : unknownRow();
48
+ try {
49
+ const j = JSON.parse(r.text);
50
+ if (!j || typeof j !== 'object' || Array.isArray(j)) return unknownRow();
51
+ return j;
52
+ } catch { return unknownRow(); }
53
+ }
54
+
55
+ const unknownRow = () => ({
56
+ kind: 'draft-live', model: null, costUsd: null, rounds: 0, calls: 1, spendComplete: false, inFlight: false,
57
+ });
58
+
59
+ /**
60
+ * Every spend row of one run/draft dir: its `spend.jsonl` rows; and, only when there are none, the draft dir's
61
+ * `draft-spend.json` record (see the file header: a finished draft's spend.jsonl supersedes it).
62
+ * @param {string} dir
63
+ * @returns {Record<string, any>[]}
64
+ */
65
+ export function readDirSpendRows(dir) {
66
+ const rows = readSpendRows(join(dir, 'spend.jsonl'));
67
+ if (rows.length > 0) return rows;
68
+ const live = readDraftSpend(dir);
69
+ return live ? [live] : [];
70
+ }
package/src/flow.js CHANGED
@@ -36,6 +36,8 @@ import { validateDeclaration } from './declaration.js';
36
36
  /** The three files a signed flow directory carries. Every place in this
37
37
  * module that names a flow file uses this — never a literal string. */
38
38
  export const FLOW_FILES = Object.freeze(['prose.txt', 'declaration.json', 'signature.json']);
39
+ /** The one folder under the flows root where the panel keeps each run start's own files (M4e piece 2b). A dot-name, so never a flow. */
40
+ export const PANEL_STARTS_DIR = '.starts';
39
41
 
40
42
  const RUNS_DIR = 'runs';
41
43
 
@@ -241,6 +243,47 @@ export function listRunIds(flowDir) {
241
243
  .sort();
242
244
  }
243
245
 
246
+ /**
247
+ * M4e amendment 3 item 2: the ONE place a run gets its default name. `run-<n>`, counting up per flow (the run lives in its flow's
248
+ * folder, so the name only has to be unique there). `nextRunId` only LOOKS (max existing `run-<n>` + 1; the page's prefill);
249
+ * `claimRunId` CLAIMS: it creates the run folder exclusively (mkdir with no `recursive` on the final component, so a second
250
+ * starter gets EEXIST, never the same folder) and bumps n on EEXIST, a bounded number of times. Runs already made keep their ids.
251
+ * @param {string} flowDir
252
+ * @returns {string}
253
+ */
254
+ export function nextRunId(flowDir) {
255
+ let max = 0;
256
+ for (const id of listRunIds(flowDir)) {
257
+ const m = /^run-([0-9]+)$/.exec(id);
258
+ if (m) max = Math.max(max, Number(m[1]));
259
+ }
260
+ return `run-${max + 1}`;
261
+ }
262
+
263
+ const CLAIM_TRIES = 50;
264
+
265
+ /**
266
+ * @param {string} flowDir
267
+ * @returns {{ok:true, runId:string, runDir:string}|{ok:false, red:string}}
268
+ */
269
+ export function claimRunId(flowDir) {
270
+ const runsDir = path.join(flowDir, RUNS_DIR);
271
+ let n = Number(nextRunId(flowDir).slice(4));
272
+ for (let i = 0; i < CLAIM_TRIES; i += 1, n += 1) {
273
+ const runId = `run-${n}`;
274
+ const r = resolveRunDir(flowDir, runId);
275
+ if (!r.ok) return r;
276
+ try {
277
+ mkdirSync(runsDir, { recursive: true });
278
+ mkdirSync(r.runDir); // NOT recursive: the exclusive create IS the claim
279
+ return { ok: true, runId, runDir: r.runDir };
280
+ } catch (err) {
281
+ if (/** @type {any} */ (err)?.code !== 'EEXIST') return { ok: false, red: `run: could not claim a run name — ${/** @type {Error} */ (err).message}` };
282
+ }
283
+ }
284
+ return { ok: false, red: `run: could not claim a run name after ${CLAIM_TRIES} tries` };
285
+ }
286
+
244
287
  /**
245
288
  * F48 round 3 (docs/logs/FINDINGS.md): the ONE mechanism every book reader
246
289
  * in src/ and bin/ routes through to read a file that lives inside a run