pi-braid 0.44.4 → 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
@@ -21,7 +21,7 @@
21
21
  * report is read by nothing that composes the prompt.
22
22
  */
23
23
  import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
24
- import { type AdherenceWriteResult } from "../../../lib/enforcement/adherence-meter.js";
24
+ import { type AdherenceWriteResult, type PendingEscalation } from "../../../lib/enforcement/adherence-meter.js";
25
25
  /** What a crossing may ask the owner channel for. */
26
26
  export interface AdherenceOwnerSender {
27
27
  (text: string, opts?: {
@@ -50,6 +50,29 @@ export interface AdherenceWiringDeps {
50
50
  reportDir?: string;
51
51
  k?: number;
52
52
  }
53
+ /**
54
+ * The hourly digest: one thing that happened, not a field dump. A bold subject
55
+ * names the rung and how many rules the message is about; one sentence carries
56
+ * the counts and the rule it quotes; one stamp says when.
57
+ *
58
+ * Two fields the labelled body carried are deliberately gone:
59
+ * - the truncated session id, because the message already opens with the
60
+ * identity label, and the label names the session the send belongs to
61
+ * (`lib/identity.ts`, telegram);
62
+ * - the report path. The report is where the counts live, not somewhere a
63
+ * reader navigates to from a chat client, so an operator path on the last
64
+ * line was one of the labelled fields the owner read as a dump.
65
+ *
66
+ * The rule is quoted in FULL, never clipped: a fragment of a regex told the
67
+ * owner nothing, and the outbound gate carries a formatted body rather than
68
+ * asking a sender to pre-chew its subject. The quietest honest count of the
69
+ * crossings it folded is stated in its own sentence, so a digest that carries
70
+ * several never reads like a single one.
71
+ */
72
+ export declare function renderAdherenceDigest(digest: {
73
+ pending: PendingEscalation[];
74
+ suppressed: number;
75
+ }, nowMs: number): string;
53
76
  /**
54
77
  * Aggregate the current branch and fold every crossing into the owner's
55
78
  * hourly digest.
@@ -29,7 +29,7 @@ import { getExtensionState, getSessionIdSafe, safeSessionManagerTyped, } from ".
29
29
  import { getWatchdogTgSignalSender } from "../../../lib/state/global-state.js";
30
30
  import { readTelegramPollerLiveness } from "../../../lib/state/telegram-poller-liveness.js";
31
31
  import { formatLocalTime } from "../../../lib/utils/local-time.js";
32
- import { activeBranchEntries, adherenceReportPath, aggregateRuleAdherence, commitDigest, createEscalationState, planDigest, planEscalation, readSessionEntriesFromFile, recordEscalation, writeAdherenceReport, } from "../../../lib/enforcement/adherence-meter.js";
32
+ import { activeBranchEntries, aggregateRuleAdherence, commitDigest, createEscalationState, planDigest, planEscalation, readSessionEntriesFromFile, recordEscalation, writeAdherenceReport, } from "../../../lib/enforcement/adherence-meter.js";
33
33
  const log = createLogger("adherence-meter");
34
34
  /** Extension-state bucket key for the per-session meter state. */
35
35
  const ADHERENCE_STATE_KEY = "adherence-meter";
@@ -59,40 +59,96 @@ function branchEntries(ctx) {
59
59
  function escapeHtml(text) {
60
60
  return text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
61
61
  }
62
- function shorten(text, max) {
63
- const trimmed = text.trim();
64
- return trimmed.length <= max ? trimmed : `${trimmed.slice(0, max - 3)}...`;
65
- }
66
- /** The rule's matched text (the key's `source::pattern` tail), shortened. */
67
- function ruleLabel(entry) {
68
- const tail = entry.ruleKey.includes("::")
62
+ /** The rule's own text: the key is `source::body`, and the body is the rule. */
63
+ function ruleText(entry) {
64
+ const body = entry.ruleKey.includes("::")
69
65
  ? entry.ruleKey.split("::").slice(1).join("::")
70
66
  : entry.ruleKey;
71
- return shorten(`${entry.source}: ${tail}`, 64);
67
+ return body.trim();
68
+ }
69
+ /** Counts up to twenty in words; past that the numeral is the honest form. */
70
+ const COUNT_WORDS = [
71
+ "zero",
72
+ "one",
73
+ "two",
74
+ "three",
75
+ "four",
76
+ "five",
77
+ "six",
78
+ "seven",
79
+ "eight",
80
+ "nine",
81
+ "ten",
82
+ "eleven",
83
+ "twelve",
84
+ "thirteen",
85
+ "fourteen",
86
+ "fifteen",
87
+ "sixteen",
88
+ "seventeen",
89
+ "eighteen",
90
+ "nineteen",
91
+ "twenty",
92
+ ];
93
+ function countWord(n) {
94
+ return Number.isInteger(n) && n >= 0 && n < COUNT_WORDS.length ? COUNT_WORDS[n] : String(n);
95
+ }
96
+ /** The same word, as the opening of a sentence. */
97
+ function sentenceCase(text) {
98
+ return text.length > 0 ? `${text[0].toUpperCase()}${text.slice(1)}` : text;
99
+ }
100
+ /**
101
+ * A rule body that already carries its own quoting is not quoted twice: the
102
+ * whisper bodies the meter counts open and close with quotation marks of their
103
+ * own.
104
+ */
105
+ function quoted(text) {
106
+ const opens = /^["'“«]/.test(text);
107
+ const closes = /["'”»]$/.test(text);
108
+ return opens && closes ? text : `"${text}"`;
72
109
  }
73
110
  /**
74
- * The hourly digest: a bold subject naming the highest rung it reports, then
75
- * labelled lines. Short enough to survive as plain text (the owner's
76
- * tweet-length rule) and valid under `parse_mode: HTML` (the Telegram outbound
77
- * gate validates it before any send).
111
+ * The hourly digest: one thing that happened, not a field dump. A bold subject
112
+ * names the rung and how many rules the message is about; one sentence carries
113
+ * the counts and the rule it quotes; one stamp says when.
114
+ *
115
+ * Two fields the labelled body carried are deliberately gone:
116
+ * - the truncated session id, because the message already opens with the
117
+ * identity label, and the label names the session the send belongs to
118
+ * (`lib/identity.ts`, telegram);
119
+ * - the report path. The report is where the counts live, not somewhere a
120
+ * reader navigates to from a chat client, so an operator path on the last
121
+ * line was one of the labelled fields the owner read as a dump.
122
+ *
123
+ * The rule is quoted in FULL, never clipped: a fragment of a regex told the
124
+ * owner nothing, and the outbound gate carries a formatted body rather than
125
+ * asking a sender to pre-chew its subject. The quietest honest count of the
126
+ * crossings it folded is stated in its own sentence, so a digest that carries
127
+ * several never reads like a single one.
78
128
  */
79
- function renderDigest(digest, ctx, nowMs) {
80
- // The subject is the highest rung in the digest; ties go to the latest.
81
- const subject = digest.pending.reduce((best, entry) => entry.milestone >= best.milestone ? entry : best);
82
- const lines = [
83
- `<b>adherence · rung ${subject.milestone}</b>`,
84
- `rule ${escapeHtml(ruleLabel(subject))}`,
85
- ...(digest.pending.length > 1 ? [`rules ${digest.pending.length}`] : []),
86
- `deliveries ${subject.deliveries}`,
87
- `repeats ${subject.repeats}`,
88
- `suppressed ${digest.suppressed}`,
89
- `session ${escapeHtml(shorten(getSessionIdSafe(ctx) || "unknown", 32))}`,
129
+ export function renderAdherenceDigest(digest, nowMs) {
130
+ // The subject is the rule at the highest rung in the digest. Among rules the
131
+ // ladder put on the same rung (it advances one rung per pass, so a tie is the
132
+ // ordinary case for a folded digest), the one with the most deliveries is the
133
+ // informative quote.
134
+ const subject = digest.pending.reduce((best, entry) => entry.milestone > best.milestone ||
135
+ (entry.milestone === best.milestone && entry.deliveries >= best.deliveries)
136
+ ? entry
137
+ : best);
138
+ const crossings = digest.pending.length;
139
+ const ruleCount = new Set(digest.pending.map((entry) => entry.ruleKey)).size;
140
+ const rules = ruleCount === 1 ? "rule" : "rules";
141
+ const folded = crossings > 1
142
+ ? sentenceCase(`${countWord(crossings)} crossings, from ${countWord(ruleCount)} ${rules}, ` +
143
+ `are reported together in this message. `)
144
+ : "";
145
+ return [
146
+ `<b>Adherence · rung ${subject.milestone} · ${countWord(ruleCount)} ${rules}</b>`,
147
+ `${folded}The rule ${escapeHtml(quoted(ruleText(subject)))} ` +
148
+ `(${escapeHtml(subject.source)}) has repeated ${subject.repeats} ` +
149
+ `times across ${subject.deliveries} deliveries.`,
90
150
  `at ${formatLocalTime(new Date(nowMs))}`,
91
- // The next step is a pointer, not advice: the full signal text and the
92
- // per-rule counts live in the session report.
93
- `where ${escapeHtml(shorten(adherenceReportPath(), 72))}`,
94
- ];
95
- return lines.join("\n");
151
+ ].join("\n");
96
152
  }
97
153
  /**
98
154
  * Aggregate the current branch and fold every crossing into the owner's
@@ -151,7 +207,7 @@ export async function checkAdherence(ctx, deps = {}) {
151
207
  let ok = false;
152
208
  try {
153
209
  ok =
154
- (await Promise.resolve(sender(renderDigest(digest, ctx, nowMs), {
210
+ (await Promise.resolve(sender(renderAdherenceDigest(digest, nowMs), {
155
211
  parseMode: "HTML",
156
212
  source: "adherence-digest",
157
213
  suppressed: digest.suppressed,
@@ -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