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,503 @@
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
+
23
+ import { spawn } from "node:child_process";
24
+ import type { ChildProcess } from "node:child_process";
25
+ import { closeSync, mkdtempSync, openSync, readSync, rmSync, statSync } from "node:fs";
26
+ import { tmpdir } from "node:os";
27
+ import { basename, join, resolve } from "node:path";
28
+ import { DEFAULT_MAX_BYTES } from "@earendil-works/pi-coding-agent";
29
+ import { findWorkspaceEscape } from "../../../lib/tools/workspace-guard.js";
30
+
31
+ /** setTimeout's own ceiling: a longer timeout cannot be armed. */
32
+ export const MAX_TIMEOUT_MS = 2_147_483_647;
33
+
34
+ /** The smallest cap worth reporting a window for. */
35
+ export const MIN_OUTPUT_BYTES = 1_024;
36
+
37
+ /** A cap past the harness's own structured-output budget buys nothing. */
38
+ export const MAX_OUTPUT_BYTES = 1_048_576;
39
+
40
+ /** Per stream, when the call names no cap: the harness's truncation default. */
41
+ export const DEFAULT_OUTPUT_BYTES = DEFAULT_MAX_BYTES;
42
+
43
+ /**
44
+ * Verbs whose operand is destroyed or rewritten. The set is this tool's policy,
45
+ * not the guard's: `git` will bring its own.
46
+ */
47
+ export const DESTRUCTIVE_VERBS: ReadonlySet<string> = new Set([
48
+ "rm",
49
+ "mv",
50
+ "dd",
51
+ "chmod",
52
+ "shred",
53
+ "truncate",
54
+ ]);
55
+
56
+ /** Programs that take a command string: `-c` makes one of them a shell again. */
57
+ const SHELL_PROGRAMS: ReadonlySet<string> = new Set(["sh", "bash", "zsh", "dash", "ksh", "fish"]);
58
+
59
+ /** Shell operators that only mean something inside a shell. */
60
+ const SHELL_OPERATORS = ["&&", "$(", "|", ";", "`"] as const;
61
+
62
+ /** Longest argument quoted back in a refusal, so the message stays readable. */
63
+ const MAX_QUOTED_ARGUMENT = 160;
64
+
65
+ /** How far past a byte budget a read looks for a line boundary. */
66
+ const LINE_WINDOW_SLACK = 8 * 1024;
67
+
68
+ /** Share of the cap kept from the head; the tail keeps the rest. */
69
+ const HEAD_SHARE = 0.6;
70
+
71
+ /** A validated `run` call. */
72
+ export interface RunRequest {
73
+ argv: string[];
74
+ cwd?: string;
75
+ env?: Record<string, string>;
76
+ stdin?: string;
77
+ timeout_ms: number;
78
+ max_output_bytes?: number;
79
+ }
80
+
81
+ /** Why a call never reached a program. */
82
+ export interface RunRefusal {
83
+ kind:
84
+ | "argv"
85
+ | "metacharacter"
86
+ | "shell-string"
87
+ | "glob"
88
+ | "timeout"
89
+ | "output-cap"
90
+ | "cwd"
91
+ | "destructive-escape";
92
+ message: string;
93
+ }
94
+
95
+ /** One stream after the cap was applied. */
96
+ export interface RunStream {
97
+ /** What the result text shows. */
98
+ text: string;
99
+ /** Bytes the program wrote to this stream. */
100
+ bytes: number;
101
+ /** Bytes the text shows, before the omission marker. */
102
+ shownBytes: number;
103
+ /** Bytes the text does not show. */
104
+ droppedBytes: number;
105
+ /** Whether the cap applied. */
106
+ truncated: boolean;
107
+ /** The file holding the full stream; present when `truncated`. */
108
+ fullTextPath?: string;
109
+ }
110
+
111
+ /** What one call captured, before the cap is applied to either stream. */
112
+ export interface RunCapture {
113
+ exitCode: number | null;
114
+ signal: string | null;
115
+ timedOut: boolean;
116
+ aborted: boolean;
117
+ durationMs: number;
118
+ cwd: string;
119
+ argv: string[];
120
+ /** Present when the child could not be spawned at all. */
121
+ spawnError?: string;
122
+ /** Full stdout, in a file this call owns. */
123
+ stdoutPath: string;
124
+ /** Full stderr, in a file this call owns. */
125
+ stderrPath: string;
126
+ stdoutBytes: number;
127
+ stderrBytes: number;
128
+ /** The capture directory, removed by `discardCapture`. */
129
+ captureDir?: string;
130
+ }
131
+
132
+ /** Where a call runs, and what bounds its destructive verbs. */
133
+ export interface RunContext {
134
+ /** Absolute directory the program runs in. */
135
+ cwd: string;
136
+ /** Boundary for the destructive guard. */
137
+ workspaceRoot: string;
138
+ }
139
+
140
+ function quote(text: string): string {
141
+ return text.length > MAX_QUOTED_ARGUMENT ? `${text.slice(0, MAX_QUOTED_ARGUMENT)}...` : text;
142
+ }
143
+
144
+ /**
145
+ * A `*` at a path-segment boundary: the whole element, a leading `*.ext`, a
146
+ * trailing directory wildcard, or a wildcard between two segments. A star
147
+ * inside a word or a pattern is the program's business.
148
+ */
149
+ export function isGlobExpression(element: string): boolean {
150
+ if (!element.includes("*")) return false;
151
+ return element.startsWith("*") || element.endsWith("*") || element.includes("/*");
152
+ }
153
+
154
+ /** The first element carrying a shell operator, or null. */
155
+ function findShellOperator(argv: readonly string[]): {
156
+ index: number;
157
+ operator: string;
158
+ } | null {
159
+ for (let index = 0; index < argv.length; index++) {
160
+ const element = argv[index];
161
+ for (const operator of SHELL_OPERATORS) {
162
+ if (element.includes(operator)) return { index, operator };
163
+ }
164
+ }
165
+ return null;
166
+ }
167
+
168
+ /** Whether a shell program is being handed a command string. */
169
+ function isShellCommandString(argv: readonly string[]): boolean {
170
+ if (!SHELL_PROGRAMS.has(basename(argv[0] ?? ""))) return false;
171
+ return argv.slice(1).some((element) => {
172
+ if (element === "--command") return true;
173
+ // A short-flag cluster: -c, -ec, -lc. A long flag (--login) is not one.
174
+ return /^-[A-Za-z]*c[A-Za-z]*$/.test(element);
175
+ });
176
+ }
177
+
178
+ /**
179
+ * Everything wrong with a call that can be known before a process starts: the
180
+ * argv shape, shell operators, a shell command string, a glob, the timeout, the
181
+ * cap, and a destructive verb reaching outside the workspace.
182
+ *
183
+ * Pure. The cwd is already resolved and its existence checked by the caller;
184
+ * the workspace boundary is passed in.
185
+ */
186
+ export function findRefusal(request: RunRequest, context: RunContext): RunRefusal | null {
187
+ const { argv } = request;
188
+ if (!Array.isArray(argv) || argv.length === 0) {
189
+ return {
190
+ kind: "argv",
191
+ message:
192
+ "refused: argv is required and must be non-empty. Pass the program as argv[0] and one element per argument.",
193
+ };
194
+ }
195
+ if (argv.some((element) => typeof element !== "string" || element === "")) {
196
+ return {
197
+ kind: "argv",
198
+ message:
199
+ "refused: every argv element must be a non-empty string. An empty element cannot be passed to a program.",
200
+ };
201
+ }
202
+
203
+ const operator = findShellOperator(argv);
204
+ if (operator) {
205
+ return {
206
+ kind: "metacharacter",
207
+ message:
208
+ `refused: argv[${operator.index}] carries "${operator.operator}". ` +
209
+ "run executes argv directly and never through a shell, so the operator would be a literal argument. " +
210
+ `Argument: ${quote(argv[operator.index])}`,
211
+ };
212
+ }
213
+
214
+ if (isShellCommandString(argv)) {
215
+ return {
216
+ kind: "shell-string",
217
+ message:
218
+ "refused: argv[0] is a shell and argv carries -c, so this is a command string rather than a program call. " +
219
+ "run does not hand commands to a shell. Use bash, or pass the program and its arguments directly.",
220
+ };
221
+ }
222
+
223
+ const glob = argv.slice(1).find(isGlobExpression);
224
+ if (glob !== undefined) {
225
+ return {
226
+ kind: "glob",
227
+ message:
228
+ `refused: "${quote(glob)}" is a glob, and run does not expand globs. ` +
229
+ "Pass the paths the glob would have matched, or use find or grep, which take patterns themselves.",
230
+ };
231
+ }
232
+
233
+ const timeout = request.timeout_ms;
234
+ if (typeof timeout !== "number" || !Number.isFinite(timeout)) {
235
+ return {
236
+ kind: "timeout",
237
+ message:
238
+ "refused: timeout_ms is required and must be a finite number of milliseconds. " +
239
+ "A call with no timeout can hang the session.",
240
+ };
241
+ }
242
+ if (!Number.isInteger(timeout) || timeout < 1 || timeout > MAX_TIMEOUT_MS) {
243
+ return {
244
+ kind: "timeout",
245
+ message:
246
+ `refused: timeout_ms must be an integer from 1 to ${MAX_TIMEOUT_MS}; got ${timeout}. ` +
247
+ "A call with no timeout can hang the session.",
248
+ };
249
+ }
250
+
251
+ if (request.max_output_bytes !== undefined) {
252
+ const cap = request.max_output_bytes;
253
+ if (!Number.isInteger(cap) || cap < MIN_OUTPUT_BYTES || cap > MAX_OUTPUT_BYTES) {
254
+ return {
255
+ kind: "output-cap",
256
+ message: `refused: max_output_bytes must be an integer from ${MIN_OUTPUT_BYTES} to ${MAX_OUTPUT_BYTES}; got ${String(cap)}.`,
257
+ };
258
+ }
259
+ }
260
+
261
+ const escape = findWorkspaceEscape({
262
+ verbs: DESTRUCTIVE_VERBS,
263
+ argv,
264
+ cwd: context.cwd,
265
+ workspaceRoot: context.workspaceRoot,
266
+ });
267
+ if (escape) {
268
+ return {
269
+ kind: "destructive-escape",
270
+ message:
271
+ `refused: "${escape.verb}" names "${escape.path}", which resolves to ${escape.resolved}, ` +
272
+ `outside the workspace ${escape.root}. A destructive verb is refused when a path argument leaves the workspace; use bash if that is intended.`,
273
+ };
274
+ }
275
+
276
+ return null;
277
+ }
278
+
279
+ function statSize(file: string): number {
280
+ try {
281
+ return statSync(file).size;
282
+ } catch {
283
+ // The capture file is created by this call and read after the child exits;
284
+ // a vanished file reads as empty output rather than failing the result.
285
+ return 0;
286
+ }
287
+ }
288
+
289
+ /** Read into `buffer` from `fd`, closing the descriptor whatever happens. */
290
+ function readFrom(fd: number, buffer: Buffer, length: number, position: number): number {
291
+ try {
292
+ return readSync(fd, buffer, 0, length, position);
293
+ } finally {
294
+ closeSync(fd);
295
+ }
296
+ }
297
+
298
+ /** Read the first `budget` bytes of a file, cut at a line boundary. */
299
+ function readHead(file: string, budget: number): string {
300
+ const window = Math.min(Math.max(budget, 1) + LINE_WINDOW_SLACK, Math.max(statSize(file), 1));
301
+ const buffer = Buffer.allocUnsafe(window);
302
+ const read = readFrom(openSync(file, "r"), buffer, window, 0);
303
+ const slice = buffer.subarray(0, read);
304
+ const newline = slice.lastIndexOf(0x0a);
305
+ const end = newline >= 0 && newline <= budget ? newline + 1 : Math.min(budget, read);
306
+ return stripSplitCharacter(slice.subarray(0, end).toString("utf8"), "end");
307
+ }
308
+
309
+ /** Read the last `budget` bytes of a file, cut at a line boundary. */
310
+ function readTail(file: string, budget: number): string {
311
+ const size = statSize(file);
312
+ const start = Math.max(0, size - budget - LINE_WINDOW_SLACK);
313
+ const length = size - start;
314
+ const buffer = Buffer.allocUnsafe(length);
315
+ const read = readFrom(openSync(file, "r"), buffer, length, start);
316
+ const slice = buffer.subarray(0, read);
317
+ const newline = slice.indexOf(0x0a);
318
+ const offset = newline >= 0 && newline < slice.length ? newline + 1 : 0;
319
+ const kept = slice.subarray(offset);
320
+ const fromEnd = kept.subarray(Math.max(0, kept.length - budget));
321
+ return stripSplitCharacter(fromEnd.toString("utf8"), "start");
322
+ }
323
+
324
+ /**
325
+ * A byte window can cut a multi-byte character in half; a lone replacement
326
+ * character at that edge is the cut, not the program's output.
327
+ */
328
+ function stripSplitCharacter(text: string, edge: "start" | "end"): string {
329
+ return edge === "end" ? text.replace(/\uFFFD$/, "") : text.replace(/^\uFFFD/, "");
330
+ }
331
+
332
+ /** Apply the byte cap to one captured stream, keeping a head and a tail. */
333
+ export function boundStream(file: string, cap: number, fullTextPath?: string): RunStream {
334
+ const bytes = statSize(file);
335
+ if (bytes <= cap) {
336
+ const buffer = Buffer.allocUnsafe(bytes);
337
+ const read = bytes === 0 ? 0 : readFrom(openSync(file, "r"), buffer, bytes, 0);
338
+ return {
339
+ text: buffer.subarray(0, read).toString("utf8"),
340
+ bytes,
341
+ shownBytes: read,
342
+ droppedBytes: 0,
343
+ truncated: false,
344
+ };
345
+ }
346
+
347
+ const headBudget = Math.floor(cap * HEAD_SHARE);
348
+ const tailBudget = cap - headBudget;
349
+ const head = readHead(file, headBudget);
350
+ const tail = readTail(file, tailBudget);
351
+ const kept = Buffer.byteLength(head) + Buffer.byteLength(tail);
352
+ const droppedBytes = Math.max(0, bytes - kept);
353
+ const marker = `\n[... ${droppedBytes} bytes omitted ...]\n`;
354
+ return {
355
+ text: `${head}${marker}${tail}`,
356
+ bytes,
357
+ shownBytes: kept,
358
+ droppedBytes,
359
+ truncated: true,
360
+ ...(fullTextPath ? { fullTextPath } : {}),
361
+ };
362
+ }
363
+
364
+ /** Kill the child's process group, falling back to the child alone. */
365
+ function killTree(child: ChildProcess): void {
366
+ const pid = child.pid;
367
+ if (pid === undefined) return;
368
+ if (process.platform !== "win32") {
369
+ try {
370
+ process.kill(-pid, "SIGKILL");
371
+ return;
372
+ } catch {
373
+ // The group is already gone, or the child never led one; fall through to
374
+ // the direct kill so a single process is still terminated.
375
+ }
376
+ }
377
+ try {
378
+ child.kill("SIGKILL");
379
+ } catch {
380
+ // The child exited between the timeout firing and this call; the exit
381
+ // event already carries the result, so there is nothing left to stop.
382
+ }
383
+ }
384
+
385
+ /**
386
+ * Run one program. The caller has already refused the shapes that never reach a
387
+ * program (see `findRefusal`) and resolved `context.cwd`.
388
+ *
389
+ * The child is spawned detached on POSIX so the timeout and an aborted tool call
390
+ * kill the whole tree, not only the leader; stdout and stderr are files rather
391
+ * than pipes, so a grandchild cannot hold the result open after the program
392
+ * exits, and the capture is byte-exact without buffering the stream in memory.
393
+ */
394
+ export async function executeArgv(
395
+ request: RunRequest,
396
+ context: RunContext,
397
+ signal?: AbortSignal,
398
+ ): Promise<RunCapture> {
399
+ const cwd = resolve(context.cwd);
400
+ const dir = mkdtempSync(join(tmpdir(), "pi-run-"));
401
+ const stdoutPath = join(dir, "stdout");
402
+ const stderrPath = join(dir, "stderr");
403
+
404
+ let child: ChildProcess;
405
+ const startedAt = performance.now();
406
+ let stdoutFd: number | undefined;
407
+ let stderrFd: number | undefined;
408
+ try {
409
+ stdoutFd = openSync(stdoutPath, "w");
410
+ stderrFd = openSync(stderrPath, "w");
411
+ child = spawn(request.argv[0], request.argv.slice(1), {
412
+ cwd,
413
+ env: { ...process.env, ...(request.env ?? {}) },
414
+ // shell: false is the default; it is written out because "no shell" is
415
+ // this tool's contract, not an inherited default a refactor could flip.
416
+ shell: false,
417
+ detached: process.platform !== "win32",
418
+ windowsHide: true,
419
+ stdio: [request.stdin === undefined ? "ignore" : "pipe", stdoutFd, stderrFd],
420
+ });
421
+ } catch (error) {
422
+ rmSync(dir, { recursive: true, force: true });
423
+ throw error;
424
+ } finally {
425
+ if (stdoutFd !== undefined) closeSync(stdoutFd);
426
+ if (stderrFd !== undefined) closeSync(stderrFd);
427
+ }
428
+
429
+ let timedOut = false;
430
+ let aborted = false;
431
+ let spawnError: string | undefined;
432
+
433
+ const exit = new Promise<{ code: number | null; signal: string | null }>((settle) => {
434
+ let done = false;
435
+ const finish = (code: number | null, killed: string | null) => {
436
+ if (done) return;
437
+ done = true;
438
+ settle({ code, signal: killed });
439
+ };
440
+ child.once("exit", (code, killed) => finish(code, killed));
441
+ child.once("error", (error) => {
442
+ spawnError = `${(error as NodeJS.ErrnoException).code ?? "spawn"}: ${error.message}`;
443
+ finish(null, null);
444
+ });
445
+ });
446
+
447
+ const onAbort = () => {
448
+ aborted = true;
449
+ killTree(child);
450
+ };
451
+ if (signal) {
452
+ if (signal.aborted) onAbort();
453
+ else signal.addEventListener("abort", onAbort, { once: true });
454
+ }
455
+
456
+ if (child.stdin) {
457
+ child.stdin.on("error", () => {
458
+ // A program may exit before reading its stdin; the write failure is then
459
+ // the program's answer, reported through its exit code, not a tool error.
460
+ });
461
+ child.stdin.end(request.stdin ?? "");
462
+ }
463
+
464
+ const timer = setTimeout(() => {
465
+ timedOut = true;
466
+ killTree(child);
467
+ }, request.timeout_ms);
468
+
469
+ // The timer and the abort listener belong to the wait, not to the call: they
470
+ // are released when the wait settles, whichever way it settles.
471
+ const result = await exit.finally(() => {
472
+ clearTimeout(timer);
473
+ if (signal) signal.removeEventListener("abort", onAbort);
474
+ });
475
+
476
+ return {
477
+ exitCode: result.code,
478
+ signal: result.signal,
479
+ timedOut,
480
+ aborted,
481
+ durationMs: Math.round(performance.now() - startedAt),
482
+ cwd,
483
+ argv: request.argv,
484
+ ...(spawnError === undefined ? {} : { spawnError }),
485
+ stdoutPath,
486
+ stderrPath,
487
+ stdoutBytes: spawnError === undefined ? statSize(stdoutPath) : 0,
488
+ stderrBytes: statSize(stderrPath),
489
+ captureDir: dir,
490
+ };
491
+ }
492
+
493
+ /** Remove the capture directory after the caller has offloaded what it needs. */
494
+ export function discardCapture(capture: RunCapture): void {
495
+ if (capture.captureDir) {
496
+ rmSync(capture.captureDir, { recursive: true, force: true });
497
+ }
498
+ }
499
+
500
+ /** The capture file for one stream, while the capture directory still exists. */
501
+ export function capturePathFor(capture: RunCapture, stream: "stdout" | "stderr"): string {
502
+ return stream === "stdout" ? capture.stdoutPath : capture.stderrPath;
503
+ }
@@ -40,7 +40,6 @@ import { readTelegramPollerLiveness } from "../../../lib/state/telegram-poller-l
40
40
  import { formatLocalTime } from "../../../lib/utils/local-time.js";
