Skip to content

DO NOT MERGE: publisher workspace mismatch for fast-uri stable backport - #187269

Closed
RomneyDa wants to merge 1033 commits into
mainfrom
openclaw/cool-shell
Closed

RomneyDa wants to merge 1033 commits into
mainfrom
openclaw/cool-shell

Conversation

@RomneyDa

@RomneyDa RomneyDa commented Oct 29, 2026 •

Copy link
Copy Markdown
Member

Publication mismatch — do not review or merge

The managed publisher was explicitly given the isolated stable-backport workspace, but published a different head/base: openclaw/cool-shell at 8a1b8a0df7739ed88682b8c4edf2f9d81846b60c against main, with 4,291 changed files. This is NOT the intended three-file fast-uri backport. No validation below applies to this published head. This PR must remain draft pending operator recovery; no RFR or merge is authorized by this task.

Intended candidate (not this PR)

  • Target: release/2026.10.8, base 5413218d77df39edac0ee99b7838d7bac519002a.
  • Local candidate: 93a55d32ab42ad019f3778b612c3a4981ac9ce6d on security/fast-uri-stable-20261029.
  • Exactly three files: fast-uri override/lock 4.2.1 → 4.2.3 and installed MCP SDK/Ajv regression.
  • Baseline regression failed on installed 4.2.1; fixed regression and 12 MCP metadata tests passed on the intended candidate only.
  • Candidate retained locally for correct publication. Independent canonical review and hosted checks remain required before RFR.

roboclaw-bot and others added 30 commits October 22, 2026 23:10
Keep the release branch's existing reset presentation owner while applying #176675.

Co-authored-by: RomneyDa <[email protected]>
…ls (#176682)

* fix(sessions): keep conversations usable after delegated recovery fails

Rewrite the reviewed recovery settlement onto the session-controller owner. Retire unowned delegated inputs, project idle when reply ownership ends, and keep interrupted cron occurrences out of generic replay. Preserve outstanding execution and delivery custody.

Co-authored-by: Paul Bohm <[email protected]>

* test(sessions): count stuck diagnostic events

Assert the absence of matching stuck events without treating the optional diagnostic reason as a required string.

* fix(sessions): preserve settled diagnostic state on retirement

Only project an existing active diagnostic entry to idle. Preserve message-owned identity, avoid creating idle state for disabled cron diagnostics, and keep unchanged cron lifecycle assertions.

Co-authored-by: Paul Bohm <[email protected]>

* fix(sessions): retain cron recovery ownership across steering

Co-authored-by: Paul Bohm <[email protected]>

* test(sessions): prune obsolete transcript mock allowance

Co-authored-by: Paul Bohm <[email protected]>

---------

Co-authored-by: Paul Bohm <[email protected]>
(cherry picked from commit d6ec4c7)
Co-authored-by: RomneyDa <[email protected]>
…ls (#176682)

Adapt the interrupted-input settlement to the 2026.10.6 recovery owner while retaining tombstones for outstanding custody.

Co-authored-by: RomneyDa <[email protected]>
)

* fix(claude-cli): stop cache-prefix churn after child completion

Ordinary local claude-cli turns now use the same exact OpenClaw-mediated
tool projection as verified child completions, so a completion no longer
swaps the tools-first cached prefix of a running native session.

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

* test(claude-cli): expect the mediated surface on ordinary turns

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

* test(claude-cli): select native tools in the workspace-only override case

Managed Claude turns are mediated by default, so the agent workspace-only override is
covered on the explicit native-selection path that still exposes native file tools.

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

* fix(claude-cli): serve configured MCP servers through the loopback bridge

Exclusive CLI runs omit native MCP servers because the CLI would call them
outside OpenClaw's per-turn caps. Managed local Claude turns are now all
exclusive, so configured mcp.servers disappeared from ordinary turns.

Materialize the session's configured MCP tools for the run and serve them
through the loopback grant. They pass the same Gateway policy pipeline and
exact grant allowlist as other tools, so ordinary and completion turns list
one catalog while each turn's cap still decides what is listed and callable.

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

* fix(claude-cli): ignore request echoes when checking for orphaned tool calls

Claude Code logs api-request-blob records that repeat already answered
tool calls under role=assistant. Counting them made a finished turn look
orphaned until the final reply was written, so a completion that resumed
the parent right after a spawn reset its native session. Only user and
assistant conversation records now count.

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

* fix(claude-cli): keep skill_workshop stable on internal turns

Only human turns receive personal-library authoring, so completion and
other internal turns published a different skill_workshop definition and
broke the native prompt cache for profiled users. Since #176587 this also
affects token-authenticated clients.

CLI turns without authoring now reuse the session's last human shape with
an expired grant, as goal continuation already does. The definition stays
identical and every call, including Workshop calls through the
workspace-default wrapper, is refused, so no sandboxed internal turn gains
Workshop access.

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

* fix(skill-workshop): keep workspace Workshop on internal CLI turns

The stable skill_workshop shape for internal turns refused every call,
including workspace Workshop calls that an unsandboxed no-grant turn may
make on main. Pass the run's sandbox state to the workspace-default
wrapper so the expired grant refuses only personal-library calls and
sandboxed workspace calls.

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

* fix(mcp): recheck loopback grant at configured-server I/O

The loopback handler checked grant and completion lineage before
executing a tool, but a configured MCP tool could still reach its server
after that check, for example after waiting for a session reconnection.
Carry the caller's check into MCP tools/call so it runs immediately
before server I/O.

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

* fix(mcp): serve configured server instructions through the loopback

Managed Claude turns used to connect configured MCP servers natively and
received each server's initialize instructions. The bridge kept the tools
but dropped the instructions. Capture them in the session MCP catalog and
return them from the loopback initialize reply, ordered by server name,
for servers that still have a listed tool. Catalog capture follows the
approach proposed in #174396.

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

* fix(mcp): guard every bridged request and serve server instructions whole

Resource reads, prompt fetches and paginated lists now recheck the loopback
caller's grant and completion lineage at the request boundary, as tool calls
already did. Configured server instructions are no longer capped at 1,200
characters. A Gateway loopback test revokes a real grant or reassigns a real
completion lineage during a server-driven catalog refresh.

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

* test(gateway): prove Workshop shape and refusal on completion turns

Through the real loopback, a completion turn after a human turn lists the
same skill_workshop definition, refuses personal-library calls without
reaching the human grant, and keeps unsandboxed workspace calls.

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

* test(gateway): prove sandboxed completions cannot write through Workshop

Sandboxed completion turns, with or without skill_workshop admitted by the
sandbox tool policy, list the same Workshop surface as the human turn and
refuse a workspace create before any file changes. The Gateway authority
file runs in the database-worker project, which owns the main-thread
shared-state broker. Drops the mock-sequenced revocation case now covered
by real grant and lineage owners.

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

* test(cli-runner): drop Workshop helper cases covered by the Gateway suite

Definition parity, personal refusal and workspace access are now proven
through the real loopback; keep session isolation and latest-shape cases.

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

* test(gateway): wait for list_changed delivery instead of sleeping

The probe follows each tools/list_changed with a ping on the same SSE
stream; the client handles stream messages in order, so its ping reply
proves the notification was consumed before the next call.

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

---------

Co-authored-by: Marvinthebored <[email protected]>
Co-authored-by: VACInc <[email protected]>
Co-authored-by: roboclaw-bot <[email protected]>
(cherry picked from commit 77d9f42)
Co-authored-by: RomneyDa <[email protected]>
(cherry picked from commit 9c62a16)

Co-authored-by: RomneyDa <[email protected]>
…159715)

Adapted to the 2026.10.6 queue owner; the newer session-controller mailbox owner is not present on this release line.

(cherry picked from commit fe1b4f5)

Co-authored-by: RomneyDa <[email protected]>
…loaded plugins on scope growth (#162226)

* fix(agents): stop model-catalog worker discarding incrementally-loaded plugins on scope growth

The prepared-model-catalog worker's plugin registry reuse check required an
exact match between the previously-loaded plugin-id set and each new
request's set. Any request needing a plugin beyond what was already loaded
(e.g. runtime provider discovery proving a new provider is needed) was
treated as a full cache miss, discarding and rebuilding the entire registry
-- including every other already-loaded plugin that hadn't changed.

loadOpenClawPluginsCore already has a correct per-plugin incremental-reuse
mechanism via a previousRegistry option; it was simply never threaded
through for this call path. Fix: thread it through unconditionally for
model-catalog requests, and remove the unsafe direct-return fast path that
could otherwise skip the loader's own signature validation entirely.

Also: resolveWorkerGenerationBasePluginIds carries previously-proven
scope-expansion plugin ids forward so a later fingerprint-miss rebuild
doesn't regress below what discovery already established; the worker now
threads its previous generation through on a fingerprint miss so the
reuse mechanism above actually has something to reuse against.

Also: markPreparedModelRuntimeSnapshotsStale/refreshPreparedModelRuntimeSnapshots
gained a resetPluginGeneration opt-out (default true, preserving existing
behavior) so refreshes with no plugin-relevant change (secrets reload,
chat-metadata polling, per-agent database startup reusing an already-captured
metadata snapshot) stop forcing an unrelated full plugin rebuild -- a second,
smaller contributing cause to the same CPU/memory/disk symptom.

Also: recordPreparedPluginRegistrySuccessor ensures a registry promoted as
a generation's successor is excluded from its predecessor's disposal, since
retained plugin instances are now shared across generations more often.

Tested: real (unmocked) plugin-load regression test proving the actual
benefit -- load A+B once, request A+B+C, only C's load path re-executes.
60+ targeted tests passing across all touched files, no regressions.

* fix(agents): resolve disposal-successor exclusion lazily at release time

Prior attempt (this commit, before amendment) added registrySuccessors-aware
exclusion inside retainPreparedPluginRegistry's inspection-owned branch, but
placed it as an EAGER check evaluated at retain-time (when the function first
runs and returns a release closure). That branch is also unreachable for the
model-catalog worker's real registries in the first place: those registries
are always registered through PreparedModelRuntimeBuildResources.load(), which
wraps them in a PreparedRegistryResources instance keyed into
retainPreparedModelRuntimeSnapshotResources's backing map BEFORE
retainPreparedPluginRegistry ever runs its own inspection lookup -- so the
earlier `if (prepared) return prepared.release` branch always wins first for
that path (ClawSweeper's finding on 8f7b6bfb303).

But fixing only the early-return order is not sufficient either: both of the
worker's call sites capture a predecessor's release closure from an EARLIER
call to retainPreparedPluginRegistry, then call
recordPreparedPluginRegistrySuccessor(previous, next) only once the successor
exists -- strictly AFTER retainPreparedPluginRegistry already returned for the
predecessor. So even moving the registrySuccessors.get() lookup to the top of
the function, unconditional of branch, still resolves it too early: the
successor is never recorded yet at that point, for any owner shape.

Fix: resolve the registrySuccessors lookup lazily, inside the returned release
closure itself, at the moment it is actually invoked -- by which point the
successor has been recorded. Every real owner shape (PreparedRegistryResources
-wrapped, bare PluginRegistryInspectionResources-owned, and the
createLifetime-owned fallback, which already did this correctly via its own
lazy accessor) now applies the same registrySuccessors-aware exclusion right
before triggering its real release, regardless of which branch is active.

Also adds a regression test that goes through the worker's actual
PreparedModelRuntimeBuildResources.load() + retainPreparedPluginRegistry flow
(not a bare PluginRegistryInspectionResources construction), confirming it
fails against the pre-amendment code and passes with this fix.

* fix(agents): transfer disposal custody for previousRegistry-retained plugin instances

Both P1 findings on the model-catalog worker's scope-growth promotion
(A -> A+B) traced to the same root cause: resolvePluginInstanceOwner's
owner.registry is set once per PluginRecord and never reassigned, so a
record retained forward into a successor via previousRegistry reuse
still reports its ORIGINAL (predecessor) registry as its disposal
custodian. Every consumer that gates disposal/liveness on
owner.registry (the inspection retire filter in loader-runtime-load.ts,
getPluginRecordRegistry, isPluginRecordActive) therefore still lets the
retiring predecessor revoke/dispose an instance the successor is
actively relying on (finding 1), and nothing ever disposes it once the
predecessor stops being considered its owner (finding 2, a leak).

Investigated whether #161267's lender/borrower borrowRegistry
mechanism (merged on main the same day) could cover this directly:
resolveLendingGatewayRegistry explicitly excludes purpose ===
model-catalog from borrowRegistry, and more fundamentally the
model-catalog worker's own generations are always loaded through
acquirePluginRegistryForInspection with activate: false, so
runtimeSideEffects is always false for them -- they never set
/record a borrowSignature on their own plugins, so they could
never act as a borrowRegistry lender for their own successor even if
wired up manually. The borrow/view-fencing model is for a lender that
stays alive and serves many concurrent short-lived borrowers; the
worker's generations are a strict linear hand-off instead, so the
right fix is to move custody forward, not to add fencing.

Fix: add transferPluginInstanceOwner(record, registry) and call it in
loader-runtime-core.ts's resolvePluginRecordRetention retention branch
whenever a record is retained from previousRegistry (never for
borrowRegistry, which keeps the lender's permanent custody as-is).
This makes the existing generic owner.registry === registry custody
check correct for the whole chain with no extra bookkeeping: the
predecessor naturally excludes a transferred instance from its own
retire filter, and the successor naturally includes it in its own
eventual retire filter, guaranteeing disposal exactly once wherever the
chain actually terminates.

With the root cause fixed, the registrySuccessors/
recordPreparedPluginRegistrySuccessor/retainInstancesFor machinery
added across this branch's prior two commits is now dead weight: it
only ever suppressed a predecessor's premature disposal (finding 1)
and never transferred custody anywhere (finding 2, still a leak even
with that machinery in place). Removed it from
prepared-model-runtime.plugin-lifetime.ts,
prepared-model-catalog.worker.ts, and
registry-inspection-resources.ts.

Replaced the three removed tests (disposal-successor,
inspection-successor, build-resources-successor -- all asserted
behavior of the now-deleted recordPreparedPluginRegistrySuccessor) with
prepared-model-runtime.plugin-lifetime.generation-handoff.test.ts,
covering the real worker path end to end:
- PreparedModelRuntimeBuildResources + retainPreparedPluginRegistry
  (the exact prepareWorkerGeneration flow): predecessor release
  survives, a real successor-side call through
  instance.runInRegistry(successorRegistry, ...) succeeds, and the
  shared instance disposes exactly once once the successor itself
  later retires.
- The same ownership transfer through the plain
  acquirePluginRegistryForInspection(previousRegistry) path.
- A disabled-plugin-between-generations case and a no-successor
  terminal-retirement case both still correctly reject a stale
  instance's call with PluginInstanceUnavailableError before any I/O,
  proving the fix does not weaken liveness fencing for the ordinary
  paths.

Tests: runtime-plugins.test.ts,
runtime-plugins.real-pool.test.ts,
runtime-plugins.real-pool.integration.test.ts,
prepared-model-catalog.worker.base-plugin-ids.test.ts,
prepared-model-runtime.plugin-generation-reset.test.ts,
prepared-model-runtime.plugin-lifetime.generation-handoff.test.ts --
6 files, 48/48 passed, 13.85s test time (22.8s wall incl. transform).
Full-project typecheck/build intentionally skipped per task constraint
(OOM risk); verified by code reading plus these targeted suites.

* Fix plugin registry inspection resource initialization ordering bug

- Fixed field initialization ordering: moved #registry declaration above #source
  in PluginRegistryInspectionResources to resolve 'Cannot read private member
  #registry from an object whose class did not declare it' error

- Added missing AsyncWorkScope import in PluginRegistrationResourceSource
  to resolve 'ReferenceError: AsyncWorkScope is not defined' error

These fixes address the class-field-initializer ordering bug causing test
failures in the plugin catalog lifecycle implementation.

* Fix fixture property mismatch: disposerCallCount → disposals in plugin lifetime tests

The test files incorrectly referenced , which doesn't exist in the real fixture. The correct property is , incremented by the NativeLifecycle class's  method in registry-inspection.test-helpers.ts.

* Fix eager-capture bug: registry read before attach()

Change PluginRegistrationResourceSource constructor parameter from plain registry value to getter function so registry is evaluated lazily at disposal time, not captured at construction time.

- Changed registry parameter to getRegistry getter function
- Updated all three #dispose() call sites to use getRegistry?.()
- Changed field initializer in PluginRegistryInspectionResources to pass () => this.#registry instead of this.#registry
- Modified #dispose to preserve disposers when shouldDispose is false so they can be disposed later by the registry that now owns the instance

Fixes the root cause identified by Core: currentRegistry was permanently undefined because captured at field-initializer/construction time, before attach() assigns #registry.

* fix: actually transfer registration resources, not just skip disposal

Previously, PluginRegistrationResourceSource would only SKIP disposing registration resources when instances were transferred away (via #shouldDisposeResourcesForPlugin), but the disposers remained on the predecessor's tracking and leaked. Now:

1. PluginRegistrationResourceSource.transferRegistration() moves disposers from predecessor to successor's #registrations map
2. PluginRegistryInspectionResources.transferRegistrationTo() exposes this to registries
3. transferPluginInstanceOwner() transfers both instance ownership AND registration resources when both registries have inspection resources

This ensures disposers are eventually disposed EXACTLY ONCE by whichever registry ends up with custody through the chain (handles A -> B -> C multi-generation transfers correctly).

Transactional rollback also transfers registration resources back to predecessor when temporary transfer is rolled back.

Fixes P1 Finding A registration resource transfer gap.

* fix(plugins): wire rollback into real failure paths

1. Roll back retained ownership when loader throws mid-load
2. Restore custody before releasing failed fingerprint replacements
3. Add missing PluginRuntimeCloseRetainedError import
4. Clear rollback closures after successful handoff
5. Add security test for transferred-then-disabled plugin stale authority

Verifications:
- All 54 tests pass (0 failures)
- Added test for transfer-then-disable scenario
- Rollback closures now properly invoked in error paths
- Worker fingerprint-miss failures restore custody before release
- Memory leak from un-cleared rollbacks fixed

* fix(plugins): three scoping/rollback bugfixes per review

1. [P1] Move transferRollbacks declaration outside try block in loader-runtime-core.ts
   (ReferenceError in catch block when rollback needed)
2. [P2] Clear rollback closures in fingerprint-match path in prepared-model-catalog.worker.ts
   (Both scope-expansion AND fingerprint-match paths must clear rollbacks)
3. [P2] Fix transactional rollback test to actually exercise catch-block rollback path
   - Create real failure scenario with throwing plugin
   - Add throwOnLoadError: true to make test fail properly
   - Verify predecessor instance survives post-rollback

* Fix plugin ownership transfer scoping and rollback clearing

- [P1] Add transferInstanceOwnership opt-in flag to PluginLoadOptions to preserve Gateway custody during unpublished reload preflight. Gateway reload preflight (preparePlugins with loadModules: false) doesn't set this flag, preserving old safe behavior. Model-catalog worker handoff explicitly sets transferInstanceOwnership: true when reusing previousRegistry.
- [P2] Clear rollback state on promoted scope-growth registry in prepared-model-catalog.worker.ts: clear rollbacks on acquiredGeneration's registry in addition to prepared registry.
- Add placeholder test for Gateway reload preflight non-transfer behavior.

* Fix regressions from opt-in flag and add real Gateway preflight test

Problem 1: Add transferInstanceOwnership: true to direct loader calls in test files that exercise ownership transfer:
- src/agents/prepared-model-runtime.plugin-lifetime.registration-resource-transfer.test.ts
- src/agents/prepared-model-runtime.plugin-lifetime.transactional-rollback.test.ts
- src/agents/prepared-model-runtime.plugin-lifetime.generation-handoff.test.ts

Problem 2: Replace fake placeholder test with real Gateway preflight test:
- src/gateway/server-plugin-reload-preflight-transfer.test.ts: Write real test verifying Gateway reload preflight does NOT transfer ownership (no transferInstanceOwnership flag).

* Fix auth-refresh rollback gap and add resource-backed security proof

1. Fix third rollback-clearing gap in auth-refresh success path:
   - Added clearRegistryTransferRollbacks() call before auth-refresh return
   - This is the third identical gap fixed (following scope-growth and fingerprint-match paths)

2. Implement resource-backed security proof:
   - Enhanced existing transfer-then-disable test with actual resource-backed proof
   - Test performs real operation before disablement, verifies rejection happens at authority-check boundary
   - Added resource access counter to prove real I/O is not touched after disablement

Both fixes address recurring security findings flagged across multiple reviews.

* fix: replace fake counter with real DB query in resource-backed proof test

The test 'rejects stale transferred authority before real I/O after transfer-then-disable sequence with resource-backed proof' was using a fake counter increment to simulate resource access, which didn't actually prove the plugin authority gates real resource I/O.

Now the test:
1. Executes a REAL SQL query () against the fixture's actual SQLite database ( instance) when authorized
2. Verifies the real result  is returned
3. Proves the same real query path is NEVER reached on the rejected attempt (PluginInstanceUnavailableError thrown before query execution)
4. Tracks query execution count to confirm only the first (allowed) query ran

This satisfies ClawSweeper's requirement for proving authority actually protects a real resource, not just gating a fake counter increment.

* Fix ordinary-agent registry superset reuse and add regression test

1. Remove .every() exact-match check from reusableAgentRuntimeRegistry, restoring loose-containment-only reuse for ordinary (non-model-catalog) agents
2. Add regression test that properly sets up mock resolveAgentRuntimePluginLoadPlan to return requested plugin IDs, verifying superset reuse works correctly
3. Verified with fail-then-pass: test correctly fails when buggy .every() logic is re-introduced, passes with restored fix

* Add real-worker-path security tests for transferred-then-disabled plugin authority rejection

- Add test 'transferred-then-disabled plugin correctly rejects stale authority via actual worker machinery (real PreparedModelRuntimeBuildResources path)' proving transferred-then-disabled plugin instances correctly reject stale authority before I/O through actual model-catalog worker machinery
- Add test 'failed worker handoff (generation build throws after transfer) restores predecessor custody via real worker path' addressing reviewer's failed-handoff recovery concern
- Both tests use PreparedModelRuntimeBuildResources real worker path, not bare loader fixture
- Verified all 9 test files pass (59 tests)

* Fix test ordering flaw for failed worker handoff rollback detection

Reorders the 'failed worker handoff' test to check predecessor custody
IMMEDIATELY AFTER disposing failed successor resources, not before.

Previously the test asserted predecessor custody while the failed successor
was still alive, then only checked final disposal count after everything
was cleaned up. This could mask a bug where failed successor cleanup
incorrectly disposes/revokes the predecessor's shared instance.

The reordered test now:
1. Loads predecessor generation
2. Attempts successor build that throws
3. Disposes failed successor resources FIRST
4. IMMEDIATELY verifies predecessor still has custody (instance not disposing,
   real registry operation works, disposal count still 0)
5. Only then releases predecessor normally

This matches the exact gap identified in review: testing whether failed
successor cleanup incorrectly touches predecessor's shared instance.

* Fix BuildResources.load rollback gap on worker-level failure

Adds rollback execution for ownership transfers when PreparedModelRuntimeBuildResources.load fails during the onPrimaryRegistry callback. This is the third call site needing rollback invocation after the load fails, matching the pattern already implemented in:

1. loader-runtime-core.ts's own catch block (fixed earlier)
2. prepared-model-catalog.worker.ts's runCatalogRequest failure paths (fixed earlier)
3. PreparedModelRuntimeBuildResources.load's failure when onPrimaryRegistry throws (this fix)

The bug manifested as the test 'failed worker handoff (generation build throws after transfer) restores predecessor custody via real worker path' failing because:
- acquireAgentRuntimePluginRegistry transfers instance ownership to the successor registry
- The onPrimaryRegistry callback throws (simulating a worker generation build failure)
- Without rollback execution, the transfer remains in effect
- When the failed successor disposes, it incorrectly disposes/revokes the predecessor's shared instance

Now catch errors from onPrimaryRegistry, lookup getRegistryTransferRollbacks for the registry being built, and invoke each rollback before propagating the error.

* fix(lint): keep prepared-model-runtime.ts under the 700-line budget

* Reduce prepared-model-runtime.ts line count below 700

Combine consecutive variable declarations to reduce line count:
- Combine three Map declarations on lines 99-101
- Combine two PreparedModelRuntimeOwnerRetention declarations on lines 102-103
- Combine refresh-related declarations on lines 106-108

Verified with npx oxlint showing zero max-lines errors and all integration tests passing.

* Reduce prepared-model-runtime.ts line count below 700 (final)

Combine setModelRuntimeBuildTimeoutMsForTest arrow function into single line to reduce line count while preserving identical behavior.

Verified with npx oxlint showing zero max-lines errors and all integration tests passing.

* Final line reduction: combine arrow function to single line

Reduce prepared-model-runtime.ts line count below 700 by combining setModelRuntimeBuildTimeoutMsForTest arrow function body into single line.

npx oxlint now shows 0 errors (file under 700-line budget).

* style: collapse multiline calls to reduce line count

- Collapsed 5 multiline function calls and declarations onto single lines:
  - getBlockingReplacement arrow function
  - acquireRetainedAgentRuntimeCleanupRegistries call
  - createPublishedModelRuntimeAccess call
  - createPreparedModelRuntimeCatalogRecovery call
  - remoteCatalogPublication destructuring

Zero behavior change, purely mechanical formatting to satisfy oxlint max-lines rule (was 702 > 700).

* style: collapse multiline calls to reduce line count below 700

Collapsed 5 multiline function calls and declarations onto single lines:
1. getBlockingReplacement arrow function
2. acquireRetainedAgentRuntimeCleanupRegistries call
3. createPublishedModelRuntimeAccess call
4. createPreparedModelRuntimeCatalogRecovery call
5. remoteCatalogPublication destructuring

Zero behavior change, purely mechanical formatting to satisfy oxlint max-lines rule (was 702 > 700).
Verified: oxlint now passes with 0 errors.

* style: collapse normalizedEvent object literal to reduce line count below 700

* fix(plugins): preserve cleanup for instance-free registrations; add missing wrapper imports

Finding 1: #shouldDisposeResourcesForPlugin collapsed two distinct cases
(instance transferred away vs. no instance at all) into one false return,
leaking resources for lifecycle-only registrations (registry-registrars-host.ts)
that have a disposer but never get a managed PluginInstanceHandle. Renamed to
#isInstanceOwnedByAnotherRegistry with three-way-correct semantics: dispose
unless an instance exists AND is owned by a different registry.

Finding 2: added src/plugins/plugin-invocation-scope.ts,
src/plugins/registry-inspection-resources.ts, and
src/plugins/registry-registration-resources.ts to
scripts/pr-lib/wrapper-components.txt -- the real transitive runtime import
closure reachable from plugin-instance-scope.ts that was missing from the
trusted wrapper inventory. (plugin-instance.types.ts and registry-types.ts
are type-only imports, erased at build, and are correctly excluded.)

Adds regression coverage in registry-registration-resources.test.ts for the
no-instance disposal path.

* fix plugin registry reuse verification failures

* fix catalog worker env serialization

* Address plugin catalog review findings

* Make plugin source copy compatible with older fs-safe exports

* Fix guarded plugin source copy fallback

* Fix catalog base plugin activation planning

* Fix catalog base plugin activation planning

* Fix Windows guarded plugin source copies

* Add guarded Windows plugin source copy fallback

* Relax Windows plugin copy identity assertions

* Handle unknown Windows plugin source identities

* Recognize structural fs-safe copy fallback errors

* Fix plugin source lookup across path spellings

* Scope internally prepared runtime plugin metadata

* Use native counter path in real-pool integration

* Use explicit metadata in real-pool reuse integration

* Use process counter for real-pool module evaluation

* Fallback when fs-safe root copy helper is absent

* Preserve implicit real-pool metadata coverage

* test: reject retained plugin callbacks before resource I/O

Exercise a loader-registered provider callback across abandoned growth and
successful inspection adoption. After successor retirement, keep its real
SQLite connection open behind the disposal gate and verify the same retained
callback rejects before preparing another statement, including after final
disposal. Preserve exactly-once resource and instance cleanup.

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

---------

Co-authored-by: roboclaw-bot <[email protected]>
Co-authored-by: RomneyDa <[email protected]>
(cherry picked from commit 3e42abb)
Co-authored-by: RomneyDa <[email protected]>
Gemini family detection keyed on gemini-3 pro/flash regexes, so
gemini-4-argon fell into the Gemini 2.5 path: thinking sent as
thinkingBudget, and unsigned replayed tool calls were not repaired,
which the live API rejects with HTTP 400.

- Detect Gemini 4 in the shared google-model-family owner and drop
  google-shared's private duplicate regexes.
- Gemini 4 uses thinkingLevel LOW/MEDIUM/HIGH; minimal and off map to
  LOW (live API rejects MINIMAL).
- Repair unsigned tool-call replay for Gemini 4 on google/google-vertex.
- Add gemini-4-argon to the bundled catalog (code mode preferred),
  a gemini-4 shorthand alias, and a forward-compat family so newer
  gemini-4-* releases resolve from the Argon template.
- Keep Gemini 4 out of explicit cachedContents (implicit caching only).
- Live tests: discovery/completion and a tool-call round trip with
  unsigned replay through the registered transport.

Co-authored-by: Peter Steinberger <[email protected]>
(cherry picked from commit 5e9b574)
Co-authored-by: RomneyDa <[email protected]>
…date hunk cannot apply (#160409)

Related: #117742

## What Problem This Solves

Fixes: a multi-file `apply_patch` call permanently deletes, creates, or rewrites earlier files when a later update hunk targets a missing file or its context lines do not match, while the tool only reports the later error.

## User Impact

User impact: when an update hunk in a patch cannot apply, the whole patch now rejects before any file changes, so the workspace is left exactly as it was and the agent's retry starts from the state it expects.

## Why This Change Was Made

The issue and #127496 leave one durability question open: after a failure that happens while files are being written (I/O error, a competing writer, cancellation mid-commit), should `apply_patch` compensate, or keep the earlier effects and report them? This PR does not make that choice. It implements only the part both options in the ClawSweeper review share, which is also the first step of the repair described in #127496: validate the ordered envelope before writing, while holding the file queues for the whole envelope.

- All hunk targets resolve first, and the patch holds the file-mutation queue for every path it touches for the whole run, so the check reads the same state the writes act on.
- Every update hunk is then computed in order before anything is written, with the same `applyUpdateHunk` the write pass uses. Earlier adds, updates, deletes and moves in the same patch are staged by physical file identity, so an update of a file added or changed earlier in the patch still works, and an update of a file an earlier hunk deletes or moves away rejects up front. A missing file, a context mismatch or invalid UTF-8 rejects with no mutation.
- Links are staged apart from the files they name. Queue identity follows a final symlink, so a link and its target share one key, but deleting the link leaves the target in place. A delete or move of a final symlink therefore stages the link path by its spelling, and later hunks at or under that path (`Add File: link`, `Update File: link`, `Move to: link`, `Add File: dir-link/x.txt`) use that path stage, which starts out removed. The target keeps its own staged contents, so `Delete File: link` followed by a mismatched `Update File: target` now rejects before the link is deleted, and `Delete File: link`, `Add File: link`, `Update File: target` no longer checks the target against the new link contents. The write pass decides whether an update is a move from the same stages, so `Update File: target` with `Move to: link` after `Delete File: link` moves the file instead of rewriting it in place.
- Names of one hardlinked file share staged contents in unrestricted host mode (`workspaceOnly: false`), where an update rewrites the file in place and every name sees it. Each name has its own queue identity, so an update hunk of a hardlinked file (more than one link at the snapshot) stages by the file's device and inode instead, until an earlier hunk in the patch deletes, re-creates or moves that name. `Update File: a` followed by `Update File: b` whose context matches the text written through `a` applies again, as it does on main. Moving one name away leaves the shared contents for the other names. Confined mode refuses hardlink aliases, and the sandbox helpers refuse hardlinked reads and replace files atomically, so neither shares contents across names.
- Path admission for a later hunk runs against the initial snapshot. When an earlier removal changes what admission sees (a symlink or file replaced by a regular file or directory, or the last other name of a hardlink), that hunk repeats strict admission in the write pass right before it runs, after the earlier hunk has removed the path. The link target is never read or written. A later path matches an earlier host symlink removal by the link entry's own identity (`lstat` device and inode) as well as by spelling, so the filesystem decides which spellings name the removed link: on a case-insensitive volume, `Delete File: link.txt` then `Add File: LINK.txt` (or `Add File: D/x.txt` after `Delete File: d`) replaces the link as it does on main. A symlink with more than one hardlinked name matches by spelling only, because its identity also names the entries that stay. Any other admission failure still rejects the whole patch up front, even after an unrelated delete.

Deliberately left out: compensation or a partial-effect result for failures that only show up during the write pass (an add whose destination exists, a delete of a missing file, a move onto an existing file, removing a directory, I/O errors, cancellation between writes). Those still behave as on main and need the maintainer decision above. For the same reason this PR does not close the issue on its own; keeping #117742 open for that decision is fine.

Scope tradeoff for maintainers: landing this PR means accepting a bounded fix. A patch whose update hunk cannot apply now leaves the workspace untouched, but a patch that fails during the write pass can still leave the effects of earlier hunks in place without reporting them, exactly as on main. Closing that gap needs the compensation or partial-effect decision tracked in #127496.

Where the check cannot predict the state it leaves the hunk to the write pass, which stays authoritative, rather than reject a patch the write pass would accept: an update of the other name of a hardlink that an earlier delete frees, and an unreadable new path whose spelling differs only in case from a path an earlier hunk staged (case-insensitive filesystems keep the spelled case in the identity of a missing path).

Design note: I chose a read-only preflight in front of the unchanged write pass over a staged plan with an undo journal. The staged plan must model every backend precondition (entry kinds, parent topology, symlink handling in the sandbox bridges), and #122933 stalled on exactly that.

The branch is rebased onto current main. The patch parser moved unchanged to `src/agents/apply-patch-parse.ts` (main's current parser, which returns the hunk list directly), and the tests this PR adds live in `src/agents/apply-patch.preflight.test.ts`, so both files stay within the line-cap ratchet.

The existing permission-change fence test now expects the abort at the envelope checkpoint: the read that triggers it happens in the preflight, so the rejection is an `AbortError` that carries the permission-change reason as its cause, and the file still stays unchanged.

## Evidence

Real behavior: an isolated Gateway built from each side (own state directory, loopback port, channels skipped) with a keyless local mock model that makes one agent turn call the real `apply_patch` tool with the envelope from the issue (`Delete File: important.txt`, then `Update File: missing.txt`). The workspace is seeded with `important.txt`.

Before (upstream main, no apply_patch changes since):

```
== workspace before: important.txt
== important.txt before: irreplaceable-user-data
== agent exit: 0
== tool result the model received:
   {
  "status": "error",
  "tool": "apply_patch",
  "error": "Failed to read file to update <workspace>/missing.txt: Failed boundary read for <workspace>/missing.txt (path not found)"
}
== workspace after:
== important.txt after: <MISSING>
```

After (this branch, same Gateway setup and turn):

```
== workspace before: important.txt
== important.txt before: irreplaceable-user-data
== agent exit: 0
== tool result the model received:
   {
  "status": "error",
  "tool": "apply_patch",
  "error": "Failed to read file to update <workspace>/missing.txt: Failed boundary read for <workspace>/missing.txt (path not found)"
}
== workspace after: important.txt
== important.txt after: irreplaceable-user-data
```

Control on this branch, a valid envelope (delete, add, then update of the just-added file) still applies in order:

```
== workspace before: important.txt
== important.txt before: irreplaceable-user-data
== agent exit: 0
== tool result the model received:
   Success. Updated the following files:
A notes.txt
M notes.txt
D important.txt
== workspace after: notes.txt
== important.txt after: <MISSING>
```

The Gateway proof above is still valid for this head: its envelope does not involve a link, a hardlink or a path an earlier hunk frees, so it takes the same path as before the link and hardlink staging changes.

Hardlink names in unrestricted mode, same Gateway setup with `tools.exec.applyPatch.workspaceOnly: false`. The workspace holds `original.txt` (`one`) and `alias.txt`, a second hardlink to the same file. The turn sends `Update File: original.txt` (`one` to `two`), then `Update File: alias.txt` (`two` to `three`).

Before (previous head of this branch, rebased onto current main without the hardlink change; main accepts this envelope):

```
== before: original.txt=one alias.txt=one links=2
== agent exit: 0
== tool result the model received:
   {
  "status": "error",
  "tool": "apply_patch",
  "error": "Failed to find expected lines in <workspace>/alias.txt:⏎two"
}
== after: original.txt=one alias.txt=one links=2
```

After (this head):

```
== before: original.txt=one alias.txt=one links=2
== agent exit: 0
== tool result the model received:
   Success. Updated the following files:
M original.txt
M alias.txt
== after: original.txt=three alias.txt=three links=2
```

Tests (`src/agents/apply-patch.preflight.test.ts`, through the real `apply_patch` tool or `applyPatch`):

- Delete before an update of a missing file, and add plus update before a context mismatch: fail on main with the earlier effects committed, pass here. Updates of files added or changed earlier in the same patch, including a move, still apply.
- `Delete File: link.txt` (a symlink to an in-workspace `target.txt`) followed by a mismatched `Update File: target.txt`, or by `Update File: target.txt` / `Move to: link.txt` and a later update of `target.txt`: fail on an earlier head of this branch (the link is deleted before the error) and pass here with the link and target unchanged.
- `Delete File: link.txt`, `Add File: link.txt`, `Update File: target.txt`, `Update File: link.txt`, and `Update File: target.txt` / `Move to: link.txt` after the delete: fail on an earlier head of this branch (false context mismatch on the target, or an in-place rewrite instead of a move) and pass here.
- Outside-link and directory-link replacement (`Delete File: d`, then `Add File: d/x.txt`, `Add File: d/..cache`, `Delete File: d/x.txt`), a regular file replaced by a directory, and both names of a hardlink (re-create the deleted name, or update the other name): sequences main accepts; they fail on earlier heads of this branch, where admission ran only against the snapshot, and pass here.
- A moved symlink path updated again, and an outside-symlink update after an unrelated delete: reject before any mutation.
- Unrestricted mode (`workspaceOnly: false`) with two hardlink names: an update of the second name using text written through the first, alone or after deleting the first name, applies as on main. These cases pass on main, fail on the previous head of this branch, and pass here. A third case (move the first name away, then update the second against the original text) guards that a move does not carry the new contents to the other name.
- A removed outside symlink replaced under different casing (`Delete File: link.txt`, `Add File: LINK.txt`; `Delete File: d`, `Add File: D/x.txt`), gated on a case-insensitive temp volume. Run on macOS 15.7.9 (Intel, case-insensitive APFS) with this head's tests and each side's `src/agents/apply-patch.ts`: main passes both, the previous head of this branch (583baf2) fails both with `Symlink escapes sandbox root`, and this head passes both. The full apply-patch suites pass there on this head (162 passed, 1 Linux-only skip). Linux CI skips these two cases.
- A hardlinked symlink (Linux `link(2)` on a symlink): `Delete File: a` then `Update File: b` for the other name still updates the target, as on main; it fails on an intermediate version of this fix that matched any symlink by identity.
- Fail-to-pass run against main (merge base, Linux): the 7 regression tests above fail on main and pass here. The hardlink cases pass on main and here, and fail when the hardlink staging is removed from this head. The casing cases skip on Linux, so their before/after evidence is the macOS run above.
- `node scripts/run-vitest.mjs src/agents/apply-patch*.test.ts`: 12 files, 161 tests pass on Linux (2 macOS-only skips).
- `pnpm check:changed`: passes on the current head, apart from the dead export scan, which fails only on exports in files this PR does not touch (`src/plugins/config-policy.ts`, `src/media-understanding/defaults.ts`) and was skipped for the rerun.
- Review: a fresh-context code review at high effort, repeated after each round of fixes; its confirmed findings (move detection after a link delete, hardlink and directory-link replacement, held queue keys for removed link paths, case-folded link detection on the host, `..`-prefixed names under a removed link, abort checks during resolution) are fixed and covered above. A fresh-context review of the hardlink change found no correctness issue; it traced further hardlink, symlink and move sequences, which all matched the ordered writer, and the one wording note it raised is applied. A fresh-context review of the casing change found that a hardlinked symlink's identity also names its other entries (a delete of one name then made an update of the other reject); identity matching now requires a single link, with a regression test.

| Test file | `pnpm test <file> --maxWorkers=1` wall | CI seconds | New cases |
| --- | --- | --- | --- |
| `src/agents/apply-patch.preflight.test.ts` | 6.0 s (20 tests, 2 skip on Linux) | pending for this head | 20 cases, each under 15 ms of test time |
| `src/agents/apply-patch.test.ts` | 6.3 s | pending for this head | none (one assertion changed) |

## Maintainer E2E verification

Verified on macOS arm64 through an isolated, built Gateway and the real `openclaw agent` CLI. The Gateway used fresh state, workspace and HOME, loopback-only ports, and a local OpenAI Responses fixture model following the repository's existing HTTP/SSE test contract. No production state, personal API credentials, or CLI-login credentials were used. The model request advertised the real `apply_patch` tool; the next model request contained its actual `function_call_output` from the filesystem operation.

Baseline: `372ff7cacef` (fresh main). Candidate: contributor head merged with that main, then simplified; final head `e8d17b1d604780c1e351f74ef7e221fde5ba1967`. Runtime E2E ran at `6353875b56e` and again at `d908d9ea2d4`; the final commit only restores the existing permission-fence test assertion, without changing production code.

| Real Gateway scenario | Main | Candidate / simplified head |
| --- | --- | --- |
| Delete `important.txt`, then update missing `missing.txt` | Tool reports the missing-file error; `important.txt` is permanently missing | Same tool error; `important.txt` retains `irreplaceable-user-data⏎` |
| Add `created.txt`, rewrite `important.txt`, then fail a later context match | Not rerun on main | Simplified head rejects; only the unchanged original `important.txt` remains |
| Valid delete, add `notes.txt`, then update the newly added file | Not rerun on main | Simplified head succeeds; `notes.txt` contains `final⏎` |

Redacted model-visible failing result on both sides:

```json
{
  "status": "error",
  "tool": "apply_patch",
  "error": "Failed to read file to update <workspace>/missing.txt: Failed boundary read for <workspace>/missing.txt (path not found)"
}
```

The valid control returned:

```text
Success. Updated the following files:
A notes.txt
M notes.txt
D important.txt
```

All task-owned Gateways and fixture model servers were stopped. This is deterministic model-boundary proof, not a claim about live model behavior or commit-time rollback.

Checks:
- Baseline full `pnpm build`, candidate and simplified `pnpm build:runtime`: passed.
- All nine `apply-patch*.test.ts` suites were exercised. Initial result: 151 passed, one Linux-only skip, one outdated permission-error assertion failed. After restoring that assertion to main's existing contract, the affected suite passed all 51 tests. The other eight suites' passing results remain applicable.
- `node scripts/run-tsgo.mjs -p tsconfig.core.json --noEmit`: passed.
- `node scripts/run-tsgo.mjs -p test/tsconfig/tsconfig.core.test.agents-root.json --noEmit`: passed, including after the assertion repair.
- Scoped Oxlint and Oxfmt: passed.
- `check:test-timeout-race-ratchet --base origin/main`, `check:test-mock-exports`, and `check:assertion-safety`: passed.
- UI was not changed; no UI typecheck was needed.

## Maintainer simplification

Preserved the contributor's commits and merged current main without rebasing or force-pushing. The merge retains main's `ToolInputError` classification and its already-simplified parser in the extracted parser module. Replaced two temporary-array constructions in patch staging with direct iteration, including removal of the tuple assertion. Restored main's existing permission-change assertion because the current guarded read rejects before the envelope checkpoint; the test still proves the file remains unchanged.

The ordered staging, link/hardlink identity handling, and distinct filesystem regression cases are retained: they preserve accepted ordered patches while adding preflight, rather than pursuing a separate behavior change. No new rollback or partial-effect contract was introduced.

Final diff against the main merge base: production +725/-299 (net +426); tests +434/-0. Parser extraction accounts for +218 production lines; the required ordered preflight and filesystem-identity handling account for the remaining growth. The original `apply-patch.test.ts` has no net diff from main.

No overlap with Pash/Sarah changes in the touched files. Full diff security read found no new network access, credential reads, package/lockfile changes, or build-script changes. The contributor had 123 merged OpenClaw PRs at inspection.

The broader durability decision in #117742 / #127496 remains open: commit-time I/O failures, cancellation between writes, and other write-pass failures can still leave partial effects. This PR is the bounded update-preflight improvement and should not close those issues by itself.

Co-authored-by: Ayaan Zaidi <[email protected]>
(cherry picked from commit 5348bbc)
Co-authored-by: RomneyDa <[email protected]>
…ss (#178522)

* chore: claim configured primary catalog auth repair

* fix(models): honor configured primary account pins in catalog readiness

Co-authored-by: Eric Cai <[email protected]>
(cherry picked from commit 173309b)
Co-authored-by: RomneyDa <[email protected]>
* fix(copilot): setup probe fails without a persistent session

* fix(system-agent): supply recorders for ephemeral Copilot turns

* fix(copilot): bind verified turns to the installed runtime

* fix(copilot): preserve runtime identity across plugin captures

* refactor(copilot): trim redundant verification checks and tests

* fix(system-agent): preserve detached setup prompt projection

Keep durable-only projection operations off caller-owned memory recorders while preserving recorder identity and normal durable admission guards. Replace mocked prompt-copy coverage with a real LLM-boundary regression and preserve runtime-artifact mock exports.

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

* test(copilot): identify the fallback SDK fixture

Give the installed fallback fixture its canonical package name so the real loader can locate and fingerprint its package root. Preserve the production SDK identity check and existing fallback-import assertion.

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

* fix(copilot): dispose detached native setup sessions

Keep explicit detached runs out of resumable binding state. Join admitted tools and background compaction, then remove only their newly created SDK history while retaining caller-owned transcripts and ordinary conversation continuity.

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

---------

Co-authored-by: roboclaw-bot <[email protected]>
Co-authored-by: RomneyDa <[email protected]>
(cherry picked from commit 5b6ce79)
Co-authored-by: RomneyDa <[email protected]>
…taging (#180769)

2026.10.6 raised engines.node to >=24.22.1 <25 || >=26.12.1 (#179992). Package-mode updates (npm/pnpm global, Control UI update.run) staged and installed the target before checking its Node requirement, so users on older Node got an opaque global-install-failed. Target resolution now runs the existing runtime-compat owner first against the Gateway's selected Node and refuses with preflight-node-runtime-incompatible, leaving the Gateway untouched and naming the current version, the required range and the next step. Unknown engines metadata never blocks. Fixes #180636 (@sglion777), Fixes #180701 (@Almost-Certified-ops), Fixes #180707 (@billpang1-sketch); Refs #180688 (@rayluo88).

(cherry picked from commit 3755040)
Co-authored-by: RomneyDa <[email protected]>
…as truncated (#152565)

* fix(config): keep last-known-good when the observer flags the config as truncated

An externally truncated but parseable openclaw.json that the config observer
flags as an anomaly is still promoted over openclaw.json.last-good by the
next gateway start, which destroys the only recoverable copy of the
operator's configuration; doctor --fix then restores the truncated stub as
if it were the real config.

promoteConfigSnapshotToLastKnownGoodCore now runs the same
resolveConfigObserveSuspiciousReasons check the observer uses, with the
health entry's lastKnownGood as the baseline. A flagged snapshot is refused
promotion with a warning, leaving the last-good copy and the anomaly marker
untouched so the anomaly keeps being reported and doctor --fix restores the
real config.

Fixes #152509

* fix(config): advance last-known-good after accepted config writes

An accepted write that only removes verbose formatting (BOM, deep
indentation) shrinks raw bytes below half of the promoted baseline,
so the new promotion admission kept rejecting it and froze recovery
at the pre-edit settings; doctor --fix would then restore the verbose
pre-edit config. Doctor repairs and plugin uninstalls hit the same
dead end through allowConfigSizeDrop size drops.

The writer now advances the health baseline right after any write the
config owner accepted, so the next startup promotes the accepted config
whether the raw-byte reduction came from formatting normalization or an
explicitly permitted size drop. Stub-shaped results (missing meta,
missing gateway mode, update-channel-only root) keep the older baseline,
and external truncations never go through the writer, so they stay
rejected. The rejected-write block moves beside its guard in
io.write-safety.ts without behavior change.

io.factory.test.ts is updated where it pinned the old contract that
accepted mutation writes leave the health row untouched: the baseline
now lands right after the accepted write, while the remaining
observation facts still refresh only on the next observed read. The
promotion regression suite lives in io.snapshot.recovery.test.ts to
keep the config-cli tsgo shard at 700 test roots and within the
line-cap ratchet for io.write-config.test.ts.

* refactor(config): extract rejected-write persistence into io.write-rejected

Split rejectConfigWriteForBlockingReasons into a coherent sibling module so
io.write-safety.ts stays within the line-cap ratchet after the rebase.

* fix(config): restore the health baseline when a committed write rolls back

A config write that grows the file beyond twice its size and then fails
runtime activation rolls the file back to the original bytes, but the
accepted-write baseline advance had already persisted the grown candidate
as last-known-good. The next startup then flags the valid restored config
as a size-drop anomaly and the promotion guard refuses it, so the
recovery backup stays frozen at an older config while every start warns
about a truncation that never happened.

The writer now publishes the pre-write baseline alongside the advance and
restoreEffects compensates it after a successful rollback, keeping newer
observations (a baseline or anomaly signature recorded after the advance)
untouched.

Fixes #152509

* test(config): add pre-upgrade health-state compatibility proof

The health-state rows persisted by the previous build keep working after
this change: the config_health_entries schema, the fingerprint JSON shape,
and the permissive read contract are all unchanged. A regression test
seeds the row exactly as the pre-change build wrote it, then drives the
new promotion guard, the accepted-write baseline advance, and the
rolled-back-write restore against that pre-upgrade row.

Also fixes the check-test-types failure (TS2741) by supplying the error
logger required by the rolled-back-write test's config IO deps.

* fix(config): keep baseline persistence off the Gateway thread and safe from intervening reads

Accepted-write baseline advancement and rollback compensation ran the
synchronous health-store reader and writer, executing SQLite reads and
write transactions on the Gateway event loop during ordinary live
config writes, and the compensation read the prior baseline only after
the candidate file was published, so an observed read landing between
the publication and the baseline advance could record the grown
candidate as healthy and freeze promotion of a validly restored
config as a size drop.

The baseline capture, advancement and restore now run on the
worker-backed config health owner, and the writer captures the
pre-publication baseline so the conditional compensation always
retains the pre-write state.

* fix(config): stop concurrent observation from freezing the recovery backup

The three write-owned health transitions (baseline capture, accepted-write
advance, rollback restore) ran on the observer's health-state scope, so an
ordinary observed read landing while they awaited the worker superseded that
scope: the read returned null and the conditional update silently no-op'd.
For an accepted formatting normalization or a permitted size reduction below
half the old baseline, the competing observation recorded a size-drop anomaly
without advancing the baseline, so the next startup promotion kept refusing
the valid edited config and openclaw.json.last-good stayed stale.

Each transition now settles through a shared bounded retry that captures a
fresh scope, re-reads the persisted snapshot and re-applies its guard, so
supersession can neither drop the transition's read nor win a silent
conditional write. Newer valid baselines are still preserved and the
state-database ownership checks are unchanged.

Regression: "settles last-known-good advancement superseded by an observed
read" interleaves a synchronous observed read into the accepted write's
baseline advance and requires the following promotion to succeed.

* refactor(config): split promotion modules to fit line budgets

main's growth left io.observe-recovery.ts at 717 counted lines (700
cap) and io.snapshot.recovery.test.ts at 1063 (1000 cap) once the
promotion admission landed on top. promoteConfigSnapshotToLastKnownGoodCore
moves to io.observe-promotion.ts (io.observe-recovery exports the
shared commit helper and deps type it builds on), and the two
last-known-good promotion suites move to io.snapshot.promotion.test.ts.
The tsgo config-cli shard grows one advisory root. io.write-rejected.ts
follows NormalizedConfigIoDeps to its new io.read.types home, and the
new module is registered in the PR wrapper inventory so the
eager-import-closure and worktree-provision guards stay closed.

* fix(config): retain input anomalies after metadata stamping

Carry inherited input loss through the existing hash-bound health marker
so accepted writes, later observations, and promotion cannot bless it.
Retain healthy reductions and restore owned anomaly markers on rollback.

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

* fix(config): stop replaying uncertain health updates

Carry the health worker's applied/conflict/unavailable outcome through
accepted-write baseline advancement and rollback. Trust acknowledged writes
and only reconsider definite comparison conflicts within the existing bound.

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

* test(config): return Doctor health write outcomes

Preserve the captured health owner result in the Doctor freshness fixture
so its override satisfies the explicit write-outcome contract.

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

* test(config): describe stored health row continuity accurately

Remove the self-derived fingerprint-key assertion and historical upgrade
claims from the synthetic stored-row continuity case. Preserve promotion,
truncation, schema-column, and baseline compensation checks.

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

---------

Co-authored-by: roboclaw-bot <[email protected]>
Co-authored-by: RomneyDa <[email protected]>
(cherry picked from commit 99418fc)
Co-authored-by: RomneyDa <[email protected]>
…later update hunk cannot apply (#160409)"

This reverts commit e57e6d3.
…ss (#178522)

(cherry picked and adapted from commit 173309b)

Co-authored-by: RomneyDa <[email protected]>
fuller-stack-dev and others added 17 commits October 26, 2026 02:29
…ated 429s (#180280)

Release adaptation: ported the provider-timing-only rate-limit cooldown (lastRateLimitAt replaces failureCounts.rate_limit, legacy counters released, timing passed from every stable failure writer, WHAM probes and the fallback probe heuristic add no local delay, Retry-After prose and Google RetryInfo parsing). Main's exhausted-bucket reset header split (resolveProviderErrorRetrySeconds) and simple-completion profile failover are absent on stable and were not ported. Stable tests were rewritten to the new semantics; the embedded e2e suites (auth-profile rotation, fault sequences, run-embedded) need a build and were not run locally, and main's new rotate-fault e2e cases were not ported.

(cherry picked from commit 442c2f7)
withReleasableExecutionCapacity joined the raw task's cleanup on every
queue rejection. On stable it wraps enqueueGlobal directly, so a global
task timeout (queue already released the slot, rethrowQueueError aborts the
raw work) waited on a task that may never settle; the admission never
rejected and the waiting session lane lost its heartbeat and timed out.
Only join cleanup when the task is suspended outside capacity and its
readmission is refused; an admitted ticket's rejection surfaces promptly
as on the baseline.

The cherry-pick also dropped main's attempt timeoutMs from the replay
harness; the cast hid it, so projection recovery got a NaN budget, aborted
at once, and rethrew the first rebuilding error.
…ed semantics

Bedrock Responses routing cases used the shared discovery cache key, so the
default-region case read a cached result. #179471 no longer fails updates on
an unavailable channel, #183703 no longer treats missing meta as clobber
evidence, #180174 downgrades a missing legacy OAuth dir to a warning, and
#180280 leaves untimed 429s without a cooldown; their stale expectations
are updated to match main. The #183390 media case is wrapped in the stable
harness shape, and the Codex ownership harness now reports the original
owner's thread as loaded until it exits, as the app server does.
The case already fails on v2026.10.7: the updater's pre-mutation guard
refuses the sibling-held checkout before run-node's own refusal, so the
expected message never appears. Main removed this case in #182564.
Codex's background account check can land between the captured request
index and the held usage read under load, adding an unrelated request to
the window the assertion inspects.
#181356 resolves an API-key-only ChatGPT catalog row to the Platform
contract, so the Codex PDF case seeds the OAuth login as main does.
#181923 lets the K3 policy name hosted-catalog K3.1 rows the bundled
manifest lacks. #181804 restores configured stores after journal loss,
so Doctor refuses the legacy schema instead of holding them; the test
takes main's expectations and its host-broker project (#181964). The
Control UI locale artifacts are regenerated for the dropped restart
summary string.
…ol authority

Backport 714d666 (main 6a62821) declares codex_threads for every
sender and rejects nonowners inside execution. Port main's follow-up
74dfd5e, which expects the inherited declaration and the
owner-authorization denial instead of an undeclared tool.

Release adaptation: main's harness host passes its liveness check as plugin
invocation authority (#173455, not on stable). Stable takes that authority
from the admitted Gateway caller that run-attempt dispatch
(withPreparedEmbeddedGatewayTools) keeps ambient for the attempt, so the
fixture now supplies the same admitted caller identity for non-worker turns.

(cherry picked from commit 74dfd5e)
…ackages

#181140 reports replacing a copied openclaw package with the host symlink
as a repair warning; main's install test expects the same warning.
…ings

Ports main's translations for the two backported TalkModeManager recovery strings, drops the retired native.apple.4f81777177325153 entry, and regenerates the iOS catalog so release preflight native:i18n:check passes.
Backports the skill-library E2E wait from main's 6ff24eb (#171926). The replacement send can race the cancelled turn's persistence and fail with SessionEntryChangedDuringReadError; shipped 2026.10.7 reproduces the same race locally, so it is not a 10.8 regression. Main later replaced this wait with an owner fix (#172421) that depends on main-only authority semantics, and its own test still joins settlement before the replacement send.

(cherry picked from commit 6ff24eb, test hunk only)
Passive macOS Gateway stops now preserve an absent current-profile service definition without invoking uninstall, while explicit low-level ghost recovery remains available.

Release adaptation: the 2026.10.8 backport of #180390 removed the absent-plist
guard from GatewayLaunchAgentManager's disable path without main's follow-up,
so every passive stop with no LaunchAgent plist ran `openclaw gateway uninstall`
(mac validation: GatewayProcessManagerTests "pause preserves unretainable
services" [absent]). Stable has no migration-pending custody or `.authority`
wrapper, so the guard checks `custody.definition.plist` directly. Mac-only
post-tag fix; npm, Docker and Linux bytes are unaffected.

(cherry picked from commit cb10ec4)
Adapt the focused dependency repair from extended-stable commit 5025458 to release/2026.10.8. Preserve malformed scheme/host rejection and relative-reference semantics through the installed MCP SDK/Ajv graph.

Upstream-Fix: fastify/fast-uri@39933a1 (Vincent Le Goff)
Upstream-Fix: fastify/fast-uri@acc5c5d (Vincent Le Goff)
Upstream-Fix: fastify/fast-uri@f6d46df (Vincent Le Goff)
Upstream-Fix: fastify/fast-uri@a9b8d67 (Ulises Gascon)
Co-authored-by: RomneyDa <[email protected]>
OpenClaw-Publication: 98b4bbf4-bb10-4642-bfc9-0f388f770b20
@clawsweeper

clawsweeper Bot commented Oct 29, 2026

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

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

@RomneyDa RomneyDa changed the title fix(security): backport fast-uri 4.2.3 to release/2026.10.8 DO NOT MERGE: publisher workspace mismatch for fast-uri stable backport Oct 29, 2026
@clawsweeper

clawsweeper Bot commented Oct 29, 2026

Copy link
Copy Markdown
Contributor

ClawSweeper proposes closing this pull request because it changes 207,816 lines (169,891 added, 37,925 removed) across 4,291 files, above this repository's 50,000-line limit for review. Changes this large cannot be reviewed safely or scanned within limits and usually indicate a stale branch merged against an old base. Please open a fresh pull request from current main containing only the intended change, or split it into focused pull requests. A maintainer can apply size: accepted-large to exempt a deliberately large change.

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.