Skip to content

fix: preserve requester routes for delayed session continuations - #156802

Merged
joshavant merged 3 commits into
mainfrom
fix/message-session-account-routing
Sep 24, 2026
Merged

joshavant merged 3 commits into
mainfrom
fix/message-session-account-routing

Conversation

@joshavant

@joshavant joshavant commented Sep 23, 2026 •

Copy link
Copy Markdown
Collaborator

What Problem This Solves

Fixes delayed sessions_send requester continuations using a later message’s reply route or entering a requester conversation that was reset while the child was working.

User Impact

Delayed requester continuations retain the original channel, account, recipient, and thread as defaults and carry the admitted session generation. A requester deleted/recreated or reset before continuation admission cannot consume the old result. Explicit routing, child progress, and unrelated ordinary work remain available. No configuration change or stored-data migration is required.

Same-session direct announcements retain their existing route lookup. The captured-route shortcut was removed after reproducing a send to a deleted requester; preserving the original route for that separate path remains deferred. This PR does not establish general direct-send revocation or durable recovery guarantees.

Why This Change Was Made

Capture the active requester route and session identity, then carry them through the existing continuation and Gateway admission owners. Active target/thread values take precedence over outbound fallbacks; numeric threads are normalized at the Gateway boundary. Exact admitted requester keys are preserved, while legacy key-only callers retain their normalization.

The backend-only expectedExistingSessionLifecycleRevision extends the existing session-ID guard: omission preserves ID-only behavior; null requires an unversioned generation; a string requires that exact revision. A revision requires the expected session ID. Existing admission and persistence checks enforce it, including reset after the initial read. This reuses the already-read requester entry and existing stored revision; it adds no database schema or parallel authority owner. The generated protocol model is updated.

Evidence

Current head: ccab80e3884af5bf906724bffe8d9472a2cb2643. Product-flow proof is bound to cf4a3501c7539596c68a35ee27bbc2c5352209d4; the follow-up changes only four Telegram test/fixture files, with unchanged production source. Reproducible proof, exact drivers, sanitized traces, and source/build bindings.

  • Original route: registered sessions_send accepted work and its sending turn ended. A later inbound changed the saved account to alternate. Completion omitted account and recipient; one result reached original default / dm:compat-sender.
  • Retired requester: supported delete/recreate and same-ID reset each produced a recorded Gateway refusal, zero requester continuation, and zero result delivery. The prior ID-only implementation reproduced one stale result after the same reset. Child progress and ordinary sends before/during/after succeeded in all final cases.
  • Removed direct shortcut: old shortcut delivered once after deletion. Final candidate: allowed 1, duplicate 0, deleted 0, subsequent ordinary recreation 1.
  • Live Telegram: Test Server destination/reset proof and reproducible drivers passed on the current head with a Convex-leased bot and independent TDLib user. One delayed report reached the original named account/chat/forum topic; same-ID reset caused a recorded Gateway refusal, zero requester model continuations, and zero stale report messages over a complete 150-second recording. Child progress, unrelated sends before/during/after, fresh requester work, and explicit alternate-topic sends all passed. Cleanup was confirmed. This uses one named account configured as default; saved-route drift remains covered by the HTTP proof above.
  • Tests: Gateway regressions distinguish matching/unversioned generations from resets, including a reset between reads, plus missing-ID rejection and ID-only compatibility. The new assertions failed before the generation comparison was implemented. Source-precedence regression also failed before repair.

Standalone test costs (pnpm test <file> --maxWorkers=1):

Test file Result Wall time
sessions-send-tool.admission.test.ts 9/9 50.408s
sessions-send-tool.a2a.test.ts 37/37 15.271s
gateway-protocol/src/schema/agent.test.ts 17/17 2.998s
server-methods/agent.test.ts 364/364 230.478s

The full Gateway suite ran before the final tool-schema extraction/ordinary-route fixture clarification; its Gateway owner/test bytes are unchanged. Final nested-step/session siblings passed 105/105 in 24.811s. Full Gateway compositions remain outside per-PR tests; new Gateway cases share the existing fixture.

The hosted ClawSweeper review reviewed current head ccab80e3884: Overall readiness Platinum (4/6), Proof confidence Diamond (5/6), Patch quality Platinum (4/6), with no actionable code findings. The requested live Telegram Test Server destination/reset proof is now complete and linked above; a fresh hosted review has been requested to reassess that evidence. This PR remains open and unmerged. Fresh independent reviews of the product change and final fixture repair also found no actionable P0–P2 findings. Production core types, changed-file type-aware lint, formatting, dead-code/structural checks, protocol generation/check, and the QA runtime build passed. The final fixture changed-file gate passed, including extension-test types and type-aware lint.

CI for the current head completed successfully, including iOS smoke. The separate iOS dead-code scan also passed. The final GitHub rollup is green with no pending or failed checks (172 success, 52 skipped, one neutral). The prior cf4a3501 Telegram failure is documented below with the repair and proof. macOS Node/Swift jobs were skipped, so no macOS-suite success is claimed. The prior agents-tools owner passed 3,013 tests (one skipped) in 106.62s Vitest / 108.67s runner time; its packed CI step took 355s. The protocol agent schema passed all 17 cases in a 20.81s gateway-client invocation (251 tests across 15 files); its shared owner took 121.65s and packed step 413s. These are shared-owner/shard measurements, not individual-test costs.

Strict local Swift lint reports inherited complexity 21 > 20 in GatewayProcessManager.swift:1160; the file/config match the PR base and current main. Its last owning change is 31dd34ff194. Existing CI policy treats complexity limits as advisory; no suppression was added. Full local core lint was interrupted without a result after 304.568s, then changed-file lint passed; no full-local-lint success is claimed.

Telegram CI fixture repair and stability evidence

The original failed job failed the General-topic accepted-transcript projection test with a plugin-state state-lifecycle contention error. Investigation found that the shared HTTP fixture faked process.hrtime, while the real SQLite worker compared admission deadlines against native hrtime. One transient conflict could therefore consume an already-expired deadline.

The fix keeps the existing simulated UI timers but preserves the native cross-thread clock. Five redundant per-test timer reinstalls were removed so the shared fixture owns the setting. No production code, assertions, timeouts, retry limits, or permanent tests were added or changed by this follow-up.

Reproduction, diagnostic patch, source bindings, and stability results: the exact failed CI merge on Linux/Node 24.19.0 reproduced the same assertion/error under one injected transient conflict with a negative deadline budget; the repaired fixture retained approximately five seconds and passed with identical instrumentation. This proves the clock defect under controlled contention; the original CI lock holder remains unidentified. Instrumentation was removed before final stability tests.

Final results: 20/20 standalone runs (26 tests each), 3/3 complete original packed-shard runs (1,257 tests across 80 files each), and all five fixture callers passed. The packed runs preserve preceding Codex → Telegram → voice-call order and original worker limits. The final source matched the committed full-index patch byte-for-byte. Standalone wall costs: reply-targets 72.050s (Linux), preview 72.539s (Linux, 30 tests), progress-lifecycle 124.783s (macOS, 23 tests). The complete shard repetitions took 632.995s, 637.282s, and 642.002s under concurrent Testbox load. Current-head CI Vitest durations: reply-targets 55.85s (26/26), progress-lifecycle 44.80s (23/23), and preview 68.40s (30/30). Their packed jobs passed in 396s and 455s respectively; those job totals include other files. The previously failing General-topic case passed in 1.875s.

Execution notes and proof limits

The first final admission attempt stopped before running tests because a concurrent QA build changed compiler inputs. After the build finished, the serialized run passed; this was a tooling/setup failure. An initial Swift lint prerequisite mismatch was resolved with the repository’s pinned SwiftLint 0.65.1 installer. Earlier reset test failures due to an incorrectly called assertion helper and assuming one error code for two existing refusal gates were corrected without changing product behavior.

The earlier proof uses isolated SQLite state, real Gateway RPC/admission, and an HTTP-backed QA channel. The additional live proof uses real Telegram Test Server transport and a TDLib QA user. Both use deterministic local models; neither claims external model-provider or production Telegram validation. Continuation cases invoke registered sessions_send; the direct harness injects a completed reply at the actual A2A owner. The ordinary during-work control uses a separate conversation; the account-switch case keeps the recipient unchanged. The proof does not establish universal exactly-once delivery or revocation during final transport I/O.

@joshavant
joshavant marked this pull request as ready for review September 23, 2026 22:05
@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: M labels Sep 23, 2026
@clawsweeper

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

@clawsweeper clawsweeper Bot added P1 High-priority user-facing bug, regression, or broken workflow. merge-risk: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. proof: telegram-e2e This PR needs Telegram Test Server proof with the repository E2E skill. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Sep 23, 2026
@clawsweeper

clawsweeper Bot commented Sep 23, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge. Reviewed September 23, 2026, 10:19 PM ET / September 24, 2026, 02:19 UTC (Revision 5).

ClawSweeper review

What this changes

The branch carries the requesting turn’s route and session generation into delayed cross-session replies, checks that generation at Gateway admission, and repairs a Telegram HTTP test fixture clock.

Merge readiness

⛔ Blocked before merge - 2 items remain

Current main still lacks this repair, and the submitted production-path evidence supports it. No actionable code defect is established. Live Telegram account and topic delivery remains a before-merge proof requirement.

Priority: P1
Reviewed head: ccab80e3884af5bf906724bffe8d9472a2cb2643

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) Strong Gateway boundary proof and focused guards support the patch; Telegram’s live destination check remains.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (terminal): Submitted terminal traces exercise the registered sessions_send tool through a real isolated Gateway, SQLite admission, and HTTP QA channel: the original route receives the delayed result, while replaced and reset requester generations are refused. Production source is unchanged since that proof; Telegram’s account and topic mapping remains a separate scoped merge gate. No stored-data contract changes.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (terminal): Submitted terminal traces exercise the registered sessions_send tool through a real isolated Gateway, SQLite admission, and HTTP QA channel: the original route receives the delayed result, while replaced and reset requester generations are refused. Production source is unchanged since that proof; Telegram’s account and topic mapping remains a separate scoped merge gate. No stored-data contract changes.
Evidence reviewed 10 items Introduced route capture: The tool receives the admitted session ID and active channel, account, recipient, and thread from the requesting turn.
Continuation handoff: The delayed Gateway agent request includes the captured route and expected session ID and lifecycle revision.
Gateway generation guard: Gateway admission rejects a mismatched session ID or lifecycle revision; the constraint is checked at admission and again against the fresh entry during persistence.
Findings None None.
Security None None.

How this fits together

The sessions_send tool starts work in another session and later asks the Gateway to continue the requester. The Gateway combines that request with session state and channel routing to determine where a reply can appear.

flowchart LR
A[Requesting chat turn] --> B[Cross-session send]
A --> C[Captured route and generation]
B --> D[Delayed child result]
C --> E{Requester still current?}
D --> E
E -->|Yes| F[Gateway continuation]
F --> G[Channel reply]
E -->|No| H[Refused result]
Loading

Before merge

  • Resolve merge risk (P1) - The HTTP QA-channel proof does not show Telegram’s actual bot account and topic interpretation for the captured route; scoped Telegram policy requires a Test Server result and reset-refusal check before merge.
  • Complete next step (P2) - Demonstrate the delayed result’s original account and topic and the reset refusal through Telegram’s Test Server before merge.
Agent review details

Security

None.

PR surface

Source +87, Tests +261, Other +4. Total +352 across 21 files.

View PR surface stats
Area Files Added Removed Net
Source 10 228 141 +87
Tests 10 359 98 +261
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 1 4 0 +4
Total 21 591 239 +352

Review metrics

Metric Value Why it matters
Gateway protocol surface 1 backend-only request field added; 0 config options or migrations The generation guard extends the existing request contract without changing stored state or user settings.
Net line growth production +91, tests and test support +261 The production growth serves route capture and admission checks; regression coverage accounts for most of the net increase.

Merge-risk options

Maintainer options:

  1. Verify Telegram destinations (recommended)
    Run the delayed continuation through Telegram’s Test Server and record the final account and topic plus the reset refusal.

Technical review

Best possible solution:

Land the captured-route and Gateway generation guard after a Telegram Test Server run confirms the delayed result’s original account and topic and the reset refusal.

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

Yes. Current-main source lacks the route and generation handoff, and the linked prior-head QA traces show the account-switch and reset failure paths; this read-only review did not execute current main.

Is this the best way to solve the issue?

Yes. The patch uses the existing Gateway admission and delivery owners for the narrow repair; Telegram’s final destination still needs live confirmation.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against e789666dc942.

Labels

Label changes:

No label changes.

Label justifications:

  • P1: A delayed cross-session result can reach the wrong requester route or a reset conversation in an active agent workflow.
  • merge-risk: 🚨 message-delivery: The changed route can alter the destination account and topic, which green CI and the QA transport do not settle for Telegram.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (terminal): Submitted terminal traces exercise the registered sessions_send tool through a real isolated Gateway, SQLite admission, and HTTP QA channel: the original route receives the delayed result, while replaced and reset requester generations are refused. Production source is unchanged since that proof; Telegram’s account and topic mapping remains a separate scoped merge gate. No stored-data contract changes.
  • proof: sufficient: Contributor real behavior proof is sufficient. Submitted terminal traces exercise the registered sessions_send tool through a real isolated Gateway, SQLite admission, and HTTP QA channel: the original route receives the delayed result, while replaced and reset requester generations are refused. Production source is unchanged since that proof; Telegram’s account and topic mapping remains a separate scoped merge gate. No stored-data contract changes.
  • proof: telegram-e2e: This PR needs Telegram Test Server proof with the repository E2E skill. The captured route can change which Telegram account and topic receive a visible delayed reply.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • Dallin Romney: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • Josh Avant: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

Rank-up moves

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

  • Show the delayed requester result’s final account and topic, plus reset refusal, through Telegram’s Test Server.

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 (4 earlier review cycles)
  • reviewed 2026-09-23T22:13:43.422Z sha a266817 :: needs real behavior proof before merge. :: [P1] Fence captured same-session replies before channel delivery
  • reviewed 2026-09-23T22:23:07.786Z sha a266817 :: needs real behavior proof before merge. :: [P1] Fence captured same-session replies before channel delivery
  • reviewed 2026-09-24T00:30:10.800Z sha cf4a350 :: needs maintainer review before merge. :: none
  • reviewed 2026-09-24T01:52:29.824Z sha ccab80e :: blocked before merge. :: none

@joshavant
joshavant force-pushed the fix/message-session-account-routing branch from a266817 to ea6ec34 Compare September 23, 2026 23:30
@joshavant

joshavant commented Sep 23, 2026 •

Copy link
Copy Markdown
Collaborator Author

Evidence for cf4a3501c7539596c68a35ee27bbc2c5352209d4 (candidate tree 76f5e852d19bfe7923f3155e9cfbbff575549d19).

The requester continuation preserves its original reply defaults and now checks both the physical session ID and reset generation through the existing Gateway admission owner. An ordinary route update keeps the generation and remains allowed; a reset invalidates the old continuation. The child and unrelated work remain available. The same-session direct shortcut stays removed.

Scenario Observed result
SID-only head ea6ec34, supported same-ID reset before releasing child Reset preserved SID and changed revision; one stale requester continuation and one result delivery reproduced the defect
Final candidate, same reset boundary Recorded Gateway refusal; zero requester continuation and zero result delivery
Final candidate, supported requester delete/recreate Different SID; recorded refusal; zero requester continuation and zero result delivery
Final candidate, later inbound changes saved account to alternate Original turn ended before child release; completion omitted account and recipient; one result reached original default account/recipient
Ordinary work and explicit child progress Before/during/after and child progress each succeeded in all three final continuation runs
Direct same-session boundary Old shortcut sent once after deletion; final restored lookup: allowed 1, duplicate 0, deleted 0, subsequent ordinary recreation 1

The final runs use isolated Gateway/SQLite state, the registered sessions_send and message tools, and an HTTP-backed QA channel with a deterministic local Responses model. They do not use an external provider or production channel. The direct harness injects a completed reply at runSessionsSendA2AFlow; it does not prove model-originated self-send. No claim of arbitrary final-adapter-I/O revocation, restart recovery custody, or universal exactly-once delivery is made. Same-session original-route preservation remains deferred.

Red/green source binding: the reset red ran on committed ea6ec34 with its build; all final green runs ran the frozen staged tree above before committing that exact tree. Each run checks source/build stability and owner cleanup. The earlier direct red is retained from the original shortcut and predates additional persisted-origin/RPC-success fixture assertions. The final direct case was rerun on this candidate. The reset red driver's exit 0 means the defect was reproduced, not that the fix passed.

Reproduction: check out the identified head, install repository dependencies, save the two exact drivers below together in a local evidence directory, and build with OPENCLAW_BUILD_PRIVATE_QA=1 node --import ./scripts/tsx.mjs scripts/build-all.mts qaRuntime. Run from the checkout with a fresh run label/output directory. No provider key is required.

OPENCLAW_COMPAT_RUN_ID=account-switch OPENCLAW_ROUTING_SWITCH_ACCOUNT=1 node --import ./scripts/tsx.mjs /absolute/evidence/routing-generation-probe-v9.mjs
OPENCLAW_COMPAT_RUN_ID=requester-replacement OPENCLAW_ROUTING_REPLACE_REQUESTER=1 node --import ./scripts/tsx.mjs /absolute/evidence/routing-generation-probe-v9.mjs
OPENCLAW_COMPAT_RUN_ID=requester-reset OPENCLAW_ROUTING_RESET_REQUESTER=1 node --import ./scripts/tsx.mjs /absolute/evidence/routing-generation-probe-v9.mjs
OPENCLAW_DIRECT_PROBE_OUTPUT=/absolute/evidence/direct-after node --import ./scripts/tsx.mjs /absolute/evidence/same-session-delivery-probe-v10.mjs
Observed traces and source/build binding
{
  "publishedHead": "cf4a3501c7539596c68a35ee27bbc2c5352209d4",
  "testedCandidateTree": "76f5e852d19bfe7923f3155e9cfbbff575549d19",
  "base": "af585c7490bd32741c9b66a3246cb36fba2dfa19",
  "patchSha256": "3852f13b82697717b3f673c3f7875cbd88fb92b5eed9a21d003a9fc0f72231dd",
  "files": {
    "apps/shared/OpenClawKit/Sources/OpenClawProtocol/GatewayModels.swift": "3fa6564fe34c987e4f5a686ada5b95e6ba68ca71b22b10c87ac8467bea5268ce",
    "packages/gateway-protocol/src/schema/agent.test.ts": "e9222d17d1fb75baa384ec616a52641f5fd4ac382795e72ba4581d74f52535bf",
    "packages/gateway-protocol/src/schema/agent.ts": "2b7ecbd22b4a0dca7292b4fd00074a609cdba57cd9f569474d1f9d8728e954e7",
    "src/agents/openclaw-tools.ts": "5fbed1416409a86bd313c4e09a86890ae58c68e3b846f4e4c2bc02ef6327b8ae",
    "src/agents/tools/agent-step.ts": "9fe569698b8aa86ad1daeb9c9862a4aefc778b5383f643472c2ef466c021557e",
    "src/agents/tools/sessions-send-tool.a2a.test.ts": "306536b8b83e9062f734ca434faa47de2276321cb7b9717731bce754d70d03b9",
    "src/agents/tools/sessions-send-tool.a2a.ts": "313da472cdf9c08d0a1d721935f0825b8470cf846553b856e7893fbf63d697cc",
    "src/agents/tools/sessions-send-tool.admission.test.ts": "d4f66bb5dab2431674538ff80931b1c263e22d30035a752fc84c1598461bca50",
    "src/agents/tools/sessions-send-tool.schema.ts": "ae7040c15e297bbbe38f3fc4529b157ad005f71319a8c30bf1a66c4a10698eac",
    "src/agents/tools/sessions-send-tool.ts": "b385f34e83fae3e57dccf683c0fef93e63c4db606e1971976670d12b4707eac9",
    "src/agents/tools/sessions-send-tool.types.ts": "b35275e716b8e630fdd13fbffbabeed2b7613f4e0b305ce4ba4589acc90baba7",
    "src/gateway/agent-turn/agent-request-preflight.ts": "13123da233c3e7d1ee084f9623fc32678cb50aa006f4ac632476376ee2510199",
    "src/gateway/server-methods/agent-expected-session.ts": "f23e9a915fdef59df256166ae6e3949c85264ba1ceb094b9b762cc90c2916003",
    "src/gateway/server-methods/agent-request-types.ts": "ba5e39282f8b77984dd54870ef7e5112693d4eaca95fb0971071fb4c8cea76df",
    "src/gateway/server-methods/agent.expected-session.test-utils.ts": "4310b076e5cf30310996a4b39a328b6a8a160d2b6b6596ad6c6133bd2b8b785f",
    "src/gateway/server-methods/agent.sessions-and-models.test-utils.ts": "e19c87e9ca374d44c3b427f1046de8f4aaa1b2cd4beb80e0daf6ade9e64eb0d4",
    "src/gateway/server-methods/agent.test.ts": "392dfb41f330953793d23cc884acd0c9f5077449da5da29264c5bb62bc54a093"
  },
  "qaBuild": {
    "exitCode": 0,
    "wallSeconds": 69.49250341695733,
    "candidateTree": "76f5e852d19bfe7923f3155e9cfbbff575549d19",
    "indexStable": true
  },
  "sameIdResetBefore": {
    "status": "regression-reproduced",
    "base": "ea6ec34a07db36d093a5c22edddde23fdbf56547",
    "sourceHash": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
    "sameIdReset": {
      "method": "sessions.reset then normal alternate-account inbound",
      "sessionId": "5f0797ea-8fdc-4762-98b4-853eacc7fc31",
      "beforeLifecycleRevision": null,
      "afterLifecycleRevision": "22f8018e-2dec-4f51-ab56-038901a77d8c",
      "terminal": {
        "runId": "0d90ef75-4d01-44fe-bf54-cd0df2fcb6d5",
        "sessionKey": "agent:qa:qa-channel:direct:dm:compat-sender",
        "phase": "end",
        "atMs": 20071
      },
      "atMs": 20101
    },
    "gatewayCleanup": {
      "process": "confirmed-stopped",
      "errors": []
    },
    "elapsedMs": 21606,
    "sourceStable": true,
    "buildStable": true,
    "outcome": {
      "receipt": {
        "runId": "928ac730-1af3-433c-b675-658398a1001f",
        "status": "accepted",
        "sessionKey": "agent:qa:qa-channel:direct:dm:compat-receiver",
        "targetDisposition": "queued",
        "delivery": {
          "status": "pending",
          "mode": "announce"
        }
      },
      "sourceTerminal": {
        "runId": "a8e3a374-e805-4ad8-80c8-8c96ffa01c4c",
        "sessionKey": "agent:qa:qa-channel:direct:dm:compat-sender",
        "phase": "end",
        "atMs": 19202
      },
      "childReleaseMs": 20101,
      "sameInitialTools": true,
      "childProgressMessages": 1,
      "automaticResultInRequesterContext": true,
      "requesterResultDeliveries": 1,
      "requesterDeliveryEvidence": [
        {
          "id": "208ed490-7185-4858-9dc3-c23e6e9922c0",
          "accountId": "default",
          "direction": "outbound",
          "conversation": {
            "id": "compat-sender",
            "kind": "direct"
          },
          "senderId": "openclaw",
          "senderName": "OpenClaw QA",
          "text": "COMPAT_REPORT_TOTAL_101",
          "timestamp": 1790206979749,
          "attachments": [],
          "reactions": []
        }
      ],
      "ordinaryEffects": {
        "before": 1,
        "during": 1,
        "after": 1
      },
      "duringScope": "Independent third ordinary conversation; not concurrent turns in the occupied receiver.",
      "contextInherited": true,
      "addressedReceiverUsed": true
    },
    "modelStageCounts": {
      "seed": 1,
      "before": 2,
      "source": 2,
      "child": 2,
      "during": 2,
      "routeupdate": 1,
      "completion": 1,
      "announce": 1,
      "after": 2
    },
    "buildHashes": {
      "dist/entry.js": "017597d4c42b4de0fc794eb1126a3e61ee8269c0834577b569d93bbbe828d4ed",
      "dist/build-info.json": "9570b1fa73e7013bd23a9f0f2d229b9c1a7754881de1185d8d9aeda628cba6ee",
      "dist/.buildstamp": "8e0a1fd24ea38dc014000c0f2356d9a7c61e218bb4e8574de9c3c97a92348d76",
      "dist/plugin-sdk/qa-runtime.js": "daf5f3646150342fd379ed7fea194d8551743b7c336a5f103b2c091278af7802"
    },
    "receipt": {
      "exitCode": 0,
      "wallSeconds": 42.85462437500246
    }
  },
  "accountSwitch": {
    "status": "passed",
    "base": "ea6ec34a07db36d093a5c22edddde23fdbf56547",
    "sourceHash": "3ce185b4ad63862dc3b00ec7a9e7bf3ac29bb63c9be3783a6046ff5f8232f940",
    "savedRouteBeforeCompletion": {
      "channel": "qa-channel",
      "to": "dm:compat-sender",
      "accountId": "alternate"
    },
    "savedRouteAfterCompletion": {
      "channel": "qa-channel",
      "to": "dm:compat-sender",
      "accountId": "default"
    },
    "routeUpdate": {
      "accountId": "alternate",
      "sessionKey": "agent:qa:qa-channel:direct:dm:compat-sender",
      "terminal": {
        "runId": "c08f9b08-6b64-4665-8375-3536cfea9d8d",
        "sessionKey": "agent:qa:qa-channel:direct:dm:compat-sender",
        "phase": "end",
        "atMs": 19142
      },
      "atMs": 19142
    },
    "gatewayCleanup": {
      "process": "confirmed-stopped",
      "errors": []
    },
    "elapsedMs": 20719,
    "sourceStable": true,
    "buildStable": true,
    "outcome": {
      "receipt": {
        "runId": "02746f2b-317b-4cf9-b905-25fff78b4558",
        "status": "accepted",
        "sessionKey": "agent:qa:qa-channel:direct:dm:compat-receiver",
        "targetDisposition": "queued",
        "delivery": {
          "status": "pending",
          "mode": "announce"
        }
      },
      "sourceTerminal": {
        "runId": "4be33aec-87bb-466d-b3d2-d6149b2198d7",
        "sessionKey": "agent:qa:qa-channel:direct:dm:compat-sender",
        "phase": "end",
        "atMs": 18646
      },
      "childReleaseMs": 19172,
      "sameInitialTools": true,
      "childProgressMessages": 1,
      "automaticResultInRequesterContext": true,
      "requesterResultDeliveries": 1,
      "requesterDeliveryEvidence": [
        {
          "id": "7adbb607-5854-4d55-af76-030b2e7eaca1",
          "accountId": "default",
          "direction": "outbound",
          "conversation": {
            "id": "compat-sender",
            "kind": "direct"
          },
          "senderId": "openclaw",
          "senderName": "OpenClaw QA",
          "text": "COMPAT_REPORT_TOTAL_101",
          "timestamp": 1790209024002,
          "attachments": [],
          "reactions": []
        }
      ],
      "ordinaryEffects": {
        "before": 1,
        "during": 1,
        "after": 1
      },
      "duringScope": "Independent third ordinary conversation; not concurrent turns in the occupied receiver.",
      "contextInherited": true,
      "addressedReceiverUsed": true
    },
    "modelStageCounts": {
      "seed": 1,
      "before": 2,
      "source": 2,
      "child": 2,
      "during": 2,
      "routeupdate": 1,
      "completion": 1,
      "announce": 1,
      "after": 2
    },
    "buildHashes": {
      "dist/entry.js": "b86588625b506d22cf3f446015bd041e234089a27519d395880cfd0f50f225cb",
      "dist/build-info.json": "06cf8f822aa81a32e4746c1023b5533fc79a2043de4d27fe411abe3e228e76cb",
      "dist/.buildstamp": "991c5c4da52e9285e18061e4f7bae1063ac8e7697acef7cd12af3dfc15daa052",
      "dist/plugin-sdk/qa-runtime.js": "daf5f3646150342fd379ed7fea194d8551743b7c336a5f103b2c091278af7802"
    },
    "receipt": {
      "exitCode": 0,
      "wallSeconds": 41.3226552499691,
      "candidateTree": "76f5e852d19bfe7923f3155e9cfbbff575549d19",
      "indexStable": true
    }
  },
  "requesterReplacement": {
    "status": "passed",
    "base": "ea6ec34a07db36d093a5c22edddde23fdbf56547",
    "sourceHash": "3ce185b4ad63862dc3b00ec7a9e7bf3ac29bb63c9be3783a6046ff5f8232f940",
    "requesterReplacement": {
      "method": "sessions.delete then normal inbound recreation",
      "previousSessionId": "ce6e9683-4ca9-4361-9922-2e493e76b178",
      "nextSessionId": "ff444cf3-608e-4f49-87a9-42637d5d3866",
      "terminal": {
        "runId": "4662c515-f125-4156-8196-24c0eefe4001",
        "sessionKey": "agent:qa:qa-channel:direct:dm:compat-sender",
        "phase": "end",
        "atMs": 18366
      },
      "atMs": 18393,
      "refusal": "Requester generation admission rejected the stale continuation before model execution",
      "diagnostic": "2026-09-23T19:17:43.839-05:00 [agents/sessions-send] sessions_send announce flow failed runId=7ecdfe6e-44a1-44b6-9219-67d543dd9fbf error=\"Session \\\"agent:qa:qa-channel:direct:dm:compat-sender\\\" changed before expected work could start.\""
    },
    "gatewayCleanup": {
      "process": "confirmed-stopped",
      "errors": []
    },
    "elapsedMs": 19671,
    "sourceStable": true,
    "buildStable": true,
    "outcome": {
      "receipt": {
        "runId": "7ecdfe6e-44a1-44b6-9219-67d543dd9fbf",
        "status": "accepted",
        "sessionKey": "agent:qa:qa-channel:direct:dm:compat-receiver",
        "targetDisposition": "queued",
        "delivery": {
          "status": "pending",
          "mode": "announce"
        }
      },
      "sourceTerminal": {
        "runId": "bc23500d-79bb-40b3-b4bc-01cb62ef90e3",
        "sessionKey": "agent:qa:qa-channel:direct:dm:compat-sender",
        "phase": "end",
        "atMs": 17694
      },
      "childReleaseMs": 18393,
      "sameInitialTools": true,
      "childProgressMessages": 1,
      "automaticResultInRequesterContext": false,
      "requesterResultDeliveries": 0,
      "requesterDeliveryEvidence": [],
      "ordinaryEffects": {
        "before": 1,
        "during": 1,
        "after": 1
      },
      "duringScope": "Independent third ordinary conversation; not concurrent turns in the occupied receiver.",
      "contextInherited": true,
      "addressedReceiverUsed": true
    },
    "modelStageCounts": {
      "seed": 1,
      "before": 2,
      "source": 2,
      "child": 2,
      "during": 2,
      "routeupdate": 1,
      "after": 2
    },
    "buildHashes": {
      "dist/entry.js": "b86588625b506d22cf3f446015bd041e234089a27519d395880cfd0f50f225cb",
      "dist/build-info.json": "06cf8f822aa81a32e4746c1023b5533fc79a2043de4d27fe411abe3e228e76cb",
      "dist/.buildstamp": "991c5c4da52e9285e18061e4f7bae1063ac8e7697acef7cd12af3dfc15daa052",
      "dist/plugin-sdk/qa-runtime.js": "daf5f3646150342fd379ed7fea194d8551743b7c336a5f103b2c091278af7802"
    },
    "receipt": {
      "exitCode": 0,
      "wallSeconds": 39.57411199994385,
      "candidateTree": "76f5e852d19bfe7923f3155e9cfbbff575549d19",
      "indexStable": true
    }
  },
  "sameIdResetAfter": {
    "status": "passed",
    "base": "ea6ec34a07db36d093a5c22edddde23fdbf56547",
    "sourceHash": "3ce185b4ad63862dc3b00ec7a9e7bf3ac29bb63c9be3783a6046ff5f8232f940",
    "sameIdReset": {
      "method": "sessions.reset then normal alternate-account inbound",
      "sessionId": "7e7d15ef-21f3-4c9d-82f7-ff3af99f0471",
      "beforeLifecycleRevision": null,
      "afterLifecycleRevision": "3c863497-91c6-41f5-b594-3a46528720b0",
      "terminal": {
        "runId": "b581de74-84f4-4dcf-8b3f-5db55a4d97e2",
        "sessionKey": "agent:qa:qa-channel:direct:dm:compat-sender",
        "phase": "end",
        "atMs": 18496
      },
      "atMs": 18529,
      "refusal": "Requester generation admission rejected the stale continuation before model execution",
      "diagnostic": "2026-09-23T19:18:23.308-05:00 [agents/sessions-send] sessions_send announce flow failed runId=c53a7005-a15e-40eb-8a0e-4c936ae59c49 error=\"Session \\\"agent:qa:qa-channel:direct:dm:compat-sender\\\" changed while starting expected work. Retry.\""
    },
    "gatewayCleanup": {
      "process": "confirmed-stopped",
      "errors": []
    },
    "elapsedMs": 19782,
    "sourceStable": true,
    "buildStable": true,
    "outcome": {
      "receipt": {
        "runId": "c53a7005-a15e-40eb-8a0e-4c936ae59c49",
        "status": "accepted",
        "sessionKey": "agent:qa:qa-channel:direct:dm:compat-receiver",
        "targetDisposition": "queued",
        "delivery": {
          "status": "pending",
          "mode": "announce"
        }
      },
      "sourceTerminal": {
        "runId": "a65f8b87-c68d-45c4-bfc1-fa680201875d",
        "sessionKey": "agent:qa:qa-channel:direct:dm:compat-sender",
        "phase": "end",
        "atMs": 17814
      },
      "childReleaseMs": 18529,
      "sameInitialTools": true,
      "childProgressMessages": 1,
      "automaticResultInRequesterContext": false,
      "requesterResultDeliveries": 0,
      "requesterDeliveryEvidence": [],
      "ordinaryEffects": {
        "before": 1,
        "during": 1,
        "after": 1
      },
      "duringScope": "Independent third ordinary conversation; not concurrent turns in the occupied receiver.",
      "contextInherited": true,
      "addressedReceiverUsed": true
    },
    "modelStageCounts": {
      "seed": 1,
      "before": 2,
      "source": 2,
      "child": 2,
      "during": 2,
      "routeupdate": 1,
      "after": 2
    },
    "buildHashes": {
      "dist/entry.js": "b86588625b506d22cf3f446015bd041e234089a27519d395880cfd0f50f225cb",
      "dist/build-info.json": "06cf8f822aa81a32e4746c1023b5533fc79a2043de4d27fe411abe3e228e76cb",
      "dist/.buildstamp": "991c5c4da52e9285e18061e4f7bae1063ac8e7697acef7cd12af3dfc15daa052",
      "dist/plugin-sdk/qa-runtime.js": "daf5f3646150342fd379ed7fea194d8551743b7c336a5f103b2c091278af7802"
    },
    "receipt": {
      "exitCode": 0,
      "wallSeconds": 39.35608966695145,
      "candidateTree": "76f5e852d19bfe7923f3155e9cfbbff575549d19",
      "indexStable": true
    }
  },
  "directBefore": {
    "head": "a2668171dcf576e114d14bf4674da8792d086cb9",
    "status": "regression-reproduced",
    "cells": [
      {
        "cell": "allowed",
        "requesterSessionId": "75e6a441-fa63-4186-b354-f7ad68323820",
        "outboundCount": 1,
        "deliveries": [
          {
            "accountId": "default",
            "conversation": {
              "id": "direct-probe-original",
              "kind": "direct"
            },
            "text": "DIRECT_PROBE_RESULT_allowed"
          }
        ],
        "methods": [
          "send"
        ]
      },
      {
        "cell": "duplicate",
        "requesterSessionId": "75e6a441-fa63-4186-b354-f7ad68323820",
        "outboundCount": 0,
        "deliveries": [],
        "methods": []
      },
      {
        "cell": "deleted",
        "requesterSessionId": "75e6a441-fa63-4186-b354-f7ad68323820",
        "outboundCount": 1,
        "deliveries": [
          {
            "accountId": "default",
            "conversation": {
              "id": "direct-probe-original",
              "kind": "direct"
            },
            "text": "DIRECT_PROBE_RESULT_deleted"
          }
        ],
        "methods": [
          "send"
        ]
      }
    ],
    "deletion": {
      "deleted": true,
      "absentFromList": true,
      "sessionKey": "agent:qa:direct:direct-probe-person"
    },
    "afterControl": {
      "newSession": true,
      "delivered": 1
    },
    "modelRequests": 2,
    "cleanup": {
      "process": "confirmed-stopped",
      "errors": []
    },
    "sourceStable": true,
    "limits": "A completed reply and captured requester identity/route are injected at runSessionsSendA2AFlow. This exercises the actual direct-delivery branch, real Gateway session mutations, routing, queue/dispatch and QA-channel HTTP I/O. It does not simulate a model self-send or establish general direct-send revocation safety.",
    "a2aSourceSha256": "7b71c46297aeeff1f08705b9115a5da07026cd55392e94a47c5370a966905dc8",
    "rpcResults": [
      {
        "method": "send",
        "status": "ok"
      },
      {
        "method": "send",
        "status": "ok"
      }
    ]
  },
  "directAfter": {
    "head": "ea6ec34a07db36d093a5c22edddde23fdbf56547",
    "status": "passed",
    "cells": [
      {
        "cell": "allowed",
        "requesterSessionId": "9f5d8533-85b0-41df-8894-2e3d5a67a51f",
        "outboundCount": 1,
        "deliveries": [
          {
            "accountId": "default",
            "conversation": {
              "id": "direct-probe-original",
              "kind": "direct"
            },
            "text": "DIRECT_PROBE_RESULT_allowed"
          }
        ],
        "methods": [
          "sessions.list",
          "send"
        ]
      },
      {
        "cell": "duplicate",
        "requesterSessionId": "9f5d8533-85b0-41df-8894-2e3d5a67a51f",
        "outboundCount": 0,
        "deliveries": [],
        "methods": []
      },
      {
        "cell": "deleted",
        "requesterSessionId": "9f5d8533-85b0-41df-8894-2e3d5a67a51f",
        "outboundCount": 0,
        "deliveries": [],
        "methods": [
          "sessions.list"
        ]
      }
    ],
    "capturedOrigin": {
      "channel": "qa-channel",
      "to": "dm:direct-probe-original",
      "accountId": "default"
    },
    "deletion": {
      "deleted": true,
      "absentFromList": true,
      "sessionKey": "agent:qa:direct:direct-probe-person"
    },
    "afterControl": {
      "newSession": true,
      "delivered": 1
    },
    "modelRequests": 2,
    "cleanup": {
      "process": "confirmed-stopped",
      "errors": []
    },
    "sourceStable": true,
    "limits": "A completed reply and captured requester identity/route are injected at runSessionsSendA2AFlow. This exercises the actual direct-delivery branch, real Gateway session mutations, routing, queue/dispatch and QA-channel HTTP I/O. It does not simulate a model self-send or establish general direct-send revocation safety.",
    "a2aSourceSha256": "313da472cdf9c08d0a1d721935f0825b8470cf846553b856e7893fbf63d697cc",
    "rpcResults": [
      {
        "method": "sessions.list",
        "status": "ok"
      },
      {
        "method": "send",
        "status": "ok"
      },
      {
        "method": "sessions.list",
        "status": "ok"
      }
    ],
    "receipt": {
      "exitCode": 0,
      "wallSeconds": 36.57982262503356,
      "candidateTree": "76f5e852d19bfe7923f3155e9cfbbff575549d19",
      "indexStable": true
    }
  }
}
routing-generation-probe-v9.mjs (SHA-256 93cad5920173116c7dfb4cbbfd25f5bcc466bb5c91cf648b67f79308d221c69b)
// Real Gateway routing regression: original account survives deferred completion.
// Uses only synthetic channel recipients and a deterministic local model.
import assert from 'node:assert/strict';
import { execFileSync } from 'node:child_process';
import { createHash } from 'node:crypto';
import fs from 'node:fs/promises';
import { createServer } from 'node:http';
import path from 'node:path';
import { fileURLToPath, pathToFileURL } from 'node:url';
import { performance } from 'node:perf_hooks';

const root = process.cwd();
const variant = 'routing-candidate';
assert.equal(JSON.parse(await fs.readFile(path.join(root, 'package.json'), 'utf8')).name, 'openclaw');
const switchAccount = process.env.OPENCLAW_ROUTING_SWITCH_ACCOUNT === '1';
const replaceRequester = process.env.OPENCLAW_ROUTING_REPLACE_REQUESTER === '1';
const resetRequester = process.env.OPENCLAW_ROUTING_RESET_REQUESTER === '1';
assert([switchAccount, replaceRequester, resetRequester].filter(Boolean).length <= 1);
const label = process.env.OPENCLAW_COMPAT_RUN_ID;
assert(label && /^[a-zA-Z0-9._-]+$/.test(label));
const out = path.join(path.dirname(fileURLToPath(import.meta.url)), 'runs', label);
await fs.mkdir(path.dirname(out), { recursive: true });
await fs.mkdir(out);
await fs.copyFile(new URL(import.meta.url), path.join(out, 'driver.mjs'));
const load = (file) => import(pathToFileURL(path.join(root, file)).href);
const { GatewayClient } = await load('dist/plugin-sdk/gateway-runtime.js');
const { buildAgentSessionKey } = await load('dist/plugin-sdk/routing.js');
const { createQaBusState, createQaChannelTransport, createQaGatewayChild, startQaBusServer } =
  await load('extensions/qa-lab/api.ts');
const { writeOpenAiResponsesSse, writeOpenAiResponsesText } =
  await load('test/helpers/openai-responses-sse.ts');
const started = performance.now();
const elapsed = () => Math.round(performance.now() - started);
const hash = (data) => createHash('sha256').update(data).digest('hex');
const sourceHash = () => hash(execFileSync('git', ['diff', 'HEAD', '--binary', '--no-ext-diff']));
const fingerprint = async () => Object.fromEntries(await Promise.all(
  ['dist/entry.js', 'dist/build-info.json', 'dist/.buildstamp', 'dist/plugin-sdk/qa-runtime.js']
    .map(async (f) => [f, hash(await fs.readFile(path.join(root, f)))]),
));
const evidence = {
  variant, switchAccount, replaceRequester, resetRequester, label, root, status: 'running',
  base: execFileSync('git', ['rev-parse', 'HEAD'], { encoding: 'utf8' }).trim(),
  sourceHash: sourceHash(), buildBefore: await fingerprint(),
  scope: 'Real Gateway/registered sessions_send; requester completion omits both accountId and target. Child progress explicitly selects default and does not test generic internal receiver inference. Synthetic allowed recipients/local model only; no retained-reader, containment, or external-provider probes.',
};
const deferred = () => {
  let resolve;
  const promise = new Promise((r) => { resolve = r; });
  return { promise, resolve };
};
const childArrived = deferred();
const releaseChild = deferred();
const completionObserved = deferred();
const fatal = deferred();
let fixtureError;
function fail(error) {
  fixtureError ??= error instanceof Error ? error : new Error(String(error));
  fatal.resolve(fixtureError);
}
async function bounded(promise, name, timeoutMs = 90000) {
  let timer;
  try {
    if (fixtureError) throw fixtureError;
    return await Promise.race([
      promise,
      fatal.promise.then((e) => { throw e; }),
      new Promise((_, reject) => { timer = setTimeout(() => reject(new Error(name + ' timed out')), timeoutMs); }),
    ]);
  } finally { clearTimeout(timer); }
}
const rows = [];
const requests = [];
const work = new Set();
const events = [];
const eventListeners = new Set();
const countByStage = new Map();
const resultText = 'COMPAT_REPORT_TOTAL_101';
const receiverFacts = 'four boxes of seventeen and three boxes of eleven';
const receiver = { id: 'compat-receiver', kind: 'direct' };
const sender = { id: 'compat-sender', kind: 'direct' };
const independent = { id: 'compat-independent', kind: 'direct' };
const keyFor = (c) => buildAgentSessionKey({
  agentId: 'qa', channel: 'qa-channel', accountId: 'default', dmScope: 'per-channel-peer',
  peer: { kind: 'direct', id: 'dm:' + c.id },
});
const receiverKey = keyFor(receiver);
const senderKey = keyFor(sender);
let receipt;
function tool(response, name, id, args) {
  const callId = hash(id).slice(0, 16);
  const item = { type: 'function_call', id: 'fc_' + callId, call_id: callId, name, arguments: JSON.stringify(args) };
  writeOpenAiResponsesSse(response, [
    { type: 'response.output_item.added', output_index: 0, item: { ...item, arguments: '' } },
    { type: 'response.function_call_arguments.delta', item_id: item.id, output_index: 0, delta: item.arguments },
    { type: 'response.output_item.done', output_index: 0, item },
    { type: 'response.completed', response: { id: 'resp_' + callId, status: 'completed', output: [item], usage: { input_tokens: 1, output_tokens: 1, total_tokens: 2 } } },
  ]);
}
const model = createServer((request, response) => {
  const pending = (async () => {
    if (request.method === 'GET' && request.url === '/v1/models') {
      response.writeHead(200, { 'content-type': 'application/json' }).end(JSON.stringify({ data: [{ id: 'qa-main', object: 'model' }] }));
      return;
    }
    assert.equal(request.method, 'POST');
    assert.equal(request.url, '/v1/responses');
    assert(requests.length < 32, 'local request budget');
    const chunks = []; let bytes = 0;
    for await (const chunk of request) { bytes += chunk.length; assert(bytes < 2 * 1024 * 1024); chunks.push(chunk); }
    const body = JSON.parse(Buffer.concat(chunks).toString());
    const input = body.input ?? [];
    const developer = JSON.stringify(input.filter((i) => i.role === 'developer' || i.role === 'system'));
    const lastUser = JSON.stringify(input.findLast((i) => i.role === 'user' && !JSON.stringify(i.content).includes('<<<BEGIN_OPENCLAW_INTERNAL_CONTEXT>>>')) ?? {});
    const full = JSON.stringify(input);
    const announce = developer.includes('Agent-to-agent announce step') || lastUser.includes('Agent-to-agent announce step');
    const opaque = full.includes('sessions_send task completion: status=');
    const replyStep = developer.includes('Agent-to-agent reply step') || developer.includes('Another session returned the result');
    const title = developer.includes('Generate a concise session title');
    const marker = lastUser.match(/COMPAT_(SEED|SOURCE|CHILD|ORDINARY|ROUTEUPDATE):([a-z-]+)/);
    const stage = title ? 'title' : announce ? 'announce' : opaque || replyStep ? 'completion' : marker?.[1] === 'ORDINARY' ? marker[2] : marker?.[1]?.toLowerCase();
    assert(stage, 'unrecognized local model request');
    const count = (countByStage.get(stage) ?? 0) + 1;
    countByStage.set(stage, count);
    assert(count <= (stage === 'title' ? 8 : 2), 'stage budget: ' + stage);
    const names = (body.tools ?? []).map((t) => t.name ?? t.type).toSorted();
    const row = { n: rows.length + 1, stage, count, names, atMs: elapsed(), inputHasReport: full.includes(resultText), inputHasReceiverContext: full.includes(receiverFacts) };
    rows.push(row); requests.push({ ...row, requestBytes: bytes, input });
    const text = (value) => writeOpenAiResponsesText(response, { text: value, messageId: 'msg_' + row.n, responseId: 'resp_' + row.n });
    if (stage === 'title') { text('Compatible delegation'); return; }
    if (stage === 'announce') { text('ANNOUNCE_SKIP'); return; }
    if (stage === 'completion') {
      assert(!replaceRequester && !resetRequester, 'Retired requester generation must not consume the stale completion');
      if (count === 1) {
        completionObserved.resolve(row);
        if (row.inputHasReport) {
          assert(names.includes('message'), 'requester delivery tool unavailable');
          tool(response, 'message', 'requester-result', {
            action: 'send', channel: 'qa-channel', message: resultText,
          });
          return;
        }
      }
      text('REPLY_SKIP'); return;
    }
    if (stage === 'seed') { text('COMPAT_SEED_DONE'); return; }
    if (stage === 'routeupdate') { text('COMPAT_ROUTE_UPDATE_DONE'); return; }
    if (stage === 'source') {
      if (count === 1) {
        assert(names.includes('sessions_send'));
        tool(response, 'sessions_send', 'source', { sessionKey: receiverKey, mode: 'followup', timeoutSeconds: 0,
          message: 'COMPAT_CHILD:report. Summarize the JUNIPER_INVENTORY details from your existing context. Send a short progress message through message to dm:compat-sink, then return the total.' });
      } else {
        const call = input.findLast((i) => i.type === 'function_call' && i.name === 'sessions_send');
        const output = input.findLast((i) => i.type === 'function_call_output' && i.call_id === call?.call_id);
        assert(output, 'sessions_send result missing');
        receipt = JSON.parse(output.output);
        assert.equal(receipt.status, 'accepted');
        text('COMPAT_SOURCE_DONE');
      }
      return;
    }
    if (stage === 'child') {
      assert(row.inputHasReceiverContext);
      if (count === 1) {
        childArrived.resolve(row);
        await releaseChild.promise;
        if (names.includes('message')) {
          tool(response, 'message', 'child-message', { action: 'send', channel: 'qa-channel', accountId: 'default', target: 'dm:compat-sink', message: 'COMPAT_CHILD_PROGRESS' });
          return;
        }
      }
      text(resultText); return;
    }
    assert(['before', 'during', 'after'].includes(stage));
    if (count === 1) {
      assert(names.includes('message'), 'ordinary message tool missing');
      tool(response, 'message', stage, { action: 'send', channel: 'qa-channel', target: 'dm:compat-sink', message: 'COMPAT_ORDINARY_' + stage });
    } else { text('COMPAT_' + stage.toUpperCase() + '_DONE'); }
  })().catch((error) => { fail(error); if (!response.headersSent) response.writeHead(500); response.end(); });
  work.add(pending);
  void pending.finally(() => work.delete(pending));
});
const busState = createQaBusState();
const transport = createQaChannelTransport(busState);
const owner = createQaGatewayChild();
let gateway; let observer; let bus;
async function eventWhere(predicate) {
  const existing = events.find(predicate); if (existing) return existing;
  let listener;
  const event = new Promise((resolve) => { listener = (e) => { if (predicate(e)) resolve(e); }; eventListeners.add(listener); });
  try { return await bounded(event, 'lifecycle event'); } finally { eventListeners.delete(listener); }
}
const send = (conversation, text, accountId = 'default') => bounded(transport.sendInbound({ accountId, conversation, senderId: 'synthetic-allowed', text }), 'inbound');
async function reply(conversation, text, accountId = 'default') {
  const message = await bounded(busState.waitFor({ kind: 'message-text', direction: 'outbound', textIncludes: text, timeoutMs: 90000 }), text);
  assert.equal(message.accountId, accountId); assert.equal(message.conversation.id, conversation.id); assert.equal(message.conversation.kind, conversation.kind);
  return message;
}
const requesterDeliveries = () => busState.getSnapshot().messages.filter((m) => m.direction === 'outbound' && m.text === resultText);
const effects = (text) => busState.getSnapshot().messages.filter((m) => m.direction === 'outbound' && m.text === text && m.conversation.id === 'compat-sink');
try {
  await new Promise((resolve, reject) => { model.once('error', reject); model.listen(0, '127.0.0.1', resolve); });
  const address = model.address(); assert(address && typeof address === 'object');
  bus = await startQaBusServer({ state: busState });
  gateway = await owner.start({ repoRoot: root, providerMode: 'mock-openai', providerBaseUrl: 'http://127.0.0.1:' + address.port + '/v1',
    primaryModel: 'mock-openai/qa-main', alternateModel: 'mock-openai/qa-main', transport, transportBaseUrl: bus.baseUrl, controlUiEnabled: false,
    mutateConfig: (cfg) => ({ ...cfg,
      channels: { ...cfg.channels, 'qa-channel': { ...cfg.channels?.['qa-channel'], accounts: { default: {}, alternate: {} }, defaultAccount: 'default' } },
      session: { ...cfg.session, dmScope: 'per-channel-peer' }, messages: { ...cfg.messages, queue: { mode: 'followup', debounceMs: 0 } },
      plugins: { ...cfg.plugins, slots: { memory: 'none' }, entries: { ...cfg.plugins?.entries, 'memory-core': { enabled: false } } },
      agents: { ...cfg.agents, defaults: { ...cfg.agents?.defaults, heartbeat: { every: '0m' }, skills: [], skipBootstrap: true,
        models: { 'mock-openai/qa-main': { agentRuntime: { id: 'openclaw' } } } }, entries: { qa: { ...cfg.agents?.entries?.qa, tools: { profile: 'messaging' } } } },
      tools: { profile: 'messaging', codeMode: false, toolSearch: false, sessions: { visibility: 'all' }, agentToAgent: { enabled: true } },
    }),
  });
  evidence.gatewayPid = gateway.pid;
  await bounded(transport.waitReady({ gateway }), 'transport ready');
  await bounded(new Promise((resolve, reject) => {
    observer = new GatewayClient({ url: gateway.wsUrl, token: gateway.token, deviceIdentity: null, clientName: 'gateway-client', mode: 'backend', scopes: ['operator.admin'],
      onHelloOk: resolve, onConnectError: reject,
      onEvent: (event) => {
        const p = event.payload;
        if (event.event !== 'agent' || p?.stream !== 'lifecycle') return;
        const e = { runId: p.runId, sessionKey: p.sessionKey, phase: p.data?.phase, atMs: elapsed() };
        events.push(e); for (const listener of eventListeners) listener(e);
      },
    }); observer.start();
  }), 'observer ready');
  for (const key of [receiverKey, senderKey, keyFor(independent)]) await observer.request('sessions.messages.subscribe', { key, agentId: 'qa' });
  console.log('COMPAT_GATEWAY_READY ' + variant);
  await send(receiver, 'COMPAT_SEED:inventory. JUNIPER_INVENTORY has ' + receiverFacts + '.');
  await reply(receiver, 'COMPAT_SEED_DONE');
  await send(receiver, 'COMPAT_ORDINARY:before. Send the requested short progress message.');
  await reply(receiver, 'COMPAT_BEFORE_DONE');
  await send(sender, 'COMPAT_SOURCE:report. Ask the existing receiver for its inventory report and continue after acceptance.');
  await reply(sender, 'COMPAT_SOURCE_DONE');
  const sourceTerminal = await eventWhere((e) => e.sessionKey === senderKey && e.phase === 'end');
  const child = await bounded(childArrived.promise, 'child admission');
  assert(receipt); assert.equal(receipt.status, 'accepted');
  assert.deepEqual(rows.find((r) => r.stage === 'source').names, rows.find((r) => r.stage === 'seed').names, 'ordinary peers must expose the same initial tools');
  await send(independent, 'COMPAT_ORDINARY:during. Send the requested short progress message.');
  await reply(independent, 'COMPAT_DURING_DONE');
  if (switchAccount) {
    const routeUpdateStartedMs = elapsed();
    await send(sender, 'COMPAT_ROUTEUPDATE:account. Reply with the route update acknowledgment.', 'alternate');
    await reply(sender, 'COMPAT_ROUTE_UPDATE_DONE', 'alternate');
    const terminal = await eventWhere((e) => e.sessionKey === senderKey && e.phase === 'end' && e.atMs >= routeUpdateStartedMs);
    evidence.routeUpdate = { accountId: 'alternate', sessionKey: senderKey, terminal, atMs: elapsed() };
    const sessions = await observer.request('sessions.list', { agentId: 'qa', includeGlobal: true, includeUnknown: true, limit: 200 });
    const current = sessions.sessions.find((row) => row.key === senderKey);
    assert.equal(current?.deliveryContext?.accountId, 'alternate', 'later inbound must actually change the saved route before completion');
    evidence.savedRouteBeforeCompletion = current.deliveryContext;
  }
  if (replaceRequester) {
    const previous = await observer.request('sessions.describe', { key: senderKey, agentId: 'qa' });
    assert(previous.session?.sessionId, 'original requester identity');
    const deletion = await observer.request('sessions.delete', { key: senderKey, agentId: 'qa', expectedSessionId: previous.session.sessionId, deleteTranscript: false });
    assert.equal(deletion.ok, true); assert.equal(deletion.deleted, true); assert.equal(deletion.key, senderKey);
    const recreateStartedMs = elapsed();
    await send(sender, 'COMPAT_ROUTEUPDATE:replacement. Reply with the route update acknowledgment.');
    await reply(sender, 'COMPAT_ROUTE_UPDATE_DONE');
    const terminal = await eventWhere((e) => e.sessionKey === senderKey && e.phase === 'end' && e.atMs >= recreateStartedMs);
    const replacement = await observer.request('sessions.describe', { key: senderKey, agentId: 'qa' });
    assert(replacement.session?.sessionId, 'replacement requester identity');
    assert.notEqual(replacement.session.sessionId, previous.session.sessionId, 'actual identity replacement');
    evidence.requesterReplacement = { method: 'sessions.delete then normal inbound recreation', previousSessionId: previous.session.sessionId, nextSessionId: replacement.session.sessionId, terminal, atMs: elapsed() };
  }
  if (resetRequester) {
    const before = await observer.request('sessions.describe', { key: senderKey, agentId: 'qa' });
    assert(before.session?.sessionId, 'original requester identity');
    const reset = await observer.request('sessions.reset', { key: senderKey, agentId: 'qa', expectedSessionId: before.session.sessionId });
    assert.equal(reset.ok, true); assert.equal(reset.key, senderKey);
    assert.equal(reset.entry?.sessionId, before.session.sessionId, 'reset must preserve physical session ID');
    assert(reset.entry?.lifecycleRevision, 'reset must issue lifecycle revision');
    assert.notEqual(reset.entry.lifecycleRevision, before.session.lifecycleRevision);
    const resetStartedMs = elapsed();
    await send(sender, 'COMPAT_ROUTEUPDATE:reset. Reply with the route update acknowledgment.', 'alternate');
    await reply(sender, 'COMPAT_ROUTE_UPDATE_DONE', 'alternate');
    const terminal = await eventWhere((e) => e.sessionKey === senderKey && e.phase === 'end' && e.atMs >= resetStartedMs);
    const after = await observer.request('sessions.describe', { key: senderKey, agentId: 'qa' });
    assert.equal(after.session?.sessionId, before.session.sessionId);
    evidence.sameIdReset = { method: 'sessions.reset then normal alternate-account inbound', sessionId: before.session.sessionId,
      beforeLifecycleRevision: before.session.lifecycleRevision ?? null, afterLifecycleRevision: reset.entry.lifecycleRevision, terminal, atMs: elapsed() };
  }
  const childReleaseMs = elapsed(); releaseChild.resolve();
  let completion;
  if (replaceRequester || resetRequester) {
    await eventWhere((e) => e.sessionKey === receiverKey && e.runId === receipt.runId && e.phase === 'end');
    await bounded((async () => {
      const deadline = performance.now() + 10000;
      while (performance.now() < deadline) {
        if (fixtureError) throw fixtureError;
        const diagnostic = gateway.logs().split('\n').find((line) =>
          line.includes('sessions_send announce flow failed') &&
          (line.includes('changed before expected work could start') || line.includes('changed while starting expected work')) &&
          line.includes(receipt.runId) && line.includes(senderKey));
        if (diagnostic) {
          const retirement = resetRequester ? evidence.sameIdReset : evidence.requesterReplacement;
          retirement.refusal = 'Requester generation admission rejected the stale continuation before model execution';
          retirement.diagnostic = diagnostic;
          return;
        }
        await new Promise((resolve) => setTimeout(resolve, 100));
      }
      throw new Error('Expected-session refusal was not observed');
    })(), 'requester replacement refusal');
    assert.equal(rows.filter((row) => row.stage === 'completion').length, 0);
  } else {
    completion = await bounded(completionObserved.promise, 'automatic completion');
    await eventWhere((e) => e.sessionKey === senderKey && e.runId !== sourceTerminal.runId && e.atMs >= childReleaseMs && e.phase === 'end');
  }
  await send(receiver, 'COMPAT_ORDINARY:after. Send the requested short progress message.');
  await reply(receiver, 'COMPAT_AFTER_DONE');
  assert.equal(child.names.includes('message'), true);
  assert.equal(effects('COMPAT_CHILD_PROGRESS').length, 1);
  assert.equal(completion?.inputHasReport ?? false, !(replaceRequester || resetRequester));
  assert.equal(requesterDeliveries().length, replaceRequester || resetRequester ? 0 : 1, 'exact requester-visible report delivery');
  for (const delivery of requesterDeliveries()) {
    assert.equal(delivery.accountId, 'default', 'original requester account');
    assert.equal(delivery.conversation.id, sender.id, 'original requester recipient');
    assert.equal(delivery.conversation.kind, sender.kind, 'original requester conversation kind');
  }
  assert.equal(receipt.sessionKey, receiverKey);
  if (switchAccount) {
    const sessions = await observer.request('sessions.list', { agentId: 'qa', includeGlobal: true, includeUnknown: true, limit: 200 });
    const current = sessions.sessions.find((row) => row.key === senderKey);
    // Successful outbound sends establish the last-used route; admission itself
    // is not the only route writer during a completed requester turn.
    evidence.savedRouteAfterCompletion = current?.deliveryContext;
  }
  for (const stage of ['before', 'during', 'after']) {
    assert.equal(effects('COMPAT_ORDINARY_' + stage).length, 1);
    assert.equal(effects('COMPAT_ORDINARY_' + stage)[0].accountId, 'default');
    assert.equal(effects('COMPAT_ORDINARY_' + stage)[0].conversation.kind, 'direct');
  }
  for (const message of effects('COMPAT_CHILD_PROGRESS')) {
    assert.equal(message.accountId, 'default');
    assert.equal(message.conversation.kind, 'direct');
  }
  assert(sourceTerminal.atMs <= childReleaseMs);
  evidence.outcome = { receipt, sourceTerminal, childReleaseMs, sameInitialTools: true, ordinaryToolNames: rows.find((r) => r.stage === 'source').names,
    childToolNames: child.names, childProgressMessages: effects('COMPAT_CHILD_PROGRESS').length, automaticResultInRequesterContext: completion?.inputHasReport ?? false, requesterResultDeliveries: requesterDeliveries().length, requesterDeliveryEvidence: requesterDeliveries(),
    requesterDeliveryMode: 'Automatic requester continuation calls message with channel but omits both accountId and target. Expected original account default and original recipient even when a later inbound updates the shared session to alternate. agent-step itself uses deliver:false.',
    ordinaryEffects: { before: 1, during: 1, after: 1 }, duringScope: 'Independent third ordinary conversation; not concurrent turns in the occupied receiver.',
    contextInherited: child.inputHasReceiverContext, addressedReceiverUsed: receipt.sessionKey === receiverKey };
  evidence.status = 'passed';
} catch (error) { fail(error); evidence.status = 'failed'; evidence.error = String(error); process.exitCode = 1; }
finally {
  evidence.outboundMessages = busState.getSnapshot().messages.filter((m) => m.direction === 'outbound');
  evidence.observedRequesterDeliveries = requesterDeliveries();
  releaseChild.resolve();
  const cleanupErrors = [];
  try { await observer?.stopAndWait(); } catch (e) { cleanupErrors.push(String(e)); }
  if (gateway) { try { await fs.writeFile(path.join(out, 'gateway.log'), gateway.logs()); } catch (e) { cleanupErrors.push(String(e)); } }
  try { evidence.gatewayCleanup = await owner.stop(); if (evidence.gatewayCleanup.process !== 'confirmed-stopped' || evidence.gatewayCleanup.errors.length) cleanupErrors.push('Gateway cleanup incomplete'); } catch (e) { cleanupErrors.push(String(e)); }
  try { await bus?.stop(); } catch (e) { cleanupErrors.push(String(e)); }
  model.closeAllConnections();
  await new Promise((resolve) => model.close(resolve));
  await Promise.allSettled([...work]);
  evidence.cleanupErrors = cleanupErrors; evidence.elapsedMs = elapsed(); evidence.rows = rows; evidence.events = events;
  evidence.finalBase = execFileSync('git', ['rev-parse', 'HEAD'], { encoding: 'utf8' }).trim();
  evidence.sourceStable = evidence.finalBase === evidence.base && sourceHash() === evidence.sourceHash; evidence.buildAfter = await fingerprint();
  evidence.buildStable = JSON.stringify(evidence.buildBefore) === JSON.stringify(evidence.buildAfter);
  if (fixtureError || cleanupErrors.length || !evidence.sourceStable || !evidence.buildStable) {
    evidence.status = 'failed'; process.exitCode = 1;
    if (fixtureError) evidence.error ??= String(fixtureError);
  }
  await fs.writeFile(path.join(out, 'requests.json'), JSON.stringify(requests, null, 2) + '\n');
  await fs.writeFile(path.join(out, 'evidence.json'), JSON.stringify(evidence, null, 2) + '\n');
  console.log(JSON.stringify({ status: evidence.status, variant, modelRequests: rows.length, outcome: evidence.outcome, cleanup: evidence.gatewayCleanup }));
}
same-session-delivery-probe-v10.mjs (SHA-256 97a6faa6493db1d03755fd49e32010aaa6f43ec2fac111b90234ce5bb1673c0e)
// Direct A2A boundary probe: real Gateway, SQLite and HTTP-backed QA channel.
// Only the completed reply and captured requester facts are injected.
import assert from 'node:assert/strict';
import { execFileSync } from 'node:child_process';
import { createHash } from 'node:crypto';
import fs from 'node:fs/promises';
import { createServer } from 'node:http';
import path from 'node:path';
import { pathToFileURL } from 'node:url';

const root = process.cwd();
const out = process.env.OPENCLAW_DIRECT_PROBE_OUTPUT;
assert(out && path.isAbsolute(out));
await fs.mkdir(out);
await fs.copyFile(new URL(import.meta.url), path.join(out, 'driver.mjs'));
const load = (file) => import(pathToFileURL(path.join(root, file)).href);
const { GatewayClient } = await load('dist/plugin-sdk/gateway-runtime.js');
const { createQaBusState, createQaChannelTransport, createQaGatewayChild, startQaBusServer } = await load('extensions/qa-lab/api.ts');
const { writeOpenAiResponsesText } = await load('test/helpers/openai-responses-sse.ts');
const { runSessionsSendA2AFlow } = await load('src/agents/tools/sessions-send-tool.a2a.ts');
const hash = (data) => createHash('sha256').update(data).digest('hex');
const fingerprint = async () => Object.fromEntries(await Promise.all([
  'src/agents/tools/sessions-send-tool.a2a.ts', 'dist/entry.js', 'dist/.buildstamp', 'dist/plugin-sdk/qa-runtime.js',
].map(async (file) => [file, hash(await fs.readFile(path.join(root, file)))])));
const head = () => execFileSync('git', ['rev-parse', 'HEAD'], { encoding: 'utf8' }).trim();
const evidence = { head: head(), before: await fingerprint(), status: 'running', cells: [], rpc: [], limits: 'A completed reply and captured requester identity/route are injected at runSessionsSendA2AFlow. This exercises the actual direct-delivery branch, real Gateway session mutations, routing, queue/dispatch and QA-channel HTTP I/O. It does not simulate a model self-send or establish general direct-send revocation safety.' };
const state = createQaBusState();
const transport = createQaChannelTransport(state);
const owner = createQaGatewayChild();
let gateway; let client; let bus; let modelRequests = 0;
let modelError;
const requests = new Set();
const model = createServer((request, response) => {
  const pending = (async () => {
    if (request.method === 'GET' && request.url === '/v1/models') {
      response.writeHead(200, { 'content-type': 'application/json' }).end(JSON.stringify({ data: [{ id: 'qa-main', object: 'model' }] }));
      return;
    }
    assert.equal(request.method, 'POST'); assert.equal(request.url, '/v1/responses');
    const chunks = []; for await (const chunk of request) chunks.push(chunk);
    const body = JSON.parse(Buffer.concat(chunks).toString());
    const text = JSON.stringify(body.input ?? []);
    const marker = text.match(/DIRECT_PROBE_SEED_([a-z]+)/);
    assert(marker, 'unexpected model input');
    modelRequests++;
    writeOpenAiResponsesText(response, { text: 'DIRECT_PROBE_READY_' + marker[1], messageId: 'msg_' + modelRequests, responseId: 'resp_' + modelRequests });
  })().catch((error) => { modelError = error; if (!response.headersSent) response.writeHead(500); response.end(); });
  requests.add(pending); void pending.finally(() => requests.delete(pending));
});
const key = 'agent:qa:direct:direct-probe-person';
const conversation = { id: 'direct-probe-original', kind: 'direct' };
let origin;
const outbound = (text) => state.getSnapshot().messages.filter((m) => m.direction === 'outbound' && m.text === text);
const gatewayCall = async (request) => {
  const row = { method: request.method, params: request.params };
  evidence.rpc.push(row);
  try { const result = await client.request(request.method, request.params); row.status = 'ok'; return result; }
  catch (error) { row.status = 'error'; row.error = String(error); throw error; }
};
async function seed(label) {
  await transport.sendInbound({ accountId: 'default', conversation, senderId: 'synthetic-allowed', text: 'DIRECT_PROBE_SEED_' + label });
  await state.waitFor({ kind: 'message-text', direction: 'outbound', textIncludes: 'DIRECT_PROBE_READY_' + label, timeoutMs: 90000 });
  const described = await client.request('sessions.describe', { key, agentId: 'qa' });
  assert(described.session?.sessionId, 'real original session exists');
  assert.equal(described.session.key, key);
  const listed = await client.request('sessions.list', { agentId: 'qa', includeGlobal: true, includeUnknown: true, limit: 200 });
  const context = listed.sessions.find((row) => row.key === key)?.deliveryContext;
  assert.equal(context?.channel, 'qa-channel');
  assert.equal(context?.accountId, 'default');
  assert.equal(context?.to, 'dm:direct-probe-original');
  origin = context;
  evidence.capturedOrigin = context;
  return described.session.sessionId;
}
async function flow(cell, sessionId, sourceReplyDelivered) {
  const text = 'DIRECT_PROBE_RESULT_' + cell;
  const start = evidence.rpc.length;
  await runSessionsSendA2AFlow({ callGateway: gatewayCall, targetSessionKey: key, targetAgentId: 'qa', displayKey: key,
    requesterSessionKey: key, requesterAgentId: 'qa', requesterSession: { sessionId }, requesterOrigin: origin, requesterChannel: 'qa-channel',
    message: 'Return the synthetic result', roundOneReply: text, announceTimeoutMs: 10000, maxPingPongTurns: 0,
    ...(sourceReplyDelivered ? { sourceReplyDelivered: true } : {}),
  });
  const effects = outbound(text);
  assert(evidence.rpc.slice(start).every((row) => row.status === 'ok'), 'A2A must not swallow an RPC failure');
  const result = { cell, requesterSessionId: sessionId, outboundCount: effects.length, deliveries: effects.map(({ accountId, conversation, text }) => ({ accountId, conversation, text })), methods: evidence.rpc.slice(start).map((r) => r.method) };
  evidence.cells.push(result);
  return result;
}
try {
  await new Promise((resolve, reject) => { model.once('error', reject); model.listen(0, '127.0.0.1', resolve); });
  bus = await startQaBusServer({ state });
  gateway = await owner.start({ repoRoot: root, providerMode: 'mock-openai', providerBaseUrl: 'http://127.0.0.1:' + model.address().port + '/v1',
    primaryModel: 'mock-openai/qa-main', alternateModel: 'mock-openai/qa-main', transport, transportBaseUrl: bus.baseUrl, controlUiEnabled: false,
    mutateConfig: (cfg) => ({ ...cfg, session: { ...cfg.session, dmScope: 'per-peer', identityLinks: { 'direct-probe-person': ['qa-channel:dm:direct-probe-original'] } },
      plugins: { ...cfg.plugins, slots: { memory: 'none' }, entries: { ...cfg.plugins?.entries, 'memory-core': { enabled: false } } },
      agents: { ...cfg.agents, defaults: { ...cfg.agents?.defaults, heartbeat: { every: '0m' }, skills: [], skipBootstrap: true,
        models: { 'mock-openai/qa-main': { agentRuntime: { id: 'openclaw' } } } } },
      tools: { profile: 'messaging', codeMode: false, toolSearch: false, sessions: { visibility: 'all' }, agentToAgent: { enabled: true } },
    }),
  });
  await transport.waitReady({ gateway });
  await new Promise((resolve, reject) => {
    client = new GatewayClient({ url: gateway.wsUrl, token: gateway.token, deviceIdentity: null, clientName: 'gateway-client', mode: 'backend', scopes: ['operator.admin'], onHelloOk: resolve, onConnectError: reject });
    client.start();
  });
  const original = await seed('original');
  const allowed = await flow('allowed', original);
  assert.equal(allowed.outboundCount, 1);
  assert.equal(allowed.deliveries[0].accountId, 'default');
  assert.equal(allowed.deliveries[0].conversation.id, conversation.id);
  const duplicate = await flow('duplicate', original, true);
  assert.equal(duplicate.outboundCount, 0); assert.deepEqual(duplicate.methods, []);
  const deletion = await client.request('sessions.delete', { key, agentId: 'qa', expectedSessionId: original, deleteTranscript: false });
  assert.equal(deletion.deleted, true);
  const listed = await client.request('sessions.list', { agentId: 'qa', includeGlobal: true, includeUnknown: true, limit: 200 });
  assert(!listed.sessions.some((row) => row.key === key), 'requester must be absent');
  evidence.deletion = { deleted: true, absentFromList: true, sessionKey: key };
  const deleted = await flow('deleted', original);
  // Leave failure observable while collecting the control and cleanup evidence.
  evidence.regressionObserved = deleted.outboundCount !== 0;
  if (evidence.regressionObserved) {
    assert.equal(deleted.outboundCount, 1); assert.deepEqual(deleted.methods, ['send']);
    assert.deepEqual(deleted.deliveries[0].conversation, conversation);
    assert.equal(deleted.deliveries[0].accountId, 'default');
  } else {
    assert.deepEqual(deleted.methods, ['sessions.list']);
  }
  const recreated = await seed('after');
  assert.notEqual(recreated, original);
  evidence.afterControl = { newSession: true, delivered: outbound('DIRECT_PROBE_READY_after').length };
  assert.equal(evidence.afterControl.delivered, 1);
  if (modelError) throw modelError;
  evidence.status = evidence.regressionObserved ? 'regression-reproduced' : 'passed';
} catch (error) { evidence.status = 'fixture-failed'; evidence.error = String(error); process.exitCode = 1; }
finally {
  const cleanupErrors = [];
  try { await client?.stopAndWait(); } catch (error) { cleanupErrors.push(String(error)); }
  if (gateway) await fs.writeFile(path.join(out, 'gateway.log'), gateway.logs());
  try { evidence.cleanup = await owner.stop(); } catch (error) { cleanupErrors.push(String(error)); }
  try { await bus?.stop(); } catch (error) { cleanupErrors.push(String(error)); }
  model.closeAllConnections(); await new Promise((resolve) => model.close(resolve)); await Promise.allSettled(requests);
  evidence.after = await fingerprint(); evidence.headAfter = head(); evidence.modelRequests = modelRequests; evidence.cleanupErrors = cleanupErrors;
  evidence.sourceStable = JSON.stringify(evidence.before) === JSON.stringify(evidence.after) && evidence.head === evidence.headAfter;
  if (!evidence.sourceStable || cleanupErrors.length || evidence.cleanup?.process !== 'confirmed-stopped' || evidence.cleanup?.errors.length) { evidence.status = 'fixture-failed'; process.exitCode = 1; }
  await fs.writeFile(path.join(out, 'evidence.json'), JSON.stringify(evidence, null, 2) + '\n');
  console.log(JSON.stringify(evidence, null, 2));
}
Exact red reset driver reconstruction (SHA-256 6bcd10e2450e4c44dc96e708af2c371b03affcb89b0bf13349b5397430d05a0b)

Apply this patch to the green driver, save as routing-reset-probe-v6.mjs, and run with OPENCLAW_ROUTING_RESET_REQUESTER=1 on ea6ec34 after building that checkout. Its expected outcome is one stale delivery; the recorded red run below used these exact bytes.

--- routing-generation-probe-v9.mjs
+++ routing-reset-probe-v6.mjs
@@ -129,7 +129,7 @@
     if (stage === 'title') { text('Compatible delegation'); return; }
     if (stage === 'announce') { text('ANNOUNCE_SKIP'); return; }
     if (stage === 'completion') {
-      assert(!replaceRequester && !resetRequester, 'Retired requester generation must not consume the stale completion');
+      assert(!replaceRequester, 'Replacement requester must not consume the stale completion');
       if (count === 1) {
         completionObserved.resolve(row);
         if (row.inputHasReport) {
@@ -284,7 +284,7 @@
   }
   const childReleaseMs = elapsed(); releaseChild.resolve();
   let completion;
-  if (replaceRequester || resetRequester) {
+  if (replaceRequester) {
     await eventWhere((e) => e.sessionKey === receiverKey && e.runId === receipt.runId && e.phase === 'end');
     await bounded((async () => {
       const deadline = performance.now() + 10000;
@@ -292,12 +292,11 @@
         if (fixtureError) throw fixtureError;
         const diagnostic = gateway.logs().split('\n').find((line) =>
           line.includes('sessions_send announce flow failed') &&
-          (line.includes('changed before expected work could start') || line.includes('changed while starting expected work')) &&
+          line.includes('changed before expected work could start') &&
           line.includes(receipt.runId) && line.includes(senderKey));
         if (diagnostic) {
-          const retirement = resetRequester ? evidence.sameIdReset : evidence.requesterReplacement;
-          retirement.refusal = 'Requester generation admission rejected the stale continuation before model execution';
-          retirement.diagnostic = diagnostic;
+          evidence.requesterReplacement.refusal = 'Existing Gateway expected-session admission rejected the stale requester before model continuation';
+          evidence.requesterReplacement.diagnostic = diagnostic;
           return;
         }
         await new Promise((resolve) => setTimeout(resolve, 100));
@@ -313,8 +312,8 @@
   await reply(receiver, 'COMPAT_AFTER_DONE');
   assert.equal(child.names.includes('message'), true);
   assert.equal(effects('COMPAT_CHILD_PROGRESS').length, 1);
-  assert.equal(completion?.inputHasReport ?? false, !(replaceRequester || resetRequester));
-  assert.equal(requesterDeliveries().length, replaceRequester || resetRequester ? 0 : 1, 'exact requester-visible report delivery');
+  assert.equal(completion?.inputHasReport ?? false, !replaceRequester);
+  assert.equal(requesterDeliveries().length, replaceRequester ? 0 : 1, 'exact requester-visible report delivery');
   for (const delivery of requesterDeliveries()) {
     assert.equal(delivery.accountId, 'default', 'original requester account');
     assert.equal(delivery.conversation.id, sender.id, 'original requester recipient');
@@ -343,7 +342,7 @@
     requesterDeliveryMode: 'Automatic requester continuation calls message with channel but omits both accountId and target. Expected original account default and original recipient even when a later inbound updates the shared session to alternate. agent-step itself uses deliver:false.',
     ordinaryEffects: { before: 1, during: 1, after: 1 }, duringScope: 'Independent third ordinary conversation; not concurrent turns in the occupied receiver.',
     contextInherited: child.inputHasReceiverContext, addressedReceiverUsed: receipt.sessionKey === receiverKey };
-  evidence.status = 'passed';
+  evidence.status = resetRequester ? 'regression-reproduced' : 'passed';
 } catch (error) { fail(error); evidence.status = 'failed'; evidence.error = String(error); process.exitCode = 1; }
 finally {
   evidence.outboundMessages = busState.getSnapshot().messages.filter((m) => m.direction === 'outbound');

@joshavant joshavant changed the title fix: send delayed session replies through the original account fix: preserve requester routes for delayed session continuations Sep 23, 2026
@joshavant

Copy link
Copy Markdown
Collaborator Author

@clawsweeper re-review: Review ea6ec34 and the updated PR body. The previously flagged same-session captured-route shortcut is removed; original-route preservation for that direct path is explicitly deferred. Retained requester model continuations preserve the active source route and physical session ID through the existing Gateway admission owner. Fresh independent P0–P2 review is clean.

Public evidence with exact portable drivers, allowlisted actual traces, and source/build binding: #156802 (comment) . It includes stale direct send before removal versus allowed/duplicate/deleted controls afterward; registered sessions_send after the sender ends and another account updates its saved route, with implicit account AND recipient; and actual delete/recreate rejection before requester continuation/result delivery. Ordinary work and child progress remain available. Direct v4 evidence is explicitly limited to its byte-identical A2A owner; v5 continuation proofs bind to the published candidate tree.

Please assess real-behavior proof on its merits even though this is a maintainer-authored PR, and provide Proof confidence as well as Overall readiness and Patch quality. These are core Gateway/HTTP QA-channel proofs with a deterministic local model, not a Telegram/provider claim or a proof override. Selected local checks and current-head hosted CI are still running and are marked pending in the body. Review only; do not merge or enable automerge.

@clawsweeper

clawsweeper Bot commented Sep 23, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@joshavant

Copy link
Copy Markdown
Collaborator Author

@clawsweeper re-review

Please review current head cf4a3501c7539596c68a35ee27bbc2c5352209d4 using the updated PR body and linked reproducible evidence.

The introduced same-session captured-route shortcut remains removed. This head also addresses the same-ID reset gap from the prior exact-review artifact: requester continuations carry the existing lifecycle revision into the Gateway's existing expected-session admission/persistence checks. Omission preserves ID-only callers; null and string bind the captured generation.

The proof includes an observed stale result on the prior ID-only head, then real isolated Gateway/SQLite/HTTP-channel green cases for account switching, requester replacement, same-ID reset, and the removed direct shortcut. Ordinary sends and child progress remain available. Exact drivers, sanitized traces, and tested-source/build bindings are in the evidence link. The model is deterministic/local; no external-provider or production-channel claim is made.

Please assess all three ratings, including proof confidence, from the submitted evidence even though the maintainer proof gate does not require it. Fresh independent review and local checks are recorded. Exact-head CI is still running at https://github.com/openclaw/openclaw/actions/runs/35937896702; no pending check is claimed as passed, and the inherited local Swift complexity failure is documented.

Review only. Keep this PR open and unmerged; do not enable autofix or auto-merge.

@openclaw-barnacle openclaw-barnacle Bot added app: web-ui App: web-ui gateway Gateway runtime labels Sep 24, 2026
@clawsweeper

clawsweeper Bot commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. 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. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Sep 24, 2026
@openclaw-barnacle openclaw-barnacle Bot added the channel: telegram Channel integration: telegram label Sep 24, 2026
@joshavant

joshavant commented Sep 24, 2026 •

Copy link
Copy Markdown
Collaborator Author

Fix commit: ccab80e3884af5bf906724bffe8d9472a2cb2643.

The CI failure exposed a Telegram HTTP fixture clock defect. This follow-up preserves native process.hrtime for cross-thread SQLite admission deadlines and removes five per-test timer reinstalls that would undo that setting. Production code, assertions, retry limits, and timeouts are unchanged.

The failing CI case was retains provider time and General-topic provenance in accepted transcript projections, with PLUGIN_STATE_WRITE_FAILED / CHANNEL_PARTIAL_DELIVERY and another OpenClaw process owns state-lifecycle. Its log did not identify the lock holder. One unchanged Linux replay of the original preceding Codex and Telegram groups passed (495 tests); that replay alone did not establish a fix.

Controlled reproduction: on the exact failed CI merge df478e81f3bcb4e1540bfab08566c5b0bbdd9de2, Linux x64 / Node 24.19.0 / pnpm 12.4.2, inject one transient coordinator contention into the real worker's pluginState.compareUpdate for this test. With the original fixture, the deadline budget was −899850.687ms, and the original assertion failed with the same error. With the narrowed fixture clock, the budget was 4999.818ms and the same test passed. This is fault-injection proof of the clock defect, not a claim that the original CI lock-holder interleaving was spontaneously reproduced. The diagnostic instrumentation was removed before stability testing.

The shared fixture uses the same explicit timer list already used by src/cron/service.heartbeat-busy-poll.test.ts. Fresh review caught one nested unrestricted timer reinstall; a caller sweep found four more. All five were removed, leaving the shared fixture as the clock owner. The final independent review was clean through P2.

Reproduction instrumentation and command

Apply this diagnostic-only patch to the failed CI merge in an isolated checkout. Run once with the original fixture and once with the final shared-fixture timer configuration, retaining identical instrumentation:

CI=1 node scripts/run-vitest.mjs extensions/telegram/src/bot-message-dispatch.reply-targets.telegram-http.test.ts --maxWorkers=1 -t 'retains provider time and General-topic provenance'
diff --git a/src/infra/sqlite-store.worker.ts b/src/infra/sqlite-store.worker.ts
index 5b5a9601..76d15b1b 100644
--- a/src/infra/sqlite-store.worker.ts
+++ b/src/infra/sqlite-store.worker.ts
@@ -217,7 +217,7 @@ async function receive(request: SqliteWorkerRequest): Promise<void> {
         retire = false;
       }
     }
-    const prepareLifecycle = async () => {
+    const prepareLifecycle = async (probeContention = false) => {
       if (lifecyclePreparation) {
         const context = stateContexts.get(request.actor);
         if (lifecyclePreparation.actor !== request.actor || !context) {
@@ -231,6 +231,7 @@ async function receive(request: SqliteWorkerRequest): Promise<void> {
           actorId: `${request.actor}:${request.id}`,
           databasePath: preparation.databasePath,
           deadlineNs: preparation.deadlineNs,
+          probeContention,
           runtime:
             request.type === "close"
               ? { ...context.coordinatorRuntime, keepAlive: false }
@@ -270,7 +271,10 @@ async function receive(request: SqliteWorkerRequest): Promise<void> {
       }
     };
     const executeCommand = async (command: unknown) => {
-      const coordinator = await prepareLifecycle();
+      const coordinator = await prepareLifecycle(
+        isRecord(command) && command.type === "pluginState.compareUpdate" &&
+        String(actorPaths.get(request.actor)).includes("telegram-general-projection"),
+      );
       const backend = actors.get(request.actor);
       if (!backend) {
         throw new Error("SQLite worker actor is closed");
diff --git a/src/infra/sqlite-worker-lifecycle-preparation.ts b/src/infra/sqlite-worker-lifecycle-preparation.ts
index 3ddfd8f2..ded7da45 100644
--- a/src/infra/sqlite-worker-lifecycle-preparation.ts
+++ b/src/infra/sqlite-worker-lifecycle-preparation.ts
@@ -104,6 +104,7 @@ export async function acquireSqliteWorkerLifecycle(params: {
   deadlineNs: bigint;
   runtime: StateDatabaseCoordinatorRuntime;
   onUnsettled(): void;
+  probeContention?: boolean;
 }) {
   const controller = new AbortController();
   type Accepted = { admission?: MessagePort; stateLifecycle?: MessagePort };
@@ -141,6 +142,7 @@ export async function acquireSqliteWorkerLifecycle(params: {
     params.port.postMessage({ type }, []);
     return waiting.promise;
   };
+  let probePending = params.probeContention === true;
   let coordinator: ReturnType<typeof acquireStateDatabaseCoordinator> | undefined;
   let delegate: Awaited<ReturnType<typeof attachStateLifecycleDelegate>> | undefined;
   try {
@@ -156,6 +158,15 @@ export async function acquireSqliteWorkerLifecycle(params: {
       acquire: async () => {
         const checked = await check("check");
         controller.signal.throwIfAborted();
+        if (probePending) {
+          probePending = false;
+          console.error("CLOCK_PROBE", JSON.stringify({
+            remainingMs: Number(params.deadlineNs - process.hrtime.bigint()) / 1_000_000,
+            operation: "pluginState.compareUpdate",
+            injectedTransientContention: true,
+          }));
+          throw new StateDatabaseCoordinatorContentionError("state-lifecycle");
+        }
         if (checked.stateLifecycle) {
           delegate = await attachStateLifecycleDelegate(checked.stateLifecycle, {
             databasePath: params.databasePath,

Red: one failed, 25 skipped; exit 1; 36.068s command wall time. Green: one passed, 25 skipped; exit 0; 33.528s command wall time. Both instrumented production source hashes were identical across the two runs. The final shared fixture SHA-256 is 33a8a3b0b25dcda37d3076c5c1be59cbdbdeae62897b036cc8aff03ebe6c784f.

Provider: Blacksmith Testbox; diagnostic lease tbx_01m38e6ncmsvcqmdbfqvkd4rss, hydration run, stopped and independently verified completed. The workflow link identifies the environment; the reproduction result is recorded above.

Final stability proof: all runs used the exact failed CI merge plus the committed four-file fixture patch, with no fault injection. The full patch SHA-256 is dacce147107cafb83c249f1ba40cb133950f65c1d9d6c6863938c1dae0abb80f; downloaded evidence and local committed source match byte-for-byte.

  • 20/20 clean standalone runs of bot-message-dispatch.reply-targets.telegram-http.test.ts, 26/26 tests each.
  • 3/3 clean runs of the complete original packed shard, 1,257 tests across 80 files each. Each run preserves Codex → Telegram → voice-call group order, original file order, serial groups, and the original two-worker budget. The three independent invocations ran concurrently on the 16-CPU Linux Testbox.
  • Preview sibling: 30/30. All five callers of the shared fixture were covered. Separate macOS progress-lifecycle cost run: 23/23.
  • The final changed-file gate passed, including formatting, extension-test types, type-aware lint, structural/dependency checks, and dead-code scans. Fresh independent review: no actionable P0–P2 findings.

Standalone file costs (pnpm test <file> --maxWorkers=1):

File Environment Tests Command wall time Current CI Vitest duration
reply-targets.telegram-http.test.ts Linux, unloaded first run 26 72.050s 55.85s
preview.telegram-http.test.ts Linux 30 72.539s 68.40s
progress-lifecycle.telegram-http.test.ts macOS 23 124.783s 44.80s

Complete original-shard command wall times: 632.995s, 637.282s, 642.002s. These are shared-shard measurements, not individual-test costs. No permanent tests or CI invocations were added.

Provider: Blacksmith Testbox; final stability lease tbx_01m38ffnyp0kga6975rq0dnqxg, hydration run, stopped after downloading and verifying the evidence. The linked Actions workflow identifies the environment, not the locally captured command result.

Tooling corrections and scope

The first repetition attempt was interrupted after review found nested timer reinstalls; it is excluded from the final 20/3 counts. Setup attempts that failed before tests (unsupported wrapper flag, shell quoting, linked-worktree metadata after Testbox sync, and differing abbreviated Git hashes) are not product failures or passing test runs. Final proof uses an independent checkout, exact full source hashes, and a full-index patch. A local check was restarted after verifying and preserving a stale task-owned build lock left by the interrupted pass; the final selected gate passed.

The existing registered-tool/Gateway/SQLite/HTTP-channel product-flow proof remains bound to cf4a3501c7539596c68a35ee27bbc2c5352209d4. This follow-up changes only four Telegram test/fixture files; production source is unchanged. It does not introduce a new external-provider or live Telegram claim. CI for the new commit completed green, including the separate iOS dead-code scan. No merge or auto-merge was requested.

Current-head CI confirms the repaired tests: reply-targets and progress-lifecycle passed all 26 and 23 cases; their packed job took 396s. Preview passed all 30 cases; its packed job took 455s. These job totals include unrelated files. The formerly failing General-topic case passed in 1.875s. Final GitHub rollup: no pending or failed checks.

@joshavant

Copy link
Copy Markdown
Collaborator Author

@clawsweeper re-review

Please review current head ccab80e3884af5bf906724bffe8d9472a2cb2643 using the updated PR body and linked evidence. The only follow-up since the reviewed product commit is the Telegram HTTP fixture clock repair: preserve native hrtime for real SQLite-worker admission deadlines and remove five redundant timer reinstalls. Production code, assertions, timeouts, and retry limits are unchanged.

The updated evidence includes a controlled red/green reproduction of the original CI error under one transient coordinator conflict, 20 clean standalone runs, three complete original packed-shard runs (1,257 tests each), every fixture sibling, source hashes, measured cost, and a clean independent review. The earlier product-flow proof remains explicitly bound to cf4a350 with unchanged production source. Setup failures and the limits of the injected-contention proof are recorded.

Please assess Overall readiness, Proof confidence, and Patch quality from this evidence, including proof confidence despite the maintainer exemption. CI for the current head is still running; no pending check is claimed as passed.

Review only. Keep this PR open and unmerged; do not enable autofix or auto-merge.

@clawsweeper

clawsweeper Bot commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot removed the merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. label Sep 24, 2026
@joshavant

Copy link
Copy Markdown
Collaborator Author

Live Telegram Test Server validation

Validated head ccab80e3884af5bf906724bffe8d9472a2cb2643 with real Telegram Test Server transport, Convex-leased SUT bots, and independently authorized TDLib QA users. Both complete runs passed. No production, test, or ClawSweeper source changed during this validation.

  • Delayed requester delivery: a real user mentioned the bot in a run-owned forum topic. Registered sessions_send accepted asynchronous work, and the requesting turn ended before the child was released. The continuation invoked message with only action, channel, and message; it supplied no account, recipient, or thread. Exactly one native Telegram result arrived from the leased bot in the original chat/topic. The persisted registered-tool receipt matches that observed forum message.
  • Reset refusal: the supported sessions.reset RPC preserved the requester session ID and advanced its lifecycle revision while the child was held. After the child finished, the existing Gateway owner rejected this stale continuation. There were zero requester completion model calls and zero stale report messages through the complete 150-second recording.
  • Capability controls: child context and progress remained available; independent ordinary message sends before, during, and after the held work succeeded in both runs. A fresh requester turn after reset also sent successfully. Explicit sends to a distinct alternate forum topic were observed there.
  • Cleanup: both run-owned forums were confirmed deleted, all credential leases released, credential scratch removed, and owned observers stopped. Source/build fingerprints remained unchanged.

Scope: these runs prove actual Telegram named-account/chat/forum-topic interpretation and reset refusal. origin is a named account and the configured default, with one bot token owner; these runs do not compare two live bot accounts. The explicit alternate-topic send did not change the requester's saved route. Actual saved-account drift remains covered by the earlier two-account HTTP Gateway proof. The model was deterministic and local; no external model-provider behavior, production Telegram, universal exactly-once delivery, or final-transport revocation is claimed.

The source reply intentionally ends immediately after a confirmed final message-tool send (src/agents/embedded-agent-runner/run/message-tool-terminal.ts). The proof checks its Gateway lifecycle end and actual persisted send receipt, without requiring an extra inference round trip.

Aliased native delivery timelines and causal verdicts

Chat/user/bot/session/message identities are replaced by run-local labels or equality facts. All marker content is synthetic. The judge compared raw TDLib sender, chat, native messageTopicForum identity, unique message IDs, the actual Bot API receipt in the same forum, lifecycle ordering, owner refusal, and real tool results; it also rejected extra/wrapped result markers across the complete SUT event capture.

{
  "status": "passed",
  "mode": "route",
  "transport": "Telegram Test Server via Convex-leased bot and independent TDLib QA user",
  "sourceReceipt": {
    "confirmedSendAction": true,
    "exactSyntheticTextMatched": true,
    "nativeLeasedUserChatAndTopicMatched": true,
    "initialObservation": "pending-before-confirmation",
    "distinctPendingAndConfirmedIds": true
  },
  "account": {
    "name": "origin",
    "namedAccount": true,
    "configuredDefault": true,
    "competingLiveAccountExercised": false,
    "nativeSenderMatchedLeasedSut": true
  },
  "destination": {
    "chat": "run-forum",
    "requesterTopic": "requester",
    "controlTopic": "alternate",
    "nativeChatAndForumTopicsVerified": true,
    "uniqueFinalMessages": 1
  },
  "causality": {
    "registeredSessionsSendAccepted": true,
    "sourceTerminatedBeforeChildRelease": true,
    "existingChildContextPreserved": true,
    "childProgressPreserved": true,
    "ordinaryBeforeDuringAfterPassed": true,
    "savedRouteActuallyChanged": false
  },
  "provider": {
    "kind": "deterministic local Responses API",
    "requests": 27,
    "fixtureErrors": 0
  },
  "recordingComplete": true,
  "observedTimeline": [
    {
      "event": "source accepted",
      "actor": "qa-user",
      "chat": "run-forum",
      "topic": "requester",
      "elapsedMs": 286
    },
    {
      "event": "TG_PROOF_ORDINARY_BEFORE_ROUTE",
      "actor": "sut-bot",
      "chat": "run-forum",
      "topic": "requester",
      "elapsedMs": 4706,
      "uniqueMessages": 1
    },
    {
      "event": "TG_PROOF_SOURCE_DONE_ROUTE",
      "actor": "sut-bot",
      "chat": "run-forum",
      "topic": "requester",
      "elapsedMs": 5686,
      "uniqueMessages": 1
    },
    {
      "event": "TG_PROOF_ORDINARY_DURING_ROUTE",
      "actor": "sut-bot",
      "chat": "run-forum",
      "topic": "requester",
      "elapsedMs": 6679,
      "uniqueMessages": 1
    },
    {
      "event": "TG_PROOF_ALTERNATE_TOPIC_CONTROL",
      "actor": "sut-bot",
      "chat": "run-forum",
      "topic": "alternate",
      "elapsedMs": 7693,
      "uniqueMessages": 1
    },
    {
      "event": "TG_PROOF_CHILD_PROGRESS_ROUTE",
      "actor": "sut-bot",
      "chat": "run-forum",
      "topic": "requester",
      "elapsedMs": 8686,
      "uniqueMessages": 1
    },
    {
      "event": "TG_LIVE_ROUTE_REPORT_101",
      "actor": "sut-bot",
      "chat": "run-forum",
      "topic": "requester",
      "elapsedMs": 9680,
      "uniqueMessages": 1
    },
    {
      "event": "TG_PROOF_ORDINARY_AFTER_ROUTE",
      "actor": "sut-bot",
      "chat": "run-forum",
      "topic": "requester",
      "elapsedMs": 10680,
      "uniqueMessages": 1
    }
  ],
  "cleanup": {
    "leaseReleased": true,
    "credentialScratchRemoved": true,
    "runForumDeleted": true,
    "observerStopped": true,
    "sourceAndBuildStable": true
  }
}
{
  "status": "passed",
  "mode": "reset",
  "transport": "Telegram Test Server via Convex-leased bot and independent TDLib QA user",
  "sourceReceipt": {
    "confirmedSendAction": true,
    "exactSyntheticTextMatched": true,
    "nativeLeasedUserChatAndTopicMatched": true,
    "initialObservation": "pending-before-confirmation",
    "distinctPendingAndConfirmedIds": true
  },
  "account": {
    "name": "origin",
    "namedAccount": true,
    "configuredDefault": true,
    "competingLiveAccountExercised": false,
    "nativeSenderMatchedLeasedSut": true
  },
  "destination": {
    "chat": "run-forum",
    "requesterTopic": "requester",
    "controlTopic": "alternate",
    "nativeChatAndForumTopicsVerified": true,
    "uniqueFinalMessages": 0
  },
  "causality": {
    "registeredSessionsSendAccepted": true,
    "sourceTerminatedBeforeChildRelease": true,
    "existingChildContextPreserved": true,
    "childProgressPreserved": true,
    "ordinaryBeforeDuringAfterPassed": true,
    "savedRouteActuallyChanged": false
  },
  "reset": {
    "physicalSessionIdPreserved": true,
    "resetIssuedLifecycleRevision": true,
    "ownerRefusedStaleContinuation": true,
    "staleModelRequests": 0,
    "staleRecipientMessages": 0,
    "freshRequesterControlPassed": true
  },
  "provider": {
    "kind": "deterministic local Responses API",
    "requests": 24,
    "fixtureErrors": 0
  },
  "recordingComplete": true,
  "observedTimeline": [
    {
      "event": "source accepted",
      "actor": "qa-user",
      "chat": "run-forum",
      "topic": "requester",
      "elapsedMs": 380
    },
    {
      "event": "TG_PROOF_ORDINARY_BEFORE_RESET",
      "actor": "sut-bot",
      "chat": "run-forum",
      "topic": "requester",
      "elapsedMs": 4545,
      "uniqueMessages": 1
    },
    {
      "event": "TG_PROOF_SOURCE_DONE_RESET",
      "actor": "sut-bot",
      "chat": "run-forum",
      "topic": "requester",
      "elapsedMs": 5534,
      "uniqueMessages": 1
    },
    {
      "event": "TG_PROOF_ORDINARY_DURING_RESET",
      "actor": "sut-bot",
      "chat": "run-forum",
      "topic": "requester",
      "elapsedMs": 6534,
      "uniqueMessages": 1
    },
    {
      "event": "TG_PROOF_ALTERNATE_TOPIC_CONTROL",
      "actor": "sut-bot",
      "chat": "run-forum",
      "topic": "alternate",
      "elapsedMs": 7542,
      "uniqueMessages": 1
    },
    {
      "event": "TG_PROOF_CHILD_PROGRESS_RESET",
      "actor": "sut-bot",
      "chat": "run-forum",
      "topic": "requester",
      "elapsedMs": 8540,
      "uniqueMessages": 1
    },
    {
      "event": "TG_PROOF_ORDINARY_AFTER_RESET",
      "actor": "sut-bot",
      "chat": "run-forum",
      "topic": "requester",
      "elapsedMs": 9544,
      "uniqueMessages": 1
    }
  ],
  "cleanup": {
    "leaseReleased": true,
    "credentialScratchRemoved": true,
    "runForumDeleted": true,
    "observerStopped": true,
    "sourceAndBuildStable": true
  }
}

Command-clock checkpoints (milliseconds from the scenario command start):

{
  "route": {
    "sourceEnded": 4641,
    "childReleased": 7148,
    "completionEnded": 9044,
    "commandCompleted": 10118
  },
  "reset": {
    "sourceEnded": 4293,
    "reset": 6057,
    "childReleased": 7055,
    "commandCompleted": 8961,
    "ownerDiagnosticIncludes": "changed while starting expected work"
  }
}
Source/build binding and reproducible drivers

The final runs used the same four driver files below, the repository's canonical runTelegramTestScenario lease/process/recorder owner, and that checkout's bound built runtime. The production tree is 76f5e852d19bfe7923f3155e9cfbbff575549d19 (cf4a3501c7539596c68a35ee27bbc2c5352209d4); the current head adds only the four already validated Telegram timer-fixture changes. The prior successful QA build receipt binds that production tree; fingerprints below were checked before/after both runs.

To reproduce, use the exact head with prepared dependencies/runtime and the canonical Telegram skill prerequisites. Supply the broker URL and CI secret privately through the configured credential owner. Place these files together in a private proof directory; replace /CHECKOUT in the wrapper with the actual checkout path. Run from that checkout: node /path/to/proof/run-live.mjs route 05 and node /path/to/proof/run-live.mjs reset 01. The wrapper chooses unused explicit ports, prepares a leased run-owned forum, and owns teardown. Its retained build-receipt assertion refers to ../build-qa-v10.json, reproduced immediately below. Host paths are the only redaction in executable drivers; original private byte hashes and the public rendered hashes are recorded separately.

Build receipt:

{
  "command": [
    "node",
    "--import",
    "./scripts/tsx.mjs",
    "scripts/build-all.mts",
    "qaRuntime"
  ],
  "exitCode": 0,
  "wallSeconds": 69.49250341695733,
  "candidateTree": "76f5e852d19bfe7923f3155e9cfbbff575549d19",
  "indexStable": true
}

Binding:

{
  "drivers": {
    "run-live.mjs": "02b4800fb511da7dc0a03495992759a26c95645f0f17771f8b2cce0aab28773f",
    "forum-fixture.py": "a58e09c68df97bd020516e3be087f0804cbab9b938deb72ede085cd506c90718",
    "telegram-proof-model.mjs": "cd05988eec614707c73fab92535756db708ff9a2072b9f66b20da4ef030ec2af",
    "telegram-proof-command.mjs": "fd931a6c7c738b17ab95e19f23005f2f6afdeccc39887622e07fc4723392fa95"
  },
  "head": "ccab80e3884af5bf906724bffe8d9472a2cb2643",
  "sourcePatch": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
  "build": {
    "dist/entry.js": "b86588625b506d22cf3f446015bd041e234089a27519d395880cfd0f50f225cb",
    "dist/build-info.json": "06cf8f822aa81a32e4746c1023b5533fc79a2043de4d27fe411abe3e228e76cb",
    "dist/.buildstamp": "991c5c4da52e9285e18061e4f7bae1063ac8e7697acef7cd12af3dfc15daa052",
    "dist/plugin-sdk/qa-runtime.js": "daf5f3646150342fd379ed7fea194d8551743b7c336a5f103b2c091278af7802"
  },
  "productionCommit": "cf4a3501c7539596c68a35ee27bbc2c5352209d4",
  "productionTree": "76f5e852d19bfe7923f3155e9cfbbff575549d19",
  "postBuildChanges": [
    "extensions/telegram/src/bot-message-dispatch.preview.telegram-http.test.ts",
    "extensions/telegram/src/bot-message-dispatch.progress-lifecycle.telegram-http.test.ts",
    "extensions/telegram/src/bot-message-dispatch.reply-targets.telegram-http.test.ts",
    "extensions/telegram/src/bot-message-dispatch.telegram-http.test-support.ts"
  ],
  "buildReceipt": "../build-qa-v10.json",
  "node": "v24.21.0"
}

run-live.mjs

import assert from 'node:assert/strict';
import fs from 'node:fs';
import path from 'node:path';
import net from 'node:net';
import { createHash } from 'node:crypto';
import { execFileSync } from 'node:child_process';
import { fileURLToPath } from 'node:url';
import { runTelegramTestScenario, runCommand, sanitizeChildEnvironment } from '/CHECKOUT/.agents/skills/telegram-e2e-userbot/scripts/run-mock-sut-user-e2e.mjs';
import { checkTelegramTestCredential } from '/CHECKOUT/.agents/skills/telegram-e2e-userbot/scripts/telegram-test-doctor.mjs';
import { withTelegramRun, currentTelegramRun, runTelegramCli } from '/CHECKOUT/.agents/skills/telegram-e2e-userbot/scripts/telegram-run-scope.mjs';
import { parseScenario } from '/CHECKOUT/.agents/skills/telegram-e2e-userbot/scripts/scenario.mjs';

const root = process.cwd();
const artifact = path.dirname(fileURLToPath(import.meta.url));
const mode = process.argv[2];
assert(['route', 'reset'].includes(mode));
const out = path.join(artifact, `${mode}-${process.argv[3] || '01'}`);
fs.mkdirSync(out, { mode: 0o700 });
process.env.TELEGRAM_PROOF_DIR = out;
process.env.E2E_MOCK_SERVER_PATH = path.join(artifact, 'telegram-proof-model.mjs');
process.env.E2E_TELEGRAM_PROVIDER_API = 'openai-responses';
const write = (name, value) => fs.writeFileSync(path.join(out, name), JSON.stringify(value, null, 2) + '\n', { mode: 0o600 });
const hash = value => createHash('sha256').update(value).digest('hex');
const git = (...args) => execFileSync('git', args, { encoding: 'utf8' }).trim();
const build = () => Object.fromEntries(['dist/entry.js','dist/build-info.json','dist/.buildstamp','dist/plugin-sdk/qa-runtime.js'].map(p => [p,hash(fs.readFileSync(path.join(root,p)))]));
const baseline = { head: git('rev-parse','HEAD'), sourcePatch: hash(git('diff','HEAD','--binary')), build: build() };
assert.equal(baseline.head, 'ccab80e3884af5bf906724bffe8d9472a2cb2643');
assert.equal(git('status','--porcelain'), '');
const productionCommit = 'cf4a3501c7539596c68a35ee27bbc2c5352209d4';
const postBuildChanges = git('diff','--name-only',productionCommit,'HEAD').split('\n');
assert(postBuildChanges.length === 4 && postBuildChanges.every(p => p.startsWith('extensions/telegram/src/bot-message-dispatch.') && /test/.test(p)));
assert.equal(git('rev-parse', productionCommit+'^{tree}'), JSON.parse(fs.readFileSync(path.join(artifact,'../build-qa-v10.json'))).candidateTree);
for (const file of ['run-live.mjs','forum-fixture.py','telegram-proof-model.mjs','telegram-proof-command.mjs']) fs.copyFileSync(path.join(artifact,file),path.join(out,file));
write('binding.json', { drivers: Object.fromEntries(['run-live.mjs','forum-fixture.py','telegram-proof-model.mjs','telegram-proof-command.mjs'].map(p=>[p,hash(fs.readFileSync(path.join(artifact,p)))])), ...baseline, productionCommit, productionTree: git('rev-parse',productionCommit+'^{tree}'), postBuildChanges, buildReceipt:'../build-qa-v10.json', node:process.version });
const unusedPort = async () => {
  const s = net.createServer(); await new Promise((r,j)=>{s.once('error',j); s.listen(0,'127.0.0.1',r);});
  const p=s.address().port; await new Promise(r=>s.close(r)); return p;
};
const gatewayPort = await unusedPort();
const mockPort = await unusedPort();
assert.notEqual(gatewayPort,mockPort);
const args = { text:'', textProvided:false, photos:[], caption:'', expect:[], expectPassed:false, timeoutMs:150000, gatewayPort,mockPort,backend:'mock',anySutReply:false,output:path.join(out,'summary.json'),record:path.join(out,'events.ndjson'),chat:'',dm:false,preSend:[],scenarioPath:'',scenario:null,sourceGateway:false };
let credentialRoot, fixtureCleanup, leaseReleased=false, readiness;
async function checkCredential(credential) {
  const scope=currentTelegramRun();
  credentialRoot=credential.stateRoot;
  const baseRelease=credential.release;
  let releasing;
  const fixture = async (operation) => {
    credential.assertLeaseHealthy();
    const resultPath=path.join(out,`fixture-${operation}.json`);
    const result=await runCommand('uv',['run',path.join(artifact,'forum-fixture.py'),operation,'--driver',path.join(root,'.agents/skills/telegram-e2e-userbot/scripts/user-driver.py'),'--output',resultPath], {cwd:root,env:{...sanitizeChildEnvironment(),...credential.driverEnv},timeoutMs:60000});
    if(result.status!==0 || result.timedOut) throw new Error(`Forum ${operation} failed: ${result.stderr || result.stdout}`);
    return JSON.parse(fs.readFileSync(resultPath,'utf8'));
  };
  credential.release=()=> releasing ??= (async()=>{
    fixtureCleanup=await withTelegramRun(()=>fixture('cleanup'),{leaseHealth:{assertHealthy:credential.assertLeaseHealthy,whenUnhealthy:credential.whenLeaseUnhealthy}});
    write('fixture-cleanup.json',fixtureCleanup);
    assert.equal(fixtureCleanup.ok,true);
    await baseRelease(); leaseReleased=true;
  })();
  const prepared=await fixture('prepare');
  assert.equal(prepared.ok,true);
  write('fixture.json',prepared);
  credential.groupId=String(prepared.groupId);
  credential.driverEnv.TELEGRAM_USER_DRIVER_CHAT_ID=String(prepared.groupId);
  args.chat=String(prepared.groupId);
  const runtime={mode,sutBotId:String(credential.sutBotId),testerUserId:String(credential.testerUserId),accountId:'origin',chatId:String(prepared.groupId),topicId:prepared.requesterTopicId,alternateTopicId:prepared.otherTopicId};
  write('runtime.json',runtime);
  args.scenario=parseScenario({actions:[
    {type:'send',atMs:0,text:`@{sut} TG_PROOF_SOURCE:${mode}. Request the existing child's report and acknowledge acceptance.`,forumTopicId:runtime.topicId},
    {type:'command',atMs:0,argv:['node',path.join(artifact,'telegram-proof-command.mjs')],cwd:'repo',timeoutMs:130000},
  ]});
  write('scenario.json',args.scenario);
  const accountTokenFile=path.join(credential.stateRoot,'proof-sut-token');
  fs.writeFileSync(accountTokenFile,credential.sutToken,{mode:0o600});
  process.env.E2E_ROOT_CONFIG_PATCH=JSON.stringify({
    channels:{telegram:{tokenFile:null,defaultAccount:'origin',streaming:'off',accounts:{origin:{enabled:true,tokenFile:accountTokenFile}}}},
    messages:{queue:{mode:'followup',debounceMs:0}},
    plugins:{slots:{memory:'none'},entries:{'memory-core':{enabled:false}}},
    agents:{defaults:{heartbeat:{every:'0m'},skills:[],skipBootstrap:true,models:{'openai/gpt-5.5':{agentRuntime:{id:'openclaw'}}}},entries:{main:{tools:{profile:'messaging'}}}},
    tools:{profile:'messaging',codeMode:false,toolSearch:false,sessions:{visibility:'all'},agentToAgent:{enabled:true}}
  });
  readiness=await checkTelegramTestCredential({credential,chat:args.chat,requireForum:true});
  const {chatTarget,...safe}=readiness; write('readiness.json',{...safe,chatKind:chatTarget.kind});
  scope.assertActive();
}
await runTelegramCli(async(signal)=>{
  let error, result;
  try { result=await runTelegramTestScenario({args,repoRoot:root,signal,checkCredential}); write('runner.json',result); process.exitCode=result.exitCode; }
  catch(e) {error=e; write('failure.json',{message:e.message,causes:e.errors?.map(x=>x.message),credentialRoot}); process.exitCode=1;}
  finally {
    const end={head:git('rev-parse','HEAD'),sourcePatch:hash(git('diff','HEAD','--binary')),build:build()};
    const receipt={mode,leaseReleased,credentialScratchRemoved:credentialRoot ? !fs.existsSync(credentialRoot) : null,fixtureCleanupOk:fixtureCleanup?.ok===true,sourceAndBuildStable:JSON.stringify(baseline)===JSON.stringify(end),runnerExitCode:result?.exitCode ?? 1,error:error?.message};
    write('closeout.json',receipt); console.log(JSON.stringify(receipt));
    if(!receipt.sourceAndBuildStable || !receipt.leaseReleased || !receipt.fixtureCleanupOk) process.exitCode=1;
  }
});

telegram-proof-model.mjs

// Deterministic provider for the real Telegram / registered sessions_send proof.
import assert from 'node:assert/strict';
import fs from 'node:fs';
import path from 'node:path';
import { createServer } from 'node:http';

const proofDir = process.env.TELEGRAM_PROOF_DIR;
assert(proofDir, 'TELEGRAM_PROOF_DIR required');
const runtime = JSON.parse(fs.readFileSync(path.join(proofDir, 'runtime.json'), 'utf8'));
assert(['route', 'reset'].includes(runtime.mode));
const mode = runtime.mode;
const childKey = `agent:main:telegram-proof-child-${mode}`;
const report = `TG_LIVE_${mode.toUpperCase()}_REPORT_101`;
const facts = 'four boxes of seventeen and three boxes of eleven';
const state = { mode, seeded: false, released: false, childHeld: false, receipt: null, rows: [], errors: [] };
const counts = new Map();
const started = Date.now();
const elapsed = () => Date.now() - started;
let resolveSeeded;
let resolveReleased;
const seeded = new Promise((resolve) => { resolveSeeded = resolve; });
const released = new Promise((resolve) => { resolveReleased = resolve; });
const write = () => fs.writeFileSync(path.join(proofDir, 'model-facts.json'), JSON.stringify(state, null, 2) + '\n', { mode: 0o600 });
function sse(response, events) {
  response.writeHead(200, { 'content-type': 'text/event-stream', 'cache-control': 'no-cache' });
  for (const event of events) response.write(`event: ${event.type}\ndata: ${JSON.stringify(event)}\n\n`);
  response.end('data: [DONE]\n\n');
}
function text(response, value, n) {
  const item = { id: `msg_${n}`, type: 'message', role: 'assistant', status: 'completed', content: [{ type: 'output_text', text: value, annotations: [] }] };
  sse(response, [
    { type: 'response.output_item.added', output_index: 0, item: { ...item, status: 'in_progress', content: [] } },
    { type: 'response.content_part.added', item_id: item.id, output_index: 0, content_index: 0, part: { type: 'output_text', text: '', annotations: [] } },
    { type: 'response.output_text.delta', item_id: item.id, output_index: 0, content_index: 0, delta: value },
    { type: 'response.output_text.done', item_id: item.id, output_index: 0, content_index: 0, text: value },
    { type: 'response.content_part.done', item_id: item.id, output_index: 0, content_index: 0, part: item.content[0] },
    { type: 'response.output_item.done', output_index: 0, item },
    { type: 'response.completed', response: { id: `resp_${n}`, status: 'completed', output: [item], usage: { input_tokens: 1, output_tokens: 1, total_tokens: 2 } } },
  ]);
}
function tool(response, name, args, row) {
  const id = `proof_${mode}_${row.n}`;
  const item = { type: 'function_call', id: `fc_${id}`, call_id: id, name, arguments: JSON.stringify(args) };
  row.tool = { name, args };
  write();
  sse(response, [
    { type: 'response.output_item.added', output_index: 0, item: { ...item, arguments: '' } },
    { type: 'response.function_call_arguments.delta', item_id: item.id, output_index: 0, delta: item.arguments },
    { type: 'response.output_item.done', output_index: 0, item },
    { type: 'response.completed', response: { id: `resp_${id}`, status: 'completed', output: [item], usage: { input_tokens: 1, output_tokens: 1, total_tokens: 2 } } },
  ]);
}
function toolResult(input, name) {
  const call = input.findLast((item) => item.type === 'function_call' && item.name === name);
  const output = input.findLast((item) => item.type === 'function_call_output' && item.call_id === call?.call_id);
  assert(output, `${name} result missing`);
  let parsed;
  try { parsed = JSON.parse(output.output); } catch { parsed = { text: output.output }; }
  return parsed;
}
const server = createServer((request, response) => {
  void (async () => {
    if (request.url === '/proof/status' && request.method === 'GET') {
      response.writeHead(200, { 'content-type': 'application/json' }).end(JSON.stringify(state)); return;
    }
    if (request.url === '/proof/seeded' && request.method === 'POST') {
      state.seeded = true; state.seededAtMs = elapsed(); resolveSeeded(); write();
      response.writeHead(200, { 'content-type': 'application/json' }).end('{"ok":true}'); return;
    }
    if (request.url === '/proof/release' && request.method === 'POST') {
      assert(state.childHeld && !state.released, 'release requires held child');
      state.released = true; state.releasedAtMs = elapsed(); resolveReleased(); write();
      response.writeHead(200, { 'content-type': 'application/json' }).end('{"ok":true}'); return;
    }
    if (request.method === 'GET' && request.url === '/v1/models') {
      response.writeHead(200, { 'content-type': 'application/json' }).end(JSON.stringify({ data: [{ id: 'gpt-5.5', object: 'model' }] })); return;
    }
    assert.equal(request.method, 'POST');
    assert.equal(request.url, '/v1/responses');
    assert(state.rows.length < 40, 'provider request budget');
    const chunks = []; let bytes = 0;
    for await (const chunk of request) { bytes += chunk.length; assert(bytes < 2 * 1024 * 1024); chunks.push(chunk); }
    const body = JSON.parse(Buffer.concat(chunks).toString());
    const input = body.input ?? [];
    const developer = String(body.instructions ?? '') + JSON.stringify(input.filter((i) => i.role === 'developer' || i.role === 'system'));
    const lastUser = JSON.stringify(input.findLast((i) => i.role === 'user' && !JSON.stringify(i.content).includes('<<<BEGIN_OPENCLAW_INTERNAL_CONTEXT>>>')) ?? {});
    const full = JSON.stringify(input);
    const auxiliary = (body.tools ?? []).length === 0;
    const announce = developer.includes('Agent-to-agent announce step') || lastUser.includes('Agent-to-agent announce step');
    const completion = full.includes('sessions_send task completion: status=') || developer.includes('Agent-to-agent reply step') || developer.includes('Another session returned the result');
    const marker = lastUser.match(/TG_PROOF_(SEED|SOURCE|CHILD|ORDINARY|ROUTEUPDATE):([a-z-]+)/);
    const stage = auxiliary ? 'auxiliary' : announce ? 'announce' : completion ? 'completion' : marker?.[1] === 'ORDINARY' ? marker[2] : marker?.[1]?.toLowerCase();
    if (!stage) {
      fs.writeFileSync(path.join(proofDir, 'unknown-request.private.json'), JSON.stringify(body, null, 2), { mode: 0o600 });
      fs.writeFileSync(path.join(proofDir, 'unknown-request-shape.json'), JSON.stringify({ roles: input.map(i => i.role ?? i.type), instructionsPresent: Boolean(body.instructions), instructionsLength: String(body.instructions ?? '').length, knownMarkers: [...new Set(full.match(/TG_PROOF_[A-Z]+:[a-z-]+/g) ?? [])], excludedUserCount: input.filter(i => i.role === 'user' && JSON.stringify(i.content).includes('<<<BEGIN_OPENCLAW_INTERNAL_CONTEXT>>>')).length, lastUserLength: lastUser.length }, null, 2), { mode: 0o600 });
    }
    assert(stage, 'unrecognized provider stage');
    const count = (counts.get(stage) ?? 0) + 1; counts.set(stage, count);
    assert(count <= (stage === 'auxiliary' ? 20 : 2), `stage budget: ${stage}`);
    const names = (body.tools ?? []).map((t) => t.name ?? t.type).toSorted();
    const row = { n: state.rows.length + 1, atMs: elapsed(), stage, count, names, hasReport: full.includes(report), hasChildFacts: full.includes(facts) };
    state.rows.push(row);
    // Count real provider requests without publishing full prompts or user identities.
    fs.appendFileSync(process.env.MOCK_REQUEST_LOG, JSON.stringify(row) + '\n', { mode: 0o600 });
    write();
    const respondText = (value) => text(response, value, row.n);
    if (stage === 'auxiliary') { assert.equal(names.length, 0, 'auxiliary request has no tools'); respondText('Telegram routing proof'); return; }
    if (stage === 'announce') { respondText('ANNOUNCE_SKIP'); return; }
    if (stage === 'seed') { respondText('TG_PROOF_SEED_DONE'); return; }
    if (stage === 'source') {
      if (count === 1) {
        assert(names.includes('sessions_send')); await seeded;
        tool(response, 'sessions_send', { sessionKey: childKey, mode: 'followup', timeoutSeconds: 0, message: 'TG_PROOF_CHILD:report. Use the inventory facts already in your context, send a short progress update, and return its total.' }, row);
      } else {
        state.receipt = toolResult(input, 'sessions_send'); assert.equal(state.receipt.status, 'accepted'); write();
        respondText(`TG_PROOF_SOURCE_DONE_${mode.toUpperCase()}`);
      }
      return;
    }
    if (stage === 'child') {
      assert(row.hasChildFacts, 'receiver must preserve existing context');
      if (count === 1) {
        assert(names.includes('message')); state.childHeld = true; state.childHeldAtMs = elapsed(); write(); await released;
        tool(response, 'message', { action: 'send', channel: 'telegram', accountId: runtime.accountId, target: String(runtime.chatId), threadId: String(runtime.topicId), message: `TG_PROOF_CHILD_PROGRESS_${mode.toUpperCase()}` }, row);
      } else { row.toolResult = toolResult(input, 'message'); write(); respondText(report); }
      return;
    }
    if (stage === 'completion') {
      assert.equal(mode, 'route', 'reset requester must not consume stale completion');
      if (count === 1) {
        assert(row.hasReport); assert(names.includes('message'));
        tool(response, 'message', { action: 'send', channel: 'telegram', message: report }, row);
      } else { row.toolResult = toolResult(input, 'message'); write(); respondText('REPLY_SKIP'); }
      return;
    }
    if (stage === 'routeupdate') {
      if (count === 1) {
        assert(names.includes('message'));
        tool(response, 'message', { action: 'send', channel: 'telegram', accountId: runtime.accountId, target: String(runtime.chatId), threadId: String(runtime.alternateTopicId), message: 'TG_PROOF_ALTERNATE_TOPIC_CONTROL' }, row);
      } else { row.toolResult = toolResult(input, 'message'); write(); respondText('TG_PROOF_ROUTE_UPDATE_DONE'); }
      return;
    }
    assert(['before', 'during', 'after'].includes(stage), 'ordinary stage');
    if (count === 1) {
      assert(names.includes('message'));
      tool(response, 'message', { action: 'send', channel: 'telegram', accountId: runtime.accountId, target: String(runtime.chatId), threadId: String(runtime.topicId), message: `TG_PROOF_ORDINARY_${stage.toUpperCase()}_${mode.toUpperCase()}` }, row);
    } else { row.toolResult = toolResult(input, 'message'); write(); respondText(`TG_PROOF_${stage.toUpperCase()}_DONE`); }
  })().catch((error) => {
    state.errors.push(String(error)); write();
    if (!response.headersSent) response.writeHead(500, { 'content-type': 'application/json' });
    response.end(JSON.stringify({ error: 'Deterministic proof fixture failed; inspect private model-facts.json.' }));
  });
});
server.listen(Number(process.env.MOCK_PORT), '127.0.0.1', () => console.log('mock-openai listening'));
for (const signal of ['SIGTERM', 'SIGINT']) process.once(signal, () => { resolveSeeded(); resolveReleased(); server.closeAllConnections(); server.close(() => process.exit(0)); });

telegram-proof-command.mjs

// Scenario command: controls real Gateway RPC work while TDLib records Telegram.
import assert from 'node:assert/strict';
import fs from 'node:fs/promises';
import path from 'node:path';
import { pathToFileURL } from 'node:url';
import { randomUUID } from 'node:crypto';

const proofDir = process.env.TELEGRAM_PROOF_DIR;
assert(proofDir, 'TELEGRAM_PROOF_DIR required');
const runtime = JSON.parse(await fs.readFile(path.join(proofDir, 'runtime.json'), 'utf8'));
const cfg = JSON.parse(await fs.readFile(process.env.OPENCLAW_CONFIG_PATH, 'utf8'));
const { GatewayClient } = await import(pathToFileURL(path.join(process.cwd(), 'dist/plugin-sdk/gateway-runtime.js')).href);
const mode = runtime.mode;
const childKey = `agent:main:telegram-proof-child-${mode}`;
const independentKey = `agent:main:telegram-proof-ordinary-${mode}`;
const requesterKey = runtime.requesterSessionKey ?? `agent:main:telegram:group:${runtime.chatId}:topic:${runtime.topicId}`;
const modelOrigin = new URL(cfg.models.providers.openai.baseUrl).origin;
const start = Date.now();
const elapsed = () => Date.now() - start;
const evidence = { mode, status: 'running', events: [], controls: {}, requesterKey, scope: 'Real Telegram inbound and registered sessions_send; Gateway RPC supplies child seed, independent controls, and same-ID reset. Deterministic local provider; no live model-provider claim.' };
let observer;
async function save() { await fs.writeFile(path.join(proofDir, 'command-evidence.json'), JSON.stringify(evidence, null, 2) + '\n', { mode: 0o600 }); }
async function control(endpoint, method = 'GET') {
  const response = await fetch(`${modelOrigin}/proof/${endpoint}`, { method, signal: AbortSignal.timeout(5000) });
  assert(response.ok, `provider control ${endpoint}: ${response.status}`);
  const value = await response.json();
  if (value.errors?.length) throw new Error(`Provider fixture: ${value.errors.join('; ')}`);
  return value;
}
async function until(label, check, timeoutMs = 90000) {
  const deadline = Date.now() + timeoutMs;
  do {
    const result = await check(); if (result) return result;
    await new Promise((resolve) => setTimeout(resolve, 100));
  } while (Date.now() < deadline);
  throw new Error(`${label} timed out`);
}
async function runAgent(sessionKey, message, extra = {}) {
  const result = await observer.request('agent', { agentId: 'main', sessionKey, message, deliver: false, idempotencyKey: randomUUID(), ...extra });
  assert(result.runId, 'RPC agent acceptance runId');
  const terminal = await observer.request('agent.wait', { runId: result.runId, timeoutMs: 90000 });
  assert.equal(terminal.status, 'ok', 'RPC agent terminal success');
  return { runId: result.runId, terminal, atMs: elapsed() };
}
async function getRequester() {
  const result = await observer.request('sessions.describe', { key: requesterKey, agentId: 'main' });
  assert(result.session?.sessionId, 'requester identity');
  return result.session;
}
async function listRequester() {
  const result = await observer.request('sessions.list', { agentId: 'main', includeGlobal: true, includeUnknown: true, limit: 100 });
  const session = result.sessions.find((s) => s.key === requesterKey);
  assert(session, 'requester list row'); return session;
}
try {
  await new Promise((resolve, reject) => {
    observer = new GatewayClient({
      url: `ws://127.0.0.1:${cfg.gateway.port}`, deviceIdentity: null, clientName: 'gateway-client', mode: 'backend', scopes: ['operator.admin'],
      onHelloOk: resolve, onConnectError: reject,
      onEvent: (event) => {
        const p = event.payload;
        if (event.event === 'agent' && p?.stream === 'lifecycle') evidence.events.push({ runId: p.runId, sessionKey: p.sessionKey, phase: p.data?.phase, atMs: elapsed() });
      },
    }); observer.start();
  });
  for (const key of [requesterKey, childKey, independentKey]) await observer.request('sessions.messages.subscribe', { key, agentId: 'main' });
  evidence.seed = await runAgent(childKey, 'TG_PROOF_SEED:inventory. The inventory is four boxes of seventeen and three boxes of eleven.');
  evidence.controls.before = await runAgent(independentKey, 'TG_PROOF_ORDINARY:before. Send the progress control.');
  await control('seeded', 'POST');
  const accepted = await until('accepted source and held child', async () => {
    const state = await control('status'); return state.receipt?.status === 'accepted' && state.childHeld ? state : undefined;
  });
  evidence.receipt = accepted.receipt;
  assert.equal(evidence.receipt.sessionKey, childKey);
  evidence.sourceTerminal = await until('source lifecycle terminal', async () => {
    await control('status');
    return evidence.events.find((event) => event.sessionKey === requesterKey && event.phase === 'end');
  });
  evidence.requesterBefore = await getRequester();
  evidence.savedRouteBefore = (await listRequester()).deliveryContext;
  assert.equal(evidence.savedRouteBefore?.accountId, runtime.accountId, 'actual nondefault originating account');
  assert.equal(String(evidence.savedRouteBefore?.threadId), String(runtime.topicId), 'actual originating topic');
  evidence.controls.during = await runAgent(independentKey, 'TG_PROOF_ORDINARY:during. Send the unrelated-work control while child is held.');
  if (mode === 'reset') {
    const before = evidence.requesterBefore;
    const reset = await observer.request('sessions.reset', { key: requesterKey, agentId: 'main', expectedSessionId: before.sessionId });
    assert.equal(reset.ok, true); assert.equal(reset.key, requesterKey);
    assert.equal(reset.entry?.sessionId, before.sessionId, 'same physical session ID');
    assert(reset.entry.lifecycleRevision, 'reset revision');
    assert.notEqual(reset.entry.lifecycleRevision, before.lifecycleRevision);
    evidence.reset = { sameSessionId: true, previousRevision: before.lifecycleRevision ?? null, nextRevision: reset.entry.lifecycleRevision, atMs: elapsed() };
    evidence.controls.freshRequester = await runAgent(requesterKey, 'TG_PROOF_ROUTEUPDATE:reset. Send an alternate-topic control after reset.', { channel: 'telegram', accountId: runtime.accountId, to: String(runtime.chatId), threadId: String(runtime.alternateTopicId) });
  } else {
    evidence.routeUpdate = await runAgent(requesterKey, 'TG_PROOF_ROUTEUPDATE:route. Send the explicit alternate-topic control.', { channel: 'telegram', accountId: runtime.accountId, to: String(runtime.chatId), threadId: String(runtime.alternateTopicId) });
  }
  evidence.savedRouteAtRelease = (await listRequester()).deliveryContext;
  evidence.savedRouteActuallyChanged = JSON.stringify(evidence.savedRouteBefore) !== JSON.stringify(evidence.savedRouteAtRelease);
  evidence.childReleaseAtMs = elapsed();
  await control('release', 'POST');
  const terminal = await observer.request('agent.wait', { runId: evidence.receipt.runId, timeoutMs: 90000 });
  assert.equal(terminal.status, 'ok', 'child completed after source and controls');
  evidence.childTerminal = terminal;
  if (mode === 'reset') {
    evidence.resetRefusal = await until('stale requester refusal', async () => {
      await control('status');
      const log = await fs.readFile(cfg.logging.file, 'utf8');
      return log.split('\n').find((line) => line.includes('sessions_send announce flow failed') && line.includes(evidence.receipt.runId) && line.includes(requesterKey) && (line.includes('changed before expected work could start') || line.includes('changed while starting expected work')));
    }, 15000);
  } else {
    evidence.completionTerminal = await until('requester completion terminal', async () => {
      const state = await control('status');
      if (!state.rows.some((row) => row.stage === 'completion' && row.count === 1)) return undefined;
      return evidence.events.find((event) => event.sessionKey === requesterKey && event.phase === 'end' && event.atMs >= evidence.childReleaseAtMs);
    });
    // A confirmed message_tool_only source reply terminates in afterToolCall.
    // Its authoritative receipt is in chat history, without another model turn.
    const completionRow = (await control('status')).rows.find((row) => row.stage === 'completion' && row.count === 1);
    const expectedArgs = { action: 'send', channel: 'telegram', message: 'TG_LIVE_ROUTE_REPORT_101' };
    const providerCallId = `proof_${mode}_${completionRow.n}`;
    const transcriptCallId = `${providerCallId}|fc_${providerCallId}`;
    const completionHistory = await until('persisted final message tool receipt', async () => {
      await control('status');
      const history = await observer.request('chat.history', { sessionKey: requesterKey, agentId: 'main', limit: 100, maxChars: 100000 });
      assert.equal(history.sessionKey, requesterKey);
      const calls = history.messages.flatMap((message) => message.role === 'assistant' && Array.isArray(message.content)
        ? message.content.filter((item) => item.type === 'toolCall' && item.name === 'message' && item.arguments?.message === expectedArgs.message)
        : []);
      if (calls.length === 0) return undefined;
      assert.equal(calls.length, 1, 'one final registered message call');
      assert.equal(calls[0].id, transcriptCallId, 'persisted call identity matches provider-issued final tool call');
      assert.deepEqual(calls[0].arguments, expectedArgs, 'persisted final call omits routing defaults');
      const results = history.messages.filter((message) => message.role === 'toolResult' && message.toolCallId === transcriptCallId);
      if (results.length === 0) return undefined;
      assert.equal(results.length, 1); assert.equal(results[0].toolName, 'message'); assert.equal(results[0].isError, false);
      const blocks = results[0].content.filter((item) => item.type === 'text');
      assert.equal(blocks.length, 1);
      const result = JSON.parse(blocks[0].text);
      assert.equal(result.ok, true); assert.equal(String(result.chatId), String(runtime.chatId));
      assert.equal(String(result.receipt?.threadId), String(runtime.topicId));
      assert(result.messageId, 'final Bot API send receipt identity');
      return { history, call: calls[0], result };
    }, 15000);
    await fs.writeFile(path.join(proofDir, 'requester-history.private.json'), JSON.stringify(completionHistory.history, null, 2) + '\n', { mode: 0o600 });
    evidence.completionToolCall = completionHistory.call;
    evidence.completionToolResult = completionHistory.result;
  }
  evidence.controls.after = await runAgent(independentKey, 'TG_PROOF_ORDINARY:after. Send the unrelated-work control after completion.');
  const final = await control('status');
  assert.equal(final.rows.filter((row) => row.stage === 'completion').length, mode === 'route' ? 1 : 0);
  for (const stage of ['child', 'before', 'during', 'after', 'routeupdate']) {
    const result = final.rows.find((row) => row.stage === stage && row.count === 2)?.toolResult;
    assert(result, `actual ${stage} message result`);
    assert(!result.error && !result.isError, `${stage} message tool failed`);
    evidence.controls[`${stage}ToolResult`] = result;
  }
  evidence.requesterAfter = await getRequester();
  evidence.modelRows = final.rows;
  evidence.status = 'passed';
} catch (error) {
  evidence.status = 'failed'; evidence.error = String(error); process.exitCode = 1;
} finally {
  try { await observer?.stopAndWait(); evidence.observerCleanup = 'stopped'; } catch (error) { evidence.status = 'failed'; evidence.cleanupError = String(error); process.exitCode = 1; }
  evidence.elapsedMs = elapsed(); await save();
  console.log(JSON.stringify({ status: evidence.status, mode, observerCleanup: evidence.observerCleanup }));
}

forum-fixture.py

#!/usr/bin/env python3
"""Run-owned Test Server forum fixture; invoke only under the live lease owner."""

import argparse
import importlib.util
import json
import os
from pathlib import Path
import secrets
import sys
import time


PURPOSE = "sessions-send-routing-telegram-v13"
MANIFEST_NAME = "owned-routing-forum.json"


def persist(path, value, *, exclusive=False):
    payload = (json.dumps(value, indent=2, sort_keys=True) + "\n").encode()
    if exclusive:
        fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
        with os.fdopen(fd, "wb") as handle:
            handle.write(payload)
            handle.flush()
            os.fsync(handle.fileno())
        return
    temporary = path.with_name(f".{path.name}.{secrets.token_hex(6)}")
    fd = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
    with os.fdopen(fd, "wb") as handle:
        handle.write(payload)
        handle.flush()
        os.fsync(handle.fileno())
    os.replace(temporary, path)


def load_driver(path):
    spec = importlib.util.spec_from_file_location("routing_telegram_user_driver", path)
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    return module


def identity(module, driver):
    actual = module.group_identity(driver)
    bot = module.telegram_bot(driver.bot_config["sutBotToken"], "getMe", test_dc=True)
    if str(bot["id"]) != actual["sutBotId"] or bot.get("is_bot") is not True:
        raise module.DriverError("The Test Bot API identity does not match this lease.")
    if bot.get("username", "").lower() != actual["sutUsername"].lower():
        raise module.DriverError("The Test Bot API username does not match this lease.")
    return actual


def require_group(module, driver, record, *, forum=False):
    chat = driver.client.request({"@type": "getChat", "chat_id": int(record["groupId"])})
    kind = chat.get("type") or {}
    if (
        str(chat.get("id")) != record["groupId"]
        or chat.get("title") != record["title"]
        or kind.get("@type") != "chatTypeSupergroup"
        or kind.get("is_channel") is not False
        or str(kind.get("supergroup_id")) != record["supergroupId"]
    ):
        raise module.DriverError("The current group does not match the run-owned fixture.")
    group = driver.client.request({
        "@type": "getSupergroup", "supergroup_id": int(record["supergroupId"]),
    })
    if group.get("is_channel") is not False or (forum and group.get("is_forum") is not True):
        raise module.DriverError("Telegram did not confirm the requested nonchannel forum.")
    member = driver.client.request({
        "@type": "getChatMember", "chat_id": int(record["groupId"]),
        "member_id": {"@type": "messageSenderUser", "user_id": int(record["testerUserId"])},
    })
    status = member.get("status") or {}
    if status.get("@type") != "chatMemberStatusCreator" or status.get("is_member") is not True:
        raise module.DriverError("The leased QA user is not the current fixture creator/member.")
    return {"chatType": kind, "isChannel": group["is_channel"], "isForum": group.get("is_forum"), "creatorStatus": status}


def prepare(module, driver, manifest):
    if manifest.exists():
        raise module.DriverError("Existing fixture record requires reconciliation; creation was not retried.")
    owner = identity(module, driver)
    bot_chat = driver.client.request({"@type": "searchPublicChat", "username": owner["sutUsername"]})
    if bot_chat.get("type") != {"@type": "chatTypePrivate", "user_id": int(owner["sutBotId"])}:
        raise module.DriverError("The bot chat does not match the leased SUT.")
    record = {
        "purpose": PURPOSE, "version": 1, **owner, "testDc": True,
        "status": "creating", "createdAtUnixMs": int(time.time() * 1000),
        "title": f"OpenClaw routing QA {secrets.token_hex(8)}",
        "topics": {"requester": {"title": "Requester"}, "other": {"title": "Other"}},
    }
    # This durable intent distinguishes an uncertain creation from no creation.
    persist(manifest, record, exclusive=True)
    try:
        created = driver.client.request({
            "@type": "createNewSupergroupChat", "title": record["title"],
            "is_forum": False, "is_channel": False, "description": PURPOSE,
            "location": None, "message_auto_delete_time": 0, "for_import": False,
        })
        record["creation"] = created
        if created.get("id") is not None:
            record["groupId"] = str(created["id"])
        if (created.get("type") or {}).get("supergroup_id") is not None:
            record["supergroupId"] = str(created["type"]["supergroup_id"])
        record["status"] = "created-response"
        persist(manifest, record)
        if "groupId" not in record or "supergroupId" not in record:
            raise module.DriverError("Creation returned no confirmed supergroup identity; preserve recovery state.")
        record["verification"] = require_group(module, driver, record)
        record["status"] = "enabling-forum"
        persist(manifest, record)
        enabled = driver.client.request({
            "@type": "toggleSupergroupIsForum", "supergroup_id": int(record["supergroupId"]),
            "is_forum": True, "has_forum_tabs": True,
        })
        if enabled.get("@type") != "ok":
            raise module.DriverError("Telegram did not confirm enabling the forum.")
        record["verification"] = require_group(module, driver, record, forum=True)
        record["status"] = "adding-bot"
        persist(manifest, record)
        addition = driver.client.request({
            "@type": "addChatMember", "chat_id": int(record["groupId"]),
            "user_id": int(owner["sutBotId"]), "forward_limit": 0,
        })
        record["addition"] = addition
        persist(manifest, record)
        if addition.get("failed_to_add_members"):
            raise module.DriverError("Telegram could not add the leased SUT to its run-owned forum.")
        bot_member = driver.client.request({
            "@type": "getChatMember", "chat_id": int(record["groupId"]),
            "member_id": {"@type": "messageSenderUser", "user_id": int(owner["sutBotId"])},
        })
        if (bot_member.get("status") or {}).get("@type") not in {"chatMemberStatusMember", "chatMemberStatusAdministrator"}:
            raise module.DriverError("Telegram did not confirm SUT forum membership.")
        record["botMembership"] = bot_member
        for role, topic in record["topics"].items():
            record["status"] = f"creating-{role}-topic"
            persist(manifest, record)
            created_topic = driver.client.request({
                "@type": "createForumTopic", "chat_id": int(record["groupId"]),
                "name": topic["title"], "is_name_implicit": False,
                "icon": {"@type": "forumTopicIcon", "color": 0x6FB9F0, "custom_emoji_id": 0},
            })
            topic["creation"] = created_topic
            topic["id"] = created_topic.get("forum_topic_id")
            persist(manifest, record)
            if type(topic["id"]) is not int or topic["id"] <= 0 or created_topic.get("name") != topic["title"]:
                raise module.DriverError("Telegram did not return the requested topic identity.")
        if record["topics"]["requester"]["id"] == record["topics"]["other"]["id"]:
            raise module.DriverError("Telegram returned the same identity for distinct topics.")
        record.update(status="ready", ok=True)
        persist(manifest, record)
        return {
            "ok": True, "status": "ready", "groupId": record["groupId"],
            "requesterTopicId": record["topics"]["requester"]["id"],
            "otherTopicId": record["topics"]["other"]["id"],
        }
    except Exception as error:
        record["failedStep"] = record["status"]
        record["status"] = "setup-failed" if record.get("groupId") else "creation-unconfirmed"
        record["error"] = str(error)
        persist(manifest, record)
        raise


def cleanup(module, driver, manifest):
    if not manifest.exists():
        return {"ok": True, "status": "not-created"}
    record = module.read_json(manifest)
    owner = identity(module, driver)
    if record.get("purpose") != PURPOSE or record.get("testDc") is not True or any(
        record.get(key) != owner[key] for key in ("testerUserId", "sutBotId")
    ):
        raise module.DriverError("The fixture record does not belong to the current leased identities.")
    if record.get("status") == "deleted" and (record.get("deletion") or {}).get("@type") == "ok":
        return {"ok": True, "status": "deleted"}
    if not record.get("groupId") or not record.get("supergroupId"):
        raise module.DriverError("Creation is unconfirmed; preserve the lease and reconcile its intent.")
    if record.get("status") in {"deleting", "deletion-unconfirmed", "cleanup-failed"}:
        raise module.DriverError("A prior cleanup requires reconciliation; delete was not retried.")
    record["cleanupVerification"] = require_group(module, driver, record)
    record["status"] = "deleting"
    persist(manifest, record)
    try:
        deletion = driver.client.request({"@type": "deleteChat", "chat_id": int(record["groupId"])})
        record["deletion"] = deletion
        if deletion.get("@type") != "ok":
            raise module.DriverError("Telegram did not confirm deleting the owned fixture.")
        record.update(status="deleted", ok=True)
        persist(manifest, record)
        return {"ok": True, "status": "deleted"}
    except Exception as error:
        record.update(status="deletion-unconfirmed", error=str(error), ok=False)
        persist(manifest, record)
        raise


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("action", choices=("prepare", "cleanup"))
    parser.add_argument("--driver", required=True, type=Path)
    parser.add_argument("--output", required=True, type=Path)
    parser.add_argument("--timeout-ms", type=int, default=120000)
    args = parser.parse_args()
    if not os.environ.get("TELEGRAM_E2E_STATE_DIR") or not os.environ.get("TELEGRAM_USER_DRIVER_STATE_DIR"):
        raise RuntimeError("The canonical lease owner must supply both isolated state directories.")
    module = load_driver(args.driver)
    if not module.CONFIG_PATH.is_file() or not module.BOT_CREDENTIALS_PATH.is_file():
        raise RuntimeError("This leased runtime has no restored user/bot configuration.")
    config = module.read_json(module.CONFIG_PATH)
    bot_config = module.read_json(module.BOT_CREDENTIALS_PATH)
    if config.get("testDc") is not True or not config.get("testerUserId") or not bot_config.get("sutBotToken"):
        raise RuntimeError("This helper requires restored Test Server user and bot credentials.")
    explicit_library = module.env_or_config("TELEGRAM_USER_DRIVER_TDLIB_PATH", config, "tdlibPath")
    if explicit_library:
        library = Path(explicit_library).expanduser()
    else:
        entry = module.TDLIB_PREBUILT.get((module.platform.system().lower(), module.platform.machine().lower()))
        if not entry:
            raise RuntimeError("Prepare an explicit TDLib runtime before acquiring the lease.")
        _, library_name, digest = entry
        library = module.TDLIB_CACHE_ROOT / digest[:16] / "package" / library_name
    if not library.is_file():
        raise RuntimeError("Prepare TDLib before acquiring the lease; fixture setup will not download it.")
    os.environ["TELEGRAM_USER_DRIVER_TDLIB_PATH"] = str(library.resolve())
    # Never turn failed authorization into interactive owner-repair work.
    def no_prompt(_message):
        raise module.DriverError("The restored user authorization needs owner repair.")
    module.prompt_secret = no_prompt
    driver = module.UserDriver(config, bot_config)
    try:
        if not driver.authorize(argparse.Namespace(timeout_ms=args.timeout_ms), need_ready=False):
            raise module.DriverError("The restored QA user is not authorized.")
        manifest = module.STATE_DIR / MANIFEST_NAME
        result = prepare(module, driver, manifest) if args.action == "prepare" else cleanup(module, driver, manifest)
        persist(args.output, result)
        print(json.dumps({"ok": True, "action": args.action, "status": result["status"]}))
    finally:
        driver.client.destroy()


if __name__ == "__main__":
    try:
        main()
    except Exception as error:
        # Detailed TDLib failures stay in the lease-local recovery manifest.
        print(json.dumps({"ok": False, "errorType": type(error).__name__, "message": "Fixture operation failed; retain leased state and inspect its private manifest."}), file=sys.stderr)
        sys.exit(1)

Public rendered source hashes:

{
  "run-live.mjs": "6ce737b3fe9a0a1aedfdedce80edf3a2973713639c2ac8dac6830a2fc1b26516",
  "telegram-proof-model.mjs": "cd05988eec614707c73fab92535756db708ff9a2072b9f66b20da4ef030ec2af",
  "telegram-proof-command.mjs": "fd931a6c7c738b17ab95e19f23005f2f6afdeccc39887622e07fc4723392fa95",
  "forum-fixture.py": "a58e09c68df97bd020516e3be087f0804cbab9b938deb72ede085cd506c90718"
}
Fixture qualification attempts

Earlier attempts were retained as unsuccessful harness runs, not product regressions or passes. They exposed (1) interleaved zero-tool auxiliary requests being counted as proof turns, (2) a duplicate root/named bot token configuration that correctly prevented named-account polling, and (3) an incorrect expectation of a second model call after successful message-tool-only termination. The final fixture separates zero-tool requests, uses one account-specific token owner, and verifies the actual terminal/send-receipt contract. Every earlier lease was released, its credential scratch removed, and its run-owned forum deleted. No product assertions, timeout budgets, retries, or production code were relaxed to obtain the final results.

@joshavant

Copy link
Copy Markdown
Collaborator Author

@clawsweeper re-review

Please reassess the Telegram destination/reset proof requests on unchanged head ccab80e3884af5bf906724bffe8d9472a2cb2643 using the completed live Telegram Test Server evidence and updated PR body.

The canonical leased runner exercised real user inbound → registered sessions_send → delayed completion → native Telegram delivery, plus same-ID reset refusal. Raw TDLib destination and Bot API receipt checks, lifecycle ordering, ordinary/child/fresh-requester controls, complete 150-second recordings, source/build bindings, reproducible drivers, and confirmed cleanup are included. Model calls were deterministic/local. The live run uses one named account configured as default and does not change the saved route; the earlier real Gateway two-account HTTP proof separately covers saved-account drift. No production/test code or ClawSweeper source changed.

Review only. Leave the PR open and unmerged; do not enable auto-merge.

@clawsweeper

clawsweeper Bot commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@joshavant
joshavant merged commit e157b56 into main Sep 24, 2026
233 checks passed
@joshavant
joshavant deleted the fix/message-session-account-routing branch September 24, 2026 02:49
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 24, 2026
…nclaw#156802)

* fix: preserve requester routes for delayed session continuations

* fix: reject delayed requester replies after session reset

* test(telegram): preserve native SQLite admission deadlines
@roboclaw-bot roboclaw-bot mentioned this pull request Sep 24, 2026
2 of 8 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling app: web-ui App: web-ui channel: telegram Channel integration: telegram gateway Gateway runtime merge-risk: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. P1 High-priority user-facing bug, regression, or broken workflow. proof: sufficient ClawSweeper judged the real behavior proof convincing. proof: telegram-e2e This PR needs Telegram Test Server proof with the repository E2E skill. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. 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.

1 participant