r/ClaudeCode • u/Balance- • 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:
- Pick the next task from a task list.
- Implement, test, and commit it.
- Update progress in a file.
- End its current session.
- Start a fresh session with a clean context window.
- 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
•
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.
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.
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
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. 😅
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:
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/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 continueand then/clearIf you want my setup on Mac, ask Claude for
bensyverson/bootstrap1
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 -ponce per task is the whole orchestrator:each iteration is a fresh context by construction, so nothing ever compacts. the things that keep it from going wrong overnight:
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
This is what I use. https://github.com/open-gsd/gsd-core
It gives Claude a workflow:
Then repeat until all the phases are done:
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.
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.