All skills
Skillintermediate

feat: Add Codex delegation mode to ce:work

Add an optional Codex delegation mode to ce:work that delegates code-writing to the Codex CLI (`codex exec`) using concrete bash templates. When active with a plan file, each implementation unit is sent to Codex with a structured prompt and result schema, then classified, verified, and committed or rolled back. This replaces ce-work-beta's prose-based delegation (PR #364) which caused non-determin

Claude Code Knowledge Pack7/10/2026

Overview

feat: Add Codex delegation mode to ce:work

Overview

Add an optional Codex delegation mode to ce:work that delegates code-writing to the Codex CLI (codex exec) using concrete bash templates. When active with a plan file, each implementation unit is sent to Codex with a structured prompt and result schema, then classified, verified, and committed or rolled back. This replaces ce-work-beta's prose-based delegation (PR #364) which caused non-deterministic CLI invocations.

Implementation note (2026-03-31): The final rollout was redirected to ce:work-beta so stable ce:work remains unchanged during beta. ce:work-beta must be invoked manually; ce:plan and other workflow handoffs remain pointed at stable ce:work until promotion.

Problem Frame

Users running ce:work from Claude Code (or other non-Codex agents) want to delegate token-heavy implementation work to Codex — either for better code quality or token conservation. PR #364's approach failed because the agent improvised CLI syntax each run. ce-work-beta has a structured 7-step External Delegate Mode with useful patterns (environment guards, circuit breaker), but the CLI invocation step itself is prose-based. This plan ports the structural patterns and replaces prose invocations with concrete, tested bash templates. (see origin: docs/brainstorms/2026-03-31-codex-delegation-requirements.md)

Requirements Trace

  • R1. Optional mode within ce:work, not separate skill; ce-work-beta superseded
  • R2. Resolution chain: argument > local.md > hard default (off)
  • R3-R4. delegate:codex / delegate:local canonical tokens with bounded imperative fuzzy matching
  • R5. Plan-only delegation; per-unit eligibility pre-screening (out-of-repo checks, trivial-work exclusions)
  • R6-R7. Environment guard (Codex sandbox detection); skill-level logic, no converter changes
  • R8-R9. Availability check; no version gating
  • R10-R13. One-time consent with sandbox mode selection during interactive ce:work execution
  • R14. Concrete bash invocation template (validated via live CLI testing)
  • R15. User-selected sandbox: --yolo (default) or --full-auto
  • R16. Serial execution for all units; delegation and swarm mode mutually exclusive; delegated execution requires a clean working tree and rolls failed units back to HEAD
  • R17. Prompt template written to .context/compound-engineering/codex-delegation/; XML-tagged sections
  • R18. Circuit breaker: 3 consecutive failures -> standard mode fallback
  • R19. Multi-signal failure classification (CLI fail / result absent / task fail / partial / verify fail / success)
  • R20. --output-schema for structured result JSON; known gpt-5-codex model bug
  • R21. Repo-root restriction via prompt constraint; complete-and-report on out-of-repo discovery
  • R22. Settings in .claude/compound-engineering.local.md: work_delegate, work_delegate_consent, work_delegate_sandbox

Scope Boundaries

  • No app-server integration (bare codex exec only)
  • No ad-hoc delegation (plan file required)
  • No minimum version gating
  • No periodic re-consent
  • No converter changes
  • No timeout for v1
  • No out-of-repo detection (prompt constraint + pre-screening only)
  • No automatic preservation of pre-existing dirty state in delegated mode
  • Delegation and swarm mode (Agent Teams) are mutually exclusive

Context & Research

Relevant Code and Patterns

  • plugins/compound-engineering/skills/ce-work/SKILL.md — target file; Phase 1 Step 4 (execution strategy, lines 126-144) and Phase 2 Step 1 (task loop, line ~159) are the insertion points
  • plugins/compound-engineering/skills/ce-work-beta/SKILL.md — External Delegate Mode (lines 413-474) provides the structural pattern being ported (guards, circuit breaker, prompt file writing)
  • plugins/compound-engineering/skills/ce-review/SKILL.md (lines 19-33) — canonical argument parsing pattern with token table, strip-before-interpret, conflict detection
  • plugins/compound-engineering/skills/ce-plan/SKILL.md (lines 167-176, 352-356, 495) — current Execution target: external-delegate posture signal to remove as part of the supersession work
  • ~/.claude/plugins/marketplaces/cli-printing-press/skills/printing-press/SKILL.md — proven codex delegation via codex exec --yolo - with 3-failure circuit breaker
  • ~/.claude/plugins/marketplaces/openai-codex/plugins/codex/skills/gpt-5-4-prompting/ — Codex prompt best practices: XML-tagged blocks, <completeness_contract>, <verification_loop>, <action_safety>

Institutional Learnings

  • Git workflow skills need explicit state machines (docs/solutions/skill-design/git-workflow-skills-need-explicit-state-machines-2026-03-27.md): Re-read state at each git transition; use git status not git diff HEAD for cleanliness; model non-zero exits as state transitions
  • Pass paths, not content, to sub-agents (docs/solutions/skill-design/pass-paths-not-content-to-subagents-2026-03-26.md): Orchestrator discovers paths; sub-agent reads content; instruction phrasing affects tool call count
  • Beta promotion must update callers atomically (docs/solutions/skill-design/beta-promotion-orchestration-contract.md): When adding new invocation semantics, update all callers in the same PR
  • Compound-refresh mode detection (docs/solutions/skill-design/compound-refresh-skill-improvements.md): Mode must be explicit opt-in via arguments, not auto-detected from environment

Key Technical Decisions

  • Insertion point: Delegation routing gate at Phase 1 Step 4 (execution strategy selection); per-unit delegation branch at Phase 2 Step 1 line ~159 ("Implement following existing conventions"). This keeps delegation as a task-level modifier within the existing execution flow rather than a separate phase.
  • Argument parsing pattern: Follow ce:review's canonical pattern — token table, strip-before-interpret, graceful fallback. Introduce delegate: as a new namespace separate from mode:. Do not add a non-interactive mode to ce:work as part of this feature; the skill remains interactive. The argument-hint frontmatter gets updated.
  • Fuzzy matching boundary: Support fuzzy activation only for imperative execution-intent phrases such as "use codex", "delegate to codex", or "codex mode". A bare mention of "codex" or prompts about Codex itself must not activate delegation.
  • Prompt template format: XML-tagged blocks following the codex gpt-5-4-prompting skill's guidance — <task>, <files>, <patterns>, <approach>, <constraints>, <verify>, <output_contract>. This is more structured than printing-press's flat format and aligns with how Codex/GPT-5.4 models parse instructions.
  • Settings parsing: No utility exists. The skill includes inline instructions for the agent to read .claude/compound-engineering.local.md, extract YAML between --- delimiters, and interpret keys. For writing, read-modify-write with explicit handling: (1) if file doesn't exist, create it with YAML frontmatter wrapper; (2) if file exists with valid frontmatter, merge new keys preserving existing keys; (3) if file exists without frontmatter or with malformed frontmatter, prepend a valid frontmatter block and preserve existing body content below the closing ---. Cross-platform path rewriting handled by converters (.claude/ -> .codex/ -> .opencode/).
  • Circuit breaker resets on success, persists across units: A successful delegation resets the counter to 0. Consecutive failures accumulate across units within a single plan execution. If delegation keeps failing, it's likely environmental (codex auth, model issues), not unit-specific.
  • Delegation takes precedence over swarm: When delegation is active, serial execution is enforced and swarm mode is suppressed. This applies even when slfg or the user explicitly requests swarm mode. Delegation is the higher-priority execution constraint because it requires serial execution. Swarm mode may be re-evaluated in the future but delegation support is more important now.
  • Delegated execution safety model: Do not auto-stash pre-existing user changes. Delegated execution only starts from a clean working tree in the current checkout or current worktree. If the tree is dirty, stop and tell the user to commit, stash explicitly, or continue in standard mode. This makes rollback-to-HEAD safe and avoids hiding user data inside automation-owned stash entries.
  • Partial result policy: Treat status: "partial" as a handoff, not a completed unit. Keep the diff, switch immediately to local completion for that same unit, verify and commit before moving on, and count it toward the circuit breaker. If local completion fails, roll the unit back to HEAD.
  • ce-work-beta disposition: Port Frontend Design Guidance (lines 266-272) to ce:work as a separate Phase 2 addition. Supersede the External Delegate Mode section entirely, and remove the old Execution target: external-delegate execution-note contract from ce:plan / ce-work-beta in the same PR. Keep ce-work-beta otherwise intact for now — deletion is a separate cleanup task.

Open Questions

Resolved During Planning

  • Optimal prompt template structure (R17): XML-tagged blocks per codex gpt-5-4-prompting guidance. Sections: <task>, <files>, <patterns>, <approach>, <constraints> (includes repo-root restriction and mandatory result reporting), <verify>, <output_contract>.
  • Insertion point in ce:work Phase 2 (R14): Phase 1 Step 4 for routing/strategy gate; Phase 2 Step 1 line ~159 for per-unit delegation branch.
  • Circuit breaker reset semantics (R18): Per-plan, resetting to 0 on success. Rationale: repeated failures are likely environmental, not unit-specific.
  • How to parse local.md YAML (R22): Inline skill instructions — agent reads the file, extracts YAML between --- delimiters, interprets the keys. No utility exists; building a general-purpose utility is out of scope.
  • Fallback when --output-schema fails (R20): If result JSON is absent or malformed, classify as task failure per R19. The agent proceeds to the next unit or triggers the circuit breaker.

Deferred to Implementation

  • Exact prompt wording: The XML-tagged template structure is defined; the exact prose within each section will be refined during implementation based on testing with representative plan units.
  • Consent flow UX copy: The consent warning content (R10) — what exactly to say about --yolo, how to present the sandbox choice — is best refined during implementation with real interaction testing.
  • Frontend Design Guidance port quality: Whether the beta's Frontend Design Guidance section ports cleanly or needs adaptation for ce:work's structure.

High-Level Technical Design

This illustrates the intended approach and is directional guidance for review, not implementation specification. The implementing agent should treat it as context, not code to reproduce.

The delegation mode adds three sections to ce:work's SKILL.md:

┌─────────────────────────────────────────────────────────────┐
│ SKILL.md Structure (additions marked with +)                │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│ + ## Argument Parsing                                       │
│   Parse delegate:codex / delegate:local tokens              │
│   Read local.md for work_delegate fallback                  │
│   Resolve delegation state: on/off + sandbox mode           │
│                                                             │
│   ## Phase 0: Input Triage (existing)                       │
│                                                             │
│   ## Phase 1: Quick Start (existing)                        │
│   + Step 4 modification: if delegation on + plan present,   │
│     force serial execution, block swarm mode                │
│                                                             │
│   ## Phase 2: Execute (existing)                            │
│   + Step 1 modification: if delegation on for this unit,    │
│     branch to Codex Delegation section instead of           │
│     "implement following existing conventions"              │
│                                                             │
│ + ## Codex Delegation Mode                                  │
│   + Pre-delegation checks (env guard, availability,         │
│     consent)                                                │
│   + Prompt template builder (XML-tagged)                    │
│   + Result schema definition                                │
│   + Execution loop (exec -> classify ->                     │
│     local-complete/commit/rollback-to-HEAD)                 │
│   + Circuit breaker logic                                   │
│                                                             │
│   ## Phase 3: Quality Check (existing, unchanged)           │
│   ## Phase 4: Ship It (existing, unchanged)                 │
│   ## Swarm Mode (existing, + mutual exclusion note)         │
│                                                             │
│ + ## Frontend Design Guidance (ported from ce-work-beta)    │
│                                                             │
└─────────────────────────────────────────────────────────────┘

Implementation Units

graph TB
    U1[Unit 1: Argument Parsing<br/>+ Settings Reading] --> U2[Unit 2: Pre-Delegation Gates]
    U2 --> U3[Unit 3: Execution Strategy Gate]
    U3 --> U4[Unit 4: Delegation Artifacts]
    U4 --> U5[Unit 5: Core Delegation Loop]
    U5 --> U6[Unit 6: ce-work-beta Sync]

  • Unit 1: Argument Parsing and Settings Reading

Goal: Add delegate:codex / delegate:local token parsing to ce:work and the resolution chain that reads local.md settings.

Requirements: R2, R3, R4, R22

Dependencies: None

Files:

  • Modify: plugins/compound-engineering/skills/ce-work/SKILL.md
  • Test: tests/pipeline-review-contract.test.ts
  • Test: manual invocation testing with delegate:codex, delegate:local, and fuzzy variants

Approach:

  • Add an ## Argument Parsing section immediately before the ## Phase 0: Input Triage heading (after the opening narrative), following ce:review's canonical pattern (token table, strip-before-interpret). Cross-reference the High-Level Technical Design diagram for placement.
  • Token table: delegate:codex (activate), delegate:local (deactivate), plus bounded fuzzy recognition for delegate activation phrases. Do not add mode:headless here; ce:work remains an interactive workflow.
  • After token extraction, read .claude/compound-engineering.local.md for work_delegate, work_delegate_consent, work_delegate_sandbox keys
  • Implement resolution chain: