Claude Code guide in three levels, Beginner to Advanced: hands-on lessons with checked exercises, every volatile fact cited to its source. Independent community guide.
JavaScript agent-skillsagentic-codingai-agentsanthropicanthropic-claudebest-practicesclaudeclaude-aiclaude-codeclaude-code-guideclaude-code-hooksclaude-code-pluginsclaude-code-skillsclaude-code-tutorialclaude-code-workflowsguidelearn-claude-codemcpsubagentstutorial
docs: add Advanced lesson 7, put bounds on autonomous runs (#99)
Wesam Abousaidee6a5cb34a47
diff --git a/README.md b/README.mdindex be27e6c..3127d0f 100644--- a/README.md+++ b/README.md@@ -48,13 +48,13 @@ macOS, Linux and WSL. For Windows and other installers, see the [official setup**Intermediate Electives:** [Skill patterns](docs/intermediate/electives/skill-patterns.md) · [Claude in Chrome](docs/intermediate/electives/claude-in-chrome.md) · [The status line](docs/intermediate/electives/status-line.md) · [Fast mode](docs/intermediate/electives/fast-mode.md)-**Advanced** (being rebuilt): [Level index](docs/advanced/README.md) · [Parallel sessions with worktrees](docs/advanced/01-parallel-sessions.md) · [Choose an orchestration pattern](docs/advanced/02-orchestration-patterns.md) · [Run and save a dynamic workflow](docs/advanced/03-dynamic-workflows.md) · [Script Claude Code with `claude -p`](docs/advanced/04-headless.md) · [GitHub Actions](docs/advanced/05-github-actions.md) · [Share your setup with a team](docs/advanced/06-share-your-setup.md)+**Advanced** (being rebuilt): [Level index](docs/advanced/README.md) · [Parallel sessions with worktrees](docs/advanced/01-parallel-sessions.md) · [Choose an orchestration pattern](docs/advanced/02-orchestration-patterns.md) · [Run and save a dynamic workflow](docs/advanced/03-dynamic-workflows.md) · [Script Claude Code with `claude -p`](docs/advanced/04-headless.md) · [GitHub Actions](docs/advanced/05-github-actions.md) · [Share your setup with a team](docs/advanced/06-share-your-setup.md) · [Put bounds on autonomous runs](docs/advanced/07-bounded-runs.md)**Topics:** [All topics](docs/topics/README.md) · [Permissions and safety](docs/topics/permissions-and-safety.md) · [Memory and context](docs/topics/memory-and-context.md) · [Models, effort and cost](docs/topics/models-effort-and-cost.md) · [Skills](docs/topics/skills.md) · [Hooks](docs/topics/hooks.md) · [Subagents and parallel work](docs/topics/subagents-and-parallel-work.md) · [MCP](docs/topics/mcp.md) · [Plugins](docs/topics/plugins.md) · [Automation](docs/topics/automation.md)**Reference:** [Reference index](docs/reference/README.md) · [Models and effort](docs/reference/models.md) · [Commands by level](docs/reference/commands.md) · [Feature map](docs/reference/feature-map.md) · [Further learning](docs/reference/further-reading.md) · [Glossary](docs/reference/glossary.md) · [Changelog](docs/reference/changelog.md)-**From the previous edition, not yet re-verified:** [Agent teams](docs/agent-teams.md) · [Dynamic workflows](docs/workflows.md)+**From the previous edition, not yet re-verified:** [Agent teams](docs/agent-teams.md)**Examples:** [How to use the examples](examples/README.md)diff --git a/docs/advanced/06-share-your-setup.md b/docs/advanced/06-share-your-setup.mdindex d8b1c3b..9876ec0 100644--- a/docs/advanced/06-share-your-setup.md+++ b/docs/advanced/06-share-your-setup.md@@ -119,4 +119,4 @@ If the first item fails, run `claude plugin validate ./team-marketplace` and com<sub>Sources: [Settings files and precedence](https://code.claude.com/docs/en/settings) · [Explore the .claude directory](https://code.claude.com/docs/en/claude-directory) · [Create a Claude Code plugin](https://code.claude.com/docs/en/plugins/create) · [Manage Claude Code plugins for your organization](https://code.claude.com/docs/en/plugins/org) · [Plugin loading reference](https://code.claude.com/docs/en/plugins/loading) · [Create a marketplace](https://code.claude.com/docs/en/plugins/create-marketplace) · [Plugin commands reference](https://code.claude.com/docs/en/plugins/cli-reference) · [All settings](https://code.claude.com/docs/en/settings-reference) · [Add components to a plugin](https://code.claude.com/docs/en/plugins/components) · [Create custom subagents](https://code.claude.com/docs/en/sub-agents) · [Interactive mode](https://code.claude.com/docs/en/interactive-mode) · [Plugin security and trust](https://code.claude.com/docs/en/plugins/security) · [Configure permissions](https://code.claude.com/docs/en/permissions)</sub>-<sub>← [GitHub Actions](05-github-actions.md) · [Advanced index](README.md) · Topic: [Plugins](../topics/plugins.md) · [Stuck on this lesson?](https://github.com/wesammustafa/Claude-Code-Everything-You-Need-to-Know/issues/new?template=lesson-feedback.yml&lesson=a-6)</sub>+<sub>← [GitHub Actions](05-github-actions.md) · [Advanced index](README.md) · [Put bounds on autonomous runs](07-bounded-runs.md) → · Topic: [Plugins](../topics/plugins.md) · [Stuck on this lesson?](https://github.com/wesammustafa/Claude-Code-Everything-You-Need-to-Know/issues/new?template=lesson-feedback.yml&lesson=a-6)</sub>diff --git a/docs/advanced/07-bounded-runs.md b/docs/advanced/07-bounded-runs.mdnew file mode 100644index 0000000..ea45ffc--- /dev/null+++ b/docs/advanced/07-bounded-runs.md@@ -0,0 +1,159 @@+# Put bounds on autonomous runs++<sub>**Advanced** · Lesson 7 of 7 · about 20 minutes, plus run time · Needs: [Script Claude Code with `claude -p`](04-headless.md), [Share your setup with a team](06-share-your-setup.md) · Verified against Claude Code v2.1.285 (stable) on 2026-10-09</sub>++## Goal++By the end of this lesson you can bound an unattended `claude -p` run with least privilege, the sandbox, turn and spend limits, a review gate and a cost estimate.++## You need++- The repository you scripted in [lesson 4](04-headless.md) and shared in [lesson 6](06-share-your-setup.md), with a test command, and your copy of the practice template with Node.js LTS and the Advanced checks ([Practice](README.md#practice)): the check runs from the copy. Set up the repository's `.practice/` folder as [Beginner lesson 1](../beginner/01-install-and-look-around.md#you-need) describes, if you haven't yet.+- bash and `jq`, on macOS, Linux or WSL 2. On Linux and WSL 2, the sandbox needs `bubblewrap` and `socat` ([Set up Linux and WSL2](https://code.claude.com/docs/en/sandboxing#set-up-linux-and-wsl2)).+- Usage: moderate. Each run stops at its limits. Cheap variant: in Your turn, set the limits from your slice run, and run the script on one more slice instead of the whole task.++## The idea++A run nobody watches does whatever you allowed in advance, so allow little and cap the rest:++- **Least privilege.** `dontAsk` mode denies every call that would otherwise prompt ([dontAsk mode](https://code.claude.com/docs/en/permission-modes#allow-only-pre-approved-tools-with-dontask-mode)), so allow only the folders the task edits and the one command it runs.+- **The sandbox.** The operating system limits what an allowed command can write and reach ([Configure the sandboxed Bash tool](https://code.claude.com/docs/en/sandboxing)). Make it strict, and required for the run to start.+- **Limits.** `--max-turns` caps agentic turns, and `--max-budget-usd` caps estimated spend ([CLI flags](https://code.claude.com/docs/en/cli-reference#cli-flags)).+- **A review gate.** Deny `git commit` and `git push`: deny rules hold in every mode ([Available modes](https://code.claude.com/docs/en/permission-modes#available-modes)). `dontAsk` refuses the forms a rule misses, such as `git -C . push`, while nothing allows them ([What a Bash rule doesn't match](https://code.claude.com/docs/en/permissions#bash-rule-limits)). You read the diff and commit what you accept.+- **A cost estimate.** Run one slice first, and set the spend limit from what it cost.++## Worked example++Work in your repository. The folders `src/` and `test/` and the command `npm test` stand for your own: swap yours in everywhere below.++1. Save the bounds as `.claude/bounded-run.json`:++ ```json+ {+ "permissions": {+ "allow": ["Edit(./src/**)", "Edit(./test/**)", "Bash(npm test *)"],+ "deny": ["Agent", "Read(./.env)", "Read(./.env.*)", "Bash(git commit *)", "Bash(git push *)"]+ },+ "sandbox": {+ "enabled": true,+ "failIfUnavailable": true,+ "allowUnsandboxedCommands": false,+ "autoAllowBashIfSandboxed": false+ }+ }+ ```++ - `allow`: edits in two folders, and `npm test` with any arguments. `Edit` rules cover every built-in tool that edits files, and a `./` path starts from the folder the run starts in ([Read and Edit](https://code.claude.com/docs/en/permissions#read-and-edit)).+ - `deny`: `.env` files; `git commit` and `git push`, where the trailing ` *` also matches the bare command ([Wildcard patterns](https://code.claude.com/docs/en/permissions#wildcard-patterns)); and the `Agent` tool, so Claude can't hand work to a subagent ([Built-in subagents](https://code.claude.com/docs/en/sub-agents#built-in-subagents)), which could run in a permission mode of its own ([Permission modes](https://code.claude.com/docs/en/sub-agents#permission-modes)).+ - `sandbox`: on; exit at startup if it can't start ([`sandbox.failIfUnavailable`](https://code.claude.com/docs/en/settings-reference#sandbox-failifunavailable)); never retry a command outside it ([Strict sandbox mode](https://code.claude.com/docs/en/sandboxing#turn-off-the-retry-with-strict-sandbox-mode)); and send sandboxed commands through your rules and mode instead of approving them all ([`sandbox.autoAllowBashIfSandboxed`](https://code.claude.com/docs/en/settings-reference#sandbox-autoallowbashifsandboxed)).++ Claude's file tools can't change this file during the run: in `dontAsk` mode, writes to the protected `.claude/` folder are denied, and allow rules don't change that ([Protected paths](https://code.claude.com/docs/en/permission-modes#protected-paths)).+2. Save the runner as `scripts/bounded-run.sh`:++ ```bash+ #!/bin/bash+ # Runs one unattended task inside the bounds in .claude/bounded-run.json.+ set -u+ if [ $# -ne 2 ]; then+ echo 'Usage: scripts/bounded-run.sh "<task>" <result.json>' >&2+ exit 2+ fi+ before=$(git rev-parse --short HEAD)+ claude -p "$1" \+ --setting-sources project \+ --settings .claude/bounded-run.json \+ --permission-mode dontAsk \+ --model sonnet \+ --max-turns 15 \+ --max-budget-usd 2 \+ --output-format json > "$2"+ status=$?+ jq '{subtype, num_turns, total_cost_usd, denied: [.permission_denials[]? | .tool_input.command // .tool_name]}' "$2"+ echo "HEAD before: $before, after: $(git rev-parse --short HEAD)"+ git status --short+ exit "$status"+ ```++ - `--setting-sources project`: leaves your user and local settings files out of the run ([CLI flags](https://code.claude.com/docs/en/cli-reference#cli-flags)), so an allow rule you saved with "Yes, and don't ask again", which goes to `.claude/settings.local.json`, doesn't join the bounds ([Permission system](https://code.claude.com/docs/en/permissions#permission-system)).+ - `--settings`: the bounds file, which Claude Code applies above the project's own settings ([Change a setting for one session](https://code.claude.com/docs/en/settings#change-a-setting-for-one-session)). The allow rules go there because a `-p` run ignores the allow rules in a never-trusted folder's `.claude/settings.json` ([What runs before you trust a folder](https://code.claude.com/docs/en/permissions#what-runs-before-you-trust-a-folder)).+ - `allowUnsandboxedCommands: false` in that file: because it comes from `--settings`, a project's `true` can't turn the unsandboxed retry back on ([Strict sandbox mode](https://code.claude.com/docs/en/sandboxing#turn-off-the-retry-with-strict-sandbox-mode)). In v2.1.285 or later, Claude Code also ignores the repository's settings that loosen the sandbox, such as `excludedCommands` ([Repository settings under an admin-required sandbox](https://code.claude.com/docs/en/sandboxing#repository-settings-under-an-admin-required-sandbox)).+ - `--model sonnet`: Sonnet handles most coding tasks well and costs less than Opus ([Choose the right model](https://code.claude.com/docs/en/costs#choose-the-right-model)).+ - `--max-turns` and `--max-budget-usd`: configuration, so set your own.+3. Make it executable and commit both files, so everyone who runs it gets the same bounds:++ ```bash+ chmod +x scripts/bounded-run.sh+ git add scripts/bounded-run.sh .claude/bounded-run.json+ git commit -m "Add a bounded runner for unattended tasks"+ ```++ If git reports a path as ignored, `git check-ignore -v <path>` shows the rule that matches it; add the path with `git add -f`.+4. See a limit stop a run. Give the same bounds a tiny spend limit:++ ```bash+ claude -p "Run npm test and summarize the result" \+ --setting-sources project --settings .claude/bounded-run.json \+ --permission-mode dontAsk --model sonnet \+ --max-budget-usd 0.01 --output-format json > .practice/a-7-capped.json+ echo "exit $?"+ jq '{subtype, total_cost_usd}' .practice/a-7-capped.json+ ```++ It prints a non-zero exit code, then `"subtype": "error_max_budget_usd"`: the run stopped at the limit, and the JSON still records it ([Handle the result](https://code.claude.com/docs/en/agent-sdk/agent-loop#handle-the-result)). `total_cost_usd` can be above the limit, because it includes the response that crossed it ([Track costs on failed conversations](https://code.claude.com/docs/en/agent-sdk/cost-tracking#track-costs-on-failed-conversations)).+5. Estimate the cost on a slice, one small part of a bigger task:++ ```bash+ scripts/bounded-run.sh "Use your Edit tool to add a test for one untested function in src/<file>. Then run npm test as a command on its own, and then commit the test." .practice/a-7-slice.json+ ```++ The summary shows `"subtype": "success"`, the turns used, `total_cost_usd`, and under `denied` each call your bounds refused, such as the `git commit`; your list will differ. HEAD is the same before and after, and `git status` lists the new test, uncommitted. Your output will differ. `total_cost_usd` is a client-side estimate, not your bill ([Track cost and usage](https://code.claude.com/docs/en/agent-sdk/cost-tracking#estimates-not-billing)); on a Claude plan, `/usage` in a session shows your plan's usage limits ([Commands](https://code.claude.com/docs/en/commands#all-commands)). To bound the whole task, scale the slice's figure up and set the spend limit above it, with room to spare.+6. Be the review gate. Read every change with `git status` and `git diff`, the bounds file included, run `npm test` yourself, and commit only what you accept. For a second opinion, start `claude` and have a subagent review the diff in a fresh context and report gaps ([Add an adversarial review step](https://code.claude.com/docs/en/best-practices#add-an-adversarial-review-step)).++## Your turn++Bound a real task in your repository that is bigger than one slice, such as tests for every untested function in one folder.++Acceptance criteria:++- `scripts/bounded-run.sh "<task>" <result.json>` runs it: one `claude -p` call in `dontAsk` mode, with JSON output saved to the result path, and the bounds from a committed file passed with `--settings`.+- It calls `claude` by name, not by a path or through `npx`, and doesn't change `PATH`: that is how the check swaps in a stand-in for it.+- Each allow rule names one folder or one command: no bare `Bash` or `Edit`, and no rule for the whole project or a whole program, such as `Bash(npm *)`. Your committed `.claude/settings.json` counts too: in a folder you've trusted, its allow rules join the bounds file's ([Lists merge instead of overriding](https://code.claude.com/docs/en/settings#lists-merge-instead-of-overriding)). So do the `allowed-tools` of the repository's skills, in a run that invokes one ([Pre-approve tools for a skill](https://code.claude.com/docs/en/skills#pre-approve-tools-for-a-skill)).+- Deny rules stop `git commit` and `git push`, each with the trailing ` *`: `Bash(git push)` matches only the bare command.+- The sandbox is on and strict, sends sandboxed commands through your rules, and the run refuses to start without it.+- There's a turn limit, and a spend limit above what your slice cost, scaled to the task.+- The script is executable, and the script and the bounds file are committed.+- You run it, then read the diff and run the tests yourself before you commit any of it.++## Check++You are done when all of these are true:++- [ ] `scripts/bounded-run.sh` is committed and executable, takes a task and a result path (`scripts/bounded-run.sh "<task>" <result.json>`), and starts `claude -p` in `dontAsk` mode with JSON output and a committed `--settings` file.+- [ ] It sets a turn limit and a spend limit.+- [ ] Every allow rule names one command or one folder, and the deny rules stop `git commit` and `git push`.+- [ ] The settings file turns the sandbox on in strict mode without auto-allow, and makes the run refuse to start without it.+- [ ] `.practice/a-7-slice.json` holds a slice run whose cost is under your spend limit.+- [ ] `.practice/a-7-capped.json` holds a run a limit stopped.+- [ ] Self-check (not tested): you read the diff and ran the tests before you committed any of it.++Run `npm run check -- a-7 --dir <your repo>` from your practice copy, or `npm run check -- a-7` in the copy itself. The check runs your committed script with a stand-in for `claude`, so it uses none of your usage.++If the first item fails, make sure the committed script is executable (`git ls-files -s scripts/bounded-run.sh` starts with `100755`) and calls `claude` by name, not by a path or through `npx`, and doesn't set `PATH`: the check reads the committed script, so commit each fix. If an allow rule fails, narrow it to the one folder or command the task needs. If the sandbox item names a key, add it to the settings file: without `failIfUnavailable`, a run whose sandbox can't start runs unsandboxed ([`sandbox.enabled`](https://code.claude.com/docs/en/settings-reference#sandbox-enabled)). If the slice item fails, make sure your script sends only `claude`'s JSON output (stdout) to the result path, then run step 5 again; a slice that ended in `error_max_budget_usd` means your spend limit is below one slice, so raise it.++## Watch out++- Your bounds don't cover everything the run loads. Hooks and local MCP servers run outside the sandbox with your full access ([What runs outside the sandbox](https://code.claude.com/docs/en/sandboxing#what-runs-outside-the-sandbox)). As [lesson 4](04-headless.md#watch-out) warned, a `-p` run uses a repository's hooks and `.mcp.json` servers without asking, and it applies the `allowed-tools` of the repository's skills too ([What runs before you trust a folder](https://code.claude.com/docs/en/permissions#what-runs-before-you-trust-a-folder)). Read those hooks, servers and skills before a bounded run, or add `"disableAllHooks": true` to the bounds file to turn hooks off for it.+- A deny rule matches the command Claude writes, not what a program does ([What a Bash rule doesn't match](https://code.claude.com/docs/en/permissions#bash-rule-limits)). The allowed `npm test` runs test files the run can edit. In the sandbox, that code can write anywhere in your working directory except protected paths, and inside `.git` only `hooks` and `config` are protected ([Protected paths](https://code.claude.com/docs/en/sandboxing#protected-paths)). So it could even make a commit. A push from it can't reach a remote: in `dontAsk` mode the sandbox refuses hosts you haven't allowed ([Hosts outside your allowed domains](https://code.claude.com/docs/en/sandboxing#hosts-outside-your-allowed-domains), [Turn off permission prompts in unattended runs](https://code.claude.com/docs/en/headless#turn-off-permission-prompts-in-unattended-runs)). That's why the script prints HEAD before and after, and why your review covers every changed file.+- A dynamic workflow starts through its own tool, `Workflow`. In a run like this one, it starts only if an allow rule or a `PreToolUse` hook approves it: `Workflow` approves any workflow, and `Workflow(<name>)` approves one saved workflow ([Approve the plan before it runs](https://code.claude.com/docs/en/workflows#approve-the-plan-before-it-runs)). The workflow's agents follow your permission rules, and their permission mode follows the subagent rules, so an agent type whose definition sets `permissionMode` can run in that mode ([Permission modes](https://code.claude.com/docs/en/sub-agents#permission-modes)). They're subagents, so their spend counts toward `--max-budget-usd`. If you allow one, also add `"workflowSizeGuideline": "small"` to the bounds file, which asks Claude for fewer agents but caps nothing ([`workflowSizeGuideline`](https://code.claude.com/docs/en/settings-reference#workflowsizeguideline)).++## Go further++- [Choose a sandbox environment](https://code.claude.com/docs/en/sandbox-environments): containers and VMs for runs the Bash sandbox can't cover.+- [How we contain Claude across products](https://www.anthropic.com/engineering/how-we-contain-claude): Anthropic's engineering post on capping how much damage an agent can do, in Claude Code and its other products.+- [Catch security issues as Claude writes code](https://code.claude.com/docs/en/security-guidance): the security-guidance plugin, which has Claude review its own changes for vulnerabilities while you work with it.++---++<sub>Sources: [Choose a permission mode](https://code.claude.com/docs/en/permission-modes) · [Configure permissions](https://code.claude.com/docs/en/permissions) · [Extend Claude with skills](https://code.claude.com/docs/en/skills) · [Configure the sandboxed Bash tool](https://code.claude.com/docs/en/sandboxing) · [All settings](https://code.claude.com/docs/en/settings-reference) · [Settings files and precedence](https://code.claude.com/docs/en/settings) · [CLI reference](https://code.claude.com/docs/en/cli-reference) · [Create custom subagents](https://code.claude.com/docs/en/sub-agents) · [Run Claude Code programmatically](https://code.claude.com/docs/en/headless) · [How the agent loop works](https://code.claude.com/docs/en/agent-sdk/agent-loop) · [Track cost and usage](https://code.claude.com/docs/en/agent-sdk/cost-tracking) · [Manage costs effectively](https://code.claude.com/docs/en/costs) · [Commands](https://code.claude.com/docs/en/commands) · [Best practices](https://code.claude.com/docs/en/best-practices) · [Orchestrate subagents at scale with dynamic workflows](https://code.claude.com/docs/en/workflows)</sub>++<sub>← [Share your setup with a team](06-share-your-setup.md) · [Advanced index](README.md) · Topic: [Permissions and safety](../topics/permissions-and-safety.md) · [Stuck on this lesson?](https://github.com/wesammustafa/Claude-Code-Everything-You-Need-to-Know/issues/new?template=lesson-feedback.yml&lesson=a-7)</sub>diff --git a/docs/advanced/README.md b/docs/advanced/README.mdindex b99cdc0..47dfad0 100644--- a/docs/advanced/README.md+++ b/docs/advanced/README.md@@ -33,9 +33,9 @@ git commit -m "Add the Advanced checks"4. [Script Claude Code with `claude -p`](04-headless.md)5. [GitHub Actions](05-github-actions.md)6. [Share your setup with a team](06-share-your-setup.md)-7. Put bounds on autonomous runs+7. [Put bounds on autonomous runs](07-bounded-runs.md)-Each lesson takes 10 to 20 minutes, plus the time an agent run takes. Lessons are linked here as they are published.+Each lesson takes 10 to 20 minutes, plus the time an agent run takes.## Capstonediff --git a/docs/reference/commands.md b/docs/reference/commands.mdindex 664455b..8c6fda8 100644--- a/docs/reference/commands.md+++ b/docs/reference/commands.md@@ -46,7 +46,7 @@ Electives: `/statusline` ([The status line](../intermediate/electives/status-lin- `claude -p "<prompt>"`: run one prompt without the interactive interface, print the answer and exit; a script adds `--output-format json`, `--allowedTools` and `--max-turns` ([CLI reference](https://code.claude.com/docs/en/cli-reference#cli-commands)). [Script Claude Code with `claude -p`](../advanced/04-headless.md)- `/install-github-app`: install the Claude GitHub App for a repository, with optional workflow and secret setup. [GitHub Actions](../advanced/05-github-actions.md)- `claude plugin validate <dir>`: check a marketplace or a plugin folder before you share it; `--strict` also fails on warnings ([Plugin commands reference](https://code.claude.com/docs/en/plugins/cli-reference#plugin-validate)). [Share your setup with a team](../advanced/06-share-your-setup.md)-- `/usage`: the session's cost, your plan's usage limits and activity stats. *Put bounds on autonomous runs*+- `/usage`: the session's cost, your plan's usage limits and activity stats. [Put bounds on autonomous runs](../advanced/07-bounded-runs.md)Electives: `/background` (agent view); `/goal`, `/loop` and `/schedule` (`/goal`, `/loop` and routines).diff --git a/docs/reference/feature-map.md b/docs/reference/feature-map.mdindex 3ff9465..a94d574 100644--- a/docs/reference/feature-map.md+++ b/docs/reference/feature-map.md@@ -70,7 +70,7 @@ How to read it:| [Projects](https://code.claude.com/docs/en/claude-projects) | "Projects are in public beta on Pro and Max plans and rolling out gradually …" | Pro and Max; not yet Team or Enterprise || [`/loop` and scheduled prompts](https://code.claude.com/docs/en/scheduled-tasks) | – | Every provider || [Routines](https://code.claude.com/docs/en/routines) | "Routines are in research preview." | Pro, Max, Team and Enterprise |-| [Running Claude Code from scripts](https://code.claude.com/docs/en/headless); taught in [Script Claude Code with `claude -p`](../advanced/04-headless.md) | – | Every provider |+| [Running Claude Code from scripts](https://code.claude.com/docs/en/headless); taught in [Script Claude Code with `claude -p`](../advanced/04-headless.md) and [Put bounds on autonomous runs](../advanced/07-bounded-runs.md) | – | Every provider || [GitHub Actions](https://code.claude.com/docs/en/github-actions); taught in [GitHub Actions](../advanced/05-github-actions.md) | – | A Claude subscription, the Console, Bedrock, Agent Platform and Foundry; not Claude Platform on AWS || [GitLab CI/CD](https://code.claude.com/docs/en/gitlab-ci-cd) | "Claude Code for GitLab CI/CD is currently in beta." | Every provider except Microsoft Foundry |diff --git a/docs/topics/permissions-and-safety.md b/docs/topics/permissions-and-safety.mdindex feb2197..ae427b1 100644--- a/docs/topics/permissions-and-safety.md+++ b/docs/topics/permissions-and-safety.md@@ -9,6 +9,7 @@ What Claude Code may do without asking, and how to keep it away from what it sho- Beginner: [Permission modes and plan mode](../beginner/02-permission-modes-and-plan-mode.md)- Beginner: [Your first change, from request to commit](../beginner/03-first-change.md)- Intermediate: [Permissions, settings scopes and the sandbox](../intermediate/04-permissions-and-sandbox.md)+- Advanced: [Put bounds on autonomous runs](../advanced/07-bounded-runs.md)Later lessons on this topic are linked here in level order, with its Electives, as they are published.diff --git a/docs/workflows.md b/docs/workflows.mdindex 729ed55..7f29e1f 100644--- a/docs/workflows.md+++ b/docs/workflows.md@@ -1,305 +1,10 @@-# Dynamic Workflows — Orchestrating Agents at Scale+<a id="dynamic-workflows--orchestrating-agents-at-scale"></a>+# Dynamic workflows-> [!NOTE]-> From the previous edition, not yet re-verified. The guide is being rebuilt as lessons; this page keeps the earlier material reachable until they land.+This page moved. Dynamic workflows are taught in the Advanced lessons, and the [Subagents and parallel work topic index](topics/subagents-and-parallel-work.md) lists the lessons that teach them.-*~12 min read · [← Back to README](../README.md#dynamic-workflows)*+<a id="contents"></a><a id="start-here-deep-research"></a><a id="three-ways-to-start-a-workflow"></a><a id="1-run-one-that-already-exists"></a><a id="2-ask-for-one-in-a-single-prompt"></a><a id="3-let-claude-decide-for-the-whole-session"></a><a id="approving-the-run"></a><a id="watching-a-run"></a><a id="what-the-script-looks-like"></a><a id="saving-a-workflow-for-reuse"></a><a id="passing-input-with-args"></a><a id="limits-and-behavior"></a><a id="resuming-a-run"></a><a id="turning-workflows-off"></a><a id="prompt-patterns-that-work"></a><a id="see-also"></a><a id="size-guideline"></a><a id="the-large-run-warning"></a><a id="model-routing"></a>Running a workflow, approving and watching it, saving it with input, and keeping its size and model in check: [Run and save a dynamic workflow](advanced/03-dynamic-workflows.md). Everything else, such as turning workflows off, is in the official [workflows docs](https://code.claude.com/docs/en/workflows).-> **Mental model:** A dynamic workflow is a **JavaScript script that orchestrates subagents**. Claude writes the script for the task you describe, and a runtime executes it in the background while your session stays responsive. The difference from every other multi-agent feature: **the script holds the plan**, not Claude's turn-by-turn judgement.+<a id="who-holds-the-plan"></a>Subagents, a workflow or a team, and who holds the plan in each: [Choose an orchestration pattern](advanced/02-orchestration-patterns.md).-Requires Claude Code v2.1.154+. Available on all paid plans, the Anthropic API, Amazon Bedrock, Google Cloud's Agent Platform, and Microsoft Foundry. On Pro, turn them on from the **Dynamic workflows** row in `/config`.-------## Contents--- [Start here: `/deep-research`](#start-here-deep-research)-- [Who holds the plan?](#who-holds-the-plan)-- [Three ways to start a workflow](#three-ways-to-start-a-workflow)-- [Watching a run](#watching-a-run)-- [What the script looks like](#what-the-script-looks-like)-- [Saving a workflow for reuse](#saving-a-workflow-for-reuse)-- [Limits and behavior](#limits-and-behavior)-- [Permissions](#permissions)-- [Controlling cost](#controlling-cost)-- [Resuming a run](#resuming-a-run)-- [Turning workflows off](#turning-workflows-off)-- [Prompt patterns that work](#prompt-patterns-that-work)-------## Start here: `/deep-research`--Don't write a script. Run the bundled one:--```text-/deep-research What changed in the Node.js permission model between v20 and v22?-```--It fans web searches across several angles, fetches and cross-checks the sources, votes on each claim, and returns a cited report with claims that failed cross-checking filtered out. Claude Code asks permission first; approve it, then run `/workflows` to watch.--This one command shows you the whole model in ~2 minutes: background execution, phases, fan-out, and adversarial verification. `/deep-research` runs only when you invoke it (as of v2.1.218 — earlier versions let Claude start it unprompted).--> It needs the WebSearch tool available in your session.-------## Who holds the plan?--Subagents, skills, agent teams, and workflows can all run a multi-step task. The real distinction is **who decides what runs next**:--| | Subagents | Skills | Agent teams | Workflows |-|---|---|---|---|---|-| **What it is** | A worker Claude spawns | Instructions Claude follows | A lead supervising peer sessions | A script the runtime executes |-| **Who decides what runs next** | Claude, turn by turn | Claude, following the prompt | The lead agent, turn by turn | **The script** |-| **Where intermediate results live** | Claude's context window | Claude's context window | A shared task list | **Script variables** |-| **What's repeatable** | The worker definition | The instructions | The team definition | **The orchestration itself** |-| **Scale** | A few tasks per turn | Same as subagents | A handful of long-running peers | **Dozens to hundreds per run** |-| **Interruption** | Restarts the turn | Restarts the turn | Teammates keep running | **Resumable in the same session** |--Two consequences fall out of "the script holds the plan":--1. **Your context stays clean.** Intermediate results live in script variables, so Claude's context holds only the final answer. This is why a workflow can coordinate 200 agents when a conversation can't.-2. **Quality patterns become repeatable.** A script can have independent agents *adversarially review each other's findings* before anything is reported, or draft a plan from several angles and weigh them against each other. That's a more trustworthy result than a single pass — and it runs the same way every time.--> 💡 **When not to use one.** A workflow is overhead for anything a couple of subagents can handle. Reach for it when the task outgrows one conversation's coordination, or when you want the orchestration codified as a script you can read and rerun.-------## Three ways to start a workflow--### 1. Run one that already exists--`/deep-research`, a workflow [you saved](#saving-a-workflow-for-reuse), or one shipped in a [plugin](https://code.claude.com/docs/en/plugins). Saved workflows appear in `/` autocomplete like any other command.--### 2. Ask for one in a single prompt--Include the keyword `ultracode`, or just say what you want in plain words — "use a workflow", "run a workflow". Claude treats a direct request as the same opt-in.--```text-ultracode: audit every API endpoint under src/routes/ for missing auth checks-```--Claude Code highlights the keyword and Claude writes a script instead of working turn by turn. The keyword only changes *how* the work is structured — the run stays inside your session's [permission mode](https://code.claude.com/docs/en/permission-modes), and its agents get the same permission checks and sandboxing as any other tool call.--**Dismiss it:** `Option+W` (macOS) or `Alt+W` (Windows/Linux) clears the highlight for this prompt; backspace right after the keyword also works. Turn it off entirely with **Ultracode keyword trigger** in `/config`.--**Where the keyword does *not* work** — by design, it's an opt-in only in a prompt *you* typed. It won't trigger from `-p`, a scheduled task, a webhook payload, or a relayed PR comment. (Before v2.1.210 it did fire from those routes.)--### 3. Let Claude decide for the whole session--```bash-/effort ultracode # this session-claude --effort ultracode # from launch (v2.1.203+); also sets xhigh-```--`ultracode` turns on automatic workflow orchestration at whatever effort level the session runs (v2.1.284+; earlier versions also forced `xhigh`): Claude plans a workflow for **every substantive task** instead of waiting to be asked. One request can become several workflows in a row — one to understand the code, one to make the change, one to verify it.--That means every request costs more and takes longer. It resets when you start a new session; drop back with `/effort high` for routine work. Only offered on models that support `xhigh`.--### Approving the run--The prompt shows the planned phases, plus **Yes, run it** / **Yes, and don't ask again for this workflow in this project** / **View raw script** / **No**. `Ctrl+G` opens the script in your editor; `Tab` lets you adjust the prompt first.--| Permission mode | When you're prompted |-|---|---|-| Manual (`default`), accept edits | Every run, unless you chose "don't ask again" for that workflow in this project |-| Auto | First launch only — a **Yes** records consent in user settings. Skipped entirely when `ultracode` is on |-| Bypass permissions, `claude -p`, Agent SDK | Never — the run starts immediately |-------## Watching a run--Runs execute in the background, so the session stays usable. `/workflows` lists running and completed runs; select one and press Enter for its progress view (phases, agent counts, token totals, elapsed time). A one-line summary also appears in the task panel below the input box — press `↓` to focus it, Enter to expand.--| Key | Action |-|---|---|-| `↑` / `↓` | Select a phase or agent |-| `Enter` / `→` | Drill into a phase, then an agent — read its prompt, recent tool calls, and result |-| `Esc` / `←` | Back out one level |-| `j` / `k` | Scroll within agent detail when it overflows |-| `f` | Filter the phase's agent list by status; press again to cycle (v2.1.186+) |-| `p` | Pause or resume the run |-| `x` | Stop the selected agent — or the whole run when focus is on the run |-| `r` | Restart the selected running agent |-| `s` | [Save](#saving-a-workflow-for-reuse) this run's script as a command |--> ℹ️ In v2.1.203–v2.1.205, `←` didn't step back out of a phase or agent. Use `Esc` on those versions.-------## What the script looks like--You don't write these by hand — but you should be able to read one, because reading it is how you audit what 50 agents are about to do. Here's the shape:--```javascript-export const meta = {- name: 'audit-routes',- description: 'Audit every route handler for missing auth checks',-}--const found = await agent('List every .ts file under src/routes/.', {- schema: { type: 'object', required: ['files'],- properties: { files: { type: 'array', items: { type: 'string' } } } },-})--const audits = await pipeline(found.files, file =>- agent(`Audit ${file} for missing authentication checks.`, { label: file }),-)--return audits.filter(Boolean)-```--Plain JavaScript with top-level `await`. `agent()` spawns one subagent; `pipeline()` runs one per item in a list; passing a `schema` forces structured output so the script gets a validated object instead of prose it has to parse.--Every run writes its script to a file under your session directory in `~/.claude/projects/`, and Claude receives the path — so you can ask for it, diff it against a previous run, or edit it and ask Claude to relaunch from the edited version.--> 📂 **A working example lives in this repo:** [`.claude/workflows/stale-docs-audit.js`](../.claude/workflows/stale-docs-audit.js) — fans one reader agent per doc file, then has independent verifier agents try to *refute* each finding before it's reported. Clone the repo and run `/stale-docs-audit` to see it work.->-> For the full script API, see the Workflow tool entry in the [Agent SDK reference](https://code.claude.com/docs/en/agent-sdk/typescript).-------## Saving a workflow for reuse--When a run does what you wanted, keep it. Run `/workflows`, select the run, press `s`. `Tab` toggles the location:--| Location | Scope |-|---|---|-| `.claude/workflows/` | Project — shared with everyone who clones the repo |-| `~/.claude/workflows/` | Personal — every project, only you. Honors `CLAUDE_CONFIG_DIR` |--Press Enter and it runs as `/<name>` from then on. If a project and personal workflow share a name, **the project one wins**.--**Monorepos** (v2.1.178+): saving to the project location writes to the closest existing `.claude/workflows/` between your cwd and the repo root. Project workflows load from *every* `.claude/workflows/` along that path, and the one closest to your cwd wins on name collisions.--**In a plugin:** put the script in a `workflows/` directory at the plugin root. Plugin workflows are namespaced — a plugin `acme-tools` with `meta.name: 'release-audit'` runs as `/acme-tools:release-audit`.--### Passing input with `args`--A saved workflow reads invocation input from a global named `args`:--```text-> Run /triage-issues on issues 1024, 1025, and 1030-```--Claude passes the list as **structured data**, so the script can call array and object methods on `args` directly — no parsing. If you omit input, `args` is `undefined`.--> 🔒 Since v2.1.216, Claude Code refuses to write a saved workflow through a symlink. For the project location it checks `.claude`, `.claude/workflows`, and the target file; for the personal location only the target file, so dotfiles-managed `~/.claude` still works.-------## Limits and behavior--| Constraint | Why |-|---|---|-| **No mid-run user input** | Only agent permission prompts pause a run. For sign-off between stages, run each stage as its own workflow |-| **No direct filesystem or shell access from the script** | Agents read, write, and run commands. The script only coordinates them |-| **Up to 16 concurrent agents** (fewer on low-core machines) | Bounds local resource use — excess calls queue and run as slots free |-| **1,000 agents total per run** | Runaway-loop backstop, set far above any real workflow |-------## Permissions--Worth internalizing, because it surprises people:--- **The subagents a workflow spawns always run in `acceptEdits` mode**, regardless of your session's permission mode. **File edits are auto-approved.** Your mode controls only the launch prompt.-- Agents inherit your [tool allowlist](https://code.claude.com/docs/en/settings#permission-settings).-- Shell commands, web fetches, and MCP tools *not* in your allowlist can still prompt you mid-run. On a long run, allowlist what the agents will need **before** starting — otherwise you'll be babysitting a background job.-- In `claude -p` and the Agent SDK there's nobody to prompt, so tool calls follow your configured rules without interactive confirmation.-------## Controlling cost--A workflow spawns many agents, so one run can use meaningfully more tokens than doing the same work in conversation. Runs count against your plan's usage and rate limits like any other session.--**The cheapest habit: run it on a slice first.** One directory instead of the whole repo, a narrow question instead of a broad one. The `/workflows` view shows per-agent token usage live, and stopping a run there never loses completed work.--### Size guideline--Tells Claude how many agents to aim for. It's **advice, not a cap** — a prompt calling for different scale still overrides it. Requires v2.1.202+.--| Value | Agents Claude aims for |-|---|---|-| `unrestricted` | No guideline — sized to the task |-| `small` | Fewer than 5 |-| `medium` *(default)* | Fewer than 15 |-| `large` | Fewer than 50 |--```bash-/config workflowSizeGuideline=small-```--On v2.1.219+ you can also set `workflowSizeGuideline` in any settings file, which takes precedence over `/config`. Changes apply on the next prompt; the [runtime caps](#limits-and-behavior) always apply regardless.--### The large-run warning--When a workflow schedules more than **25 agents**, or its projected token total passes **1.5 million**, its progress line shows a `Large workflow` warning pointing you at `/workflows` (v2.1.203+). It's advisory — it doesn't pause anything. Choosing a size guideline replaces the 25-agent threshold with that guideline's count, and sessions with `ultracode` on don't show it at all (you already opted in).--### Model routing--Every agent uses your session's model unless the script routes a stage elsewhere or `CLAUDE_CODE_SUBAGENT_MODEL` is set (that env var overrides both). So: **check `/model` before a large run**, and when describing the task, ask Claude to use a smaller model for stages that don't need the strongest one.-------## Resuming a run--Stop a run and you can resume it: agents that already completed return **cached** results, and the rest run live. Resume from `/workflows` with `p`, or ask Claude to relaunch with the same script.--> 💡 **The non-obvious consequence:** an agent still running when you stopped isn't saved and starts over. So a workflow that fans work across **many small agents preserves far more progress on interruption** than one built around a few long-running agents. Worth knowing before you write a script that does everything in three giant steps.--Resume works **within the same session only**. Exit Claude Code mid-run and the next session starts that workflow fresh.-------## Turning workflows off--For yourself:--- Toggle **Dynamic workflows** off in `/config` — persists across sessions-- `"disableWorkflows": true` in `~/.claude/settings.json` — persists-- `CLAUDE_CODE_DISABLE_WORKFLOWS=1` — read at startup, applies wherever you set it--Organization-wide: `"disableWorkflows": true` in [managed settings](https://code.claude.com/docs/en/server-managed-settings), or the toggle on the [Claude Code admin settings](https://claude.ai/admin-settings/claude-code) page.--When disabled, bundled workflow commands disappear, the `ultracode` keyword stops triggering, and `ultracode` is removed from the `/effort` menu.-------## Prompt patterns that work--You describe the shape; Claude writes the script. These are the shapes that pay off:--| Goal | Prompt |-|---|---|-| **Audit many files for one issue** | `use a workflow to audit every route handler under src/routes/ for missing authentication checks, and adversarially verify each finding before reporting it` |-| **Fix until a check passes** | `use a workflow to run npx tsc --noEmit and keep fixing the reported errors until the type check passes or two rounds in a row make no progress` |-| **Migrate many files in parallel** | `use a workflow to migrate every component under src/components/ from styled-components to Tailwind, working on each file in its own isolated copy` |-| **Review, then one summary** | `use a workflow to review every file changed in this PR for correctness issues, then merge the per-file findings into one ranked summary` |-| **Research across sources** | `use a workflow to research how our three competitors handle rate limiting: read their public docs and recent changelog entries in parallel, then compare the approaches` |-| **Find issues until the list stops growing** | `use a workflow to find flaky tests in this repo: run the suite repeatedly, record which tests fail intermittently, and stop once two rounds in a row find nothing new` |--Three phrases that reliably improve the script Claude writes:--- **"adversarially verify each finding"** — adds skeptic agents that try to *refute* results before they're reported. Kills plausible-but-wrong findings.-- **"in its own isolated copy"** — puts each agent in a separate git worktree so parallel edits can't conflict.-- **"until two rounds in a row find nothing new"** — replaces a guessed count with a convergence condition. Better for discovery work where you don't know the answer's size.--> 💡 Already have an orchestrator built another way — a folder of subagent prompts, or a skill that fans work out? Point Claude at it and ask for a workflow that does the same thing.-------## See also--- [Official workflows docs](https://code.claude.com/docs/en/workflows) — authoritative reference-- [Run agents in parallel](https://code.claude.com/docs/en/agents) — subagents vs agent view vs teams vs workflows-- [Agent Teams guide](agent-teams.md) — the other multi-agent surface, and when to pick it instead-- [Effort levels](reference/effort-levels.md) — what `ultracode` changes-- [Slash commands](reference/commands.md) — `/workflows`, `/deep-research`, `/batch`-------[← Back to README](../README.md#dynamic-workflows) · [Agent Teams](agent-teams.md) · [Skills](skills.md)+<a id="permissions"></a><a id="controlling-cost"></a>What a workflow may do and spend in a run nobody watches: [Put bounds on autonomous runs](advanced/07-bounded-runs.md#watch-out).