Skip to content

improve(config): cut sync filesystem work on multi-agent config reads - #193841

Merged
vyctorbrzezowski merged 1 commit into
openclaw:mainfrom
etzelm:improve/agent-dir-case-probe-candidates
Nov 9, 2026
Merged

vyctorbrzezowski merged 1 commit into
openclaw:mainfrom
etzelm:improve/agent-dir-case-probe-candidates

Conversation

@etzelm

@etzelm etzelm commented Nov 6, 2026 •

Copy link
Copy Markdown
Contributor

Closes #193840

What Problem This Solves

Fixes: config reads, writes and reloads on multi-agent Gateways block the event loop on filesystem work that grows with agent count.

User Impact

User impact: multi-agent Gateways spend less sync I/O on every config snapshot read (config.get, config writes, reloads and startup); the measured paths are the config.get cache miss and the watcher's re-read. At 32 agents each config snapshot read makes 192 fewer lstat, up to 96 fewer stat and 64 fewer readdir calls. Duplicate agent directory detection reports the same collisions as before. There is no config or behavior change.

Why This Change Was Made

Case folding can only merge two directories whose resolved paths are equal ignoring case. findDuplicateAgentDirs now resolves all agent directories first and runs isPathCaseInsensitive only for agents whose lowercased path matches another agent's. Every other agent keeps its resolved path as its key, and no folded key can equal that key, so the reported collision groups and their order are unchanged. Candidates still get the same per-path probe as before, which keeps the case-sensitive volume fix from #105402 intact.

This removes the probe calls instead of caching them, so there is no new cache key to invalidate. I considered a per-volume memo and rejected it. Case sensitivity can differ between directories on the same device (Linux casefold, Windows per-directory case sensitivity), so a dev key could change answers.

Evidence

Isolated Gateway, config.get through the shipped CLI

Separate pnpm builds of base 14d9d554 and this change, on the same Mac Studio (APFS, case-insensitive). Each run starts its own openclaw gateway run with a temporary HOME, state dir and config, a loopback port and auth: none. It is not the live Gateway. The config has 32 agents with distinct existing agentDirs and gateway.reload.mode: "off". A preload hook (NODE_OPTIONS=--import fs-count.mjs) counts sync fs calls in every thread of the Gateway process. The CLI processes are not counted. Each sample is one openclaw gateway call config.get --port <port> --json.

config.get caches its response per config revision while the config watcher is live, and the watcher stays live with reload.mode: "off". A repeated call on an unchanged file is therefore a cache hit. Each repeated sample is an edit cycle instead: rewrite the config (rename agent a0), wait 1.5 s, then call config.get. Every call returned the edited name, so each one was a cache miss.

Four rounds in the order base, fix, base, fix, 10 edit cycles per run. Mean sync fs calls in the Gateway process:

Sample lstat readdir stat
config.get after an edit (cache miss) 514.0 to 515.0 -> 322.3 to 323.1 64.0 to 64.1 -> 0 to 0.1 5 to 5.4 -> 5
First config.get after start 514 to 522 -> 322 64 -> 0 5 to 7 -> 5 to 7
Watcher work after each edit (it re-reads the config) 973 to 986 -> 779 to 793 65 -> 1 71 -> 71
Cached config.get (5 calls) 2.8 to 7.6 -> 2.8 to 4.4 0 -> 0 0 to 0.4 -> 0 to 0.4
Idle control, 1.9 s windows 0 to 2.3 -> 0 to 1.3 0 -> 0 0 to 0.7 -> 0.7

Each cache miss loses 192 lstat and 64 readdir, and so does the watcher's re-read after each edit. These are the same per-read deltas that probe.mjs in the linked issue measures for existing directories. Per-call lstat was 514 to 518 on base and 322 to 326 on the fix in every sample. The remaining lstat calls come from path prefix resolution, which symlink alias detection still needs. Background timers add up to about 40 existsSync calls in some windows on both builds, including idle ones, so they are left out of the table.

One fix run (round 2) stopped at the harness self-check config.get missed the edit: the watcher had not seen the edit within 1.5 s while another job loaded the host. Round 4 replaces it. All other runs completed. Not measured: reload.mode: "hybrid" (a hot reload mixes reload work into each sample, so off keeps samples comparable) and a Linux or case-sensitive volume end to end (the agent-dirs.fs-identity.test.ts case-sensitive arm covers that branch).

