Codex Harness Guide
Audience: Users - Operators configuring or troubleshooting the Codex harness adapter.
The Codex adapter uses the official openai-codex Python SDK and explicitly directs it to a standalone codex executable that must be on PATH.
hpilot passes any normalized explicit effort to each SDK turn and sends nothing when effort is omitted. The installed SDK and selected model decide which values are valid. An explicit SDK rejection ends the stage on its first attempt with the SDK diagnosis rather than silently using the Codex default or repeating an unrepairable retry.
Native persisted goals
Set goal: true in a Codex stage override or iteration threshold to opt into one native persisted goal operation. Goal mode requires an SDK exposing the native goal protocol and standalone codex-cli 0.158.0 or newer; startup and hpilot doctor reject a missing protocol surface or older CLI without retrying or falling back to ordinary turns. Install the current CLI with npm install -g @openai/codex@latest, verify it with codex --version, and use uv sync for the SDK. A repository checkout follows uv.lock; run uv lock --upgrade-package openai-codex before uv sync to select a newer SDK release. Explicit false disables an inherited true, omission inherits, and any effective true on another harness is invalid. Fresh goals receive the stage model, effort, workspace, instructions and permission settings before activation. Resuming a shared goal keeps the chat’s sandbox and approval settings. See shared server permissions.
Configure the opt-in in the active global config (~/.hpilot/config.yaml or workspace-local .hpilot/config.yaml) using exact case-sensitive stage names:
stage_overrides:
Implement:
harness: codex
goal: true
Review Code:
iterations:
2:
goal: true
4:
goal: falseCommand stages ignore goal because they do not resolve agent runtimes. Use explicit goal: false to disable an inherited true value for later visits without affecting other fields, and see the Configuration Reference for cumulative iteration semantics and hpilot use preservation. For version, harness, state, or unconfirmed-stop failures, see Pipeline Execution Troubleshooting.
hpilot writes the original stage instructions to .hpilot/goal.md when it starts a new native goal or explicitly resumes one with --resume. The default goal tells Codex to keep working until all tasks in that file are complete. The file remains accessible after context compaction. If the stage result needs correction, hpilot sends a message to the goal's Codex thread before reactivating the goal. Codex receives it as a user message on its next automatic turn, even if the app doesn't display a separate chat bubble. The message lists outstanding tasks, identifies status or field issues, and includes one <contract_guidance> block with the writing instructions and YAML examples.
Physical turn endings are progress while the goal is active. hpilot evaluates only after a terminal complete state and thread quiescence, preserves the actual final parent reply, records physical turn identifiers without treating them as attempts, and revalidates contract artifacts before routing. If the contract or verifier rejects completion, the next allowed stage attempt reactivates the same native goal with a status-only update. This works through both the Codex app's shared writer and standalone resume. Each completed operation consumes one stage attempt, and max_retries bounds correction attempts.
Completed-goal resume preserves the thread, objective, token budget, and cumulative token/time accounting. hpilot checks the activation response and aborts without further retries if the runtime rejects reactivation or changes that accounting. Explicit --resume can also reactivate a completed goal with remaining allowance. Usage-limited, budget-limited, and exhausted goals remain blocked; hpilot never clears or recreates a goal to bypass its limits.
If a native goal becomes blocked because of serverOverloaded (“Selected model is at capacity”) or a response-stream disconnect after Codex exhausts its own reconnects, hpilot waits for the failed physical turn to finish and retries the same goal within the current stage attempt. These retries preserve the thread, objective, instructions, history and native accounting, remain cancellable, and do not consume max_retries, emit a stage failure, or run stage hooks again. A blocked goal without a temporary provider error, a cleared goal, and usage or budget limits retain their normal failure behavior.
If another connected client clears a goal after hpilot observes completion, hpilot retains that outcome, waits for the final physical turn, and evaluates its reply once. A goal cleared before completion is observed, or missing when resumed, stops the stage immediately without automatic retries because its native allowance is no longer available. Start the stage without --resume to begin a fresh goal. Clearing never counts as proof of completion.
An active goal can remain quiet while a command or sleep tool runs. hpilot polls the goal notification queue for cancellation without treating an empty poll as a stage failure; goal status, transport errors and explicit cancellation determine whether it stops waiting.
Cancellation and exceptional exits pause the owned goal before interrupting the current physical turn, reconcile rollover, run the Git-backed guard at physical boundaries and close subscriptions, followers and the client. An unconfirmed stop is an explicit failure and prevents stage advancement or overlapping replacement. This remains detect-only filesystem enforcement, not preventive isolation. Native goal diagnostics and raw events appear in the ordinary console, daemon output and stage JSONL; parent usage is derived from cumulative native snapshots, replay is not double-counted and observed child usage is not added separately.
The 2026-09-29 release qualification used SDK 0.144.4, CLI 0.158.0 and automatic effort medium. Authenticated thread 01a0e913-1d5e-70b0-96d2-ff91dde90a47 completed in two physical turns; native state reported complete, 12,670 tokens and 21 seconds, and both requested phase files matched. A separate active goal was paused and read back as paused for real cancellation evidence. SDK 0.158.0 passed the deterministic adapter suite and an isolated thread/goal/get protocol probe, but its authenticated goal lifecycle remains unverified. The runtime did not expose a separate child-usage total. Completed-goal resume was subsequently checked on 2026-10-25 with SDK 0.158.0, CLI 0.163.0, an isolated shared writer, and a local mock provider; its thread, objective, token budget, and cumulative usage survived reactivation. That check made no authenticated model requests.
Runtime
- hpilot starts a new SDK thread for a fresh stage attempt and reopens the captured thread for retry continuation or explicit
--resume. - “Selected model is at capacity” and a
responseStreamDisconnectedfailure after Codex exhausts its own reconnects are temporary failures handled inside the Codex adapter. hpilot preserves the structured error details and retries in three-attempt batches. Ordinary turns resend the unchanged original prompt, while native goals reactivate the same persisted goal after its failed physical turn finishes. Neither path generates a retry-continuation prompt. hpilot waits 30 seconds after the first exhausted batch and 60 seconds after later batches, retries indefinitely without consuming the stage'smax_retriesbudget, and remains cancellable during the inter-batch waits. - The requested model and current workspace are passed to the SDK.
- A standalone server uses Full access. Shared servers support both Approve for me and Full access.
- Live SDK notifications are shown as
reply:,thinking:, andtool call:messages. - Reply and reasoning deltas are ignored. Complete SDK message and reasoning items are rendered once when their item lifecycle finishes.
- The SDK's final response is the authoritative stage reply.
Shell command logs
When Codex reports a command through a recognized bash -lc or zsh -lc wrapper, hpilot shows the logical command separately from the shell metadata while keeping the canonical tool name Bash:
tool call: Bash
command: pwd
shell: /bin/bash
shell_args: -lcAbsolute and bare shell names are supported, so /bin/zsh -lc pwd reports shell: /bin/zsh and zsh -lc pwd reports shell: zsh. Safely removable outer quotes are omitted from the displayed command while inner quoting and shell syntax are preserved. Unrecognized or ambiguous command shapes remain unchanged in the command field and do not receive shell or shell_args fields.
This normalization affects logs only. hpilot does not change the command sent to Codex, protocol traffic, subprocess launch behavior, quoting, environment, login-shell behavior, working directory, or read-only-path enforcement.
Subagent logs
Codex subagents run as separate native threads. hpilot follows only threads explicitly referenced by collaboration or subagent-activity events and merges their observable activity into the stage stream without changing delegation, scheduling, or prompts. Direct and nested descendants are followed; each descendant uses one compact prefix rather than a chain of ancestor prefixes. Whether a stage spawns subagents is decided by the model; a run without a [subagent:<label>] line is normal when the model handles the task directly. No extra configuration is required beyond the normal Codex prerequisites (codex on PATH, authenticated, multi_agent enabled by default), and extraction ignores the collaboration tool, status, and activity kind values so newer runtimes remain observable with an older SDK. Subagent lines appear in both hpilot run stderr and daemon task output (hpilot submit, hpilot attach, hpilot logs) and in the per-stage JSONL file under .hpilot/logs/stages/<Stage>.jsonl.
A child line uses [<stage>][codex][subagent:<label>], where <label> is the nickname reported by Codex or the last eight alphanumeric characters of the thread ID when no nickname is available. Child reasoning, replies, shell activity, file changes, MCP calls, web searches, collaboration calls, and failures use the same canonical rendering as the parent, and multiline tool call: blocks are written atomically so they are never torn by concurrent output from the parent or another child. Successful child turn completions are quiet, and a child reply never becomes the stage's final response or contributes to the parent's partial reply.
When children exchange messages or reply to an ancestor, hpilot follows new activity without repeatedly processing unchanged past exchanges. This avoids an observation loop that can keep both hpilot and Codex busy after the children finish. Ordinary turns and native goals share this behavior.
Example interleaved stderr (truncated IDs):
[Spec][codex] tool call: Collab
tool: spawnAgent
receiverThreadIds: ["018f8a9b-..."]
[Spec][codex][subagent:Dalton] thinking: reviewing workspace files
[Spec][codex][subagent:Dalton] tool call: Bash
command: rg --files
[Spec][codex] thinking: waiting for subagentshpilot attaches to an active child turn when possible, so its lines can appear live and interleaved with parent activity without blocking the parent turn stream. A fast child may finish before attachment; hpilot then reconstructs its items from native thread history during a bounded final reconciliation before normal stage shutdown (skipped when cancelled). Live and reconstructed events share item IDs and are deduplicated, so overlap does not produce duplicate lines, and no periodic polling is used — reads occur only on discovery, repeated references, live-subscription boundaries, and that final pass. Only turns from the current attempt are emitted (in-progress turns or turns started at or after attempt start minus 2 seconds for clock skew), so a resumed parent does not replay older history. A nested child's structured metadata names its immediate parent and depth even though stderr keeps the single compact child suffix.
Parent JSONL records remain raw Codex notifications (previously dropped notifications with empty params now render with their preserved payload, for example tool call: Collab for a followupTask call). Each child record is an envelope with source, origin, and notification: source.kind is subagent and includes the full thread_id, parent_thread_id, depth, and any reported agent_nickname, agent_role, or agent_path; origin is live or history; and notification preserves the normalized Codex method and params. This hierarchy lets log consumers reconstruct the descendant tree, and replaying a stage log through the Codex line parser unwraps child envelopes into canonical events without falling back to plain text.
Child envelope example (truncated IDs):
{"source":{"kind":"subagent","thread_id":"018f8a9b-c123-7d00-8000-abc123456789","parent_thread_id":"0190a1b2-d234-7d00-8000-def987654321","depth":1,"agent_nickname":"Dalton"},"origin":"live","notification":{"method":"item/completed","params":{"threadId":"018f8a9b-c123-7d00-8000-abc123456789","turnId":"turn_abc123","item":{"id":"msg_abc123","type":"agentMessage","text":"done"}}}}Constraints: this observation is Codex-only and does not change when subagents are spawned, what they are asked to do, or how they are scheduled; it does not add child usage to hpilot usage; at most eight child turns are followed live concurrently with history covering the remainder; and fast children that finish before attachment appear as history only, which is expected.
Following does not add child token-usage notifications to hpilot's usage snapshots. The parent turn's SDK counters remain the sole reported total, so whether those native counters aggregate descendant work is provider-defined and is not adjusted by hpilot. The opt-in smoke test reports whether it observed a live child envelope, the parent-reported token total, and the descendant event count; deterministic automated coverage also confirms that the follower leaves usage snapshots unchanged. An authenticated Codex CLI 0.154.0 implementation smoke observed four live child envelopes with no duplicate item keys and a parent-reported total of 34,805 tokens, but exposed no separate descendant token total with which to confirm native aggregation.
If hpilot cannot read or follow a child, it writes one warning such as [<stage>][codex] subagent log warning: <reason> per child and failure category. The warning affects observability only and does not change the stage result. Check codex --version, authentication, and the stage JSONL for the preserved protocol payload. Confirm that delegation is available with codex features list and that multi_agent is enabled; without that feature, Codex will not create native subagent threads. History-only envelopes are expected for very fast children, but a repeatable absence of every origin: live envelope during longer delegated work indicates that live attachment is unavailable and should be investigated while history reconstruction continues to provide completion coverage.
Resume and retries
Codex supports both automatic retry continuation and explicit resumed stage continuation:
hpilot run "task" --start-from Implement --resume
hpilot submit "task" --start-from Implement --resume--resume reopens the Codex thread recorded in .hpilot/latest-session.json when the saved metadata matches the selected stage, persisted stage visit, harness, workspace, model, effort and goal mode. On explicit resume, hpilot regenerates .hpilot/goal.md from the current rendered stage instructions before reopening the thread. A blocked, paused, or completed native goal can resume in place, preserving its objective, history, token usage, elapsed time and budget. Completed goals require remaining allowance and a runtime that preserves their accounting on resume. Usage-limited and budget-limited goals remain terminal. Use the same CODEX_HOME as the original run so Codex can find its stored history. --start-from without --resume starts a fresh thread.
Automatic retries reopen the chat captured by the previous failed attempt and send feedback about the failure. When Codex rejects a resume request, the attempt fails with the SDK diagnosis and follows the normal pipeline failure policy.
Shared Codex server
On Unix hosts, fresh stages, retry continuation and explicit --resume prefer the existing local Codex server in the same CODEX_HOME. A chat does not need to be open in the desktop app or already loaded by that server: hpilot can create a fresh chat or reopen a saved session through the shared connection. The stage log reports using shared app-server with the captured thread ID. If the socket is unavailable or the connection fails during initialization, hpilot starts a standalone server before opening a chat. If the shared server explicitly rejects a request or its settings, even during initialization, the stage stops on the first attempt and reports the server’s reason.
| When hpilot starts a stage | Permissions Codex uses |
|---|---|
| New chat on a shared server with permissions configured | The server’s settings for the workspace. With Approve for me, Codex automatically reviews requests to go beyond the sandbox. With Full access, commands can access files available to the account running Codex without an approval prompt. |
| New chat on a shared server with no permissions configured | hpilot’s Full access default. |
| Retry or resume of a shared chat | The chat’s own sandbox, approval policy and reviewer, including for later turns and native goals. |
| Stage using a standalone server | hpilot’s Full access default. |
An idle chat can resume even after the server unloads it. If hpilot reports that it cannot read or recognize the saved sandbox settings, open the chat in Codex and retry the stage. Before resuming and before every ordinary shared stage turn, hpilot checks whether the chat has a running turn and stops the attempt with an actionable diagnosis if it does. If another Codex process owns the thread and its server cannot be reached, hpilot reports the ownership conflict without consuming stage retries. Release that thread in Codex before resuming. Switching to another chat may leave it loaded.
Ordinary shared turns use the stage’s model, workspace and any explicit effort. A shared native goal inherits those values from its chat on each automatic turn, so hpilot checks that they match the stage before reactivating the goal. Workspace trust applies only to the stage connection.
Other platforms use a separate server. Disconnecting a shared connection leaves other clients and their server running. Codex controls how long a thread stays loaded after its subscribers leave.
Cancellation
hpilot cancel, SIGINT, and SIGTERM interrupt the active Codex turn. In goal mode hpilot first pauses the active persisted goal, then checks the read-only guard, interrupts and reconciles any rollover; outside goal mode it interrupts the active turn directly. If shutdown does not finish within the bounded cancellation window, hpilot closes the SDK transport. A shared connection closes only hpilot's client connection and leaves the owning server and other chats running. An interrupted stage exits with code 130, persists the captured session for explicit resume, retains native history and partial output, and does not start a verifier continuation.
Read-Only Paths
Codex cannot express selected protected paths in its SDK sandbox. hpilot therefore captures a Git-backed baseline for read_only_paths, checks after every turn outcome, and reports created, modified, or deleted protected files without restoring them. Any detected protected-path change fails the stage attempt after detection.
This is Git-backed detect-only enforcement: it does not prevent the write before it occurs. Use an outer read-only filesystem boundary when data must never be writable. Git administration and ignored files are outside the guard's Git-visible scope.
Troubleshooting
Run hpilot doctor. If the SDK is unavailable, reinstall hpilot with its locked dependencies, such as with uv sync, and verify the import with python -c "import openai_codex". If the CLI is unavailable, install the latest npm release with npm install -g @openai/codex@latest, then verify it with codex --version.
Subagent logs are missing or show a warning
Shutdown waits up to five seconds for final child history, then closes the connection to release unfinished reads. Reads interrupted after observation stops do not produce warnings. A missing or invalid required contract artifact still fails stage validation even if Codex marked its native goal complete; subagent logging does not cause that failure.
A single [<stage>][codex] subagent log warning: <reason> line per child and failure category means observation failed for that child only; the stage outcome, final response, retry routing, and usage are unaffected. Confirm codex --version, authentication, and that multi_agent is enabled with codex features list; without that feature Codex does not create native subagent threads. Inspect the stage JSONL under .hpilot/logs/stages/<Stage>.jsonl for the preserved notification payload and source hierarchy. history-only envelopes are expected for very fast children, but a repeatable absence of every origin: live envelope during longer delegated work indicates that live attachment is unavailable while history reconstruction continues to provide completion coverage. Cancellation skips the final reconciliation and never interrupts children directly, so a cancelled stage may show partial history only.
Native session discovery
hpilot leaves CODEX_HOME exactly as inherited, so sessions remain in the normal Codex home rather than a temporary directory. hpilot does not copy Codex files or change your auth.json or config.toml; the active workspace is trusted for the stage without persisting a new trust entry.
Use codex resume --all --include-non-interactive for reliable discovery of hpilot SDK sessions, then use codex resume <session-id> for deterministic access. An isolated Codex 0.144.1 smoke containing only the generated SDK session confirmed the native row survived teardown and direct resume accepted the exact identifier. That CLI also showed the row in the plain picker, but picker filtering can vary by version, and a row may present a title rather than the raw identifier, so .hpilot/latest-session.json remains the deterministic correlation source. Use Ctrl+C to quit the verified resume picker without starting or resuming a conversation; Esc starts a new conversation in that picker.
Native inspection uses the same standalone Codex CLI selected by the SDK. Run it with the same CODEX_HOME that hpilot used, or leave both unset to use ~/.codex, and verify the CLI with codex --version.