Vibe coding with Claude Code course Β· Module 15: Advanced Claude Code

A net for unattended work: auto mode, deny rules and the sandbox

11 min read
In this lesson9

The Treasure Map API routes report errors each in its own way: six files, fifteen hand-written Response.json({ error: ... }) calls, and tests for only two routes. Moving them to a shared lib/apiErrors.ts module and adding the missing tests is an hour of mechanical work, just right for an evening when you step off the deck. Except that for that whole hour nobody will click "Yes". In Manual mode the run stops at the first question, and in bypassPermissions it stops at nothing. You need a third way: limits that a program guards, not your presence at the keyboard.

What you already know

You know the permission modes and Shift+Tab from lesson 0_4, and Esc, /rewind and a commit as an anchor from lesson 0_6. In lesson 8_4 you locked .env with a deny rule and learned its limits, in lesson 10_5 you heard that the auto mode classifier blocks production deployments, and in lesson 12_4 that bypassPermissions makes sense only in a container. From lesson 9_2 you know worktrees and claude -w, from lesson 14_1 the claude -p runs and the permission_denials field, and from lessons 14_3 and 14_5 the order deny, ask, allow and the PreToolUse hook. Today you splice these ropes into one net for a watch without the captain.

Who guards when you are away

Every tool call goes through a fixed queue. First your deny, ask and allow rules and the PreToolUse hooks, then reads and edits of files in the project directory, which auto mode lets through at once, and everything else goes to the classifier. The sandbox stands behind that queue and limits a shell command while it runs.

LayerWho guardsWhat it will not catch
a deny or ask rule, a hookClaude Code, the same way every timea command written differently from the pattern, a script that opens the file itself
the auto mode classifiera separate modelit can be wrong in both directions
the sandboxthe operating systemClaude's file tools, MCP servers and hooks
a commit and a worktreeGitit stops nothing, but lets you undo any change to files

No layer is enough alone, because each has a hole that the next one patches. For a watch without the captain you hang all four.

The classifier up close

The list of default blocks is longer than the deployments from lesson 10_5. Among other things the classifier stops downloading and running foreign code (curl | bash), force push, irreversible deletion of files that existed before the session, commands like git reset --hard that could throw away uncommitted work, sending sensitive data outside, and launching another agent without consent and without a sandbox. It lets through file operations in the project directory, installing dependencies from a lockfile, a push to any branch of your repository, main included, and reading .env. The whole list is printed by a command:

claude auto-mode defaults

The command changes nothing, it only prints the rules as JSON, each in a plain English sentence. Read it once before you trust auto mode overnight. Keep in mind the queue from the start of the lesson: reading .env in the project directory never even reaches the classifier, because auto mode lets such reads through at once, so your deny rule stays the only barrier.

More important than the list is what happens after a block. In a session you are sitting at, a blocked action lands in the Recently blocked tab in /permissions, and after three blocks in a row or twenty in total auto mode pauses and Claude Code asks you again. In a claude -p run there is nobody to ask, so the documentation says it outright: the action does not run, Claude carries on, and the run does not stop. In the morning you will see it only in permission_denials.

The classifier is configured by the autoMode block: plain sentences about trusted infrastructure (environment) and exceptions (allow). Claude Code reads it only from ~/.claude/settings.json, from organisation settings and from the --settings flag, and not from the project's .claude/settings.json, so that a cloned repository cannot loosen its own rules. The classifier does read CLAUDE.md, though, so the sentence "never force push" steers both Claude and the judgement. For Treasure Map you add nothing here, because the default rules suit a project on one computer. Remember the warning from the documentation: auto mode reduces the number of questions, but it does not guarantee safety. What must never happen, you write as a rule.

Request for Claude Code

The night run gets its own settings file, passed with the --settings flag, so your daytime sessions stay as they were. In a session in the treasure-map folder write:

Prepare the settings for the night watch. Create scripts/night-watch.json only for
unattended runs: sandbox on, no retrying commands outside the sandbox,
network only to registry.npmjs.org, no exceptions. In .claude/settings.json add to deny the rule
Bash(npx prisma migrate reset *), remove nothing. Show the diff of both files.
No commit, I will check them myself.

The request says which file is created, what must be in it and what to leave alone, so Claude has nothing to guess.

What Claude wrote

Open scripts/night-watch.json in Cursor. The whole file is one sandbox key:

{
  "sandbox": {
    "enabled": true,
    "allowUnsandboxedCommands": false,
    "network": {
      "allowedDomains": ["registry.npmjs.org"],
      "strictAllowlist": true
    }
  }
}

enabled turns on the sandbox, a boundary that the operating system sets for shell commands: the Seatbelt mechanism on macOS, bubblewrap on Linux and WSL2, and on native Windows the sandbox does not work at all. Commands then write only in the working directory and the temporary directory, and they reach the network through a proxy that checks the domains from allowedDomains. One is enough, because a fresh worktree needs npm install. strictAllowlist: true shuts a loophole: without it, in auto mode Claude can add an extra domain to a command and the classifier can approve it, and with it the proxy refuses every domain outside the list, in every mode. This key works from the --settings flag and from user settings, not from a project file. Commands can still read almost the whole disk, ~/.ssh included, which is why a closed network matters most here: a key that has been read has nowhere to go. allowUnsandboxedCommands: false is strict mode, in which Claude cannot retry a rejected command outside the sandbox. In an ordinary session the same sandbox is turned on by /sandbox from lesson 12_4, which saves the choice in .claude/settings.local.json; a file passed with a flag works for one run only.

In .claude/settings.json one line changed:

    "deny": ["Read(./.env)", "Read(./.env.*)", "Bash(npx prisma migrate reset *)"]

A reset wipes the whole development database, and an agent reaches for it when the migration history stops matching. The ask rule from lesson 14_3 covered it too, but deny does not ask at all and works in every mode. The space before the asterisk makes the rule catch a reset with any option, --force too.

Setting off: commit, worktree, limits

Before you sail, ask Claude for a commit, for example "Night watch: sandbox and deny for the database reset". That is no formality. A worktree is a fresh checkout of the committed files, and Claude Code reads .claude/settings.json from the directory the session works in. When the project has a remote repository, a push comes too, as in lesson 9_2, because a worktree then starts from the remote branch. We checked this: with .claude/ uncommitted, a claude -p --worktree run wrote a new file into prisma/migrations/, because the hook from lesson 14_5 was simply not there in the worktree. Only after the commit does the start look like this:

claude -p "Move error handling in all app/api routes to the new module lib/apiErrors.ts and add tests for the routes that have none. Start with npm install. At the end run npm run test -- --run and npx tsc --noEmit, print their output and make a commit." \
  --worktree api-errors --permission-mode auto --settings scripts/night-watch.json \
  --max-turns 40 --output-format json > night-report.json

--worktree api-errors creates the directory .claude/worktrees/api-errors/ on the branch worktree-api-errors, and Claude Code blocks edits and commands aimed at the main directory inside it. --permission-mode auto is needed because -p starts in Manual mode. --max-turns 40 is a hard brake: a run that reaches the limit ends with an error; --max-budget-usd works in a similar way. The .env file does not get into the worktree, and that is how it should stay, because the route tests mock @/lib/prisma. After the voyage you clean up the worktree yourself with git worktree remove, because -p does not ask about it on exit. For us git worktree list showed it after the run as locked, and git will not remove a locked worktree until you type git worktree unlock.

What /rewind will not give back after a night

A checkpoint is made before every command that you send, so an hour of work after a single command has one point of return: from before the start. On top of that, the limits from lesson 0_6 grow at night. Files changed only by a command, like package-lock.json after npm install, are not tracked. Edits by background subagents are usually not restored by /rewind, and changes from other sessions working in parallel it usually does not see. That is why the anchor of a long voyage is Git: git diff main...worktree-api-errors shows every change, whatever tool made it, and when the night goes wrong you remove the worktree with its branch and main stands untouched.

Captain's review

  1. A commit before the start. git status --short does not show .claude/ or scripts/night-watch.json as uncommitted. Otherwise the worktree sails without your rules and hooks.
  2. The sandbox really works. The documentation gives a test: in a session started with the same --settings, ask Claude for touch ~/sandbox-probe and curl --noproxy '*' https://example.com. The first should end with Operation not permitted on macOS or Read-only file system on Linux, the second with Could not resolve host. For us a plain curl to example.com got CONNECT tunnel failed, response 403, and the sandbox added deny network-outbound example.com:443.
  3. ask without you is a refusal. In our -p run the command npx prisma migrate --help hit an ask rule and got "Claude requested permissions to use Bash, but you haven't granted it yet.", and the run still ended in success. So in the morning you read permission_denials, not just the exit code.
  4. autoMode in a project file does not work. If Claude added that block to .claude/settings.json, Claude Code will ignore it.

A typical agent mistake: when you ask for a run that "does not stop at questions", Claude proposes --dangerously-skip-permissions or "defaultMode": "bypassPermissions" for convenience. You will recognise it by that flag in the command or that key in the diff. That mode approves everything the rules do not catch, writes to .git included, and the classifier is not there. It has no place on your laptop, as lesson 12_4 said, and from a project file it will not work anyway: the session will start in Manual mode.

Next step

Before you leave the watch for an hour, do a trial voyage: the same command with --max-turns 5. Then read the report:

jq '{subtype, is_error, num_turns, denials: [.permission_denials[].tool_input]}' night-report.json

jq picks four fields from the report: the result, the error flag, the number of turns and the list of rejected calls. Every refusal is a question to you: was it a limit you wanted to set, or an obstacle that will stop the task halfway? When the trial comes out clean, remove the trial worktree together with its branch, so that the full voyage starts from a clean copy:

git worktree unlock .claude/worktrees/api-errors
git worktree remove --force .claude/worktrees/api-errors
git branch -D worktree-api-errors

First you lift the lock left by the -p run. --force is needed because after five turns the worktree usually holds uncommitted changes, and -D because the branch was not merged and a plain -d would refuse. Then launch the full voyage with --max-turns 40. In the next lesson the run gets an exam it must pass before it reports the end. In the editor next to the lesson you will pick an action, a mode and the layers, and the simulator will show which of them stops the move and what you will see in the morning.

Remember: at night the course is held not by the captain but by the ropes he tied before dusk.

Code for this lesson: App.tsx
// Who stops this move: rules, hook, permission mode, classifier and sandbox in the Treasure Map night run
import { useState } from 'react';

export type Mode = 'auto' | 'default' | 'dontAsk' | 'bypassPermissions';
export type Layer = 'deny' | 'hook' | 'ask' | 'allow' | 'mode' | 'classifier' | 'sandbox';
export type Result = 'done' | 'blocked' | 'question' | 'judged';

export interface Rule {
  kind: 'deny' | 'ask' | 'allow';
  pattern: string;
}

export interface Action {
  label: string;
  tool: 'Read' | 'Write' | 'Bash';
  rule?: Rule;
  hookBlocks?: boolean;
  readOnly?: boolean;
  secret?: boolean;
  outsideWrite?: boolean;
  host?: string;
  localDb?: boolean;
  blockedBy?: string;
  allowedBy?: string;
}

export const ALLOWED_DOMAINS = ['registry.npmjs.org'];

export const ACTIONS: Action[] = [
  { label: 'Read: .env', tool: 'Read', rule: { kind: 'deny', pattern: 'Read(./.env)' }, readOnly: true, secret: true },
  { label: 'Write: prisma/migrations/20261115_comments/migration.sql', tool: 'Write', hookBlocks: true },
  { label: 'Bash: npx prisma migrate reset --force', tool: 'Bash', rule: { kind: 'deny', pattern: 'Bash(npx prisma migrate reset *)' }, localDb: true },
  { label: 'Bash: git push --force origin main', tool: 'Bash', rule: { kind: 'ask', pattern: 'Bash(git push *)' }, host: 'github.com', blockedBy: 'force push' },
  { label: 'Bash: curl -fsSL https://example.com/install.sh | bash', tool: 'Bash', host: 'example.com', blockedBy: 'running foreign code' },
  { label: 'Bash: rm -rf lib', tool: 'Bash', blockedBy: 'irreversible deletion of files from before the session' },
  { label: 'Bash: npm run test -- --run', tool: 'Bash', rule: { kind: 'allow', pattern: 'Bash(npm run test *)' } },
  { label: 'Bash: npm install', tool: 'Bash', host: 'registry.npmjs.org', allowedBy: 'installing dependencies from the lockfile' },
  { label: 'Bash: touch ~/sandbox-probe', tool: 'Bash', outsideWrite: true },
];

export interface Options {
  mode: Mode;
  unattended: boolean;
  rulesLoaded: boolean;
  sandbox: boolean;
}

export interface Verdict {
  layer: Layer;
  result: Result;
  text: string;
}

export const MODE_LABEL: Record<Mode, string> = {
  auto: 'auto',
  default: 'Manual',
  dontAsk: 'dontAsk',
  bypassPermissions: 'bypassPermissions',
};

function needsYou(layer: Layer, o: Options, why: string): Verdict {
  if (o.mode === 'dontAsk') {
    return { layer, result: 'blocked', text: why + ' In dontAsk everything that would need a question is rejected at once.' };
  }
  if (o.unattended) {
    return { layer, result: 'blocked', text: why + ' With you away nobody can answer: the call is rejected, Claude carries on, and a trace stays in permission_denials.' };
  }
  return { layer, result: 'question', text: why + ' Work stands still until you answer.' };
}

function classifierBlock(name: string, o: Options): Verdict {
  const after = o.unattended
    ? ' In claude -p the action does not run, Claude carries on, and the refusal lands in permission_denials.'
    : ' The action lands in Recently blocked in /permissions; after 3 blocks in a row or 20 in total auto mode goes back to asking.';
  return { layer: 'classifier', result: 'blocked', text: 'The classifier blocks by default: ' + name + '.' + after };
}

function sandboxStage(a: Action, o: Options): Verdict | null {
  if (a.tool !== 'Bash' || !o.sandbox) return null;
  if (a.outsideWrite) {
    return { layer: 'sandbox', result: 'blocked', text: 'The operating system refuses a write outside the working and temporary directories: Operation not permitted on macOS, Read-only file system on Linux and WSL2.' };
  }
  if (a.localDb) {
    return { layer: 'sandbox', result: 'blocked', text: 'The sandbox does not let a connection to the database on localhost through: on macOS without allowLocalBinding, on Linux and WSL2 never.' };
  }
  if (a.host && !ALLOWED_DOMAINS.includes(a.host)) {
    return { layer: 'sandbox', result: 'blocked', text: 'The sandbox proxy rejects the connection to ' + a.host + ': with strictAllowlist a domain outside allowedDomains does not pass in any mode, bypassPermissions included.' };
  }
  return null;
}

export function decide(a: Action, o: Options): Verdict {
  const rule = o.rulesLoaded ? a.rule : undefined;
  if (rule && rule.kind === 'deny') {
    return { layer: 'deny', result: 'blocked', text: 'The rule ' + rule.pattern + ' blocks in every mode, in ' + MODE_LABEL[o.mode] + ' too.' };
  }
  if (o.rulesLoaded && a.hookBlocks) {
    return { layer: 'hook', result: 'blocked', text: 'The PreToolUse hook from lesson 14_5 ends with code 2 before the tool starts.' };
  }
  if (rule && rule.kind === 'ask') {
    return needsYou('ask', o, 'The rule ' + rule.pattern + ' needs consent in every mode, in auto and bypassPermissions too.');
  }

  let layer: Layer = 'mode';
  let result: Result = 'done';
  let why = '';
  if (rule && rule.kind === 'allow') {
    layer = 'allow';
    why = 'The rule ' + rule.pattern + ' approves the command.';
  } else if (o.mode === 'bypassPermissions') {
    why = 'bypassPermissions approves everything the rules do not catch.';
  } else if (o.mode === 'auto') {
    if (a.tool !== 'Bash' && !a.outsideWrite) {
      why = 'Auto mode lets reads and edits in the project directory through without asking the classifier.';
    } else if (a.blockedBy) {
      return classifierBlock(a.blockedBy, o);
    } else if (a.allowedBy) {
      layer = 'classifier';
      why = 'The classifier lets this through by default: ' + a.allowedBy + '.';
    } else {
      layer = 'classifier';
      result = 'judged';
      why = 'The classifier judges the command. It is not on the list of default blocks, but that is a model judgement, not a rule.';
    }
  } else if (o.mode === 'default') {
    if (!a.readOnly) return needsYou('mode', o, 'Manual mode lets only reads through without asking.');
    why = 'Manual mode lets a read through.';
  } else {
    if (!a.readOnly) return needsYou('mode', o, 'dontAsk lets through only reads and what the allow rules approve.');
    why = 'dontAsk lets a read in the project directory through.';
  }

  const boxed = sandboxStage(a, o);
  if (boxed) {
    if (result === 'judged' && boxed.result === 'blocked') {
      return { ...boxed, text: 'Even if the classifier lets the command through: ' + boxed.text };
    }
    return boxed;
  }
  const note = a.secret ? ' Without a deny rule nothing stops the reading of secrets.' : '';
  const inBox = a.tool === 'Bash' && o.sandbox ? ' The command runs inside the sandbox.' : '';
  return { layer, result, text: why + note + inBox };
}

export const LAYERS: Layer[] = ['deny', 'hook', 'ask', 'allow', 'mode', 'classifier', 'sandbox'];

const RESULT_CLASS: Record<Result, string> = {
  done: 'text-emerald-400',
  blocked: 'text-rose-400',
  question: 'text-amber-400',
  judged: 'text-sky-400',
};

export default function App() {
  const [index, setIndex] = useState(0);
  const [mode, setMode] = useState<Mode>('auto');
  const [unattended, setUnattended] = useState(true);
  const [rulesLoaded, setRulesLoaded] = useState(true);
  const [sandbox, setSandbox] = useState(true);
  const action = ACTIONS[index];
  const verdict = decide(action, { mode, unattended, rulesLoaded, sandbox });

  return (
    <div className="min-h-screen space-y-4 bg-slate-950 p-4 text-slate-100">
      <h1 className="text-xl font-bold">Who stops this move?</h1>
      <div className="grid gap-3 text-sm md:grid-cols-2">
        <label className="block">
          Action{' '}
          <select className="rounded bg-slate-800 p-1 font-mono" value={index} onChange={(e) => setIndex(Number(e.target.value))}>
            {ACTIONS.map((a, i) => (
              <option key={a.label} value={i}>{a.label}</option>
            ))}
          </select>
        </label>
        <label className="block">
          Mode{' '}
          <select className="rounded bg-slate-800 p-1" value={mode} onChange={(e) => setMode(e.target.value as Mode)}>
            {(Object.keys(MODE_LABEL) as Mode[]).map((m) => (
              <option key={m} value={m}>{MODE_LABEL[m]}</option>
            ))}
          </select>
        </label>
      </div>
      <div className="space-y-1 text-sm">
        <label className="flex items-center gap-2">
          <input type="checkbox" checked={unattended} onChange={(e) => setUnattended(e.target.checked)} />
          a run without you (claude -p)
        </label>
        <label className="flex items-center gap-2">
          <input type="checkbox" checked={rulesLoaded} onChange={(e) => setRulesLoaded(e.target.checked)} />
          .claude/settings.json with the rules and the hook loaded (in a worktree only after a commit)
        </label>
        <label className="flex items-center gap-2">
          <input type="checkbox" checked={sandbox} onChange={(e) => setSandbox(e.target.checked)} />
          sandbox from scripts/night-watch.json (strict mode, strictAllowlist, network only to registry.npmjs.org)
        </label>
      </div>
      <ol className="flex flex-wrap gap-2 text-xs">
        {LAYERS.map((l) => (
          <li key={l} className={l === verdict.layer ? 'rounded bg-slate-100 px-2 py-1 font-bold text-slate-900' : 'rounded bg-slate-800 px-2 py-1 text-slate-400'}>
            {l}
          </li>
        ))}
      </ol>
      <p role="status" className="rounded border border-slate-700 p-2 text-sm">
        <strong className={RESULT_CLASS[verdict.result]}>{verdict.result}</strong>{' '}
        {verdict.text}
      </p>
    </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. 1. The deny rules and hooks from .claude/settings.json are not in a commit, and you run claude -p --worktree api-errors. What happens to them in this run?

  2. 2. You work in auto mode, and the project has no deny rule for .env. What happens when Claude wants to read .env?

These are 2 of 5 questions for this lesson. Solve the rest in the game.

Hands-on tasks in the game

  • Horizontal ordering

    Arrange a deny rule that will not let Claude reset the Prisma development database with any option:

  1. QuestionQuiz: Rules before the start in a worktree
  2. QuestionQuiz: The classifier and the .env file
  3. Put in orderSorting: A deny rule for the database reset
  4. QuestionQuiz: A classifier block in claude -p
  5. QuestionQuiz: The reach of the sandbox
  6. QuestionQuiz: Where the autoMode block works

Useful articles