41
41
  import {
42
42
  activeBranchEntries,
43
- adherenceReportPath,
44
43
  aggregateRuleAdherence,
45
44
  commitDigest,
46
45
  createEscalationState,
@@ -121,48 +120,109 @@ function escapeHtml(text: string): string {
121
120
  return text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
122
121
  }
123
122
 
124
- function shorten(text: string, max: number): string {
125
- const trimmed = text.trim();
126
- return trimmed.length <= max ? trimmed : `${trimmed.slice(0, max - 3)}...`;
127
- }
128
-
129
- /** The rule's matched text (the key's `source::pattern` tail), shortened. */
130
- function ruleLabel(entry: PendingEscalation): string {
131
- const tail = entry.ruleKey.includes("::")
123
+ /** The rule's own text: the key is `source::body`, and the body is the rule. */
124
+ function ruleText(entry: PendingEscalation): string {
125
+ const body = entry.ruleKey.includes("::")
132
126
  ? entry.ruleKey.split("::").slice(1).join("::")
133
127
  : entry.ruleKey;
134
- return shorten(`${entry.source}: ${tail}`, 64);
128
+ return body.trim();
129
+ }
130
+
131
+ /** Counts up to twenty in words; past that the numeral is the honest form. */
132
+ const COUNT_WORDS = [
133
+ "zero",
134
+ "one",
135
+ "two",
136
+ "three",
137
+ "four",
138
+ "five",
139
+ "six",
140
+ "seven",
141
+ "eight",
142
+ "nine",
143
+ "ten",
144
+ "eleven",
145
+ "twelve",
146
+ "thirteen",
147
+ "fourteen",
148
+ "fifteen",
149
+ "sixteen",
150
+ "seventeen",
151
+ "eighteen",
152
+ "nineteen",
153
+ "twenty",
154
+ ];
155
+
156
+ function countWord(n: number): string {
157
+ return Number.isInteger(n) && n >= 0 && n < COUNT_WORDS.length ? COUNT_WORDS[n] : String(n);
158
+ }
159
+
160
+ /** The same word, as the opening of a sentence. */
161
+ function sentenceCase(text: string): string {
162
+ return text.length > 0 ? `${text[0].toUpperCase()}${text.slice(1)}` : text;
135
163
  }
136
164
 
137
165
  /**
138
- * The hourly digest: a bold subject naming the highest rung it reports, then
139
- * labelled lines. Short enough to survive as plain text (the owner's
140
- * tweet-length rule) and valid under `parse_mode: HTML` (the Telegram outbound
141
- * gate validates it before any send).
166
+ * A rule body that already carries its own quoting is not quoted twice: the
167
+ * whisper bodies the meter counts open and close with quotation marks of their
168
+ * own.
142
169
  */
143
- function renderDigest(
170
+ function quoted(text: string): string {
171
+ const opens = /^["'“«]/.test(text);
172
+ const closes = /["'”»]$/.test(text);
173
+ return opens && closes ? text : `"${text}"`;
174
+ }
175
+
176
+ /**
177
+ * The hourly digest: one thing that happened, not a field dump. A bold subject
178
+ * names the rung and how many rules the message is about; one sentence carries
179
+ * the counts and the rule it quotes; one stamp says when.
180
+ *
181
+ * Two fields the labelled body carried are deliberately gone:
182
+ * - the truncated session id, because the message already opens with the
183
+ * identity label, and the label names the session the send belongs to
184
+ * (`lib/identity.ts`, telegram);
185
+ * - the report path. The report is where the counts live, not somewhere a
186
+ * reader navigates to from a chat client, so an operator path on the last
187
+ * line was one of the labelled fields the owner read as a dump.
188
+ *
189
+ * The rule is quoted in FULL, never clipped: a fragment of a regex told the
190
+ * owner nothing, and the outbound gate carries a formatted body rather than
191
+ * asking a sender to pre-chew its subject. The quietest honest count of the
192
+ * crossings it folded is stated in its own sentence, so a digest that carries
193
+ * several never reads like a single one.
194
+ */
195
+ export function renderAdherenceDigest(
144
196
  digest: { pending: PendingEscalation[]; suppressed: number },
145
- ctx: ExtensionContext,
146
197
  nowMs: number,
147
198
  ): string {
148
- // The subject is the highest rung in the digest; ties go to the latest.
199
+ // The subject is the rule at the highest rung in the digest. Among rules the
200
+ // ladder put on the same rung (it advances one rung per pass, so a tie is the
201
+ // ordinary case for a folded digest), the one with the most deliveries is the
202
+ // informative quote.
149
203
  const subject = digest.pending.reduce((best, entry) =>
150
- entry.milestone >= best.milestone ? entry : best,
204
+ entry.milestone > best.milestone ||
205
+ (entry.milestone === best.milestone && entry.deliveries >= best.deliveries)
206
+ ? entry
207
+ : best,
151
208
  );
152
- const lines = [
153
- `<b>adherence · rung ${subject.milestone}</b>`,
154
- `rule ${escapeHtml(ruleLabel(subject))}`,
155
- ...(digest.pending.length > 1 ? [`rules ${digest.pending.length}`] : []),
156
- `deliveries ${subject.deliveries}`,
157
- `repeats ${subject.repeats}`,
158
- `suppressed ${digest.suppressed}`,
159
- `session ${escapeHtml(shorten(getSessionIdSafe(ctx) || "unknown", 32))}`,
209
+ const crossings = digest.pending.length;
210
+ const ruleCount = new Set(digest.pending.map((entry) => entry.ruleKey)).size;
211
+ const rules = ruleCount === 1 ? "rule" : "rules";
212
+ const folded =
213
+ crossings > 1
214
+ ? sentenceCase(
215
+ `${countWord(crossings)} crossings, from ${countWord(ruleCount)} ${rules}, ` +
216
+ `are reported together in this message. `,
217
+ )
218
+ : "";
219
+ return [
220
+ `<b>Adherence · rung ${subject.milestone} · ${countWord(ruleCount)} ${rules}</b>`,
221
+ `${folded}The rule ${escapeHtml(quoted(ruleText(subject)))} ` +
222
+ `(${escapeHtml(subject.source)}) has repeated ${subject.repeats} ` +
223
+ `times across ${subject.deliveries} deliveries.`,
160
224
  `at ${formatLocalTime(new Date(nowMs))}`,
161
- // The next step is a pointer, not advice: the full signal text and the
162
- // per-rule counts live in the session report.
163
- `where ${escapeHtml(shorten(adherenceReportPath(), 72))}`,
164
- ];
165
- return lines.join("\n");
225
+ ].join("\n");
166
226
  }
167
227
 
168
228
  /**
@@ -231,7 +291,7 @@ export async function checkAdherence(
231
291
  try {
232
292
  ok =
233
293
  (await Promise.resolve(
234
- sender(renderDigest(digest, ctx, nowMs), {
294
+ sender(renderAdherenceDigest(digest, nowMs), {
235
295
  parseMode: "HTML",
236
296
  source: "adherence-digest",
237
297
  suppressed: digest.suppressed,
@@ -18,6 +18,7 @@ import orchestratorFn from "./orchestrator/index.js";
18
18
  // context-management (tool profile switching)
19
19
  import contextManagementFn from "./context-management/index.js";
20
20
  import coreAgentEnvFn from "./core/agent-environment/index.js";
21
+ import coreRunToolFn from "./core/run-tool/index.js";
21
22
  import corePromptBuilderFn from "./core/prompt-builder/index.js";
22
23
 
23
24
  // cognitive (reasoning tools + detectors: think, verify, topic-drift, MARS reflection, ...)
@@ -106,6 +107,11 @@ export const MANIFEST: ManifestEntry[] = [
106
107
  alwaysOn: true,
107
108
  desc: "time_status, L1 context injection",
108
109
  },
110
+ {
111
+ id: "run-tool",
112
+ fn: coreRunToolFn,
113
+ desc: "run tool - one program and its argv, without a shell",
114
+ },
109
115
  {
110
116
  id: "workspace-snapshot",
111
117
  fn: workspaceSnapshotFn,
@@ -33,6 +33,7 @@ export const TOOL_FAMILIES: Readonly<Record<string, ToolFamily>> = {
33
33
  get_search_content: "web-fetch",
34
34
 
35
35
  bash: "terminal",
36
+ run: "terminal",
36
37
  herdr_pane: "terminal",
37
38
  herdr_layout: "terminal",
38
39