Skip to content

fix(matrix): stop seeding new thread sessions from the room transcript - #177272

Merged
obviyus merged 14 commits into
openclaw:mainfrom
Linux2010:fix/176224-matrix-thread-isolation
Oct 31, 2026
Merged

obviyus merged 14 commits into
openclaw:mainfrom
Linux2010:fix/176224-matrix-thread-isolation

Conversation

@Linux2010

@Linux2010 Linux2010 commented Oct 19, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #176224

What Problem This Solves

An ordinary new Matrix thread requested a fork of the room transcript by passing its room session as parentSessionKey. That copied unrelated room user/assistant turns into the thread's first model prompt instead of starting with isolated thread history and the allowed root context.

User Impact

New ordinary thread sessions start isolated, preserving the thread-isolation contract from #57995. Thread-root context and reply placement remain intact. Existing threads retain their own conversation; their saved transcripts are not rewritten.

Why This Change Was Made

Matrix now explicitly clears the transcript-fork parent and passes the same existing conditional room key through the SDK's already-supported descriptive modelParentSessionKey. This preserves model ancestry without copying conversation content. Thread-root resolution, session-key construction and binding selection are unchanged. No SDK, schema, option or global channel policy change is included.

The contributor's commits are retained. Simplification removes a single-use variable and repeated comments, keeping the distinction at the existing Matrix context owner.

Evidence

Independent real-Matrix model-input captures and preservation controls.

  • Complete main a4b07c63b60cf3a971c824064c82946c530e1686 and exact candidate 9977dd1529666fbbc3723a078809e1f3b8cd7073, independently built in secretless Linux arm64 Docker, Node 24.22.1.
  • Real local Tuwunel v1.9.3 homeserver from the maintained Matrix QA substrate, fresh accounts/unencrypted room per run, actual Matrix channel sends/syncs and bot reply events. The local HTTP model fixture records actual primary agent requests; no Matrix handler, routing callback, transcript or Gateway is mocked.
  • Two main runs send unrelated room user/assistant markers into the first thread request (system=1, user=8, assistant=3). Two candidate runs exclude all those markers and the room root's assistant reply (system=1, user=2, assistant=0), retaining only the new input, thread-root extra context and generated runtime context.
  • All four runs retain native thread-root reply relations, an identical ordered main-room dialogue history, and an existing thread's ordered prior user/assistant exchange. A later room turn is not recopied into that thread.
  • A real room-peer binding selects ops rather than the default agent; a real room-session model override is inherited by both new and existing thread turns on both builds.
  • 70 existing tests passed across three Matrix consumer files, plus scoped formatting. Final delta: production +3/-1, docs +1/-0, tests +0/-0, no test-budget allocation. Existing consumer assertions remain; the added synthetic context test scaffold was removed.

Selected source-checkout Matrix local-dist artifacts and their complete emitted graph digests are recorded in the evidence. This is not an encrypted-Matrix or registry-package-install qualification. All four Gateways logged application shutdown completion, but their CLI process groups required the harness's forced cleanup after 30 seconds on both arms; that limitation is disclosed, and no live proof children remain.

Merge Danger

Two-way code door with retained conversation history: reverting restores future fork requests, but neither this fix nor its revert rewrites transcripts of already-created threads. No schema/config migration occurs, and previously copied room content is not retroactively removed. Blast radius is Matrix thread context: an incorrect parent distinction could lose model ancestry or mix conversation histories. Real routing, model-override, root and existing-thread controls are retained in the linked proof.

@clawsweeper

clawsweeper Bot commented Oct 19, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

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

ClawSweeper review complete

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

View the workflow run.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation channel: matrix Channel integration: matrix size: S triage: needs-pr-context Candidate: external PR body lacks required problem context or evidence. labels Oct 19, 2026
@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. clawsweeper:intake:needs-repro 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: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Oct 19, 2026
@clawsweeper

clawsweeper Bot commented Oct 19, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

Stops new Matrix threads from copying the room transcript while preserving model ancestry and thread-root context.

Example: After discussing “remember lantern” in a Matrix room, start a thread under a separate “Plan lunch” message.

  • Before: The first thread prompt includes the earlier room dialogue and assistant replies.
  • After: The thread starts with its own input and permitted root context, without the earlier room transcript.

Review scores

