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/src/send.js CHANGED
@@ -32,8 +32,27 @@ export async function sendViaPrimitive(target, filename, content) {
32
32
  const destination = checkSendDestination(target);
33
33
  if (!destination.ok) return { ok: false, red: destination.red };
34
34
 
35
+ // F48 round 4 (redesign) defense in depth: `src/runner.js`'s send slot
36
+ // now halts BEFORE calling this function on a missing/refused read, so
37
+ // `content` should never arrive `undefined` here — but this function must
38
+ // never again paper over that with `?? null` the way it used to (that is
39
+ // exactly what turned a swapped/deleted accepted artifact into a
40
+ // recorded-green 4-byte `null` shipped to the signed destination). A
41
+ // legitimate on-disk artifact is always a non-null object: every step's
42
+ // model output is validated to carry a boolean `done` before it is ever
43
+ // written (src/runner.js's checkDoneBlocker), and `done`/`blocker` are
44
+ // stripped afterward (stripDoneBlocker) — the stripped artifact that
45
+ // actually reaches disk (and this function) is always the remaining
46
+ // object, never `null` and never a bare non-object value.
47
+ if (content === undefined) {
48
+ return { ok: false, red: 'send: no content to send (artifact missing or its read was refused) — refused' };
49
+ }
50
+ if (content === null || typeof content !== 'object' || Array.isArray(content)) {
51
+ return { ok: false, red: `send: content is not an artifact object (got ${JSON.stringify(content)}) — refused` };
52
+ }
53
+
35
54
  const path = join(destination.dir, filename);
36
- const serialised = JSON.stringify(content ?? null, null, 2);
55
+ const serialised = JSON.stringify(content, null, 2);
37
56
  await WRITE_TOOL.execute({ path, content: serialised });
38
57
 
39
58
  const bytes = readFileSync(path);
package/src/types.js CHANGED
@@ -263,6 +263,11 @@
263
263
 
264
264
  /**
265
265
  * One row appended to `runs/<run-id>/audit.jsonl` (M2 scope item 9).
266
+ * `at`/`tokens` were added by Amendment M4a-2 and `tools`/`ungranted` by
267
+ * Amendment M4a-3 (docs/wiki/the-module-ladder.md, "M4a" section) — every
268
+ * row `appendAudit` writes from here on carries `at`/`tokens`/`tools`; a row
269
+ * written before its amendment simply lacks the newer keys (read back as-is,
270
+ * never backfilled) — see `auditRowTokens`/`auditRowTools` in `src/books.js`.
266
271
  * @typedef {object} AuditRow
267
272
  * @property {string|null} step
268
273
  * @property {number} attempt
@@ -275,6 +280,19 @@
275
280
  * @property {string|null} model
276
281
  * @property {boolean|null} modelMatch
277
282
  * @property {boolean} strike
283
+ * @property {string} at - ISO time this attempt finished.
284
+ * @property {{inputTokens:number, outputTokens:number, cacheReadTokens:number} | null} tokens -
285
+ * summed over this attempt's model calls; `null` only when `model` is
286
+ * `null` (no model call this row).
287
+ * @property {Record<string, number> | null} tools - a {toolName: count}
288
+ * tally of every GRANTED tool the model actually invoked this attempt,
289
+ * summed across every round; `{}` when the model called no tool; `null`
290
+ * only when `model` is `null` (no model call this row).
291
+ * @property {string[]} [ungranted] - tool names the model called that this
292
+ * step never granted; absent when empty, never an invented empty array.
293
+ * @property {Array<{verb:string, path:string, rule:string}>} [refused] - bareguard
294
+ * fs-gate refusals during this attempt; `[]` (never omitted) on every row
295
+ * written by a model attempt, absent on rows with no model call.
278
296
  */
279
297
 
280
298
  /**
package/types/ask.d.ts CHANGED
@@ -16,6 +16,24 @@ export function makeFileAskStep({ timeoutMs, pollMs, clock, writeLine, }?: {
16
16
  decision: string;
17
17
  reason?: string;
18
18
  }>;
19
+ /**
20
+ * @param {any} ask the parsed ask.json object (or its `evidence` field's
21
+ * container — pass the whole ask so a missing `evidence` key is itself a
22
+ * handled case, not the caller's problem).
23
+ * @returns {{ draft: {step?: string, text: string} | null, unjudged: Array<{step: string, emits?: string, text: string}>, why?: string }}
24
+ */
25
+ export function readAskEvidence(ask: any): {
26
+ draft: {
27
+ step?: string;
28
+ text: string;
29
+ } | null;
30
+ unjudged: Array<{
31
+ step: string;
32
+ emits?: string;
33
+ text: string;
34
+ }>;
35
+ why?: string;
36
+ };
19
37
  /**
20
38
  * @param {{ runDir: string, askId: string, decision: 'accept'|'reject'|'rerun', reason?: string, clock?: () => string }} opts
21
39
  * @returns {{ ok: true } | { ok: false, red: string }}
@@ -32,3 +50,62 @@ export function answerAsk({ runDir, askId, decision, reason, clock, }: {
32
50
  ok: false;
33
51
  red: string;
34
52
  };
53
+ /**
54
+ * Writes `asks/<askId>.json` in `runDir`, creating the `asks/` directory if
55
+ * needed. Called by `src/runner.js` right after it writes `ask.json` for a
56
+ * fresh park (same `askId`/`question`/`askedAt`/`expiresAt`/`evidence` — the
57
+ * archive is a permanent copy of the SAME content, not a second source of
58
+ * truth). Exclusive-create: a second call for an already-archived `askId`
59
+ * is refused (a red naming the file) rather than silently overwriting it —
60
+ * proven by the write itself failing (`EEXIST`), not by a separate
61
+ * existence check that a concurrent writer could race past.
62
+ *
63
+ * Crash-order note: this is called AFTER `ask.json` is written, so a crash
64
+ * between the two writes leaves `ask.json` present and `asks/<askId>.json`
65
+ * missing — the run is still correctly parked and resumable (ask.json/
66
+ * state.json govern resume, unchanged), just without its archive entry for
67
+ * that one askId. `listArchivedAsks` below tolerates this (it only reports
68
+ * what is actually on disk); it is never treated as "before M4a-1" (that
69
+ * `why` is reserved for a run with NO `asks/` directory at all).
70
+ *
71
+ * @param {{ runDir: string, askId: string, question: string, askedAt: string, expiresAt: string, evidence: unknown }} opts
72
+ * @returns {{ ok: true } | { ok: false, red: string }}
73
+ */
74
+ export function writeAskArchive({ runDir, askId, question, askedAt, expiresAt, evidence, }: {
75
+ runDir: string;
76
+ askId: string;
77
+ question: string;
78
+ askedAt: string;
79
+ expiresAt: string;
80
+ evidence: unknown;
81
+ }): {
82
+ ok: true;
83
+ } | {
84
+ ok: false;
85
+ red: string;
86
+ };
87
+ /**
88
+ * @param {string} runDir
89
+ * @returns {{ archived: true, asks: Array<{ askId: string, question?: string, askedAt?: string, expiresAt?: string,
90
+ * evidence: ReturnType<typeof readAskEvidence>,
91
+ * answer: { status: string, reason?: string, answeredAt?: string, why?: string } }> } | { archived: false, why: string }}
92
+ */
93
+ export function listArchivedAsks(runDir: string): {
94
+ archived: true;
95
+ asks: Array<{
96
+ askId: string;
97
+ question?: string;
98
+ askedAt?: string;
99
+ expiresAt?: string;
100
+ evidence: ReturnType<typeof readAskEvidence>;
101
+ answer: {
102
+ status: string;
103
+ reason?: string;
104
+ answeredAt?: string;
105
+ why?: string;
106
+ };
107
+ }>;
108
+ } | {
109
+ archived: false;
110
+ why: string;
111
+ };
package/types/books.d.ts CHANGED
@@ -1,13 +1,73 @@
1
1
  /**
2
2
  * One row per attempt (also used for one row per ask and one row per send —
3
3
  * M2 scope item 9). `row` shape: `{ step, attempt, class, verdict, gap, usd,
4
- * spendComplete, wallMs, model, modelMatch, strike }`. Append-only, one
5
- * writer.
4
+ * spendComplete, wallMs, model, modelMatch, strike, at, tokens }` (`at`/
5
+ * `tokens` added by Amendment M4a-2 — every row appended from here on must
6
+ * carry both; a pre-M4a-2 row already on disk simply lacks them, read back
7
+ * as-is by `readAudit`). Append-only, one writer.
6
8
  *
7
9
  * @param {string} runDir
8
10
  * @param {Record<string, any>} row
9
11
  */
10
12
  export function appendAudit(runDir: string, row: Record<string, any>): void;
13
+ /**
14
+ * Amendment M4a-2's own reader helper: the honest reading of one audit
15
+ * row's `tokens`, whether or not it was written before M4a-2 landed. A row
16
+ * that never had a `tokens` key at all (any row appended before this
17
+ * amendment) reads as "not recorded", never as `null` standing in for a
18
+ * genuine zero-token model call and never an invented number. A row that
19
+ * does carry the key (including a post-M4a-2 `tokens: null` no-model-call
20
+ * row) reads back exactly what was written.
21
+ *
22
+ * @param {Record<string, any>} row
23
+ * @returns {{tokens: {inputTokens:number, outputTokens:number, cacheReadTokens:number} | null, why?: string}}
24
+ */
25
+ export function auditRowTokens(row: Record<string, any>): {
26
+ tokens: {
27
+ inputTokens: number;
28
+ outputTokens: number;
29
+ cacheReadTokens: number;
30
+ } | null;
31
+ why?: string;
32
+ };
33
+ /**
34
+ * Amendment M4a-3's own reader helper, the same honest-read shape as
35
+ * `auditRowTokens`/`auditRowAt`: a row written before M4a-3 never had a
36
+ * `tools` key at all, and reads as "not recorded", never as an invented
37
+ * empty tally. A row that does carry the key reads back exactly what was
38
+ * written — `tools` (object or `null`) and `ungranted` (defaulted to `[]`
39
+ * when the writer left it out, never `undefined`).
40
+ *
41
+ * @param {Record<string, any>} row
42
+ * @returns {{tools: Record<string, number> | null, ungranted: string[], why?: string}}
43
+ */
44
+ export function auditRowTools(row: Record<string, any>): {
45
+ tools: Record<string, number> | null;
46
+ ungranted: string[];
47
+ why?: string;
48
+ };
49
+ /**
50
+ * Amendment M4a-2's own reader helper for `at`, the same honest-read shape
51
+ * as `auditRowTokens`: a row written before M4a-2 (any row appended before
52
+ * this amendment, or a raw/legacy line on disk) never had an `at` key at
53
+ * all, and reads as "not recorded", never as `undefined` silently rendered
54
+ * blank. A row that does carry the key reads back exactly what was written.
55
+ *
56
+ * @param {Record<string, any>} row
57
+ * @returns {{at: string|null, why?: string}}
58
+ */
59
+ export function auditRowAt(row: Record<string, any>): {
60
+ at: string | null;
61
+ why?: string;
62
+ };
63
+ /**
64
+ * Read back every row `appendAudit` has written for one run, in file order
65
+ * (append order — never re-sorted). `[]` when the file doesn't exist yet
66
+ * (a run that hasn't made an attempt), never a thrown error.
67
+ * @param {string} runDir
68
+ * @returns {any[]}
69
+ */
70
+ export function readAudit(runDir: string): any[];
11
71
  /**
12
72
  * One row per run. `row` shape: `{ runId, at, outcome, spentUsd,
13
73
  * spendComplete, capUsd, wallMs, signatureHash }`. Append-only, one writer.
@@ -16,3 +76,11 @@ export function appendAudit(runDir: string, row: Record<string, any>): void;
16
76
  * @param {Record<string, any>} row
17
77
  */
18
78
  export function appendHistory(flowDir: string, row: Record<string, any>): void;
79
+ /**
80
+ * Read back every row `appendHistory` has written for one flow, in file
81
+ * order. `[]` when the file doesn't exist yet (a flow with no completed/
82
+ * halted run), never a thrown error.
83
+ * @param {string} flowDir
84
+ * @returns {any[]}
85
+ */
86
+ export function readHistory(flowDir: string): any[];
package/types/flow.d.ts CHANGED
@@ -10,6 +10,141 @@
10
10
  * @returns {CheckFlowNameResult}
11
11
  */
12
12
  export function checkFlowName(name: unknown): CheckFlowNameResult;
13
+ /**
14
+ * Check a runId against the allowed shape: 1..128 characters, letters
15
+ * (upper or lower), digits, `.`, `_`, `-`, starting with a letter or digit.
16
+ * Walked character by character — never a regex — same reasoning as
17
+ * `checkFlowName`: a runId that would escape the flow's runs directory
18
+ * (`..`, a `/` or `\` segment, a NUL byte, an absolute path) is refused by
19
+ * the same loop that refuses a bad character, not a separate ad-hoc check.
20
+ *
21
+ * One writer: every caller that turns an externally-supplied runId into a
22
+ * path (`bin/fwdloop`'s `run`/`resume`, `runFlow`, `resumeRun`) goes through
23
+ * this function (via `resolveRunDir`, below) — a runId is never trusted
24
+ * enough to be joined onto a path any other way. Fixes the path escape a
25
+ * branch review found: `--run-id ../../../../tmp/pwned`.
26
+ *
27
+ * @param {unknown} runId
28
+ * @returns {{ok:true}|{ok:false,red:string}}
29
+ */
30
+ export function checkRunId(runId: unknown): {
31
+ ok: true;
32
+ } | {
33
+ ok: false;
34
+ red: string;
35
+ };
36
+ /**
37
+ * Turn a checked runId into its run directory under `flowDir/runs/`, then
38
+ * confirm the built path actually resolves INSIDE that runs directory —
39
+ * belt and braces alongside `checkRunId`'s character allow-list (mirrors
40
+ * `src/runner.js`'s own `checkSendDestination` shape: lexical containment,
41
+ * checked after the path is built, never trusted from the allow-list
42
+ * alone).
43
+ *
44
+ * Lexical containment (`path.resolve` plus a prefix compare) only catches a
45
+ * bad runId string — it does not catch a runId that *passes* the allow-list
46
+ * but names a symlink pointing outside `flowDir/runs/` (F36 fixed `runs/`
47
+ * itself being a symlink; this is the same class one level down, for an
48
+ * entry inside it). So once the lexical check passes, anything that
49
+ * actually EXISTS on disk is re-checked with `realpathSync`: `runs/` itself
50
+ * must realpath inside `flowDir` (mirrors F36's `readFlow` check), and — if
51
+ * the run dir exists — it must realpath inside the real `runs/` dir. A
52
+ * not-yet-existing run dir (a new run being created) has nothing to
53
+ * realpath yet, so only the lexical result is returned for it; the check
54
+ * holds at use time (here, on every call), not only at some earlier
55
+ * preflight.
56
+ *
57
+ * @param {string} flowDir
58
+ * @param {unknown} runId
59
+ * @returns {{ok:true, runDir:string}|{ok:false, red:string}}
60
+ */
61
+ export function resolveRunDir(flowDir: string, runId: unknown): {
62
+ ok: true;
63
+ runDir: string;
64
+ } | {
65
+ ok: false;
66
+ red: string;
67
+ };
68
+ /**
69
+ * Every flow name that has a real, readable directory under `root` — M4a
70
+ * piece 2 (docs/wiki/the-module-ladder.md M4a scope item 2: "every flow
71
+ * under --root"). A directory entry that fails `checkFlowName` (should not
72
+ * happen for anything `writeFlow` itself created, but a hand-placed or
73
+ * legacy directory is possible) is skipped rather than crashing the whole
74
+ * listing — this is a best-effort enumeration, not a validator; a caller
75
+ * that wants to know a flow is well-formed calls `readFlow` on it.
76
+ * `[]` when `root` doesn't exist or has no entries — never a thrown error.
77
+ * Sorted so a caller gets a stable, deterministic order.
78
+ * @param {string} root
79
+ * @returns {string[]}
80
+ */
81
+ export function listFlowNames(root: string): string[];
82
+ /**
83
+ * Every runId with a real, readable directory under a flow's own `runs/`
84
+ * (M4a scope item 2: "every run"). Same best-effort posture as {@link
85
+ * listFlowNames} — a malformed entry is skipped, never thrown on.
86
+ * @param {string} flowDir
87
+ * @returns {string[]}
88
+ */
89
+ export function listRunIds(flowDir: string): string[];
90
+ /**
91
+ * F48 round 3 (docs/logs/FINDINGS.md): the ONE mechanism every book reader
92
+ * in src/ and bin/ routes through to read a file that lives inside a run
93
+ * dir or flow dir — closing the symlink-escape class at the source instead
94
+ * of patching each reader a second time. `resolveInside(baseDir, relPath)`
95
+ * requires the target to both (a) not itself be a symlink and (b) realpath
96
+ * to somewhere inside `realpath(baseDir)` — the second check alone also
97
+ * catches a symlinked ANCESTOR directory partway down `relPath` (e.g.
98
+ * `asks/` itself replaced by a symlink to an outside directory), the same
99
+ * shape `readFlow`'s own `runs/` check and `resolveRunDir` already apply one
100
+ * level up. A path that does not exist yet is reported as `missing: true`
101
+ * (never a red) so every existing caller keeps its own "not written yet"
102
+ * behaviour unchanged.
103
+ *
104
+ * @param {string} baseDir
105
+ * @param {string} relPath
106
+ * @returns {{ok:true, full:string}|{ok:false, missing:true}|{ok:false, missing:false, red:string}}
107
+ */
108
+ export function resolveInside(baseDir: string, relPath: string): {
109
+ ok: true;
110
+ full: string;
111
+ } | {
112
+ ok: false;
113
+ missing: true;
114
+ } | {
115
+ ok: false;
116
+ missing: false;
117
+ red: string;
118
+ };
119
+ /**
120
+ * `resolveInside` plus the actual read — every raw-text book reader's one
121
+ * gateway. Same result shape as `resolveInside`, plus `{ok:true, text}`.
122
+ * @param {string} baseDir
123
+ * @param {string} relPath
124
+ * @returns {{ok:true, text:string}|{ok:false, missing:true}|{ok:false, missing:false, red:string}}
125
+ */
126
+ export function readFileInside(baseDir: string, relPath: string): {
127
+ ok: true;
128
+ text: string;
129
+ } | {
130
+ ok: false;
131
+ missing: true;
132
+ } | {
133
+ ok: false;
134
+ missing: false;
135
+ red: string;
136
+ };
137
+ /**
138
+ * `readdirSync` guarded the same way: refuses (returns `[]`) when `relDir`
139
+ * itself is a symlink or resolves outside `baseDir`, and skips (never
140
+ * follows) any individual entry that is itself a symlink — a directory
141
+ * listing must never hand a caller a name that, joined back onto `relDir`,
142
+ * would escape `baseDir`. `[]` when `relDir` doesn't exist.
143
+ * @param {string} baseDir
144
+ * @param {string} relDir
145
+ * @returns {string[]}
146
+ */
147
+ export function readdirInside(baseDir: string, relDir: string): string[];
13
148
  /**
14
149
  * Write a signed flow to `<root>/<name>/`. Refuses (writing nothing) if the
15
150
  * flow name is invalid, if `proseText`/`declaration` don't parse/validate,
package/types/index.d.ts CHANGED
@@ -1,8 +1,10 @@
1
1
  export { closeByClass } from "./closers.js";
2
+ export { readSpendRows } from "./provider.js";
2
3
  export { parseSignedText, ARBITER_FIELDS } from "./signed-text.js";
3
4
  export { signFlow, verifyFlow, canonicalBytes, SIGNATURE_FIELDS } from "./signature.js";
4
5
  export { validateDeclaration, DECLARATION_FIELDS } from "./declaration.js";
5
6
  export { parseCatalogue, loadCatalogue, menu, primitiveFor, resolveEntry, CATALOGUE_FIELDS } from "./catalogue.js";
6
- export { checkFlowName, writeFlow, readFlow, FLOW_FILES } from "./flow.js";
7
- export { runFlow, resumeRun, makeParkingAskStep, STRIKE_LIMIT, MAX_ATTEMPTS } from "./runner.js";
8
- export { makeFileAskStep, answerAsk } from "./ask.js";
7
+ export { checkFlowName, checkRunId, resolveRunDir, writeFlow, readFlow, listFlowNames, listRunIds, FLOW_FILES } from "./flow.js";
8
+ export { runFlow, resumeRun, makeParkingAskStep, STRIKE_LIMIT, MAX_ATTEMPTS, readAsk, readRunState, readLog } from "./runner.js";
9
+ export { makeFileAskStep, answerAsk, readAskEvidence, writeAskArchive, listArchivedAsks } from "./ask.js";
10
+ export { appendAudit, appendHistory, readAudit, readHistory, auditRowTokens, auditRowTools } from "./books.js";