brl-subagent 2.6.0 → 2.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,98 @@
1
+ // Purpose: Owner-only repair for the persistent stores' directories and files — mkdirSync's mode applies only on CREATE.
2
+ /**
3
+ * Issue #408 — owner-only persistence repair.
4
+ *
5
+ * F6 (issue #29) intended `0o700` directories and `0o600` files, but
6
+ * `mkdirSync(dir, { recursive: true, mode: 0o700 })` does NOT chmod a directory
7
+ * that already exists (and the SDK's `SessionManager` creates its per-run dir
8
+ * with the process default). A store created before the mode intent therefore
9
+ * stayed world-readable: `.pi/subagents`, `.pi/subagents/sessions`,
10
+ * `.pi/run-registry` and `.pi/output` were all `0o755` on the machine this was
11
+ * found on.
12
+ *
13
+ * THE CONFIDENTIALITY BOUNDARY IS THE DIRECTORY MODE. A `0o700` directory
14
+ * denies other local users traversal, so the files inside are unreachable even
15
+ * if a file mode is wider; the file repairs below are defense-in-depth, not the
16
+ * enforcement. Every store therefore calls `ensureOwnerOnlyDir` on EVERY use —
17
+ * create-only modes are not a repair.
18
+ *
19
+ * Both helpers are best-effort by construction: they never throw, because they
20
+ * run on spawn/settle/registry-write paths where a permission failure must not
21
+ * break execution. A failure is logged and the path is left as it was.
22
+ */
23
+ import { chmodSync, lstatSync, mkdirSync, readdirSync, statSync } from 'node:fs';
24
+ import { join } from 'node:path';
25
+ import { createLogger } from './logging';
26
+
27
+ const log = createLogger('brl-subagent');
28
+
29
+ /** Owner-only directory mode (rwx for the owner, no traversal for anyone else). */
30
+ export const OWNER_ONLY_DIR_MODE = 0o700;
31
+ /** Owner-only file mode (read/write for the owner only). */
32
+ export const OWNER_ONLY_FILE_MODE = 0o600;
33
+
34
+ /**
35
+ * Create `dir` owner-only, or repair an existing directory whose mode grants
36
+ * any group/other bits (`mode & 0o077 !== 0`). Idempotent; never throws.
37
+ *
38
+ * When `dir` is missing, `mkdirSync` creates it (and any missing parents); the
39
+ * explicit `statSync`/`chmodSync` below then normalizes the LEAF, so a fresh
40
+ * directory is `0o700` regardless of umask or Node's per-component defaults.
41
+ */
42
+ export function ensureOwnerOnlyDir(dir: string): void {
43
+ try {
44
+ mkdirSync(dir, { recursive: true, mode: OWNER_ONLY_DIR_MODE });
45
+ } catch (err) {
46
+ log.warn(`Could not create owner-only dir ${dir}`, {
47
+ error: err instanceof Error ? err.message : String(err),
48
+ });
49
+ return;
50
+ }
51
+ try {
52
+ // A symlink must never be followed: `chmod` would retarget the LINK's target
53
+ // (a local user with write access to the store could otherwise point a dir at
54
+ // another path). Not reachable today (the stores are owner-writable), but the
55
+ // guard makes the boundary structural.
56
+ if (lstatSync(dir).isSymbolicLink()) {
57
+ log.warn(`Refusing to repair a symlinked store dir: ${dir}`);
58
+ return;
59
+ }
60
+ const mode = statSync(dir).mode & 0o777;
61
+ if ((mode & 0o077) !== 0) chmodSync(dir, OWNER_ONLY_DIR_MODE);
62
+ } catch (err) {
63
+ // Best-effort: a vanished/unreadable path must never break the caller.
64
+ log.warn(`Could not repair owner-only dir ${dir}`, {
65
+ error: err instanceof Error ? err.message : String(err),
66
+ });
67
+ }
68
+ }
69
+
70
+ /**
71
+ * Repair the modes of the FLAT files directly inside `dir` (the per-run session
72
+ * dir is small — one `.jsonl` plus at most a retention marker), leaving
73
+ * subdirectories alone. Best-effort: a file that vanishes between `readdir` and
74
+ * `stat` is skipped silently, and a failed chmod is logged, never thrown.
75
+ *
76
+ * Defense-in-depth only — see the module comment: the directory mode is what
77
+ * keeps other local users out.
78
+ */
79
+ export function repairOwnerOnlyFiles(dir: string): void {
80
+ let names: string[];
81
+ try {
82
+ names = readdirSync(dir);
83
+ } catch {
84
+ return; // missing/unreadable dir — nothing to repair
85
+ }
86
+ for (const name of names) {
87
+ const file = join(dir, name);
88
+ try {
89
+ // Same no-follow rule as the directory repair: never chmod through a link.
90
+ if (lstatSync(file).isSymbolicLink()) continue;
91
+ const stat = statSync(file);
92
+ if (!stat.isFile()) continue;
93
+ if ((stat.mode & 0o077) !== 0) chmodSync(file, OWNER_ONLY_FILE_MODE);
94
+ } catch {
95
+ // Vanished between readdir and stat, or otherwise unreadable — skip.
96
+ }
97
+ }
98
+ }
package/src/templates.ts CHANGED
@@ -27,7 +27,8 @@ import * as path from "node:path";
27
27
  import type { TaskTemplate, ThinkingLevel, SubagentPreset } from "./types";
28
28
  import { TEMPLATE_PARAM_RE, THINKING_LEVELS } from "./types";
29
29
  import type { Logger } from "./logging";
30
- import { parseFrontmatter, sanitizeFileName } from "./presets";
30
+ import { loadMarkdownRecords } from "./loader";
31
+ import { sanitizeFileName } from "./presets";
31
32
  import { pkgPath } from "./paths";
32
33
 
33
34
  // ---------------------------------------------------------------------------
@@ -177,6 +178,40 @@ export function validateTemplate(meta: Record<string, unknown>, fileName: string
177
178
  // Loading
178
179
  // ---------------------------------------------------------------------------
179
180
 
181
+ /**
182
+ * Normalise validated template frontmatter into a TaskTemplate. Shared by both
183
+ * template tiers — the file walk and validation live in loadMarkdownRecords.
184
+ */
185
+ function templateFromFrontmatter(
186
+ meta: Record<string, unknown>,
187
+ body: string,
188
+ name: string,
189
+ ): TaskTemplate {
190
+ return {
191
+ name,
192
+ description: (meta.description as string) || undefined,
193
+ task: body,
194
+ preset: (meta.preset as string) || undefined,
195
+ thinkingLevel: (meta.thinkingLevel as string) || undefined,
196
+ outputFile: (meta.outputFile as string) || undefined,
197
+ timeout: meta.timeout !== undefined ? Number(meta.timeout) : undefined,
198
+ tools: Array.isArray(meta.tools) ? (meta.tools as string[]) : undefined,
199
+ excludeTools: Array.isArray(meta.excludeTools) ? (meta.excludeTools as string[]) : undefined,
200
+ noBuiltinTools: meta.noBuiltinTools === "true" ? true : undefined,
201
+ inheritSystemPrompt: meta.inheritSystemPrompt === "false" ? false : undefined,
202
+ };
203
+ }
204
+
205
+ /**
206
+ * Reject empty/whitespace-only bodies at load: shipping task: "" would later
207
+ * trip mode-detection with the confusing "Provide exactly one of:
208
+ * task/chain/..." error instead of a load-time warn-and-skip (parseFrontmatter
209
+ * already trims the body).
210
+ */
211
+ function templateBodyError(meta: Record<string, unknown>, body: string): string | null {
212
+ return body.trim() ? null : `Template "${meta.name}" has empty task body`;
213
+ }
214
+
180
215
  /**
181
216
  * Load custom task templates from user directories. Templates are
182
217
  * file-backed, mirroring the custom-preset pattern (issue #66) — the TUI
@@ -197,73 +232,25 @@ export function validateTemplate(meta: Record<string, unknown>, fileName: string
197
232
  * missing directories are skipped silently.
198
233
  */
199
234
  export function loadCustomTemplates(cwd: string, log?: Logger): TaskTemplate[] {
200
- const templates: TaskTemplate[] = [];
201
- const seenNames = new Set<string>();
202
235
  const homedir = process.env.HOME || process.env.USERPROFILE || "";
203
236
 
204
- const dirs = [
205
- path.join(cwd, ".pi", "brl-subagent", "templates"),
206
- path.join(homedir, ".pi", "agent", "brl-subagent", "templates"),
207
- ];
208
-
209
- for (const dir of dirs) {
210
- try {
211
- const files = fs.readdirSync(dir);
212
- for (const file of files) {
213
- if (!file.endsWith(".md")) continue;
214
- try {
215
- const filePath = path.join(dir, file);
216
- const content = fs.readFileSync(filePath, "utf-8");
217
- const { meta, body } = parseFrontmatter(content);
218
-
219
- const errors = validateTemplate(meta, file);
220
- if (errors.length > 0) {
221
- for (const err of errors) {
222
- log?.warn("Custom template validation failed", { file, error: err });
223
- }
224
- continue;
225
- }
226
-
227
- // Reject empty/whitespace-only bodies at load: shipping task: ""
228
- // would later trip mode-detection with the confusing "Provide
229
- // exactly one of: task/chain/..." error instead of a load-time
230
- // warn-and-skip (parseFrontmatter already trims the body).
231
- if (!body.trim()) {
232
- log?.warn("Custom template validation failed", {
233
- file,
234
- error: `Template "${meta.name}" has empty task body`,
235
- });
236
- continue;
237
- }
238
-
239
- const name = meta.name as string;
240
- // Dedup by name: the first occurrence (project-local, scanned
241
- // first) wins; user-global duplicates are skipped.
242
- if (seenNames.has(name)) continue;
243
- seenNames.add(name);
244
- templates.push({
245
- name,
246
- description: (meta.description as string) || undefined,
247
- task: body,
248
- preset: (meta.preset as string) || undefined,
249
- thinkingLevel: (meta.thinkingLevel as string) || undefined,
250
- outputFile: (meta.outputFile as string) || undefined,
251
- timeout: meta.timeout !== undefined ? Number(meta.timeout) : undefined,
252
- tools: Array.isArray(meta.tools) ? (meta.tools as string[]) : undefined,
253
- excludeTools: Array.isArray(meta.excludeTools) ? (meta.excludeTools as string[]) : undefined,
254
- noBuiltinTools: meta.noBuiltinTools === "true" ? true : undefined,
255
- inheritSystemPrompt: meta.inheritSystemPrompt === "false" ? false : undefined,
256
- });
257
- } catch (err) {
258
- log?.warn("Failed to load custom template file", { file, error: (err as Error).message });
259
- }
260
- }
261
- } catch {
262
- // Directory doesn't exist — that's fine, no custom templates
263
- }
264
- }
265
-
266
- return templates;
237
+ return loadMarkdownRecords<TaskTemplate>({
238
+ dirs: [
239
+ path.join(cwd, ".pi", "brl-subagent", "templates"),
240
+ path.join(homedir, ".pi", "agent", "brl-subagent", "templates"),
241
+ ],
242
+ validate: validateTemplate,
243
+ map: templateFromFrontmatter,
244
+ bodyError: templateBodyError,
245
+ // Dedup by name: the first occurrence (project-local, scanned first) wins.
246
+ dedupeByName: true,
247
+ log,
248
+ messages: {
249
+ invalid: "Custom template validation failed",
250
+ readFailed: "Failed to load custom template file",
251
+ },
252
+ // A missing directory is fine — no custom templates in that tier.
253
+ });
267
254
  }
268
255
 
269
256
  /**
@@ -274,62 +261,19 @@ export function loadCustomTemplates(cwd: string, log?: Logger): TaskTemplate[] {
274
261
  * loadBuiltinPresets (src/presets.ts).
275
262
  */
276
263
  export function loadBuiltinTemplates(templatesDir: string, log?: Logger): TaskTemplate[] {
277
- const templates: TaskTemplate[] = [];
278
-
279
- try {
280
- const files = fs.readdirSync(templatesDir);
281
- for (const file of files) {
282
- if (!file.endsWith(".md")) continue;
283
-
284
- try {
285
- const filePath = path.join(templatesDir, file);
286
- const content = fs.readFileSync(filePath, "utf-8");
287
- const { meta, body } = parseFrontmatter(content);
288
-
289
- const errors = validateTemplate(meta, file);
290
- if (errors.length > 0) {
291
- for (const err of errors) {
292
- log?.warn("Builtin template validation failed", { file, error: err });
293
- }
294
- continue;
295
- }
296
-
297
- // Same empty-body guard as loadCustomTemplates: shipped templates
298
- // are authored non-empty, but keep the check so a regressed copy
299
- // warns at load time instead of tripping mode-detection later.
300
- if (!body.trim()) {
301
- log?.warn("Builtin template validation failed", {
302
- file,
303
- error: `Template "${meta.name}" has empty task body`,
304
- });
305
- continue;
306
- }
307
-
308
- const name = meta.name as string;
309
-
310
- templates.push({
311
- name,
312
- description: (meta.description as string) || undefined,
313
- task: body,
314
- preset: (meta.preset as string) || undefined,
315
- thinkingLevel: (meta.thinkingLevel as string) || undefined,
316
- outputFile: (meta.outputFile as string) || undefined,
317
- timeout: meta.timeout !== undefined ? Number(meta.timeout) : undefined,
318
- tools: Array.isArray(meta.tools) ? (meta.tools as string[]) : undefined,
319
- excludeTools: Array.isArray(meta.excludeTools) ? (meta.excludeTools as string[]) : undefined,
320
- noBuiltinTools: meta.noBuiltinTools === "true" ? true : undefined,
321
- inheritSystemPrompt: meta.inheritSystemPrompt === "false" ? false : undefined,
322
- });
323
- } catch (err) {
324
- log?.warn("Failed to load builtin template file", { file, error: (err as Error).message });
325
- }
326
- }
327
- } catch {
264
+ return loadMarkdownRecords<TaskTemplate>({
265
+ dirs: [templatesDir],
266
+ validate: validateTemplate,
267
+ map: templateFromFrontmatter,
268
+ bodyError: templateBodyError,
269
+ log,
270
+ messages: {
271
+ invalid: "Builtin template validation failed",
272
+ readFailed: "Failed to load builtin template file",
273
+ },
328
274
  // Templates directory doesn't exist or can't be read — no built-in templates
329
- log?.info("No built-in templates directory found", { dir: templatesDir });
330
- }
331
-
332
- return templates;
275
+ onMissingDir: (dir) => log?.info("No built-in templates directory found", { dir }),
276
+ });
333
277
  }
334
278
 
335
279
  // ---------------------------------------------------------------------------
package/src/transcript.ts CHANGED
@@ -1,8 +1,9 @@
1
1
  // Purpose: JSONL transcript recording for every agent run (`.pi/output/agent-<id>.jsonl`).
2
- import { mkdirSync, appendFileSync, readFileSync, existsSync } from 'fs';
2
+ import { appendFileSync, readFileSync, existsSync } from 'fs';
3
3
  import type { TranscriptEntry, TranscriptEntryType } from './types';
4
4
  import { transcriptPath, TRANSCRIPT_DIR } from './transcript-path';
5
5
  import { createLogger } from './logging';
6
+ import { ensureOwnerOnlyDir } from './store-permissions';
6
7
 
7
8
  // Issue #265: route the settle-path warning through the logger (file-only by
8
9
  // default) instead of a raw console.warn that corrupts the pi TUI.
@@ -28,7 +29,9 @@ function ensureOutputDir(): void {
28
29
  // F6 (issue #29): transcripts may hold task/steering text — the dir must be
29
30
  // owner-only (0o700) so other local users cannot list the files. NOTE: the
30
31
  // transcript is NOT the full conversation (see appendEntry below).
31
- mkdirSync(OUTPUT_DIR, { recursive: true, mode: 0o700 });
32
+ // Issue #408: `mode` only applies on CREATE, so repair a pre-existing 0o755
33
+ // output dir on every use (the DIR MODE is the traversal boundary).
34
+ ensureOwnerOnlyDir(OUTPUT_DIR);
32
35
  }
33
36
 
34
37
  /**
@@ -0,0 +1,90 @@
1
+ // Purpose: The pure auto-retry predicate for background runs that settled with a transport-class failure (issue #365).
2
+ import type { SubagentRun } from "./types";
3
+
4
+ /**
5
+ * Conservative transport signatures (issue #365). The four observed failures in
6
+ * the 2026-10 cycle were all externally-caused drops — `"Connection error."`
7
+ * from the SDK — that died before any file work, so a replay with the recorded
8
+ * params is cheap and safe. The list is substring-matched against the settled
9
+ * run's `errorMessage` (case-insensitive) and deliberately narrow: a retry is
10
+ * never armed for a failure whose cause is unknown, because re-running a
11
+ * genuinely broken dispatch just spends twice.
12
+ */
13
+ const TRANSPORT_SIGNATURES = [
14
+ "connection error",
15
+ "econnreset",
16
+ "econnrefused",
17
+ "socket hang up",
18
+ "fetch failed",
19
+ "network error",
20
+ "etimedout",
21
+ "enotfound",
22
+ "eai_again",
23
+ ] as const;
24
+
25
+ /**
26
+ * The user-visible warning surfaced when the auto-retry is scheduled. Lives here
27
+ * so the handler and its tests agree on one literal (the runtime-vocabulary
28
+ * ratchet forbids internal vocabulary — this string is user-facing and stays
29
+ * plain).
30
+ */
31
+ export const TRANSPORT_RETRY_TOAST = "Transport failure — auto-retrying once (attempt 2/2)";
32
+
33
+ /**
34
+ * The CLASS half of the predicate: the run failed as a process-level exit
35
+ * (`exit_error`, with the legacy `originalParams.errorCategory` fallback the
36
+ * rest of the code uses) AND its `errorMessage` carries a transport signature.
37
+ *
38
+ * Extracted for issue #404: the settle path must decide whether to RETAIN the
39
+ * run's session directory from exactly the values the run record is about to
40
+ * receive, and it must do so before that record is written. Keeping the half
41
+ * here (not inlined at the settle site) means the retention decision and the
42
+ * retry decision can never drift apart.
43
+ *
44
+ * Pure: no pi SDK, no state, no I/O.
45
+ */
46
+ export function isTransportFailure(
47
+ run: Pick<SubagentRun, "status" | "errorCategory" | "errorMessage" | "originalParams">,
48
+ ): boolean {
49
+ if (run.status !== "failed") return false;
50
+ // New consumers read the top-level category; the legacy snapshot key is the
51
+ // documented fallback (same rule as buildCompletionMessage).
52
+ const category = run.errorCategory ?? run.originalParams?.errorCategory;
53
+ if (category !== "exit_error") return false;
54
+ const message = (run.errorMessage ?? "").toLowerCase();
55
+ return TRANSPORT_SIGNATURES.some((signature) => message.includes(signature));
56
+ }
57
+
58
+ /**
59
+ * TRUE when a settled run should be re-dispatched ONCE automatically.
60
+ *
61
+ * Every condition must hold (issue #365 spec):
62
+ *
63
+ * 1. `isTransportFailure` — failed as `exit_error` with a transport
64
+ * signature in the message (the class the runner already stamps for an
65
+ * external drop);
66
+ * 2. it is the ORIGINAL dispatch (`attempt ?? 1 === 1`): a user retry, or a
67
+ * previous auto-retry that failed again, surfaces normally. This is what
68
+ * bounds the machinery structurally — one retry per logical dispatch,
69
+ * never a chain, no timer, no queue;
70
+ * 3. it ran in the BACKGROUND — a foreground failure is already visible
71
+ * inline (and `retryOnTimeout` covers the foreground timeout case);
72
+ * 4. the record carries `originalParams`, which is what the retry restores.
73
+ * Fan-out units deliberately omit it (their retry semantics belong to
74
+ * issue #229), so they fall out here by construction.
75
+ *
76
+ * Issue #404: this is ALSO the settle-time retention gate. The resume preamble
77
+ * that points at a retained session is built only by `scheduleTransportRetry`,
78
+ * which fires only when this predicate holds — so exactly this class has a
79
+ * reader. An attempt-2 transport failure (or one of a background-less run)
80
+ * prunes its session as before.
81
+ *
82
+ * Pure: no pi SDK, no state, no I/O — unit-testable as a matrix.
83
+ */
84
+ export function isTransportRetryable(
85
+ run: Pick<SubagentRun, "status" | "errorCategory" | "errorMessage" | "attempt" | "originalParams">,
86
+ ): boolean {
87
+ if (!isTransportFailure(run)) return false;
88
+ if ((run.attempt ?? 1) !== 1) return false;
89
+ return run.originalParams?.background === true;
90
+ }