π€ Codex Rig β Native Codex Workflows and Specialist Roles¶
Codex Rig is the OpenAI Codex product in Borda's AI-Rig. It packages 13 reusable workflow skills, one lifecycle-manager skill, 15 canonical specialist role cards, shared quality gates, calibration, and an optional health hook as one Apache-2.0-licensed plugin.
Calibration measures instruction quality against synthetic cases. It is not evidence that any individual run is correct.
The package covers the capabilities Codex can currently install and verify. It contains no MCP server and no native bundled agent registrations. Parallel work uses a runtime blank agent with the exact role card injected when that route is available; an inline role pass is the serial fallback. Persistent named-agent routing remains platform-blocked until Codex exposes a verifiable custom-agent selector. The split schema, approval allowlist, synchronization gates, runtime evidence, telemetry, fallback, and promotion lifecycle are defined in ARCHITECTURE.md.
Current release:
0.13.0. Codex Rig is a peer product to foundry, oss, develop, research, and codemap-pyβnot a copy of the repository's.codex/configuration.
Navigation
- [What Codex Rig adds](#-what-codex-rig-adds) - [Requirements and installation](#-requirements) - [Quick start](#-quick-start) - [Skills and specialist roles](#-skills) - [Quality, review, and calibration](#-quality-gates-and-artifacts) - [Update, uninstall, and safety limits](#-update-or-reinstall) - [Package layout and verification](#-package-layout)Value at a glance: install one independently verifiable plugin to get evidence-backed workflows, bounded specialist role cards, portable fallbacks, and auditable artifacts without pretending Codex has native persistent-agent selection.
Current limits at a glance: named-agent shim installation remains platform-blocked; networked workflows require runtime approval; Codex CLI, Python 3.10+, and optional
gh/Kaggle authentication are needed for their respective paths; shim mutation is unsupported on Windows and network/distributed filesystems.
π― What Codex Rig adds¶
- A complete development loop: investigate, change-analysis, implement, review, remediate, optimize, release, and audit with measurable gates.
- Specialist depth without a permanent agent install: exact packaged role cards can guide independent blank agents or inline passes.
- Bounded context: each specialist receives a narrow context pack instead of the whole parent thread.
- Evidence-backed completion: workflows write comparable artifacts under
.reports/codex/<skill>/<timestamp>/, validate a digest-bound final response after gates, and disclose failed gates and confidence limits. - Auditable commit handoffs: every proposed or created commit records all meaningful changes, concrete impacts, executed verification, and residual limits in the commit body.
- Cold PR review and remediation:
$code-review #123and$code-remediate #123 +reviewpreserve current PR evidence and local merge context. - Scoped network access: shell networking stays blocked by default; workflows request one runtime approval for the complete command owning each intentional GitHub, Kaggle, marketplace-refresh, or paid live-calibration operation.
- Calibration: fixed and behavioral checks measure recall, precision, confidence accuracy, routing leaks, stale assumptions, fixture misuse, unjustified local imports, and incomplete abstractions.
- Safe legacy cleanup: authenticated, exact-plan removal exists for thin shims created during pre-release development.
- Optional codemap-py structural context: the
implement,investigate, andoptimizeworkflows select a task-neutral route and probe the public codemap-py CLI once per run for only the required structural fact, or record a zero-query decision for a localized edit; they persist one artifact and fall back to bounded file inspection when Codemap is absent.
β Requirements¶
- Codex CLI with plugin support
- Python 3.10+
- GitHub CLI (
gh) installed and authenticated for complete PR review, checkout, and private evidence; public metadata fallback remains limited - Kaggle CLI installed and authenticated for grounded Kaggle workflows; when it is missing, Codex Rig only explains the user-owned setup and never installs it
- Public GitHub access for a Git marketplace install or refresh
- Windows, macOS, or Linux for workflows, package verification, sync, and read-only diagnostics
- A POSIX local filesystem only for authenticated legacy agent-shim cleanup
No official marketplace is assumed. Local, unpushed changes are not installable from GitHub.
Codex Rig never enables persistent workspace network access. In a network-sandboxed runtime, invoking a networked workflow authorizes the plugin to request a narrow runtime approval for the complete owning command; the user/runtime still grants or denies the prompt. Approving only gh, kaggle, or another nested executable is insufficient when a Python helper owns its subprocesses and HTTPS traffic.
Approval and denial behavior: the brief names the operation's purpose, capability and effects, target, owning command, and denial outcome. If approval is denied, the current tool call stops and the assistant turn may end; the external command is not run, and Codex Rig does not issue an equivalent reprompt or silently broaden the fallback. To continue, send a new message. Separate operations with materially different effects, such as a GitHub read and a local checkout or lifecycle mutation, remain separate approvals.
π¦ Install from GitHub¶
codex plugin marketplace add Borda/AI-Rig
# Optional reproducible release pin:
# codex plugin marketplace add Borda/AI-Rig --ref codex-rig-v0.4.0
codex plugin add codex-rig@borda-ai-rig
The primary command follows the GitHub repository's default branch. The commented form pins immutable release bytes.
Start a fresh Codex session. Codex discovers the plugin's skills/ and default hooks/hooks.json; plugin hooks run only after their current definition is reviewed and trusted.
Verify the install in a fresh session:
doctor verifies the active package, manifest, helpers, role cards, and legacy shim state without writing. The audit workflow checks the consuming repository and reports concrete gaps. Skill/all audits also emit prompt-efficiency evidence: matched instruction cost, loaded-reference cost, obligation preservation, behavioral/calibration guards, and adversarial review. axis=value-per-token accepts a candidate only with matched native/tokenizer evidence, no hard-guard regression, and the declared material cost reduction; length or byte count alone cannot establish quality.
π Managed global instructions¶
Global-instruction behavior and sync commands
`assets/AGENTS.md` is a versioned template, not an automatically installed plugin capability. Its policy requires the following: - **Implementation:** Use the simplest solution for verified current behavior; prefer maintained standard-library/native/already-installed package functionality over duplicating custom code; reject machinery justified only by hypothetical future states, risks, scale, reuse, or edge cases; and preserve trust-boundary, data-loss, security, accessibility, and explicit-contract safeguards. - **Abstractions and imports:** Abstractions must reduce reader-visible concepts, and Python imports stay at module scope unless a verified boundary requires locality. - **Fixtures and simplification:** Fixtures provide concrete state unless fixture-managed lifecycle requires a callable; use ordinary helpers for configurable construction instead of nested fixture factories or aliases that add no meaning. A deliberately bounded simplification records its present ceiling and observable revisit trigger without creating a separate debt system. The sync paths differ as follows: | Operation | Explicit behavior | | ------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Direct marketplace/plugin installation | Leaves `${CODEX_HOME:-$HOME/.codex}/AGENTS.md` unchanged and does not project repository `.codex/` settings. | | Direct `plugins/codex-rig/scripts/sync_codex.py` | Installs or updates the managed Codex plugins and authenticated Codex Rig block only; it does not project repository model defaults or personal policy. | | Root `make sync-codex` | Additionally projects the root `model` and `review_model` from `.codex/config.toml` and the authenticated personal-policy block from `.codex/global-session-policy.md`. | The current repository policy keeps the parent session on Terra and permits Sol only for an explicitly requested advisory pass or explicitly selected Sol agent. From an AI-Rig checkout: Native Codex-only restore and teardown need no Bash or `jq`: `make sync-claude` changes only Claude scope, and `make sync-codex` changes only Codex scope; host selection does not otherwise alter refresh or clean-install semantics. Claude sync manages foundry, oss, develop, research, codemap-py, and `bridge`; it refreshes only the retained external caveman plugin. After the bridge installs successfully, sync removes any installed copy of the retired external Codex rescue plugin; a failed bridge install preserves it for recovery. The retired plugin and its marketplace are never installed or refreshed. Codex sync removes its managed plugins by default, refreshes an existing Git marketplace or replaces a non-Git registration with the canonical `Borda/AI-Rig` Git source, and then reinstalls all managed plugins. Codex sync then runs the installed Bridge static doctor: it requires the `python` launcher used by MCP to report Python 3.10 or newer and checks the Claude CLI help contract without model inference, authentication changes, or provider cost. MCP inventory and workspace binding remain per fresh Codex project session. Codex sync always removes managed plugins before reinstalling and always tracks the marketplace default branch; the earlier `--no-clean` and `--codex-ref` flags that varied this are gone β there is no flag-level override for either behavior anymore. The direct `sync_codex.py clear` action removes the managed Codex plugins and strips only the authenticated Codex Rig block from `${CODEX_HOME:-$HOME/.codex}/AGENTS.md`; it leaves repository-projected model defaults and personal policy untouched. Root `make clear-all` reverses the selected Claude/Codex installation: it also uninstalls this marketplace's Claude plugins when Claude scope is active, strips the Codex Rig block, and leaves repository model defaults and personal-policy state in place; `make clear-codex` and `make clear-claude` scope the same teardown to one side only. Both commands keep a timestamped backup and preserve user-owned content byte-for-byte, honor `claude`/`codex` scoping where applicable, and leave marketplace registrations plus external plugins in place. A tampered managed block makes the strip fail without writing, exactly like install. Codex sync uses the template from the installed marketplace revision. A missing global file is created as one SHA-256-authenticated managed block. Existing user instructions are backed up and preserved byte-for-byte outside that block. An exact unmarked copy from an older sync is adopted without duplication. Later runs update only an unmodified managed block and otherwise fail without writing when markers are missing, duplicated, malformed, or manually changed. Marketplace/plugin refresh can finish before a later global-instruction merge fails; resolve the reported target state and rerun sync. Avoid concurrent edits during restoration. The installer rechecks observed bytes immediately before atomic replacement, but portable filesystems provide no universal compare-and-swap operation. Project `AGENTS.md` files remain project-owned and are never changed. Review merged instructions for semantic conflicts; byte preservation cannot resolve contradictory policies.β‘ Quick start¶
Skills can be invoked explicitly with $codex-rig:<skill> or selected implicitly when the request matches their description.
$codex-rig:investigate find the root cause of this Windows-only CI failure
$codex-rig:implement apply the verified fix and run relevant gates
$codex-rig:code-review review the current diff with no prior assumptions
$codex-rig:code-remediate close the high-severity findings
$codex-rig:release assess release readiness for the current package
For PR work:
A bare PR number, #number, PR URL, or natural-language PR target refreshes current online PR items and the verified local checkout directly, so it does not require an assessed review artifact. Add +review (or another report alias or an explicit report path) when remediation should combine a matching assessed review report with refreshed online PR evidence.
To remediate the latest assessed review created in the current session without refreshing PR evidence or online comments:
When the same invocations are passed from a shell, quote them so $ is not expanded:
codex '$codex-rig:code-review #123'
codex '$codex-rig:code-remediate #123'
codex '$codex-rig:code-remediate #123 +review'
codex '$codex-rig:code-remediate review'
π§ Skills¶
Skill frontmatter uses compact routing descriptions to conserve the Codex skills catalog; each
SKILL.mdbody remains the complete workflow contract.
Codex Rig installs 14 skills: 13 workflows plus the legacy shim manager.
| Skill | Purpose |
|---|---|
change-analysis |
Inspect an issue, PR, module, or problem before implementation; emit ranked findings and gates. |
audit |
Detect configuration, workflow, routing, documentation, prompt-efficiency, and quality-gate drift. |
calibrate |
Run fixed and behavioral checks across packaged skills and roles; score recall, precision, and confidence accuracy. |
code-remediate |
Triage review findings, select valid work, assign owners/verifiers, apply fixes, and prove closure. |
code-review |
Close a PR at an evidence-backed proposal gate or review its local diff across mandatory and risk-triggered axes. |
implement |
Run the linear, serial-default plan-build-verify implementation loop with measurable acceptance gates. |
investigate |
Debug code and narrow unknown failures to an evidence-backed root cause before implementation. |
kaggle |
Create or extend grounded Jupytext Kaggle notebooks, grounding schema via the authenticated kaggle CLI. |
manage |
Safely create, update, or remove Codex skills, agent configuration, and related references under serial authority. |
optimize |
Measure first, change one bounded variable, remeasure, and reject regressions. |
release |
Assess SemVer, changelog, migration, packaging, and release readiness. |
research |
Collect current primary evidence and map findings to concrete implementation choices. |
sync |
Inspect active plugin-cache drift or refresh the public-GitHub Codex Rig installation without cache edits. |
agent-shims |
Diagnose and remove authenticated thin shims from pre-release development; new installation stays blocked. |
Every workflow defines an input contract, fail-fast rules, required gates, artifact shape, and confidence output. shared/quality-gates.md owns the compact outcome-coupled final-chat frameβOutcome, Results, Verification, Remaining, Recommendations / next steps, Confidence, Artifactβwhile shared/final-handoff-contract.md makes that structure executable after gates: schema-v2 results bind the validated final-handoff.json, rendered final.md, and digest record before promotion, and the workflow emits final.md verbatim. Rendered section and table labels use portable Markdown bold text instead of headings or terminal color escapes. Each skill keeps its exact outcome vocabulary, result table, and terminal exceptions; next steps reference result rows instead of repeating them, and artifacts supplement rather than replace the readable result. Historical schema-v1 artifacts remain readable. agent-shims stays the explicit exception because it has no canonical run/result artifact, and the current host still has no post-send transcript hook to prove chat transport bytes. shared/native-skill-contract.md likewise owns generic shell-network approval and denial behavior while each networked skill retains its five concrete operation values and recovery exceptions. Workflow instructions live in skills/<name>/SKILL.md; shared executable contracts live in shared/.
π Optional codemap-py structural context¶
Bounded Codemap integration and fallback vocabulary
`implement`, `investigate`, and `optimize` select a route and probe the [codemap-py](https://github.com/Borda/AI-Rig/tree/main/plugins/codemap-py) plugin once at a bounded decision point via `shared/codemap_adapter.py`, then persist the result to the run artifact β specialists consume that artifact, never a fresh query. An exact localized edit with no unresolved structural fact uses `skip`; one unresolved fact uses the matching single route; broad or unknown scope uses the legacy `standard` batch; an explicit structural request overrides `skip`. The other workflows retain their existing category-specific standard behavior or recorded not-applicable status. The adapter reads only the public `codemap-py doctor --json`/`query` CLI surface, never codemap-py's cache internals, source paths, or a cross-plugin Python import. The adapter reports one named status: `available`, `absent`, `stale`, `incompatible`, `degraded`, `stale+degraded`, or `skipped`. `skipped` means the workflow deliberately selected zero Codemap subprocesses; it is not structural evidence. `stale+degraded` is the vocabulary's only composed value and means both caveats hold at once, so neither masks the other. A standard batch run without `--target` omits the queries that require one instead of failing them, so a targetless probe reports the honest status of the queries it actually ran. Each query also records the index file that answered it, and any disagreement with the path the health probe resolved is listed under `index_path_divergence` as evidence β both paths retained, never reconciled, and never folded into the status. Absence and incompatibility are non-fatal β the workflow falls back to its normal bounded file inspection. `manage`, `sync`, `agent-shims`, `calibrate`, and `kaggle` stay not-applicable with a recorded behavioral reason (no Python call-graph subject); see `shared/codemap-contract.md` for the full protocol, adaptive route vocabulary, category-to-query map, per-skill route selection, and not-applicable rationale. Repository sync installs Codemap alongside Codex Rig, but Codex Rig retains zero runtime dependency on it: packaging, skill discovery, and startup still work when Codemap is absent or incompatible.π€ Specialist role cards¶
Roles are canonical behavioral profiles, not claims that Codex selected a custom agent configuration. Each card includes trigger/skip boundaries, evidence ownership, execution constraints, handover fields, and confidence rules.
When several independent role passes are justified, Codex Rig fixes their routes and narrow context packs first, dispatches the approved work in one wave when the runtime supports it, and joins every handoff before parent acceptance. The installed shared/parallel_execution.py validator derives parallel only from overlapping substantive intervals recorded in one manifest wave; completed spawned passes without overlap are independent-spawned, while unsafe or unavailable fan-out is serial-fallback with equal gates. Schema-v1 manifests remain readable for historical structural checks only; generic runtime promotion requires schema-v2 and a non-sensitive portable-read-restricted plan/manifest. That runtime evidence binds the frozen parent plan, parent spawn/start, child lineage, persisted restricted controls and approval never, terminal interval, exact output, parent result-delivery event, and context/output common-secret scans to the currently observed Codex rollout shape; filesystem credential isolation remains unverified. The summary does not claim global network, command, credential, or filesystem denial or that all command behavior was inspected. Generic parallel writes and the future host-isolated tier remain unavailable; code-remediate-local has a separate production lifecycle described below. That shape and its timestamp units are internal rather than a documented platform guarantee, so drift fails closed. It never starts a second wave for the same parent work item; new discoveries stay parent-serial or require a user-visible re-plan. Scheduling never expands fan-out, overlaps ownership, bypasses approval, treats requested-only controls as enforced, or accepts unjoined output.
The staged activation contract uses --execution=serial|parallel-read|parallel-write|auto, which avoids ambiguity with positional task text. An explicit invocation value wins over CODEX_RIG_EXECUTION, which wins over the shipped phase default. The default remains serial during staged rollout and changes to auto only after every general-availability gate passes; until each skill adopts the resolver, these values are a shared contract rather than a universal CLI surface. A launch-wide future default can be selected with CODEX_RIG_EXECUTION=auto codex, while one opted-in invocation can request --execution=parallel-read. Neither auto, the environment, nor --execution=parallel-write grants write authority: the exact digest-bound write plan still needs its separate approval, and unpromoted modes fail closed or report an equal-gate serial fallback.
implement and manage now document their prospective P4 read-only splits, freeze/join barriers, resource conflicts, serial parent decisions, equal-gate fallback, and stop rules. This is declaration-only: neither skill dispatches parallel work from that section, every mutation and canonical quality gate remains parent-serial, and generic writes remain disabled. Native Linux and Windows P3b evidence, separate user promotion, and each consumer's shared runtime matrix must pass before runtime opt-in; flags, CODEX_RIG_EXECUTION, auto, or natural-language requests cannot bypass those gates.
shared/parallel_telemetry.py provides privacy-minimized timing and token accounting for later rollout analysis. It retains HMAC identifiers, counters, declared outcomes, child timing, workload-key digests, and explicit dispatch-to-final-join duration; it excludes prompts, messages, reasoning, tool data, paths, environments, credentials, and raw runtime IDs. Saved wall time, speedup, and token multiplier remain unavailable until serial and parallel attempts carry the same normalized workload digest and authoritative wall-time envelope. Child-duration maxima are diagnostic proxies only and never support a savings claim.
Each future parallel wave must freeze a positive token-admission ceiling and positive per-node reservations before dispatch. Completed and active reservations must form a stable prefix and remain charged; admission stops before the first node that would exceed the ceiling, active children finish to terminal evidence, and all unstarted nodes are serially re-planned with the same gates. Schema-v2 runtime acceptance binds each wave and spawned node to token_budgets in the exact hashed plan. Pre-P5 schema-v2 evidence can be read only with historical_unbudgeted=True; that result is acceptance-blocked and promotion-ineligible, while the default path remains budget-required. This bounds admitted reservations, not actual provider usage: the current host exposes no enforceable child token cap, so compact telemetry reports any actual overrun. Retained wave proof uses HMAC identity, a proof digest, and bounded status/counters. The helper emits a policy for diagnostics to expire 30 days after success or resolution and for unresolved failed, cancelled, or conflicted diagnostics to remain until resolution; it does not persist or delete files, so the future storage consumer must enforce that policy before P5/GA promotion. Unknown or raw fields fail closed.
Operator rollback is deliberately procedural:
- Disable the affected skill's parallel opt-in without changing the frozen plan or its digest.
- Preserve completed outputs, terminal child evidence, parent joins, and the original quality gates.
- Serially execute only unfinished work; never replay completed nodes.
- Retain failed or conflicted worktrees and stop when cleanup or repository state is ambiguous.
shared/parallel_worktrees.py is a bounded P3a generated-fixture scaffold, not a production write route. The active parent freezes exactly two disjoint work packages at one clean HEAD, creates separate detached worktrees, dispatches both subagents, and joins exactly two child reports containing node ID, completed status, concise summary, exact changed paths, and canonical Git patch SHA-256. A completed child obtains that fixed-shape report through create_completed_child_handover, which hashes raw Git subprocess bytes through the lifecycle module rather than shell- or RTK-rendered diff output. The parent verifies both reports against the actual worktrees before deriving patches, integrates them in stable order, and cleans successful worktrees without force only after durable evidence. It strips inherited GIT_* redirection overrides, rederives managed authority before every transition, fingerprints declared retained attempts, and rejects source drift, commits, staged/untracked/undeclared/delete/rename/mode/type changes, aliases, ownership ancestry, symlinks, partial joins, report mismatches, conflicts, and cleanup uncertainty.
The retained record is an operational audit trail under parent authority, not cryptographic host attestation. P3a does not claim a particular child tool, child authorship, edit-time overlap, native-Windows Git lifecycle coverage, or production eligibility. It keeps write_parallel_eligible=false, write_parallel_promoted=false, the default serial, and every generic production route disabled. App Server readers, brokers, sidecars, signed receipts, and full-thread filtering are intentionally unnecessary.
Code-remediate-local has a separate accepted production lifecycle, not a generic resolver promotion. Its exact schema-v2 plan and approval bind one clean authoritative source repository and exact HEAD/tree, two to four disjoint buckets, actual context-pack paths and SHA-256 values, resource locks, detached worktrees under only the external sibling root .codex-rig-worktrees/<run-id> outside that checkout, a fixed new state basename and output names under the source-local run root, the fixed code-remediate-shared-quality-gates reference, rollback policy, and non-force cleanup policy. Plan, approval, state, patch, rollback, and lifecycle artifacts stay in the authoritative repository's normal .reports/codex/code-remediate/... run directory. Preparation and every authority transition re-hash each actual context pack and reject drift. The thin argparse sequence is prepare, create-handover, join, collect, integrate, apply-source, and cleanup; it is not a scheduler, registry, or global promotion mechanism. The parent prepares the worktrees; children edit only their owned paths, do not commit, and return canonical terminal status, summary, changed paths, and patch SHA-256. The parent re-derives patches, joins every terminal handover, integrates them in lexical bucket order in a separate integration worktree, and records only Git-structural integration as structurally-verified; it does not execute arbitrary plan-provided commands. After source application, the existing shared quality-gate phase remains the executable result authority and its validated gates.json is required for a passing remediation result.
Source application rechecks exact raw integration postimages, captures raw source preimages, stores a durable reverse patch, applies one parent-generated forward source bundle, and verifies expected Git content after the authoritative worktree's clean filters. The lifecycle records raw source SHA-256 postimages for cleanup and evidence, while Git clean-filtered object identities allow LF and CRLF worktree bytes to represent the same repository content across native platforms. Only known Git-content states may be restored after recomputing affected identities and confirming each path is at its recorded preimage or expected postimage; a mismatch, filter failure, restore error, or failed recomputation records rollback-ambiguous, retains worktrees and evidence, and stops without automatic restore. Non-force cleanup occurs only after durable source application and exact recorded source postconditions, and failures retain evidence. The artifact validator independently re-hashes every child patch, forward source bundle, and rollback patch beneath the exact run root, while source, worktree, evidence-root, state, output, and patch path components reject symlinks and path escapes. The schema-v2 lifecycle record and digest are bound into the remediation result; schema-v1 plans are planning-only and cannot prove completed execution. Containment is parent-authoritative operational postcondition containment with capability_sandbox_verified=false, not a per-child capability sandbox, hostile-child security boundary, globally atomic source transaction, or security isolation guarantee. Separately sandboxed processes remain a future stronger alternative, not a current prerequisite.
The local macOS production pilot completed the full lifecycle and rollback proof. Installed-package acceptance now runs the same lifecycle suite from manifest-declared payload, and the repository's existing full-test matrix executes that gate on Linux, macOS, and native Windows. P3b is not promoted until the exact candidate has green native Linux and Windows evidence. CI configuration, a previous local pilot, auto, an environment value, or --execution=parallel-write never substitutes for a newly frozen consumer plan and exact-digest write approval.
| Role | Requested model | Primary axis |
|---|---|---|
delegation-lead |
Luna | Cost-aware workstream routing and consolidated handover. |
sw-engineer |
Terra | Core implementation, APIs, types, and reproducible Python/ML code. |
qa-specialist |
Terra | Regression proof, edge cases, test design, and executable acceptance. |
squeezer |
Terra | Profile-first performance, throughput, memory, and synchronization analysis. |
doc-scribe |
Luna | User documentation, docstrings, examples, changelogs, and migration guidance. |
security-auditor |
Sol | Auth, permissions, secrets, deserialization, supply chain, and trust boundaries. |
data-steward |
Terra | Dataset integrity, leakage, splits, augmentation, and reproducibility. |
cicd-steward |
Luna | CI/CD, matrices, caching, publishing, and flaky-run diagnosis. |
linting-expert |
Luna | Ruff, mypy, pre-commit, suppressions, and static-analysis policy. |
oss-shepherd |
Luna | OSS triage, SemVer, deprecations, contributor workflow, and release readiness. |
solution-architect |
Sol | System design, public contracts, coupling, compatibility, and migrations. |
web-explorer |
Luna | Current external documentation, changelogs, and migration evidence. |
curator |
Terra | Configuration quality, duplication, drift, stale references, and weak gates. |
challenger |
Terra | Adversarial stress tests for plans, risky changes, and no-finding conclusions. |
scientist |
Terra | Papers, hypotheses, experimental methods, metrics, and ablations. |
The model names are requested role settings. Blank-agent injection does not prove the actual model, reasoning effort, sandbox, approval policy, or nesting profile. Workflows must record requested and observed controls and stop when an unproved setting is mandatory for safety.
π How portable role routing works¶
Role-card injection, fallback, and provenance details
The canonical policy is `shared/specialist-orchestration.md`. 1. The parent determines whether the work actually benefits from an independent specialist. 2. It reads and hashes `roles/π° Orchestration and cost control¶
Tier ownership and escalation guardrails
Use delegation only when two or more disjoint workstreams can proceed without duplicating the same context. Typical high-value splits are implementation versus tests, architecture versus migration docs, or CI diagnosis versus static analysis. - Luna owns bounded coordination, documentation, CI/CD, web evidence, OSS, and linting support. - Terra owns implementation, runtime behavior, tests, data/ML, performance, curation, challenge, and executable verification. - Sol is reserved for solution architecture and security. Select the smallest capable tier from current task evidence: escalate only for a mandatory boundary or observed lower-tier insufficiency, de-escalate only after an evidenced scope split leaves bounded support, and never change tiers on cost alone. The canonical policy is [`shared/specialist-orchestration.md`](https://github.com/Borda/AI-Rig/blob/main/plugins/codex-rig/shared/specialist-orchestration.md#delegation-lead-and-model-routing). Two consecutive work cycles without material progress, or three evidence-backed attempts that leave the same closure condition unmet, trigger a persisted and validated `reasoning-progress.json` stall ledger and one advisory escalation: a supported higher reasoning effort first, then the next permitted tier. The advisor supplies a bounded recovery action and stop condition but makes no changes; its route is valid only when the observed sandbox is `read-only`. If no safe route exists or that one action still fails to close the condition, Codex Rig stops and asks the user with consolidated evidence, hypotheses, rejected alternatives, and a recommended next step. This guardrail is distinct from, and never resets, the repeated-obstacle policy. The delegation lead returns one handover. Executable acceptance, runtime/API changes, release-blocking decisions, and security/architecture conclusions remain parent- or appropriate Terra/Sol-owned. Narrow work stays in the parent when handoff cost would exceed its value.π Quality gates and artifacts¶
Artifact shape and confidence thresholds
Workflow artifacts commonly use this shape; exact files vary by workflow: The exact files vary by workflow, but completion requires the requested output, explainable gate results, unresolved risks, and a validated `result.json`. Shared helpers provide diff collection, PR evidence collection, gate execution, artifact validation, severity mapping, and result writing. Confidence is evidence-backed: - `<= 0.80`: incomplete; continue recovery or report a blocker. - `0.80 < confidence < 0.85`: very questionable; stronger evidence is required. - `0.85 <= confidence < 0.90`: cautious-low; objective recovery evidence and remaining limits must be explicit. - `>= 0.90`: fair, not automatic; material residual limits still belong in the result.πΊοΈ PR review-to-remediation¶
Evidence collection, review closure, and remediation boundaries
- **Review intake:** `$codex-rig:code-review #123` collects contributor intent from the PR title/body, comments/reviews, target-branch evidence, an exact local PR head, and a locally derived diff before producing a structured review artifact. Assessed PR handoffs begin with a snapshot rebuilt from those run artifacts: PR number/link, author, GitHub check status, intent-based type, and the review suggestion; validation rejects missing or replaced fields and a suggestion that disagrees with the structured decision. - **Terminal closure:** After successful collection it may emit an evidence-backed terminal `close` decision before detailed review for one of `FALSE_GOAL`, `BREAKING_CONDUCT`, `WRONG_SCOPE`, `WRONG_PROVENANCE`, `DUPLICATE`, `UNADDRESSED_REVERT`, `SPAM`, or `ARCHITECTURE_VIOLATION`; ambiguous evidence always continues to detailed review, and the decision never closes, comments on, merges, or otherwise mutates GitHub. - **Review routing:** It performs mandatory QA/challenge passes for broad or high-risk diffs and conditionally triggers architecture, security, CI, docs, data, performance, research, or web evidence when detailed review proceeds. Routing evidence and triggered-role reasons are always non-empty JSON string arrays, so validators can distinguish malformed output from an assessed review. - **GitHub transport:** `shared/github_read.py` is the sole GitHub data transport: it prefers authenticated `gh` but never reads credentials; permits only audited built-in view groups (`gist`, `issue`, `pr`, `project`, `release`, `repo`, `ruleset`, `run`, `workflow`), REST GET, and GraphQL query operations; and retains no CLI failure output. - **Approval boundary:** In a network-sandboxed runtime, the complete collector commandβnot a standalone `gh` preflightβmust receive external-network approval because its nested CLI, HTTPS fallback, checkout, and Git fetches inherit the collector's execution context. - **Retry and denial:** If an agent mistakenly launched that collector without approval and receives a sandbox-shaped `github-network` failure before any user prompt or denial, one unchanged collector retry through the approval mechanism is required before the failure becomes terminal. A user denial always stops the current turn and forbids that retry. - **Evidence tiers:** `collect_pr.py` separates core source evidence from supplemental online evidence: PR identity/body, base-repository identity, target ancestry, exact PR-head checkout, and local diff are mandatory; GraphQL review-thread resolution status and derived statistics may degrade with explicit artifacts and confidence gaps. - **Checkout and ancestry:** Open fork PRs use `gh pr checkoutποΈ Calibration¶
Offline and live calibration boundaries
The packaged runner supports the plugin layout directly: It validates packaged skills, role cards, shared contracts, behavior fixtures, accepted routing evidence, confidence scoring, and known workflow leaks. The offline CI harness shadows network and LLM commands, uses an isolated home, and writes compact failure artifacts without contacting an LLM. Paid live A/B calibration is separate, explicit, and never implied by the offline result.π§Ύ Approval prompts and commit handoffs¶
For every intentional approval request, Codex keeps the detailed safety and effects pre-brief separate from the runtime prompt. The prompt reason is a short plain-English question about the outcome or material effect; it never duplicates command syntax, arguments, flags, paths, multiline content, or the full pre-brief. Reusable approval uses only a justified short categorical safe prefix, while one-time or high-risk commands omit the persistent prefix.
Codex-created commit handoffs identify every commit by hash and title, summarize behavior and affected surfaces, list exact verification evidence, disclose residual limits, and explain boundaries between multiple commits. As one application of the approval rule, multiline messages remain complete but stay out of the approval argv: Codex shows the exact message, stores it in a private temporary file outside the worktree, and requests one-time approval for rtk git commit --cleanup=verbatim -F <file> without a persistent prefix rule.
π©Ί Optional SessionStart diagnostic¶
Read-only hook behavior
`hooks/hooks.json` defines a read-only diagnostic for `startup` and `resume`. Codex discovers this default plugin hook path after install. The hook runs the same shim doctor used by the manager; it does not install, update, or remove shims. Review the hook command before trusting it. Declining hook trust leaves the diagnostic inactive and does not disable skills.β¬οΈ Update or reinstall¶
Use the bundled $codex-rig:sync workflow for a dry-run state report and an approval-gated refresh, or run the supported CLI commands directly:
codex plugin marketplace upgrade borda-ai-rig
codex plugin add codex-rig@borda-ai-rig
codex plugin add bridge@borda-ai-rig
Then start a fresh Codex session. Plugin reinstall does not update external user-agent files automatically. Use the manager's authenticated remove action to clean prior development shims; new installation remains platform-blocked.
Repository sync never restores the legacy .codex/ tree. When Codex scope is active, root make sync-codex installs or updates the public Codex plugins and authenticated Codex Rig block, then projects repository model defaults and personal policy as described above. There is no flag to skip that global-instructions projection anymore β the earlier --no-codex-global-agents opt-out is gone, and make sync-codex always projects model, review_model, and the personal-policy block together.
Legacy project-to-home copies¶
Legacy copy cleanup warning
Older `sync.sh` versions β the script has since been retired and its logic folded into the root `Makefile` β copied AI-Rig files into `~/.codex/`. The copied files had no durable per-file ownership marker, so Codex Rig does not delete them automatically. Before manual cleanup, back up the home, distinguish AI-Rig copies from user-owned modifications, and remove only files whose ownership you can establish. An old home copy can otherwise expose duplicate unnamespaced skills or stale named-agent registrations beside the plugin.π§ͺ Experimental agent shims¶
Shim diagnostics and authenticated cleanup
The manager diagnoses prior development installations and safely removes authenticated standalone TOML files. New installation is platform-blocked because current collaboration tooling does not expose a verifiable custom-agent selector. Do not infer selection from a matching task name, child path, or file name. Invoke exactly one action: - `doctor`: read-only runtime, active-package, manifest, helper, role-card, and filesystem checks. - `status`: read-only installed-roster, lifecycle-state, target, and recovery summary. - `install`: report the platform block without creating or relinking files. - `remove`: plan removal of intact, authenticated Codex Rig shims. No prefix-based cleanup. `doctor` and `status` are read-only on Windows, macOS, and Linux. Windows verifies package hashes, active selection, executables, and an inventory of exact `codex-rig-*.toml` names; it does not authenticate, adopt, or mutate those files. POSIX additionally validates lifecycle state and permissions. A blocked result names the failed check and required invariant; it does not authorize a repair. The optional SessionStart hook shows the first bounded reason and confirms that no files changed. Do not apply recursive permission changes or delete/link-replace evidence from the diagnostic alone. Existing POSIX `$CODEX_HOME/agents` directories are accepted when they are real current-user directories without group/world write or special permission bits; lifecycle state and recovery directories remain private mode `0700`. Prior lifecycle files use authenticated names such as `codex-rig-linting-expert.toml`. `remove` prints the exact target root, operations, and SHA-256 approval digest. Review the displayed plan. Type that exact digest only after explicit approval. Wrong or missing digest causes cancellation without authorized writes. Interrupted recognized transactions use a separate recovery digest. Approved recovery rolls back partial mutation or finalizes durable committed state. Repeat the original action after recovery. Use `remove` to recover prior interrupted transactions; blocked `install` never enters recovery or mutation planning.β¬οΈ Uninstall¶
Plugin removal and recovery procedure
Remove authenticated legacy shims while the plugin manager still exists: 1. Run `$codex-rig:agent-shims remove` and approve the exact plan when one exists. 2. If global instructions were installed, back up `$CODEX_HOME/AGENTS.md` and remove only the block between the `codex-rig:global-agents` markers when it is no longer wanted. 3. Run `codex plugin remove codex-rig@borda-ai-rig`. 4. Start a fresh Codex session. Removing plugin first deliberately leaves thin shim files behind. Those shims break because role cards and the verifier live in the removed plugin cache. They are not auto-deleted. Recovery: reinstall `codex-rig@borda-ai-rig`, start a fresh session, run `doctor`, then run approved `remove`. Compatible historical state can authenticate guarded cleanup. Verification failure remains blocked; no force cleanup is provided.π§ Lifecycle safety limits¶
Fail-closed mutation limits
- Foreign or marker-only `codex-rig-*.toml` files are never adopted, overwritten, or removed. - Modified managed shims, concurrent drift, unsafe links/nodes, ambiguous package selection, or changed runtime binaries block mutation. - Executable hashing is bounded consistently at 512 MiB across the manager, generator, and verifier; larger files report the selected path, observed size, and limit. - Missing, malformed, oversized, aliased, or identity-inconsistent lifecycle state blocks cleanup. Manual evidence recovery is required. - Only one exact recognized interrupted transaction can be recovered. Unknown, conflicting, or multiple residue remains blocked. - The manager owns only its authenticated roster and state under the current user's Codex home; it never cleans unrelated agents. - Thin shims require an active compatible plugin cache. Offline cached use may work; update, reinstall, and active-package validation depend on Codex CLI state. - Hook trust, plugin install, shim install, and shim removal are separate lifecycle decisions. - Plugin removal does not edit `$CODEX_HOME/AGENTS.md`; a sync-installed managed block remains until explicitly removed. - A successful shim transaction proves file ownership and link integrity, not runtime profile selection. - Native Windows and network/distributed filesystems are unsupported for shim mutation. Windows workflows, package verification, sync, hooks, and read-only shim inventory remain supported.π― What changed from the idealized design¶
Architecture evidence and remaining platform dependency
The initial design assumed a plugin could bundle named agents with model, sandbox, approval, and nesting controls. Implementation evidence changed that architecture: 1. **Agents became role cards.** The behavioral instructions remain full-fidelity, versioned product assets, but they are no longer presented as directly installable native agents. 2. **Selection became injection.** Skills load the exact role card and inject it into a runtime blank agent. This preserves parallel specialist reasoning when available without inventing a selector that Codex does not expose. 3. **Inline execution became the mandatory fallback.** When a safe blank-agent route is unavailable, the parent applies the card serially and reports lost independence. 4. **Thin shims became cleanup-only.** The transaction engine can authenticate and remove development shims, but `install` fails closed until runtime selection is observable and testable. 5. **Project configuration left the product.** Models, MCP, and repository runtime defaults belong to user/project configuration. The plugin distributes reusable workflows, roles, hooks, helpers, evidence fixtures, and one inert global-instructions template. Repository sync installs it when Codex scope is active unless explicitly opted out; direct plugin installation alone leaves it inert. 6. **Install identity became immutable.** Released package bytes are tied to a SemVer version and manifest hashes; README or code changes require a new version rather than same-version cache drift. This design delivers the maintainable part of the original goal today and records the remaining platform dependency honestly. If Codex later exposes custom-agent selection, named shims can be reconsidered behind fresh runtime probes without changing skill or role-card semantics.ποΈ Package layout¶
Installed package topology
codex-rig/
βββ .codex-plugin/plugin.json
βββ ARCHITECTURE.md # parallel split, approvals, gates, evidence, telemetry
βββ assets/AGENTS.md # inert global-instructions template
βββ skills/ # 13 workflows + agent-shims lifecycle manager
βββ roles/ # 15 canonical role cards
βββ shared/ # gates, helpers, orchestration, artifact contracts
βββ runtime/calibration/ # fixed, behavioral, and live calibration assets
βββ hooks/ # optional read-only SessionStart diagnostic
βββ scripts/ # package, role, and shim lifecycle executables
βββ tests/ # package and cross-platform acceptance tests
βββ package-manifest.json # exact packaged file and role-card hashes
π§ͺ Development and verification¶
Maintainer verification commands and acceptance gate
From the repository root:python3 plugins/codex-rig/scripts/build_package.py --update
python3 plugins/codex-rig/scripts/build_package.py --check
python3 plugins/codex-rig/scripts/validate_package.py
python3 -m pytest -q plugins/codex-rig
NO_MKDOCS_2_WARNING=1 python3 -m mkdocs build --strict
π License¶
Codex Rig is licensed under Apache-2.0. See LICENSE and NOTICE.