Skip to content

refactor(plugins): prefer setup descriptors for setup lookup - #64786

Merged
vincentkoc merged 8 commits into
mainfrom
feat/ocplugins-setup-fallback
Apr 12, 2026
Merged

vincentkoc merged 8 commits into
mainfrom
feat/ocplugins-setup-fallback

Conversation

@vincentkoc

Copy link
Copy Markdown
Member

Summary

  • Problem: phase 2 of the ocplugins plan needed setup lookups to prefer manifest descriptors before falling back to setup-api, but resolvePluginSetupCliBackend() still built the whole setup registry and loaded every setup module first.
  • Why it matters: broad setup fanout is exactly the kind of import cost that makes plugin-heavy tests and startup paths slower than they need to be.
  • What changed: added shared setup-descriptor helpers, switched provider/cli-backend setup lookup to consume descriptor-owned ids first, added a direct cli-backend cache, updated the bundled runtime fallback, and added setup-focused tests plus docs.
  • What did NOT change (scope boundary): no activation planner, no full setup-registry rewrite, no plugin-wide descriptor backfill, and no changes to runtime plugin activation behavior.
  • AI-assisted: yes.

Change Type (select all)

  • Bug fix
  • Feature
  • Refactor required for the fix
  • Docs
  • Security hardening
  • Chore/infra

Scope (select all touched areas)

  • Gateway / orchestration
  • Skills / tool execution
  • Auth / tokens
  • Memory / storage
  • Integrations
  • API / contracts
  • UI / DX
  • CI/CD / infra

Linked Issue/PR

Root Cause (if applicable)

  • Root cause: setup lookup still had a broad eager path, especially for CLI backends, where it loaded the full setup registry before doing the narrow manifest-directed fallback that already existed.
  • Missing detection / guardrail: there was no test asserting that cli-backend setup lookup should avoid loading unrelated setup-api modules.
  • Contributing context (if known): phase 1 added descriptor metadata, but setup lookup had not started consuming it yet.

Regression Test Plan (if applicable)

  • Coverage level that should have caught this:
    • Unit test
    • Seam / integration test
    • End-to-end test
    • Existing coverage already sufficient
  • Target test or file: src/plugins/setup-registry.test.ts, src/plugins/setup-registry.runtime.test.ts
  • Scenario the test should lock in: descriptor-first provider/cli-backend lookup narrows to the owning plugin and avoids loading unrelated setup modules.
  • Why this is the smallest reliable guardrail: the regression is in setup-registry import/load behavior, so the narrow setup-registry tests are the most direct place to prove fanout stays small.
  • Existing test that already covers this (if any): none
  • If no new test is added, why not: N/A

User-visible / Behavior Changes

Setup lookup now prefers manifest setup.providers / setup.cliBackends descriptors when present, then falls back to setup-api only for the matched plugin that still needs runtime setup hooks.

Diagram (if applicable)

Before:
setup cli-backend lookup -> build full setup registry -> load many setup-api modules -> find one backend

After:
setup cli-backend lookup -> read manifest descriptors -> pick owning plugin -> load one setup-api module if needed

Security Impact (required)

  • New permissions/capabilities? (Yes/No): No
  • Secrets/tokens handling changed? (Yes/No): No
  • New/changed network calls? (Yes/No): No
  • Command/tool execution surface changed? (Yes/No): No
  • Data access scope changed? (Yes/No): No
  • If any Yes, explain risk + mitigation: N/A

Repro + Verification

Environment

  • OS: macOS
  • Runtime/container: Node 22 / pnpm
  • Model/provider: N/A
  • Integration/channel (if any): plugin setup registry
  • Relevant config (redacted): default repo config

Steps

  1. Add manifest setup descriptors to setup lookup selection logic.
  2. Resolve setup providers / cli backends through the setup registry helpers.
  3. Run focused setup-registry tests, targeted lint, and a full build.

Expected

  • setup lookup narrows from manifest descriptors first
  • cli-backend setup lookup does not load unrelated setup-api modules
  • bundled runtime fallback respects setup descriptor ids
  • build stays green

Actual

  • Works as expected.

Evidence

  • Failing test/log before + passing after
  • Trace/log snippets
  • Screenshot/recording
  • Perf numbers (if relevant)

Verification:

  • pnpm test:serial src/plugins/setup-registry.test.ts src/plugins/setup-registry.runtime.test.ts
  • pnpm lint -- src/plugins/setup-descriptors.ts src/plugins/setup-registry.ts src/plugins/setup-registry.runtime.ts src/plugins/setup-registry.test.ts src/plugins/setup-registry.runtime.test.ts
  • pnpm build

Known unrelated local gate:

  • pnpm check:host-env-policy:swift still fails on fresh main drift in apps/macos/Sources/OpenClaw/HostEnvSecurityPolicy.generated.swift.

Human Verification (required)

  • Verified scenarios: descriptor-first provider lookup, descriptor-first cli-backend lookup, one-plugin cli-backend setup loading, bundled runtime fallback, targeted lint, and full build.
  • Edge cases checked: setup descriptors override top-level setup lookup ids when present; repeated cli-backend lookups hit the direct cache instead of reloading the setup module.
  • What you did not verify: no plugin-wide manifest backfill in this PR, and no activation-planner behavior yet.

Review Conversations

  • I replied to or resolved every bot review conversation I addressed in this PR.
  • I left unresolved only the conversations that still need reviewer or maintainer judgment.

Compatibility / Migration

  • Backward compatible? (Yes/No): Yes
  • Config/env changes? (Yes/No): No
  • Migration needed? (Yes/No): No
  • If yes, exact upgrade steps: N/A

Risks and Mitigations

  • Risk: setup descriptors could be misread as replacing richer setup runtime objects.
    • Mitigation: docs now say descriptor-first lookup still falls back to setup-api when requiresRuntime is needed, and the code only narrows selection rather than synthesizing full backend/provider objects.

@vincentkoc vincentkoc self-assigned this Apr 11, 2026
@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation size: M maintainer Maintainer-authored PR labels Apr 11, 2026
@vincentkoc
vincentkoc marked this pull request as ready for review April 11, 2026 11:55
@greptile-apps

greptile-apps Bot commented Apr 11, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR refactors plugin setup lookup (provider and CLI backend) to prefer manifest setup.providers/setup.cliBackends descriptors before falling back to setup-api module execution, reducing eager import fanout in plugin-heavy paths. New shared helpers in setup-descriptors.ts, a direct cli-backend cache in setup-registry.ts, a lightweight bundled runtime fallback in setup-registry.runtime.ts, and matching tests are all well-structured.

  • The new resolvePluginSetupCliBackend diverges from the established async-register pattern: it caches null and returns early when register(api) yields a Promise, while resolvePluginSetupProvider and resolvePluginSetupRegistry ignore the Promise and fall through so synchronously-registered entries are still returned — any plugin whose register function is async (even incidentally) will have its CLI backend permanently cached as a miss.

Confidence Score: 4/5

Mostly safe to merge, but the async-register early-return in resolvePluginSetupCliBackend diverges from the established pattern and could silently cache a null result for any plugin whose register function returns a Promise.

One P1 logic inconsistency: the new cli-backend path treats a returned Promise as a hard failure and caches null, while the analogous provider and registry paths fall through and return whatever was synchronously registered. All other changes are correct and well-tested.

src/plugins/setup-registry.ts — specifically the async branch in resolvePluginSetupCliBackend (lines 563-567).

Comments Outside Diff (1)

  1. src/plugins/setup-registry.runtime.ts, line 39-50 (link)

    P2 listSetupCliBackendIds called twice per plugin

    listSetupCliBackendIds(plugin) is invoked once in .filter() (for the length check) and again in .flatMap() for mapping. Each call re-reads setup.cliBackends ?? cliBackends, which is cheap but redundant. Caching the result avoids the double traversal and makes intent clearer.

    Prompt To Fix With AI
    This is a comment left during a code review.
    Path: src/plugins/setup-registry.runtime.ts
    Line: 39-50
    
    Comment:
    **`listSetupCliBackendIds` called twice per plugin**
    
    `listSetupCliBackendIds(plugin)` is invoked once in `.filter()` (for the length check) and again in `.flatMap()` for mapping. Each call re-reads `setup.cliBackends ?? cliBackends`, which is cheap but redundant. Caching the result avoids the double traversal and makes intent clearer.
    
    
    
    How can I resolve this? If you propose a fix, please make it concise.
Prompt To Fix All With AI
This is a comment left during a code review.
Path: src/plugins/setup-registry.ts
Line: 563-567

Comment:
**Async-register early-return discards synchronously-set `matchedBackend`**

When `resolved.register(api)` returns a Promise, this block caches `null` and returns `undefined` even though the synchronous portion of `register` may have already called `registerCliBackend` and set `matchedBackend`. The same Promise case in `resolvePluginSetupProvider` (line ~467) and `resolvePluginSetupRegistry` (line ~367) uses the comment `// Keep setup registration sync-only.` and falls through so the synchronously-registered entry is still returned. The new cli-backend path is stricter without a clear reason — if any plugin's `register` function returns a Promise (even incidentally), the backend is permanently cached as `null`.

```suggestion
  try {
    const result = resolved.register(api);
    if (result && typeof result.then === "function") {
      // Keep setup registration sync-only.
    }
  } catch {
    setupCliBackendCache.set(cacheKey, null);
    return undefined;
  }
```

How can I resolve this? If you propose a fix, please make it concise.

---

This is a comment left during a code review.
Path: src/plugins/setup-registry.runtime.ts
Line: 39-50

Comment:
**`listSetupCliBackendIds` called twice per plugin**

`listSetupCliBackendIds(plugin)` is invoked once in `.filter()` (for the length check) and again in `.flatMap()` for mapping. Each call re-reads `setup.cliBackends ?? cliBackends`, which is cheap but redundant. Caching the result avoids the double traversal and makes intent clearer.

```suggestion
  bundledSetupCliBackendsCache = loadPluginManifestRegistry({ cache: true })
    .plugins.flatMap((plugin) => {
      if (plugin.origin !== "bundled") return [];
      const ids = listSetupCliBackendIds(plugin);
      if (ids.length === 0) return [];
      return ids.map(
        (backendId) =>
          ({
            pluginId: plugin.id,
            backend: { id: backendId },
          }) satisfies SetupCliBackendRuntimeEntry,
      );
    });
```

How can I resolve this? If you propose a fix, please make it concise.

Reviews (1): Last reviewed commit: "Merge branch 'main' into feat/ocplugins-..." | Re-trigger Greptile

Comment thread src/plugins/setup-registry.ts Resolved
@vincentkoc

Copy link
Copy Markdown
Member Author

follow-up is pushed.

addressed the Aisle findings by:

  • failing closed when more than one discovered plugin claims the same normalized setup.providers[].id or setup.cliBackends[] value, so setup lookup no longer relies on manifest/discovery order before executing plugin code
  • bounding the setup lookup caches with LRU-style eviction instead of leaving them unbounded
  • documenting the setup-id uniqueness rule in the manifest / architecture docs

also addressed the Greptile review note by:

  • keeping synchronously registered CLI backends even when register() returns a promise, matching the existing provider/setup-registry behavior
  • adding a regression test for that case
  • cleaning up the bundled setup runtime helper to avoid the duplicate listSetupCliBackendIds(...) traversal

verified locally with:

  • pnpm test:serial src/plugins/setup-registry.test.ts src/plugins/setup-registry.runtime.test.ts
  • pnpm lint -- src/plugins/setup-registry.ts src/plugins/setup-registry.runtime.ts src/plugins/setup-registry.test.ts docs/plugins/manifest.md docs/plugins/architecture.md
  • pnpm format -- src/plugins/setup-registry.ts src/plugins/setup-registry.runtime.ts src/plugins/setup-registry.test.ts docs/plugins/manifest.md docs/plugins/architecture.md
  • pnpm build

@vincentkoc
vincentkoc force-pushed the feat/ocplugins-setup-fallback branch from a737148 to 25a3e67 Compare April 12, 2026 01:41

@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: bdc7d541fb

ℹ️ 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 thread src/plugins/setup-registry.runtime.ts Resolved
@vincentkoc
vincentkoc merged commit 8ba50aa into main Apr 12, 2026
3 checks passed
@vincentkoc
vincentkoc deleted the feat/ocplugins-setup-fallback branch April 12, 2026 02:29
@aisle-research-bot

aisle-research-bot Bot commented Apr 12, 2026 •

Copy link
Copy Markdown

🔒 Aisle Security Analysis

We found 1 potential security issue(s) in this PR:

# Severity Title
1 🟡 Medium Insufficient provider ID normalization allows zero-width/Unicode confusable IDs to bypass uniqueness checks
1. 🟡 Insufficient provider ID normalization allows zero-width/Unicode confusable IDs to bypass uniqueness checks
Property Value
Severity Medium
CWE CWE-178
Location src/agents/provider-id.ts:3-28

Description

The setup registry’s new ownership/uniqueness enforcement relies on normalizeProviderId() to decide whether a provider/CLI-backend ID is the “same” as another.

normalizeProviderId() currently only:

  • trim()s and lowercases input (via normalizeLowercaseStringOrEmpty())
  • applies a small set of ASCII alias rewrites

It does not perform security-hardened identifier canonicalization (e.g., Unicode normalization such as NFKC/NFKD, stripping format characters like zero-width space, or restricting to a safe ASCII slug charset).

As a result, a plugin manifest can declare IDs that are visually/confusably identical but compare as distinct after normalization (e.g., "openai" vs "openai\u200b"). This can undermine the intended “fail-closed ambiguity” behavior in findUniqueSetupManifestOwner() and related lookups, enabling plugin shadowing/user-confusion scenarios.

Vulnerable code:

export function normalizeProviderId(provider: string): string {
  const normalized = normalizeLowercaseStringOrEmpty(provider);
  ​// ... alias mapping ...
  return normalized;
}

Recommendation

Harden provider/CLI-backend ID canonicalization and/or restrict allowed characters.

A robust approach is:

  • Require IDs to match a strict ASCII slug pattern (recommended for identifiers)
  • Additionally apply Unicode normalization and strip format/control characters before validation

Example:

const STRIP_FORMAT = /[\p{Cf}\p{Cc}]/gu; // format + control
const SAFE_ID = /^[a-z0-9][a-z0-9._+-]*$/;

export function normalizeProviderId(provider: unknown): string {
  if (typeof provider !== "string") return "";
  const normalized = provider
    .normalize("NFKC")
    .replace(STRIP_FORMAT, "")
    .trim()
    .toLowerCase();

  if (!SAFE_ID.test(normalized)) return ""; // or throw/diagnose

  ​// apply alias mapping on normalized
  ​// ...
  return normalized;
}

Also ensure callers reject empty results (""), rather than treating them as a valid identifier in lookups/ownership checks.


Analyzed PR: #64786 at commit 7fd0e74

Last updated on: 2026-04-12T02:35:43Z

@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: 7fd0e74c6c

ℹ️ 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 +39 to +43
(plugin) => {
if (plugin.origin !== "bundled") {
return [];
}
const backendIds = listSetupCliBackendIds(plugin);

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.

P2 Badge Reject ambiguous bundled setup backend ids in fallback

When setup-registry cannot be loaded, this fallback now flattens descriptor-owned backend ids from bundled manifests but still resolves by first match later, so two bundled plugins with the same normalized setup.cliBackends id will silently pick one owner instead of failing closed. That bypasses the ambiguity guard added in resolvePluginSetupCliBackend and can misclassify a CLI provider in isCliProvider/setup flows in runtime-unavailable environments.

Useful? React with 👍 / 👎.

trudbot pushed a commit to trudbot/openclaw that referenced this pull request Apr 12, 2026
…w#64786)

* refactor(plugins): prefer setup descriptors for setup lookup

* fix(plugins): harden setup descriptor lookup

* fix(plugins): keep sync cli backend setup results

* fix(plugins): resolve setup registry rebase

* fix(plugins): preserve fail-closed cli backend lookup

* fix(plugins): fail closed on shadowed setup owners

* fix(plugins): swallow async setup register rejections
TOMUIV pushed a commit to TOMUIV/openclaw that referenced this pull request Apr 14, 2026
…w#64786)

* refactor(plugins): prefer setup descriptors for setup lookup

* fix(plugins): harden setup descriptor lookup

* fix(plugins): keep sync cli backend setup results

* fix(plugins): resolve setup registry rebase

* fix(plugins): preserve fail-closed cli backend lookup

* fix(plugins): fail closed on shadowed setup owners

* fix(plugins): swallow async setup register rejections
lovewanwan pushed a commit to lovewanwan/openclaw that referenced this pull request Apr 28, 2026
…w#64786)

* refactor(plugins): prefer setup descriptors for setup lookup

* fix(plugins): harden setup descriptor lookup

* fix(plugins): keep sync cli backend setup results

* fix(plugins): resolve setup registry rebase

* fix(plugins): preserve fail-closed cli backend lookup

* fix(plugins): fail closed on shadowed setup owners

* fix(plugins): swallow async setup register rejections
ogt-redknie pushed a commit to ogt-redknie/OPENX that referenced this pull request May 2, 2026
…w#64786)

* refactor(plugins): prefer setup descriptors for setup lookup

* fix(plugins): harden setup descriptor lookup

* fix(plugins): keep sync cli backend setup results

* fix(plugins): resolve setup registry rebase

* fix(plugins): preserve fail-closed cli backend lookup

* fix(plugins): fail closed on shadowed setup owners

* fix(plugins): swallow async setup register rejections
globalcaos pushed a commit to globalcaos/tinkerclaw that referenced this pull request May 13, 2026
…w#64786)

* refactor(plugins): prefer setup descriptors for setup lookup

* fix(plugins): harden setup descriptor lookup

* fix(plugins): keep sync cli backend setup results

* fix(plugins): resolve setup registry rebase

* fix(plugins): preserve fail-closed cli backend lookup

* fix(plugins): fail closed on shadowed setup owners

* fix(plugins): swallow async setup register rejections
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request May 24, 2026
…w#64786)

* refactor(plugins): prefer setup descriptors for setup lookup

* fix(plugins): harden setup descriptor lookup

* fix(plugins): keep sync cli backend setup results

* fix(plugins): resolve setup registry rebase

* fix(plugins): preserve fail-closed cli backend lookup

* fix(plugins): fail closed on shadowed setup owners

* fix(plugins): swallow async setup register rejections
jameslcowan pushed a commit to jameslcowan/openclaw that referenced this pull request Jun 2, 2026
…w#64786)

* refactor(plugins): prefer setup descriptors for setup lookup

* fix(plugins): harden setup descriptor lookup

* fix(plugins): keep sync cli backend setup results

* fix(plugins): resolve setup registry rebase

* fix(plugins): preserve fail-closed cli backend lookup

* fix(plugins): fail closed on shadowed setup owners

* fix(plugins): swallow async setup register rejections
vixco pushed a commit to vixco/openclaw that referenced this pull request Aug 16, 2026
…w#64786)

* refactor(plugins): prefer setup descriptors for setup lookup

* fix(plugins): harden setup descriptor lookup

* fix(plugins): keep sync cli backend setup results

* fix(plugins): resolve setup registry rebase

* fix(plugins): preserve fail-closed cli backend lookup

* fix(plugins): fail closed on shadowed setup owners

* fix(plugins): swallow async setup register rejections
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

docs Improvements or additions to documentation maintainer Maintainer-authored PR size: XL

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant