brl-subagent 2.6.0 → 2.8.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.
package/src/state.ts CHANGED
@@ -78,17 +78,24 @@ export const STALE_FINALIZE_GRACE_MS = POLLER_TICK_MS + 1000;
78
78
  * preference rule. Recovery's `dedupeRunEntriesById` delegates here, so the
79
79
  * boot scan and every display/retry lookup agree by construction.
80
80
  *
81
- * Each run writes TWO custom entries sharing its id, in append order: a spawn
82
- * entry (status "running", carrying `originalParams`) FIRST, then the final
83
- * entry (status "done"/"failed", stamped with fullOutput/cost/duration) at
84
- * settle. Preference, in order:
81
+ * Each run writes a spawn entry (status "running", carrying `originalParams`)
82
+ * FIRST, then its terminal entry (status "done"/"failed", stamped with
83
+ * fullOutput/cost/duration) at settle. A run stopped by the deadline writes ONE
84
+ * MORE terminal entry at the late settle — a payload AMENDMENT of the deadline's
85
+ * classification snapshot (issue #453, ADR 0023 decision 4). Preference, in order:
85
86
  *
86
- * 1. a TERMINAL entry (status !== "running") — the run is resolved;
87
+ * 1. the LAST terminal entry (status !== "running") — with an amendment that
88
+ * is the amended payload; without one it is the only terminal entry, so
89
+ * this is unchanged for every pre-#453 run (mutant M5 is `find` here);
87
90
  * 2. among non-terminal entries, one carrying the D3 `interruptedAt` mark —
88
91
  * append-only stores keep the original spawn entry forever, so the marked
89
92
  * clone is the authoritative RECOVERED state U3's shared lookup reads;
90
93
  * 3. otherwise the first match (the pre-finalize spawn shape).
91
94
  *
95
+ * Ordering contract: callers pass a store-ordered list (`getRunEntries` is
96
+ * newest-first with a STABLE sort, so a run's entries stay in append order —
97
+ * spawn, snapshot, amendment). "Last" therefore means "appended last".
98
+ *
92
99
  * Returns undefined when no entry matches.
93
100
  */
94
101
  export function resolveTerminalRunEntry(
@@ -98,12 +105,39 @@ export function resolveTerminalRunEntry(
98
105
  const matching = entries.filter((r) => r.id === id);
99
106
  if (matching.length === 0) return undefined;
100
107
  return (
101
- matching.find((r) => r.status !== "running") ??
108
+ matching.findLast((r) => r.status !== "running") ??
102
109
  matching.find((r) => r.interruptedAt) ??
103
110
  matching[0]
104
111
  );
105
112
  }
106
113
 
114
+ /**
115
+ * Issue #453 (ADR 0023 decision 4): ONE logical run per id — the projection every
116
+ * raw-entry consumer reads.
117
+ *
118
+ * A run that hits its deadline and settles late has three entries sharing its id
119
+ * (spawn, `failed/timeout` snapshot, payload amendment). Aggregates that take the
120
+ * raw list count it two or three times and sum two full payloads (measured: 3
121
+ * runs / $5 for a $2 snapshot + $3 amendment pair). This yields, per id, the LAST
122
+ * entry in the input's order: the amendment when there is one (so the amended
123
+ * payload — the real cost/tokens/output — is what readers see), the terminal entry
124
+ * for an ordinary run, the spawn entry for a run still in flight.
125
+ *
126
+ * ORDER: the output keeps each id's FIRST-seen position and drops repeats, so a
127
+ * caller's window (`slice(0, n)`) applied AFTER this projects runs, not entries.
128
+ * That is the contract — apply the projection BEFORE any window or cap, or a
129
+ * window can split one run's entries across its edge.
130
+ */
131
+ export function projectLogicalRuns(entries: SubagentRun[]): SubagentRun[] {
132
+ const lastById = new Map<string, SubagentRun>();
133
+ const order: string[] = [];
134
+ for (const entry of entries) {
135
+ if (!lastById.has(entry.id)) order.push(entry.id);
136
+ lastById.set(entry.id, entry);
137
+ }
138
+ return order.map((id) => lastById.get(id)!);
139
+ }
140
+
107
141
  /**
108
142
  * Run-history display projection (issue #259): ONE record per SETTLED run.
109
143
  *
@@ -111,7 +145,8 @@ export function resolveTerminalRunEntry(
111
145
  * "running") first, then the terminal entry at settle — so a raw entry list
112
146
  * renders every run twice and the spawn row shows a stale "running" forever.
113
147
  * This collapses each id to its terminal-preferred entry via the ONE shared
114
- * rule (`resolveTerminalRunEntry`). Runs still in flight (spawn entry, no
148
+ * rule (`resolveTerminalRunEntry`). Callers pass the LOGICAL list
149
+ * (`getLogicalRunEntries`) since #453, so an amended run is already one entry. Runs still in flight (spawn entry, no
115
150
  * terminal entry yet) are omitted: live state belongs to the monitor. U3 (D1)
116
151
  * carves ONE exception — an INTERRUPTED run (running + `interruptedAt`, per
117
152
  * `isInterruptedRun`) is surfaced, because the human must see it to recover or
@@ -217,6 +252,14 @@ export class SessionState {
217
252
  */
218
253
  private _finalizedLiveIds = new Set<string>();
219
254
 
255
+ /**
256
+ * The pending deferred-delete handle per finalized id (issue #423). Kept so
257
+ * a RE-registration can cancel it: a retry inside the 3 s window re-claims
258
+ * the id, and a stale delete would otherwise evict the fresh live row that
259
+ * the display surfaces just started rendering again.
260
+ */
261
+ private _finalizeTimers = new Map<string, ReturnType<typeof setTimeout>>();
262
+
220
263
  /** Loaded built-in presets */
221
264
  builtinPresets = new Array<import("./types").SubagentPreset>();
222
265
 
@@ -389,8 +432,13 @@ export class SessionState {
389
432
  // Run entry access
390
433
  // -------------------------------------------------------------------
391
434
 
392
- getRunEntries(ctx: ExtensionContext): SubagentRun[] {
393
- const runs = ctx.sessionManager
435
+ /**
436
+ * The RAW run-entry store, session order (oldest append first), uncapped.
437
+ * Two callers only: {@link getRunEntries} (the raw view) and
438
+ * {@link getLogicalRunEntries} (the one every aggregate reads).
439
+ */
440
+ private readRunEntries(ctx: ExtensionContext): SubagentRun[] {
441
+ return ctx.sessionManager
394
442
  .getEntries()
395
443
  .filter((e: { type: string; customType?: string }) =>
396
444
  e.type === "custom" && e.customType === CUSTOM_ENTRY_TYPES.run,
@@ -402,7 +450,32 @@ export class SessionState {
402
450
  return undefined;
403
451
  })
404
452
  .filter((r): r is SubagentRun => r !== undefined);
405
- return cleanupRuns(runs, this.config.maxHistoryEntries);
453
+ }
454
+
455
+ /**
456
+ * The RAW run-entry view, newest-first and capped at `maxHistoryEntries`
457
+ * ENTRIES. Not the display/aggregate view — a run has two entries (spawn +
458
+ * terminal) and a deadline-stopped one has three, so a consumer that counts,
459
+ * sums or windows these sees one run several times. It remains the right view
460
+ * for `findSpawnRunById` (which deliberately wants the SPAWN entry) and for
461
+ * raw-store bookkeeping.
462
+ */
463
+ getRunEntries(ctx: ExtensionContext): SubagentRun[] {
464
+ return cleanupRuns(this.readRunEntries(ctx), this.config.maxHistoryEntries);
465
+ }
466
+
467
+ /**
468
+ * Issue #453: the LOGICAL run-entry view — one entry per run id, carrying the
469
+ * amended payload when the deadline and a late settle both wrote (see
470
+ * {@link projectLogicalRuns}). Every aggregate/display consumer uses THIS:
471
+ * metrics, cost accounting, history, the reports and the dashboard.
472
+ *
473
+ * The projection runs BEFORE the cap, so `maxHistoryEntries` counts RUNS: an
474
+ * amended run cannot be half-kept, and its amendment can never be windowed
475
+ * away from the snapshot it amends.
476
+ */
477
+ getLogicalRunEntries(ctx: ExtensionContext): SubagentRun[] {
478
+ return cleanupRuns(projectLogicalRuns(this.readRunEntries(ctx)), this.config.maxHistoryEntries);
406
479
  }
407
480
 
408
481
  /**
@@ -422,7 +495,10 @@ export class SessionState {
422
495
  * `fullOutput`, `cost`, `durationMs`, `errorCategory`.
423
496
  */
424
497
  findTerminalRunById(ctx: ExtensionContext, id: string): SubagentRun | undefined {
425
- return resolveTerminalRunEntry(this.getRunEntries(ctx), id);
498
+ // #453 review: the LOGICAL view, not the raw capped list — at the
499
+ // `maxHistoryEntries` edge a raw read can return the deadline snapshot while
500
+ // every other surface shows the later amendment (the run's real payload).
501
+ return resolveTerminalRunEntry(this.getLogicalRunEntries(ctx), id);
426
502
  }
427
503
 
428
504
  // -------------------------------------------------------------------
@@ -430,6 +506,11 @@ export class SessionState {
430
506
  // -------------------------------------------------------------------
431
507
 
432
508
  registerLiveSubagent(id: string, data: Omit<LiveSubagent, "liveOutput" | "usage">): void {
509
+ // Issue #423: a registration means the id is live AGAIN — a retry
510
+ // re-registers inside the 3 s linger window, and every display surface
511
+ // filters finalized ids, so the claim (and its pending delete) must not
512
+ // survive the re-registration.
513
+ this.clearLiveFinalize(id);
433
514
  this.subagentSessions.set(id, { ...data, liveOutput: "", usage: { input: 0, output: 0 } });
434
515
  }
435
516
 
@@ -459,13 +540,30 @@ export class SessionState {
459
540
  // review: the poller must not decrement when the sweep already did).
460
541
  if (this._finalizedLiveIds.has(id)) return false;
461
542
  this._finalizedLiveIds.add(id);
462
- setTimeout(() => {
463
- this.subagentSessions.delete(id);
464
- this._finalizedLiveIds.delete(id);
465
- }, FINALIZE_RESET_WINDOW_MS);
543
+ this._finalizeTimers.set(
544
+ id,
545
+ setTimeout(() => {
546
+ this._finalizeTimers.delete(id);
547
+ this.subagentSessions.delete(id);
548
+ this._finalizedLiveIds.delete(id);
549
+ }, FINALIZE_RESET_WINDOW_MS),
550
+ );
466
551
  return true;
467
552
  }
468
553
 
554
+ /**
555
+ * Drop a pending finalize claim AND its deferred delete (issue #423). Called
556
+ * by {@link registerLiveSubagent} when an id is registered again.
557
+ */
558
+ private clearLiveFinalize(id: string): void {
559
+ const handle = this._finalizeTimers.get(id);
560
+ if (handle !== undefined) {
561
+ clearTimeout(handle);
562
+ this._finalizeTimers.delete(id);
563
+ }
564
+ this._finalizedLiveIds.delete(id);
565
+ }
566
+
469
567
  /** True when the live entry has been finalized (deferred delete pending). */
470
568
  isLiveEntryFinalized(id: string): boolean {
471
569
  return this._finalizedLiveIds.has(id);
@@ -509,6 +607,8 @@ export class SessionState {
509
607
  * would no-op on an id a stale claim still remembers (PR #71 review).
510
608
  */
511
609
  resetLiveFinalizeClaims(): void {
610
+ for (const handle of this._finalizeTimers.values()) clearTimeout(handle);
611
+ this._finalizeTimers.clear();
512
612
  this._finalizedLiveIds.clear();
513
613
  }
514
614
 
@@ -604,7 +704,9 @@ export class SessionState {
604
704
  * Sum the cost of all completed runs in the current session.
605
705
  */
606
706
  getSessionTotalCost(ctx: ExtensionContext): number {
607
- const runs = this.getRunEntries(ctx);
707
+ // Issue #453: one row per run — a deadline snapshot and its amendment both
708
+ // carry a full cost, so summing raw entries would charge the run twice.
709
+ const runs = this.getLogicalRunEntries(ctx);
608
710
  return runs.reduce((acc, r) => acc + (r.cost ?? 0), 0);
609
711
  }
610
712
 
@@ -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,9 @@ 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 { applyFrontmatterMappers, loadMarkdownRecords } from "./loader";
31
+ import type { FrontmatterFieldMapper, FrontmatterMapContext } from "./loader";
32
+ import { sanitizeFileName } from "./presets";
31
33
  import { pkgPath } from "./paths";
32
34
 
33
35
  // ---------------------------------------------------------------------------
@@ -173,10 +175,70 @@ export function validateTemplate(meta: Record<string, unknown>, fileName: string
173
175
  return errors;
174
176
  }
175
177
 
178
+ // ---------------------------------------------------------------------------
179
+ // Frontmatter → TaskTemplate mapping
180
+ // ---------------------------------------------------------------------------
181
+
182
+ /**
183
+ * Per-key return types: same shape as `PresetFieldMappers` (src/presets.ts), so
184
+ * a mapper that returns the wrong type — `timeout: () => "soon"` — fails at the
185
+ * row instead of at the assembly cast.
186
+ */
187
+ type TemplateFieldMappers = {
188
+ [K in keyof TaskTemplate]: FrontmatterFieldMapper<TaskTemplate[K]>;
189
+ };
190
+
191
+ /**
192
+ * THE declaration of which frontmatter keys reach a `TaskTemplate` — every
193
+ * field (no omission allowlist), so a new declared field is a missing-key
194
+ * compile error and a stale key is an excess-property error.
195
+ *
196
+ * `task` comes from the markdown body (multiline by construction), and
197
+ * `timeout` is the one numeric coercion: frontmatter values are strings.
198
+ */
199
+ const TEMPLATE_FIELD_MAPPERS = {
200
+ name: (_meta, ctx) => ctx.name,
201
+ description: (meta) => (meta.description as string) || undefined,
202
+ task: (_meta, ctx) => ctx.body,
203
+ preset: (meta) => (meta.preset as string) || undefined,
204
+ thinkingLevel: (meta) => (meta.thinkingLevel as string) || undefined,
205
+ outputFile: (meta) => (meta.outputFile as string) || undefined,
206
+ timeout: (meta) => (meta.timeout !== undefined ? Number(meta.timeout) : undefined),
207
+ tools: (meta) => (Array.isArray(meta.tools) ? (meta.tools as string[]) : undefined),
208
+ excludeTools: (meta) =>
209
+ Array.isArray(meta.excludeTools) ? (meta.excludeTools as string[]) : undefined,
210
+ noBuiltinTools: (meta) => (meta.noBuiltinTools === "true" ? true : undefined),
211
+ inheritSystemPrompt: (meta) =>
212
+ (meta.inheritSystemPrompt === "false" ? false : undefined),
213
+ } satisfies TemplateFieldMappers;
214
+
176
215
  // ---------------------------------------------------------------------------
177
216
  // Loading
178
217
  // ---------------------------------------------------------------------------
179
218
 
219
+ /**
220
+ * Normalise validated template frontmatter into a TaskTemplate. Shared by both
221
+ * template tiers — the file walk and validation live in loadMarkdownRecords.
222
+ */
223
+ function templateFromFrontmatter(
224
+ meta: Record<string, unknown>,
225
+ body: string,
226
+ name: string,
227
+ ): TaskTemplate {
228
+ const ctx: FrontmatterMapContext = { name, body };
229
+ return applyFrontmatterMappers<TaskTemplate>(TEMPLATE_FIELD_MAPPERS, meta, ctx);
230
+ }
231
+
232
+ /**
233
+ * Reject empty/whitespace-only bodies at load: shipping task: "" would later
234
+ * trip mode-detection with the confusing "Provide exactly one of:
235
+ * task/chain/..." error instead of a load-time warn-and-skip (parseFrontmatter
236
+ * already trims the body).
237
+ */
238
+ function templateBodyError(meta: Record<string, unknown>, body: string): string | null {
239
+ return body.trim() ? null : `Template "${meta.name}" has empty task body`;
240
+ }
241
+
180
242
  /**
181
243
  * Load custom task templates from user directories. Templates are
182
244
  * file-backed, mirroring the custom-preset pattern (issue #66) — the TUI
@@ -197,73 +259,25 @@ export function validateTemplate(meta: Record<string, unknown>, fileName: string
197
259
  * missing directories are skipped silently.
198
260
  */
199
261
  export function loadCustomTemplates(cwd: string, log?: Logger): TaskTemplate[] {
200
- const templates: TaskTemplate[] = [];
201
- const seenNames = new Set<string>();
202
262
  const homedir = process.env.HOME || process.env.USERPROFILE || "";
203
263
 
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;
264
+ return loadMarkdownRecords<TaskTemplate>({
265
+ dirs: [
266
+ path.join(cwd, ".pi", "brl-subagent", "templates"),
267
+ path.join(homedir, ".pi", "agent", "brl-subagent", "templates"),
268
+ ],
269
+ validate: validateTemplate,
270
+ map: templateFromFrontmatter,
271
+ bodyError: templateBodyError,
272
+ // Dedup by name: the first occurrence (project-local, scanned first) wins.
273
+ dedupeByName: true,
274
+ log,
275
+ messages: {
276
+ invalid: "Custom template validation failed",
277
+ readFailed: "Failed to load custom template file",
278
+ },
279
+ // A missing directory is fine — no custom templates in that tier.
280
+ });
267
281
  }
268
282
 
269
283
  /**
@@ -274,62 +288,19 @@ export function loadCustomTemplates(cwd: string, log?: Logger): TaskTemplate[] {
274
288
  * loadBuiltinPresets (src/presets.ts).
275
289
  */
276
290
  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 {
291
+ return loadMarkdownRecords<TaskTemplate>({
292
+ dirs: [templatesDir],
293
+ validate: validateTemplate,
294
+ map: templateFromFrontmatter,
295
+ bodyError: templateBodyError,
296
+ log,
297
+ messages: {
298
+ invalid: "Builtin template validation failed",
299
+ readFailed: "Failed to load builtin template file",
300
+ },
328
301
  // 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;
302
+ onMissingDir: (dir) => log?.info("No built-in templates directory found", { dir }),
303
+ });
333
304
  }
334
305
 
335
306
  // ---------------------------------------------------------------------------
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
  /**