brl-subagent 2.9.0 → 2.9.2

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,295 @@
1
+ // Purpose: Resolve, contain and verify the conductor-named background guard (#620).
2
+ /**
3
+ * A background delegation builds its own resource loader with extension
4
+ * discovery OFF, because background sessions have no trust prompt and would
5
+ * otherwise import model-chosen code into the conductor's process (F1). The
6
+ * side effect was that the repository's own policy guard never loaded either,
7
+ * so rule #5 had no mechanical enforcement for the DEFAULT dispatch shape
8
+ * (#620; a live probe wrote the cockpit's `src/` by absolute path).
9
+ *
10
+ * The fix keeps `noExtensions: true` and adds exactly ONE absolute entry to
11
+ * `additionalExtensionPaths` — a path the loader imports (one mechanism, one
12
+ * module instance) that our shipped `src/` never imports itself. That makes
13
+ * three properties load-bearing, and this module owns all three so they cannot
14
+ * drift apart:
15
+ *
16
+ * 1. THE NAME IS NOT A PATH. `brl-subagent.backgroundGuard` is a single path
17
+ * component, validated against `GUARD_NAME_RE`, resolved to
18
+ * `<projectRoot>/.pi/extensions/<name>/index.ts`. A relative name, a
19
+ * separator, `.`/`..` and an absolute name have no spelling that passes.
20
+ * 2. THE RESOLVED FILE MUST BE INSIDE THE PROJECT. A relative
21
+ * `additionalExtensionPath` resolves against the loader's cwd — the
22
+ * CHILD's, which the model chooses (F5) — so the entry must be absolute, and
23
+ * an absolute entry is only safe if it is contained. Both the root and the
24
+ * file are realpathed and compared with a `sep`-anchored prefix, so a
25
+ * symlink resolving out of the project is a named refusal, never a silent
26
+ * load. A bare `startsWith` would accept `<root>-evil/…`.
27
+ * 3. LOADING IS NOT REGISTRATION. `reload()` never throws; a load failure or a
28
+ * factory that registers nothing lands in `getExtensions()` (F9). So
29
+ * "required" is only real if the handlers are read back, which
30
+ * `verifyGuardLoaded` does for the two handlers the guard exists to
31
+ * provide.
32
+ *
33
+ * Every refusal is a thrown `Error` whose message starts `background guard:`
34
+ * and names the setting plus the concrete cause, and it is thrown BEFORE
35
+ * `createAgentSession` — so a refused spawn leaves no agent record and no run
36
+ * entry, and the pipeline's existing `catch` renders it as an ordinary
37
+ * "Failed to spawn background agent: …" result.
38
+ *
39
+ * The manifest read itself stays in `project-flags.ts` (re-exported here): that
40
+ * module is the ONE reader of the `brl-subagent` section, and its ratchet test
41
+ * fails a second one.
42
+ */
43
+
44
+ import { realpathSync, statSync } from "node:fs";
45
+ import { join, resolve, sep } from "node:path";
46
+ import { readBackgroundGuard, readProcessChecks } from "./project-flags";
47
+
48
+ export { readBackgroundGuard };
49
+
50
+ /**
51
+ * The value that turns the setting OFF while keeping the key — what a project writes
52
+ * after opting out of a guard it once required.
53
+ */
54
+ export const GUARD_DISABLED = "none";
55
+
56
+ /**
57
+ * A guard name is ONE path component: it starts alphanumeric (so `.`, `..` and a
58
+ * leading dot are all impossible) and contains no separator, so no name can
59
+ * escape the extension directory it is resolved under. Deliberately narrower
60
+ * than a filename: a guard directory is a package-shaped unit.
61
+ */
62
+ const GUARD_NAME_RE = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
63
+
64
+ /**
65
+ * The two handlers a required guard must register. `tool_call` is the
66
+ * enforcement; `before_agent_start` is the reminder that covers the `bash`
67
+ * blind spot — a guard without the second is a guard whose silence looks like
68
+ * compliance.
69
+ */
70
+ export const REQUIRED_GUARD_HANDLERS = ["tool_call", "before_agent_start"] as const;
71
+
72
+ /** The project-wide symbol key a loaded guard registers itself under (see `.pi/extensions/worktree-guard`). */
73
+ export const LOADED_GUARDS_SYMBOL_KEY = "brl-subagent.loaded-guards";
74
+
75
+ /** The setting's name as it is written in `package.json` — every message names it. */
76
+ const SETTING = "brl-subagent.backgroundGuard";
77
+
78
+ function refusal(cause: string): Error {
79
+ return new Error(`background guard: ${SETTING} ${cause}`);
80
+ }
81
+
82
+ /**
83
+ * The guard this project REQUIRES, or `null` for "off". The `"none"` sentinel is
84
+ * folded here — the one place — so the spawn seam and the conductor-start
85
+ * warning cannot disagree about what "off" means.
86
+ */
87
+ export function readRequiredGuard(cwd: string | undefined): string | null {
88
+ const named = readBackgroundGuard(cwd);
89
+ return named === null || named === GUARD_DISABLED ? null : named;
90
+ }
91
+
92
+ /** `realpath` of `path`, or `null` when it does not exist (the caller names the cause). */
93
+ function resolveExisting(path: string): string | null {
94
+ try {
95
+ return realpathSync(path);
96
+ } catch {
97
+ return null;
98
+ }
99
+ }
100
+
101
+ /**
102
+ * Resolve `name` to the absolute, realpathed path of the guard's entry module
103
+ * under `projectRoot`, or throw a named refusal.
104
+ *
105
+ * The returned path is used VERBATIM as the loader entry: it is already
106
+ * canonical and absolute, which is the only shape that cannot be re-resolved
107
+ * against the child's cwd (F5).
108
+ */
109
+ export function resolveGuardPath(projectRoot: string, name: string): string {
110
+ if (!GUARD_NAME_RE.test(name)) {
111
+ throw refusal(
112
+ `names "${name}", which is not a single path component (letters, digits, dot, dash and underscore; no separator, no leading dot) — refusing to resolve it`,
113
+ );
114
+ }
115
+ const realRoot = resolveExisting(projectRoot);
116
+ if (realRoot === null) {
117
+ throw refusal(
118
+ `names "${name}", but the project root ${projectRoot} does not exist — cannot resolve it`,
119
+ );
120
+ }
121
+ const candidate = join(realRoot, ".pi", "extensions", name, "index.ts");
122
+ const realGuard = resolveExisting(candidate);
123
+ if (realGuard === null) {
124
+ throw refusal(
125
+ `names "${name}", but ${candidate} does not exist — the named guard was not found (a missing, renamed or mis-spelled guard is a refusal, not a silent spawn)`,
126
+ );
127
+ }
128
+ let isFile: boolean;
129
+ try {
130
+ isFile = statSync(realGuard).isFile();
131
+ } catch (error) {
132
+ throw refusal(`names "${name}", but ${candidate} cannot be read — ${(error as Error).message}`);
133
+ }
134
+ if (!isFile) throw refusal(`names "${name}", but ${candidate} is not a file — the guard entry point must be a module`);
135
+ // `sep`-anchored containment: a bare `startsWith(realRoot)` also accepts a
136
+ // sibling named `<root>-something`, which is the escape this check exists for.
137
+ if (realGuard !== realRoot && !realGuard.startsWith(realRoot + sep)) {
138
+ throw refusal(
139
+ `names "${name}", but ${candidate} resolves to ${realGuard}, which is OUTSIDE the project root ${realRoot} — a symlink may not carry the guard out of the project`,
140
+ );
141
+ }
142
+ return realGuard;
143
+ }
144
+
145
+ /** The minimal shape `verifyGuardLoaded` reads — one small interface, so the caller is not coupled to the SDK class. */
146
+ export interface GuardLoaderView {
147
+ getExtensions(): {
148
+ readonly extensions?: readonly GuardExtensionView[];
149
+ readonly errors?: readonly { readonly path: string; readonly error: string }[];
150
+ };
151
+ }
152
+
153
+ /** An extension as the loader reports it: its advertised paths and its registered handlers. */
154
+ export interface GuardExtensionView {
155
+ readonly path?: string;
156
+ readonly resolvedPath?: string;
157
+ readonly sourceInfo?: { readonly path?: string };
158
+ readonly handlers?: ReadonlyMap<string, readonly unknown[]>;
159
+ }
160
+
161
+ /** Every path an extension advertises, canonicalized; used only for identity comparison. */
162
+ function extensionPaths(extension: GuardExtensionView): string[] {
163
+ const advertised = [extension.sourceInfo?.path, extension.resolvedPath, extension.path];
164
+ return advertised.filter((p): p is string => typeof p === "string" && p !== "");
165
+ }
166
+
167
+ /** Two spellings of one file: canonical when it exists, absolute-lexical otherwise. */
168
+ function samePath(left: string, right: string): boolean {
169
+ const a = resolveExisting(left) ?? resolve(left);
170
+ const b = resolveExisting(right) ?? resolve(right);
171
+ return a === b;
172
+ }
173
+
174
+ /**
175
+ * Prove the named guard is loaded AND registered both handlers, or throw.
176
+ *
177
+ * Three failure shapes, each named, because they are three different fixes:
178
+ * - a loader `errors` entry for the guard file (syntax error, bad export, a
179
+ * throwing factory) — the module never became an extension (F9);
180
+ * - no extension advertises that path at all — the loader silently skipped it;
181
+ * - the extension is there but a handler is missing — `{ block }` will never be
182
+ * produced, which is the silent-success shape of F9/#620.
183
+ */
184
+ export function verifyGuardLoaded(loader: GuardLoaderView, guardPath: string): void {
185
+ let reported: ReturnType<GuardLoaderView["getExtensions"]>;
186
+ try {
187
+ reported = loader.getExtensions();
188
+ } catch (error) {
189
+ throw refusal(`resolved ${guardPath}, but the resource loader could not report its extensions: ${(error as Error).message}`);
190
+ }
191
+ const errors = reported.errors ?? [];
192
+ const failed = errors.find((entry) => samePath(entry.path, guardPath));
193
+ if (failed !== undefined) {
194
+ throw refusal(`resolved ${guardPath}, but it FAILED TO LOAD: ${failed.error}`);
195
+ }
196
+ const loaded = (reported.extensions ?? []).find((extension) =>
197
+ extensionPaths(extension).some((advertised) => samePath(advertised, guardPath)),
198
+ );
199
+ if (loaded === undefined) {
200
+ throw refusal(
201
+ `resolved ${guardPath}, but the resource loader did not load it as an extension — no registered guard means no enforcement`,
202
+ );
203
+ }
204
+ const missing = REQUIRED_GUARD_HANDLERS.filter((handler) => {
205
+ const registered = loaded.handlers?.get(handler);
206
+ return registered === undefined || registered.length === 0;
207
+ });
208
+ if (missing.length > 0) {
209
+ throw refusal(
210
+ `resolved ${guardPath} and loaded it, but it registered no ${missing.join(" and no ")} handler — a required guard must register both: the block enforces, the reminder covers the shell blind spot`,
211
+ );
212
+ }
213
+ }
214
+
215
+ /**
216
+ * The loaded-guard marker's shape: guard directory basename → how many LIVE
217
+ * registrations this process holds. It is the ONLY channel from a loaded
218
+ * extension back to the conductor's start-up warning, and nothing else in this
219
+ * repository uses a global (ADR 0029).
220
+ *
221
+ * A COUNT, not a set, because more than one loader can import the same guard in
222
+ * one process (the conductor's own runtime, plus every background delegation). A
223
+ * plain set would be erased by whichever instance shut down first — a background
224
+ * child's shutdown would blank the conductor's marker, and `/reload` would blank
225
+ * it for the instant between the old runner's shutdown and the new load. The guard
226
+ * factory increments AFTER its handlers are armed; its `session_shutdown` handler
227
+ * decrements and deletes at zero (`/reload` emits shutdown to the OLD runner, so
228
+ * the pair nets to unchanged).
229
+ *
230
+ * A guard that never arms cannot write it, which is exactly what makes its
231
+ * absence meaningful. Missing or foreign marker ⇒ empty counts (never a throw):
232
+ * the warning is a sensor, not a new fault.
233
+ */
234
+ export function readLoadedGuardCounts(): ReadonlyMap<string, number> {
235
+ const marker = (globalThis as Record<symbol, unknown>)[Symbol.for(LOADED_GUARDS_SYMBOL_KEY)];
236
+ if (!(marker instanceof Map)) return new Map<string, number>();
237
+ const counts = new Map<string, number>();
238
+ for (const [name, count] of marker as Map<unknown, unknown>) {
239
+ // A foreign writer may leave anything under the key; only a positive count names a guard.
240
+ if (typeof name === "string" && typeof count === "number" && count > 0) counts.set(name, count);
241
+ }
242
+ return counts;
243
+ }
244
+
245
+ /**
246
+ * The names whose count is positive — "present" for every caller that only asks
247
+ * whether a guard is armed. Derived from {@link readLoadedGuardCounts} so the two
248
+ * can never disagree about what presence means.
249
+ */
250
+ export function readLoadedGuards(): ReadonlySet<string> {
251
+ return new Set(readLoadedGuardCounts().keys());
252
+ }
253
+
254
+ /**
255
+ * The conductor-start warning text, or `null` when there is nothing to say.
256
+ *
257
+ * SILENT unless all three hold: process checks are on for this project, a guard
258
+ * is named (not absent, not `"none"`), and that name is missing from the
259
+ * loaded-guard marker. The silence for `"none"`/absent is the contract — a
260
+ * project that did not opt in must never see our process machinery.
261
+ */
262
+ export function missingGuardWarning(cwd: string | undefined): string | null {
263
+ const named = readRequiredGuard(cwd);
264
+ if (named === null) return null;
265
+ if (!readProcessChecks(cwd)) return null;
266
+ if ((readLoadedGuardCounts().get(named) ?? 0) > 0) return null;
267
+ // The consequence must be the TRUE one (review of PR #627, F1): a background
268
+ // delegation loads this guard EXPLICITLY from its absolute path, so it is
269
+ // guarded whether or not this conductor's own session is. What is missing is
270
+ // the conductor's own enforcement, and that is what the text must say.
271
+ return (
272
+ `${SETTING} names "${named}", but no extension named "${named}" registered its handlers in this process, ` +
273
+ `so THIS conductor session is not guarded — its own write/edit calls are not checked. ` +
274
+ `Background delegations are still guarded: each one loads .pi/extensions/${named}/index.ts explicitly. ` +
275
+ `To guard this session too, enable project extensions and trust this project (or remove the setting).`
276
+ );
277
+ }
278
+
279
+ /**
280
+ * `missingGuardWarning`, latched: the returned closure answers on the first
281
+ * `session_start` that has something to say and `null` forever after. The latch
282
+ * is per closure, and the composition root builds one per extension invocation —
283
+ * so it is once per process for the surface that matters, and never twice for one.
284
+ * One flag, no repeats — the warning exists to end a silence, not to fill the log
285
+ * on every session switch.
286
+ */
287
+ export function createGuardStartNotice(): (cwd: string | undefined) => string | null {
288
+ let emitted = false;
289
+ return (cwd) => {
290
+ if (emitted) return null;
291
+ const warning = missingGuardWarning(cwd);
292
+ if (warning !== null) emitted = true;
293
+ return warning;
294
+ };
295
+ }
@@ -66,6 +66,7 @@ import {
66
66
  type DelegateTaskParams,
67
67
  type GitMode,
68
68
  type RecoveryMode,
69
+ type RetryCause,
69
70
  type SubagentResult,
70
71
  type SubagentRun,
71
72
  type SubagentToolOptions,
@@ -140,6 +141,9 @@ interface BackgroundAgentSpawnRequest {
140
141
  dispatchId?: string;
141
142
  resumeOf?: string;
142
143
  attempt?: number;
144
+ // Issue #616: why this attempt exists — stated by the MINT SITE, never
145
+ // inferred from the source run's failure class.
146
+ retryCause?: RetryCause;
143
147
  // Option B U3 (D4): recovery posture snapshot for the background run.
144
148
  recoveryPosture?: RecoveryMode;
145
149
  }
@@ -170,6 +174,12 @@ interface BackgroundPipeline {
170
174
  singleTask: string,
171
175
  retrySourceRun?: SubagentRun,
172
176
  attemptContext?: string,
177
+ /**
178
+ * Issue #616: WHY this spawn is a retry. `scheduleTransportRetry` passes
179
+ * `"transport"`; a caller-driven `retryRunId` retry passes `"manual"`.
180
+ * Omitted for a fresh dispatch. Never derived from the source record.
181
+ */
182
+ retryCause?: RetryCause,
173
183
  ) => Promise<ToolResult<undefined>>;
174
184
  }
175
185
 
@@ -520,6 +530,9 @@ export function createBackgroundPipeline(
520
530
  attempt: spawn.attempt,
521
531
  // Option B U3 (D4): recovery posture snapshot for the background run.
522
532
  recoveryPosture: spawn.recoveryPosture,
533
+ // Issue #616: the retry cause rides the spawn onto the agent record, the
534
+ // run entry and the registry entry.
535
+ retryCause: spawn.retryCause,
523
536
  });
524
537
 
525
538
  // -----------------------------------------------------------------
@@ -835,6 +848,10 @@ export function createBackgroundPipeline(
835
848
  * cannot be steered by the preamble's wording.
836
849
  */
837
850
  attemptContext?: string,
851
+ /** Issue #616: WHY this spawn is a retry — stated by the caller, never
852
+ * inferred. `"transport"` from `scheduleTransportRetry`, `"manual"` from a
853
+ * caller-driven retry; omitted for a fresh dispatch. */
854
+ retryCause?: RetryCause,
838
855
  ): Promise<ToolResult<undefined>> {
839
856
  // Issue #443: the DECLARED level, guarded before `bgResolved` clamps it.
840
857
  // This is the seam for the TRANSPORT auto-retry (`scheduleTransportRetry`
@@ -939,7 +956,7 @@ export function createBackgroundPipeline(
939
956
  );
940
957
 
941
958
  // Option B U1: durability identity (retry inherits the original dispatch).
942
- const bgIdentity = newDispatchIdentity(retrySourceRun);
959
+ const bgIdentity = newDispatchIdentity(retrySourceRun, retryCause);
943
960
  const spawned = await startBackgroundAgent(pi, ctx, {
944
961
  // Issue #411: the preamble rides the system-prompt side
945
962
  // (`resumeContext`), never the task. The task stays the recorded
@@ -964,6 +981,7 @@ export function createBackgroundPipeline(
964
981
  dispatchId: bgIdentity.dispatchId,
965
982
  resumeOf: bgIdentity.resumeOf,
966
983
  attempt: bgIdentity.attempt,
984
+ retryCause: bgIdentity.retryCause,
967
985
  recoveryPosture: state.config.recovery,
968
986
  });
969
987
 
@@ -109,21 +109,53 @@ export function createBootRecovery(rt: RuntimeContext): BootRecovery {
109
109
  // pid-only liveness cannot rule out pid reuse, so nothing is killed or
110
110
  // marked unverified.
111
111
  async function performBootRecovery(): Promise<void> {
112
+ // Issue #546 (major 6): the whole session-manager wiring — the record-flip
113
+ // applier included — is built at the EXISTING lazy import site and in its own
114
+ // containment. A failure there leaves `wiring` undefined: the scan still runs
115
+ // over the run registry, and `applyRecordFlip`/`readFreshAgentRecord` are not
116
+ // passed at all, so the scan takes its no-applier branch (the pre-#546
117
+ // behaviour: markers untouched). No half-wired repair is possible.
118
+ //
119
+ // The import must stay DYNAMIC: a static named import of a lifecycle mutator
120
+ // violates the reader-API rule in architecture-rules.test.ts (the allow-list
121
+ // is `getAgent`/`listAgents`; a dynamic `import()` edge carries no names
122
+ // there), and it would load session-manager on every extension start.
123
+ let sm: typeof import("./session-manager") | undefined;
124
+ try {
125
+ sm = await import("./session-manager");
126
+ } catch (err) {
127
+ log.warn("Boot recovery: session-manager unavailable — running the registry-only scan", {
128
+ error: (err as Error).message,
129
+ });
130
+ }
131
+ const wiring = sm;
132
+ // Issue #554: a SIGKILL cannot run the atomic writer's cleanup, so `.tmp`
133
+ // siblings accumulate in the agent store. Bound them at boot, beside the
134
+ // other store-hygiene steps. Only temps older than an hour are removed, so
135
+ // a live writer's temp always survives; the sweep never throws, and the
136
+ // line is emitted only when something was actually reclaimed.
137
+ if (wiring) {
138
+ try {
139
+ const sweptTemps = wiring.sweepAgentRecordTemps();
140
+ if (sweptTemps > 0) log.info("Boot recovery swept stale agent-record temps", { count: sweptTemps });
141
+ } catch (err) {
142
+ log.warn("Boot recovery temp sweep failed", { error: (err as Error).message });
143
+ }
144
+ }
112
145
  try {
113
- const { getAgent, markAgentInterrupted } = await import("./session-manager");
114
146
  // `recoverProduction` owns the /proc platform guard (nothing is marked or
115
147
  // killed without start-token verification) — see src/recovery.ts.
116
148
  const summary = await recoverProduction({
117
149
  log,
118
150
  // Read THAT ONE agent record by id — never the whole store.
119
- readAgentRecord: (id) => getAgent(id),
151
+ readAgentRecord: wiring ? (id) => wiring.getAgent(id) : undefined,
120
152
  mark(record, interruptedAt) {
121
153
  // Registry entry = the durable mark for every kind. Issue #304: its
122
154
  // boolean is the durable-write result — do NOT drop it, or the boot
123
155
  // summary would claim a mark that never landed. The scan counts a
124
156
  // `false` as `markFailures` and warns with the id.
125
157
  const durable = markInterrupted(record.id, interruptedAt);
126
- if (record.kind === "agent") markAgentInterrupted(record.id, interruptedAt);
158
+ if (record.kind === "agent") wiring?.markAgentInterrupted(record.id, interruptedAt);
127
159
  return durable;
128
160
  },
129
161
  // Issue #447: a dispatch whose acceptance marker is still `null` never
@@ -133,6 +165,24 @@ export function createBootRecovery(rt: RuntimeContext): BootRecovery {
133
165
  finalizeNeverStarted: (run) => {
134
166
  state.persistRun(pi, run);
135
167
  },
168
+ ...(wiring
169
+ ? {
170
+ // Issue #546 (major 3): the pre-flip read is DISK-ONLY — `getAgent`
171
+ // is memory-first and a stale map would re-stamp a settled record.
172
+ readFreshAgentRecord: (id: string) => wiring.readAgentRecordFromDisk(id),
173
+ // Issue #546: the terminal write whose process died before the
174
+ // agent record was flipped. The two writes belong together — the
175
+ // registry entry IS the marker, so it may be retired only once
176
+ // the flip is durable. The outcome is passed through, and a
177
+ // settlement that did not land (record write OR unlink, major 4)
178
+ // keeps the entry for the next boot.
179
+ applyRecordFlip: (verdict) => {
180
+ const outcome = wiring.flipAgentRecord(verdict.id, verdict.status, verdict.error);
181
+ if (outcome === false) return false;
182
+ return clearInflightRun(verdict.id) ? outcome : false;
183
+ },
184
+ }
185
+ : {}),
136
186
  });
137
187
  // Report the scan whenever it did anything durable OR attempted a mark
138
188
  // that failed — a failure-only boot must not be silent (issue #304).
@@ -141,6 +191,19 @@ export function createBootRecovery(rt: RuntimeContext): BootRecovery {
141
191
  }
142
192
  // Issue #447: never-started dispatches are finalized, not marked — a
143
193
  // separate line so the two outcomes cannot be read as one another.
194
+ // Issue #546: record flips a dead process left pending. A separate line
195
+ // from both the interrupted marks and the never-started finalizes — this
196
+ // outcome rewrites the AGENT RECORD, which neither of those does.
197
+ if (summary.flipRepaired > 0 || summary.flipRetired > 0 || summary.flipFailures > 0) {
198
+ log.warn("Boot recovery settled pending record flips", {
199
+ repaired: summary.flipRepaired,
200
+ retired: summary.flipRetired,
201
+ failures: summary.flipFailures,
202
+ // Issue #554: the corrupt SUBSET of `failures`, present only when
203
+ // non-zero — with none, this object is byte-identical to today's.
204
+ ...(summary.flipCorrupt > 0 ? { corrupt: summary.flipCorrupt } : {}),
205
+ });
206
+ }
144
207
  if (summary.neverStarted > 0) {
145
208
  log.info("Boot recovery finalized never-started dispatches", {
146
209
  count: summary.neverStarted,