Personal_AI_Infrastructure icon indicating copy to clipboard operation
Personal_AI_Infrastructure copied to clipboard

isSubagentContext() is broken both ways since install: true in every main session (kills the memory pipeline), and never true inside a subagent

Open michaelaye opened this issue 2 months ago • 6 comments

settings.system.json sets CLAUDE_CODE_FORK_SUBAGENT=1, so isSubagentContext() is true in every main session

Version: LifeOS 7.40.4 (fresh install, migrating from PAI 4.0.3)

Summary

The shipped settings.system.json sets CLAUDE_CODE_FORK_SUBAGENT as a global env toggle. hooks/lib/subagent.ts reads that same variable as a runtime marker meaning "I am a forked subagent". Both ship in the same release, so on a stock install isSubagentContext() returns true in the main session, and the seven hooks that guard on it exit immediately.

The memory pipeline is silently dead from the first session onward.

Evidence

settings.system.json (shipped):

"CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS": "1",
"CLAUDE_CODE_FORK_SUBAGENT": "1",
"CLAUDE_CODE_MAX_CONCURRENT_SUBAGENTS": "20",

hooks/lib/subagent.ts:

process.env.CLAUDE_CODE_FORK_SUBAGENT === '1' ||

In a main session with the stock settings file, env | grep CLAUDE_ shows CLAUDE_CODE_FORK_SUBAGENT=1 and no CLAUDE_CODE_SUBAGENT_NAME / CLAUDE_CODE_SUBAGENT_TYPE. isSubagentContext() returns true.

Affected hooks

All seven bail on this guard as their first statement:

MemoryTurnStart, LoadMemory, MemoryDeltaSurface, MemoryReviewFire, SystemChangeSurface, ISASync, ConfigEvalFire.

Observed symptoms

  • MemoryReviewFire never ticks, so review-state.json stays at turn_count_since_last_review: 1 and last_review_at: null forever. The 8-turn threshold is never reached and the autonomic reviewer never runs.
  • No per-session file is ever written under MEMORY/STATE/memory-review/.
  • MEMORY/OBSERVABILITY/reviewer-runs/ is never created, so MemoryHealthCheck CHECK 6 warns reviewer-runs/ directory does not exist yet indefinitely. This warning is the only user-visible symptom, and it reads as a benign not-yet-run notice rather than a dead subsystem.
  • No memory-delta or system-change surface lines are ever emitted.
  • ISASync emits no ascent-delta blocks.

Repro

  1. Fresh LifeOS 7.40.4 install with the shipped settings.system.json.
  2. Run a main session for more than 8 turns.
  3. cat $LIFEOS_DIR/MEMORY/OBSERVABILITY/review-state.json — the turn count has not moved and last_review_at is still null.

Why each half looks correct alone

The fork marker was added to subagent.ts deliberately (referenced in-file as public issue #1831): forked subagents set only that marker, and without it eight consumers re-inject main-session context into forks. That is correct when the harness alone sets the variable. It breaks when the same release also sets it globally as a feature switch.

The comment in subagent.ts states the union "cannot false-positive" in a main session, verified 2026-07-28. That verification predates the toggle landing in the shipped settings file.

Suggested fix

Separate the switch from the marker. Options, roughly in order of preference:

  1. Drop CLAUDE_CODE_FORK_SUBAGENT from the union in isSubagentContext() and detect forks by a marker the harness sets per-process, not one the user's settings set globally.
  2. If the fork marker must stay in the union, stop setting it in the shipped settings.system.json and let the harness set it.
  3. Failing both, gate the fork branch on the absence of a main-session marker (e.g. treat it as a fork only when CLAUDE_CODE_SESSION_ID is absent, or when a subagent name/type is also present).

A regression test worth adding either way: assert isSubagentContext() === false under the shipped settings.system.json env, which is exactly the case the in-file comment claims is verified.


Update after applying fix option 2 — the bug is deeper than the toggle

I removed CLAUDE_CODE_FORK_SUBAGENT from my local settings (option 2 above) and restarted. The main session recovered: the memory hooks fire, MemoryReviewFire ticks on every Stop, the per-session state file is written, and the surface lines appear. So option 2 does fix the reported symptom.

But it also reveals that isSubagentContext() never detected subagents at all on this harness version. It is not that the toggle broke fork detection; there was no working fork detection to break.

Evidence

I spawned two subagents and had each report the guard plus all six env markers:

context isSubagentContext() env markers set
main session false (correct) none
fork subagent false (wrong) none
plain subagent (general-purpose) false (wrong) none

Every marker in the union is unset in a fork: CLAUDE_PROJECT_DIR, CLAUDE_AGENT_TYPE, CLAUDE_CODE_SUBAGENT_NAME, CLAUDE_CODE_SUBAGENT_TYPE, CLAUDE_CODE_FORK_SUBAGENT, CLAUDE_AGENT_SDK.

The harness signals subagency in the hook stdin payload, not the environment. LifeOS's own EventLogger.hook.ts already reads it:

...(typeof data.agent_id   === 'string' ? { agent_id:   data.agent_id   } : {}),
...(typeof data.agent_type === 'string' ? { agent_type: data.agent_type } : {}),

In MEMORY/OBSERVABILITY/tool-activity.jsonl for one session, exactly 2 of 248 entries carry agent_type, and they are precisely the two subagent tool calls ("fork" and the named general-purpose agent). All 246 main-session entries have neither field. So the signal is present and reliable, just not in process.env.

Note this is the same class of gap already recorded in HookSystem.md for SubagentStart ("payload omits subagent_type / description / prompt"), which is why lifecycle tracking moved to the PreToolUse:Agent boundary. The env-marker approach in subagent.ts has the mirror-image problem.

Consequence

Of the seven guard consumers, only two can execute inside a subagent at all:

hook event reachable in a subagent?
MemoryTurnStart UserPromptSubmit no — a subagent submits no user prompt
MemoryReviewFire Stop no — a subagent's finish is SubagentStop
LoadMemory, MemoryDeltaSurface, SystemChangeSurface imported by the above no
ISASync PostToolUse[Write/Edit/MultiEdit] yes
ConfigEvalFire PostToolUse[Write/Edit/MultiEdit] yes

So any subagent that writes or edits a file runs ISASync and ConfigEvalFire unguarded. ISASync computes and emits <lifeos-ascent-delta>, which the system prompt states subagents must never receive.

That narrow blast radius is presumably why this went unnoticed: the guard's failure is invisible unless a delegate writes a file and you inspect what it received.

Suggested fix, revised

Options 1 and 3 in the original report cannot work, because there is no per-process env marker for the harness to set. Read the payload instead. Adding a second helper avoids changing the existing signature or dropping the env union:

/** True when a parsed hook payload came from a subagent tool call. */
export function isSubagentPayload(p: unknown): boolean {
  const o = (p ?? {}) as Record<string, unknown>;
  return typeof o.agent_id === 'string' || typeof o.agent_type === 'string';
}

Then OR it into the guard at the two PostToolUse sites that already parse the payload. The other five consumers are unaffected.

Caveat: agent_id / agent_type are not in the documented payload shape (HookSystem.md "Hook Input (stdin)" and "Hook Data Payloads by Event Type" list neither), so they are undocumented harness fields. They are observably present and already relied on by EventLogger, but a maintainer should confirm they are stable before this is depended on more widely.

Two doc gaps that made this expensive to diagnose

  1. Nothing in DOCUMENTATION/ mentions isSubagentContext or hooks/lib/subagent.ts. grep -rn 'isSubagentContext\|subagent\.ts' DOCUMENTATION/ returns zero hits, despite seven hooks depending on it. Each restarted session has to re-derive the contract from source.
  2. The in-file comment asserts the union "cannot false-positive" in a main session, "verified 2026-07-28". Worth adding the inverse assertion as a test too: that the guard returns true inside a fork. That test would have failed from the start.

michaelaye avatar Sep 08 '26 16:09 michaelaye

Second confirmation on LifeOS 7.40.4 / Claude Code 2.1.267 (macOS, bun), reproduced independently before finding this issue and landing on the same line.

Measured, not inferred. I ran the same two probes in three contexts — the main session, a real fork (subagent_type: "fork"), and a plain subagent — reading process.env and calling isSubagentContext() in each:

Context The four process markers CLAUDE_CODE_FORK_SUBAGENT isSubagentContext()
Main session all unset "1" true
Real fork all unset "1" true
Plain subagent all unset "1" true

All three report the same CLAUDE_PID and the same CLAUDE_CODE_SESSION_ID, i.e. the fork runs in process and reads the parent's environment verbatim.

Stated limit: those probes ran as tool-spawned child processes, not as hook processes. Both are children of the same parent and both inherit the settings env block, so I would expect no difference, but I have not measured a hook process directly and I am not claiming it. Anyone who can instrument a live hook and log its process.env would close that gap.

How #1831 reached the wrong conclusion. That issue states forks "set ONLY the fork marker — none of the above". The reconstruction that fits the data: the reporter had CLAUDE_CODE_FORK_SUBAGENT=1 in their own settings, observed it set inside a fork, and read it as a marker the fork had set — without checking a main session, where it was equally 1. It is an easy mistake to make: the variable really is present in a fork, and the four other markers really are absent there, so the observation was correct and only the attribution was wrong. The underlying problem #1831 raised — forks receiving context they already inherited — is real and still unsolved.

What the measurement adds is that the flag could never have solved it: the variable was already present in both parent and child because settings.system.json puts it in the session-wide env block, so the row was never a discriminator, only a constant that made the union return true everywhere. PR #1942's comment says exactly this — "a fork inherits the parent env anyway, so the flag cannot discriminate a fork from its parent even in principle" — and the three-context table backs it.

Blast radius observed on a stock install. MemoryTurnStart exits at its guard, taking LoadMemory, MemoryDeltaSurface and the retriever with it; MemoryReviewFire exits, so the reviewer cadence never fires again after any failed run; SystemChangeSurface and ISASync return early. The delta-surface heartbeat froze the minute the 7.40.4 upgrade landed and stayed frozen for a day, until I ran the reviewer by hand.

One detail for triage, and I would rather ask than assert. At the only path I can find it, the flag row still appears to be on main:

https://github.com/danielmiessler/LifeOS/blob/5e2f2e8c0abde612da0e99c16c0d07d4ec21b88c/LifeOS/install/hooks/lib/subagent.ts#L33

process.env.CLAUDE_CODE_FORK_SUBAGENT === '1' ||, in a file last touched by the 7.40.4 release commit be9e8ef (2026-08-14). I looked for a second copy first, since this repo has carried duplicated paths before: walking the full tree at main (2658 entries, untruncated) turns up exactly one subagent.ts.

#1942 and #2031 were both closed noting that the flag half had landed on 08-17 under #1864. Did that removal land on a path I am not seeing, was it reverted, or am I misreading the file? A pointer would settle it.

Possibly useful either way: the same walk finds two copies of settings.system.json — LifeOS/install/settings.system.json and LifeOS/install/skills/LifeOS/install/settings.system.json — byte-identical (blob a49c91e8), each shipping CLAUDE_CODE_FORK_SUBAGENT: "1". Whatever the fix turns out to be, the flag ships from two places.

Consequence for the fix that is queued. The stdin detection hand-ported from #1958 cannot fix this on its own: it ORs a new signal into a union that already short-circuits to true whenever the shipped env block is in effect. The flag row has to come out as well, otherwise the new signal is unreachable.

On applying #1942 locally — it is a controlled rollback, not a fix. Removing the row restores all nine hooks, and it knowingly re-opens #1831: with the row gone, isSubagentContext() returns false in a real fork and in a plain subagent too, because none of the four process markers is ever set on 2.1.267. That is a deliberate trade, not a claim that subagents do not matter. #1831 classifies its own impact as "Functional/efficiency, not security" — a delegate re-reading context it already had — while the regression it introduced silently kills the memory pipeline of every main session. The worse of the two goes first, and the rollback stands only until #1958's stdin detection ships, which is what actually fixes both directions. The env-based union is not merely poisoned, it is inert in both — which is the strongest argument for that approach.

mefsnef avatar Sep 10 '26 22:09 mefsnef

Confirming this from a separate install, with a measurement that may help — and with one question about the repo state that I can't answer from outside.

I measured the environment in all three contexts, and there is no marker to find

Probe wired to PostToolUse / Stop / SubagentStop, then a real subagent run. Claude Code 2.1.268, macOS.

context CLAUDE_PID the four union markers agent_id in stdin payload
main session same never set absent
forked subagent same never set present
plain subagent same never set present

The environment is identical across all three. That is the part I think the earlier PRs were missing: the question isn't which env var to key on, it's that none of them can work, because the parent and the child share one process environment. A fork inherits its parent's env by definition, so no inherited variable can distinguish them even in principle.

Two neighbouring candidates also failed, worth naming so nobody re-tries them: in the payload, session_id is identical to the parent's, and transcript_path points at the parent's transcript — even though on disk a subagent's transcript does sit under <parent-id>/subagents/.

What does discriminate is agent_id / agent_type in the hook's stdin payload: present in every event born inside a subagent (its own PostToolUse, and SubagentStop), absent from every main-session event including the Agent spawn call itself.

One more thing that surprised me: inside a subagent, Stop does not fire — SubagentStop does. Any hook registered only on Stop never runs for a subagent, which narrows the blast radius of this bug from what I first assumed.

The question: which branch feeds install/?

Reading the closing comments on #1942, #2031 and #1958, the fix is described as already landed — the flag removal on 08-17 under #1864, and the stdin signal ported by hand as isSubagentHookInput, OR'd in at all seven consumers.

From outside I can't see that on main. What I can see, at 5e2f2e8c0abde612da0e99c16c0d07d4ec21b88c:

  • isSubagentHookInput returns zero results across the whole repository. That's the fastest thing to check here.
  • LifeOS/install/hooks/lib/subagent.ts#L33 still has process.env.CLAUDE_CODE_FORK_SUBAGENT === '1' in the union, with no payload check anywhere in the file.
  • That file's last commit is be9e8ef8, 2026-08-14 — three days before the described 08-17 landing.

So: am I looking at the wrong branch? If the install tree is cut from somewhere other than main, or the fixed copy lives at a path my search missed, then this comment is noise and I'd rather know. If it isn't, then what ships to new installs still carries the 2026-08 behaviour, which would explain why this issue keeps getting reported by people who installed recently.

Offer

I have the raw recorded payloads from the run above (8 events, main + subagent) and a replay test suite built from them, deliberately hermetic — it neutralises the union's env vars so a dirty runner environment can't turn a green into a red or the reverse. Before that, CLAUDE_AGENT_SDK=1 alone turned 21 passes into 17 failures, which is worth knowing for anyone testing this in CI or from an agent.

Happy to open a PR, hand over just the fixtures, or do nothing — whichever is actually useful.

What I don't know

  • The fork direction is inferred, not measured on a real fork: the recorded subagent was a plain one, so the fork rows above come from the env sweep, not from a fork's own payload.
  • Everything here is on 2.1.268. The env sweep was on 2.1.267; both behaved the same, but I haven't tested anything older.
  • I haven't verified any of the repo-side claims beyond what the API shows from outside, which is exactly why the section above is a question.

mefsnef avatar Sep 11 '26 10:09 mefsnef

Confirming #2075 in both directions on 2.1.272, from an A/B rather than a read of the code.

Main-session false positive. The shipped settings put CLAUDE_CODE_FORK_SUBAGENT: "1" in env, so it is present in every process including the primary, and the env union in hooks/lib/subagent.ts reads it as "I am a fork".

Same hook, same stdin payload, only the variable differs:

run MemoryReviewFire writes its per-session state file
flag set (normal) no
env -u CLAUDE_CODE_FORK_SUBAGENT yes

Corroboration on the same install, independent of that test: MemoryReviewFire and MemoryTurnStart — the two guarded hooks that write per-session state — were both frozen at the same timestamp for seven days, while unguarded hooks on the same events logged normally throughout. review-state.json had carried last_review_at: null since install, i.e. the memory reviewer had never run once.

Delegate false negative. Also measured, not read: agent_id / agent_type are stamped on real delegate hook events here (2178 such rows in the local observability log, with agent_type values like Explore). None of the env markers in the union were set on those same events.

What I did not measure: a real fork's own SessionStart payload. The source: "fork" row is inferred from the documented source set, not observed — same caveat as the earlier comment in this thread.

Local fix, since both PRs here are closed. The payload becomes the primary signal, the feature-flag row is dropped, and the remaining env markers stay as a fallback for callers that have no stdin:

export function isSubagentContext(hookInput?: unknown): boolean {
  return payloadSaysSubagent(hookInput) || envSaysSubagent();
}

where payloadSaysSubagent tests a non-empty agent_id, a non-empty agent_type, or source === "fork".

Three details that cost me time, in case they save someone else's:

  1. Four hooks needed the guard moved below their stdin parse. It previously ran before anything had been read, so passing the payload alone changes nothing there.
  2. fd 0 drains once. The three hooks that never parsed stdin (LoadContext, LoadMemory, MemoryDeltaSurface) share one memoized reader rather than each calling readFileSync(0, ...).
  3. A top-level subagent_type is deliberately not tested. The Agent tool's own PreToolUse payload carries it under tool_input, and that event fires in the primary session as it spawns a delegate — testing it would reintroduce the same false positive from a different direction.

Verification after the patch, main-session payload vs fork payload, bytes on stdout: LoadMemory 165/0, MemoryDeltaSurface 364/0, LoadContext 1281/0, MemoryTurnStart 2965/0. MemoryReviewFire writes state for the first and not the second. The reviewer then fired for the first time on this install.

Happy to open a PR if a maintainer wants it in this shape.

gjaworski86 avatar Sep 15 '26 13:09 gjaworski86

This is Shiva, Eugene's AI Assistant, reporting on Eugene's behalf.

Does not reproduce on our install (7.40.4, migrated from PAI 4.0 mid-2026). No CLAUDE_CODE_FORK_SUBAGENT in settings.json/settings.system.json or live env, and MEMORY/OBSERVABILITY/review-state.json shows an active review cycle (last_review_at from today) with 128 historical runs in reviewer-runs/. Might be install-path or timing specific — sharing as a data point in case it's useful for scoping.

waveman2020-sudo avatar Sep 15 '26 14:09 waveman2020-sudo

Thanks for running it. I read your install as a control for the same mechanism rather than a counterexample.

You migrated from PAI 4.0, so the settings.system.json on your disk predates the flag row. The row ships in the 7.40.4 install tree. Your result (flag absent from env, reviewer cycling, 128 runs in reviewer-runs/) is exactly what the unset side of my env -u CLAUDE_CODE_FORK_SUBAGENT A/B produced, held permanently.

Two cheap checks would settle it from your side:

  1. Look at the file as shipped, not the one you migrated: grep FORK_SUBAGENT in the 7.40.4 install tree (install/settings.system.json, plus the byte-identical copy under install/skills/LifeOS/install/). If the row is there, the difference between our installs is the migration path, not the version string.

  2. The delegate direction is independent of the flag. Do your hook events for real subagents carry agent_id / agent_type, and does isSubagentContext() return true on them? Here they carry both and the guard still returns false, because no env marker in the union is ever set on a subagent event. That half stays broken on your install too if detection is still env-only.

What I have not tested: anything on a PAI-4.0 migration path. If the migrator merges into an existing settings.system.json instead of replacing it, that alone would explain why fresh installs report this and upgrades do not.

gjaworski86 avatar Sep 15 '26 17:09 gjaworski86

Both directions were real. Detection now reads the hook's own stdin (agent_id / agent_type / source: "fork") and the fork env flag is no longer treated as a marker (hooks/lib/subagent.ts). Next release carries it. Thanks for the thorough thread, @michaelaye.

danielmiessler avatar Sep 17 '26 21:09 danielmiessler