fwdloop 0.5.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 +559 -0
- package/package.json +7 -3
- package/src/ask.js +360 -7
- package/src/books.js +209 -2
- package/src/declaration.js +12 -1
- package/src/flow.js +247 -2
- package/src/index.js +9 -2
- package/src/model-step.js +153 -14
- 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 +1231 -137
- package/src/send.js +20 -1
- package/src/types.js +18 -0
- package/types/ask.d.ts +95 -1
- package/types/books.d.ts +70 -2
- package/types/flow.d.ts +135 -0
- package/types/index.d.ts +5 -2
- 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 +135 -26
- package/types/types.d.ts +41 -0
package/src/ask.js
CHANGED
|
@@ -20,8 +20,10 @@ import {
|
|
|
20
20
|
existsSync, mkdirSync, readFileSync, renameSync, writeFileSync,
|
|
21
21
|
} from 'node:fs';
|
|
22
22
|
import { join } from 'node:path';
|
|
23
|
+
import { randomUUID } from 'node:crypto';
|
|
23
24
|
|
|
24
25
|
import { appendAudit } from './books.js';
|
|
26
|
+
import { readFileInside, resolveInside, readdirInside } from './flow.js';
|
|
25
27
|
|
|
26
28
|
function sleep(ms) {
|
|
27
29
|
return new Promise((resolve) => { setTimeout(resolve, ms); });
|
|
@@ -33,7 +35,7 @@ function safeStamp(iso) {
|
|
|
33
35
|
|
|
34
36
|
/**
|
|
35
37
|
* @param {{ timeoutMs?: number, pollMs?: number, clock?: () => string, writeLine?: (line:string) => void }} [opts]
|
|
36
|
-
* @returns {(opts:{question:string, evidence:unknown, runDir:string}) => Promise<{decision:string, reason?:string}>}
|
|
38
|
+
* @returns {(opts:{question:string, evidence:unknown, runDir:string, ttlMs?: number}) => Promise<{decision:string, reason?:string}>}
|
|
37
39
|
*/
|
|
38
40
|
export function makeFileAskStep({
|
|
39
41
|
timeoutMs = 120_000,
|
|
@@ -43,25 +45,42 @@ export function makeFileAskStep({
|
|
|
43
45
|
} = {}) {
|
|
44
46
|
let attemptCounter = 0;
|
|
45
47
|
|
|
46
|
-
return async function fileAskStep({
|
|
48
|
+
return async function fileAskStep({
|
|
49
|
+
question, evidence, runDir, ttlMs,
|
|
50
|
+
}) {
|
|
47
51
|
attemptCounter += 1;
|
|
48
52
|
const attempt = attemptCounter;
|
|
49
53
|
|
|
54
|
+
// M3 scope item 1 (fixes F43): a signed `ttlMs` threaded in by the
|
|
55
|
+
// runner always governs — this constructor's own `timeoutMs` is only
|
|
56
|
+
// ever the fallback for a DIRECT call that carries no signed ttl (e.g.
|
|
57
|
+
// this module's own unit tests). No code default overrides a signed
|
|
58
|
+
// value.
|
|
59
|
+
const effectiveTimeoutMs = typeof ttlMs === 'number' ? ttlMs : timeoutMs;
|
|
60
|
+
|
|
50
61
|
mkdirSync(runDir, { recursive: true });
|
|
51
62
|
const askPath = join(runDir, 'ask.json');
|
|
52
63
|
const answerPath = join(runDir, 'answer.json');
|
|
53
64
|
const askedAt = clock();
|
|
65
|
+
const askId = randomUUID();
|
|
66
|
+
const expiresAt = new Date(Date.parse(askedAt) + effectiveTimeoutMs).toISOString();
|
|
54
67
|
|
|
55
68
|
writeFileSync(askPath, JSON.stringify({
|
|
56
|
-
question, evidence, askedAt, attempt,
|
|
69
|
+
askId, question, evidence, askedAt, expiresAt, attempt,
|
|
57
70
|
}, null, 2));
|
|
58
|
-
writeLine(`ASK OPEN (expires in ${Math.round(
|
|
71
|
+
writeLine(`ASK OPEN (expires in ${Math.round(effectiveTimeoutMs / 1000)}s): ${question} — answer by writing ${answerPath}`);
|
|
59
72
|
|
|
60
|
-
const deadline = Date.now() +
|
|
73
|
+
const deadline = Date.now() + effectiveTimeoutMs;
|
|
61
74
|
let staleCount = 0;
|
|
62
75
|
|
|
63
76
|
for (;;) {
|
|
64
|
-
|
|
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) {
|
|
65
84
|
let raw = null;
|
|
66
85
|
try { raw = readFileSync(answerPath, 'utf8'); } catch { raw = null; }
|
|
67
86
|
let parsed = null;
|
|
@@ -76,7 +95,7 @@ export function makeFileAskStep({
|
|
|
76
95
|
while (existsSync(staleName)) { staleCount += 1; staleName = join(runDir, `answer.stale.${staleCount}.json`); }
|
|
77
96
|
renameSync(answerPath, staleName);
|
|
78
97
|
appendAudit(runDir, {
|
|
79
|
-
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,
|
|
80
99
|
});
|
|
81
100
|
// Keep polling — a stale file quarantined does not mean THIS
|
|
82
101
|
// ask has been answered.
|
|
@@ -95,3 +114,337 @@ export function makeFileAskStep({
|
|
|
95
114
|
}
|
|
96
115
|
};
|
|
97
116
|
}
|
|
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
|
+
|
|
198
|
+
// ---------------------------------------------------------------------------
|
|
199
|
+
// M3 piece 1 (docs/wiki/the-module-ladder.md, "M3 — scope, exit, negative —
|
|
200
|
+
// SIGNED", scope item 3, the function only — the CLI is piece 2): a separate
|
|
201
|
+
// process's half of the park protocol. Writes `answer.json` exactly once,
|
|
202
|
+
// refusing (never throwing) a blank reason on reject/rerun, an unknown
|
|
203
|
+
// askId, an expired askId, or a second answer to an already-answered ask —
|
|
204
|
+
// each by name, so an answer for ask A can never be consumed by ask B.
|
|
205
|
+
// ---------------------------------------------------------------------------
|
|
206
|
+
|
|
207
|
+
/**
|
|
208
|
+
* @param {{ runDir: string, askId: string, decision: 'accept'|'reject'|'rerun', reason?: string, clock?: () => string }} opts
|
|
209
|
+
* @returns {{ ok: true } | { ok: false, red: string }}
|
|
210
|
+
*/
|
|
211
|
+
export function answerAsk({
|
|
212
|
+
runDir, askId, decision, reason, clock,
|
|
213
|
+
}) {
|
|
214
|
+
const now = typeof clock === 'function' ? clock : () => new Date().toISOString();
|
|
215
|
+
|
|
216
|
+
if (typeof runDir !== 'string' || runDir.length === 0) {
|
|
217
|
+
return { ok: false, red: 'answerAsk: "runDir" must be a non-empty string' };
|
|
218
|
+
}
|
|
219
|
+
if (typeof askId !== 'string' || askId.length === 0) {
|
|
220
|
+
return { ok: false, red: 'answerAsk: "askId" must be a non-empty string' };
|
|
221
|
+
}
|
|
222
|
+
if (decision !== 'accept' && decision !== 'reject' && decision !== 'rerun') {
|
|
223
|
+
return { ok: false, red: `answerAsk: unrecognised decision "${decision}"` };
|
|
224
|
+
}
|
|
225
|
+
|
|
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}` };
|
|
235
|
+
}
|
|
236
|
+
let ask;
|
|
237
|
+
try {
|
|
238
|
+
ask = JSON.parse(askRead.text);
|
|
239
|
+
} catch (err) {
|
|
240
|
+
return { ok: false, red: `answerAsk: ask.json for run ${runDir} is not valid JSON — ${err.message}` };
|
|
241
|
+
}
|
|
242
|
+
if (ask.askId !== askId) {
|
|
243
|
+
return { ok: false, red: `answerAsk: askId "${askId}" is unknown for run ${runDir}` };
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
const nowIso = now();
|
|
247
|
+
// A present-but-unparseable expiresAt (Date.parse -> NaN) must never read
|
|
248
|
+
// as "not expired" — `NaN > x`/`x > NaN` are both false, so the comparison
|
|
249
|
+
// below would silently treat garbage as "still open forever". Refuse by
|
|
250
|
+
// name instead, naming the askId and the bad value.
|
|
251
|
+
if (Number.isNaN(Date.parse(ask.expiresAt))) {
|
|
252
|
+
return { ok: false, red: `answerAsk: askId "${askId}" has an unparseable expiresAt "${ask.expiresAt}" for run ${runDir} — refusing rather than treating it as not-expired` };
|
|
253
|
+
}
|
|
254
|
+
if (Date.parse(nowIso) > Date.parse(ask.expiresAt)) {
|
|
255
|
+
return { ok: false, red: `answerAsk: askId "${askId}" expired at ${ask.expiresAt} for run ${runDir}` };
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
const answerPath = join(runDir, 'answer.json');
|
|
259
|
+
// A consumed marker survives long after the run has moved on (or ended) —
|
|
260
|
+
// it must still refuse a second answer naming the SAME askId, never only
|
|
261
|
+
// while answer.json happens to still be sitting there.
|
|
262
|
+
if (existsSync(join(runDir, `answer.${askId}.consumed.json`))) {
|
|
263
|
+
return { ok: false, red: `answerAsk: askId "${askId}" already answered for run ${runDir}` };
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
const trimmedReason = typeof reason === 'string' ? reason.trim() : '';
|
|
267
|
+
if ((decision === 'reject' || decision === 'rerun') && trimmedReason.length === 0) {
|
|
268
|
+
return { ok: false, red: `answerAsk: askId "${askId}" needs a non-blank reason to ${decision}` };
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
const payload = { askId, decision, answeredAt: nowIso };
|
|
272
|
+
if (trimmedReason.length > 0) payload.reason = trimmedReason;
|
|
273
|
+
// Orchestrator review fix (5): a plain `existsSync` check followed by a
|
|
274
|
+
// separate `writeFileSync` is a check-then-act race — two concurrent
|
|
275
|
+
// answers can both pass the check before either writes, and the second
|
|
276
|
+
// silently overwrites the first. `{ flag: 'wx' }` makes the write itself
|
|
277
|
+
// the exclusive gate (fails EEXIST if the file already exists), so there
|
|
278
|
+
// is no window between "is it answered" and "answer it" for a second
|
|
279
|
+
// caller to land in.
|
|
280
|
+
try {
|
|
281
|
+
writeFileSync(answerPath, JSON.stringify(payload, null, 2), { flag: 'wx' });
|
|
282
|
+
} catch (err) {
|
|
283
|
+
if (err.code === 'EEXIST') {
|
|
284
|
+
return { ok: false, red: `answerAsk: askId "${askId}" already answered for run ${runDir}` };
|
|
285
|
+
}
|
|
286
|
+
return { ok: false, red: `answerAsk: could not write ${answerPath} — ${err.message}` };
|
|
287
|
+
}
|
|
288
|
+
return { ok: true };
|
|
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
|
+
}
|
package/src/declaration.js
CHANGED
|
@@ -623,7 +623,18 @@ export function validateDeclaration(declaration, context = {}) {
|
|
|
623
623
|
reds.push(`declaration: send at line ${n} (steps[${sendIdx}]) is not granted a catalogue primitive of class "write"`);
|
|
624
624
|
}
|
|
625
625
|
|
|
626
|
-
|
|
626
|
+
// M3 scope item 8 (F42's "Also seen" note): "earlier" is judged by STEP
|
|
627
|
+
// ORDER, never by prose line number — the runner folds over
|
|
628
|
+
// `declaration.steps` in array order (`acceptedAskEmitsThisRun` is
|
|
629
|
+
// populated as steps execute), so a line-number comparison here can
|
|
630
|
+
// disagree with what actually runs. A signed ask whose step sits before
|
|
631
|
+
// the send step in `declaration.steps`, whatever its own prose line
|
|
632
|
+
// number, is "earlier"; one whose step sits at or after the send step
|
|
633
|
+
// never is, even if its line number is smaller.
|
|
634
|
+
const earlierAskLines = askLines.filter((a) => {
|
|
635
|
+
const askIdx = stepInfo.findIndex((st) => st.fromLine === a);
|
|
636
|
+
return askIdx !== -1 && askIdx < sendIdx;
|
|
637
|
+
});
|
|
627
638
|
if (earlierAskLines.length === 0) {
|
|
628
639
|
reds.push(`declaration: send at line ${n} (steps[${sendIdx}]) has no signed ask at an earlier line to read from`);
|
|
629
640
|
} else {
|