Cursor Skill

claude-delegate

Delegate a coding task to a separate Claude Code CLI process or another Claude session as an implementer, then review its diff and land it yourself. Use only when the user explicitly asks to delegate implementation to Claude Code, another Claude session, or the `claude` CLI — for

LLM Mart · 0 points · 11 views 0 listing impressions 0 install-command copies
Virus-scanned Reviewed automatically before listing.

Full trust report

Download amElnagdy-delegate-skills-skills_claude-delegate-f36c3db.zip · 32 KB
Part of amelnagdy/delegate-skills — 18 skills

Install

skills CLI npx skills add https://github.com/amElnagdy/delegate-skills/tree/master/skills/claude-delegate
Claude Code claude plugin marketplace add https://llmmart.ai/marketplace.json && claude plugin install amelnagdy-delegate-skills@llmmart
Git git clone https://github.com/amElnagdy/delegate-skills.git

The skills CLI installs just this skill, for any of its supported agents. Claude Code installs the whole amelnagdy/delegate-skills collection as a plugin from our marketplace. Git is the plain clone.

Skill manifest

Claude Delegate

You are the orchestrator. Delegate one bounded coding task to a separate implementer — a Claude Code CLI session — then review what it produced and land it yourself. You write the brief and own the judgment; the separate Claude session edits the working tree; you verify and commit.

This skill is not a signal for the current Claude to implement directly. Use it only after the human explicitly asks for delegation to another Claude Code process or session.

When not to use this

  • The human asked the current agent to implement the task directly.
  • The task is small enough to do inline and the human did not request delegation.
  • The claude CLI is missing or unauthenticated (claude auth status).
  • The task needs a stronger host boundary than Claude Code's tool permissions and shell-only sandbox provide. Use an isolated container or VM for that requirement.

Prerequisites

  1. claude --version succeeds.
  2. claude auth status reports an authenticated session. On macOS the live credentials sit in the login Keychain; when the orchestrator's own sandbox blocks Keychain access (Codex's sandbox does), claude falls back to a possibly stale credentials file and reports loggedIn: false even though the login is valid. Re-run the check — and the dispatch itself — with that sandbox escalated or outside it before concluding the CLI is unauthenticated.
  3. The target repository is the directory passed with --cd.
  4. On Linux/WSL2, Claude's sandbox dependencies are installed. The normal relay profile is configured to fail when the sandbox is unavailable instead of silently running shell commands unsandboxed. Existing merged settings can still affect the effective boundary.

The loop

1. Write the brief

The separate session has no orchestrator chat history. It receives the brief on stdin and can inspect the target working tree.

Claude Code automatically discovers the target project's CLAUDE.md and normal local Claude configuration because the relay does not use --bare. It does not generically auto-load AGENTS.md. Read AGENTS.md yourself and copy every load-bearing constraint and the real gate commands into the brief. Tell the implementer not to commit. Keep one task per brief.

Template and details: references/writing-the-brief.md.

2. Dispatch

node "<skill-dir>/scripts/relay.mjs" --brief brief.txt --cd /path/to/repo
# review/diagnosis only:                 add --read-only
# continue the latest session:           add --resume-last
# continue the recorded session:         add --session <id>
# choose limits:                         add --max-turns 40 --max-budget-usd 10
# set the auto-compact window:           add --autocompact 400k
# hard relay deadline:                   add --timeout 2h
# inspect every option:                  node .../relay.mjs --help

<skill-dir> is this installed skill directory, the folder containing this SKILL.md.

The relay runs claude -p --output-format stream-json --verbose, sends the brief through stdin, and writes artifacts under the system temp directory by default. It never uses --bg or --bare, and it never commits. See references/dispatch-and-poll.md.

--autocompact <auto|tokens> passes Claude Code's auto-compact window setting on every new or resumed invocation, and needs Claude Code 2.1.221 or newer — older builds fail the dispatch with unknown option '--autocompact'. The installed CLI owns the accepted range (auto, or 100k–1M tokens); the relay records the requested value but does not claim that Claude applied or enforced it.

3. Wait

The relay blocks until Claude exits. Use the orchestrator's background-command facility, or run it in the foreground and wait. Completion means the process exited and result.json exists.

  • A pre-run usage error exits 2 and writes no result.json.
  • A missing claude exits 127 and writes status: "claude_unavailable".
  • Timeout and caught relay signals terminate the whole implementer process tree and preserve an outcome artifact.

Read finalMessage, touchedFiles, resultSubtype, and the raw artifact paths from result.json.

4. Review

Treat the implementer's report and gate outcomes as claims:

  • Review edits to existing tests before a green gate means anything.
  • Re-run the project's actual gates yourself.
  • Read the complete diff against the brief, starting with touchedFiles.
  • Inspect untracked and staged content as well as the ordinary diff.
  • Run relevant guard skills if installed.

Full checklist: references/review-and-land.md.

5. Land

The orchestrator commits only after the gates pass and the diff holds. For rework, resume the same Claude session with a delta brief:

echo "Keep the implementation, replace the mocked DB test with the migrated fixture, and remove the
unused import." | node "<skill-dir>/scripts/relay.mjs" --session <id> --cd /path/to/repo

Review a resumed run exactly like the first run.

Permission profiles

The normal profile is deliberately explicit:

  • acceptEdits permission mode.
  • Built-in tools restricted to Read, Glob, Grep, Edit, Write, and the platform shell.
  • On macOS, Linux, and WSL2, Claude's shell sandbox is enabled with startup failure on missing dependencies and no unsandboxed retry. Commands that stay sandboxed are auto-approved so ordinary gates can run headlessly. The sandbox governs shell processes and their children only; merged local or managed sandbox settings can add effective paths or exclusions.
  • Configured MCP discovery and Claude.ai connectors are disabled, all MCP tools are denied, and skills, commands, and Claude's Agent tool are unavailable to the child. Project CLAUDE.md, hooks, normal authentication, session persistence, and other local settings still load.
  • String rules deny common direct shell forms of git commit, git push, and nested claude, plus any command containing claude-delegate. Aliases, scripts, and wrappers can bypass them, so they are only a speed bump; the brief's no-commit instruction and orchestrator review remain the boundary.

Native Windows does not support Claude's shell sandbox. The relay restricts the tool surface and pre-approves PowerShell so the run remains non-interactive, but that shell is not OS-isolated. Native claude.exe and npm claude.cmd launch paths are implemented; Windows verification is pending.

--read-only uses plan mode with only Read, Glob, and Grep. It removes edit, write, and shell paths, then compares parsed git porcelain and fingerprints the working-tree identity and index entries of Git-visible paths that were already dirty. readOnlyViolation is true when either signal proves a change, false when coverage is complete and detects none, and null when coverage is incomplete. This is a reporting tripwire, not an OS boundary: ignored paths and perfect restores are outside it, local hooks can write, and concurrent changes cannot be attributed to Claude.

--dangerously-skip-permissions is an explicit opt-in to Claude's bypassPermissions mode. The restricted tool surface, direct commit/push deny rules, and supported-platform shell sandbox remain, but direct file tools can cross normal permission boundaries. Use it only with the human's explicit acceptance.

Complementary to native Claude features

Claude subagents, agent teams, and background sessions are useful when the current Claude environment is already the orchestrator and native coordination is the goal. This skill is complementary: it provides a cross-orchestrator contract — self-contained brief → dispatch → artifacts → review → land — and keeps the commit with the orchestrator.

References

Files (delegate-skills)
  • references
    • dispatch-and-poll.md 12.9 KB
      # Dispatch and poll
      
      `scripts/relay.mjs` wraps Claude Code's non-interactive `claude -p` mode, sends a brief on stdin,
      captures the structured stream, and writes `delegate-relay.result.v1`.
      
      ## Before the first run
      
      ```bash
      command -v claude
      claude --version
      claude auth status
      ```
      
      The relay performs its own `claude --version` preflight and records the answer as `claudeVersion`.
      When an orchestrator is itself Claude Code, the relay removes only inherited `CLAUDECODE` from the
      child environment so a separate CLI process can start. It preserves credentials,
      `CLAUDE_CODE_CHILD_SESSION`, and every other environment entry. Version preflight uses that same
      environment.
      
      ## Dispatch
      
      ```bash
      node "<skill-dir>/scripts/relay.mjs" --brief brief.txt --cd /path/to/repo
      ```
      
      `<skill-dir>` is the installed folder containing this skill's `SKILL.md`.
      
      | Flag | Effect |
      | --- | --- |
      | `--brief <file>` | Brief path. Omit it to read stdin. The exact text is then sent to Claude on stdin, never argv. |
      | `--cd <dir>` | Child process cwd and target working root (default: current directory). |
      | `--lane <name>` | Fleet lane from `delegate-setup` config. Applies that lane's dials; fails if the lane's `implementer` is not this relay. Explicit dial flags win. |
      | `--out-dir <dir>` | Artifact directory (default: a fresh directory under the system temp directory). |
      | `--timeout <dur>` | Relay watchdog, such as `30m`, `90s`, or `2h` (default: off). |
      | `--model <name>` | Claude model alias or full name (default: Claude's configured choice). The relay does not pin a model version. |
      | `--effort <level>` | Claude effort: `low`, `medium`, `high`, `xhigh`, `max`, or `ultracode`; availability depends on the model. |
      | `--max-turns <n>` | Positive agentic-turn cap. |
      | `--max-budget-usd <amount>` | Positive decimal spend cap for print mode. |
      | `--autocompact <auto\|tokens>` | Set Claude Code's auto-compact window on Claude Code `2.1.221` or newer. The relay validates a shell-safe shape; the installed Claude CLI owns the supported range. |
      | `--resume-last` | Resume the latest session for this cwd with Claude's `--continue`; send a delta brief. |
      | `--session <id>` | Resume a specific session with Claude's `--resume <id>`; mutually exclusive with `--resume-last`. |
      | `--read-only` | Plan mode with only Read, Glob, and Grep, plus a Git-visible change tripwire. |
      | `--dangerously-skip-permissions` | Opt into Claude's `bypassPermissions`; mutually exclusive with `--read-only`. |
      | `-h`, `--help` | Print the relay header and option reference. |
      
      Values that can reach an npm `claude.cmd` launch on Windows are token- or number-validated. The brief
      never reaches a shell command line.
      
      ## What the relay launches
      
      The common shape is:
      
      ```bash
      claude -p --output-format stream-json --verbose \
        --tools Read,Glob,Grep,Edit,Write,Bash \
        --strict-mcp-config --disallowedTools 'mcp__*' \
        --disable-slash-commands \
        --settings <profile.json> \
        --permission-mode acceptEdits \
        < brief.txt
      ```
      
      On native Windows, `PowerShell` replaces `Bash` and is passed through `--allowedTools` because Claude's
      shell sandbox is unavailable there. Read-only uses `--tools Read,Glob,Grep --permission-mode plan`. A
      specific session adds `--resume <id>`; the latest session adds `--continue`. The permission and tool
      profile is re-passed on every resumed invocation. When requested, `--autocompact <value>` is also
      re-passed on every new, `--resume`, or `--continue` invocation rather than assumed to persist from an
      earlier launch.
      
      The relay never adds `--bg`: Claude documents background mode as incompatible with `-p`. It never adds
      `--bare`, because bare mode skips `CLAUDE.md` and OAuth/keychain authentication.
      
      `--strict-mcp-config` without an MCP config prevents configured-server discovery. The inline settings
      also disable Claude.ai connectors, while `--disallowedTools 'mcp__*'` denies any MCP tool that managed
      policy still supplies. `--disable-slash-commands` prevents skill and command recursion, and `--tools`
      omits the Agent tool. These controls do not suppress project `CLAUDE.md` or normal authentication.
      
      ## Permission reach
      
      ### Normal write-capable profile
      
      The normal profile pairs `acceptEdits` with sandbox auto-approval on supported platforms.
      `acceptEdits` accepts file edits but does not, by itself, approve ordinary shell gates in a headless
      run. `autoAllowBashIfSandboxed: true` approves commands that stay inside Claude's sandbox. A command
      that cannot stay sandboxed fails instead of being retried outside it. Native Windows is the explicit
      exception: the relay pre-approves PowerShell because no Claude shell sandbox is available there.
      
      The generated `profile.json`:
      
      - uses string rules to deny common direct shell forms of `git commit`, `git push`, and nested
        `claude`, plus any command containing `claude-delegate`; aliases, scripts, and wrappers can bypass
        these speed bumps, so the brief's no-commit instruction and orchestrator review remain the boundary;
      - on macOS, Linux, and WSL2, enables Claude's Bash sandbox with `failIfUnavailable: true`,
        `autoAllowBashIfSandboxed: true`, `allowUnsandboxedCommands: false`, and filesystem isolation
        explicitly enabled;
      - on native Windows, leaves the unsupported sandbox unconfigured and enables Claude's PowerShell
        tool through its documented settings environment switch;
      - disables Claude.ai connectors for every profile.
      
      On supported platforms, the strict settings prevent a shell command from silently falling back to an
      unsandboxed retry. Claude's sandbox covers **Bash and its child processes only**. Edit/Write remain
      Claude Code tools governed by its permission system; the Claude process, local hooks, inherited
      configuration, and unrelated host processes are not enclosed in a universal workspace sandbox.
      
      Claude merges some sandbox arrays across settings scopes. Existing managed, user, project, or local
      allowlists and `excludedCommands` can therefore affect the effective shell boundary, while managed
      policy can further restrict or reject the run. Existing `ask` and `deny` permission rules take
      precedence over sandbox auto-approval, so they can still stop a headless gate. Inspect both
      `profile.json` and the effective local Claude configuration when the precise boundary matters. Use a
      container or VM when only a host-level boundary is acceptable.
      
      ### Read-only profile
      
      `--read-only` removes Edit, Write, Bash/PowerShell, Agent, MCP, skills, and commands from the child and
      uses `plan` mode. Local hooks still load outside that tool surface and can write. The relay compares
      parsed `git status --porcelain -z -uall` and fingerprints working-tree identity and index entries for
      paths that were already dirty on every outcome, including aborts:
      
      - `readOnlyViolation: true` — either signal proves a Git-visible change.
      - `readOnlyViolation: false` — coverage was complete and neither signal detected a change.
      - `readOnlyViolation: null` — coverage was incomplete, for example because git could not report or a
        dirty submodule or unreadable path could not be fingerprinted.
      
      This detects new dirt and changes to readable, already-dirty Git-visible paths, but cannot attribute a
      concurrent change. Ignored paths, submodule internals, and writes perfectly restored before the final
      snapshot remain outside coverage. Inspect the diff whenever read-only integrity matters.
      
      ### Permission bypass
      
      `--dangerously-skip-permissions` passes Claude's flag and records
      `permissionMode: "bypassPermissions"` unless the init event reports another value. The explicit tool
      surface, commit/push deny rules, MCP/skill restrictions, and supported-platform shell sandbox remain.
      However, direct file tools can cross ordinary Claude permission boundaries. This mode requires the
      human's explicit acceptance.
      
      ## Artifacts
      
      The default artifact directory is outside the repository so relay output does not pollute
      `touchedFiles`. A caller-selected `--out-dir` inside the worktree will appear in git status. For a
      meaningful `--read-only` review, keep artifacts outside the worktree. The fingerprint signal excludes
      only the relay-owned artifact paths, so their later writes do not prove a violation.
      
      - `brief.txt` — exact stdin brief.
      - `events.jsonl` — raw stdout bytes from `--output-format stream-json`.
      - `final.txt` — final `result` event's `result` text; present even when empty.
      - `stderr.txt` — complete stderr.
      - `profile.json` — exact inline settings passed to Claude.
      - `result.json` — stable result contract, written atomically.
      
      ## `result.json`
      
      Core fields:
      
      - `schema` — `"delegate-relay.result.v1"`.
      - `tool` — `"claude"`.
      - `status` — `completed` | `failed` | `timeout` | `aborted` | `claude_unavailable`.
      - `exitCode` — Claude's code, `127` when missing, a signal-derived code when available, or a forced
        non-zero value when the watchdog or terminal error result makes a zero code non-successful.
      - `signal` — terminating child/relay signal when reported, otherwise `null`.
      - `claudeVersion` — version preflight text, `"unknown"` when the binary answered abnormally, or `null`
        when unavailable.
      - `permissionMode` — selected profile, updated from `system/init` when present.
      - `sessionId` — parsed defensively from init/result events; use with `--session`.
      - `resultSubtype` — final result subtype, such as `success` or an error subtype.
      - `finalMessage` — final result text.
      - `numTurns`, `usage`, `totalCostUsd` — terminal result metadata when present.
      - `touchedFiles` — final `git status --porcelain` lines for `--cd`; `null` means git could not report,
        while `[]` means git reported a clean tree. This is the whole final tree, not attribution.
      - `readOnlyViolation` — present only on `--read-only`, with the three-state meaning above.
      
      Run metadata includes `workdir`, `model`, `effort`, `maxTurns`, `maxBudgetUsd`, optional
      `autocompact`, `timeout`, `readOnly`,
      `resumed`, `resumeLast`, `toolSurface`, `shellSandbox`, `dangerouslySkipPermissions`, timestamps, and
      all artifact paths. Failed, timed-out, and aborted runs include `stderrTail` when available;
      launch/watchdog/signal failures include `error`.
      
      `autocompact` records only the value the relay requested and passed in argv. It is absent when the
      flag was omitted and is not proof that Claude Code applied or enforced the setting. On Claude Code older than 2.1.221 the launch fails with `unknown option '--autocompact'`; if a newer CLI rejects the value's range it fails at argument parsing. Either way the non-zero exit and stderr are preserved and the relay does not retry without the flag.
      
      The relay prints a concise summary and the complete final report to stdout, then exits with
      `result.json`'s `exitCode`.
      
      ## Wait for completion
      
      The relay blocks. Use the orchestrator's background-command facility or foreground it for short work.
      If using a shell's own background feature, completion requires both:
      
      1. the relay process has exited; and
      2. `result.json` contains a terminal `status`.
      
      A usage error exits 2 before creating `result.json`, so also observe process exit. A missing CLI is
      different: it exits 127 **with** `status: "claude_unavailable"`.
      
      ## Failure recovery
      
      - **`claude_unavailable`:** install Claude Code, authenticate with `claude auth login`, and verify the
        same PATH the orchestrator uses.
      - **`failed`:** inspect `resultSubtype`, `error`, `stderrTail`, `stderr.txt`, and the tail of
        `events.jsonl`. Common causes are authentication, a model/effort mismatch, managed policy, a missing
        sandbox dependency, or a gate that needs access outside the strict shell boundary.
      - **`timeout`:** the relay sent termination to the whole process group/tree and escalated. The working
        tree may contain partial edits; inspect it before resuming or re-dispatching.
      - **`aborted`:** the relay caught SIGTERM, SIGINT, or SIGHUP, terminated the implementer tree, wrote an
        outcome, then refreshed `touchedFiles` after a grace window. Native Windows cannot deliver every
        termination as a catchable Node signal; a vanished relay with no result still requires direct
        artifact/tree inspection.
      - **Host `SIGKILL`:** the relay cannot catch its own SIGKILL. If the child reports SIGKILL, investigate
        host memory or supervisor deadlines.
      - **Empty `finalMessage`:** inspect the raw events and diff. Require a closing report in the next brief.
      
      Never clean, reset, or switch branches before inspecting partial work, staged changes, and untracked
      files.
      
      ## Windows launch
      
      The relay resolves PATH itself. A native `claude.exe` is spawned directly. An npm `claude.cmd` is
      invoked through `cmd.exe /d /v:off /s /c` with every argument quoted and user-selectable values
      restricted; stdin still carries the brief. `taskkill /t /f` terminates the process tree.
      
      This path is implemented but not yet verified on native Windows. Claude's Bash sandbox is unsupported
      there, so even a successful Windows smoke would verify launch and termination mechanics, not provide
      the supported-platform shell boundary.
      
      ## Commit boundary
      
      The relay never commits. Claude edits; the orchestrator reviews, re-runs gates, and lands. See
      [review-and-land.md](review-and-land.md).
      
    • multi-task-queues.md 2.7 KB
      # Multi-task queues
      
      The single-task loop scales to a migration, removal, or refactor queue. Sequencing and bookkeeping,
      not parallelism, keep the work reviewable.
      
      ## Run sequentially
      
      Dispatch one task at a time in dependency order. Review, run gates, and land it before dispatching the
      next:
      
      ```bash
      node "<skill-dir>/scripts/relay.mjs" --brief task-01.txt --cd /path/to/repo
      ```
      
      - Later tasks can rely on earlier behavior only after it lands.
      - One reviewed commit per task keeps rollback and history clear.
      - A clean tree before each dispatch makes `touchedFiles` useful.
      
      Use parallel dispatches only for genuinely independent tasks in separate working trees. Multiple
      implementers editing one tree destroy attribution and make the review boundary unreliable.
      
      ## Use fresh sessions for fresh tasks
      
      Each unrelated queue item should start a new Claude session. Use `--resume-last` or `--session <id>`
      only for rework on the same task; send a delta brief.
      
      A fresh session does not remember prior queue decisions. If task 2 chose a helper name, fixture
      location, interface, or migration ordering that task 5 needs, write that fact explicitly into task
      5's brief.
      
      Claude Code will discover `CLAUDE.md`, but it does not generically auto-load `AGENTS.md`. Carry the
      applicable `AGENTS.md` constraints into every brief rather than assuming the first session established
      them for later sessions.
      
      ## Keep a progress file
      
      For more than two or three tasks, maintain one durable progress file:
      
      - **Status:** queued / dispatched / reviewed+landed, including the commit hash.
      - **Per-task review:** what landed, what was inspected, and gate outcomes.
      - **Needs your eyes:** design decisions, non-blocking concerns, and questions for the human.
      - **Session/artifact pointers:** the task's `sessionId` and `result.json` path for rework or diagnosis.
      - **End-of-run gates:** the final cross-task verification still required.
      
      Update it when each task lands, not in one batch at the end.
      
      ## Close with coherence
      
      After the last task:
      
      - run the full project gates, not only the last task's narrow slice;
      - search repository-wide for the concept the queue migrated, removed, or renamed;
      - replay all new migrations from a clean state and check drift when applicable;
      - inspect the final commit sequence and working tree;
      - only then push and open or update the pull request.
      
      ## Stop and ask when
      
      Proceed on work that follows from the agreed queue. Stop and surface when:
      
      - a task cannot be completed correctly within its brief;
      - review calls the plan itself into question;
      - a gate reveals a problem in an already-landed task;
      - the next task requires a permission or host-boundary change the human did not approve.
      
      Report what has landed, commit hashes, the current tree state, and the open question, then wait.
      
    • review-and-land.md 5.4 KB
      # Review and land
      
      The separate Claude session did the typing; the orchestrator owns the judgment. Verify against the
      working tree and gate output, never against the implementer's self-report.
      
      ## Review tests before trusting gates
      
      If existing tests changed, inspect those edits first:
      
      - An unbriefed test edit is a contract change, not automatically part of the fix.
      - Treat a new skip, disable marker, commented-out case, or deleted test as a failure until justified.
      - Reject assertions weakened from exact behavior to contains/truthy, broader error types, or wider
        tolerances unless the brief required that semantic change.
      
      A green gate proves less if the implementer shortened the yardstick.
      
      ## Re-run the gates
      
      `finalMessage` reports Claude's claims. Run the project's actual test, lint, format, type, and build
      commands yourself in the final working tree and read their output. Passing is necessary, not
      sufficient.
      
      Add verification suited to the change:
      
      - **Migrations/schema:** apply, reverse, and re-apply from a clean scratch state; check drift.
      - **Removals/renames:** search repository-wide for dangling names and stale docs/config.
      - **Stateful behavior:** exercise the behavior, not only compilation.
      - **Generated output:** regenerate it through the canonical command and compare.
      
      ## Inspect the complete tree
      
      Start with `touchedFiles`, but remember it is final git porcelain, not attribution. It includes
      pre-existing dirt and can omit modifications inside ignored files. Inspect:
      
      ```bash
      git status --short
      git diff
      git diff --cached
      ```
      
      Open every untracked file directly; ordinary `git diff` does not show its contents. Review staged
      changes even though the relay denies common direct `git commit`/`git push` shell forms and the brief
      forbids staging. A local hook, another tool, or an unusual command path may still have touched the
      index.
      
      For `--read-only`, treat `readOnlyViolation: true` as a hard warning and `null` as unknown. `false`
      means the Git-visible tripwire had complete coverage and detected no change. Ignored paths, submodule
      internals, perfect restores, and attribution remain outside its contract. Compare the actual diff when
      read-only integrity matters.
      
      ## Hold the diff against the brief
      
      - **Scope creep:** files or behavior the brief excluded, unrelated cleanup, opportunistic renames.
      - **Scope shortfall:** missing edge cases, integration updates, cleanup, or required gates.
      - **Quiet judgment calls:** defensible choices not authorized by the brief. Understand and surface
        them rather than silently accepting them.
      - **Repository constraints:** especially constraints copied from `AGENTS.md`, which Claude Code does
        not generically auto-load.
      
      ## Implementer sweep
      
      Generated code can satisfy tests while remaining wrong. Check every diff for:
      
      - hardcoded success, fixture values, or fake fallbacks on real-work paths;
      - broad catches that suppress failures and return defaults;
      - APIs, methods, flags, and dependencies absent from the installed versions;
      - unused imports, uncalled helpers, unreachable branches, and scaffolding comments;
      - a second HTTP client, error idiom, state mechanism, or logging style beside the existing one;
      - tests that assert implementation details or mock the project's own behavior;
      - near-duplicate tests that inflate volume without adding behavior coverage;
      - optional parameters, configuration, or abstractions with no caller;
      - guards for impossible internal states that obscure real trust-boundary validation;
      - network or filesystem assumptions hidden by the implementer's environment.
      
      Run relevant guard skills when installed. Anything blocking goes back through a delta brief or is
      fixed in the tree, and either choice is reported to the human.
      
      ## Preserve interrupted work
      
      From dispatch until a reviewed commit, the uncommitted tree is the authoritative copy. Do not
      reflexively run `git checkout`, `git reset`, `git clean`, or switch branches after a timeout, abort, or
      failed result. First inspect status, unstaged and staged diffs, untracked files, `events.jsonl`, and
      `stderr.txt`. After inspection, discarding premise-invalid work can be the correct decision.
      
      ## Rework in the same session
      
      Send only the review delta:
      
      ```bash
      echo "The runtime fix is correct. Replace the mocked database test with the existing migrated fixture,
      remove the unused import, rerun the original gates, and leave the tree uncommitted." |
        node "<skill-dir>/scripts/relay.mjs" --session <id> --cd /path/to/repo
      ```
      
      Use `--resume-last` only when the latest session for that cwd is unambiguous. `--session <id>` is safer
      when several Claude sessions exist. The relay maps them to `--continue` and `--resume`, respectively,
      and re-passes the permission profile.
      
      Rework gets the same test review, gate rerun, diff review, and implementer sweep. Repeat until the work
      holds.
      
      ## Commit boundary
      
      When the gates pass and the diff satisfies the brief, **the orchestrator commits**, never the
      implementer. Write a clear message describing what landed.
      
      ## Surface, do not absorb
      
      The human opted into delegation, so landing verified work is the contract. Keep them informed when
      the work changes shape:
      
      - report design decisions and defensible-but-unrequested turns;
      - note non-blocking concerns you chose not to block on;
      - stop and ask when correct completion requires expanding the brief.
      
      For a queue, record these in the progress file described in
      [multi-task-queues.md](multi-task-queues.md).
      
    • writing-the-brief.md 7 KB
      # Writing the brief
      
      A brief carries the task-specific context from the orchestrator to the separate Claude Code session.
      The implementer has **no orchestrator chat history or other shared context**. It receives the brief on
      stdin, can inspect the target working tree, and loads Claude Code's usual local context as described
      below. A resumed session also retains its own Claude conversation.
      
      If a fact is not in the brief, discoverable in that tree, or present in the loaded Claude context, do
      not assume the implementer knows it.
      
      ## Know what Claude loads
      
      The relay deliberately does not use `--bare`, so Claude Code discovers the project's `CLAUDE.md`,
      normal local Claude settings, and session state in its usual way. The relay overrides a small,
      inspectable subset for the child: MCP servers are not discovered, skills and commands are disabled,
      and the built-in tool surface is restricted. Local hooks still load; account for any repository
      effects they are configured to perform.
      
      Claude Code does **not** generically auto-load `AGENTS.md`. Before writing the brief:
      
      1. Read the applicable `AGENTS.md` files yourself.
      2. Copy every load-bearing rule into the brief: scope boundaries, forbidden patterns, required
         commands, generated-file policy, and commit policy.
      3. Name the real gates rather than telling Claude to "run the tests."
      
      The implementer can read an `AGENTS.md` when the brief points to it, but that is explicit task context,
      not automatic Claude Code behavior.
      
      ## A compact structure
      
      Use a bounded, block-structured brief:
      
      ```xml
      <task>
      State the concrete job, current behavior, desired behavior, and where it lives. Name what must remain
      untouched. Include any facts from the orchestrator conversation that the implementer cannot discover
      from the tree.
      </task>
      
      <repo_constraints>
      Copy the applicable load-bearing constraints from AGENTS.md and other project instructions here.
      Claude also loads CLAUDE.md, but restate rules whose violation would invalidate the work.
      </repo_constraints>
      
      <verification_loop>
      Run these exact project gates, fix failures caused by the change, and report the final outcomes:
        <actual test command>
        <actual lint/format command>
        <actual build/typecheck command>
      Confirm the working tree contains only intended changes.
      </verification_loop>
      
      <action_safety>
      Keep changes within the task. Do not perform unrelated cleanup. Do not run git add, git commit, or git
      push. Do not invoke another Claude session or delegation skill. Leave all work uncommitted for the
      orchestrator to review and land.
      </action_safety>
      
      <structured_output_contract>
      End with:
        1. What changed and why
        2. Files touched
        3. Gate outcomes, including useful counts
        4. Deviations, open questions, and decisions the orchestrator should review
      </structured_output_contract>
      ```
      
      Remove empty blocks rather than adding ceremony. Add focused blocks when needed:
      
      - **Debugging:** `<completeness_contract>` to require a full root-cause fix, and
        `<missing_context_gating>` to prohibit guesses about missing repository facts.
      - **Read-only diagnosis:** `<grounding_rules>` to require file/line or command evidence and clearly
        label inference. Dispatch with `--read-only`.
      - **Migration or removal:** an explicit repository-wide search and round-trip requirement.
      
      ## Discover the real gates
      
      Read the repository's `CLAUDE.md`, `AGENTS.md`, `Makefile`, package scripts, and language tooling before
      dispatch. Copy exact commands into `<verification_loop>`. Include required setup and the narrowest
      useful test slice, but do not replace a required full gate with a guessed shortcut.
      
      `acceptEdits` alone does not approve ordinary gate commands in non-interactive mode. On supported
      platforms the normal relay profile auto-approves commands that stay inside Claude's shell sandbox and
      requests failure when that sandbox is unavailable. A gate that needs network access, host services,
      or writes outside the working tree may fail under that profile; state the need in the brief and decide
      whether a different isolated environment is appropriate instead of silently weakening the boundary.
      Merged local or managed settings can affect the effective sandbox. Native Windows pre-approves
      PowerShell without that sandbox; see [dispatch-and-poll.md](dispatch-and-poll.md).
      
      ## One task per brief
      
      One brief → one separate Claude session → one reviewed commit keeps scope and rollback clear. Split a
      mixed request such as "fix the bug, redesign the API, update unrelated docs, and propose a roadmap"
      into separate dispatches.
      
      Use a resumed session only for rework on the same task. Start unrelated queue items in fresh sessions.
      
      ## Premises freeze at dispatch
      
      There is no steering channel while the relay is running. Audit ownership, scope, branch, constraints,
      and expected behavior before dispatch. If a premise changes during the run, stop it and inspect the
      working tree before sending a corrected brief. Do not discard partial edits before reviewing them.
      
      ## Delta briefs for resumed sessions
      
      `--resume-last` maps to Claude's `--continue`; `--session <id>` maps to `--resume <id>`. Both retain the
      conversation, so send only what changed:
      
      ```xml
      <review_delta>
      The implementation behavior is correct. Replace the test's mocked database session with the existing
      migrated fixture, remove the unused import, run the same gates, and leave the tree uncommitted.
      </review_delta>
      ```
      
      The relay re-passes the selected permission profile on resume. A resumed run receives the same review
      as a fresh run.
      
      ## Brief delivery
      
      The relay reads `--brief <file>` or stdin, saves the exact text as `brief.txt`, and sends it to
      `claude -p` through stdin — never as an argv value. It therefore stays out of the process list and
      needs no shell quoting. Claude Code caps piped stdin at 10 MB; the relay rejects a larger brief before
      dispatch. Put large context in workspace files and reference those paths instead.
      
      ## Worked example
      
      ```xml
      <task>
      In services/billing/, refund retries can create a second refund because the idempotency key is checked
      after submission. Check for an existing refund before creating one. Touch only refund handling and
      its behavior-level tests. Leave charge creation, routes, and data models unchanged.
      </task>
      
      <repo_constraints>
      Follow the repository's Python style and test conventions copied from AGENTS.md. Do not add ticket
      identifiers to source comments. Do not add dependencies.
      </repo_constraints>
      
      <verification_loop>
      Run and make green:
        pytest tests/billing/ -q
        ruff check services/billing/ tests/billing/
      Confirm git status contains only the intended refund implementation and tests.
      </verification_loop>
      
      <action_safety>
      No unrelated refactors. Do not git add, commit, or push; leave the work uncommitted.
      </action_safety>
      
      <structured_output_contract>
      Report the root cause and fix, files touched, pytest and ruff outcomes with counts, and anything left
      open or needing a decision.
      </structured_output_contract>
      ```
      
      Dispatch with [dispatch-and-poll.md](dispatch-and-poll.md), then review and land with
      [review-and-land.md](review-and-land.md).
      
  • scripts
    • relay.mjs 48.5 KB · in bundle
  • SKILL.md 9.3 KB
    ---
    name: claude-delegate
    description: >-
      Delegate a coding task to a separate Claude Code CLI process or another Claude session as an
      implementer, then review its diff and land it yourself. Use only when the user explicitly asks to
      delegate implementation to Claude Code, another Claude session, or the `claude` CLI — for example,
      "have another Claude implement this", "delegate this to Claude Code", or "run this queue through a
      separate Claude session." Do not trigger merely because the current orchestrator is Claude, and do
      not use when the user asks the current Claude to implement directly without delegation.
    license: MIT
    compatibility: Requires the `claude` CLI (Claude Code) installed and authenticated, Node 18+, and git. The orchestrating agent must be able to run shell commands and read files. Claude's shell sandbox requires macOS, Linux, or WSL2; native Windows launch is pending verification. The optional --autocompact flag requires claude 2.1.221 or newer.
    metadata:
      version: 0.5.0
    ---
    
    # Claude Delegate
    
    You are the **orchestrator**. Delegate one bounded coding task to a separate **implementer** — a Claude
    Code CLI session — then review what it produced and land it yourself. You write the brief and own the
    judgment; the separate Claude session edits the working tree; you verify and commit.
    
    This skill is not a signal for the current Claude to implement directly. Use it only after the human
    explicitly asks for delegation to another Claude Code process or session.
    
    ## When not to use this
    
    - The human asked the current agent to implement the task directly.
    - The task is small enough to do inline and the human did not request delegation.
    - The `claude` CLI is missing or unauthenticated (`claude auth status`).
    - The task needs a stronger host boundary than Claude Code's tool permissions and shell-only sandbox
      provide. Use an isolated container or VM for that requirement.
    
    ## Prerequisites
    
    1. `claude --version` succeeds.
    2. `claude auth status` reports an authenticated session. On macOS the live credentials sit in the
       login Keychain; when the orchestrator's own sandbox blocks Keychain access (Codex's sandbox
       does), `claude` falls back to a possibly stale credentials file and reports `loggedIn: false`
       even though the login is valid. Re-run the check — and the dispatch itself — with that sandbox
       escalated or outside it before concluding the CLI is unauthenticated.
    3. The target repository is the directory passed with `--cd`.
    4. On Linux/WSL2, Claude's sandbox dependencies are installed. The normal relay profile is
       configured to fail when the sandbox is unavailable instead of silently running shell commands
       unsandboxed. Existing merged settings can still affect the effective boundary.
    
    ## The loop
    
    ### 1. Write the brief
    
    The separate session has no orchestrator chat history. It receives the brief on stdin and can inspect
    the target working tree.
    
    Claude Code automatically discovers the target project's `CLAUDE.md` and normal local Claude
    configuration because the relay does not use `--bare`. It does **not** generically auto-load
    `AGENTS.md`. Read `AGENTS.md` yourself and copy every load-bearing constraint and the real gate
    commands into the brief. Tell the implementer not to commit. Keep one task per brief.
    
    Template and details: [references/writing-the-brief.md](references/writing-the-brief.md).
    
    ### 2. Dispatch
    
    ```bash
    node "<skill-dir>/scripts/relay.mjs" --brief brief.txt --cd /path/to/repo
    # review/diagnosis only:                 add --read-only
    # continue the latest session:           add --resume-last
    # continue the recorded session:         add --session <id>
    # choose limits:                         add --max-turns 40 --max-budget-usd 10
    # set the auto-compact window:           add --autocompact 400k
    # hard relay deadline:                   add --timeout 2h
    # inspect every option:                  node .../relay.mjs --help
    ```
    
    `<skill-dir>` is this installed skill directory, the folder containing this `SKILL.md`.
    
    The relay runs `claude -p --output-format stream-json --verbose`, sends the brief through stdin, and
    writes artifacts under the system temp directory by default. It never uses `--bg` or `--bare`, and it
    never commits. See [references/dispatch-and-poll.md](references/dispatch-and-poll.md).
    
    `--autocompact <auto|tokens>` passes Claude Code's auto-compact window setting on every new or resumed invocation, and needs Claude Code `2.1.221` or newer — older builds fail the dispatch with `unknown option '--autocompact'`. The installed CLI owns the accepted range (`auto`, or 100k–1M tokens); the relay records the requested value but does not claim that Claude applied or enforced it.
    
    ### 3. Wait
    
    The relay blocks until Claude exits. Use the orchestrator's background-command facility, or run it in
    the foreground and wait. Completion means the process exited and `result.json` exists.
    
    - A pre-run usage error exits 2 and writes no `result.json`.
    - A missing `claude` exits 127 and writes `status: "claude_unavailable"`.
    - Timeout and caught relay signals terminate the whole implementer process tree and preserve an
      outcome artifact.
    
    Read `finalMessage`, `touchedFiles`, `resultSubtype`, and the raw artifact paths from `result.json`.
    
    ### 4. Review
    
    Treat the implementer's report and gate outcomes as claims:
    
    - Review edits to existing tests before a green gate means anything.
    - Re-run the project's actual gates yourself.
    - Read the complete diff against the brief, starting with `touchedFiles`.
    - Inspect untracked and staged content as well as the ordinary diff.
    - Run relevant guard skills if installed.
    
    Full checklist: [references/review-and-land.md](references/review-and-land.md).
    
    ### 5. Land
    
    The **orchestrator commits** only after the gates pass and the diff holds. For rework, resume the same
    Claude session with a delta brief:
    
    ```bash
    echo "Keep the implementation, replace the mocked DB test with the migrated fixture, and remove the
    unused import." | node "<skill-dir>/scripts/relay.mjs" --session <id> --cd /path/to/repo
    ```
    
    Review a resumed run exactly like the first run.
    
    ## Permission profiles
    
    The normal profile is deliberately explicit:
    
    - `acceptEdits` permission mode.
    - Built-in tools restricted to Read, Glob, Grep, Edit, Write, and the platform shell.
    - On macOS, Linux, and WSL2, Claude's shell sandbox is enabled with startup failure on missing
      dependencies and no unsandboxed retry. Commands that stay sandboxed are auto-approved so ordinary
      gates can run headlessly. The sandbox governs shell processes and their children only; merged
      local or managed sandbox settings can add effective paths or exclusions.
    - Configured MCP discovery and Claude.ai connectors are disabled, all MCP tools are denied, and
      skills, commands, and Claude's Agent tool are unavailable to the child. Project `CLAUDE.md`, hooks,
      normal authentication, session persistence, and other local settings still load.
    - String rules deny common direct shell forms of `git commit`, `git push`, and nested `claude`, plus
      any command containing `claude-delegate`. Aliases, scripts, and wrappers can bypass them, so they
      are only a speed bump; the brief's no-commit instruction and orchestrator review remain the boundary.
    
    Native Windows does not support Claude's shell sandbox. The relay restricts the tool surface and
    pre-approves PowerShell so the run remains non-interactive, but that shell is not OS-isolated. Native
    `claude.exe` and npm `claude.cmd` launch paths are implemented; Windows verification is pending.
    
    `--read-only` uses `plan` mode with only Read, Glob, and Grep. It removes edit, write, and shell paths,
    then compares parsed git porcelain and fingerprints the working-tree identity and index entries of
    Git-visible paths that were already dirty.
    `readOnlyViolation` is `true` when either signal proves a change, `false` when coverage is complete and
    detects none, and `null` when coverage is incomplete. This is a reporting tripwire, not an OS boundary:
    ignored paths and perfect restores are outside it, local hooks can write, and concurrent changes cannot
    be attributed to Claude.
    
    `--dangerously-skip-permissions` is an explicit opt-in to Claude's `bypassPermissions` mode. The
    restricted tool surface, direct commit/push deny rules, and supported-platform shell sandbox remain,
    but direct file tools can cross normal permission boundaries. Use it only with the human's explicit
    acceptance.
    
    ## Complementary to native Claude features
    
    Claude subagents, agent teams, and background sessions are useful when the current Claude environment
    is already the orchestrator and native coordination is the goal. This skill is complementary: it
    provides a cross-orchestrator contract — self-contained brief → dispatch → artifacts → review → land
    — and keeps the commit with the orchestrator.
    
    ## References
    
    - [references/writing-the-brief.md](references/writing-the-brief.md) — context, `CLAUDE.md` versus
      `AGENTS.md`, real gates, report contract, and delta briefs.
    - [references/dispatch-and-poll.md](references/dispatch-and-poll.md) — flags, profiles, artifacts,
      `result.json`, polling, and failure recovery.
    - [references/review-and-land.md](references/review-and-land.md) — generated-code review, the commit
      boundary, and session rework.
    - [references/multi-task-queues.md](references/multi-task-queues.md) — sequential queues, progress
      tracking, constraint carry-forward, and final coherence.
    

Comments (0)

Sign in to join the conversation.

No comments yet.

Reviews (0)

No reviews yet.

Related