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.
@@ -0,0 +1,268 @@
1
+ // borrowed-from: bareloop src/panel/server.js@a30bbef — ADAPTED for fwdloop.
2
+ // M4a piece 2 (docs/wiki/the-module-ladder.md, "M4a — read-only panel —
3
+ // SIGNED", scope item 1/2): the read-only panel server.
4
+ //
5
+ // What is kept from bareloop, verbatim in spirit: the `node:http` HTTP
6
+ // shell — GET/HEAD only (anything else -> 405), bound to `127.0.0.1` ONLY, a
7
+ // taken port fails LOUDLY (prints the port, exits non-zero, never silently
8
+ // tries another one).
9
+ //
10
+ // What is deleted, per ruling A (2026-09-26) and the M4a fit-check: every
11
+ // import of a bareloop-only module (`runlist`, `replayio`, `replay`,
12
+ // `behaviour`, `ledger`, `job`, `authorflow`) and everything only those fed —
13
+ // per-round `parts[]`, tool-call Audit rows, the judge seam,
14
+ // scoutPlan/fixLoop, memoryCache, the resolved-spec provenance chain. None of
15
+ // these have an fwdloop analog; fwdloop has exactly one flow shape (linear,
16
+ // human-authored, signed steps), one book granularity (one `audit.jsonl` row
17
+ // per step attempt), and exactly one signed `declaration.json` +
18
+ // `signature.json` per flow.
19
+ //
20
+ // All real data derivation now lives in `src/panel/data.js`, which reads
21
+ // fwdloop's own books through the readers `src/` already owns (`readFlow`,
22
+ // `readAudit`, `readHistory`, `readAsk`, `readRunState`, `readLog`,
23
+ // `readSpendRows`, `readAskEvidence`, `loadCatalogue`) — this file is only
24
+ // the HTTP shell + route dispatch, never a second copy of any derivation.
25
+ //
26
+ // READ-ONLY, BY CONSTRUCTION: GET/HEAD only; no endpoint runs a job, spends
27
+ // money, signs, or reads a key/.env. Nothing here imports `src/provider.js`'s
28
+ // key-reading path or touches `process.env` for a secret.
29
+ //
30
+ // PATH SAFETY: a URL may name a flow ONLY (checked with `checkFlowName`) and
31
+ // a runId ONLY (resolved with `resolveRunDir`, both `src/flow.js`) — a URL
32
+ // segment is never joined into a filesystem path directly. The one exception
33
+ // is the fixed, whitelisted `/` route, which always serves this same
34
+ // directory's own `index.html`, never a URL-derived filename.
35
+
36
+ import { createServer } from 'node:http';
37
+ import { readFileSync } from 'node:fs';
38
+ import { dirname, join } from 'node:path';
39
+ import { fileURLToPath } from 'node:url';
40
+
41
+ import { loadCatalogue } from '../catalogue.js';
42
+ import {
43
+ listRuns, getRunDetail, getRunAudit, getRunJob, listStops, getRunAsks,
44
+ } from './data.js';
45
+
46
+ const HERE = dirname(fileURLToPath(import.meta.url));
47
+
48
+ /** Default bind port. Ruling, hamr 2026-09-27: fwdloop's panel default port
49
+ * is 4800 — bareloop owns 4700, and the two panels must be able to run
50
+ * side by side. */
51
+ export const DEFAULT_PORT = 4800;
52
+
53
+ /** @param {any} res @param {number} code @param {any} body */
54
+ function sendJson(res, code, body) {
55
+ const text = JSON.stringify(body);
56
+ res.writeHead(code, { 'content-type': 'application/json; charset=utf-8', 'content-length': Buffer.byteLength(text) });
57
+ res.end(text);
58
+ }
59
+
60
+ /** @param {any} res @param {number} code @param {string} text */
61
+ function sendText(res, code, text) {
62
+ res.writeHead(code, { 'content-type': 'text/plain; charset=utf-8', 'content-length': Buffer.byteLength(text) });
63
+ res.end(text);
64
+ }
65
+
66
+ /**
67
+ * Handle one request against the read-only API + the page. Exported
68
+ * separately from {@link createPanelServer} so tests can drive it without a
69
+ * real listening socket where that is simpler.
70
+ * @param {import('node:http').IncomingMessage} req
71
+ * @param {import('node:http').ServerResponse} res
72
+ * @param {{ root: string, port: number }} opts
73
+ */
74
+ export function handleRequest(req, res, opts) {
75
+ const method = req.method ?? 'GET';
76
+ if (method !== 'GET' && method !== 'HEAD') {
77
+ sendText(res, 405, 'method not allowed — this panel is read-only (GET/HEAD only)');
78
+ return;
79
+ }
80
+
81
+ let url;
82
+ try {
83
+ url = new URL(/** @type {string} */ (req.url), 'http://127.0.0.1');
84
+ } catch {
85
+ sendText(res, 400, 'bad request');
86
+ return;
87
+ }
88
+ const { pathname } = url;
89
+
90
+ const send = (code, body) => {
91
+ if (method === 'HEAD') {
92
+ const text = JSON.stringify(body);
93
+ res.writeHead(code, { 'content-type': 'application/json; charset=utf-8', 'content-length': Buffer.byteLength(text) });
94
+ res.end();
95
+ return;
96
+ }
97
+ sendJson(res, code, body);
98
+ };
99
+
100
+ if (pathname === '/' || pathname === '/index.html') {
101
+ const indexPath = join(HERE, 'index.html');
102
+ let html;
103
+ try {
104
+ html = readFileSync(indexPath, 'utf8');
105
+ } catch {
106
+ sendText(res, 500, 'panel page missing on disk');
107
+ return;
108
+ }
109
+ html = html.replace(/__FWDLOOP_PANEL_PORT__/g, String(opts.port));
110
+ if (method === 'HEAD') {
111
+ res.writeHead(200, { 'content-type': 'text/html; charset=utf-8', 'content-length': Buffer.byteLength(html) });
112
+ res.end();
113
+ return;
114
+ }
115
+ res.writeHead(200, { 'content-type': 'text/html; charset=utf-8', 'content-length': Buffer.byteLength(html) });
116
+ res.end(html);
117
+ return;
118
+ }
119
+
120
+ const loaded = loadCatalogue();
121
+ if (!loaded.ok) {
122
+ sendText(res, 500, `catalogue failed to load: ${loaded.reds.join('; ')}`);
123
+ return;
124
+ }
125
+ const catalogue = loaded.primitives;
126
+
127
+ if (pathname === '/api/runs') {
128
+ send(200, { rows: listRuns({ root: opts.root, catalogue }) });
129
+ return;
130
+ }
131
+
132
+ if (pathname === '/api/inbox') {
133
+ send(200, { rows: listStops({ root: opts.root }) });
134
+ return;
135
+ }
136
+
137
+ // /api/runs/:flow/:runId(/audit|/job|/asks)?
138
+ const runMatch = /^\/api\/runs\/([^/]+)\/([^/]+)(\/(audit|job|asks))?$/.exec(pathname);
139
+ if (runMatch) {
140
+ let flow;
141
+ let runId;
142
+ try {
143
+ flow = decodeURIComponent(runMatch[1]);
144
+ runId = decodeURIComponent(runMatch[2]);
145
+ } catch {
146
+ sendText(res, 400, 'bad request');
147
+ return;
148
+ }
149
+ const sub = runMatch[4] ?? null;
150
+
151
+ if (sub === 'audit') {
152
+ const result = getRunAudit({ root: opts.root, flow, runId });
153
+ if (!result) { sendText(res, 404, 'no such run'); return; }
154
+ send(200, result);
155
+ return;
156
+ }
157
+ if (sub === 'job') {
158
+ const result = getRunJob({
159
+ root: opts.root, flow, runId, catalogue,
160
+ });
161
+ if (!result) { sendText(res, 404, 'no such run'); return; }
162
+ send(200, result);
163
+ return;
164
+ }
165
+ if (sub === 'asks') {
166
+ const result = getRunAsks({
167
+ root: opts.root, flow, runId, catalogue,
168
+ });
169
+ if (!result) { sendText(res, 404, 'no such run'); return; }
170
+ send(200, result);
171
+ return;
172
+ }
173
+ const result = getRunDetail({
174
+ root: opts.root, flow, runId, catalogue,
175
+ });
176
+ if (!result) { sendText(res, 404, 'no such run'); return; }
177
+ send(200, result);
178
+ return;
179
+ }
180
+
181
+ sendText(res, 404, 'not found');
182
+ }
183
+
184
+ /**
185
+ * Start the panel server. Binds `127.0.0.1` ONLY. A taken port is a LOUD,
186
+ * non-zero-exit failure — this never falls back to another port (see file
187
+ * header). Resolves once actually listening; rejects on a bind error
188
+ * (including `EADDRINUSE`) with a `.port` field on the error for the
189
+ * caller's message.
190
+ * @param {{ port?: number, root: string }} opts
191
+ * @returns {Promise<{ server: import('node:http').Server, port: number, close: () => Promise<void> }>}
192
+ */
193
+ export function createPanelServer(opts) {
194
+ if (typeof opts?.root !== 'string' || opts.root.length === 0) {
195
+ return Promise.reject(new Error('createPanelServer: "root" is required (the flows directory to serve)'));
196
+ }
197
+ const requestedPort = opts.port ?? DEFAULT_PORT;
198
+ const { root } = opts;
199
+ return new Promise((resolve, reject) => {
200
+ // Bound port is resolved from the live socket (`server.address().port`)
201
+ // once listening starts, not the requested value — this is what makes
202
+ // `port: 0` (OS-assigned ephemeral port) work for callers such as the
203
+ // test suite, while `--port N` / DEFAULT_PORT callers still get back
204
+ // exactly the port they asked for.
205
+ let boundPort = requestedPort;
206
+ const server = createServer((req, res) => {
207
+ try {
208
+ handleRequest(req, res, { root, port: boundPort });
209
+ } catch (e) {
210
+ sendText(res, 500, `internal error: ${/** @type {Error} */ (e).message}`);
211
+ }
212
+ });
213
+ server.once('error', (e) => {
214
+ const err = /** @type {any} */ (e);
215
+ err.port = requestedPort;
216
+ reject(err);
217
+ });
218
+ server.listen(requestedPort, '127.0.0.1', () => {
219
+ const addr = server.address();
220
+ boundPort = typeof addr === 'object' && addr !== null ? addr.port : requestedPort;
221
+ resolve({
222
+ server,
223
+ port: boundPort,
224
+ close: () => new Promise((res2) => { server.close(() => res2(undefined)); }),
225
+ });
226
+ });
227
+ });
228
+ }
229
+
230
+ /**
231
+ * `fwdloop panel [--port N] [--root <dir>]` — the CLI entry (`bin/fwdloop`
232
+ * dispatch). Never picks a different port on collision (see file header):
233
+ * prints a loud, named error to stderr and returns 1.
234
+ * @param {string[]} argv
235
+ * @param {{ out: (s: string) => void, err: (s: string) => void }} ctx
236
+ * @returns {Promise<number>}
237
+ */
238
+ export async function panelMain(argv, ctx) {
239
+ let port = DEFAULT_PORT;
240
+ let root = '.';
241
+ for (let i = 0; i < argv.length; i += 1) {
242
+ if (argv[i] === '--port') {
243
+ const v = Number(argv[i + 1]);
244
+ if (!Number.isInteger(v) || v <= 0 || v > 65535) { ctx.err(`--port must be a valid TCP port, got ${JSON.stringify(argv[i + 1])}`); return 1; }
245
+ port = v;
246
+ i += 1;
247
+ } else if (argv[i] === '--root') {
248
+ root = argv[i + 1];
249
+ i += 1;
250
+ }
251
+ }
252
+ try {
253
+ const { port: boundPort } = await createPanelServer({ port, root });
254
+ ctx.out(`fwdloop panel — read-only, http://127.0.0.1:${boundPort} (root: ${root}) (Ctrl-C to stop)`);
255
+ // never resolves on its own — the process stays up until killed, same
256
+ // shape any other long-running dev server takes.
257
+ await new Promise(() => {});
258
+ return 0;
259
+ } catch (e) {
260
+ const err = /** @type {any} */ (e);
261
+ if (err && err.code === 'EADDRINUSE') {
262
+ ctx.err(`fwdloop panel: port ${port} is already in use — pass --port to use a different one (never picked automatically)`);
263
+ return 1;
264
+ }
265
+ ctx.err(`fwdloop panel: failed to start — ${err && err.message ? err.message : String(err)}`);
266
+ return 1;
267
+ }
268
+ }
package/src/primitives.js CHANGED
@@ -23,15 +23,24 @@
23
23
  // signed-scope gap for hamr's ruling (job #2's step 3 declares `compress`,
24
24
  // which this piece cannot yet honour).
25
25
 
26
- import { readFileSync } from 'node:fs';
26
+ import { readFileSync, mkdirSync } from 'node:fs';
27
27
  import path from 'node:path';
28
- import { createShellTools } from 'bare-agent/tools';
28
+ import { createShellTools, resolveToolPath } from 'bare-agent/tools';
29
+ import { Gate } from 'bareguard';
29
30
 
30
31
  import { primitiveFor } from './catalogue.js';
31
32
  import { readDocxText } from './docx.js';
32
33
  import { parseCsv } from './csv.js';
33
34
 
34
- const { tools: SHELL_TOOLS } = createShellTools();
35
+ // bare-agent >=0.47.0: `noFollowSymlinks: true` makes shell_read/write/edit/
36
+ // grep throw `err.code === 'ELOOP'` when the path's FINAL component is a
37
+ // symlink (file, dir, or dangling) — verified directly against the
38
+ // installed package (a symlinked file/dir/dangling-link all throw ELOOP; a
39
+ // real file still reads). This closes the "open what the check approved"
40
+ // gap the lexical-only `isPathAllowed` this module used to run could not:
41
+ // a symlink planted inside the run dir after the gate check but before the
42
+ // real open used to be followed silently.
43
+ const { tools: SHELL_TOOLS } = createShellTools({ noFollowSymlinks: true });
35
44
 
36
45
  function shellTool(name) {
37
46
  const found = SHELL_TOOLS.find((t) => t.name === name);
@@ -39,20 +48,44 @@ function shellTool(name) {
39
48
  return found;
40
49
  }
41
50
 
42
- /** True when `candidate` resolves inside one of `allowedRoots` (or IS one of
43
- * them) — lexical containment only, matching `src/runner.js`'s own
44
- * `checkSendDestination` shape (a symlink escape is out of this check's
45
- * scope; the run dir is created fresh by `runFlow`, never attacker-placed). */
46
- function isPathAllowed(candidate, allowedRoots) {
47
- const resolved = path.resolve(candidate);
48
- return allowedRoots.some((root) => {
49
- const r = path.resolve(root);
50
- return resolved === r || resolved.startsWith(r + path.sep);
51
- });
51
+ /**
52
+ * Resolve a model-given path string against `runDir` and pass it through the
53
+ * step's bareguard `Gate`. A `~`-prefixed or already-absolute path is handed
54
+ * to `resolveToolPath` as-is (it expands `~`/normalizes); anything else is
55
+ * joined onto `runDir` first, THEN resolved — so a relative path always
56
+ * lands inside the run dir before the gate ever sees it, matching
57
+ * bareguard's own "agent paths must be absolute" rule (`fs.invalidPath`
58
+ * otherwise). The SAME resolved string that was checked is what the caller
59
+ * must hand to the real tool's `execute` — never re-derive a second string
60
+ * after the decision (F48's own re-check rule: check and open the same
61
+ * value). Throws naming the verb, the path, and bareguard's own rule name
62
+ * on a deny; returns the resolved path on allow.
63
+ */
64
+ /** Typed carrier for a bareguard fs-gate deny: `model-step` catches it by
65
+ * `instanceof` and records `{verb, path, rule}` on the attempt's audit row —
66
+ * never parsed back out of the message string. */
67
+ export class GateRefusal extends Error {
68
+ constructor(verb, resolved, rule) {
69
+ super(`${verb}: "${resolved}" is outside the sandbox — refused (bareguard rule: ${rule})`);
70
+ this.name = 'GateRefusal';
71
+ this.verb = verb;
72
+ this.path = resolved;
73
+ this.rule = rule;
74
+ }
52
75
  }
53
76
 
54
- function sandboxError(verb, candidatePath) {
55
- return new Error(`${verb}: "${candidatePath}" is outside the sandbox (the run dir and its frozen inputs) — refused`);
77
+ async function resolveAndGate(gate, verb, tool, runDir, rawPath) {
78
+ if (typeof rawPath !== 'string' || rawPath.length === 0) {
79
+ throw new Error(`${verb}: path must be a non-empty string`);
80
+ }
81
+ const joined = (rawPath.startsWith('~') || path.isAbsolute(rawPath)) ? rawPath : path.join(runDir, rawPath);
82
+ const resolved = resolveToolPath(joined);
83
+ const type = verb === 'write' ? 'write' : 'read';
84
+ const decision = await gate.check({ type, tool, path: resolved });
85
+ if (decision.outcome !== 'allow') {
86
+ throw new GateRefusal(verb, resolved, decision.rule);
87
+ }
88
+ return resolved;
56
89
  }
57
90
 
58
91
  /** Which primitive owns a frozen input's text, by extension of its frozen path —
@@ -71,7 +104,7 @@ export function rolePrimitiveFor(frozenPath) {
71
104
  * the run's frozen inputs — the same `inputsByRole` map `readDocx`/
72
105
  * `addressCells` use. `role` resolves to the frozen path and THEN goes
73
106
  * through the same sandbox check as any path (the frozen path is always
74
- * inside `allowedRoots`, so this can never widen what a path-only call
107
+ * inside the gate's `readScope`, so this can never widen what a path-only call
75
108
  * could already reach) — never a shortcut around the sandbox, just a name
76
109
  * for a path the model was never handed directly. `role` wins when both
77
110
  * `path` and `role` are given. */
@@ -95,15 +128,21 @@ function roleParameters(real, roles) {
95
128
  }
96
129
 
97
130
  /** Resolves `args.role`/`args.path` down to the one path to actually use,
98
- * honouring "role wins if both given" and the sandbox check. Throws (never
99
- * silently falls through) when neither is usable. `roles` is the TEXT-only
100
- * role list (for the "no frozen input" message); the role lookup itself
101
- * goes through the full `inputsByRole` map so a non-text role (e.g. a
102
- * .docx) is refused BY NAME naming the primitive that owns it, even if the
103
- * model passes a role the schema's enum never offered it (F41 item 3). */
104
- function resolveRoleOrPath(verb, args, inputsByRole, roles, allowedRoots) {
131
+ * honouring "role wins if both given", then runs it through the SAME
132
+ * `resolveAndGate` every path-only call goes through (F41's own role
133
+ * contract: a role is a name for a path the model was never handed
134
+ * directly, never a shortcut around the sandbox check — a frozen input's
135
+ * directory is always in the gate's `readScope`, so this can never widen
136
+ * what a path-only call could already reach). Throws (never silently falls
137
+ * through) when neither is usable. `roles` is the TEXT-only role list (for
138
+ * the "no frozen input" message); the role lookup itself goes through the
139
+ * full `inputsByRole` map so a non-text role (e.g. a .docx) is refused BY
140
+ * NAME naming the primitive that owns it, even if the model passes a role
141
+ * the schema's enum never offered it (F41 item 3). */
142
+ async function resolveRoleOrPath(gate, verb, tool, runDir, args, inputsByRole, roles) {
105
143
  if (args && Object.prototype.hasOwnProperty.call(args, 'role') && args.role !== undefined) {
106
- const frozen = inputsByRole[args.role];
144
+ // Own-key lookup: "__proto__"/"constructor" must not resolve to Object.prototype members.
145
+ const frozen = Object.hasOwn(inputsByRole, args.role) ? inputsByRole[args.role] : undefined;
107
146
  if (!frozen) throw new Error(`${verb}: no frozen input for role "${args.role}" (available: ${roles.join(', ')})`);
108
147
  const owner = rolePrimitiveFor(frozen);
109
148
  if (owner === 'readDocx') throw new Error(`${verb}: role "${args.role}" is a .docx — use readDocx`);
@@ -112,13 +151,12 @@ function resolveRoleOrPath(verb, args, inputsByRole, roles, allowedRoots) {
112
151
  const ext = path.extname(frozen) || '(no extension)';
113
152
  throw new Error(`${verb}: role "${args.role}" is a ${ext} — no text primitive serves it`);
114
153
  }
115
- return frozen;
154
+ return resolveAndGate(gate, verb, tool, runDir, frozen);
116
155
  }
117
- if (!isPathAllowed(args?.path, allowedRoots)) throw sandboxError(verb, args?.path);
118
- return args.path;
156
+ return resolveAndGate(gate, verb, tool, runDir, args?.path);
119
157
  }
120
158
 
121
- function sandboxedReadTool(allowedRoots, inputsByRole) {
159
+ function sandboxedReadTool(gate, runDir, inputsByRole) {
122
160
  const real = shellTool('shell_read');
123
161
  const textRoles = Object.keys(inputsByRole).filter((r) => rolePrimitiveFor(inputsByRole[r]) === 'read');
124
162
  return {
@@ -126,13 +164,13 @@ function sandboxedReadTool(allowedRoots, inputsByRole) {
126
164
  description: roleDescription(real, textRoles),
127
165
  parameters: roleParameters(real, textRoles),
128
166
  execute: async (args) => {
129
- const path = resolveRoleOrPath('read', args, inputsByRole, textRoles, allowedRoots);
130
- return real.execute({ ...args, path });
167
+ const resolvedPath = await resolveRoleOrPath(gate, 'read', 'read', runDir, args, inputsByRole, textRoles);
168
+ return real.execute({ ...args, path: resolvedPath });
131
169
  },
132
170
  };
133
171
  }
134
172
 
135
- function sandboxedGrepTool(allowedRoots, inputsByRole) {
173
+ function sandboxedGrepTool(gate, runDir, inputsByRole) {
136
174
  const real = shellTool('shell_grep');
137
175
  const textRoles = Object.keys(inputsByRole).filter((r) => rolePrimitiveFor(inputsByRole[r]) === 'read');
138
176
  return {
@@ -140,21 +178,38 @@ function sandboxedGrepTool(allowedRoots, inputsByRole) {
140
178
  description: roleDescription(real, textRoles),
141
179
  parameters: roleParameters(real, textRoles),
142
180
  execute: async (args) => {
143
- const path = resolveRoleOrPath('grep', args, inputsByRole, textRoles, allowedRoots);
144
- return real.execute({ ...args, path });
181
+ const resolvedPath = await resolveRoleOrPath(gate, 'grep', 'grep', runDir, args, inputsByRole, textRoles);
182
+ return real.execute({ ...args, path: resolvedPath });
145
183
  },
146
184
  };
147
185
  }
148
186
 
149
- function sandboxedWriteTool(allowedRoots) {
187
+ function sandboxedWriteTool(gate, runDir, outDir) {
150
188
  const real = shellTool('shell_write');
151
189
  return {
152
190
  name: 'write',
153
- description: real.description,
191
+ description: `${real.description} Sandboxed: only reaches <runDir>/out — the run dir root, its `
192
+ + 'frozen inputs, state.json, audit.jsonl, spend.jsonl and any other run record are never '
193
+ + 'writable, even though some are readable.',
154
194
  parameters: real.parameters,
155
195
  execute: async (args) => {
156
- if (!isPathAllowed(args?.path, allowedRoots)) throw sandboxError('write', args?.path);
157
- return real.execute(args);
196
+ const resolvedPath = await resolveAndGate(gate, 'write', 'write', runDir, args?.path);
197
+ // Created lazily, on the FIRST actual write (never at tool-resolve
198
+ // time) — `bin/fwdloop` calls `resolvePrimitives` to build a step's
199
+ // tools BEFORE `runFlow` creates the run dir at all (a predicted-path
200
+ // call, deliberately touching nothing on disk yet, per its own
201
+ // comment: "runFlow... owns the ONLY mkdirSync/freezeInputs for this
202
+ // run dir, so a refusal leaves nothing behind"). Creating `out/` any
203
+ // earlier than this would leave a run dir behind even when `runFlow`
204
+ // itself goes on to refuse the run (e.g. F46's unwired-verb
205
+ // preflight) — silently breaking that contract. `resolveAndGate`
206
+ // above already ran the gate check against a not-yet-existing root
207
+ // (bareguard resolves a missing root by walking up to its nearest
208
+ // existing ancestor — see fs.js — so the check needs no directory to
209
+ // exist first); `shell_write` itself also creates parent directories
210
+ // as needed, so this is belt-and-suspenders, not load-bearing.
211
+ mkdirSync(outDir, { recursive: true });
212
+ return real.execute({ ...args, path: resolvedPath });
158
213
  },
159
214
  };
160
215
  }
@@ -198,6 +253,14 @@ function addressCellsPrimitiveTool(inputsByRole) {
198
253
  };
199
254
  }
200
255
 
256
+ /** The verbs this piece actually implements (the switch below, as data) —
257
+ * one writer for "is this verb wired": `resolvePrimitives`'s own reds use
258
+ * it, and `src/runner.js`'s preflight (F46: a step granted a
259
+ * catalogue-present-but-unwired verb, e.g. litectx's `compress`, must
260
+ * refuse before any model call or spend) imports this SAME set rather than
261
+ * keeping a second copy of the list. */
262
+ export const WIRED_VERBS = new Set(['read', 'grep', 'write', 'readDocx', 'addressCells']);
263
+
201
264
  /**
202
265
  * Resolve the granted tools for one step's model call. Never throws —
203
266
  * a verb absent from the catalogue, or present but unimplemented here, is
@@ -211,8 +274,28 @@ function addressCellsPrimitiveTool(inputsByRole) {
211
274
  */
212
275
  export function resolvePrimitives(catalogue, grantedVerbs, ctx) {
213
276
  const { runDir, inputs = [] } = ctx;
214
- const allowedRoots = [runDir, ...inputs.map((entry) => path.dirname(entry.frozen))];
215
277
  const inputsByRole = Object.fromEntries(inputs.map((entry) => [entry.id, entry.frozen]));
278
+ const outDir = path.join(runDir, 'out');
279
+
280
+ // One bareguard Gate per step: read reaches the run dir and every frozen
281
+ // input's own directory (deduped — several inputs can share a dir); write
282
+ // reaches ONLY `<runDir>/out`, never the run dir root (state.json,
283
+ // audit.jsonl, spend.jsonl, answer*.json, ask.json, inputs/ all live at
284
+ // the run dir root — readable, never writable). No tools/rwx/budget block:
285
+ // this gate exists to answer fs questions only, nothing else a step here
286
+ // can do goes through it.
287
+ const readScope = [...new Set([runDir, ...inputs.map((entry) => path.dirname(entry.frozen))])];
288
+ // bareguard >=0.19.2 THROWS at construct when any scope entry is or sits
289
+ // under a symlink (the scope roots are bareguard's to police, not ours).
290
+ // Fail closed: no tool at all for this step — not even readDocx/
291
+ // addressCells, which read the run dir's frozen inputs outside the gate —
292
+ // and a red naming bareguard's own message, so the caller refuses the run.
293
+ let gate;
294
+ try {
295
+ gate = new Gate({ fs: { readScope, writeScope: [outDir] } });
296
+ } catch (err) {
297
+ return { tools: {}, reds: [`primitives: bareguard refused the step's file scope — ${err.message}`] };
298
+ }
216
299
 
217
300
  const tools = {};
218
301
  const reds = [];
@@ -224,15 +307,27 @@ export function resolvePrimitives(catalogue, grantedVerbs, ctx) {
224
307
  // eslint-disable-next-line no-continue
225
308
  continue;
226
309
  }
310
+ if (!WIRED_VERBS.has(verb)) {
311
+ reds.push(`primitives: verb "${verb}" is in the catalogue but has no M2 implementation yet`);
312
+ // eslint-disable-next-line no-continue
313
+ continue;
314
+ }
227
315
  switch (verb) {
228
316
  case 'read':
229
- tools.read = sandboxedReadTool(allowedRoots, inputsByRole);
317
+ tools.read = sandboxedReadTool(gate, runDir, inputsByRole);
230
318
  break;
231
319
  case 'grep':
232
- tools.grep = sandboxedGrepTool(allowedRoots, inputsByRole);
320
+ tools.grep = sandboxedGrepTool(gate, runDir, inputsByRole);
233
321
  break;
234
322
  case 'write':
235
- tools.write = sandboxedWriteTool(allowedRoots);
323
+ // `out/` itself is created lazily, inside the tool's own `execute`
324
+ // on the first actual write — never here. `resolvePrimitives` can
325
+ // be called against a PREDICTED runDir before it exists at all
326
+ // (`bin/fwdloop`'s own "run" command does exactly this, deliberately
327
+ // touching nothing on disk before `runFlow` itself creates the run
328
+ // dir) — creating `out/` eagerly here would leave a run dir behind
329
+ // even for a run `runFlow` goes on to refuse.
330
+ tools.write = sandboxedWriteTool(gate, runDir, outDir);
236
331
  break;
237
332
  case 'readDocx':
238
333
  tools.readDocx = readDocxPrimitiveTool(inputsByRole);