Skip to content

fix(codex): preserve refusals when fallback access is denied - #145105

Merged
steipete merged 2 commits into
mainfrom
codex/codex-fallback-terminal-20260911
Sep 11, 2026
Merged

steipete merged 2 commits into
mainfrom
codex/codex-fallback-terminal-20260911

Conversation

@steipete

@steipete steipete commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor

Problem

A configured Codex fallback denied with 401/403 before assistant output could escape unavailable-target classification. The plugin read an obsolete top-level error field while the runner produced a canonical terminal result, so later refused turns repeated the denied target and the unavailable notice was missed.

Changes

Read failure details through the canonical terminal projection and derive the classifier input type from the runner contract. Preserve the original refusal for an unavailable target only when the fallback has a normal failure, affirmative replay safety, and no tool progress. Otherwise return the entire fallback result so delivery receipts, tool activity, native continuation and interruption reach the outer runner with their original identity.

Native continuation also prevents replaying an already-active primary attempt, and canonical cancellation, timeout or another failure supersedes a retained refusal diagnostic. The workspace cooldown, one-attempt fallback limit, prompt-persistence suppression and stored model selection remain unchanged. Runtime docs describe these outcomes and distinguish the plugin fallback from native retry handling.

Validation

  • Before the original repair, real-projector harness cases for 401 and 403 made four native-attempt calls across two same-workspace refusals instead of three.
  • Seven preservation regressions failed before the corrective guard: messaging and accepted-child effects, native continuation, abort, timeout, read-only tool progress, and primary continuation replay. Three additional primary-refusal cases proved that cancellation, timeout or another failure caused an unwanted second attempt; the canonical terminal eligibility check repairs those cases. All 97 focused tests now pass across four files.
  • The tests exercise the actual projector, harness, classifier, planner, cache and notices. Native execution is mocked. Continuation and interruption cases inject canonical finalizer-owned result facts at the runner seam; they do not execute live cancellation or the full finalizer.
  • Two public-entry tests used obsolete success-only result fixtures; both reproduced the missing-terminal error and pass with canonical terminal fixtures.
  • The existing separate-workspace case verifies a successful fallback remains eligible. Tests also check notice emission, original-result identity for a simple denial, prompt persistence and unchanged model selection.
  • The full changed-code gate passed, including both extension typechecks, lint, dependency and storage guards, dead-code scans, and zero runtime import cycles. Fresh independent review is clean through P2.
  • Final-head CI passed. The first Linux job and second Linux job executed all 97 focused cases on Ubuntu 24.04.3 / Node 24.19.0. All seven PR file blobs match between the head and the executed CI merge.
  • Two standalone remote leases failed during setup before dispatching their test commands; both were stopped and their workflows are cancelled. Those attempts remain failures and are not counted as passing proof.

Native source was inspected for the failed-turn and refusal contracts. Installed binary parity, live entitlement, reconnect latency and real model execution were not verified. General multi-attempt usage aggregation is an existing limitation outside this change. No configuration defaults, schema, dependencies or additional retries are introduced.

@clawsweeper

clawsweeper Bot commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation extensions: codex size: M maintainer Maintainer-authored PR labels Sep 11, 2026
@steipete
steipete marked this pull request as ready for review September 11, 2026 17:39
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Sep 11, 2026
@clawsweeper

clawsweeper Bot commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed September 11, 2026, 2:19 PM ET / 18:19 UTC (Revision 2).

ClawSweeper review

What this changes

The Codex plugin recognizes denied fallback access from canonical attempt results while preserving tool progress, side effects, continuation, and interruption outcomes.

Merge readiness

✅ Ready for maintainer review

Keep open: current main still has the terminal-field mismatch, and this focused repair has no supported blocking findings.

Priority: P2
Reviewed head: 062355da299e96972c9e938f897011224386c012

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused contract repair with meaningful regression coverage and no blocking finding; native runtime validation is accurately disclosed as unverified.
Proof confidence 🌊 off-meta tidepool Not applicable: The maintainer-authored exemption applies. Tests exercise the production projector, harness, classifier, cache, and notices with mocked native attempts; after-fix native execution remains unverified, and the reported remote setup failures and earlier UI screenshots are not counted as proof of this repair.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: The maintainer-authored exemption applies. Tests exercise the production projector, harness, classifier, cache, and notices with mocked native attempts; after-fix native execution remains unverified, and the reported remote setup failures and earlier UI screenshots are not counted as proof of this repair.
Evidence reviewed 9 items Current main still needs the repair: Current main reads result.promptError, whereas the projector places ordinary failures in terminal and can produce no assistant message. A denial before assistant output therefore escapes the existing classifier.
Canonical result and preservation guards: The classifier consumes the existing terminal projection and excludes superseded refusals and native continuations from replay. The harness retains the original refusal only for a replay-safe failed fallback with no tool progress; otherwise it returns the fallback object intact.
Producer and finalizer contracts: The projector converts provider refusals into diagnostic assistant rows without a prompt failure, computes replay safety from observed effects, and always supplies toolMetas. Finalization applies stronger terminal outcomes and attaches native continuation to the same result object.
Findings None None.
Security None None.

How this fits together

The Codex plugin connects OpenClaw agent turns to Codex app-server. Its fallback policy reads completed attempt results, decides whether one retry is safe, and returns results and notices to the outer runner.

flowchart TD
  A[Selected model attempt] --> B[Canonical attempt result]
  B --> C{Completed refusal and safe to retry?}
  C -->|No| G[Return attempt result]
  C -->|Yes| D[Configured fallback attempt]
  D --> E{Denied without progress or interruption?}
  E -->|Yes| F[Remember denial and retain original refusal]
  E -->|No| G
  F --> G
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source +4, Tests +298, Docs +6. Total +308 across 7 files.

View PR surface stats
Area Files Added Removed Net
Source 2 33 29 +4
Tests 4 352 54 +298
Docs 1 12 6 +6
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 7 397 89 +308

Review metrics

Metric Value Why it matters
Production versus regression coverage production net +4 lines; tests net +298 lines The small production increase adds result-preservation guards, while most growth exercises previously missed terminal outcomes.

Technical review

Best possible solution:

Keep fallback classification on the canonical terminal contract and preserve the complete result whenever the fallback progressed or was interrupted.

Do we have a high-confidence way to reproduce the issue?

Yes, from source: a fallback 401/403 before assistant output populates terminal while current main reads an absent top-level error. The focused tests exercise that path, but this review did not execute it.

Is this the best way to solve the issue?

Yes. Reusing the existing terminal projection repairs the contract mismatch without adding another error owner, configuration surface, or retry mechanism.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against ebb7cb266fb6.

Labels

Label justifications:

  • P2: This repairs a bounded Codex fallback failure that otherwise repeats denied attempts and loses the intended unavailable outcome.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🌊 off-meta tidepool and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Not applicable: The maintainer-authored exemption applies. Tests exercise the production projector, harness, classifier, cache, and notices with mocked native attempts; after-fix native execution remains unverified, and the reported remote setup failures and earlier UI screenshots are not counted as proof of this repair.

Evidence

What I checked:

Likely related people:

  • unknown: The claimed source-line change could not be verified from bounded local history. (role: source history unknown; confidence: low)

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

History

Review history (1 earlier review cycle)
  • reviewed 2026-09-11T17:45:15.196Z sha c343e94 :: needs maintainer review before merge. :: none

@steipete
steipete merged commit c3406f7 into main Sep 11, 2026
155 of 156 checks passed
@steipete
steipete deleted the codex/codex-fallback-terminal-20260911 branch September 11, 2026 18:36
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

nvtoroy added a commit to nvtoroy/openclaw that referenced this pull request Sep 11, 2026
…1009)

Adds plugins.entries.codex.config.appServer.nativeHookRelay = { enabled? } -
a single narrowly scoped opt-out wiring the existing internal relay options of
the run-attempt and side-question paths to plugin config. Without the key the
parse layer returns the historical { enabled: true } byte-for-byte.

The parse layer carries no policy logic. A single guard
(resolveCodexNativeHookRelayForApprovalPolicy) applies the safety floor in
both run paths after runtime policy resolution, keyed on the EFFECTIVE
approval policy - the resolved value, which can force a prompting policy over
a configured "never" (unknown-model or exec-mode reviewer forcing, forced
guardian reviewer, forced danger-full-access sandbox), and on the
side-question path is the bound thread's policy when a persistent binding
carries one:

- effective "never" AND no active OpenClaw before-tool policy
  (hasBeforeToolCallPolicy(): before_tool_call hook or trusted-tool policy -
  the same predicate the relay's own local-work gate uses) -> the opt-out is
  honored verbatim: the opt-out overlay clears OpenClaw's four session-layer
  hook arrays and writes disabled hooks.state markers for its session-layer
  command keys, leaving features.hooks and independent user/project/plugin/
  managed Codex hooks untouched (review finding: features.hooks=false would
  disable the whole hook engine pre-discovery; the overlay also deliberately
  OMITS features.hooks rather than asserting true, because it merges last and
  would otherwise re-enable hooks for ring-zero callers). The harness-
  restricted sandbox path keeps full suppression via its own builder. This is
  the constrained-host case from openclaw#91009, including stock yolo deployments.
- otherwise (a prompting/forced effective policy, or an active before-tool
  policy under explicit "never") -> enabled:false narrows to the required
  before-tool policy relay (events: ["pre_tool_use"]) and logs a one-line
  deduped warning naming the actual reason. The floor mirrors
  loopDetectionPreToolUseRelay's contract ("before-tool plugin hooks and
  trusted-tool policy still install their required relay").

Event scoping stays an internal option of the run paths with upstream's own
semantics (openclaw#116117, "honor hook approval ownership"); it is deliberately not
exposed to operator config. The
relay object is strict at BOTH boundaries: the plugin manifest
(additionalProperties: false) rejects unknown keys at load time with a named
config error, and the zod parser stays strict as defense in depth; covered at
the manifest/loader boundary against the real manifest.

The approval transport is out of this key's reach by construction: approvals
ride the app-server approval bridge over JSON-RPC and fall back to the
in-process before_tool_call hook when the relay is absent. The forced-policy
case is pinned by an integration test through
resolveCodexAppServerRuntimeOptions; a manifest/zod parity test covers the
schema. An opt-in live capture lane
(gateway-codex-harness.native-hook-relay-proof.live.test.ts) reproduces the
wire evidence against a real codex app-server and asserts the captured
thread/start and thread/fork hook overlays per mode and per path.

Rebased onto app-server 0.153.4 main. Three adaptations were needed. (1) The
managed-only hook attestation added since the merge base gates
assertCodexNativeHookRelayAllowed on nativeHookRelayRequired, which read the
RAW operator relay config; a narrowed opt-out would therefore have skipped
attestation while still installing the enforcing relay, failing open on
allowManagedHooksOnly installs. It now reads the guarded shape, so the
narrowing arms the assert instead of disarming it (regression test added).
(2) openclaw#128464 removed resolveCodexAppServerForOpenClawToolPolicy and its
never->untrusted promotion; the effective policy now comes from
applyCodexSessionPermissionPolicy, which never consults
hasBeforeToolCallPolicy() and resolves permission mode "full" to "never". The
guard's two-predicate design is unchanged, but its rationale comment now cites
session permission modes and config-runtime's forced policies. (3) Loop
detection became explicit opt-in and the selected-but-no-work PreToolUse
marker was removed, so the live proof lane now enables tools.loopDetection so
its "installed" expectations still hold and attestation is exercised;
deliberately loop detection rather than a global before_tool_call hook, which
would narrow the disabled-never mode and stop the lane proving the full
kill-switch.

Re-based again onto current main. The three adaptations above still hold; the
refresh only followed upstream moves. The reference table the relay row lives in
was split out to docs/plugins/codex-harness-reference/app-server-transport.md.
CodexPluginConfig is now derived from the zod schema, so the relay field comes
from config-parsing and CodexNativeHookRelayOptions moved to the leaf
config-contracts.shared.ts (config-contracts re-exports it) to keep the module
graph acyclic. Live-shard membership is now discovery-driven, so the proof lane
needs no shard-list edit; it still routes to native-live-src-gateway-core. On
the side-question path the guard keys on appServer.approvalPolicy, the same
value the relay's own event scoping uses, rather than the MCP-elicitation-
widened policy introduced since, which grants elicitation only and opens no
tool-approval path.

Coverage extended to the canonical fork preparation path (openclaw#134660).

Proof-lane refresh: request/test timeouts resized to real backend latency, the two approval modes migrated off the retired "untrusted" policy to on-request with an explicit approvalsReviewer: "user" so the escalation escapes the in-process auto_review subagent and is observable on the wire, and all captures re-recorded on codex 0.153.4 / gpt-5.6-terra.

The proof lane also covers existing-session transitions (mode `transition`): one
gateway, one session and one native thread across three real turns while an
operator flips `nativeHookRelay.enabled` off and back on between them. Phase 1
opens the thread with `thread/start` and installs the relay; the flip changes the
merged thread config, so the warm live-thread path's config fingerprint no longer
matches and each later turn is served by a cold `thread/resume` carrying the whole
rebuilt config - the opt-out overlay in phase 2, the relay restored byte-for-byte
in phase 3, on the same thread id. Every phase also asserts that each `hooks.state`
key the overlay writes names OpenClaw's own `<session-flags>` layer and that
`features.hooks` is never written false, which is the mechanical form of "the
opt-out cannot reach a hook it did not install": Codex discovers hooks per config
layer and keys their state by source path.

Re-based onto current main once more; five adaptations, none of them behavior on
the configured path. (1) The cyber-refusal escalation added to `runAttempt` since
the last rebase now runs both its attempts with the resolved relay options rather
than the hardcoded literal, so an escalated retry carries the same kill-switch
decision as the first try. (2) The plugin entry no longer imports the
`app-server/config.js` barrel eagerly, so the harness reads
`resolveCodexAppServerNativeHookRelay` from the `config-parsing.js` leaf it already
loads; importing the barrel would have pulled the app-server runtime graph into
plugin registration (registration-imports.test.ts pins that boundary).
(3) `config-contracts.ts` no longer re-exports `CodexNativeHookRelayOptions`: every
consumer reads the canonical `config-contracts.shared.ts`, and the re-export had no
callers. (4) The live proof lane moved to `src/gateway/test/` and split per topic -
the five static modes, the existing-session transition, and a shared
`*.test-helpers.ts` that owns the gateway bootstrap both use: `src/gateway/*.test.ts`
sits at the 720-root tsgo core-test shard cap, and the single file had outgrown the
1000-line test ceiling. The new attestation suite joins the codex attempt-extra
vitest project so every full-suite test file keeps exactly one owner. (5) The
kill-switch raises the plugin config-surface budget by the two entries it adds
(`nativeHookRelay` and its `enabled` flag) in
docs/.generated/config-baseline.counts.json.

Rebased onto current main again (8b343fc). One further adaptation, in the
tests only: openclaw#145105 made `readCodexCyberAttemptVerdict` read `result.terminal.kind`
directly, so an attempt result without a `terminal` now throws where it previously
read as "not refused". The stub results in this change's own harness and plugin
tests, which only pin the relay options `runAttempt` forwards, carry the same
`{ terminal: { kind: "ok" } }` shape upstream gave its fixtures in that commit.
The escalation invariant is unchanged and still holds: both attempts run through
one `runAttemptOnModel` closure over the resolved relay options, so a retry can
never widen the kill-switch decision the first attempt ran under.
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 12, 2026
…w#145105)

* fix(codex): preserve refusals when fallback access is denied

* fix(codex): preserve fallback effects and terminal ownership
@VACInc

VACInc commented Sep 13, 2026

Copy link
Copy Markdown
Member

Related embedded-runtime follow-up: #145291 (#145291) is now merged. Its Daybreak attempt uses local auth-failure accounting, restores the original refusal after a clean failed attempt, and preserves committed-work and terminal outcomes instead of pretending nothing ran. This complements the Codex-plugin repair here; it does not replace this PR's native continuation, interruption, or denied-target handling.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

docs Improvements or additions to documentation extensions: codex maintainer Maintainer-authored PR P2 Normal backlog priority with limited blast radius. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: M status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants