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
package/src/runner.js CHANGED
@@ -41,12 +41,13 @@ import {
41
41
  } from 'node:fs';
42
42
  import { createHash, randomUUID } from 'node:crypto';
43
43
  import {
44
- dirname, extname, isAbsolute, join, resolve, sep,
44
+ basename, dirname, extname, isAbsolute, join, resolve, sep,
45
45
  } from 'node:path';
46
+ import { parseCsv } from './csv.js';
46
47
  import { fileURLToPath } from 'node:url';
47
48
 
48
49
  import {
49
- readFlow, resolveRunDir, readFileInside, readdirInside, resolveInside, FLOW_FILES, PANEL_STARTS_DIR,
50
+ readFlow, resolveRunDir, readFileInside, readdirInside, resolveInside, FLOW_FILES, PANEL_STARTS_DIR, writeRunJobCopy,
50
51
  } from './flow.js';
51
52
  import {
52
53
  writeAskArchive, readAcceptedHashesByEmits, serializeArtifact, normalizeDecision, answerTiming, effectiveExpiresAt, withReopen, setAsideAnswer,
@@ -55,7 +56,7 @@ import {
55
56
  findUnwiredVerbStep, unwiredRed, findUnbuildableCheckStep, unbuildableRed,
56
57
  } from './canrun.js'; // M4e am7 item 7: the ONE decider (F46 refusal lives there)
57
58
  import { configHome, configDoorHome } from './config.js';
58
- import { closeByClass } from './closers.js';
59
+ import { closeByClass, isCellsPath } from './closers.js';
59
60
  import {
60
61
  appendAudit, appendHistory, readAudit, readHistory, endRow, HALT_OUTCOMES,
61
62
  } from './books.js';
@@ -83,7 +84,7 @@ export const MAX_ATTEMPTS = 4;
83
84
  * (audit.jsonl) stay the source of truth; this tolerance only absorbs
84
85
  * summation-order noise, not a real gap. A billionth of a dollar is ~6
85
86
  * orders of magnitude below the cheapest real round (audit rows here run
86
- * $0.0006+), so nothing a real tamper produces can hide inside it. */
87
+ * a few hundredths of a cent and up), so nothing a real tamper produces can hide inside it. */
87
88
  export const SPEND_TOLERANCE_USD = 1e-9;
88
89
 
89
90
  // ---------------------------------------------------------------------------
@@ -188,23 +189,17 @@ export function readHaltRecord(runDir) {
188
189
  }
189
190
 
190
191
  // ---------------------------------------------------------------------------
191
- // Money — piece 2 wires live provider rates; this piece takes a per-attempt
192
- // ceiling as injected data, defaulting to a frozen table's highest entry for
193
- // an unknown model id (never a silent $0/unbounded assumption).
192
+ // Money - the per-attempt hold is injected data: the caller works it out from the
193
+ // picked model's own Settings prices (`ceilingCostUsd(rates)`, src/provider.js) and passes
194
+ // it as `ceilingUsd`. No model name or price lives here (M4d amendment 5 item 4).
194
195
  // ---------------------------------------------------------------------------
195
196
 
196
- const CEILING_TABLE_USD = Object.freeze({
197
- 'deepseek-flash': 0.02,
198
- 'synthetic-default': 0.05,
199
- });
200
-
201
- /** @param {string|null|undefined} modelId */
202
- export function resolveCeilingUsd(modelId) {
203
- if (typeof modelId === 'string' && Object.prototype.hasOwnProperty.call(CEILING_TABLE_USD, modelId)) {
204
- return CEILING_TABLE_USD[modelId];
205
- }
206
- return Math.max(...Object.values(CEILING_TABLE_USD));
207
- }
197
+ /**
198
+ * The hold one model round must fit under the cap. A caller with a model passes the number from Settings prices;
199
+ * a caller with no model prices (a test double) holds nothing.
200
+ * @param {number|undefined} ceilingUsd
201
+ */
202
+ const holdOf = (ceilingUsd) => (Number.isFinite(ceilingUsd) && /** @type {number} */ (ceilingUsd) >= 0 ? /** @type {number} */ (ceilingUsd) : 0);
208
203
 
209
204
  // ---------------------------------------------------------------------------
210
205
  // The executor — "goal in, gap back", constructed WITHOUT its close and
@@ -574,11 +569,32 @@ function readArtifactsMapChecked(runDir, ids) {
574
569
  if (!result.ok && !result.missing) {
575
570
  return { ok: false, red: `artifact "${id}" — ${result.red}` };
576
571
  }
572
+ if (!result.ok && result.missing) {
573
+ // M4d amendment 8: an id no step wrote may name a frozen CSV input; a step reads it as cells, so a green check can cite it.
574
+ const input = readInputCells(runDir, id);
575
+ if (!input.ok && !input.missing) return { ok: false, red: `input "${id}" — ${input.red}` };
576
+ if (input.ok) { map[id] = input.value; continue; }
577
+ }
577
578
  map[id] = result.ok ? result.value : undefined;
578
579
  }
579
580
  return { ok: true, map };
580
581
  }
581
582
 
583
+ /** A frozen CSV input as `{kind:'cells', header, rows}` (the shape `addressCells` gives), checked against the sha256 recorded at freeze.
584
+ * Same three outcomes as `readArtifactResult`: not an input of this run (`missing`), refused (`red`), or the cells. */
585
+ function readInputCells(runDir, id) {
586
+ const manifest = readFileInside(runDir, 'inputs.json');
587
+ if (!manifest.ok) return manifest.missing ? { ok: false, missing: true } : { ok: false, missing: false, red: manifest.red };
588
+ let entries;
589
+ try { entries = JSON.parse(manifest.text); } catch (err) { return { ok: false, missing: false, red: `inputs.json is not valid JSON — ${err.message}` }; }
590
+ const entry = Array.isArray(entries) ? entries.find((e) => e?.id === id) : undefined;
591
+ if (!entry || !isCellsPath(entry.frozen)) return { ok: false, missing: true };
592
+ const file = readFileInside(runDir, `inputs/${basename(entry.frozen)}`);
593
+ if (!file.ok) return file.missing ? { ok: false, missing: false, red: 'the frozen copy is missing' } : { ok: false, missing: false, red: file.red };
594
+ if (createHash('sha256').update(file.text).digest('hex') !== entry.sha256) return { ok: false, missing: false, red: 'the frozen copy changed since it was frozen' };
595
+ return { ok: true, value: { kind: 'cells', ...parseCsv(file.text) } };
596
+ }
597
+
582
598
  // ---------------------------------------------------------------------------
583
599
  // Item 4 (small): an `answer.json` still on disk, unconsumed, at run end —
584
600
  // a late human answer that arrived after the run already moved on. One
