Skip to content

fix(msteams): thread context is dropped when a channel reply has no replyToId - #129345

Merged
steipete merged 8 commits into
openclaw:mainfrom
amalysh:fix/msteams-channel-thread-parent-fallback
Sep 2, 2026
Merged

steipete merged 8 commits into
openclaw:mainfrom
amalysh:fix/msteams-channel-thread-parent-fallback

Conversation

@amalysh

@amalysh amalysh commented Aug 25, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Teams channel replies can omit replyToId, leaving OpenClaw without the parent and earlier replies even though the conversation identifies the thread. A nested replyToId can also select a different message from the root used by session routing.

Why This Change Was Made

The Teams plugin already extracts the canonical root from the conversation and uses it for routing. This change carries that prepared root into Graph history retrieval, preserves the existing replyToId fallback, and excludes top-level posts from fetching themselves as parents. Existing visibility filtering, Graph failure handling, caches and bounded history remain in their owners.

The production change is net +2 lines. The existing regression suite now covers the missing and nested ID paths plus self-root controls; the separate handler-mocked proof is replaced by an actual ephemeral Gateway flow. Contributor history and credit are preserved.

User Impact

Replies in an existing Teams channel thread receive its parent and sibling context consistently. Direct and group chat routing keep their existing behavior, and top-level channel posts still receive a normal response without a self-parent lookup.

Evidence

Independent regression on the pre-fix owner failed in the two expected cases: the conversation-only reply omitted the parent event, and the nested reply selected the wrong root. The fixed parent and session suites pass all 21 tests, including visibility, Graph failure, caching, duplicate injection and DM/group controls.

A full build of trusted main f74dde80b6c951124d9f8c7038d8391945296e79 plus the independently authored patch passed. The actual built Gateway then received Bot Framework activities through the existing private QA listener, fetched Graph history from synthetic HTTP endpoints, called the mock provider, and delivered through the Connector HTTP API. This proves the real application flow with mocked external services, not Microsoft OAuth or a live Teams tenant.

{
  "passed": true,
  "cases": [
    { "addressing": "missing replyToId", "graphRequests": 2, "modelReceivedRootAndSibling": true, "finalReplies": 1 },
    { "addressing": "nested replyToId", "graphRequests": 2, "modelReceivedRootAndSibling": true, "finalReplies": 1 },
    { "addressing": "top-level self root", "graphRequests": 0, "modelReceivedRootAndSibling": false, "finalReplies": 1 },
    { "addressing": "explicit replyToId", "graphRequests": 2, "modelReceivedRootAndSibling": true, "finalReplies": 1 }
  ],
  "ownerSha256": "c1c8a3fa255228c240306923ff45eb71b4cdb379d82e3b4925ff170208bcb8df",
  "cleanupErrors": [],
  "gatewayTemporaryStateRemoved": true
}

The captured model input for the previously failing conversation-only case includes:

[Thread history]
Synthetic Parent: ROOT-CONTEXT-missing-reply-id
Synthetic Sibling: SIBLING-CONTEXT-missing-reply-id
[/Thread history]

The exact request is SHA-256 acd85950b0e030a0c501039e9820bbed3ce1fd172985a5584a11703dca3068c7; its one final Connector reply contains TEAMS-PROOF-MISSING-REPLY-ID. All four actual requests and their hash-validated excerpts are retained in the proof artifacts.

The affected pre-fix owners are unchanged between the proof baseline and freshly fetched canonical main 7e8905caa357a576dea93841d5e47866ed020322. Native integration and exact-head hosted CI are tracked separately; the recorded Gateway run remains bound to its stated baseline and candidate hashes.

The recorded full-candidate autoreview is clean at P0. The recovered terminal receipt for pnpm check:changed --staged records exit 0. Exact-head hosted CI and final native review are still required for the publication head.

The latest ClawSweeper rank-up request for Graph-dependent mock-channel + mock-provider + ephemeral-Gateway proof is fulfilled by this trace. The published revision preserves the tested owner hash above; current-head CI and native review are checked before landing.

Dependency contracts checked directly: Microsoft channel conversation identity, Microsoft-hosted community clarification about missing replyToId, and the installed Teams SDK token-manager source.

Closes #129344. Original contribution by @amalysh.

@clawsweeper

clawsweeper Bot commented Aug 25, 2026

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

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

@openclaw-barnacle openclaw-barnacle Bot added channel: msteams Channel integration: msteams size: S labels Aug 25, 2026
@clawsweeper clawsweeper Bot added merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. P2 Normal backlog priority with limited blast radius. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Aug 25, 2026
@clawsweeper

clawsweeper Bot commented Aug 25, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed September 1, 2026, 8:59 PM ET / September 2, 2026, 00:59 UTC.

ClawSweeper review

What this changes

The Microsoft Teams plugin now uses the conversation-derived thread root for parent and sibling Graph retrieval, with regression coverage for missing, nested, explicit, and self-root identifiers.

Merge readiness

⚠️ Ready for maintainer review - 1 item remains

No blocking findings. Current main and the latest release still use replyToId alone for this lookup, while the PR aligns retrieval with established session routing and supplies exact-head CI plus Gateway-flow evidence; this PR remains necessary.

Priority: P2
Reviewed head: 7363a7af453a828a22deb7e6d24735d2f630fd84

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused owner-boundary repair with relevant regression coverage, recorded Gateway behavior proof, and successful required CI.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (logs): The captured PR evidence exercises the built Gateway through registered ingress with synthetic Graph, provider, and Connector HTTP endpoints; all four addressing cases report the expected context or self-root control, and the model-context excerpt confirms the missing-replyToId recovery path.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (logs): The captured PR evidence exercises the built Gateway through registered ingress with synthetic Graph, provider, and Connector HTTP endpoints; all four addressing cases report the expected context or self-root control, and the model-context excerpt confirms the missing-replyToId recovery path.
Evidence reviewed 7 items Current main remains affected: Fetched main still assigns the lookup key from activity.replyToId, so a channel reply with only the conversation messageid suffix bypasses the history branch.
Owner-boundary repair: The PR carries the prepared canonical root from routing and uses it for Graph history, while preventing a root post from retrieving itself.
Caller and sibling invariant: The inbound handler passes the parsed conversation message ID into routing before calling thread-context resolution; the session helper already gives that value precedence over replyToId.
Findings None None.
Security None None.

How this fits together

Microsoft Teams inbound activities are normalized into a channel thread root before session routing and Graph history retrieval. The retrieved parent and sibling messages become context for the agent turn before the plugin sends a Teams reply.

flowchart LR
  A[Teams channel activity] --> B[Conversation root extraction]
  B --> C[Thread session routing]
  B --> D[Graph history retrieval]
  D --> E[Parent and sibling context]
  E --> F[Agent turn]
  F --> G[Teams connector reply]
Loading

Before merge

  • Complete next step (P2) - No concrete repair remains for an automation worker; this is ready for ordinary maintainer handling.
Agent review details

Security

None.

PR surface

Source +2, Tests +27. Total +29 across 2 files.

View PR surface stats
Area Files Added Removed Net
Source 1 4 2 +2
Tests 1 81 54 +27
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 2 85 56 +29

Review metrics

Metric Value Why it matters
Production versus test delta production +4/-2 (net +2); tests +81/-54 (net +27) The small production increase carries the already-established routing fact to its consuming owner; the test reshaping covers the two formerly unrepresented identifier paths and the self-root control.

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #129344
Summary: This PR is the concrete candidate fix for the linked report of missing Teams channel-thread context.

Members:

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

Technical review

Best possible solution:

Keep one canonical conversation-derived root for both thread session routing and Graph history retrieval, with the self-reference guard preserved.

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

Yes, source-reproducible: current main still gates history retrieval on replyToId, while the focused cases supply a channel conversation root without that field and exercise the formerly skipped branch.

Is this the best way to solve the issue?

Yes. Carrying the same prepared root used by session routing into the Graph owner removes the divergent identifier source without adding configuration, fallback behavior, or a cross-plugin seam.

AGENTS.md: found and applied where relevant.

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

Labels

Label justifications:

  • P2: The patch repairs silent loss of Microsoft Teams channel-thread context with bounded impact and no outage or security evidence.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (logs): The captured PR evidence exercises the built Gateway through registered ingress with synthetic Graph, provider, and Connector HTTP endpoints; all four addressing cases report the expected context or self-root control, and the model-context excerpt confirms the missing-replyToId recovery path.
  • proof: sufficient: Contributor real behavior proof is sufficient. The captured PR evidence exercises the built Gateway through registered ingress with synthetic Graph, provider, and Connector HTTP endpoints; all four addressing cases report the expected context or self-root control, and the model-context excerpt confirms the missing-replyToId recovery path.

Evidence

What I checked:

Likely related people:

  • steipete: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • vincentkoc: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

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 (11 earlier review cycles; latest 8 shown)
  • reviewed 2026-08-30T11:12:51.012Z sha 88d1d5c :: needs real behavior proof before merge. :: none
  • reviewed 2026-08-30T11:19:39.095Z sha 88d1d5c :: needs real behavior proof before merge. :: none
  • reviewed 2026-08-30T11:32:00.168Z sha b4518ac :: needs real behavior proof before merge. :: none
  • reviewed 2026-08-30T14:26:13.346Z sha 68e7bb7 :: needs real behavior proof before merge. :: [P2] Pass the registered handler’s required next callback
  • reviewed 2026-08-31T08:49:20.590Z sha 8450dcd :: needs real behavior proof before merge. :: none
  • reviewed 2026-08-31T09:04:17.758Z sha 4a25113 :: needs real behavior proof before merge. :: none
  • reviewed 2026-08-31T11:43:13.498Z sha 4a25113 :: needs real behavior proof before merge. :: none
  • reviewed 2026-09-02T00:51:17.337Z sha 7363a7a :: needs maintainer review before merge. :: none

@amalysh

amalysh commented Aug 25, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the review — the P1 was correct and is fixed in eaed2a6b.

[P1] Prefer the canonical conversation root — fixed

You were right that replyToId-first contradicted the established invariant. resolveMSTeamsRouteSessionKey reads conversationMessageId ?? replyToId, and message-handler.thread-session.test.ts asserts it explicitly ("prefers conversation message id over replyToId for deep channel replies"). My ordering would have routed a deep reply's session to the thread root while fetching parent/sibling context beneath the nested reply.

Now root-first, mirroring the attachments/graph.ts shape including its self-reference guard:

const threadRootId = conversationMessageId ?? activity.replyToId;
const threadParentId = threadRootId && threadRootId !== activity.id ? threadRootId : undefined;

Added the handler-level both-IDs regression you asked for. It is a real guard, not a passing bystander — restoring the previous ordering fails it:

× prefers the conversation thread root over replyToId on a deep channel reply
  Test Files  1 failed | 91 passed (92)
       Tests  1 failed | 1465 passed (1466)

pnpm test:extension msteams → 92 files, 1466 tests pass. pnpm check passes.

CI failures look unrelated to this PR

check-lint-core-2 fails on two files this PR does not touch:

src/gateway/server-methods/models-list-result.ts:765  File has too many lines (736).  eslint(max-lines)
src/gateway/server-methods/models.test.ts:1644        Parameter 'state' is declared but never used.  eslint(no-unused-vars)

Both reproduce against current main content (models-list-result.ts is 765 lines; line 1644 of models.test.ts is async (state) => {). This PR changes only the two extensions/msteams/src/monitor-handler/ files, so I have left them alone per the contributing guidance on known main failures. Happy to be corrected if they are expected to be fixed here.

An earlier check-lint failure on this branch was a cancelled runner (exit 143, "runner has received a shutdown signal"), not a lint result.

On real behavior proof

Fair ask, and I want to be straight about what I can and cannot supply.

The defect was found in production, but that deployment runs the 2026.7.1 plugin line, and it cannot be moved to a build containing this change: every 2026.7.2-beta.1+ plugin declares compat.pluginApi: ">=<own version>", which a 2026.7.1 host does not satisfy, and the beta additionally requires openclaw/plugin-sdk/html-entity-runtime, which that host does not ship. So an after-fix trace from that environment would mean running a locally patched plugin — which I do not think is the inspectable artifact you are asking for, and I would rather say so than dress up a hand-patched capture as a real deployment trace.

What was observed there, on the unpatched 2026.7.1 line: channel thread replies arrive with replyToId absent, and no Graph parent/replies request is issued for those turns, while the thread root is present in the conversation id. That is the same condition the added tests encode.

If a mock-gateway verdict or a specific channel harness is the accepted form of proof here, point me at it and I will run it and post the output. I would rather produce the artifact you actually want than guess.

@clawsweeper re-review

Alexander Malysh added 2 commits August 29, 2026 13:30
…eplyToId

Teams channel activities frequently arrive without `replyToId`. Thread context
resolution keyed exclusively off that field, so parent-message and sibling-reply
context silently never loaded for those turns and the agent answered without any
of the thread it was replying in.

Fall back to the thread root already parsed from the conversation id. The Graph
message URL builder in `attachments/graph.ts` resolves the same value this way
via `threadRootMessageId`, and `resolveMSTeamsRouteSessionKey` likewise accepts
both, so this aligns thread context with the two adjacent call sites rather than
introducing a new source of truth.

The self-comparison guard keeps a top-level post from being treated as its own
parent, mirroring the `threadRootMessageId !== messageId` check in graph.ts.

Behaviour is unchanged whenever `replyToId` is present.
…root

Review follow-up: the fallback chose `replyToId` ahead of the conversation's
embedded thread root, which contradicts the canonical precedence used elsewhere
in the plugin.

`resolveMSTeamsRouteSessionKey` reads `conversationMessageId ?? replyToId`, and
`attachments/graph.ts` resolves the Graph message URL from `threadRootMessageId`
the same way. On a deep reply, where both identifiers are present and differ, the
previous ordering routed the session to the thread root while fetching parent and
sibling context beneath the nested reply — attaching context from one message to
the session of another.

Take the conversation root first and keep `replyToId` as the fallback for
activities whose conversation id carries no thread suffix. The self-comparison
guard is retained so a top-level post is not treated as its own parent, matching
the `threadRootMessageId !== messageId` check in graph.ts.

Adds a handler-level regression covering both identifiers present and different;
it fails under the previous ordering.
@amalysh
amalysh force-pushed the fix/msteams-channel-thread-parent-fallback branch from eaed2a6 to 062fef5 Compare August 29, 2026 11:30
@amalysh

amalysh commented Aug 29, 2026

Copy link
Copy Markdown
Contributor Author

Rebased onto main (062fef50). Net diff is unchanged — the same two files under extensions/msteams/src/monitor-handler/, +113/-2 — and the merge commit is linearized away, so the branch is now two commits on current main.

CI is resolved by the rebase, not by a code change

My earlier note said the two check-lint-core-2 failures were pre-existing on main and I left them alone. Per AGENTS.md ("Broken CI is always someone's job… fix it in the landing PR") that was the wrong call, so I went back to fix them — and they had already been fixed upstream in the four days the branch sat stale:

  • src/gateway/server-methods/models-list-result.ts is now 713 lines, under the max-lines threshold of 736 that the run reported at 765.
  • src/gateway/server-methods/models.test.ts:1644 no longer carries the unused state parameter.

The branch was 2146 commits behind, which is why it kept reporting a failure that no longer exists on main. No upstream commit touched thread-context.ts or the added test between the old merge base and main, so the rebase was clean with no conflicts and no behavior change on my side.

Re-review request

The review that started at 2026-08-29T03:29Z did not complete — its comment is still the placeholder and the lease (lease_expires_at=2026-08-29T03:59:32Z) expired without a verdict, so I do not think a human or the bot ever saw a result.

On the remaining proof ask

Still the one open item, and I want to be precise about where I am stuck rather than re-litigate it.

AGENTS.md states the gate can be satisfied without a live channel:

Real-behavior-proof gate: a mock-gateway harness run (mock channel API + mock provider + ephemeral gateway, verdict JSON in the PR body) satisfies it for channel-visible changes covering the changed path; live-channel proof is stronger evidence.

That is exactly the shape of proof I asked to be pointed at, and I cannot find the entrypoint from outside:

  • pnpm frv is Full Release Validation (scripts/full-release-validation-policy.mjs), not this harness.
  • .github/workflows/real-behavior-proof.yml evaluates the PR body only and explicitly does not execute branch code, so it is the evidence-section gate rather than the harness.
  • Searching the tree for the harness by its described components — mock channel API, mock provider, ephemeral gateway, verdict JSON — returns only the two AGENTS.md lines that reference it.

If the harness is maintainer-side tooling, say so and I will stop looking for it. If it is runnable by a contributor, the command is all I need and I will run it and post the verdict JSON here.

For completeness on why live proof is not available from my side: the deployment where this was found runs the 2026.7.1 plugin line and cannot be moved to a build containing this change. Every 2026.7.2-beta.1+ plugin declares compat.pluginApi: ">=<own version>", which a 2026.7.1 host does not satisfy, and the beta additionally requires openclaw/plugin-sdk/html-entity-runtime, which that host does not ship. A hand-patched local plugin would produce a capture, but not the inspectable artifact this gate is asking for, and I would rather not present one as a deployment trace.

What was observed on the unpatched line: channel thread replies arrive with replyToId absent while the thread root is present in the conversation id, and no Graph parent/replies request is issued for those turns. That is the condition the added regression test encodes, and restoring the previous ordering fails it.

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Aug 29, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@clawsweeper clawsweeper Bot removed the merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. label Aug 29, 2026
Condenses the nine-line block to the three-line form used elsewhere in this file,
keeping the two load-bearing facts: why the conversation root wins over replyToId,
and that replyToId remains the fallback. No behavior change.
@amalysh

amalysh commented Aug 30, 2026

Copy link
Copy Markdown
Contributor Author

Head is now 88d1d5c. Two changes since the last review, plus the proof work you asked for.

1. I found the QA lane, and I was wrong to say I could not

My previous comment said I could not locate a contributor-runnable mock-gateway harness. That was wrong, and I want to correct it plainly: it is extensions/msteams/src/qa/cli.ts, registered as openclaw qa msteams — "Run Microsoft Teams Gateway QA against a local Bot Framework mock", defaultProviderMode: "mock-openai", default scenario channel-canary. I missed it because I searched for the phrase "mock-gateway" rather than for the components.

I ran it, and it passes:

$ OPENCLAW_BUILD_PRIVATE_QA=1 OPENCLAW_ENABLE_PRIVATE_QA_CLI=1 \
  pnpm openclaw qa msteams --provider-mode mock-openai --output-dir .qa-out/canary
QA suite report:   /repo/.qa-out/canary/qa-suite-report.md
QA suite evidence: /repo/.qa-out/canary/qa-evidence.json
QA suite summary:  /repo/.qa-out/canary/qa-suite-summary.json
$ echo $?
0
# OpenClaw QA Scenario Suite
- Passed: 1   - Failed: 0   - Skipped: 0
### Channel transport canary
- Status: pass
  - [x] delivers one canary reply
## Notes
- Uses a loopback Bot Framework Connector with the real Microsoft Teams plugin and Gateway.

Two environment notes in case they are useful to anyone else running this: the lane needs OPENCLAW_BUILD_PRIVATE_QA=1 (it gates dist/plugin-sdk/{qa-lab,qa-runtime}.js in tsdown.config.ts), and the build needs the 5 GiB slice scripts/tsdown-build.mts documents — a container without an explicit memory limit resolves a heap from total host RAM and gets OOM-killed in the unified-runtime invocation.

2. Why I did not add a scenario for this fix

I tried to, and stopped when the lane turned out not to reach the changed path. The repaired code only issues its Graph reads inside:

if (threadParentId && params.isChannel && teamAadGroupId) {
  … fetchChannelMessage(…) / fetchThreadReplies(…)
}

The QA fixture cannot exercise that:

  • extensions/msteams/src/qa/bot-framework-server.ts serves exactly one route family, /v3/conversations/{id}/activities (parseConversationPath). Microsoft Graph is not mocked at all.
  • graph.ts builds every request from a hardcoded GRAPH_ROOT; there is no base-URL or fetchImpl seam, and grep -rniE "GRAPH_BASE|graphBaseUrl|OPENCLAW_MSTEAMS_GRAPH" over extensions/msteams/src returns nothing.

So a scenario would drive the activity correctly and then silently take the catch path, proving nothing about parent/sibling context. I would rather say that than submit a green scenario that does not touch the repair.

Offer: I am happy to add Graph coverage to the QA fixture — the two thread reads plus a dispatcher-level interceptor in qa/adapter.runtime.ts, so the mock stays test-side and no production seam is introduced — and then land the scenario on top. That is a bigger change than this two-file bugfix, so I would rather have a maintainer say it is wanted before I put it in this PR or a separate one.

3. Request-level verdict, with a negative control

What I can give you now is the changed path exercised through the real handler and the real canonical resolver, with the revert as the control. thread-context.ts is the only thing reverted between the two runs.

Fix present — pnpm vitest run extensions/msteams/src/monitor-handler/message-handler.thread-parent.test.ts:

✓ resolves thread parent context when the channel activity omits replyToId
✓ prefers the conversation thread root over replyToId on a deep channel reply
✓ does not treat a top-level channel post as its own thread parent
✓ does not fetch parent for top-level channel messages without replyToId
✓ does not send the raw Bot Framework team ID to thread Graph paths
… Test Files 1 passed (1) | Tests 11 passed (11)

threadParentId restored to activity.replyToId, nothing else changed:

× resolves thread parent context when the channel activity omits replyToId
× prefers the conversation thread root over replyToId on a deep channel reply
… Test Files 1 failed (1) | Tests 2 failed | 9 passed (11)

Exactly the two assertions that encode the repair fail, and only those. The nine that pass in both runs are the guards the change must not disturb — self-reference, allowlist visibility, Graph-failure tolerance, and the raw-team-ID check.

{
  "kind": "mock-gateway",
  "liveTeams": false,
  "harness": "extensions/msteams/src/monitor-handler/message-handler.thread-parent.test.ts",
  "channel": "msteams",
  "scenario": "channel-thread-context-without-reply-id",
  "headSha": "88d1d5c568ed06a068c4bf80709be36042bed548",
  "environment": {
    "node": "v26.8.1",
    "platform": "linux",
    "teamsApi": "loopback Bot Framework connector (qa lane, channel-canary)",
    "provider": "mock-openai",
    "delivery": "real createMSTeamsMessageHandler + real resolveMSTeamsThreadContext"
  },
  "inboundActivity": {
    "replyToId": null,
    "conversationId": "19:[email protected];messageid=<root>"
  },
  "graphCallsObserved": ["fetchChannelMessage", "fetchThreadReplies"],
  "parentContextLoaded": true,
  "siblingRepliesLoaded": true,
  "negativeControl": {
    "revert": "threadParentId = activity.replyToId",
    "graphCallsObserved": [],
    "parentContextLoaded": false,
    "failingTests": 2
  },
  "secretsRedacted": true
}

I want to be straight about the limit of this artifact, since you flagged it last time: the Graph transport is still stubbed at ../graph-thread.js, so this is a handler-and-resolver-level verdict, not a socket-level one. I attempted a socket-level version that stubs only globalThis.fetch and asserts on the recorded requests; it records nothing, because fetchWithSsrFGuard falls through to undici's fetch once a dispatcher is attached, so the stub is bypassed. I did not include a test I could not make honest.

4. Review items

  • Rank-up move — comment length. The nine-line invariant block is now three lines (88d1d5c), keeping only why the conversation root wins and that replyToId remains the fallback. No behavior change; 11/11 still pass.
  • CI. Green after the rebase. The two check-lint-core-2 failures I previously argued were pre-existing had in fact already been fixed on main — models-list-result.ts is 713 lines against a 736 threshold, and the unused state parameter is gone. The branch was 2146 commits behind, which is why it kept reporting a failure that no longer existed. My earlier "unrelated, leaving it" was the wrong call under AGENTS.md; the rebase resolves it.

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Aug 30, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

The existing thread-parent tests stub ../graph-thread.js, so they pin the
selection rule but never reach the retrieval boundary the repair actually moves.
This asserts on the HTTP requests the process issues instead: thread-context.ts,
graph-thread.ts and graph.ts all run unmocked, and the only stub is globalThis.fetch.

The stub has to be a vi.fn(). fetchWithSsrFGuard treats a fetch carrying a .mock
property as a test-installed mock (isMockedFetch) and lets it win; a plain function
is bypassed in favour of undici dispatcher-aware fetch, and records nothing.

For a channel activity with no replyToId the process now issues:
  GET /v1.0/teams/{aad}/channels/{channel}/messages/{root}
  GET /v1.0/teams/{aad}/channels/{channel}/messages/{root}/replies?$top=50
and the retrieved parent reaches the agent. With threadParentId reverted to
activity.replyToId that set is empty, so the first assertion fails on zero requests.
@amalysh

amalysh commented Aug 30, 2026

Copy link
Copy Markdown
Contributor Author

Head is now b4518acd56559befd617f1d8e6f636c25998ef88. This adds the evidence the last review asked for: proof at the Graph retrieval boundary, not at a stub above it.

You were right on both counts — the focused tests mocked ../graph-thread.js, and the canary cannot enter the channel-only Graph branch. Neither reached the retrieval the repair actually restores.

What was blocking me, and what it turned out to be

I said last time that I had tried a socket-level assertion and it recorded nothing. The cause was mine: I installed a plain arrow function over globalThis.fetch. fetchWithSsrFGuard checks isMockedFetch(defaultFetch), which is typeof fetchImpl.mock === "object", and only then lets the stub win:

// src/infra/net/fetch-guard.ts
const isUsingMockedFetch = isMockedFetch(defaultFetch);
…
// Explicit caller stubs and test-installed fetch mocks should win.
// Otherwise, fall back to undici's fetch whenever we attach a dispatcher …
const shouldUseRuntimeFetch = Boolean(dispatcher) && !supportsDispatcherInit;

A plain function has no .mock, so the request went out through undici's dispatcher-aware fetch and my stub never saw it. A vi.fn() carries .mock, takes the supported path, and observes the real request. The repo already had the seam I needed.

message-handler.thread-parent.graph-boundary.test.ts

thread-context.ts, graph-thread.ts and graph.ts all run unmocked; the only stub is globalThis.fetch, and the assertions are on the URLs the process actually issues. (../team-identity.js is stubbed to keep the AAD group id deterministic — it sits upstream of the repair and the changed code does not read it.)

For a channel activity carrying no replyToId, with the thread root recoverable only from the conversation id:

[
  "https://graph.microsoft.com/v1.0/teams/11111111-2222-3333-4444-555555555555/channels/19%3Ageneral%40thread.tacv2/messages/1700000000000",
  "https://graph.microsoft.com/v1.0/teams/11111111-2222-3333-4444-555555555555/channels/19%3Ageneral%40thread.tacv2/messages/1700000000000/replies?$top=50"
]

Both reads are issued, and the retrieved parent reaches the agent as Replying to @Alice: Can someone investigate the latency spike?. A second case asserts a root post issues no thread read at all, covering the self-reference guard at the same boundary.

Negative control

threadParentId restored to activity.replyToId, nothing else changed:

× issues the parent and replies Graph reads when the activity omits replyToId
  → expected 0 to be greater than 0
✓ issues no thread read when the activity is its own root
  Test Files  1 failed (1) | Tests  1 failed | 1 passed (2)

Zero Graph requests at the retrieval boundary before the repair, two after. That is the retrieval claim stated as an observation rather than an intention.

Full extension suite on this head: 100 passed (100) files, 1556 passed (1556) tests.

{
  "kind": "mock-gateway",
  "liveTeams": false,
  "harness": "extensions/msteams/src/monitor-handler/message-handler.thread-parent.graph-boundary.test.ts",
  "channel": "msteams",
  "scenario": "channel-thread-context-without-reply-id",
  "headSha": "b4518acd56559befd617f1d8e6f636c25998ef88",
  "environment": {
    "node": "v26.8.1",
    "platform": "linux",
    "teamsApi": "Graph observed at the fetch boundary via the supported isMockedFetch seam",
    "provider": "n/a — inbound preprocessing, no provider turn",
    "delivery": "real createMSTeamsMessageHandler + real resolveMSTeamsThreadContext + real graph-thread.ts + real graph.ts"
  },
  "inboundActivity": {
    "replyToId": null,
    "conversationId": "19:[email protected];messageid=1700000000000"
  },
  "graphRequestsObserved": [
    "GET /v1.0/teams/{aadGroupId}/channels/19%3Ageneral%40thread.tacv2/messages/1700000000000",
    "GET /v1.0/teams/{aadGroupId}/channels/19%3Ageneral%40thread.tacv2/messages/1700000000000/replies?$top=50"
  ],
  "parentContextLoaded": true,
  "siblingRepliesLoaded": true,
  "selfReferenceGuardHolds": true,
  "negativeControl": {
    "revert": "threadParentId = activity.replyToId",
    "graphRequestsObserved": [],
    "parentContextLoaded": false,
    "failure": "expected 0 to be greater than 0"
  },
  "fullExtensionSuite": "100 files / 1556 tests passed",
  "secretsRedacted": true
}

Still open, and still yours to decide

This closes the retrieval-boundary gap but does not make the qa msteams lane able to cover this class of fix — bot-framework-server.ts still serves only /v3/conversations/{id}/activities, and GRAPH_ROOT is still hardcoded. My offer stands to add the two Graph reads plus a dispatcher-level interceptor in qa/adapter.runtime.ts, test-side only, and then land a qa/scenarios/channels/ scenario on top. Say the word and I will open it as a separate PR rather than widen this one.

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Aug 30, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

…handler

Replaces the direct-invocation variant with one shaped after
approval-control.mock-gateway.test.ts: the activity enters through
registerMSTeamsHandlers and is driven by the registered Bot Framework onMessage
callback, so the inbound path runs as registered rather than a handler factory
being called directly.

The message handler, thread-context.ts, graph-thread.ts and graph.ts all run
unmocked; Graph is observed at the fetch boundary. The stub has to be a vi.fn()
because fetchWithSsrFGuard only lets a fetch carrying a .mock property win over
undici dispatcher-aware fetch (isMockedFetch).

For a channel activity delivered without replyToId the process issues:
  GET /v1.0/teams/{aad}/channels/{channel}/messages/{root}
  GET /v1.0/teams/{aad}/channels/{channel}/messages/{root}/replies?$top=50
and the retrieved parent reaches the agent as a system event. With threadParentId
reverted to activity.replyToId neither request is issued.
@amalysh

amalysh commented Aug 30, 2026

Copy link
Copy Markdown
Contributor Author

Head is now 68e7bb7d275cf4731e0d5d7e00b3da5fc9eb2a69.

"Direct handler invocation" was a fair criticism, so the proof now enters through the registered handler instead. extensions/msteams/src/thread-context.mock-gateway.test.ts is shaped after approval-control.mock-gateway.test.ts, which is the artifact #115301 carries proof: sufficient for: the activity goes in via registerMSTeamsHandlers, and the registered Bot Framework onMessage callback drives the inbound path. The earlier direct-invocation file is removed rather than kept alongside — it asserted the same thing from a weaker position.

Unmocked throughout the changed path: the message handler, thread-context.ts, graph-thread.ts, graph.ts. Graph is observed at the fetch boundary.

Why the earlier attempt observed nothing

Worth recording, since it is a trap for anyone writing transport-level tests here. A plain function assigned over globalThis.fetch is silently bypassed:

// src/infra/net/fetch-guard.ts
const isUsingMockedFetch = isMockedFetch(defaultFetch);   // typeof fetchImpl.mock === "object"
…
// Explicit caller stubs and test-installed fetch mocks should win.
// Otherwise, fall back to undici's fetch whenever we attach a dispatcher …
const shouldUseRuntimeFetch = Boolean(dispatcher) && !supportsDispatcherInit;

A vi.fn() carries .mock, so it takes the supported path and sees the request. The seam was already there; I had built the stub wrong.

Result

Channel activity delivered with no replyToId, thread root recoverable only from the conversation id:

[
  "https://graph.microsoft.com/v1.0/teams/00000000-0000-4000-8000-000000000001/channels/19%3Ageneral%40thread.tacv2/messages/1700000000000",
  "https://graph.microsoft.com/v1.0/teams/00000000-0000-4000-8000-000000000001/channels/19%3Ageneral%40thread.tacv2/messages/1700000000000/replies?$top=50"
]

Both reads issued, and the retrieved parent reaches the agent as Replying to @Alice: Can someone investigate the latency spike?. A second case covers the self-reference guard at the same boundary: a root post issues no thread retrieval.

Negative control — threadParentId restored to activity.replyToId, nothing else touched:

× retrieves thread parent and sibling replies for a channel activity without replyToId
  → expected 0 to be greater than 0
✓ issues no thread retrieval when the channel activity is its own thread root
  Test Files  1 failed (1) | Tests  1 failed | 1 passed (2)

Full extension suite on this head: 1556 passed (1556). oxlint and oxfmt clean on the changed files.

{
  "kind": "mock-gateway",
  "verdict": "PASS",
  "liveTeams": false,
  "harness": "extensions/msteams/src/thread-context.mock-gateway.test.ts",
  "channel": "msteams",
  "scenario": "channel-thread-context-without-reply-id",
  "headSha": "68e7bb7d275cf4731e0d5d7e00b3da5fc9eb2a69",
  "gateway": "request-level-mock-gateway",
  "ingress": "registerMSTeamsHandlers -> registered onMessage callback",
  "environment": {
    "node": "v26.8.1",
    "platform": "linux",
    "teamsApi": "Graph observed at the fetch boundary via the supported isMockedFetch seam",
    "delivery": "real registerMSTeamsHandlers + real message handler + real resolveMSTeamsThreadContext + real graph-thread.ts + real graph.ts"
  },
  "inboundActivity": {
    "replyToId": null,
    "conversationId": "19:[email protected];messageid=1700000000000"
  },
  "graphRequestsObserved": [
    "GET /v1.0/teams/{aadGroupId}/channels/19%3Ageneral%40thread.tacv2/messages/1700000000000",
    "GET /v1.0/teams/{aadGroupId}/channels/19%3Ageneral%40thread.tacv2/messages/1700000000000/replies?$top=50"
  ],
  "parentContextReachedAgent": true,
  "siblingRepliesLoaded": true,
  "selfReferenceGuardHolds": true,
  "negativeControl": {
    "revert": "threadParentId = activity.replyToId",
    "graphRequestsObserved": [],
    "parentContextReachedAgent": false,
    "failure": "expected 0 to be greater than 0"
  },
  "fullExtensionSuite": "1556 passed (1556)",
  "secretsRedacted": true
}

One structural note, and a standing offer

The qa msteams lane still cannot reach this branch, and I do not think that is fixable from a scenario. bot-framework-server.ts serves only /v3/conversations/{id}/activities, GRAPH_ROOT is hardcoded in graph.ts with no override, and the QA Gateway runs as a separate process, so an interceptor installed in the CLI process does not apply to it. As it stands no msteams scenario can exercise a Graph-dependent path, which is most of the channel's thread, quote and attachment behavior.

I am happy to fix that in a separate PR — Graph routes on the QA fixture plus the plumbing needed to reach the spawned Gateway — but it needs a maintainer decision, because the only clean ways in touch either the QA runner's process launch or add a base-URL seam to production code. Say which you would accept and I will build it.

check-lint on the previous head failed to a cancelled runner (The runner has received a shutdown signal, with [oxlint:extensions] finished printed after it) — the third on this PR. oxlint and oxfmt pass locally on every changed file. I cannot re-run jobs on a fork PR; this push starts a fresh run.

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Aug 30, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@clawsweeper clawsweeper Bot added merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. labels Aug 30, 2026
…ignatures

Three defects in the proof added by the previous commit, all caught by CI:

- The fetch stub was never restored, so it leaked into sibling suites sharing the
  worker and extensions/msteams/src/qa/bot-framework-server.test.ts began seeing 200
  for requests it expects to reject. An afterEach now restores the ambient fetch.
  The local full-suite run passed only because vitest happened to order the files
  the other way round; running the two files together reproduces it.
- OpenClawConfig was imported from ./runtime-api.js; the module sits one level up.
- The registered onMessage callback takes (context, next, turnAdoptionLifecycle);
  both call sites passed only the context.
@amalysh

amalysh commented Aug 31, 2026

Copy link
Copy Markdown
Contributor Author

Head 8450dcdc982914acd0734bfaa825a9bffb014277. The proof I added in 68e7bb7d had three defects, all correctly caught by CI. Two were signature slips; the third was a real one and worth stating plainly.

The fetch stub was never restored. installGraphFetchMock() assigned globalThis.fetch with no afterEach, so it leaked into sibling suites sharing the worker and extensions/msteams/src/qa/bot-framework-server.test.ts started seeing 200 for requests it expects to reject — the expected 200 to be 401 / to be 504 failures in checks-node-changed-extensions-config. An earlier draft of this file had the restore and I dropped it when reshaping the test around registerMSTeamsHandlers.

My local full-suite run passed and hid it, because vitest ordered the files the other way. Running the two together reproduces it immediately, and that is now the check I use:

$ pnpm vitest run \
    extensions/msteams/src/thread-context.mock-gateway.test.ts \
    extensions/msteams/src/qa/bot-framework-server.test.ts
✓ bot-framework-server > rejects missing per-run credentials
✓ bot-framework-server > parses encoded conversation threads and captures outbound activity
✓ bot-framework-server > models an ambiguous gateway timeout after accepting the marked activity
✓ bot-framework-server > stops accepting requests after cleanup
✓ thread-context mock-gateway proof > retrieves thread parent and sibling replies …
✓ thread-context mock-gateway proof > issues no thread retrieval when … its own thread root
  Test Files  2 passed (2) | Tests  6 passed (6)

The other two: OpenClawConfig was imported from ./runtime-api.js when the module sits one level up, and both call sites passed only the context to a callback typed (context, next, turnAdoptionLifecycle).

The proof itself is unchanged — same two Graph reads for a replyToId-less channel activity, same negative control at zero requests when threadParentId is reverted.

One caveat I would rather declare than have found: I could not run pnpm tsgo:extensions:test locally to completion — it exits 137 under the memory available to me, and tsgo is a native binary so a heap cap does not govern it. I verified both type errors directly instead (the module resolves one level up; the callback arity matches the registration site) and am relying on CI for the full check.

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Aug 31, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@clawsweeper clawsweeper Bot added rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. and removed rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. labels Aug 31, 2026
typescript(no-unnecessary-type-conversion) flagged both call sites: the optional
chain already yields a string once defaulted, so String() changes neither type nor
value. The rule is type-aware, so a bare oxlint run over the single file did not
surface it; only the project shard does.
@clawsweeper clawsweeper Bot removed the merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. label Aug 31, 2026
@amalysh

amalysh commented Aug 31, 2026

Copy link
Copy Markdown
Contributor Author

Head 4a25113aa29cc209b6831703fbd872a48936cbd3. merge-risk: session-state has cleared — that label came from a leaked globalThis.fetch in my own proof file, fixed in 8450dcd, and the rating recovered with it.

Taking the review at its word that the remaining blocker "is contributor real-behavior evidence, not a narrow repair an automated worker can safely supply", so this is the maintainer decision rather than another proof attempt from me.

Why I cannot supply either accepted artifact

An after-fix Teams trace. The deployment where this was found runs the 2026.7.1 plugin line and cannot be moved to a build containing this change: every 2026.7.2-beta.1+ declares compat.pluginApi: ">=<own version>", which a 2026.7.1 host does not satisfy, and additionally requires openclaw/plugin-sdk/html-entity-runtime, absent on that host. I could hand-patch a local plugin and screenshot it, but that is not a deployment trace and I would rather not present it as one.

A complete mock-channel, mock-provider, ephemeral-Gateway verdict reaching the retrieval path. This one is not a limitation of my setup, it is the fixture:

  • extensions/msteams/src/qa/bot-framework-server.ts serves exactly one route family, /v3/conversations/{id}/activities (parseConversationPath). Microsoft Graph is not mocked.
  • graph.ts builds every request from a hardcoded GRAPH_ROOT; there is no base-URL or fetchImpl seam (grep -rniE "GRAPH_BASE|graphBaseUrl|OPENCLAW_MSTEAMS_GRAPH" over extensions/msteams/src returns nothing).
  • The QA Gateway is a separate process, so an interceptor installed in the CLI process does not apply to it.

I did run the lane to confirm it works rather than assuming — openclaw qa msteams --provider-mode mock-openai passes channel-canary, exit 0. It simply cannot enter the channel-only Graph branch, and neither can any scenario written against the current fixture. The same is true for every Graph-dependent msteams path: thread context, quote recovery, attachment retrieval.

What I am offering

I will build the missing coverage if a maintainer says which shape is acceptable, because both clean routes touch something that is yours to decide:

  1. Graph routes on the QA fixture + reach the spawned Gateway. Serve the two thread reads from bot-framework-server.ts, then get the interception into the Gateway process — realistically NODE_OPTIONS --import preload wired by the QA runner.
  2. A narrow production seam. An env-driven Graph base URL that only the QA lane sets. Smaller, but it is production code changed for testability, which I would not add uninvited.

Either lands as a separate PR, not folded into this two-file fix, and unblocks this class of proof for the whole channel rather than just this bug.

Meanwhile

The repair is unchanged since the rebase and has been rated patch quality: 🐚 platinum hermit (4/6) — no actionable review findings on three consecutive reviews. The regression coverage pins the selection rule, the mock-gateway test observes the two Graph reads through the registered handler, and reverting threadParentId alone drops that to zero requests.

One request I cannot action myself: check-lint has now been cancelled four times on this PR — always around the four-minute mark, always The runner has received a shutdown signal with no findings in the log, including the run on this head. oxlint and oxfmt pass locally on every changed file. Fork PRs cannot re-run jobs, and I would rather not push empty commits to re-roll a runner, so if someone with write access can re-run that single job the head is otherwise green.

@amalysh

amalysh commented Aug 31, 2026

Copy link
Copy Markdown
Contributor Author

The review at 09:04 UTC predates my comment at 09:07, so it did not take that into account. That comment states the exact blocker rather than asking for the bar to be lowered: neither accepted artifact is producible from here, and for the mock-gateway one the reason is the fixture rather than my setup — qa/bot-framework-server.ts serves only /v3/conversations/{id}/activities, GRAPH_ROOT is hardcoded with no seam, and the QA Gateway is a separate process, so no scenario can reach the channel Graph branch. I ran the lane to confirm rather than assume: channel-canary passes, exit 0.

AGENTS.md sanctions declaring an infeasible proof with the exact blocker, which is what that comment does, and it carries a concrete offer to add the missing Graph coverage to the fixture as a separate PR once a maintainer picks which shape is acceptable.

Also noting openclaw/ci-gate is red only because check-lint has been cancelled four times on this PR — always The runner has received a shutdown signal, no findings in any of those logs, including on this head. Fork PRs cannot re-run jobs.

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Aug 31, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@amalysh

amalysh commented Aug 31, 2026

Copy link
Copy Markdown
Contributor Author

One of the open items is something I can close: "The Microsoft/Bot Framework payload relationship behind the fallback was not independently contract-checked in this review because the official documentation host was unreachable."

Here is the contract, from Microsoft. It turns out this PR implements their documented recommendation rather than inferring a workaround.

conversation.id carries the thread root

Channel and group chat conversations, on the properties a bot receives in a channel:

conversation.id The reply chain ID, consisting of channel ID plus the ID of the first message in the reply chain.

and under Replying to messages:

In a channel, replying to a message shows as a reply to the initiating reply chain. The conversation.id contains the channel and the top level message ID. Although the Bot Framework takes care of the details, you can cache that conversation.id for future replies to that conversation thread as needed.

The payload example on that page shows the encoding this PR parses:

"conversation": {
  "id": "19:[email protected];messageid=1481567603816"
}

replyToId is explicitly not guaranteed

Missing replyToId in Activity Object – Clarification Required, answering a developer seeing exactly this:

In Microsoft Teams the replyToId field is optional in the Bot Framework schema and Teams often doesn't set it on incoming activities even for thread replies.

It is always omitted for new posts, frequently for replies in Teams channel threads, also for 1:1/group chats (no threading).

So what you are seeing is a normal behavior because replyToId is not guaranteed by channels since Teams commonly omits it.

The recommended fix is what this PR does

The same answer recommends deriving the root from conversation.id and distinguishing a root post from a reply by comparing it against the activity id:

var m = Regex.Match(convId, @";messageid=([^;]+)", RegexOptions.IgnoreCase);
…
bool isRootPost = isChannel && rootId != null && activity.Id == rootId;
bool isReply    = isChannel && rootId != null && activity.Id != rootId;

That is this patch:

const threadRootId = conversationMessageId ?? activity.replyToId;
const threadParentId = threadRootId && threadRootId !== activity.id ? threadRootId : undefined;

conversationMessageId is the already-parsed ;messageid= value, and threadRootId !== activity.id is the same root-post discriminator. So the root-first ordering is not a preference between two equivalent identifiers — the documented one is conversation.id, and replyToId is the one the platform says may be absent. Keeping replyToId as the fallback covers activities whose conversation id carries no thread suffix.

Note the first page is the archived v3 article; it is the clearest statement of the conversation.id contract and the payload shape, and the 2026 support answer above confirms the same behaviour on current Teams.

This does not change the proof position — that remains the maintainer decision described in the review, and my offer to add Graph coverage to the QA fixture still stands. It only closes the contract-check item, since the sources were reachable from here.

@shojikumaru shojikumaru left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Real-setup verification — tested at head 4a25113aa29cc209b6831703fbd872a48936cbd3

Setup: isolated checkout (git fetch origin pull/129345/head), Docker node:26, pnpm install --ignore-scripts, no secrets in env, tests run with --network=none. Linux host.

After (head 4a25113a): node scripts/run-vitest.mjs extensions/msteams/src/monitor-handler/message-handler.thread-parent.test.ts extensions/msteams/src/thread-context.mock-gateway.test.ts → 13/13 passed (34.00s).

Before (merge-base d179dc3e): overlaid only the PR's test files onto the merge-base, same command → 3 failed | 10 passed (both test files failing) — reproducing the base behavior where thread context is dropped when a channel message arrives.

Note: three earlier revisions of this branch also verified clean on the same setup (062fef50: 11/11 after / 2 failed | 9 passed before; b4518acd and 68e7bb7d: 13/13 after / 3 failed | 10 passed before). Re-verified in full each time the branch moved.

Not covered: live MS Teams round-trip (unit-level proof only).

Verified by Sho (human) + Alpha (AI agent) on a real OpenClaw setup. Happy to re-run against a new head if the branch moves.

Carry the canonical conversation root into Graph context retrieval; avoid self-parent reads. Preserve parent and sibling history for channel replies with missing or nested replyToId.

Refs openclaw#129345, openclaw#129344.

Co-authored-by: Alexander Malysh <[email protected]>
@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: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Sep 2, 2026
@steipete

steipete commented Sep 2, 2026

Copy link
Copy Markdown
Contributor

@clawsweeper re-review

The maintainer revision preserves contributor ancestry and uses the routed thread root. The updated body includes four actual ephemeral-Gateway flows through synthetic Graph, provider and Connector HTTP endpoints, the model context excerpt, source/request hashes, and the top-level control.

@clawsweeper

clawsweeper Bot commented Sep 2, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@steipete
steipete merged commit 51b0b03 into openclaw:main Sep 2, 2026
121 checks passed
@steipete

steipete commented Sep 2, 2026

Copy link
Copy Markdown
Contributor

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 2, 2026
…eplyToId (openclaw#129345)

* fix(msteams): thread context is dropped when a channel reply has no replyToId

Teams channel activities frequently arrive without `replyToId`. Thread context
resolution keyed exclusively off that field, so parent-message and sibling-reply
context silently never loaded for those turns and the agent answered without any
of the thread it was replying in.

Fall back to the thread root already parsed from the conversation id. The Graph
message URL builder in `attachments/graph.ts` resolves the same value this way
via `threadRootMessageId`, and `resolveMSTeamsRouteSessionKey` likewise accepts
both, so this aligns thread context with the two adjacent call sites rather than
introducing a new source of truth.

The self-comparison guard keeps a top-level post from being treated as its own
parent, mirroring the `threadRootMessageId !== messageId` check in graph.ts.

Behaviour is unchanged whenever `replyToId` is present.

* fix(msteams): resolve thread context against the conversation thread root

Review follow-up: the fallback chose `replyToId` ahead of the conversation's
embedded thread root, which contradicts the canonical precedence used elsewhere
in the plugin.

`resolveMSTeamsRouteSessionKey` reads `conversationMessageId ?? replyToId`, and
`attachments/graph.ts` resolves the Graph message URL from `threadRootMessageId`
the same way. On a deep reply, where both identifiers are present and differ, the
previous ordering routed the session to the thread root while fetching parent and
sibling context beneath the nested reply — attaching context from one message to
the session of another.

Take the conversation root first and keep `replyToId` as the fallback for
activities whose conversation id carries no thread suffix. The self-comparison
guard is retained so a top-level post is not treated as its own parent, matching
the `threadRootMessageId !== messageId` check in graph.ts.

Adds a handler-level regression covering both identifiers present and different;
it fails under the previous ordering.

* refactor(msteams): tighten the thread-root invariant comment

Condenses the nine-line block to the three-line form used elsewhere in this file,
keeping the two load-bearing facts: why the conversation root wins over replyToId,
and that replyToId remains the fallback. No behavior change.

* test(msteams): prove channel thread retrieval at the Graph boundary

The existing thread-parent tests stub ../graph-thread.js, so they pin the
selection rule but never reach the retrieval boundary the repair actually moves.
This asserts on the HTTP requests the process issues instead: thread-context.ts,
graph-thread.ts and graph.ts all run unmocked, and the only stub is globalThis.fetch.

The stub has to be a vi.fn(). fetchWithSsrFGuard treats a fetch carrying a .mock
property as a test-installed mock (isMockedFetch) and lets it win; a plain function
is bypassed in favour of undici dispatcher-aware fetch, and records nothing.

For a channel activity with no replyToId the process now issues:
  GET /v1.0/teams/{aad}/channels/{channel}/messages/{root}
  GET /v1.0/teams/{aad}/channels/{channel}/messages/{root}/replies?$top=50
and the retrieved parent reaches the agent. With threadParentId reverted to
activity.replyToId that set is empty, so the first assertion fails on zero requests.

* test(msteams): prove channel thread retrieval through the registered handler

Replaces the direct-invocation variant with one shaped after
approval-control.mock-gateway.test.ts: the activity enters through
registerMSTeamsHandlers and is driven by the registered Bot Framework onMessage
callback, so the inbound path runs as registered rather than a handler factory
being called directly.

The message handler, thread-context.ts, graph-thread.ts and graph.ts all run
unmocked; Graph is observed at the fetch boundary. The stub has to be a vi.fn()
because fetchWithSsrFGuard only lets a fetch carrying a .mock property win over
undici dispatcher-aware fetch (isMockedFetch).

For a channel activity delivered without replyToId the process issues:
  GET /v1.0/teams/{aad}/channels/{channel}/messages/{root}
  GET /v1.0/teams/{aad}/channels/{channel}/messages/{root}/replies?$top=50
and the retrieved parent reaches the agent as a system event. With threadParentId
reverted to activity.replyToId neither request is issued.

* fix(test): restore ambient fetch and correct the mock-gateway proof signatures

Three defects in the proof added by the previous commit, all caught by CI:

- The fetch stub was never restored, so it leaked into sibling suites sharing the
  worker and extensions/msteams/src/qa/bot-framework-server.test.ts began seeing 200
  for requests it expects to reject. An afterEach now restores the ambient fetch.
  The local full-suite run passed only because vitest happened to order the files
  the other way round; running the two files together reproduces it.
- OpenClawConfig was imported from ./runtime-api.js; the module sits one level up.
- The registered onMessage callback takes (context, next, turnAdoptionLifecycle);
  both call sites passed only the context.

* fix(test): drop redundant String() conversions in the mock-gateway proof

typescript(no-unnecessary-type-conversion) flagged both call sites: the optional
chain already yields a string once defaulted, so String() changes neither type nor
value. The rule is type-aware, so a bare oxlint run over the single file did not
surface it; only the project shard does.

---------

Co-authored-by: Alexander Malysh <[email protected]>
Co-authored-by: Alexander Malysh <[email protected]>
Co-authored-by: Peter Steinberger <[email protected]>
RomneyDa added a commit that referenced this pull request Sep 29, 2026
* fix(plugins): recover orphan installs without weakening ownership

Closes #134321

## What Problem This Solves

Operators could not run `openclaw plugins update --all` or uninstall a path-source plugin after both tracked plugin paths disappeared. Registry refresh succeeded but left the durable install record behind, so both commands failed on the same ownership check.

## Why This Change Was Made

Plugin lifecycle ownership now distinguishes an active package from an exact orphan record. Update and uninstall may act on an orphan only after duplicate-path and conflicting-plugin checks pass. Inspection, capability consent, active packages, and restored packages keep strict package ownership.

Post-update reconciliation accepts an unchanged safe orphan while another package updates. If an orphan install record changes, the replacement must restore a strictly valid package before any update can commit.

Uninstall removes owner-keyed plugin and channel policy plus the durable install record. Child policy remains based only on authoritative discovered children.

## User Impact

Operators can update their remaining plugins and remove stale path-source install records without editing OpenClaw state by hand. Ambiguous, conflicting, and invalid replacement packages still fail closed.

## Evidence

Current `main` at `77fee957919f06dbaff09dd5cc7f9664d9655651` failed through the real command-line flow after a local plugin was installed and both tracked paths were moved away:

```text
$ openclaw plugins update --all --dry-run
Plugin "orphan-proof" package owner "orphan-proof" has no authoritative runtime child list.
Exit 1

$ openclaw plugins uninstall orphan-proof --force
Plugin "orphan-proof" package owner "orphan-proof" has no authoritative runtime child list.
Exit 1

$ openclaw plugins registry --refresh
Plugin registry refreshed: 0/0 enabled plugins indexed.
Exit 0

$ openclaw plugins update --all --dry-run
Plugin "orphan-proof" package owner "orphan-proof" has no authoritative runtime child list.
Exit 1
```

Exact head `06de2f66734fd338e457f50a3060e2d625288274` passed the same flow:

```text
$ openclaw plugins update --all --dry-run
Skipping "orphan-proof" (source: path).
Exit 0

$ openclaw plugins uninstall orphan-proof --force
Uninstalled plugin "orphan-proof". Removed: config entry, install record.
Exit 0

$ openclaw plugins update --all --dry-run
No tracked plugins or hook packs to update.
Exit 0
```

The contributor head initially accepted a changed orphan install record with no authoritative children. The new owner-boundary regression failed with `{ ok: true }` before the maintainer repair and passes after it.

Validation:

- `node scripts/run-vitest.mjs src/plugins/manifest-registry-installed.test.ts src/plugins/management-service.uninstall-ownership.test.ts src/plugins/plugin-package-update.test.ts src/cli/plugins-cli.update.test.ts src/cli/plugins-cli.uninstall.test.ts` — 129 passed.
- Targeted Oxfmt and Oxlint — passed.
- Max-lines and assertion-safety ratchets — passed.
- Coercion, deprecated-API, dead-export, native-schema, and import-cycle guards — passed.
- `git diff --check` — passed.
- Local type checking was not run because host policy requires CI for OpenClaw type checks.

The proof fixture, isolated states, removed plugin copies, and proof manifest remain in the durable maintainer worktree.

Co-authored-by: Ayaan Zaidi <[email protected]>

* fix(doctor): repair keyed multi-agent rosters without ownership (#134706)

* fix: prevent device pairing migration crash on contaminated records

Closes #134340

## What Problem This Solves

Operators upgrading from the retired JSON device-pairing store can have pending requests or malformed values inside `devices/paired.json`. One bad record aborts the full JSON-to-SQLite import, keeps every valid pairing out of SQLite, and repeats the failed migration on each gateway start.

The pairing migration failure is caught and logged. It does not stop gateway startup by itself. The field report also contained a separate legacy session-store blocker.

## Why This Change Was Made

The migration now validates every field that SQLite binds directly. It skips records with invalid required pairing data. When only optional metadata is malformed, it omits that field and preserves the usable pairing. The original legacy store is archived only after the safe import completes.

Validation includes required timestamps, optional `lastSeenAtMs`, and optional text columns. Separate warnings report skipped records and omitted optional fields. The SQLite mapper remains strict, and no schema or fallback path changes.

## User Impact

Valid device pairings survive an upgrade even when the legacy file also contains pending requests or malformed records. The gateway completes the import once and does not retry it after restart.

## Evidence

- Current-main red at `77fee957919f06dbaff09dd5cc7f9664d9655651`: a normal isolated gateway logged `NOT NULL constraint failed: device_pairing_paired.created_at_ms` for a pending-shaped leaf and retained `paired.json`.
- Anti-cheat red: changing the malformed leaf to `lastSeenAtMs: 1e100` logged `cannot store REAL value in INTEGER column device_pairing_paired.last_seen_at_ms`.
- Regression red on contributor head `ee7ea2bfbc5bde3e1b6f90ea58e4d070b7e7ff61`: the expanded boundary test failed with `Provided value cannot be bound to SQLite parameter 47`.
- Fixed-head boundary proof: `node scripts/run-vitest.mjs src/infra/device-pairing-migration.test.ts` passed 7/7; targeted formatting and Oxlint passed.
- Optional-preservation red on `4f47648f1d6bcf279697d4e8ec5044960bb27cf5`: the corrected regression failed because only one row imported instead of preserving three usable pairings.
- Final real gateway proof: startup returned `status=started`, imported three usable pairings, stored malformed optional metadata as `NULL`, skipped one record with invalid required data, archived `paired.json`, and restarted with no migration log.

Co-authored-by: Ayaan Zaidi <[email protected]>

* fix(doctor): preserve per-agent memory search during upgrades

Closes #134256

Reported by @vdruts.

## What Problem This Solves

Fixes an issue where operators running `openclaw doctor --fix` after an upgrade could silently lose every per-agent memory-search override when Doctor converted `agents.list` to keyed `agents.entries` first. This removed settings such as `extraPaths`, `sources`, `experimental.sessionMemory`, and `enabled`.

## Why This Change Was Made

Doctor now visits both keyed agent entries and legacy list entries at the migration owner. It moves `memorySearch` before unknown-key cleanup, preserves explicit canonical values, and applies the existing provider, nested-field, and retired-path migrations to the moved data.

The shared agent-scope traversal replaces two duplicate traversal implementations. The regression was introduced by #112678, which moved roster normalization before the older list-only migration from #111527.

## User Impact

Per-agent memory-search settings now survive `openclaw doctor --fix` and remain attached to the correct agent. Operators no longer lose per-agent retrieval paths silently during this upgrade path.

## Evidence

- Red on current-main baseline `8abb80073c8648e85d11a0e9bd22b09d1d2bfac2`: [Testbox run 33466170600](https://github.com/openclaw/openclaw/actions/runs/33466170600) removed the legacy block and retained only the pre-existing canonical field.
- Green on exact head `983df6b6ddf33ffad80f32874966ffeeaf0a803f`: [Testbox run 33467597600](https://github.com/openclaw/openclaw/actions/runs/33467597600) ran the real CLI, preserved supported fields and canonical precedence, verified the authored input, and produced byte-identical config on a second Doctor run.
- Regression proof: the strengthened Doctor process test fails on the baseline and passes on the head.
- `node scripts/run-vitest.mjs src/commands/doctor-config-preflight.process.test.ts` — 10 passed.
- `node scripts/run-vitest.mjs src/commands/doctor/shared/legacy-config-migrate.test.ts src/commands/doctor/shared/legacy-config-migrations.runtime.retired.memory-qmd.test.ts src/commands/doctor/shared/legacy-config-migrations.runtime.retired.test.ts` — 294 passed.
- Focused format, Oxlint, Doctor registry, coercion helper, max-lines, assertion safety, import-cycle, temp-directory, conflict-marker, and dead-export checks passed.
- Autoreview on the exact local diff: clean, no actionable P0 findings.

Agent task: https://chatgpt.com/codex/tasks/01a040d7-aa3d-7433-83eb-de7f49979443

Co-authored-by: Ayaan Zaidi <[email protected]>

* fix(doctor): detect shared auth migration by provenance (#134808)

* fix(cron): refuse stale doctor store rewrites

Prevent `openclaw doctor` from replacing cron definitions or runtime-owned state captured before its interactive repair prompt.

Doctor now rechecks a bounded definition-and-order fingerprint inside the SQLite write transaction. Definition changes stop the repair with a retry warning. Runtime columns and current runtime authority remain owned by the Gateway, while repaired authorization-input changes fail closed into recovery.

Preserve old embedded-authority migration and current quarantine recovery.

Co-authored-by: Ayaan Zaidi <[email protected]>

* fix(gateway): refresh model catalog after auth changes (#134361)

* fix(models): refresh catalog content after credential-identity changes

* refactor(agents): split auth-profile mutation lineage out of runtime-snapshots

Split the max-lines boundary by moving persisted mutation lineage out of runtime snapshots; behavior is unchanged.

* refactor(agents): annotate the moved test-api global assertion for the safety ratchet

* test(agents): type the catalog worker mock and shrink the assertion baseline

* perf(agents): bound auth publication provider facts

* perf(gateway): keep auth status off catalog discovery

* fix(agents): reject retired catalog owners

* test(gateway): resolve the auth-status handler result before racing it

* fix(models): gate catalog refresh by read intent

* test(models): prove deferred catalog reads stay static

* test(models): type the unscoped catalog-refresh row context

* fix(openai): repair stale doctor route pins

Declare canonical OpenAI session-route ownership at the OpenAI plugin manifest boundary.

Clear automatic fallback-origin provenance when Doctor removes the stale model override. Preserve explicit model choices and valid locked harness sessions.

Fixes #101672.

Credit @849261680 for the original report-driven repair.

Co-authored-by: Ayaan Zaidi <[email protected]>

* fix(auth): verify shared credential migration receipts (#134952)

Attach expected credential fingerprints to both credential-store receipt
variants so interrupted shared-store imports use the existing verification
and archive recovery flow. State-only receipts retain their own verification.

Regression coverage interrupts archival and removes the destination before
retrying both legacy auth file formats against both SQLite destinations.
The shared-store cases fail before this change; all 90 focused tests pass.

Related to #134608, reported by @erameson. This preserves the existing
non-replay policy for completed receipts; recovery of already-completed
receipts requires a separate maintainer decision.

* fix(cron): keep model aliases scoped to the selected owner (#135069)

Reuse the published model owner metadata for default, agent, subagent, payload, session, and Gmail selections. Consolidate override arguments while retaining agent-specific policy and existing precedence. Six regression cases fail before and pass after; 83 related tests pass. Related: #130324, #130706.

* fix(memory): resolve profile auth for compatible embeddings (#134744)

* fix(memory): resolve profile auth for compatible embeddings

* test(memory): close profile fixture SQLite handles

* fix(memory): preserve credential ownership in embedding auth

Resolve saved profile bindings through the canonical terminal auth capability while preserving literal, blank, explicit-header and destination behavior. Retain general model-auth precedence and shared guard policy; exercise real HTTP, SQLite and public CLI indexing/search. Reuse the canonical doctor CI fixture and repair executable-preflight test isolation.

Co-authored-by: 0x-Parzival <[email protected]>

* fix(memory): preserve auth policy for configured embeddings

Carry the selected provider API into the canonical auth-mode check, so direct OpenAI routes reject saved token profiles before embedding HTTP. Check auth migration readiness before classifying provider-entry credentials, including warm snapshots after a legacy credentials file is restored. Keep explicit remote credentials, literal keys, and canonical SQLite profile ownership intact.

Regression coverage exercises provider/API/credential-mode combinations and cold-empty, warm-empty, and populated canonical stores with real embedding HTTP and SQLite.

Co-authored-by: 0xParzival <[email protected]>

* test(pr): reuse landed cross-checkout fixture

Adopt the exact cross-checkout fixture already landed in main by #134740, resolving the overlapping cleanup while preserving the isolated executable command stubs. The embedding and auth implementation is unchanged.

Co-authored-by: 0xParzival <[email protected]>

---------

Co-authored-by: 0x-Parzival <[email protected]>
Co-authored-by: Peter Steinberger <[email protected]>
Co-authored-by: 0xParzival <[email protected]>

* fix(auth): recover credentials stranded by completed migrations (#135346)

* fix(auth): recover inconsistent completed credential migrations

* test(auth): brace completed receipt recovery branches

* fix(auth): relogin repairs stale profile order after upgrade

Closes #135140

Reported by @mattcbianco.

## What Problem This Solves

Fixes an issue where users who signed in to OpenAI again after shared auth-store relocation could still get `Explicit auth order for openai has no usable profiles.` before a model request started.

## Why This Change Was Made

Login credentials and per-agent profile order have separate SQLite owners after relocation. Profile promotion now reads the effective credential view before it updates the agent-local order, and it preserves the inherited profile ID when it saves that order.

This keeps explicit order fail-closed behavior unchanged. It does not add a dispatch fallback or copy shared OAuth credentials into the agent database.

## User Impact

A successful OpenAI relogin now places the new usable profile before stale entries, so the next `openai/*` model call can start with the login that just succeeded.

## Evidence

- Current-main baseline: `2e3f734017b9b1a5a32ba11d844d1fa7a5141de9`.
- Before: Codex reported a healthy ChatGPT login and OpenClaw listed a healthy OAuth profile, but the selected Codex runtime had no effective profile. Real Luna and Sol turns stopped before provider dispatch with `Explicit auth order for openai has no usable profiles.`
- After: OpenClaw device login stored the fresh OAuth profile, agent-local order became `[fresh, stale]`, and status reported a usable Codex runtime route.
- Live exact-head result: a real `openclaw agent --local` Luna turn returned exactly `ISSUE_135140_EXACT_HEAD_GREEN_2` through provider `openai`.
- Shipped CLI regression: `models auth login --provider openai --agent main` failed on the baseline because local order stayed absent; passed after the fix with `[fresh, stale]`.
- Focused CLI, owner, and sibling tests: 131 passed across login promotion, auth upsert/rollback, shared-store relocation, and runtime auth planning.
- Oxfmt, Oxlint, and `git diff --check`: passed.
- Autoreview P0: clean.

Production delta: `+4/-5` (net `-1`). Test delta: `+108/-0`.

Co-authored-by: Ayaan Zaidi <[email protected]>

* fix(auth): preserve custom provider SecretRefs in Doctor

Fixes #135079.

Thanks @dannevang for the detailed report and two-provider reproduction.

## Problem

After an upgrade, `openclaw doctor` could treat custom-provider environment references and generated catalog values as plaintext API keys. It persisted them as auth profiles, and those profiles could shadow the provider's direct environment credential.

## Root cause

Config substitution discarded the fact that a resolved string came from an authored environment SecretRef. Doctor then classified model catalog strings without the provider's authored resolution facts. Runtime planning and status also treated stored profiles as usable ahead of an unqualified provider SecretRef.

## Fix

- Record resolved environment SecretRef provenance during config substitution.
- Make Doctor keep an authored provider SecretRef authoritative over root and plugin catalogs.
- Remove only persisted profiles whose values exactly match that provider's reference markers.
- Make runtime planning and model status prefer the authored provider SecretRef.
- Reuse the already loaded authored model config during status readback.

The production delta is +122 lines. The added code carries provider-specific pending/resolved provenance across config and worker boundaries and performs exact-value cleanup at the credential-migration owner. A global marker heuristic or downstream guard would not preserve this ownership or safely repair existing rows.

## Proof

- Baseline main `9d10dcb5d39d09be94f48a1bfce1dbfd7a256903`: Doctor migrated two `${VAR}` references plus stale or bare generated values; model status selected stored profiles over fresh direct environment values.
- Exact head `fc74120ab55d071e7c876b2f00c9db47032b8bb8`: Doctor migrated no model credentials, preserved both authored references, left no `authProfiles.store` row, and status selected two distinct environment credentials with zero profiles.
- Main commits after the baseline did not touch any changed file.
- Regression tests were red before the fix and green at the exact head.
- Focused tests, the remote changed-scope gate, and the exact-head remote build passed. The first PR CI run exposed source-authority and max-lines defects; the exact failing tests now pass locally.

Co-authored-by: Ayaan Zaidi <[email protected]>

* fix(docker): install libgomp1 in the runtime image for managed llama.cpp (#134532)

* fix(docker): install libgomp1 in the runtime image for managed llama.cpp

The official ghcr.io/openclaw/openclaw image (bookworm-slim) never
installed libgomp1. The verified llama.cpp release binaries downloaded
by managed local llama-server setup are linked against libgomp, so the
--version preflight probe fails with "libgomp.so.1: cannot open shared
object file", making local embeddings unreachable in the official
Docker image.

Fixes #134439.

* fix(docker): clarify managed llama-server runtime requirement

Keep the mandatory OpenMP runtime in the image and identify its preflight contract in the existing comment and regression test.

Co-authored-by: chelsealong <[email protected]>

---------

Co-authored-by: Peter Steinberger <[email protected]>
Co-authored-by: chelsealong <[email protected]>

* fix(devices): allow authorized scoped node token management (#135617)

* fix(cli): allow authorized node token rotation and revocation

* test(cli): keep token scope fixture indices typed

* test(ui): scope catalog marquee assertions to session rows

* fix(msteams): thread context is dropped when a channel reply has no replyToId (#129345)

* fix(msteams): thread context is dropped when a channel reply has no replyToId

Teams channel activities frequently arrive without `replyToId`. Thread context
resolution keyed exclusively off that field, so parent-message and sibling-reply
context silently never loaded for those turns and the agent answered without any
of the thread it was replying in.

Fall back to the thread root already parsed from the conversation id. The Graph
message URL builder in `attachments/graph.ts` resolves the same value this way
via `threadRootMessageId`, and `resolveMSTeamsRouteSessionKey` likewise accepts
both, so this aligns thread context with the two adjacent call sites rather than
introducing a new source of truth.

The self-comparison guard keeps a top-level post from being treated as its own
parent, mirroring the `threadRootMessageId !== messageId` check in graph.ts.

Behaviour is unchanged whenever `replyToId` is present.

* fix(msteams): resolve thread context against the conversation thread root

Review follow-up: the fallback chose `replyToId` ahead of the conversation's
embedded thread root, which contradicts the canonical precedence used elsewhere
in the plugin.

`resolveMSTeamsRouteSessionKey` reads `conversationMessageId ?? replyToId`, and
`attachments/graph.ts` resolves the Graph message URL from `threadRootMessageId`
the same way. On a deep reply, where both identifiers are present and differ, the
previous ordering routed the session to the thread root while fetching parent and
sibling context beneath the nested reply — attaching context from one message to
the session of another.

Take the conversation root first and keep `replyToId` as the fallback for
activities whose conversation id carries no thread suffix. The self-comparison
guard is retained so a top-level post is not treated as its own parent, matching
the `threadRootMessageId !== messageId` check in graph.ts.

Adds a handler-level regression covering both identifiers present and different;
it fails under the previous ordering.

* refactor(msteams): tighten the thread-root invariant comment

Condenses the nine-line block to the three-line form used elsewhere in this file,
keeping the two load-bearing facts: why the conversation root wins over replyToId,
and that replyToId remains the fallback. No behavior change.

* test(msteams): prove channel thread retrieval at the Graph boundary

The existing thread-parent tests stub ../graph-thread.js, so they pin the
selection rule but never reach the retrieval boundary the repair actually moves.
This asserts on the HTTP requests the process issues instead: thread-context.ts,
graph-thread.ts and graph.ts all run unmocked, and the only stub is globalThis.fetch.

The stub has to be a vi.fn(). fetchWithSsrFGuard treats a fetch carrying a .mock
property as a test-installed mock (isMockedFetch) and lets it win; a plain function
is bypassed in favour of undici dispatcher-aware fetch, and records nothing.

For a channel activity with no replyToId the process now issues:
  GET /v1.0/teams/{aad}/channels/{channel}/messages/{root}
  GET /v1.0/teams/{aad}/channels/{channel}/messages/{root}/replies?$top=50
and the retrieved parent reaches the agent. With threadParentId reverted to
activity.replyToId that set is empty, so the first assertion fails on zero requests.

* test(msteams): prove channel thread retrieval through the registered handler

Replaces the direct-invocation variant with one shaped after
approval-control.mock-gateway.test.ts: the activity enters through
registerMSTeamsHandlers and is driven by the registered Bot Framework onMessage
callback, so the inbound path runs as registered rather than a handler factory
being called directly.

The message handler, thread-context.ts, graph-thread.ts and graph.ts all run
unmocked; Graph is observed at the fetch boundary. The stub has to be a vi.fn()
because fetchWithSsrFGuard only lets a fetch carrying a .mock property win over
undici dispatcher-aware fetch (isMockedFetch).

For a channel activity delivered without replyToId the process issues:
  GET /v1.0/teams/{aad}/channels/{channel}/messages/{root}
  GET /v1.0/teams/{aad}/channels/{channel}/messages/{root}/replies?$top=50
and the retrieved parent reaches the agent as a system event. With threadParentId
reverted to activity.replyToId neither request is issued.

* fix(test): restore ambient fetch and correct the mock-gateway proof signatures

Three defects in the proof added by the previous commit, all caught by CI:

- The fetch stub was never restored, so it leaked into sibling suites sharing the
  worker and extensions/msteams/src/qa/bot-framework-server.test.ts began seeing 200
  for requests it expects to reject. An afterEach now restores the ambient fetch.
  The local full-suite run passed only because vitest happened to order the files
  the other way round; running the two files together reproduces it.
- OpenClawConfig was imported from ./runtime-api.js; the module sits one level up.
- The registered onMessage callback takes (context, next, turnAdoptionLifecycle);
  both call sites passed only the context.

* fix(test): drop redundant String() conversions in the mock-gateway proof

typescript(no-unnecessary-type-conversion) flagged both call sites: the optional
chain already yields a string once defaulted, so String() changes neither type nor
value. The rule is type-aware, so a bare oxlint run over the single file did not
surface it; only the project shard does.

---------

Co-authored-by: Alexander Malysh <[email protected]>
Co-authored-by: Alexander Malysh <[email protected]>
Co-authored-by: Peter Steinberger <[email protected]>

* fix(ui): ignore tool-only model auth rows (#134218)

* fix(ui): ignore tool-only model auth rows

* fix(ui): ignore tool-only model auth rows

* fix(ui): ignore tool-only model auth rows

* fix(ui): ignore tool-only model auth rows

* fix(ui): preserve model accounts when filtering tool credentials

Use canonical monitored-auth evidence for Model Providers cards. Preserve
OAuth and non-expiring token profiles, alias logout targets, configured
models and usage while omitting tool-only API-key rows. Remove duplicate
usage-presence bookkeeping.

Refs #134218. Production LOC -3; tests +56.

Co-authored-by: wantosure <[email protected]>

* test(ui): assert usage failures without provider cards

Replace the stale OpenAI-card readiness wait with the visible usage
failure outcome and assert that an unconfigured provider stays absent.
Preserve the RPC assertion and all configured-provider sibling cases.

Refs #134218. Production unchanged; test LOC net zero.

Co-authored-by: wantosure <[email protected]>

---------

Co-authored-by: Peter Steinberger <[email protected]>
Co-authored-by: wantosure <[email protected]>

* fix(cron): kind change fails with "command env must be an object" when env is omitted (#134639)

* fix(cron): omit undefined payload fields

* fix(cron): preserve valid payload kind conversions

Omit absent optional payload fields at the replacement producer and remove
unreachable same-kind fallback branches. Keep strict validation and cover
actual service persistence, malformed env, and tool restrictions.

Co-authored-by: Solomon Neas <[email protected]>

---------

Co-authored-by: Peter Steinberger <[email protected]>
Co-authored-by: Solomon Neas <[email protected]>

* fix(backup): exclude workspaces before traversal

Carry disabled workspace roots into the shared backup inventory before tar and SQLite traversal. Preserve nested agent state and keep absolute-link rejection for included content.

Fixes #135218. Supersedes #135243 and #133990.

Thanks @jarvismazz and @yubingjiaocn for the reports. Thanks @ericcaiwx-star and @ruel225 for the original repair work.

Co-authored-by: ericcaiwx-star <[email protected]>
Co-authored-by: Ayaan Zaidi <[email protected]>

* fix(infra): drop empty PATHEXT entries from Windows extension lookup (#135807)

* fix(infra): drop empty PATHEXT entries from Windows extension lookup

resolveWindowsExecutableExtensions split PATHEXT on ";" without dropping
empty components. A trailing ";", which is common in real PATHEXT values,
leaves "" in the list, so an extensionless file matches even when the
caller passed includeExtensionless: false. windows-command.ts and tui.ts
both pass false.

The sibling resolveWindowsExecutableExtSet in the same file already
filters, so this was just the one path missing it.

* fix(infra): reuse normalized Windows executable extensions

Keep extensionless command lookup explicit by sharing the existing PATHEXT parser. Remove duplicate parsing and cover empty suffixes, explicit filenames, and the command-resolution caller.

Co-authored-by: Teddy Tennant <[email protected]>

---------

Co-authored-by: Peter Steinberger <[email protected]>
Co-authored-by: Teddy Tennant <[email protected]>

* fix(anthropic): context usage is lost when a proxy omits message_delta usage (#135467)

* fix(anthropic): keep context usage when message_delta omits usage

The Anthropic SDK lane guarded the shared usage accumulator against an omitted
message_delta usage object; the managed transport lane called it unconditionally,
where the payload ?? {} fallback overwrote the message_start prompt snapshot with
contextUsage: unavailable. Anthropic-compatible routes whose provider is not
"anthropic" are forced onto that transport, so the population the guard was written
for never had it.

Move the presence check into the accumulator that owns the payload contract and drop
the duplicated guard in the SDK lane, so both lanes follow one rule. A present but
empty usage object still resolves to unavailable, matching the previous SDK check.

* test(anthropic): assert delta context usage through the usage object

expect(usage.contextUsage) narrowed to the object literal returned by the local
emptyUsage helper, which does not declare contextUsage, so the core test-types
stripe rejected it. Read it through toMatchObject like the neighboring cases.

---------

Co-authored-by: Peter Steinberger <[email protected]>
Co-authored-by: Yigtwxx <[email protected]>

* fix(systemd): protect credentials in managed backups (#131786)

Sanitize and privatize managed unit backups, restore them atomically on publication failure, surface unsafe remnants, and remove them across uninstall paths.

Closes #131781. Supersedes #131784.

Co-authored-by: vyctorbrzezowski <[email protected]>

Worked on by:
- @vyctorbrzezowski

* fix(agents): preserve requester MCP runtime ownership (#134819)

## What Problem This Solves

Requester-scoped MCP resolution can own serialized work for a runtime key while that runtime has no lease. Idle or cap cleanup could dispose the runtime and its transport before the work finished.

## Why This Change Was Made

The lifecycle owner now treats the existing requester work chain as active ownership. Idle cleanup skips that key, and cap cleanup does not queue an eviction behind that work. Required session disposal still drains the same chain.

## User Impact

Requester-scoped MCP transports and sessions now survive resolver work. Normal idle cleanup still removes the runtime after that work drains.

## Evidence

- Current-main loopback reproduction: the production manager returned one idle eviction while requester resolution was held; expected zero.
- Exact candidate loopback proof: the shipped harness runtime retained the same runtime object and MCP session identifier through the protected sweep, then the later idle sweep removed the runtime and closed the session.
- Cap regression: the original PR head disposed the refreshed requester runtime; the repaired head preserved it.
- [Exact-head agent shard](https://github.com/openclaw/openclaw/actions/runs/33675253407/job/100398989009): 89 files and 1,395 tests passed, including the real loopback boundary.
- Formatting and `git diff --check`: passed.
- Exact-head Autoreview P0: clean.

## Proof Boundary

The proof uses the production MCP runtime manager, the pinned MCP SDK 1.30.0 client and server, and a real loopback Streamable HTTP session. It does not claim external MCP service or provider authentication behavior.

Co-authored-by: Ayaan Zaidi <[email protected]>

* fix(plugins): refresh persisted registry when source mounts change (#136517)

* fix(plugins): retain mounted source ownership through loading and restart

* ci: refresh checks against current main

* fix: gateway restart hangs while followup drain retries a draining error (#136713)

Closes #136684

## What Problem This Solves

Fixes an issue where operators restarting a Gateway with a queued follow-up could wait several minutes for shutdown. The queued turn retried after restart admission rejected it, so the old Gateway stayed active until its shutdown deadline.

## Why This Change Was Made

The follow-up queue now follows the existing one-way restart signal. When restart drain commits, it retires process-local queue work and its old callback before the Gateway inspects active work. A reversible restart-signal fence still waits for settlement and retries after rollback.

Durable accepted-input recovery remains the restart owner. The old in-memory queue and execution authority do not cross restart, as documented in `docs/gateway/restart-recovery.md`.

## User Impact

A Gateway with a queued follow-up can finish a supervised restart on the normal shutdown path instead of emitting a retry burst until forced termination. If restart signal admission rolls back, the queued follow-up resumes normally.

## Evidence

Current-main red at `3100ba535f1d003d67a6a7536deacf8666367b38`:

- Blacksmith child-Gateway run: https://github.com/openclaw/openclaw/actions/runs/33711422936
- One held model turn, one confirmed queued same-session follow-up, then `SIGTERM`.
- Queued case reached the real follow-up admission path and emitted `7` `followup queue drain failed` events.
- No-queue control emitted `0` drain failures.

Exact repaired tree at `2baff4f9ed3f84dc9493149dcc20fed441c9baea`:

- Blacksmith exact-tree run: https://github.com/openclaw/openclaw/actions/runs/33714572460
- The same child-Gateway scenario emitted no retry burst and exited in `3.465s`.
- `src/auto-reply/reply/queue.drain-restart.test.ts`: `29` passed.
- `test/gateway-queued-session-rotation.e2e.test.ts`: `2` passed.
- Materialized source hashes matched the local commit on https://github.com/openclaw/openclaw/actions/runs/33715159753.
- Type-aware Oxlint passed on all touched files.
- Oxfmt and `git diff --check` passed.

The focused tests also cover:

- a typed draining error while restart admission stays open;
- restart-signal rollback and queue resume;
- restart-signal promotion to one-way drain;
- synchronous retirement of queued turn ownership and stale callbacks.

Production LOC: `+33/-2` (net `+31`). The growth binds queue authority to the existing restart signal and closes the user-visible shutdown lifecycle gap. Tests: `+316/-0`.

## AI Assistance

AI-assisted repair. The contributor's original restart-fence distinction and credit are preserved. Maintainer follow-up added the real Gateway reproduction, lifecycle retirement, and exact-head proof.

Co-authored-by: Cursor <[email protected]>
Co-authored-by: Ayaan Zaidi <[email protected]>

* fix(auth): preserve OAuth metadata during session SDK refresh (#127988)

The shipped agent sessions SDK replaced a persisted OAuth credential with the provider refresh result. Providers such as Anthropic return only rotated token fields, so the write removed identity and plan metadata.

Merge the locked stored credential beneath the provider result at the session AuthStorage persistence boundary. Rotated tokens still win, while omitted persisted fields survive.

Tests:
- Published `openclaw/plugin-sdk/agent-sessions` path with real SQLite-backed AuthStorage refresh: red on current main, green on the repaired head.
- `node scripts/run-vitest.mjs src/agents/sessions/auth-storage.test.ts`: 23 passed.
- Focused formatting, lint, and diff checks passed.

Co-authored-by: Ayaan Zaidi <[email protected]>

* fix(doctor): recognize configured memory provider secret references (#137782)

Recognize structured provider SecretRefs at Doctor's mapped-provider credential-presence boundary without resolving secret bytes or accepting empty environment markers.

Preserve missing-key warnings for absent credentials and preserve the live Gateway's owner-specific unresolved-secret diagnostics.

Verified with the real doctor command on baseline main and the exact candidate: provider-owned and remote-memory references, absent keys, bare markers, and two live unresolved-reference controls. All 102 focused tests pass. Synthetic credentials were used with container networking disconnected; no provider authentication is claimed.

Closes #137742.

Co-authored-by: Ayaan Zaidi <[email protected]>

* fix(sessions): preserve logical shared-store ownership (#138380)

* fix: full-access tasks lose tools after Gateway restart (#138701)

* fix: preserve full access when continuing interrupted tasks

* test: exercise full-access continuation across a live restart

* fix: retain replay safety beyond the recent transcript window

* test: make live restart checkpoints suspend explicitly

* fix: keep unchanged files out of session diffs (#138877)

* fix(auth): recover billing-disabled profiles in minutes instead of hours (#136364)

Reduce the initial billing-disable window from five hours to ten minutes for stored auth profiles and inline API keys. Inline keys become eligible after expiry; another billing failure starts a new ten-minute window. Stored-profile recovery probes and already-active persisted deadlines remain unchanged.

Correct the recovery-policy documentation and source comment. Verified with 598 focused auth/fallback tests and docs checks on Cloudflare, real SQLite persistence and eligibility proof, independent review, and successful CI on c44f81187bd745c70b23a360fe15496c40251bf9. Live provider recharge was not exercised; the maintainer accepted that documented proof limitation.

Fixes #135835. Thanks @holny.

Co-authored-by: holny <[email protected]>
Co-authored-by: Altay <[email protected]>

* fix(auth): keep an unset default model unchanged during login (#139218)

Preserve an absent default model during ordinary provider login, just as existing model values are preserved. Remove only the provider-injected default while keeping connection settings, aliases, and credentials.

Keep --set-default as the explicit model-selection action. Extend the existing command regression across supported model shapes.

Related: #136257

Co-authored-by: Ayaan Zaidi <[email protected]>

* fix(gateway): avoid crashes when an upgrading client disconnects (#139061)

* fix(gateway): avoid crashes during interrupted upgrades

* test(gateway): bound upgrade regression websocket payloads

* fix(shell-env): preserve CLI terminal ownership during login imports (#139308)

Start the shared login-shell probe in a separate session so interactive Bash cannot take the CLI's controlling terminal. Preserve interactive startup exports and existing filtering, framing, timeout, executable lookup, and cache behavior.

Verified the current-main Doctor SIGTTOU failure and candidate completion using the built CLI in a real job-control terminal. Added a real-Bash startup regression and verified JSON output, imported keys, terminal restoration, and timeout behavior.

Closes #139257.

Co-authored-by: Ayaan Zaidi <[email protected]>

* fix(auto-reply): fold trailing transcript growth into memory-flush fresh totals (#138928)

* fix(auto-reply): fold trailing transcript growth into memory-flush fresh totals

runMemoryFlushIfNeeded persisted totalTokensFresh=true using only the last
provider usage anchor, ignoring messages appended after it. A later
preflight compaction check trusts totalTokensFresh and skips re-reading the
transcript, so real growth after the anchor could silently escape both the
early memory-flush trigger and the blocking compaction gate.

Project trailing messages the same way runSessionCompactionIfNeeded already
does before persisting the total as fresh.

* refactor(auto-reply): share anchor-plus-trailing prompt token calc

Memory flush duplicated the anchor-plus-trailing-projection calculation
that preflight compaction (estimatePromptTokensFromSessionTranscript)
already used. Extract resolveAnchoredPromptTokens() and have both call
sites use it, so the two calculations can no longer drift.

* fix(auto-reply): share fresh usage projection without duplicate accounting

Include transcript growth after the latest provider usage report before
memory maintenance saves a fresh total for preflight compaction. Reuse the
existing provider-visible estimator and canonical freshness validation,
removing the extra wrapper and redundant freshness check.

Related: #138871
Co-authored-by: chelsealong <[email protected]>

---------

Co-authored-by: Peter Steinberger <[email protected]>
Co-authored-by: chelsealong <[email protected]>

* fix(cron): preserve pending paced checks across restart (#140083)

Let the shared missed-slot decision honor the accepted future paced
occurrence before startup admission or backoff repair can replace it.
Keep ordinary unpaced and overdue catch-up behavior unchanged.

* fix(daemon): systemd install no longer aborts on "ownership could not be verified" after a clock step (#137253)

Replace wall-clock deadline arithmetic with `performance.now()` for systemd ownership probes, definition mutation, effective-manager reads, and legacy metadata refresh.

This preserves the existing shared timeout budgets, fallback behavior, and fail-closed ownership checks while preventing NTP, resume, or manual clock steps from collapsing later calls to the 1 ms floor or inflating them beyond the configured budget.

Regression coverage exercises forward and backward wall-clock steps across all four deadline owners. Exact-head CI, Workflow Sanity, independent P0/P1 review, and the durable ClawSweeper review passed.

Co-authored-by: coderdailyone <[email protected]>

* fix(config): apply environment changes after in-process restart (#141296)

## What Problem This Solves

Fixes an issue where users could update or remove a configured environment value after an in-process Gateway restart, but the process kept using its old value. A full process restart applied the saved configuration correctly.

## Why This Change Was Made

Snapshot cleanup discarded environment ownership without removing the values it owned. The next startup could then mistake those surviving values for inherited environment settings. Keep that ownership through snapshot cleanup, fence old rollback transactions, and retain explicit full-reset behavior.

## User Impact

Accepted configuration changes can replace or remove their environment values after restart. Inherited environment values keep their precedence, and config-selected paths remain stable.

## Evidence

- A real Gateway using main dcc68718f57e196bef10a07178fc8061b896140c accepts a replacement after a successful same-process restart, but public config.get still resolves the old value despite matching new applied/config revisions.
- On c7b393e10286b8b43c316cc7229f3bca94786493, the real Gateway completes restart, replacement, and removal. Public reads return the new value after replacement and the normal unresolved placeholder after removal. The inherited control stays unchanged throughout. Both config writes and final shutdown exit 0.
- Both runs use the real source CLI entry with synthetic config and normal token authentication. The candidate uses the Gateway's existing signed-device WebSocket client for public reads and the normal config set/unset CLI for writes. Complete private command, response, lifecycle, source, and resource receipts are retained. The interrupted baseline removal read is not claimed as proof.
- All 58 focused tests pass across runtime-snapshot.env.test.ts, config.env-vars.test.ts, and runtime-snapshot.test.ts. Controls cover late rollback, ambient precedence, aliases, casing, blocked variables, and explicit reset. Pinned formatting and focused lint pass.
- [Required CI passed](https://github.com/openclaw/openclaw/actions/runs/34136580481) on the exact candidate. No provider call or local build was needed for this proof.

Co-authored-by: Ayaan Zaidi <[email protected]>

* fix: pasted text is missing in model-locked Codex sessions (#142021)

* test(models): consolidate runtime policy matrix

* test(models): extract registry fixtures to satisfy lint

* fix: deliver pasted text to model-locked harness sessions

* fix(docker): restore source builds after dependency ownership guard (#142073)

* fix(docker): restore source builds after dependency ownership guard

* fix(docker): preserve existing lifecycle copy prefix

* fix(security): preserve existing WhatsApp group allowlists (#142589)

* fix(doctor): avoid installing unselected search providers (#142640)

Respect a normalized explicit web-search provider during plugin repair.
Only derive search plugin candidates from environment credentials when
no provider is selected, retaining independent plugin configuration.

Cover selection normalization, environment-only discovery, and existing
plugin disable and deny controls at the repair boundary.

* fix(doctor): migrate legacy Codex music model selectors (#143235)

Doctor left a legacy music selection such as `openai-codex/gpt-5.4` unchanged after `doctor --fix`. Its media selector scan and repair covered image and video but omitted music.

Include music in both existing loops. Doctor now reports the affected setting and saves eligible references under `openai`, using the same primary/fallback handling and provider blockers as the other media selectors.

Validation:

- Required CI passed on `51f0f308`: [run 34372705782](https://github.com/openclaw/openclaw/actions/runs/34372705782).
- Actual CLI proof reproduced the saved-state failure on baseline build `006aaacc` and verified the fix on candidate merge build `0b17e570`, which contains this PR head.
- Scalar and structured selectors passed repair, public config readback, and repeated repair. Suffixes, fallback order, explicit metadata, and canonical/custom references stayed intact.
- Non-interactive Doctor preview named the music setting without changing saved configuration. A blocked legacy provider retained its selection and authored settings while an eligible fallback migrated.
- All six regression cases passed in [the required CI job](https://github.com/openclaw/openclaw/actions/runs/34372705782/job/102537913364). They cover both legacy aliases, selector shapes, provider/model blockers, and agreement with image/video. The native pre-commit hook passed for all three files.

This completes the music-specific omission left after #142284. Proof uses synthetic configuration and covers stored references; it makes no live generation or authentication claim.

Co-authored-by: Ayaan Zaidi <[email protected]>

* fix(doctor): preserve selected model metadata in diagnostics (#144332)

Keep active tool schema diagnostics on the primary model already selected
from manifest aliases. A second alias pass could use another model's
context window while labeling the tools with the selected model ID.

The regression reproduces middle selecting final's 4096-token context
instead of its own 32000-token context.

Related: #130706

* fix(discord): report parent channel denies for thread permissions (#121144)

* fix(discord): use parent permissions for thread diagnostics

Punchcard-Session: brisk-lantern-meadow-g5

* test(discord): preserve voice send diagnostics

* fix(discord): keep send diagnostics operation-specific

* fix(discord): share thread channel classification

* fix(config): avoid false model changes when saving settings (#144807)

* fix(doctor): preserve legacy registry files when quarantine fails (#144787)

Closes #144773

## What Problem This Solves

Doctor could delete malformed legacy sandbox registry data after its quarantine rename failed, then report a quarantine location that had not received the bytes. Both container and browser registry repair used the same failure path.

## Why This Change Was Made

The existing quarantine owner now reports success only after rename succeeds. It preserves the source and propagates other rename errors; a source that disappears maps to the existing missing result. Doctor retains its normal warning handling for this optional repair.

The regression cases now share the existing migration fixture and real SQLite writers. The separate mocked-writer fixture is removed, and the successful-quarantine test verifies the actual destination bytes.

## User Impact

Failed quarantine leaves the malformed bytes available for manual repair and reports the failure. Valid migration, existing SQLite rows, sharded precedence, read-only inspection, empty/missing inputs, and maintenance ownership retain their contracts. This changes no schema, configuration, retention policy, dependency, or overall Doctor exit policy.

## Evidence

Pinned main `1d4afe39664428308a2c71a64c94dea7b607bc0a` was exercised through the built public `openclaw doctor --fix --non-interactive` command in isolated offline state. For each registry kind, a real nonempty destination directory caused `rename` to return `EISDIR`; the source was then unlinked and Doctor reported successful quarantine. Original synthetic input and destination bytes were preserved independently.

The corrected source was independently exercised through the same public repair for both registry kinds. The native filesystem trace still records `EISDIR`, but the source and existing destination remain byte-for-byte intact, and Doctor reports:

```text
doctor:sandbox run failed: EISDIR: illegal operation on a directory,
```

| Before | After |
| --- | --- |
| Failed rename was followed by source deletion and a successful-quarantine claim. | Failed rename preserves both inputs and reports failure without claiming quarantine. |
| The claimed destination had not received the malformed bytes. | After resolving the owned collision, repair moves the identical bytes to the reported file; a repeat leaves the result unchanged. |

Independent acceptance also verified real-clock quarantine, registered read-only lint, empty/missing inputs, and real SQLite migration with existing-row conflicts and mixed valid/invalid shards. Whole canonical rows, including JSON and update timestamps, remained unchanged; canonical rows take precedence over shards, and shards over monolithic input. No database writer was mocked in this public proof.

An initial fixture reused an old fixed timestamp and was correctly refused by maintenance before reaching quarantine. Its failed and prematurely batched dependent steps are retained. The corrected fixture uses a contemporaneous timestamp and stops dependent actions on nonzero repair exit. Product leases, workers, permission checks and deadlines were unchanged. The original baseline proof remains valid and was not replayed.

The consolidated regressions produced the intended four failures on baseline. All 34 focused tests across three files pass with the repair. Native formatting, syntax lint, line-size and assertion-safety checks, and the complete runtime/UI artifact build passed. Full type checks and broad suites remain hosted. The tested source tree matches published head `84dffef7a099a9918fd08ae63993dfef4df788d9`; signing changed no runtime input. The retained build keeps its original pre-signing stamp.

The source-disappearance test is a deterministic filesystem-spy primitive, not a public concurrent-process claim. No host-power-loss or elapsed lease-expiry behavior is claimed. Complete private proof and failure history are retained; publication omits account and infrastructure details.

Thanks @Alix-007 for the original repair and regression coverage.

Co-authored-by: Ayaan Zaidi <[email protected]>

* fix: retain route ownership while discovering conversations (#146927)

* fix(install): preserve runtime links when Node validation fails (#147221)

* fix(install): preserve runtime links when Node validation fails

* fix(install): preserve relative runtime targets and empty aliases

* test(install): preserve runtime fixture tuple types

* fix: doctor reports missing OAuth dir for channel config with no installed plugin (#147888)

Doctor no longer reports a missing OAuth directory or offers to create credentials storage solely because leftover channel configuration requests pairing for an unavailable plugin. Reuse the existing effective installed-plugin set in the state-integrity check, while preserving CRITICAL diagnostics and repair prompts for installed pairing plugins and explicit OAuth-directory overrides.

The missing-plugin regression fails with the production change reverted and passes after restoration. The complete state-integrity test file passes all 30 tests, including an explicit installed-Telegram CRITICAL assertion; exact-head CI is green.

Fixes #147772.

Thanks @zhangguiping-xydt for the implementation.

Co-authored-by: Peter Steinberger <[email protected]>

* fix(doctor): stopped private inputs replay after session repair (#148625)

* fix(doctor): retain private input receipts during canonical repair

* test(doctor): use lint-safe receipt rekey expectation

* fix(channels): settle task-scoped context leases once (#148922)

* fix(push): normalize malformed proxy auth errors (#149112)

* fix(cron): reject invalid stagger before silent schedule changes (#151740)

Closes #146446

## What Problem This Solves

Fixes raw Gateway cron requests reporting success after silently discarding an invalid explicit `staggerMs`, substituting a default or retaining the previous value while other requested changes commit.

## User Impact

Invalid explicit stagger values now return `INVALID_REQUEST` before creating or updating a job. This includes explicit `null`: the existing schedule schema permits an optional integer, not a nullable value. Supported integer strings, zero, numeric flooring/clamping, omitted values, and ordinary CLI duration parsing retain their behavior. No operator migration is required; Doctor's existing legacy schedule repair is unchanged.

## Why This Change Was Made

The shared schedule normalizer rejects an invalid authored value before create defaults or update retention erase it. The fix uses the existing parser and request-error boundary rather than broadening the parser or adding a second validation policy. Non-cron schedules still discard stale stagger fields.

## Evidence

The authenticated comparison used Linux arm64 and Node 24.19.0, with registered `openclaw gateway call` commands, a task-only token, actual Gateway handlers, and SQLite readback. Baseline: `bef4c20d45bdd23c3557eb71962f908c691a7ed6`. Candidate: that same main revision plus this PR's two-file delta from `f9be3cb73438f6f68c4ead73103d413564398210`—not an execution of the full original PR checkout.

| Request | Baseline | Candidate |
| --- | --- | --- |
| Hourly add with `"1e3"` | Success; stored `300000` | `INVALID_REQUEST`; no mutation |
| Non-hourly add with `"1e3"` | Success; stagger omitted | `INVALID_REQUEST`; no mutation |
| Rename/update with `"42.8"`, same expression | Success; rename committed and previous stagger retained | `INVALID_REQUEST`; no mutation |
| Rename/update with `"42.8"`, changed expression | Success; rename/expression committed with default stagger | `INVALID_REQUEST`; no mutation |

For each rejected candidate request, all cron-table rows and authenticated views remained unchanged. All 20 expected-observation checks passed on each side, including integer strings, numeric/string zero, omitted add/update behavior, numeric floor/clamp, non-cron stale fields, explicit `null`, and a wrong-token control. Physical candidate restart preserved authenticated `cron.get` responses and complete serialized cron-table values.

Five focused files passed **167 tests**, covering normalization, stagger behavior, persisted schedules, and Doctor legacy schedule repair. With the original normalizer and the same regression tests, **8 failed and 95 passed**, demonstrating the invalid-input regression. Doctor coverage is focused-test evidence, not a published-updater upgrade test.

The initial fixture attempts are not product failures: the first stopped before mutation checks because native Workshop monitors were enabled in the fixture. Baseline restart initially compared `cron.list` projections with `cron.get` and then compared SQLite null-prototype records with JSON objects. Retained same-API responses and exact serialized row values confirmed persistence without replay; the failed fixture results remain retained.

During the completed comparison, scheduling and all jobs stayed disabled; native Workshop monitor rows were retained disabled. No scheduling timers, jobs, provider requests, channel delivery, or execution-delay measurement were exercised.

Existing hosted CI is not all green: [run 35338846156](https://github.com/openclaw/openclaw/actions/runs/35338846156) reports websocket transcript-event timeouts in `session-message-events.test.ts` in `checks-node-compact-large-4`, with the aggregate CI gate failing. No CI replay or unrelated repair is included in this PR.

Co-authored-by: Ayaan Zaidi <[email protected]>

* fix(cli): keep model validation out of session execution (#154763)

* fix(agents): treat empty credential environment variables as unresolved (#155558)

Closes #153484

## What Problem This Solves

The session credential resolver returned the environment variable name when the variable existed but was empty.

## Why This Change Was Made

Distinguish a present empty variable from an absent variable in cached and uncached resolution. Empty values remain unresolved; non-empty variables override literals; absent names retain literal fallback.

## User Impact

SDK consumers of `openclaw/plugin-sdk/agent-sessions` no longer receive the variable name as credential/header material for an explicitly empty variable. Required headers use the existing resolution error. This is verified SDK hardening, not a claim that normal CLI provider headers use this resolver.

## Evidence

- Exercised the built public `ModelRegistry` export with an authored models.json provider header. The export is present in release v2026.9.5. Before the fix, empty returned the variable name; after the fix, it returned the existing failed-to-resolve-header error.
- Non-empty resolved the synthetic value; unset preserved the literal name. Repeated after integrating current main.
- Focused resolver suite: six tests passed; command wall 14.43s including worker preparation, test cases 15ms total.
- Simplification kept the two existing resolver owners and corrected the absent-variable test to exercise the deliberately unset name. No new abstraction/config/schema.
- CLI models probes and local agent requests were also inspected but use a different header path; they are not evidence for this fix.

## Compatibility

Shell command resolution and unset-name literal fallback are unchanged.

Co-authored-by: Ayaan Zaidi <[email protected]>

* fix(doctor): apply ambient-owner fallback to dream diary and all memory target handlers (#156437)

Apply the existing ambient-owner fallback in the shared Doctor memory target resolver, matching doctor.memory.status. Older clients that omit agentId can read the dream diary and run the five maintenance handlers when a configured owner is unambiguous. Explicit selection still wins, and ownerless multi-agent fleets still receive the selection error.

Thanks @Orionation for the fix and @Cyb3rb1ade for reporting the legacy-client failures. The configured-owner case is addressed; selecting an agent remains necessary for ownerless fleets.

Validation: scoped review found no accepted/actionable P0 or P1 findings, the author supplied a resolver comparison, and exact-head hosted CI passed. No fresh after-fix Gateway trace was captured for this landing. Production +6/-1; tests unchanged.

Closes #138369

Co-authored-by: Jonathan Sieling <[email protected]>

* fix(sandbox): unblock scoped recreation across runtime targets (#157808)

* fix(sandbox): unblock scoped recreation across runtime targets

* test(sandbox): validate mocked process arguments

Co-authored-by: Vincent Koc <[email protected]>

* fix(security): parse gpt generation numbers in the audit tier check (#140012)

Fix security audit warnings that incorrectly classify numbered GPT-6 models as below GPT-5. Compare numeric generations in the shared model-hygiene classifier while preserving older-model warnings and Azure's legacy gpt-35-turbo naming contract.

The repair covers primary models, fallbacks, image models, and agent overrides without changing provider routing, authorization, or unknown-name advisory policy. Broader unknown-name behavior remains separate in #160580.

Fixes #139751
Thanks @holny for the fix, regression coverage, and isolated CLI evidence.

Co-authored-by: holny <[email protected]>
Co-authored-by: IWhatsskill <[email protected]>

* fix(doctor): report shared auth health without a default agent (#134902)

* fix(doctor): report shared auth health without a default agent

* fix(ci): stabilize tooling timing and fixture cleanup

Use fake time for the existing readiness-body polling test, preserve explicit
success and delegated return statuses in Bash 5.2 EXIT cleanup, and remove a
repeated seven-compiler declaration invalidation build already covered by
the shared SDK writer.

Validation: 146 readiness/fixture tests and two real declaration-build cases
pass, along with 15 shell controls across Bash 3.2, 5.2, and 5.3. The scoped
changed gate and Codex review pass.

* fix(doctor): converge redundant shared auth relocation subsets (#135096)

* fix(doctor): converge redundant shared auth subsets

Preserve richer canonical credential stores and original source receipts through cleanup. Keep differing credentials and state rows fail-closed with actionable diagnostics. Reported by @jodok and independently reproduced by @felixboenkost-droid in #132605.

* fix(doctor): satisfy shared auth relocation validation

* fix(doctor): report retained device-auth files (#133978)

Surface retained client device-auth JSON in ordinary Doctor output and opted-in
lint checks, including when identity, pairing state, or Gateway health is absent.
Resolve only retired-file diagnostics and profile-aware repair hints from the
original health context environment; keep pairing and token reads on the active
state view.

Describe remaining migration or cleanup debt without inferring import history.
Keep the legacy-file token guard and Doctor-owned migration unchanged, share
friendly and structured findings, and remove redundant string-formatting paths.

Refs: #127973, #133978.
Reported by @yetval.

Co-authored-by: yetval <[email protected]>

* fix(update): stop detached updates after chat ownership is revoked (#137312)

* fix(update): recheck chat ownership before detached update launch

* test(update): keep helper owner cases in lifecycle support

* docs(update): describe the implemented session-less notice route

* test(update): match conditional Vitest API in owner cases

* fix(doctor): inspect source auth stores during full lint (#137610)

* fix(doctor): inspect source auth stores during full lint

* test(ci): freeze release candidate fixture clock

* refactor(doctor): simplify scoped environment restoration

* test(release): preserve elapsed time in fixture clocks

* test(auth): join migration fixture callbacks before teardown

* fix(gateway): recover queued RPC replies across restart (#138565)

Bind RPC and scheduled lifetime resolvers to their exact Gateway host. Reuse the canonical host for HTTP hooks and worker dispatch so shutdown retains pending reply recovery without weakening execution fences.

Fixes #138564

* fix(doctor): preserve legacy ownership during config repair (#138837)

Carry the retained default-agent owner through legacy migration, persist the
canonical roster through the config writer, and verify startup repair with
that same ownership preparation. This prevents a migratable legacy fleet
from being replaced by stale last-known-good configuration during update.

Verify the actual persisted roster and retained settings, keep ambiguous
owners rejected, and document migration before recovery.

Validation: 77 owner tests, changed checks, and independent P0-P2 review.
Release-note context: preserves update settings and legacy default-agent
ownership through automatic Doctor config migration.

* fix: prevent browser profile permission hangs in Doctor (#139612)

* fix: prevent browser profile permission hangs in Doctor

* docs: explain explicit browser registration repair

* fix(gateway): prevent systemd restarts from hanging (#140914)

With OPENCLAW_NO_RESPAWN enabled, a managed restart could reopen the Gateway inside the original process while systemd waited for it to exit. Use the existing external-restart action to drain, close, retain the recorded reason, and exit so the service manager creates the successor.

Verified through real Linux user-systemd restart, all five drain modes, ordinary stop/start, unmanaged SIGUSR1, independent runtime acceptance, and 384 focused lifecycle controls. Preserve existing managed-update ownership and service settings.

Thanks to @rboy1 for the report. Closes #140821.

Co-authored-by: Ayaan Zaidi <[email protected]>

* fix(doctor): recover legacy node tokens with invalid scopes (#143599)

Doctor detects legacy node tokens that inherited operator scopes, but its suggested rotation preserves those scopes and is denied. Add `devices rotate --no-scopes` and use it in Doctor's node recovery guidance. Rotation removes only the matching stale local node…
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

channel: msteams Channel integration: msteams P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: S 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.

msteams: thread parent/reply context never loads for channel threads without replyToId

3 participants