fwdloop 0.14.0 → 0.16.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 (58) hide show
  1. package/bin/fwdloop +106 -31
  2. package/package.json +2 -2
  3. package/src/authoring.js +26 -11
  4. package/src/checked.js +9 -5
  5. package/src/closers.js +5 -0
  6. package/src/config.js +66 -4
  7. package/src/declaration.js +27 -1
  8. package/src/draft-steps.js +79 -0
  9. package/src/drafter.js +54 -15
  10. package/src/flow.js +220 -5
  11. package/src/flowmodel.js +30 -0
  12. package/src/input-facts.js +12 -3
  13. package/src/keysfile.js +51 -16
  14. package/src/model-step.js +13 -11
  15. package/src/monthly.js +9 -1
  16. package/src/panel/author.js +89 -24
  17. package/src/panel/authorcard.js +80 -20
  18. package/src/panel/authorflows.js +72 -21
  19. package/src/panel/authorresume.js +11 -10
  20. package/src/panel/authorstart.js +29 -19
  21. package/src/panel/data.js +62 -21
  22. package/src/panel/index.html +662 -185
  23. package/src/panel/resume.js +3 -3
  24. package/src/panel/server.js +5 -4
  25. package/src/panel/settings.js +138 -80
  26. package/src/panel/spawn.js +15 -9
  27. package/src/provider.js +136 -178
  28. package/src/providershapes.js +7 -7
  29. package/src/runner.js +47 -23
  30. package/src/signed-diff.js +71 -0
  31. package/src/thinking.js +55 -0
  32. package/types/authoring.d.ts +20 -7
  33. package/types/checked.d.ts +6 -4
  34. package/types/closers.d.ts +2 -0
  35. package/types/config.d.ts +9 -1
  36. package/types/draft-steps.d.ts +14 -0
  37. package/types/drafter.d.ts +13 -10
  38. package/types/flow.d.ts +42 -2
  39. package/types/flowmodel.d.ts +16 -0
  40. package/types/input-facts.d.ts +6 -1
  41. package/types/keysfile.d.ts +23 -6
  42. package/types/model-step.d.ts +1 -1
  43. package/types/monthly.d.ts +1 -0
  44. package/types/panel/author.d.ts +78 -6
  45. package/types/panel/authorcard.d.ts +53 -8
  46. package/types/panel/authorflows.d.ts +68 -6
  47. package/types/panel/authorresume.d.ts +2 -1
  48. package/types/panel/authorstart.d.ts +17 -6
  49. package/types/panel/data.d.ts +10 -6
  50. package/types/panel/resume.d.ts +2 -1
  51. package/types/panel/server.d.ts +3 -1
  52. package/types/panel/settings.d.ts +3 -1
  53. package/types/panel/spawn.d.ts +13 -4
  54. package/types/provider.d.ts +94 -284
  55. package/types/providershapes.d.ts +3 -4
  56. package/types/runner.d.ts +2 -4
  57. package/types/signed-diff.d.ts +10 -0
  58. package/types/thinking.d.ts +25 -0
@@ -36,7 +36,7 @@
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';
39
+ import { buildSoftgreenRubric, isCellsPath } from './closers.js';
40
40
 
41
41
  /** @typedef {import('./types.js').Arbiter} Arbiter */
42
42
  /** @typedef {import('./types.js').SignedLine} SignedLine */
@@ -442,6 +442,9 @@ export function validateDeclaration(declaration, context = {}) {
442
442
  const safeArbiter = /** @type {Arbiter} */ (arbiter);
443
443
  const skills = Array.isArray(safeArbiter.skills) ? safeArbiter.skills : [];
444
444
  const sourceRoles = Array.isArray(safeArbiter.sources) ? safeArbiter.sources.map((s) => s?.role) : [];
445
+ // M4d amendment 8: the inputs with cells (a spreadsheet file). A step may read one by its role; a green step must.
446
+ const cellsRoles = Array.isArray(safeArbiter.sources)
447
+ ? safeArbiter.sources.filter((s) => s?.kind === 'file' && isCellsPath(s.path)).map((s) => s.role) : [];
445
448
  const asks = Array.isArray(safeArbiter.asks) ? safeArbiter.asks : [];
446
449
  const askLines = asks.map((a) => a.line);
447
450
  const sends = Array.isArray(safeArbiter.sends) ? safeArbiter.sends : [];
@@ -490,6 +493,8 @@ export function validateDeclaration(declaration, context = {}) {
490
493
  let unjudgeable = {};
491
494
  if (!Object.prototype.hasOwnProperty.call(declaration, 'unjudgeable')) {
492
495
  reds.push('declaration: "unjudgeable" is required (an object keyed by line number; {} is fine)');
496
+ } else if (Array.isArray(declaration.unjudgeable) && declaration.unjudgeable.length === 0) {
497
+ // am41 item 1 (F63): an empty list carries no data; it counts as {}. A non-empty list falls to the red below.
493
498
  } else if (isPlainObject(declaration.unjudgeable)) {
494
499
  unjudgeable = declaration.unjudgeable;
495
500
  for (const [key, reason] of Object.entries(unjudgeable)) {
@@ -631,12 +636,15 @@ export function validateDeclaration(declaration, context = {}) {
631
636
  // walkable chain — every read must have been emitted by an EARLIER step
632
637
  if (reads !== null && emits !== null) {
633
638
  for (const readId of reads) {
639
+ if (cellsRoles.includes(readId) && !declaredEmits.has(readId)) continue; // an input with cells, frozen at run start (M4d amendment 8)
634
640
  if (readId === emits || !declaredEmits.has(readId)) {
635
641
  reds.push(`declaration: ${label} reads artifact "${readId}" that no earlier step declared`);
636
642
  }
637
643
  }
638
644
  }
645
+ const earlierEmits = [...declaredEmits]; // outputs of EARLIER steps, in order (the nearest is last)
639
646
  if (emits !== null) declaredEmits.add(emits);
647
+ if (fitJobLine === true && emits !== null && cellsRoles.includes(emits)) reds.push(`declaration: ${label}.emits "${emits}" is also a signed input — one id, one meaning`);
640
648
 
641
649
  // fromLine + class derivation — the key itself is required (value may be
642
650
  // null, meaning "no line"; the key being entirely absent is not the same
@@ -691,6 +699,24 @@ export function validateDeclaration(declaration, context = {}) {
691
699
  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
700
  }
693
701
 
702
+ // M4d amendment 8: a step whose check is green (every figure cites a source cell) must read an input with cells; a text
703
+ // output of an earlier step has no cells to cite.
704
+ if (fitJobLine === true && effectiveClass === 'green' && reads !== null && !reads.some((r) => cellsRoles.includes(r))) {
705
+ const n = fromLine;
706
+ const reading = reads.length === 0 ? 'it reads nothing' : `it reads only ${reads.join(', ')}`;
707
+ const want = cellsRoles.length === 0 ? 'a spreadsheet input, and this job signs none' : cellsRoles.join(' or ');
708
+ reds.push(`declaration: Line ${n}'s check needs cells, but ${reading}. Line ${n} must read ${want}.`);
709
+ }
710
+
711
+ // M4d amendment 9: an ask step shows you something: its FIRST read must be the output of an earlier step. A read is not a
712
+ // grant (the ask stays a pure stop); the check is for the plan checker only (fitJobLine), so signed flows still run.
713
+ if (fitJobLine === true && reads !== null && fromLine !== null && askLines.includes(fromLine)
714
+ && (reads.length === 0 || !earlierEmits.includes(reads[0]))) {
715
+ const want = earlierEmits.length === 0 ? 'the output of an earlier step, and no earlier step makes one' : earlierEmits[earlierEmits.length - 1];
716
+ const got = reads.length === 0 ? 'it reads nothing' : `its first read, ${reads[0]}, is not made by an earlier step`;
717
+ reds.push(`declaration: Line ${fromLine} asks you to check something, but ${got}. Line ${fromLine} must read ${want}.`);
718
+ }
719
+
694
720
  // picks — the listing rule, generalised
695
721
  if (step.picks !== undefined) {
696
722
  if (!isPlainObject(step.picks)) {
@@ -0,0 +1,79 @@
1
+ // M4d amendment 10: the Chat card's list of what a draft really did. ONE function builds it (here), from the draft's own log.json and its
2
+ // declaration; the page only renders it. It sits outside the readout (never signed, never hashed).
3
+ //
4
+ // Each entry: { id, label, status: 'done' | 'failed', details: string[], reds?: string[] }. `reds` (plan checks and try lines) are the checker's raw
5
+ // refusals: the page turns each into its plain sentence (one function there). A step that didn't happen is not in the list.
6
+ // Throws away: the log's per-round tokens, the model's replies and the questions; only the facts named in the amendment are kept.
7
+ // Third outcomes: no log -> null (nothing to list); a cost that is null reads "cost unknown", an incomplete sum reads "at least $X", never 0.
8
+
9
+ const REBUILD_RE = /^declaration: steps\[(\d+)\]\.close\.shape cannot be built into a check — (.*)$/s;
10
+ const TRIES = 3;
11
+
12
+ function money(log) {
13
+ if (typeof log.costUsd !== 'number') return 'cost unknown';
14
+ return `${log.spendComplete === false ? 'at least ' : ''}$${log.costUsd.toFixed(4)}`;
15
+ }
16
+
17
+ /** Why a round did not give a plan: its validator reds (raw, as `reds`: the page's one translator makes them plain), else its outcome as a detail line. */
18
+ function reasonOf(entry) {
19
+ if (Array.isArray(entry?.reds) && entry.reds.length > 0) return { details: [], reds: entry.reds.map(String) };
20
+ const o = typeof entry?.outcome === 'string' ? entry.outcome : '';
21
+ return { details: o === '' ? [] : [o.replace(/^structure: /, '')] };
22
+ }
23
+
24
+ /**
25
+ * @param {{ log: any, declaration: any }} p `log` = the draft's log.json (parsed), `declaration` = declaration.json or declaration.rejected.json (parsed)
26
+ * @returns {Array<{ id: string, label: string, status: 'done'|'failed', details: string[], reds?: string[] }> | null}
27
+ */
28
+ export function draftStepList({ log, declaration }) {
29
+ if (log === null || typeof log !== 'object') return null;
30
+ const rounds = Array.isArray(log.log) ? log.log : [];
31
+ /** @type {Array<{ id: string, label: string, status: 'done'|'failed', details: string[], reds?: string[] }>} */
32
+ const out = [];
33
+
34
+ const t = log.thinking;
35
+ if (t && (t.asked === 'on' || t.asked === 'off') && typeof t.status === 'string') {
36
+ if (t.status === 'applied') out.push({ id: 'thinking', label: `thinking ${t.asked}`, status: 'done', details: [] });
37
+ else if (typeof t.say === 'string' && t.say !== '') out.push({ id: 'thinking', label: t.say, status: 'failed', details: [] });
38
+ }
39
+
40
+ if (Array.isArray(log.inputs) && log.inputs.length > 0) {
41
+ out.push({ id: 'inputs', label: 'inputs', status: 'done', details: log.inputs.map((i) => `${i.role}: ${i.detail}`) });
42
+ }
43
+
44
+ // a plan came back (valid or refused by the checker) vs. a round that never gave one (provider red, cut off, budget)
45
+ const gotPlan = rounds.some((e) => e.outcome === 'valid' || String(e.outcome).startsWith('validator'));
46
+ const n = typeof log.rounds === 'number' ? log.rounds : 0;
47
+ const who = typeof log.modelId === 'string' && log.modelId !== '' ? log.modelId : 'the drafter';
48
+ const drafted = { id: 'drafted', label: `drafted with ${who}`, status: /** @type {'done'|'failed'} */ (gotPlan ? 'done' : 'failed'), details: [`${n} round${n === 1 ? '' : 's'} · ${money(log)}`] };
49
+ if (!gotPlan) drafted.details.push(...(Array.isArray(log.reds) ? log.reds.map(String) : []));
50
+ out.push(drafted);
51
+
52
+ const reds = Array.isArray(log.reds) ? log.reds.map(String) : [];
53
+ const steps = Array.isArray(declaration?.steps) ? declaration.steps : [];
54
+ const rubricReds = [];
55
+ const checkReds = [];
56
+ for (const r of reds) {
57
+ const m = REBUILD_RE.exec(r);
58
+ if (m) rubricReds.push(`line ${steps[Number(m[1])]?.fromLine ?? '?'}: ${m[2]}`); else checkReds.push(r);
59
+ }
60
+ if (gotPlan) {
61
+ out.push(log.ok === true
62
+ ? { id: 'checks', label: 'plan checks', status: 'done', details: [] }
63
+ : { id: 'checks', label: 'plan checks', status: 'failed', details: [], reds: checkReds });
64
+ }
65
+
66
+ if (log.ok === true) {
67
+ const soft = steps.filter((s) => s?.close?.class === 'softgreen');
68
+ if (soft.length > 0) out.push({ id: 'rubrics', label: 'rubrics', status: 'done', details: soft.map((s) => `line ${s.fromLine}: built`) });
69
+ } else if (rubricReds.length > 0) {
70
+ out.push({ id: 'rubrics', label: 'rubrics', status: 'failed', details: rubricReds });
71
+ }
72
+
73
+ rounds.forEach((e, i) => {
74
+ if (i === 0) return;
75
+ const no = i + 1;
76
+ out.push({ id: `try-${no}`, label: no <= TRIES ? `try ${no} of ${TRIES}` : `try ${no}`, status: e.outcome === 'valid' ? 'done' : 'failed', ...reasonOf(rounds[i - 1]) });
77
+ });
78
+ return out;
79
+ }
package/src/drafter.js CHANGED
@@ -21,9 +21,13 @@ import { validateDeclaration, SHAPE_KEYS, checkGuardrailSums, guardrailWordsPerS
21
21
  import { loadCatalogue } from './catalogue.js';
22
22
  import { WIRED_VERBS, wiredMenu } from './primitives.js';
23
23
  import { readInputFacts } from './input-facts.js';
24
- import { makeProvider, sumMeterings, ceilingCostUsd, priceRecord } from './provider.js';
24
+ import { isCellsPath } from './closers.js';
25
+ import {
26
+ makeProvider, ModelRefusal, sumMeterings, ceilingCostUsd, priceRecord,
27
+ } from './provider.js';
25
28
  import { LIVE_PROVIDER_OPTIONS } from './model-step.js';
26
29
  import { ConfigError } from './config.js';
30
+ import { thinkingSay, worstThinkingStatus } from './thinking.js';
27
31
 
28
32
  export const MAX_STRUCTURE_RETRIES = 2;
29
33
  export const MAX_REVISIONS = 2;
@@ -63,7 +67,7 @@ export function buildDeclarationSchema(menu) {
63
67
  items: { type: 'string', enum: menu.map((e) => e.verb) },
64
68
  description: 'verbs this step is granted, from the menu only; [] for a pure stop',
65
69
  },
66
- reads: { type: 'array', items: { type: 'string' }, description: 'artifact ids emitted by EARLIER steps only' },
70
+ reads: { type: 'array', items: { type: 'string' }, description: 'artifact ids emitted by EARLIER steps only (an ask step lists the earlier output to be checked FIRST), or the role of a CSV input (a step whose line has a green guardrail must list a CSV input role here)' },
67
71
  emits: { type: 'string', minLength: 1, description: 'the ONE new artifact id this step declares (unique)' },
68
72
  fromLine: { type: ['integer', 'null'], description: 'the ONE numbered job line this step serves' },
69
73
  picks: {
@@ -214,6 +218,15 @@ function jobLinesText(lines, asks) {
214
218
  .join('\n');
215
219
  }
216
220
 
221
+ /** M4d amendment 8: the green step must read an input with cells, so the drafter is told the rule and which inputs have cells. */
222
+ function greenReadRule(sources) {
223
+ const csvRoles = (sources ?? []).filter((s) => s.kind === 'file' && isCellsPath(s.path)).map((s) => s.role);
224
+ const rule = '- A step whose line has a "green" guardrail must list the CSV input\'s role in its reads (for example reads: ["aging"]), because only an input with cells can be cited; a text output of an earlier step has no cells. A green step that reads only other steps is refused.';
225
+ return [csvRoles.length
226
+ ? `${rule} CSV inputs in this job: ${csvRoles.join(', ')}.`
227
+ : `${rule} This job signs no CSV input, so a guardrail that needs cited cells cannot be classed green here: class it "hitl".`];
228
+ }
229
+
217
230
  export function buildSystemPrompt({ menu, lines, arbiter, factsInfo }) {
218
231
  const askLines = arbiter.asks.map((a) => a.line);
219
232
  const sendLines = arbiter.sends.map((s) => s.line);
@@ -224,14 +237,16 @@ export function buildSystemPrompt({ menu, lines, arbiter, factsInfo }) {
224
237
  ...menu.map((e) => `- ${e.verb}: ${e.desc} (class: ${e.class})`),
225
238
  '',
226
239
  'Rules:',
227
- '- 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.',
240
+ '- Steps share one artifact space. Each step: primitives (verbs it needs, [] if none), reads (artifact ids emitted by an EARLIER step, or the role of a CSV input listed under Inputs), 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.',
228
241
  '- Every numbered job line must be served by a step (fromLine = that line) or listed in "refused" with a reason.',
229
242
  '- 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".',
230
243
  '- 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.',
244
+ ...greenReadRule(arbiter.sources),
231
245
  '- close.shape only on a softgreen step; it is the human\'s declared shape in structured form.',
232
246
  '- 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.',
233
247
  `- 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.`,
234
248
  `- 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.`,
249
+ '- An ask step must read the output of an earlier step, the thing you are asked to check: its FIRST read is what the human sees at the ask (for example reads: ["bucket_assignment"], the nearest earlier step\'s emits). An ask that reads nothing, or reads something no earlier step makes, is refused. Reading is not a grant: the ask still grants no primitive.',
235
250
  '- Nothing hitl may come after the last signed ask except the send step.',
236
251
  '- You never author a trigger, cap, ask position or TTL, allow-list, send target, or what "done" means.',
237
252
  '',
@@ -260,9 +275,6 @@ function reviseMessage(reds) {
260
275
 
261
276
  function isPlainObject(v) { return !!v && typeof v === 'object' && !Array.isArray(v); }
262
277
 
263
- // F49: deepseek-flash 400s on a forced tool_choice in thinking mode; the drafter forces its tool, so disable thinking.
264
- export const DRAFT_PROVIDER_OPTIONS = Object.freeze({ ...LIVE_PROVIDER_OPTIONS, thinking: Object.freeze({ type: 'disabled' }) });
265
-
266
278
  /**
267
279
  * Draft one declaration. `provider`/`rates`/`modelId` may be injected (tests,
268
280
  * the batch); otherwise a live provider is built from `slot` (throws on a bad
@@ -275,17 +287,24 @@ export const DRAFT_PROVIDER_OPTIONS = Object.freeze({ ...LIVE_PROVIDER_OPTIONS,
275
287
  *
276
288
  * @returns {Promise<{ok:boolean, declaration:object|null, reds:string[], rounds:number, calls:number, spendComplete:boolean,
277
289
  * 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[]}>}
290
+ * questions?:{line:number, question:string}[], droppedQuestions?:object[], notChecked?:string[], thinking?:{asked:string, status:string|null, say:string|null}, inputs?:{role:string, detail:string}[]}>}
279
291
  */
280
292
  export async function draft({
281
- proseText, slot = 'deepseek', model, provider: injected, rates: injectedRates, modelId: injectedModelId, env,
282
- budgetUsd = 0.10, skills = DRAFT_SKILLS, makeProviderFn = makeProvider, onBook, offerQuestions = true,
293
+ proseText, slot, model, provider: injected, rates: injectedRates, modelId: injectedModelId, env,
294
+ budgetUsd = 0.10, skills = DRAFT_SKILLS, makeProviderFn = makeProvider, onBook, offerQuestions = true, draftThinking = /** @type {'on'|'off'} */ ('off'),
283
295
  }) {
296
+ // What was asked of thinking and the WORST status bareagent reported across the rounds (the page says it loudly unless 'applied'). Read from the round log, the one record.
297
+ const thinkingOf = () => {
298
+ const status = worstThinkingStatus(log.map((e) => e.thinkingStatus));
299
+ return { asked: draftThinking, status, say: thinkingSay(status) };
300
+ };
284
301
  const fail = (reds, extra = {}) => ({
285
302
  ok: false, declaration: null, reds, rounds: 0, calls: 0, spendComplete: true, costUsd: 0, modelReturned: null, structureRetries: 0, revisions: 0, stop: 'pre-flight', log: [], ...extra,
286
303
  });
287
304
 
288
305
  // ---- $0 gates, before any provider is built -------------------------------
306
+ // `draftThinking` ('on'|'off', M4d am6 item 7 / am7: the Chat tick-box, per job) is an intent only: turning thinking on or off on the wire is bareagent's (am7 item 3).
307
+ if (draftThinking !== 'on' && draftThinking !== 'off') return fail([`config: draftThinking must be on | off, got ${JSON.stringify(draftThinking)}`]);
289
308
  const parsed = parseSignedText(proseText);
290
309
  if (!parsed.ok) return fail(parsed.reds.map((r) => `signed-text: ${r}`));
291
310
  const { lines, arbiter } = parsed;
@@ -304,9 +323,9 @@ export async function draft({
304
323
  try {
305
324
  ({
306
325
  provider, rates, modelId, prices = null,
307
- } = makeProviderFn(slot, { model, env, ...DRAFT_PROVIDER_OPTIONS }));
326
+ } = makeProviderFn(slot, { model, env, ...LIVE_PROVIDER_OPTIONS }));
308
327
  } catch (err) {
309
- return fail([`${err instanceof ConfigError ? 'config' : 'key'}: ${err.message}`]);
328
+ return fail([err instanceof ModelRefusal ? err.message : `${err instanceof ConfigError ? 'config' : 'key'}: ${err.message}`]);
310
329
  }
311
330
  }
312
331
 
@@ -318,7 +337,9 @@ export async function draft({
318
337
  const cat = loadCatalogue();
319
338
  if (!cat.ok) return fail([`catalogue: ${cat.reds.join('; ')}`]);
320
339
  const validationCatalogue = cat.primitives;
321
- const roundCeiling = ceilingCostUsd(modelId, undefined, prices ? { prices } : {});
340
+ // The hold: the picked model's own Settings prices (or the rates a test injected) times the token bounds - never a table.
341
+ if (!rates) return fail(['price: this round has no price to hold - tick a model in Settings > Providers with both prices first']);
342
+ const roundCeiling = ceilingCostUsd(rates);
322
343
  // One round at its ceiling must fit the budget, or refuse at $0 before any provider call.
323
344
  if (roundCeiling > budgetUsd) {
324
345
  return fail([`budget: $${budgetUsd} is below one round's worst-case cost — the minimum budget is $${roundCeiling.toFixed(4)}`]);
@@ -374,7 +395,9 @@ export async function draft({
374
395
  result = await loop.run(
375
396
  [{ role: 'system', content: system }, { role: 'user', content: userText }],
376
397
  [tool],
377
- { maxTokens: DRAFT_MAX_TOKENS, toolChoice: { name: TOOL } },
398
+ // M4d am4: thinking 'on' forces no tool (provider default 'auto'; a text reply goes to the structure retry); 'off' forces it.
399
+ // M4d am7 item 3: `thinkingMode` is bareagent's switch ('on' | 'off'); we send no raw `thinking` field anywhere.
400
+ { maxTokens: DRAFT_MAX_TOKENS, thinkingMode: draftThinking, ...(draftThinking === 'on' ? {} : { toolChoice: { name: TOOL } }) },
378
401
  );
379
402
  } catch (err) {
380
403
  threw = err;
@@ -383,6 +406,9 @@ export async function draft({
383
406
  book(false);
384
407
  const entry = { round: log.length + 1, kind: nextKind };
385
408
 
409
+ if (result?.thinkingApplied !== undefined) entry.thinkingApplied = result.thinkingApplied; // bareagent's verdict on this round: true | false | null
410
+ if (result?.thinkingStatus !== undefined) entry.thinkingStatus = result.thinkingStatus; // 'applied' | 'unsupported' | 'ignored' | 'unknown' (bare-agent >= 0.52)
411
+
386
412
  if (threw) {
387
413
  entry.outcome = `provider-red: ${threw.message}`;
388
414
  log.push(entry);
@@ -399,6 +425,19 @@ export async function draft({
399
425
  entry.outcome = `structure: ${why}`;
400
426
  log.push(entry);
401
427
  lastReds = [why];
428
+ // M4d am3 A3: a round cut off at the output cap before tries 1 and 2 are spent is a FAILED TRY, advancing the same counter a
429
+ // validator red does, so the try-3 question can open. A cut-off names no line, so then every job line may be asked about.
430
+ if (result?.stopReason === 'max_tokens' && revisions < MAX_REVISIONS) {
431
+ revisions += 1;
432
+ nextKind = 'revision';
433
+ userText = `Your last reply was cut off at the output limit before a complete tool call. Call ${TOOL} now with a complete, valid JSON declaration.`;
434
+ 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')}`;
435
+ if (offerQuestions && revisions === MAX_REVISIONS) {
436
+ failedLines = lineNums;
437
+ userText += `\n\n${QUESTIONS_PROMPT}`;
438
+ }
439
+ continue;
440
+ }
402
441
  if (structureRetries >= MAX_STRUCTURE_RETRIES) { stop = 'structure'; break; }
403
442
  structureRetries += 1;
404
443
  nextKind = 'structure-retry';
@@ -439,7 +478,7 @@ export async function draft({
439
478
  log.push(entry);
440
479
  const m = sumMeterings(meterings);
441
480
  return {
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,
481
+ 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, thinking: thinkingOf(), inputs: facts.list, ...extras,
443
482
  };
444
483
  }
445
484
  lastReds = [...verdict.reds];
@@ -461,6 +500,6 @@ export async function draft({
461
500
  // Runner convention: `costUsd` is the priced sum (null when ANY round is unpriced, so the CLI prints UNKNOWN,
462
501
  // never a bare number), and `spendComplete:false` marks a call that failed unmetered or a round left unpriced.
463
502
  return {
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,
503
+ 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, thinking: thinkingOf(), inputs: facts.list, ...extras,
465
504
  };
466
505
  }
package/src/flow.js CHANGED
@@ -28,6 +28,7 @@ import path from 'node:path';
28
28
  import { parseSignedText } from './signed-text.js';
29
29
  import { signFlow, verifyFlow } from './signature.js';
30
30
  import { validateDeclaration } from './declaration.js';
31
+ import { describeChange } from './signed-diff.js';
31
32
 
32
33
  /** @typedef {import('./types.js').WriteFlowResult} WriteFlowResult */
33
34
  /** @typedef {import('./types.js').ReadFlowResult} ReadFlowResult */
@@ -40,6 +41,15 @@ export const FLOW_FILES = Object.freeze(['prose.txt', 'declaration.json', 'signa
40
41
  export const PANEL_STARTS_DIR = '.starts';
41
42
 
42
43
  const RUNS_DIR = 'runs';
44
+ /** Amendment 43: the write-once copy of the two signed files, made at sign by `writeFlow` (the ONE writer). Outside FLOW_FILES: it never enters the signature or `readFlow`'s success path. */
45
+ const SIGNED_COPY_DIR = 'signed';
46
+ const CHANGED_PREFIX = 'changed since signing: ';
47
+
48
+ /** The plain "what changed" sentences inside a readFlow refusal (am43), joined for a sentence a human reads; '' when there are none. @param {string[]} reds */
49
+ export function changeSentence(reds) {
50
+ const xs = reds.filter((r) => typeof r === 'string' && r.startsWith(CHANGED_PREFIX)).map((r) => r.slice(CHANGED_PREFIX.length));
51
+ return xs.length > 0 ? ` What changed: ${xs.join('; ')}.` : '';
52
+ }
43
53
 
44
54
  /**
45
55
  * Check a flow name against the allowed shape: 1..64 characters, lowercase
@@ -404,11 +414,14 @@ function readTextFile(filePath, label, reds) {
404
414
  * last (each via a temp file + rename in the same directory), creates an
405
415
  * empty `runs/`, and proves the result by reading it back with `readFlow`.
406
416
  *
407
- * @param {{root: unknown, name: unknown, proseText: unknown, declaration: unknown, signedBy: unknown, signedAt: unknown, catalogue: unknown}} input
417
+ * M6: with `replaces: {flowHash}` it instead REPLACES the signed job already under that name (see `replaceSigned`), and only if that job is
418
+ * still the one with that signature hash. `onReplaceStep` is a test seam: called after each move of the swap; a throw there is a failure.
419
+ *
420
+ * @param {{root: unknown, name: unknown, proseText: unknown, declaration: unknown, signedBy: unknown, signedAt: unknown, catalogue: unknown, replaces?: {flowHash: string}, onReplaceStep?: (step: string) => void}} input
408
421
  * @returns {WriteFlowResult}
409
422
  */
410
423
  export function writeFlow({
411
- root, name, proseText, declaration, signedBy, signedAt, catalogue,
424
+ root, name, proseText, declaration, signedBy, signedAt, catalogue, replaces, onReplaceStep,
412
425
  }) {
413
426
  const nameCheck = checkFlowName(name);
414
427
  if (!nameCheck.ok) return { ok: false, reds: [nameCheck.red] };
@@ -440,6 +453,12 @@ export function writeFlow({
440
453
 
441
454
  const dir = path.join(root, safeName);
442
455
 
456
+ if (replaces !== undefined) {
457
+ return replaceSigned({
458
+ root, name: safeName, dir, proseText: /** @type {string} */ (proseText), declarationText, signature: signResult.signature, replaces, catalogue, onReplaceStep,
459
+ });
460
+ }
461
+
443
462
  // Refuse if any of the three files already exists — M1 never overwrites a
444
463
  // signed flow (versions are M4).
445
464
  for (const fileName of FLOW_FILES) {
@@ -455,6 +474,10 @@ export function writeFlow({
455
474
  }
456
475
  }
457
476
 
477
+ if (existsSync(path.join(dir, SIGNED_COPY_DIR))) {
478
+ return { ok: false, reds: [`flow: "${SIGNED_COPY_DIR}" already exists at ${path.join(dir, SIGNED_COPY_DIR)}`] };
479
+ }
480
+
458
481
  // Track what THIS call creates so a failure partway through can be rolled
459
482
  // back — a directory must never be left with a signature but a missing
460
483
  // file.
@@ -466,7 +489,7 @@ export function writeFlow({
466
489
  if (createdDir) {
467
490
  rmSync(dir, { recursive: true, force: true });
468
491
  } else {
469
- for (const p of written) rmSync(p, { force: true });
492
+ for (const p of written) rmSync(p, { recursive: true, force: true });
470
493
  }
471
494
  } catch {
472
495
  // best-effort cleanup; the red already reports the real failure
@@ -495,6 +518,12 @@ export function writeFlow({
495
518
  try {
496
519
  writeOne('prose.txt', proseText);
497
520
  writeOne('declaration.json', declarationText);
521
+ // am43: the copy of what is being signed, write-once (`wx` refuses an existing file), before the signature that makes it a signed flow.
522
+ const copyDir = path.join(dir, SIGNED_COPY_DIR);
523
+ mkdirSync(copyDir);
524
+ written.push(copyDir);
525
+ writeFileSync(path.join(copyDir, 'prose.txt'), /** @type {string} */ (proseText), { encoding: 'utf8', flag: 'wx' });
526
+ writeFileSync(path.join(copyDir, 'declaration.json'), declarationText, { encoding: 'utf8', flag: 'wx' });
498
527
  writeOne('signature.json', `${JSON.stringify(signResult.signature, null, 2)}\n`);
499
528
 
500
529
  const runsDir = path.join(dir, RUNS_DIR);
@@ -517,6 +546,95 @@ export function writeFlow({
517
546
  };
518
547
  }
519
548
 
549
+ /**
550
+ * The signature hash (`signature.json` `flow`) of the signed job in `flowDir`, or null when there is no readable one. It does NOT verify the
551
+ * files (that is `readFlow`): it only says which signing this folder is at, for M6's "was this job signed again since you opened it".
552
+ * @param {string} flowDir @returns {string|null}
553
+ */
554
+ export function signedHashOf(flowDir) {
555
+ const f = readFileInside(flowDir, 'signature.json');
556
+ if (!f.ok) return null;
557
+ try { const h = JSON.parse(f.text)?.flow; return typeof h === 'string' && h !== '' ? h : null; } catch { return null; }
558
+ }
559
+
560
+ /** M6: the names `replaceSigned` swaps, signature last (the file that makes the folder a signed flow). `setup.jsonl` is only moved away: the caller writes the new one. */
561
+ const SWAP_NAMES = ['prose.txt', 'declaration.json', SIGNED_COPY_DIR, 'setup.jsonl', 'signature.json'];
562
+
563
+ /**
564
+ * M6 ("Signing replaces the job"): replace the signed job in `<root>/<name>/`, ALL OR NOTHING, keeping the name, `runs/` and the flow's books.
565
+ * Refuses (touching nothing) unless the folder holds a signed job whose `signature.json` `flow` hash is `replaces.flowHash` (a draft opened from an
566
+ * older version of the job, or a job signed again meanwhile, is refused by name). The new files are staged inside the folder first; the swap then moves
567
+ * each old file into a backup folder and its new one into place (signature last); ANY failure, or a proof read that does not verify, moves everything
568
+ * back. On success the backup is deleted — no old version is kept anywhere (hamr's ruling). Only a hard kill inside the swap leaves the backup
569
+ * (`.replace-old-*`) holding the old files; nothing recovers it automatically.
570
+ * @param {{root: string, name: string, dir: string, proseText: string, declarationText: string, signature: any, replaces: {flowHash: string}, catalogue: unknown, onReplaceStep?: (step: string) => void}} a
571
+ * @returns {WriteFlowResult}
572
+ */
573
+ function replaceSigned({
574
+ root, name, dir, proseText, declarationText, signature, replaces, catalogue, onReplaceStep,
575
+ }) {
576
+ const red = (/** @type {string} */ r) => ({ ok: /** @type {false} */ (false), reds: [r] });
577
+ let dirStat;
578
+ try { dirStat = lstatSync(dir); } catch { return red(`flow: nothing signed to replace — "${name}" has no folder here`); }
579
+ if (dirStat.isSymbolicLink() || !dirStat.isDirectory()) return red(`flow: "${dir}" is not a plain folder, refused`);
580
+ const current = signedHashOf(dir);
581
+ if (current === null) return red(`flow: nothing signed to replace — "${name}" has no readable signature.json`);
582
+ if (typeof replaces?.flowHash !== 'string' || current !== replaces.flowHash) {
583
+ return red(`flow: "${name}" was signed again since you opened it for editing, so this edit is out of date. Nothing was changed. Open the job again and redo the edit.`);
584
+ }
585
+
586
+ const stamp = `${process.pid}-${Date.now()}`;
587
+ const stage = path.join(dir, `.replace-new-${stamp}`);
588
+ const backup = path.join(dir, `.replace-old-${stamp}`);
589
+ const moved = []; // names whose OLD file is now in backup
590
+ const placed = []; // names whose NEW file is now in dir
591
+ const cleanup = () => {
592
+ for (const p of [stage, backup]) { try { rmSync(p, { recursive: true, force: true }); } catch { /* best-effort */ } }
593
+ };
594
+ const putBack = () => {
595
+ for (const n of [...placed].reverse()) rmSync(path.join(dir, n), { recursive: true, force: true });
596
+ for (const n of [...moved].reverse()) renameSync(path.join(backup, n), path.join(dir, n));
597
+ };
598
+ const fail = (/** @type {string} */ why) => {
599
+ try { putBack(); } catch (err) {
600
+ // the old files could not all be put back: say where they are rather than pretend (the backup is NOT cleaned up)
601
+ return red(`flow: ${why}; the old job could not be fully put back (${err.message}) — its files are in ${backup}`);
602
+ }
603
+ cleanup();
604
+ return red(`flow: ${why}`);
605
+ };
606
+
607
+ try {
608
+ mkdirSync(stage);
609
+ mkdirSync(backup);
610
+ mkdirSync(path.join(stage, SIGNED_COPY_DIR));
611
+ writeFileSync(path.join(stage, 'prose.txt'), proseText, 'utf8');
612
+ writeFileSync(path.join(stage, 'declaration.json'), declarationText, 'utf8');
613
+ writeFileSync(path.join(stage, SIGNED_COPY_DIR, 'prose.txt'), proseText, { encoding: 'utf8', flag: 'wx' });
614
+ writeFileSync(path.join(stage, SIGNED_COPY_DIR, 'declaration.json'), declarationText, { encoding: 'utf8', flag: 'wx' });
615
+ writeFileSync(path.join(stage, 'signature.json'), `${JSON.stringify(signature, null, 2)}\n`, 'utf8');
616
+ } catch (err) {
617
+ cleanup();
618
+ return red(`flow: could not stage the new files — ${err.message}. Nothing was changed.`);
619
+ }
620
+
621
+ try {
622
+ for (const n of SWAP_NAMES) {
623
+ if (existsSync(path.join(dir, n))) { renameSync(path.join(dir, n), path.join(backup, n)); moved.push(n); }
624
+ if (existsSync(path.join(stage, n))) { renameSync(path.join(stage, n), path.join(dir, n)); placed.push(n); }
625
+ onReplaceStep?.(n);
626
+ }
627
+ } catch (err) {
628
+ return fail(`could not replace the job — ${err.message}`);
629
+ }
630
+
631
+ // the mechanical "it happened" check, as at sign: read the replaced job back through the one reader
632
+ const proof = readFlow({ root, name, catalogue });
633
+ if (!proof.ok) return fail(`the replaced job does not verify (${proof.reds.join('; ')})`);
634
+ cleanup();
635
+ return { ok: true, dir, signature };
636
+ }
637
+
520
638
  /**
521
639
  * Read and verify a signed flow from `<root>/<name>/`. Verifies the bytes on
522
640
  * disk against the signature FIRST — before anything in the flow is
@@ -602,8 +720,21 @@ export function readFlow({ root, name, catalogue }) {
602
720
  const verified = verifyFlow({
603
721
  proseText, declarationText, signature: signatureJson,
604
722
  });
605
- if (!verified.ok) return { ok: false, reds: verified.reds };
723
+ if (!verified.ok) return { ok: false, reds: [...verified.reds, ...explainEdit(dir, signatureJson, /** @type {string} */ (proseText), /** @type {string} */ (declarationText))] };
606
724
 
725
+ return interpretSigned({
726
+ proseText: /** @type {string} */ (proseText), declarationJson, signatureJson, catalogue, dir,
727
+ });
728
+ }
729
+
730
+ /**
731
+ * The part of a read that follows a passed signature check, shared by `readFlow` and `readRunJobCopy`: parse the signed text, validate the declaration.
732
+ * @param {{proseText: string, declarationJson: any, signatureJson: any, catalogue: unknown, dir: string}} a
733
+ * @returns {ReadFlowResult}
734
+ */
735
+ function interpretSigned({
736
+ proseText, declarationJson, signatureJson, catalogue, dir,
737
+ }) {
607
738
  const signed = parseSignedText(proseText);
608
739
  if (!signed.ok) return { ok: false, reds: signed.reds };
609
740
 
@@ -613,7 +744,7 @@ export function readFlow({ root, name, catalogue }) {
613
744
  if (!validated.ok) return { ok: false, reds: validated.reds };
614
745
 
615
746
  return {
616
- ok: true,
747
+ ok: /** @type {true} */ (true),
617
748
  dir,
618
749
  lines: signed.lines,
619
750
  arbiter: signed.arbiter,
@@ -622,3 +753,87 @@ export function readFlow({ root, name, catalogue }) {
622
753
  classes: validated.classes,
623
754
  };
624
755
  }
756
+
757
+ /** M6: the folder inside a run that holds the copy of the job it ran. */
758
+ const RUN_JOB_DIR = 'job';
759
+
760
+ /**
761
+ * M6 ("Each run saves a copy of the job it ran when it starts"): the ONE writer of `<runDir>/job/`. Reads the flow's three files, proves them against
762
+ * the flow's own signature first (a flow that does not verify is never copied), then writes them write-once (`wx`). `{ok:false, red}` writes nothing
763
+ * it did not finish (a half-written copy is removed). Never throws.
764
+ * @param {string} flowDir @param {string} runDir @param {string} [expectedFlowHash] the `signature.flow` the caller read; a different job on disk is refused
765
+ * @returns {{ok: true} | {ok: false, red: string}}
766
+ */
767
+ export function writeRunJobCopy(flowDir, runDir, expectedFlowHash) {
768
+ const texts = {};
769
+ for (const f of FLOW_FILES) {
770
+ const r = readFileInside(flowDir, f);
771
+ if (!r.ok) return { ok: false, red: `job copy: could not read ${f} (${r.missing ? 'missing' : r.red})` };
772
+ texts[f] = r.text;
773
+ }
774
+ let signature;
775
+ try { signature = JSON.parse(texts['signature.json']); } catch { return { ok: false, red: 'job copy: signature.json is not valid JSON' }; }
776
+ const verified = verifyFlow({ proseText: texts['prose.txt'], declarationText: texts['declaration.json'], signature });
777
+ if (!verified.ok) return { ok: false, red: `job copy: the flow does not match its signature (${verified.reds[0]})` };
778
+ // M6 F3: the copy must be the job the run verified at its start; a job replaced since is never copied (nothing is written)
779
+ if (typeof expectedFlowHash === 'string' && signature.flow !== expectedFlowHash) return { ok: false, red: 'the job was replaced while this run was starting' };
780
+ const dir = path.join(runDir, RUN_JOB_DIR);
781
+ try {
782
+ mkdirSync(dir);
783
+ for (const f of FLOW_FILES) writeFileSync(path.join(dir, f), texts[f], { encoding: 'utf8', flag: 'wx' });
784
+ } catch (err) {
785
+ try { if (err.code !== 'EEXIST') rmSync(dir, { recursive: true, force: true }); } catch { /* best-effort */ }
786
+ return { ok: false, red: err.code === 'EEXIST' ? 'job copy: this run already has its copy — never overwritten' : `job copy: could not write (${err.code ?? err.message})` };
787
+ }
788
+ return { ok: true };
789
+ }
790
+
791
+ /**
792
+ * M6: the job a run ran, from its own copy. `{present:false}` = the run has none (it started before M6). `{present:true, ok:true, ...}` = the same
793
+ * shape as a good `readFlow` (lines, arbiter, declaration, signature, classes), after the copy was verified against the copied signature.
794
+ * `{present:true, ok:false, reds}` = a copy that was edited or is incomplete: refused, never shown as the job.
795
+ * @param {string} runDir @param {unknown} catalogue
796
+ * @returns {{present: false} | ({present: true} & ReadFlowResult)}
797
+ */
798
+ export function readRunJobCopy(runDir, catalogue) {
799
+ const dir = path.join(runDir, RUN_JOB_DIR);
800
+ if (!existsSync(dir)) return { present: false };
801
+ const reds = [];
802
+ const proseText = readTextFile(path.join(dir, 'prose.txt'), 'prose.txt', reds);
803
+ const declarationText = readTextFile(path.join(dir, 'declaration.json'), 'declaration.json', reds);
804
+ const signatureText = readTextFile(path.join(dir, 'signature.json'), 'signature.json', reds);
805
+ let declarationJson;
806
+ let signatureJson;
807
+ try { if (declarationText !== null) declarationJson = JSON.parse(declarationText); } catch { reds.push('flow: declaration.json is not valid JSON'); }
808
+ try { if (signatureText !== null) signatureJson = JSON.parse(signatureText); } catch { reds.push('flow: signature.json is not valid JSON'); }
809
+ if (reds.length > 0) return { present: true, ok: false, reds };
810
+ const verified = verifyFlow({ proseText, declarationText, signature: signatureJson });
811
+ if (!verified.ok) return { present: true, ok: false, reds: [...verified.reds] };
812
+ return {
813
+ present: /** @type {true} */ (true),
814
+ ...interpretSigned({
815
+ proseText: /** @type {string} */ (proseText), declarationJson, signatureJson, catalogue, dir,
816
+ }),
817
+ };
818
+ }
819
+
820
+ /**
821
+ * Amendment 43: after a failed verify, name what changed by comparing with the copy `writeFlow` kept at sign. The copy is trusted ONLY if it
822
+ * verifies against signature.json itself; otherwise it is never compared. Returns extra reds (plain sentences); never throws.
823
+ * @param {string} dir @param {any} signature @param {string} proseText @param {string} declarationText
824
+ * @returns {string[]}
825
+ */
826
+ function explainEdit(dir, signature, proseText, declarationText) {
827
+ const oldProse = readFileInside(dir, `${SIGNED_COPY_DIR}/prose.txt`);
828
+ const oldDecl = readFileInside(dir, `${SIGNED_COPY_DIR}/declaration.json`);
829
+ if (!oldProse.ok && oldProse.missing && !oldDecl.ok && oldDecl.missing) {
830
+ return [CHANGED_PREFIX + '(signed before amendment 43: no copy to compare)'];
831
+ }
832
+ if (!oldProse.ok || !oldDecl.ok) return [CHANGED_PREFIX + "the saved copy of the signed files is incomplete, so it can't be trusted to compare"];
833
+ if (!verifyFlow({ proseText: oldProse.text, declarationText: oldDecl.text, signature }).ok) {
834
+ return [CHANGED_PREFIX + "the saved copy of the signed files does not match the signature, so it can't be trusted to compare"];
835
+ }
836
+ const changes = describeChange({ oldProse: oldProse.text, newProse: proseText, oldDecl: oldDecl.text, newDecl: declarationText });
837
+ if (changes.length === 0) return [CHANGED_PREFIX + 'the files match the saved copy; signature.json itself was changed'];
838
+ return changes.map((c) => `${CHANGED_PREFIX}${c}`);
839
+ }