Genuine aliases are still rejected

In the same Gateway runs, the config was then rewritten to the 32 agents plus one alias pair, and config.get and openclaw config validate were run. The output is byte-identical between base and fix in every completed round:

-- missing case-variant alias (Future vs future, neither exists): config.get valid=false
   issue agents.entries: Duplicate agentDir detected (multi-agent config). | - <tmp>/agents/Future: "future", "future2"
   openclaw config validate: exit 1; Duplicate agentDir detected (multi-agent config). | - <tmp>/agents/Future: "future", "future2"
-- existing case-variant alias (Team exists, team configured): config.get valid=false
   issue agents.entries: Duplicate agentDir detected (multi-agent config). | - <tmp>/agents/Team: "upper", "lower"
   openclaw config validate: exit 1; Duplicate agentDir detected (multi-agent config). | - <tmp>/agents/Team: "upper", "lower"
-- symlink alias (real vs link): config.get valid=false
   issue agents.entries: Duplicate agentDir detected (multi-agent config). | - <tmp>/agents/real: "real", "link"
   openclaw config validate: exit 1; Duplicate agentDir detected (multi-agent config). | - <tmp>/agents/real: "real", "link"

Only the first and conflict lines of each message are shown. The rest is the fixed help text. <tmp> is the run's temporary directory.

One full run per build (redacted)
### run 4 base (14d9d554f7d, agent-dirs.ts blob 644aed9ab98)
== base: node v24.22.2, darwin arm64, reload.mode=off, 32 agents, N=10
gateway ready (health ok)
settled: quiet 2 s window, gateway sync fs calls: {"lstatSync":4}
config.get cold (first after start): valid=true, agents.entries=32, fs {"lstatSync":522,"statSync":5,"readdirSync":64,"realpathSync":88,"openSync":4,"readFileSync":5}
config.get warm cache hits x5, mean fs: {"lstatSync":2.8,"statSync":0.4,"realpathSync":1.4,"openSync":0.2,"readFileSync":0.6}
edit cycles x10: watcher work after each edit, mean fs: {"lstatSync":985.4,"statSync":71.4,"readdirSync":65,"realpathSync":1.2,"openSync":1.1,"readFileSync":27.3,"existsSync":42.1}
edit cycles x10: config.get after each edit (cache miss, saw the edit), mean fs: {"lstatSync":514.3,"statSync":5,"readdirSync":64.1,"realpathSync":6.1,"readFileSync":1.5,"openSync":0.5}
  lstat per config.get, in order: [514,514,514,517,514,514,514,514,514,514]
idle control 1.9 s windows x3, mean fs: {"existsSync":40.3,"statSync":0.7,"readFileSync":0.3}
-- missing case-variant alias (Future vs future, neither exists): config.get valid=false
   issue agents.entries: Duplicate agentDir detected (multi-agent config). | - <tmp>/agents/Future: "future", "future2"
   openclaw config validate: exit 1; Duplicate agentDir detected (multi-agent config). | - <tmp>/agents/Future: "future", "future2"
-- existing case-variant alias (Team exists, team configured): config.get valid=false
   issue agents.entries: Duplicate agentDir detected (multi-agent config). | - <tmp>/agents/Team: "upper", "lower"
   openclaw config validate: exit 1; Duplicate agentDir detected (multi-agent config). | - <tmp>/agents/Team: "upper", "lower"
-- symlink alias (real vs link): config.get valid=false
   issue agents.entries: Duplicate agentDir detected (multi-agent config). | - <tmp>/agents/real: "real", "link"
   openclaw config validate: exit 1; Duplicate agentDir detected (multi-agent config). | - <tmp>/agents/real: "real", "link"
exit 0
### run 4 fix (this branch, agent-dirs.ts blob 566a21c776f)
== fix: node v24.22.2, darwin arm64, reload.mode=off, 32 agents, N=10
gateway ready (health ok)
settled: quiet 2 s window, gateway sync fs calls: {"lstatSync":8}
config.get cold (first after start): valid=true, agents.entries=32, fs {"lstatSync":322,"statSync":5,"realpathSync":88,"openSync":4,"readFileSync":5}
config.get warm cache hits x5, mean fs: {"lstatSync":2.8,"realpathSync":1.4,"openSync":0.2,"readFileSync":0.6,"statSync":0.4}
edit cycles x10: watcher work after each edit, mean fs: {"lstatSync":792.9,"statSync":71.4,"readdirSync":1.1,"realpathSync":3.3,"openSync":1.6,"readFileSync":27.8,"existsSync":30}
edit cycles x10: config.get after each edit (cache miss, saw the edit), mean fs: {"lstatSync":322.8,"statSync":5,"realpathSync":4,"readFileSync":1,"existsSync":12.1}
  lstat per config.get, in order: [322,326,322,322,322,322,326,322,322,322]
idle control 1.9 s windows x3, mean fs: {"statSync":0.7,"readFileSync":0.3}
-- missing case-variant alias (Future vs future, neither exists): config.get valid=false
   issue agents.entries: Duplicate agentDir detected (multi-agent config). | - <tmp>/agents/Future: "future", "future2"
   openclaw config validate: exit 1; Duplicate agentDir detected (multi-agent config). | - <tmp>/agents/Future: "future", "future2"
-- existing case-variant alias (Team exists, team configured): config.get valid=false
   issue agents.entries: Duplicate agentDir detected (multi-agent config). | - <tmp>/agents/Team: "upper", "lower"
   openclaw config validate: exit 1; Duplicate agentDir detected (multi-agent config). | - <tmp>/agents/Team: "upper", "lower"
-- symlink alias (real vs link): config.get valid=false
   issue agents.entries: Duplicate agentDir detected (multi-agent config). | - <tmp>/agents/real: "real", "link"
   openclaw config validate: exit 1; Duplicate agentDir detected (multi-agent config). | - <tmp>/agents/real: "real", "link"
exit 0
Commands and scripts
# Build both trees (base = merge base 14d9d554, fix = this branch)
git worktree add ../base 14d9d554f7d04b0c036c543ff2c2b4592faf958c
(cd ../base && pnpm install --frozen-lockfile && pnpm build)
pnpm install --frozen-lockfile && pnpm build

# Save fs-count.mjs and e2e-gateway.mjs (below) in one directory outside both checkouts, then:
for r in 1 2 3 4; do
  node /path/to/e2e-gateway.mjs /path/to/base base 10
  node /path/to/e2e-gateway.mjs /path/to/fix fix 10
done

The ### run N ... headers and trailing exit 0 lines in the log above come from a small wrapper around this loop that echoes the run label and exit status.

fs-count.mjs:

// Preload hook: counts sync fs calls in this process.
// Usage: NODE_OPTIONS="--import /abs/path/fs-count.mjs" FS_COUNT_DIR=/abs/dir <command>
// Every 200 ms each thread writes <FS_COUNT_DIR>/<pid>-<threadId>.json = { argv, counts } (written atomically; its own writes are not counted).
import fs from "node:fs";
import { syncBuiltinESMExports } from "node:module";
import path from "node:path";
import { threadId } from "node:worker_threads";

const dir = process.env.FS_COUNT_DIR;
if (dir) {
  const names = ["lstatSync", "statSync", "readdirSync", "realpathSync", "openSync", "readFileSync", "existsSync", "mkdirSync", "rmdirSync", "rmSync"];
  const counts = Object.fromEntries(names.map((n) => [n, 0]));
  let paused = false;
  for (const name of names) {
    const orig = fs[name];
    const wrapped = function (...args) {
      if (!paused) counts[name] += 1;
      return orig.apply(this, args);
    };
    if (orig.native) wrapped.native = orig.native;
    fs[name] = wrapped;
  }
  syncBuiltinESMExports();
  const file = path.join(dir, `${process.pid}-${threadId}.json`);
  const flush = () => {
    paused = true;
    try {
      fs.writeFileSync(`${file}.tmp`, JSON.stringify({ argv: process.argv.slice(1), counts }));
      fs.renameSync(`${file}.tmp`, file);
    } finally {
      paused = false;
    }
  };
  setInterval(flush, 200).unref();
  process.on("exit", flush);
}

e2e-gateway.mjs:

