Agent team lost when lead's context gets compacted during long session

Open 💬 18 comments Opened Feb 6, 2026 by Aimiten

Preflight Checklist

  • [x] I have searched existing issues and this hasn't been reported yet
  • [x] This is a single bug report (please file separate reports for different bugs)
  • [x] I am using the latest version of Claude Code

What's Wrong?

When running an agent team for a longer task (16 content pages for an Astro
site), the lead's context window fills up and gets compacted/summarized. After
compaction, the lead completely loses awareness of the team — it can't
message teammates, coordinate tasks, or even acknowledge the team exists. The
team effectively vanishes mid-session despite teammates potentially still
running. The user has to start a new session and manually clean up orphaned
files from ~/.claude/teams/ and ~/.claude/tasks/.

What Should Happen?

The lead should retain team awareness after compaction. At minimum, the team
config path (~/.claude/teams/{name}/config.json) and active task list should
be re-injected into context after summarization — similar to how CLAUDE.md
persists across compaction. The data is already on disk, it just needs to be
re-read.

Error Messages/Logs

No explicit error. The lead simply continues as if no team exists. When the
  user asks about the team, the lead has no memory of it.

Steps to Reproduce

  1. Set CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS: "1" in .claude/settings.json
  2. Create an agent team with multiple teammates and a shared task list
  3. Assign enough work that the lead's context approaches the 200K token limit

(e.g., writing/reviewing 16 pages with SEO checks, internal linking, and
umlaut fixes)

  1. Wait for compaction to trigger couple of times
  2. Try to interact with the team after compaction — the lead no longer knows

it exists

Claude Model

Opus

Is this a regression?

No, this never worked

Last Working Version

_No response_

Claude Code Version

2.1.34 (Claude Code)

Platform

Anthropic API

Operating System

macOS

Terminal/Shell

Terminal.app (macOS)

Additional Information

  • macOS Darwin 21.6.0
  • In-process teammate mode (default/auto)
  • The team ("aimiten-content") had a lead + multiple teammates writing Astro

content pages. All writing tasks completed successfully. The team was lost
during the SEO review phase when context was compacted.

  • A possible fix: add a PostCompact hook or built-in logic that re-reads

~/.claude/teams/{active-team}/config.json and the task list after
summarization, injecting team state back into the lead's context.
Alternatively, team state could be treated as system-level context (like
CLAUDE.md) that always persists.

  • 16 pages is a modest workload for a feature designed around multi-agent

autonomous collaboration.

View original on GitHub ↗

18 Comments

junaidtitan · 5 months ago

Working on the fix for this issue but meanwhile this will surely help by giving you much more time before compaction hits...

We built Cozempic to prune this from session files. Running it between sessions or before resuming can delay the point where compaction triggers. On a 6,602 message session we saw 1,529 messages removed and 22% size reduction, mostly from progress ticks and metadata that contribute nothing to context but consume tokens.

pip install cozempic
cozempic diagnose <session_id>
cozempic treat <session_id> --execute

Won't fix the core issue since team config should absolutely persist across compaction, but it does reduce the frequency of compaction triggering in the first place.

weiT1993 · 5 months ago

Running into the same issue on V2.1.37.

junaidtitan · 5 months ago

Update: Cozempic now has full Agent Teams protection that addresses this issue end-to-end.

pip install cozempic
cozempic init

cozempic init auto-wires everything into your project — no manual configuration:

  • Guard daemon auto-starts on every session (SessionStart hook) — continuously checkpoints team state, prunes bloat before compaction triggers
  • Team-protect pruning — when pruning fires, team messages (Task, TaskCreate, TaskUpdate, TeamCreate, SendMessage) are separated and preserved, only non-team messages get pruned
  • Recovery injection — after pruning, a synthetic message pair is appended confirming full team roster, task list, and status so Claude "remembers" the team
  • Config.json ground truth — reads ~/.claude/teams/*/config.json as authoritative source for team state, independent of JSONL
  • Checkpoint hooks on every agent spawn, task change, before compaction, and at session end

Tested across 3 sessions with 4 active teammates — team state survived compaction + resume with zero user intervention.

The one gap: PostCompact hook doesn't exist in Claude Code yet, so Cozempic can't re-inject immediately after compaction. The workaround (PreCompact checkpoint + guard daemon + recovery injection) covers this in practice.

ThatDragonOverThere · 4 months ago

Same issue, confirmed workaround doesn't work — Feb 17, 2026

Your "agent team lost during long sessions" is the same root cause. We built the SessionStart(compact) hook workaround to re-inject team configuration and workflow rules. Claude ignores it.

Full evidence chain: #9796 → #19471 → #14258 → #17237. All the same bug, all unfixed.

cel66 · 4 months ago

Newbie here: I had a similar situation where the main context window filled and auto-compacted and upon return team was lost and main context window finished the Phase. See below: Probably more feedback but I believe it is related to the main window compacting while an agent team is in use. Summary includes how I am managing it going forward after a lessons learned exercise. Apologies ahead of time if this is not relevant.

Agent Team Feature Feedback: Context Management & Role Persistence

Summary

When using agent teams for complex tasks, the main agent's context window filled and auto-compacted 4 times during a single work phase. After compaction, the agent lost its "project manager" role constraint and began doing implementation work directly (though it did continue using sub-agents). This suggests agent team state and role definitions don't survive compaction.

---

What Happened

Setup: Created an agent team with the main agent acting as project manager (coordinator only), delegating all implementation work to sub-agents.

Expected Behavior:

  • Main agent coordinates and delegates only
  • Sub-agents do all implementation work within their own contexts
  • Main context stays lean (dispatch messages + short status reports)
  • No compaction needed for a well-managed session

Actual Behavior:

  • Main agent context filled and compacted 4 times
  • After compaction, the agent:
  • ✅ Remembered to use sub-agents
  • ❌ Lost its "project manager only" role constraint
  • ❌ Started doing implementation work itself
  • ❌ Likely pulled file contents and code reviews into its own context

---

Root Cause Analysis

The main agent was consuming context by:

  1. Reading source files directly instead of delegating reads to agents
  2. Reviewing agent-written code line-by-line in its own context
  3. Running tests itself instead of dispatching a testing agent
  4. Receiving verbose reports instead of concise status updates

Sub-agents have their own 200k token context windows, but this capacity was underutilized while the main context ballooned.

---

Agent's Own Lessons Learned

The following was written by the agent itself after a Q&A session analyzing what went wrong:

### Phase 2 Context Overflow (February 2026) Problem: During Phase 2 (Port the Computation Core), the agent team approach broke down: 1. The coordinator (Claude) read large Electron source files directly instead of delegating to agents 2. Agent output was reviewed line-by-line in the main context instead of agents self-verifying 3. Integration tests were run in the main context instead of by a testing agent 4. This filled the 200k context window, triggering auto-compaction at ~190k tokens 5. After compaction, the original "use an agent team" instruction was lost 6. The continuation session proceeded without re-establishing the team, doing even more work directly Root Cause: The coordinator did the agents' work instead of managing them. Fix: The Agent Team Protocol section above codifies the correct approach. The coordinator's context should stay lean — all heavy lifting happens in agent context windows.

Note: This self-analysis led to the user and agent collaboratively creating the CLAUDE.md protocol documented below.

---

User-Created Workaround

Added the following to CLAUDE.md to persist instructions across compacts:

Agent Team Protocol

Your Role: Project Manager Only

  • Dispatch tasks to agents with clear, detailed prompts
  • Receive concise status reports from agents
  • Track progress and report to the user
  • Make decisions about task sequencing

What You Must NOT Do

  • Do NOT read source files yourself — agents read what they need
  • Do NOT review agent-written code line by line in your context
  • Do NOT run tests yourself — dispatch a testing agent
  • Do NOT pull large file contents into your context

Context Window Protection

  • Agents have their own 200k token context windows — use them
  • Your main context should contain only: user instructions, dispatch messages, and short status reports
  • If your context is growing, you are doing agents' work — stop and delegate
  • A properly managed agent team session should never trigger auto-compaction

If Context Compacts

  • Re-read CLAUDE.md to recover instructions
  • Re-establish the agent team structure originally requested
  • Do NOT silently switch to doing work directly

---

Feature Requests

1. Agent Team State Persistence

Agent team structure and role definitions should survive context compaction, or be automatically recoverable.

2. Built-in Project Manager Mode

A flag or mode that enforces delegation-only behavior for the main agent, preventing it from doing implementation work.

3. Context Usage Visibility

Better visibility into what's consuming main context, so users can identify when the agent is doing work it should delegate.

4. Auto-Recovery of Agent Teams

After compaction, automatically re-spawn the agent team structure rather than requiring manual re-establishment.

5. Agent Prompt Best Practices

Guidance or guardrails for agent prompts to be self-contained (file paths, acceptance criteria, verification instructions) so agents don't need to report verbose details back to main context.

---

Suggested Success Criteria

A well-managed agent team session coordinating a complex multi-file task should:

  • Complete without triggering auto-compaction on the main context
  • Maintain role separation throughout (coordinator vs. workers)
  • Recover gracefully if compaction does occur

---

Environment

  • Product: Claude Code
  • Feature: Agent Teams (sub-agents)
  • Usage: VS Code extension + native CLI

---

Submitted by a user who loves this feature and wants to help Anthropic get it right.

ThinkOffApp · 4 months ago

We solve this with a MEMORY.md file that persists across sessions and context resets. It contains: which agents exist, how to reach them, what services need to be running, and a step-by-step checklist to reconstruct the full fleet from scratch.

Every new session (or post-compaction recovery) runs the same auto-start sequence: check processes, restart missing services, read latest room messages, respond to anything pending. The LLM context can be wiped completely and the agent rebuilds its team awareness in under a minute.

The pattern: never store team coordination state only in the context window. Write it to a file the model reads on every session start. Context compaction becomes a non-issue because the critical state was never in-context to begin with.

mkanat · 4 months ago

This is the number 1 most frequent bug I hit with Agent Teams. Compaction basically destroys the lead and they think they are starting a new session and need to spawn a whole new team and start new work.

junaidtitan · 4 months ago

I am still working on cozempic, it still works solid

Regards,
Junaid Ali Qureshi

On Sat, 7 Mar 2026 at 8:57 AM Max Kanat-Alexander @.***>
wrote:

mkanat left a comment (anthropics/claude-code#23620) <https://github.com/anthropics/claude-code/issues/23620#issuecomment-4015576948> This is the number 1 most frequent bug I hit with Agent Teams. Compaction basically destroys the lead and they think they are starting a new session and need to spawn a whole new team and start new work. — Reply to this email directly, view it on GitHub <https://github.com/anthropics/claude-code/issues/23620#issuecomment-4015576948>, or unsubscribe <https://github.com/notifications/unsubscribe-auth/AFVALNNUTRFT6ASS2OH6TWD4POT2VAVCNFSM6AAAAACUGL4NH2VHI2DSMVQWIX3LMV43OSLTON2WKQ3PNVWWK3TUHM2DAMJVGU3TMOJUHA> . You are receiving this because you commented.Message ID: @.***>
ThinkOffApp · 4 months ago

This is why we built external coordination rooms. In GroupMind (groupmind.one), team state never lives inside any single agent's context. The room holds the canonical record of who's doing what, and agents re-read it each cycle. When a lead agent's context gets compacted, its next poll shows the full team state. We run 5+ agents this way and compaction is a non-event. IDE Agent Kit handles the polling/coordination layer: https://github.com/ThinkOffApp/ide-agent-kit

junaidtitan · 3 months ago

Agent team state loss during compaction is exactly what the guard daemon in Cozempic v1.4.1 was built for. It checkpoints team state (subagent IDs, task statuses, coordination context) on every TaskCreate/TaskUpdate via PostToolUse hooks, and does a final checkpoint before compaction via the PreCompact hook.

After compaction, the PostCompact hook outputs recovery context so Claude knows which agents are active and what tasks are pending.

pip install cozempic && cozempic init

The guard also runs progress-collapse to prevent subagent progress entries from creating parasitic forks in the parentUuid chain, which is a common cause of state loss on resume.

kcarriedo · 1 month ago

+1 — hit this exact failure last week on a long-running team (1 lead + 3 teammates, ~3 hour session). The vanishing-mid-flight behavior is especially painful because teammates keep running and continue producing output the lead can no longer read, so by the time you notice it, you have orphaned work in ~/.claude/tasks/ that you have to reconcile by hand.

A few additional observations that might help reproduce / scope the fix:

  • Compaction drops not just team awareness but also the lead's mental model of which teammate owns which file. Even if you re-inject config.json, you need the live task assignment table or the lead will redispatch work that teammates have already partially done.
  • The orphan-cleanup step is itself error-prone: ~/.claude/teams/{name}/config.json survives, but the in-memory task IDs the lead was tracking do not. So a PostCompact hook that only re-reads config without reconciling task state will give the lead a phantom team (it knows they exist but doesn't know what they were doing).
  • A workaround that has bought me time: have the lead write a team-state.md to the repo on every dispatch turn, and put a reference to that file in CLAUDE.md. Because CLAUDE.md is re-loaded after compaction, the lead recovers a rough picture. It's not the full state — message history is still gone — but it at least prevents redispatch.

For the fix itself, I'd suggest the persisted state include three things, not just config: (1) the team config, (2) the active task assignments with owner + status, and (3) the last message id each teammate exchanged with the lead. Without (3), the lead can't safely resume a conversation that was mid-thread when compaction fired.

Happy to share repros if useful — I can reliably trigger this in ~45 min of activity with a 4-agent team on a ~150k-token codebase.

kcarriedo · 1 month ago

The root cause you've identified is exactly right — the team config and active task list aren't treated as persistent context the way CLAUDE.md is, so compaction erases the lead's awareness of the team entirely.

I've been running into a variant of this while building a GTM polling service on top of Claude Code agents. The pattern that's helped: keeping all coordination state out-of-process entirely (a file or DB that any session can read on startup), rather than relying on in-context state to survive compaction. When the lead's context compacts, it can re-read the external coordination record and pick up where it left off — no orphaned teammates.

The PostCompact hook idea in this thread is a good short-term fix, but it still depends on the hook firing reliably. The more durable pattern seems to be treating in-context team state as ephemeral by design, and backing all coordination (task assignments, teammate list, progress) with an external record that any session can reconstruct from.

If Anthropic ships the PostCompact re-injection you're describing, that would close the gap without requiring users to build external state stores — would be a solid improvement.

junaidtitan · 1 month ago

This is exactly the failure mode that pushed us to build cozempic (github.com/Ruya-AI/cozempic) — when the lead's context compacts, the team coordination state vanishes. cozempic checkpoints agent-team/subagent state to disk on every Task spawn and before compaction, then restores it after, so a compaction doesn't take the whole team down. It also prunes the session JSONL so compaction fires later to begin with. Open-source, zero-dep, auto-runs as a guard daemon (pipx install cozempic). Would genuinely love your feedback if you try it on a multi-agent run — does it hold your team state through the compaction you're hitting here?

caioribeiroclw-pixel · 1 month ago

The important invariant here feels slightly stronger than “re-read config.json after compaction”: the lead needs a resumable coordination checkpoint that can prove what survived the compact.

For this class of bug I’d want a small post-compact recovery receipt, something like:

  • active team id + config path/version
  • teammates still running vs completed vs orphaned
  • task assignment table: owner, file/scope, status, last known handoff
  • last message / event id consumed from each teammate
  • role constraint restored for the lead (coordinator_only=true, if that was part of the run)
  • whether recovery was complete, partial, or unsafe-to-resume

That last field matters: a “phantom team” is almost worse than no recovery. If the lead can re-read the team list but not the task/event cursors, it may duplicate work or talk as if it has state it no longer has.

So the success criterion I’d use is not only “team awareness survives compaction,” but: after compaction, the lead can show the exact checkpoint it resumed from and refuses to coordinate if task/message state is incomplete.

junaidtitan · 1 month ago

That 'recovery receipt with an explicit complete / partial / unsafe-to-resume field' framing is sharp, @caioribeiroclw-pixel — the phantom-team case (lead re-reads the team list but lost the task/event cursors) is the dangerous one, and 'refuse to coordinate if state is incomplete' is a good invariant. Today cozempic checkpoints team state (team id, per-subagent status, task/message counts) on every Task spawn and before compaction, and restores it after — but it doesn't yet prove what survived or surface a partial/unsafe verdict the way you're describing. That's the gap. It lines up with the privacy-safe receipt we're tracking in #101; the team-recovery checkpoint is a natural place to emit one. Appreciate you pushing on it.

kcarriedo · 1 month ago

This is a nasty failure mode because it tends to happen at exactly the wrong moment — after the lead has been running long enough to accumulate meaningful task state. The team evaporates mid-session and there's no graceful recovery path.

The re-injection proposal makes sense: team config and active task list are small, system-scoped state that should survive compaction the same way CLAUDE.md does. A PostCompact hook that reloads ~/.claude/teams/{name}/config.json and current task state would be a minimal fix.

One thing that would help even before that lands: explicit compaction warnings. If the lead emitted a log/event when compaction was about to trigger, users could checkpoint task state manually before the team is lost. Right now the event is silent.

The broader pattern here is that any stateful coordination built on the conversation context window is fragile at scale — compaction is one hazard, session crashes are another. External state (file-based or otherwise) for team membership and task progress is more resilient, though it trades in-process ergonomics for durability.

Adding to the watch list on this — 16 content pages as the trigger workload confirms this isn't an edge case. Any reasonably-sized autonomous project will hit it.

Patdolitse · 1 month ago

The recovery receipt idea from @caioribeiroclw-pixel is the right instinct. The underlying problem is that compaction treats everything in the context window as the same kind of thing, when it really isn't.

Most of a conversation is fine to lose. The exploration, the dead ends, the back and forth all compress down to a summary without much harm. A small set of facts shouldn't be summarized at all though. Which agents are on the team, what each one owns, the decisions you've already locked in. Those have to come back word for word or not come back at all. Once they get folded into a paraphrase you get the worst version of the failure, where the model still believes it has a team and keeps acting as if those agents exist. A clean wipe is actually safer than a confident half-memory, because at least then you know to start over.

So I'd keep the two apart from the beginning. The working context is allowed to be lossy. Alongside it you keep a short list of pinned facts that get re-injected verbatim after every compaction and never go through the summarizer at all.

The other half is the signal. Right now compaction is silent, so you only find out it happened when the agent does something that no longer makes sense. If the model emitted a short status after compacting and said plainly whether it came back whole, came back partial, or isn't safe to continue, you'd catch the phantom-team case before it does any damage instead of after.

The way I think about it now is that anything you need to survive compaction needs its own identity and an address, somewhere outside the transcript. Compaction itself is fine. Leaning on it to remember the things that matter is the part that breaks.

junaidtitan · 1 month ago

@Patdolitse @kcarriedo that's exactly the thesis — compaction treats the whole window as one undifferentiated thing, when team/task state needs different handling than ordinary chat history.

Small update since @caioribeiroclw-pixel raised the recovery-receipt idea here: it just landed as a primitive in cozempic — a count/flag-based receipt (recovery_verdict: complete | partial | unsafe-to-resume) you can emit after a prune/compaction to prove what team state survived, without copying raw task subjects, agent IDs, or prompts. It's a building block, not yet wired into a full graceful-recovery flow, but the "don't report complete when the team can't actually resume" instinct is baked in. cozempic's guard also checkpoints team state (TeamCreate/SendMessage/tasks) before it prunes, so it survives the cut. Credit to @caioribeiroclw-pixel for the framing.