Vibe coding with Claude Code course · Module 15: Advanced Claude Code
Parallel and background work: worktrees, background tasks, /batch, /loop and /schedule
In this lesson10
Two features are waiting on the Treasure Map list. The first is shared boards: the owner invites collaborators to a board and they save their pins on it. The board has had a collaboratorIds field since lesson 13_2; only the invitations are missing. The second is a better magnifying glass: search by photo today compares only the dominant colour, and it could weigh the pins' tags too. The features do not depend on each other, yet in one session they stand in a queue anyway: the second waits until the first is finished, and the details of both get mixed up in the conversation. This lesson shows when to split the work between several sessions, how to leave it running in the background and who gets the clock.
What you already know
In lesson 9_2 you launched two longboats, claude -w sounds and claude -w recorder, each in the .claude/worktrees/<name>/ directory on the branch worktree-<name>, and you saw a conflict when two branches added something in the same place of lib/format.ts. In lesson 6_4 you moved the server to the background with Ctrl+B and looked at it in /tasks, and from lesson 5_10 you know that every subagent pays from the same limit as the conversation. From lesson 14_6 you know cloud sessions, and from lesson 14_7 the claude -p --worktree run, after which the worktree stays locked. Here you add what you need when parallel tasks multiply and you are not there beside them.
The file map first
Two sessions in two worktrees will not overwrite each other's files, but when the branches are merged a shared file will surface anyway. So before you launch the longboats, check that they sail to different coves. Do it in plan mode, in which Claude only reads the project:
Request for Claude Code (plan mode):
Do not write code. Two Treasure Map features: (1) invitations to a board, (2) search
by photo that compares the pins' tags as well as the colour. For each, list the files
it will change or create, and mark whether it needs a database migration or a new npm
package. At the end, list the files shared by both features.A list instead of code costs little and tells you at once whether the work can sail in parallel. A good plan looks roughly like this:
1. Invitations: lib/boards.ts, app/api/boards/[id]/collaborators/route.ts (new),
components/InviteDialog.tsx (new), app/boards/[id]/page.tsx. No migration, no packages.
2. Search: lib/visualSearch.ts, app/api/visual-search/route.ts, components/CameraSearch.tsx.
No migration, no packages.
Shared files: none.An empty list of shared files is a green light. Three cases keep you in port even when the files do not repeat. The first is two migrations: both longboats get the same .env, so the same database, which means you change the schema first, separately, in the main directory. The second is two new packages, because both branches will change package.json and package-lock.json. The third is a dependency: when one feature needs the result of the other, they sail one after the other.
Two longboats with one .env
In lesson 14_7 the worktree sailed without .env, because the tests did not need it. The invitations read the database, though, so this time the file has to sail with the crew. That is the job of .worktreeinclude in the project root, with .gitignore syntax:
.envClaude Code copies into every new worktree the files that match the pattern and are ignored by Git, and it never duplicates tracked files. In our case, after adding this one line, the run of claude -p --worktree boards found in the worktree an .env identical to the original. The pattern covers only .env, so every session installs node_modules itself, and so the Prisma client: the app/generated/prisma folder is in .gitignore, so a fresh checkout does not have it. Now two terminals in Cursor, one command in each:
claude -w boards
claude -w searchA project without a remote repository starts the worktree from your current commit. With a repository on GitHub it starts from the default branch of the remote, so you do a push, as in lesson 9_2, or set "worktree": { "baseRef": "head" } in the settings. The boards session gets a request with a clear boundary:
Request for Claude Code (boards session):
You are working in a worktree on invitations to boards. First npm install and npx prisma generate.
Only the board owner adds a collaborator: the route app/api/boards/[id]/collaborators/route.ts
with a Zod schema and 403 for everyone else, the dialog components/InviteDialog.tsx on the board page.
No migrations and no new packages. Do not touch lib/visualSearch.ts, app/api/visual-search
or components/CameraSearch.tsx. At the end tests, lint and tsc, then a commit.The second session gets a mirror request: its own files from the map and a ban on entering the boards files.
When a session has made its commit, you exit it, and Claude Code asks what to do with the worktree that holds work. Choose to keep it. Removing deletes the directory together with the branch and its commits, and that work is not in main yet.
The longboats return
Before you merge anything, compare the lists of files changed on both branches. In the terminal of the main directory:
comm -12 <(git diff --name-only main...worktree-boards | sort) <(git diff --name-only main...worktree-search | sort)git diff --name-only lists the files changed on a branch since it diverged from main, and comm -12 keeps only the lines present on both lists. An empty result means the branches changed no shared file, so Git will not report a conflict. In a trial repository in which both branches touched lib/types.ts, the command printed exactly that one path. The <(...) syntax works in bash and zsh, but not in PowerShell, the default Cursor terminal on Windows: there, run the command in Git Bash or ask Claude to compare both lists. You then merge one after the other, as in lesson 9_2.
After the merge comes the tidying. You remove the worktrees you kept on exit yourself. A worktree from a -p run is locked as well: in our case git worktree remove answered cannot remove a locked working tree. So the full sequence has three commands, and the first one is needed only for a lock:
git worktree unlock .claude/worktrees/boards
git worktree remove .claude/worktrees/boards
git branch -d worktree-boardsThe copied .env does not block the removal, because Git ignores it. git branch -d deletes only a branch that is already merged, so it will not destroy work you have not poured in yet.
A whole session in the background
Ctrl+B from lesson 6_4 moves one command or one subagent to the background. The /background command (/bg for short) detaches the whole session: it keeps working as a background agent and the terminal comes back to you. You start a new background session from the shell with claude --bg "task", and you see all of them on one screen after claude agents, still in the testing phase (research preview). A session sent with claude --bg moves to its own worktree before it changes anything. A session sent to the background with /background keeps editing where it was working, so one sent from the main directory has no isolation.
/batch: one change, many files
For a big, mechanical change across many files there is a built-in skill, /batch. According to the documentation, Claude first investigates the project, splits the work into independent units and shows a plan. After you approve it, every unit gets a background subagent and its own worktree, and the subagent makes the change, runs the tests and opens a pull request or reports what it did. It looks like this:
/batch add to every component in components/ a rendering test in Vitest next to the component fileThat is a good candidate: the same change, every test in a separate file, each one checkable on its own. With seven Treasure Map components it is a cannon to shoot a sparrow, though, because one session will do it cheaper, and /batch pays for itself with dozens of files. Do not reach for it when the units touch a shared file, when the change needs a design decision, or when the project has no tests with which the subagent can check its part. Remember too that the subagents' worktrees start like claude -w, that is, with a repository on GitHub from the remote's branch.
/loop and /schedule: who watches the clock
/loop repeats a request in an open session: at the interval you give, or at a pace Claude picks itself. For example, a report on the longboats:
/loop 10m check git log -1 --oneline on the branches worktree-boards and worktree-search and tell me which session has already made a commitEvery repetition is a new turn that sends the whole conversation, even when nothing has changed, so do not leave a loop in a long session. The loop works only while the session is open, and a recurring task expires after seven days (as of November 2026). You stop a loop with an interval by asking Claude to cancel it, and a loop at Claude's own pace with the Esc key.
/schedule sets up a recurring task in the cloud, formerly called a routine. Every run is a full Claude Code session on a fresh clone of the repository from GitHub, so it works with the laptop closed, but it does not see your uncommitted files. It requires signing in with a claude.ai account, not an API key, it pushes changes to branches with the claude/ prefix, and the documentation advises protecting main first with a branch rule on GitHub. Today you set up nothing: first the repository and the rule for main, then the first runs under your eye.
/loop | /schedule | |
|---|---|---|
| Where it works | in your open session | in the Anthropic cloud |
| Computer off | the loop stops | the task runs |
| Files | your directory, uncommitted too | a fresh clone from GitHub |
| What it is for | short watching while you work | standing tasks every night or every week |
The cost of parallelism
Every session, background session, subagent and /batch unit sends its own requests and pays from the same plan limit. The documentation says it outright: ten background agents use up the limit roughly ten times faster than one. Parallelism buys time, not savings, so you launch it where waiting really hurts.
Captain's review
- A map with no common part. The
comm -12from the section above prints nothing. - One database. Both sessions have the same
DATABASE_URL, so in the diff of neither branch is there a new folder inprisma/migrations/. - Packages.
package.jsonandpackage-lock.jsonwere changed by one branch at most. - After the voyage.
git worktree listshows only the main directory.
A typical agent mistake: two parallel tasks touch the same files. The boards session "while it is at it" adds a link to the navigation in app/layout.tsx or a field to the Pin type in lib/types.ts, and the other session does the same in its own way. You will recognise it by the output of comm -12 or by that file in the diff of both branches in Cursor. You revert the shared change on one branch and make it after the merge, in one session.
Next step
In a session in the main directory write: "Merge the branches worktree-boards and worktree-search into main, one after the other, then tests, lint and tsc". The merge records the history by itself, so you ask for a commit only when the tests forced fixes, for example "Fixes after merging boards and the magnifying glass". Finally, tidy up the longboats. In the editor next to the lesson you will type the files of two tasks, and the checker will tell you whether they can sail in parallel and give you the commands.
Remember: you launch longboats together only when each sails to a different cove, and you hand the clock to whoever will be on deck when the hour strikes.
Code for this lesson: App.tsx
// Longboats or a queue: can two Treasure Map tasks sail in parallel and who watches the clock
import { useState } from 'react';
export type Level = 'ok' | 'warn' | 'error';
export interface Finding {
level: Level;
text: string;
}
export interface Task {
name: string;
files: string;
migration: boolean;
packages: boolean;
}
export interface Verdict {
parallel: boolean;
findings: Finding[];
commands: string[];
}
export const SHARED = ['app/layout.tsx', 'lib/types.ts', 'package.json', 'package-lock.json', 'prisma/schema.prisma'];
const PL: Record<string, string> = { ą: 'a', ć: 'c', ę: 'e', ł: 'l', ń: 'n', ó: 'o', ś: 's', ź: 'z', ż: 'z' };
export function slug(name: string): string {
const ascii = name.toLowerCase().split('').map((ch) => PL[ch] ?? ch).join('');
const s = ascii.replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '');
return s === '' ? 'task' : s;
}
export function parseFiles(text: string): string[] {
const out: string[] = [];
for (const raw of text.split(/[,\n]/)) {
let f = raw.trim();
if (f.startsWith('./')) f = f.slice(2);
if (f !== '' && !out.includes(f)) out.push(f);
}
return out;
}
function touches(a: string, b: string): boolean {
if (a === b) return true;
if (a.endsWith('/') && b.startsWith(a)) return true;
return b.endsWith('/') && a.startsWith(b);
}
export function overlap(a: string[], b: string[]): string[] {
const out: string[] = [];
for (const fa of a) {
for (const fb of b) {
if (touches(fa, fb)) {
const shorter = fa.length <= fb.length ? fa : fb;
if (!out.includes(shorter)) out.push(shorter);
}
}
}
return out.sort();
}
export function check(a: Task, b: Task, dependent: boolean): Verdict {
const fa = parseFiles(a.files);
const fb = parseFiles(b.files);
const findings: Finding[] = [];
if (fa.length === 0 || fb.length === 0) {
findings.push({ level: 'warn', text: 'No file map. Ask Claude in plan mode for the list of files of each task.' });
}
const common = overlap(fa, fb);
if (common.length > 0) {
findings.push({ level: 'error', text: 'Shared files: ' + common.join(', ') + '. Merging will surface a conflict or one version will overwrite the other.' });
}
for (const s of SHARED) {
const inA = fa.includes(s);
const inB = fb.includes(s);
if (inA !== inB) {
findings.push({ level: 'warn', text: s + ' is a file of the whole app. Better change it after the merge, in one session.' });
}
}
if (a.migration && b.migration) {
findings.push({ level: 'error', text: 'Two migrations, and .env from .worktreeinclude gives both sessions the same database. Schema changes one after the other, in the main directory.' });
} else if (a.migration || b.migration) {
findings.push({ level: 'warn', text: 'A migration in a worktree goes to the same database as the main directory. Do it before splitting the work.' });
}
if (a.packages && b.packages) {
findings.push({ level: 'error', text: 'Both branches will change package.json and package-lock.json.' });
}
if (dependent) {
findings.push({ level: 'error', text: b.name + ' needs the result of ' + a.name + ', so they sail one after the other.' });
}
const parallel = !findings.some((f) => f.level === 'error') && fa.length > 0 && fb.length > 0;
if (parallel) {
findings.push({ level: 'ok', text: 'Different coves: each task can get its own worktree.' });
}
const wa = 'worktree-' + slug(a.name);
const wb = 'worktree-' + slug(b.name);
const commands = parallel
? [
'claude -w ' + slug(a.name) + ' # terminal 1',
'claude -w ' + slug(b.name) + ' # terminal 2',
'comm -12 <(git diff --name-only main...' + wa + ' | sort) <(git diff --name-only main...' + wb + ' | sort)',
]
: ['claude # one session: first ' + a.name + ', commit, then ' + b.name];
return { parallel, findings, commands };
}
export type ClockTool = '/loop' | '/schedule' | 'none';
export function clockTool(laptopOff: boolean, needsLocal: boolean): { tool: ClockTool; text: string } {
if (laptopOff && needsLocal) {
return { tool: 'none', text: 'Contradiction: the cloud does not see uncommitted files, and /loop does not work without your session. Commit and push, or leave the computer on.' };
}
if (laptopOff) {
return { tool: '/schedule', text: 'A cloud task on a fresh clone from GitHub. Sign in with a claude.ai account, changes go to claude/ branches, first a rule protecting main.' };
}
return { tool: '/loop', text: 'Repetitions in an open session. Each one sends the whole conversation, so do not leave a loop in a long session. You stop it by asking Claude to cancel.' };
}
const BOARDS = 'lib/boards.ts\napp/api/boards/[id]/collaborators/route.ts\ncomponents/InviteDialog.tsx\napp/boards/[id]/page.tsx';
const SEARCH = 'lib/visualSearch.ts\napp/api/visual-search/route.ts\ncomponents/CameraSearch.tsx';
export const PRESETS: Record<string, { a: Task; b: Task; dependent: boolean }> = {
'Invitations and search': {
a: { name: 'boards', files: BOARDS, migration: false, packages: false },
b: { name: 'search', files: SEARCH, migration: false, packages: false },
dependent: false,
},
'Agent mistake: a shared type': {
a: { name: 'boards', files: BOARDS + '\nlib/types.ts\napp/layout.tsx', migration: false, packages: false },
b: { name: 'search', files: SEARCH + '\nlib/types.ts', migration: false, packages: false },
dependent: false,
},
'Two migrations': {
a: { name: 'boards', files: BOARDS + '\nprisma/schema.prisma', migration: true, packages: false },
b: { name: 'favorites', files: 'lib/favorites.ts\napp/api/favorites/route.ts\nprisma/schema.prisma', migration: true, packages: false },
dependent: false,
},
'Dependent task': {
a: { name: 'boards', files: BOARDS, migration: false, packages: false },
b: { name: 'notifications', files: 'lib/notifications.ts\ncomponents/InviteBadge.tsx', migration: false, packages: false },
dependent: true,
},
};
const LEVEL_CLASS: Record<Level, string> = {
ok: 'text-emerald-400',
warn: 'text-amber-400',
error: 'text-rose-400',
};
function TaskForm(props: { title: string; task: Task; onChange: (t: Task) => void }) {
const t = props.task;
return (
<fieldset className="space-y-2 rounded border border-slate-700 p-3">
<legend className="px-1 font-semibold">{props.title}</legend>
<label className="block text-sm">
Name (the end of the branch)
<input className="mt-1 w-full rounded bg-slate-900 p-1 font-mono" value={t.name} onChange={(e) => props.onChange({ ...t, name: e.target.value })} />
</label>
<label className="block text-sm">
Files, one per line (a folder ends with /)
<textarea className="mt-1 h-28 w-full rounded bg-slate-900 p-2 font-mono text-xs" value={t.files} onChange={(e) => props.onChange({ ...t, files: e.target.value })} />
</label>
<label className="flex items-center gap-2 text-sm">
<input type="checkbox" checked={t.migration} onChange={(e) => props.onChange({ ...t, migration: e.target.checked })} />
database migration
</label>
<label className="flex items-center gap-2 text-sm">
<input type="checkbox" checked={t.packages} onChange={(e) => props.onChange({ ...t, packages: e.target.checked })} />
new npm package
</label>
</fieldset>
);
}
export default function App() {
const start = PRESETS['Invitations and search'];
const [a, setA] = useState<Task>(start.a);
const [b, setB] = useState<Task>(start.b);
const [dependent, setDependent] = useState(start.dependent);
const [laptopOff, setLaptopOff] = useState(false);
const [needsLocal, setNeedsLocal] = useState(true);
const verdict = check(a, b, dependent);
const clock = clockTool(laptopOff, needsLocal);
return (
<div className="min-h-screen space-y-4 bg-slate-950 p-4 text-slate-100">
<h1 className="text-xl font-bold">Longboats or a queue?</h1>
<div className="flex flex-wrap gap-2 text-sm">
{Object.keys(PRESETS).map((name) => (
<button
key={name}
type="button"
className="rounded bg-slate-800 px-2 py-1 hover:bg-slate-700"
onClick={() => {
setA(PRESETS[name].a);
setB(PRESETS[name].b);
setDependent(PRESETS[name].dependent);
}}
>
{name}
</button>
))}
</div>
<div className="grid gap-3 md:grid-cols-2">
<TaskForm title="Task A" task={a} onChange={setA} />
<TaskForm title="Task B" task={b} onChange={setB} />
</div>
<label className="flex items-center gap-2 text-sm">
<input type="checkbox" checked={dependent} onChange={(e) => setDependent(e.target.checked)} />
B needs the result of A
</label>
<p role="status" className={'text-lg font-semibold ' + (verdict.parallel ? 'text-emerald-400' : 'text-rose-400')}>
{verdict.parallel ? 'In parallel: two worktrees' : 'One after the other: one session'}
</p>
<ul className="space-y-1 text-sm">
{verdict.findings.map((f) => (
<li key={f.text} className={LEVEL_CLASS[f.level]}>{f.level}: {f.text}</li>
))}
</ul>
<pre className="overflow-x-auto whitespace-pre-wrap rounded bg-slate-900 p-2 font-mono text-xs">{verdict.commands.join('\n')}</pre>
<section className="space-y-2 rounded border border-slate-700 p-3">
<h2 className="font-semibold">Who watches the clock</h2>
<label className="flex items-center gap-2 text-sm">
<input type="checkbox" checked={laptopOff} onChange={(e) => setLaptopOff(e.target.checked)} />
must work when the laptop is closed
</label>
<label className="flex items-center gap-2 text-sm">
<input type="checkbox" checked={needsLocal} onChange={(e) => setNeedsLocal(e.target.checked)} />
needs uncommitted files from my directory
</label>
<p className="text-sm">
<strong className="font-mono">{clock.tool}</strong>: {clock.text}
</p>
</section>
</div>
);
}Spotted a mistake in this lesson?
Check yourself
Answer the questions from this lesson. Pick an answer to see right away whether it is correct.
1. What does running claude -w boards give you in the Treasure Map project?
2. Every night a report of the open tasks in the Treasure Map repository on GitHub is to be produced, also when the laptop is closed. What will you use?
These are 2 of 3 questions for this lesson. Solve the rest in the game.
Hands-on tasks in the game
- Horizontal ordering
Put together the command that removes the boards worktree after the merge and unlocking:
- Click in order
Click the elements in order to commission one big, mechanical change across many files, with each part in its own worktree: