- name
- cc-delegate
- description
- Delegate local repository tasks from Codex, WorkBuddy, or another orchestrator to Claude Code with an independent read-only Peer Plan, scoped paths, resumable sessions, automatic run history, a three-use optimization loop, receipts, monitoring, and verification. Use for Codex Plan mode unless the user explicitly opts out, or when the user asks to plan with, dispatch, resume, monitor, audit, optimize, or stop Claude Code/CC, including “双计划”, “让 CC 也规划”, “让 CC 干活”, “调 Claude Code”, “继续这个项目”, “检查 CC 记录”, or “CC 卡住了”.
# cc-delegate
Current release: `v1.16.0`.
Use this skill as the standard way to delegate work to the local Claude Code
CLI. Keep the orchestration quiet: infer safe routine details, surface one
minimal decision only when authority or intent is genuinely missing, and
verify the result rather than trusting the worker's summary.
## Apply The User's Defaults
- Treat Codex and Claude Code as general-purpose workers. Do not force a
visual/text or tool-based division unless the user asks for one.
- When the user says “这个仓库 / 当前目录 / 接着干” and the current working
directory is unambiguous and exists, use it without asking for the path.
- Ask one short question when multiple target directories are plausible, the
directory does not exist, a business choice is required, or authority for a
destructive/external action is missing.
- Make routine implementation choices autonomously. Do not ask the user to
choose ordinary libraries, filenames, test commands, or formatting.
- Read applicable `AGENTS.md`, `CLAUDE.md`, and repository instructions before
delegation. Preserve existing user changes.
- Do not commit, push, publish, delete material data, or modify external
systems unless the user explicitly authorizes that action.
- For work likely to exceed two minutes, first give a short overview of the
expected phases, monitoring interval, and conditions that will pause for the
user. Report only meaningful progress changes.
## Run A Peer Plan In Codex Plan Mode
When Codex is in Plan mode, always use this skill to request an independent
Claude Code Plan B. Skip it only when the user explicitly says they do not
want a CC/Claude plan, want only the Codex plan, or do not want dual planning.
Do not infer an opt-out from urgency, task size, or silence.
Keep the plans independent:
1. Codex forms Plan A from the original task and repository evidence before
reading Claude's answer.
2. Send Claude the original task, work folder, and repository instructions,
but never Codex Plan A.
3. Use `run-plan`, which pins `--permission-mode plan`, exposes only
`Read/Glob/Grep`, and disables configured MCP servers. The planner cannot
edit, run tests, commit, push, publish, or operate external systems.
4. If `run-plan` returns `IN_PROGRESS`, call `plan-status` on the same state
file. It preserves stdout after launcher timeout and strictly parses the
outer `--output-format json` response when the original worker exits.
5. Compare consensus, Claude-only catches, Codex-only catches, and conflicts,
then return one merged plan with explicit verification.
Attempt one Peer Plan per materially changed planning request. If Claude is
unavailable or fails, label the comparison `CC_PLAN_UNAVAILABLE` and state the
gap; never imply that two-model review happened.
The parser may recover one unambiguous plan wrapped in prose and marks it
`NON_JSON_WRAPPER`. It also converts only a singleton string intended for a
string-array field into a one-item array and marks
`NORMALIZED_SINGLETON_ARRAYS`. Missing/extra fields, object mismatches,
ambiguous output, and untraceable plans become `CC_PLAN_UNAVAILABLE`. Read
[peer-plan.md](references/peer-plan.md) for the exact command flow, comparison
rubric, timeout handling, and opt-out semantics. Peer planning is separate
from implementation delegation below.
## Resolve The Skill Root
Set `SKILL_ROOT` to the directory containing the `SKILL.md` that triggered this
run. Invoke bundled scripts from `SKILL_ROOT/scripts`.
Never hard-code `.workbuddy`, `.codex`, `.claude`, or `.agents` as the runtime
location. Installations may be junctions or separate copies.
On Windows/PowerShell, use absolute paths:
```powershell
$delegate = Join-Path $skillRoot "scripts\cc_delegate.py"
$monitor = Join-Path $skillRoot "scripts\cc_monitor.py"
$registry = Join-Path $skillRoot "scripts\session_registry.py"
$history = Join-Path $skillRoot "scripts\run_history.py"
$optimizer = Join-Path $skillRoot "scripts\optimization_tracker.py"
$sync = Join-Path $skillRoot "scripts\sync_installations.py"
```
## Preserve Every Run
Every CLI invocation through `cc_delegate.py`, `cc_monitor.py`,
`poll_tick.py`, or `session_registry.py` automatically writes one structured
record under `~/.cc-delegate/run-history/YYYY/MM/DD/`. A record is written as
`RUNNING` before the command executes and atomically finalized afterward.
Hard-killed or crashed invocations therefore remain visible as stale
`RUNNING`, rather than disappearing.
Set `CC_DELEGATE_CALLER=codex` or `workbuddy` in the invoking shell when the
caller is known. Normal runs fail closed when history is disabled or the
initial `RUNNING` record cannot be written. Isolated tests may disable history
only by setting both `CC_DELEGATE_HISTORY_DIR=off` and
`CC_DELEGATE_HISTORY_TESTING=1`. Records include command metadata,
paths, marker/correlation, duration, status, Peer Plan cost, and receipt
summary. They never store raw prompts, transcript contents, `--json`, or
session descriptions.
At the end of a Peer Plan or delegated task, query the current marker or state
path and confirm at least one correlated record exists. If not, report
`RUN_HISTORY_MISSING`; never claim the run was recorded without checking.
```powershell
python -X utf8 $history list --limit 20 --json
python -X utf8 $history stats --days 30
```
Read [run-history.md](references/run-history.md) for status semantics,
correlation queries, privacy boundaries, and the evidence-based optimization
loop.
## Review And Improve Every Use
Every completed Peer Plan or implementation delegation must produce exactly
one optimization review for its new correlated run IDs. Use `--no-point` when
the orchestrator found no manual Skill-level issue; deterministic failures,
stale runs, Peer Plan warnings, and bad verification still become automatic
points.
```powershell
python -X utf8 $optimizer review `
--correlation "<exact-marker-or-absolute-state-path>" `
--no-point
```
For a concrete reusable issue, replace `--no-point` with a stable
`--point-code`, category, one-line observation, and one-line suggestion.
Reuse an existing fingerprint for the same problem. Never put raw prompts,
transcripts, credentials, or secrets in a review.
Only the same unresolved fingerprint appearing in three separate reviews
becomes `AUTO_OPTIMIZE_READY`; three unrelated ideas do not. The current
orchestrator must claim a ready item before editing. It then reads the three
reviews, edits only the configured cc-delegate Git truth source, runs the full
verification suite, safely syncs configured installations, and resolves the
claim. Do not delegate cc-delegate to optimize itself.
Automatic optimization must not modify delegated user projects, weaken
security/privacy boundaries, perform destructive or external actions, or
commit/push. Record `NEEDS_USER_INPUT` when any such decision is required.
After the user explicitly decides, a new window may use
`claim --user-approved`; never use that flag without the user's decision.
Read [optimization-loop.md](references/optimization-loop.md) for configuration,
claim/resolve commands, safe synchronization, reset semantics, and recovery.
## Choose One Delegation Mode
Prefer the local `claude` CLI because it works from both Codex and WorkBuddy
and supports native resume.
| Situation | Mode |
|---|---|
| Tiny read-only diagnostic known to finish within 60 seconds | `claude -p` |
| Any file edit, code task, or uncertain duration | `claude --background <prompt>`, then monitor |
| Multi-step or cross-session task | CLI plus `--resume <sid>` and registry |
| CLI unavailable, or user explicitly requests WorkBuddy MCP | WorkBuddy MCP fallback |
Read [workbuddy-mcp.md](references/workbuddy-mcp.md) only when using or
repairing the WorkBuddy MCP route.
Do not start a second worker merely because the foreground shell or MCP call
timed out. Inspect the receipt and transcript first.
## Prepare The Task
1. Resolve `workFolder`.
2. Keep one stable task ID, but generate a new marker for every dispatch, for
example `TID=cc_<task-slug>_step2_<timestamp>_<random>`.
3. Choose and explicitly pin `HANDOFF_DIR`.
Use `~/.cc-delegate/tasks/<task-id>` by default. This keeps runtime receipts
out of Git worktrees and prevents stale root-level files or same-directory
task collisions. If project instructions or the user specify another
location, use that location instead.
Run preflight once. It may create a missing handoff directory only inside the
validated work folder or the controlled `~/.cc-delegate/tasks` state root:
```powershell
python -X utf8 $delegate preflight `
--workfolder $workFolder `
--handoff-dir $handoffDir `
--create-handoff
```
Stop before delegation if preflight reports `ok: false`. Never silently fall
back to a home directory.
## Assemble And Launch
Create the prompt as a UTF-8 file so PowerShell passes it as one string:
```powershell
$promptFile = python -X utf8 $delegate assemble `
--base $taskPrompt `
--workfolder $workFolder `
--handoff-dir $handoffDir `
--marker $marker `
--output-file (Join-Path $env:TEMP "$taskId-prompt.txt") `
--begin-step
$prompt = Get-Content -Raw -LiteralPath $promptFile
```
`--begin-step` archives the previous `result.json` and `HANDOFF.md` under the
handoff directory, then writes fresh `IN_PROGRESS` state before launch. This
prevents a resumed step from consuming the previous step's `DONE`.
Use foreground only for a tiny read-only diagnostic with a known sub-minute
runtime:
```powershell
claude --dangerously-skip-permissions -p $prompt
```
For implementation and file-editing tasks, return control immediately and
monitor in the background:
```powershell
$launch = claude --background --dangerously-skip-permissions $prompt 2>&1
```
Claude Code 2.1.204 rejects `--background` together with `-p/--print`.
Pass the prompt as the positional argument in background mode.
Keep the short background ID printed as `backgrounded · <id>`. In a
non-interactive shell, inspect background state with `claude agents --json`.
After verified completion, run `claude stop <id>` so idle background services
do not accumulate.
Use bypass permissions only after validating a trusted work folder and only
for actions already authorized by the user. It does not authorize publishing,
credential changes, destructive cleanup, or edits outside the declared scope.
For a multi-step task, resume from the previous SID, then locate the current
SID from the new step marker:
```powershell
$previousSid = $sid
claude --background --dangerously-skip-permissions `
--resume $previousSid $nextPrompt
$sid = python -X utf8 $monitor `
--workfolder $workFolder --handoff-dir $handoffDir `
--marker $marker --print-sid
```
Keep the same task ID, work folder, and handoff directory. Use a new marker for
each dispatch. Claude Code background resume may create a new SID; the marker
lookup after launch is the source of truth. Update the registry with `set-sid`
and the current marker rather than assuming the previous SID remains active.
## Require A Verifiable Receipt
Every delegated step writes both files into the declared handoff directory:
- `result.json` for machine decisions.
- `HANDOFF.md` for human-readable context and cross-session recovery.
The `result.json` contract is:
```json
{
"status": "DONE|IN_PROGRESS|BLOCKED|NEEDS_USER_INPUT|ERROR",
"summary": "concrete result",
"artifacts": ["relative/or/absolute/path"],
"issues": [],
"next_suggestions": [],
"verification": {
"command": "exact command actually run",
"pass": true
}
}
```
All six top-level fields are required. `artifacts`, `issues`, and
`next_suggestions` are arrays of strings only; do not put objects such as
`{"path": "...", "change": "..."}` in them. The parser rejects malformed
receipts instead of guessing.
Write `DONE` only after the task and its verification finish. If no meaningful
verification exists, set `verification.pass` to `false`, explain why in
`issues`, and do not claim verified completion.
Write the final `HANDOFF.md` first and write `result.json` with `status=DONE`
last. Completion still requires both files to report exact `DONE`; either file
on its own is a transient split receipt and must return `POLL`, never
`CONSUME`.
`HANDOFF.md` must contain one exact line:
```text
STATUS: DONE
```
Use `STATUS: IN_PROGRESS` when another worker step is still required. Do not
accept `NOT_DONE`, prose containing “done”, or historical receipt files as
completion.
## Monitor Without Blocking The User
Use one-shot checks rather than a long sleep loop:
```powershell
python -X utf8 $monitor `
--workfolder $workFolder `
--handoff-dir $handoffDir `
--marker $marker `
--show
```
Use these default check intervals:
| Current phase | Interval |
|---|---|
| Reading, planning, one-file edits | 30 seconds |
| Multi-file coding | 60 seconds |
| Rendering or long commands | 90-120 seconds |
For long generation or rendering, raise `--stale` to `300`. A stale transcript
is a signal to inspect, not permission to kill. Read
[monitor-reference.md](references/monitor-reference.md) before using `--kill`.
For `--background` launches, stop by the returned background ID; marker-based
OS process kill is intended for foreground/MCP workers and may not identify a
background service.
When a foreground invocation times out:
1. Do not re-dispatch.
2. Treat shell exit `124` as a launcher timeout, not proof that Claude stopped.
3. Check `result.json` and `HANDOFF.md`.
4. Run monitor with the marker or SID.
5. Re-dispatch only after proving the original worker stopped before producing
the expected artifacts.
## Decide And Verify
Locate the exact transcript with the marker or SID. Marker misses fail closed;
never substitute the newest unrelated session.
Parse and decide:
```powershell
python -X utf8 $delegate parse `
--workfolder $workFolder --handoff-dir $handoffDir `
--transcript $transcript
python -X utf8 $delegate decide `
--workfolder $workFolder --handoff-dir $handoffDir `
--transcript $transcript
```
Interpret actions as follows:
- `CONSUME`: independently inspect artifacts and rerun the important
verification before reporting completion.
- `CONTINUE`: assemble/begin the next bounded step, resume from the current
SID, then discover the new current SID from that step's marker.
- `POLL`: inspect the existing worker; never spawn a duplicate.
- `RETRY`: retry one clarified bounded step only.
- `ESCALATE`: ask the user one minimal decision with the evidence.
A reported verification command must match a real transcript command.
Harmless output-capture redirection such as trailing `2>&1` is ignored, but
meaningful argument differences remain a mismatch.
Read [audit-parsing.md](references/audit-parsing.md) when a detailed tool,
Skill, command, or file audit is needed.
## Manage Resumable Sessions
Use the registry only for multi-step, cross-session, or explicitly named
projects. One-shot tasks do not need registry entries.
```powershell
python -X utf8 $registry registry-path
python -X utf8 $registry register `
--project $project --sid $sid --workfolder $workFolder `
--desc $taskSummary --marker $marker
```
Before resuming, acquire a lease with a unique window owner. Resume only after
`CLAIMED`; release it after the step. Close the project when finished.
After a background resume, run `set-sid --sid <new> --marker <current>` with
the newly discovered SID and step marker.
The registry defaults to `~/.cc-delegate/sessions.json`, honors
`CC_DELEGATE_REGISTRY`, and reads the legacy WorkBuddy registry when that is
the only existing state file.
## Escalate Only Real Decisions
Pause for the user when:
- the target directory is ambiguous or missing;
- the worker requests a business/content choice;
- credentials, payment, publishing, external messages, or production changes
require authorization;
- a destructive action is proposed;
- the receipt is damaged or verification cannot be trusted;
- the same bounded retry remains blocked.
Do not pause for routine code choices, harmless file naming, test selection,
or normal progress.
## Finish
Before reporting completion:
1. Confirm artifacts are inside the authorized scope.
2. Confirm exact `DONE` belongs to this run.
3. Confirm transcript verification is `MATCH`.
4. Independently rerun the important check.
5. Close/release a registered session.
6. Stop a completed background service by its exact background ID.
7. Confirm the current run appears in automatic history.
8. Write the correlated optimization review exactly once.
9. If it returns `AUTO_OPTIMIZE_READY`, claim and complete the bounded
optimization protocol before closing this task.
10. Report the concrete result, artifact paths, verification, review ID, and any remaining
risk in concise Chinese.
Do not commit or push unless the user explicitly asks.
View on GitHub