// Isolated-Gateway proof for findDuplicateAgentDirs probe work.
// Usage: node e2e-gateway.mjs <built-openclaw-checkout> <label> [N=10]
// Env: RELOAD=off|hybrid (default off), PORT (default 19431).
// Starts `openclaw gateway run` from <checkout>/dist/entry.js with its own temp HOME,
// state dir, config and loopback port (never the live Gateway), preloading fs-count.mjs.
// Then: (1) 32 agents with distinct existing agentDirs: one cold `gateway call config.get`,
// 5 warm (cached) calls, and N edit cycles (rewrite the config, wait 1.5 s, config.get),
// counting sync fs calls in all threads of the Gateway process; (2) with reload.mode=off,
// rewrites the config with a genuine alias pair (missing case variants, existing case
// variants, symlink) and prints config.get validity + issues and `openclaw config validate`.
import { spawn, spawnSync } from "node:child_process";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { fileURLToPath } from "node:url";

const repo = path.resolve(process.argv[2]);
const label = process.argv[3] ?? "run";
const N = Number(process.argv[4] ?? 10);
const reload = process.env.RELOAD ?? "off";
const port = Number(process.env.PORT ?? 19431);
const hook = path.join(path.dirname(fileURLToPath(import.meta.url)), "fs-count.mjs");
const entry = path.join(repo, "dist/entry.js");

const root = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), "oc-f1-e2e-")));
const home = path.join(root, "home");
const state = path.join(home, ".openclaw");
const countDir = path.join(root, "fs-counts");
const configPath = path.join(state, "openclaw.json");
const agentsRoot = path.join(root, "agents");
for (const d of [state, countDir, agentsRoot]) fs.mkdirSync(d, { recursive: true });

const redact = (s) =>
  String(s).replaceAll(root, "<tmp>").replaceAll(os.homedir(), "~").replaceAll(String(port), "<port>");
const log = (...a) => console.log(redact(a.join(" ")));

const ids = Array.from({ length: 32 }, (_, i) => `a${i}`);
for (const id of ids) fs.mkdirSync(path.join(agentsRoot, id, "agent"), { recursive: true });
const distinctEntries = Object.fromEntries(
  ids.map((id) => [id, { name: id, agentDir: path.join(agentsRoot, id, "agent") }]),
);
const writeConfig = (entries) =>
  fs.writeFileSync(
    configPath,
    `${JSON.stringify(
      {
        browser: { enabled: false },
        update: { checkOnStart: false },
        discovery: { mdns: { mode: "off" } },
        gateway: {
          mode: "local",
          bind: "loopback",
          port,
          auth: { mode: "none" },
          controlUi: { enabled: false },
          tailscale: { mode: "off" },
          reload: { mode: reload },
        },
        agents: { ownership: "explicit", entries },
      },
      null,
      2,
    )}\n`,
  );
writeConfig(distinctEntries);

const baseEnv = {
  PATH: process.env.PATH,
  HOME: home,
  TMPDIR: path.join(root, "tmp"),
  OPENCLAW_STATE_DIR: state,
  OPENCLAW_CONFIG_PATH: configPath,
  OPENCLAW_SKIP_CHANNELS: "1",
};
fs.mkdirSync(baseEnv.TMPDIR, { recursive: true });

const cli = (args) =>
  spawnSync(process.execPath, [entry, ...args], { env: baseEnv, encoding: "utf8", timeout: 60_000 });
const callConfigGet = () => {
  const r = cli(["gateway", "call", "config.get", "--port", String(port), "--json", "--timeout", "30000"]);
  if (r.status !== 0) throw new Error(`config.get exit ${r.status}: ${redact(r.stderr).slice(0, 600)}`);
  return JSON.parse(r.stdout.slice(r.stdout.indexOf("{")));
};
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
// Sums all threads (main + workers) of the spawned Gateway process.
const gatewayCounts = () => {
  const counts = {};
  let threads = 0;
  for (const f of fs.readdirSync(countDir)) {
    if (!f.startsWith(`${gw.pid}-`) || !f.endsWith(".json")) continue;
    threads += 1;
    const data = JSON.parse(fs.readFileSync(path.join(countDir, f), "utf8"));
    for (const [k, v] of Object.entries(data.counts)) counts[k] = (counts[k] ?? 0) + v;
  }
  if (!threads) throw new Error(`no fs-count file for gateway pid; files: ${fs.readdirSync(countDir).length}`);
  return { threads, counts };
};
const diff = (a, b, per = 1) =>
  Object.fromEntries(
    Object.keys(b.counts)
      .map((k) => [k, +((b.counts[k] - (a.counts[k] ?? 0)) / per).toFixed(1)])
      .filter(([, v]) => v !== 0),
  );

