Skip to content

fix(codex): preserve unconsumed native child results - #149490

Open
jalehman wants to merge 1 commit into
mainfrom
fix/pr-137822-native-consumption
Open

jalehman wants to merge 1 commit into
mainfrom
fix/pr-137822-native-consumption

Conversation

@jalehman

@jalehman jalehman commented Sep 15, 2026 •

Copy link
Copy Markdown
Contributor

Closes #137710.

Supersedes #137822 by @bounce12340 (Josh Tsai), whose contribution is preserved in the commit co-author credit. This maintainer-owned replacement incorporates the reviewed owner-level repair without squashing rewritten ancestry under the contributor PR.

What Problem This Solves

A native Codex child can finish while its parent yields or tears down. Codex can persist the child's completion message without starting another model response. Treating arrival as consumption suppresses OpenClaw's follow-up and leaves the parent without its promised response.

Why This Change Was Made

The existing delivery-receipt owner now holds receipt captures outside its matching state until the same foreground parent turn completes a subsequent non-compaction model response. An exact bound, non-yielded owner must confirm consumption. Native wait results additionally require the matching tool output to be recorded before a later response can confirm consumption: the response that requested an eagerly completed wait cannot consume its own result.

Rebased onto 9b4bbdf41a9c10f66b3a243f974d82077840930e. This uses main's immutable assignment, successful V1 submission, and serialized thread-ownership implementations. Delayed acknowledgement of predecessor A does not own or release successor B. Unsampled receipts cannot become acknowledged through a later alias/result/history operation. Foreground turn sampling is released separately from receipt owners retained by child assignments and recovery.

User Impact

  • Unconsumed native child results remain eligible for the existing detached parent continuation.
  • Sampled foreground results retain native-wait deduplication and safe same-turn child reuse.
  • No new wake mechanism, retry policy, idle retention, configuration, SDK, storage schema, or dependency changes.

Evidence

Candidate: 9d4bc16a5370e2088eb1a9f40ada51f2f49f7b2b.

  • Full changed-file gate passed: extension and extension-test typechecks, typed lint, formatting, line/suppression ratchets, export scans, plugin/storage guards, and zero runtime import cycles.

  • 576 tests passed across 23 files in the native-subagent and registered native run-attempt suites on this candidate. Coverage includes successful V1 submissions, warm expiry, recovery, close ownership, rotated parents, native waits, compaction exclusion, yielded/aborted parents, and exact pre-bind ownership.

  • The seven native follow-up custody cases now record the matching native wait tool output and subsequent model response before expecting delivery. The fixtures also assert delivery remains pending before those boundaries; existing successor-custody assertions are unchanged. This fixes the PR-attributable CI fixture failure without weakening the production sampling gate.

  • The rebased candidate preserves main’s compact pending-receipt shape and map-replacement restoration. A fresh P0–P2 review passed after conflict resolution, and the committed Git tree exactly matches the validated staged tree.

  • Local single-worker test batches took 161.93 s (170 tests / 11 files) and 218.95 s (406 tests / 12 files). Hosted CI on the new head is not yet confirmed green.

  • Registered-runtime reused-child proof covers eight combinations: receipt before/after reuse, successor running/completed, and identical/distinct results. Sampling A leaves B's task and live claim intact; B subsequently produces its own detached completion.

  • Sampling regression comparison against pinned main: 14 failed / 2 passed before the repair; the production snapshot was restored byte-for-byte afterward. A further four-case eager-wait regression reproduced the review finding before the matching-output gate was added.

  • Fresh independent P0–P2 review of the repaired candidate: scoped-clean, no accepted/actionable findings. The first review's eager-wait finding was reproduced and fixed before this review.

  • Direct protocol inspection used Codex rust-v0.154.0 (6b9826e3aa83b1a5947db50f4332cb9c65f1b340): eager wait dispatch, tool-output recording, normal response completion, task-end input persistence, compaction response events, and non-triggering native completion delivery.

The changed registered custody suite passed all seven cases, with 30.026 seconds summed test-body time. It exercises the existing registered run-attempt and native follow-up ownership boundary; a receipt-helper test cannot establish this wiring or successor custody. No real-time sleeps, retries, or timeout increases were added. Isolated per-file wall times and new-head hosted CI durations have not been measured.

Reproducible local checks:

node scripts/run-vitest.mjs \
  extensions/codex/src/app-server/native-subagent-*.test.ts \
  extensions/codex/src/app-server/run-attempt.native-*.test.ts --maxWorkers=1
node scripts/check-changed.mjs --staged \
  --base 9b4bbdf41a9c10f66b3a243f974d82077840930e

Real Gateway/Codex behavior proof remains blocked and merge readiness is not claimed. The configured Testbox credential was rejected as revoked during the previous live attempt; no native child or parent final response was produced. Those captures are setup failure, not before/after proof. The local regression suite does not establish a live yielded-parent continuation, visible final reply, and settled parent. See the recorded proof blocker. The configured credential must be refreshed through the authorized route before repeating that proof; no substitute credential or retention expansion is part of this change.


View the OpenClaw team session

@clawsweeper

clawsweeper Bot commented Sep 15, 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.

@jalehman
jalehman marked this pull request as ready for review September 15, 2026 23:00
@clawsweeper clawsweeper Bot added P1 High-priority user-facing bug, regression, or broken workflow. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Sep 15, 2026
@clawsweeper

clawsweeper Bot commented Sep 15, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge.

What this changes

The Codex plugin delays acknowledging native child results until the parent completes a later model response, and updates ordering tests and harness documentation.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The focused owner repair and regression evidence are useful, but the expressly required real behavior result remains unproven.
Proof confidence 🦐 gold shrimp (3/6) Real behavior proof is not required for maintainer- or bot-authored pull requests.
Patch quality 🐚 platinum hermit (4/6) 1 actionable review finding remain.

Merge readiness

⛔ Blocked before merge - 4 items remain

Keep open: current main fixes yielded and ended-parent receipt handling, but this branch still adds meaningful active-turn sampling and eager-wait protection. The protected maintainer-owned work is not eligible for cleanup closure.

Priority: P1
Reviewed head: 9d4bc16a5370e2088eb1a9f40ada51f2f49f7b2b

Before merge

  • [P3] Replace polling waits with task settlement signals (P3) - The prior finding remains unresolved: this new eight-case reuse matrix polls task and thread-claim state at five sites with vi.waitFor. These ordering regressions should await the owning persistence, delivery, or release completion and then assert directly; polling adds scheduler-dependent latency and can conceal an early observation. Root policy and the test-writing guide prohibit new polling. This was discovered late on the unchanged head in the previous review.
  • Resolve merge risk - The current head conflicts with main; the remaining sampling repair needs review against the newer parent and completion owners after conflict resolution.
  • Resolve merge risk - The explicitly requested Gateway/Codex behavior proof remains incomplete: available captures show authentication failure rather than parent continuation, visible final delivery, and settled ownership.
  • Complete next step - Resolve the current-main conflicts around the remaining sampling change, address the retained polling finding, and complete the PR’s expressly required Gateway/Codex proof. Redact credentials and private identifiers, then update the PR body for re-review; if automatic review does not trigger, ask a maintainer to comment @clawsweeper re-review.

Findings

  • [P3] [P3] Replace polling waits with task settlement signals — extensions/codex/src/app-server/native-subagent-monitor.sampling.test.ts:289-290
Agent review details

How this fits together

OpenClaw’s Codex plugin observes native child completions and decides whether the parent already consumed them. Unconsumed results feed the existing detached continuation so the parent can finish and reply.

flowchart TD
  A[Native child completes] --> B[Parent completion receipt]
  B --> C[Per-turn sampling state]
  D[Recorded wait output] --> C
  E[Later parent response] --> C
  C --> F{Exact parent consumed result?}
  F -->|Yes| G[Acknowledge delivery]
  F -->|No| H[Detached parent continuation]
Loading

Technical review

Best possible solution:

Integrate the remaining active-turn sampling and eager-wait guards into current main’s receipt owner while preserving its yielded, settled, cancelled, and successor-assignment protections.

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

Yes, source establishes the remaining active-parent mechanism: main immediately matches receipts without requiring a later response or recorded wait output. No current-main execution was performed in this read-only review.

Is this the best way to solve the issue?

Yes, confirming consumption within the existing receipt owner is a focused solution; the implementation now needs to fit main’s newer lifecycle guards.

Full review comments:

  • [P3] [P3] Replace polling waits with task settlement signals — extensions/codex/src/app-server/native-subagent-monitor.sampling.test.ts:289-290
    The prior finding remains unresolved: this new eight-case reuse matrix polls task and thread-claim state at five sites with vi.waitFor. These ordering regressions should await the owning persistence, delivery, or release completion and then assert directly; polling adds scheduler-dependent latency and can conceal an early observation. Root policy and the test-writing guide prohibit new polling. This was discovered late on the unchanged head in the previous review.
    Confidence: 0.99
    Late finding: first raised on code an earlier review cycle already covered.

Overall correctness: patch is correct
Overall confidence: 0.85

AGENTS.md: found and applied where relevant.

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

Merge-risk options

Maintainer options:

  1. Carry forward the remaining sampling repair (recommended)
    Resolve conflicts around current main’s owners and establish the requested real parent continuation and safe child-reuse behavior before landing.

Security

None.

Evidence

What I checked:

  • Pinned introduced change: Reviewed merge-base 9b4bbdf to head 9d4bc16. Receipt captures remain outside matching state until a non-compaction response and an exact non-yielded owner confirm consumption; native waits additionally require matching recorded output. (extensions/codex/src/app-server/native-subagent-delivery-receipts.ts:315, 9d4bc16a5370)
  • Current-main partial implementation: Current main rejects receipt consumption by yielded, settled, cancelled, or already-completed pre-bind owners. Its receipt tracker still matches arrival immediately; it does not implement this branch’s later-response and matching-wait-output gates. (extensions/codex/src/app-server/native-subagent-parent-owner.ts:62, 90c6934d630f)
  • Merged yielded-parent repair: GitHub verifies fix(codex): resume parent sessions after workers finish #160608 merged as 7c8c71b. Its stated repair preserves pending results for yielded, settled, and cancelled parents, while retaining active-parent deduplication. (7c8c71bf1d3f)
  • Release provenance for overlapping repair: The merged yielded-parent repair dates to 2026-09-28T19:22:44Z. Both v2026.9.7 and the supplied latest release v2026.9.8 contain it; the v2026.9.8 parent-owner source confirms the consumption guard. This establishes partial overlap, not complete implementation of the proposed sampling gate. (extensions/codex/src/app-server/native-subagent-parent-owner.ts:62, 7c8c71bf1d3f)
  • Affirmative dependency contract: The changed sampler consumes Codex raw-response and tool-output events, and the PR explicitly claims compatibility with rust-v0.154.0. Personally inspected the sibling source at the claimed revision: normal response completion emits the raw completion event, recorded conversation items emit raw items after persistence, and the native wait handler emits completion before returning its tool output. GitHub verified this SHA belongs to openai/codex. (codex-rs/core/src/session/turn.rs:2667, 6b9826e3aa83)
  • Compaction exclusion: Compaction also calls record_observed_response_completed, supporting the need to exclude compaction responses from consumption confirmation. (codex-rs/core/src/compact.rs:807, 6b9826e3aa83)

PR surface

Source +136, Tests +482, Docs +3. Total +621 across 19 files.

View PR surface stats
Area Files Added Removed Net
Source 5 172 36 +136
Tests 13 590 108 +482
Docs 1 5 2 +3
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 19 767 146 +621

Review metrics

Metric Value Why it matters
Production and test growth production +136 net; tests and test support +482 net Production growth is explained by compact per-turn receipt capture and sampling state within the existing receipt owner.

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #137710
Summary: This PR targets the native receipt-consumption issue; later merged work covers part of its original failure path while active-turn sampling remains distinct.

Members:

Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.

Labels

Label changes:

  • add status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action.
  • remove status: 👀 ready for maintainer look: Current PR status label is status: ⏳ waiting on author.

Label justifications:

  • P1: Incorrect native completion accounting can strand delegated results and prevent promised parent replies.
  • merge-risk: 🚨 session-state: The changed consumption boundary controls delivery settlement and retained successor ownership, with real boundary proof still outstanding.
  • merge-risk: 🚨 message-delivery: Acknowledging a receipt suppresses detached continuation, so incorrect event ordering can suppress or duplicate the parent’s final reply.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.
  • status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action.

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Replace the five new polling sites with owning completion signals while retaining all reuse assertions.
  • Publish redacted Gateway/Codex output showing continuation, final delivery, and safe reuse after the refreshed repair; terminal traces are sufficient, with screenshots or recordings useful when they show the result.

Rating scale

6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only. Repair and merge execution lanes are retired.

History

Review history (4 earlier review cycles)
  • reviewed 2026-09-15T23:20:33.167Z sha e094a1c :: needs real behavior proof before merge. :: [P1] Preserve child reuse before acknowledging the previous result
  • reviewed 2026-09-18T01:32:57.132Z sha b0ae52b :: blocked before merge. :: none
  • reviewed 2026-09-21T23:44:53.769Z sha 9d4bc16 :: blocked before merge. :: none
  • reviewed 2026-09-26T07:59:39.663Z sha 9d4bc16 :: blocked before merge. :: [P3] Replace polling waits with task settlement signals

Reviewed October 5, 2026, 8:53 PM ET / October 6, 2026, 00:53 UTC (Revision 5).

@jalehman

Copy link
Copy Markdown
Contributor Author

Verification remains blocked — no live behavior claim

The requested real Gateway/Codex test could not authenticate: the configured Testbox Codex refresh token was rejected as revoked. The Gateway and Control UI started, but no native child spawned and no parent final response was produced. These are setup-failure captures, not before/after proof. Both temporary Testboxes were stopped.

Published candidate remains e094a1c9e871d61dadf9eaf4e38c6149e775f0c7 (comparison base 14b8ad1d187104ac0ba4bc13afa364997aa4bc39). The Testbox attempt does not satisfy the proof gate.

The child-reuse repairs remain local and unpublished. The last validated local candidate passed 153 monitor/mirror tests and full changed-file checks; an additional admission-ordering regression is still open. Pinned Codex acknowledges either a started turn or steering of an existing turn, so retaining the subscription cannot rely on always receiving a new turn/started event. That distinction still needs a safe owner-level resolution and real verification.

No merge, no source-PR closure, and no substitution of another credential. Landing remains gated on the remaining repair/review, exact-head CI, and real yielded-parent plus safe-reuse proof after the configured Testbox authentication is restored.

@VACInc

VACInc commented Sep 16, 2026

Copy link
Copy Markdown
Member

Related fix: #150065 updates private-completion guidance and Gateway cancellation classification. It does not determine whether a native Codex completion receipt was actually consumed by a later model response. This PR's per-turn receipt accounting and follow-up for unconsumed native child results remain distinct; it is not superseded by #150065.

@fuller-stack-dev fuller-stack-dev self-assigned this Sep 18, 2026
@jalehman
jalehman force-pushed the fix/pr-137822-native-consumption branch from e094a1c to b0ae52b Compare September 18, 2026 01:24
@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation size: L and removed size: M labels Sep 18, 2026
@clawsweeper clawsweeper Bot added rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Sep 18, 2026
Keep native completion receipts pending until a later non-compaction model response confirms consumption. Preserve yielded-parent wakeups, exact pre-bind ownership, native wait deduplication, and same-turn child reuse.

Based on #137822; fixes #137710.

Co-authored-by: Josh Tsai <[email protected]>
@jalehman
jalehman force-pushed the fix/pr-137822-native-consumption branch from b0ae52b to 9d4bc16 Compare September 21, 2026 23:35
@clawsweeper clawsweeper Bot removed the rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. label Sep 22, 2026
@clawsweeper clawsweeper Bot added the rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. label Sep 22, 2026
@clawsweeper clawsweeper Bot added the merge-risk: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. label Sep 26, 2026
@clawsweeper clawsweeper Bot added rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. and removed rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. labels Oct 6, 2026
@SanderHelgesen

Copy link
Copy Markdown
Contributor

A live case from our install (OpenClaw + Codex plugin 2026.10.1, Telegram, 10-11 to 10-13). Results the parent already consumed in the foreground still get the detached redelivery.

  • 31 native children. In 30, the parent got the child's FINAL_ANSWER in its foreground turn 0–26 s after the child finished, and answered the user.
  • All 31 still went through detached redelivery and logged Native subagent completion retries exhausted ("This operation was aborted"). Several did this again after gateway restarts. One child logged it 78 times over two days.
  • Suspected cause (not verified): main 656c851b24, native-subagent-completion-delivery.ts:79-84 defers to the foreground parent and relies on receipts to dedupe. Only a matched receipt marks the child delivered. Retry exhaustion comes only from scheduleRetry, so match() in native-subagent-delivery-receipts.ts:135-171 never matched these children. My guess is a result-key mismatch, or ambiguous because one agent path had several runIds (one example had 3). I have not confirmed which branch.
  • Today the [Bug]: Native Codex completion inherits an aborted run scope and fails before parent admission #167410 abort hides this, because the redelivery never reaches the user. Once that is fixed (fix(gateway): rehome stale native completion authorization #167638), each redelivery would wake the parent again, and users would get a second answer per delegated task.

From the diff, this PR changes when a receipt is accepted, not how match() keys it. Does it cover this case, a V2 agent_message receipt with FINAL_ANSWER for a child with several runIds? Happy to test a build of this branch on our install.

Evidence (Codex rollouts + gateway log, UTC)
child     agent path                    child done          parent got FINAL_ANSWER  parent replied      retries exhausted
01a12c5f  /root/ahrefs_mcp_check        10-11 19:18:51      19:18:51                 19:18:57            19:19:50, then 78 lines through 10-13 10:04
01a135b8  /root/apperio_dependency_up…  10-13 14:51:24      14:51:25                 14:51:32            15:00:23, 15:53:44

Counts: 31 children with completion in the rollout; 30 have a parent agent_message with the child's FINAL_ANSWER after child task_complete; 31/31 have Native subagent completion retries exhausted with childThreadId in the gateway log (223 lines total).

Found by Claude Opus 5.5 (Claude Code) while tuning our own install.

@cassthebandit

Copy link
Copy Markdown
Contributor

I found a possible false-settlement path at the current head 9d4bc16a5370e2088eb1a9f40ada51f2f49f7b2b: pending raw receipts survive successful compaction and can be accepted by a later response that no longer carries their result.

In CodexNativeSubagentReceiptSampling.observe, a contextCompaction item only toggles compacting; it does not invalidate pending. After compaction completes, the next rawResponse/completed marks every pending receipt without a waitCallId as sampled. The flag excludes the compaction response itself, but not a later response over replaced history.

The source-supported schedule is:

  1. Native records a child's raw FINAL_ANSWER for the active parent turn; the tracker captures it with sampled:false.
  2. The sampling carrying that result is preempted before native handles its completion.
  3. Mid-turn remote compaction succeeds and removes the original result envelope from history.
  4. A later ordinary sampling in that same turn completes without the result.
  5. The retained pending receipt becomes sampled and is accepted, suppressing its detached delivery.

Relevant Codex0.164 source:

The native preemption → compaction → history-omission schedule above is source analysis, not a deterministic native/Gateway reproduction. The tracker-level component is now reproduced independently below.

Could the existing staging owner invalidate unacknowledged receipt evidence at this history-replacement boundary? I am not proposing a second receipt mechanism, and this finding is separate from the native resume raw-event opt-in gap discussed in openai/codex#34353.

Runnable tracker-level regression

I reproduced the stale-pending part of this finding against the actual receipt classes at 9d4bc16a5370e2088eb1a9f40ada51f2f49f7b2b.

An unsampled raw FINAL_ANSWER survives contextCompaction started/completed. The compaction response correctly does not acknowledge it, but a later ordinary rawResponse/completed returns the old child run ID with no new receipt. The positive control, a fresh post-compaction receipt followed by completion, passes.

Observed: 1 failing regression, 1 passing control, exit1 (Node v26.10.0). This is deterministic tracker/parser evidence, not a native preemption+compaction or Gateway E2E reproduction. Those synthetic events do not prove what a particular compaction summary retained. The native schedule and history-retention concern remain the separate source analysis described above.

To reproduce without installing dependencies, save the script below as compaction-repro.mjs and run it against a checkout of the pinned commit:

node /path/to/compaction-repro.mjs /path/to/openclaw

The production receipt/parser/protocol/coercion modules are unchanged. Only unrelated logging/history/task-ID imports are isolated with fail-fast stubs; invoking one would fail the test. The regression expects [] but currently receives ['child-run'].

Self-contained regression and control
// Run with Node 26 (tested v26.10.0): node compaction-repro.mjs /path/to/pinned/openclaw
// Production receipt, parser, protocol and coercion modules are not modified.
import assert from "node:assert/strict";
import { test } from "node:test";
import { registerHooks } from "node:module";
import { resolve } from "node:path";
import { pathToFileURL } from "node:url";

const root = pathToFileURL(resolve(process.argv[2] ?? ".") + "/");
const unexpected = `const fail = () => { throw new Error("Unrelated dependency invoked"); };
export const embeddedAgentLog = { warn: fail };
export const readCodexNativeSubagentHistoryOwner = fail;
export const codexNativeSubagentRunId = fail;
export const readNativeTaskAssignment = fail;`;
// Isolate unrelated logging/history/assignment APIs. They must not be invoked.
// The string-coercion facade routes to its actual production implementation.
registerHooks({
  resolve(specifier, context, next) {
    if (specifier === "openclaw/plugin-sdk/string-coerce-runtime") {
      return { url: new URL("packages/normalization-core/src/record-coerce.ts", root).href, shortCircuit: true };
    }
    if (specifier === "openclaw/plugin-sdk/agent-harness-runtime" ||
        specifier === "./native-subagent-history-owner.js" ||
        specifier === "./native-subagent-task-ids.js") {
      return { url: "data:text/javascript," + encodeURIComponent(unexpected), shortCircuit: true };
    }
    if (specifier.startsWith("./") && specifier.endsWith(".js")) {
      return next(specifier.slice(0, -3) + ".ts", context);
    }
    return next(specifier, context);
  },
});
const { CodexNativeSubagentDeliveryReceipts, CodexNativeSubagentReceiptSampling } =
  await import(new URL("extensions/codex/src/app-server/native-subagent-delivery-receipts.ts", root));

function fixture() {
  const tracker = new CodexNativeSubagentDeliveryReceipts();
  const sampling = new CodexNativeSubagentReceiptSampling();
  assert.deepEqual(tracker.record("child-run", ["/root/child"], "child result"), []);
  const observe = (method, item) => {
    sampling.observe({ method, params: { threadId: "parent", turnId: "turn", ...(item ? { item } : {}) } }, [tracker]);
    return sampling.consume({ isTurnYielded: () => false });
  };
  return {
    observe,
    receipt: () => observe("rawResponseItem/completed", {
      type: "agent_message", id: "receipt", author: "/root/child", recipient: "/root",
      content: [{ type: "input_text", text: "Message Type: FINAL_ANSWER\nTask name: /root\nSender: /root/child\nPayload:\nchild result" }],
    }),
    compact: () => {
      assert.deepEqual(observe("item/started", { type: "contextCompaction", id: "compact" }), []);
      assert.deepEqual(observe("rawResponse/completed"), [], "compaction response must not acknowledge");
      assert.deepEqual(observe("item/completed", { type: "contextCompaction", id: "compact" }), []);
    },
  };
}

test("unsampled pre-compaction receipt is not accepted by a later ordinary completion", () => {
  const f = fixture();
  assert.deepEqual(f.receipt(), [], "arrival alone must not acknowledge");
  // No normal completion acknowledged this receipt before history replacement.
  f.compact();
  // No new receipt after compaction. The tracker sees only this later completion.
  assert.deepEqual(f.observe("rawResponse/completed"), []);
});

test("a fresh post-compaction receipt is accepted after ordinary completion", () => {
  const f = fixture();
  f.compact();
  assert.deepEqual(f.receipt(), [], "arrival alone must not acknowledge");
  assert.deepEqual(f.observe("rawResponse/completed"), ["child-run"]);
  assert.deepEqual(f.observe("rawResponse/completed"), [], "do not deliver twice");
});

Could the existing staging owner invalidate unsampled receipt evidence at the history-replacement boundary while preserving genuinely sampled receipts and new post-compaction receipts? This is not a proposed second receipt mechanism or a claim that the separate resumed-thread raw-event gap is fixed.

This branch has not been deployed

No deployments
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 merge-risk: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. P1 High-priority user-facing bug, regression, or broken workflow. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. size: L 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.

[Bug]: Native Codex completion is recorded but does not wake a sessions_yield parent

5 participants