Skip to content

fix(cli): keep Memory and Matrix state consistent with the Gateway - #168471

Merged
steipete merged 26 commits into
mainfrom
dbasync/ow3-memory-matrix
Oct 10, 2026
Merged

steipete merged 26 commits into
mainfrom
dbasync/ow3-memory-matrix

Conversation

@steipete

@steipete steipete commented Oct 10, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Memory and Matrix CLI processes could write SQLite while the Gateway retained cached state. With the Gateway as the single database owner, these commands must execute in that owner or hold exclusive offline custody.

Stacked on the Workboard CLI owner foundation (#168457; dbasync/ow3-workboard); this PR changes only the Memory and Matrix families and their shared effect scope.

User Impact

Commands Behavior with a running local Gateway
memory search Routes through the existing search owner, preserving CLI limits, session scope, recalls, diagnostics, and disabled/error output.
memory session-backfill preview/apply/rollback Routes bounded batches through the existing backfill owner, preserving full CLI results and the same owner across the operation.
Other Memory commands; backfill with --rem or --archive-files Refuses before opening writable state and explains how to stop the Gateway and retry offline.
matrix verify status, verify bootstrap, verify device Routes through the existing account verification handlers.
Other Matrix commands Requires exclusive offline ownership through crypto persistence and client shutdown.

The existing memory.status RPC returns provider health, not the CLI's aggregate index/source/embedding/dreaming diagnostics or repair options. Those CLI operations remain offline-only. Account setup/encryption commands retain their combined crypto and configuration publication rather than substituting only a bootstrap RPC.

Why This Change Was Made

The canonical runWithLocalStateOwner selects the live owner or acquires offline custody. Distinct .owner RPC adapters share the existing domain implementations and require the expected owner identity. Required-method discovery prevents an older, independently installed plugin from ignoring the new contract. Legacy RPC names and responses remain available.

The lazy search artifact and Gateway adapter share types from the existing memory host owner. Core consumes that contract without importing the plugin's implementation into its TypeScript graph.

Routed responses follow accepted work and cleanup. Matrix preserves its existing client-owned crypto settlement independently of caller transport authority. Memory binds actual keyed-store, origin-worker, diary, and corpus effects to current authority; its workspace lease remains outside that revocable scope so cleanup can settle. Backfill keeps the existing batch limit, ordering, aggregation, and progress rules. A lost owner between batches refuses before local configuration admission. Uncertain requests are never replayed locally.

The normal unscoped Memory path retains its original store APIs, worker requests, and append operations. No schema, index, retention, permission, or durability change is introduced. Corpus writes retain hardlink/parent-symlink checks, mode 0600, and the existing non-fsync durability behavior. Existing configuration CAS and Matrix recovery-key opt-in remain intact.

Evidence

Candidate b9e6f84640bdd (tree c4503b7d65c73f0bb2ebebf472d17577f6e63f45) uses tested Workboard parent a536559ee72c and its main integration ff06ae699514; the target parent is 3c0ab3d0ee7b, which also carries the later Workboard repairs. Their merge tree is clean. Final behavioral and API proof ran at d1fec3c9bfb79. The only subsequent difference is three erased test declarations changed from method signatures to standalone function properties; typed lint passes on b9e6f84640bdd.

All 87 final focused cases passed: CLI owner routing/refusal (34), real Memory write authority (9), backfill Gateway (11), backfill owner (32), and Matrix persistence/disclosure (1). They exercise actual lock discovery and registered handlers with mocked transport, public plugin registration, no local replay after uncertain delivery, complete batch output, offline custody, real SQLite/file effects, and accepted-work settlement after revocation. Unchanged Matrix, Memory search/CLI, origin, ingestion, and diary owner proof is reused. These are isolated synthetic fixtures, not authenticated homeserver proof.

Negative controls passed only when the intended assertions failed; collection failures and timeouts were rejected. Each control ran in a private snapshot, and the original tree was verified after restoration:

Disabled contract Expected failing cases Wall seconds
Route/exclusive-offline admission 12 34.4
Memory authority capture at four real write boundaries 4 31.1
Matrix final disclosure check after persistence settles 1 23.9

Madge passed in 74.0 seconds. The T1 worker ratchet passed against a536559ee72c, with no growth; subsequent repairs preserve the database call sites. The final SDK API diff passed in 346.9 seconds (acknowledgement digest c6bf74ec): one documented effect-scope export and one compatible optional onNoOwner: "refuse" argument. Four changed reachable declarations affect 212 exports transitively. SDK budgets are 152 entrypoints, 3,649 exports, and 2,119 callable exports; the shared Memory types use the existing private-local facade.

The full check:changed wrapper stops on an inherited environment-name budget failure: parent and candidate both contain 456 names against 455, with no names added or removed by this PR. The extra OPENCLAW_PITCH is in untouched src/gateway/control-ui-public-session-render.ts; main fixed it in 060b20e595f3. All remaining canonical commands and affected repair checks ran directly without changing the wrapper or budget. Owned diagnostics are cleared. Broad graph/type checks still report only Workboard entries from the tested parent, repaired in the target parent branch. The final narrow typed lint passes in 11.6 seconds; the CLI type shard takes 10.4 seconds and reports only those inherited Workboard errors.

Knip all-exports passed in 92.1 seconds. Production Knip flags only three untouched inherited items: .github/actions/setup-release-harness/narrow-lockfile.mjs, src/infra/sqlite-source-fence-admission.ts, and PUBLIC_SESSION_ENTRY_SCRIPT in the public-session renderer.

Full pnpm build passed on final head b9e6f84640bdd in 487.81 seconds on macOS / Node 26.11.1, using the permitted static-proof fallback through the campaign proof slot after remote capacity waits. A 1.36-second smoke then used the compiled dist/plugins/public-surface-runtime.js resolver, found the built Memory Core manifest and search-api.js artifact, imported the compiled export, and invoked it against synthetic state and a synthetic manager. The expected result, exact query, max-results/min-score options, and CLI session key were preserved. No TypeScript loader or source import was used; source remained clean.

Three Codex P2 review rounds were completed. Routing findings are addressed by the owner adapters above. The retained P2 follow-up is to carry Matrix's initially resolved account identity into response labeling instead of resolving it again after awaited work. The current owner/config fence rejects changed configuration before disclosure. The campaign's three-round convergence limit applies; subsequent changes complete required search routing and correct settlement, path safety, and validation failures.

Published-driver × candidate update proof: PASS on b8fd5eee5d4d1b70ac443213c4b24096ed88aaf9, Testbox tbx_01m4kbkyty1253x73aw2pjhprz. Released 2026.9.9 driver updated to the candidate successfully; readyz returned 200 and the running candidate version was verified. Package SHA-256: 94125651f76de3480a388535fd6b5d924f8d8786089faa33a32f2f33d09e54d3. No migration is required.

SQL and worker-request accounting

No statement or worker-request saving is claimed by this ownership cutover. Memory and Matrix CLI family-flow statement/request totals were not measured. The shared campaign measured the following baseline at 427f926e7c2d across three alternating pairs. These are context, not a measurement of this PR's head. Each cell is median [minimum–maximum]; warmed values are per turn across ten turns, while the other rows are phase totals.

Phase Baseline all-thread SQL Baseline MAIN SQL Baseline worker requests
Boot 3347 [3325–3351] 1988 [1986–1988] 69 [66–70]
Connect 379 [314–462] 61 [61–63] 45 [37–46]
First turn 1988 [1875–2497] 77 [56–105] 291 [290–346]
Warmed turn 1105.7 [1087.7–1189] 13 [11–19] 204.4 [200.1–213.2]
Second session 4270 [4108–4347] 134 [126–156] 709 [688–729]
Control plane 86 [33–100] 13 [0–23] 11 [5–20]
Cron 1327 [1257–1403] 44 [40–46] 202 [190–213]
Compaction 422 [408–526] 25 [25–53] 85 [84–102]
Shutdown 201 [197–205] 133 [130–133] 15 [15–15]

The original root devices/backups macOS comparison retained warmed medians of 1105.7 → 1121.5 SQL/turn and 204.4 → 204.8 requests/turn, plus first-turn SQL of 1988 → 2478. Those increases led to the designated whole-workload follow-up; they are not replaced by later observations.

The campaign ran two separate whole-workload follow-ups for that root change. Both compare 427f926e7c2d → b2825e4bebc51, not this Memory/Matrix head, and neither is pooled with the macOS samples above:

Follow-up, startup through shutdown All-thread SQL M → C Worker requests M → C Evidence limit
Designated Hetzner check 22583 → 22437 (−146) 3396 → 3391 (−5) Summary retained; per-operation data and the complete phase table were lost during cleanup.
Separate retained Testbox check 21645 → 21652 (+7) 3315 → 3317 (+2) Counts fully reconciled from retained operation/caller vectors; raw event-level async origins are unavailable.

The designated follow-up passed the campaign's whole-total criterion. Its retained summary also records first-turn SQL of 1904 → 1808, warmed SQL/turn of 1079.4 → 1069.3, and whole-workload duration of 52.239 → 52.149 seconds. Its missing breakdown cannot be reconstructed from the separate Testbox vectors. The Testbox increases remain visible; no reproducible statement/request class caused by the measured routing change was established. Neither observation supports a statement/request saving claim.

The retained Testbox pair compares 427f926e7c2d → b2825e4bebc51 on one host in M,C order. Each cell is a one-sample median [minimum–maximum]; warmed values are per turn over ten turns. Whole-workload duration was 41.840 → 41.774 seconds, and all phase duration ratios were between 0.983 and 1.060.

Testbox phase All-thread SQL M → C MAIN SQL M → C Worker requests M → C
Boot 3320 [3320–3320] → 3319 [3319–3319] 1984 [1984–1984] → 1984 [1984–1984] 67 [67–67] → 67 [67–67]
Connect 484 [484–484] → 490 [490–490] 69 [69–69] → 69 [69–69] 72 [72–72] → 73 [73–73]
First turn 1813 [1813–1813] → 1816 [1816–1816] 59 [59–59] → 59 [59–59] 264 [264–264] → 263 [263–263]
Warmed turn 1023.9 [1023.9–1023.9] → 1023.4 [1023.4–1023.4] 7.8 [7.8–7.8] → 7.8 [7.8–7.8] 195 [195–195] → 195 [195–195]
Second session 3944 [3944–3944] → 3948 [3948–3948] 118 [118–118] → 118 [118–118] 684 [684–684] → 686 [686–686]
Control plane 34 [34–34] → 34 [34–34] 0 [0–0] → 0 [0–0] 5 [5–5] → 5 [5–5]
Cron 1210 [1210–1210] → 1211 [1211–1211] 44 [44–44] → 44 [44–44] 175 [175–175] → 175 [175–175]
Compaction 406 [406–406] → 405 [405–405] 25 [25–25] → 25 [25–25] 84 [84–84] → 84 [84–84]
Shutdown 195 [195–195] → 195 [195–195] 129 [129–129] → 129 [129–129] 14 [14–14] → 14 [14–14]

The Testbox phase deltas reconcile exactly: SQL −1 +6 +3 −5 +4 +0 +1 −1 +0 = +7; requests 0 +1 −1 +0 +2 +0 +0 +0 +0 = +2. First-turn SQL reconciles as +3 lifecycle-artifact-plan, +3 session-pending-archives, +1 each for mentions.snapshot, restartSentinel.snapshot, and workers.placementProjection, −1 session-exact-entries, and −5 catalog. The two added whole-workload requests are one each in session-row-facts and sessionRows.sharedFacts.

Every named varying caller file is byte-identical between the measured pins, and no retained native SQL stack names any of that root change's nine changed operational files. All 26 top-level turns completed and MAIN/worker calibration agreed; two failed native executions remain recorded in the shared evidence. Raw per-event streams were removed after verified reduction. Retained phase boundaries, request totals, normalized SQL, and unique stacks provide complete count attribution, but cannot reconstruct arbitrary worker/timestamp/async-origin chains or prove that every unknown origin was background work. This limitation and the separate lost Hetzner breakdown remain explicit.

Attribution Removed SQL Removed worker requests
This PR 0 0

Only owner-routed CLI invocations install the new mutation callback. Without that scope, openMemoryCoreStateStore returns the original store without withCurrent; origin writes receive their existing undefined optional assertion; ordinary batch execution bypasses the new scope; and the legacy memory.search path retains its original acquisition, search, response, and cleanup calls. The lazy public artifact does not load recall runtime for legacy searches. No new ordinary-turn statement or request is identified by source inspection. This is a source-level comparison, not a measured zero delta for this head.

Size and validation cost

Relative to the shared parent foundation: production +1053/-446, tests +1366/-18, docs +41/-1. Production is Matrix +142/-35, Memory and its host contract +882/-408, and shared ownership/budget +29/-3. Memory includes extraction of the existing search handler, CLI rendering, and batch-drain algorithm so online and offline paths share behavior. Ignoring whitespace-only movement, Memory is +681/-207. The raw count exceeds the grouping aim; the additional code carries effect-boundary authority, settlement, and the required existing-RPC adapters.

Each full file below ran as pnpm test <file> --maxWorkers=1 on the local macOS host under the campaign proof slot. The final fallback preflight measured one-minute load 12.14 and about 78 GiB free. Earlier unchanged-file proof is marked separately. CI seconds are not yet available.

Test file Passed Wall seconds Witness
extensions/matrix/src/config-handoff.test.ts 8 34.0 Reused 7b859baeab70b
extensions/matrix/src/matrix/client-bootstrap.test.ts 6 24.5 Reused 7b859baeab70b
src/gateway/server-methods/memory-search.test.ts 22 58.8 Reused 7b859baeab70b
extensions/memory-core/src/memory-mutation-authority.test.ts 9 72.4 d1fec3c9bfb79
extensions/memory-core/src/cli.test.ts 59 73.1 Reused 7b859baeab70b
extensions/memory-core/src/session-backfill-gateway.test.ts 11 35.5 d1fec3c9bfb79
extensions/memory-core/src/session-backfill.test.ts 32 69.1 d1fec3c9bfb79
src/cli/plugin-local-state-owner.test.ts 34 87.8 d1fec3c9bfb79

The Matrix disclosure case was rerun at d1fec3c9bfb79: 1 passed in 31.7 seconds. Unchanged Matrix CLI/lifecycle siblings passed 39 tests in 55.9 seconds; Gateway descriptor/registry siblings passed 11 in 4.3 seconds. Wall time includes transformation and compiled-worker preparation. The existing Memory CLI suite spends about 45 seconds in tests covering real index reset/rebuild, preservation of canonical session bytes, backfill, and cleanup. The Gateway search suite spends about 27 seconds in tests, principally real recall persistence and concurrent format-repair ownership. Replacing those boundaries with mocked writes would lose the state and settlement contracts this change needs.

Accepted P1 correction: requester authority on node-backed Memory writes

Fixed in fd1b559668ac2; final head 2463c25b7b268 completes the regression fixture's provenance fields. Owner-routed diary and corpus writes previously checked the requesting operator before entering a remote client that retained only the workspace service lifetime. Revocation during duplex preparation could still send the remote start frame.

writeDreams and appendCorpus now carry the captured assertCurrent callback through the Memory maintenance API and shared client, separately from the serialized request. The node adapter passes it into the existing service invoker, checks after openDuplex resolves, and checks immediately before sending start. Startup refusal closes the channel and awaits its accepted cleanup; listener setup is covered by the same cleanup boundary. The wire request and database schemas are unchanged.

Validation for this correction:

Proof Result
Pre-fix regressions Both diary/corpus cases sent start after revocation; both capture cases received no assertion. Four intended failures reproduced on b9e6f84640bdd.
Focused production-owner and sibling tests 64/64 across six files, 170.48 s wall with --maxWorkers=1. Includes held duplex preparation, revocation, no remote start, held cleanup settlement, and permitted controls.
Final fixture recheck memory-mutation-authority.test.ts: 11/11, 68.15 s wall. Final extension-test typecheck reports only the inherited Workboard diagnostics below.
Build pnpm build passed, 1090.72 s wall at fd1b559668ac2; the later commit changes only test fixture data. Nonfatal UI startup gzip warning: 365.0 KiB versus 364.7 KiB. No UI source changes in this correction.
Static checks Both changed-file lint passes; no T1 call-count growth; zero runtime import cycles; Knip full-tree and script scans each report zero entries. Of 40 selected commands, 34 pass and six report the inherited issues below.
SDK diff b9e6f84640bdd → 2463c25b7b268, digest 127c1ded, 362.37 s. One signature and two reachable declaration changes, adding optional callbacks; no exports added or removed.

The new remote-race test body takes 6 ms in the final single-worker run. The changed Memory suite's wall time includes compiled-worker preparation and its existing real SQLite/rollback tests. CI seconds for this head are not yet available.

The top-level check-changed failure is retained; its remaining native command plan was run separately to completion. Inherited failures are:

  • Environment-name budget: 456 names versus 455 on the pre-fix head, candidate, and origin/main at baff85bf5e7b. This correction introduces no environment names.
  • Workboard's old core-test imports/runtime fixture and CLI started/startFailures typing: the affected files are byte-identical to the pre-fix head. Main includes the corrected Workboard code in c4e70bc82a5f7 (fix(workboard): keep CLI changes visible to the running Gateway #168457).
  • The separate production export scan rejects PUBLIC_SESSION_ENTRY_SCRIPT in an unchanged Gateway file. Main fixes it in 06c6e83f4351f.

Initial automatic test-runtime preparation refused because managed-artifact separation was unverified. The explicitly requested normal build succeeded, and the subsequent test run reused those completed artifacts successfully. All proof here ran locally through the campaign proof slot; the full remote queue was released without acquiring a lease.

This correction adds/removes 61/35 production lines, 150/1 test lines, and 4/0 documentation lines. The production growth carries the existing authority closure and settles accepted transport work; it adds no routing owner. No ordinary-turn SQL path changes or SQL savings are claimed, and no SQL remeasurement was requested for this correction. The existing three-round review convergence limit remains in effect; this addresses the accepted P1 without starting another review loop.

Landing check at b8fd5eee5d4d1b70ac443213c4b24096ed88aaf9

Merged main 9d38ebae7d220cfae45f312d727611e700a97e95 with conflict-only resolutions. Focused remote proof passed 86 tests across the Workboard CLI/Gateway, shared local-state owner, and method registry in 86.61 seconds.

Landing is blocked by CI run 38070217223:

  • checks-node-changed-extensions-config-7: both named-encryption Commander repair cases in extensions/matrix/src/direct-encryption.test.ts:232 expect zero host SQLite calls but observe [22, 0, 2, 1, 8, 11] after the new local-state ownership admission. Repair output and cleanup assertions pass. Resolving the zero-SQL contract without weakening its assertion needs coordinator disposition.
  • QA Smoke CI (profile 4/4): memory-dreaming-sweep invokes an offline-only Memory CLI operation while the test Gateway owns the state. Admission refuses with This operation requires exclusive offline state ownership. The fixture needs an owner-compatible flow.
  • checks-node-changed-compact-small-18-1: chat.send returns in_flight when duplicate attachment send wins parsing race expects one call and observes zero in src/gateway/server.chat.gateway-server-chat-b.test.ts. Attribution is not established; no inherited-failure waiver is claimed.

No assertions, budgets, or baselines were relaxed, and no auto-merge request was submitted.

Earlier correction at 31c362d7dd45: offline ownership, QA indexing, and chat attribution

The asynchronous shared config-loading change and CLI-wide zero-host-SQL scope described in this historical evidence were superseded by the coordinator decision below. The QA lifecycle fix and worker-owned lease inspection remain.

Fixed in 31c362d7dd45 after the conflict merge. Normal offline CLI admission now uses the existing worker-owned lease reader and asynchronous config reader. Once physical custody is held, the lease worker reads the selected database directly; it does not create a temporary snapshot whose SQLite staging tokens run on the host. Explicit Doctor/maintenance reads retain their private snapshot and legacy-schema admission. The internal worker command carries that distinction; its existing Doctor caller and regression are migrated together. The Matrix zero-host-SQL assertion is unchanged.

The memory-dreaming-sweep helper invoked memory index --force while its Gateway was live. There is no existing force-index RPC. The helper now uses the existing restartAfterStateMutation lifecycle: stop, run the offline index command, restart, then run the already-routed Memory search. The CLI's clear live-owner refusal remains. This adds no RPC or routing owner.

Host SQLite API calls per Matrix Commander repair case (two encryption settings) are below. Counters are not additive statement totals:

API Before After
prepare 22 0
exec 0 0
get 2 0
all 11 0
run 8 0
iterate 1 0

A traced intermediate run isolated the remaining 17 prepares to SQLite snapshot-staging tokens. Direct worker inspection removes that staging path from ordinary offline admission; lease inspection itself stays in the worker. No all-thread statement or request reduction is claimed. These changes execute during offline CLI admission or QA orchestration, not ordinary chat turns; no turn-SQL measurement was run for this correction.

Both Matrix cases failed before the repair. The new QA regression also failed before the repair because index spawned while the Gateway was live; it now verifies stop → index → restart → search through the real CLI process adapter. Final focused proof includes 5 Matrix tests, 24 QA helper tests, 34 shared CLI-owner tests, and 7 Doctor serving-owner tests: 70 passed. Earlier in this correction, the 37 lease-owner tests and the ambient-selector regression also passed. The Matrix/QA run took 495.91 s wall (286.13/37.10 s Vitest per file); shared-owner/Doctor took 505.74 s wall (191.96/294.13 s per file). Cold compiled-worker preparation and real ownership/SQLite lifecycle coverage account for the longer wall times. CI seconds for this correction are pending.

The requested single main comparison used fa95932d442fd3aa82ae4fe01dd0b9ac5abdf993, Node 24.21.0 on macOS, and the exact chat.send returns in_flight when duplicate attachment send wins parsing race test. It failed in 505.94 s wall at line 2366: catalog loading had not begun within the existing 2,000 ms wait; cleanup reported Session target discovery was revoked. CI run 38070217223 failed later at line 2396 because dispatch had not begun. This is not an identical reproduction, and no exact-failure waiver is claimed. The test, chat handler, dispatch, setup, and skill-library owner are byte-identical between candidate and main and untouched by this PR. The handler acknowledges started before detached dispatch awaits preparation, making the immediate dispatch-count assertion timing-dependent. No PR-specific chat regression was identified; the nonidentical main failure remains an explicit evidence limitation. No second comparison or chat change was made.

This correction is production +48/-35 and tests +41/-1. It adds no schema migration or public SDK surface. The existing three-round review convergence limit remains in effect; no fourth review loop was started. Dependency refresh used the merged lockfile. Initial lint preparation timed out and then exposed the stale install's missing eslint-plugin-solid; the refreshed core lint passes.

pnpm build passed at 31c362d7dd45 in 1,047.06 s wall. Its nonfatal UI startup gzip warning is 366.2 KiB against 366.1 KiB; this correction changes no UI source. The new QA regression takes 4 ms. Full QA Smoke CI was not rerun locally; the focused lifecycle regression proves the corrected helper path. The published-driver update proof above remains evidence for the earlier merged head; no new update cell or SQL measurement was requested for this correction.

Final targeted core and QA lint passes both succeeded after dependency refresh. Formatting and git diff --check pass. The worktree is clean; the PR is left open and ready, without a merge request.

Final conflict resolution: preserve lazy CLI config admission

Integrated main 457515502e84 in dbeb76eb1a3f. src/cli/local-state-owner.ts is byte-identical to that main version from #168466: ownership checks happen before config loading, and config-free local operations can refuse without loading config or creating/changing their database. Configuration is loaded only when the accepted callback accesses it. No new accessor, public contract, or consumer migration was added.

This follows AGENTS.md, whose worker rule explicitly lists “Doctor/CLI one-shots” among synchronous SQLite exceptions. The Matrix Commander repair test runs in the CLI process, so its blanket zero-host-SQL assertion was removed while keeping its output, encryption, auth, ownership, and persistence assertions. Gateway-hosted native approval target preparation retains its original, unchanged zero-additional-host-SQL assertion, covering encryption resolution and direct-room repair. The existing availability credential lookup remains outside that original measurement boundary. Worker-owned reads remain intact.

The eager async alternative was rejected by the unchanged owner regressions: it created a 1,429,504-byte database on the missing-file refusal and expanded a zero-byte database to 1,421,312 bytes. Main's lazy implementation is retained instead. The byte-preservation regressions and corrected backup outcome assertion are unchanged.

Taking main unchanged also removes this branch's unshipped onNoOwner option. The existing between-batches regression caught a local replay after that removal. Memory now rejects at the start of its existing local callback once a Gateway batch has run, before importing or executing local backfill. The retired option and its documentation were removed. This adds no shared API and keeps the helper unchanged. The existing 34 owner tests pass locally, including the stopped-owner/no-local-replay case; the earlier SDK diff's onNoOwner addition is superseded.

Final commit 47094194f085 has tested tree d9af2b8a2bef00382e4f38c740148918b180d0c8. All 289 focused tests across 15 files passed in 151.08 seconds of wrapper wall time on Testbox tbx_01m4kkmx62a6nrc4a28bbcs9a8 (run). Coverage includes #168466's unchanged missing/zero-byte/live-owner byte-preservation regressions and archive cases, Matrix Gateway target preparation and Commander behavior, Memory routing/authority/backfill, remote workspace writes, shared owners, Doctor admission, and the QA index lifecycle. The Testbox command including install/setup took 206.50 seconds; those are runner seconds, not local estimates.

Full pnpm build passed in 200 seconds on 29cc956a56fc. The final commit changes only the Matrix test to restore its original Gateway scope, so production and build inputs are identical. Dependency installation, formatting, and diff-whitespace checks passed. Earlier failed runs were the stopped-owner regression corrected in Memory's local callback and the overly broad test assertion corrected above; neither was bypassed. No new SQL measurement or published-driver cell was run for this conflict correction; prior evidence and limitations remain above.

Relative to integrated main: production +1,150/-511 (net +639), tooling +4/-2, tests +1,588/-58, docs +45/-1. The shared config helper has no diff against main. The first test-only revision unnecessarily included the existing availability lookup (one prepare/iterate) in the Gateway assertion; that scope expansion was reverted, preserving the original Gateway assertion exactly. Size reflects the two-family ownership cutover and its existing authority/settlement contracts; this resolution keeps the existing helper and adds only the callback’s early refusal. No new turn SQL or worker-request savings are claimed. Earlier SQL/update evidence and its stated limitations remain above. Three P2 review rounds were already completed; the campaign's review-convergence rule is unchanged.

@clawsweeper

clawsweeper Bot commented Oct 10, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

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

ClawSweeper review complete

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

View the workflow run.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation channel: matrix Channel integration: matrix gateway Gateway runtime extensions: memory-core Extension: memory-core cli CLI command changes scripts Repository scripts size: XL labels Oct 10, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. labels Oct 10, 2026
@steipete
steipete merged commit e40606f into main Oct 10, 2026
152 of 158 checks passed
@steipete
steipete deleted the dbasync/ow3-memory-matrix branch October 10, 2026 20:09
steipete added a commit that referenced this pull request Oct 11, 2026
The Gateway route introduced in #168471 loaded Memory Core's CLI search
helper as a public library artifact outside its registered plugin instance.
Search still returned hits, but recall recording used an unconfigured
instance-local store and its best-effort error was swallowed.

Delegate CLI search through the acquired memory runtime so retrieval and
recall recording share the configured plugin instance and requested agent.
Keep the Gateway as the database owner and remove the superseded public
search helper.

Strengthen the Gateway recall test with an instance-local store and add a
Memory Core regression proving three routed searches become a dreaming
candidate only in the requested agent's workspace. The original Gateway
handler fails the strengthened recall assertion.

Validation: 98 focused and sibling tests passed (117s wall; new candidate
regression 0.9s), followed by all 22 Gateway tests after the test-only type
boundary correction. One P1 Codex autoreview found no actionable issues.

Changed-check caveats: the baseline has an unrelated first-party mock
export violation in model-picker/apply-session-model-selection-placement
and an unused env in plugins/channel-presence-policy.ts. Production and
full-tree Knip scans timed out, as did extension lint's SDK declaration
preparation. Core test typechecks, extension test typechecks, and targeted
core lint passed after correcting fixture-only type/naming issues.

Optional Testbox QA never started: admission timed out after 15 minutes
queued. The lease is stopped and the campaign slot released.
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 11, 2026
…penclaw#168471)

* fix(cli): fence memory and Matrix commands behind state ownership

* feat(plugin-sdk): expose local state owner routing for CLI commands

* fix(cli): route memory and Matrix writes through the Gateway owner

* fix(workboard): route CLI mutations through the active Gateway

* fix(workboard): preserve dispatch without explicit parameters

* fix(plugin-sdk): type and account for the CLI ownership surface

* fix(memory): preserve search semantics through Gateway ownership

* test(workboard): preserve state owner module exports

* test(workboard): prune the retired config mock allowance

* test(cli): capture runtime search diagnostics at console output

* fix(memory): keep CLI search contracts outside plugin runtime graphs

* test(cli): load owner fixtures through public plugin facades

* test(cli): model facade exports as standalone functions

* fix(memory): retain requester authority through remote dispatch

* test(memory): complete remote corpus authority fixture

* fix(cli): keep offline owner admission off host SQLite

* fix(memory): reject offline replay at backfill callback

* test(matrix): retain Gateway SQL boundary for CLI exception

* test(qa): keep recorded memory command arguments typed

Record the command slice so noUncheckedIndexedAccess does not pass string | undefined into the operation log. All existing lifecycle assertions are preserved. Focused QA suite: 24 passed in 49.97 seconds; P0/P1 autoreview clean.
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 11, 2026
The Gateway route introduced in openclaw#168471 loaded Memory Core's CLI search
helper as a public library artifact outside its registered plugin instance.
Search still returned hits, but recall recording used an unconfigured
instance-local store and its best-effort error was swallowed.

Delegate CLI search through the acquired memory runtime so retrieval and
recall recording share the configured plugin instance and requested agent.
Keep the Gateway as the database owner and remove the superseded public
search helper.

Strengthen the Gateway recall test with an instance-local store and add a
Memory Core regression proving three routed searches become a dreaming
candidate only in the requested agent's workspace. The original Gateway
handler fails the strengthened recall assertion.

Validation: 98 focused and sibling tests passed (117s wall; new candidate
regression 0.9s), followed by all 22 Gateway tests after the test-only type
boundary correction. One P1 Codex autoreview found no actionable issues.

Changed-check caveats: the baseline has an unrelated first-party mock
export violation in model-picker/apply-session-model-selection-placement
and an unused env in plugins/channel-presence-policy.ts. Production and
full-tree Knip scans timed out, as did extension lint's SDK declaration
preparation. Core test typechecks, extension test typechecks, and targeted
core lint passed after correcting fixture-only type/naming issues.

Optional Testbox QA never started: admission timed out after 15 minutes
queued. The lease is stopped and the campaign slot released.
obviyus added a commit that referenced this pull request Oct 11, 2026
Related: #168135, #168108, #168471

## What Problem This Solves

Fixes API-key setup from the CLI when a running Gateway owns local state.

## User Impact

Users can run `openclaw models auth paste-api-key --provider <id>` without stopping the Gateway. The Gateway saves the key and refreshes its model catalog. Offline behavior is unchanged. An explicit, non-empty `--profile-id` still requires offline use.

## Why This Change Was Made

#168135 correctly stopped CLI processes from writing credentials around a live Gateway. It also kept CLI flows offline where the existing Gateway APIs could not preserve their behavior. Manual API-key setup already uses the same credential writer as `models.authSetApiKey`, so that subset can use the owner instead of refusing.

This change uses the canonical `local-state-owner.ts` route, as in #168108 and #168471. It binds the request to the discovered local owner and port, sends `expectedOwnerId`, requires `operator.admin`, rechecks ownership before dispatch, and never retries a possibly accepted write locally. API-key input is collected only after owner selection. The RPC checks the expected owner at credential and config writes; calls without that field retain their existing behavior. Owner-bound requests preserve the CLI's agent-selection rules.

Update behavior: an older Gateway that lacks `models-auth-set-api-key-owner-v1` is refused before the API-key request; update and restart it, or stop it and retry offline.

No request/response schema, new RPC method, config option, database schema, or paired-device fallback is added.

### Command-to-RPC mapping

| CLI command or option | Existing RPC | Result in this change |
| --- | --- | --- |
| `paste-api-key --provider <id> [--agent <id>]` | `models.authSetApiKey` | Delegate provider, key, and agent; print saved profile and any application warning. |
| `paste-api-key --profile-id <id>` | No profile-id field in `models.authSetApiKey` | Refuse this option with offline guidance. |
| `paste-token [--expires-in <duration>]` | No equivalent API-key write | Stay offline: token type and expiry must not become an API key. |
| `login`, including API-key plugin methods | `models.authLogin` and `wizard.*` | Stay offline: CLI method/profile/default/force semantics are not an exact manual-key mapping. |
| `login-github-copilot` | `models.authLogin` and `wizard.*` | Stay offline; device flow is outside this change. |
| `add` / `setup-token` | No exact generic mapping | Stay offline; these can run local provider CLI or import flows. |
| `list` | `models.authStatus` | Stay offline: the status projection lacks the CLI list's state-path, cooldown, disabled-state, and recovery fields. |
| `logout <profileId> [--yes]` | `models.authLogout` | Deferred; retain current offline behavior. |
| `order get` | `models.authStatus` | Deferred; retain the existing owner-aware read. |
| `order set <profileIds...>` | `models.authOrderSet` | Stay offline: the RPC requires the full profile order; the CLI allows partial lists. |
| `order clear` | `models.authOrderSet` | Deferred; retain offline reset behavior. |
| `activate <profileId>` | No exact test-and-activate mapping | Stay offline. |

## Evidence


ACP CI comparison: `src/gateway/server.chat.acp-completion.test.ts` passed all 12 cases when run directly on PR head `4f32198a3a8f5446e1c24b783d624884415553e6` and on clean main at its exact merge parent `4f3eb4f254664cd0ed1a4b31678e9e4957348d20`. The CI failure in `completes persistence failure after explicit abort once` expected `[start, end]` but received `[end]`; that case passed on both local runs. This does not establish an inherited failure or a PR-caused failure—it records that neither isolated run reproduced it. No code or test assertion was changed.


Latest review repair: removed only the stale `prepareDispatchCurrent` test expectation after #168882 retired that callback. Owner binding, capabilities, authentication, `assertDispatchCurrent`, and no-local-write assertions remain. The requested direct command `node scripts/run-vitest.mjs run src/cli/models-cli.state-owner.test.ts` passed all 16 tests (24.22 seconds total). No retired production callback was restored.

- The new CLI regression fails with the original main-branch auth router: 12 existing refusal cases pass, and API-key delegation fails with `OWNER_UNAVAILABLE`.
- The initial candidate passed 153 targeted tests across CLI ownership, the real API-key writer, Gateway transport, and the real API-key RPC.
- Tests cover cancelled input, no local fallback, old-Gateway capability refusal before request dispatch, and rejected owner changes without credential/config writes.
- Existing unbound API-key RPC requests still pass the real credential-writer test.
- `pnpm build` passed.
- Isolated live profile: piped a real OpenAI key into `pnpm openclaw --profile <profile> models auth paste-api-key --provider openai`. The Gateway picker changed from zero available OpenAI models to one. A real `openclaw agent` turn returned `AUTH_OWNER_OK`, using the saved auth profile. The listener PID stayed the same; no restart was needed.
- The Gateway token was supplied only at runtime and was not in config. The same CLI path worked when it received that token. Without the token, it refused without a local write and named `OPENCLAW_GATEWAY_TOKEN` / `OPENCLAW_GATEWAY_PASSWORD` as the next step.
- An earlier `node scripts/check-changed.mjs --staged` run passed the format, ownership, dependency, and other early guards, then stopped at main's UI-e2e test-root budget (722 versus 720). That result predates the empty-input regression below; no UI files are changed here.

### Review repair: authority at the final write

- The captured requester guard now reaches the auth store's existing SQLite worker admission, not only the updater callback. It also reaches config `beforeCommit` and the config writer's effect-time authority check.
- Credential observation: revoke after the real updater returns, before commit; the operation rejects, the original stored key remains, and config bytes do not change. The permitted control stores the replacement key.
- Config observation: revoke after the transform returns; the operation rejects and the source config remains byte-for-byte unchanged. The already saved, unchanged credential remains intact. The permitted control publishes the auth-profile config.
- The four allowed/revoked controls and 17 auth-store update tests pass. These tests use real credential/config persistence; only the revocation instant is controlled.
- Fixed the two `curly` lint errors in the CLI input adapter. Targeted production lint passes for the adapter, API-key writer, and auth-profile upsert owner.
- After merging main, the changed-file gate passed core typechecking and all 28 core test graphs. It stopped at unrelated unused exports in `extensions/codex/src/app-server/managed-binary.ts`, `tools/solid-lint/index.mjs`, and `ui/src/test-helpers/solid-application-context.tsx`; those files are unchanged by this PR.

### Review repair: configured loopback auth-none

- Owner-bound shared-auth requests now enable the transport's existing bounded auth-none path. A Gateway explicitly configured with `gateway.auth.mode: "none"` uses the backend client identity without creating or reading device credentials. Remote targets and URL overrides retain the existing refusal rules.
- A registered `paste-api-key` regression invokes the real `resolveGatewayCallDeviceAuth` with the owner route's options. It failed before the fix with `GatewayLocalBackendSharedAuthUnavailableError` and passes after the fix. All 105 transport tests and 16 CLI ownership tests pass.
- The latest main was merged after these focused checks. Clean-main export-name collision checking passed at `76a282c7a1c6ca958517ce15f13e17371c14be11`; the channel collision was fixed upstream by `13296b17cd0`. The same clean main reproduced the three lint errors in the untouched plugin-state observation cache and SQLite comparison test. Remaining baseline runs were stopped at maintainer request while upstream CI repairs were being merged.

### Review repair: empty API-key input

- Empty or whitespace-only stdin now reports: `No API key was supplied. Rerun this command and paste a non-empty API key, or pipe one to stdin.`
- Two short tests read real streams and cover both inputs. Both failed with the old `Required` message and pass after this change.
- The changed-file gate passed formatting, core typechecking, and all six selected test graphs. It stopped at the unrelated `GatewayApprovalEventPublisherV2` unused export in `src/gateway/server-instance-runtime.types.ts`, which this repair does not modify.

### Existing CI failures checked on main

- On clean main `aec6e7a56eb03eaba1a648310876d2d6d4811745`, the UI cloud-startup toast-recovery case fails with the same `Control UI readiness hook is unavailable` error as this branch (two cases pass, one fails).
- The same clean main also reproduces the FIFO assertions missing `QUEUED_STEER_A` and `ORDINARY_MESSAGE_B`. Neither test nor its steer behavior is changed by this PR.
- The document-steer case also fails on clean main, but earlier: the initial turn does not reach the mock provider (zero requests). On this branch it reaches the later missing-document assertion. The baseline failure prevents an exact comparison of that later assertion; it is not claimed as an identical local reproduction.
- On the repaired head, [the Node shard](https://github.com/openclaw/openclaw/actions/runs/38082252267/job/114301617040) reports the same FIFO failures. A [separate cron shard](https://github.com/openclaw/openclaw/actions/runs/38082252267/job/114301616913) reports `hydrates runtime metadata for a reasoning-capable fallback candidate` (expected two calls, received four); its main-branch investigation is separate and no auth change is claimed to fix it.
- `src/cli/plugin-local-state-owner.test.ts` has the same result on this branch (`5033eb75ade`) and clean main (`9a165c492058ddf6fc3468cde27b201514c954f1`): 33 pass, one fails. The failed case is `routes memory search limits and JSON output through the discovered owner`; both report `The memory runtime does not support CLI search` inside `OUTCOME_UNKNOWN`. The fixture supplies a manager but not the `searchForCli` callback now required by the Memory Core handler. This is a main-branch fixture mismatch, not an auth routing regression; no test or routing behavior was changed to hide it.

### CI 38113017692: pinned per-file comparison

Compared PR head `f062e5069509128680db873fa6643d262b034b0b` with its exact main parent `9e444e1078169a5bd1117eaf8b5c50cdca2fde15`. Each file ran through the repository test runner under pueue.

| File | PR result | Main result | Verdict |
| --- | --- | --- | --- |
| `src/gateway/server-methods/models-auth-api-key.integration.test.ts` | 1 failed: corrupt config revision key during startup | Same | Inherited; failure occurs before the auth RPC or acknowledgment |
| `src/gateway/gateway-cli-plugin-routing.test.ts` | 1 failed: corrupt config revision key | Same | Inherited |
| `src/gateway/server-methods/sessions-mutations.sticky-model.test.ts` | 3 failed, 66 passed: two undefined-error assertions and an invalid transcript frame | Same | Inherited |
| `src/gateway/server.sessions.create-worktree-spawn.test.ts` | 1 failed, 18 passed: invalid transcript frame | Same | Inherited |
| `src/gateway/server/ws-connection/connect-device-pairing.test.ts` | 12 failed: corrupt config revision key | Same | Inherited |
| `src/gateway/session-message-events.test.ts` | Setup failed: corrupt config revision key; 30 skipped | Same | Inherited |
| `src/gateway/session-message-events.exec-completion.test.ts` | Setup failed: corrupt config revision key; 2 skipped | Same | Inherited |
| `src/gateway/session-message-events.history-worker.test.ts` | Setup failed: corrupt config revision key; 2 skipped | Same | Inherited |
| `src/gateway/sessions-history-http.physical-source.test.ts` | 4 failed: corrupt config revision key | Same | Inherited |
| `ui/src/pages/workboard/workboard-native-bundle.e2e.test.ts` | 2 passed (Chromium and WebKit) | Same | CI failure not reproduced on either revision |

The config-revision owner unit file also passes both tests on both revisions. The Gateway integration failures therefore do not establish an auth-specific `configRevisionHash`/`appliedConfigHash` regression: they stop while loading the installation revision key. No corruption check was weakened and no test was changed to bypass startup. Workboard's initial missing dependencies/browser artifact were repaired before the successful comparison runs.

No overlap with protected maintainer changes.

Two-way code change: a revert restores offline-only CLI setup. Keys saved through the Gateway remain saved. The affected paths are local CLI API-key setup and the existing Gateway API-key save handler.

Co-authored-by: Ayaan Zaidi <[email protected]>
obviyus added a commit that referenced this pull request Oct 12, 2026
…ement (#169450)

## What Problem This Solves

Fixes the QA memory provenance lane failing before it can exercise explicit-owner deep consolidation. This is an explicitly requested repair of a main-branch CI regression.

## User Impact

No product behavior changes. The existing end-to-end proof can again validate researcher-owned recall provenance and deep consolidation.

## Why This Change Was Made

`memory index` became intentionally offline-only with #168471. The fixture already stops its isolated Gateway to seed the memory file, but ran indexing after restarting it. Run the same forced, researcher-scoped index command inside that existing offline window. All provenance and consolidation assertions remain unchanged.

## Evidence

Baseline: `5889e62f4902b8f3fa4b6eb2cecbbd26f5b8ceb0` (current origin/main at reproduction).

- Before: `routes the explicit workspace owner into deep consolidation` failed with `Cannot admit memory.cli ... requires exclusive offline state ownership`.
- After: both tests in `memory-dreaming-provenance.e2e.test.ts` passed, including restricted-session memory and explicit-owner consolidation (2/2).
- Built `qaRuntime` once; reused it with `OPENCLAW_E2E_USE_PREBUILT_DIST=1`.
- `pnpm tsgo:test:root`: all four root shards passed.
- Changed-file Oxlint and Oxfmt checks passed; line-cap ratchet passed.
- Independent autoreview: scoped-clean at P2, no actionable findings.

Focused proof command: `node scripts/run-vitest.mjs run --config test/vitest/vitest.e2e.config.ts test/e2e/qa-lab/runtime/memory-dreaming-provenance.e2e.test.ts` (executed alongside the independent vision fixture test).

Co-authored-by: Ayaan Zaidi <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 12, 2026
)

Related: openclaw#168135, openclaw#168108, openclaw#168471

## What Problem This Solves

Fixes API-key setup from the CLI when a running Gateway owns local state.

## User Impact

Users can run `openclaw models auth paste-api-key --provider <id>` without stopping the Gateway. The Gateway saves the key and refreshes its model catalog. Offline behavior is unchanged. An explicit, non-empty `--profile-id` still requires offline use.

## Why This Change Was Made

openclaw#168135 correctly stopped CLI processes from writing credentials around a live Gateway. It also kept CLI flows offline where the existing Gateway APIs could not preserve their behavior. Manual API-key setup already uses the same credential writer as `models.authSetApiKey`, so that subset can use the owner instead of refusing.

This change uses the canonical `local-state-owner.ts` route, as in openclaw#168108 and openclaw#168471. It binds the request to the discovered local owner and port, sends `expectedOwnerId`, requires `operator.admin`, rechecks ownership before dispatch, and never retries a possibly accepted write locally. API-key input is collected only after owner selection. The RPC checks the expected owner at credential and config writes; calls without that field retain their existing behavior. Owner-bound requests preserve the CLI's agent-selection rules.

Update behavior: an older Gateway that lacks `models-auth-set-api-key-owner-v1` is refused before the API-key request; update and restart it, or stop it and retry offline.

No request/response schema, new RPC method, config option, database schema, or paired-device fallback is added.

### Command-to-RPC mapping

| CLI command or option | Existing RPC | Result in this change |
| --- | --- | --- |
| `paste-api-key --provider <id> [--agent <id>]` | `models.authSetApiKey` | Delegate provider, key, and agent; print saved profile and any application warning. |
| `paste-api-key --profile-id <id>` | No profile-id field in `models.authSetApiKey` | Refuse this option with offline guidance. |
| `paste-token [--expires-in <duration>]` | No equivalent API-key write | Stay offline: token type and expiry must not become an API key. |
| `login`, including API-key plugin methods | `models.authLogin` and `wizard.*` | Stay offline: CLI method/profile/default/force semantics are not an exact manual-key mapping. |
| `login-github-copilot` | `models.authLogin` and `wizard.*` | Stay offline; device flow is outside this change. |
| `add` / `setup-token` | No exact generic mapping | Stay offline; these can run local provider CLI or import flows. |
| `list` | `models.authStatus` | Stay offline: the status projection lacks the CLI list's state-path, cooldown, disabled-state, and recovery fields. |
| `logout <profileId> [--yes]` | `models.authLogout` | Deferred; retain current offline behavior. |
| `order get` | `models.authStatus` | Deferred; retain the existing owner-aware read. |
| `order set <profileIds...>` | `models.authOrderSet` | Stay offline: the RPC requires the full profile order; the CLI allows partial lists. |
| `order clear` | `models.authOrderSet` | Deferred; retain offline reset behavior. |
| `activate <profileId>` | No exact test-and-activate mapping | Stay offline. |

## Evidence


ACP CI comparison: `src/gateway/server.chat.acp-completion.test.ts` passed all 12 cases when run directly on PR head `4f32198a3a8f5446e1c24b783d624884415553e6` and on clean main at its exact merge parent `e1b944d4a80ef3b4e0df75f1e324cb4a5ffc08dd`. The CI failure in `completes persistence failure after explicit abort once` expected `[start, end]` but received `[end]`; that case passed on both local runs. This does not establish an inherited failure or a PR-caused failure—it records that neither isolated run reproduced it. No code or test assertion was changed.


Latest review repair: removed only the stale `prepareDispatchCurrent` test expectation after openclaw#168882 retired that callback. Owner binding, capabilities, authentication, `assertDispatchCurrent`, and no-local-write assertions remain. The requested direct command `node scripts/run-vitest.mjs run src/cli/models-cli.state-owner.test.ts` passed all 16 tests (24.22 seconds total). No retired production callback was restored.

- The new CLI regression fails with the original main-branch auth router: 12 existing refusal cases pass, and API-key delegation fails with `OWNER_UNAVAILABLE`.
- The initial candidate passed 153 targeted tests across CLI ownership, the real API-key writer, Gateway transport, and the real API-key RPC.
- Tests cover cancelled input, no local fallback, old-Gateway capability refusal before request dispatch, and rejected owner changes without credential/config writes.
- Existing unbound API-key RPC requests still pass the real credential-writer test.
- `pnpm build` passed.
- Isolated live profile: piped a real OpenAI key into `pnpm openclaw --profile <profile> models auth paste-api-key --provider openai`. The Gateway picker changed from zero available OpenAI models to one. A real `openclaw agent` turn returned `AUTH_OWNER_OK`, using the saved auth profile. The listener PID stayed the same; no restart was needed.
- The Gateway token was supplied only at runtime and was not in config. The same CLI path worked when it received that token. Without the token, it refused without a local write and named `OPENCLAW_GATEWAY_TOKEN` / `OPENCLAW_GATEWAY_PASSWORD` as the next step.
- An earlier `node scripts/check-changed.mjs --staged` run passed the format, ownership, dependency, and other early guards, then stopped at main's UI-e2e test-root budget (722 versus 720). That result predates the empty-input regression below; no UI files are changed here.

### Review repair: authority at the final write

- The captured requester guard now reaches the auth store's existing SQLite worker admission, not only the updater callback. It also reaches config `beforeCommit` and the config writer's effect-time authority check.
- Credential observation: revoke after the real updater returns, before commit; the operation rejects, the original stored key remains, and config bytes do not change. The permitted control stores the replacement key.
- Config observation: revoke after the transform returns; the operation rejects and the source config remains byte-for-byte unchanged. The already saved, unchanged credential remains intact. The permitted control publishes the auth-profile config.
- The four allowed/revoked controls and 17 auth-store update tests pass. These tests use real credential/config persistence; only the revocation instant is controlled.
- Fixed the two `curly` lint errors in the CLI input adapter. Targeted production lint passes for the adapter, API-key writer, and auth-profile upsert owner.
- After merging main, the changed-file gate passed core typechecking and all 28 core test graphs. It stopped at unrelated unused exports in `extensions/codex/src/app-server/managed-binary.ts`, `tools/solid-lint/index.mjs`, and `ui/src/test-helpers/solid-application-context.tsx`; those files are unchanged by this PR.

### Review repair: configured loopback auth-none

- Owner-bound shared-auth requests now enable the transport's existing bounded auth-none path. A Gateway explicitly configured with `gateway.auth.mode: "none"` uses the backend client identity without creating or reading device credentials. Remote targets and URL overrides retain the existing refusal rules.
- A registered `paste-api-key` regression invokes the real `resolveGatewayCallDeviceAuth` with the owner route's options. It failed before the fix with `GatewayLocalBackendSharedAuthUnavailableError` and passes after the fix. All 105 transport tests and 16 CLI ownership tests pass.
- The latest main was merged after these focused checks. Clean-main export-name collision checking passed at `25b2400af13218f379b306a2e4cc504288f320eb`; the channel collision was fixed upstream by `2f395451b88`. The same clean main reproduced the three lint errors in the untouched plugin-state observation cache and SQLite comparison test. Remaining baseline runs were stopped at maintainer request while upstream CI repairs were being merged.

### Review repair: empty API-key input

- Empty or whitespace-only stdin now reports: `No API key was supplied. Rerun this command and paste a non-empty API key, or pipe one to stdin.`
- Two short tests read real streams and cover both inputs. Both failed with the old `Required` message and pass after this change.
- The changed-file gate passed formatting, core typechecking, and all six selected test graphs. It stopped at the unrelated `GatewayApprovalEventPublisherV2` unused export in `src/gateway/server-instance-runtime.types.ts`, which this repair does not modify.

### Existing CI failures checked on main

- On clean main `e99d1a8c933639bea9961f7731624eb1ef3f3615`, the UI cloud-startup toast-recovery case fails with the same `Control UI readiness hook is unavailable` error as this branch (two cases pass, one fails).
- The same clean main also reproduces the FIFO assertions missing `QUEUED_STEER_A` and `ORDINARY_MESSAGE_B`. Neither test nor its steer behavior is changed by this PR.
- The document-steer case also fails on clean main, but earlier: the initial turn does not reach the mock provider (zero requests). On this branch it reaches the later missing-document assertion. The baseline failure prevents an exact comparison of that later assertion; it is not claimed as an identical local reproduction.
- On the repaired head, [the Node shard](https://github.com/openclaw/openclaw/actions/runs/38082252267/job/114301617040) reports the same FIFO failures. A [separate cron shard](https://github.com/openclaw/openclaw/actions/runs/38082252267/job/114301616913) reports `hydrates runtime metadata for a reasoning-capable fallback candidate` (expected two calls, received four); its main-branch investigation is separate and no auth change is claimed to fix it.
- `src/cli/plugin-local-state-owner.test.ts` has the same result on this branch (`5033eb75ade`) and clean main (`45943833ee81802976d1e7ef0650d668b13b6f5a`): 33 pass, one fails. The failed case is `routes memory search limits and JSON output through the discovered owner`; both report `The memory runtime does not support CLI search` inside `OUTCOME_UNKNOWN`. The fixture supplies a manager but not the `searchForCli` callback now required by the Memory Core handler. This is a main-branch fixture mismatch, not an auth routing regression; no test or routing behavior was changed to hide it.

### CI 38113017692: pinned per-file comparison

Compared PR head `f062e5069509128680db873fa6643d262b034b0b` with its exact main parent `fece4b1cfc8b5778c0e8f69a8c9899f548038819`. Each file ran through the repository test runner under pueue.

| File | PR result | Main result | Verdict |
| --- | --- | --- | --- |
| `src/gateway/server-methods/models-auth-api-key.integration.test.ts` | 1 failed: corrupt config revision key during startup | Same | Inherited; failure occurs before the auth RPC or acknowledgment |
| `src/gateway/gateway-cli-plugin-routing.test.ts` | 1 failed: corrupt config revision key | Same | Inherited |
| `src/gateway/server-methods/sessions-mutations.sticky-model.test.ts` | 3 failed, 66 passed: two undefined-error assertions and an invalid transcript frame | Same | Inherited |
| `src/gateway/server.sessions.create-worktree-spawn.test.ts` | 1 failed, 18 passed: invalid transcript frame | Same | Inherited |
| `src/gateway/server/ws-connection/connect-device-pairing.test.ts` | 12 failed: corrupt config revision key | Same | Inherited |
| `src/gateway/session-message-events.test.ts` | Setup failed: corrupt config revision key; 30 skipped | Same | Inherited |
| `src/gateway/session-message-events.exec-completion.test.ts` | Setup failed: corrupt config revision key; 2 skipped | Same | Inherited |
| `src/gateway/session-message-events.history-worker.test.ts` | Setup failed: corrupt config revision key; 2 skipped | Same | Inherited |
| `src/gateway/sessions-history-http.physical-source.test.ts` | 4 failed: corrupt config revision key | Same | Inherited |
| `ui/src/pages/workboard/workboard-native-bundle.e2e.test.ts` | 2 passed (Chromium and WebKit) | Same | CI failure not reproduced on either revision |

The config-revision owner unit file also passes both tests on both revisions. The Gateway integration failures therefore do not establish an auth-specific `configRevisionHash`/`appliedConfigHash` regression: they stop while loading the installation revision key. No corruption check was weakened and no test was changed to bypass startup. Workboard's initial missing dependencies/browser artifact were repaired before the successful comparison runs.

No overlap with protected maintainer changes.

Two-way code change: a revert restores offline-only CLI setup. Keys saved through the Gateway remain saved. The affected paths are local CLI API-key setup and the existing Gateway API-key save handler.

Co-authored-by: Ayaan Zaidi <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 12, 2026
…ement (openclaw#169450)

## What Problem This Solves

Fixes the QA memory provenance lane failing before it can exercise explicit-owner deep consolidation. This is an explicitly requested repair of a main-branch CI regression.

## User Impact

No product behavior changes. The existing end-to-end proof can again validate researcher-owned recall provenance and deep consolidation.

## Why This Change Was Made

`memory index` became intentionally offline-only with openclaw#168471. The fixture already stops its isolated Gateway to seed the memory file, but ran indexing after restarting it. Run the same forced, researcher-scoped index command inside that existing offline window. All provenance and consolidation assertions remain unchanged.

## Evidence

Baseline: `11f576b23cf70615ca4504eb12fdba93591b9c8f` (current origin/main at reproduction).

- Before: `routes the explicit workspace owner into deep consolidation` failed with `Cannot admit memory.cli ... requires exclusive offline state ownership`.
- After: both tests in `memory-dreaming-provenance.e2e.test.ts` passed, including restricted-session memory and explicit-owner consolidation (2/2).
- Built `qaRuntime` once; reused it with `OPENCLAW_E2E_USE_PREBUILT_DIST=1`.
- `pnpm tsgo:test:root`: all four root shards passed.
- Changed-file Oxlint and Oxfmt checks passed; line-cap ratchet passed.
- Independent autoreview: scoped-clean at P2, no actionable findings.

Focused proof command: `node scripts/run-vitest.mjs run --config test/vitest/vitest.e2e.config.ts test/e2e/qa-lab/runtime/memory-dreaming-provenance.e2e.test.ts` (executed alongside the independent vision fixture test).

Co-authored-by: Ayaan Zaidi <[email protected]>
Grynn added a commit to Grynn/openclaw that referenced this pull request Oct 21, 2026
Retain the remaining raw-byte behavior from local8039fc5195d on upstreamf91bca9546f5. The host fs-safe append option recognizes leadingLF only; a proposed delta beginning withCR orCRLF must not receive an extraLF. Apply the same separator decision in sandbox writes and provenance contentAfter without changing replay rejection, source authority or path guards.

Do not replay the old aggregate maintenance/routing patch: upstream#168123 owns duplicate-note rejection,openclaw#138786 reindex backoff,openclaw#168471 and8fc0987fb08 Gateway CLI recall routing,openclaw#168860/openclaw#171322 worker-owned memory publication and admission. Raw proposed Markdown remains verbatim; no prefix stripping or normalized-offset mapping is retained.

Proof: four actual host/sandbox wrapper cases fail before the repair, then24tests pass including replay rejection, authority revocation and exact provenance/disk bytes forCRLF,CR,indentation,hard-break spaces and non-BMP text. Targeted agents-root types,scoped lint,format andline-cap pass; fresh independentP0-P2 review scoped-clean. Full candidate build,Doctor andactivation remain separate gates. Related:openclaw#125309.

Local-Feature: memory-append-raw-separators
Semantic-Source: 39a740d
Upstream-Tracking: openclaw#125309
Drop-When: Upstream host/sandbox append and provenance preserve leading CR and CRLF bytes.
Rebase-Base: ed9d493
Grynn added a commit to Grynn/openclaw that referenced this pull request Oct 21, 2026
Retain the remaining raw-byte behavior from local8039fc5195d on upstreamf91bca9546f5. The host fs-safe append option recognizes leadingLF only; a proposed delta beginning withCR orCRLF must not receive an extraLF. Apply the same separator decision in sandbox writes and provenance contentAfter without changing replay rejection, source authority or path guards.

Do not replay the old aggregate maintenance/routing patch: upstream#168123 owns duplicate-note rejection,openclaw#138786 reindex backoff,openclaw#168471 and8fc0987fb08 Gateway CLI recall routing,openclaw#168860/openclaw#171322 worker-owned memory publication and admission. Raw proposed Markdown remains verbatim; no prefix stripping or normalized-offset mapping is retained.

Proof: four actual host/sandbox wrapper cases fail before the repair, then24tests pass including replay rejection, authority revocation and exact provenance/disk bytes forCRLF,CR,indentation,hard-break spaces and non-BMP text. Targeted agents-root types,scoped lint,format andline-cap pass; fresh independentP0-P2 review scoped-clean. Full candidate build,Doctor andactivation remain separate gates. Related:openclaw#125309.

Local-Feature: memory-append-raw-separators
Semantic-Source: 39a740d
Upstream-Tracking: openclaw#125309
Drop-When: Upstream host/sandbox append and provenance preserve leading CR and CRLF bytes.
Rebase-Base: ed9d493
RomneyDa added a commit that referenced this pull request Nov 2, 2026
Two Matrix QA scenarios asserted behavior the product intentionally retired;
earlier lane failures masked them.

- matrix-e2ee-cli-setup-then-gateway-reply ran `openclaw matrix encryption
  setup` while the Gateway owned the state root. Since #168471 only verify
  status/bootstrap/device route through a running Gateway; other Matrix
  commands refuse until it is stopped (docs/channels/matrix.md). Run setup in
  the stop/run/restart window, then keep the Gateway reply proof.
- matrix-e2ee-corrupt-crypto-idb-snapshot expected backup restore to repair a
  corrupted crypto snapshot. Since #160707 crypto ownership refuses unsafe or
  corrupt snapshots and points at `openclaw matrix doctor inspect`
  (docs/channels/matrix/encryption.md). Assert that refusal and that the
  corrupted snapshot is left in place.
RomneyDa added a commit that referenced this pull request Nov 3, 2026
Two Matrix QA scenarios asserted behavior the product intentionally retired;
earlier lane failures masked them.

- matrix-e2ee-cli-setup-then-gateway-reply ran `openclaw matrix encryption
  setup` while the Gateway owned the state root. Since #168471 only verify
  status/bootstrap/device route through a running Gateway; other Matrix
  commands refuse until it is stopped (docs/channels/matrix.md). Run setup in
  the stop/run/restart window, then keep the Gateway reply proof.
- matrix-e2ee-corrupt-crypto-idb-snapshot expected backup restore to repair a
  corrupted crypto snapshot. Since #160707 crypto ownership refuses unsafe or
  corrupt snapshots and points at `openclaw matrix doctor inspect`
  (docs/channels/matrix/encryption.md). Assert that refusal and that the
  corrupted snapshot is left in place.

The refusal assertion and the backup-bootstrap classifier move to the
destructive-recovery sibling to keep the scenario module under its line cap.

Forward-port of 0f4dc59 from release/2026.10.10.
RomneyDa added a commit that referenced this pull request Nov 5, 2026
Two Matrix QA scenarios asserted behavior the product intentionally retired;
earlier lane failures masked them.

- matrix-e2ee-cli-setup-then-gateway-reply ran `openclaw matrix encryption
  setup` while the Gateway owned the state root. Since #168471 only verify
  status/bootstrap/device route through a running Gateway; other Matrix
  commands refuse until it is stopped (docs/channels/matrix.md). Run setup in
  the stop/run/restart window, then keep the Gateway reply proof.
- matrix-e2ee-corrupt-crypto-idb-snapshot expected backup restore to repair a
  corrupted crypto snapshot. Since #160707 crypto ownership refuses unsafe or
  corrupt snapshots and points at `openclaw matrix doctor inspect`
  (docs/channels/matrix/encryption.md). Assert that refusal and that the
  corrupted snapshot is left in place.

The refusal assertion and the backup-bootstrap classifier move to the
destructive-recovery sibling to keep the scenario module under its line cap.

Forward-port of 0f4dc59 from release/2026.10.10.
RomneyDa added a commit that referenced this pull request Nov 5, 2026
)

* fix(matrix): defer ready status through startup

Keep account readiness in startup until Matrix startup maintenance and crypto ownership initialization have settled, preventing hard-restart consumers from interrupting final state handoff.

The monitor is the status controller's only consumer, so deferral is unconditional rather than an option.

Forward-port of 5fe32d9 from release/2026.10.10.

* fix(matrix): let Matrix CLI commands exit after their client stops

matrix-js-sdk's timeoutSignal ponyfill arms a referenced setTimeout for every
request and never clears it. /sync requests use pollTimeout + 80s, so each
Matrix CLI command stayed alive for up to 110s after printing its result once
CLI completion stopped forcing process exit (#168587). matrix-js-sdk 43.0.0
still ships the same ponyfill.

Unref the deadline timer, matching AbortSignal.timeout semantics: an in-flight
request still keeps the process alive through its socket and the deadline still
fires while the loop is running.

Forward-port of 4bbc597 from release/2026.10.10.

* fix(matrix): report late in-room verification failures instead of crashing

matrix-js-sdk starts in-room verification processing without awaiting it,
including after an encrypted verification event finishes decrypting. Once the
client has stopped, OpenClaw's retired crypto IndexedDB generation rejects
receiveVerificationEvent, and the rejection reaches the process
unhandled-rejection guard, which begins process exit. In the QA Matrix lane the
exit gate stopped the CLI scheduler mid-run, so every later isolated scenario
failed with "Failed to stage the isolated QA auth profile store".
matrix-js-sdk 43.0.0 still leaves this path unguarded.

Catch and log the failure inside the SDK's fire-and-forget verification path.

Forward-port of 2a6a3bc from release/2026.10.10.

* test(qa): align Matrix E2EE scenarios with offline ownership contracts

Two Matrix QA scenarios asserted behavior the product intentionally retired;
earlier lane failures masked them.

- matrix-e2ee-cli-setup-then-gateway-reply ran `openclaw matrix encryption
  setup` while the Gateway owned the state root. Since #168471 only verify
  status/bootstrap/device route through a running Gateway; other Matrix
  commands refuse until it is stopped (docs/channels/matrix.md). Run setup in
  the stop/run/restart window, then keep the Gateway reply proof.
- matrix-e2ee-corrupt-crypto-idb-snapshot expected backup restore to repair a
  corrupted crypto snapshot. Since #160707 crypto ownership refuses unsafe or
  corrupt snapshots and points at `openclaw matrix doctor inspect`
  (docs/channels/matrix/encryption.md). Assert that refusal and that the
  corrupted snapshot is left in place.

The refusal assertion and the backup-bootstrap classifier move to the
destructive-recovery sibling to keep the scenario module under its line cap.

Forward-port of 0f4dc59 from release/2026.10.10.

* test(matrix): scope forward-port regression allocation
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 5, 2026
…claw#192385)

* fix(matrix): defer ready status through startup

Keep account readiness in startup until Matrix startup maintenance and crypto ownership initialization have settled, preventing hard-restart consumers from interrupting final state handoff.

The monitor is the status controller's only consumer, so deferral is unconditional rather than an option.

Forward-port of 5fe32d9 from release/2026.10.10.

* fix(matrix): let Matrix CLI commands exit after their client stops

matrix-js-sdk's timeoutSignal ponyfill arms a referenced setTimeout for every
request and never clears it. /sync requests use pollTimeout + 80s, so each
Matrix CLI command stayed alive for up to 110s after printing its result once
CLI completion stopped forcing process exit (openclaw#168587). matrix-js-sdk 43.0.0
still ships the same ponyfill.

Unref the deadline timer, matching AbortSignal.timeout semantics: an in-flight
request still keeps the process alive through its socket and the deadline still
fires while the loop is running.

Forward-port of 4bbc597 from release/2026.10.10.

* fix(matrix): report late in-room verification failures instead of crashing

matrix-js-sdk starts in-room verification processing without awaiting it,
including after an encrypted verification event finishes decrypting. Once the
client has stopped, OpenClaw's retired crypto IndexedDB generation rejects
receiveVerificationEvent, and the rejection reaches the process
unhandled-rejection guard, which begins process exit. In the QA Matrix lane the
exit gate stopped the CLI scheduler mid-run, so every later isolated scenario
failed with "Failed to stage the isolated QA auth profile store".
matrix-js-sdk 43.0.0 still leaves this path unguarded.

Catch and log the failure inside the SDK's fire-and-forget verification path.

Forward-port of 2a6a3bc from release/2026.10.10.

* test(qa): align Matrix E2EE scenarios with offline ownership contracts

Two Matrix QA scenarios asserted behavior the product intentionally retired;
earlier lane failures masked them.

- matrix-e2ee-cli-setup-then-gateway-reply ran `openclaw matrix encryption
  setup` while the Gateway owned the state root. Since openclaw#168471 only verify
  status/bootstrap/device route through a running Gateway; other Matrix
  commands refuse until it is stopped (docs/channels/matrix.md). Run setup in
  the stop/run/restart window, then keep the Gateway reply proof.
- matrix-e2ee-corrupt-crypto-idb-snapshot expected backup restore to repair a
  corrupted crypto snapshot. Since openclaw#160707 crypto ownership refuses unsafe or
  corrupt snapshots and points at `openclaw matrix doctor inspect`
  (docs/channels/matrix/encryption.md). Assert that refusal and that the
  corrupted snapshot is left in place.

The refusal assertion and the backup-bootstrap classifier move to the
destructive-recovery sibling to keep the scenario module under its line cap.

Forward-port of 0f4dc59 from release/2026.10.10.

* test(matrix): scope forward-port regression allocation
Grynn added a commit to Grynn/openclaw that referenced this pull request Nov 13, 2026
Retain the remaining raw-byte behavior from local8039fc5195d on upstreamf91bca9546f5. The host fs-safe append option recognizes leadingLF only; a proposed delta beginning withCR orCRLF must not receive an extraLF. Apply the same separator decision in sandbox writes and provenance contentAfter without changing replay rejection, source authority or path guards.

Do not replay the old aggregate maintenance/routing patch: upstream#168123 owns duplicate-note rejection,openclaw#138786 reindex backoff,openclaw#168471 and8fc0987fb08 Gateway CLI recall routing,openclaw#168860/openclaw#171322 worker-owned memory publication and admission. Raw proposed Markdown remains verbatim; no prefix stripping or normalized-offset mapping is retained.

Proof: four actual host/sandbox wrapper cases fail before the repair, then24tests pass including replay rejection, authority revocation and exact provenance/disk bytes forCRLF,CR,indentation,hard-break spaces and non-BMP text. Targeted agents-root types,scoped lint,format andline-cap pass; fresh independentP0-P2 review scoped-clean. Full candidate build,Doctor andactivation remain separate gates. Related:openclaw#125309.

Local-Feature: memory-append-raw-separators
Semantic-Source: 39a740d
Upstream-Tracking: none (no upstream issue or PR tracks CR-led append separators); related openclaw#125309 (closed completed 2026-10-24, memory-maintenance scope)
Drop-When: Upstream host/sandbox append and provenance preserve leading CR and CRLF bytes.
Rebase-Base: 0220489
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling channel: matrix Channel integration: matrix cli CLI command changes commands Command implementations docs Improvements or additions to documentation extensions: memory-core Extension: memory-core extensions: qa-lab gateway Gateway runtime merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. P2 Normal backlog priority with limited blast radius. plugin: file-transfer proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. scripts Repository scripts security-sensitive-changed size: XL status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant