This is how I build several products at once. One session holds the big picture and sets tasks, subagents write code in their own branches, a separate session reviews the result, and hooks enforce the rules the model forgets. I run all of it, plus chats, production and service dashboards, from one conversation with Claude. Agents have access everywhere, so tasks get finished, not handed back. Below is how it works and how to start with your own
How I use Claude Code outside of software is in a separate guide (in Russian). This one is about code and the tools around it
A harness is everything around the model: rules, agent roles, checks, how agents wait and how they remember. Everyone has the same model. The results depend a lot on what is around it
I did not design it up front. Every piece came from something that broke. An agent did the wrong thing, I corrected it a second time, the rule went into a file, the rule in the file did not hold, and then a hook appeared. Almost every rule in my files has a date and the incident that caused it
A normal day looks like this. I give a task by voice to the orchestrator session. It checks whether this was already done, starts a subagent in a separate branch, the subagent writes code, opens a PR and stops. CI and review run on my own machines, PR events come back to the session by themselves, and a green PR is merged without me. Several such sessions are open at once, each with its own task
CLAUDE.md~/.claudeCLAUDE.mdCLAUDE.md keeps one line and a linkEvery rule has the same shape: what to do, why, and the case that caused it. A bare ban gets followed literally and does not carry over to the next similar case. Here is a line from my file, almost as is:
- .bak before editing anything outside git:
~/.claude/*, server configs, state files, DBs.
Tell subagents explicitly. Destructive things
(refresh, rotation, migration) – on a throwaway
copy. Case: an agent tested a token refresh on
the live account, the token rotates, old backups
went stale, two automations died with 401
When I correct the same thing twice and say “again”, “I told you”, “always”, the session writes the rule into the right file in the same turn and tells me where. If a machine can check the rule, the next step is a hook
The general skills I use most:
orient, divedo-it-nicelyacceptpublish-static-filesave, sessionswrite-as-me, antineuroretroI write a skill description from the phrases I actually use to ask for that work: “publish the report”, “give me a link”. The model reads the description to decide whether to load the skill
A hook is a script Claude Code runs on an event: before and after a tool call, when a turn stops, before context compaction, at session start and end. I have around forty of them on ten events
The rule “use git -C X, no cd X && git” sat in the text for a long time, and subagents broke it in half of their calls. Now a hook rewrites such a command itself and tells the model in one line what actually ran. Rules are read at session start, the mistake happens hours and a couple of compactions later. Subagents never see the startup warnings at all
A hook can do three things: refuse (exit code 2 or permissionDecision: deny), give the model a hint (additionalContext) and rewrite the command in place (updatedInput). The most useful ones I have:
cd && git, stop a subagent from waiting for CI, no merge without green checks, no git add -A, no full test runs or Docker on the laptop, no ssh agent forwarding to a serverclaude -pstop_hook_active and blocks at most once per turnOn top of the hooks I run with tool auto-approval. Without them I would not: guards first, then take the brakes off
The main session does not write code, not even small fixes. It plans, sets tasks, reviews and merges. Implementation eats the context in about an hour, and a session that holds several products in its head starts to get confused after that
Subagents have roles. I set the model explicitly: by default a subagent inherits the parent's model, and mechanical work ends up on the most expensive one
Money, migrations, security and review judges always run on the top model. Research and simple implementation moved to the middle one, because the checks hold the quality: the judge sees only the diff and the contract and catches a mismatch whatever model wrote the code
An agent definition is a plain file with a header:
---
name: razvedchik
description: Read only. Code search, research
before a task, triage. Never edits, commits
or sends anything out
model: sonnet
tools: Read, Grep, Glob, Bash, WebFetch
---
Answer with facts: path:line and a quote.
“It does not exist” – only from code and data
paths. The backlog does not prove absence
The last line is from an incident: twice an agent wrote “not there” based on the backlog, and the feature was already in the code
The orchestrator always puts the same things into an implementer's prompt: edit only in the worktree, backup before editing outside git, background jobs only under timeout, full paths, temp files outside the repo, nothing heavy on the laptop. An agent gets one stage of work. A long agent rereads its whole context on every turn, so the next stage goes to a fresh agent with a short prompt
Every task lives in its own git worktree with its own branch:
git -C ~/code/app worktree add \
.claude/worktrees/fix-login -b fix-login origin/main
Switching branches in a shared checkout affects everyone, and the second session silently breaks the first one's tree and index. So nobody edits or switches the shared checkout, it is only fast-forwarded to fresh main with merge --ff-only, and a hook keeps edits out of it
Sessions do not know about each other, Claude Code gives them no shared memory. So there is a board: a folder of JSON files. A session registers at start, sees its neighbours and can claim an area (all files of one product, for example). An edit in someone else's area gives a warning. Liveness is checked by process pid: once a session decided its neighbour was dead because it had been quiet for forty minutes, and took over its branch
Sessions can message each other, but only with a task or a question the receiver needs to move on. Every message wakes a session, and it rereads its whole context. A hook drops receipts like “got it” and “thanks”
My laptop holds about ten live sessions. A session that has nothing left but waiting closes itself, more on that below
A PR is the unit of deploy, rollback and review. Each one costs a CI run, a judge verdict and a place in the queue, so a PR holds what ships and rolls back together. I split when urgency or risk differ: a hotfix does not wait for a big PR, money and migrations stay apart from cosmetics. A chain of “part 1, part 2” PRs for one piece of work is almost always a mistake
CI runs on my own machines: builds and tests on a build machine, deploys on a server. On the laptop only lint and the unit test of the changed file. Typecheck moved off the laptop too, one tsc for the monorepo took 5–6 GB of memory there. A command runs it remotely and returns output and exit code like a local run. A hook refuses full test runs, Playwright and Docker on the laptop
Deterministic merge gates are one script. CI calls the same script, so “green on my side” and “green in CI” match by construction. Pre-push runs the fast half of these gates in seconds
Whoever wrote the code is a poor judge of it. The verdict comes from a fresh headless claude -p session with a pinned model and read-only tools. It gets the diff and the task contract and has not seen the implementation. The verdict is bound to the SHA of the branch head and committed right away, so a new commit needs a new verdict
Every acceptance item in the contract links to a test that fails when the change is rolled back. The implementer checks the rollback by hand and writes a table: what changed, which test, did it go red on rollback
Three quarters of the judge's rejections turned out to be real behaviour bugs, almost all of one kind. So before pushing, the implementer walks the diff through five failure paths:
A heavy CI run that went red because of the PR is a lesson for next time. I close it with the strongest tool available: a check in pre-push, a test that must run before push, and only if a machine cannot catch it – a note with a path glob that lands in the implementer's prompt and the judge's checklist by itself. A flaky test is a bug with a fix ticket, a rerun without a ticket is not allowed
Green PRs are merged without me. Urgent ones get labels: urgent – someone is waiting right now, critical – production is broken for users or money, and that run pushes everything else off the CI machines
Every turn of an agent rereads its whole context. After a pause longer than five minutes the prompt cache expires and the reread is paid in full. An agent that waits for CI in a “check, sleep, check” loop burns hundreds of turns and does nothing. This turned out to be one of the biggest items in my spend
Before, every watcher, every session and every script polled GitHub on its own. We ran out of the API rate limit three times in one week, and then everything stopped at once. Now one bus on a server polls GitHub: webhooks plus a reconcile every one to five minutes keep a snapshot of every PR in a database (checks, verdict, conflict, merge, deploy). Everyone else reads from the bus, and waiting is a subscription to an event that does not touch the GitHub limit. If the bus is down, clients get exit code 75 and fall back to the old path
The bus delivers meaningful events to the session that owns the PR: red CI, red verdict, conflict, a human comment. No owner – the event goes to the on-duty session. “Merged, nothing to do” does not wake anyone, such events pile up and arrive as one line with the next real wake-up
The implementer pushes, opens a PR, records it in the wait registry and finishes. A hook refuses any blocking CI wait in a subagent and answers with the ready command to use the registry. The exception is a step that cannot happen without waiting: one wait per agent life, at most 15 minutes, with the limit written into the command itself
A session that has nothing left but waiting for its PRs hands the wait to a separate “Merges and CI” session and closes. When the event comes (merged, deployed), a timer wakes the author with a note on what to do next. A hook does not let a session with a large context schedule wake-ups for itself and suggests an event subscription instead
Claude Code auto-memory is off in settings, and a hook blocks writes to it. Everything that lives longer than a session sits in repo files, where git and any other session can see it. Product decisions are one file per decision with a date, process rules live in a shared core and are copied into every product. Machines and access are described in one file. Secrets never go into git, they live in env files with mode 600, and the repo has a pointer to them
Before any task the session searches whether it was already done: the database of past sessions, my data, the product's research, neighbouring repos. Before saying “this does not exist” or “the API cannot do it” – the same search. When I say “this used to work”, it is treated as a regression to check. The rule appeared after an agent built a document package from scratch while a finished one was already there, with a checklist and a fixed error in the data
Numbers I ask for often come from one ready command. If it took a subagent search to get one, that search becomes a new subcommand in the same turn
Before a session closes, the save skill pushes loose ends into branches and PRs and writes a handoff for the next session. Before compaction a hook builds the state snapshot, see above
I counted my corrections over three weeks: 8% of my messages to sessions were corrections, and the most common reason was an agent asking instead of doing. The list now looks like this
No question, report after: an answer on a topic I already discussed, a draft, a deploy to staging I am waiting for, merge on green checks, committing and pushing its own work, deleting its own drafts, sending after I say “send”, an obvious choice
Ask: money, commitments in my name, a new recipient or client, production data (migrations, deletion, secret rotation), the rules of the harness itself
A question goes as one block at the end, with a default: “if you stay silent, I do A”. By then option A is already running, because silence will not continue the turn. Each question is saved as a file right away: the point, options with risks, whether it can be undone, a recommendation. I answer when it suits me, and the answer reaches the session even if it is already closed
In one week in September about sixteen “done” reports turned out to be false once you opened the thing. “Opened the live site on phone and desktop, all good”, and the link preview had old text and the phone showed an empty band. “Data is loaded”, and the client saw zeros. “Visible” had been checked as “returns 200”
Now “done” about something a person will see is written only after a screenshot of the exact address that goes to that person, on phone and desktop. The report says what exactly I looked at. If it cannot be looked at, the report says so. A stop hook catches “done” without a screenshot
The post-deploy smoke test checks content too. Once a kiosk subdomain returned 200 and showed the admin login page. Now every important surface has a text marker that must be on the page and a marker of what must not be there
The browser for these checks runs only headless. Once an agent opened a real Chrome window moved off the edge of the screen, and the window still popped up over my work
Chats, production, GitHub, service dashboards and the terminal itself: I run all of it from one place, a conversation with Claude. What matters most is that agents have access everywhere I work. So a task does not end with “prepared it, the rest is yours”. The agent posts in the chat, merges the PR, restarts the service and checks the result itself
Access is narrow: on a server each role has its own key that can do only its job. Money and anything irreversible go through a question to me, and anything outside git gets a backup before an edit
One session watches all my work chats, production and PRs at once. Watchers write event lines into a single stream, and while it is quiet the session spends zero tokens. Each event goes through the same ladder: understand it, apply a safe reversible fix itself, hand a task to the right session. It writes to me in one sentence, and only about what cannot be solved without me. A watcher's alert goes to the on-duty session first, and if it acknowledges within an hour, the alert never reaches me
chats ─┐
prod ─┼─► one stream ─► on duty
PRs ─┘ ├ fixes it
├ task to a session
└ one line to me
Twice a day the on-duty session restarts: a new tab takes over the role, the old one writes its loose ends to a file. That keeps the context small
Sessions live in tabs of agterm, a macOS terminal you can drive with commands. So agents open and close tabs themselves. A dispatcher session opens a tab for a new task with a ready prompt, revives a crashed one so it can finish its work, and closes the finished ones. I get a summary in three parts: done, waiting for you, in progress
sess new --name "fix login" \
--prompt-file task.md
sess list
sess resume <id>
A session with nothing left but waiting for its PRs hands the wait over and closes itself. A new task on a product goes to a fresh session, not to one carrying all the old context: every turn rereads the whole context, and you see it in the limits
Many tasks need a login to a service dashboard: a bank, a payment provider, an app store, an admin panel. I used to copy cookies from DevTools. Now I log in in my own Chrome, and a small extension hands the session to the agent on the same Mac. It talks to a local program through Chrome's native messaging, with no port and no server, so cookies never leave the machine
“Logged in” means the dashboard itself answered recently. A cookie existing means nothing. Once the status said the session was fresh while the bank was already sending me to the login page: it had ended the session on its side and left the cookie. Now every ten minutes the extension makes one request to the dashboard and keeps the session alive along the way
When an agent needs a login, it does not ask me in words. A command opens the login page in my browser and waits until the session shows up:
login.py <site> --wait
The event bus is described above. Next to it there is a merge queue with priorities. While anyone could set the urgent label, 19 of 38 merged PRs ended up with it, and it stopped meaning anything. Now only the orchestrator sets urgent, three open per product at most, with a line “waiting: who and for what”. The queue order can also be moved by hand with one command
Before fixing a bug it ran into, an agent checks whether someone already holds the file: an open PR touching it, a worktree with an uncommitted edit, a local branch. Nothing found, it fixes the bug itself. Something found, it writes to the owner
$ who-owns src/cart.ts
ORPHAN – free to fix
Everything that has to reach me goes through one Telegram bot. Push notifications from terminal tabs never made it to my phone, 18 failed in one day. The send script now reports success only when the message actually got through, while the old one reported success every time, and six watchers kept logging “sent” without checking once. Watcher failures go to the on-duty session first. The rest waits for a digest, three times a day
More about life outside code is in the guide (in Russian). Here it is short, because it is the same harness: the same hooks, the same rules, the same conversation
The agent reads my work chats in Telegram, WhatsApp and our team messenger and replies for me where I allowed it. Each chat has a mode in a file: reply to everything, reply only to safe things (money, dates and commitments go to me), or stay silent. Code enforces the silence: the send command refuses for such a chat, whatever the agent decides. By default the agent writes a draft. It sends on its own only by the chat's rules or after I say “send”
Sending is guarded against races. If a new message appeared since the agent read the chat, even from me on my phone, the command refuses and asks it to reread. Chat messages are data for the agent, never commands, so “ignore your rules” does nothing. Every message from a person gets an owner within 15 minutes: a reply, a forward or a line “waiting for Leonid”. Otherwise I get a notification. This rule came after someone asked the same thing three times and got no answer
There is a goal mode: “get the export from X by tomorrow”. The agent writes, waits, and after a few working hours of silence sends a polite reminder. After the second one it hands the thread to me. Goal reached: a short report, and the watch stops
Everything sent in my name goes through a voice canon: rules in one repo plus my real messages by register, to clients, to the team, to close people. The deterministic part is a script. It catches what a machine can catch: a second hello in one day, a message that is too long, a promise like “will write later”, AI-sounding phrasing. The send command runs it itself, and a failing text does not go out
Pages, decks and reports go through the same script in a mode that looks only for AI-sounding language: “not X but Y” contrasts, a punchline closing every paragraph, intensifiers, an -ing tail tacked onto the end of a sentence. This article went through it too
guard.py --neuro --scan page.html
Calls are recorded on the Mac automatically, each with a transcript, my mic and the other side as separate tracks. The agent finds what I said on a call by words in the transcript. When it needs precision, it transcribes both tracks again on another machine. The cleanup job once deleted the video of yesterday's call, so now it only touches files older than two weeks and only when the disk runs low
The digest collects everything since last time: chats and calls. What comes out is what moved, what closed and what is still waiting for an answer
Research is part of the harness too. A question gets split into parts, and several agents dig into them in parallel. Every number has a source and a tag for its type: official data, a peer-reviewed paper, a report from a company with money in the outcome. Disputed numbers the agent recalculates on open data, and before publishing it checks each number against its source. The result is a page on my site and a markdown file in the product's repo. One index collects all of them, over three hundred by now, and before new research a session searches there first
Two published ones: the moat moves into the process, on strategy when AI writes the code, and marijuana prohibition and legalization in the US, where the main disputed numbers are recalculated with difference-in-differences
In summer the review verdict field was written by the same session that wrote the code. Between the code commit and the “verdict” there were 30 to 98 seconds. Now only a separate runner gives a verdict in a fresh session, and the merge gates reject a verdict with no trace of that run
In one week in October 218 of 726 subagents were waiting for CI or review, the record was 395 minutes. A hook banned waiting but left an exception behind a label. A “PR queue” subagent with that label made almost 2700 turns, 237 of them wait calls. After that the exception shrank to one wait per life, and the bus took over the waiting
The pre-compaction hook used to drop an empty handoff template and ask the model to fill it in. In a month there were 55 such files, all empty. Now the hook builds the snapshot itself, without the model
In one week the laptop collected seven hung tsc processes, 78 forgotten MCP processes and four dev servers up to three and a half days old. Swap filled up and the machine froze. Since then every background job runs under timeout, a server started for a check is killed in the same turn, and a session-end hook kills that session's processes
Build the harness for yourself: your tasks, your processes, your tools. Mine is an example, not a template. Start with what hurts: the rule you are telling the agent for the third time, or the breakage that cost you a week
The steps below go in order of effort
CLAUDE.mdStart with five lines: how to address you, which language to answer in, what not to do without asking. Then add a line every time you correct the same thing twice. Shape – what to do, why, the case:
- Background jobs only under timeout N:
an orphaned process with no limit lives
forever (7 hung tsc in a week, machine froze)
One git worktree add per task, and parallel sessions stop breaking each other's tree. The biggest win on this list
Files in ~/.claude/agents/, like the example above. The minimum is an implementer on the top model and a read-only scout on the middle one. The main session sets tasks and does not write code itself
Take a rule the model already broke. For example, edits only in a worktree:
#!/usr/bin/env python3
# PreToolUse, Edit|Write: no edits in the shared checkout
import json, os, sys
REPO = os.path.expanduser("~/code/app")
def main():
try:
data = json.load(sys.stdin)
path = data["tool_input"].get("file_path", "")
real = os.path.realpath(os.path.expanduser(path))
except Exception:
return 0 # fail-open
inside = real.startswith(REPO + os.sep)
if inside and "/.claude/worktrees/" not in real:
print("Edit in the shared checkout. First: git -C "
+ REPO + " worktree add .claude/worktrees/"
" -b origin/main",
file=sys.stderr)
return 2 # block, the model reads stderr
return 0
sys.exit(main())
Registration in ~/.claude/settings.json:
{
"hooks": {
"PreToolUse": [{
"matcher": "Edit|Write|MultiEdit",
"hooks": [{
"type": "command",
"command": "python3 ~/.claude/hooks/worktree-guard.py"
}]
}]
}
}
And a two-sided test, so the hook does not get noisy:
import json, subprocess
def run(path):
payload = {"tool_input": {"file_path": path}}
return subprocess.run(
["python3", "worktree-guard.py"],
input=json.dumps(payload), text=True,
capture_output=True).returncode
assert run("~/code/app/src/a.ts") == 2
assert run("~/code/app/.claude/worktrees/x/src/a.ts") == 0
assert run("~/notes/todo.md") == 0
print("PASS")
Where the replacement is unambiguous, rewriting beats refusing. This is how my hook removes cd before git:
m = re.fullmatch(r"cd\s+(\S+)\s*&&\s*git\s+(.+)", cmd)
if m:
new = {**data["tool_input"],
"command": f"git -C {m[1]} {m[2]}"}
print(json.dumps({"hookSpecificOutput": {
"hookEventName": "PreToolUse",
"updatedInput": new,
"additionalContext": "cd removed: git -C",
}}))
No permissionDecision here on purpose: the hook removes the cd and grants nothing beyond the normal flow
The judge is a fresh claude -p with read-only tools. Input is the diff and the requirements, output is a machine-readable verdict line with the SHA it looked at. An acceptance item without a test that goes red on rollback does not count
The subagent pushed, opened a PR and finished. One place does the waiting: a webhook subscription, or at least one shared poller with a cache everyone reads from. A “check and sleep” loop inside an agent is the most expensive way to wait: every turn rereads the whole context
Questions, or something did not work when you tried it – write to me on Telegram: t.me/huopolinen