brl-subagent 2.9.2 → 2.9.3

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/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  > Multi-agent orchestration for [pi](https://github.com/earendil-works/pi) — chain, parallel, and dependency-graph delegation to isolated subagents with per-step model routing, preset-driven tool scoping, thinking-level control, and background execution with live monitoring, real abort, and per-agent timeouts.
4
4
 
5
- **Version:** 2.9.2 · **Author:** Azmeen Afandi / [Beeroo Labs](https://beeroolabs.com) · **License:** MIT
5
+ **Version:** 2.9.3 · **Author:** Azmeen Afandi / [Beeroo Labs](https://beeroolabs.com) · **License:** MIT
6
6
 
7
7
  ---
8
8
 
@@ -14,7 +14,7 @@
14
14
  - **True background execution** — live monitor, real abort (`stop_subagent`), per-agent timeouts, and a 30-minute default deadline for runs that don't set one. Nothing orphans; nothing leaks.
15
15
  - **Preset-driven tool scoping** — every subagent runs with exactly the tools its job needs, restricted by preset or per-call `tools`/`excludeTools`, with auto-route that picks the right preset when you don't.
16
16
  - **Templates with slots** — saved, file-backed task templates with `${param}` placeholders for workflows you run again and again.
17
- - **Safety by default** — task-fence injection protection, sanitized error paths, owner-only persistence (`0o700` stores, `0o600` files; the directory mode is repaired on every write and is the confidentiality boundary), and a 3700+ test suite pinning every contract against the real pi SDK.
17
+ - **Safety by default** — task-fence injection protection, sanitized error paths, owner-only persistence (`0o700` stores, `0o600` files; the directory mode is repaired on every write and is the confidentiality boundary), and a 3600+ test suite pinning every contract against the real pi SDK.
18
18
 
19
19
  ---
20
20
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "brl-subagent",
3
- "version": "2.9.2",
3
+ "version": "2.9.3",
4
4
  "description": "Subagent delegation for pi — blocking or background runs, chain/parallel/graph modes, presets and task templates, live monitor, and dispatch capability guards.",
5
5
  "keywords": [
6
6
  "pi-package"
@@ -15,6 +15,7 @@
15
15
  "presets/",
16
16
  "templates/",
17
17
  "README.md",
18
+ "CHANGELOG.md",
18
19
  "LICENSE",
19
20
  "AGENT.md",
20
21
  "!src/__tests__/"
@@ -22,7 +23,8 @@
22
23
  "pi": {
23
24
  "extensions": [
24
25
  "./src/index.ts"
25
- ]
26
+ ],
27
+ "changelogPath": "./CHANGELOG.md"
26
28
  },
27
29
  "brl-subagent": {
28
30
  "processChecks": true,
@@ -35,17 +37,17 @@
35
37
  "docs:decisions": "node scripts/docs-decisions.mjs --write"
36
38
  },
37
39
  "peerDependencies": {
38
- "@earendil-works/pi-agent-core": "*",
39
- "@earendil-works/pi-ai": "*",
40
- "@earendil-works/pi-coding-agent": "*",
41
- "@earendil-works/pi-tui": "*",
40
+ "@earendil-works/pi-agent-core": ">=1.8.0",
41
+ "@earendil-works/pi-ai": ">=1.8.0",
42
+ "@earendil-works/pi-coding-agent": ">=1.8.0",
43
+ "@earendil-works/pi-tui": ">=1.8.0",
42
44
  "typebox": "*"
43
45
  },
44
46
  "devDependencies": {
45
- "@earendil-works/pi-agent-core": "^1.7.0",
46
- "@earendil-works/pi-ai": "^1.7.0",
47
- "@earendil-works/pi-coding-agent": "^1.7.0",
48
- "@earendil-works/pi-tui": "^1.7.0",
47
+ "@earendil-works/pi-agent-core": "^1.8.0",
48
+ "@earendil-works/pi-ai": "^1.8.0",
49
+ "@earendil-works/pi-coding-agent": "^1.8.0",
50
+ "@earendil-works/pi-tui": "^1.8.0",
49
51
  "jiti": "^2.7.0",
50
52
  "typebox": "1.3.27",
51
53
  "typescript": "7.0.2",
@@ -170,7 +170,7 @@ interface BackgroundPipeline {
170
170
  spawnBackgroundRun: (
171
171
  pi: ExtensionAPI,
172
172
  ctx: ExtensionContext,
173
- params: (DelegateTaskParams & { noJev?: string }) | ReturnType<typeof resolveRetryParams>,
173
+ params: DelegateTaskParams | ReturnType<typeof resolveRetryParams>,
174
174
  singleTask: string,
175
175
  retrySourceRun?: SubagentRun,
176
176
  attemptContext?: string,
@@ -334,7 +334,6 @@ export function createBackgroundPipeline(
334
334
  outputFile: merged.outputFile,
335
335
  force: params.force as boolean | undefined,
336
336
  cwd: targets.cwd,
337
- noJev: params.noJev,
338
337
  },
339
338
  });
340
339
  if (preTask.error) return preTask.error;
@@ -833,7 +832,7 @@ export function createBackgroundPipeline(
833
832
  * the two shapes disagree on, and claiming the recorded value was
834
833
  * schema-validated would be a lie: records are read back from disk.
835
834
  */
836
- params: (DelegateTaskParams & { noJev?: string }) | ReturnType<typeof resolveRetryParams>,
835
+ params: DelegateTaskParams | ReturnType<typeof resolveRetryParams>,
837
836
  singleTask: string,
838
837
  // Option B U1: the spawn entry a retryRunId resolved to, so a retried
839
838
  // background run inherits dispatchId/resumeOf/attempt (record identity,
@@ -939,7 +938,6 @@ export function createBackgroundPipeline(
939
938
  outputFile: bgResolvedOutputFile,
940
939
  force: params.force,
941
940
  cwd: targets.cwd,
942
- noJev: params.noJev,
943
941
  },
944
942
  });
945
943
  if (bgPreTask.error) return bgPreTask.error;
@@ -111,7 +111,7 @@ import {
111
111
  import { delegateTaskParamsSchema } from "./schema";
112
112
  import { readProcessChecks } from "./project-flags";
113
113
  import { buildSubagentPrompt, describePromptMode } from "./prompt";
114
- import { runSubagent } from "./runner";
114
+ import { runSubagent, usageGroupsFrom } from "./runner";
115
115
  import { currentProcessOwner, newDispatchIdentity } from "./recovery";
116
116
  import { writeHeadState, clearHeadState, HEAD_STATE_VERSION } from "./headstate";
117
117
  import { clearInflightRun } from "./run-registry";
@@ -972,7 +972,7 @@ interface ForegroundPrepared {
972
972
  *
973
973
  * `force` degrades a capability error to a warning (B2's override) — the flag
974
974
  * is read off `params` here because it is a CALL-level decision, not a resolved
975
- * value; `cwd`/`noJev` likewise reach H1 straight from the dispatch.
975
+ * value; `cwd` likewise reaches H1 straight from the dispatch.
976
976
  */
977
977
  function prepareForeground(
978
978
  params: DelegateTaskParams,
@@ -1078,7 +1078,6 @@ function prepareForeground(
1078
1078
  outputFile: resolvedOutputFile,
1079
1079
  force: params.force,
1080
1080
  cwd: resolvedCwd,
1081
- noJev: params.noJev,
1082
1081
  });
1083
1082
  if (validation.warnings.length > 0) {
1084
1083
  log.warn("Pre-task validation warnings", { warnings: validation.warnings });
@@ -1802,7 +1801,9 @@ function terminalizePreStartRejection(
1802
1801
  };
1803
1802
  finalizeRunRecord(run, rejection, "", new Date(run.startedAt).getTime());
1804
1803
  run.originalParams = { ...run.originalParams, errorCategory: rejection.errorCategory };
1805
- state.persistRun(pi, run);
1804
+ // Issue #648: nothing ran, so the group list is empty by measurement and the
1805
+ // run record is still written — the required payload makes that explicit.
1806
+ state.persistSettledRun(pi, run, usageGroupsFrom(rejection.messages));
1806
1807
  state.finalizeLiveSubagent(run.id);
1807
1808
  }
1808
1809
 
@@ -1950,7 +1951,10 @@ function finalizeForegroundResult(
1950
1951
  ...run.originalParams,
1951
1952
  errorCategory: result.errorCategory,
1952
1953
  };
1953
- state.persistRun(pi, run);
1954
+ // Issue #648 (Q6): the terminal write carries the run's spend through the
1955
+ // required-payload choke point — `result` is the LAST attempt's result, so the
1956
+ // same-id timeout re-entry appends the retry's groups exactly once.
1957
+ state.persistSettledRun(pi, run, usageGroupsFrom(result.messages));
1954
1958
 
1955
1959
  // R2: Prune old run entries
1956
1960
  pruneHistoryIfNeeded(state, ctx, log);
@@ -2106,7 +2110,9 @@ function finalizeCrashedRun(err: unknown, run: SubagentRun, deps: CrashDeps): To
2106
2110
  crashOutput,
2107
2111
  new Date(run.startedAt).getTime(),
2108
2112
  );
2109
- state.persistRun(pi, run);
2113
+ // Issue #648: a crash carries no assistant turns of its own; the crash
2114
+ // result's (empty) messages are the measured source.
2115
+ state.persistSettledRun(pi, run, usageGroupsFrom(result.details.messages));
2110
2116
 
2111
2117
  return result;
2112
2118
  }
@@ -19,15 +19,11 @@
19
19
  *
20
20
  * BOUNDARY, stated once so CRLF/BOM/blank-separator cases have one answer:
21
21
  * the block starts at the first non-blank line and consumes consecutive lines
22
- * matching `^(dispatch|brief|jev):`, ending at the first line that does not
22
+ * matching `^(dispatch|brief):`, ending at the first line that does not
23
23
  * match (a blank line ends it too). The task is `\r?\n`-split and a leading BOM
24
24
  * is stripped before the first line is read. A title (`# Task`) before the block
25
25
  * ends it — that is a refusal, not a tolerance, because a silent tolerance would
26
26
  * let a quoted example at the top of a task become the declaration.
27
- *
28
- * The Jev line may still appear ANYWHERE (src/dispatch-line.ts scans every line
29
- * and takes the first valid one), which is why `jev:` is a block-continuation
30
- * line here but does not have to be inside the block.
31
27
  */
32
28
 
33
29
  /** The four dispatch kinds. `impl` is the gated class: it needs a brief. */
@@ -59,7 +55,7 @@ export const BRIEF_SLUG_PATTERN = /^[a-z0-9][a-z0-9-]{0,63}$/;
59
55
  export const BRIEF_ESCAPE_TOKEN = "none";
60
56
 
61
57
  /** A line that belongs to the leading block. Anchored: an indented copy does not. */
62
- const BLOCK_LINE_RE = /^(dispatch|brief|jev):/;
58
+ const BLOCK_LINE_RE = /^(dispatch|brief):/;
63
59
 
64
60
  const DISPATCH_PREFIX = "dispatch:";
65
61
  const BRIEF_PREFIX = "brief:";
@@ -167,7 +163,7 @@ export function parseDispatchHeader(task: string): DispatchHeaderVerdict {
167
163
  return refuse(
168
164
  strayDeclaration
169
165
  ? "missing dispatch header: the block must be the first content — the task's first non-blank line " +
170
- "is not one of `dispatch:`/`brief:`/`jev:`, so a later declaration is outside the block. " +
166
+ "is not one of `dispatch:`/`brief:`, so a later declaration is outside the block. " +
171
167
  "Move the block to the top of the task."
172
168
  : "missing dispatch header: the task's first non-blank line must declare the kind.",
173
169
  );
package/src/history.ts CHANGED
@@ -197,11 +197,6 @@ export function resolveRetryParams(
197
197
  gitMode?: string;
198
198
  approvalMode?: string;
199
199
  force?: boolean;
200
- /** The call-level Jev-line bypass (issue #412) — kept so an explicit
201
- * noJev on a retry call still reaches the validation seam; it is never
202
- * inherited from the original (a bypass is per dispatch, and the
203
- * original's line already rides the recorded task). */
204
- noJev?: string;
205
200
  },
206
201
  run: SubagentRun,
207
202
  ): typeof params {
@@ -226,7 +221,6 @@ export function resolveRetryParams(
226
221
  gitMode: params.gitMode ?? orig?.gitMode,
227
222
  approvalMode: params.approvalMode ?? orig?.approvalMode,
228
223
  force: params.force ?? orig?.force,
229
- noJev: params.noJev,
230
224
  };
231
225
  }
232
226
 
package/src/index.ts CHANGED
@@ -114,11 +114,7 @@ type _NonResolutionDelegateKey =
114
114
  | "retryOnTimeout"
115
115
  | "model"
116
116
  | "priority"
117
- | "background"
118
- // Issue #412: `force`/`noJev` are consumed at the validation seam (they
119
- // reach `validatePreTask`, not the merge), so `force` stays in the resolver's
120
- // key list while `noJev` — never read by resolution — is excluded here.
121
- | "noJev";
117
+ | "background";
122
118
  type _ResolveInputCoverage = _ExpectNever<
123
119
  Exclude<_KnownDelegateKey, keyof ResolveInputParams | _NonResolutionDelegateKey>
124
120
  >;
@@ -51,8 +51,10 @@
51
51
  *
52
52
  * #299 RE-REVIEW FIX A.1 closes one more major on `0fa2fc2`:
53
53
  * - A reaped pid must classify as GONE in `pidGone` (positive `kill(pid,0)`
54
- * sample + `/proc/<pid>/stat` ENOENT — see src/proc.ts), so our own reaped
55
- * leader is not mistaken for a live FOREIGN pid and refused its group kill.
54
+ * sample + `/proc/<pid>/stat` ENOENT **or** ESRCH — see src/proc.ts), so our
55
+ * own reaped leader is not mistaken for a live FOREIGN pid and refused its
56
+ * group kill. Both vanished codes are absence-of-process evidence; any other
57
+ * read failure stays ambiguous.
56
58
  * - Honest reporting: a REFUSED final group SIGKILL over a group that still
57
59
  * has live members is counted as a survivor (`refusedForceKillGroup`), so a
58
60
  * guard decision can never yield a clean `survivors=[]` over a live group we
@@ -138,11 +140,14 @@ export function __setProcessGroupKillSupportedForTest(value: boolean | undefined
138
140
  *
139
141
  * - direct pid signal — allowed only when `isOwn(pid)` is true;
140
142
  * - group signal — allowed when `isOwn(pid)` is true OR the pid is confirmed
141
- * GONE (`!pidAlive(pid)`). A dead leader's pgid cannot have been reused by a
142
- * LIVE foreign leader, so `kill(-pgid)` can only reach our surviving members
143
- * (this keeps D5's group SIGKILL for a TERM-stubborn member working after the
144
- * leader exits). An ALIVE pid that no longer carries the marker IS the
145
- * review's reused-pid case: EVERY signal is skipped, never unverified.
143
+ * GONE (`!pidAlive(pid)`). The gone case keeps D5's group SIGKILL for a
144
+ * TERM-stubborn member working after the leader exits, and it PREMISES that
145
+ * the pgid still names OUR group — which the reuse check cannot prove: a pid
146
+ * reused by a FOREIGN process and then reaped can leave its number naming
147
+ * that foreign group, and a same-uid group signal is not `EPERM`ed by the
148
+ * kernel (the boundary is uid, not the marker — see `groupTarget`). An ALIVE
149
+ * pid that no longer carries the marker IS the review's reused-pid case:
150
+ * EVERY signal is skipped, never unverified.
146
151
  *
147
152
  * `onSkip` records a refused signal. A skipped signal is never retried
148
153
  * unverified.
@@ -248,6 +253,15 @@ function bestEffortGroupKill(
248
253
  * (D5).
249
254
  *
250
255
  * `guard` (optional) re-verifies a marker-derived pid at signal time (Major 1).
256
+ *
257
+ * BOUNDARY (pre-existing, NOT widened by #644): `isGone` licenses the group
258
+ * signal when the pid is gone, which assumes the pgid still names OUR group. A
259
+ * pid reused by a FOREIGN process and then reaped can leave its number naming
260
+ * that foreign group — and a same-uid group is not `EPERM`ed by the kernel, so
261
+ * `kill(-pgid)` lands on it. The marker constrains the pid, not the pgid; the
262
+ * real boundary here is uid, not the reuse check. This is identical on the
263
+ * pre-existing `ENOENT` path — #644 only adds a second vanished errno to the
264
+ * same classification, so it does not widen the exposure.
251
265
  */
252
266
  export function groupTarget(
253
267
  pid: number,
@@ -258,8 +272,10 @@ export function groupTarget(
258
272
  guard?: SignalGuard,
259
273
  ): EscalationTarget {
260
274
  // A group signal is skipped ONLY for a live pid that is no longer ours (the
261
- // reused-pid case). A gone/zombie leader's pgid can only name our surviving
262
- // members, so the group signal must still land (D5).
275
+ // reused-pid case). A gone/zombie leader's group signal must still land (D5):
276
+ // those members are exactly the ones we need to reach. The pgid is trusted to
277
+ // name OUR group; a reused-then-reaped pid number naming a same-uid FOREIGN
278
+ // group is the known residual documented in BOUNDARY above.
263
279
  // #299 re-review A.1: remember a REFUSED final group SIGKILL so the escalation
264
280
  // can report the still-live group it could not end (never a clean report).
265
281
  let finalGroupRefused = false;
@@ -306,6 +322,13 @@ export function groupTarget(
306
322
  // #299 fix A.2: only a POSITIVELY empty group (`false`) may report clean.
307
323
  // `undefined` (unknown inspection) and an ABSENT reader both mean emptiness
308
324
  // could not be established, so the fail-safe is to count a survivor.
325
+ //
326
+ // #644 residual (deliberate, decision Q3): this one boolean therefore CONFLATES
327
+ // "the group has live members we could not signal" with "the group's state could
328
+ // not be established" (an ambiguous read — `undefined`). Both are reported as one
329
+ // bare pid. That is deliberate: no consumer branches on the distinction and the
330
+ // operator's action is the same (inspect the pid), so making it visible is its own
331
+ // unit rather than a field added here.
309
332
  refusedForceKillGroup: () =>
310
333
  finalGroupRefused && (groupHasMembers ? groupHasMembers(pid) !== false : true),
311
334
  };
@@ -49,12 +49,7 @@ import { depthLimitRejection, gateSessionCost, rejection, runPreTaskValidation,
49
49
  /** The params object the shared resolver consumes (`ResolveInputParams`,
50
50
  * params.ts) — the same type the background and single paths pass. */
51
51
  export interface ModePrologueInput {
52
- /**
53
- * `noJev` is carried alongside the resolution inputs rather than inside
54
- * `ResolveInputParams`: resolution never reads it, but the mode-level H1
55
- * gate forwards it as the call's stated bypass (issue #412).
56
- */
57
- params: ResolveInputParams & { noJev?: string };
52
+ params: ResolveInputParams;
58
53
  state: SessionState;
59
54
  ctx: ExtensionContext;
60
55
  log: Logger;
@@ -149,12 +144,9 @@ export function runModePrologue(input: ModePrologueInput): ModePrologueOutcome {
149
144
  thinkingLevel: globalParams.thinkingLevel,
150
145
  gitMode: globalParams.resolvedGitMode,
151
146
  outputFile: globalParams.outputFile,
152
- // Issue #412: the project-local Jev-line check keys on the DISPATCH
153
- // cwd (the project whose manifest opts in), and `noJev` is the
154
- // call-level stated bypass — the mode-level task text is the caller's
155
- // own, so it is checked and bypassable exactly like a single task.
147
+ // Project-local process checks key on the DISPATCH cwd (the project
148
+ // whose manifest opts in).
156
149
  cwd: targets.cwd,
157
- noJev: params.noJev,
158
150
  },
159
151
  });
160
152
  if (preTask.error) return { ok: false, error: preTask.error };
@@ -384,7 +384,6 @@ function rejectedUnitResult(
384
384
  ctx,
385
385
  log,
386
386
  force: params.force as boolean | undefined,
387
- noJev: params.noJev,
388
387
  // Issue #443: the DECLARED per-step level (the merged one is resolved).
389
388
  declaredThinkingLevel: (step) => step.thinkingLevel,
390
389
  merge: (step) =>
@@ -787,7 +786,6 @@ function rejectedUnitResult(
787
786
  ctx,
788
787
  log,
789
788
  force: params.force as boolean | undefined,
790
- noJev: params.noJev,
791
789
  // Issue #443: the DECLARED per-task level (the merged one is resolved).
792
790
  declaredThinkingLevel: (task) => task.thinkingLevel,
793
791
  merge: (task) =>
@@ -1215,7 +1213,6 @@ function rejectedUnitResult(
1215
1213
  ctx,
1216
1214
  log,
1217
1215
  force: params.force as boolean | undefined,
1218
- noJev: params.noJev,
1219
1216
  // Issue #443: the DECLARED per-node level (the merged one is resolved).
1220
1217
  declaredThinkingLevel: (node) => node.thinkingLevel,
1221
1218
  merge: (node) =>
package/src/params.ts CHANGED
@@ -54,7 +54,7 @@ export const KNOWN_DELEGATE_KEYS = new Set([
54
54
  "outputFile", "label", "model", "timeout", "cwd", "tools",
55
55
  "excludeTools", "noBuiltinTools", "preset", "template", "params",
56
56
  "retryRunId", "gitMode", "retryOnTimeout", "approvalMode", "background",
57
- "priority", "chain", "tasks", "graph", "force", "noJev",
57
+ "priority", "chain", "tasks", "graph", "force",
58
58
  ] as const);
59
59
 
60
60
  /**
package/src/prelude.ts CHANGED
@@ -369,13 +369,6 @@ export interface UnitPrePassInput<U, M extends UnitPrePassSource> {
369
369
  log: Logger;
370
370
  /** Per-unit force flag (IN10): mode entry never carries it. */
371
371
  force?: boolean;
372
- /**
373
- * The call-level `noJev` bypass (issue #412), forwarded to every unit's H1.
374
- * Mode entry never carries it either: the mode-level pre-task check has no
375
- * task text of its own to bypass, and a per-unit bypass would let a caller
376
- * silence the check for a batch while appearing to pass it for the call.
377
- */
378
- noJev?: string;
379
372
  /**
380
373
  * The unit's DECLARED thinkingLevel, read from the unit itself (issue #443).
381
374
  * Required, so a new caller cannot silently skip the check: the merged value
@@ -407,7 +400,7 @@ export type UnitPrePassOutcome<U, M extends UnitPrePassSource> =
407
400
  export function validateUnitPrePass<U, M extends UnitPrePassSource>(
408
401
  input: UnitPrePassInput<U, M>,
409
402
  ): UnitPrePassOutcome<U, M> {
410
- const { units, merge, describe, label, gitMode, ctx, log, force, noJev, declaredThinkingLevel } = input;
403
+ const { units, merge, describe, label, gitMode, ctx, log, force, declaredThinkingLevel } = input;
411
404
  const validated: Array<ValidatedUnit<U, M>> = [];
412
405
  const warnings: string[] = [];
413
406
 
@@ -447,7 +440,6 @@ export function validateUnitPrePass<U, M extends UnitPrePassSource>(
447
440
  outputFile: merged.outputFile,
448
441
  force,
449
442
  cwd: targets.cwd,
450
- noJev,
451
443
  },
452
444
  });
453
445
  if (validation.error) return { ok: false, error: validation.error };
package/src/proc.ts CHANGED
@@ -57,18 +57,64 @@ export function isProcAvailable(): boolean {
57
57
  return procAvailable;
58
58
  }
59
59
 
60
- /** The outcome of a `/proc/<pid>/stat` read: the fields, or why it failed. */
60
+ /**
61
+ * The outcome of a `/proc/<pid>/stat` read: the fields, or why it failed.
62
+ *
63
+ * `code` is the errno of the FAILED READ, in three shapes:
64
+ *
65
+ * - a VANISHED code — `"ENOENT"` when the pid was gone at open, `"ESRCH"` when
66
+ * the record was opened and the task was released before the read (both in
67
+ * `VANISHED_READ_CODES`) — the task was RELEASED, i.e. absence-of-process
68
+ * evidence;
69
+ * - any OTHER errno (`"EACCES"`, `"EIO"`) — the read failed and we cannot tell
70
+ * whether the process is alive: AMBIGUOUS;
71
+ * - `undefined` when /proc is unavailable, the pid is invalid, or the record
72
+ * cannot be parsed — there is no errno to classify. Readers resolve the
73
+ * no-`/proc` case to their documented PLATFORM answer, never to a partial
74
+ * inspection (see `GroupMembership`).
75
+ */
61
76
  type StatFieldsRead =
62
77
  | { ok: true; fields: string[] }
63
78
  | { ok: false; code: string | undefined };
64
79
 
80
+ /**
81
+ * #644 — the errnos that PROVE the task was RELEASED, so a failed read is a
82
+ * COMPLETED observation of absence rather than a partial one:
83
+ *
84
+ * - `ENOENT` — gone at `open` (the dentry no longer exists);
85
+ * - `ESRCH` — opened, then the task was released before the read.
86
+ *
87
+ * Both were MEASURED, not reasoned: a held-fd control answered `ESRCH` 400/400,
88
+ * and a real scan under foreign churn saw 48 `ESRCH` against 25,462 `ENOENT` in
89
+ * 10,291 scans (1,718,042 reads). Treating only `ENOENT` as vanished made a
90
+ * COMPLETE scan look partial (`groupHasMembers` → `undefined`, so the kill path
91
+ * reported an unsignalled survivor) and made a reaped leader look like a live
92
+ * FOREIGN pid (`pidGone` → false, so the surviving members were never signalled).
93
+ *
94
+ * ONE set, honoured by BOTH readers (`statFieldsVanished`). Every other READ
95
+ * outcome stays AMBIGUOUS — another errno (`EACCES`, `EIO`) or a record that
96
+ * cannot be parsed. A host with NO `/proc` at all is not an ambiguous read: it is
97
+ * the documented PLATFORM boundary at each reader (`groupHasMembers` answers
98
+ * `false`, `pidGone` degrades to `!pidAlive`), untouched by this classification.
99
+ */
100
+ const VANISHED_READ_CODES: ReadonlySet<string> = new Set(["ENOENT", "ESRCH"]);
101
+
102
+ /**
103
+ * True when the failed read PROVES the task was released — the single predicate
104
+ * both readers honour, so the classification cannot drift between them. The
105
+ * `code !== undefined` narrowing is load-bearing: `Set.has` takes a `string`, and
106
+ * a parse anomaly / unavailable /proc carries no errno to test.
107
+ */
108
+ function statFieldsVanished(read: Extract<StatFieldsRead, { ok: false }>): boolean {
109
+ return read.code !== undefined && VANISHED_READ_CODES.has(read.code);
110
+ }
111
+
65
112
  /**
66
113
  * The `readStatFields` primitive WITH the failure cause preserved: `code` is the
67
- * errno of a failed read (`"ENOENT"` when the pid is absent) or undefined when
68
- * /proc is unavailable, the pid is invalid, or the read failed for a reason
69
- * other than a missing file. `pidGone` needs the cause to separate "the pid was
70
- * REAPED" (ENOENT — absence-of-process evidence) from "the read failed and we
71
- * cannot tell" (everything else).
114
+ * errno of the failed read — see `StatFieldsRead` for its three shapes. Callers
115
+ * that only need the coarse split use `statFieldsVanished`: a vanished code means
116
+ * the task was RELEASED (absence-of-process evidence), anything else — another
117
+ * errno, or `undefined` — means "the read failed and we cannot tell".
72
118
  */
73
119
  function readStatFieldsDetailed(pid: number): StatFieldsRead {
74
120
  if (!isProcAvailable() || !Number.isInteger(pid) || pid <= 0) {
@@ -133,9 +179,11 @@ export function readProcessGroup(pid: number): number | undefined {
133
179
  * `undefined`: with no `/proc` at all the caller degrades to leader liveness
134
180
  * (this returns `false`). `undefined` is reserved for an inspection that FAILED
135
181
  * on a `/proc`-capable host — a `/proc` listing failure, or a member's stat read
136
- * that failed for a reason other than the process being gone (`EACCES`, `EIO`, a
137
- * parse anomaly). A member that genuinely vanished during the scan is skipped
138
- * (ENOENT — it cannot be a live member).
182
+ * that failed AMBIGUOUSLY (an errno outside `VANISHED_READ_CODES`, such as
183
+ * `EACCES`/`EIO`, or no errno at all — a parse anomaly). A member that genuinely
184
+ * vanished during the scan is skipped — `ENOENT`, or `ESRCH` when it was reaped
185
+ * between the listing and the read (both in `VANISHED_READ_CODES`) — and the
186
+ * scan stays COMPLETE (a gone task cannot be a live member).
139
187
  */
140
188
  export type GroupMembership = boolean | undefined;
141
189
 
@@ -229,9 +277,10 @@ export function groupHasMembers(pgid: number): GroupMembership {
229
277
  if (pid === pgid) continue; // the leader (possibly a zombie) is not a member
230
278
  const read = readStatFieldsDetailed(pid);
231
279
  if (!read.ok) {
232
- // A member gone mid-scan is skippable (it cannot be a live member); any
280
+ // A member gone mid-scan is skippable (it cannot be a live member) — and
281
+ // #644: BOTH vanished codes prove that, so the scan stays complete. Any
233
282
  // OTHER failure makes the inspection partial → unknown.
234
- if (read.code === "ENOENT") continue;
283
+ if (statFieldsVanished(read)) continue;
235
284
  return undefined;
236
285
  }
237
286
  // #299 fix A.5: ONE strict prefix validation. A truncated, shifted or
@@ -315,8 +364,15 @@ export function pidAlive(pid: number): boolean {
315
364
  * not-yet-reaped zombie included), so ENOENT is absence-of-process evidence;
316
365
  * classifying it as "not gone" made the guard treat our own reaped leader as a
317
366
  * live FOREIGN pid and refuse BOTH the group SIGTERM and the final group
318
- * SIGKILL while its group still had live members. Every OTHER read failure
319
- * (EACCES, a parse anomaly, /proc unavailable) stays conservatively not-gone.
367
+ * SIGKILL while its group still had live members. #644: `ESRCH` is the SAME
368
+ * absence-of-process evidence — the record was opened and the task was released
369
+ * before the read. The held-fd control measures exactly that sub-window: once the
370
+ * record was opened before the reap, the read answers `ESRCH` 400/400. A real
371
+ * `readFileSync` has a far narrower open→read window, so a real scan answers
372
+ * mostly `ENOENT` (measured: 48 `ESRCH` against 25,462 `ENOENT` in 10,291 scans)
373
+ * and `ESRCH` only when the reap lands inside that window. Every OTHER read
374
+ * failure (EACCES, a parse anomaly, /proc unavailable) stays conservatively
375
+ * not-gone.
320
376
  *
321
377
  * PLATFORM BOUNDARY (hidepid=2): on a `/proc` mounted with `hidepid=2` a foreign
322
378
  * LIVE pid we do not own can read `kill -0` EPERM (alive) and then
@@ -324,12 +380,14 @@ export function pidAlive(pid: number): boolean {
324
380
  * ATTEMPT a group signal despite the marker mismatch. This is a documented
325
381
  * platform boundary, NOT a signal-safety guarantee: the kernel's EPERM on the
326
382
  * signal constrains the unprivileged blast radius, and the group signal still
327
- * targets only the pgid we derived (it does not widen the target set).
383
+ * targets only the pgid we derived (it does not widen the target set). A hidden
384
+ * pid is indistinguishable from a reaped one — already documented, unchanged by
385
+ * the `ESRCH` classification above.
328
386
  */
329
387
  export function pidGone(pid: number): boolean {
330
388
  if (!pidAlive(pid)) return true;
331
389
  const read = readStatFieldsDetailed(pid);
332
- if (!read.ok) return read.code === "ENOENT";
390
+ if (!read.ok) return statFieldsVanished(read);
333
391
  const state = read.fields[0];
334
392
  return state === "Z" || state === "X";
335
393
  }
@@ -3,10 +3,9 @@
3
3
  * The umbrella project-local flags: `{"brl-subagent": {"processChecks": true}}` and
4
4
  * `{"brl-subagent": {"backgroundGuard": "worktree-guard"}}`.
5
5
  *
6
- * `processChecks` gates OUR process mechanisms — the Jev dispatch-line check
7
- * (#407/#412), rule 2's durable-shape auto-switch (#412), and the
8
- * engineering-bar injection (#421). It replaces the merged-but-unreleased
9
- * `requireJevLine`: one flag, one reader, no per-rule fields.
6
+ * `processChecks` gates OUR process mechanisms — the mandatory dispatch header
7
+ * & signed-brief check (#606), rule 2's durable-shape auto-switch (#412), and the
8
+ * engineering-bar injection (#421): one flag, one reader, no per-rule fields.
10
9
  *
11
10
  * Why one reader (issue #415): the shape rule shipped GLOBAL, so a user's
12
11
  * explicit `background: false` + timeout was overridden by our conductor