Skip to content

fix: plugin tools disappear for agents with separate workspaces - #194876

Open
saariuslystoned wants to merge 3 commits into
openclaw:mainfrom
saariuslystoned:codex/research-workspace-tools-20261107
Open

saariuslystoned wants to merge 3 commits into
openclaw:mainfrom
saariuslystoned:codex/research-workspace-tools-20261107

Conversation

@saariuslystoned

@saariuslystoned saariuslystoned commented Nov 7, 2026 •

Copy link
Copy Markdown
Contributor

Related: #194674 (merged; this is a separate workspace-recovery fix).

What Problem This Solves

Fixes enabled plugin tools, including x_search, disappearing from effective tool inventory when an agent uses a workspace different from the Gateway's discovery workspace.

User Impact

Agents with separate workspaces recover the Gateway's available plugin tools while retaining their existing tool and authentication policy. No configuration migration is needed. This PR covers inventory recovery; actual X invocation and citations remain pending on a separate Research execution failure.

Why This Change Was Made

The recovery guard compared a fingerprint captured for Gateway plugin discovery with one computed using the agent's execution workspace. It now compares the Gateway's discovery workspace while continuing to use the caller's config; tool creation still receives the agent's actual workspace.

Current-owner, manifest-identity, discovery-fingerprint, plugin-policy, narrow selected-model scope and retain/release guards remain intact. No new credential source or global fallback is introduced. Temporary Research timeout diagnostics are excluded.

The integration tests use real selected-model acquisition, the admitting Gateway registry and bundled XAI tool construction. A schema-only mock would not cross the discovery-workspace fingerprint guard that caused the empty inventory. Shared provider/owner setup and a three-row XAI table remove 96 lines from the initial tests while preserving all four cases. The remaining net growth is 177 regression-test lines. The separate allocation record grants exactly those 177 lines under the documented test-line policy; the shared scalar and all other allocations remain unchanged. This preserves existing base slack rather than consuming a moving shared allowance.

Evidence

  • Red: on 60521f723188be7c91b768d424cafa1ef1e49453, real selected-model acquisition passes with equal workspaces and fails with distinct workspaces: expected ['x_search'], actual []. Both affected baseline files match source base 963de16b208f24f398172db276fba482af98277c.
  • Green code/test source: all four cases pass at 5efaa44c7e70e9f1a5220a2c48b4a2735bc0b18b: direct OpenAI/Codex preview metadata, real selected-model acquisition with equal and distinct workspaces, and full Gateway recovery without widening the selected-model generation. Synthetic inherited XAI OAuth is present; no provider inference or X fetch occurs.
  • Negative and lifecycle coverage retains changed discovery precedence, mismatched manifest identity, disabled plugins, unavailable current owner, no cold plugin reload, execution-workspace delivery, and retained work during owner closure.
  • Measured cost: the focused file passes 4/4 in 70.02 seconds of wall time including compilation/import; reported case times total 3.874 seconds. File-specific CI seconds are not separately available. The cold wall time is why this uses the real composition only at its owning boundary rather than duplicating it across layers.
  • Core types, affected test types, type-aware lint, formatting and whitespace checks pass for the unchanged code/test bytes. The allocation-only follow-up reuses that runtime proof and validates the native ratchet against both source base 963de16 and CI's exact merge a921c919268147d320de3976c6fa03840c6290ff over base 4f84bfd25e78aa35f6eb5fb17c5332d271fdfb29. The old CI failed by 51 lines because newer main reduced shared slack from 177 to 126; the allocation preserves both bases' existing slack.
  • Supporting live evidence on combined candidate c3d95bd2ece101a370c85d6ae79818214bc7237b (base 60521f7) changed the existing separate-workspace Research inventory from empty to exactly ['x_search']. Its production repair is byte-identical, but that candidate also contains excluded diagnostics and is not exact-head PR proof. Its 59-test inventory suite is supporting evidence only.
  • An exact P3 comprehensive review of code/test head 5efaa44 found zero actionable defects. Current-head CI/review remain required; the native generation for that head failed before publishing a verdict and does not clear native review. No merge or release is requested.
Focused validation commands
node scripts/run-vitest.mjs src/agents/tools-effective-inventory.gateway-plugin-tools.test.ts --maxWorkers=1
node scripts/run-tsgo.mjs -p tsconfig.core.json --incremental --tsBuildInfoFile .artifacts/tsgo-cache/core.tsbuildinfo
node scripts/run-tsgo-core-test-shards.mts --changed-paths-json '["src/agents/tools-effective-inventory.gateway-plugin-tools.test.ts"]' --concurrency 1
node scripts/run-oxlint.mjs --threads 2 src/agents/tools-effective-inventory.ts src/agents/tools-effective-inventory.gateway-plugin-tools.test.ts
node_modules/.bin/oxfmt --check src/agents/tools-effective-inventory.ts src/agents/tools-effective-inventory.gateway-plugin-tools.test.ts
node --import ./scripts/tsx.mjs scripts/check-test-lines-ratchet.mts --base 963de16b208f24f398172db276fba482af98277c
git diff --check

The acquisition fixture uses a synthetic non-XAI dynamic model; it does not claim native OpenAI/Codex model discovery. Allocation checks also use task-owned index snapshots of the exact source and CI merge, with the real index and worktree untouched.

@clawsweeper

clawsweeper Bot commented Nov 7, 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 agents Agent runtime and tooling size: M labels Nov 7, 2026
@saariuslystoned
saariuslystoned marked this pull request as ready for review November 7, 2026 23:57
@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Nov 8, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. and removed clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Nov 8, 2026
@clawsweeper

clawsweeper Bot commented Nov 8, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR validates Gateway registry recovery using its discovery workspace while preserving the agent’s workspace for tool construction.

Example: The research agent uses <root>/research-workspace while Gateway plugin discovery uses <root>/workspace, with x_search enabled and a dynamic model selected.

  • Before: tools.effective omits x_search and reports it unavailable.
  • After: tools.effective includes x_search@xai and reports it available.

Review scores

Measure Result What it means
Overall readiness 🦞 diamond lobster (5/6) Focused owner-level repair with shipped-entry-point red/green evidence, meaningful regression coverage, successful exact-head gates, and no actionable findings.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): The complete new comment supplies exact-head macOS Gateway CLI and real WebSocket RPC evidence for selected-model inventory recovery: research changes from no tools to x_search@xai available, while the equal-workspace control is unchanged, resolving the previous review’s proof request.
Patch quality 🦞 diamond lobster (5/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: An agent with a separate workspace sees enabled plugin tools reported as unavailable in its effective-tool preview.
Reason: Restores the existing complete-inventory contract without changing authentication, configuration, or execution policy; actual X invocation is outside the stated inventory scope.

Regression provenance

Possible regression — suspected (reviewed change). No predecessor PR is attributed.

Merge readiness

✅ Ready for maintainer review

This PR fixes a current-main inventory defect with a focused change; no actionable defects remain in the reviewed patch.

Priority: P2
Reviewed head: f98e0643a0e607c84c63b268e22cf1b74ca170c2

Before merge

None.

Findings

None.

Agent review details

How this fits together

The effective-tool resolver receives session, model, workspace, and policy facts, assembles tools from lifecycle-owned plugin registrations, and returns filtered inventory groups and availability diagnostics.

flowchart TD
A[Gateway tools.effective request] --> B[Selected model context]
B --> C[Gateway registry recovery]
D[Captured discovery workspace] --> C
C --> E[Tool construction with agent workspace]
E --> F[Policy and compatibility filtering]
F --> G[Inventory and diagnostics]
Loading

Technical review

Best possible solution:

Merge the focused workspace comparison repair through the normal landing workflow.

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

The fingerprint producer and current-main consumer show the workspace mismatch directly, corroborated by the contributor’s shipped-Gateway base/head trace; no target code was executed during this read-only review.

Is this the best way to solve the issue?

This is the smallest complete production repair: compare discovery identity using the existing registry owner’s workspace and retain the agent workspace for construction, without adding state, loaders, APIs, or policy.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against dec19a6acb83.

Provenance checked

  • Gateway registry recovery keeps the original intent (b28fe43: Recover tool-only plugins omitted by narrow dynamic-model generations while preserving registry identity, configuration matching, and retained-work custody.)
  • Shared integration fixture keeps the original intent (d180188: Consolidate duplicated setup while retaining meaningful owner-boundary assertions.)
  • Managed GitHub inventory projection keeps the original intent (b1e2c66: Project eligible managed GitHub tools through existing session policy; the changed enclosing call preserves that projection.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

Likely related people:

  • TUARAN: Raw commit b28fe43 adds src/agents/tools-effective-inventory.ts:221 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: b28fe43ccf65; files: src/agents/tools-effective-inventory.ts)
  • Peter Steinberger: Raw commit 34e0e5d adds src/agents/tools-effective-inventory.ts:239 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 34e0e5d7e53c; files: src/agents/tools-effective-inventory.ts)

PR surface

Source +4, Tests +177, Other +3. Total +184 across 3 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 1 7 3 +4
Tests 1 228 51 +177
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 1 3 0 +3
Total 3 238 54 +184

Preflight source

Source unknown. Source comparison at the observed PR snapshot only. Completion is self-reported; body, policy, tests, execution, and report bytes are not verified.

Review metrics

Metric Value Why it matters
Production versus regression coverage Production +7/-3; tests +228/-51 (net +177) Small production correction with shared real-loader fixtures covering workspace recovery and distinct identity, policy, and lifecycle boundaries.

Labels

Label changes:

No label changes.

Label justifications:

  • P2: Incorrect tool availability previews affect separate-workspace agents with dynamic models; the demonstrated scope is inventory rather than failed tool execution.
  • rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • proof: sufficient: Contributor real behavior proof is sufficient.

Rating scale

6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only. Repair and merge execution lanes are retired.

History

Review history (1 earlier review cycle)
  • reviewed 2026-11-08T03:35:26.182Z sha f98e064 :: needs real behavior proof before merge. :: none

Reviewed November 8, 2026, 11:07 AM ET / 16:07 UTC (Revision 2).

@saariuslystoned

Copy link
Copy Markdown
Contributor Author

Shipped-Gateway proof for f98e0643a0e6: tools.effective for an agent with its own workspace

This supplies the missing end-to-end proof from the review: sanitized tools.effective output from a running Gateway, for a selected-model session whose agent workspace differs from the Gateway's plugin discovery workspace. It covers base and head, with an equal-workspace control.

Setup. macOS arm64, Node 24.22.1, pnpm 12.15.0.

  • Builds: each checkout is prepared with node scripts/worktree-setup.mjs gateway.
    • Head: exact f98e0643a0e607c84c63b268e22cf1b74ca170c2.
    • Base: the same checkout with only src/agents/tools-effective-inventory.ts restored from the PR's merge base 963de16b208f24f398172db276fba482af98277c. That is the PR's only production file, so the base runtime is 963de16b.
  • Gateway: node scripts/run-node.mjs gateway run --port <ephemeral> --bind loopback --auth none --tailscale off --allow-unconfigured. It runs with a throwaway HOME, state, config, TMPDIR and XDG tree and an allowlisted environment.
  • No real credentials, no I/O: XAI_API_KEY is a placeholder, and nothing contacts xAI or any model.
  • Config, as in the PR fixture:
    • Default model inventory-dynamic/chat-dynamic, from a local provider plugin (plugins.load.paths) that implements prepareDynamicModel.
    • xai enabled with xSearch.enabled: true, and tools: { profile: "full", allow: ["x_search"] }.
    • The Gateway discovers plugins from agents.defaults.workspace = <root>/workspace. Agent main uses that same directory (equal control). Agent research uses <root>/research-workspace (distinct).
  • Calls: sessions.create { agentId, key: "agent:<id>:inventory-proof" }, then tools.effective { sessionKey, agentId }, for each agent.

Result

Build main (equal workspace) research (distinct workspace)
base 963de16b x_search@xai, available no tools; x_search unavailable, "Not included in the session preview"
head f98e0643 x_search@xai, available x_search@xai, available

The main control output is byte-identical on base and head (same SHA-256 below). Only the distinct-workspace agent changes.

tools.effective, projected (agentId, profile, groups, the x_search access row)
base main:     {"agentId":"main","profile":"full","groups":[{"id":"plugin","tools":["x_search@xai"]}],"x_search":{"id":"x_search","status":"available","reasons":[]}}
base research: {"agentId":"research","profile":"full","groups":[],"x_search":{"id":"x_search","status":"unavailable","reasons":[{"kind":"runtime","label":"Not included in the session preview"}]}}
head main:     {"agentId":"main","profile":"full","groups":[{"id":"plugin","tools":["x_search@xai"]}],"x_search":{"id":"x_search","status":"available","reasons":[]}}
head research: {"agentId":"research","profile":"full","groups":[{"id":"plugin","tools":["x_search@xai"]}],"x_search":{"id":"x_search","status":"available","reasons":[]}}

Artifact hashes (SHA-256). These are the full tools.effective responses with the state root replaced by <root>. No home or host paths appear in them.

098585b6df241a563103f6070e9c2fef7031a16696cd1cbdd2506dc686b5cf46  base-963de16b/tools-effective-main.json
a5ba3a5d1f234d743b2441e4c203bfcd8edc8ff6c05c9b8913e19ef70688c3fa  base-963de16b/tools-effective-research.json
098585b6df241a563103f6070e9c2fef7031a16696cd1cbdd2506dc686b5cf46  head-f98e0643/tools-effective-main.json
312aa81e64100804a536663e4a6769aaa787dc5a54ffbd264e19819efe473766  head-f98e0643/tools-effective-research.json

Scope: this covers inventory recovery only, as the PR states. It does not invoke X search or a model. Reproduce with the two files below: node --import <checkout>/scripts/tsx.mjs scenario-194876.mts <checkout> <outDir> <label>.

gw-lib.mts (isolated Gateway harness)
// Shared isolated-Gateway harness for PR proof runs.
// Starts `node scripts/run-node.mjs gateway run` from a checkout with a throwaway
// HOME/state/config/TMPDIR/XDG tree, an ephemeral loopback port, auth none, and an
// allowlisted environment (no inherited OPENCLAW_* or provider keys).
import { spawn, type ChildProcess } from "node:child_process";
import { existsSync, mkdirSync, openSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { connect, createServer } from "node:net";
import path from "node:path";
import { setTimeout as sleep } from "node:timers/promises";

export type GatewayHandle = {
  root: string;
  port: number;
  call: (method: string, params: unknown, timeoutMs?: number) => Promise<any>;
  stop: () => Promise<{ code: number | null; signal: string | null }>;
};

// run-node keeps the checkout's dist lock for the Gateway's lifetime and leaves it on SIGTERM.
// Remove it only when its recorded owner process is gone (scratch checkout only).
export function clearDeadDistLock(checkout: string) {
  const dir = path.join(checkout, ".artifacts", "dist-artifacts.lock");
  const owner = path.join(dir, "owner.json");
  if (!existsSync(owner)) return;
  const pid = Number(JSON.parse(readFileSync(owner, "utf8")).pid);
  try {
    process.kill(pid, 0);
    return; // still alive
  } catch {}
  rmSync(dir, { recursive: true, force: true });
}

export async function freePort(): Promise<number> {
  return await new Promise((resolve) => {
    const s = createServer();
    s.listen(0, "127.0.0.1", () => {
      const p = (s.address() as { port: number }).port;
      s.close(() => resolve(p));
    });
  });
}

export function makeRoot(outDir: string) {
  const root = path.join(outDir, "root");
  for (const d of ["home", "state", "workspace", "tmp", "logs", "xdg-config", "xdg-data", "xdg-cache", "xdg-state"]) {
    mkdirSync(path.join(root, d), { recursive: true });
  }
  return root;
}

export function isolatedEnv(root: string, configPath: string, extra: Record<string, string | undefined> = {}) {
  const env: NodeJS.ProcessEnv = {
    PATH: process.env.PATH,
    LANG: "en_US.UTF-8",
    HOME: path.join(root, "home"),
    OPENCLAW_HOME: path.join(root, "home"),
    OPENCLAW_STATE_DIR: path.join(root, "state"),
    OPENCLAW_CONFIG_PATH: configPath,
    TMPDIR: path.join(root, "tmp"),
    XDG_CONFIG_HOME: path.join(root, "xdg-config"),
    XDG_DATA_HOME: path.join(root, "xdg-data"),
    XDG_CACHE_HOME: path.join(root, "xdg-cache"),
    XDG_STATE_HOME: path.join(root, "xdg-state"),
    OPENCLAW_SKIP_CHANNELS: "1",
    OPENCLAW_SKIP_CRON: "1",
    OPENCLAW_SKIP_BROWSER_CONTROL_SERVER: "1",
    OPENCLAW_SKIP_CANVAS_HOST: "1",
    OPENCLAW_SKIP_GMAIL_WATCHER: "1",
    // Own service-coordination key: the default label is shared by every checkout on this Mac.
    OPENCLAW_LAUNCHD_LABEL: "ai.openclaw.proofcloser",
  };
  for (const [k, v] of Object.entries(extra)) {
    if (v === undefined) delete env[k];
    else env[k] = v;
  }
  return env;
}

const portOpen = (port: number) =>
  new Promise<boolean>((resolve) => {
    const sock = connect(port, "127.0.0.1");
    sock.once("connect", () => {
      sock.destroy();
      resolve(true);
    });
    sock.once("error", () => resolve(false));
  });

export async function startGateway(params: {
  checkout: string;
  outDir: string;
  root: string;
  port: number;
  config: Record<string, unknown>;
  env?: Record<string, string | undefined>;
}): Promise<GatewayHandle> {
  const { checkout, outDir, root, port } = params;
  const configPath = path.join(root, "openclaw.json");
  writeFileSync(configPath, `${JSON.stringify(params.config, null, 2)}\n`);
  const env = isolatedEnv(root, configPath, params.env);
  const args = ["scripts/run-node.mjs", "gateway", "run", "--port", String(port), "--bind", "loopback", "--auth", "none", "--tailscale", "off", "--allow-unconfigured"];
  writeFileSync(
    path.join(outDir, "gateway-command.txt"),
    `cwd=<checkout>\nnode ${args.join(" ")}\nenv keys: ${Object.keys(env).toSorted().join(",")}\n`,
  );
  const gw: ChildProcess = spawn(process.execPath, args, {
    cwd: checkout,
    env,
    detached: true,
    stdio: ["ignore", openSync(path.join(outDir, "gateway.stdout.log"), "w"), openSync(path.join(outDir, "gateway.stderr.log"), "w")],
  });
  const exited = new Promise<{ code: number | null; signal: string | null }>((resolve) =>
    gw.once("exit", (code, signal) => resolve({ code, signal })),
  );
  const deadline = Date.now() + 1_800_000;
  while (!(await portOpen(port))) {
    if (gw.exitCode !== null) throw new Error(`gateway exited early (${gw.exitCode}); see gateway.stderr.log`);
    if (Date.now() > deadline) throw new Error("gateway not listening within 1800s");
    await sleep(500);
  }
  const { GatewayClient, startGatewayClientWhenEventLoopReady } = await import(
    path.join(checkout, "src/plugin-sdk/gateway-runtime.ts")
  );
  let helloResolve!: () => void;
  const hello = new Promise<void>((r) => (helloResolve = r));
  const client = new GatewayClient({
    url: `ws://127.0.0.1:${port}`,
    requestTimeoutMs: 180_000,
    clientName: "gateway-client",
    deviceIdentity: null,
    mode: "backend",
    scopes: ["operator.admin"],
    onHelloOk: () => helloResolve(),
  });
  const readiness = await startGatewayClientWhenEventLoopReady(client, { timeoutMs: 180_000 });
  if (!readiness.ready) throw new Error("gateway client readiness timeout");
  await Promise.race([hello, sleep(180_000).then(() => { throw new Error("hello timeout"); })]);
  return {
    root,
    port,
    call: (method, p, timeoutMs = 180_000) => client.request(method, p, { timeoutMs }),
    stop: async () => {
      await client.stopAndWait?.().catch?.(() => {});
      // Signal the run-node wrapper only: it forwards to the Gateway and releases its dist lock.
      if (gw.exitCode === null && gw.pid) {
        try { process.kill(gw.pid, "SIGTERM"); } catch {}
      }
      const timer = setTimeout(() => { try { if (gw.pid) process.kill(-gw.pid, "SIGKILL"); } catch {} }, 60_000);
      const result = await exited;
      clearTimeout(timer);
      clearDeadDistLock(checkout);
      return result;
    },
  };
}
scenario-194876.mts
// PR 194876: tools.effective for an agent whose workspace differs from the Gateway's
// discovery workspace, with a selected dynamic model (narrow selected-model lease).
// Usage: node --import <checkout>/scripts/tsx.mjs scenario-194876.mts <checkout> <outDir> <label>
import { mkdirSync, writeFileSync } from "node:fs";
import path from "node:path";
import { freePort, makeRoot, startGateway } from "./gw-lib.mts";

const [checkout, outDir, label] = process.argv.slice(2);
if (!checkout || !outDir || !label) throw new Error("usage: scenario-194876.mts <checkout> <outDir> <label>");
mkdirSync(outDir, { recursive: true });
const root = makeRoot(outDir);
const researchWorkspace = path.join(root, "research-workspace");
mkdirSync(researchWorkspace, { recursive: true });
writeFileSync(path.join(researchWorkspace, ".keep"), "synthetic Research workspace\n");

// Local provider plugin with a dynamic model, as in the PR's regression fixture.
const pluginDir = path.join(root, "plugins", "provider");
mkdirSync(pluginDir, { recursive: true });
const model = {
  id: "chat-dynamic",
  name: "chat-dynamic",
  provider: "inventory-dynamic",
  api: "openai-completions",
  baseUrl: "http://127.0.0.1:9/v1", // never contacted: no inference in this scenario
  reasoning: false,
  input: ["text"],
  cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
  contextWindow: 128000,
  maxTokens: 4096,
};
writeFileSync(
  path.join(pluginDir, "index.cjs"),
  `module.exports = {
  id: "inventory-provider",
  register(api) {
    api.registerProvider({
      id: "inventory-dynamic", label: "Inventory dynamic provider", auth: [],
      async prepareDynamicModel(ctx) {
        if (ctx.modelId === "chat-dynamic") return ${JSON.stringify(model)};
      },
    });
  },
};
`,
);
writeFileSync(
  path.join(pluginDir, "openclaw.plugin.json"),
  JSON.stringify({ id: "inventory-provider", providers: ["inventory-dynamic"], configSchema: { type: "object", additionalProperties: false } }, null, 2),
);

const port = await freePort();
const config = {
  meta: { migrations: { skillWorkshopPlugin: true } },
  logging: { file: path.join(root, "logs", "openclaw-YYYY-MM-DD.log") },
  gateway: { mode: "local", bind: "loopback", port, auth: { mode: "none" } },
  agents: {
    defaults: { model: "inventory-dynamic/chat-dynamic", workspace: path.join(root, "workspace"), systemAgent: { agentId: "main" } },
    ownership: "explicit",
    // main: same directory the Gateway discovers plugins from (equal control); research: separate.
    entries: { main: { workspace: path.join(root, "workspace") }, research: { workspace: researchWorkspace } },
  },
  tools: { profile: "full", allow: ["x_search"] },
  plugins: {
    allow: ["inventory-provider", "xai"],
    load: { paths: [path.join(pluginDir, "index.cjs")] },
    slots: { memory: "none" },
    entries: {
      "inventory-provider": { enabled: true },
      xai: { enabled: true, config: { xSearch: { enabled: true } } },
    },
  },
};
const gw = await startGateway({
  checkout,
  outDir,
  root,
  port,
  config,
  // Placeholder only; inventory never contacts xAI.
  env: { XAI_API_KEY: "placeholder-not-a-real-key" },
});

const redact = (value: unknown) => JSON.parse(JSON.stringify(value).split(root).join("<root>"));
const toolIds = (inv: any) => (inv?.groups ?? []).flatMap((g: any) => (g.tools ?? []).map((t: any) => `${t.id}${t.pluginId ? `@${t.pluginId}` : ""}`));
const results: Record<string, unknown> = { label, port };
try {
  for (const agentId of ["main", "research"]) {
    const key = `agent:${agentId}:inventory-proof`;
    const created = await gw.call("sessions.create", { agentId, key });
    const inventory = await gw.call("tools.effective", { sessionKey: key, agentId });
    writeFileSync(path.join(outDir, `tools-effective-${agentId}.json`), `${JSON.stringify(redact(inventory), null, 2)}\n`);
    const ids = toolIds(inventory);
    results[agentId] = {
      sessionKey: key,
      created: redact({ key: created?.key }),
      toolCount: ids.length,
      xSearch: ids.filter((id: string) => id.startsWith("x_search")),
      xSearchAccess: inventory?.toolAccess?.tools?.find((t: any) => t.id === "x_search") ?? null,
    };
  }
  const agents = await gw.call("agents.list", {}).catch((e: unknown) => ({ error: String(e) }));
  results.agents = redact(
    (agents?.agents ?? agents)?.map?.((a: any) => ({ id: a.id, workspace: a.workspace ?? a.workspaceDir })) ?? agents,
  );
} finally {
  results.gatewayExit = await gw.stop();
}
writeFileSync(path.join(outDir, "summary.json"), `${JSON.stringify(results, null, 2)}\n`);
console.log(JSON.stringify(results, null, 2));

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Nov 8, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Nov 8, 2026
@roboclaw-bot roboclaw-bot added the clawtributors PR from a clawtributor label Nov 8, 2026

This branch has not been deployed

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

Labels

agents Agent runtime and tooling clawtributors PR from a clawtributor P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. size: M status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants