pi-braid 0.44.5 → 0.45.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,394 @@
1
+ /**
2
+ * The execution core of the `run` tool: one program and its argv, no shell.
3
+ *
4
+ * What this module refuses is what a shell would have interpreted:
5
+ * - the five operators that make a command string a program (`|`, `&&`, `;`,
6
+ * a backtick, `$(`);
7
+ * - a shell invoked with a command string (`sh -c ...`), which is the same
8
+ * thing in a different spelling;
9
+ * - a glob at a path-segment boundary (`*.md`, `src/*`), because the caller
10
+ * passed an expression where a program expects a path.
11
+ * A `*` inside an argument (a sed quantifier, a grep `--include` filter) is
12
+ * not a boundary and is left to the program, which is where such a pattern
13
+ * belongs.
14
+ *
15
+ * What it does not do is as load-bearing: no TTY, no shell profile, no glob
16
+ * expansion, no environment invention. The child gets the caller's environment,
17
+ * a stdin that ends (or the text the caller supplied), and stdout/stderr to
18
+ * files so the bytes are exact and the memory is bounded. Both streams are
19
+ * returned separately; each is capped, and the dropped bytes and the file that
20
+ * holds the rest are named rather than dropped silently.
21
+ */
22
+ import { spawn } from "node:child_process";
23
+ import { closeSync, mkdtempSync, openSync, readSync, rmSync, statSync } from "node:fs";
24
+ import { tmpdir } from "node:os";
25
+ import { basename, join, resolve } from "node:path";
26
+ import { DEFAULT_MAX_BYTES } from "@earendil-works/pi-coding-agent";
27
+ import { findWorkspaceEscape } from "../../../lib/tools/workspace-guard.js";
28
+ /** setTimeout's own ceiling: a longer timeout cannot be armed. */
29
+ export const MAX_TIMEOUT_MS = 2_147_483_647;
30
+ /** The smallest cap worth reporting a window for. */
31
+ export const MIN_OUTPUT_BYTES = 1_024;
32
+ /** A cap past the harness's own structured-output budget buys nothing. */
33
+ export const MAX_OUTPUT_BYTES = 1_048_576;
34
+ /** Per stream, when the call names no cap: the harness's truncation default. */
35
+ export const DEFAULT_OUTPUT_BYTES = DEFAULT_MAX_BYTES;
36
+ /**
37
+ * Verbs whose operand is destroyed or rewritten. The set is this tool's policy,
38
+ * not the guard's: `git` will bring its own.
39
+ */
40
+ export const DESTRUCTIVE_VERBS = new Set([
41
+ "rm",
42
+ "mv",
43
+ "dd",
44
+ "chmod",
45
+ "shred",
46
+ "truncate",
47
+ ]);
48
+ /** Programs that take a command string: `-c` makes one of them a shell again. */
49
+ const SHELL_PROGRAMS = new Set(["sh", "bash", "zsh", "dash", "ksh", "fish"]);
50
+ /** Shell operators that only mean something inside a shell. */
51
+ const SHELL_OPERATORS = ["&&", "$(", "|", ";", "`"];
52
+ /** Longest argument quoted back in a refusal, so the message stays readable. */
53
+ const MAX_QUOTED_ARGUMENT = 160;
54
+ /** How far past a byte budget a read looks for a line boundary. */
55
+ const LINE_WINDOW_SLACK = 8 * 1024;
56
+ /** Share of the cap kept from the head; the tail keeps the rest. */
57
+ const HEAD_SHARE = 0.6;
58
+ function quote(text) {
59
+ return text.length > MAX_QUOTED_ARGUMENT ? `${text.slice(0, MAX_QUOTED_ARGUMENT)}...` : text;
60
+ }
61
+ /**
62
+ * A `*` at a path-segment boundary: the whole element, a leading `*.ext`, a
63
+ * trailing directory wildcard, or a wildcard between two segments. A star
64
+ * inside a word or a pattern is the program's business.
65
+ */
66
+ export function isGlobExpression(element) {
67
+ if (!element.includes("*"))
68
+ return false;
69
+ return element.startsWith("*") || element.endsWith("*") || element.includes("/*");
70
+ }
71
+ /** The first element carrying a shell operator, or null. */
72
+ function findShellOperator(argv) {
73
+ for (let index = 0; index < argv.length; index++) {
74
+ const element = argv[index];
75
+ for (const operator of SHELL_OPERATORS) {
76
+ if (element.includes(operator))
77
+ return { index, operator };
78
+ }
79
+ }
80
+ return null;
81
+ }
82
+ /** Whether a shell program is being handed a command string. */
83
+ function isShellCommandString(argv) {
84
+ if (!SHELL_PROGRAMS.has(basename(argv[0] ?? "")))
85
+ return false;
86
+ return argv.slice(1).some((element) => {
87
+ if (element === "--command")
88
+ return true;
89
+ // A short-flag cluster: -c, -ec, -lc. A long flag (--login) is not one.
90
+ return /^-[A-Za-z]*c[A-Za-z]*$/.test(element);
91
+ });
92
+ }
93
+ /**
94
+ * Everything wrong with a call that can be known before a process starts: the
95
+ * argv shape, shell operators, a shell command string, a glob, the timeout, the
96
+ * cap, and a destructive verb reaching outside the workspace.
97
+ *
98
+ * Pure. The cwd is already resolved and its existence checked by the caller;
99
+ * the workspace boundary is passed in.
100
+ */
101
+ export function findRefusal(request, context) {
102
+ const { argv } = request;
103
+ if (!Array.isArray(argv) || argv.length === 0) {
104
+ return {
105
+ kind: "argv",
106
+ message: "refused: argv is required and must be non-empty. Pass the program as argv[0] and one element per argument.",
107
+ };
108
+ }
109
+ if (argv.some((element) => typeof element !== "string" || element === "")) {
110
+ return {
111
+ kind: "argv",
112
+ message: "refused: every argv element must be a non-empty string. An empty element cannot be passed to a program.",
113
+ };
114
+ }
115
+ const operator = findShellOperator(argv);
116
+ if (operator) {
117
+ return {
118
+ kind: "metacharacter",
119
+ message: `refused: argv[${operator.index}] carries "${operator.operator}". ` +
120
+ "run executes argv directly and never through a shell, so the operator would be a literal argument. " +
121
+ `Argument: ${quote(argv[operator.index])}`,
122
+ };
123
+ }
124
+ if (isShellCommandString(argv)) {
125
+ return {
126
+ kind: "shell-string",
127
+ message: "refused: argv[0] is a shell and argv carries -c, so this is a command string rather than a program call. " +
128
+ "run does not hand commands to a shell. Use bash, or pass the program and its arguments directly.",
129
+ };
130
+ }
131
+ const glob = argv.slice(1).find(isGlobExpression);
132
+ if (glob !== undefined) {
133
+ return {
134
+ kind: "glob",
135
+ message: `refused: "${quote(glob)}" is a glob, and run does not expand globs. ` +
136
+ "Pass the paths the glob would have matched, or use find or grep, which take patterns themselves.",
137
+ };
138
+ }
139
+ const timeout = request.timeout_ms;
140
+ if (typeof timeout !== "number" || !Number.isFinite(timeout)) {
141
+ return {
142
+ kind: "timeout",
143
+ message: "refused: timeout_ms is required and must be a finite number of milliseconds. " +
144
+ "A call with no timeout can hang the session.",
145
+ };
146
+ }
147
+ if (!Number.isInteger(timeout) || timeout < 1 || timeout > MAX_TIMEOUT_MS) {
148
+ return {
149
+ kind: "timeout",
150
+ message: `refused: timeout_ms must be an integer from 1 to ${MAX_TIMEOUT_MS}; got ${timeout}. ` +
151
+ "A call with no timeout can hang the session.",
152
+ };
153
+ }
154
+ if (request.max_output_bytes !== undefined) {
155
+ const cap = request.max_output_bytes;
156
+ if (!Number.isInteger(cap) || cap < MIN_OUTPUT_BYTES || cap > MAX_OUTPUT_BYTES) {
157
+ return {
158
+ kind: "output-cap",
159
+ message: `refused: max_output_bytes must be an integer from ${MIN_OUTPUT_BYTES} to ${MAX_OUTPUT_BYTES}; got ${String(cap)}.`,
160
+ };
161
+ }
162
+ }
163
+ const escape = findWorkspaceEscape({
164
+ verbs: DESTRUCTIVE_VERBS,
165
+ argv,
166
+ cwd: context.cwd,
167
+ workspaceRoot: context.workspaceRoot,
168
+ });
169
+ if (escape) {
170
+ return {
171
+ kind: "destructive-escape",
172
+ message: `refused: "${escape.verb}" names "${escape.path}", which resolves to ${escape.resolved}, ` +
173
+ `outside the workspace ${escape.root}. A destructive verb is refused when a path argument leaves the workspace; use bash if that is intended.`,
174
+ };
175
+ }
176
+ return null;
177
+ }
178
+ function statSize(file) {
179
+ try {
180
+ return statSync(file).size;
181
+ }
182
+ catch {
183
+ // The capture file is created by this call and read after the child exits;
184
+ // a vanished file reads as empty output rather than failing the result.
185
+ return 0;
186
+ }
187
+ }
188
+ /** Read into `buffer` from `fd`, closing the descriptor whatever happens. */
189
+ function readFrom(fd, buffer, length, position) {
190
+ try {
191
+ return readSync(fd, buffer, 0, length, position);
192
+ }
193
+ finally {
194
+ closeSync(fd);
195
+ }
196
+ }
197
+ /** Read the first `budget` bytes of a file, cut at a line boundary. */
198
+ function readHead(file, budget) {
199
+ const window = Math.min(Math.max(budget, 1) + LINE_WINDOW_SLACK, Math.max(statSize(file), 1));
200
+ const buffer = Buffer.allocUnsafe(window);
201
+ const read = readFrom(openSync(file, "r"), buffer, window, 0);
202
+ const slice = buffer.subarray(0, read);
203
+ const newline = slice.lastIndexOf(0x0a);
204
+ const end = newline >= 0 && newline <= budget ? newline + 1 : Math.min(budget, read);
205
+ return stripSplitCharacter(slice.subarray(0, end).toString("utf8"), "end");
206
+ }
207
+ /** Read the last `budget` bytes of a file, cut at a line boundary. */
208
+ function readTail(file, budget) {
209
+ const size = statSize(file);
210
+ const start = Math.max(0, size - budget - LINE_WINDOW_SLACK);
211
+ const length = size - start;
212
+ const buffer = Buffer.allocUnsafe(length);
213
+ const read = readFrom(openSync(file, "r"), buffer, length, start);
214
+ const slice = buffer.subarray(0, read);
215
+ const newline = slice.indexOf(0x0a);
216
+ const offset = newline >= 0 && newline < slice.length ? newline + 1 : 0;
217
+ const kept = slice.subarray(offset);
218
+ const fromEnd = kept.subarray(Math.max(0, kept.length - budget));
219
+ return stripSplitCharacter(fromEnd.toString("utf8"), "start");
220
+ }
221
+ /**
222
+ * A byte window can cut a multi-byte character in half; a lone replacement
223
+ * character at that edge is the cut, not the program's output.
224
+ */
225
+ function stripSplitCharacter(text, edge) {
226
+ return edge === "end" ? text.replace(/\uFFFD$/, "") : text.replace(/^\uFFFD/, "");
227
+ }
228
+ /** Apply the byte cap to one captured stream, keeping a head and a tail. */
229
+ export function boundStream(file, cap, fullTextPath) {
230
+ const bytes = statSize(file);
231
+ if (bytes <= cap) {
232
+ const buffer = Buffer.allocUnsafe(bytes);
233
+ const read = bytes === 0 ? 0 : readFrom(openSync(file, "r"), buffer, bytes, 0);
234
+ return {
235
+ text: buffer.subarray(0, read).toString("utf8"),
236
+ bytes,
237
+ shownBytes: read,
238
+ droppedBytes: 0,
239
+ truncated: false,
240
+ };
241
+ }
242
+ const headBudget = Math.floor(cap * HEAD_SHARE);
243
+ const tailBudget = cap - headBudget;
244
+ const head = readHead(file, headBudget);
245
+ const tail = readTail(file, tailBudget);
246
+ const kept = Buffer.byteLength(head) + Buffer.byteLength(tail);
247
+ const droppedBytes = Math.max(0, bytes - kept);
248
+ const marker = `\n[... ${droppedBytes} bytes omitted ...]\n`;
249
+ return {
250
+ text: `${head}${marker}${tail}`,
251
+ bytes,
252
+ shownBytes: kept,
253
+ droppedBytes,
254
+ truncated: true,
255
+ ...(fullTextPath ? { fullTextPath } : {}),
256
+ };
257
+ }
258
+ /** Kill the child's process group, falling back to the child alone. */
259
+ function killTree(child) {
260
+ const pid = child.pid;
261
+ if (pid === undefined)
262
+ return;
263
+ if (process.platform !== "win32") {
264
+ try {
265
+ process.kill(-pid, "SIGKILL");
266
+ return;
267
+ }
268
+ catch {
269
+ // The group is already gone, or the child never led one; fall through to
270
+ // the direct kill so a single process is still terminated.
271
+ }
272
+ }
273
+ try {
274
+ child.kill("SIGKILL");
275
+ }
276
+ catch {
277
+ // The child exited between the timeout firing and this call; the exit
278
+ // event already carries the result, so there is nothing left to stop.
279
+ }
280
+ }
281
+ /**
282
+ * Run one program. The caller has already refused the shapes that never reach a
283
+ * program (see `findRefusal`) and resolved `context.cwd`.
284
+ *
285
+ * The child is spawned detached on POSIX so the timeout and an aborted tool call
286
+ * kill the whole tree, not only the leader; stdout and stderr are files rather
287
+ * than pipes, so a grandchild cannot hold the result open after the program
288
+ * exits, and the capture is byte-exact without buffering the stream in memory.
289
+ */
290
+ export async function executeArgv(request, context, signal) {
291
+ const cwd = resolve(context.cwd);
292
+ const dir = mkdtempSync(join(tmpdir(), "pi-run-"));
293
+ const stdoutPath = join(dir, "stdout");
294
+ const stderrPath = join(dir, "stderr");
295
+ let child;
296
+ const startedAt = performance.now();
297
+ let stdoutFd;
298
+ let stderrFd;
299
+ try {
300
+ stdoutFd = openSync(stdoutPath, "w");
301
+ stderrFd = openSync(stderrPath, "w");
302
+ child = spawn(request.argv[0], request.argv.slice(1), {
303
+ cwd,
304
+ env: { ...process.env, ...(request.env ?? {}) },
305
+ // shell: false is the default; it is written out because "no shell" is
306
+ // this tool's contract, not an inherited default a refactor could flip.
307
+ shell: false,
308
+ detached: process.platform !== "win32",
309
+ windowsHide: true,
310
+ stdio: [request.stdin === undefined ? "ignore" : "pipe", stdoutFd, stderrFd],
311
+ });
312
+ }
313
+ catch (error) {
314
+ rmSync(dir, { recursive: true, force: true });
315
+ throw error;
316
+ }
317
+ finally {
318
+ if (stdoutFd !== undefined)
319
+ closeSync(stdoutFd);
320
+ if (stderrFd !== undefined)
321
+ closeSync(stderrFd);
322
+ }
323
+ let timedOut = false;
324
+ let aborted = false;
325
+ let spawnError;
326
+ const exit = new Promise((settle) => {
327
+ let done = false;
328
+ const finish = (code, killed) => {
329
+ if (done)
330
+ return;
331
+ done = true;
332
+ settle({ code, signal: killed });
333
+ };
334
+ child.once("exit", (code, killed) => finish(code, killed));
335
+ child.once("error", (error) => {
336
+ spawnError = `${error.code ?? "spawn"}: ${error.message}`;
337
+ finish(null, null);
338
+ });
339
+ });
340
+ const onAbort = () => {
341
+ aborted = true;
342
+ killTree(child);
343
+ };
344
+ if (signal) {
345
+ if (signal.aborted)
346
+ onAbort();
347
+ else
348
+ signal.addEventListener("abort", onAbort, { once: true });
349
+ }
350
+ if (child.stdin) {
351
+ child.stdin.on("error", () => {
352
+ // A program may exit before reading its stdin; the write failure is then
353
+ // the program's answer, reported through its exit code, not a tool error.
354
+ });
355
+ child.stdin.end(request.stdin ?? "");
356
+ }
357
+ const timer = setTimeout(() => {
358
+ timedOut = true;
359
+ killTree(child);
360
+ }, request.timeout_ms);
361
+ // The timer and the abort listener belong to the wait, not to the call: they
362
+ // are released when the wait settles, whichever way it settles.
363
+ const result = await exit.finally(() => {
364
+ clearTimeout(timer);
365
+ if (signal)
366
+ signal.removeEventListener("abort", onAbort);
367
+ });
368
+ return {
369
+ exitCode: result.code,
370
+ signal: result.signal,
371
+ timedOut,
372
+ aborted,
373
+ durationMs: Math.round(performance.now() - startedAt),
374
+ cwd,
375
+ argv: request.argv,
376
+ ...(spawnError === undefined ? {} : { spawnError }),
377
+ stdoutPath,
378
+ stderrPath,
379
+ stdoutBytes: spawnError === undefined ? statSize(stdoutPath) : 0,
380
+ stderrBytes: statSize(stderrPath),
381
+ captureDir: dir,
382
+ };
383
+ }
384
+ /** Remove the capture directory after the caller has offloaded what it needs. */
385
+ export function discardCapture(capture) {
386
+ if (capture.captureDir) {
387
+ rmSync(capture.captureDir, { recursive: true, force: true });
388
+ }
389
+ }
390
+ /** The capture file for one stream, while the capture directory still exists. */
391
+ export function capturePathFor(capture, stream) {
392
+ return stream === "stdout" ? capture.stdoutPath : capture.stderrPath;
393
+ }
394
+ //# sourceMappingURL=run.js.map
@@ -13,6 +13,7 @@ import orchestratorFn from "./orchestrator/index.js";
13
13
  // context-management (tool profile switching)
14
14
  import contextManagementFn from "./context-management/index.js";
15
15
  import coreAgentEnvFn from "./core/agent-environment/index.js";
16
+ import coreRunToolFn from "./core/run-tool/index.js";
16
17
  import corePromptBuilderFn from "./core/prompt-builder/index.js";
17
18
  // cognitive (reasoning tools + detectors: think, verify, topic-drift, MARS reflection, ...)
18
19
  import metacognitionFn from "./cognitive/metacognition/index.js";
@@ -76,6 +77,11 @@ export const MANIFEST = [
76
77
  alwaysOn: true,
77
78
  desc: "time_status, L1 context injection",
78
79
  },
80
+ {
81
+ id: "run-tool",
82
+ fn: coreRunToolFn,
83
+ desc: "run tool - one program and its argv, without a shell",
84
+ },
79
85
  {
80
86
  id: "workspace-snapshot",
81
87
  fn: workspaceSnapshotFn,
@@ -29,6 +29,7 @@ export const TOOL_FAMILIES = {
29
29
  web_search: "web-fetch",
30
30
  get_search_content: "web-fetch",
31
31
  bash: "terminal",
32
+ run: "terminal",
32
33
  herdr_pane: "terminal",
33
34
  herdr_layout: "terminal",
34
35
  read: "files",
@@ -0,0 +1,70 @@
1
+ /**
2
+ * Workspace escape guard for destructive argv.
3
+ *
4
+ * A tool that takes an argv list lets a caller name a path, and a verb that
5
+ * removes or overwrites what it names turns a path typo into data loss. This
6
+ * module answers one question for such a tool: does this argv carry a path
7
+ * argument that resolves outside the workspace root?
8
+ *
9
+ * It is a mechanism, not a policy:
10
+ * - the destructive verb set is the caller's, passed in;
11
+ * - the workspace root and the invocation cwd are the caller's;
12
+ * - nothing here executes, refuses, rewrites or reports. The caller decides
13
+ * what to do with an escape, and its own message names the outcome.
14
+ *
15
+ * Resolution is canonical on both sides. The root and the target's nearest
16
+ * existing ancestor go through realpath, so a symlink that lives inside the
17
+ * workspace and points outside it is caught, while a target that does not exist
18
+ * yet is compared by the canonical path of its parent. A target equal to the
19
+ * root is an escape: removing or rewriting the workspace itself is outside the
20
+ * set of things a single path argument may name.
21
+ */
22
+ /** One path argument that resolves outside the workspace. */
23
+ export interface WorkspaceEscape {
24
+ /** The program (argv[0]) whose verb the caller marked destructive. */
25
+ verb: string;
26
+ /** The argument as the caller wrote it. */
27
+ argument: string;
28
+ /** The path value read out of the argument (`of=` is read as its right side). */
29
+ path: string;
30
+ /** That path, canonical and absolute. */
31
+ resolved: string;
32
+ /** The workspace root, canonical and absolute. */
33
+ root: string;
34
+ }
35
+ /** A candidate path value and the argument it was read from. */
36
+ interface Candidate {
37
+ argument: string;
38
+ path: string;
39
+ }
40
+ /**
41
+ * Path values carried by an argv, read conservatively: every element after the
42
+ * program that is not a flag, plus the right side of any `key=value` element
43
+ * (`dd of=/etc/passwd`). A flag's own value (`-o /etc/x`) is not followed by the
44
+ * scanner, which is why the caller keeps destructive verbs to the set whose
45
+ * operands are positional or `key=value`; the guard never guesses at a program's
46
+ * option grammar.
47
+ */
48
+ export declare function pathCandidates(argv: readonly string[]): Candidate[];
49
+ /** Canonical absolute path for a target, whether or not it exists yet. */
50
+ export declare function canonicalPath(target: string): string;
51
+ /** Whether `target` is strictly below `root` after both are canonicalized. */
52
+ export declare function isBelow(root: string, target: string): boolean;
53
+ /**
54
+ * The first path argument, in argv order, that resolves outside the workspace.
55
+ * Null when the program's verb is not in `verbs`, when no path argument escapes,
56
+ * or when the argv carries no path argument at all.
57
+ *
58
+ * `cwd` is the directory the argv runs in, so relative operands are read the
59
+ * way the program will read them. `workspaceRoot` is the boundary, which need
60
+ * not be `cwd`: a call may run in a subdirectory and still be bounded by the
61
+ * session's working directory.
62
+ */
63
+ export declare function findWorkspaceEscape(options: {
64
+ verbs: ReadonlySet<string>;
65
+ argv: readonly string[];
66
+ cwd: string;
67
+ workspaceRoot: string;
68
+ }): WorkspaceEscape | null;
69
+ export {};
70
+ //# sourceMappingURL=workspace-guard.d.ts.map
@@ -0,0 +1,111 @@
1
+ /**
2
+ * Workspace escape guard for destructive argv.
3
+ *
4
+ * A tool that takes an argv list lets a caller name a path, and a verb that
5
+ * removes or overwrites what it names turns a path typo into data loss. This
6
+ * module answers one question for such a tool: does this argv carry a path
7
+ * argument that resolves outside the workspace root?
8
+ *
9
+ * It is a mechanism, not a policy:
10
+ * - the destructive verb set is the caller's, passed in;
11
+ * - the workspace root and the invocation cwd are the caller's;
12
+ * - nothing here executes, refuses, rewrites or reports. The caller decides
13
+ * what to do with an escape, and its own message names the outcome.
14
+ *
15
+ * Resolution is canonical on both sides. The root and the target's nearest
16
+ * existing ancestor go through realpath, so a symlink that lives inside the
17
+ * workspace and points outside it is caught, while a target that does not exist
18
+ * yet is compared by the canonical path of its parent. A target equal to the
19
+ * root is an escape: removing or rewriting the workspace itself is outside the
20
+ * set of things a single path argument may name.
21
+ */
22
+ import { existsSync, realpathSync } from "node:fs";
23
+ import { basename, dirname, isAbsolute, resolve, sep } from "node:path";
24
+ /**
25
+ * Path values carried by an argv, read conservatively: every element after the
26
+ * program that is not a flag, plus the right side of any `key=value` element
27
+ * (`dd of=/etc/passwd`). A flag's own value (`-o /etc/x`) is not followed by the
28
+ * scanner, which is why the caller keeps destructive verbs to the set whose
29
+ * operands are positional or `key=value`; the guard never guesses at a program's
30
+ * option grammar.
31
+ */
32
+ export function pathCandidates(argv) {
33
+ const candidates = [];
34
+ for (const argument of argv.slice(1)) {
35
+ if (argument === "" || argument === "--" || argument.startsWith("-"))
36
+ continue;
37
+ const eq = argument.indexOf("=");
38
+ const path = eq >= 0 ? argument.slice(eq + 1) : argument;
39
+ if (path === "")
40
+ continue;
41
+ candidates.push({ argument, path });
42
+ }
43
+ return candidates;
44
+ }
45
+ /** Canonical absolute path for a target, whether or not it exists yet. */
46
+ export function canonicalPath(target) {
47
+ let current = resolve(target);
48
+ const missing = [];
49
+ // realpath the nearest existing ancestor, then re-attach the names that do
50
+ // not exist yet. The loop is bounded by the filesystem's depth: each step
51
+ // removes one segment.
52
+ for (;;) {
53
+ if (existsSync(current)) {
54
+ let real;
55
+ try {
56
+ real = realpathSync(current);
57
+ }
58
+ catch {
59
+ // A path that exists but cannot be resolved (a race, a permission
60
+ // boundary) is compared as written rather than skipped: a guard that
61
+ // ignores what it cannot resolve is a guard that can be bypassed by
62
+ // making the target unreadable.
63
+ real = current;
64
+ }
65
+ return missing.length ? resolve(real, ...missing.reverse()) : real;
66
+ }
67
+ const parent = dirname(current);
68
+ if (parent === current)
69
+ return resolve(current, ...missing.reverse());
70
+ missing.push(basename(current));
71
+ current = parent;
72
+ }
73
+ }
74
+ /** Whether `target` is strictly below `root` after both are canonicalized. */
75
+ export function isBelow(root, target) {
76
+ const canonicalRoot = canonicalPath(root);
77
+ const canonicalTarget = canonicalPath(target);
78
+ return canonicalTarget.startsWith(canonicalRoot + sep);
79
+ }
80
+ /**
81
+ * The first path argument, in argv order, that resolves outside the workspace.
82
+ * Null when the program's verb is not in `verbs`, when no path argument escapes,
83
+ * or when the argv carries no path argument at all.
84
+ *
85
+ * `cwd` is the directory the argv runs in, so relative operands are read the
86
+ * way the program will read them. `workspaceRoot` is the boundary, which need
87
+ * not be `cwd`: a call may run in a subdirectory and still be bounded by the
88
+ * session's working directory.
89
+ */
90
+ export function findWorkspaceEscape(options) {
91
+ const { verbs, argv, cwd, workspaceRoot } = options;
92
+ const program = argv[0] ?? "";
93
+ const verb = basename(program);
94
+ if (!verbs.has(verb))
95
+ return null;
96
+ const root = canonicalPath(workspaceRoot);
97
+ for (const candidate of pathCandidates(argv)) {
98
+ const target = isAbsolute(candidate.path) ? candidate.path : resolve(cwd, candidate.path);
99
+ if (isBelow(root, target))
100
+ continue;
101
+ return {
102
+ verb,
103
+ argument: candidate.argument,
104
+ path: candidate.path,
105
+ resolved: canonicalPath(target),
106
+ root,
107
+ };
108
+ }
109
+ return null;
110
+ }
111
+ //# sourceMappingURL=workspace-guard.js.map
package/docs/LOCAL_DEV.md CHANGED
@@ -138,7 +138,7 @@ before and after a full run. A non-zero delta is the leak this rule prevents.
138
138
  ### New fixtures: use `node:test`
139
139
 
140
140
  A new fixture is written on `node:test`. The runner does not care which style a
141
- file uses - 124 of the core suite's 361 fixtures already use `node:test` - so the
141
+ file uses - 125 of the core suite's 362 fixtures already use `node:test` - so the
142
142
  reason is the failure the other style produces. A hand-rolled helper that calls
143
143
  `fn()` without awaiting it discards the case's promise, so an `async` case runs
144
144
  detached and the file can print its green tally before that case settles, with
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-braid",
3
- "version": "0.44.5",
3
+ "version": "0.45.0",
4
4
  "description": "🥨 Braid - Metacognitive extension suite for pi coding agent: Adds memory, plan tracking, structured cognitive signals and completion checks on top of pi core loop, so long sessions keep their context and stop claiming unfinished work.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -6,7 +6,7 @@ Narrows the active tool set to a curated profile on request, using `pi.setActive
6
6
 
7
7
  ## Problem
8
8
 
9
- The core package alone documents 33 tools in [TOOLS.md](../../../TOOLS.md); a
9
+ The core package alone documents 34 tools in [TOOLS.md](../../../TOOLS.md); a
10
10
  full install adds the contrib and third-party families on top. Most sessions
11
11
  use only a subset. Displaying every registered tool in the system prompt wastes
12
12
  tokens and increases cognitive load on the model.
@@ -20,13 +20,13 @@ drifted from it.
20
20
 
21
21
  ## Profiles
22
22
 
23
- | Profile | Tools | Use case |
24
- | ----------- | ------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------ |
25
- | `lean` | read, edit, write, bash, grep, find, ls, think, verify, finalize, scratchpad, memory | General-purpose coding & reasoning |
26
- | `research` | read, fetch_content, grep, find, ls, bash, think, memory, scratchpad, verify | Information gathering, web search |
27
- | `debugging` | read, edit, write, bash, grep, find, ls, think, hypothesize, explore_paths, verify, conflict_qa | Bug finding and fixing |
28
- | `browser` | browser_navigate, browser_snapshot, browser_eval, browser_screenshot, read, bash, think, describe_image, fetch_content, verify | Web browsing, UI testing |
29
- | `deep` | read, edit, write, bash, grep, find, ls, think, verify, codebase, file_diff, scratchpad | Deep code analysis, dependency graph |
23
+ | Profile | Tools | Use case |
24
+ | ----------- | ----------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------ |
25
+ | `lean` | read, edit, write, bash, run, grep, find, ls, think, verify, finalize, scratchpad, memory | General-purpose coding & reasoning |
26
+ | `research` | read, fetch_content, grep, find, ls, bash, run, think, memory, scratchpad, verify | Information gathering, web search |
27
+ | `debugging` | read, edit, write, bash, run, grep, find, ls, think, hypothesize, explore_paths, verify, conflict_qa | Bug finding and fixing |
28
+ | `browser` | browser_navigate, browser_snapshot, browser_eval, browser_screenshot, read, bash, run, think, describe_image, fetch_content, verify | Web browsing, UI testing |
29
+ | `deep` | read, edit, write, bash, run, grep, find, ls, think, verify, codebase, file_diff, scratchpad | Deep code analysis, dependency graph |
30
30
 
31
31
  ## How It Works
32
32