@@ -940,7 +956,7 @@ async function runStepRalph({
940
956
  * @param {string[]} [opts.primitiveReds] - `resolvePrimitives`'s own `reds` (e.g. bareguard refusing a symlinked file scope); any entry refuses the run at $0 like an unwired verb, before the run dir exists.
941
957
  * @param {() => string} [opts.clock] - returns the current ISO timestamp; defaults to the wall clock.
942
958
  * @param {string} opts.businessDate - the run's explicit "as of today", never the wall clock.
943
- * @param {number} [opts.ceilingUsd] - per-attempt ceiling override; defaults to `resolveCeilingUsd(null)`.
959
+ * @param {number} [opts.ceilingUsd] - per-attempt ceiling override; the model's hold from Settings prices (`ceilingCostUsd`); absent = no hold.
944
960
  * @param {string|null} [opts.initialGap] - M3 scope item 7 (rerun as a fresh
945
961
  * run): a human's rerun reason, carried as the FIRST ordinary step's
946
962
  * starting gap. Never used by a plain `runFlow` call outside `resumeRun`'s
@@ -1003,7 +1019,7 @@ export async function runFlow({
1003
1019
  const { arbiter } = applied;
1004
1020
  const capUsd = arbiter.capUsd;
1005
1021
  const redoCap = arbiter.redoCap ?? 3;
1006
- const effectiveCeilingUsd = ceilingUsd ?? resolveCeilingUsd(null);
1022
+ const effectiveCeilingUsd = holdOf(ceilingUsd);
1007
1023
  const askLines = new Map((arbiter.asks ?? []).map((a) => [a.line, a]));
1008
1024
  const sendLines = new Map((arbiter.sends ?? []).map((s) => [s.line, s]));
1009
1025
 
@@ -1046,6 +1062,14 @@ export async function runFlow({
1046
1062
  }
1047
1063
  mkdirSync(runDir, { recursive: true });
1048
1064
 
1065
+ // M6: the run keeps a write-once copy of the job it runs, from before its first step (its Job tab shows this, not the flow's later versions)
1066
+ const jobCopy = writeRunJobCopy(flowDir, runDir, signature.flow);
1067
+ if (!jobCopy.ok) {
1068
+ return haltRun({
1069
+ flowDir, runDir, runId, capUsd, startedAt, now, nowMs: getNowMs, signatureHash: signature.flow, outcome: 'preflight-red', red: jobCopy.red, spent: { value: 0 },
1070
+ });
1071
+ }
1072
+
1049
1073
  const frozen = freezeInputs(runDir, sources ?? []);
1050
1074
  if (!frozen.ok) {
1051
1075
  return haltRun({
@@ -2226,7 +2250,7 @@ export async function resumeRun({
2226
2250
 
2227
2251
  const capUsd = arbiter.capUsd;
2228
2252
  const redoCap = arbiter.redoCap ?? 3;
2229
- const effectiveCeilingUsd = ceilingUsd ?? resolveCeilingUsd(null);
2253
+ const effectiveCeilingUsd = holdOf(ceilingUsd);
2230
2254
 
2231
2255
  const step = steps[state.stepIndex];
2232
2256
  const askSlot = askLines.get(step.fromLine);
@@ -2510,7 +2534,7 @@ export async function continueRun({
2510
2534
  inputsManifest: halt.inputsManifest,
2511
2535
  capUsd,
2512
2536
  redoCap: arbiter.redoCap ?? 3,
2513
- effectiveCeilingUsd: ceilingUsd ?? resolveCeilingUsd(null),
2537
+ effectiveCeilingUsd: holdOf(ceilingUsd),
2514
2538
  primitives,
2515
2539
  businessDate,
2516
2540
  modelStep,
@@ -0,0 +1,71 @@
1
+ // M5 close / amendment 43: say what changed. Pure — no disk, no clock. Given the signed copy of the two signed files and what is on disk now,
2
+ // name each change in plain words ("line 3 changed", "line 3's guardrail changed", "the cap changed") instead of only the file name.
3
+ // What this throws away: the old and new values themselves (only that a thing changed, and for a number the two numbers); a prose edit
4
+ // that parses to the same lines and arbiter (spacing, blank lines) is named as "wording or spacing", never silently dropped.
5
+
6
+ import { parseSignedText } from './signed-text.js';
7
+
8
+ const same = (a, b) => JSON.stringify(a) === JSON.stringify(b);
9
+ const sec = (ms) => (ms % 3600000 === 0 ? `${ms / 3600000}h` : ms % 60000 === 0 ? `${ms / 60000}m` : `${ms / 1000}s`);
10
+
11
+ /**
12
+ * @param {{ oldProse: string, newProse: string, oldDecl: string, newDecl: string }} x the signed copy (old) and the files on disk (new)
13
+ * @returns {string[]} plain sentences; empty when nothing differs
14
+ */
15
+ export function describeChange({ oldProse, newProse, oldDecl, newDecl }) {
16
+ const out = [];
17
+ const a = parseSignedText(oldProse);
18
+ const b = parseSignedText(newProse);
19
+ if (oldProse.replace(/\r\n/g, '\n') !== newProse.replace(/\r\n/g, '\n')) {
20
+ if (!a.ok || !b.ok) {
21
+ out.push(b.ok ? 'the signed text could not be compared with the saved copy' : `prose.txt no longer reads as a signed job (${b.reds[0]})`);
22
+ } else {
23
+ const before = new Map(a.lines.map((l) => [l.n, l]));
24
+ const after = new Map(b.lines.map((l) => [l.n, l]));
25
+ for (const [n, l] of before) {
26
+ const m = after.get(n);
27
+ if (!m) { out.push(`line ${n} was removed`); continue; }
28
+ if (l.text !== m.text) out.push(`line ${n} changed`);
29
+ if (l.guardrail !== m.guardrail) out.push(`line ${n}'s guardrail changed`);
30
+ }
31
+ for (const n of after.keys()) if (!before.has(n)) out.push(`line ${n} was added`);
32
+ const x = a.arbiter;
33
+ const y = b.arbiter;
34
+ if (x.capUsd !== y.capUsd) out.push(`the cap changed (from $${x.capUsd} to $${y.capUsd})`);
35
+ if (x.redoCap !== y.redoCap) out.push(`the redo cap changed (from ${x.redoCap} to ${y.redoCap})`);
36
+ if (x.roundBudgetMs !== y.roundBudgetMs) out.push(`the round budget changed (from ${sec(x.roundBudgetMs)} to ${sec(y.roundBudgetMs)})`);
37
+ if (!same(x.skills, y.skills)) out.push('the skills changed');
38
+ for (const k of x.asks) {
39
+ const o = y.asks.find((s) => s.line === k.line);
40
+ if (!o) out.push(`the ask at line ${k.line} was removed`);
41
+ else if (o.ttlMs !== k.ttlMs) out.push(`the wait of the ask at line ${k.line} changed (from ${sec(k.ttlMs)} to ${sec(o.ttlMs)})`);
42
+ else if (o.question !== k.question) out.push(`the question of the ask at line ${k.line} changed`);
43
+ }
44
+ for (const k of y.asks) if (!x.asks.some((s) => s.line === k.line)) out.push(`an ask was added at line ${k.line}`);
45
+ for (const k of x.sends) {
46
+ const o = y.sends.find((s) => s.line === k.line);
47
+ if (!o) out.push(`the send at line ${k.line} was removed`);
48
+ else if (!same(o.target, k.target)) out.push(`the send destination at line ${k.line} changed`);
49
+ }
50
+ for (const k of y.sends) if (!x.sends.some((s) => s.line === k.line)) out.push(`a send was added at line ${k.line}`);
51
+ for (const k of x.sources) {
52
+ const o = y.sources.find((s) => s.role === k.role);
53
+ if (!o) out.push(`the input "${k.role}" was removed`);
54
+ else if (!same(o, k)) out.push(`the input "${k.role}" changed`);
55
+ }
56
+ for (const k of y.sources) if (!x.sources.some((s) => s.role === k.role)) out.push(`an input "${k.role}" was added`);
57
+ if (out.length === 0) out.push('prose.txt changed in wording or spacing (no job line, guardrail or arbiter value differs)');
58
+ }
59
+ }
60
+ let d1;
61
+ let d2;
62
+ try { d1 = JSON.stringify(sortDeep(JSON.parse(oldDecl))); d2 = JSON.stringify(sortDeep(JSON.parse(newDecl))); } catch { d1 = oldDecl; d2 = newDecl; }
63
+ if (d1 !== d2) out.push('the plan changed (declaration.json)');
64
+ return out;
65
+ }
66
+
67
+ function sortDeep(v) {
68
+ if (Array.isArray(v)) return v.map(sortDeep);
69
+ if (v && typeof v === 'object') return Object.fromEntries(Object.keys(v).sort().map((k) => [k, sortDeep(v[k])]));
70
+ return v;
71
+ }
@@ -0,0 +1,55 @@
1
+ // M4d amendment 7: bareagent decides whether a model's thinking can be changed - not our code, not a table of ours.
2
+ // ONE function wraps bareagent's `thinkingSupport(provider, model, { baseUrl })` (bare-agent >= 0.52, 'bare-agent/providers'): a pure lookup that returns
3
+ // `{ switchable: true | false | 'unverified', off, on, note }`. We return just `switchable`. Its first argument is bareagent's own provider KIND,
4
+ // not our row's API shape id, so a shape id is mapped to its kind here. A shape with no kind, or an answer that is not that object, is 'unverified'
5
+ // (the Chat "Thinking on" box then works and bareagent errors loudly at the call).
6
+ // The row's Base URL is the 3rd argument: bareagent picks the specific kind from the model id / Base URL host exactly as its request path does (0.52).
7
+ // A call whose model can't switch no longer throws: bareagent runs it and reports `thinkingStatus`; the sentences for that are `thinkingSay` below.
8
+ import * as providers from 'bare-agent/providers';
9
+
10
+ /** The sentence under a greyed "Thinking on" box (amendment 7 item 2). */
11
+ export const THINKING_FIXED_SAY = "can't change this for this model";
12
+
13
+ /** Our API shape id -> bareagent's provider kind. */
14
+ const KIND_OF_SHAPE = Object.freeze({ 'anthropic-api': 'anthropic', 'openai-api': 'openai', 'gemini-api': 'gemini' });
15
+
16
+ /**
17
+ * @param {string} shape the row's API shape @param {string} model
18
+ * @param {{ impl?: unknown, baseUrl?: string }} [opts] `impl` is a test seam: the function standing in for bareagent's export (default: the installed export); `baseUrl` is the row's Base URL
19
+ * @returns {true|false|'unverified'}
20
+ */
21
+ export function thinkingSupport(shape, model, { impl = /** @type {any} */ (providers).thinkingSupport, baseUrl } = {}) {
22
+ const kind = /** @type {Record<string, string>} */ (KIND_OF_SHAPE)[shape];
23
+ if (typeof impl !== 'function' || kind === undefined) return 'unverified';
24
+ let answer;
25
+ try { answer = impl(kind, model, baseUrl === undefined || baseUrl === '' ? undefined : { baseUrl }); } catch { return 'unverified'; }
26
+ const s = answer !== null && typeof answer === 'object' ? answer.switchable : undefined;
27
+ return s === true || s === false ? s : 'unverified';
28
+ }
29
+
30
+ /** bareagent's `thinkingStatus` values, worst first (its own order: ignored > unsupported > unknown > applied). */
31
+ const WORST_FIRST = Object.freeze(['ignored', 'unsupported', 'unknown', 'applied']);
32
+
33
+ /**
34
+ * The worst of a draft's per-round statuses; `null` when no round carried one.
35
+ * @param {Array<string|null|undefined>} statuses @returns {string|null}
36
+ */
37
+ export function worstThinkingStatus(statuses) {
38
+ return WORST_FIRST.find((s) => statuses.includes(s)) ?? null;
39
+ }
40
+
41
+ /** The note beside the Chat "Thinking on" box, before any draft, for a model bareagent has not checked (M4d am11 item 2). */
42
+ export const THINKING_UNVERIFIED_SAY = 'thinking off (not verified for this model)';
43
+
44
+ /**
45
+ * The ONE place the thinking words live (M4d am11: bareloop's words). The ✗ line shown in the Chat list when thinking did not go as asked.
46
+ * The words are fixed strings, never built from what was asked: they say what the model did (bareloop's code-owned words).
47
+ * 'applied' (and no status) says nothing here (the list's own "thinking on ✓" / "thinking off ✓" covers it).
48
+ * @param {string|null} status @returns {string|null}
49
+ */
50
+ export function thinkingSay(status) {
51
+ if (status === 'ignored') return 'thinking on (the model thought anyway)';
52
+ if (status === 'unsupported') return "thinking on (this model can't change it)";
53
+ if (status === 'unknown') return 'thinking off (not confirmed)';
54
+ return null;
55
+ }
@@ -86,13 +86,15 @@ export function draftKeyRefusal(slot: string, env: Record<string, string | undef
86
86
  *
87
87
  * Test seam: `provider`/`rates`/`modelId` are injected; without them a live provider is built.
88
88
  */
89
- export function draftToDir({ proseFile, dir, root, name, slot, model, budgetUsd, env, provider, rates, modelId, noQuestions, }: {
89
+ export function draftToDir({ proseFile, dir, root, name, slot, model, draftThinking, keyNames, budgetUsd, env, provider, rates, modelId, noQuestions, }: {
90
90
  proseFile: any;
91
91
  dir: any;
92
92
  root: any;
93
93
  name: any;
94
- slot?: string | undefined;
94
+ slot: any;
95
95
  model: any;
96
+ draftThinking?: "on" | "off" | undefined;
97
+ keyNames: any;
96
98
  budgetUsd?: number | undefined;
97
99
  env?: NodeJS.ProcessEnv | undefined;
98
100
  provider: any;
@@ -146,14 +148,21 @@ export function draftToDir({ proseFile, dir, root, name, slot, model, budgetUsd,
146
148
  * The human step, $0. Every refusal returns reds and writes NO flow.
147
149
  * `signedBy` must come from the human's own invocation (the CLI's --signed-by/username).
148
150
  * `sessionDir` (the panel's draft folder: card, notes, every change) widens the setup record; the CLI has none, so its record is the one plan folder.
151
+ * M6: `replaces: {flowHash}` (a draft opened from an existing signed job, carrying that job's signature hash) makes this sign REPLACE that job
152
+ * (`writeFlow` checks the hash is still the job's); without it a taken name is refused as ever.
153
+ * @param {{dir: any, approve?: any, signedBy: any, signedAt?: string, env?: Record<string, string|undefined>, keyNames?: string[], sessionDir?: string, replaces?: {flowHash: string}}} a
149
154
  */
150
- export function signDraft({ dir, approve, signedBy, signedAt, env, sessionDir, }: {
155
+ export function signDraft({ dir, approve, signedBy, signedAt, env, keyNames, sessionDir, replaces, }: {
151
156
  dir: any;
152
- approve: any;
157
+ approve?: any;
153
158
  signedBy: any;
154
- signedAt?: string | undefined;
155
- env?: NodeJS.ProcessEnv | undefined;
156
- sessionDir: any;
159
+ signedAt?: string;
160
+ env?: Record<string, string | undefined>;
161
+ keyNames?: string[];
162
+ sessionDir?: string;
163
+ replaces?: {
164
+ flowHash: string;
165
+ };
157
166
  }): {
158
167
  ok: boolean;
159
168
  reds: any[];
@@ -169,6 +178,10 @@ export function signDraft({ dir, approve, signedBy, signedAt, env, sessionDir, }
169
178
  ok: false;
170
179
  red: string;
171
180
  };
181
+ modelRecord: {
182
+ ok: boolean;
183
+ recorded: boolean;
184
+ };
172
185
  };
173
186
  export const DRAFT_BUDGET_USD: 0.1;
174
187
  export const SPEC_HASH_FILE: "spec.hash";
@@ -1,12 +1,14 @@
1
1
  /**
2
2
  * One entry per step, in plan order: the plain sentences for what its typed close checks.
3
- * @param {{ steps?: any[] }} declaration @param {{ hasAsk?: boolean }} [opts] hasAsk = the job has a signed ask line (so "you check it at the ask" is true)
3
+ * @param {{ steps?: any[] }} declaration @param {{ hasAsk?: boolean, askLines?: number[] }} [opts] hasAsk = the job has a signed ask line (so "you check it at the ask" is true);
4
+ * askLines = the job lines of the signed asks, which also lets a step after the LAST ask read "you check it after you accept" (am41 item 2, am42: the ONE place for these words)
4
5
  * @returns {{ step: number, line: number|null, goal: string, class: string, sentences: string[] }[]}
5
6
  */
6
7
  export function checkedLines(declaration: {
7
8
  steps?: any[];
8
- }, { hasAsk }?: {
9
+ }, { hasAsk, askLines }?: {
9
10
  hasAsk?: boolean;
11
+ askLines?: number[];
10
12
  }): {
11
13
  step: number;
12
14
  line: number | null;
@@ -19,5 +21,5 @@ export function notCheckedBlock(items: unknown): {
19
21
  label: string;
20
22
  items: any[];
21
23
  };
22
- /** The label that always sits with the "Not checked" list. */
23
- export const NOT_CHECKED_LABEL: "the drafter's own reading, not a guarantee";
24
+ /** The label that always sits with the "Not checked" list (am41 item 3: the ONE place these words live; the Job tab and the Chat card read it off their payloads). */
25
+ export const NOT_CHECKED_LABEL: "not checked (the AI's own reading)";
@@ -1,3 +1,5 @@
1
+ /** An input with cells (M4d amendment 8): a file whose name ends `.csv`. The one decider for "this input can be cited". */
2
+ export function isCellsPath(p: any): boolean;
1
3
  /**
2
4
  * `green` close: every field in `artifact.fields`, in declared order,
3
5
  * resolves and matches its cite. First red wins.
package/types/config.d.ts CHANGED
@@ -22,6 +22,14 @@ export function configDoorHome(): {
22
22
  };
23
23
  /** One provider field's value problem in plain words, or null when fine. Shared by validateDoc and the route. */
24
24
  export function providerFieldProblem(field: any, v: any): string | null;
25
+ /**
26
+ * THE one rule for a slot's model lines (M4d amendment 3 items 7-8), used by config validation and the Settings
27
+ * route. A price is a PAIR (`inPerM` and `outPerM`, each a finite number >= 0 — 0 / 0 typed is a chosen price,
28
+ * recorded so it is never unknown) or neither (null / absent). A ticked line (`use`) needs both. Plain words, or null.
29
+ * @param {any} list
30
+ * @returns {string|null}
31
+ */
32
+ export function modelsProblem(list: any): string | null;
25
33
  /**
26
34
  * The parsed, validated document. `{}` when the file is missing. THROWS ConfigError when the file is
27
35
  * there but unreadable, not a JSON object, or holds an invalid known field — never `{}` for those.
@@ -33,7 +41,7 @@ export function readConfig(opts?: {
33
41
  }): Record<string, any>;
34
42
  /**
35
43
  * Apply a patch and write. `null` deletes a field. Top-level fields shallow-merge; `prices` merges
36
- * per slot, then per field (`prices.<slot> = null` clears the slot, `prices.<slot>.<field> = null`
44
+ * per slot, then per field; `models.<slot>` is replaced whole (`prices.<slot> = null` clears the slot, `prices.<slot>.<field> = null`
37
45
  * clears the field). Everything is validated before anything is written; a refusal leaves the file
38
46
  * untouched.
39
47
  * @param {Record<string, any>} patch
@@ -0,0 +1,14 @@
1
+ /**
2
+ * @param {{ log: any, declaration: any }} p `log` = the draft's log.json (parsed), `declaration` = declaration.json or declaration.rejected.json (parsed)
3
+ * @returns {Array<{ id: string, label: string, status: 'done'|'failed', details: string[], reds?: string[] }> | null}
4
+ */
5
+ export function draftStepList({ log, declaration }: {
6
+ log: any;
7
+ declaration: any;
8
+ }): Array<{
9
+ id: string;
10
+ label: string;
11
+ status: "done" | "failed";
12
+ details: string[];
13
+ reds?: string[];
14
+ }> | null;
@@ -253,11 +253,11 @@ export function goalForLine(fromLine: any, lines: any): any;
253
253
  *
254
254
  * @returns {Promise<{ok:boolean, declaration:object|null, reds:string[], rounds:number, calls:number, spendComplete:boolean,
255
255
  * costUsd:number|null, modelReturned:string|null, modelId?:string, price?:object|null, tokens?:object|null, structureRetries:number, revisions:number, stop:string|null, log:object[],
256
- * questions?:{line:number, question:string}[], droppedQuestions?:object[], notChecked?:string[]}>}
256
+ * questions?:{line:number, question:string}[], droppedQuestions?:object[], notChecked?:string[], thinking?:{asked:string, status:string|null, say:string|null}, inputs?:{role:string, detail:string}[]}>}
257
257
  */
258
- export function draft({ proseText, slot, model, provider: injected, rates: injectedRates, modelId: injectedModelId, env, budgetUsd, skills, makeProviderFn, onBook, offerQuestions, }: {
258
+ export function draft({ proseText, slot, model, provider: injected, rates: injectedRates, modelId: injectedModelId, env, budgetUsd, skills, makeProviderFn, onBook, offerQuestions, draftThinking, }: {
259
259
  proseText: any;
260
- slot?: string | undefined;
260
+ slot: any;
261
261
  model: any;
262
262
  provider: any;
263
263
  rates: any;
@@ -268,6 +268,7 @@ export function draft({ proseText, slot, model, provider: injected, rates: injec
268
268
  makeProviderFn?: typeof makeProvider | undefined;
269
269
  onBook: any;
270
270
  offerQuestions?: boolean | undefined;
271
+ draftThinking?: "on" | "off" | undefined;
271
272
  }): Promise<{
272
273
  ok: boolean;
273
274
  declaration: object | null;
@@ -290,6 +291,15 @@ export function draft({ proseText, slot, model, provider: injected, rates: injec
290
291
  }[];
291
292
  droppedQuestions?: object[];
292
293
  notChecked?: string[];
294
+ thinking?: {
295
+ asked: string;
296
+ status: string | null;
297
+ say: string | null;
298
+ };
299
+ inputs?: {
300
+ role: string;
301
+ detail: string;
302
+ }[];
293
303
  }>;
294
304
  export const MAX_STRUCTURE_RETRIES: 2;
295
305
  export const MAX_REVISIONS: 2;
@@ -305,11 +315,4 @@ export const CHECKABLE: readonly string[];
305
315
  export const NOTCHECKED_PROMPT: string;
306
316
  /** 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. */
307
317
  export const QUESTIONS_PROMPT: string;
308
- export const DRAFT_PROVIDER_OPTIONS: Readonly<{
309
- thinking: Readonly<{
310
- type: "disabled";
311
- }>;
312
- timeoutMs: 300000;
313
- deadlineMs: 240000;
314
- }>;
315
318
  import { makeProvider } from './provider.js';
package/types/flow.d.ts CHANGED
@@ -1,3 +1,5 @@
1
+ /** The plain "what changed" sentences inside a readFlow refusal (am43), joined for a sentence a human reads; '' when there are none. @param {string[]} reds */
2
+ export function changeSentence(reds: string[]): string;
1
3
  /**
2
4
  * Check a flow name against the allowed shape: 1..64 characters, lowercase
3
5
  * a-z, 0-9, `-`, `_`, starting with a letter or digit. Walked character by
@@ -174,10 +176,13 @@ export function readdirInside(baseDir: string, relDir: string): string[];
174
176
  * last (each via a temp file + rename in the same directory), creates an
175
177
  * empty `runs/`, and proves the result by reading it back with `readFlow`.
176
178
  *
177
- * @param {{root: unknown, name: unknown, proseText: unknown, declaration: unknown, signedBy: unknown, signedAt: unknown, catalogue: unknown}} input
179
+ * M6: with `replaces: {flowHash}` it instead REPLACES the signed job already under that name (see `replaceSigned`), and only if that job is
180
+ * 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.
181
+ *
182
+ * @param {{root: unknown, name: unknown, proseText: unknown, declaration: unknown, signedBy: unknown, signedAt: unknown, catalogue: unknown, replaces?: {flowHash: string}, onReplaceStep?: (step: string) => void}} input
178
183
  * @returns {WriteFlowResult}
179
184
  */
180
- export function writeFlow({ root, name, proseText, declaration, signedBy, signedAt, catalogue, }: {
185
+ export function writeFlow({ root, name, proseText, declaration, signedBy, signedAt, catalogue, replaces, onReplaceStep, }: {
181
186
  root: unknown;
182
187
  name: unknown;
183
188
  proseText: unknown;
@@ -185,7 +190,17 @@ export function writeFlow({ root, name, proseText, declaration, signedBy, signed
185
190
  signedBy: unknown;
186
191
  signedAt: unknown;
187
192
  catalogue: unknown;
193
+ replaces?: {
194
+ flowHash: string;
195
+ };
196
+ onReplaceStep?: (step: string) => void;
188
197
  }): WriteFlowResult;
198
+ /**
199
+ * 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
200
+ * 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".
201
+ * @param {string} flowDir @returns {string|null}
202
+ */
203
+ export function signedHashOf(flowDir: string): string | null;
189
204
  /**
190
205
  * Read and verify a signed flow from `<root>/<name>/`. Verifies the bytes on
191
206
  * disk against the signature FIRST — before anything in the flow is
@@ -200,6 +215,31 @@ export function readFlow({ root, name, catalogue }: {
200
215
  name: unknown;
201
216
  catalogue: unknown;
202
217
  }): ReadFlowResult;
218
+ /**
219
+ * 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
220
+ * 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
221
+ * it did not finish (a half-written copy is removed). Never throws.
222
+ * @param {string} flowDir @param {string} runDir @param {string} [expectedFlowHash] the `signature.flow` the caller read; a different job on disk is refused
223
+ * @returns {{ok: true} | {ok: false, red: string}}
224
+ */
225
+ export function writeRunJobCopy(flowDir: string, runDir: string, expectedFlowHash?: string): {
226
+ ok: true;
227
+ } | {
228
+ ok: false;
229
+ red: string;
230
+ };
231
+ /**
232
+ * 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
233
+ * shape as a good `readFlow` (lines, arbiter, declaration, signature, classes), after the copy was verified against the copied signature.
234
+ * `{present:true, ok:false, reds}` = a copy that was edited or is incomplete: refused, never shown as the job.
235
+ * @param {string} runDir @param {unknown} catalogue
236
+ * @returns {{present: false} | ({present: true} & ReadFlowResult)}
237
+ */
238
+ export function readRunJobCopy(runDir: string, catalogue: unknown): {
239
+ present: false;
240
+ } | ({
241
+ present: true;
242
+ } & ReadFlowResult);
203
243
  /** @typedef {import('./types.js').WriteFlowResult} WriteFlowResult */
204
244
  /** @typedef {import('./types.js').ReadFlowResult} ReadFlowResult */
205
245
  /** @typedef {import('./types.js').CheckFlowNameResult} CheckFlowNameResult */
@@ -0,0 +1,16 @@
1
+ /**
2
+ * @param {string} dir a draft folder or a flow folder
3
+ * @returns {{ slot: string, model: string }|null} null when there is no usable record (missing, unreadable, or not a name and a model id)
4
+ */
5
+ export function readModelRecord(dir: string): {
6
+ slot: string;
7
+ model: string;
8
+ } | null;
9
+ /**
10
+ * Write the record once (never over an existing one). @param {string} dir @param {{ slot: string, model: string }} pick
11
+ */
12
+ export function writeModelRecord(dir: string, { slot, model }: {
13
+ slot: string;
14
+ model: string;
15
+ }): void;
16
+ export const MODEL_FILE: "model.json";
@@ -1,6 +1,7 @@
1
1
  /**
2
2
  * @param {Array<{kind?:string, role:string, path:string}>} sources arbiter.sources
3
- * @returns {{ok:boolean, inputFacts:Record<string,string[]>, info:string[], reds:string[]}}
3
+ * `list` (M4d am10) is one `{role, detail}` per readable input for the Chat card's list (a CSV: its columns; text: its headings); never hashed.
4
+ * @returns {{ok:boolean, inputFacts:Record<string,string[]>, info:string[], list:Array<{role:string, detail:string}>, reds:string[]}}
4
5
  */
5
6
  export function readInputFacts(sources: Array<{
6
7
  kind?: string;
@@ -10,5 +11,9 @@ export function readInputFacts(sources: Array<{
10
11
  ok: boolean;
11
12
  inputFacts: Record<string, string[]>;
12
13
  info: string[];
14
+ list: Array<{
15
+ role: string;
16
+ detail: string;
17
+ }>;
13
18
  reds: string[];
14
19
  };
@@ -1,3 +1,9 @@
1
+ /**
2
+ * THE rule for what may be a key name (hamr's ruling, branch-review): it looks like an API key, `…_KEY` in capitals. Used at every gate:
3
+ * the `names` Settings lists, the env pass-through, and the routes that take a slot name. A `NODE_OPTIONS` line is not a key.
4
+ * @param {unknown} name @returns {name is string}
5
+ */
6
+ export function isKeyName(name: unknown): name is string;
1
7
  /**
2
8
  * `~/.config/fwdloop`, or an injected override. The CLI/panel door honors the test-only
3
9
  * `FWDLOOP_CONFIG_HOME` through `keysForDoor` (two gates, like the other test seams).
@@ -25,20 +31,29 @@ export function parseKeysText(text: string): Record<string, string>;
25
31
  * @property {string} path the keys file's path as shown to people
26
32
  * @property {boolean} exists the file is there (true after a create)
27
33
  * @property {string[]} names the NAMES the file defines with a value (sorted; never values)
28
- * @property {string[]} shellOnly the known key names that only the shell sets (file empty/absent)
34
+ * @property {string[]} shellOnly the configured key names that only the shell sets (file empty/absent)
35
+ * @property {string[]} keyNames the NAMES of the keys that are set up in Settings and hold a value in `env` (the scrub list's names; never values)
29
36
  * @property {string|null} refusal a plain sentence when `ok` is false, else null
30
37
  * @property {Record<string,string|undefined>} env shell env with the file filling the names the
31
38
  * shell does not set; on a refusal just a copy of the shell env (no file value). THE ONLY
32
39
  * place file values leave this module.
33
40
  */
34
41
  /**
35
- * Load the keys file over an env. A missing file is created (0600) and is not a refusal.
36
- * @param {{ env?: Record<string,string|undefined>, home?: string }} [opts]
42
+ * The key VALUES of the named keys in an env: the scrub list. The names come from a load's `keyNames`.
43
+ * @param {Record<string,string|undefined>} env @param {readonly string[]|undefined} names
44
+ * @returns {string[]}
45
+ */
46
+ export function keyValues(env: Record<string, string | undefined>, names: readonly string[] | undefined): string[];
47
+ /**
48
+ * Load the keys file over an env. A missing file is created (0600) and is not a refusal. `configured` = the key names that have a row
49
+ * set up in Settings (`config.providers`): only those file values reach `env`.
50
+ * @param {{ env?: Record<string,string|undefined>, home?: string, configured?: string[] }} [opts]
37
51
  * @returns {KeysLoad}
38
52
  */
39
53
  export function loadKeysEnv(opts?: {
40
54
  env?: Record<string, string | undefined>;
41
55
  home?: string;
56
+ configured?: string[];
42
57
  }): KeysLoad;
43
58
  /**
44
59
  * The door helper the CLI and the panel call. Loads the file only when the caller is on the
@@ -54,8 +69,6 @@ export function keysForDoor(deps?: {
54
69
  }): KeysLoad & {
55
70
  skipped: boolean;
56
71
  };
57
- /** The key names fwdloop knows (one per provider slot). */
58
- export const KEY_NAMES: readonly ("SYNTHETIC_API_KEY" | "DEEPSEEK_API_KEY")[];
59
72
  export type KeysLoad = {
60
73
  /**
61
74
  * false = refused: nothing that needs a key may run
@@ -74,9 +87,13 @@ export type KeysLoad = {
74
87
  */
75
88
  names: string[];
76
89
  /**
77
- * the known key names that only the shell sets (file empty/absent)
90
+ * the configured key names that only the shell sets (file empty/absent)
78
91
  */
79
92
  shellOnly: string[];
93
+ /**
94
+ * the NAMES of the keys that are set up in Settings and hold a value in `env` (the scrub list's names; never values)
95
+ */
96
+ keyNames: string[];
80
97
  /**
81
98
  * a plain sentence when `ok` is false, else null
82
99
  */
@@ -80,7 +80,7 @@ export function buildEmitArtifactSchema(stepClass: any): Readonly<{
80
80
  }>;
81
81
  /**
82
82
  * @param {object} opts
83
- * @param {string} [opts.slot] - a `src/provider.js` PROVIDER_SLOTS name; required when `provider` isn't injected.
83
+ * @param {string} [opts.slot] - a provider row (the name of a key in the keys file); required when `provider` isn't injected.
84
84
  * @param {string} [opts.model] - overrides the slot's default model.
85
85
  * @param {string} opts.spendPath - the run's spend.jsonl (never a second ledger).
86
86
  * @param {any} [opts.provider] - an injected provider (tests only; production always builds live via `slot`).