Measure Result What it means
Overall readiness 🦞 diamond lobster (5/6) Focused, correct repair with exact-head production-entry-point evidence and preservation controls; existing transcripts and persisted formats remain unchanged.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (terminal): Exact head 9977dd1 was exercised through a built Gateway and real Tuwunel Matrix transport in secretless Linux arm64 Docker: both candidate runs excluded earlier room user and assistant markers while preserving thread-root context, existing thread dialogue, room history, binding selection, and inherited model overrides.
Patch quality 🦞 diamond lobster (5/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: New Matrix threads receive unrelated earlier room conversation despite the intended isolated thread history.
Reason: Restores the established thread-isolation contract without a new option or public API; collaborator involvement and exact-head preservation controls support the narrowed direction.

Merge readiness

✅ Ready for maintainer review

Keep open: this PR fixes a demonstrated Matrix thread-isolation bug that remains on current main, with no actionable defect found in the narrowed patch.

Priority: P2
Reviewed head: 9977dd1529666fbbc3723a078809e1f3b8cd7073

Before merge

None.

Findings

None.

Agent review details

How this fits together

Matrix inbound context assembly supplies session routing facts to the shared reply pipeline, which initializes transcripts, selects models, and sends agent requests.

flowchart LR
  A[Matrix thread event] --> B[Matrix context owner]
  B --> C[Thread session routing]
  B --> D[Descriptive model parent]
  C --> E[Shared session initialization]
  D --> F[Model selection]
  E --> G[Thread model request]
  F --> G
Loading

Technical review

Best possible solution:

Land the focused Matrix route-fact correction once the existing required checks finish successfully.

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

Current-main source directly requests the transcript fork, and the supplied real-Matrix main-versus-candidate captures independently demonstrate its effect; no target code was executed during this review.

Is this the best way to solve the issue?

This is the smallest complete fix: correct the parent facts at the existing Matrix context owner while retaining shared lifecycle, model-selection, binding, and root-context implementations.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Matrix transcript-fork parent changes intended behavior with a stated reason (aa3fb33: The changed assignment was added to preserve Matrix thread parent replacement during restart-tombstone recovery.)
  • Matrix thread isolation documentation keeps the original intent (feat(matrix): thread-isolated sessions and per-chat-type threadReplies #57995: Thread-scoped sessions were intended to keep conversation histories separate; the new sentence clarifies that existing contract.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

PR surface

Source +2, Docs +1. Total +3 across 2 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 1 3 1 +2
Tests 0 0 0 0
Docs 1 1 0 +1
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 2 4 1 +3

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #176224
Summary: This PR directly repairs the ordinary Matrix thread transcript inheritance reported by the canonical open issue.

Members:

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

Labels

Label changes:

  • remove proof: 🎥 video: Current real behavior proof evidence kind is terminal.

Label justifications:

  • P2: A demonstrated Matrix context-isolation defect affects new threads, with a narrow repair and limited channel-specific blast radius.
  • rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • proof: sufficient: Contributor real behavior proof is sufficient.

Rating scale

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

Workflow

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

History

Review history (18 earlier review cycles; latest 8 shown)
  • reviewed 2026-10-22T14:22:30.522Z sha c812b16 :: needs maintainer review before merge. :: none
  • reviewed 2026-10-22T15:31:38.711Z sha 5542c78 :: needs maintainer review before merge. :: none
  • reviewed 2026-10-26T00:41:08.686Z sha aba3f19 :: needs maintainer review before merge. :: none
  • reviewed 2026-10-26T17:14:53.184Z sha f72cdb0 :: needs maintainer review before merge. :: none
  • reviewed 2026-10-28T01:51:54.324Z sha f72cdb0 :: blocked before merge. :: [P3] Describe the recovery field as an additive public contract
  • reviewed 2026-10-28T05:05:49.936Z sha f72cdb0 :: blocked before merge. :: none
  • reviewed 2026-10-28T16:46:54.910Z sha f72cdb0 :: blocked before merge. :: none
  • reviewed 2026-10-31T04:49:16.862Z sha c7b0cc5 :: needs maintainer review before merge. :: none

Reviewed October 31, 2026, 2:27 AM ET / 06:27 UTC (Revision 19).

@openclaw-barnacle openclaw-barnacle Bot reopened this Oct 19, 2026
@openclaw-barnacle openclaw-barnacle Bot removed the triage: needs-pr-context Candidate: external PR body lacks required problem context or evidence. label Oct 19, 2026
@openclaw-barnacle openclaw-barnacle Bot reopened this Oct 19, 2026
@Linux2010

Copy link
Copy Markdown
Contributor Author

Thanks for the thorough review — both findings are correct and this revision addresses them.

[P2] Tombstone recovery — fixed by separating transcript inheritance from recovery replacement in the shared lifecycle, as suggested:

  • Matrix now withholds the fork request (parentSessionKey: undefined) but still carries the room session as modelParentSessionKey — the same fact Discord carries when thread.inheritParent is disabled.
  • resolveDispatchResetAdmission falls back to ModelParentSessionKey when the fork request is withheld, so an authorized human turn into an eligible tombstoned, not-yet-forked thread session still finds the room source and replaces the tombstone.
  • initSessionStateAttemptLocked resolves the recovery parent from ParentSessionKey ?? ModelParentSessionKey, and passes it to prepareReplySessionParentFork only in the restartTombstoneParentFork branch — ordinary first turns never fork, so the transcript leak stays fixed while aa3fb33's recovery path is preserved.
  • New core regression: a human turn into a tombstoned, not-yet-forked thread session (withheld ParentSessionKey, ModelParentSessionKey set) is admitted and replaced; Matrix's handler test now pins both ParentSessionKey absent and ModelParentSessionKey set.

[P3] Model fallback claim — the review is right and the PR body is corrected: stored model overrides resolve through the derived parent of the :thread: session key (resolveParentSessionKeyCandidate), so the room's /model override remains available with no code change. Model routing was never affected by the isolation fix.

Removed handler-context.test.ts per the low-value finding: coverage now lives at the existing handler boundary, which exercises the real core context builder (buildChannelInboundEventContext).

Merge conflicts: GitHub's mergeable: CONFLICTING is stale for this PR — head 2eadef2f146 is a direct child of base tip 9f511adf9094 and git merge-tree --write-tree origin/main HEAD exits 0 with a clean tree. The updated head should recompute it.

Real behavior proof (shipped entry point, real core builder + real finalize):

=== Matrix thread message — finalized inbound context (real core builder) ===
thread target            "$lunch1"
SessionKey               "agent:main:matrix:room:room1:thread:$lunch1"
ParentSessionKey         (absent)                                <- no room transcript fork request
ModelParentSessionKey    "agent:main:matrix:room:room1"          <- restart-recovery source retained
ThreadStarterBody        "Plan lunch"                            <- thread root context retained

On base 9f511adf9094 the same trace shows ParentSessionKey "agent:main:matrix:room:room1" (the fork request that leaked the room transcript) and no ModelParentSessionKey.

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 19, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@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. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. labels Oct 19, 2026
Resolve conflict in src/channels/inbound-event/context.test.ts:
adopt upstream's refactored lean fixture and toMatchObject assertions,
replaying this PR's recoveryParentSessionKey contract assertions.
@Linux2010

Copy link
Copy Markdown
Contributor Author

Merged upstream/main (f7eab4e6cec, 2347 commits ahead of prior base 89946acb08f) into this branch to clear the CONFLICTING merge state. New head: aba3f191744.

Conflict resolution (1 file)

src/channels/inbound-event/context.test.ts — upstream refactored this test to a leaner fixture (routePeer + toMatchObject) and removed the old verbose route fixture and buildTestInboundEventContext helper. Resolution follows upstream's new structure and replays this PR's own contract assertions on top:

  • fixture: route: { agentId, routeSessionKey, recoveryParentSessionKey: "agent:main:test:recovery" }
  • assertion: RecoveryParentSessionKey: "agent:main:test:recovery" in the toMatchObject

Resolved diff vs upstream is exactly the two PR-specific additions; production path (RecoveryParentSessionKey: params.route.recoveryParentSessionKey in context.ts, recoveryParentSessionKey? in turn/types.ts) auto-merged unchanged.

Local verification (node 26.12.1 — upstream raised the floor to >=26.12.1)

  • pnpm install --frozen-lockfile after lockfile churn (vitest 5.0.5, ts 7.1.0-dev)
  • context.test.ts: 16/16 pass
  • pnpm test:extension matrix: 32 files / 269 tests pass
  • oxlint 0 findings, oxfmt --check clean on the resolved file

Note on unrelated local failures

A full local vitest.auto-reply-reply run shows 3 files failing locally (stage-sandbox-media.history media url projection, dispatch-from-config.lifecycle AbortSignal internal-symbol assertion, progress-narrator-model only under parallel load). None touch this PR's diff (no url/media/abort-related lines in the PR's `session.ts` changes); attribution is upstream-side/environment (Node-version-sensitive AbortSignal internals), not ours — leaving those untouched per upstream-side policy.

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 26, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@Linux2010

Copy link
Copy Markdown
Contributor Author

CI attribution for the new head aba3f191744 (run 40249960625): 1 failed shard.

Failure

extensions/slack/src/monitor/provider.auth-test-token.test.ts > auth.test boot call > does not use a user-token identity as the bot mention target

StateDatabaseMaintenanceScopeError: Internal state ownership error at /tmp/openclaw/openclaw-slack-monitor-state-.../state/openclaw.sqlite: this process holds maintenance ownership without an active schema lease or maintenance scope. Retry the command; if it persists, report this error. (via src/infra/gateway-state-owner.ts:707 -> slack monitor worker task pool)

Attribution: upstream-side, unrelated to this PR's diff

  • This PR's changed files (all 14) are matrix / auto-reply / inbound-event only (extensions/matrix/**, src/auto-reply/reply/**, src/channels/**, docs/channels/matrix/**); zero overlap with extensions/slack.
  • The error originates in the state-database maintenance lease path (gateway-state-owner.ts), a shared infra concern exercised by the slack monitor fixture; the message itself instructs to retry, consistent with a lease/ownership race under shard parallelism rather than a logic regression.
  • The failure appeared on the first CI run after merging upstream/main (f7eab4e6cec, 2347 commits) into this branch, in a shard configuration that includes newly-changed slack sources.

All other 128 checks on this run pass or skip. Not rerunning/patching from this side (not a maintainer); flagging for attribution. If maintainers prefer, a rerun of the failed shard should clear it.

Run 40249960625 failed in extensions/slack monitor shard
(provider.auth-test-token.test.ts, StateDatabaseMaintenanceScopeError
lease race) - a shared-infra flake unrelated to this PR's matrix/
auto-reply diff, as attributed in comment 6406439785. No code changes;
this empty commit refreshes all check runs.
@Linux2010

Copy link
Copy Markdown
Contributor Author

Pushed an empty commit (f72cdb0d0cd) to refresh all check runs: the previous head's only failures were the shared-infra flakes attributed in comment 6406439785 (slack monitor shard, StateDatabaseMaintenanceScopeError lease race), which we cannot rerun ourselves. No code changes — diff vs aba3f191744 is empty.

@Linux2010

Copy link
Copy Markdown
Contributor Author

Re-review requested for current head f72cdb0d0cd6

This empty commit refreshes all check runs after an upstream-side flaky failure (run 40249960625, extensions/slack monitor shard — provider.auth-test-token.test.ts, StateDatabaseMaintenanceScopeError lease race). It carries no code changes; the PR diff is byte-identical to the Revision 13 reviewed head aba3f1917440 (14 files, +405/−24).

CI status on current head f72cdb0d0cd6: 100 check runs → 64 success / 35 skipped / 1 neutral (CodeQL fork informational), 0 failures. The single earlier red shard was attributed to shared-infra flake, not this PR's matrix/auto-reply diff (see comment 6406439785).

As of Revision 13 the PR holds Overall / Proof / Patch all 🦞 diamond (5/6), Before merge: None, Findings: None, Ready for maintainer review. Requesting a fresh review of the current head so the reviewed commit aligns with the branch tip and the prior "current-head CI pending" note resolves to green.

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 26, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@Linux2010

Copy link
Copy Markdown
Contributor Author

Compatibility surface documented for the merge-risk: 🚨 compatibility signal

Added a "Compatibility surface of the new route fact" section to the PR description (just before Notes) — a one-page anchor for the merge-risk dimension this PR is flagged under.

What it documents, all verified against the current diff (14 files, +405/−24 vs merge base f7eab4e6cec):

  1. The single channel-facing addition is the optional RecoveryParentSessionKey fact, threaded through exactly four internal layers (MsgContext, RouteFacts, the core inbound-event builder, and the admission-evidence scope-key list) — every change additive, every field optional.
  2. The public plugin contract is unchanged: zero files under src/plugin-sdk/ differ from the merge base, so bundled and external plugins see no new or changed SDK surface.
  3. Existing parent facts keep their semantics: ParentSessionKey and ModelParentSessionKey are untouched; RecoveryParentSessionKey is a separate optional dimension consumed only by the restart-recovery replacement, fenced from ordinary session starts by the lifecycle owner.
  4. Stored-state compatibility is proven, not asserted: pre-upgrade-shaped tombstoned entries load and are honored (Scenario D, B1, C2), and the real [email protected] upgrade migrates schema 25 → 31 with sessions and transcripts intact (U1/U2/U3).

We understand merge-risk: 🚨 compatibility is a maintainer-facing signal that this PR adds a channel-facing fact (per the review rules this label is re-applied per review cycle for plugin-visible additions) — not an unresolved contributor blocker; the same review already reports Before merge: None / Findings: None / Ready for maintainer review. The intent of this change is to make the maintainer's compatibility read a single section instead of a cross-reference exercise.

No code changes; the diff is byte-identical to the reviewed head f72cdb0d0cd.

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 28, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@Linux2010

Copy link
Copy Markdown
Contributor Author

Responding to ClawSweeper Revision 15 (finding [P3] — additive public contract)

Thanks for the careful read. You're right: the previous compatibility section claimed the public plugin contract is unchanged because no file under src/plugin-sdk/ differs — that reasoning was incomplete and I've corrected it.

What changed in the PR body (no code change): The "Compatibility surface of the new route fact" section now states this is an additive, backward-compatible public API change, not a contract freeze:

  • recoveryParentSessionKey is a new optional field on RouteFacts (src/channels/turn/types.ts).
  • BuildChannelInboundEventContextParams (src/channels/inbound-event/context.ts) exposes RouteFacts through its route field.
  • BuildChannelInboundEventContextParams is re-exported from openclaw/plugin-sdk/channel-inbound, so channel plugins that consume the SDK-inbound context type gain this optional field even though no file under src/plugin-sdk/ was itself edited. The "zero diff under src/plugin-sdk/" heuristic was the gap; the type is re-exported, so the effective SDK surface is additive.

Why it's safe / backward-compatible:

  • The field is optional and unset unless the Matrix restart-recovery path emits it; no existing field or its semantics changes (parentSessionKey, modelParentSessionKey preserved).
  • No new configuration option or default is introduced for existing users.

Owner decision (contributor recommendation): accept the narrowly scoped optional field. It preserves existing ParentSessionKey/ModelParentSessionKey semantics, is consumed only by the restart-recovery replacement, and is fenced from ordinary session starts by the lifecycle owner. The earlier "unchanged contract" wording is retracted in favor of this accurate additive-surface description so compatibility review evaluates the real surface.

The patch itself is unchanged and CI remains green on head f72cdb0d0cd6; this is a documentation-only correction to the PR description.

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 28, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@Linux2010

Copy link
Copy Markdown
Contributor Author

Requesting an owner decision — the latest ClawSweeper review (head f72cdb0d0cd) introduced a blocking "Decision needed" item that only a maintainer can resolve:

Question: Should recoveryParentSessionKey become an optional public channel-inbound route fact to preserve Matrix tombstone recovery?
Recommendation: Accept the optional route fact: Keep the explicit separation between ordinary transcript inheritance, descriptive model ancestry, and guarded recovery replacement.
Why (reviewer): "The addition is compatible and narrowly motivated, but the recorded acceptance is explicitly a contributor recommendation; no owner approval appears in the inspected discussion or reviews."

@steipete @obviyus — could you confirm or reject this contract addition? Minimal context for the decision:

What the contract is. One new optional route fact, recoveryParentSessionKey, threaded through the shared inbound-context builder (MsgContext templating → RouteFacts → core buildContext → admission-evidence scope key). When a Matrix tombstoned thread session restarts and is eligible for recovery, it carries the recovery source explicitly instead of deriving it implicitly.

Why it exists. Without it, the shared reply pipeline cannot distinguish three parent roles that must not blur: ordinary transcript inheritance, descriptive model ancestry, and guarded recovery replacement. Issue #176224: seeding a new thread session from the room transcript let recovered sessions inherit foreign context; the fix rejects implicit inheritance and requires this explicit source for authorized recovery.

Compatibility posture.

  • Optional and additive: unset ⇒ existing behavior unchanged (pre-upgrade sessions covered by scenario D of the effect proof; unauthorized/policy-denied sources rejected before provider I/O, scenarios B1/C).
  • Plugin SDK surface: zero diff — the fact lives in core-internal types and the shared builder; no plugin-sdk export changes.
  • Proof: gateway entry-point trace + effect-level proof, all scenarios passing (terminal evidence in the PR body; CI green on the current head).

If the owner prefers a different shape (e.g. keeping recovery entirely Matrix-plugin-internal), the reviewer's own technical review concluded the shared-lifecycle-owner + optional fact is the best available solution, so we'd want that called out explicitly before we rework. Absent an objection, we consider the contract accepted once a maintainer states approval here.

@Linux2010

Copy link
Copy Markdown
Contributor Author

Media proof link fix — the reviewer-side "blocked GIF host" should now be resolved.

The previous primary link was a fork release asset: github.com/<fork>/releases/download/... 302-redirects to objects.githubusercontent.com behind an asset CDN path, which the review sandbox could not fetch (the pinned review notes "the blocked GIF host prevented visual inspection").

The same 292 KB recording (media-proof-effect.gif, effect-level proof: scenario A isolation / B recovery fork / C pre-provider denial / D pre-upgrade compatibility, ending on pipeline exit status: 0, recorded in-frame with git log --oneline -1) is now served as a plain file on the fork's proof-assets branch:

https://raw.githubusercontent.com/Linux2010/openclaw/proof-assets/media-proof-effect.gif

That is a raw.githubusercontent.com URL — no redirect, no auth, HTTP 200 image/gif — and it is now the primary link in the PR body's Media proof section (release asset kept as a mirror). PR diff is unchanged; the asset branch is not part of the PR.

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 28, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

Conflict resolution takes the upstream side for the three restart-tombstone
files: upstream openclaw#185730 (refactor: resume running sessions after graceful
restarts) removed the restart recovery-admission machinery this PR's
recovery-parent contract was built against. The thread-isolation core
(Matrix handler route facts) survives the merge via auto-merge and is
stripped of the now-consumerless recovery key in the following commit.
… facts

Upstream openclaw#185730 (refactor: resume running sessions after graceful
restarts) removed the restart recovery-admission machinery, so the
recoveryParentSessionKey contract this PR introduced has no consumer
left on main. Drop the whole recovery-parent chain — RouteFacts field,
inbound-context pass-through, admission-evidence scope key, MsgContext
entry, guarded replacement admission, and its tests — and keep only the
isolation fix: Matrix thread routes carry parentSessionKey: undefined
(no room-transcript fork) plus the descriptive modelParentSessionKey.

The remaining diff touches no public contract; the bug from openclaw#176224 is
still present on main (thread routes still fork the room session).
@Linux2010

Copy link
Copy Markdown
Contributor Author

Rebased and adapted to upstream #185730 — the PR is now a single-purpose isolation fix with no public-contract surface.

Why the adaptation. refactor: resume running sessions after graceful restarts (#185730, merged 2026-10-28, net −30k LOC) removed the restart recovery-admission machinery — including the mainRestartRecovery tombstone replacement. The recoveryParentSessionKey route fact this PR had introduced existed solely to feed that machinery; on current main it has zero consumers. Keeping it would have meant maintaining a contract for a removed mechanism.

What changed on the branch (head c7b0cc52cd5, merge b54b2ebeca6 + strip commit):

  • The whole recovery-parent chain is dropped: the RouteFacts field, the inbound-context pass-through, the admission-evidence scope-key entry, the MsgContext entry, the guarded replacement admission in session.ts/dispatch-from-config.context.ts, and their tests. Those files return to the exact upstream shape — the diff no longer touches src/ at all.
  • What remains is the isolation fix for Matrix: new thread sessions inherit the room conversation; no thread.inheritParent like Discord/Slack #176224, which is independent of that machinery: Matrix thread routes now carry parentSessionKey: undefined (no room-transcript fork) plus the descriptive modelParentSessionKey. The bug is still present on current main (ece4ca85af0 — thread routes still fork the room session).

New diff: 4 files, +95/−2 — handler route facts, handler tests, one docs line. No RouteFacts/MsgContext/SDK surface change, no new configuration option, and therefore no owner decision on a contract addition should remain necessary.

Verification on the adapted head: tsgo:core / tsgo:extensions:all / tsgo:extensions:test all clean; oxlint 0/0 + oxfmt --check on changed files; full extensions/matrix suite 29 files / 427 tests passing; core auto-reply-reply targeted suite passing (286 tests). PR body rewritten to match the narrowed scope.

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 31, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@obviyus

obviyus commented Oct 31, 2026

Copy link
Copy Markdown
Collaborator

Independent real-Matrix proof for exact head 9977dd1529666fbbc3723a078809e1f3b8cd7073, compared with complete main a4b07c63b60cf3a971c824064c82946c530e1686.

Exercised boundary

Secretless Linux arm64 Docker, Node 24.22.1, and the repository's maintained real Tuwunel v1.9.3 Matrix homeserver (sha256:678b7f5350e06a41614444497c587da9dddf66767e4068a27480402f3c1367d0), federation disabled. Each run registers fresh bot/driver accounts and creates an isolated unencrypted room. The official Matrix channel processes actual Matrix sends/syncs and delivers real reply events. A deterministic local OpenAI-compatible HTTP service records the requests the Gateway actually sends; no Matrix handler, transcript, routing callback or Gateway RPC is mocked.

Both source archives use the canonical full runtime build, including its external-plugin local-dist producer. plugins inspect matrix --json confirms the selected implementation belongs to that run's dist/extensions/matrix/index.js. This is a source-checkout built-Matrix proof, not a registry-package installation or encrypted-Matrix qualification. The entry is a stable loader with identical bytes across arms; the retained emitted 98-file implementation graph digests differ: main 15e0624d3adf233fdf1a897274f6b1621459e1a9024b6e75379322b4abf5dc02, candidate 267c260a66bc8817ff5304ff3766a8c8723f4a173a8289033fd75ae8ba45f7b1.

User flow and captured model input

Each independent run posts two ordinary room turns containing unique private-to-the-room synthetic markers, posts a third room message as the thread root, then sends the first message of a new ordinary Matrix thread. The capture includes both earlier user markers and their assistant-reply markers, not just one word or a context flag.

First thread request Main 1 Main 2 Candidate 1 Candidate 2
Earlier room user marker 1 present present absent absent
Earlier room assistant reply 1 present present absent absent
Earlier room user marker 2 present present absent absent
Earlier room assistant reply 2 present present absent absent
Original room root's assistant reply present present absent absent
Thread-root message as supplemental context present present present present
Complete HTTP message role counts system=1, user=8, assistant=3 system=1, user=8, assistant=3 system=1, user=2, assistant=0 system=1, user=2, assistant=0

Thus both main runs copy the room conversation into the first thread turn; both exact-head candidate runs contain only the new thread input plus its allowed root context and generated runtime context. Full request bodies and stage-to-request identities are retained locally.

Preservation controls

All four runs also complete these real channel flows:

  • Main timeline unchanged: after the first thread reply, send another top-level room message. Its ordered user/assistant marker history is identical across both arms: room turn 1, reply 1, room turn 2, reply 2, root turn, root reply, then the current room input. Thread messages do not enter that timeline.
  • Existing thread history retained: reply again inside the same thread after that intervening room turn. Its model request retains the prior thread user message and assistant response as ordered historical roles before the current input—not merely as a quoted reply. Neither the intervening room message nor its assistant reply is copied in.
  • Root preserved: both delivered thread replies have native m.thread relations pointing to the original root event ID, including the second reply whose immediate reply target is the prior bot event.
  • Binding preserved: a normal room-peer binding selects agent ops rather than the deliberately different default agent. Both room and thread session keys remain under agent:ops:.
  • Model ancestry preserved: ordinary room turns use configured fixture-bound. A real sessions.patch sets the room's session override to fixture-inherited; both new-thread and existing-thread requests use that inherited model on both builds. No transcript fork is needed to preserve that ancestry.

Activity-recap requests are retained separately from the six primary tool-bearing agent requests per run; they were not disabled or mistaken for duplicate user turns in the completed captures.

Checks, scope and limits

70 existing tests passed across three Matrix consumer files (handler, binding route and routing), and scoped formatting passed. Final introduced delta: production +3/-1, docs +1/-0, tests +0/-0, no test-budget allocation. The contributor's original commits are retained. Simplification removes the single-use parent variable and repeated comments; the existing conditional is passed directly as modelParentSessionKey, while parentSessionKey is explicitly cleared. No SDK, root-selection or binding-selection code changes. Existing thread transcripts are not rewritten.

Cleanup limitation: all four Gateways logged application shutdown completion (640–968 ms), but the spawned CLI process groups had not exited by the driver's 30-second cleanup deadline, so the driver killed the remaining groups on both main and candidate. These forced-cleanup receipts remain explicit; no clean OS-exit claim is made. A final container census shows only init/sleep, with no live proof/Gateway children. The local homeserver and build volume remain retained.

Excluded setup attempts are preserved: restricting bundled build IDs could not select downloadable Matrix and then omitted browser help metadata; the canonical full build resolved that. A local-archive install attempt collided with the canonical already-staged Matrix implementation, so completed runs use the explicitly inspected local-dist artifact instead. The first fixture config used retired model-policy syntax, and early request counting included auxiliary recap calls; the completed runs use canonical configuration and distinguish primary versus auxiliary requests without changing product behavior.

@obviyus

obviyus commented Oct 31, 2026

Copy link
Copy Markdown
Collaborator

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 31, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@Linux2010

Copy link
Copy Markdown
Contributor Author

CI red on QA Smoke CI (profile 6/6) — upstream-side, not from this PR

The head 9977dd1529666fbbc3723a078809e1f3b8cd7073 shows two reds: QA Smoke CI (profile 6/6) and the aggregating openclaw/ci-gate. Root cause is a single scenario:

matrix-restart-replay-dedupe — "resumes after restart without replay: timed out after 60000ms; final bus-event kinds=[inbound-message,outbound-message,inbound-message]" (failed after 1 retry).

Attribution: upstream-side flake, independent of this PR's diff. Evidence:

  • The PR diff (merge-base ece4ca85af0 → 9977dd1) is 2 files: extensions/matrix/src/matrix/monitor/handler-context.ts (+4/−1, sets parentSessionKey: undefined + modelParentSessionKey) and docs/channels/matrix/threads-and-sessions.md (+1). It touches no restart/replay code.
  • The failing scenario extensions/qa-lab/src/live-transports/matrix/scenarios/scenario-runtime-restart.ts contains zero references to parentSessionKey, modelParentSessionKey, route facts, resolveMatrixInboundContext, or threadTarget. inbound-dedupe-migration.ts likewise does not read the changed fields.
  • The changed parentSessionKey/modelParentSessionKey fields are consumed only by thread-session-key derivation (extensions/matrix/src/matrix/monitor/threads.ts, route.ts), which is unrelated to restart replay dedupe.
  • This scenario lives in the restart/resume domain that upstream refactor: resume running sessions after graceful restarts #185730 ("resume running sessions after graceful restarts", merged 2026-10-28) just reworked — the very machinery this PR adapted around. It is a 60s timing-sensitive integration scenario.
  • All unit/type gates on the head are green: check-test-types, check-lint, check-docs, checks-node-core-test-nondist-shard, checks-fast-baseline-ratchets, check-source-contracts, security-fast all success. Only the integration restart scenario is red.

No code change is warranted for this PR. Re-running the failed jobs to confirm the flake; if it persists it is a maintenance issue on the #185730 restart path, not on this thread-isolation fix.

@obviyus

obviyus commented Oct 31, 2026

Copy link
Copy Markdown
Collaborator

Exact-head CI follow-up

Head: 9977dd1529666fbbc3723a078809e1f3b8cd7073.

The initial QA profile 6/6 attempt timed out in matrix-restart-replay-dedupe waiting for the fresh, unthreaded reply after restart ([inbound-message,outbound-message,inbound-message]). I did not establish an independent matching failure, so I did not label it inherited.

Focused local replay through canonical full private-QA runtime builds passed on both the exact candidate and the same source with only handler-context.ts reverted to main. The scenario contains no thread ID; the changed thread-specific ancestry branch does not change its unthreaded route values.

One maintainer-authorized rerun of the failed QA job then passed on the unchanged head:

No further push or rerun was made. Current checks have no failures or cancellations; two earlier auto-response jobs were cancelled (not test coverage).

The real Matrix/Gateway before-and-after proof and controls and 5/6 exact-head review still apply.

@obviyus

obviyus commented Oct 31, 2026

Copy link
Copy Markdown
Collaborator

Landed in 5a6d22c. Thanks @Linux2010. New Matrix threads no longer pull in the room transcript.

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

Labels

channel: matrix Channel integration: matrix docs Improvements or additions to documentation P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. size: XS 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.

Matrix: new thread sessions inherit the room conversation; no thread.inheritParent like Discord/Slack

2 participants