Codex Worker Mechanical Specification
This is the single mechanical specification for these five closed-set scripts:
skills/sshx/scripts/run-codex-worker.sh;skills/sshx/scripts/run-codex-worker-batch.sh;skills/sshx/scripts/read-codex-worker-status.sh;skills/sshx/scripts/clean-codex-worker-runs.sh;skills/sshx/scripts/prune-inactive-codex-worker-runs.sh.
The sixth closed-set script, skills/sshx/scripts/run-oracle-worker.py, is specified by
ORACLE_WORKER_SPEC.md. It shares the run layout below through the runner's pure
--project-paths query and never launches this runner.
The completion predicate is defined once in SKILL.md under
## Worker Completion Contract; this file references that contract and does
not restate it. Caller-side dispatch and collection are governed solely by
SKILL.md under ## Worker Delegation and are likewise not restated here.
Invocation
bash <skill-root>/scripts/run-codex-worker.sh \
--stage <thinking|implementation|review|termination> \
--work-target <absolute-path> [--sandbox <danger-full-access|workspace-write>] \
[--retry-provider-id <native-bare-key>] \
[--request-max-retries <nonnegative-integer>] \
[--stream-max-retries <nonnegative-integer>] \
[--flight-id <returned-id> --attempt <positive-integer>]--stage and --work-target are required; --sandbox is optional and defaults to
danger-full-access when omitted. Missing required, duplicate, unknown, or positional
arguments are USAGE_ERROR (exit 64). flight-id is exactly 24 lowercase
hexadecimal characters allocated by the runner, attempt is a
positive integer. Identity options must appear together or both be omitted;
omission allocates a fresh identity with attempt 1. Until a valid receipt binds
identity, a retry of the pending record also omits both options; its first
allocated external attempt remains 1. Once bound, a retry reuses the returned
identity and explicitly increments its external attempt. The external attempt
does not count pre-receipt retries: both pending and bound retries consume the
same fixed allowance under SKILL.md's Worker Delegation contract, without a
reset on missing receipt or allocation. Each retry consumes one unit before
relaunch, recorded in the caller's transcript independently of the external
attempt; exhausted pending and bound records use the existing fallback path.
Provenance and increasing bound retry
numbers are caller obligations, not registry or directory-scan checks. A new
task or fallback omits both options. Mechanically valid explicit values remain
accepted, but caller minting is not authorized. The
stage and sandbox use the enumerations above, and work-target is
absolute and contains neither LF (0x0A) nor CR (0x0D). This is a
locale-independent POSIX text-line boundary: stdout lines are LF-separated,
not Unicode logical lines. Other characters, including TAB, C1 controls,
zero-width joiners/non-joiners, and U+2028/U+2029, are accepted in path values.
The brief is read from stdin; artifact paths and arbitrary Codex flags are never
caller-supplied.
The optional retry controls are run-mode-only and form one narrow native bridge.
--retry-provider-id must be a non-empty TOML bare-key component containing only
ASCII letters, digits, _, or -; dots, quotes, whitespace, and other syntax are
rejected so the runner cannot silently address a different key path. At least one
of the two count options must accompany the provider ID, and every supplied count
must contain only decimal digits (including 0). A count without the provider ID,
or a provider ID without a count, is USAGE_ERROR before any directory, stdin, or
carrier side effect. Each supplied count becomes exactly one native override:
model_providers.<id>.request_max_retries=<value> or
model_providers.<id>.stream_max_retries=<value>, passed as a -c argument to the
existing codex exec entrance. An omitted count remains inherited from the native
provider configuration; the runner supplies no retry default or algorithm. Native
provider lookup and numeric-range validation remain native behavior, so a native
rejection retains the ordinary nonzero carrier outcome. This key encoding was
verified against native CLI 0.165.0 for provider IDs custom and loop; support
for other native versions or provider namespaces remains caller verification.
The runner also has three mutually exclusive pure query invocations:
bash <skill-root>/scripts/run-codex-worker.sh \
--project-paths --flight-id <id> --attempt <positive-integer>
bash <skill-root>/scripts/run-codex-worker.sh \
--project-flight --flight-id <id>
bash <skill-root>/scripts/run-codex-worker.sh --project-rootMissing required identity options, combining the query modes, or combining a
query with an option it does not take is USAGE_ERROR (exit 64):
--project-paths refuses --stage, --work-target, and --sandbox;
--project-flight additionally refuses --attempt and takes only the flight
identity; --project-root takes no identity and refuses
every other option. Identity validation and run-root normalization are
identical to run mode. No query requires the run root or any projected
directory to exist or be writable. They read no stdin, create no directory,
launch no carrier, write no projection, and delete nothing.
At a first launch, after syntax and dependency checks and run-root normalization,
the runner allocates an identity with the ObjectId shape: 24 lowercase hexadecimal characters whose
first 8 encode the big-endian UNIX second of minting and whose remaining 16
come from the operating system's random source; each allocation is its own process,
so the ObjectId per-process random and counter fields collapse into
randomness. Identities therefore sort chronologically and do not collide in
practice. A date, random-source, or self-check failure is INTERNAL_ERROR
and emits nothing. Before creating directories, reading stdin, or invoking the
carrier, every launch emits one compact strict JSON receipt as its first and
only stdout line, using exactly the --project-paths object shape below.
Receipt delivery failure prevents carrier start. Failures before allocation
expose no identity; handled failures after receipt delivery retain that identity
even when a status file cannot be written. An allocation whose receipt cannot
be rendered or delivered never starts a carrier and has no recoverable receipt.
On success --project-paths emits one strict JSON object containing
schema_version, flight_id, attempt, run_dir, brief_ref, result_ref,
completion_sentinel_ref, carrier_exit_ref, status_ref, and log_refs for
stdout, stderr, and the last message. --project-flight emits schema_version,
flight_id, the runner-owned flight_dir and sshx_root, and every namespace
entry matching the runner's attempt naming rule. Each attempt entry contains
its positive integer attempt, run_dir, and terminal status_ref; an entry
whose suffix is not a canonical positive integer carries attempt: null so a
consumer can mark it invalid without parsing the name. --project-root emits
schema_version, sshx_root, root_present (whether that root is currently
a directory), flights (every direct root entry whose name satisfies the
identity shape, as {flight_id, flight_dir} in name order, which is minting
order), and unrecognized (the names of every other direct entry, hidden
entries included). It classifies by name only and leaves an entry's type to
the consumer. Directory enumeration is read-only. Every query and run mode
share the same single path-derivation function; there is no parallel formula.
Run Directory
The runner derives exactly:
${SSHX_HOME:-$HOME/.sshx}/<flight-id>/attempt-<attempt>The run root is SSHX_HOME when that variable is non-empty, otherwise .sshx
directly under HOME; when neither is set the invocation is
RUN_DIR_UNAVAILABLE. Trailing slashes are removed except for /. The run
root must be absolute and contain neither LF nor CR. In run mode it must be an
existing writable non-symbolic-link directory or be creatable with one mkdir
inside an existing writable parent; the runner creates it on first use with
the same private mode as every other directory it owns. The run root and the
runner-created flight directory are rejected when symbolic links; relocating
the layout is done by setting SSHX_HOME, never by linking. Each is created
or validated before one atomic mkdir of the attempt directory; an existing
attempt is RUN_DIR_COLLISION.
Every invocation projects this layout from its own effective SSHX_HOME and
HOME, so dispatch by either runner, pure queries, batch dispatch, status read,
cleanup, and the inactivity sweep must run with the same effective values as the
dispatch they inspect. A different value projects a disjoint layout: cleanup fails
closed on its consistency checks and the sweep prunes that other root, but a
status read there reports every artifact absent and exits zero, which is
indistinguishable from a pre-terminal flight.
The runner owns brief.md, the three diagnostic logs, carrier.exit, and
status.json. The worker alone owns result.json and completion.sentinel.
The runner never creates, repairs, copies, normalizes, touches, or substitutes
either worker artifact. The brief requests same-directory temporary files and
atomic rename for those artifacts. It also states the envelope's structural
acceptance conditions and includes one runner-rendered, stage-specific minimum
valid envelope example.
The actual injected brief must convey exclusive ownership: worker writes only result,
sentinel and their same-directory publication temporaries; stdout/stderr/last-message,
brief/status/exit and their temporaries are runner-owned and must not be created,
overwritten, appended, repaired, normalized or forged by the worker. log_ref is copied
as an opaque reference to the existing diagnostic sink, without opening its body or
creating a narrative log; another existing reference needs explicit task supply.
All work/checks precede publication. The last worker tool action atomically publishes
result then sentinel, and the worker immediately returns its compact final reply with
no further tool, artifact inspection or rewrite. These prompt obligations do not impose
same-user filesystem protection. Simulation may demonstrate violations; it does not
prove real workers comply, nor establish timeout causality. A post-sentinel rewrite or
log overwrite cannot replace successful terminal carrier observation. The runner does
not audit write history or strengthen/weaken the completion predicate to do so.
Launch receipts and pure queries are the only sanctioned path discovery mechanisms for the batch, status-read, cleanup, and sweep scripts and for the oracle runner. Those scripts contain no run-layout formula, attempt naming rule, or artifact basename and do not parse human progress logs; the oracle runner adds only its own request file inside the projected attempt directory. The batch, status-read, and cleanup scripts check manifest identities against the identity shape before consulting the runner; the sweep contains no identity rule at all and takes the runner's classification.
Batch Dispatch
bash <skill-root>/scripts/run-codex-worker-batch.sh \
--manifest <absolute-path> --report <absolute-path>The manifest is exactly one strict JSON object with schema_version: 1 and a
non-empty workers array. Each worker has exactly stage, work_target, and
brief_ref, plus optional sandbox and a paired flight_id/attempt for bound retries.
Batch dispatch intentionally has no retry-provider or retry-count fields; the
single-runner controls above do not change its manifest or fanout surface.
Fresh rows and retries whose records still lack a valid receipt omit both identity
fields under the same pending/bound rule as a single launch. Identity,
stage, target, and sandbox values obey the runner's run-mode rules. For the
batch dispatcher, status reader, and cleanup tool alike, attempt must be a
JSON number whose jq text projection matches [1-9][0-9]*; that projected
decimal string is passed unchanged to the runner. Thus 1 and very large
digit-only integer values are accepted subject to parser and filesystem
resource limits, while 1.0, "1", 0, and -1 are rejected as
USAGE_ERROR (exit 64) with an attempt-specific diagnostic. Every
brief_ref is an absolute path to a regular non-symbolic-link file that the
dispatcher can open for reading. Duplicate explicit identity pairs are invalid. The
report parent must be writable and the report target must be absent; an existing
file, symbolic link, or other entry is rejected rather than overwritten. The
dispatcher validates the entire document, probes every brief for readability,
invokes the runner's shared-root query and pure path projection for explicit
retry identities, checks the report target, atomically reserves that final path
as an empty regular file, and exclusively creates one unique same-directory
report temporary file before launching any worker. Fresh paths are projected
only after joined receipt collection; the dispatcher never pre-mints identities.
It also reserves private per-row stdout captures named <report>.receipt.<index>.*
and emits one compact stdout recovery object with schema_version: 1 and
receipt_refs: [{worker_index, receipt_ref}] before any child launch. Preserve
that output with the host job. A recovery-output delivery failure launches no child.
Caller-input, option, manifest, brief, and report-target failures are
USAGE_ERROR (exit 64): no worker launches, and this invocation creates no JSON
report or changes an existing target. An internal pre-launch failure, including
an unavailable parser or runner, a failed runner projection, or failure to
create or validate the report temporary, is INTERNAL_ERROR (exit 1): no worker
launches and no complete JSON report exists. Before reservation, the dispatcher
installs both the EXIT release handler and the INT/TERM recording handlers.
A catchable signal whose dispatcher trap is effective therefore cannot terminate
the dispatcher inside acquisition. The EXIT handler removes the final-path
reservation on a handled unpublished exit. A successfully reserved path is only
an empty ownership placeholder while the dispatcher runs, not a published
report.
A termination after the reservation file is created but before the
exclusive-creation subshell returns can leave that zero-byte reservation. This
includes an uncatchable dispatcher termination and a group-directed catchable
signal that terminates the subshell while the dispatcher survives. A later
invocation on the same path exits 64 with report target must be absent. After
confirming that no dispatcher still owns the path, recover with
rm -- <report>.
The brief probe opens and then closes each descriptor. It establishes file type
and readability only at the instant of that probe; each launch later reopens the
caller-owned path. Replacement, deletion, or permission changes between those
operations can therefore produce a partial dispatch. Preflight makes no
all-or-nothing claim that survives such replacement, consistent with ## Threat Model; the dispatcher does not copy, stage, or otherwise take ownership of a
caller brief.
After preflight, the dispatcher launches the runner exactly once per manifest
worker and passes that worker's brief on stdin. Omitted sandbox values remain
omitted so the runner owns its default. Children run concurrently under one
foreground dispatcher. The dispatcher records every PID and uses wait for
every child even after a sibling fails. It never detaches, polls artifacts or
logs, or uses file contents to infer child exit.
The dispatcher uses join-then-publish interruption handling. When effective,
its INT and TERM traps record only the first signal but do not exit and do
not forward the signal to runners or carriers. Until launch completes, later
signals with effective traps remain caught and cannot replace that first
record. Only after every child has been launched does the dispatcher change
both dispositions to ignore, immediately when a signal was already recorded or
from the first later signal handler, so a second signal cannot interrupt a
recovery wait. Every asynchronous runner is therefore launched with the same
Bash dispositions independent of signal
timing: INT is ignored by Bash's non-job-control background launch and TERM
is default on entry because the dispatcher's caught handler is reset in the
child; the runner then installs its own INT/TERM handlers, although an
inherited ignored INT remains ignored. The dispatcher repeats a wait only
when that wait's own return status equals the recorded signal status. It joins
every recorded child before publication. It then publishes the report with
interrupted: true and exits nonzero when a signal was recorded. This preserves
ownership of recorded children but does not promise prompt cancellation or
carrier teardown. The runner may itself defer traps during its synchronous
carrier call and does not propagate signals, so teardown of the whole job tree
remains the host's responsibility.
The dispatcher's INT half has the same inherited-disposition limit as its
children: if the host starts it with SIGINT ignored, Bash cannot make its
INT trap effective, so those signals are inert and the dispatcher can finish
with interrupted: false. The stated TERM behavior likewise presumes that
TERM is trappable on dispatcher entry.
This guarantee has a shell prerequisite: the supported Bash must retain an
exited child's status when wait is repeated for that PID. The repository
collision/recovery behavior test distinguishes this behavior by recording a
signal outside wait, consuming a genuine child status of 143, repeating the
wait, and requiring both waits and the published report to retain 143. Separate
behavior tests cover a signal during a running child and a signal between
joins. A shell that does not retain the status is not a supported dispatcher
runtime.
Only after all children have been waited does the dispatcher render into the
exclusively created temporary file and atomically replace its own empty
reservation at <report>. The temporary file is unique to the invocation and
was created in the report directory during preflight; the reserved final target
is revalidated before publication, and the published report must be a regular
non-symbolic-link file. Failure is closed.
After all joins, each capture must contain exactly one structured receipt that
equals the runner's pure path projection for its identity. Retry receipts must
match the requested pair; fresh receipts must have attempt 1. No human log is
parsed. Missing, invalid, or mismatched receipts have explicit receipt_error
diagnostics and null identity/path fields; no identity is fabricated.
The report has
schema_version, all_workers_waited: true, and manifest-order worker records
containing flight_id, attempt, runner_exit_code, run_dir, and
status_ref, and receipt_error (null for a validated receipt), plus the
batch-level interrupted boolean; both paths come from the pure runner query.
resolved_manifest: {schema_version: 1, workers: [...]} contains the original
rows enriched with validated assigned identities, including nonzero runners,
in original order; unallocated rows remain explicit in workers only. It is
dispatcher-owned orchestration evidence, not a worker artifact or a completion
or verdict source.
The dispatcher exits 0 only after every runner exits 0 and a complete report is
published. It exits 1 after publishing the report when any runner exits nonzero
or the dispatcher was interrupted. The two pre-launch classes are the exit 64
caller/manifest class and exit 1 internal class described above; neither
launches a worker or publishes a complete report. An internal failure after
launch exits 1 after joining every recorded child, but no complete report is
promised because rendering or publication itself failed. Receipt captures are
retained on report or receipt-validation failure for recovery using the pre-launch
references. After successful report publication with all receipts validated,
the captures are removed. Extract collection input
with jq '.resolved_manifest' report.json > resolved.json, then pass that file
to status reading or cleanup after host completion notification; an empty
resolved set means no reader or cleanup invocation. These consumers require
assigned identity pairs and do not accept unresolved dispatch rows.
It has no retry, fallback,
identity-selection, result-reading,
completion-recognition, or lifecycle authority. It covers only the Codex
subset of a multi-seat stage, never the reserved non-Codex seats and therefore
never the whole stage.
One-Shot Status Read
bash <skill-root>/scripts/read-codex-worker-status.sh \
--manifest <absolute-path>This command accepts the resolved batch manifest shape but validates only the identity
fields it consumes; run-only values are not reinterpreted. For each manifest
worker in order it obtains status_ref through the pure runner query and makes
one filesystem read when that reference is a regular non-symbolic-link file.
There is no loop over time, delay, retry, glob, watch, process inspection, or
log parsing.
The command emits one strict JSON object with schema_version and a workers
array. Each item contains flight_id, attempt, status_present, and
status_document. status_present reports only whether a regular
non-symbolic-link file existed during that one pass. When present, the parsed
runner document is embedded with semantic JSON equality as status_document;
byte-for-byte whitespace and object-key formatting are not preserved. When
absent, that field is null. The present/absent file fact is required. What is
forbidden is any derived completion or lifecycle boolean, lifecycle inference,
verdict checking, or reason_code remapping. Absence is ambiguous and carries
no process-state meaning.
This is an after-terminal collection convenience. It may be called only after host completion notification. Calling it repeatedly while a runner is active violates the caller-side no-polling rule. A completed single pass exits 0 even when files are absent; usage or manifest failure exits 64 and internal failure exits 1.
Whole-Flight Cleanup
bash <skill-root>/scripts/clean-codex-worker-runs.sh \
--manifest <absolute-path> [--delete]Cleanup accepts the resolved batch manifest document shape: exactly one strict JSON
object with schema_version: 1 and a non-empty workers array whose items have
exactly flight_id, attempt, stage, work_target, and brief_ref, plus
optional sandbox; identity pairs must be unique. Like the status reader, it
validates only the identity fields it consumes, including the shared projected
decimal attempt domain defined under ## Batch Dispatch, and does not
reinterpret the run-only values. Missing or invalid options, a non-absolute or
non-regular manifest, and an invalid manifest document are USAGE_ERROR (exit
64).
Cleanup granularity is the whole flight directory, never one attempt. Removing
one attempt while siblings remain would allow a later launch of the same
identity to pass the runner's collision guard while a surviving flight record
still refers to the vanished attempt. Targets are only the distinct flight
directories returned for manifest identities by the runner's pure
--project-flight query. The same projection supplies the runner-owned
sshx_root and every attempt's number, run_dir, and terminal status_ref.
Cleanup derives no ancestry, naming pattern, or artifact basename.
There is no arbitrary-path or whole-root option here; the only age-based
retention rule is the separate ## Inactive-Flight Sweep, and any finer
policy is caller or maintainer choice.
All named flights pass one all-or-nothing preflight before any deletion. A
flight is eligible only when the runner-published flight directory and sshx
root are mutually consistent before and after canonicalization, every
runner-published path component from that root through each attempt is
non-symbolic-link, at least one canonical attempt entry exists, and every
runner-published terminal status reference is a regular non-symbolic-link file.
These comparisons are consistency checks on values from the layout owner, not
an independently derived confinement boundary. The terminal file fact is the
only mechanical evidence available that runner cleanup ended and no carrier can
still be writing. Any ineligible flight makes the whole request fail before
deletion with exit 1 and a machine-readable per-flight reason. In every cleanup
document, all_eligible, flights[].eligible, and flights[].reason are the
immutable preflight snapshot: reason is null for a preflight-eligible flight
and otherwise names only its preflight ineligibility. The dry-run document then
has mode: "dry-run", all_eligible: false, those per-flight snapshot records,
and removed: []. The delete document instead has mode: "delete",
all_eligible: false, the same records extended with state: "untouched" and
failure_reason: null, plus removed: [] and failed: []. No deletion has
begun in either shape. There is no force override.
Immediately before each individual removal, cleanup repeats that same runner
projection, canonical containment, attempt, symlink, terminal-status, and
entry-snapshot eligibility check and compares the projection with preflight. It
refuses the flight if the check fails or the projection changed. This narrows
the authorization window but does not eliminate TOCTOU between the repeated
check and rm, consistent with ## Threat Model.
Dry-run is the default and exits 0 with mode: "dry-run",
all_eligible: true, the per-flight eligibility records, and would_remove
naming exactly the eligible flight directories. Usage and internal failures
before a mode-specific document can be rendered emit no JSON. --delete grants
narrow, irreversible artifact-retirement authority for this invocation only:
it removes only flight directories returned by --project-flight. Every flight
in every mode: "delete" document has state equal to removed,
partially-removed, or untouched and has failure_reason, which is null when
no delete-phase failure is attributed to that flight and otherwise names only
the current eligibility, interruption, removal, or reporting failure. The
preflight reason never changes meaning after deletion starts. Every delete
document also has removed and failed arrays. A successful report names the
exact removed paths and has an empty failed array. After a failed removal,
absence means removed; otherwise cleanup compares an immediate
filesystem-entry count with the count taken just before rm to distinguish
untouched from partially-removed. A failed[] record carries flight_id,
flight_dir, state, and failure_reason; an already absent flight is also
included in removed.
The repeated projection equality check maps a false comparison to
failure_reason: "FLIGHT_CHANGED". Any other nonzero jq status maps to
failure_reason: "PROJECTION_COMPARE_FAILED"; both refuse deletion, but the
latter makes no factual claim that the flight changed.
Before entering the delete loop, cleanup installs INT and TERM handlers.
The first signal records interruption and changes both dispositions to ignore;
after the current operation returns, cleanup classifies its observed effect,
emits the exact fully removed subset, and exits 1. Signals are not forwarded to
rm. State accounting itself uses shell-owned arrays. The normal report
renderer uses jq, and every eligibility or removal failure after deletion
begins routes through that reporter. If normal rendering fails, including
because jq fails, the reporter uses a pure-Bash JSON fallback that does not
invoke jq. The fallback escapes quote, backslash, and C0 controls and passes
unsigned bytes at or above 0x80 through. For valid UTF-8 paths its document is
semantically equal to the jq document but is not necessarily byte-identical:
jq escapes U+007F as \u007f, while the fallback emits the raw 0x7F byte.
For a non-UTF-8 path the fallback passes invalid high bytes through, so its
document is not decodable as UTF-8 JSON; it deliberately does not imitate
jq's U+FFFD substitution, which could name a path that was never removed. If
stdout is unwritable, the same strict JSON document is attempted on stderr.
Any stdout publication failure exits 1 whether or not that stderr attempt
succeeds; when stderr is writable, its document carries the delete states and
exact fully removed subset. A successful dry-run or complete delete exits 0
only after its stdout document is published. Ineligibility and internal failure
also exit 1. All-or-nothing applies to preflight, not to rollback after deletion
begins. Cleanup makes no
independent confinement claim: it never constructs a target above or below the
runner-returned flight directory. It has
no process-teardown or host-lifecycle authority. A runner that never publishes
terminal status intentionally leaves its flight ineligible.
Inactive-Flight Sweep
bash <skill-root>/scripts/prune-inactive-codex-worker-runs.sh \
[--older-than <positive-integer><m|h|d>] [--dry-run]The sweep is the retention tool for the whole run root: it removes every
flight directory whose last change is older than the window. The window
defaults to 1d; the value is a positive integer with a unit of minutes,
hours, or days, and 0, a missing unit, any other unit, or a duplicate,
unknown, or positional option is USAGE_ERROR (exit 64) before anything is
read. Unlike ## Whole-Flight Cleanup, deletion is the default and
--dry-run is the preview: the manifest cleanup names specific flights and is
a caller retirement decision, while the sweep is a maintenance command whose
only target selector is the window. It is not a stage of the protocol and is
never run by a worker.
The sweep discovers the root and its flights through the runner's pure
--project-root query and contains no layout formula, identity rule, or
artifact basename. For each projected flight in order it applies these checks
and records the first that fails as state: "skipped" with a reason:
OWNER_PROJECTION_INCONSISTENT when the projected directory is not under the
projected root, INVALID_FLIGHT_DIRECTORY when the entry is a symbolic link or
not a directory, and ACTIVITY_PROBE_FAILED when the activity probe itself
fails. The probe is one find over the flight tree that does not follow
symbolic links and asks whether any entry, the flight directory itself
included, was modified within the window; the answer is recorded as
inactive. Modification time is the whole criterion: an attempt without
terminal status that has been silent longer than the window is treated as
abandoned and removed, because such orphans are exactly what accumulates. The
default window is the only safeguard for a live flight; a short window can
retire a flight whose carrier is still running silently, so the sweep must not
be run with a short window while a dispatch is in flight.
An active flight is kept. An inactive flight is would-remove in dry-run;
otherwise it is removed with one rm -rf of the projected flight directory and
recorded as removed, or as failed with reason REMOVE_FAILED when rm
fails or FLIGHT_REMAINS when the path still exists afterwards. A failed
removal may leave a partial flight whose refreshed directory time protects the
remainder until the window elapses again. Failures do not stop the sweep, as
each flight is independent. INT and TERM are recorded after the current
operation returns, the loop stops, and the report carries interrupted: true.
The report is one strict JSON object with schema_version, mode (delete
or dry-run), sshx_root, root_present, older_than_minutes,
interrupted, flights (in projection order, each with flight_id,
flight_dir, inactive, which is null for a skipped flight, state, and
reason, which is null unless skipped or failed), unrecognized (the root
entries the runner did not classify as flights, reported so a leftover is
never silently ignored), removed (the exact removed paths), and failed
(each failed flight with its reason). The sweep exits 0 after publishing a
report with no failed flight and no interruption, and 1 otherwise. Usage and
internal failures before publication emit no JSON; an internal failure after
deletion began lists the already removed paths on stderr.
Carrier
After jq, directory, brief, log, and executable codex preflight checks, the
runner performs one synchronous foreground call:
codex exec --json -C <work-target> --sandbox <sandbox> \
--skip-git-repo-check -o <last-message.txt> -The command's stdout and stderr go to the fixed diagnostic logs. There is no
timeout, supervisor, helper, PID state, signal propagation, process-group
handling, or KILL escalation. The carrier wait status is written atomically to
carrier.exit. A missing executable is LAUNCH_FAILED; once invoked, any
nonzero carrier status is CARRIER_EXIT_NONZERO.
INT and TERM traps set reason_code=INTERRUPTED and exit through the
normal EXIT trap. Bash may defer these traps while the synchronous foreground
command is running. The runner does not promise signal reachability in every
phase and does not tear down descendants.
Status Projection
status.json is written only by terminal cleanup; there is no startup or
in-progress status projection. Its status is exactly COMPLETE or
NOT_COMPLETE. It contains invocation identity, derived artifact and log
references, started_at, finished_at, duration_seconds, work_target,
sandbox, and brief_ref. Times use UTC ISO-8601
(%Y-%m-%dT%H:%M:%SZ); duration is the integer epoch-second difference when
both lookups succeed. A failed time lookup writes null and does not fail the
flight.
Informational Execution Failure
execution_failure is a runner-owned field of the same atomically published
terminal status, not a new artifact. It is null unless collection reaches an
invoked nonzero carrier. reason_code=CARRIER_EXIT_NONZERO, runner exit 1,
worker-artifact ownership and the completion checks remain unchanged. No result
or verdict is collected from that carrier, even if its worker artifacts exist.
This diagnostic may explain an unavailable execution after host completion; it
must never select retry/fallback, salvage a partial result, count as completion
evidence, or enter worker briefs or consensus decision inputs. The finite
caller retry/fallback path remains independent of failure category.
The non-null object has exactly these fields; no source strings are copied:
| Field | Values and meaning |
|---|---|
category |
UPSTREAM_OVERLOADED or UNCLASSIFIED; a recognized native report, not a worker verdict or a claim about account-wide availability |
terminal_event |
turn.failed when the final nonempty sampled line has that native shape with a string error.message; otherwise null |
error_events |
Number of sampled top-level error objects with a string message, saturated at 255; not a reconnect/retry count; null if scanning fails |
invalid_records |
Number of sampled nonempty lines that fail JSON parsing or are not objects, saturated at 255; unknown object types are ignored; null if scanning fails |
scan |
complete, tail, or unavailable; scope of this bounded observation, never event compliance or authenticity |
After carrier termination and atomic carrier.exit publication, the runner
reads at most the last 65,537 bytes of its regular, non-symbolic-link stdout
log once through tail, then parses this bounded sample with jq. If the
decoded sample exceeds 65,536 UTF-8 bytes, it marks tail and discards the first
sampled line, which may be partial. Invalid UTF-8 replacement can conservatively
mark a smaller sample as tail. Empty LF lines are ignored. Malformed or
unknown final input prevents classification of any earlier failure. Parse
errors and non-object records count as invalid; malformed native shapes and
unknown objects are unclassified. Nested item contents are never searched.
Earlier transient error events cannot classify a final turn, and error
without a final turn.failed remains unclassified. A scan read/parser failure
uses UNCLASSIFIED, null event/counts and scan: unavailable, with a fixed
progress diagnostic; it cannot change the carrier outcome. Zero-exit carriers
are not scanned, so native events cannot bypass or invalidate artifact checks.
The recognition allowlist is exactly Our servers are currently overloaded. Please try again later. and the same string prefixed with stream disconnected before completion: . Matching is exact and case-sensitive against the final
turn.failed.error.message. Other wording, structured codes or future shapes
remain UNCLASSIFIED. There is no raw error text, item, reasoning, prompt,
thread identifier, path, HTTP status, Retry-After, retry advice or timing
estimate in this object. Full stdout/stderr/last-message logs and log_ref
remain opaque; projection reads never modify them. This is mechanical
sanitization, not same-user filesystem tamper resistance or universal native
event compliance.
Source grounding: Codex CLI non-interactive JSONL documentation
lists error, turn.failed and item events; the pinned
0.164.0 native event definitions
define top-level error.message and nested turn.failed.error.message.
The overload wording is the caller-supplied #1077 observation, not a measured
HTTP response or server-internal cause. tests/test_run_codex_worker.py records
the pre-edit baseline and tests these shapes with synthetic carriers, including
unknown/malformed input, bounded scanning, opaque-log preservation, unavailable
projection and unchanged completion semantics. No live upstream replay is claimed.
Caller-Owned Time Boundary
The Codex configuration reference
documents provider stream_max_retries (SSE interruption count),
stream_idle_timeout_ms (SSE idle time), and request_max_retries (HTTP request
count). These are not a documented total reconnect or whole-invocation deadline;
an idle limit is not an elapsed-time limit, and retry counts do not bound the
duration of each request, backoff, or every transport. No supported total native
reconnect deadline is established by these sources. The runner adds no timeout
option, provider/config override (except the optional per-invocation native retry
controls documented in ## Invocation), supervisor, signal propagation or early
event notification. A caller needing a finite observable allowance must set a
whole-job harness limit and verify that harness's process-tree teardown; runner
PID termination alone does not establish teardown (see ## Teardown Prerequisite).
Only after termination, existing carrier_exit, started_at, finished_at
and duration_seconds report observed terminal facts. Duration is wall-clock
integer-second pre-call-to-cleanup time, includes collection, may be null, and
is neither reconnect latency nor a future bound. No HTTP status, retry timing or
timeout causality is inferred. The gated-carrier behavior test verifies there
is no status/exit publication while a carrier remains blocked, even when it has
already emitted a native failure and worker artifacts; its watchdog belongs
solely to the test harness.
Exit code is the sole authority: 0 means complete, 1 means not complete,
and 64 means usage error. status.json is a terminal, machine-readable
projection for callers that need structured data. stdout contains only the
structured launch receipt. stderr is a human-readable streaming log; it carries
no decision authority and is not guaranteed to be parseable.
status.json and the batch report are mechanical projections only. Neither is
a completion or verdict source under SKILL.md.
Before the synchronous carrier call, stderr reports all then-known invocation
identity and derived artifact paths followed by carrier starting. After the
call returns, it reports the carrier exit status; terminal cleanup then reports
status, reason_code, verdict, and duration. Every progress line begins with
a UTC ISO-8601 timestamp. stderr progress write failure is diagnostic only and cannot
change the authoritative exit decision.
Each progress write runs in a narrow subshell so a closed stream cannot override
that exit decision or change the carrier's signal disposition. Terminal
cleanup clears only its recursive EXIT trap and ignores
INT and TERM for the rest of publication, so a second signal cannot leave
the terminal projection half-published.
Terminal Projection
trap finish EXIT is the only terminal publisher and the script has one
process-terminating exit. The default is fail-closed INTERNAL_ERROR with
exit 1; only the final successful path changes the reason to COMPLETE and
exit 0. Other ordinary failures also exit 1. The first failure encountered in
the fixed check order determines reason_code:
PARSER_UNAVAILABLE, LAUNCH_FAILED, RUN_DIR_UNAVAILABLE, RUN_DIR_COLLISION,
CARRIER_EXIT_NONZERO, RESULT_MISSING,
ENVELOPE_INVALID, VERDICT_INVALID, SENTINEL_MISSING,
INTERRUPTED, or INTERNAL_ERROR.
After the attempt directory is owned, finish renders formatted (pretty-print)
status.json.tmp, then renames the temporary file to status.json. The status
contains invocation identity, status (COMPLETE or
NOT_COMPLETE), reason_code, carrier_exit (or null), derived artifact
references, diagnostic log references, the six fields started_at,
finished_at, duration_seconds, work_target, sandbox, and brief_ref,
the informational execution_failure, and a verdict only when the stage has a
verdict mapping. Before either
runner-owned projection is written, its temporary
and final target must be absent or a non-symbolic-link regular file. After each
rename, the fixed carrier.exit or status.json path must be a non-symbolic-link
regular file; every target-type or publication failure fails closed.
Both the primary rendering and the INTERNAL_ERROR fallback must exit zero and
produce a non-empty temporary file before rename. If both renderings fail,
the runner installs no status.json, reports INTERNAL_ERROR, and exits 1.
The renderer is not asked to validate its own output.
jq is mandatory. Parsing or structural failure is ENVELOPE_INVALID; no
text matching fallback exists. SKILL.md is the sole source of the exact stage
verdict sets. The runner's executable projection is kept bidirectionally equal
to that contract by tests; this specification does not repeat the sets.
No diagnostic surface participates in completion or verdict recognition:
stdout, stderr, last-message.txt, log tails, marker text, event streams,
process snapshots, repository state, and hashes are diagnostic only.
Callers obtain launch identity from the receipt and terminal details from
status.json; a Unicode-aware
splitter such as Python str.splitlines() may treat U+2028, U+2029, or U+0085
inside a path as logical separators even though those bytes are valid under
the POSIX text-line contract.
Teardown Prerequisite
Verified in two independent Claude Code harness experiments: TaskStop
terminates the entire process tree, including a child that actively ignores
TERM and INT; this indicates the harness uses SIGKILL or process-group
teardown. The runner therefore does not propagate signals.
Codex, Cursor, and Gemini host teardown behavior is unverified. An interactive
Ctrl-C normally sends INT to the foreground process group, which includes the
synchronous carrier. A default TERM sent only to the runner PID may be
deferred by Bash until the foreground carrier returns. An uncatchable SIGKILL
sent only to the runner PID can leave the carrier orphaned and running. The
runner does not attempt to compensate for any of these host behaviors.
Threat Model
The carrier is an internally dispatched Codex worker: trusted is
non-adversarial, not infallible. The runner rejects normal malformed output,
missing artifacts, and accidental projection-path type collisions, but it is
not a sandbox against a hostile carrier. This design does not defend TOCTOU
races, including caller-brief replacement after the dispatcher's readability
probe or flight changes after cleanup's repeated eligibility check; those checks
narrow their respective windows but do not make object identity immutable. It
also does not defend an active setsid escape, forged runner artifact paths, or
deliberate replacement of files inside the owned attempt directory. An
untrusted carrier or a requirement to cover those attacks requires a new design
review rather than more checks in this runner.
Boundaries
The runner has no git, GitHub, label, release, host lifecycle, cleanup, or
global-state authority. Time limits and whole-job teardown belong to the
caller harness. Power-loss durability is not guaranteed. Deletion authority
lives only in clean-codex-worker-runs.sh, bounded to terminal-only,
manifest-named, whole-flight artifact retirement with dry-run default and no
force override, and in prune-inactive-codex-worker-runs.sh, bounded to
whole-flight removal under one inactivity window over the runner-projected
root.
No other skill may depend on these mechanisms. To reverse the exception completely, use this one recipe:
- First reverse the oracle runner with the recipe in
ORACLE_WORKER_SPEC.md, because it consumes this runner's path projection. - Delete
scripts/run-codex-worker.sh,scripts/run-codex-worker-batch.sh,scripts/read-codex-worker-status.sh,scripts/clean-codex-worker-runs.sh, andscripts/prune-inactive-codex-worker-runs.sh. - Delete this specification,
tests/test_run_codex_worker.py, andtests/test_codex_worker_tools.py. - Restore the narrow
SKILL.mdclauses to direct caller dispatch with caller-assigned artifact paths and a prompt-only boundary that forbids every helper script. - Remove mechanical-script assertions from
tests/test_sshx_contract.pyand run the remaining sshx contract suite. No compatibility shell is retained.
A new design review is required before adding daemon behavior, lifecycle
authority, a second consuming skill, or completion semantics cease to be
isomorphic to SKILL.md's ## Worker Completion Contract.