const gw = spawn(
  process.execPath,
  [entry, "gateway", "run", "--port", String(port), "--bind", "loopback", "--auth", "none", "--tailscale", "off", "--allow-unconfigured"],
  { env: { ...baseEnv, NODE_OPTIONS: `--import ${hook}`, FS_COUNT_DIR: countDir }, stdio: ["ignore", "pipe", "pipe"] },
);
let gwOut = "";
gw.stdout.on("data", (d) => (gwOut += d));
gw.stderr.on("data", (d) => (gwOut += d));

try {
  log(`== ${label}: node ${process.version}, ${os.platform()} ${os.arch()}, reload.mode=${reload}, ${ids.length} agents, N=${N}`);
  let ready = false;
  for (let i = 0; i < 90 && !ready; i++) {
    if (gw.exitCode !== null) throw new Error(`gateway exited ${gw.exitCode}: ${redact(gwOut).slice(-1500)}`);
    ready = cli(["gateway", "call", "health", "--port", String(port), "--json", "--timeout", "3000"]).status === 0;
    if (!ready) await sleep(1000);
  }
  if (!ready) throw new Error(`gateway not ready: ${redact(gwOut).slice(-1500)}`);
  log("gateway ready (health ok)");
  // Startup work continues after health is ok; wait for a quiet 2 s window.
  const total = (d) => Object.values(d).reduce((a, b) => a + b, 0);
  let quiet;
  for (let i = 0, prev = gatewayCounts(); i < 60; i++) {
    await sleep(2000);
    const cur = gatewayCounts();
    quiet = diff(prev, cur);
    prev = cur;
    if (total(quiet) < 50) break;
  }
  log(`settled: quiet 2 s window, gateway sync fs calls: ${JSON.stringify(quiet)}`);

  // config.get is cached per watcher-owned config revision, so measure a cold
  // miss, warm hits, and N edit cycles (rewrite config, then config.get).
  const sample = async (fn) => {
    const before = gatewayCounts();
    const res = await fn();
    await sleep(400);
    return { res, d: diff(before, gatewayCounts()) };
  };
  const mean = (ds) => {
    const out = {};
    for (const d of ds) for (const [k, v] of Object.entries(d)) out[k] = (out[k] ?? 0) + v / ds.length;
    return Object.fromEntries(Object.entries(out).map(([k, v]) => [k, +v.toFixed(1)]));
  };
  const lstats = (ds) => JSON.stringify(ds.map((d) => d.lstatSync ?? 0));
  const getValid = () => {
    const res = callConfigGet();
    if (res.valid !== true) throw new Error(`distinct config not valid: ${JSON.stringify(res.issues)}`);
    return res;
  };

  const cold = await sample(getValid);
  log(`config.get cold (first after start): valid=${cold.res.valid}, agents.entries=${Object.keys(cold.res.config?.agents?.entries ?? {}).length}, fs ${JSON.stringify(cold.d)}`);
  const warm = [];
  for (let i = 0; i < 5; i++) warm.push((await sample(getValid)).d);
  log(`config.get warm cache hits x5, mean fs: ${JSON.stringify(mean(warm))}`);

  const watch = [];
  const calls = [];
  for (let i = 0; i < N; i++) {
    const w = await sample(async () => {
      writeConfig({ ...distinctEntries, a0: { ...distinctEntries.a0, name: `a0 edit ${i}` } });
      await sleep(1500);
    });
    watch.push(w.d);
    const c = await sample(getValid);
    if (c.res.config?.agents?.entries?.a0?.name !== `a0 edit ${i}`) throw new Error("config.get missed the edit");
    calls.push(c.d);
  }
  log(`edit cycles x${N}: watcher work after each edit, mean fs: ${JSON.stringify(mean(watch))}`);
  log(`edit cycles x${N}: config.get after each edit (cache miss, saw the edit), mean fs: ${JSON.stringify(mean(calls))}`);
  log(`  lstat per config.get, in order: ${lstats(calls)}`);
  const idle = [];
  for (let i = 0; i < 3; i++) idle.push((await sample(() => sleep(1500))).d);
  log(`idle control 1.9 s windows x3, mean fs: ${JSON.stringify(mean(idle))}`);

  if (reload === "off") {
    // Genuine aliases on a case-insensitive volume: missing and existing case variants, and a symlink.
    fs.mkdirSync(path.join(agentsRoot, "Team"), { recursive: true });
    fs.mkdirSync(path.join(agentsRoot, "real"), { recursive: true });
    fs.symlinkSync(path.join(agentsRoot, "real"), path.join(agentsRoot, "link"));
    const cases = {
      "missing case-variant alias (Future vs future, neither exists)": { future: { agentDir: path.join(agentsRoot, "Future") }, future2: { agentDir: path.join(agentsRoot, "future") } },
      "existing case-variant alias (Team exists, team configured)": { upper: { agentDir: path.join(agentsRoot, "Team") }, lower: { agentDir: path.join(agentsRoot, "team") } },
      "symlink alias (real vs link)": { real: { agentDir: path.join(agentsRoot, "real") }, link: { agentDir: path.join(agentsRoot, "link") } },
    };
    for (const [name, extra] of Object.entries(cases)) {
      writeConfig({ ...distinctEntries, ...extra });
      const res = callConfigGet();
      log(`-- ${name}: config.get valid=${res.valid}`);
      // First line of each issue plus its conflict lines; the rest is fixed help text.
      const brief = (m) => [m.split("\n")[0], ...m.split("\n").filter((l) => l.startsWith("- "))].join(" | ");
      for (const issue of res.issues ?? []) log(`   issue ${issue.path}: ${brief(issue.message)}`);
      const v = cli(["config", "validate"]);
      const out = `${v.stdout}${v.stderr}`.replaceAll("\\n", "\n");
      log(`   openclaw config validate: exit ${v.status}; ${brief(out.slice(out.indexOf("Duplicate agentDir")))}`);
    }
    writeConfig(distinctEntries);
  }
} finally {
  gw.kill("SIGTERM");
  for (let i = 0; i < 40 && gw.exitCode === null; i++) await sleep(250);
  if (gw.exitCode === null) gw.kill("SIGKILL");
  fs.rmSync(root, { recursive: true, force: true });
}

In-process counts per readConfigFileSnapshot

Earlier pnpm builds of ee00ba6b and this change on ee00ba6b were measured with probe.mjs from the linked issue (60 reads per run, base, fix, base, fix). src/config/agent-dirs.ts is identical in ee00ba6b and 14d9d554. This also covers missing directories, where each probe adds 3 stat calls:

Agents Agent dirs lstat stat readdir
2 missing 34 -> 22 6 -> 0 4 -> 0
8 missing 136 -> 88 24 -> 0 16 -> 0
32 missing 544 -> 352 96 -> 0 64 -> 0
2 existing 38 -> 26 0 -> 0 4 -> 0
8 existing 152 -> 104 0 -> 0 16 -> 0
32 existing 608 -> 416 0 -> 0 64 -> 0

Tests

  • The mock-driven probe-selection cases in src/config/agent-dirs.test.ts are removed. That file is unchanged from base, and the test-line allocation file is gone.
  • src/config/agent-dirs.fs-identity.test.ts: the existing "missing directories" test now also asserts the result. Missing case variants (FutureState, futurestate) are reported as one directory exactly when the volume is case-insensitive (detected with a real mkdir and stat), and kept apart otherwise. It still checks that nothing is created or left behind. This is the only path where the fix's candidate filter decides the result. Existing case variants already resolve to their on-disk spelling, so they collide without folding. Mutation check: with folding disabled (false ? folded : resolved) the test is red on APFS (expected [] to deeply equal [ { …(2) } ]). With the fix it is green.
  • pnpm test src/config/agent-dirs.test.ts src/config/agent-dirs.fs-identity.test.ts --maxWorkers=1: 2 files, 9 passed, 31.3 s wall. The changed file alone: 5 passed, 8.1 s wall (vitest 5.3 s).
  • Test lines: net +8. check-test-lines-ratchet.mts --base origin/main: OK, slack 21, no allocation. check-max-lines-ratchet.mts --base origin/main: OK. The baseline is unchanged.

pnpm check:changed: exit 1, 414 s. 33 of 35 lanes pass, including typecheck core and core tests, lint, format, import cycles and the line-cap ratchet.

Pre-existing gate failures (in files this PR does not touch; both fail the same way on base 14d9d554):

  • changelog attributions: 26 "Thanks @steipete" lines in CHANGELOG/records/2026.11.1.md. scripts/check-changelog-attributions.mts exits 1 on base.
  • dead export scan: unused setSourceConfig in src/gateway/talk/handlers/catalog.test-support.ts. pnpm deadcode:exports exits 1 on base.

@clawsweeper

clawsweeper Bot commented Nov 6, 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.

@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. P2 Normal backlog priority with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. labels Nov 6, 2026
@clawsweeper

clawsweeper Bot commented Nov 6, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR limits filesystem case probes to resolved agent directories that share a normalized lowercase path.

Example: An isolated macOS Gateway reads configuration for 32 agents with distinct existing directories.

  • Before: A config.get cache miss performs about 514 lstat calls and 64 readdir calls.
  • After: The supplied trace shows about 322 lstat calls and zero readdir calls, with genuine aliases still rejected.

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) Focused, useful optimization with sufficient shipped-entry-point evidence and no introduced finding; hosted build/test CI has not yet run.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (logs): The updated PR body resolves the previous proof gap with isolated macOS APFS Gateway runs through the built CLI: distinct 32-agent config.get cache misses and watcher rereads lose the expected filesystem calls, while missing case aliases, existing aliases, and symlinks retain matching rejection output.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Performance · Worth it: Yes · Fix scope: Complete
User problem: Multi-agent Gateways perform unnecessary synchronous filesystem work during configuration reads.
Reason: The measured reduction addresses a shared hot path without changing configuration, defaults, collision results, or dependency ownership.

Merge readiness

✅ Ready for maintainer review

Keep open: this PR removes demonstrated filesystem work while preserving directory-collision detection; no actionable introduced defect was found.

Priority: P2
Reviewed head: 3dcd2ced09cb3f733f40b16374e37470cafc615a

Before merge

None.

Findings

None.

Agent review details

How this fits together

Configuration loading and validation pass agent directories to the shared collision detector, which resolves filesystem identities and returns conflicting agent groups.

flowchart TD
  A[CLI config.get] --> B[Gateway config snapshot]
  B --> C[Configuration validation]
  C --> D[Resolve agent directory identities]
  D --> E[Group lowercase candidates]
  E --> F[Probe candidate case semantics]
  F --> G[Report duplicate directories]
Loading

Technical review

Best possible solution:

Retain the focused candidate filter in the existing collision detector and complete normal ready-for-review CI before landing.

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

Current-main source unconditionally probes every multi-agent directory, and contributor-supplied base Gateway traces demonstrate the cost; no target code was executed during this read-only review.

Is this the best way to solve the issue?

The smallest complete fix selects possible collisions inside the existing owner, preserves path resolution and per-candidate probes, and introduces no persistent cache or competing policy.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Filesystem identity and case-sensitive volume handling keeps the original intent (927070b: Accept distinct directories on case-sensitive volumes while rejecting case and symlink aliases.)
  • Shared filesystem prefix resolution keeps the original intent (f06ffe2: Replace duplicate filesystem traversal with released fs-safe primitives, including dangling-link handling.)
  • Avoiding unnecessary directory validation work keeps the original intent (87e2cfb: Skip directory collision work when fewer than two distinct agents exist.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

  • Pinned introduced change: The introduced diff retains prefix resolution and existing collision grouping, adding only per-invocation candidate selection before case probing. (src/config/agent-dirs.ts:68, 3dcd2ced09cb)
  • Current main still performs redundant probes: Current main unconditionally probes each resolved directory in multi-agent configurations; both touched files match the merge-base versions. (src/config/agent-dirs.ts:33, bc47d05a49fb)
  • Updated shipped-entry-point proof: The full PR body supplies base/candidate isolated-Gateway logs, cold and cached config.get samples, edit-triggered cache misses, watcher counts, and matching CLI rejection of missing case variants, existing case aliases, and symlinks; the candidate source blob matches the reviewed diff. (3dcd2ced09cb)
  • Original filesystem contract: Merged fix(config): respect agent directory filesystem case #105402 deliberately preserved case-distinct directories on sensitive volumes and rejected true aliases; this PR retains that decision and strengthens the existing missing-directory assertion. (src/config/agent-dirs.fs-identity.test.ts:60, 927070b91094)
  • Direct dependency contract: OpenClaw directly imports resolvePathPrefixSync and uses probePathCaseInsensitiveSync through its adapter, establishing the dependency-policy signal. Version 0.27.1 documents canonical existing prefixes, dangling-link suffixes, path-local case observations, and no probe cache; its policy was read and these contracts remain intact. (docs/path-prefix.md:3, ea225ba262cf)
  • Draft and CI state: GitHub reports the reviewed head as draft and cleanly mergeable; its main CI workflow was skipped, so hosted build/test coverage is not established and no diff-caused CI failure is shown. (3dcd2ced09cb)

PR surface

Source +11, Tests +8. Total +19 across 2 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 1 18 7 +11
Tests 1 14 6 +8
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 2 32 13 +19

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.

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #193840
Summary: The linked issue documents the same unconditional per-agent probing that this PR removes.

Members:

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

Labels

Label changes:

  • add proof: sufficient: Contributor real behavior proof is sufficient.
  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • remove rating: 🦐 gold shrimp: Current PR rating is rating: 🐚 platinum hermit, so this older rating label is no longer current.
  • remove status: 📣 needs proof: Current PR status label is status: 👀 ready for maintainer look.

Label justifications:

  • P2: Measured synchronous filesystem overhead affects multi-agent configuration reads with limited per-read impact.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • 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-06T01:16:56.948Z sha 801209630d71eb5fdd572001358eec9ca4daad4f :: needs real behavior proof before merge. :: none

Reviewed November 5, 2026, 9:31 PM ET / November 6, 2026, 02:31 UTC (Revision 2).

findDuplicateAgentDirs ran a sync filesystem case probe for every agent
on every config snapshot read. Case folding can only merge paths that
are equal ignoring case, so the probe now runs only for agents whose
resolved directory matches another agent's when lowercased. The set of
reported collisions is unchanged.

At 32 agents this removes 192 lstat, 96 stat and 64 readdir calls per
readConfigFileSnapshot with missing agent directories. In an isolated
Gateway with 32 existing agent directories, each config.get that misses
the response cache drops from 514 lstat and 64 readdir to 322 lstat and
0 readdir.

The fs identity test now asserts that missing case variants are reported
as one directory exactly when the volume is case-insensitive, the only
case where the probe decides the result.
@etzelm
etzelm force-pushed the improve/agent-dir-case-probe-candidates branch from 8012096 to 3dcd2ce Compare November 6, 2026 02:26
@etzelm

etzelm commented Nov 6, 2026

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Nov 6, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Nov 6, 2026
@etzelm
etzelm marked this pull request as ready for review November 6, 2026 03:05
@roboclaw-bot roboclaw-bot added the clawtributors PR from a clawtributor label Nov 6, 2026
@vyctorbrzezowski
vyctorbrzezowski merged commit b299821 into openclaw:main Nov 9, 2026
212 of 216 checks passed
@vyctorbrzezowski

vyctorbrzezowski commented Nov 9, 2026 •

Copy link
Copy Markdown
Member

Merged via squash.

Thanks, @etzelm, for removing unnecessary case-sensitivity probes while preserving agent-directory collision checks.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 10, 2026
…nclaw#193841)

Group resolved agent directory paths by their lowercase form before checking filesystem case sensitivity. Only potential collision groups run the existing per-path probe, while alias resolution and collision ordering remain unchanged.

Strengthen the existing filesystem-identity test for missing case variants and probe cleanup.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

clawtributors PR from a clawtributor P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: XS 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.

[Bug]: Config snapshot reads run a sync filesystem case probe for every agent

3 participants