Skip to content

refactor(sessions): address chats by ChatRef, fence writers by lease, and stop refusing on captured ids - #200191

Merged
obviyus merged 11 commits into
mainfrom
obviyus/identity-types-guard
Nov 16, 2026
Merged

obviyus merged 11 commits into
mainfrom
obviyus/identity-types-guard

Conversation

@obviyus

@obviyus obviyus commented Nov 16, 2026 •

Copy link
Copy Markdown
Collaborator

What Problem This Solves

Work was stopped by inference: a check captured an id that changes on its own (a transcript id, lifecycle revision, run id, generation or displayed leaf), and later treated "it changed" as "it was revoked". Users saw:

  • A message queued in Control UI during a turn was refused as "switched branches" once the turn ended. The sender's leaf was one entry behind the new reply, and a send without a session id needed an exact leaf match.
  • sessions_send to a task session was refused with "Task resume differs from the captured communication owner." after the task moved to a new run (exec wake, yield, follow-up) or was compacted.
  • A requester-wake failure notice for a lost subagent batch was pinned to the requester's old transcript and refused as session-rebound after a reset or compaction successor.
  • Deleting a chat left its queued outbound replies in the durable queue, so a chat recreated with the same key could receive them.
  • Every delivery, queue, wake and session-event API took a SessionDeliveryGeneration with a transcript id and revision, so any new caller could pin a chat to an id again.

Why This Change Was Made

Make the bad state hard to express and guard the rest:

  • ChatRef (src/sessions/chat-ref.ts) is the only durable chat address: agent id, store path and session key, branded. chatRef() copies only the address, so ids in rows queued by older builds never travel with it. Delivery, queue, wake, cron delivery, memory audience and session-event APIs take a ChatRef. SessionDeliveryGeneration and SessionGenerationFacts are deleted.
  • TranscriptLease (src/config/sessions/transcript-lease.ts) is the only way to hold one transcript. Live writers (cron root, fork, subagent control, restart resume, a scheduled occurrence) acquire it with a private pin. It refuses to serialise.
  • One prefix rule for sends: a send is admitted while the sender's leaf is on the active path; an empty view is a prefix of every path. A rewind, branch switch or reset away from the leaf still refuses it (feat(gateway): chat.send expectedLeafEntryId precondition keeps stale panes off switched branches #113073 holds). Deleted: the exact-match branch, activePathNavigationMoved and its reader, the send's own session-id fence, and the test-only relation reader. activePathRelation becomes onActivePath.
  • Task sends follow the chat: sessions_send continues the task's current run. The previousRunId / generation / childSessionId compares, the retained-task pins and the target-incarnation compare are deleted. It refuses only when the task ended or was cancelled, the chat was deleted, or another session controls the task.
  • Lost-run notice by key, and delete purges queued sends (a send that already started stays with its recovery owner).
  • Guard: check:session-identity-ratchet counts, per file outside src/config/sessions/, any ===/!== on a session id, run id, generation, lifecycle revision or leaf id, the expectedSessionId / expectedLifecycleRevision pin names, and refusal strings ("differs from the captured", "no longer active", "changed before", "was replaced"). Existing hits are listed in config/session-identity-allowlist.txt, which may only shrink.

Kept on purpose:

  • Typed Stop keeps its incarnation fence (an empty view must still be empty, and the session id must match), so a Stop never cancels work that started after it. It moves to a recorded stop cause in the next change.
  • Memory grants hold the incarnation they were minted in through a transcript lease: a reset revokes the grant, a compaction successor keeps it. This is the narrower authority and matches the memory audience's own tests.
  • Knowledge partitions, the deep-research job store and GitHub publication rows key on transcript ids in stored rows; changing them needs a data migration and is left for a separate decision.

Production code (src, extensions, without tests): +524 / −602.

User Impact

  • A message queued during a turn is sent when the turn ends.
  • A pane that still shows a branch another client switched away from is still refused, and the message is parked as not sent.
  • A send to a task session reaches its current run after wakes, yields and compaction; a send to a cancelled task is refused with a reason.
  • Deleting a chat drops its unsent queued replies.
  • Rows queued by older builds still deliver. A row queued by this build and replayed by an older build has no transcript id; the older build treats it as unavailable and retries it until its retry budget ends.

Evidence

Base = merge base edbc5bcea9b6, head = this PR.

Journey Tier Base Head
Control UI: queue a message during a held turn, release the turn (send carries only the displayed leaf) Control UI E2E, real Gateway, scripted provider (ui/src/e2e/chat-send-leaf-ancestor.real-gateway.e2e.test.ts) chat.send ok=false, message parked "Not sent" chat.send ok=true, reply "Flag mentioned."
Control UI: pane still shows Plan C, another client switches to the Plan B tip, pane sends same refused, no provider request refused, no provider request
Compaction successor while a background exec runs, then a next turn ocx src scratch Gateway, real Claude model exec wake lands in the successor transcript; next turn runs same
Queue an outbound reply, delete the chat, recreate the key ocx src scratch Gateway 1 queued reply still pending 0 pending
Reaction, then edit a later message ocx src scratch Gateway reaction still listed reaction still listed
Plant entry.sessionId === saved in a new file check:session-identity-ratchet — fails: src/sessions/chat-ref.ts: 1 > 0

The task-send fix is proven by unit tests only: a send to an owned task after its run id and generation advanced, with a stale resume binding, is delivered (fails on base), and a send after the task is killed is refused. Real-Gateway journeys with a real Claude model (spawn a task, then send after an exec wake, after compaction, after cancel, or while the task is busy so the send is held and released) did not reproduce the refusal on base: base delivered in each. The live refusal needs the in-process resume binding of a retained self-hold replay, which these journeys do not reach.

Gates: oxfmt, oxlint, pnpm tsgo:core, tsgo:ui, tsgo:scripts, pnpm check:test-types, and ocx test on the lease, session store, outbound queue, subagent registry, cron, memory audience, session events, chat send and Stop, sessions_send, restart resume and UI E2E inventory suites.

test/plugins/deep-research-routing.gateway.test.ts fails the same way on main (CI run 43939332007, job 133553190527); this PR does not touch it.

@clawsweeper

clawsweeper Bot commented Nov 16, 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 clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. labels Nov 16, 2026
@clawsweeper

clawsweeper Bot commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge.

What this changes

This PR separates durable chat addresses from live transcript leases, accepts sends from active ancestors, and purges deleted chats’ queued replies.

Example: A client queues “Also mention the new flag.” while “Draft the release note.” is running and sends only its displayed leaf.

  • Before: The completed reply advances the tip, and the queued message is parked as “Not sent.”
  • After: The displayed leaf remains an active ancestor, so the message receives “Flag mentioned.”

Review scores

Measure Result What it means
Overall readiness 🦪 silver shellfish (2/6) Useful direction and credible browser proof, with incomplete consumer migration and no demonstrated latest-stable upgrade for sessionGeneration in delivery_queue_entries.entry_json.
Proof confidence 🦪 silver shellfish (2/6) Real behavior proof is not required for maintainer- or bot-authored pull requests.
Patch quality 🦪 silver shellfish (2/6) 2 actionable review findings remain.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: Valid queued messages can be refused after normal transcript progress, deleted chats retain pending replies, and lost-run notices can target an obsolete transcript.
Reason: The maintainer-authored direction addresses concrete delivery failures and enforces the identity distinction already established on main.

Merge readiness

⛔ Blocked before merge - 3 items remain

Keep open: this maintainer-authored PR makes a useful session-identity cutover, but leaves consumer tests and UI test inventories inconsistent with its changes.

Priority: P2
Reviewed head: 25e4a072f6e2d34d9ee38c8308ce3d54772d4061

Before merge

  • Complete the lease API cutover in its test consumers (P2) - The shared mocked generation module now exports only prepareChatLease, but scheduled admission calls acquireTranscriptLease, which requires prepareLeaseFacts. In execution-context-memory-audience.test.ts that missing export is caught as failed admission, so otherwise valid occurrences produce undefined audiences; exact-head CI records this failure. Other consumers still assert the removed transcript fields or the previous empty-leaf behavior, including reset-followup-durable, restart media-binding, sessions-send admission, and Stop tests. Migrate the shared fake to support exact leases and update affected assertions to the explicitly chosen contracts, preserving independent rejection and authority coverage.
  • Complete ownership registration for the new browser test (P2) - The new file is registered in the real-Gateway and private-server lists, but test/vitest-ui-e2e-config.test.ts still omits it from its realGatewayFiles and serialGatewayFiles inventories. The private-server insertion also violates the sorted order compared by ci-ui-e2e-ownership.test-support.ts. Exact-head CI fails both execution-inventory and ownership checks on these differences. Register the file in the matching expected execution inventories and place the private-server entry in canonical order.
  • Add data-model compatibility proof - The review found that existing stored data may not work after upgrade. Show that existing data still loads and works with this change.

Findings

  • [P2] Complete the lease API cutover in its test consumers — src/plugins/memory-audience.test-support.ts:39-42
  • [P2] Complete ownership registration for the new browser test — test/vitest/vitest.ui-e2e.config.ts:58

Provenance

  • Requester-wake failure-notice transcript pin: original intent not found (unknown: Path history identifies requester settlement and restart work, but git blame could not resolve the changed base lines because a historical blob was unavailable.)

Tests

  • Missing end-to-end proof: Provide redacted Gateway output for a lost-run failure notice reaching the reset or compaction successor, plus a v2026.11.4 upgrade replay of existing outbound rows with settings and data intact.
Agent review details

How this fits together

Gateway admission validates interactive sends against the session store; background producers pass chat addresses through durable delivery, while live writers retain transcript-specific leases.

flowchart LR
  A[Interactive clients] --> B[Gateway send admission]
  B --> C[Session store and active path]
  D[Background producers] --> E[Durable outbound queue]
  E --> C
  C --> F[Transcript writes and channel delivery]
Loading

Technical review

Best possible solution:

Keep durable references keyed by ChatRef and live writers fenced by the existing lease owner, with a complete consumer cutover and verified persisted-queue upgrades.

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

Current-main source rejects active ancestors without sessionId, matching the supplied base screenshot and real-Gateway scenario; no target code was executed during this review.

Is this the best way to solve the issue?

The identity split uses the existing lease and queue owners and removes superseded paths; the remaining concrete implementation work is completing the test-consumer migration.

Full review comments:

  • [P2] Complete the lease API cutover in its test consumers — src/plugins/memory-audience.test-support.ts:39-42
    The shared mocked generation module now exports only prepareChatLease, but scheduled admission calls acquireTranscriptLease, which requires prepareLeaseFacts. In execution-context-memory-audience.test.ts that missing export is caught as failed admission, so otherwise valid occurrences produce undefined audiences; exact-head CI records this failure. Other consumers still assert the removed transcript fields or the previous empty-leaf behavior, including reset-followup-durable, restart media-binding, sessions-send admission, and Stop tests. Migrate the shared fake to support exact leases and update affected assertions to the explicitly chosen contracts, preserving independent rejection and authority coverage.
    Confidence: 0.99
  • [P2] Complete ownership registration for the new browser test — test/vitest/vitest.ui-e2e.config.ts:58
    The new file is registered in the real-Gateway and private-server lists, but test/vitest-ui-e2e-config.test.ts still omits it from its realGatewayFiles and serialGatewayFiles inventories. The private-server insertion also violates the sorted order compared by ci-ui-e2e-ownership.test-support.ts. Exact-head CI fails both execution-inventory and ownership checks on these differences. Register the file in the matching expected execution inventories and place the private-server entry in canonical order.
    Confidence: 1

Overall correctness: patch is incorrect
Overall confidence: 0.94

AGENTS.md: found and applied where relevant.

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

Provenance checked

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

PR surface

PR surface statistics unavailable: the file list is incomplete.

Preflight source

Source unknown. Source comparison at the observed PR snapshot only. Completion is self-reported; body, policy, tests, execution, and report bytes are not verified.

Labels

Label changes:

No label changes.

Label justifications:

  • P2: The PR repairs valid ancestor sends and background-delivery lifecycle behavior with limited blast radius.
  • merge-risk: 🚨 compatibility: The persisted outbound payload loses transcript fields under the same namespace; the body explicitly accepts older-build replay failure, while forward-upgrade evidence remains incomplete.
  • rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦪 silver shellfish and patch quality is 🦪 silver shellfish.
  • status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action.

Rating scale

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

Workflow

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

Reviewed November 16, 2026, 1:00 PM ET / 18:00 UTC.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation app: web-ui App: web-ui gateway Gateway runtime scripts Repository scripts agents Agent runtime and tooling size: XL labels Nov 16, 2026
@obviyus
obviyus force-pushed the obviyus/identity-types-guard branch from 6a54523 to 951572b Compare November 16, 2026 20:51
obviyus and others added 10 commits November 17, 2026 02:22
…lease

- Add ChatRef, the only durable chat address. Delivery, queue, wake and session
  event APIs take it; SessionDeliveryGeneration and SessionGenerationFacts are
  deleted.
- Add TranscriptLease for live writers. Exact pins are private to it and it
  refuses to serialise.
- The session identity ratchet now counts pin names and sessionId/
  lifecycleRevision compares per file outside the session store.
- A send is admitted while the sender's leaf is on the active path, so a message
  queued during a turn is no longer refused as a branch switch.
  activePathRelation becomes onActivePath; activePathNavigationMoved and the
  session-id leaf fence are deleted.

Co-authored-by: obviyus <[email protected]>
Deleting a session now dead-letters its unsent queued outbound sends, so a
recreated key never receives them. A send that already started stays with
its recovery owner.

Co-authored-by: obviyus <[email protected]>
…chat by key

The requester-wake lost-run failure notice now resolves the requester's
current transcript at write instead of pinning the transcript and lifecycle
revision captured at admission, so a compaction successor still gets it.

Co-authored-by: obviyus <[email protected]>
- Stop runs before send admission, so its leaf check also refuses a session the
  sender never saw.
- Add a Control UI real-Gateway E2E: a message queued during a turn is sent
  after the turn ends, and a pane that still shows the pre-switch branch is
  refused.
- Build the queue test address with chatRef.

Co-authored-by: obviyus <[email protected]>
…lease probe

- An ordinary send that names a replaced session id is refused as
  active-leaf-changed again, so Control UI refreshes the stale pane.
- The delivery-generation perf probe uses the ChatRef lease APIs.
- The leaf E2E provider matches the scripted prompt even when runtime context
  follows it.

Co-authored-by: obviyus <[email protected]>
Set the follow-up mode in config before the page opens, wait for each turn to
settle before withholding events, pick the off-path tip from
sessions.branches.list, and send the queued message without a session id like
a client that sends only its displayed leaf.

Co-authored-by: obviyus <[email protected]>
- A memory audience grant holds the incarnation it was minted in, through a
  transcript lease: a parent reset ends it, a compaction successor keeps it.
- An empty view is a prefix of any path for a message only; typed Stop still
  needs an empty transcript, so it never cancels work it did not see.
- Mark the ChatRef brand assertion and register the leaf E2E in the UI E2E
  inventory tests.
- Update tests that expected transcript ids on chat addresses.

Co-authored-by: obviyus <[email protected]>
- A send is admitted while the sender's leaf is on the active path; an empty
  view is a prefix of every path. The send's own session-id fence is deleted.
  Typed Stop keeps its incarnation fence until Stop records a stop cause.
- check:session-identity-ratchet now counts compares on any session id, run id,
  generation, lifecycle revision or leaf id, the pin names, and inference
  refusal messages, per file outside the session store. Existing hits are in
  config/session-identity-allowlist.txt, which may only shrink.

Co-authored-by: obviyus <[email protected]>
A sessions_send to a task session pinned the run id, generation and
session id captured when the send was approved. Any exec wake, yield,
follow-up or compaction moved the task on, so the coordinator could no
longer reach its own worker ("Task resume differs from the captured
communication owner").

The send now continues the task's current run. It is refused only when
the task ended or was cancelled, the chat was deleted, or another
session took control. Retained replays bind a fresh resume at dispatch
instead of carrying the held run's pins.

Co-authored-by: obviyus <[email protected]>
@obviyus
obviyus force-pushed the obviyus/identity-types-guard branch from 951572b to 74bcf01 Compare November 16, 2026 20:53
@obviyus obviyus changed the title refactor(sessions): address chats by ChatRef, hold transcripts by lease, and accept sends behind the tip refactor(sessions): address chats by ChatRef, fence writers by lease, and stop refusing on captured ids Nov 16, 2026
@obviyus

obviyus commented Nov 16, 2026

Copy link
Copy Markdown
Collaborator Author

Maintainer override: one unrelated red on head 496707d.

@obviyus
obviyus merged commit 8d581e9 into main Nov 16, 2026
454 of 464 checks passed
@obviyus
obviyus deleted the obviyus/identity-types-guard branch November 16, 2026 23:22
@obviyus

obviyus commented Nov 16, 2026

Copy link
Copy Markdown
Collaborator Author

Landed as 8d581e9.

  • Bug: checks stopped work because a captured id changed (transcript id, run id, generation, displayed leaf). Effects: a message queued during a turn was refused as "switched branches". A sessions_send to a task after a wake or a compaction was refused. A lost-run notice was refused after a reset. Deleting a chat did not purge its queued replies.
  • Fix: ChatRef is now the only durable chat address, and TranscriptLease is the only way to hold one transcript. Sends use one rule: the sender's leaf must be on the active path. The task-send id compares are deleted. A shrink-only identity ratchet blocks new id compares.
  • Proof: Control UI E2E on a real Gateway (refused on base, delivered on head) and the delete-purge journey. Unit tests cover the task-send fix. Local ClawSweeper review on the exact head found no issues. The one red job, deep-research-routing, fails the same way on main.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 17, 2026
… and stop refusing on captured ids (openclaw#200191)

## What Problem This Solves

Work was stopped by inference: a check captured an id that changes on its own (a transcript id, lifecycle revision, run id, generation or displayed leaf), and later treated "it changed" as "it was revoked". Users saw:

- A message queued in Control UI during a turn was refused as "switched branches" once the turn ended. The sender's leaf was one entry behind the new reply, and a send without a session id needed an exact leaf match.
- `sessions_send` to a task session was refused with "Task resume differs from the captured communication owner." after the task moved to a new run (exec wake, yield, follow-up) or was compacted.
- A requester-wake failure notice for a lost subagent batch was pinned to the requester's old transcript and refused as `session-rebound` after a reset or compaction successor.
- Deleting a chat left its queued outbound replies in the durable queue, so a chat recreated with the same key could receive them.
- Every delivery, queue, wake and session-event API took a `SessionDeliveryGeneration` with a transcript id and revision, so any new caller could pin a chat to an id again.

## Why This Change Was Made

Make the bad state hard to express and guard the rest:

- **`ChatRef`** (`src/sessions/chat-ref.ts`) is the only durable chat address: agent id, store path and session key, branded. `chatRef()` copies only the address, so ids in rows queued by older builds never travel with it. Delivery, queue, wake, cron delivery, memory audience and session-event APIs take a `ChatRef`. `SessionDeliveryGeneration` and `SessionGenerationFacts` are deleted.
- **`TranscriptLease`** (`src/config/sessions/transcript-lease.ts`) is the only way to hold one transcript. Live writers (cron root, fork, subagent control, restart resume, a scheduled occurrence) acquire it with a private pin. It refuses to serialise.
- **One prefix rule for sends:** a send is admitted while the sender's leaf is on the active path; an empty view is a prefix of every path. A rewind, branch switch or reset away from the leaf still refuses it (openclaw#113073 holds). Deleted: the exact-match branch, `activePathNavigationMoved` and its reader, the send's own session-id fence, and the test-only relation reader. `activePathRelation` becomes `onActivePath`.
- **Task sends follow the chat:** `sessions_send` continues the task's current run. The `previousRunId` / `generation` / `childSessionId` compares, the retained-task pins and the target-incarnation compare are deleted. It refuses only when the task ended or was cancelled, the chat was deleted, or another session controls the task.
- **Lost-run notice by key**, and **delete purges queued sends** (a send that already started stays with its recovery owner).
- **Guard:** `check:session-identity-ratchet` counts, per file outside `src/config/sessions/`, any `===`/`!==` on a session id, run id, generation, lifecycle revision or leaf id, the `expectedSessionId` / `expectedLifecycleRevision` pin names, and refusal strings ("differs from the captured", "no longer active", "changed before", "was replaced"). Existing hits are listed in `config/session-identity-allowlist.txt`, which may only shrink.

Kept on purpose:
- **Typed Stop** keeps its incarnation fence (an empty view must still be empty, and the session id must match), so a Stop never cancels work that started after it. It moves to a recorded stop cause in the next change.
- **Memory grants** hold the incarnation they were minted in through a transcript lease: a reset revokes the grant, a compaction successor keeps it. This is the narrower authority and matches the memory audience's own tests.
- Knowledge partitions, the deep-research job store and GitHub publication rows key on transcript ids in stored rows; changing them needs a data migration and is left for a separate decision.

Production code (`src`, `extensions`, without tests): +524 / −602.

## User Impact

- A message queued during a turn is sent when the turn ends.
- A pane that still shows a branch another client switched away from is still refused, and the message is parked as not sent.
- A send to a task session reaches its current run after wakes, yields and compaction; a send to a cancelled task is refused with a reason.
- Deleting a chat drops its unsent queued replies.
- Rows queued by older builds still deliver. A row queued by this build and replayed by an older build has no transcript id; the older build treats it as unavailable and retries it until its retry budget ends.

## Evidence

Base = merge base `2c94bae9c3ea`, head = this PR.

| Journey | Tier | Base | Head |
|---|---|---|---|
| Control UI: queue a message during a held turn, release the turn (send carries only the displayed leaf) | Control UI E2E, real Gateway, scripted provider (`ui/src/e2e/chat-send-leaf-ancestor.real-gateway.e2e.test.ts`) | `chat.send` ok=false, message parked "Not sent" | `chat.send` ok=true, reply "Flag mentioned." |
| Control UI: pane still shows Plan C, another client switches to the Plan B tip, pane sends | same | refused, no provider request | refused, no provider request |
| Compaction successor while a background exec runs, then a next turn | `ocx src` scratch Gateway, real Claude model | exec wake lands in the successor transcript; next turn runs | same |
| Queue an outbound reply, delete the chat, recreate the key | `ocx src` scratch Gateway | 1 queued reply still pending | 0 pending |
| Reaction, then edit a later message | `ocx src` scratch Gateway | reaction still listed | reaction still listed |
| Plant `entry.sessionId === saved` in a new file | `check:session-identity-ratchet` | — | fails: `src/sessions/chat-ref.ts: 1 > 0` |

The task-send fix is proven by unit tests only: a send to an owned task after its run id and generation advanced, with a stale resume binding, is delivered (fails on base), and a send after the task is killed is refused. Real-Gateway journeys with a real Claude model (spawn a task, then send after an exec wake, after compaction, after cancel, or while the task is busy so the send is held and released) did not reproduce the refusal on base: base delivered in each. The live refusal needs the in-process resume binding of a retained self-hold replay, which these journeys do not reach.

Gates: oxfmt, oxlint, `pnpm tsgo:core`, `tsgo:ui`, `tsgo:scripts`, `pnpm check:test-types`, and `ocx test` on the lease, session store, outbound queue, subagent registry, cron, memory audience, session events, chat send and Stop, `sessions_send`, restart resume and UI E2E inventory suites.

`test/plugins/deep-research-routing.gateway.test.ts` fails the same way on `main` (CI run 43939332007, job 133553190527); this PR does not touch it.

Co-authored-by: Ayaan Zaidi <[email protected]>
RomneyDa added a commit that referenced this pull request Nov 18, 2026
Bounded backport of #200191: admit omitted-ID active prefixes, rebind paused task resumes through the existing owner, and fence runtime-owner replacement after each accepted task execution. Explicit incarnation and typed Stop protections remain. Broad ChatRef migration and remaining source paths are not included.

(cherry picked from commit 8d581e9)

Co-authored-by: Ayaan Zaidi <[email protected]>
Co-authored-by: RomneyDa <[email protected]>
RomneyDa added a commit that referenced this pull request Nov 19, 2026
… and stop refusing on captured ids (#200191)

## What Problem This Solves

Work was stopped by inference: a check captured an id that changes on its own (a transcript id, lifecycle revision, run id, generation or displayed leaf), and later treated "it changed" as "it was revoked". Users saw:

- A message queued in Control UI during a turn was refused as "switched branches" once the turn ended. The sender's leaf was one entry behind the new reply, and a send without a session id needed an exact leaf match.
- `sessions_send` to a task session was refused with "Task resume differs from the captured communication owner." after the task moved to a new run (exec wake, yield, follow-up) or was compacted.
- A requester-wake failure notice for a lost subagent batch was pinned to the requester's old transcript and refused as `session-rebound` after a reset or compaction successor.
- Deleting a chat left its queued outbound replies in the durable queue, so a chat recreated with the same key could receive them.
- Every delivery, queue, wake and session-event API took a `SessionDeliveryGeneration` with a transcript id and revision, so any new caller could pin a chat to an id again.

## Why This Change Was Made

Make the bad state hard to express and guard the rest:

- **`ChatRef`** (`src/sessions/chat-ref.ts`) is the only durable chat address: agent id, store path and session key, branded. `chatRef()` copies only the address, so ids in rows queued by older builds never travel with it. Delivery, queue, wake, cron delivery, memory audience and session-event APIs take a `ChatRef`. `SessionDeliveryGeneration` and `SessionGenerationFacts` are deleted.
- **`TranscriptLease`** (`src/config/sessions/transcript-lease.ts`) is the only way to hold one transcript. Live writers (cron root, fork, subagent control, restart resume, a scheduled occurrence) acquire it with a private pin. It refuses to serialise.
- **One prefix rule for sends:** a send is admitted while the sender's leaf is on the active path; an empty view is a prefix of every path. A rewind, branch switch or reset away from the leaf still refuses it (#113073 holds). Deleted: the exact-match branch, `activePathNavigationMoved` and its reader, the send's own session-id fence, and the test-only relation reader. `activePathRelation` becomes `onActivePath`.
- **Task sends follow the chat:** `sessions_send` continues the task's current run. The `previousRunId` / `generation` / `childSessionId` compares, the retained-task pins and the target-incarnation compare are deleted. It refuses only when the task ended or was cancelled, the chat was deleted, or another session controls the task.
- **Lost-run notice by key**, and **delete purges queued sends** (a send that already started stays with its recovery owner).
- **Guard:** `check:session-identity-ratchet` counts, per file outside `src/config/sessions/`, any `===`/`!==` on a session id, run id, generation, lifecycle revision or leaf id, the `expectedSessionId` / `expectedLifecycleRevision` pin names, and refusal strings ("differs from the captured", "no longer active", "changed before", "was replaced"). Existing hits are listed in `config/session-identity-allowlist.txt`, which may only shrink.

Kept on purpose:
- **Typed Stop** keeps its incarnation fence (an empty view must still be empty, and the session id must match), so a Stop never cancels work that started after it. It moves to a recorded stop cause in the next change.
- **Memory grants** hold the incarnation they were minted in through a transcript lease: a reset revokes the grant, a compaction successor keeps it. This is the narrower authority and matches the memory audience's own tests.
- Knowledge partitions, the deep-research job store and GitHub publication rows key on transcript ids in stored rows; changing them needs a data migration and is left for a separate decision.

Production code (`src`, `extensions`, without tests): +524 / −602.

## User Impact

- A message queued during a turn is sent when the turn ends.
- A pane that still shows a branch another client switched away from is still refused, and the message is parked as not sent.
- A send to a task session reaches its current run after wakes, yields and compaction; a send to a cancelled task is refused with a reason.
- Deleting a chat drops its unsent queued replies.
- Rows queued by older builds still deliver. A row queued by this build and replayed by an older build has no transcript id; the older build treats it as unavailable and retries it until its retry budget ends.

## Evidence

Base = merge base `edbc5bcea9b6`, head = this PR.

| Journey | Tier | Base | Head |
|---|---|---|---|
| Control UI: queue a message during a held turn, release the turn (send carries only the displayed leaf) | Control UI E2E, real Gateway, scripted provider (`ui/src/e2e/chat-send-leaf-ancestor.real-gateway.e2e.test.ts`) | `chat.send` ok=false, message parked "Not sent" | `chat.send` ok=true, reply "Flag mentioned." |
| Control UI: pane still shows Plan C, another client switches to the Plan B tip, pane sends | same | refused, no provider request | refused, no provider request |
| Compaction successor while a background exec runs, then a next turn | `ocx src` scratch Gateway, real Claude model | exec wake lands in the successor transcript; next turn runs | same |
| Queue an outbound reply, delete the chat, recreate the key | `ocx src` scratch Gateway | 1 queued reply still pending | 0 pending |
| Reaction, then edit a later message | `ocx src` scratch Gateway | reaction still listed | reaction still listed |
| Plant `entry.sessionId === saved` in a new file | `check:session-identity-ratchet` | — | fails: `src/sessions/chat-ref.ts: 1 > 0` |

The task-send fix is proven by unit tests only: a send to an owned task after its run id and generation advanced, with a stale resume binding, is delivered (fails on base), and a send after the task is killed is refused. Real-Gateway journeys with a real Claude model (spawn a task, then send after an exec wake, after compaction, after cancel, or while the task is busy so the send is held and released) did not reproduce the refusal on base: base delivered in each. The live refusal needs the in-process resume binding of a retained self-hold replay, which these journeys do not reach.

Gates: oxfmt, oxlint, `pnpm tsgo:core`, `tsgo:ui`, `tsgo:scripts`, `pnpm check:test-types`, and `ocx test` on the lease, session store, outbound queue, subagent registry, cron, memory audience, session events, chat send and Stop, `sessions_send`, restart resume and UI E2E inventory suites.

`test/plugins/deep-research-routing.gateway.test.ts` fails the same way on `main` (CI run 43939332007, job 133553190527); this PR does not touch it.

Co-authored-by: Ayaan Zaidi <[email protected]>
(cherry picked from commit 8d581e9)

Release adaptation: Direct backport; retain baseline event-handoff fixes and adopt ChatRef plus transcript leases consistently.
Follow-up disposition: Active-path admission and requester-event changes retained; focused regression proof recorded in lane report.

Co-authored-by: RomneyDa <[email protected]>
(cherry picked from commit 6191c103b746aa121f5d88f570f760064c6da731)
RomneyDa added a commit that referenced this pull request Nov 19, 2026
Release adaptation: Regenerate the shrink-only ratchet after composing #200328 with #200191 and #200314. Only the obsolete update-doctor-result allowance is removed.

Co-authored-by: RomneyDa <[email protected]>
(cherry picked from commit cfcd57db7ed4758d2a6013f8f66fe1a84e13d015)
RomneyDa added a commit that referenced this pull request Nov 19, 2026
Release adaptation: combine #200191 and #200326 using canonical307e88 hadTask/expectTargetTask replay admission, retaining explicit reset/delete stop settlement. Independent source review and 26 focused tests pass; targeted type-aware lint and formatting pass.

Co-authored-by: RomneyDa <[email protected]>
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 docs Improvements or additions to documentation gateway Gateway runtime merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P2 Normal backlog priority with limited blast radius. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. scripts Repository scripts size: XL status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant