Skip to content

refactor(pairing): store channel pairing state in SQLite - #105802

Merged
steipete merged 4 commits into
mainfrom
codex/pairing-sqlite
Jul 13, 2026
Merged

steipete merged 4 commits into
mainfrom
codex/pairing-sqlite

Conversation

@steipete

Copy link
Copy Markdown
Contributor

Closes #105761

What Problem This Solves

Resolves a problem where channel pairing requests and approved-sender allowlists remained live JSON state under the credentials directory. Runtime reads also continued merging a legacy unscoped allowlist, so pairing was the remaining non-migration exception to SQLite-only runtime state.

Why This Change Was Made

Pairing requests and account-scoped allowlists now use the existing shared SQLite tables and synchronous write transactions. Startup migration and openclaw doctor --fix import recognizable legacy JSON files, resolve effective channel defaults through channel contracts, and remove a source only after a successful transactional merge; unreadable, unresolved, or ambiguous files remain in place with a warning. The deprecated SDK path helper remains available only for migration compatibility.

User Impact

Pairing approvals and pending requests now have one canonical SQLite owner. Existing recognized JSON state migrates automatically without losing concurrent changes or crossing channel/account boundaries, while ambiguous legacy filenames fail closed for operator review.

Evidence

  • Blacksmith Testbox tbx_01kxcbbnmwqvtr6kwevbqsdcsv (swift-lobster-1c1c)
  • pnpm test src/pairing/pairing-store.test.ts src/infra/state-migrations.channel-pairing.test.ts src/infra/state-migrations.test.ts src/commands/doctor-state-migrations.test.ts — 141 tests passed
  • pnpm test src/pairing/pairing-store-keys.test.ts src/plugins/contracts/plugin-sdk-subpaths.test.ts src/plugin-sdk/channel-pairing.test.ts extensions/telegram/src/state-migrations.test.ts — 32 tests passed
  • pnpm check:changed -- <touched files> — formatting, SDK API/export gates, core/test/extension typechecks, full core/extension lint, database-first guard, import-cycle checks, and pairing guards passed
  • Post-review focused core/test typechecks, lint, database-first guard, and pairing guards passed after the final migration safety fixes
  • Fresh autoreview: clean, no accepted/actionable findings

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation channel: telegram Channel integration: telegram commands Command implementations size: XL maintainer Maintainer-authored PR labels Jul 13, 2026

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 73c74b1d8b

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +110 to +112
const matchingAccountIds = (accountIds[channel] ?? []).filter(
(accountId) => safeAccountKey(accountId) === accountKey,
);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P1 Badge Import default-scoped legacy allowlists

When a legacy file is already account-scoped as <channel>-default-allowFrom.json, this resolver only accepts it if default appears in accountIds[channel]. Env-only/default-account installs can have no cfg.channels.<channel> account list even though the runtime still uses the default account, so startup migration leaves the file “unresolved”; since the new runtime no longer reads legacy JSON files, those previously approved senders lose access after upgrade. Treat the default account key as DEFAULT_ACCOUNT_ID for known channels even when it is not configured explicitly.

Useful? React with 👍 / 👎.

@clawsweeper clawsweeper Bot added rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. 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. labels Jul 13, 2026
@clawsweeper

clawsweeper Bot commented Jul 13, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs real behavior proof before merge. Reviewed July 12, 2026, 9:44 PM ET / July 13, 2026, 01:44 UTC.

Summary
Moves channel pairing requests and approved-sender allowlists from credential-directory JSON files to shared SQLite tables, with startup and doctor migration plus documentation and regression-test updates.

PR surface: Source -9, Tests -354, Docs +5. Total -358 across 17 files.

Reproducibility: yes. from source, but not by a live run in this review: current main writes pairing requests and approvals through the legacy JSON store despite existing SQLite tables and the documented database-first boundary.

Review metrics: 3 noteworthy metrics.

  • Authorization state owners: 2 moved from JSON to SQLite. Pending pairing requests and approved-sender entries both affect channel access and must migrate without loss or cross-account widening.
  • Legacy filename shapes: 3 migration shapes handled. Pairing-request, unscoped allowlist, and account-scoped allowlist files each require distinct account-resolution and cleanup behavior.
  • SDK compatibility surface: 1 deprecated helper retained. The migration keeps the legacy path resolver available for compatibility, so its migration-only contract must remain narrow and tested.

