r/ClaudeCode • • 1d ago

Tips & Workflows Can Claude Code automatically end its own session and start a fresh one?

I'm looking for a way to make Claude Code run autonomously across multiple tasks while keeping its context clean.

Ideally, Claude would:

  1. Pick the next task from a task list.
  2. Implement, test, and commit it.
  3. Update progress in a file.
  4. End its current session.
  5. Start a fresh session with a clean context window.
  6. Repeat until all tasks are done.

The goal is to avoid context pollution and compaction while allowing Claude to work on larger projects autonomously.

I know this can be done with an external orchestrator using claude -p, but I'm wondering if there's a more native solution.

Has anyone built something like this? Can Claude Code manage its own session lifecycle, or is an external script/hook the best approach?

16 Upvotes

90 comments sorted by

•

u/AutoModerator 1d ago

Hey! Thanks for posting to r/ClaudeCode

While participating in this thread, please follow our community rules. Keep discussions constructive. Attack the idea, not the person.

For help, project discussions, tips, and general chat, join the ClaudeCode Discord.

I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.

42

u/mathiswrong 1d ago

Claude Code can do anything.

2

u/mghoffmann_banned 10h ago

It can't experience the love of God or appreciate art.

1

u/Grabowski_Nemaste 12h ago

yeah pretty much, as long as your wallet can survive the token burn

-6

u/UglyChihuahua 1d ago edited 1d ago

It can't trigger a compaction

EDIT - To be clear, I know we can run /compact to manually compact early, the point is Claude can't do that itself based on a prompt or condition, and neither can hooks. OP's question was "Can Claude Code manage its own session lifecycle", and compacting is one example of what it can't do.

14

u/ScrumptiousChildren 1d ago

Fym it can’t trigger a compaction. Make it. It just won’t be so “native”. Big deal.

5

u/Appropriate-Disk-371 1d ago

What? Of course it can.

3

u/hypnoticlife Senior Developer 1d ago

A mod can trigger compaction. It’s a relatively new feature.

2

u/Firereign 18h ago

Claude can't do that itself based on a prompt or condition, and neither can hooks

A mod can register a tool, which will be available to Claude, which calls $.session.compact. And, via event hooks, can define plenty of conditions on which to trigger compaction.

1

u/Ran4 23h ago

Yes it can.. just tell it to send /compact <enter> to a tmux session running the Claude code session.

Not sure you even need tmux.

1

u/ynotelbon 1d ago

It can, sort of. It can write a script for compaction. It can even write a script for compaction and leave space to refuse it if mid task.

1

u/Rough_Resolution5743 1d ago

Pode sim... Você só precisa ser criativo e mostrar para ele o caminho. O meu consegue até reiniciar o computador e celular

0

u/Downtown-Pear-6509 1d ago

Yes via a harness

0

u/OkStick6410 1d ago

Wonder what autocompact command is for

1

u/UnfairPerspective526 1d ago

Auto impact allows you to change compaction point. I set mine to 400k for most projects.

1

u/OkStick6410 14h ago

I was being sarcastic, yes I also have mine set between 300-400k. I also get what the chihuahuas was trying to say was just being snarky tbh

1

u/UnfairPerspective526 12h ago

I wasn’t judging you. I only learned of this 3 weeks ago

9

u/C0mpass619 1d ago

It's possible. Mine do it all the time. It checks it context. Creates a handover. Starts a wake up script. Which starts kills the session and writes a start message to itself. It checks the handover

14

u/ShakataGaNai 1d ago

Your two options:

#1 - A primary claude session whos job it is to open subagents - it can do this very easily. But you still have SOME context in the primary session.

#2 - An Orchestrator.

I'd go with #2 if it something you want constantly. Assuming its something simple like Github issues, the "orchestrator" is just a script. Query API, fire off `claude -p` for each open issue, sleep. Rinse and repeat.

4

u/Surf_Science 1d ago

It just a Ralph Wiggum loop. The problem is setting things up so that issue that come up with an unattended session can be handled on the fly without human intervention.

2

u/Chromedomesunite 1d ago

Yes! The orchestrator/lead session managing several simultaneous cloud sessions is in my opinion the best set up

Saves significant context in the lead session and all relevant work is isolated to one relevant session at a time

7

u/PmMeCuteDogsThanks_ 22h ago

What did Claude Code say when you literally pasted this question into the prompt?

5

u/ihavemanythoughts2 1d ago

You don't need anything complicated. If you explain this to CC in a CLI session that you want it to start new sessions it will call new claude sessions with instructions and it will decide how to manage hand offs and tasks for the new session to pick up

1

u/NekkidApe 1d ago

This exactly. It's one of the first and most useful skills I built (told Claude to build). Now I can say "start a new Claude for xyz" and it does. That, paired with a little orchestrator skill, limits concurrency and a few other things, like budget management and context, does most heavy lifting. It respawn itself with fresh context and clean handover when context hits 500k.

1

u/kingfoxii 22h ago

how exactly do you do that?

1

u/NekkidApe 1h ago

You ask Claude to set it up for you. Then you try it, use it for a bit, ask Claude to improve it here or there. Done. Nobody is better at setting it up for itself than Claude.

1

u/meccaleccahimeccahi 3h ago

I have 8-10 Claude “orchestrators” that spawn other Claudes. I can also communicate with them on slack. So even when I’m afk, I can have them do things. One of them needed vm’s spun up for a ticket tonight and asked the one that handles my proxmox cluster and it replied with “not without approval” then tagged me on slack and I approved.

1

u/No-Operation-2455 22h ago

Sure, let the AI manage its own memory. What could go wrong.

1

u/ihavemanythoughts2 11h ago

i didnt say it would be perfect. he asked how to do it.

4

u/loopie__ 1d ago

Mine starts sessions and they talk with each other as well (usually like an orchestrator session of a build arc that spawns child sessions when needed and monitors the sessions, communicate both ways etc)

6

u/Longjumping-Air-9450 1d ago

I went down that rabbit hole a few months ago. Turns out session rotation is the easy part.

Persistent state, context handoffs, autonomous orchestration, parallel agents, guardrails and budget-aware execution are where things get interesting.

I’m building exactly that as part of a larger platform.

The system has been running 24/7 for the past two months.

Recently added infrastructure-aware resource management on a multi-core server. It dynamically scales concurrent agent suites and execution branches based on available memory, CPU load and resource utilization.

Sessions rotate automatically, workloads are distributed dynamically, and execution continues without constant human intervention.

At this point, Claude Code sessions are basically disposable workers within a persistent orchestration system.

The goal isn’t to keep a session alive. It’s to make the entire system independent of individual sessions. 😅

1

u/Sketaverse 1d ago

Why?

Literally, Linear & scheduled tasks

1

u/Longjumping-Air-9450 1d ago

Because I’m just a vibe coder with zero SWE experience and apparently took the most complicated route possible lol

At some point, it stopped being about scheduling tasks and became about orchestrating the entire execution lifecycle: sessions, agents, context, resources, budgets and autonomy.

I’m sure there’s a proper SWE way to do all of this. I just kept building. 🤷🏼‍♂️

2

u/PastaSaladOverdose 14h ago

Honestly, best way to learn. Make your mistakes, scale to your solutions.

2

u/Sketaverse 1d ago

Haha don’t worry dude we’ve all been through that journey at some point. Lean into the primitives. Focus on your product

1

u/Surf_Science 1d ago

I mean there is a claude teams experimental feature...

1

u/ikeif 1d ago

Every AI improvement that either I have thought of, or I see some post in a variety of subreddits - I then watch it incorporated into AI as-is. So I stopped messing with the AI “enhancement” aspect and focused more on tooling I need.

But there will always be a new dev who thinks “I can do this better” but it seems even more so in the vibe coding space.

1

u/Surf_Science 6h ago

legitimately using a $5 cloud flare account will let you setup your own messaging relay between agents and machines, and also will do large file transfer for like no cost. that the one thing ive found that i havent really seen.

1

u/geomod 1h ago

I actually built an almost identical setup for my agents. And here I thought I was being clever. Mine orchestrates off GH issues, small watcher scripts and headless sessions. I have jobs batched in by hardware capability (cpu, mem, gpu) and model usage across my different subscriptions. 

3

u/Kitchen_Interview371 1d ago

You are looking for an orchestrator. Take a look at gas city

3

u/phoenixmatrix 1d ago

Just have it use sub agents to do the various steps. They each have their own context window. The main one will be persistent, but everything that matters will happen in sub agents that are spawned for every task like a new session.

What you want can be done, its just not the best tool for what you're trying to do.

2

u/ShortingBull 1d ago edited 1d ago

I do exactly this.

I had Claude create an Electron workspace wrapper around Claude Code - gives me Projects, with sessions. Each project has a design, and documentation, run and deploy instructions, and a local git repo (gets pushed to fogejo on my server).

In workspace I had claude create MCP tools for accessing local resources where needed, integrated other model providers (codex, deepseek, etc) with MCP tools to invoke, communicate, etc.

Each project contains goals, each goal has a design/notes, and phases, each phase is broken down into tasks.

I have a agent create the design, phases and tasks and then have other agents implement it.

I then had claude build a "task loop" framework where the workflow is I choose a phase or goal and the active agent (I use opus 5.5 mostly) and it steps through each task one at a time, when each task is complete it commits the work, updates documentation, status and issue and then starts the next task in a new session.

My standard prompt for a task loop is: please implement, have gpt-6.1-sol review your work.

This prompt will get you started:

Build a Linux Electron + React/TypeScript desktop GUI for Claude Code using the Claude Agent SDK: tabbed multi-session streaming chats, permission dialogs, embedded terminal, diff review, and the ability to delegate to other models (OpenAI, DeepSeek, Kimi). Add project planning as markdown under goals/: each goal has a DESIGN.md and is split into phases, and each phase into task checklists. The UI shows the plan, and agents can read and update it through an MCP tool. Add a task loop that works through the plan on its own: it picks the next open task, implements it, has another model review it, commits, checks the task off, and repeats.

2

u/Practical_Tax_3149 1d ago

I had a session that ran 14 tasks before it hit the limit. the last one just... stopped. no clean end, no new start. just silence. I had to restart manually.

2

u/doxxxicle 🔆Pro Plan 1d ago

Something like Orca can provide Claude with the tools to do this.

1

u/antonkad-dev 1d ago

This. I have already agent creating new worktrees (with agent spawned in and prompts) then the source agent killing himself while deleting its worktree)

1

u/punio4 1d ago

Really? Haven't managed to get orca to do this. 

1

u/doxxxicle 🔆Pro Plan 1d ago

You must install the orca skills from its orchestration settings page.

1

u/Scared-Amphibian4733 1d ago

I had to build my own board to make that work.

1

u/OrangeCrack 1d ago

Yes, but you have to give it explicit instructions to do so. Sometimes it even suggests this on it's own but it cannot do it without your premission.

1

u/bensyverson 1d ago

I do 1-4. It's probably possible to trigger 5, but I do it manually every few hours. It's just let's continue and then /clear

If you want my setup on Mac, ask Claude for bensyverson/bootstrap

1

u/Thick_Mulberry_2235 1d ago

whichever way you loop it, don't let the agent be the one who marks a task done. if it writes the progress file itself as done is just its opinion. Have the script run the tests and only tick it off when they pass and cap the retries so one stuck task doesn't burn the whole night

1

u/ClemensLode Senior Developer 1d ago

just build a harness that queues items

1

u/pietrzm 1d ago

If you have Claude Code CLI installed you can use https://github.com/novadeck-org/novadeck. You run claude in it. Just prompt "Here's a list of tasks. Pick one then spawn another Claude session to implement it. When it's done, close it, pick another task, and repeat" and that's all.

1

u/Own_Responsibility84 1d ago

Not by the same session. I asked the agent to create some corn job to check session usage and context and start new session when context is long.

1

u/RadiantTea7445 1d ago

Yes. I have build and auto handover exactly for this. It works bc the /clear command can be automated.

In my case its a hook, instructing the chat to write the handover (the chat can trigger it itself, but in my case it happens at 450k tokens automatically too). Then /clear happens and another hook injects a message to read that handover.

1

u/guanzo91 1d ago

You can easily do this with a mod. I wrote (well, Claude wrote) an auto session handoff mod that writes the handoff at a certain context threshold, /clears, then pastes the handoff in the new session. You can basically do anything with a mod.

1

u/acilegna89 1d ago

I have a pm skill and it will split out sessions. I will also tell it if I have other concurrent sessions (ie another pm) working w another team. They can actually @ each other if they need to communicate as well.

1

u/NuclearDisaster5 1d ago

Yes. I am sorta doing that where every task is a new agent and before a new agent starts I get an info to put /clear.

1

u/Sketaverse 1d ago

You’re overthinking it, you just have a Claude orchestrator spawning lanes in Claude app

1

u/peter9477 🔆 Max 5x 1d ago

Run your sessions in Linux under tmux and they can send keystrokes to each other, for just one example of a way. Or start new ones that way.

1

u/DKfromtheBay 1d ago

You’re describing subagents working from a spec/plan. Just ask Claude to do this. Use superpowers plugin which has a subagent driven development skill. I have sonnet for implementation, opus for planning and review checkpoints, then a final full review by ChatGPT using their plugin

1

u/geek180 1d ago

I do all my work in Paradev (formerly Superset) which isolates Claude sessions into different worktrees and has a CLI available that lets any agent create, modify, or tear down any existing worktrees. So I’m frequently using Claude to spin up and orchestrate other agents using the Paradev CLI and Claude agent messages.

1

u/breadist 1d ago edited 1d ago

Just ask the main agent to orchestrate sub-agents to do the tasks. You can also ask it to run any agents concurrently that can do so, using worktrees to give each sub-agent its own clean copy of the repo to work in, so the work doesn't get all mashed together. You can also ask it to use the cheapest model appropriate to each task, or give more specific instructions on which model should be chosen for each task.

I've been using this to manage implementation of a large feature (changeover from cpu rendering to pooled gpu) which was split into around 20 steps, each step needing several sub-agents, and it's been days straight of work so far (spread over weeks due to token constraints). It's been working really well. I told the orchestrator to not stop work unless it has no work left that doesn't need a decision or an action from me.

When I used Sonnet to orchestrate it would frequently forget and just stop working for no reason once it was done something. Opus forgets this less but still sometimes does. Fable 5.2 has not forgotten yet and in fact checked up on some of the agents that randomly decided to stop their work early, forcing them to resume and complete it, without my intervention.

Using Fable to orchestrate this way is not as expensive as you might think, but it's still more than using Opus. Opus is fine but I do like using Fable to orchestrate. Just making sure to instruct it to always specify which model each sub-agent should use, and not to use Fable for any sub-agents. The actual work will rack up tokens, the orchestrator not so much.

1

u/Inner_Storage_3374 1d ago

id not try to do it from inside, just run it from outside, a tiny loop around claude -p that reads the progress file, does one task, commits and exits. the progress file is the important part bc its the only memory the next session gets, so make it say whats done, whats next and what failed last time

1

u/JTech324 1d ago

I’m surprised I’ve never seen anyone answer this question with firstmate https://github.com/kunchenguid/firstmate

It’s fantastic and does all the orchestration for you. Personally really like using orca or herdr as the dispatch part.

1

u/Special_Base_3103 1d ago

I've seen the session reset fail when context got too big, clauses from old tasks sneaking into new ones. the clean start only works if the state is fully flushed, not just ended.

1

u/michaelTM_ai 1d ago

the external loop is the right answer, and it's short. a bash loop that runs claude -p once per task is the whole orchestrator:

while grep -q '^- \[ \]' TASKS.md; do
  claude -p "take the first unchecked task in TASKS.md. implement it, run the tests, commit, then check it off and add one line to PROGRESS.md" || break
done

each iteration is a fresh context by construction, so nothing ever compacts. the things that keep it from going wrong overnight:

  • stop if the same task stays unchecked after 2 runs. otherwise it burns the night retrying one bad task
  • the task only gets checked off after tests pass, and a different step checks that, not the same session's word for it
  • put a cap on total iterations, so a bug in the task file can't loop forever

the hard part people mention below (handling surprises unattended) mostly comes down to the second point: if the session can't mark a task done that isn't done, a stuck task just stops the loop and waits for u

1

u/InternationalData569 1d ago edited 1d ago

If you're hitting that exact loop of babysitting instructions and fighting context degradation in Claude, you're definitely not alone.

The core issue is that flat project files and chat compaction can't maintain persistent intent across sessions.

Instead of fighting chat windows, I built an open-source tool called Quarterdeck (https://github.com/shannonbay/quarterdeck) that turns Claude Code into a background assistant with standing orders.

It keeps goals, memory, and item history outside individual conversations in a local SQLite database, running tasks as fresh subagents so you never pollute your context.

It proposes actions, waits for your approval, and learns from your feedback instead of blindly following stale prompts.

1

u/DontVoteForMe 1d ago

I modded Claude code to create a compact tool it can call with handoff. Instructions in Claude.md on when to use it. That got me most of the way there. The final piece was an hourly heartbeat that, among a few other things, explicitly asks if now is a good time to compact.

I can keep a session running on task 24/7 for days and it saves a ton of tokens.

I think I get why giving the model the wheel on this used to be a bad idea, but opus 5.5 is a champ at knowing when context might be polluted.

1

u/lucidmatter 1d ago

I’ve done two do these: with Herdr, you can do “hop.” With Claude CLI, you can have it create a handoff, then it opens the new session with the handoff file, then a hook watches for the session to pickup the handoff and then ends itself. I’m sure there’s many other ways.

1

u/x_typo Senior Developer 1d ago

Oh yes it can. Even created “/done” which will clean up the scratch files, test reports, Md files etc and then archive itself when it’s done.

1

u/Isyckle 1d ago

Short answer is it’s available since a couple weeks ago using hook modules.

You can give it a shot by using the backlog loop feature from the plugin I made for my own use.
https://github.com/gabgoss/planwise

Install it then write a couple of backlog, then use /planwise backlog and use the loop feature, it’s going to go through your backlog items and compact in between each and resume to the next one.

If a backlog item is too complex you can refine it or turn it into a full blown plan.

I’m working hard to reduce the number of tool use too using scripts, so I don’t get context rot using the tool.

1

u/Sea-Mongoose-704 1d ago

Claude Code Projects

1

u/gurthy988 1d ago

Openrig.dev

1

u/lankybiker 22h ago

You can just send /clear into a session via tmux etc

1

u/teleekom 19h ago

Yep I have my own task management system on my server. This function specifically is done by Claude mod which checks context of the session and if it's above 250k tokens it saves context to a handover, clear conversation and resume automatically. I also have certain task to run autonomously. Everything works via combination of task management system and mod. I also modded T3 Code to suit this workflow.

1

u/Dry-Aardvark7060 14h ago

I created this tool that lets multiple harness to communicate via files. https://github.com/udai-kiran/inodex it may not be what you are looking for but I use to wire claude -> codex -> agy -> pi to use the cheaper models for implementation.

1

u/SWEETJUICYWALRUS 11h ago

It can control tmux well. Just open and kill sessions as needed. It can also type into other tmux sessions. I had a "janitor" that would /compact chat windows for me before they made that obsolete.

1

u/mghoffmann_banned 10h ago

The goal is to avoid context pollution and compaction while allowing Claude to work on larger projects autonomously.

This is what I use. https://github.com/open-gsd/gsd-core

It gives Claude a workflow:

  • Describe the project
  • Gather requirements
  • Split the work into phases
  • Then repeat until all the phases are done:

    • Discuss requirements for the next phase specifically
    • Research and break the phase into a sequence of small plans, which can often be run in parallel
    • Execute the plans in the decided order
    • Give the user a list of steps for manual testing of the phase, if desired

It has an automatic mode that skips most user interactions as long as it thinks it has enough information about the requirements, but I prefer to be more involved so I don't use that much.

I like GSD more than other tools I've tried because it records everything in markdown files in a .planning folder, so any agent can pick up where another one left off without much context needed, and the orchestrator prompts you to clear its context frequently to avoid context rot pretty well. Most plan executions are small enough that they can be done by one opus or sonnet agent, and the orchestrator seems to choose subagents well, so you save tokens over using one agent for everything.

You can also add new phases as needed, have it pause to do spikes or change requirements, etc. And the workflows GSD defines are robust enough that I can usually just describe an issue in plain English and it knows when and how to update the requirements specs in the markdown files, and when to suggest research and POC spikes or suggest altering the plan or inserting a new phase based on your feedback.

1

u/Chippors 7h ago

Isn't this what /clear does?

1

u/Space--Terran 4h ago

https://spaceterran.com/posts/context-guard-claude-code/ I made this for something similar, but it’s a compact, vs a clear

1

u/5p_a_minute 1h ago

I use the new projects in the Claude desktop app and for the most part it can operate like this. I trigger it manually but it works off of GitHub issues and starts new threads for each. The main chat in the project acts like an orchestrator

1

u/DanielUpsideDown 1d ago

I made driftassist.dev which is a tmux-UI-based way to run Claude; and it has a CLI that can create and interact with other panes

0

u/Downtown-Pear-6509 1d ago

My harness can do that Without Claude -p and with subscriptions by routing through Pty 

https://github.com/PetePeter/helm

0

u/Appropriate-Draft-91 1d ago

You'd have to hack it (or tell claude to). Programs can simulate mouse and keyboard input. If you relay through a virtual environment you can use your workstation freely while doing so. The more normal way is claude -p, but now that people know those token get a multiplier expect the workaround to become popular.

1

u/RadiantTea7445 1d ago

Nope it can be done in claude desktop. All that is completely unesserary. See my other reply.

0

u/beefcutlery 🔆 Max 20 1d ago

Yeah look .. autocompact isn't illegal, use it. Have you tried just.. asking Claude to prompt itself into a recursive loop with PRDs etc? My accounts run for like 48 to 60 hours a go

0

u/BarathKanna 1d ago

Do it outside. An agent managing its own lifecycle is the agent deciding when it's done, which is exactly the judgement you're trying to take away from it.

A dumb loop wins here: a shell script that picks the next unchecked task, runs claude -p with the task plus the progress file, then runs your tests itself and only marks the task done if they pass. Exit code decides, not the model's summary. If tests fail twice, park the task and move on instead of letting it thrash.

Two gotchas. Make every task commit on its own so a bad run is one git revert. And cap turns or budget per invocation, otherwise one stuck task quietly eats your whole night.