fwdloop 0.13.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.
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.',
@@ -166,33 +258,6 @@ function reviseMessage(reds) {
166
258
  + `${TOOL} again with the complete corrected declaration:\n${reds.map((r) => `- ${r}`).join('\n')}`;
167
259
  }
168
260
 
169
- /**
170
- * M4e amendment 3 item 3 (revise the plan): the first round's user text when the human asked for a change. The model sees the
171
- * current plan (its own fields only: no machine-set `goal`, no `inputFacts`) and the note; the rules above still hold, and the
172
- * validator below is the ONE check that refuses a plan that touches what only the card may set.
173
- */
174
- export function reviseOpening(plan, note) {
175
- const own = {
176
- steps: (plan.steps ?? []).map(({ goal, ...rest }) => rest), // eslint-disable-line no-unused-vars
177
- guardrailClasses: plan.guardrailClasses ?? {},
178
- unjudgeable: plan.unjudgeable ?? {},
179
- refused: plan.refused ?? [],
180
- };
181
- return [
182
- `The human reviewed the plan below and asks for a change to the plan. Call ${TOOL} with the complete revised plan.`,
183
- '',
184
- 'Current plan:',
185
- JSON.stringify(own),
186
- '',
187
- 'The human\'s note:',
188
- note,
189
- '',
190
- 'The note may change HOW steps are done (their primitives, reads, close checks). It can never change the numbered job lines, '
191
- + 'the cap, the destination, the signed asks and their waits, or the inputs: those come only from the card, so keep every '
192
- + 'line served by its step and every signed ask a pure stop exactly as the rules above say.',
193
- ].join('\n');
194
- }
195
-
196
261
  function isPlainObject(v) { return !!v && typeof v === 'object' && !Array.isArray(v); }
197
262
 
198
263
  // F49: deepseek-flash 400s on a forced tool_choice in thinking mode; the drafter forces its tool, so disable thinking.
@@ -207,15 +272,14 @@ export const DRAFT_PROVIDER_OPTIONS = Object.freeze({ ...LIVE_PROVIDER_OPTIONS,
207
272
  * `calls`) and right AFTER it (`inFlight: false`), with what is known so far, so the caller can book spend per call
208
273
  * and a draft killed between rounds still has its paid rounds on disk. It may throw before a call (nothing is
209
274
  * spent then and the draft stops); after a call it is the caller's to keep from throwing.
210
- * `revise` (M4e amendment 3 item 3): `{ plan, note }` — the current green plan and the human's note; the first round then asks for the
211
- * revised plan. Everything else (the $0 gates, the validator, the budget, the metering) is the same code path as a first draft.
212
275
  *
213
276
  * @returns {Promise<{ok:boolean, declaration:object|null, reds:string[], rounds:number, calls:number, spendComplete:boolean,
214
- * 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[]}>}
215
279
  */
216
280
  export async function draft({
217
281
  proseText, slot = 'deepseek', model, provider: injected, rates: injectedRates, modelId: injectedModelId, env,
218
- budgetUsd = 0.10, skills = DRAFT_SKILLS, makeProviderFn = makeProvider, onBook, revise,
282
+ budgetUsd = 0.10, skills = DRAFT_SKILLS, makeProviderFn = makeProvider, onBook, offerQuestions = true,
219
283
  }) {
220
284
  const fail = (reds, extra = {}) => ({
221
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,
@@ -227,6 +291,9 @@ export async function draft({
227
291
  const { lines, arbiter } = parsed;
228
292
  const ttlReds = unsignedAskTtls(arbiter);
229
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);
230
297
  const menu = wiredMenu(skills);
231
298
  const facts = readInputFacts(arbiter.sources);
232
299
  if (!facts.ok) return fail(facts.reds);
@@ -243,8 +310,10 @@ export async function draft({
243
310
  }
244
311
  }
245
312
 
246
- const schema = buildDeclarationSchema(menu);
247
- 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);
248
317
  // Full catalogue + the wired set: an unwired verb reds "not wired" by name; an unsigned skill reds by skill.
249
318
  const cat = loadCatalogue();
250
319
  if (!cat.ok) return fail([`catalogue: ${cat.reds.join('; ')}`]);
@@ -261,10 +330,13 @@ export async function draft({
261
330
  let revisions = 0;
262
331
  let lastReds = [];
263
332
  let lastDecl = null;
264
- let userText = revise ? reviseOpening(revise.plan, revise.note) : `Call ${TOOL} now.`;
333
+ let userText = `Call ${TOOL} now.`;
265
334
  let nextKind = 'first'; // what the round about to run actually is
266
335
  let validatorReds = []; // the last validator refusal; a structure retry after a revision must not drop it
267
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
268
340
  let calls = 0; // provider calls made (a call that threw before metering is in `calls`, not in `rounds`)
269
341
  let unmetered = 0; // calls that failed with no metering: their cost is unknown
270
342
 
@@ -274,7 +346,13 @@ export async function draft({
274
346
  const spent = meterings.reduce((sum, ev) => sum + (ev.costUsd ?? roundCeiling), 0);
275
347
  if (spent + roundCeiling > budgetUsd) { stop = 'budget'; break; }
276
348
 
349
+ // assigned inside the tool's execute callback, which TS cannot see
350
+ /** @type {any} */
277
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 });
278
356
  const tool = {
279
357
  name: TOOL,
280
358
  description: 'Emit the flow declaration over the granted primitives, or refuse lines you cannot serve.',
@@ -326,24 +404,42 @@ export async function draft({
326
404
  nextKind = 'structure-retry';
327
405
  userText = `Your last reply was not a usable tool call (${why}). Call ${TOOL} now with a complete, valid JSON declaration.`;
328
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}`;
329
408
  continue;
330
409
  }
331
410
 
332
- 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 };
333
416
  // M6a amendment 1 (F50): the goal is the signed line, set by the machine; whatever the model sent is overwritten.
334
417
  if (Array.isArray(declaration.steps)) {
335
418
  declaration.steps = declaration.steps.map((st) => (isPlainObject(st) ? { ...st, goal: goalForLine(st.fromLine, lines) } : st));
336
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
+ }
337
430
  const verdict = validateDeclaration(declaration, {
338
431
  arbiter, lines, catalogue: validationCatalogue, wired: WIRED_VERBS, verbatimGoals: true, fitJobLine: true,
339
432
  });
340
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;
341
437
  if (verdict.ok) {
342
438
  entry.outcome = 'valid';
343
439
  log.push(entry);
344
440
  const m = sumMeterings(meterings);
345
441
  return {
346
- 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,
347
443
  };
348
444
  }
349
445
  lastReds = [...verdict.reds];
@@ -355,12 +451,16 @@ export async function draft({
355
451
  validatorReds = lastReds;
356
452
  nextKind = 'revision';
357
453
  userText = reviseMessage(lastReds);
454
+ if (offerQuestions && revisions === MAX_REVISIONS) {
455
+ failedLines = linesNamedByReds(lastReds, declaration, lineNums);
456
+ userText += `\n\n${QUESTIONS_PROMPT}`;
457
+ }
358
458
  }
359
459
 
360
460
  const m = sumMeterings(meterings);
361
461
  // Runner convention: `costUsd` is the priced sum (null when ANY round is unpriced, so the CLI prints UNKNOWN,
362
462
  // never a bare number), and `spendComplete:false` marks a call that failed unmetered or a round left unpriced.
363
463
  return {
364
- 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,
365
465
  };
366
466
  }
package/src/keysfile.js CHANGED
@@ -145,8 +145,10 @@ export function loadKeysEnv(opts = {}) {
145
145
  const parsed = parseKeysText(readFileSync(fd, 'utf8'));
146
146
  /** @type {Record<string,string|undefined>} */
147
147
  const env = { ...base };
148
- for (const [name, value] of Object.entries(parsed)) {
149
- if (!env[name]) env[name] = value;
148
+ // C4 (amendment 16): only the known key names reach the env (and so a child). Any other name in the file is listed in `names`
149
+ // for Settings but its value stays here — a `NODE_OPTIONS` line must never reach a run, resume or draft child.
150
+ for (const name of KEY_NAMES) {
151
+ if (!env[name] && Object.hasOwn(parsed, name)) env[name] = parsed[name];
150
152
  }
151
153
  return {
152
154
  ok: true, path, exists: true, names: Object.entries(parsed).filter(([, v]) => v !== '').map(([n]) => n).sort(), shellOnly: knownShell(parsed), refusal: null, env,
package/src/model-step.js CHANGED
@@ -103,10 +103,10 @@ const SOFTGREEN_SCHEMA = Object.freeze({
103
103
  type: 'object',
104
104
  properties: {
105
105
  text: { type: 'string' },
106
- lines: { type: 'array', items: { type: 'string' } },
107
106
  ...DONE_PROPS,
108
107
  },
109
108
  required: ['text', 'done'],
109
+ additionalProperties: false,
110
110
  });
111
111
 
112
112
  // hitl/read-style steps: the documented common shapes are {text} or
package/src/monthly.js CHANGED
@@ -4,8 +4,12 @@
4
4
  // ONE record: `<configHome>/runs.jsonl`, append-only, mode 0600, one row per hold and per terminal note.
5
5
  // hold: { kind:'hold', holdId, what:'run'|'resume'|'draft', flow, runId, runDir, pid, procStart, holdUsd, spentAtHold, at }
6
6
  // terminal: { kind:'settled'|'released'|'refused', holdId, at, why [, alsoRunDirs] }
7
- // Rows are only ever appended. Month spend is read from each named run/draft dir's OWN `spend.jsonl`
8
- // (so the total is the same whichever `--root` a run used) — this file carries no money of its own.
7
+ // named: { kind:'named', holdId, at, alsoRunDirs } — a hold's process starts spending into one more run dir (a rerun's new run)
8
+ // rolled: { kind:'rolled', at, seen, dirs } — the reduced spend rows of dirs whose holds all ended on their own (never "process
9
+ // gone"), so a read opens one record, not one file per run; `seen` = how many rows the record had when it was read
10
+ // Rows are only ever appended. Month spend is read from each named run/draft dir's OWN `spend.jsonl` (so the total is the same
11
+ // whichever `--root` a run used); only a `rolled` row stands in for a dir's file (its copy of that dir's spend, kept if the dir is
12
+ // deleted). hold, terminal and named rows carry no money.
9
13
  //
10
14
  // The claim (bareloop `claimRun`): the door APPENDS its hold FIRST, then reads the file; only live,
11
15
  // unsettled holds that come BEFORE its own row count against it, so whoever is first holds. A hold whose
@@ -61,7 +65,7 @@ export function readRuns(home) {
61
65
  try { text = readFileSync(runsPath(home), 'utf8'); } catch { return []; }
62
66
  const rows = [];
63
67
  for (const line of text.split('\n')) {
64
- if (!line.trim()) continue;
68
+ if (line === '') continue; // a blank or torn line is skipped by the parse below
65
69
  try { const r = JSON.parse(line); if (r && typeof r === 'object') rows.push(r); } catch { /* skip */ }
66
70
  }
67
71
  return rows;
@@ -75,10 +79,7 @@ const sameMonth = (a, b) => a.getFullYear() === b.getFullYear() && a.getMonth()
75
79
  /** Every run/draft dir the record names (deduped by realpath), including dirs a settle note adds. */
76
80
  function namedDirs(rows) {
77
81
  const dirs = new Set();
78
- for (const r of rows) {
79
- if (r.kind === 'hold' && typeof r.runDir === 'string') dirs.add(r.runDir);
80
- if (Array.isArray(r.alsoRunDirs)) for (const d of r.alsoRunDirs) if (typeof d === 'string') dirs.add(d);
81
- }
82
+ for (const r of rows) for (const d of dirsNamedBy(r)) dirs.add(d);
82
83
  return [...dirs];
83
84
  }
84
85
 
@@ -87,9 +88,79 @@ function dirSpend(dir) {
87
88
  return readDirSpendRows(dir).reduce((n, r) => n + spendRowCost(r).usd, 0);
88
89
  }
89
90
 
91
+ /**
92
+ * One spend row reduced to exactly what `spendSummary` reads of it (I1, amendment 16): `u` cost (spendRowCost), `c` complete, `t` tokens,
93
+ * `w` wall ms or null, `p` the provider key, `a` the row's `at` as written (absent when it had none). Nothing else of a row is used.
94
+ */
95
+ function reduceRow(row) {
96
+ const { usd, complete } = spendRowCost(row);
97
+ return {
98
+ u: usd,
99
+ c: complete,
100
+ t: tokensOf(row.tokens),
101
+ w: Number.isFinite(row.wallMs) && row.wallMs >= 0 ? row.wallMs : null,
102
+ p: typeof row.provider === 'string' && row.provider !== '' ? row.provider : NOT_RECORDED,
103
+ ...(row.at === undefined ? {} : { a: row.at }),
104
+ };
105
+ }
106
+
107
+ const diskRows = (dir) => readDirSpendRows(dir).map(reduceRow);
108
+
109
+ /** The run dirs a row names: a hold's `runDir`, and any `alsoRunDirs` (a settle or named note). */
110
+ function dirsNamedBy(r) {
111
+ const out = [];
112
+ if (r.kind === 'hold' && typeof r.runDir === 'string') out.push(r.runDir);
113
+ if (Array.isArray(r.alsoRunDirs)) for (const d of r.alsoRunDirs) if (typeof d === 'string') out.push(d);
114
+ return out;
115
+ }
116
+
117
+ /**
118
+ * The dirs of every hold the checker settled as "process gone" (amendment 17 3A): that run may have been misjudged and still spend,
119
+ * so such a dir is never rolled (rollSettled) and an older rolled row for it is never used (rolledEntries, amendment 19 1).
120
+ * @param {any[]} rows
121
+ * @returns {Set<string>}
122
+ */
123
+ function goneDirs(rows) {
124
+ const goneHolds = new Set(rows.filter((r) => r.kind === 'settled' && r.why === 'process gone').map((r) => r.holdId));
125
+ const out = new Set();
126
+ for (const r of rows) {
127
+ if (r.kind !== 'rolled' && typeof r.holdId === 'string' && goneHolds.has(r.holdId)) for (const d of dirsNamedBy(r)) out.add(d);
128
+ }
129
+ return out;
130
+ }
131
+
132
+ /**
133
+ * The rolled spend of settled dirs (I1, amendment 16). A `rolled` row in runs.jsonl carries, for dirs whose every hold had ended,
134
+ * their reduced spend rows, and `seen` = how many rows the record had when the snapshot was read. An entry is used only if NO row
135
+ * at index >= `seen` names that dir (a resume or a rerun names it again, so its live spend is read from the dir instead). Anything
136
+ * else — no entry, a newer naming row — reads the dir as before, so a total can never differ from reading every dir.
137
+ * @param {any[]} rows
138
+ * @returns {Map<string, ReturnType<typeof reduceRow>[]>}
139
+ */
140
+ function rolledEntries(rows) {
141
+ /** @type {Map<string, {seen: number, rows: any[]}>} */
142
+ const best = new Map();
143
+ /** @type {Map<string, number>} */
144
+ const lastNamed = new Map();
145
+ rows.forEach((r, i) => {
146
+ for (const d of dirsNamedBy(r)) lastNamed.set(d, i);
147
+ if (r.kind === 'rolled' && Number.isInteger(r.seen) && r.dirs && typeof r.dirs === 'object') {
148
+ for (const [d, rs] of Object.entries(r.dirs)) {
149
+ const prev = best.get(d);
150
+ if (Array.isArray(rs) && !(prev && prev.seen > r.seen)) best.set(d, { seen: r.seen, rows: rs });
151
+ }
152
+ }
153
+ });
154
+ const gone = goneDirs(rows);
155
+ const out = new Map();
156
+ for (const [d, e] of best) if (!gone.has(d) && (lastNamed.get(d) ?? -1) < e.seen) out.set(d, e.rows);
157
+ return out;
158
+ }
159
+
90
160
  /**
91
161
  * The Money tab's figures (piece 4 reads this) and the check's month total.
92
- * @param {{ home?: string, now?: () => number }} [opts]
162
+ * `rows` (a caller that has just read the record, like the claim) saves a second parse of the same file.
163
+ * @param {{ home?: string, now?: () => number, rows?: any[] }} [opts]
93
164
  */
94
165
  export function spendSummary(opts = {}) {
95
166
  const nowDate = new Date((opts.now ?? Date.now)());
@@ -107,17 +178,18 @@ export function spendSummary(opts = {}) {
107
178
  if (wall === null) b.modelMsAtLeast = true;
108
179
  else b.modelMs = (b.modelMs ?? 0) + wall;
109
180
  };
110
- for (const dir of namedDirs(readRuns(opts.home))) {
111
- for (const row of readDirSpendRows(dir)) {
112
- const { usd, complete } = spendRowCost(row);
113
- const tokens = tokensOf(row.tokens);
114
- const wall = Number.isFinite(row.wallMs) && row.wallMs >= 0 ? row.wallMs : null;
115
- const key = typeof row.provider === 'string' && row.provider !== '' ? row.provider : NOT_RECORDED;
181
+ const record = opts.rows ?? readRuns(opts.home);
182
+ const rolled = rolledEntries(record);
183
+ for (const dir of namedDirs(record)) {
184
+ for (const row of rolled.get(dir) ?? diskRows(dir)) {
185
+ const {
186
+ u: usd, c: complete, t: tokens, w: wall, p: key,
187
+ } = row;
116
188
  const p = (byProvider[key] ??= { label: key, month: newBucket(), total: newBucket() });
117
189
  add(total, usd, complete, tokens, wall);
118
190
  add(p.total, usd, complete, tokens, wall);
119
- if (row.at === undefined || row.at === null) { undatedRows += 1; continue; }
120
- const at = new Date(row.at);
191
+ if (row.a === undefined || row.a === null) { undatedRows += 1; continue; }
192
+ const at = new Date(row.a);
121
193
  if (Number.isNaN(at.getTime())) { month.atLeast = true; p.month.atLeast = true; continue; } // could be this month: unknown, never dropped
122
194
  if (sameMonth(at, nowDate)) {
123
195
  add(month, usd, complete, tokens, wall);
@@ -169,7 +241,7 @@ function liveHeldBefore(rows, idx, home, nowIso, settle = true) {
169
241
  */
170
242
  function roomFor({ limit, holdUsd, rows, idx, home, now, nowIso, settle = true }) {
171
243
  const { heldUsd, heldRuns } = liveHeldBefore(rows, idx, home, nowIso, settle);
172
- const month = spendSummary({ home, now }).month;
244
+ const month = spendSummary({ home, now, rows }).month;
173
245
  const leftCents = Math.max(0, Math.floor((limit - month.usd - heldUsd) * 100 + 1e-6));
174
246
  const needCents = Math.ceil(holdUsd * 100 - 1e-6); // a non-finite hold never fits — never read as $0
175
247
  return {
@@ -250,6 +322,55 @@ export function claimHold({
250
322
  return { ok: true, holdId, room };
251
323
  }
252
324
 
325
+ /**
326
+ * Amendment 16 C2: a hold's process starts spending into one more run dir (a rerun's new run): name it NOW, so a process killed hard
327
+ * still has that dir's spend counted. Append-only; `namedDirs` dedupes, so the settle note naming it again never counts it twice.
328
+ * Never throws (a failed note is closed by the settle note's `alsoRunDirs` on a normal exit).
329
+ * @param {{ holdId: string|null, runDir: string, home?: string, now?: () => number }} a
330
+ */
331
+ export function nameRunDir({
332
+ holdId, runDir, home, now = Date.now,
333
+ }) {
334
+ if (!holdId) return;
335
+ try {
336
+ appendRow(home, {
337
+ kind: 'named', holdId, at: new Date(now()).toISOString(), alsoRunDirs: [realpathLoose(runDir)],
338
+ });
339
+ } catch { /* see above */ }
340
+ }
341
+
342
+ /** How many dirs one `rolled` row carries (keeps each appended line small enough to be one whole write). */
343
+ const ROLL_CHUNK = 200;
344
+
345
+ /**
346
+ * I1 (amendment 16): fold the spend of every run/draft dir whose holds have ALL ended (settled, released or refused) into `rolled`
347
+ * rows, so the next month figure or Money load reads one record instead of one file per run. Append-only; a dir already rolled and not
348
+ * named since is left alone. Reads the dirs it folds exactly as `spendSummary` would, so no total changes. Never throws.
349
+ * @param {{ home?: string, now?: () => number }} [a]
350
+ */
351
+ export function rollSettled({ home, now = Date.now } = {}) {
352
+ try {
353
+ const rows = readRuns(home);
354
+ const seen = rows.length;
355
+ const ended = new Set(rows.filter((r) => r.kind === 'settled' || r.kind === 'released' || r.kind === 'refused').map((r) => r.holdId));
356
+ /** @type {Set<string>} */
357
+ const open = new Set();
358
+ for (const r of rows) {
359
+ if (r.kind === 'rolled') continue;
360
+ const named = dirsNamedBy(r);
361
+ const unended = typeof r.holdId !== 'string' || !ended.has(r.holdId);
362
+ if (unended) for (const d of named) open.add(d);
363
+ }
364
+ for (const d of goneDirs(rows)) open.add(d);
365
+ const have = rolledEntries(rows);
366
+ const todo = namedDirs(rows).filter((d) => !open.has(d) && !have.has(d));
367
+ for (let i = 0; i < todo.length; i += ROLL_CHUNK) {
368
+ const dirs = Object.fromEntries(todo.slice(i, i + ROLL_CHUNK).map((d) => [d, diskRows(d)]));
369
+ appendRow(home, { kind: 'rolled', at: new Date(now()).toISOString(), seen, dirs });
370
+ }
371
+ } catch { /* a failed roll only means the next read opens the dirs, as before */ }
372
+ }
373
+
253
374
  /**
254
375
  * The run's own process ends or parks: give the hold back. Never throws (a failed settle is closed by the
255
376
  * next check as "process gone"). `alsoRunDirs` names dirs this process also spent into (a rerun's new run).
@@ -264,6 +385,7 @@ export function settleHold({
264
385
  kind: 'settled', holdId, at: new Date(now()).toISOString(), why, ...(alsoRunDirs?.length ? { alsoRunDirs: alsoRunDirs.map(realpathLoose) } : {}),
265
386
  });
266
387
  } catch { /* see above */ }
388
+ rollSettled({ home, now });
267
389
  }
268
390
 
269
391
  /**