Commit Graph

503 Commits

Author SHA1 Message Date
jif
4e6d5c0a96 Move Guardian reporting and denial accounting into the extension (#44544)
## What changed

- Move assessment event construction, metrics, and analytics tracking into `codex-guardian-reviewer` through `ReviewReport`.
- Store denial accounting in thread extension data through `ReviewDenials`, with core retaining turn interruption and lifecycle cleanup.
- Move failed-review record selection and bounded serialization into the extension, with core supplying captured review context.

## Testing

Add coverage that denial accounting clears on turn completion and interruption. Move the oversized-record test into the extension and exercise the new API.

GitOrigin-RevId: 6e5b3d9d4128b356f99b1d0e74a68111e40261ab
2026-09-10 14:13:57 +00:00
jif
eca63f0803 Move Guardian reviewer settings and execution into the reviewer crate (#44536)
## What changed

- Move reviewer configuration overrides, turn request construction, and deadline, cancellation, and completion handling into `codex-guardian-reviewer`.
- Adapt core sessions through `ReviewerRuntime`, keeping context construction, managed constraints, and live network rules in core.
- Make `GuardianReviewSession` crate-private and remove direct reviewer pool initialization and the reviewer dependency from `guardian-v2`.

## Testing

Update the turn-draining test to exercise `wait_for_guardian_review`, checking that prior-turn completion events are ignored and the session remains reusable after draining the current turn.

GitOrigin-RevId: fdf2b335b88b3f405d2370298ee68932808e1186
2026-09-10 13:49:08 +00:00
jif
ed6dde9fda Decouple session isolation from subagent attribution (#44521)
## Why

Session isolation relied on Guardian source attribution. An explicit policy lets callers control inherited capabilities independently of how a session is attributed.

## What changed

- Add `SessionIsolation` with default `Inherit` and opt-in `Isolated` modes, captured at session startup through `ExtensionDataInit`.
- Use the policy to control inherited instructions, extensions, execution rules, and MCP resources. Isolated sessions retain managed execution rules and omit executor-discovered MCP servers.
- Explicitly isolate Guardian reviewers while preserving source-based fallback for older callers and saved reviewers.

## Testing

Extend delegate tests to cover isolation independently of attribution, update execution-policy coverage to supply the explicit policy, and assert that managed reviewers do not inherit the parent's configured MCP tools.

GitOrigin-RevId: f0ab42fa2f0237860ec661e72693ab191216afbf
2026-09-10 12:52:27 +00:00
felixxia-oai
9688359977 Bound MCP descriptions separately from Guardian action JSON (#44493)
## Why

MCP tool and connector descriptions were included in required action JSON, consuming review input budget even though they are optional metadata.

## What changed

Move `tool_description` and `connector_description` into an optional, explicitly untrusted `guardian_tool_descriptions` fragment. Limit each description to 400 estimated tokens, escape closing tags, and allow budget enforcement to omit the fragment while retaining the required action JSON. Preserve nested arguments such as `arguments.description` and mention tool descriptions in the budget omission notice.

## Testing

Add regression coverage for oversized descriptions, escaped closing markers, and budget eviction without changing action arguments. Update MCP approval and elicitation tests to verify descriptions appear separately from the action JSON.

GitOrigin-RevId: 30734567c2ebc4b180110276c83d79ddb315ceab
2026-09-10 10:38:10 +00:00
jif
5d3fe48b08 Improve Guardian retries and review failure reporting (#44482)
## Why

Transient rate limits can end automatic approval reviews prematurely, and review failures currently report high risk even when no assessment completed.

## What changed

- Retry rate limits and recoverable exhausted-stream errors, while excluding non-transient HTTP failures.
- Preserve server retry delays after stream retries are exhausted and honor them within the review deadline. Scope retry advice to the current turn so reused sessions cannot apply stale delays.
- Keep failed reviews denied, but leave risk and authorization unset and explain that the review could not complete without declaring the action unsafe.

## Testing

Add an integration test covering rate-limit recovery through approval and tool execution, asserting that the action executes exactly once after approval. Update failure assertions to check absent assessment fields and the review-failure explanation.

GitOrigin-RevId: 1163cfde35c6b8eb23b6f24f1f24461b86ded838
2026-09-10 09:50:59 +00:00
Eric Traut
0735c51978 Block goals after three empty automatic continuation turns (#44320)
## Why

Automatic goal continuations can repeatedly return empty final answers without
making progress. Stop this loop by marking the goal as `blocked` after three
consecutive empty turns with no other activity.

## What changed

- Observe completed turn items through a new `on_item_completed` lifecycle hook.
- Track empty final answers only for automatically admitted goal turns, resetting
  the streak on activity, user turns, or goal changes.
- Preserve normal turn completion and streamed message deltas when blocking a goal.

## Testing

Add accounting coverage for the three-turn threshold and streak resets, plus
app-server tests for empty continuations and recovery through final-answer text,
commentary, or tool activity.

GitOrigin-RevId: 4b9d2cb2e306b0adc316972429cc35000115b88b
2026-09-09 22:27:37 +00:00
joeytrasatti-openai
742472c525 Set turn triggers for guardian and memory requests (#44298)
## What changed

Populate `turn_trigger` in request metadata with `guardian_review` for guardian reviews, `guardian_classifier` for classifier requests, and `memory_consolidation` for both detached memory requests and consolidation agent turns.

## Testing

Extend request metadata assertions to cover each trigger across guardian reviews, classifier requests, and both memory startup phases.

GitOrigin-RevId: 2dc3c173ede6563b942b8099ad9901c32967b969
2026-09-09 20:32:57 +00:00
felixxia-oai
72348693ec Enforce the async Guardian classifier's complete input budget (#44293)
## Why

Async classifications need to account for the complete request, including parent compaction checkpoints and images, before sending it to the classifier.

## What changed

- Resolve the input allowance from the classifier's model metadata, independently of parent-model context-window overrides.
- Reject requests whose estimated input exceeds that allowance minus a 256-token reserve. Record `input_too_large` and defer to synchronous review without sending the oversized request or dropping evidence to make it fit.

## Testing

Add integration coverage for checkpoint and image budgets, verifying that oversized inputs defer to synchronous review and inputs that fit retain their evidence. Update Guardian context-budget tests to exercise V2 remote compaction.

GitOrigin-RevId: 765060e08d2d5f3028ef5207508d256d4bf8d856
2026-09-09 20:10:01 +00:00
Eric Traut
fa7af3883d Allow user-requested goal pauses through update_goal (#44290)
## Why

`update_goal` only accepted `complete` and `blocked`, preventing the agent from pausing a goal in response to an explicit user request.

## What changed

- Accept `paused` and account for final goal progress when pausing, with budget limits taking precedence.
- Update tool instructions and goal prompts to allow pauses only at the user's explicit request, report the returned status, and stop goal work. A later resume revokes the pause request.

## Testing

Extend coverage for pause accounting, budget-limit precedence, rejection of resume and system-limit statuses, and preservation of a tool-paused goal when resuming a thread.

GitOrigin-RevId: c3c15a51f848ce6eb65854d51b1a1bc75bb456a7
2026-09-09 20:03:38 +00:00
jif
2617ed2e1c Move synchronous Guardian orchestration into the reviewer extension (#44252)
## What changed

Move the synchronous review loop, outcome mapping, deadline helpers, and session pool into `codex-guardian-reviewer`. Core supplies adapters for evidence capture, authorization checks, session creation, and event publication through the new host interfaces.

Have `guardian-v2` initialize the reviewer pool and host separately, with the pool managing prewarming, session reuse, concurrent forks, invalidation, and shutdown.

## Testing

Extend the app-server reviewer lifecycle test to cover interrupted concurrent reviews as well as completed reviews, including resuming a reviewer after parent shutdown. Adapt core reviewer tests to use the pool and factory interfaces.

GitOrigin-RevId: 2d69bd20c169b20534764b98cbdb63f38564a530
2026-09-09 17:59:10 +00:00
jif
e8e7103cb9 Extract Guardian review policy into a dedicated crate (#44227)
## What changed

Move assessment parsing and schema, model selection, review outcomes, retry handling, and rejection circuit breakers into `codex-guardian-reviewer`. Update core to use the extracted APIs while retaining session execution and decision enforcement in the host.

## Testing

Move existing assessment, circuit breaker, and retry tests into the new crate, including coverage for transient errors, cancellation, and deadlines.

GitOrigin-RevId: 96ec9989a0066acb012bf3bec0b9f7d8bf11a4ef
2026-09-09 17:31:37 +00:00
Abhinav
8ff4aa8ee4 Use captured step model settings for extension context (#44202)
## Why

Model switches within a turn can leave extension context using stale model metadata. Skill catalogs, context windows, and metric attribution need to match the model captured for each sampling step.

## What changed

- Pass captured model metadata and step-specific telemetry to world-state contributors.
- Use that metadata for skill catalog budgets and usage instructions, preserving configured budget overrides.
- Supply the captured model's usable context window to turn-context contributors, including when rebuilding context.

## Testing

Add regression coverage for model switches during skill discovery, catalog budgets and metric attribution, and extension context windows after `new_context` and retained-step context rebuilds.

GitOrigin-RevId: c51b40b739a380b9767a54ea8c8ee6de45bf01c8
2026-09-09 16:48:49 +00:00
felixxia-oai
2bba3a29a0 Use explicit histogram buckets for Guardian context metrics (#44181)
## Why

Guardian request and section cost distributions need shared bucket boundaries across synchronous and asynchronous reviewers so their measurements align.

## What changed

- Add `histogram_with_boundaries` to session telemetry and extension metrics while preserving session attribution.
- Use shared request-token buckets up to 2,000,000 tokens and section-cost buckets up to 16,777,216 for both review paths.

## Testing

Extend telemetry tests to verify explicit bucket boundaries and sample counts, and Guardian integration coverage to check exported request and section metric bounds for both synchronous and asynchronous reviews.

GitOrigin-RevId: e34f6972b3418bac3b061939b62eeeccaec5a299
2026-09-09 15:48:39 +00:00
felixxia-oai
d3ffbbed5a Add Guardian context cost and request token telemetry (#44164)
## What changed

- Record per-section text bytes, estimated text tokens, image bytes, and image counts for synchronous reviews and asynchronous scoring without logging evidence payloads.
- Emit estimated request tokens through `codex.guardian.context.request_tokens`. Synchronous estimates include assembled history, instructions, tool definitions, and output format, and measure the full logical request before WebSocket delta generation. Asynchronous estimates cover the assembled input.
- Add shared context budgeting helpers, including conservative image token reservations independent of encoded payload size and model-aware input limit calculation.

## Testing

Add coverage for separate text and image accounting, image estimates independent of encoded size, and section estimates that bound delivered messages. Extend asynchronous scorer and app-server tests to verify cost metric emission.

GitOrigin-RevId: aed45ecd9c23706f88caa51f2a4f2c77872d3bdb
2026-09-09 14:48:08 +00:00
Chris Dong
929389f596 Preserve per-image generation IDs in image generation analytics (#43953)
## What changed

Parse optional `generation_id` values from image API responses and carry the selected image's ID through the image generation tool into analytics events. Keep the ID out of serialized extension items, JSON schemas, and TypeScript types. Responses without an ID remain supported.

## Testing

Add coverage for distinct IDs in multi-image responses and responses without IDs. Extend analytics and app-server tests to verify that the selected image's ID reaches analytics, and item tests to verify that it is omitted from serialization and TypeScript types.

GitOrigin-RevId: 70a600856990140b76fdbda51a0d73b3414338b1
2026-09-09 00:34:45 +00:00
Eric Traut
7c098d8741 Gate new turn submissions on host shutdown admission (#43943)
## Why

Hosts need to stop new turn-input work during shutdown without consuming pending input or preventing already-running delegated work from finishing.

## What changed

- Add an optional `TurnStartAdmission` extension gate, checked before reserving or starting a new turn. Hosts without a gate retain existing behavior.
- Return `NotSubmittedReason::ServerDraining` for refused starts and surface an app-server error instructing clients to reconnect and retry.
- Keep steering, parent-delegated subagent input, and memory-only mailbox wakeups available during drain, while gating automatic starts.
- Close realtime conversations with an ordered handoff, error, and close event sequence when a handoff is refused during drain.

## Testing

Add regression coverage for rejected input staying out of subsequent requests, persisted queue items remaining available for later starts, delegated agent and review work completing during drain, mailbox wakeups, and realtime handoff error ordering.

GitOrigin-RevId: 03dbdcd71eab200e597c0649e6eb39bd92dbc82f
2026-09-08 23:45:10 +00:00
jif
553df1c691 Add dedicated memory v2 consolidation and read prompts (#43813)
## What changed

- Consolidate v2 rollout summaries into `memory_summary.md` without generating `raw_memories.md` or requiring `MEMORY.md`. Validate the summary's required sections and size below 10,000 UTF-8 bytes.
- Add v2 read instructions for selective history retrieval, evidence-grounded preferences, citations, and explicit memory edits. Split injected instructions into fragments to preserve the complete summary within fragment byte limits.
- Record memory citation usage in the store selected by `memories.version`.

## Testing

Add coverage for v2 consolidation without a handbook, summary validation, version-isolated memory reads, and resetting both memory versions while preserving threads.

GitOrigin-RevId: 1d895fb4a23a973f1a45ba03be07a1f480c10227
2026-09-08 12:58:11 +00:00
felixxia-oai
0337192dfd Centralize Guardian transcript policy in context profiles (#43806)
## What changed

Add `ContextProfile` to `codex-guardian-context` and route synchronous and asynchronous Guardian transcript rendering through it. Move default limits, retention, formatting, and async chunked eviction into the shared crate while preserving the distinct retention policies and host-managed full/delta cursors.

Carry transcript truncation observations through `RenderedTranscript` into context composition, and derive async image collection flags from the resolved profile.

## Testing

Add a profile regression test covering distinct sync/async retention priorities, original entry numbering, omission notes, and async truncation observations. Adapt existing transcript tests to the updated input API.

GitOrigin-RevId: 7f7dc249629d8017e9547085f6617f815ae43a1b
2026-09-08 12:17:28 +00:00
felixxia-oai
0034ef93a7 Centralize Guardian context composition (#43805)
## Why

Synchronous approval reviews and asynchronous scoring assemble Guardian evidence separately, duplicating transcript framing and section placement.

## What changed

- Move evidence ordering, framing, and delivery into `codex-guardian-context`, while keeping transcript retention, budgets, and delta cursors with their callers.
- Pass composed messages directly to the asynchronous sampler, preserving roles, annotations, trusted message boundaries, and image placement.
- Reject unsupported synchronous delivery with `SectionError::UnsupportedDelivery` instead of silently dropping content.

## Testing

Add composition coverage for preserving separate messages and rejecting them for synchronous delivery. Extend Guardian integration coverage to check trusted tool and skill messages, mixed text and image evidence ordering, and full and delta review framing.

GitOrigin-RevId: efc06695ee4e2b7400b123b77ef2a21c8bf40646
2026-09-08 12:06:44 +00:00
jif
3f76e88a48 Add configurable memory versions with isolated storage (#43797)
## What changed

- Add `memories.version` with `v1` as the default and `v2` as an opt-in selection.
- Route memory generation, summaries, and retrieval tools through the selected version. Store `v2` artifacts in `memories_v2` and lazily create a separate SQLite database, keeping jobs and outputs isolated while sharing the thread catalog.
- Preserve the initial memory version across extension config updates so summaries and retrieval tools use the same namespace.
- Clear both versions on memory reset and remove thread memory from both stores on thread deletion. Recognize both artifact roots in shell usage telemetry.

## Testing

Add regression coverage for version defaults and validation, independent job claims and outputs, deletion and reset across versions, and shell usage classification for both memory roots.

GitOrigin-RevId: aa799bf87ab6ec10c8f5668213931e57547d080b
2026-09-08 10:55:48 +00:00
felixxia-oai
d75ed505d7 Move Guardian REPL evidence rendering into the shared context registry (#43602)
## What changed

Move completed REPL response rendering into `codex-guardian-context` and register a synchronous-only `NodeReplEvidence` section. Core supplies a borrowed view of its evidence snapshot and retains responsibility for capture, storage eviction, and the delivery cursor.

Preserve the existing text and multimodal layouts, rendering bounds, omission markers, image ordering, and deduplication. Exclude evidence payloads from the rendered section's debug output.

## Testing

Adapt the existing evidence tests to exercise the shared renderer. Extend registry coverage to verify synchronous-only inclusion, rendered content, and omission of evidence payloads from debug output.

GitOrigin-RevId: eb181870558a7f2f77270dee7c17d36700f3e148
2026-09-07 21:54:56 +00:00
felixxia-oai
b4373e53ab Move Guardian image selection into shared context sections (#43601)
## What changed

Move bounded transcript image collection into `codex-guardian-context` and expose it through an optional `TranscriptImages` section. Update the async scorer to consume this section, preserving source filtering, image detail, omission accounting, and the existing limits of four images and 8 MiB of image URL data.

## Testing

Add coverage for source order, tool-output filtering, disabled image collection, oldest-image eviction, oversized images, and omitted-byte accounting.

GitOrigin-RevId: 097799ea1be6d73b347088f959de1fd23f02ec2c
2026-09-07 21:46:23 +00:00
felixxia-oai
f5331dc237 Move trusted skill evidence into the Guardian context registry (#43599)
## What changed

Move trusted skill rendering into `codex-guardian-context` as `TrustedSkills` and collect it through an async-only context section. Pass the collected section to the sampler, preserving the separate developer message and bounded JSON rendering. Omit skill paths from `Debug` output, exposing only their count.

## Testing

Move rendering tests alongside the shared type, covering multiple paths and escaped UTF-8 within the size budget. Extend registry tests to cover async-only inclusion, omission for empty input, section ordering, and path redaction in debug output.

GitOrigin-RevId: c0778067f19d31e693ca954aee1a7d7be8f9739a
2026-09-07 21:38:25 +00:00
felixxia-oai
2554239561 Move trusted tool metadata into shared Guardian context (#43597)
## What changed

Represent host-verified tool metadata as `TrustedTool` in `codex-guardian-context` and collect it through an async-only context section. Route Guardian v2 sampling through that section while preserving separate developer-message delivery and the 512-token rendering budget. Omit tool metadata from debug output.

## Testing

Move the rendering-budget test into the shared crate, extend registry coverage for async-only collection and debug redaction, and narrow the scoped approval test to messages tagged `guardian.trusted_tool`.

GitOrigin-RevId: ee7cb4e9b9ceced70438cb58060d1a2973e1dc6a
2026-09-07 21:29:31 +00:00
felixxia-oai
0b9b5ecff3 Centralize bounded Guardian review evidence in guardian-context (#43595)
## What changed

Move prior-review rendering and developer-message construction into `codex_guardian_context`, and route async scorer evidence through a dedicated `PreviousReviews` context section.

Validate a maximum of eight review fragments and a per-fragment byte budget equivalent to 1,000 approximate tokens. Reject oversized evidence without rewriting or dropping records, and fail closed when validation fails. Preserve authorization-version filtering and the existing developer-role delivery. Keep review contents out of debug output.

## Testing

Add coverage for count and UTF-8 byte-size boundaries, preservation of accepted fragments, async-only section delivery, and omission of review contents from debug output.

GitOrigin-RevId: 05e9f53a6405f490b2424b2491a834cd90ab24f0
2026-09-07 21:20:31 +00:00
jif
98a5cb46b1 Manage synchronous Guardian reviewers through the thread manager (#43570)
## What changed

- Store the shared `GuardianReviewSessionManager` in thread extension data and let the Guardian extension spawn and fork reviewers through `ThreadManager`, independently of async scorer startup.
- Preserve reviewer reuse, concurrent forks, cancellation, inherited environments, and user instructions. Gate managed reviewer startup on parent registration and remove terminated reviewers from the manager.
- Retain the `guardian` subagent identity in saved conversations. Reject resume of live Guardian reviewers and reject client archive or delete of live owner-managed workers with JSON-RPC error `-32600`; allow normal access after the owner releases them.
- Keep standalone reviewer support for inline delegates and remove duplicated extension prompt and configuration code.

## Testing

Add app-server tests covering reviewer reuse and concurrent forks, inherited instructions and prompt cache keys, live resume and removal rejection, saved reviewer discovery and resume after parent shutdown, and strict Guardian assessment inside an inline review.

GitOrigin-RevId: 4f9893c1ade151eacb4c11ffeae3d9e9ec019187
2026-09-07 19:43:10 +00:00
felixxia-oai
81f23bc186 Move Guardian permission context into the shared section registry (#43538)
## What changed

Represent denied read paths and globs with `PermissionContext` and render them through a sync-only section in `codex-guardian-context`. Keep policy resolution in the host and preserve the existing permission warning in Guardian review prompts.

## Testing

Extend registry tests to verify permission sections appear only for synchronous reviews. Extend the session reuse test to check that resolved denied paths and globs appear in both the initial review request and the next review's delta.

GitOrigin-RevId: a966a14b367f1eedb5a577f7ed74a869559ae646
2026-09-07 18:10:05 +00:00
felixxia-oai
93ac341410 Preserve Guardian context sections and share planned-action rendering (#43534)
## What changed

- Replace `ComposedContext` with ordered `ContextSection` values that retain section identities through transcript selection and rendering.
- Add a shared `PlannedAction` section and renderer for core synchronous approval prompts and the Guardian V2 asynchronous scorer, preserving full, delta, terminal-input, and network-request framing.
- Keep action JSON and retry reasons out of `PlannedAction` debug output.

## Testing

Update registry and transcript tests to assert section identities and source roles. Extend registry coverage to verify planned-action collection for both consumers and omission of action JSON and reasons from debug output.

GitOrigin-RevId: 675b841a2cad06afce03f414615b4d7aa0553b13
2026-09-07 18:02:06 +00:00
jif
1e66885a16 Discount an approval's own code-mode wrapper from Guardian score lag (#43527)
## Why

A code-mode `exec` wrapper and its nested tool calls each advance Guardian's score lag. Counting the unscored wrapper against its own nested approval can trigger a synchronous review sooner than needed.

## What changed

Track originating response items and approval tool-call IDs so cached approvals discount their own wrapper when it is newer than the latest score. Preserve wrapper identity across yields and waits, and retain the full lag when provenance is missing or evicted. Other wrappers and scoring failures still count.

Use the current `write_stdin` call's identity for approval freshness, and omit tool-call identity for `execve` intercepts that only retain the launch ID.

## Testing

Add coverage for wrapper-specific discounts, already-scored wrappers, missing and evicted provenance, identity across code-mode resumes, and approval identities for stdin writes and `execve` intercepts.

GitOrigin-RevId: 4002a06d64c4e1e0a13c072303503d6ddfacad09
2026-09-07 17:35:23 +00:00
jif
db0568dbbb Remove legacy Guardian approval review paths (#43462)
## What changed

- Remove the `fast_decision` and `full_review` extension hooks and `ApprovalAssessment`, leaving `ApprovalReviewContributor::decide` as the approval decision interface.
- Remove the duplicate Guardian V2 fast-approval implementation and `StrictReviewReason` state.
- Require an explicit `GuardianReviewReason` for synchronous reviews.

## Testing

Migrate Guardian reviewer tests to the production `decide_approval` path and cached-score tests to the registry's decision interface.

GitOrigin-RevId: 1f9092c0ff5bb1eed0c63fa557fb3807e2e71564
2026-09-07 13:02:46 +00:00
felixxia-oai
8260619cb6 Centralize Guardian context mode and checkpoint policy (#43458)
## What changed

Resolve `GuardianContextMode` once at session construction and share it across history retention, replay, evidence capture, compaction, and review consumers.

Extract synchronous reviewer context policy and consolidate Guardian V2 parent checkpoint selection so sampling and fast approval use the same eligibility checks. Preserve legacy checkpoint omission and strict compatibility requirements for thread-owned context.

## Testing

Adapt existing review and history tests to the explicit context mode. Move checkpoint tests alongside the extracted selector, retaining coverage for latest-item identity, unusable checkpoints, and complete-item size limits.

GitOrigin-RevId: c73fb6fea556921acfffe758a5f709d7494019dd
2026-09-07 12:53:57 +00:00
jif
e1eb98461c Route approvals through the extension decision API (#43432)
## What changed

- Let approval extensions choose between cached approval, synchronous review, and a user prompt for tool and permission requests, while core enforces mandatory Guardian and fresh-review requirements.
- Carry an optional `review_reason` on Guardian assessment events and use it to trigger strict-review notifications, retaining the fallback for older events.
- Require synchronous review when cached evidence has an unusable encrypted parent compaction.

## Testing

Add regression coverage for manual prompts and cached approvals with non-UTF-8 working directories. Update approval contributors in existing tests to use the decision API.

GitOrigin-RevId: a4e66416070bdaa881daa41429c49021629f44c1
2026-09-07 11:07:28 +00:00
jif
7769bccbb2 Avoid WebSocket connection waits in Guardian v2 classification (#43408)
## Why

When no healthy pooled WebSocket is available, classification waits for a new connection to open and can stall on its handshake.

## What changed

- Use HTTP streaming when no healthy idle WebSocket is ready, and replenish the pool in the background with a five-minute cooldown after connection timeouts.
- Share concurrency limits and the sampling retry budget across both transports, and bound the wait for HTTP response headers.
- Cancel superseded requests while awaiting response headers and stop SSE polling when the consumer closes.

## Testing

Add coverage for HTTP fallback and recovery after cooldown, shared transport capacity, stalled response headers, and cancellation before headers or during body draining. Update sampler and extension tests to cover fallback after socket expiry, authentication changes, and transient failures.

GitOrigin-RevId: 0b23ccc1bfb2dfdbc8d2791d097706cd4dd44f39
2026-09-07 09:24:03 +00:00
felixxia-oai
e4ce83419b Move Guardian thread context into guardianv2 configuration (#43104)
## What changed

Replace `features.guardian_thread_context` with `features.guardianv2.thread_context` and update the configuration schema. The setting controls thread-owned context for synchronous and asynchronous Guardian, defaults to `false`, and remains independent of `features.guardianv2.enabled`.

## Testing

Update configuration tests to cover the nested setting, profile overrides, and enabling thread context while Guardian v2 is disabled. Migrate Guardian approval, history, and async scorer tests to the new configuration key.

GitOrigin-RevId: 54a91555eb68001e0adedc8a07bdbc5ea2273f9b
2026-09-05 21:28:11 +00:00
jif
588b781ab4 Add Guardian V2 failure reasons and connection timing metrics (#43005)
## Why

Classification metrics report failures without distinguishing their causes, and WebSocket connection attempts lack a dedicated duration metric.

## What changed

- Add `failure_reason` tags to classification counters and duration histograms, covering setup, sampler, and output-processing errors.
- Record `codex.guardian_v2.connection.duration_ms` for WebSocket connection attempts with endpoint, outcome, and failure reason tags.
- Map sampler errors to fixed, low-cardinality categories instead of using error messages that may contain server responses or credentials.

GitOrigin-RevId: bb366be92af2f605643ea7cd527678fa8dbfe53f
2026-09-05 13:11:59 +00:00
jif
dee21ec1bc Replace Guardian tickets with parent response IDs (#43002)
## What changed

Capture the ID from `response.created` and pass it as `parent_response_id` in Guardian review and classifier request metadata. Clear the current response ID before sampling retries so tool reviews cannot inherit a failed response's ID.

Request Guardian credits with `guardian_credits_requested` on eligible parent requests. Remove the ticket protocol, transport attachment, and ticket-specific body redaction. Keep ordinary app-server client `parent_response_id` values inside `x-codex-turn-metadata` rather than promoting them to Guardian request metadata.

## Testing

Update coverage for HTTP fallback, WebSocket review reuse, missing response IDs, classifier transport retries, and code-mode yield/resume attribution. Extend app-server tests to verify client metadata placement over HTTP and WebSocket.

GitOrigin-RevId: c1665e56382ecec8d260fc2ca0ecd5e20b0b2391
2026-09-05 13:02:49 +00:00
felixxia-oai
4636819a35 Harden Guardian reviews after context compaction (#42852)
## Why

Guardian reviews must not lose user authorization constraints or reuse an
unreadable or incompatible parent checkpoint after compaction.

## What changed

- Retain bounded excerpts of oversized root user messages across compaction,
  resume, and rollback, and recover excerpts from legacy Guardian history when
  available.
- Require thread-owned Guardian review sessions and asynchronous scoring to
  reuse only non-empty checkpoints produced by a compatible review model.
- Fail closed instead of reviewing without the required checkpoint when reuse
  is disabled, compatibility is unknown, or checkpoint content is unusable.

## Testing

Expanded retained-context, review-session, asynchronous-scoring, and app-server
coverage for oversized instructions, legacy recovery, model incompatibility,
missing content, resume, rollback, and disabled checkpoint reuse.

GitOrigin-RevId: f30d837197e0d838e656a632109f490c38208f5e
2026-09-04 21:07:14 +00:00
felixxia-oai
9c4253ffc1 Retain user instructions in Guardian context (#42844)
## Why

Guardian reviews need the original user instructions even when compaction or
transcript selection removes them from the active conversation window.

## What changed

- Capture complete user messages in host-owned retained context and include them
  as ordered authorization evidence alongside verified answers.
- Omit oversized instructions atomically and emit an explicit incomplete-evidence
  notice instead of exposing a potentially misleading partial permission.
- Mark user messages inherited by forked agents so they remain model-visible
  without becoming child-local authorization.

## Testing

- Cover retained instructions across compaction, resume, rollback, and agent
  forks, including oversized evidence and legacy context behavior.

GitOrigin-RevId: 97122509d818c90d2f87c6a1b29c99c05ad0316e
2026-09-04 20:27:18 +00:00
felixxia-oai
87628df77a Preserve root authorization context in Guardian reviews (#42832)
## Why

Guardian reviews for delegated workers need the current root instructions and verified answers even after the parent context is compacted. Approvals must also become stale when that root authorization changes.

## What changed

- Build bounded root review evidence from retained context, preserving source order and answer scope while prioritizing user instructions over optional assistant context.
- Recover retained instructions from Guardian history after compaction and mark authorization incomplete when required instructions or answers are unavailable.
- Version root authorization in synchronous and reusable review sessions so an allow result is cancelled when its evidence changes.
- Strip parent-only Guardian approvals when forking worker history in retained-context mode.

## Testing

- Cover retained and legacy context modes, oversized evidence, message limits, parent compaction, and authorization changes during review.

GitOrigin-RevId: 658219b7cee08f2752adcea9966268fd21727976
2026-09-04 19:19:04 +00:00
jif
3fde89f628 Route Guardian approvals independently of async scoring (#42819)
## Why

Approval routing must remain available even when the async scorer does not start successfully.

## What changed

- Register a dedicated Guardian approval reviewer before the existing async scorer contributor.
- Reuse eligible cached low-risk evidence, including the initial computer-use allowance, without waiting for a fresh score.
- Route requests to the user when automatic review does not apply, and fall back to a synchronous assessment with the applicable review reason when cached evidence cannot be used.

GitOrigin-RevId: 956427040456bed4c497da952f0bed7f22e93fa6
2026-09-04 18:10:55 +00:00
jif
0ae02915bd Add request-scoped Guardian approval decisions (#42807)
## What changed

- Extend `ApprovalReviewContributor` with a `decide` hook that can allow an
  action, return a synchronous review result, or hand the request to the user.
- Pass contributors the request's approval state and a callback bound to the
  existing synchronous reviewer. Review results satisfy the review gate while
  the host continues to enforce permissions.
- Add structured reasons for requesting a fresh Guardian review and select the
  first contributor decision in registration order.

GitOrigin-RevId: ec84474b3fcbcf1027c8502aa1c2947c10149f9d
2026-09-04 17:38:39 +00:00
jif
cc4b8bdeb8 Propagate response tickets to Guardian reviews (#42758)
## What changed

- Request and parse server-issued Guardian tickets for eligible Codex backend responses.
- Scope each ticket to the response that produced a Guardian review or classifier request, including HTTP and WebSocket retries, without adding it to model-visible or persisted context.
- Validate ticket shape, reserve its metadata keys, redact it from debug and request-body logging, and attach it only at the Guardian transport boundary.

## Testing

- Cover ticket parsing, endpoint and authentication routing, retry scoping, classifier retries, and redaction for compressed and uncompressed requests.

GitOrigin-RevId: 6219dd15c9f19ed3387de516aac1b8e7c9cdb0e3
2026-09-04 12:56:26 +00:00
jif
4e48cd02da Honor model-provided Guardian review policies (#42744)
## What changed

- Add optional per-model Guardian modes for computer use, shell, code mode,
  file changes, MCP, network, and permission requests.
- Apply disabled, synchronous, or adaptive review by action category while
  preserving legacy configuration when model policy is absent.
- Bind cached risk scores to the active model policy, thread settings, and
  environment selections so outdated scores cannot approve later actions.
- Keep unknown review modes on the synchronous path and ignore unknown policy
  fields for forward compatibility.

## Testing

- Cover policy serialization, legacy fallback, scoped tool classification,
  disabled categories, and score invalidation after policy changes.

GitOrigin-RevId: f334a5f4fffb198da66cde3a400233e0df650516
2026-09-04 11:59:18 +00:00
felixxia-oai
ad8ee16a5f Require Guardian review for incompatible compaction checkpoints (#42588)
## Why

Guardian can reuse an opaque parent compaction only when the checkpoint's
recorded producer hash matches the scoring model. Missing or incompatible
provenance must not allow an asynchronous score or cached approval to omit
compacted context.

## What changed

- Record the producing model's compatibility hash on compaction history items
  and expose the latest checkpoint hash through conversation snapshots.
- In thread-owned context mode, fail closed and require synchronous review when
  checkpoint reuse is enabled but the latest checkpoint is incompatible or has
  unknown provenance.
- Reject incompatible checkpoints in the sampler while preserving the legacy
  context behavior.

## Testing

Add coverage for local, remote, resumed, compacted, and rolled-back histories,
including matching, mismatched, missing, and empty compatibility hashes.

GitOrigin-RevId: 1ce959cb276edc602fd7dfa442133c7fe5e53857
2026-09-03 17:48:15 +00:00
felixxia-oai
1d74c3ba1e Persist verified user answers in Guardian thread context (#42579)
## Why

Guardian authorization reviews need host-verified `request_user_input` answers to
remain aligned with thread history across compaction, resume, and rollback.

## What changed

- Record verified question-and-answer pairs in retained thread context when
  `GuardianThreadContext` is enabled, and source both local and delegated Guardian
  review evidence from that context.
- Preserve complete answer records within the evidence budget. Mark authorization
  context incomplete when records are unavailable or oversized, and defer cached
  fast approvals in that case.
- Keep the existing runtime-only answer path for threads that do not enable the
  thread-owned context.

## Testing

- Cover answer retention through compaction and resume, removal after rollback,
  source-call eviction, oversized answers, delegated review evidence, and legacy
  behavior.

GitOrigin-RevId: 01f6f4541515434a0d00fdde318ff59f2f8bd2eb
2026-09-03 16:41:11 +00:00
jif
38ba8cdceb Honor model requirements in Guardian computer-use scoring (#42422)
## Why

Computer-use-only Guardian scoring should follow the active model's REPL
auto-review requirement, including when the model changes within a live thread.

## What changed

- Run computer-use scoring and fast approval decisions only when the active
  model sets `node_repl_auto_review_required`.
- Invalidate prior or in-flight scores when a model switch skips scoring, so
  switching back to a reviewed model cannot revive a stale decision.

## Testing

- Cover model switches for both `node_repl` and `cua_repl` MCP servers.
- Verify skipped scoring and stale-score rejection across requirement changes.

GitOrigin-RevId: 46aec4d017bea8f135b435bcd769b87369b8ce95
2026-09-03 02:27:43 +00:00
felixxia-oai
0d502a4230 Support durable reasoning configuration updates (#42328)
## Why

Reasoning configuration changes need to retain their position and trusted provenance when model history is persisted and replayed. Client-injected history must not be able to forge these controls.

## What changed

- Add a typed `configuration_update` response item carrying reasoning effort, including custom model-defined values.
- Persist harness-authored updates with provenance and preserve them across history reconstruction, thread resume, raw response notifications, and agent forks.
- Exclude untrusted configuration updates from model history, strip client-supplied provenance metadata, and reject configuration updates supplied as turn input.
- Export the new item through the JSON and TypeScript app-server schemas and classify it in telemetry and persistence metrics.

## Testing

- Cover serialization, provenance persistence, history filtering and rollback, resume reconstruction, and injection attempts before and after restart.

GitOrigin-RevId: eb5559d2b52b7a931621e7c9812f009ff9fb8939
2026-09-02 18:52:44 +00:00
felixxia-oai
5971d42847 Preserve verified answers across history compaction (#42293)
## Why

Compaction replaces the model history window, but host-verified user answers may
still be needed for the rest of the owning thread.

## What changed

- Add bounded, model-invisible retained context for verified
  `request_user_input` answers.
- Persist retained context in rollout events and compaction checkpoints, and
  restore it when a thread resumes.
- Remove answers when their source turns are rolled back, and prevent
  parent-local answers from being inherited by child forks.

## Testing

Add lifecycle coverage for deduplication and size limits, compaction and resume,
rollback, rollout migration, and child forks.

GitOrigin-RevId: c32900d3e8120a9899b71f0576683acd67a4b898
2026-09-02 15:07:11 +00:00
jif
50fffd5ed3 Refresh plugin skills after out-of-process version changes (#42284)
## Why

Another process sharing `CODEX_HOME` can replace an installed plugin version
without invalidating the current process's caches. This could leave skill
listings tied to stale plugin paths and retain obsolete plugin generations.

## What changed

- Reject cached plugin loads when their roots no longer match the active
  installation, so skills are reloaded after upgrades or rollbacks.
- Keep the 32 most recently used configuration-based skill snapshots while
  allowing callers to continue using snapshots that have been evicted.

## Testing

- Cover external plugin upgrades and rollbacks through `skills/list`, including
  a subsequent warm-cache read.
- Cover cache eviction, reuse, and the lifetime of caller-held snapshots.

GitOrigin-RevId: ca00f9539c01461e3945d340bf63f8436665220b
2026-09-02 14:14:44 +00:00
jif
a0dcfe2ada Skip Guardian scoring in User approval mode (#42256)
## What changed

- Skip Guardian prewarming and asynchronous scoring when `approvalsReviewer` is
  `"user"`, including when the reviewer changes during an active turn.
- Automatically accept ordinary `node_repl.js` execution confirmations in this
  mode while continuing to surface sensitive-action checks and requests for user
  input.
- Cover transitions between User approval, automatic review, and Full Access in
  the app-server integration tests.

GitOrigin-RevId: 599c8ebb672728b9bf3d64c34377ddec230325f8
2026-09-02 10:32:22 +00:00