
Coding Agent
- 22 installs
- 10 repo stars
- Updated May 27, 2026
- kesslerio/coding-agent-openclaw-skill
Helps with ai & agent building tasks.
About
coding-agent is a Claude Code skill for ai & agent building. It helps solo builders move faster with AI-assisted development.
- coding-agent
- AI & Agent Building
- AI-coding skill
Coding Agent by the numbers
- 22 all-time installs (skills.sh)
- Ranked #10,137 of 16,546 AI & Agent Building skills by installs in the Skillselion catalog
- Data as of Jul 25, 2026 (Skillselion catalog sync)
npx skills add https://github.com/kesslerio/coding-agent-openclaw-skill --skill coding-agentAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 22 |
|---|---|
| repo stars | ★ 10 |
| Last updated | May 27, 2026 |
| Repository | kesslerio/coding-agent-openclaw-skill ↗ |
What it does
Helps with ai & agent building tasks.
Files
Coding Agent Skill 💻
When to Use
Trigger this skill when the user wants:
- Code review, PR review, or standards review
- Implementation or refactoring
- GitHub workflows, commits, and PRs
Execution Modes
Plan Mode (new)
Use plan-first workflow before risky implementation:
# Generate read-only plan artifact
scripts/code-plan --engine codex --repo /path/to/repo "Add feature X"
# Execute approved plan
scripts/code-implement --plan /path/to/repo/.ai/plans/<plan>.mdPlan artifacts are written to .ai/plans/*.md with machine-checkable status metadata. code-implement --plan enforces approval status (or requires explicit --force bypass).
Primary: Direct CLI (Session Resume + Permission Bypass)
Agent CLIs now support non-interactive execution with full autonomy and session persistence:
Reasoning default policy for Codex implementation:
- Use
-c model_reasoning_effort="high"for feature implementation and architectural refactors. - Use
medium/lowfor simple fixes, docs-only updates, or when the user explicitly asks for fast/cheap execution.
# Codex — full autonomy, no TTY needed
codex --yolo exec -c model_reasoning_effort="high" "Implement feature X. No questions."
codex exec resume --last # restore context from last session
# Claude Code — full autonomy, no TTY needed
claude -p --dangerously-skip-permissions "Implement feature X"
claude -p --resume <id> # restore specific session
claude -p -c "Follow up" # continue most recent sessionSecondary: tmux Wrappers (Optional)
For long-running implementation tasks where TTY logging and session durability are needed:
# Implementation (3 min timeout, tmux)
"${CODING_AGENT_DIR:-./}/scripts/code-implement" "Implement feature X in /path/to/repo"Multi-Phase Workflow (Session Resume)
Full issue → implement → PR → review → fix cycle using session resume:
1. Implement: codex --yolo exec -c model_reasoning_effort="high" "Implement feature from issue #N" 2. Create PR: gh pr create --title "feat: ..." --body "..." 3. Review: timeout 600s codex review --base <base> --title "Review PR #N" 4. Fix issues: codex exec resume --last (context preserved) 5. Re-review: timeout 600s codex review --base <base> --title "Re-review PR #N" 6. Merge: gh pr merge
`<base>` = repo's default branch (main, master, or trunk). Detect with:
git symbolic-ref refs/remotes/origin/HEAD 2>/dev/null | sed 's@^refs/remotes/origin/@@'Fallback if origin/HEAD is unset:git remote show origin | sed -n '/HEAD branch/s/.*: //p'Non-Negotiable Rules (Summary)
1. Use agent CLIs — Never write code directly. Use Codex CLI or Claude Code CLI (direct or via tmux wrappers). Do not switch to MCP orchestration unless explicitly required. 2. Feature branch — Always use a feature branch for changes. 3. PR before done — Always create a PR before completion. 4. GitHub hygiene — Precise titles, structured bodies, explicit test commands, AI disclosure. 5. No `--max-turns` — Let agent runs complete naturally. 6. Adequate timeouts — Minimum 600s for reviews. 7. Self-audit before completion — Run implementation and review audit checklists before marking done.
Self-Audit Policy (Option A)
Self-audit is required when any of these are true:
- Code or config changed.
- Tests changed or should have changed.
- Review is requested (PR review, standards review, architecture/code quality review).
- Docs changed with executable commands/examples.
Self-audit may be skipped only for:
- Pure informational answers with zero repo changes.
- User explicitly asks for raw output only.
If skipped, state why it was skipped.
Fallback Chain
Implementation: Codex CLI (direct) → Codex CLI (tmux) → Claude CLI → BLOCKED
Reviews: Codex CLI (direct) → Claude CLI → BLOCKED
⛔ NEVER skip to direct edits — request user override insteadImplementation mode is configurable:
CODING_AGENT_IMPL_MODE=direct|tmux|auto(default:direct)autoselects tmux first only when running in an interactive TTY with tmux available
Tooling + Workflow References
Read these before doing any work:
references/WORKFLOW.mdfor branch, PR, review order, multi-phase workflowsreferences/STANDARDS.mdfor coding standards and limitsreferences/quick-reference.mdfor commands and guardrailsreferences/tooling.mdfor CLI usage, session management, and timeoutsreferences/codex-cli.mdfor canonical Codex CLI workflows (exec,review,resume, MCP distinctions)references/claude-code.mdfor Claude Code CLI reference and session resumereferences/reviews.mdfor review formats and GH review postingreferences/examples.mdfor violation examples and recoveryreferences/templates/plan-system-prompt.txtfor deterministic plan mode output contractreferences/templates/plan-template.mdfor plan artifact structurereferences/frontend-design.mdfor frontend-design-ultimate source refs
Humanizer Usage (User-Facing Copy)
For user-facing long-form text (status updates, outreach copy, explanatory prose), default to a humanization pass:
- Preferred command:
/humanizer - Keep exact technical artifacts unchanged (commands, code, IDs, links, payloads, legal text).
- If unavailable, fall back to original text and proceed.
Persona
You are Dev: pragmatic, experienced, and direct. Explain tradeoffs and risks. Prefer simple, working solutions.
name: Bug report
description: Report a defect or unexpected behavior in this skill repository.
title: "bug: <symptom> when <condition>"
labels:
- bug
- needs triage
body:
- type: markdown
attributes:
value: |
Thanks for filing this report. Keep it concise, reproducible, and evidence-based.
- type: textarea
id: summary
attributes:
label: Summary
description: One-sentence statement of what is broken.
placeholder: Wrapper rejects valid CLI flags on macOS.
validations:
required: true
- type: textarea
id: repro
attributes:
label: Steps to reproduce
description: Provide the shortest deterministic repro path.
placeholder: |
1. cd /path/to/repo
2. export FOO=bar
3. ./scripts/...
validations:
required: true
- type: textarea
id: expected
attributes:
label: Expected behavior
description: What should happen if the bug does not exist.
validations:
required: true
- type: textarea
id: actual
attributes:
label: Actual behavior
description: What happened instead, including user-visible errors.
validations:
required: true
- type: input
id: version
attributes:
label: Skill version/ref
description: Exact branch/commit/tag tested.
placeholder: main@<sha>
validations:
required: true
- type: input
id: os
attributes:
label: Operating system
description: OS and shell where this occurs.
placeholder: macOS 15.x + zsh / Ubuntu 24.04 + bash
validations:
required: true
- type: input
id: tooling
attributes:
label: Related tool versions
description: Include versions for codex/gh/claude if relevant.
placeholder: codex --version, gh --version, claude --version
- type: textarea
id: logs
attributes:
label: Logs, screenshots, and evidence
description: Include redacted logs/screenshots/recordings that prove the behavior.
render: shell
- type: textarea
id: impact
attributes:
label: Impact and severity
description: |
Explain who is affected, severity, frequency, and practical consequence.
Include:
- Affected users/workflows
- Severity (annoying, blocks workflow, data risk, etc.)
- Frequency (always/intermittent/edge case)
- Consequence (failed reviews, incorrect fallback, extra manual work, etc.)
- type: textarea
id: additional_information
attributes:
label: Additional information
description: Any context that helps triage but does not fit above.
- type: checkboxes
id: confirmations
attributes:
label: Confirmations
options:
- label: I reproduced this on the latest `main`.
required: true
- label: I searched existing issues and did not find a duplicate.
required: true
blank_issues_enabled: false
contact_links:
- name: Security disclosure
url: https://github.com/kesslerio/coding-agent-openclaw-skill/security/advisories/new
about: Report security vulnerabilities privately.
name: "📗 Documentation issue"
description: Tell us if documentation is missing, incorrect, or confusing.
labels:
- docs
- needs triage
body:
- type: markdown
attributes:
value: |
Thank you for submitting a documentation issue.
- type: dropdown
id: issue_type
attributes:
label: What is the type of issue?
multiple: true
options:
- Documentation is missing
- Documentation is incorrect
- Documentation is confusing
- Example command is not working
- Something else
validations:
required: true
- type: textarea
id: details
attributes:
label: What is the issue?
description: Explain what should be changed.
validations:
required: true
- type: textarea
id: locations
attributes:
label: Where did you find it?
description: Provide file paths and/or URLs.
placeholder: README.md, references/quick-reference.md
validations:
required: true
name: Feature request
description: Propose a capability or workflow improvement.
title: "feat: <capability> (for <surface>)"
labels:
- enhancement
- needs triage
body:
- type: markdown
attributes:
value: |
Help us evaluate this request with concrete use cases and tradeoffs.
- type: textarea
id: summary
attributes:
label: Summary
description: One-line statement of the requested capability.
placeholder: Add automatic base-branch detection helper for review commands.
validations:
required: true
- type: textarea
id: problem
attributes:
label: Problem to solve
description: What user pain this solves and why current behavior is insufficient.
validations:
required: true
- type: textarea
id: proposed_solution
attributes:
label: Proposed solution
description: Desired behavior/API/docs changes with as much specificity as possible.
validations:
required: true
- type: textarea
id: alternatives
attributes:
label: Alternatives considered
description: Other approaches considered and why they are weaker.
- type: textarea
id: impact
attributes:
label: Impact
description: |
Explain who is affected, severity/urgency, frequency, and practical consequence.
Include:
- Affected users/workflows
- Severity (annoying, blocks workflow, etc.)
- Frequency (always/intermittent/edge case)
- Consequence (delays, errors, extra manual work, etc.)
validations:
required: true
- type: textarea
id: acceptance
attributes:
label: Acceptance criteria
description: Checklist that can be verified by tests/commands.
placeholder: |
- [ ] ...
- [ ] ...
validations:
required: true
- type: textarea
id: evidence
attributes:
label: Evidence/examples
description: Prior art, links, snippets, or metrics.
- type: textarea
id: additional_information
attributes:
label: Additional information
description: Extra context, constraints, or references not covered above.
name: "🧹 Task / chore"
description: Track maintenance/refactor/process work.
title: "TODO: <cleanup> after <dependency>"
labels:
- chore
- needs triage
body:
- type: markdown
attributes:
value: |
Use this for concrete, non-feature work with clear verification steps.
- type: textarea
id: objective
attributes:
label: Objective
description: What needs to be done and why now?
validations:
required: true
- type: textarea
id: scope
attributes:
label: Scope
description: Explicit in-scope and out-of-scope items.
placeholder: |
In scope:
- ...
Out of scope:
- ...
validations:
required: true
- type: textarea
id: plan
attributes:
label: Execution plan
description: Ordered implementation steps.
placeholder: |
1. ...
2. ...
3. ...
validations:
required: true
- type: textarea
id: verification
attributes:
label: Verification commands
description: Exact commands and expected outcomes.
render: shell
validations:
required: true
- type: textarea
id: risks
attributes:
label: Risks and rollback
description: Main risks + how to revert safely.
validations:
required: true
- type: checkboxes
id: done_definition
attributes:
label: Definition of done
options:
- label: Scope, plan, and verification are specific and testable.
required: true
- label: Risk and rollback plan is documented.
required: true
Summary
Describe the problem and fix in 2-5 bullets:
- Problem:
- Why it matters:
- What changed:
- What did not change (scope boundary):
Change Type (select all)
- [ ] Bug fix
- [ ] Feature
- [ ] Refactor
- [ ] Docs
- [ ] Security hardening
- [ ] Chore/infra
Scope (select all touched areas)
- [ ] Scripts/wrappers
- [ ] Skill docs/references
- [ ] Issue/PR templates or community files
- [ ] CI/workflows
- [ ] Other
Linked Issue/PR
- Closes #
- Related #
User-visible / Behavior Changes
List user-visible changes (including defaults/config). If none, write None.
Security Impact (required)
- New permissions/capabilities? (
Yes/No) - Secrets/tokens handling changed? (
Yes/No) - New/changed network calls? (
Yes/No) - Tool execution surface changed? (
Yes/No) - If any
Yes, explain risk + mitigation:
Repro + Verification
Environment
- OS:
- Shell/runtime:
- Relevant tool versions:
Steps
1. 2. 3.
Expected
-
Actual
-
Evidence
Attach at least one:
- [ ] Failing output before + passing output after
- [ ] Log snippets
- [ ] Screenshot/recording
- [ ] N/A (docs-only or template-only change)
Human Verification (required)
What you personally verified (not just CI), and how:
- Verified scenarios:
- Edge cases checked:
- What you did not verify:
Compatibility / Migration
- Backward compatible? (
Yes/No) - Config/env changes? (
Yes/No) - Migration needed? (
Yes/No) - If yes, exact upgrade steps:
Failure Recovery
- How to disable/revert this change quickly:
- Files/config to restore:
- Known bad symptoms reviewers should watch for:
Risks and Mitigations
- Risk:
- Mitigation:
AI Assistance
- AI-assisted: yes/no
- Tools/agents/models used:
- Testing level: untested/lightly tested/fully tested
- Human understanding confirmation: yes/no
name: Wrapper Smoke Tests
on:
pull_request:
push:
branches:
- main
- master
jobs:
wrappers:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Install shellcheck
run: sudo apt-get update && sudo apt-get install -y shellcheck
- name: Bash syntax check
run: |
set -euo pipefail
while IFS= read -r script; do
[[ -f "$script" ]] || continue
bash -n "$script"
done < <(git ls-files scripts)
- name: Shellcheck
run: |
set -euo pipefail
while IFS= read -r script; do
[[ -f "$script" ]] || continue
shellcheck "$script"
done < <(git ls-files scripts)
- name: Codex doc drift checks
run: ./scripts/doc-drift-check
- name: Wrapper smoke tests
run: ./scripts/smoke-wrappers.sh
Current date: 2026-02-19
Purpose
High-signal instructions for coding agents in this repository. Keep this file concise; move long examples and deep procedures to README.md and references/.
Scope
- Applies to the repository root and descendants.
- Add nested
AGENTS.mdfiles only when a subdirectory needs different rules. CLAUDE.mdshould remain a symlink to this file.
Language
- English only for code, comments, docs, examples, commits, configs, errors, and tests.
Tooling
- Prefer
rgovergrep. - Prefer
fd/treewhen available; fall back tofind/ls -Rwhen missing. - Resolve Claude CLI in this order:
~/.claude/local/claude(if present), otherwiseclaudefromPATH. - Prefer non-interactive command execution.
Runtime Reality Check
- Before running major workflows, verify toolchain:
command -v codex && codex --versioncommand -v timeoutcommand -v ghcommand -v claude || test -x ~/.claude/local/claude- If a required binary is missing, stop and report exact install/unblock steps.
Codex Command Canon
- Prefer Codex for implementation and review:
- Implementation:
codex exec "..."(orcodex --yolo exec "..."only in trusted/sandboxed environments) - Resume:
codex exec resume --last - Review:
codex review --base <branch> "custom focus prompt" - Use
--full-autofor sandboxed low-friction automation. - Use
--yoloonly when bypassing sandbox/approvals is explicitly intended.
Workflow
1. Gather context with read-only operations first. 2. For non-trivial work, propose a concise plan with assumptions, risks, and one alternative. 3. Get explicit APPROVE before file writes, package installs, or system changes. 4. After approval, execute end-to-end and report progress, results, and deviations.
Long-Running Commands
- Ensure
tsxscripts close watchers/timers and callprocess.exit(0). - Wrap long tasks with process-group timeout, e.g.:
timeout -k5s 60s bash -lc 'exec npx --yes tsx scripts/tool-schema-lint.ts'- Avoid
timeout --foreground. - After timeout, verify child processes are stopped; if not, run
pkill -P <wrapper_pid>.
Code Standards
- Prefer KISS and YAGNI; avoid speculative abstractions.
- Apply DRY with a three-strikes rule before abstraction.
- Keep modules and classes focused (SRP).
- TypeScript: avoid
any; prefer precise types orRecord<string, unknown>. - Use explicit error handling; never fail silently.
- Import order: node -> external -> internal.
- Use descriptive names and named constants instead of magic numbers.
Review Expectations (Plan/Review Mode)
- Review in this order: Architecture, Code Quality, Tests, Performance.
- For each issue:
- include file/line references,
- present 2-3 options (include do-nothing when reasonable),
- state effort, risk, impact, and maintenance burden per option,
- recommend one option and ask for user decision before implementation.
- Interactive flow:
- Big change: section-by-section with up to 4 top issues per section.
- Small change: one focused question per section.
Testing and Validation
- Reproduce first when debugging.
- Before finalizing, run relevant checks:
- formatting/lint
- typecheck
- unit/integration/e2e tests as applicable
- Report exact commands run and outcomes.
- Explicitly call out checks not run and residual risk.
Documentation Hygiene
- Update
README.mdorreferences/when public behavior/workflow changes. - Final report must summarize files changed, key diffs, and side effects.
- Prefer inclusive language: allowlist/blocklist, primary/replica, main branch.
Humanized Communication Policy
- For user-facing long-form writing (outreach copy, status updates, explanations, docs prose), run a humanization pass by default.
- Preferred invocation in OpenClaw contexts:
/humanizer. - Keep exact technical artifacts untouched: code blocks, CLI commands, JSON/YAML payloads, IDs/UUIDs, URLs, stack traces, legal/compliance text, and direct quotations.
- If humanizer is unavailable, continue safely with original text and note the fallback.
OpenClaw Skill Notes
- Keep
SKILL.mdAgentSkills-compatible: clearname+description, concise body, references for deep detail. - For OpenClaw compatibility, keep frontmatter keys single-line and keep
metadataas a single-line JSON object.
CLI Drift Check
- Periodically verify docs/scripts against real CLI help:
codex --helpcodex review --helpclaude --help- Update references when flags/behavior drift.
AGENTS.md
Contributing
How to contribute
- Bugs and focused fixes: open a PR.
- New features or architecture changes: open an issue/discussion first.
- Questions: open an issue or discussion.
Before you open a PR
- Search existing issues and PRs first.
- Keep PRs focused; do not mix unrelated concerns.
- Use the issue forms in
.github/ISSUE_TEMPLATE/for new reports and requests.
Branches and commits
- Branch names should be short and descriptive (example:
codex/<topic>). - Prefer commit format
type(scope): subject.
Validation expectations
Include exact commands and outcomes in every PR.
For script changes, run:
while IFS= read -r script; do [[ -f "$script" ]] || continue; bash -n "$script"; done < <(git ls-files scripts)
while IFS= read -r script; do [[ -f "$script" ]] || continue; shellcheck "$script"; done < <(git ls-files scripts)
./scripts/doc-drift-check
./scripts/smoke-wrappers.shWhen wrapper behavior is involved, also run:
./scripts/doctorAI-assisted contributions
AI-assisted PRs are welcome. Be explicit:
- Mark AI assistance in the PR.
- State testing level (untested/lightly tested/fully tested).
- Include prompt/session notes when feasible.
- Confirm you understand the final code and behavior.
PR requirements
Complete all sections in .github/pull_request_template.md, especially:
- Security impact
- Repro + verification
- Human verification
- Compatibility/migration
- Failure recovery
coding-agent OpenClaw Skill 💻
OpenClaw skill for coding assistant using agent CLIs (Codex, Claude Code). Primary mode: direct CLI with session resume and permission bypass. Secondary mode: tmux wrappers for durable TTY sessions.
Features
- Session Resume Workflows — Multi-phase issue → implement → PR → review → fix cycles with full context preservation
- Agent CLI Integration — Direct CLI execution with permission bypass (
--yolo,--dangerously-skip-permissions) - PR Review Workflow — Direct CLI reviews with proper timeouts
- Plan Mode Workflow — Read-only plan generation with machine-checkable approval gate before implementation
- Self-Auditing Workflow — Mandatory implementation + review checklists with VERIFIED/UNVERIFIED command labeling
- Dev Persona — Pragmatic code reviews with clear feedback
- Git Workflow Documentation — Branch, commit, PR conventions
- Code Quality Standards — KISS, YAGNI, DRY, SRP principles
Requirements
- GitHub CLI (
gh) - One of: Codex CLI (
codex) or Claude Code CLI (claude) - GNU
timeoutcommand (coreutils on macOS) - Optional: tmux (for durable TTY sessions and wrapper scripts)
Installation
# Clone to OpenClaw skills directory
cd /home/art/clawd/skills
git clone https://github.com/kesslerio/coding-agent-openclaw-skill.git coding-agentPreflight and Validation
# Verify local tooling before running wrappers
./scripts/doctor
# Run wrapper behavior smoke tests
./scripts/smoke-wrappers.shUsage
In OpenClaw, activate with:
/codingPlan-first shortcut:
/plan <task>Direct CLI (Primary)
# Implementation (Codex)
codex --yolo exec "Implement feature X. No questions."
# Implementation (Claude Code)
claude -p --dangerously-skip-permissions "Implement feature X"
# Resume last session (context preserved)
codex exec resume --last
claude -p -c "Fix the review findings"Reviews (Direct CLI)
gh pr checkout <PR>
timeout 600s codex review --base <base> --title "Review PR #N"Wrapper Scripts (Plan + Implementation)
# Plan mode (read-only planning artifact)
./scripts/code-plan --engine codex --repo /path/to/repo "Implement feature X"
# Execute plan (prompts for approval if status is still PENDING)
./scripts/code-implement --plan /path/to/repo/.ai/plans/<plan>.md
# Direct implementation (3 min timeout, tmux)
./scripts/code-implement "Implement feature X"Implementation mode policy can be configured:
export CODING_AGENT_IMPL_MODE=direct # direct|tmux|autoFiles
SKILL.md— Full skill documentation (includes Dev persona)references/WORKFLOW.md— Coding workflow, Git integration, multi-phase workflowsreferences/STANDARDS.md— Coding standards & rulesreferences/quick-reference.md— Command quick referencereferences/tooling.md— CLI usage, session management, timeoutsreferences/codex-cli.md— Canonical Codex CLI reference and policy matrixreferences/claude-code.md— Claude Code CLI reference and session resumescripts/code-plan— Plan mode wrapper (read-only execution + artifact validation)references/reviews.md— Review + PR/issue writing patternsreferences/templates/plan-system-prompt.txt— Deterministic plan-mode system promptreferences/templates/plan-template.md— Canonical plan structure template
GitHub Hygiene
- PR titles:
type(scope): imperative summary(or repo override). - Issue titles:
- Feature:
feat: <capability> (for <surface>) - Bug:
bug: <symptom> when <condition> - Tracking:
TODO: <cleanup> after <dependency> - PR bodies must include:
What,Why,Tests,AI Assistance. Testsshould be exact commands;AI Assistanceshould include prompt/session link when available.
License
MIT
Claude Code CLI Reference
Detailed reference for Claude Code as a fallback when Codex is unavailable, or as primary CLI for Claude-based workflows.
Contents
- Non-interactive mode flags
- Session resume (non-interactive)
- Model selection
- Permission modes
- Budget controls
- Output formats
- Examples
- Codex → Claude mapping
---
Non-Interactive Mode (-p/--print)
The -p flag runs Claude in non-interactive mode: it processes the prompt and exits.
claude -p "Your prompt here"Note: The -p flag skips workspace trust dialogs. Only use in trusted directories.
---
Flags Reference
| Flag | Description |
|---|---|
-p, --print | Non-interactive mode, print and exit |
--model <model> | Model: sonnet, opus, haiku, or full name |
--permission-mode <mode> | Permission handling (see below) |
--dangerously-skip-permissions | Skip all permission checks |
--max-budget-usd <amount> | Cap API spending |
--fallback-model <model> | Auto-fallback if primary overloaded |
--output-format <format> | Output: text, json, stream-json |
--add-dir <dirs> | Additional directories to allow access |
-c, --continue | Continue most recent conversation |
-r, --resume <id> | Resume specific session |
--resume | Interactive session picker (no ID = browse) |
---
Session Resume (Non-Interactive)
Session resume restores full conversation context from disk. Use this for multi-phase workflows where context must persist across separate CLI invocations.
Continue Most Recent Session
# Continue the last conversation with a new prompt
claude -p -c "Fix the review findings from the previous session"
# Continue without a new prompt (re-runs last context)
claude -p -cResume Specific Session
# Browse sessions interactively to find the ID
claude --resume
# Resume a specific session by ID
claude -p --resume abc123 "Address the security concern raised in review"Session Storage
Sessions persist to ~/.claude/projects/<project>/sessions/. Each session contains the full conversation history, tool calls, and file context.
When to Use Resume
| Scenario | Command |
|---|---|
| Fix review findings | claude -p -c "Fix the issues from code review" |
| Continue implementation | claude -p --resume <id> "Continue implementing the auth module" |
| Follow-up on same PR | claude -p -c "Now add tests for the changes" |
| Unrelated new task | claude -p "New task prompt" (fresh session) |
Multi-Phase Example
# Phase 1: Implement
claude -p --dangerously-skip-permissions "Implement JWT auth middleware"
# Phase 2: Fix review findings (context preserved)
claude -p -c --dangerously-skip-permissions "Fix the review findings: add token expiry check"
# Phase 3: Add tests (context preserved)
claude -p -c --dangerously-skip-permissions "Add unit tests for the JWT middleware"---
Permission Modes
| Mode | Behavior |
|---|---|
default | Prompt for approval (interactive) |
acceptEdits | Auto-accept file edits |
bypassPermissions | Skip all permission checks |
dontAsk | Don't ask, but still enforce permissions |
plan | Planning mode only |
# Auto-accept edits (recommended for automation)
claude -p --permission-mode acceptEdits "Fix the bug"
# Full bypass (like Codex --yolo)
claude -p --dangerously-skip-permissions "Build the feature"---
Model Selection
# Use Opus for complex tasks
claude -p --model opus "Design the database schema"
# Use Haiku for quick/cheap tasks
claude -p --model haiku "Add a docstring"
# Use Sonnet (default, balanced)
claude -p --model sonnet "Refactor this function"
# With fallback
claude -p --model opus --fallback-model sonnet "Complex task"Models:
opus- Most capable, highest costsonnet- Balanced (default)haiku- Fastest, lowest cost
---
Budget Controls
# Cap spending at $5
claude -p --max-budget-usd 5 "Build a REST API"
# Combine with fallback for cost optimization
claude -p --model opus --fallback-model haiku --max-budget-usd 2 "Review this code"---
Output Formats
# Plain text (default)
claude -p "Summarize this file"
# JSON (single result)
claude -p --output-format json "List the functions in this file"
# Streaming JSON (for real-time processing)
claude -p --output-format stream-json "Analyze this codebase"---
Working Directory
# Add specific directories for file access
claude -p --add-dir ~/project --add-dir ~/shared "Refactor across both directories"---
Session Management
# Continue last conversation
claude -p -c "Follow up on the previous task"
# Resume specific session
claude -p -r session-id "Continue from here"
# Browse/pick sessions interactively
claude --resume---
Examples
Quick Code Fix
claude -p --permission-mode acceptEdits "Fix the null pointer exception in src/api.ts"Full Auto Build
claude -p --dangerously-skip-permissions "Build a REST API with CRUD endpoints for users"Code Review with Budget
claude -p --model opus --max-budget-usd 1 "Review this PR for security issues"Multi-Phase Implementation
# Phase 1: Implement
claude -p --dangerously-skip-permissions "Implement the user registration endpoint"
# Phase 2: Fix issues (resume context)
claude -p -c --dangerously-skip-permissions "Fix the validation error in registration"
# Phase 3: Add tests
claude -p -c --dangerously-skip-permissions "Add integration tests for registration"---
Codex → Claude Mapping
| Codex | Claude |
|---|---|
codex exec "prompt" | claude -p "prompt" |
codex exec --full-auto "prompt" | claude -p --permission-mode acceptEdits "prompt" |
codex --yolo "prompt" | claude -p --dangerously-skip-permissions "prompt" |
codex review --base <base> | claude -p "Review changes vs <base> branch" |
codex exec resume --last | claude -p -c "prompt" |
codex exec resume <id> | claude -p --resume <id> "prompt" |
Codex CLI Reference
Canonical Codex guidance for this skill.
Default Strategy
Use single-agent Codex for most work: 1. codex --yolo exec -c model_reasoning_effort="high" "..." for one-off implementation/refactor prompts. 2. codex exec resume --last "..." for follow-up work on the same task. 3. Use tmux only when terminal persistence/reattach is required.
This keeps workflows interactive and stateful without forcing a persistent tmux session.
Reasoning default policy:
- Use
highfor feature implementation and architectural refactors. - Use
medium/lowonly for simple fixes/docs tasks or when the user explicitly asks for fast/cheap execution.
Core Commands
One-off implementation
codex --yolo exec -c model_reasoning_effort="high" "Implement feature X. No questions."Resume previous context
codex exec resume --last "Fix findings from the previous run"Review against base branch
timeout 600s codex review --base <base> --title "PR #N Review"Structured non-interactive output
codex exec --json --output-last-message /tmp/last.txt "Summarize changes"Useful automation flags:
--json--output-schema <FILE>--output-last-message <FILE>--skip-git-repo-check
Safety Profiles
Choose one profile per run:
- Guardrailed sandbox:
codex exec --full-auto "..." - Full bypass (externally sandboxed environments only):
codex exec --dangerously-bypass-approvals-and-sandbox "..."codex --yolo exec is equivalent to bypass mode.
Execution Policy Matrix
| Task | Primary | Secondary | Notes |
|---|---|---|---|
| Implementation | direct codex exec with -c model_reasoning_effort="high" | tmux transport | Use resume for iterative loops; use medium/low only for simple/docs or fast/cheap requests |
| PR review | codex review --base | Claude CLI fallback | Keep timeout >= 600s |
| Long-running implementation | tmux transport | direct codex exec with -c model_reasoning_effort="high" | For reattach/log durability |
Implementation-mode env var:
CODING_AGENT_IMPL_MODE=direct|tmux|autodirect: run Codex directly firsttmux: run tmux transport firstauto: tmux first only when attached to TTY and tmux is available
MCP Clarification
There are two distinct MCP paths:
1. codex mcp ...
- Configure external MCP tools for Codex.
- Use when Codex needs extra context/tools.
2. codex mcp-server
- Expose Codex itself as an MCP server for another orchestrator.
- Experimental; use behind feature flags/pilots.
Multi-Agent Guidance
Codex multi-agent workflows are experimental.
Use only when the task is truly decomposable into parallel tracks (for example: independent security/performance/test-review streams). Prefer single-agent exec + resume for normal implementation cycles.
Official Sources
- https://developers.openai.com/codex/cli/reference
- https://developers.openai.com/codex/noninteractive
- https://developers.openai.com/codex/mcp
- https://developers.openai.com/codex/multi-agent
Violation Examples and Recovery
Violation Consequences
If any rule is violated: 1. Stop immediately. 2. Acknowledge the violation. 3. Revert or fix. 4. Document the violation in PR/commit notes. 5. Resume correctly.
Common Pitfalls
❌ Writing code directly
Wrong:
Edit file.py: add function xyz...Correct:
./scripts/code-implement "Add function xyz to file.py"❌ Skipping review
Wrong:
git push && gh pr create && gh pr mergeCorrect:
gh pr create
timeout 600s codex review --base <base> --title "PR Review"
./scripts/tmux-run timeout 1200s codex --yolo exec -c model_reasoning_effort="medium" \
"Review against STANDARDS.md and report PASS/FAIL per category"❌ Chaining without timeouts
Wrong:
codex exec "Part 1" && codex exec "Part 2"Correct:
timeout 300s codex --yolo exec -c model_reasoning_effort="high" "Part 1"
timeout 300s codex --yolo exec -c model_reasoning_effort="high" "Part 2"Real Violation Examples
Example 1: “Trivial Change” Rationalization
- What happened: Direct edit for a typo.
- Why wrong: Rule 1 has no exceptions.
- Fix:
./scripts/code-implement "Fix typo in config.py line 42"Example 2: Skipped PR Creation
- What happened: Commit on main, pushed directly.
- Why wrong: Rule 2 and Rule 3.
- Fix:
git checkout -b fix/typo-config
git add -A && git commit -m "fix: correct typo"
git push -u origin fix/typo-config
gh pr createExample 3: Missing Self-Check
- What happened: Implementation started without STOP-AND-VERIFY.
- Why wrong: Mandatory protocol.
- Fix: perform STOP-AND-VERIFY before any changes.
Frontend Design References
When reviewing frontend/UI work, check consistency with these sources:
1. Anthropic frontend-design
- https://github.com/anthropics/skills/blob/main/skills/frontend-design/SKILL.md
- Anti-AI-slop philosophy, typography, color, motion, spatial composition
- BANNED: Inter, Roboto, Arial, purple gradients, centered layouts
2. Anthropic web-artifacts-builder
- https://github.com/anthropics/skills/blob/main/skills/web-artifacts-builder/SKILL.md
- React 18 + TypeScript + Vite + Tailwind + shadcn/ui
- Single-file HTML bundling with Parcel
3. Community frontend-design-v2
- https://github.com/nhatmobile1/claude-skills/blob/main/skills/frontend/frontend-design-v2/SKILL.md
- Mobile-first patterns, hero layouts, accordions, form consistency
Gemini CLI Reference
Optional reference for Gemini CLI. This skill does not use Gemini by default. To enable Gemini as a fallback in scripts/safe-fallback.sh, set:
export GEMINI_FALLBACK_ENABLE=1Contents
- Basic usage
- Approval modes
- Model selection
- Sandbox mode
- Session management
- Output formats
- Examples
---
Basic Usage
Gemini CLI defaults to one-shot mode with positional prompts:
gemini "Your prompt here"For interactive mode, use -i:
gemini -i "Start with this prompt"---
Flags Reference
| Flag | Description |
|---|---|
-y, --yolo | Auto-approve all actions |
--approval-mode <mode> | Approval handling (see below) |
-m, --model <model> | Select model |
-s, --sandbox | Run in sandbox mode |
-i, --prompt-interactive | Interactive mode with initial prompt |
-o, --output-format <format> | Output: text, json, stream-json |
-r, --resume <id> | Resume session (latest or index) |
--include-directories <dirs> | Additional directories to include |
-d, --debug | Debug mode |
---
Approval Modes
| Mode | Behavior |
|---|---|
default | Prompt for approval |
auto_edit | Auto-approve edit tools only |
yolo | Auto-approve all tools |
# Auto-approve edits only
gemini --approval-mode auto_edit "Fix the bug in api.ts"
# Full auto (yolo)
gemini -y "Build the feature"
# or
gemini --approval-mode yolo "Build the feature"---
Model Selection
# Specify model
gemini -m gemini-2.5-pro "Complex analysis task"
# Default model (usually gemini-2.5-flash)
gemini "Quick task"---
Sandbox Mode
Run in a sandboxed environment for safety:
gemini -s "Experiment with this code"
gemini --sandbox "Run untrusted operations"---
Working Directories
# Include additional directories
gemini --include-directories ~/project,~/shared "Work across directories"
# Multiple flags
gemini --include-directories ~/project --include-directories ~/lib "Cross-repo task"---
Session Management
# List available sessions
gemini --list-sessions
# Resume latest session
gemini -r latest "Continue where we left off"
# Resume specific session by index
gemini -r 5 "Continue session 5"
# Delete a session
gemini --delete-session 3---
Output Formats
# Plain text (default)
gemini "Summarize this"
# JSON output
gemini -o json "List functions in this file"
# Streaming JSON
gemini -o stream-json "Analyze codebase"---
Examples
Quick Code Fix
gemini --approval-mode auto_edit "Fix the null check in src/api.ts"Full Auto Build
gemini -y "Build a REST API with user authentication"Sandboxed Experiment
gemini -s -y "Try refactoring this module using a different pattern"Interactive Session (with PTY)
bash pty:true workdir:~/project command:"gemini -i 'Help me debug this issue'"Background Task
bash pty:true workdir:~/project background:true command:"gemini -y 'Build the feature module'"---
Codex → Gemini Mapping
| Codex | Gemini |
|---|---|
codex exec "prompt" | gemini "prompt" |
codex exec --full-auto "prompt" | gemini --approval-mode auto_edit "prompt" |
codex --yolo "prompt" | gemini -y "prompt" |
---
Extensions & MCP
Gemini supports extensions and MCP servers:
# List extensions
gemini -l
# Use specific extensions
gemini -e code-search,git "Find and fix the bug"
# Manage MCP servers
gemini mcpcoding-agent Reference
Contents
- STOP-AND-VERIFY (Before ANY Implementation)
- Self-Audit Triggers (Option A)
- Forbidden Flags & Minimum Timeouts
- Tool Fallback Chain
- Direct CLI Commands (Primary)
- Plan Mode Commands
- Wrapper Scripts (Secondary)
- Preflight Checks
- Pre-Completion Checklist
- Quick Reference
- Command Reference
- Code Quality Standards
- Issue Priority (P0-P3)
- tmux for Interactive Sessions (Optional)
STOP-AND-VERIFY (Before ANY Implementation)
Say this out loud before writing/changing any code:
STOP. Before I proceed, let me verify:
□ Am I using an agent CLI (Codex/Claude)? (not Edit/Write tools)
□ Am I on a feature branch? (not main)
□ Will I create a PR before completing this task?
□ Am I using adequate timeout? (minimum: 600s for reviews)
□ Am I avoiding --max-turns? (let it complete naturally)If any box is unchecked → STOP and fix before proceeding.
Self-Audit Triggers (Option A)
Run self-audit before final response when:
- code/config changed,
- tests changed (or should have changed),
- review requested,
- docs commands/examples changed.
Skip only when:
- informational response with zero repo changes, or
- user asks for raw output only.
Forbidden Flags & Minimum Timeouts
❌ FORBIDDEN: --max-turns (any value)
❌ FORBIDDEN: timeout < 600s for reviews
✅ Reviews: TIMEOUT=600 minimum
✅ Architecture: TIMEOUT=600 minimumTool Fallback Chain
Implementation: Codex CLI (direct) → Codex CLI (tmux) → Claude CLI → BLOCKED
Reviews: Codex CLI (direct) → Claude CLI → BLOCKED
⛔ NEVER skip to direct edits — request user override insteadImplementation mode routing:
CODING_AGENT_IMPL_MODE=direct|tmux|auto(default:direct)auto-> tmux-first only in interactive TTY + tmux available; otherwise direct-first
Direct CLI Commands (Primary)
Codex
# Implementation default (feature work / architectural refactor)
codex --yolo exec -c model_reasoning_effort="high" "Implement feature X. No questions."
# Simple fix/docs or explicit fast/cheap request
codex --yolo exec -c model_reasoning_effort="medium" "Fix typo in one file"
codex --yolo exec -c model_reasoning_effort="low" "Update README command example quickly"
# Resume last session (context preserved)
codex exec resume --lastClaude Code
# Implementation (full autonomy)
claude -p --dangerously-skip-permissions "Implement feature X"
# Complex task with Opus
claude -p --model opus --dangerously-skip-permissions "Complex refactor..."
# Continue most recent session
claude -p -c "Fix the review findings"
# Resume specific session
claude -p --resume <session-id> "Continue implementation"
# List sessions
claude --resumePlan Mode Commands
# Generate read-only plan (Codex)
./scripts/code-plan --engine codex --repo /path/to/repo --base main "Implement feature X"
# Generate strict plan mode output (Claude)
./scripts/code-plan --engine claude --model sonnet --repo /path/to/repo "Implement feature X"
# Execute approved plan (prompts for approval if still PENDING)
./scripts/code-implement --plan /path/to/repo/.ai/plans/<plan>.mdWrapper Scripts (Secondary)
# Implementation (3 min timeout, tmux)
./scripts/code-implement "Implement feature X"
# Enforcement wrappers
TIMEOUT=600 ./scripts/safe-review.sh codex review --base <base> --title "PR Review"
TIMEOUT=180 ./scripts/safe-impl.sh codex --yolo exec -c model_reasoning_effort="high" "Implement feature X"Preflight Checks
# Verify local prerequisites and Claude binary resolution
./scripts/doctor
# Verify Codex command/flag drift before editing command docs
./scripts/doc-drift-check
# Validate wrapper behavior
./scripts/smoke-wrappers.shClaude is resolved in this order: CODING_AGENT_CLAUDE_BIN → ~/.claude/local/claude → claude in PATH.
Pre-Completion Checklist
Before marking ANY task complete:
- [ ] On feature branch? (not main)
- [ ] PR created with URL?
- [ ] Used agent CLI (direct or tmux)? (not direct edits)
- [ ] Code review posted to PR?
- [ ] Standards review posted to PR?
- [ ] Implementation audit completed?
- [ ] Review audit completed?
- [ ] PR body includes
What,Why,Tests,AI Assistance? - [ ] Issue/PR title follows repo conventions?
- [ ] User-facing long-form text passed through
/humanizer(or fallback explicitly noted)?
Unchecked box = Task NOT complete.
---
Quick Reference
Activate
Use /coding in OpenClaw to activate this skill.
For plan-first flow, use /plan <task> (maps to scripts/code-plan).
Agent CLI Commands
Codex — full autonomy:
codex --yolo exec -c model_reasoning_effort="high" "Your task. No questions."Codex — resume session:
codex exec resume --lastClaude Code — full autonomy:
claude -p --dangerously-skip-permissions "Your task"Claude Code — resume session:
claude -p -c "Follow up prompt"PR Review (direct CLI):
cd /path/to/repo
timeout 600s codex review --base <base> --title "Review PR #N"Git Workflow
# Checkout and review
gh pr checkout <PR> --repo owner/repo
timeout 600s codex review --base <base> --title "Review PR #<PR>"
# Merge (Martin only)
gh pr merge <PR> --repo owner/repo --admin --mergeIssue/PR Title Patterns
PR: type(scope): imperative summary
Issue: feat: <capability> (for <surface>)
Issue: bug: <symptom> when <condition>
Issue: TODO: <cleanup> after <dependency>PR Body Skeleton
## What
- ...
## Why
- ...
## Tests
- `command 1`
- `command 2`
## AI Assistance
- AI-assisted: yes/no
- Testing level: untested/lightly tested/fully tested
- Prompt/session log: <link or note>
- I understand this code: yesSelf-Audit Response Skeleton
## Self-Audit Summary
- Audit status: complete | skipped (reason)
- Tests run:
- `command ...`
- Residual risks:
- ...
- Assumptions:
- ...
- Command/docs verification:
- VERIFIED: ...
- UNVERIFIED: ...Definitions:
VERIFIED: command/example was executed in this session.UNVERIFIED: command/example was not executed in this session.
Command Reference
| Task | Command |
|---|---|
| List PRs | gh pr list --repo owner/repo |
| View PR | gh pr view <PR> --json number,title,state |
| Checkout PR | gh pr checkout <PR> |
| Review PR | timeout 600s codex review --base <base> --title "PR #N Review" |
| Preflight wrappers | ./scripts/doctor |
| Codex doc drift check | ./scripts/doc-drift-check |
| Wrapper smoke tests | ./scripts/smoke-wrappers.sh |
| Check CI | gh pr checks <PR> --repo owner/repo |
| Merge PR | gh pr merge <PR> --repo owner/repo --admin --merge |
| Resume Codex | codex exec resume --last |
| Resume Claude | claude -p -c "prompt" |
| Pick Claude session | claude --resume (interactive) |
Code Quality Standards
- Functions: max 30-40 lines
- Classes: max 500 lines
- Files: max 500 lines
- KISS, YAGNI, DRY, SRP principles
Issue Priority (P0-P3)
- P0: Critical (security, data loss)
- P1: High (major feature broken)
- P2: Medium (minor features)
- P3: Low (nice-to-have)
tmux for Interactive Sessions (Optional)
For durable TTY sessions with logging. See references/tooling.md for full tmux documentation.
SOCKET_DIR="${OPENCLAW_TMUX_SOCKET_DIR:-${CLAWDBOT_TMUX_SOCKET_DIR:-${TMPDIR:-/tmp}/openclaw-tmux-sockets}}"
mkdir -p "$SOCKET_DIR"
SOCKET="$SOCKET_DIR/openclaw.sock"
SESSION=codex-impl
tmux -S "$SOCKET" new-session -d -s "$SESSION" -n shell
TARGET="$(tmux -S "$SOCKET" list-panes -t "$SESSION" -F "#{session_name}:#{window_index}.#{pane_index}" | head -n 1)"
tmux -S "$SOCKET" send-keys -t "$TARGET" -l -- "codex --yolo exec -c model_reasoning_effort=\"high\" 'Implement feature X'"
tmux -S "$SOCKET" send-keys -t "$TARGET" Enter
# Monitor
tmux -S "$SOCKET" attach -t "$SESSION"
tmux -S "$SOCKET" capture-pane -p -J -t "$TARGET" -S -200
# Cleanup
tmux -S "$SOCKET" kill-session -t "$SESSION"Reviews and Standards
Review Workflow
New Features (Issue → PR)
1. Implement with agent CLI. 2. Create PR. 3. Run Codex review. 4. Run standards review (references/STANDARDS.md) — required. 5. Fix issues, push updates to same branch.
Existing PRs
1. Checkout PR. 2. Run Codex review locally. 3. Run standards review. 4. Post both reviews to GitHub. 5. Fix issues, push updates.
Codebase Reviews
1. Run full review (Codex or Claude CLI with long timeout). 2. Classify findings by severity (P0–P3). 3. Create issues with file:line references.
Review Output Contract (Required)
- List findings first, ordered by severity (
P0->P3). - Include concrete file:line reference for each finding.
- Include open questions/assumptions after findings.
- If command/docs examples were changed, label each as:
VERIFIED(executed) orUNVERIFIED(not executed)- Never imply a command was validated when it was not run.
Self-Audit Summary Block (Required in final review response)
## Self-Audit Summary
- Audit status: complete | skipped (reason)
- Tests run:
- `command ...`
- Residual risks:
- ...
- Assumptions:
- ...
- Command/docs verification:
- VERIFIED: ...
- UNVERIFIED: ...Issue/PR Authoring Standard (Peter-style)
PR Titles
- Default:
type(scope): imperative summary - Use repo-specific override only when documented (e.g.,
Type: Description #issue)
Issue Titles
- Feature:
feat: <capability> (for <surface>) - Bug:
bug: <symptom> when <condition> - Tracking:
TODO: <cleanup> after <dependency>
PR Body Sections (required)
1. What (3-6 concrete bullets) 2. Why (impact/reason) 3. Tests (exact commands run) 4. AI Assistance (used/not used, testing level, prompt/session log, understanding confirmation)
Review Commands
# Code review (direct CLI)
timeout 600s codex review --base <base> --title "PR #N Review"
# Standards review (direct CLI, preferred)
timeout 1200s codex --yolo exec -c model_reasoning_effort="medium" \
"Review against coding standards in references/STANDARDS.md. Report PASS/FAIL per category with file:line refs."
# Standards review (tmux transport, optional for persistence)
./scripts/tmux-run timeout 1200s codex --yolo exec -c model_reasoning_effort="medium" \
"Review against coding standards in references/STANDARDS.md. Report PASS/FAIL per category with file:line refs."Posting Reviews to GitHub
# Approve
gh pr review <PR> --approve --body "LGTM"
# Request changes
gh pr review <PR> --request-changes --body "Found issues that need fixing"
# Comment only
gh pr review <PR> --comment --body "Suggestions and notes"Standards Review Output Format
## references/STANDARDS.md Standards Review ✅|⚠️|❌
### ✅ PASSED
- Code Quality: Functions under 40 lines
### ⚠️ WARNINGS (P2)
- [file:23] Function has 7 parameters (limit: 4)
### ❌ ISSUES (P1)
- [file:8] Commit uses wrong format
### Assumptions / Open Questions
- Assumption: ...
### Command/Docs Verification
- VERIFIED: `timeout 600s codex review --base main`
- UNVERIFIED: `claude ...`
### Recommendation: APPROVE / REQUEST_CHANGESCoding Standards
Contents
- Principles
- Size Limits
- Naming & Clarity
- Error Handling
- Testing
- Security
- Documentation
Language: English only - all code, comments, docs, examples, commits, configs, errors, tests
Foundational Principles
KISS (Keep It Simple)
- Simplest solution wins | Avoid premature abstraction | Reduce complexity
- Inline single-use helpers | Remove unused flexibility | Flatten unnecessary layers
YAGNI (You Aren't Gonna Need It)
- Build only what's needed now | No speculative features | No "future-proofing"
- Delete unused code completely | Add complexity when required, not before
DRY (Don't Repeat Yourself)
- Extract common patterns | Maintain consistency | Single source of truth
- Three strikes rule - don't abstract until third occurrence
SRP (Single Responsibility)
- One class, one reason to change | One responsibility per module
- Separate authentication, database operations, business logic, UI concerns
Design Principles
Law of Demeter
- Classes know only direct dependencies | Avoid chaining | "Don't talk to strangers"
- Add delegation methods | Pass required objects directly | Flatten access patterns
Dependency Injection
- Inject dependencies explicitly | Avoid hidden coupling | Make relationships visible
- Constructor injection for required dependencies | Method injection for optional
Polymorphism over Conditionals
- Prefer polymorphism to if/else chains | Use interfaces for extensibility
- Extract strategy pattern | Replace conditionals with polymorphic dispatch
Size Limits & Refactoring Triggers
- Functions: Max 30-40 lines
- Classes: Max 500 lines | Refactor when >30 methods
- Files: Max 500 lines | Split when exceeding or mixing multiple concerns
- Methods per Class: Max 20-30 methods
Refactoring Best Practices
- Small Steps: Incremental changes to reduce bugs | Test each modification
- Separate Concerns: Never mix refactoring with bug fixing
- No Backwards-Compatibility Hacks: Delete unused code completely | No renaming to _vars | No // removed comments
Universal Coding Standards
- Naming: Descriptive, searchable names | Replace magic numbers with named constants
- Functions: Max 3-4 parameters | Encapsulate boundary conditions | Declare variables near usage
- TypeScript: Use Record<string, unknown> over any | PascalCase (classes/interfaces) | camelCase (functions/variables)
- Error Handling: Explicit error patterns | Never silent failures
- Imports: Order as node → external → internal | Remove unused immediately
- Git Commits: Conventional format: type(scope): subject | 50 chars max, imperative mood | Atomic changes
- Repo override: If a repository defines a different format (e.g.,
Type: Description #issue), follow the repo and retain#issuelinkage.
Inclusive Language
- Terms: allowlist/blocklist, primary/replica, placeholder/example, main branch, conflict-free, concurrent/parallel
Process Compliance Checks
During standards review, also verify process compliance:
Git Workflow Compliance
- [ ] Changes made on feature branch (not main)
- [ ] PR exists with descriptive title
- [ ] Commits follow conventional format (
type(scope): description) - [ ] No force pushes to shared branches
- [ ] No direct commits to main
- [ ] PR/issue titles follow repo conventions
- [ ] PR body includes
What,Why,Tests,AI Assistance - [ ]
Testssection lists exact commands run
Tool Usage Compliance
- [ ] If agent CLI specified → verify CLI was used (look for CLI invocation in session log)
- [ ] Implementation done via agent CLI (Codex/Claude); direct CLI primary, tmux optional for durable runs (not direct file edits)
- [ ] Reviews done via
codex revieworclaude -p - [ ] Tool used is documented in PR description
- [ ] If AI-assisted, PR documents testing level and prompt/session log reference
Review Process Compliance
- [ ] Code/logic review completed
- [ ] Standards review completed
- [ ] Both reviews posted to GitHub PR
- [ ] Self-audit completed (or explicit skip reason documented)
- [ ] Issues found are addressed before merge
Compliance Review Output Format
## Process Compliance Review ✅|❌
### Git Workflow
- [x] Feature branch used
- [x] PR created
- [x] Conventional commits
### Tool Usage
- [x] Specified tools used
- [x] Implementation via agent CLI (direct or tmux)
### Review Process
- [x] Code review posted
- [x] Standards review posted
**Status**: COMPLIANT / NON-COMPLIANTYou are in PLAN MODE for a coding task.
CRITICAL CONSTRAINTS:
1) READ-ONLY behavior only.
2) Do NOT modify files.
3) Do NOT run install commands.
4) Do NOT run git mutation commands (commit/push/merge/rebase/reset/checkout -b/cherry-pick).
5) Do NOT claim work was implemented.
6) If information is missing, state assumptions explicitly.
OUTPUT CONTRACT:
- Return ONLY markdown.
- Use EXACT section headers and order from the required schema below.
- No extra sections.
- No preamble, no epilogue.
- Keep content concrete, testable, and implementation-ready.
- Include exact commands where requested.
- Use concise bullets; avoid fluff.
REQUIRED SCHEMA (EXACT):
# Plan: <short title>
## Fast-Path
- Eligible: yes|no
- Reason: <one sentence>
## 1. Problem statement
<content>
## 2. Current state evidence
- Files:
- `<path>#Lx-Ly` — <why relevant>
- Commands run:
- `<command>`
- Observations:
- <bullet>
## 3. Proposed approach
<content>
## 4. Step-by-step change list
1. <step>
2. <step>
## 5. Risks + rollback
- Risks:
- <risk>
- Rollback:
- <exact rollback command/process>
## 6. Test plan
- Automated:
- `<exact command>`
- Manual:
- <manual check>
- Success criteria:
- <bullet>
## 7. Out-of-scope
- <bullet>
## 8. Approval prompt
Reply with one:
- `APPROVE: <plan-id>`
- `REVISE: <what to change>`
QUALITY BAR:
- Evidence must reference real files/commands (or explicitly say “not verified”).
- Step list must be actionable and sequenced.
- Test plan must be executable.
- If task is trivial, still fill all sections; mark Fast-Path Eligible: yes.
Plan: <short title>
Fast-Path
- Eligible: yes|no
- Reason: <one sentence>
1. Problem statement
2. Current state evidence
- Files:
<path>#Lx-Ly— <why relevant>- Commands run:
<command>- Observations:
- <bullet>
3. Proposed approach
4. Step-by-step change list
1. <step> 2. <step>
5. Risks + rollback
- Risks:
- <risk>
- Rollback:
- <exact rollback command/process>
6. Test plan
- Automated:
<exact command>- Manual:
- <manual check>
- Success criteria:
- <bullet>
7. Out-of-scope
- <bullet>
8. Approval prompt
Reply with one:
APPROVE: <plan-id>REVISE: <what to change>
Tooling and Timeouts
Approach Comparison
| Method | Reliability | Output | Best For |
|---|---|---|---|
Direct Codex CLI (exec + resume) | ✅ High | Text/JSON stream | Most implementation loops and iterative follow-ups |
| tmux transport + Codex CLI | ✅ High | Full TTY + logs | Long-running tasks requiring reattach and terminal durability |
| Claude CLI fallback | ⚠️ Medium | Text stream | When Codex is unavailable |
Execution Policy Matrix
| Task | Primary | Secondary | Notes |
|---|---|---|---|
| Plan mode | scripts/code-plan --engine codex | scripts/code-plan --engine claude | Read-only planning artifact + approval gate |
| Implementation | direct codex --yolo exec -c model_reasoning_effort="high" | tmux transport | Default high for feature/architectural work; use medium/low for simple/docs or fast/cheap requests |
| PR review | codex review --base <base> | Claude CLI | Keep timeout >= 600s |
| Long-running implementation | tmux transport | direct codex --yolo exec -c model_reasoning_effort="high" | Use tmux when persistence/reattach is required |
Implementation routing is configurable:
CODING_AGENT_IMPL_MODE=direct-> direct first, tmux secondCODING_AGENT_IMPL_MODE=tmux-> tmux first, direct secondCODING_AGENT_IMPL_MODE=auto-> tmux first only when attached to an interactive TTY and tmux exists
Default behavior: direct.
Direct CLI (Primary)
Agent CLIs support non-interactive execution with permission bypass and session resume.
Reasoning defaults for Codex implementation:
highfor feature implementation and architectural refactors.medium/lowfor simple fixes, docs-only work, or explicit fast/cheap requests.
Codex CLI
| Command | Purpose |
|---|---|
codex --yolo exec -c model_reasoning_effort="high" "prompt" | Full-autonomy implementation (default for feature/architectural work) |
codex exec resume --last "follow-up" | Resume previous context |
codex review --base <base> | Code review against base branch |
codex exec --json "prompt" | Structured event stream for automation |
codex exec --output-last-message /tmp/last.txt "prompt" | Persist final response for wrappers/scripts |
Claude Code CLI
| Command | Purpose |
|---|---|
claude -p --dangerously-skip-permissions "prompt" | Full-autonomy implementation fallback |
claude -p --model opus "prompt" | Complex fallback task |
claude -p -c "follow up" | Continue most recent session |
claude -p --resume <id> "follow up" | Resume specific session |
claude --resume | Interactive session picker |
Permission Bypass
| CLI | Flag | Behavior |
|---|---|---|
| Codex | --yolo | Alias for full bypass in exec workflows |
| Codex | --dangerously-bypass-approvals-and-sandbox | Skip approvals and sandbox |
| Codex | --full-auto | Lower-friction sandboxed automation |
| Claude | --dangerously-skip-permissions | Skip all permission checks |
| Claude | --permission-mode bypassPermissions | Equivalent via mode flag |
| Claude | --permission-mode acceptEdits | Auto-accept file edits only |
Session Management
| CLI | Command | Purpose |
|---|---|---|
| Codex | codex exec resume --last | Resume last session |
| Claude | claude -p -c "prompt" | Continue most recent conversation |
| Claude | claude -p --resume <id> "prompt" | Resume specific session by ID |
| Claude | claude --resume | Interactive session picker |
Sessions persist to disk (~/.codex/sessions/ and ~/.claude/projects/<project>/) and survive process restarts.
MCP Clarification
Two MCP modes exist and should not be conflated:
1. codex mcp ...
- Adds external MCP tools for Codex to use during a run.
2. codex mcp-server
- Exposes Codex itself as an MCP server for another orchestrator.
- Experimental; use behind feature flags/pilots.
Preflight Checks
Run preflight before wrapper use:
./scripts/doctorRun CLI drift checks before changing command docs:
./scripts/doc-drift-checkscripts/doctor checks:
codexghtimeout- Claude binary resolution in this order:
CODING_AGENT_CLAUDE_BIN->~/.claude/local/claude->claudeinPATH
Wrapper Scripts
# Plan mode wrapper (read-only)
"${CODING_AGENT_DIR:-./}/scripts/code-plan" --engine codex --repo /path/to/repo "Implement feature X"
# Implementation wrapper (tmux transport)
"${CODING_AGENT_DIR:-./}/scripts/code-implement" "Implement feature X in /path/to/repo"
# Execute an approved plan artifact
"${CODING_AGENT_DIR:-./}/scripts/code-implement" --plan /path/to/repo/.ai/plans/<plan>.mdFor reviews, use direct CLI — no wrapper needed:
# Detect base branch: main, master, or trunk (whichever exists)
timeout 600s codex review --base <base> --title "Review PR #N"Validate wrappers locally:
./scripts/smoke-wrappers.shAdvanced: tmux Wrapper (Optional)
For durable TTY sessions with logging. Use when you need to monitor long-running tasks or preserve terminal output.
tmux Conventions (OpenClaw)
- Socket directory:
OPENCLAW_TMUX_SOCKET_DIR(legacy:CLAWDBOT_TMUX_SOCKET_DIR) - Default socket:
${TMPDIR:-/tmp}/openclaw-tmux-sockets/openclaw.sock - Send commands literally:
tmux ... send-keys -l -- "cmd" - Always print monitor commands after creating a session
Direct tmux Usage
SOCKET_DIR="${OPENCLAW_TMUX_SOCKET_DIR:-${CLAWDBOT_TMUX_SOCKET_DIR:-${TMPDIR:-/tmp}/openclaw-tmux-sockets}}"
mkdir -p "$SOCKET_DIR"
SOCKET="$SOCKET_DIR/openclaw.sock"
SESSION="codex-impl-$(date +%Y%m%d-%H%M%S)"
# Start session and run codex
tmux -S "$SOCKET" new-session -d -s "$SESSION" -n shell
TARGET="$(tmux -S "$SOCKET" list-panes -t "$SESSION" -F "#{session_name}:#{window_index}.#{pane_index}" | head -n 1)"
tmux -S "$SOCKET" send-keys -t "$TARGET" -l -- "codex --yolo exec -c model_reasoning_effort=\"high\" 'Implement feature X'"
tmux -S "$SOCKET" send-keys -t "$TARGET" Enter
# Monitor
tmux -S "$SOCKET" attach -t "$SESSION"
tmux -S "$SOCKET" capture-pane -p -J -t "$TARGET" -S -200tmux-run Helper
scripts/tmux-run standardizes sockets, logging, and session names. Non-blocking by default unless --wait is passed.
# Run an implementation command in tmux (non-blocking)
CODEX_TMUX_SESSION_PREFIX=codex-impl \
./scripts/tmux-run timeout 180s codex --yolo exec -c model_reasoning_effort="high" "Implement feature X"
# Run a long implementation in tmux and wait for completion
CODEX_TMUX_SESSION_PREFIX=codex-impl \
./scripts/tmux-run --wait timeout 600s codex --yolo exec -c model_reasoning_effort="high" "Complex multi-file refactor"Logs: ${XDG_STATE_HOME:-$HOME/.local/state}/openclaw/tmux/<session>.log
Cleanup:
- Kill session:
tmux -S "$SOCKET" kill-session -t "$SESSION" - Remove old logs:
find "$LOG_DIR" -type f -mtime +7 -delete
Minimum Timeouts
| Task Type | Minimum | Default |
|---|---|---|
| Code review | 600s | 600s |
| Architectural review | 600s | 600s |
| Single-file implementation | 120s | 180s |
| Multi-file implementation | 300s | 600s |
Environment Variables
| Variable | Purpose | Default |
|---|---|---|
CODING_AGENT_IMPL_MODE | Implementation routing policy (`direct | tmux |
CODING_AGENT_CLAUDE_BIN | Explicit Claude CLI path override | unset |
OPENCLAW_TMUX_SOCKET_DIR | Socket directory (preferred) | ${TMPDIR:-/tmp}/openclaw-tmux-sockets |
CLAWDBOT_TMUX_SOCKET_DIR | Legacy socket directory | unset |
CODEX_TMUX_SOCKET_DIR | Explicit socket directory override | unset |
CODEX_TMUX_SOCKET | Explicit socket path | ${OPENCLAW_TMUX_SOCKET_DIR}/openclaw.sock |
CODEX_TMUX_SESSION | Explicit session name | autogenerated |
CODEX_TMUX_SESSION_PREFIX | Session name prefix | codex |
CODEX_TMUX_LOG_DIR | Log directory | ${XDG_STATE_HOME:-$HOME/.local/state}/openclaw/tmux |
CODEX_TMUX_WAIT | Block until command finishes | 0 |
CODEX_TMUX_CLEANUP | Kill session after completion | 0 |
CODEX_TMUX_WAIT_TIMEOUT | Optional wait timeout (seconds) | unset |
CODEX_TMUX_DISABLE | Legacy override: force direct mode | 0 |
CODEX_TMUX_REQUIRED | Legacy override: force tmux mode | 0 |
GEMINI_FALLBACK_ENABLE | Enable Gemini fallback in safe-fallback.sh | 0 |
CODE_IMPLEMENT_TIMEOUT | Implement wrapper timeout (ms) | 180000 |
Coding Workflow & Operations
Contents
- Overview
- Git Workflow
- Hard Requirements (Violation = Task Failure)
- Self-Audit Protocol
- GitHub CLI (gh)
- Agent Workflow
- Multi-Phase Workflow (Session Resume)
- Agent CLI Reference
- Agent Utilization
Overview
Roles:
- @kesslerIO (Martin): Human Owner. Approves P0/P1 changes.
- @niemandBot (Niemand): AI Agent. Reviews code, runs checks, implements features.
Philosophy:
- Plan First: Always discuss approach before implementation.
- Surface Decisions: Present options with trade-offs.
- Confirm Alignment: Ensure agreement before coding.
- No Direct Edits: Use agent CLIs (Codex/Claude) to write code.
Git Workflow
Note: Niemand does NOT create branches, commit code, or merge PRs unless explicitly requested.
Standard Flow
1. Create Branch: git checkout -b type/description 2. Implement: Use agent CLI (see below) 3. Commit: git commit -m "type(scope): description" 4. Push: git push -u origin branch-name 5. PR: gh pr create 6. Review: Run code review (see below) 7. Fix: Address issues (resume session for context) 8. Merge: gh pr merge
Commit Types
feat: New featurefix: Bug fixdocs: Documentation onlystyle: Formatting (no code change)refactor: Restructuring code (no API change)test: Adding testschore: Build/tooling changes
Hard Requirements (Violation = Task Failure)
These are non-negotiable requirements. Violating any of these means the task has FAILED.
1. Branch Requirement
- MUST create feature branch before any code changes
- MUST NOT commit directly to main
- Violation Response: Stop and ask user to confirm branch creation
2. PR Requirement
- MUST create PR before code can be considered "done"
- MUST post review to PR before merge
- MUST include PR URL in task completion message
- Violation Response: Refuse to mark task complete without PR URL
3. Tool Usage Requirement
- When user specifies "use claude/codex/gemini": MUST use that CLI tool when available/configured
- MUST use agent CLI (direct or tmux wrappers) — not direct file edits
- For reviews: use direct
codex review --base <base>orclaude -p - For implementation: prefer direct CLI (
codex --yolo exec -c model_reasoning_effort="high") orscripts/code-implement - Default reasoning policy: use
highfor feature implementation and architectural refactors; usemedium/lowonly for simple fixes/docs or explicit fast/cheap requests - MUST NOT use direct file edits when agent CLI is specified
- MUST document which tool was used in PR description
- Violation Response: Stop and switch to specified tool
4. Review Requirement
- MUST run code review before merge
- MUST run standards review (references/STANDARDS.md) before merge
- MUST post both reviews to GitHub PR
- Violation Response: Block merge until reviews are posted
5. Self-Audit Requirement
- MUST run self-audit before reporting completion when code/config/docs commands were changed
- MUST use findings-first format with severity order and file:line references for review tasks
- MUST verify changed command examples or explicitly mark them unverified
- Violation Response: Do not mark complete; run audit and report gaps
Self-Check Before Completion
Before reporting task complete, verify:
- [ ] Changes on feature branch (not main)?
- [ ] PR created and URL available?
- [ ] Correct tools used (agent CLI, direct or tmux)?
- [ ] Code review completed and posted?
- [ ] Standards review completed and posted?
- [ ] Self-audit completed (or explicit skip reason documented)?
Self-Audit Protocol
Run this before final response unless skip conditions apply.
When Required
- Code/config changed.
- Tests changed or should have changed.
- Review requested by user.
- Docs changed with executable commands/examples.
Skip Conditions
- Informational response only, no repo changes.
- User requested raw command output only.
If skipped, explicitly state why.
Phase 1: Implementation Audit
- [ ] Requirement coverage checked against user request.
- [ ] Edge cases and failure paths reviewed.
- [ ] Tests added/updated or explicit rationale for none.
- [ ] Risky assumptions called out.
Phase 2: Review Audit
- [ ] Findings ordered by severity (P0-P3).
- [ ] Every finding includes file:line reference.
- [ ] Regressions/unintended side effects checked.
- [ ] Changed docs commands/examples verified; if not run, mark
UNVERIFIED.
Final Response Contract
Use this block in completion messages:
## Self-Audit Summary
- Audit status: complete | skipped (reason)
- Tests run:
- `command ...`
- Residual risks:
- ...
- Assumptions:
- ...
- Command/docs verification:
- VERIFIED: ...
- UNVERIFIED: ...GitHub CLI (gh)
Authentication
- Check status:
gh auth status - Login:
gh auth login(uses PAT or browser) - Switch account:
gh auth switch --user <username>
Common Commands
- Create PR:
gh pr create --title "feat: ..." --body "..." - View PR:
gh pr view <number> - Checkout PR:
gh pr checkout <number> - Review PR:
gh pr review <number> --approve - Merge PR:
gh pr merge <number> --admin --merge --delete-branch
Issue/PR Hygiene (Required)
- Keep one logical change per PR.
- Search before opening issues:
gh issue list --search "<keywords>". - PR title default:
type(scope): imperative summary(unless repo override). - Issue title defaults:
- Feature:
feat: <capability> (for <surface>) - Bug:
bug: <symptom> when <condition> - Tracking:
TODO: <cleanup> after <dependency> - PR body sections (required):
What,Why,Tests,AI Assistance. Tests: list exact commands run.AI Assistance: used/not used, testing level, prompt/session log link, and "I understand this code."
Agent Workflow
Primary: Direct CLI
Use agent CLIs directly for most tasks. Session resume preserves full context across phases and is preferred over spawning sub-agents for routine implementation.
# Implementation (Codex)
codex --yolo exec -c model_reasoning_effort="high" "Implement feature X. No questions."
# Implementation (Claude)
claude -p --dangerously-skip-permissions "Implement feature X"
# Review (Codex)
codex review --base <base> --title "PR Review"
# Review (Claude)
claude -p --model opus "Review changes vs main branch for bugs, security, quality"Secondary: tmux Wrappers
For durable implementation sessions with logging and monitoring:
# Implementation (tmux)
./scripts/code-implement "Implement feature X in /path/to/repo"Code Review Process
Hierarchy: 1. Codex: Primary reviewer (codex review --base <base>). 2. Claude: Default fallback if Codex is unavailable. 3. Gemini (optional): Only if explicitly enabled (GEMINI_FALLBACK_ENABLE=1). 4. Sub-agent: Last resort for orchestration.
Step 1: Code Review (Logic/Bugs)
gh pr checkout <PR>
timeout 600s codex review --base <base> --title "PR #N Review"Step 2: Standards Review (Required)
codex --yolo exec --model gpt-5.3-codex \
-c model_reasoning_effort="medium" "Review against STANDARDS.md..."Step 3: Posting Results
gh pr review <PR> --comment --body "$(cat review.md)"Multi-Phase Workflow (Session Resume)
For complex tasks spanning multiple phases, use session resume to preserve full context:
Issue → Implement → PR → Review → Fix → Merge
# Phase 1: Implement from issue
codex --yolo exec -c model_reasoning_effort="high" "Implement feature described in issue #42. No questions."
# Phase 2: Create PR
gh pr create --title "feat(auth): add JWT validation" --body "..."
# Phase 3: Review
timeout 600s codex review --base <base> --title "Review PR #N"
# Phase 4: Fix review findings (resume preserves context)
codex exec resume --last
# Or with Claude:
claude -p --resume <session-id> "Fix the review findings"
# Phase 5: Re-review after fixes
timeout 600s codex review --base <base> --title "Re-review PR #N"
# Phase 6: Merge
gh pr merge --merge --delete-branchSession Resume Commands
| Phase | Codex | Claude Code |
|---|---|---|
| Resume last | codex exec resume --last | claude -p -c "prompt" |
| Resume specific | codex exec resume <id> | claude -p --resume <id> "prompt" |
| List/pick session | — | claude --resume (interactive picker) |
Codex resume compatibility note:
- Preferred:
codex exec resume --lastorcodex exec resume <id>. - If your installed Codex build does not support
resume, start a fresh run and reference the prior issue/PR context explicitly.
When to Resume vs Start Fresh
- Resume: Fix review findings, continue implementation, follow-up on same codebase
- Fresh: New issue, different repo, unrelated task
Base Branch Detection (<base>)
Use this order:
# Primary
git symbolic-ref refs/remotes/origin/HEAD 2>/dev/null | sed 's@^refs/remotes/origin/@@'
# Fallback (when origin/HEAD is unset)
git remote show origin | sed -n '/HEAD branch/s/.*: //p'Prompt Engineering Best Practices
- Be Specific: "Implement X using Y library" vs "Add X".
- No Confirmation: "Do not ask for confirmation. Just implement."
- Small Batches: Don't change 50 files at once.
- Clear Exit: "Reply with DONE when finished."
Agent CLI Reference
Codex CLI
For automated runs with full autonomy:
# Implementation (full autonomy)
codex --yolo exec -c model_reasoning_effort="high" "Implement feature X. No questions."
# Simple fix/docs or explicit fast/cheap request
codex --yolo exec -c model_reasoning_effort="medium" "Fix typo in one file"
codex --yolo exec -c model_reasoning_effort="low" "Update README command example quickly"
# Resume last session
codex exec resume --lastClaude Code CLI
# Implementation (full autonomy)
claude -p --dangerously-skip-permissions "Implement feature X"
# With model selection
claude -p --model opus --dangerously-skip-permissions "Complex task"
# Resume/continue
claude -p -c "Follow up on the previous task"
claude -p --resume <session-id> "Continue from here"See references/claude-code.md for full Claude Code reference. See references/codex-cli.md for canonical Codex execution policy (exec, resume, MCP distinctions). See references/tooling.md for tmux wrappers, timeouts, and environment variables.
Agent Utilization
Delegate specific tasks to focused agents only when decomposition is clear and parallelizable:
- requirements-specialist: Specs → GitHub Issues
- implementation-architect: API/UI Design
- quality-assurance-specialist: Tests, Security, Perf
- docs-architect: Documentation updates
Trigger: Use sub-agents for independent tracks (for example: separate security/performance/test review streams). Keep single-agent codex exec + codex exec resume as the default path for implementation loops.
Sub-agent note:
- Codex multi-agent workflows are experimental.
- Non-interactive approval handling can fail if sub-agents request escalation unexpectedly.
#!/usr/bin/env bash
# code-implement - Wrapper for code implementation with proper timeout
#
# Usage:
# code-implement "Implement feature X in /path/to/project"
# code-implement --plan .ai/plans/<plan>.md [--force]
set -euo pipefail
export PATH="$PATH:/run/current-system/sw/bin"
usage() {
cat >&2 <<'USAGE'
Usage:
code-implement "<prompt>"
code-implement --plan <path> [--force]
USAGE
}
PLAN_PATH=""
FORCE=0
PROMPT=""
EXEC_REPO="$(pwd)"
while [[ $# -gt 0 ]]; do
case "$1" in
--plan)
PLAN_PATH="${2:-}"
shift 2
;;
--force)
FORCE=1
shift
;;
-h|--help)
usage
exit 0
;;
--)
shift
break
;;
*)
if [[ -z "$PROMPT" ]]; then
PROMPT="$1"
else
PROMPT="$PROMPT $1"
fi
shift
;;
esac
done
if [[ $# -gt 0 ]]; then
if [[ -z "$PROMPT" ]]; then
PROMPT="$*"
else
PROMPT="$PROMPT $*"
fi
fi
if [[ -n "$PLAN_PATH" && -n "$PROMPT" ]]; then
echo "Error: provide either --plan or a prompt, not both" >&2
exit 1
fi
if [[ -z "$PLAN_PATH" && -z "$PROMPT" ]]; then
usage
exit 1
fi
TIMEOUT_MS="${CODE_IMPLEMENT_TIMEOUT:-180000}"
if [[ ! "$TIMEOUT_MS" =~ ^[0-9]+$ ]]; then
echo "Error: CODE_IMPLEMENT_TIMEOUT must be a number (milliseconds)" >&2
echo "Got: $TIMEOUT_MS" >&2
exit 1
fi
TIMEOUT_SEC=$((TIMEOUT_MS / 1000))
get_frontmatter_field() {
local file="$1"
local key="$2"
awk -F': ' -v wanted="$key" '
BEGIN { in_fm=0 }
$0 == "---" {
if (in_fm == 0) { in_fm=1; next }
else { exit }
}
in_fm == 1 {
if (index($0, wanted ":") == 1) {
sub("^[^:]+:[ ]*", "", $0)
print $0
exit
}
}
' "$file"
}
set_frontmatter_field() {
local file="$1"
local key="$2"
local value="$3"
local tmp
tmp="$(mktemp)"
awk -v k="$key" -v v="$value" '
BEGIN { in_fm=0; replaced=0 }
$0 == "---" {
if (in_fm == 0) { in_fm=1; print; next }
if (in_fm == 1) {
if (replaced == 0) { print k ": " v }
in_fm=2
print
next
}
}
in_fm == 1 {
if (index($0, k ":") == 1) {
print k ": " v
replaced=1
next
}
}
{ print }
' "$file" > "$tmp"
mv "$tmp" "$file"
}
if [[ -n "$PLAN_PATH" ]]; then
if [[ ! -f "$PLAN_PATH" ]]; then
echo "Error: plan file not found: $PLAN_PATH" >&2
exit 1
fi
status="$(get_frontmatter_field "$PLAN_PATH" "status")"
plan_id="$(get_frontmatter_field "$PLAN_PATH" "id")"
if [[ -z "$plan_id" ]]; then
plan_id="$(basename "$PLAN_PATH" .md)"
fi
repo_from_plan="$(get_frontmatter_field "$PLAN_PATH" "repo_path")"
if [[ -n "$repo_from_plan" ]]; then
if ! git -C "$repo_from_plan" rev-parse --git-dir >/dev/null 2>&1; then
echo "Error: repo_path from plan is not a git repo: $repo_from_plan" >&2
exit 1
fi
EXEC_REPO="$repo_from_plan"
fi
if [[ "$status" != "APPROVED" && "$FORCE" != "1" ]]; then
echo "⚠️ Plan $plan_id is currently ${status:-PENDING}."
read -r -p "Do you approve this plan for execution? [y/N/revise] " answer
case "${answer,,}" in
y|yes)
set_frontmatter_field "$PLAN_PATH" "status" "APPROVED"
set_frontmatter_field "$PLAN_PATH" "approved_by" "${USER:-unknown}"
set_frontmatter_field "$PLAN_PATH" "approved_at" "$(date -Iseconds)"
;;
revise)
echo "Plan left unchanged. Revise by rerunning code-plan with updated guidance." >&2
exit 1
;;
*)
echo "Execution cancelled." >&2
exit 1
;;
esac
fi
status="$(get_frontmatter_field "$PLAN_PATH" "status")"
if [[ "$status" != "APPROVED" && "$FORCE" != "1" ]]; then
echo "Error: plan status must be APPROVED to execute. Use --force to bypass." >&2
exit 1
fi
echo "Executing approved plan: $PLAN_PATH" >&2
plan_body="$(cat "$PLAN_PATH")"
PROMPT=$(cat <<EOF
Executing approved plan: $PLAN_PATH
Follow this plan exactly unless blocked by new evidence. If blocked, explain deviation and proceed with the safest minimal change set.
PLAN CONTENT:
$plan_body
EOF
)
fi
echo "Starting implementation in tmux with ${TIMEOUT_SEC}s timeout..." >&2
echo "Execution repository: $EXEC_REPO" >&2
if ! command -v codex &> /dev/null; then
echo "Error: codex CLI not found. Please install: npm install -g @openai/codex" >&2
exit 1
fi
if ! command -v tmux &> /dev/null; then
echo "Error: tmux not found. Install tmux or use a host with tmux available." >&2
exit 1
fi
if ! command -v timeout &> /dev/null; then
echo "Error: timeout command not found. Install coreutils (brew install coreutils on macOS)." >&2
exit 1
fi
SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
TMUX_RUN="$SCRIPT_DIR/tmux-run"
if [[ ! -x "$TMUX_RUN" ]]; then
echo "Error: tmux-run not found or not executable: $TMUX_RUN" >&2
exit 1
fi
(
cd "$EXEC_REPO"
CODEX_TMUX_SESSION_PREFIX="${CODEX_TMUX_SESSION_PREFIX:-codex-impl}" \
"$TMUX_RUN" timeout "${TIMEOUT_SEC}s" codex --yolo exec "$PROMPT"
)
#!/usr/bin/env bash
set -euo pipefail
export PATH="$PATH:/run/current-system/sw/bin"
SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
ROOT_DIR="$(cd -- "$SCRIPT_DIR/.." && pwd)"
SYSTEM_PROMPT_FILE="$ROOT_DIR/references/templates/plan-system-prompt.txt"
# shellcheck disable=SC1091
source "$SCRIPT_DIR/lib/resolve-cli.sh"
usage() {
cat >&2 <<'USAGE'
Usage:
code-plan [--engine codex|claude] [--model <name>] [--repo <path>] [--base <branch>] [--prompt <text>]
code-plan [--engine codex|claude] [--model <name>] [--repo <path>] [--base <branch>] "<prompt>"
Defaults:
--engine codex
--repo current working directory
--base auto-detected origin default branch (fallback: main)
USAGE
}
ENGINE="${CODING_AGENT_PLAN_ENGINE:-codex}"
MODEL=""
REPO_PATH="$(pwd)"
BASE_BRANCH=""
PROMPT=""
while [[ $# -gt 0 ]]; do
case "$1" in
--engine)
ENGINE="${2:-}"
shift 2
;;
--model)
MODEL="${2:-}"
shift 2
;;
--repo)
REPO_PATH="${2:-}"
shift 2
;;
--base)
BASE_BRANCH="${2:-}"
shift 2
;;
--prompt)
PROMPT="${2:-}"
shift 2
;;
-h|--help)
usage
exit 0
;;
--)
shift
break
;;
*)
if [[ -z "$PROMPT" ]]; then
PROMPT="$1"
else
PROMPT="$PROMPT $1"
fi
shift
;;
esac
done
if [[ $# -gt 0 ]]; then
if [[ -z "$PROMPT" ]]; then
PROMPT="$*"
else
PROMPT="$PROMPT $*"
fi
fi
if [[ -z "$PROMPT" ]]; then
usage
exit 1
fi
if [[ "$ENGINE" != "codex" && "$ENGINE" != "claude" ]]; then
echo "Error: --engine must be codex or claude" >&2
exit 1
fi
REPO_PATH="$(cd "$REPO_PATH" && pwd)"
if ! git -C "$REPO_PATH" rev-parse --git-dir >/dev/null 2>&1; then
echo "Error: --repo must point to a git repository" >&2
exit 1
fi
if [[ -z "$BASE_BRANCH" ]]; then
BASE_BRANCH="$(git -C "$REPO_PATH" symbolic-ref refs/remotes/origin/HEAD 2>/dev/null | sed 's@^refs/remotes/origin/@@')"
fi
if [[ -z "$BASE_BRANCH" ]]; then
BASE_BRANCH="main"
fi
CURRENT_BRANCH="$(git -C "$REPO_PATH" rev-parse --abbrev-ref HEAD 2>/dev/null || echo unknown)"
HEAD_SHA="$(git -C "$REPO_PATH" rev-parse HEAD 2>/dev/null || echo unknown)"
REPO_REMOTE="$(git -C "$REPO_PATH" remote get-url origin 2>/dev/null || echo unknown)"
PLAN_DIR="$REPO_PATH/.ai/plans"
FAILED_DIR="$PLAN_DIR/.failed"
mkdir -p "$PLAN_DIR" "$FAILED_DIR"
TIMESTAMP="$(date +"%Y-%m-%d-%H%M%S")"
CREATED_AT="$(date -Iseconds)"
slugify() {
echo "$1" | tr '[:upper:]' '[:lower:]' | sed -E 's/[^a-z0-9]+/-/g; s/^-+//; s/-+$//' | cut -c1-40
}
SLUG="$(slugify "$PROMPT")"
if [[ -z "$SLUG" ]]; then
SLUG="plan"
fi
PLAN_FILENAME="${TIMESTAMP}-${SLUG}.md"
PLAN_PATH="$PLAN_DIR/$PLAN_FILENAME"
FAILED_PATH="$FAILED_DIR/${TIMESTAMP}-${SLUG}.raw.md"
PLAN_ID="${PLAN_FILENAME%.md}"
TMP_DIR="$(mktemp -d)"
trap 'rm -rf "$TMP_DIR"' EXIT
RAW_OUTPUT_FILE="$TMP_DIR/raw.md"
SYSTEM_PROMPT="$TMP_DIR/system_prompt.txt"
cat "$SYSTEM_PROMPT_FILE" > "$SYSTEM_PROMPT"
cat >> "$SYSTEM_PROMPT" <<EOF
TASK CONTEXT:
- Repository: $REPO_PATH
- Base branch: $BASE_BRANCH
- Current branch: $CURRENT_BRANCH
- Head SHA: $HEAD_SHA
USER REQUEST:
$PROMPT
EOF
run_codex() {
local -a cmd=(codex exec --sandbox read-only --ephemeral)
if [[ -n "$MODEL" ]]; then
cmd+=(--model "$MODEL")
fi
cmd+=("$(cat "$SYSTEM_PROMPT")")
(
cd "$REPO_PATH"
"${cmd[@]}"
)
}
run_claude() {
local claude_bin
if ! claude_bin="$(resolve_claude_bin)"; then
echo "Error: Claude CLI not found" >&2
exit 1
fi
local -a cmd=("$claude_bin" -p --permission-mode plan --no-session-persistence)
if [[ -n "$MODEL" ]]; then
cmd+=(--model "$MODEL")
fi
cmd+=("$(cat "$SYSTEM_PROMPT")")
(
cd "$REPO_PATH"
"${cmd[@]}"
)
}
if [[ "$ENGINE" == "codex" ]]; then
run_codex > "$RAW_OUTPUT_FILE"
else
run_claude > "$RAW_OUTPUT_FILE"
fi
validate_headings() {
local file="$1"
local -a headings=(
"# Plan:"
"## Fast-Path"
"## 1. Problem statement"
"## 2. Current state evidence"
"## 3. Proposed approach"
"## 4. Step-by-step change list"
"## 5. Risks + rollback"
"## 6. Test plan"
"## 7. Out-of-scope"
"## 8. Approval prompt"
)
local prev=0
local found
for heading in "${headings[@]}"; do
found="$(grep -nF "$heading" "$file" | head -1 | cut -d: -f1 || true)"
if [[ -z "$found" ]]; then
echo "missing heading: $heading" >&2
return 1
fi
if (( found <= prev )); then
echo "heading out of order: $heading" >&2
return 1
fi
prev=$found
done
return 0
}
if ! validate_headings "$RAW_OUTPUT_FILE"; then
cp "$RAW_OUTPUT_FILE" "$FAILED_PATH"
echo "❌ Plan validation failed. Raw output saved to: $FAILED_PATH" >&2
exit 1
fi
{
echo "---"
echo "id: $PLAN_ID"
echo "status: PENDING"
echo "created_at: $CREATED_AT"
echo "repo_path: $REPO_PATH"
echo "repo_remote: $REPO_REMOTE"
echo "base_branch: $BASE_BRANCH"
echo "current_branch: $CURRENT_BRANCH"
echo "head_sha: $HEAD_SHA"
echo "engine: $ENGINE"
echo "model: ${MODEL:-default}"
echo "invocation: code-plan --engine $ENGINE${MODEL:+ --model $MODEL} --repo $REPO_PATH --base $BASE_BRANCH"
echo "approved_by:"
echo "approved_at:"
echo "---"
cat "$RAW_OUTPUT_FILE"
} > "$PLAN_PATH"
echo "✅ Plan generated: $PLAN_PATH"
echo "Next: code-implement --plan $PLAN_PATH"
#!/usr/bin/env bash
# doc-drift-check - verify documented Codex commands/flags still exist
set -euo pipefail
# Ensure standard tools are available on NixOS
export PATH="$PATH:/run/current-system/sw/bin"
if ! command -v codex >/dev/null 2>&1; then
if [[ "${CI:-}" == "true" || "${GITHUB_ACTIONS:-}" == "true" ]]; then
echo "[skip] codex not found in PATH; skipping doc drift checks in CI" >&2
exit 0
fi
echo "Error: codex not found in PATH" >&2
exit 1
fi
assert_contains() {
local haystack="$1"
local needle="$2"
local label="$3"
if ! grep -Fq -- "$needle" <<<"$haystack"; then
echo "[fail] missing '${needle}' in ${label}" >&2
return 1
fi
echo "[ok] ${label}: ${needle}" >&2
}
root_help="$(codex --help)"
exec_help="$(codex exec --help)"
review_help="$(codex review --help)"
resume_help="$(codex exec resume --help)"
mcp_help="$(codex mcp --help)"
assert_contains "$root_help" "exec" "codex --help"
assert_contains "$root_help" "review" "codex --help"
assert_contains "$root_help" "mcp" "codex --help"
assert_contains "$root_help" "mcp-server" "codex --help"
assert_contains "$root_help" "resume" "codex --help"
assert_contains "$exec_help" "--json" "codex exec --help"
assert_contains "$exec_help" "--output-schema" "codex exec --help"
assert_contains "$exec_help" "--output-last-message" "codex exec --help"
assert_contains "$exec_help" "--skip-git-repo-check" "codex exec --help"
assert_contains "$exec_help" "--full-auto" "codex exec --help"
assert_contains "$exec_help" "--dangerously-bypass-approvals-and-sandbox" "codex exec --help"
assert_contains "$review_help" "--base" "codex review --help"
assert_contains "$resume_help" "--last" "codex exec resume --help"
assert_contains "$mcp_help" "add" "codex mcp --help"
echo "Codex doc drift checks passed." >&2
#!/usr/bin/env bash
# doctor - preflight checks for OpenClaw coding skill wrappers
set -euo pipefail
# Ensure standard tools are available on NixOS
export PATH="$PATH:/run/current-system/sw/bin"
SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck disable=SC1091
source "$SCRIPT_DIR/lib/resolve-cli.sh"
failures=0
check_cmd() {
local name="$1"
local remediation="$2"
if command -v "$name" &>/dev/null; then
printf '[ok] %s: %s\n' "$name" "$(command -v "$name")"
else
printf '[fail] %s: not found\n' "$name" >&2
printf ' Fix: %s\n' "$remediation" >&2
failures=$((failures + 1))
fi
}
printf 'OpenClaw wrapper preflight\n'
printf '==========================\n'
check_cmd "codex" "npm install -g @openai/codex"
check_cmd "gh" "brew install gh"
check_cmd "timeout" "brew install coreutils && mkdir -p \"$HOME/.local/bin\" && ln -sf \"\$(brew --prefix coreutils)/bin/gtimeout\" \"$HOME/.local/bin/timeout\""
if claude_bin="$(resolve_claude_bin)"; then
printf '[ok] claude: %s\n' "$claude_bin"
else
if [[ -n "${CODING_AGENT_CLAUDE_BIN:-}" ]]; then
printf '[fail] claude: CODING_AGENT_CLAUDE_BIN is set but not executable: %s\n' "${CODING_AGENT_CLAUDE_BIN}" >&2
printf ' Fix: unset CODING_AGENT_CLAUDE_BIN or point it to a valid Claude binary\n' >&2
else
printf '[fail] claude: not found (checked CODING_AGENT_CLAUDE_BIN, ~/.claude/local/claude, then PATH)\n' >&2
printf ' Fix (PATH install): npm install -g @anthropic-ai/claude-code\n' >&2
printf ' Fix (local binary): install/use ~/.claude/local/claude\n' >&2
fi
failures=$((failures + 1))
fi
printf '[info] implementation mode default: %s (set CODING_AGENT_IMPL_MODE=direct|tmux|auto to override)\n' "${CODING_AGENT_IMPL_MODE:-direct}"
if [[ "$failures" -gt 0 ]]; then
printf '\nPreflight failed with %s issue(s).\n' "$failures" >&2
exit 1
fi
printf '\nPreflight passed.\n'
#!/usr/bin/env bash
set -euo pipefail
resolve_claude_bin() {
if [[ -n "${CODING_AGENT_CLAUDE_BIN:-}" ]]; then
if [[ -x "${CODING_AGENT_CLAUDE_BIN}" ]]; then
printf '%s\n' "${CODING_AGENT_CLAUDE_BIN}"
return 0
fi
return 1
fi
local claude_local="${HOME}/.claude/local/claude"
if [[ -x "$claude_local" ]]; then
printf '%s\n' "$claude_local"
return 0
fi
if command -v claude &>/dev/null; then
command -v claude
return 0
fi
return 1
}
#!/usr/bin/env bash
set -euo pipefail
SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
exec "$SCRIPT_DIR/code-plan" "$@"
#!/usr/bin/env bash
# safe-fallback.sh - Try tools in order, report blocker if all fail
# NEVER falls back to direct edits - that's a Rule 1 violation
set -euo pipefail
# Ensure standard tools are available on NixOS
export PATH="$PATH:/run/current-system/sw/bin"
# Configuration
MODE="${1:-impl}" # impl or review
shift || true
if [[ "$MODE" != "impl" && "$MODE" != "review" ]]; then
echo "Error: invalid mode '$MODE' (expected: impl|review)" >&2
echo "Usage: safe-fallback.sh <impl|review> \"prompt...\"" >&2
exit 1
fi
PROMPT="${*:-}"
if [[ -z "$PROMPT" ]]; then
echo "Usage: safe-fallback.sh <impl|review> \"prompt...\""
echo ""
echo "Examples:"
echo " safe-fallback.sh impl \"Implement feature X\""
echo " safe-fallback.sh review \"Review this PR for bugs and security issues\""
exit 1
fi
SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck disable=SC1091
source "$SCRIPT_DIR/lib/resolve-cli.sh"
# Timeouts
IMPL_TIMEOUT=${IMPL_TIMEOUT:-180}
REVIEW_TIMEOUT=${REVIEW_TIMEOUT:-1200}
TIMEOUT=$([[ "$MODE" == "review" ]] && echo "$REVIEW_TIMEOUT" || echo "$IMPL_TIMEOUT")
# Gemini fallback is opt-in only.
GEMINI_FALLBACK_ENABLE=${GEMINI_FALLBACK_ENABLE:-0}
if [[ "$GEMINI_FALLBACK_ENABLE" != "0" && "$GEMINI_FALLBACK_ENABLE" != "1" ]]; then
echo "Error: GEMINI_FALLBACK_ENABLE must be 0 or 1" >&2
exit 1
fi
# Colors
RED='\033[0;31m'
YELLOW='\033[1;33m'
GREEN='\033[0;32m'
CYAN='\033[0;36m'
NC='\033[0m'
error() { echo -e "${RED}❌ $1${NC}" >&2; }
warn() { echo -e "${YELLOW}⚠️ $1${NC}" >&2; }
ok() { echo -e "${GREEN}✅ $1${NC}" >&2; }
info() { echo -e "${CYAN}ℹ️ $1${NC}" >&2; }
resolve_impl_mode() {
if [[ -n "${CODING_AGENT_IMPL_MODE:-}" ]]; then
printf '%s\n' "${CODING_AGENT_IMPL_MODE}"
return 0
fi
# Legacy compatibility knobs.
if [[ "${CODEX_TMUX_DISABLE:-0}" == "1" ]]; then
printf 'direct\n'
return 0
fi
if [[ "${CODEX_TMUX_REQUIRED:-0}" == "1" ]]; then
printf 'tmux\n'
return 0
fi
printf 'direct\n'
}
# Track failures (portable array init)
FAILURES=()
# Try Codex CLI in tmux (implementation only)
try_codex_tmux() {
if [[ "$MODE" != "impl" ]]; then
FAILURES+=("Codex tmux: unsupported in review mode")
return 1
fi
info "Trying Codex CLI in tmux..."
if "$SCRIPT_DIR/code-implement" "$PROMPT"; then
ok "Codex tmux session started"
return 0
fi
FAILURES+=("Codex tmux: failed to start")
return 1
}
# Try Codex CLI (direct, no tmux)
try_codex_cli_direct() {
info "Trying Codex CLI (direct)..."
if command -v codex &>/dev/null; then
if ! command -v timeout &>/dev/null; then
FAILURES+=("Codex CLI: timeout not installed")
return 1
fi
if [[ "$MODE" == "review" ]]; then
local base_branch="main"
if git rev-parse --git-dir &>/dev/null; then
base_branch="$(git symbolic-ref --quiet refs/remotes/origin/HEAD 2>/dev/null | sed 's@^refs/remotes/origin/@@')"
if [[ -z "$base_branch" ]]; then
for candidate in main master trunk; do
if git show-ref --verify --quiet "refs/heads/${candidate}" || \
git show-ref --verify --quiet "refs/remotes/origin/${candidate}"; then
base_branch="$candidate"
break
fi
done
fi
if [[ -z "$base_branch" ]]; then
base_branch="$(git rev-parse --abbrev-ref HEAD 2>/dev/null || echo main)"
fi
fi
if timeout "${TIMEOUT}s" codex review --base "$base_branch" --title "${PROMPT:0:100}" "$PROMPT"; then
ok "Codex CLI review succeeded"
return 0
fi
FAILURES+=("Codex CLI: review failed or timeout")
return 1
fi
if timeout "${TIMEOUT}s" codex --yolo exec "$PROMPT"; then
ok "Codex CLI implementation succeeded"
return 0
fi
FAILURES+=("Codex CLI: exec failed or timeout")
return 1
fi
FAILURES+=("Codex CLI: codex not installed")
return 1
}
# Try Claude CLI
try_claude_cli() {
info "Trying Claude CLI (timeout: ${TIMEOUT}s, skip-permissions)..."
local claude_bin
if claude_bin="$(resolve_claude_bin)"; then
if command -v timeout &>/dev/null; then
# Use --dangerously-skip-permissions to avoid hanging on permission prompts
if timeout "${TIMEOUT}s" "$claude_bin" -p --dangerously-skip-permissions "$PROMPT"; then
ok "Claude CLI succeeded"
return 0
fi
FAILURES+=("Claude CLI: timeout or error (${TIMEOUT}s)")
else
FAILURES+=("Claude CLI: timeout command not available")
fi
else
if [[ -n "${CODING_AGENT_CLAUDE_BIN:-}" ]]; then
FAILURES+=("Claude CLI: CODING_AGENT_CLAUDE_BIN is set but not executable (${CODING_AGENT_CLAUDE_BIN})")
else
FAILURES+=("Claude CLI: not found (CODING_AGENT_CLAUDE_BIN, ~/.claude/local/claude, PATH)")
fi
fi
return 1
}
# Try Gemini CLI (opt-in only)
try_gemini_cli() {
if [[ "$GEMINI_FALLBACK_ENABLE" != "1" ]]; then
FAILURES+=("Gemini CLI: disabled (set GEMINI_FALLBACK_ENABLE=1 to enable)")
return 1
fi
info "Trying Gemini CLI (timeout: ${TIMEOUT}s)..."
if command -v gemini &>/dev/null; then
if command -v timeout &>/dev/null; then
if timeout "${TIMEOUT}s" gemini -y "$PROMPT"; then
ok "Gemini CLI succeeded"
return 0
fi
FAILURES+=("Gemini CLI: timeout or error (${TIMEOUT}s)")
else
FAILURES+=("Gemini CLI: timeout command not available")
fi
else
FAILURES+=("Gemini CLI: gemini not installed")
fi
return 1
}
# Report blocker (all to stderr)
report_blocker() {
echo "" >&2
error "BLOCKED: All tools unavailable for mode '$MODE'"
echo "" >&2
echo "Failures:" >&2
for failure in "${FAILURES[@]}"; do
echo " - $failure" >&2
done
echo "" >&2
echo "Options:" >&2
echo " a) Wait for tool availability (e.g., Codex usage limit reset)" >&2
echo " b) User manually runs: codex --yolo exec \"$PROMPT\"" >&2
echo " c) User explicitly authorizes override: 'Override Rule 1 for this task'" >&2
echo "" >&2
echo "⛔ DO NOT use direct file edits - this is a Rule 1 violation" >&2
exit 1
}
# Main execution
main() {
# All status to stderr so stdout only has tool output
echo "Mode: $MODE | Timeout: ${TIMEOUT}s" >&2
echo "Gemini fallback: $GEMINI_FALLBACK_ENABLE" >&2
if [[ "$MODE" == "review" ]]; then
try_codex_cli_direct && exit 0
warn "Codex CLI unavailable for review, trying next..."
else
impl_mode="$(resolve_impl_mode)"
case "$impl_mode" in
direct|tmux|auto)
;;
*)
error "Invalid CODING_AGENT_IMPL_MODE '$impl_mode' (expected: direct|tmux|auto)"
exit 1
;;
esac
if [[ "$impl_mode" == "auto" ]]; then
if command -v tmux &>/dev/null && [[ -t 1 ]]; then
impl_mode="tmux"
else
impl_mode="direct"
fi
fi
echo "Implementation mode: $impl_mode" >&2
if [[ "$impl_mode" == "tmux" ]]; then
try_codex_tmux && exit 0
warn "Codex tmux unavailable, trying direct CLI..."
try_codex_cli_direct && exit 0
warn "Codex direct CLI unavailable, trying next..."
else
try_codex_cli_direct && exit 0
warn "Codex direct CLI unavailable, trying tmux..."
try_codex_tmux && exit 0
warn "Codex tmux unavailable, trying next..."
fi
fi
try_claude_cli && exit 0
warn "Claude CLI unavailable..."
try_gemini_cli && exit 0
warn "Gemini CLI unavailable..."
# All tools failed
report_blocker
}
main
#!/usr/bin/env bash
# safe-impl.sh - Wrapper for implementation commands
# Enforces branch check and blocks --max-turns
set -euo pipefail
# Ensure standard tools are available on NixOS
export PATH="$PATH:/run/current-system/sw/bin"
# Configuration
MIN_IMPL_TIMEOUT=${MIN_IMPL_TIMEOUT:-180}
DEFAULT_TIMEOUT=${DEFAULT_TIMEOUT:-180}
SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck disable=SC1091
source "$SCRIPT_DIR/lib/resolve-cli.sh"
# Colors
RED='\033[0;31m'
YELLOW='\033[1;33m'
GREEN='\033[0;32m'
NC='\033[0m' # No Color
error() { echo -e "${RED}❌ $1${NC}" >&2; }
warn() { echo -e "${YELLOW}⚠️ $1${NC}" >&2; }
ok() { echo -e "${GREEN}✅ $1${NC}" >&2; }
resolve_impl_mode() {
if [[ -n "${CODING_AGENT_IMPL_MODE:-}" ]]; then
printf '%s\n' "${CODING_AGENT_IMPL_MODE}"
return 0
fi
# Legacy compatibility knobs.
if [[ "${CODEX_TMUX_DISABLE:-0}" == "1" ]]; then
printf 'direct\n'
return 0
fi
if [[ "${CODEX_TMUX_REQUIRED:-0}" == "1" ]]; then
printf 'tmux\n'
return 0
fi
printf 'direct\n'
}
# Check for forbidden --max-turns flag
for arg in "$@"; do
if [[ "$arg" == "--max-turns"* ]] || [[ "$arg" == "--max-turns="* ]]; then
error "--max-turns is FORBIDDEN by coding-agent skill."
echo " Let the command complete naturally with adequate timeout."
echo " See: SKILL.md Rule 4"
exit 1
fi
done
# Check timeout command exists (not default on macOS)
if ! command -v timeout &>/dev/null; then
error "'timeout' command not found. Install coreutils (brew install coreutils on macOS)."
exit 1
fi
# Check we're not on main/master branch
BRANCH=$(git branch --show-current 2>/dev/null || echo "")
if [[ -z "$BRANCH" ]]; then
error "Not in a git repository or no branch checked out."
echo " Implementation requires a git repository with a feature branch."
exit 1
fi
PROTECTED_BRANCHES="main master"
for protected in $PROTECTED_BRANCHES; do
if [[ "$BRANCH" == "$protected" ]]; then
error "Cannot run implementation on '$BRANCH' branch."
echo " Create a feature branch first:"
echo " git checkout -b type/description"
echo " See: SKILL.md Rule 2"
exit 1
fi
done
ok "Branch check passed: $BRANCH"
# Parse timeout from environment
TIMEOUT="${TIMEOUT:-$DEFAULT_TIMEOUT}"
# Validate minimum timeout
if [[ $TIMEOUT -lt $MIN_IMPL_TIMEOUT ]]; then
warn "Timeout ${TIMEOUT}s is below recommended ${MIN_IMPL_TIMEOUT}s"
fi
# Require explicit CLI specification
CLI="${1:-}"
if [[ -z "$CLI" ]]; then
error "Usage: safe-impl.sh <codex|claude> [args...]"
exit 1
fi
if [[ "$CLI" != "codex" && "$CLI" != "claude" ]]; then
error "Unknown CLI: $CLI. Must be 'codex' or 'claude'."
exit 1
fi
shift # Remove CLI name from args
# Validate CLI exists
CLI_BIN="$CLI"
if [[ "$CLI" == "claude" ]]; then
if ! CLI_BIN="$(resolve_claude_bin)"; then
if [[ -n "${CODING_AGENT_CLAUDE_BIN:-}" ]]; then
error "CODING_AGENT_CLAUDE_BIN is set but not executable: ${CODING_AGENT_CLAUDE_BIN}"
else
error "Claude CLI not found (tried CODING_AGENT_CLAUDE_BIN, ~/.claude/local/claude, then PATH)."
fi
exit 1
fi
elif ! command -v "$CLI" &>/dev/null; then
error "CLI '$CLI' not found in PATH"
exit 1
fi
# Codex implementation mode:
# - direct: run codex directly
# - tmux: require tmux transport
# - auto: tmux when attached to interactive TTY and tmux exists; otherwise direct
if [[ "$CLI" == "codex" ]]; then
IMPL_MODE="$(resolve_impl_mode)"
case "$IMPL_MODE" in
direct)
RUN_IN_TMUX=0
;;
tmux)
RUN_IN_TMUX=1
;;
auto)
if command -v tmux &>/dev/null && [[ -t 1 ]]; then
RUN_IN_TMUX=1
else
RUN_IN_TMUX=0
fi
;;
*)
error "Invalid CODING_AGENT_IMPL_MODE '$IMPL_MODE' (expected: direct|tmux|auto)"
exit 1
;;
esac
if [[ "$RUN_IN_TMUX" == "1" ]]; then
if ! command -v tmux &>/dev/null; then
error "tmux not found in PATH. Install tmux or set CODING_AGENT_IMPL_MODE=direct."
exit 1
fi
TMUX_RUN="$SCRIPT_DIR/tmux-run"
if [[ ! -x "$TMUX_RUN" ]]; then
error "tmux-run not found or not executable: $TMUX_RUN"
exit 1
fi
warn "Running codex implementation in tmux with ${TIMEOUT}s timeout (mode: ${IMPL_MODE})"
CODEX_TMUX_SESSION_PREFIX="${CODEX_TMUX_SESSION_PREFIX:-codex-impl}" \
"$TMUX_RUN" timeout "${TIMEOUT}s" "$CLI" "$@"
exit $?
fi
fi
# For Claude CLI with -p flag, add --dangerously-skip-permissions to avoid hanging,
# unless running explicit plan permission mode.
EXTRA_ARGS=()
if [[ "$CLI" == "claude" ]]; then
has_print_mode=0
has_plan_permission_mode=0
for arg in "$@"; do
if [[ "$arg" == "-p" || "$arg" == "--print" ]]; then
has_print_mode=1
fi
if [[ "$arg" == "--permission-mode" ]]; then
has_plan_permission_mode=2
continue
fi
if [[ "$has_plan_permission_mode" == "2" ]]; then
if [[ "$arg" == "plan" ]]; then
has_plan_permission_mode=1
else
has_plan_permission_mode=0
fi
fi
if [[ "$arg" == "--permission-mode=plan" ]]; then
has_plan_permission_mode=1
fi
done
if [[ "$has_print_mode" == "1" && "$has_plan_permission_mode" != "1" ]]; then
if [[ ! " $* " =~ " --dangerously-skip-permissions " ]]; then
EXTRA_ARGS+=("--dangerously-skip-permissions")
warn "Adding --dangerously-skip-permissions to prevent permission prompt hangs"
fi
fi
fi
# Execute with timeout (use ${arr[@]+...} for older bash compatibility)
warn "Running $CLI implementation with ${TIMEOUT}s timeout"
exec timeout "${TIMEOUT}s" "$CLI_BIN" ${EXTRA_ARGS[@]+"${EXTRA_ARGS[@]}"} "$@"
#!/usr/bin/env bash
# safe-review.sh - Wrapper for claude/codex review commands
# Enforces timeout minimums and blocks --max-turns
set -euo pipefail
# Ensure standard tools are available on NixOS
export PATH="$PATH:/run/current-system/sw/bin"
# Configuration
MIN_REVIEW_TIMEOUT=${MIN_REVIEW_TIMEOUT:-600}
DEFAULT_TIMEOUT=${DEFAULT_TIMEOUT:-1200}
SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck disable=SC1091
source "$SCRIPT_DIR/lib/resolve-cli.sh"
# Colors
RED='\033[0;31m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color
error() { echo -e "${RED}❌ $1${NC}" >&2; }
warn() { echo -e "${YELLOW}⚠️ $1${NC}" >&2; }
# Detect which CLI to use
CLI="${1:-}"
if [[ -z "$CLI" ]]; then
error "Usage: safe-review.sh <claude|codex> [args...]"
exit 1
fi
if [[ "$CLI" != "claude" && "$CLI" != "codex" ]]; then
error "Unknown CLI: $CLI. Must be 'codex' or 'claude'."
exit 1
fi
shift # Remove CLI name from args
# Check for forbidden --max-turns flag
for arg in "$@"; do
if [[ "$arg" == "--max-turns"* ]] || [[ "$arg" == "--max-turns="* ]]; then
error "--max-turns is FORBIDDEN by coding-agent skill."
echo " Let the command complete naturally with adequate timeout."
echo " See: SKILL.md Rule 4"
exit 1
fi
done
# Check timeout command exists (not default on macOS)
if ! command -v timeout &>/dev/null; then
error "'timeout' command not found. Install coreutils (brew install coreutils on macOS)."
exit 1
fi
# Parse timeout from environment or args
TIMEOUT="${TIMEOUT:-$DEFAULT_TIMEOUT}"
# Check minimum timeout for reviews
if [[ $TIMEOUT -lt $MIN_REVIEW_TIMEOUT ]]; then
error "Timeout ${TIMEOUT}s is below minimum ${MIN_REVIEW_TIMEOUT}s for reviews."
echo " Reviews require adequate time for quality analysis."
echo " See: SKILL.md Rule 5"
echo ""
echo " Fix: TIMEOUT=$MIN_REVIEW_TIMEOUT $0 $CLI $*"
exit 1
fi
# Validate CLI exists
CLI_BIN="$CLI"
if [[ "$CLI" == "claude" ]]; then
if ! CLI_BIN="$(resolve_claude_bin)"; then
if [[ -n "${CODING_AGENT_CLAUDE_BIN:-}" ]]; then
error "CODING_AGENT_CLAUDE_BIN is set but not executable: ${CODING_AGENT_CLAUDE_BIN}"
else
error "Claude CLI not found (tried CODING_AGENT_CLAUDE_BIN, ~/.claude/local/claude, then PATH)."
fi
exit 1
fi
elif ! command -v "$CLI" &>/dev/null; then
error "CLI '$CLI' not found in PATH"
exit 1
fi
# For Claude CLI with -p flag, add --dangerously-skip-permissions to avoid hanging
EXTRA_ARGS=()
if [[ "$CLI" == "claude" ]]; then
for arg in "$@"; do
if [[ "$arg" == "-p" || "$arg" == "--print" ]]; then
# Check if --dangerously-skip-permissions is already present
if [[ ! " $* " =~ " --dangerously-skip-permissions " ]]; then
EXTRA_ARGS+=("--dangerously-skip-permissions")
warn "Adding --dangerously-skip-permissions to prevent permission prompt hangs"
fi
break
fi
done
fi
# Execute with timeout (use ${arr[@]+...} for older bash compatibility)
warn "Running $CLI with ${TIMEOUT}s timeout (min: ${MIN_REVIEW_TIMEOUT}s)"
exec timeout "${TIMEOUT}s" "$CLI_BIN" ${EXTRA_ARGS[@]+"${EXTRA_ARGS[@]}"} "$@"
#!/usr/bin/env bash
# smoke-wrappers.sh - lightweight behavior checks for wrapper scripts
set -euo pipefail
# Ensure standard tools are available on NixOS
export PATH="$PATH:/run/current-system/sw/bin"
SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
tmp_dir="$(mktemp -d)"
trap 'rm -rf "$tmp_dir"' EXIT
fake_bin="$tmp_dir/bin"
mkdir -p "$fake_bin"
cat >"$fake_bin/timeout" <<'EOF'
#!/usr/bin/env bash
set -euo pipefail
if [[ $# -lt 2 ]]; then
exit 2
fi
shift
exec "$@"
EOF
cat >"$fake_bin/codex" <<'EOF'
#!/usr/bin/env bash
set -euo pipefail
: "${SMOKE_CODEX_ARGS_FILE:?}"
{
for arg in "$@"; do
printf '%s\n' "$arg"
done
} >"$SMOKE_CODEX_ARGS_FILE"
cat <<'PLAN'
# Plan: Smoke test
## Fast-Path
- Eligible: yes
- Reason: test
## 1. Problem statement
x
## 2. Current state evidence
- Files:
- `README.md#L1-L1` — test
- Commands run:
- `rg foo`
- Observations:
- test
## 3. Proposed approach
x
## 4. Step-by-step change list
1. a
2. b
## 5. Risks + rollback
- Risks:
- r
- Rollback:
- `git restore .`
## 6. Test plan
- Automated:
- `echo ok`
- Manual:
- check
- Success criteria:
- ok
## 7. Out-of-scope
- none
## 8. Approval prompt
Reply with one:
- `APPROVE: smoke`
- `REVISE: tweak`
PLAN
exit 0
EOF
cat >"$fake_bin/claude" <<'EOF'
#!/usr/bin/env bash
set -euo pipefail
: "${SMOKE_CLAUDE_ARGS_FILE:?}"
{
for arg in "$@"; do
printf '%s\n' "$arg"
done
} >"$SMOKE_CLAUDE_ARGS_FILE"
exit 0
EOF
chmod +x "$fake_bin/timeout" "$fake_bin/codex" "$fake_bin/claude"
assert_contains() {
local file="$1"
local expected="$2"
if ! grep -Fq -- "$expected" "$file"; then
printf 'Assertion failed: expected "%s" in %s\n' "$expected" "$file" >&2
printf '--- file content ---\n' >&2
cat "$file" >&2
exit 1
fi
}
test_invalid_mode_rejected() {
local output="$tmp_dir/invalid-mode.txt"
if "$SCRIPT_DIR/safe-fallback.sh" bad-mode "prompt" >"$output" 2>&1; then
printf 'Expected safe-fallback.sh to reject invalid mode\n' >&2
exit 1
fi
assert_contains "$output" "invalid mode"
}
test_invalid_cli_rejected() {
local output="$tmp_dir/invalid-cli.txt"
if "$SCRIPT_DIR/safe-review.sh" bad-cli >"$output" 2>&1; then
printf 'Expected safe-review.sh to reject invalid CLI\n' >&2
exit 1
fi
assert_contains "$output" "Unknown CLI"
}
test_review_prompt_pass_through() {
local prompt="Review this PR thoroughly: preserve this custom prompt text and include edge-case notes for wrappers 1234567890."
local title="${prompt:0:100}"
local codex_args="$tmp_dir/codex-args.txt"
local output="$tmp_dir/review-pass-through.txt"
PATH="$fake_bin:$PATH" \
SMOKE_CODEX_ARGS_FILE="$codex_args" \
"$SCRIPT_DIR/safe-fallback.sh" review "$prompt" >"$output" 2>&1
assert_contains "$codex_args" "review"
assert_contains "$codex_args" "--title"
assert_contains "$codex_args" "$title"
assert_contains "$codex_args" "$prompt"
}
test_invalid_impl_mode_rejected() {
local output="$tmp_dir/invalid-impl-mode.txt"
if CODING_AGENT_IMPL_MODE=invalid "$SCRIPT_DIR/safe-fallback.sh" impl "prompt" >"$output" 2>&1; then
printf 'Expected safe-fallback.sh to reject invalid CODING_AGENT_IMPL_MODE\n' >&2
exit 1
fi
assert_contains "$output" "Invalid CODING_AGENT_IMPL_MODE"
}
test_impl_direct_mode_uses_codex_exec() {
local prompt="Implement feature with direct mode fallback check."
local codex_args="$tmp_dir/codex-impl-args.txt"
local output="$tmp_dir/impl-direct.txt"
PATH="$fake_bin:$PATH" \
CODING_AGENT_IMPL_MODE=direct \
SMOKE_CODEX_ARGS_FILE="$codex_args" \
"$SCRIPT_DIR/safe-fallback.sh" impl "$prompt" >"$output" 2>&1
assert_contains "$codex_args" "--yolo"
assert_contains "$codex_args" "exec"
assert_contains "$codex_args" "$prompt"
}
test_code_plan_generates_artifact() {
local repo="$tmp_dir/repo"
local codex_args="$tmp_dir/codex-plan-args.txt"
mkdir -p "$repo"
git -C "$repo" init -q
git -C "$repo" config user.email smoke@example.com
git -C "$repo" config user.name smoke
echo "hi" > "$repo/README.md"
git -C "$repo" add README.md
git -C "$repo" commit -q -m "init"
PATH="$fake_bin:$PATH" \
SMOKE_CODEX_ARGS_FILE="$codex_args" \
"$SCRIPT_DIR/code-plan" --engine codex --repo "$repo" --base main "smoke plan request" > "$tmp_dir/code-plan.out"
local plan_file
plan_file="$(find "$repo/.ai/plans" -maxdepth 1 -type f -name '*.md' | head -1)"
[[ -n "$plan_file" && -f "$plan_file" ]] || { echo "Expected plan file" >&2; exit 1; }
assert_contains "$codex_args" "--sandbox"
assert_contains "$codex_args" "read-only"
assert_contains "$codex_args" "--ephemeral"
assert_contains "$plan_file" "status: PENDING"
assert_contains "$plan_file" "## 8. Approval prompt"
}
test_safe_impl_claude_plan_mode_no_dangerous_skip() {
local repo="$tmp_dir/repo-claude"
local claude_args="$tmp_dir/claude-args.txt"
mkdir -p "$repo"
git -C "$repo" init -q
git -C "$repo" config user.email smoke@example.com
git -C "$repo" config user.name smoke
echo "hi" > "$repo/README.md"
git -C "$repo" add README.md
git -C "$repo" commit -q -m "init"
git -C "$repo" checkout -q -b feat/test
(
cd "$repo"
PATH="$fake_bin:$PATH" \
SMOKE_CLAUDE_ARGS_FILE="$claude_args" \
TIMEOUT=10 \
"$SCRIPT_DIR/safe-impl.sh" claude -p --permission-mode plan "plan only"
) > "$tmp_dir/safe-impl-claude.out" 2>&1
if grep -Fq -- "--dangerously-skip-permissions" "$claude_args"; then
echo "Expected no dangerous-skip flag in plan permission mode" >&2
exit 1
fi
}
test_invalid_mode_rejected
test_invalid_cli_rejected
test_review_prompt_pass_through
test_invalid_impl_mode_rejected
test_impl_direct_mode_uses_codex_exec
test_code_plan_generates_artifact
test_safe_impl_claude_plan_mode_no_dangerous_skip
printf 'Wrapper smoke tests passed.\n'
#!/usr/bin/env bash
# tmux-run - Run a command inside tmux with logging and monitoring hints
# Usage: tmux-run [--wait] [--cleanup] <command...>
set -euo pipefail
# Ensure standard tools are available on NixOS
export PATH="$PATH:/run/current-system/sw/bin"
usage() {
cat >&2 <<EOF
Usage: tmux-run [--wait] [--cleanup] <command...>
Options:
--wait Block until the command finishes (signals via tmux wait-for)
--cleanup Kill the tmux session after completion (implies --wait)
Environment:
CODEX_TMUX_WAIT=1 Same as --wait
CODEX_TMUX_CLEANUP=1 Same as --cleanup
CODEX_TMUX_WAIT_TIMEOUT= Optional seconds to bound --wait
EOF
}
WAIT="${CODEX_TMUX_WAIT:-0}"
CLEANUP="${CODEX_TMUX_CLEANUP:-0}"
while [[ $# -gt 0 ]]; do
case "$1" in
--wait) WAIT=1; shift ;;
--cleanup) CLEANUP=1; shift ;;
-h|--help) usage; exit 0 ;;
--) shift; break ;;
*) break ;;
esac
done
if [[ "$CLEANUP" == "1" && "$WAIT" != "1" ]]; then
WAIT=1
fi
if [[ $# -lt 1 ]]; then
usage
exit 1
fi
if ! command -v tmux &>/dev/null; then
echo "Error: tmux not found in PATH" >&2
exit 1
fi
SOCKET_DIR="${CODEX_TMUX_SOCKET_DIR:-${OPENCLAW_TMUX_SOCKET_DIR:-${CLAWDBOT_TMUX_SOCKET_DIR:-${TMPDIR:-/tmp}/openclaw-tmux-sockets}}}"
mkdir -p "$SOCKET_DIR"
SOCKET="${CODEX_TMUX_SOCKET:-$SOCKET_DIR/openclaw.sock}"
SESSION_PREFIX="${CODEX_TMUX_SESSION_PREFIX:-codex}"
ts="$(date +%Y%m%d-%H%M%S)"
ns="$(date +%N 2>/dev/null || true)"
if [[ "$ns" =~ ^[0-9]+$ ]]; then
ts="${ts}-${ns}"
fi
SESSION="${CODEX_TMUX_SESSION:-${SESSION_PREFIX}-${ts}-${RANDOM}-$$}"
LOG_DIR="${CODEX_TMUX_LOG_DIR:-${XDG_STATE_HOME:-$HOME/.local/state}/openclaw/tmux}"
mkdir -p "$LOG_DIR"
LOG_FILE="$LOG_DIR/${SESSION}.log"
: > "$LOG_FILE"
EXIT_FILE="$LOG_DIR/${SESSION}.exit"
if ! tmux -S "$SOCKET" new-session -d -s "$SESSION" -n shell; then
echo "Error: Failed to create tmux session on socket: $SOCKET" >&2
exit 1
fi
tmux -S "$SOCKET" set-option -t "$SESSION" remain-on-exit on
# Resolve the actual first pane target. Do not assume :0.0 because tmux
# base-index and pane-base-index can be non-zero (for example 1.1).
FIRST_WINDOW="$(tmux -S "$SOCKET" list-windows -t "$SESSION" -F '#{window_index}' 2>/dev/null | head -n 1 || true)"
if [[ -z "$FIRST_WINDOW" ]]; then
tmux -S "$SOCKET" kill-session -t "$SESSION" || true
echo "Error: Failed to resolve tmux window index for session: $SESSION" >&2
exit 1
fi
FIRST_PANE="$(tmux -S "$SOCKET" list-panes -t "${SESSION}:${FIRST_WINDOW}" -F '#{pane_index}' 2>/dev/null | head -n 1 || true)"
if [[ -z "$FIRST_PANE" ]]; then
tmux -S "$SOCKET" kill-session -t "$SESSION" || true
echo "Error: Failed to resolve tmux pane index for session: $SESSION" >&2
exit 1
fi
TARGET="${SESSION}:${FIRST_WINDOW}.${FIRST_PANE}"
if ! tmux -S "$SOCKET" pipe-pane -t "$TARGET" -o "cat >> \"$LOG_FILE\""; then
tmux -S "$SOCKET" kill-session -t "$SESSION" || true
echo "Error: Failed to attach pipe-pane for logging" >&2
exit 1
fi
cmd_str=$(printf '%q ' "$@")
cmd_str="${cmd_str% }"
if [[ "$WAIT" == "1" ]]; then
cmd_str="$cmd_str; __tmux_run_rc=\$?; printf '%s\n' \"\${__tmux_run_rc}\" > \"$EXIT_FILE\"; tmux -S \"$SOCKET\" wait-for -S \"$SESSION.done\""
fi
if ! tmux -S "$SOCKET" send-keys -t "$TARGET" -l -- "$cmd_str"; then
echo "Error: Failed to send command text to tmux session" >&2
exit 1
fi
if ! tmux -S "$SOCKET" send-keys -t "$TARGET" Enter; then
echo "Error: Failed to send Enter key to tmux session" >&2
exit 1
fi
cat >&2 <<EOF
tmux session started.
Socket: $SOCKET
Session: $SESSION
Log: $LOG_FILE
Mode: $([[ "$WAIT" == "1" ]] && echo "blocking (--wait)" || echo "non-blocking")
To monitor:
tmux -S "$SOCKET" attach -t "$SESSION"
tmux -S "$SOCKET" capture-pane -p -J -t "$TARGET" -S -200
tail -f "$LOG_FILE"
EOF
if [[ "$WAIT" == "1" ]]; then
wait_timeout="${CODEX_TMUX_WAIT_TIMEOUT:-}"
if [[ -n "$wait_timeout" ]]; then
if command -v timeout &>/dev/null; then
if ! timeout "${wait_timeout}s" tmux -S "$SOCKET" wait-for "$SESSION.done"; then
echo "Warning: wait timed out after ${wait_timeout}s" >&2
exit 1
fi
else
echo "Warning: timeout command not found; waiting without timeout" >&2
tmux -S "$SOCKET" wait-for "$SESSION.done"
fi
else
tmux -S "$SOCKET" wait-for "$SESSION.done"
fi
# Dump pane content to stdout so callers can capture it
tmux -S "$SOCKET" capture-pane -p -J -t "$TARGET" -S - 2>/dev/null || true
if [[ -f "$EXIT_FILE" ]]; then
rc="$(cat "$EXIT_FILE" 2>/dev/null || echo 1)"
if [[ ! "$rc" =~ ^[0-9]+$ ]]; then
echo "Warning: Invalid exit code in $EXIT_FILE (got: $rc)" >&2
rc=1
fi
else
echo "Warning: Exit code file not found: $EXIT_FILE" >&2
rc=1
fi
if [[ "$CLEANUP" == "1" ]]; then
tmux -S "$SOCKET" kill-session -t "$SESSION" || true
fi
exit "$rc"
fi
0.1.0