fwdloop 0.6.0 → 0.7.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/bin/fwdloop +143 -64
- package/package.json +3 -3
- package/src/ask.js +260 -6
- package/src/books.js +209 -2
- package/src/flow.js +247 -2
- package/src/index.js +9 -3
- package/src/model-step.js +151 -12
- package/src/panel/data.js +1589 -0
- package/src/panel/index.html +2377 -0
- package/src/panel/server.js +268 -0
- package/src/primitives.js +136 -41
- package/src/provider.js +57 -41
- package/src/runner.js +393 -54
- package/src/send.js +20 -1
- package/src/types.js +18 -0
- package/types/ask.d.ts +77 -0
- package/types/books.d.ts +70 -2
- package/types/flow.d.ts +135 -0
- package/types/index.d.ts +5 -3
- package/types/panel/data.d.ts +433 -0
- package/types/panel/server.d.ts +45 -0
- package/types/primitives.d.ts +29 -0
- package/types/provider.d.ts +11 -0
- package/types/runner.d.ts +66 -5
- package/types/types.d.ts +41 -0
package/src/ask.js
CHANGED
|
@@ -23,6 +23,7 @@ import { join } from 'node:path';
|
|
|
23
23
|
import { randomUUID } from 'node:crypto';
|
|
24
24
|
|
|
25
25
|
import { appendAudit } from './books.js';
|
|
26
|
+
import { readFileInside, resolveInside, readdirInside } from './flow.js';
|
|
26
27
|
|
|
27
28
|
function sleep(ms) {
|
|
28
29
|
return new Promise((resolve) => { setTimeout(resolve, ms); });
|
|
@@ -73,7 +74,13 @@ export function makeFileAskStep({
|
|
|
73
74
|
let staleCount = 0;
|
|
74
75
|
|
|
75
76
|
for (;;) {
|
|
76
|
-
|
|
77
|
+
// F48 round 3: `answer.json` is checked with `resolveInside`
|
|
78
|
+
// (`src/flow.js`) before it is ever read — a symlinked answer file (or
|
|
79
|
+
// a symlinked run-dir ancestor) is treated exactly like "no answer
|
|
80
|
+
// yet" (kept polling), never read through to an outside file's
|
|
81
|
+
// content standing in for the human's real decision.
|
|
82
|
+
const answerResolved = resolveInside(runDir, 'answer.json');
|
|
83
|
+
if (answerResolved.ok) {
|
|
77
84
|
let raw = null;
|
|
78
85
|
try { raw = readFileSync(answerPath, 'utf8'); } catch { raw = null; }
|
|
79
86
|
let parsed = null;
|
|
@@ -88,7 +95,7 @@ export function makeFileAskStep({
|
|
|
88
95
|
while (existsSync(staleName)) { staleCount += 1; staleName = join(runDir, `answer.stale.${staleCount}.json`); }
|
|
89
96
|
renameSync(answerPath, staleName);
|
|
90
97
|
appendAudit(runDir, {
|
|
91
|
-
step: 'ask', attempt, class: null, verdict: 'stale-answer-ignored', gap: `answeredAt ${answeredAt} predates this ask's askedAt ${askedAt}`, usd: 0, spendComplete: true, wallMs: 0, model: null, modelMatch: null, strike: false,
|
|
98
|
+
step: 'ask', attempt, class: null, verdict: 'stale-answer-ignored', gap: `answeredAt ${answeredAt} predates this ask's askedAt ${askedAt}`, usd: 0, spendComplete: true, wallMs: 0, model: null, modelMatch: null, strike: false, at: clock(), tokens: null, tools: null,
|
|
92
99
|
});
|
|
93
100
|
// Keep polling — a stale file quarantined does not mean THIS
|
|
94
101
|
// ask has been answered.
|
|
@@ -108,6 +115,86 @@ export function makeFileAskStep({
|
|
|
108
115
|
};
|
|
109
116
|
}
|
|
110
117
|
|
|
118
|
+
// ---------------------------------------------------------------------------
|
|
119
|
+
// F47 fix (docs/logs/FINDINGS.md F47, M4a ladder item 1): the ONE shared
|
|
120
|
+
// reader for ask.json's `evidence` field, across every real shape on disk —
|
|
121
|
+
// M3 (`evidence.artifact.text` + `evidence.unjudged[].artifact.text`), M2
|
|
122
|
+
// (`evidence.text`/`evidence.lines`, no unjudged concept), and none (parked
|
|
123
|
+
// before F45 finding 2 landed the evidence-carry fix, so no `evidence` key
|
|
124
|
+
// at all). `bin/fwdloop`'s `artifactText()`/`cmdShow` and `poc/m4/panel-
|
|
125
|
+
// data.mjs` both read ask.json evidence ad hoc today; this is the one
|
|
126
|
+
// place, per "one writer/one reader" (AGENT_RULES.md), that normalises it.
|
|
127
|
+
// Never returns "undefined"/""/0 standing in for missing data — an
|
|
128
|
+
// unparseable shape is a named `why`, never a crash, never silently empty.
|
|
129
|
+
// ---------------------------------------------------------------------------
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* @param {any} ask the parsed ask.json object (or its `evidence` field's
|
|
133
|
+
* container — pass the whole ask so a missing `evidence` key is itself a
|
|
134
|
+
* handled case, not the caller's problem).
|
|
135
|
+
* @returns {{ draft: {step?: string, text: string} | null, unjudged: Array<{step: string, emits?: string, text: string}>, why?: string }}
|
|
136
|
+
*/
|
|
137
|
+
export function readAskEvidence(ask) {
|
|
138
|
+
const evidence = ask && typeof ask === 'object' ? ask.evidence : undefined;
|
|
139
|
+
|
|
140
|
+
if (evidence === undefined || evidence === null) {
|
|
141
|
+
return {
|
|
142
|
+
draft: null,
|
|
143
|
+
unjudged: [],
|
|
144
|
+
why: 'this ask was parked before evidence was recorded (pre-F45 finding 2)',
|
|
145
|
+
};
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
if (typeof evidence !== 'object') {
|
|
149
|
+
return {
|
|
150
|
+
draft: null,
|
|
151
|
+
unjudged: [],
|
|
152
|
+
why: `ask.json "evidence" is neither an object nor absent — unrecognised shape: ${typeof evidence}`,
|
|
153
|
+
};
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
// M3 shape: evidence.artifact.text (+ evidence.unjudged[]).
|
|
157
|
+
if (evidence.artifact && typeof evidence.artifact === 'object' && typeof evidence.artifact.text === 'string') {
|
|
158
|
+
const rawUnjudged = Array.isArray(evidence.unjudged) ? evidence.unjudged : [];
|
|
159
|
+
const unjudged = [];
|
|
160
|
+
for (const item of rawUnjudged) {
|
|
161
|
+
// `step` (an ask.json unjudged entry's own field name) actually
|
|
162
|
+
// carries the step's GOAL text, not its id — `emits` (when present) is
|
|
163
|
+
// the real step id (e.g. "resume-text"), dropped by the ONLY earlier
|
|
164
|
+
// version of this reader (hamr's review #9, 2026-09-27: the panel's
|
|
165
|
+
// Inbox was labelling by goal text because this function never
|
|
166
|
+
// returned `emits` at all). Both are kept honestly: `step` falls back
|
|
167
|
+
// to `emits` only when the entry names no goal text of its own,
|
|
168
|
+
// `emits` is included ONLY when the entry actually names one — a
|
|
169
|
+
// caller must never assume `emits` is present (an M2/no-`emits`
|
|
170
|
+
// fixture omits it, never a guessed value).
|
|
171
|
+
const step = item && (item.step ?? item.emits);
|
|
172
|
+
const emits = item && typeof item.emits === 'string' ? item.emits : undefined;
|
|
173
|
+
const text = item && item.artifact && typeof item.artifact.text === 'string' ? item.artifact.text : undefined;
|
|
174
|
+
if (typeof step === 'string' && typeof text === 'string') {
|
|
175
|
+
unjudged.push(emits ? { step, emits, text } : { step, text });
|
|
176
|
+
}
|
|
177
|
+
// An unjudged entry with neither a nameable step nor readable text is
|
|
178
|
+
// dropped rather than shown as a blank row — the draft itself is
|
|
179
|
+
// never lost by a malformed sibling entry.
|
|
180
|
+
}
|
|
181
|
+
return { draft: { text: evidence.artifact.text }, unjudged };
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
// M2 shape: evidence.text (+ evidence.lines) — no unjudged concept.
|
|
185
|
+
if (typeof evidence.text === 'string') {
|
|
186
|
+
return { draft: { text: evidence.text }, unjudged: [] };
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
// Present but neither recognised shape — never fall through to
|
|
190
|
+
// `undefined`/`JSON.stringify(undefined)` ("undefined" the string).
|
|
191
|
+
return {
|
|
192
|
+
draft: null,
|
|
193
|
+
unjudged: [],
|
|
194
|
+
why: `ask.json "evidence" has neither ".artifact.text" (M3) nor ".text" (M2) — unrecognised shape: keys ${JSON.stringify(Object.keys(evidence))}`,
|
|
195
|
+
};
|
|
196
|
+
}
|
|
197
|
+
|
|
111
198
|
// ---------------------------------------------------------------------------
|
|
112
199
|
// M3 piece 1 (docs/wiki/the-module-ladder.md, "M3 — scope, exit, negative —
|
|
113
200
|
// SIGNED", scope item 3, the function only — the CLI is piece 2): a separate
|
|
@@ -136,13 +223,19 @@ export function answerAsk({
|
|
|
136
223
|
return { ok: false, red: `answerAsk: unrecognised decision "${decision}"` };
|
|
137
224
|
}
|
|
138
225
|
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
226
|
+
// F48 round 3: routed through `readFileInside` — a symlinked `ask.json`
|
|
227
|
+
// (or a symlinked run-dir ancestor) reads as "no open ask", never as some
|
|
228
|
+
// outside file's content.
|
|
229
|
+
const askRead = readFileInside(runDir, 'ask.json');
|
|
230
|
+
if (!askRead.ok) {
|
|
231
|
+
if (askRead.missing) {
|
|
232
|
+
return { ok: false, red: `answerAsk: no open ask for run ${runDir}` };
|
|
233
|
+
}
|
|
234
|
+
return { ok: false, red: `answerAsk: ask.json for run ${runDir} — ${askRead.red}` };
|
|
142
235
|
}
|
|
143
236
|
let ask;
|
|
144
237
|
try {
|
|
145
|
-
ask = JSON.parse(
|
|
238
|
+
ask = JSON.parse(askRead.text);
|
|
146
239
|
} catch (err) {
|
|
147
240
|
return { ok: false, red: `answerAsk: ask.json for run ${runDir} is not valid JSON — ${err.message}` };
|
|
148
241
|
}
|
|
@@ -194,3 +287,164 @@ export function answerAsk({
|
|
|
194
287
|
}
|
|
195
288
|
return { ok: true };
|
|
196
289
|
}
|
|
290
|
+
|
|
291
|
+
// ---------------------------------------------------------------------------
|
|
292
|
+
// M4a Amendment M4a-1 — SIGNED by hamr 2026-09-27 ("sign m4a1")
|
|
293
|
+
// (docs/wiki/the-module-ladder.md, "M4a" section): every park writes a
|
|
294
|
+
// PERMANENT copy of that ask into `asks/<askId>.json` alongside the
|
|
295
|
+
// (mutable, single-slot) `ask.json`. `ask.json` keeps its current role
|
|
296
|
+
// unchanged — this is a second, append-only record, one file per askId,
|
|
297
|
+
// never overwritten, never deleted (not by resume, not by answer
|
|
298
|
+
// consumption, not by rerun — a rerun always gets a fresh run dir, so it
|
|
299
|
+
// never revisits an old askId). Write-once is a MECHANISM (exclusive
|
|
300
|
+
// create, `{ flag: 'wx' }'), not a check-then-write race: a second write
|
|
301
|
+
// for the same askId is refused, by name, and the first file on disk is
|
|
302
|
+
// left byte-identical.
|
|
303
|
+
// ---------------------------------------------------------------------------
|
|
304
|
+
|
|
305
|
+
/**
|
|
306
|
+
* Writes `asks/<askId>.json` in `runDir`, creating the `asks/` directory if
|
|
307
|
+
* needed. Called by `src/runner.js` right after it writes `ask.json` for a
|
|
308
|
+
* fresh park (same `askId`/`question`/`askedAt`/`expiresAt`/`evidence` — the
|
|
309
|
+
* archive is a permanent copy of the SAME content, not a second source of
|
|
310
|
+
* truth). Exclusive-create: a second call for an already-archived `askId`
|
|
311
|
+
* is refused (a red naming the file) rather than silently overwriting it —
|
|
312
|
+
* proven by the write itself failing (`EEXIST`), not by a separate
|
|
313
|
+
* existence check that a concurrent writer could race past.
|
|
314
|
+
*
|
|
315
|
+
* Crash-order note: this is called AFTER `ask.json` is written, so a crash
|
|
316
|
+
* between the two writes leaves `ask.json` present and `asks/<askId>.json`
|
|
317
|
+
* missing — the run is still correctly parked and resumable (ask.json/
|
|
318
|
+
* state.json govern resume, unchanged), just without its archive entry for
|
|
319
|
+
* that one askId. `listArchivedAsks` below tolerates this (it only reports
|
|
320
|
+
* what is actually on disk); it is never treated as "before M4a-1" (that
|
|
321
|
+
* `why` is reserved for a run with NO `asks/` directory at all).
|
|
322
|
+
*
|
|
323
|
+
* @param {{ runDir: string, askId: string, question: string, askedAt: string, expiresAt: string, evidence: unknown }} opts
|
|
324
|
+
* @returns {{ ok: true } | { ok: false, red: string }}
|
|
325
|
+
*/
|
|
326
|
+
export function writeAskArchive({
|
|
327
|
+
runDir, askId, question, askedAt, expiresAt, evidence,
|
|
328
|
+
}) {
|
|
329
|
+
if (typeof runDir !== 'string' || runDir.length === 0) {
|
|
330
|
+
return { ok: false, red: 'writeAskArchive: "runDir" must be a non-empty string' };
|
|
331
|
+
}
|
|
332
|
+
if (typeof askId !== 'string' || askId.length === 0) {
|
|
333
|
+
return { ok: false, red: 'writeAskArchive: "askId" must be a non-empty string' };
|
|
334
|
+
}
|
|
335
|
+
const asksDir = join(runDir, 'asks');
|
|
336
|
+
mkdirSync(asksDir, { recursive: true });
|
|
337
|
+
const archivePath = join(asksDir, `${askId}.json`);
|
|
338
|
+
const payload = {
|
|
339
|
+
askId, question, askedAt, expiresAt, evidence,
|
|
340
|
+
};
|
|
341
|
+
try {
|
|
342
|
+
writeFileSync(archivePath, JSON.stringify(payload, null, 2), { flag: 'wx' });
|
|
343
|
+
} catch (err) {
|
|
344
|
+
if (err.code === 'EEXIST') {
|
|
345
|
+
return { ok: false, red: `writeAskArchive: "${archivePath}" already exists — refusing to overwrite an archived ask` };
|
|
346
|
+
}
|
|
347
|
+
return { ok: false, red: `writeAskArchive: could not write ${archivePath} — ${err.message}` };
|
|
348
|
+
}
|
|
349
|
+
return { ok: true };
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
// ---------------------------------------------------------------------------
|
|
353
|
+
// M4a Amendment M4a-1 reader: pairs each archived ask (`asks/<askId>.json`)
|
|
354
|
+
// with its consumed answer (`answer.<askId>.consumed.json`), by askId only —
|
|
355
|
+
// never by position/order, so the reader is correct even if archives and
|
|
356
|
+
// consumed-answer files land out of step with each other. A run with no
|
|
357
|
+
// `asks/` directory at all predates M4a-1: its asks are not lost, they were
|
|
358
|
+
// simply never kept — reported with a named `why`, never an invented entry.
|
|
359
|
+
// ---------------------------------------------------------------------------
|
|
360
|
+
|
|
361
|
+
/**
|
|
362
|
+
* @param {string} runDir
|
|
363
|
+
* @returns {{ archived: true, asks: Array<{ askId: string, question?: string, askedAt?: string, expiresAt?: string,
|
|
364
|
+
* evidence: ReturnType<typeof readAskEvidence>,
|
|
365
|
+
* answer: { status: string, reason?: string, answeredAt?: string, why?: string } }> } | { archived: false, why: string }}
|
|
366
|
+
*/
|
|
367
|
+
export function listArchivedAsks(runDir) {
|
|
368
|
+
// F48 round 3: the `asks/` directory itself — and every entry inside it —
|
|
369
|
+
// is checked with `resolveInside`/`readFileInside` (`src/flow.js`), so a
|
|
370
|
+
// symlinked `asks/` (the exact shape F48's live plant used one level up,
|
|
371
|
+
// for `runs/`) is refused here rather than followed to list an outside
|
|
372
|
+
// directory, and any individual entry that is itself a symlink is skipped
|
|
373
|
+
// before this loop ever sees its name.
|
|
374
|
+
const asksDirResolved = resolveInside(runDir, 'asks');
|
|
375
|
+
if (!asksDirResolved.ok) {
|
|
376
|
+
if (asksDirResolved.missing) {
|
|
377
|
+
return { archived: false, why: 'draft not kept (before M4a-1)' };
|
|
378
|
+
}
|
|
379
|
+
return { archived: false, why: `listArchivedAsks: ${asksDirResolved.red}` };
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
const entries = readdirInside(runDir, 'asks');
|
|
383
|
+
|
|
384
|
+
const asks = [];
|
|
385
|
+
for (const entry of entries.sort()) {
|
|
386
|
+
if (!entry.endsWith('.json')) continue; // eslint-disable-line no-continue
|
|
387
|
+
const askId = entry.slice(0, -'.json'.length);
|
|
388
|
+
const archivePath = join(runDir, 'asks', entry);
|
|
389
|
+
const archiveRead = readFileInside(runDir, join('asks', entry));
|
|
390
|
+
let ask;
|
|
391
|
+
if (!archiveRead.ok) {
|
|
392
|
+
asks.push({
|
|
393
|
+
askId, question: undefined, askedAt: undefined, expiresAt: undefined,
|
|
394
|
+
evidence: {
|
|
395
|
+
draft: null,
|
|
396
|
+
unjudged: [],
|
|
397
|
+
why: archiveRead.missing
|
|
398
|
+
? `${archivePath} is missing`
|
|
399
|
+
: `${archivePath} — ${archiveRead.red}`,
|
|
400
|
+
},
|
|
401
|
+
answer: { status: 'open' },
|
|
402
|
+
});
|
|
403
|
+
continue; // eslint-disable-line no-continue
|
|
404
|
+
}
|
|
405
|
+
try {
|
|
406
|
+
ask = JSON.parse(archiveRead.text);
|
|
407
|
+
} catch (err) {
|
|
408
|
+
asks.push({
|
|
409
|
+
askId, question: undefined, askedAt: undefined, expiresAt: undefined,
|
|
410
|
+
evidence: { draft: null, unjudged: [], why: `${archivePath} is not valid JSON — ${err.message}` },
|
|
411
|
+
answer: { status: 'open' },
|
|
412
|
+
});
|
|
413
|
+
continue; // eslint-disable-line no-continue
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
const consumedRelPath = `answer.${askId}.consumed.json`;
|
|
417
|
+
const consumedRead = readFileInside(runDir, consumedRelPath);
|
|
418
|
+
let answer = { status: 'open' };
|
|
419
|
+
if (consumedRead.ok) {
|
|
420
|
+
let parsed;
|
|
421
|
+
try {
|
|
422
|
+
parsed = JSON.parse(consumedRead.text);
|
|
423
|
+
const decisionToStatus = { accept: 'accepted', reject: 'rejected', rerun: 'reran' };
|
|
424
|
+
answer = {
|
|
425
|
+
status: decisionToStatus[parsed.decision] ?? `unrecognised: ${parsed.decision}`,
|
|
426
|
+
answeredAt: parsed.answeredAt,
|
|
427
|
+
};
|
|
428
|
+
if (typeof parsed.reason === 'string') answer.reason = parsed.reason;
|
|
429
|
+
} catch (err) {
|
|
430
|
+
answer = { status: 'open', why: `${join(runDir, consumedRelPath)} is not valid JSON — ${err.message}` };
|
|
431
|
+
}
|
|
432
|
+
} else if (typeof ask.expiresAt === 'string' && !Number.isNaN(Date.parse(ask.expiresAt))
|
|
433
|
+
&& Date.now() > Date.parse(ask.expiresAt)) {
|
|
434
|
+
answer = { status: 'expired' };
|
|
435
|
+
} else {
|
|
436
|
+
answer = { status: 'unanswered' };
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
asks.push({
|
|
440
|
+
askId,
|
|
441
|
+
question: ask.question,
|
|
442
|
+
askedAt: ask.askedAt,
|
|
443
|
+
expiresAt: ask.expiresAt,
|
|
444
|
+
evidence: readAskEvidence(ask),
|
|
445
|
+
answer,
|
|
446
|
+
});
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
return { archived: true, asks };
|
|
450
|
+
}
|
package/src/books.js
CHANGED
|
@@ -21,11 +21,41 @@
|
|
|
21
21
|
import { appendFileSync, mkdirSync } from 'node:fs';
|
|
22
22
|
import { dirname, join } from 'node:path';
|
|
23
23
|
|
|
24
|
+
import { readFileInside } from './flow.js';
|
|
25
|
+
|
|
24
26
|
function appendLine(filePath, row) {
|
|
25
27
|
mkdirSync(dirname(filePath), { recursive: true });
|
|
26
28
|
appendFileSync(filePath, `${JSON.stringify(row)}\n`);
|
|
27
29
|
}
|
|
28
30
|
|
|
31
|
+
/**
|
|
32
|
+
* Raw read-back of one JSONL book, one writer's own sibling reader (M4a
|
|
33
|
+
* piece 2, docs/wiki/the-module-ladder.md M4a scope item 2: "one reader per
|
|
34
|
+
* book"). Never throws on a missing file (`[]`) or a malformed line (that
|
|
35
|
+
* one line is skipped, never crashes the whole read) — the panel and any
|
|
36
|
+
* other reader need an honest best-effort array, not a hard failure over one
|
|
37
|
+
* bad byte someone else wrote.
|
|
38
|
+
*
|
|
39
|
+
* F48 round 3: goes through `readFileInside` (`src/flow.js`) — a book file
|
|
40
|
+
* that is itself a symlink, or that sits behind a symlinked ancestor
|
|
41
|
+
* directory, resolving outside `baseDir` reads as `[]`, same as a missing
|
|
42
|
+
* file, never as the outside target's content.
|
|
43
|
+
* @param {string} baseDir - the run dir (audit.jsonl) or flow dir (history.jsonl)
|
|
44
|
+
* @param {string} relPath - the book's own file name, relative to baseDir
|
|
45
|
+
* @returns {any[]}
|
|
46
|
+
*/
|
|
47
|
+
function readLines(baseDir, relPath) {
|
|
48
|
+
const result = readFileInside(baseDir, relPath);
|
|
49
|
+
if (!result.ok) return [];
|
|
50
|
+
const rows = [];
|
|
51
|
+
for (const line of result.text.split('\n')) {
|
|
52
|
+
const trimmed = line.trim();
|
|
53
|
+
if (trimmed.length === 0) continue;
|
|
54
|
+
try { rows.push(JSON.parse(trimmed)); } catch { /* malformed line: skip, never crash the read */ }
|
|
55
|
+
}
|
|
56
|
+
return rows;
|
|
57
|
+
}
|
|
58
|
+
|
|
29
59
|
/**
|
|
30
60
|
* Refuse (throw) a row whose cost field is `undefined` (never `?? 0` — the
|
|
31
61
|
* caller must say `null` on purpose for "unknown"), or whose cost field is
|
|
@@ -49,20 +79,186 @@ function checkCostField(row, field, label) {
|
|
|
49
79
|
}
|
|
50
80
|
}
|
|
51
81
|
|
|
82
|
+
/**
|
|
83
|
+
* Refuse (throw) a row whose `at` is not a valid ISO timestamp string
|
|
84
|
+
* (Amendment M4a-2, docs/wiki/the-module-ladder.md "M4a" section: "every
|
|
85
|
+
* new row carries a valid `at`"). Never coerced/defaulted here — the caller
|
|
86
|
+
* (the runner's own injected clock) must supply it, so a test's fixed clock
|
|
87
|
+
* governs `at` exactly like it governs every other timestamp this module
|
|
88
|
+
* writes.
|
|
89
|
+
*/
|
|
90
|
+
function checkAtField(row, label) {
|
|
91
|
+
const value = row.at;
|
|
92
|
+
if (typeof value !== 'string' || Number.isNaN(Date.parse(value))) {
|
|
93
|
+
throw new Error(`${label}: "at" must be a valid ISO timestamp string, got ${JSON.stringify(value)}`);
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* Refuse (throw) a row whose `tokens` is `undefined` (never silently
|
|
99
|
+
* omitted — say `null` on purpose), or whose `tokens` is `null` while
|
|
100
|
+
* `model` is not `null` (Amendment M4a-2: "a model-call audit row written
|
|
101
|
+
* without tokens is refused at write time"), or whose non-null `tokens` is
|
|
102
|
+
* not an object of three non-negative integers
|
|
103
|
+
* (`inputTokens`/`outputTokens`/`cacheReadTokens`). A row with no model
|
|
104
|
+
* call (`model: null`) may carry `tokens: null` — that is the one honest
|
|
105
|
+
* "nothing to sum" case, never a zeroed object standing in for a call that
|
|
106
|
+
* never happened.
|
|
107
|
+
*/
|
|
108
|
+
function checkTokensField(row, label) {
|
|
109
|
+
const value = row.tokens;
|
|
110
|
+
if (value === undefined) {
|
|
111
|
+
throw new Error(`${label}: "tokens" must not be undefined — pass null (no model call) or a {inputTokens,outputTokens,cacheReadTokens} object`);
|
|
112
|
+
}
|
|
113
|
+
if (value === null) {
|
|
114
|
+
if (row.model !== null && row.model !== undefined) {
|
|
115
|
+
throw new Error(`${label}: "tokens" is null but "model" is "${row.model}" — a model-call row must carry its tokens`);
|
|
116
|
+
}
|
|
117
|
+
return;
|
|
118
|
+
}
|
|
119
|
+
if (typeof value !== 'object' || Array.isArray(value)) {
|
|
120
|
+
throw new Error(`${label}: "tokens" must be null or an object, got ${JSON.stringify(value)}`);
|
|
121
|
+
}
|
|
122
|
+
for (const key of ['inputTokens', 'outputTokens', 'cacheReadTokens']) {
|
|
123
|
+
const v = value[key];
|
|
124
|
+
if (typeof v !== 'number' || !Number.isInteger(v) || v < 0) {
|
|
125
|
+
throw new Error(`${label}: "tokens.${key}" must be a non-negative integer, got ${JSON.stringify(v)}`);
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* Refuse (throw) a row whose `tools` is `undefined` (never silently omitted
|
|
132
|
+
* — say `null` on purpose), or whose `tools` is `null` while `model` is not
|
|
133
|
+
* `null` (Amendment M4a-3, docs/wiki/the-module-ladder.md "M4a" section: a
|
|
134
|
+
* model-call row must carry its tool tally — mirrors `checkTokensField`'s
|
|
135
|
+
* discipline exactly), or whose non-null `tools` is not a plain object of
|
|
136
|
+
* non-negative integer counts. A row with no model call (`model: null`) may
|
|
137
|
+
* carry `tools: null` — the one honest "no model call, so no tool call
|
|
138
|
+
* either" case; a model-call row that made zero tool calls carries `tools:
|
|
139
|
+
* {}`, never `null`.
|
|
140
|
+
*/
|
|
141
|
+
function checkToolsField(row, label) {
|
|
142
|
+
const value = row.tools;
|
|
143
|
+
if (value === undefined) {
|
|
144
|
+
throw new Error(`${label}: "tools" must not be undefined — pass null (no model call) or a {toolName: count} object`);
|
|
145
|
+
}
|
|
146
|
+
if (value === null) {
|
|
147
|
+
if (row.model !== null && row.model !== undefined) {
|
|
148
|
+
throw new Error(`${label}: "tools" is null but "model" is "${row.model}" — a model-call row must carry its tool tally`);
|
|
149
|
+
}
|
|
150
|
+
return;
|
|
151
|
+
}
|
|
152
|
+
if (typeof value !== 'object' || Array.isArray(value)) {
|
|
153
|
+
throw new Error(`${label}: "tools" must be null or an object, got ${JSON.stringify(value)}`);
|
|
154
|
+
}
|
|
155
|
+
for (const [name, count] of Object.entries(value)) {
|
|
156
|
+
if (typeof count !== 'number' || !Number.isInteger(count) || count < 0) {
|
|
157
|
+
throw new Error(`${label}: "tools.${name}" must be a non-negative integer, got ${JSON.stringify(count)}`);
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/**
|
|
163
|
+
* Refuse (throw) a row whose `ungranted` key is present but is not an array
|
|
164
|
+
* of strings (Amendment M4a-3: "ungranted absent or an array of strings").
|
|
165
|
+
* `ungranted` itself is optional — a row with nothing ungranted simply omits
|
|
166
|
+
* the key, never carries an empty array as noise (the caller's own choice;
|
|
167
|
+
* this check only refuses a WRONG shape, never requires the key).
|
|
168
|
+
*/
|
|
169
|
+
function checkUngrantedField(row, label) {
|
|
170
|
+
if (!Object.prototype.hasOwnProperty.call(row, 'ungranted')) return;
|
|
171
|
+
const value = row.ungranted;
|
|
172
|
+
if (!Array.isArray(value) || !value.every((v) => typeof v === 'string')) {
|
|
173
|
+
throw new Error(`${label}: "ungranted" must be an array of strings when present, got ${JSON.stringify(value)}`);
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
|
|
52
177
|
/**
|
|
53
178
|
* One row per attempt (also used for one row per ask and one row per send —
|
|
54
179
|
* M2 scope item 9). `row` shape: `{ step, attempt, class, verdict, gap, usd,
|
|
55
|
-
* spendComplete, wallMs, model, modelMatch, strike }
|
|
56
|
-
*
|
|
180
|
+
* spendComplete, wallMs, model, modelMatch, strike, at, tokens }` (`at`/
|
|
181
|
+
* `tokens` added by Amendment M4a-2 — every row appended from here on must
|
|
182
|
+
* carry both; a pre-M4a-2 row already on disk simply lacks them, read back
|
|
183
|
+
* as-is by `readAudit`). Append-only, one writer.
|
|
57
184
|
*
|
|
58
185
|
* @param {string} runDir
|
|
59
186
|
* @param {Record<string, any>} row
|
|
60
187
|
*/
|
|
61
188
|
export function appendAudit(runDir, row) {
|
|
62
189
|
checkCostField(row, 'usd', 'appendAudit');
|
|
190
|
+
checkAtField(row, 'appendAudit');
|
|
191
|
+
checkTokensField(row, 'appendAudit');
|
|
192
|
+
checkToolsField(row, 'appendAudit');
|
|
193
|
+
checkUngrantedField(row, 'appendAudit');
|
|
63
194
|
appendLine(join(runDir, 'audit.jsonl'), row);
|
|
64
195
|
}
|
|
65
196
|
|
|
197
|
+
/**
|
|
198
|
+
* Amendment M4a-2's own reader helper: the honest reading of one audit
|
|
199
|
+
* row's `tokens`, whether or not it was written before M4a-2 landed. A row
|
|
200
|
+
* that never had a `tokens` key at all (any row appended before this
|
|
201
|
+
* amendment) reads as "not recorded", never as `null` standing in for a
|
|
202
|
+
* genuine zero-token model call and never an invented number. A row that
|
|
203
|
+
* does carry the key (including a post-M4a-2 `tokens: null` no-model-call
|
|
204
|
+
* row) reads back exactly what was written.
|
|
205
|
+
*
|
|
206
|
+
* @param {Record<string, any>} row
|
|
207
|
+
* @returns {{tokens: {inputTokens:number, outputTokens:number, cacheReadTokens:number} | null, why?: string}}
|
|
208
|
+
*/
|
|
209
|
+
export function auditRowTokens(row) {
|
|
210
|
+
if (!row || !Object.prototype.hasOwnProperty.call(row, 'tokens')) {
|
|
211
|
+
return { tokens: null, why: 'not recorded (before M4a-2)' };
|
|
212
|
+
}
|
|
213
|
+
return { tokens: row.tokens };
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/**
|
|
217
|
+
* Amendment M4a-3's own reader helper, the same honest-read shape as
|
|
218
|
+
* `auditRowTokens`/`auditRowAt`: a row written before M4a-3 never had a
|
|
219
|
+
* `tools` key at all, and reads as "not recorded", never as an invented
|
|
220
|
+
* empty tally. A row that does carry the key reads back exactly what was
|
|
221
|
+
* written — `tools` (object or `null`) and `ungranted` (defaulted to `[]`
|
|
222
|
+
* when the writer left it out, never `undefined`).
|
|
223
|
+
*
|
|
224
|
+
* @param {Record<string, any>} row
|
|
225
|
+
* @returns {{tools: Record<string, number> | null, ungranted: string[], why?: string}}
|
|
226
|
+
*/
|
|
227
|
+
export function auditRowTools(row) {
|
|
228
|
+
if (!row || !Object.prototype.hasOwnProperty.call(row, 'tools')) {
|
|
229
|
+
return { tools: null, ungranted: [], why: 'not recorded (before M4a-3)' };
|
|
230
|
+
}
|
|
231
|
+
return { tools: row.tools, ungranted: row.ungranted ?? [] };
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
/**
|
|
235
|
+
* Amendment M4a-2's own reader helper for `at`, the same honest-read shape
|
|
236
|
+
* as `auditRowTokens`: a row written before M4a-2 (any row appended before
|
|
237
|
+
* this amendment, or a raw/legacy line on disk) never had an `at` key at
|
|
238
|
+
* all, and reads as "not recorded", never as `undefined` silently rendered
|
|
239
|
+
* blank. A row that does carry the key reads back exactly what was written.
|
|
240
|
+
*
|
|
241
|
+
* @param {Record<string, any>} row
|
|
242
|
+
* @returns {{at: string|null, why?: string}}
|
|
243
|
+
*/
|
|
244
|
+
export function auditRowAt(row) {
|
|
245
|
+
if (!row || !Object.prototype.hasOwnProperty.call(row, 'at')) {
|
|
246
|
+
return { at: null, why: 'not recorded (before M4a-2)' };
|
|
247
|
+
}
|
|
248
|
+
return { at: row.at };
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
/**
|
|
252
|
+
* Read back every row `appendAudit` has written for one run, in file order
|
|
253
|
+
* (append order — never re-sorted). `[]` when the file doesn't exist yet
|
|
254
|
+
* (a run that hasn't made an attempt), never a thrown error.
|
|
255
|
+
* @param {string} runDir
|
|
256
|
+
* @returns {any[]}
|
|
257
|
+
*/
|
|
258
|
+
export function readAudit(runDir) {
|
|
259
|
+
return readLines(runDir, 'audit.jsonl');
|
|
260
|
+
}
|
|
261
|
+
|
|
66
262
|
/**
|
|
67
263
|
* One row per run. `row` shape: `{ runId, at, outcome, spentUsd,
|
|
68
264
|
* spendComplete, capUsd, wallMs, signatureHash }`. Append-only, one writer.
|
|
@@ -74,3 +270,14 @@ export function appendHistory(flowDir, row) {
|
|
|
74
270
|
checkCostField(row, 'spentUsd', 'appendHistory');
|
|
75
271
|
appendLine(join(flowDir, 'history.jsonl'), row);
|
|
76
272
|
}
|
|
273
|
+
|
|
274
|
+
/**
|
|
275
|
+
* Read back every row `appendHistory` has written for one flow, in file
|
|
276
|
+
* order. `[]` when the file doesn't exist yet (a flow with no completed/
|
|
277
|
+
* halted run), never a thrown error.
|
|
278
|
+
* @param {string} flowDir
|
|
279
|
+
* @returns {any[]}
|
|
280
|
+
*/
|
|
281
|
+
export function readHistory(flowDir) {
|
|
282
|
+
return readLines(flowDir, 'history.jsonl');
|
|
283
|
+
}
|