hooks/lib/subagent.ts: CLAUDE_CODE_FORK_SUBAGENT is set in main sessions on Claude Code 2.1.26x+, muting nine hooks (fix + tests attached)
Summary
hooks/lib/subagent.ts treats CLAUDE_CODE_FORK_SUBAGENT === '1' as "this process is a fork subagent" (added in 7.40.4 for #1831). On Claude Code 2.1.26x+ (verified on 2.1.274, Linux) the harness exports that variable into every child process of the main interactive session, hooks included, so isSubagentContext() returns true in every primary session and nine consumers exit silently: LoadContext, LoadMemory, MemoryDeltaSurface, MemoryTurnStart, MemoryReviewFire, SystemChangeSurface, ISASync (session strip), ConfigEvalFire, KittyEnvPersist.
Net effect in a primary session: no session-start dynamic context, no hot-layer memory injection on any prompt, no 🧠 / 🩺 / ⚙️ lines, no ascent strip, and the memory reviewer never triggers. Nothing errors; MemoryHealthCheck stays at WARN (its surface-liveness check only assesses when curation is writing, and curation never starts because the reviewer never fires), and the 🩺 line only surfaces on CRITICAL. It took four days to notice.
Evidence
- Live PostToolUse hook process on 2.1.274:
/proc/<pid>/environcarriesCLAUDE_CODE_FORK_SUBAGENT=1andCLAUDE_CODE_CHILD_SESSION=1; the parentclaudeprocess carries neither. isSubagentContext()in that environment →true; with onlyCLAUDE_CODE_FORK_SUBAGENTunset →false.- A real fork subagent (
Agentwithsubagent_type: "fork") has an env identical to the main session's (fork=1, child=1, noCLAUDE_AGENT_TYPE), so the env cannot separate the two. Its hook stdin, however, carries"agent_id": "…", "agent_type": "fork". MemoryTurnStart.hook.tsunder that env: 0 bytes of stdout before the fix; ~18 KB (memory block + 🧠 line) after, and still 0 bytes when the stdin payload carriesagent_id.- Timeline on one node: last hook-fed 🧠 line at the exact minute Claude Code went 2.1.258 → 2.1.272.
Preflight: UpstreamPreflight reports DEFECT-LIVE for hooks/lib/subagent.ts against main @ 5e2f2e8.
Proposed fix (diff attached)
Decide on the documented signal first. The hooks reference says that inside a subagent the stdin JSON carries agent_id and agent_type; callers that have parsed stdin pass it in, and the explicit env markers (CLAUDE_AGENT_TYPE, CLAUDE_CODE_SUBAGENT_NAME, CLAUDE_CODE_SUBAGENT_TYPE, CLAUDE_AGENT_SDK) remain as the no-stdin fallback. CLAUDE_CODE_FORK_SUBAGENT is dropped. Consumers that decided before reading stdin (MemoryTurnStart, MemoryReviewFire, ConfigEvalFire, KittyEnvPersist, LoadContext) now read first; SystemChangeSurface and ISASync pass the input they already had. A bun test suite covers the negative control (2.1.274 env, main-session stdin → false) and the positive ones (raven / fork stdin → true).
Two follow-ons in the same change on our fork, offered in case they are useful: MemoryHealthCheck gains a hook-liveness check keyed on processed prompts vs the surface heartbeat (evidence that always exists, rather than curation writes that may never exist), and MemoryDeltaSurface surfaces 🩺 for a WARN that has persisted 24 h, not only for CRITICAL.
diff --git i/LifeOS/install/hooks/lib/subagent.ts w/LifeOS/install/hooks/lib/subagent.ts
index b3a031e..6858b7a 100644
--- i/LifeOS/install/hooks/lib/subagent.ts
+++ w/LifeOS/install/hooks/lib/subagent.ts
@@ -1,4 +1,5 @@
/**
+ * @version 2.0.0
* subagent.ts — the single answer to "am I running inside a subagent?"
*
* Eight hooks each carried their own copy of this test, and the copies had
@@ -12,25 +13,47 @@
* because nothing compares them; one function is the fix, not a rule telling
* people to keep nine copies in step.
*
- * The test is the UNION of every known marker. That is strictly safer than any
- * single family: a missed subagent leaks main-session context (and a duplicate
- * surface line) into a delegate, while a false positive would suppress context
- * in a main session. Verified 2026-07-28 in a main session — every marker below
- * is unset, so the union cannot false-positive there.
+ * v2.0.0 (2026-09-18, INC-20260918-hook-mute): the documented signal comes
+ * first. Claude Code puts `agent_id` (and `agent_type`) in the hook's stdin
+ * JSON when, and only when, the hook runs inside a subagent (hooks reference:
+ * "When running with --agent or inside a subagent, two additional fields are
+ * included"). Callers that have parsed their stdin pass it in; the env markers
+ * remain as the fallback for callers with no stdin.
+ *
+ * The one marker that is GONE is `CLAUDE_CODE_FORK_SUBAGENT`. It was added
+ * for public issue #1831 (forks set only that marker). From Claude Code
+ * 2.1.26x the harness exports it into EVERY child of the main interactive
+ * session — hooks included, verified on a live PostToolUse hook process on
+ * 2.1.274 — so keying on it muted nine hooks in every primary session for
+ * four days before anyone noticed. A false positive here suppresses the
+ * session-start context, the hot-layer memory, the 🧠/🩺/⚙️ lines, the ascent
+ * strip and the memory reviewer, silently. Never key on an undocumented
+ * env variable again; the stdin field is the contract.
*/
-/** True when this process is a subagent/delegate rather than the main session. */
-export function isSubagentContext(): boolean {
+/** The two fields Claude Code adds to hook stdin inside a subagent. */
+export interface SubagentIdentity {
+ agent_id?: unknown;
+ agent_type?: unknown;
+}
+
+/**
+ * True when this process is a subagent/delegate rather than the main session.
+ *
+ * @param input the hook's parsed stdin JSON, when the caller has it. A hook
+ * that has not read stdin passes nothing and gets the env-only answer.
+ */
+export function isSubagentContext(input?: SubagentIdentity | null): boolean {
+ if (input && typeof input === 'object') {
+ if (typeof input.agent_id === 'string' && input.agent_id.length > 0) return true;
+ if (typeof input.agent_type === 'string' && input.agent_type.length > 0) return true;
+ }
const projectDir = process.env.CLAUDE_PROJECT_DIR || '';
return Boolean(
projectDir.includes('/.claude/Agents/') ||
process.env.CLAUDE_AGENT_TYPE ||
process.env.CLAUDE_CODE_SUBAGENT_NAME ||
process.env.CLAUDE_CODE_SUBAGENT_TYPE ||
- // Forked subagents set ONLY the fork marker — none of the above.
- // Without it, 8 hook consumers re-inject main-session context into
- // forks that inherited it via cache. (public issue #1831, @DRAZY)
- process.env.CLAUDE_CODE_FORK_SUBAGENT === '1' ||
process.env.CLAUDE_AGENT_SDK === '1',
);
}
Filed as issue-plus-diff per our usual shape; no PR. Happy to adjust if you would rather keep the env marker for some harness version we have not seen.
Adding a runnable falsifier to this thread, since main at 5e2f2e8c still has the CLAUDE_CODE_FORK_SUBAGENT === '1' row in LifeOS/install/hooks/lib/subagent.ts:33, and the fix described on #2075 and #1958 hasn't reached the public tree yet.
The patch below applies cleanly to 5e2f2e8c. It adds LifeOS/install/test/hooks/lib/subagent.test.ts, a bun test file with no dependencies that clears every env marker before each case. It also changes the guard. Two points differ from the diff in this issue and from the #1958 port as it was described:
- Only
agent_idcounts. The hooks reference saysagent_idis "Present only when the hook fires inside a subagent call," butagent_typeis "Present when the session uses--agentor the hook fires inside a subagent." So aclaude --agent <name>main session carriesagent_type, and treating it as a marker would bring back the same false positive through a different field. The test covers that case. - SessionStart
source: "fork"isn't counted. That source is documented as "A new session forked from an existing one:--fork-sessionwith--resumeor--continue, the/forkbackground copy, or/branch". It's a new top-level session, not a forked subagent.
Negative control, unpatched 5e2f2e8c plus only the test file:
(fail) (a) fork-mode flag set, main-session payload → NOT a subagent > PostToolUse payload without agent_id
(fail) (a) fork-mode flag set, main-session payload → NOT a subagent > Stop payload without agent_id
(fail) (a) fork-mode flag set, main-session payload → NOT a subagent > no payload at all (hooks that never read stdin)
(fail) (a) fork-mode flag set, main-session payload → NOT a subagent > --agent main session: agent_type without agent_id
(fail) (b) payload with agent_id → subagent > fork (agent_type "fork")
(fail) (b) payload with agent_id → subagent > ordinary delegate
(fail) hook-level: MemoryReviewFire with the fork-mode flag set > main-session Stop → per-session state written
13 pass
7 fail
With the patch applied:
20 pass
0 fail
27 expect() calls
The hook-level case runs the real MemoryReviewFire.hook.ts with HOME pointed at a temporary directory, so it touches nothing outside that directory. Bun 1.4.2, macOS, Claude Code 2.1.278.
Not measured: a real fork's own hook payload. The docs describe agent_id for hooks "inside a subagent," and the sub-agents docs say "A fork is a subagent that inherits the entire conversation." That forks carry agent_id in practice comes from the report at the top of this issue and from #2075, not from my own run.
If the private-tree fix already covers this, the test file may still be worth porting on its own. It is the inverse assertion #2075 asked for.
Patch against 5e2f2e8c (8 files, test included)
diff --git a/LifeOS/install/hooks/ConfigEvalFire.hook.ts b/LifeOS/install/hooks/ConfigEvalFire.hook.ts
index 172ea4d..26bf15b 100755
--- a/LifeOS/install/hooks/ConfigEvalFire.hook.ts
+++ b/LifeOS/install/hooks/ConfigEvalFire.hook.ts
@@ -41,15 +41,15 @@ function isSentinel(path: string): boolean {
return /(^|\/)CLAUDE\.md$/.test(path);
}
-function readInput(): { filePath: string | null } {
+function readInput(): { filePath: string | null; payload: unknown } {
try {
const raw = readFileSync(0, 'utf8');
- if (!raw.trim()) return { filePath: null };
+ if (!raw.trim()) return { filePath: null, payload: null };
const j = JSON.parse(raw);
const fp = j?.tool_input?.file_path;
- return { filePath: typeof fp === 'string' ? fp : null };
+ return { filePath: typeof fp === 'string' ? fp : null, payload: j };
} catch {
- return { filePath: null };
+ return { filePath: null, payload: null };
}
}
@@ -76,9 +76,8 @@ function saveLastFire(iso: string): void {
function main(): void {
try {
- if (isSubagent()) process.exit(0);
-
- const { filePath } = readInput();
+ const { filePath, payload } = readInput();
+ if (isSubagent(payload)) process.exit(0);
if (!filePath || !isSentinel(filePath)) process.exit(0);
if (minutesSince(loadLastFire()) < DEBOUNCE_MINUTES) process.exit(0);
if (!existsSync(RUNNER)) process.exit(0);
diff --git a/LifeOS/install/hooks/ISASync.hook.ts b/LifeOS/install/hooks/ISASync.hook.ts
index 79bab2f..4685854 100755
--- a/LifeOS/install/hooks/ISASync.hook.ts
+++ b/LifeOS/install/hooks/ISASync.hook.ts
@@ -153,7 +153,7 @@ async function main(): Promise<string | null> {
// without a phase edit. Per-session dedupe file; subagents never emit (their
// ISA edits would strip-spam their own contexts, which helps nobody).
let stripDelta: string | null = null;
- if (input.session_id && fm.slug && !isSubagentContext()) {
+ if (input.session_id && fm.slug && !isSubagentContext(input)) {
try {
const stripDir = join(homedir(), '.claude/LIFEOS/MEMORY/STATE/ascent-strip');
const stripFile = join(stripDir, `${String(input.session_id).replace(/[^\w-]/g, '')}.json`);
diff --git a/LifeOS/install/hooks/KittyEnvPersist.hook.ts b/LifeOS/install/hooks/KittyEnvPersist.hook.ts
index 1564e1e..c39b088 100755
--- a/LifeOS/install/hooks/KittyEnvPersist.hook.ts
+++ b/LifeOS/install/hooks/KittyEnvPersist.hook.ts
@@ -20,22 +20,23 @@ import { isSubagentContext } from './lib/subagent';
const paiDir = getLifeosDir();
-// Skip for subagents
-if (isSubagentContext()) process.exit(0);
-
// Read session_id + source from stdin (SessionStart hook input)
-// source ∈ {"startup", "resume", "compact", "clear"}; absent on older CC versions.
+// source ∈ {"startup", "resume", "compact", "clear", "fork"}; absent on older CC versions.
let sessionId = '';
let source = '';
+let parsed: unknown = null;
try {
const raw = readFileSync(0, 'utf-8');
if (raw) {
- const parsed = JSON.parse(raw);
- sessionId = String(parsed.session_id || '');
- source = String(parsed.source || '');
+ parsed = JSON.parse(raw);
+ sessionId = String((parsed as any).session_id || '');
+ source = String((parsed as any).source || '');
}
} catch { /* best-effort */ }
+// Skip for subagents (decided on the payload, so after stdin is read)
+if (isSubagentContext(parsed)) process.exit(0);
+
// Persist Kitty environment for hooks that run later without terminal context
const kittyListenOn = process.env.KITTY_LISTEN_ON;
const kittyWindowId = process.env.KITTY_WINDOW_ID;
diff --git a/LifeOS/install/hooks/MemoryReviewFire.hook.ts b/LifeOS/install/hooks/MemoryReviewFire.hook.ts
index 08c205e..4811d47 100755
--- a/LifeOS/install/hooks/MemoryReviewFire.hook.ts
+++ b/LifeOS/install/hooks/MemoryReviewFire.hook.ts
@@ -201,17 +201,18 @@ function logFire(payload: Record<string, unknown>): void {
* of guessing via globally-newest-mtime, which grabs a concurrent session's
* transcript whenever two sessions overlap (public issue #1495, @christauff).
*/
-function readHookInput(): { sessionId: string | null; transcriptPath: string | null } {
+function readHookInput(): { sessionId: string | null; transcriptPath: string | null; payload: unknown } {
try {
const raw = readFileSync(0, "utf8");
- if (!raw.trim()) return { sessionId: null, transcriptPath: null };
+ if (!raw.trim()) return { sessionId: null, transcriptPath: null, payload: null };
const j = JSON.parse(raw);
return {
sessionId: typeof j.session_id === "string" ? j.session_id : null,
transcriptPath: typeof j.transcript_path === "string" ? j.transcript_path : null,
+ payload: j,
};
} catch {
- return { sessionId: null, transcriptPath: null };
+ return { sessionId: null, transcriptPath: null, payload: null };
}
}
@@ -240,9 +241,8 @@ function spawnReviewer(turnsReviewed: number, transcriptPath: string | null): {
function main(): void {
try {
- if (isSubagent()) process.exit(0);
-
- const { sessionId, transcriptPath } = readHookInput();
+ const { sessionId, transcriptPath, payload } = readHookInput();
+ if (isSubagent(payload)) process.exit(0);
const nowMs = Date.now();
const now = new Date(nowMs).toISOString();
const config = loadConfig();
diff --git a/LifeOS/install/hooks/MemoryTurnStart.hook.ts b/LifeOS/install/hooks/MemoryTurnStart.hook.ts
index 1e73f45..61307e8 100755
--- a/LifeOS/install/hooks/MemoryTurnStart.hook.ts
+++ b/LifeOS/install/hooks/MemoryTurnStart.hook.ts
@@ -88,16 +88,17 @@ async function readStdin(): Promise<string> {
});
}
-if (isSubagent()) process.exit(0);
-
(async () => {
let sessionId = "unknown";
let prompt = "";
+ let input: unknown = null;
try {
- const input = JSON.parse(await readStdin());
- sessionId = input.session_id || "unknown";
- prompt = typeof input.prompt === "string" ? input.prompt : "";
+ input = JSON.parse(await readStdin());
+ sessionId = (input as any).session_id || "unknown";
+ prompt = typeof (input as any).prompt === "string" ? (input as any).prompt : "";
} catch {}
+ // Decided on the payload, so this runs after stdin is read (lib/subagent.ts).
+ if (isSubagent(input)) process.exit(0);
// Turn boundary for the ⚙️ SYSTEM surface. It lives here because this is the
// ONE UserPromptSubmit composer, so it needs no new settings.json entry — and
diff --git a/LifeOS/install/hooks/SystemChangeSurface.hook.ts b/LifeOS/install/hooks/SystemChangeSurface.hook.ts
index 08500cb..af389dd 100755
--- a/LifeOS/install/hooks/SystemChangeSurface.hook.ts
+++ b/LifeOS/install/hooks/SystemChangeSurface.hook.ts
@@ -69,6 +69,7 @@ interface Ledger {
export interface HookInput {
session_id?: string;
+ agent_id?: string;
tool_name?: string;
tool_input?: { file_path?: string };
}
@@ -113,7 +114,7 @@ function writeLedger(path: string, ledger: Ledger): void {
export function run(input: HookInput): string | null {
try {
- if (isSubagent()) return null;
+ if (isSubagent(input)) return null;
const tool = input.tool_name ?? "";
if (!WRITE_TOOLS.has(tool)) return null;
const filePath = input.tool_input?.file_path;
diff --git a/LifeOS/install/hooks/lib/subagent.ts b/LifeOS/install/hooks/lib/subagent.ts
index b3a031e..16a990e 100644
--- a/LifeOS/install/hooks/lib/subagent.ts
+++ b/LifeOS/install/hooks/lib/subagent.ts
@@ -15,22 +15,37 @@
* The test is the UNION of every known marker. That is strictly safer than any
* single family: a missed subagent leaks main-session context (and a duplicate
* surface line) into a delegate, while a false positive would suppress context
- * in a main session. Verified 2026-07-28 in a main session — every marker below
- * is unset, so the union cannot false-positive there.
+ * in a main session.
+ *
+ * The documented signal comes first: Claude Code puts `agent_id` in a hook's
+ * stdin JSON "only when the hook fires inside a subagent call" (hooks
+ * reference, Common input fields). A fork is a subagent, and it inherits the
+ * parent's environment, so no env variable can tell the two apart; the
+ * payload can. Callers that have parsed stdin pass it in. `agent_type` alone
+ * is not enough: a `claude --agent <name>` main session carries it too.
+ *
+ * `CLAUDE_CODE_FORK_SUBAGENT` is deliberately NOT a marker. It is the fork-mode
+ * switch (env-vars reference), and settings.system.json sets it session-wide,
+ * so reading it as "I am a fork" made every main session a subagent and nine
+ * hooks exited early. It was added for public issue #1831; the false positive
+ * was reported as #1864, #2075 and #2150.
*/
-/** True when this process is a subagent/delegate rather than the main session. */
-export function isSubagentContext(): boolean {
+/**
+ * True when this process is a subagent/delegate rather than the main session.
+ * @param input the hook's parsed stdin JSON, when the caller has it.
+ */
+export function isSubagentContext(input?: unknown): boolean {
+ if (input && typeof input === 'object') {
+ const agentId = (input as { agent_id?: unknown }).agent_id;
+ if (typeof agentId === 'string' && agentId.length > 0) return true;
+ }
const projectDir = process.env.CLAUDE_PROJECT_DIR || '';
return Boolean(
projectDir.includes('/.claude/Agents/') ||
process.env.CLAUDE_AGENT_TYPE ||
process.env.CLAUDE_CODE_SUBAGENT_NAME ||
process.env.CLAUDE_CODE_SUBAGENT_TYPE ||
- // Forked subagents set ONLY the fork marker — none of the above.
- // Without it, 8 hook consumers re-inject main-session context into
- // forks that inherited it via cache. (public issue #1831, @DRAZY)
- process.env.CLAUDE_CODE_FORK_SUBAGENT === '1' ||
process.env.CLAUDE_AGENT_SDK === '1',
);
}
diff --git a/LifeOS/install/test/hooks/lib/subagent.test.ts b/LifeOS/install/test/hooks/lib/subagent.test.ts
new file mode 100644
index 0000000..8d3022d
--- /dev/null
+++ b/LifeOS/install/test/hooks/lib/subagent.test.ts
@@ -0,0 +1,150 @@
+/**
+ * subagent.test.ts — falsifier for hooks/lib/subagent.ts isSubagentContext().
+ *
+ * Regression: settings.system.json ships CLAUDE_CODE_FORK_SUBAGENT=1 in its
+ * session-wide `env` block (it is the fork-mode enable flag), and the guard
+ * read that same variable as "this process is a fork". Every main session
+ * classified itself as a subagent and nine hooks exited early.
+ *
+ * The documented discriminator is `agent_id` in the hook's stdin payload:
+ * "Present only when the hook fires inside a subagent call."
+ * (https://code.claude.com/docs/en/hooks, Common input fields)
+ *
+ * Hermetic: every env marker the guard reads is cleared before each case and
+ * restored after, so a runner that is itself a Claude Code session (where
+ * CLAUDE_CODE_FORK_SUBAGENT may be set) cannot flip a result.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
+import { spawnSync } from 'node:child_process';
+import { existsSync, mkdtempSync, readdirSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join, resolve } from 'node:path';
+import { isSubagentContext } from '../../../hooks/lib/subagent';
+
+const MARKERS = [
+ 'CLAUDE_PROJECT_DIR',
+ 'CLAUDE_AGENT_TYPE',
+ 'CLAUDE_CODE_SUBAGENT_NAME',
+ 'CLAUDE_CODE_SUBAGENT_TYPE',
+ 'CLAUDE_CODE_FORK_SUBAGENT',
+ 'CLAUDE_AGENT_SDK',
+] as const;
+
+let saved: Record<string, string | undefined> = {};
+
+beforeEach(() => {
+ saved = {};
+ for (const k of MARKERS) {
+ saved[k] = process.env[k];
+ delete process.env[k];
+ }
+});
+
+afterEach(() => {
+ for (const k of MARKERS) {
+ if (saved[k] === undefined) delete process.env[k];
+ else process.env[k] = saved[k];
+ }
+});
+
+// Main-session payload shapes: no agent_id. `agent_type` alone is what a
+// `claude --agent <name>` main session carries, so it must not count.
+const MAIN_POST_TOOL_USE = {
+ session_id: 'main-1',
+ transcript_path: '/tmp/main-1.jsonl',
+ cwd: '/tmp',
+ hook_event_name: 'PostToolUse',
+ tool_name: 'Write',
+ tool_input: { file_path: '/tmp/x.md' },
+};
+const MAIN_STOP = { session_id: 'main-1', transcript_path: '/tmp/main-1.jsonl', hook_event_name: 'Stop' };
+const MAIN_WITH_AGENT_FLAG = { ...MAIN_POST_TOOL_USE, agent_type: 'security-reviewer' };
+
+const FORK_POST_TOOL_USE = { ...MAIN_POST_TOOL_USE, agent_id: 'a1b2c3', agent_type: 'fork' };
+const DELEGATE_POST_TOOL_USE = { ...MAIN_POST_TOOL_USE, agent_id: 'd4e5f6', agent_type: 'Explore' };
+
+describe('(a) fork-mode flag set, main-session payload → NOT a subagent', () => {
+ test('PostToolUse payload without agent_id', () => {
+ process.env.CLAUDE_CODE_FORK_SUBAGENT = '1';
+ expect(isSubagentContext(MAIN_POST_TOOL_USE)).toBe(false);
+ });
+ test('Stop payload without agent_id', () => {
+ process.env.CLAUDE_CODE_FORK_SUBAGENT = '1';
+ expect(isSubagentContext(MAIN_STOP)).toBe(false);
+ });
+ test('no payload at all (hooks that never read stdin)', () => {
+ process.env.CLAUDE_CODE_FORK_SUBAGENT = '1';
+ expect(isSubagentContext()).toBe(false);
+ });
+ test('--agent main session: agent_type without agent_id', () => {
+ process.env.CLAUDE_CODE_FORK_SUBAGENT = '1';
+ expect(isSubagentContext(MAIN_WITH_AGENT_FLAG)).toBe(false);
+ });
+});
+
+describe('(b) payload with agent_id → subagent', () => {
+ test('fork (agent_type "fork")', () => {
+ expect(isSubagentContext(FORK_POST_TOOL_USE)).toBe(true);
+ });
+ test('ordinary delegate', () => {
+ expect(isSubagentContext(DELEGATE_POST_TOOL_USE)).toBe(true);
+ });
+ test('fork with the fork-mode flag also set', () => {
+ process.env.CLAUDE_CODE_FORK_SUBAGENT = '1';
+ expect(isSubagentContext(FORK_POST_TOOL_USE)).toBe(true);
+ });
+ test('malformed payloads never throw and never count', () => {
+ for (const p of [null, undefined, 'x', 42, [], {}, { agent_id: '' }, { agent_id: 7 }]) {
+ expect(isSubagentContext(p as never)).toBe(false);
+ }
+ });
+});
+
+describe('(c) legacy env markers still → subagent', () => {
+ const cases: Array<[string, string]> = [
+ ['CLAUDE_AGENT_TYPE', 'Engineer'],
+ ['CLAUDE_CODE_SUBAGENT_NAME', 'researcher'],
+ ['CLAUDE_CODE_SUBAGENT_TYPE', 'general-purpose'],
+ ['CLAUDE_AGENT_SDK', '1'],
+ ['CLAUDE_PROJECT_DIR', '/home/u/.claude/Agents/Engineer'],
+ ];
+ for (const [k, v] of cases) {
+ test(`${k} alone, main-session payload`, () => {
+ process.env[k] = v;
+ expect(isSubagentContext(MAIN_POST_TOOL_USE)).toBe(true);
+ });
+ test(`${k} alone, no payload`, () => {
+ process.env[k] = v;
+ expect(isSubagentContext()).toBe(true);
+ });
+ }
+});
+
+// Hook-level: run the real MemoryReviewFire.hook.ts (Stop) against a throwaway
+// HOME. It writes its per-session state file only when it decides it is in a
+// main session. Nothing under the real ~/.claude is touched.
+describe('hook-level: MemoryReviewFire with the fork-mode flag set', () => {
+ const HOOK = resolve(import.meta.dir, '../../../hooks/MemoryReviewFire.hook.ts');
+
+ function runStop(payload: object): string[] {
+ const home = mkdtempSync(join(tmpdir(), 'subagent-test-'));
+ try {
+ const env: Record<string, string> = { ...(process.env as Record<string, string>), HOME: home };
+ for (const k of MARKERS) delete env[k];
+ env.CLAUDE_CODE_FORK_SUBAGENT = '1';
+ spawnSync('bun', [HOOK], { input: JSON.stringify(payload), env, encoding: 'utf8' });
+ const dir = join(home, '.claude/LIFEOS/MEMORY/STATE/memory-review');
+ return existsSync(dir) ? readdirSync(dir) : [];
+ } finally {
+ rmSync(home, { recursive: true, force: true });
+ }
+ }
+
+ test('main-session Stop → per-session state written', () => {
+ expect(runStop(MAIN_STOP)).toEqual(['main-1.json']);
+ });
+ test('Stop carrying agent_id → nothing written', () => {
+ expect(runStop({ ...MAIN_STOP, agent_id: 'a1b2c3', agent_type: 'fork' })).toEqual([]);
+ });
+});
Thanks @0bsolescence, and @mj-deving for the falsifier. The fork feature flag no longer counts as a subagent marker. Following the hook schema, only agent_id marks a subagent now, so --agent main sessions and /fork or /branch sessions get their context hooks back. No safety or permission gate reads this check. It's in hooks/lib/subagent.ts with updated tests, and goes out in the next public release (8.3.0).