Stored data model
Persistent data-model change detected: migration/backfill/repair: docs/channels/pairing.md, migration/backfill/repair: src/commands/doctor-config-flow.test.ts, migration/backfill/repair: src/commands/doctor-state-migrations.test.ts, migration/backfill/repair: src/commands/doctor.e2e-harness.ts, migration/backfill/repair: src/infra/state-migrations.channel-pairing.test.ts, serialized state: extensions/telegram/src/state-migrations.ts, and 10 more. Confirm migration or upgrade compatibility proof before merge.

Root-cause cluster
Relationship: fixed_by_candidate
Canonical: #105761
Summary: The linked issue is the canonical report of live JSON pairing state, and this PR is its open candidate fix.

Members:

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

Merge readiness
Overall: 🧂 unranked krab
Proof: 🧂 unranked krab
Patch quality: 🐚 platinum hermit
Result: blocked until real behavior proof from a real setup is added.

Overall follows the weaker of proof and patch quality, so missing proof can cap an otherwise strong patch.

Rank-up moves:

  • [P1] Add redacted live gateway evidence for a fresh pairing request, approval, restart, and SQLite persistence with no new legacy JSON writes.
  • [P1] Add a redacted upgrade transcript covering unscoped, default-scoped, named-account, wildcard-binding, ambiguous, and unreadable legacy files, including which sources are retained or removed.
  • Refresh the branch onto current main and rerun the exact-head proof.

Proof guidance:

  • [P1] Needs real behavior proof before merge: Tests and Testbox checks are extensive, but the PR still needs redacted after-fix terminal output or runtime logs from a real fresh pairing and legacy upgrade; redact IDs, tokens, paths, endpoints, and other private data, then update the PR body to trigger review or ask a maintainer for @clawsweeper re-review.

Risk before merge

  • [P1] A wrong legacy filename-to-account resolution can place approved senders under an account runtime never reads, locking existing users out after upgrade.
  • [P1] Because pairing allowlists are an authorization boundary, an incorrect cross-account merge could broaden access even if normal unit and CI checks stay green.
  • [P1] No real gateway upgrade proof currently demonstrates that recognized sources are removed only after successful import while unreadable, wildcard-routed, or ambiguous sources remain safe.
  • [P1] The branch is behind current main, so the exact merge result needs a refreshed review after rebase or merge-base update.

Maintainer options:

  1. Require live fresh and upgrade proof (recommended)
    Keep the PR open until redacted runtime evidence shows new pairing, restart persistence, scoped and unscoped legacy import, correct account selection, and safe source-file cleanup.
  2. Accept the migration risk with an explicit override
    A maintainer may override the proof gate only after personally validating the authorization-state upgrade path and recording why test-only evidence is sufficient.
  3. Pause for a current-main refresh
    Delay merge review until the branch is rebased or refreshed and the migration proof is rerun against the resulting exact head.

Next step before merge

  • [P1] The next action is maintainer review of real upgrade proof for a protected authorization-state migration; there is no confirmed narrow current-head defect suitable for an automated repair lane.

Security
Cleared: No concrete new code-execution, dependency, secret-exposure, or authorization defect is confirmed on the current head; the remaining concern is proof of a security-sensitive state migration.

Review details

Best possible solution:

Make SQLite the sole runtime owner while preserving each recognized legacy request and approval under the exact channel/account identity, leaving ambiguous files untouched, and prove fresh pairing plus representative upgrade cases on a real gateway before merge.

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

Yes from source, but not by a live run in this review: current main writes pairing requests and approvals through the legacy JSON store despite existing SQLite tables and the documented database-first boundary.

Is this the best way to solve the issue?

Yes in direction: moving the canonical runtime state into the existing typed SQLite tables with doctor-owned migration is the narrowest repository-aligned fix, but the exact upgrade implementation still needs real behavior proof before it is safe to merge.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against 43901be298b3.

Label changes

Label justifications:

  • P1: A migration error can immediately break or broaden paired channel access for existing users during upgrade.
  • merge-risk: 🚨 compatibility: The PR replaces shipped file-backed authorization state with SQLite and deletes successfully imported legacy sources, making upgrade correctness merge-critical.
  • merge-risk: 🚨 security-boundary: Pairing allowlists control who may message an assistant, so account mis-scoping or cross-account merging changes an authorization boundary.
  • rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🧂 unranked krab and patch quality is 🐚 platinum hermit.
  • status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask. Needs real behavior proof before merge: Tests and Testbox checks are extensive, but the PR still needs redacted after-fix terminal output or runtime logs from a real fresh pairing and legacy upgrade; redact IDs, tokens, paths, endpoints, and other private data, then update the PR body to trigger review or ask a maintainer for @clawsweeper re-review.
Evidence reviewed

PR surface:

Source -9, Tests -354, Docs +5. Total -358 across 17 files.

View PR surface stats
Area Files Added Removed Net
Source 8 887 896 -9
Tests 7 561 915 -354
Docs 2 20 15 +5
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 17 1468 1826 -358

What I checked:

  • Runtime storage boundary: The PR replaces the live file-backed pairing store with shared SQLite reads and synchronous transactional writes, matching the repository's database-first runtime-state policy. (src/pairing/pairing-store.ts:1, a64cc92759df)
  • Legacy migration boundary: A doctor/startup importer detects pairing-request, unscoped allowlist, and account-scoped allowlist files, merges recognized state into SQLite, and is designed to retain unresolved or ambiguous files. (src/infra/state-migrations.channel-pairing.ts:1, a64cc92759df)
  • Focused regression coverage: The branch adds dedicated channel-pairing migration tests and rewrites pairing-store tests around SQLite account isolation and transactional behavior; the PR reports 173 focused tests passing. (src/infra/state-migrations.channel-pairing.test.ts:1, a64cc92759df)
  • Prior review continuity: Earlier reviews identified default-account and wildcard-binding migration hazards at reviewed head 6725971; the current head adds a later migration-safety/import-cycle commit, but the supplied evidence still lacks a real upgrade run demonstrating those account-selection cases. (src/infra/state-migrations.ts:4379, a64cc92759df)
  • Real behavior proof gap: The PR body provides unit tests, checks, and a Testbox identifier, but no after-fix gateway pairing transcript, runtime logs, or legacy-file upgrade transcript showing preserved access and source cleanup. (a64cc92759df)
  • Current-main comparison: Current main still represents the file-backed behavior reported by the linked issue; this PR remains the open candidate fix rather than redundant work already implemented on main. (src/pairing/pairing-store.ts:1, 43901be298b3)

Likely related people:

  • steipete: Authored the linked bug report and this three-commit SQLite migration, and is closely connected to the repository's broader shared-state refactor work. (role: database-first and pairing refactor contributor; confidence: high; commits: 73c74b1d8bc0, 6725971e29d7, a64cc92759df; files: src/pairing/pairing-store.ts, src/infra/state-migrations.channel-pairing.ts, docs/refactor/database-first.md)
  • vincentkoc: Release history credits this contributor on the omitted-account fallback and legacy default-account pairing behavior that this migration must preserve. (role: recent pairing and account-scope contributor; confidence: medium; commits: 2001603020fa, 075ece3dac40; files: src/pairing/pairing-store.ts, src/pairing/allow-from-store-file.ts)
  • Sid-Qin: Release history credits this contributor on account-default pairing fallback behavior and nearby Telegram/doctor upgrade fixes relevant to migration compatibility. (role: pairing fallback contributor; confidence: medium; commits: 2001603020fa; files: src/pairing/pairing-store.ts, src/commands/doctor-state-migrations.test.ts)
What the crustacean ranks mean
  • 🦀 challenger crab: rare, exceptional readiness with strong proof, clean implementation, and convincing validation.
  • 🦞 diamond lobster: very strong readiness with only minor maintainer review expected.
  • 🐚 platinum hermit: good normal PR, likely mergeable with ordinary maintainer review.
  • 🦐 gold shrimp: useful signal, but proof or patch confidence is still limited.
  • 🦪 silver shellfish: thin signal; proof, validation, or implementation needs work.
  • 🧂 unranked krab: not merge-ready because proof is missing/unusable or there are serious correctness or safety concerns.
  • 🌊 off-meta tidepool: rating does not apply to this item.

Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

How this review workflow works
  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.
Review history (3 earlier review cycles)
  • reviewed 2026-07-13T01:00:23.848Z sha 73c74b1 :: needs real behavior proof before merge. :: none
  • reviewed 2026-07-13T01:22:13.765Z sha 6725971 :: needs real behavior proof before merge. :: none
  • reviewed 2026-07-13T01:27:39.934Z sha 6725971 :: needs real behavior proof before merge. :: [P1] Ignore wildcard bindings when choosing the migration account

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 6725971e29

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +4418 to +4424
(binding) =>
normalizeAgentId(binding.agentId) === targetAgentId &&
binding.match?.channel === channelId &&
typeof binding.match.accountId === "string",
)?.match.accountId;
if (typeof boundAccountId === "string" && boundAccountId.trim()) {
return [[channelId, boundAccountId.trim()]];

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P1 Badge Ignore wildcard bindings for default pairing imports

When a config has a channel-wide route binding such as bindings[].match.accountId: "*", this new default-account resolver treats "*" as a concrete account and imports the legacy unscoped <channel>-allowFrom.json rows into SQLite account "*". Wildcard bindings are routing-only channel matches (src/routing/resolve-route.ts:792) and Telegram account selection explicitly ignores them (extensions/telegram/src/account-selection.ts:60), so the gateway still starts/reads the real account such as default; after this migration the approved DM senders sit under an account id runtime never reads and lose access. Skip wildcard/empty binding matches here and fall through to the plugin/default-account resolver.

Useful? React with 👍 / 👎.

@clawsweeper clawsweeper Bot added rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. P1 High-priority user-facing bug, regression, or broken workflow. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. P2 Normal backlog priority with limited blast radius. labels Jul 13, 2026
@steipete

Copy link
Copy Markdown
Contributor Author

Land-ready at exact head 987e1f63ba9cf54ac584a08075fb95412860c675.

Proof:

Known proof gaps: none.

@steipete
steipete merged commit 024b7d5 into main Jul 13, 2026
110 checks passed
@steipete
steipete deleted the codex/pairing-sqlite branch July 13, 2026 01:53
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Jul 13, 2026
…5802)

* refactor(pairing): move channel state to SQLite

* fix(pairing): preserve doctor and SDK contracts

* fix(pairing): break SQLite storage import cycle

* fix(pairing): keep SQLite types outside SDK graph
senw-developers added a commit to senw-developers/va-openclaw that referenced this pull request Aug 11, 2026
…ovider headers (R-3)

An unset OPENCLAW_ORGANIZATION_ID makes the config-interpolation path re-emit the
literal ${OPENCLAW_ORGANIZATION_ID} placeholder, which would then ship verbatim
in the cf-aig-metadata header to Cloudflare.

Closes R-3 with a plugin-owned doctor health check registered via
openclaw/plugin-sdk/health — the same seam the policy plugin uses — so it adds
zero core conflict surface. It walks models.providers.*.headers.* and
*.request.headers.* for values referencing an env var that is absent or empty,
and emits an error finding naming the path and the variable. Proven against the
real spawn-seed: org id unset yields one error on the cf-aig-metadata header,
org id set yields none. Registration is unit-tested since no plugin doctor
checks run on a bare dev box to exercise it end to end.

Also adds the first coverage for the spawn-seed itself (5 invariants: main is the
sole agent and the pinned default, the default survives a seat add, every nabu
skill token is an env SecretRef, and the org id reaches Cloudflare only through a
placeholder). Located in the nabu-gateway extension lane, which is already
routed, rather than adding a nabu-integration test project.

Ledger: R-3 fixed; Job 2 measured — upstream is ~20,283 commits ahead with all
38 fork files also changed upstream, so the catch-up is a scheduled merge; and
paired.json->SQLite must NOT be built on our side because upstream already
migrated it (openclaw#105802), so we adopt theirs on catch-up.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

channel: telegram Channel integration: telegram commands Command implementations docs Improvements or additions to documentation maintainer Maintainer-authored PR 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. P1 High-priority user-facing bug, regression, or broken workflow. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. size: XL status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Runtime pairing state still writes legacy JSON files

1 participant