Skip to content

Commit 2296f3f

Browse files
committed
fix(agents): preserve workspace ownership across path aliases
1 parent 4eea0d3 commit 2296f3f

7 files changed

Lines changed: 136 additions & 73 deletions

File tree

‎src/agents/agent-delete-safety.test.ts‎

Lines changed: 32 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
1+
import fs from "node:fs";
12
import os from "node:os";
23
import path from "node:path";
34
import { describe, expect, it } from "vitest";
4-
import { isSharedAuthStoreOwner } from "./agent-delete-safety.js";
5+
import type { OpenClawConfig } from "../config/types.openclaw.js";
6+
import { findOverlappingWorkspaceAgentIds, isSharedAuthStoreOwner } from "./agent-delete-safety.js";
57

68
describe("shared auth store deletion safety", () => {
79
const sharedAuthDbPath = path.join(os.tmpdir(), "shared-auth", "openclaw-agent.sqlite");
@@ -30,3 +32,32 @@ describe("shared auth store deletion safety", () => {
3032
expect(isSharedAuthStoreOwner({ ownership, agentAuthDbPath, sharedAuthDbPath })).toBe(expected);
3133
});
3234
});
35+
36+
describe("shared workspace deletion safety", () => {
37+
it("detects another agent behind a dangling workspace symlink", () => {
38+
const rootDir = fs.mkdtempSync(path.join(os.tmpdir(), "openclaw-agent-delete-alias-"));
39+
const workspaceDir = path.join(rootDir, "vanished-workspace");
40+
const workspaceAliasDir = path.join(rootDir, "workspace-alias");
41+
try {
42+
fs.symlinkSync(
43+
workspaceDir,
44+
workspaceAliasDir,
45+
process.platform === "win32" ? "junction" : "dir",
46+
);
47+
const config: OpenClawConfig = {
48+
agents: {
49+
list: [
50+
{ id: "alpha", workspace: workspaceAliasDir },
51+
{ id: "beta", workspace: workspaceDir },
52+
],
53+
},
54+
};
55+
56+
expect(findOverlappingWorkspaceAgentIds(config, "alpha", workspaceAliasDir)).toEqual([
57+
"beta",
58+
]);
59+
} finally {
60+
fs.rmSync(rootDir, { recursive: true, force: true });
61+
}
62+
});
63+
});

‎src/agents/agent-delete-safety.ts‎

Lines changed: 3 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,11 @@
11
/** Safety checks for deleting agents whose workspaces may overlap other agents. */
2-
import fs from "node:fs";
3-
import path from "node:path";
4-
import { lowercasePreservingWhitespace } from "@openclaw/normalization-core/string-coerce";
52
import type { OpenClawConfig } from "../config/types.openclaw.js";
63
import { isPathInside } from "../infra/path-guards.js";
74
import { normalizeAgentId } from "../routing/session-key.js";
85
import { isSameOpenClawAgentDatabasePath } from "../state/openclaw-agent-db-registry.js";
96
import { listAgentEntries, resolveAgentWorkspaceDir } from "./agent-scope.js";
107
import type { SharedAuthStoreOwnership } from "./auth-profiles/path-resolve.js";
8+
import { resolveCanonicalWorkspacePath } from "./workspace-state-identity.js";
119

1210
/** True when deleting this agent database would remove the legacy shared auth store. */
1311
export function isSharedAuthStoreOwner(params: {
@@ -25,23 +23,9 @@ export function formatSharedAuthStoreOwnerDeleteError(agentId: string): string {
2523
return `Agent "${agentId}" owns the legacy shared auth store and cannot be deleted. Run openclaw doctor --fix to migrate shared auth, then retry.`;
2624
}
2725

28-
function normalizeWorkspacePathForComparison(input: string): string {
29-
const resolved = path.resolve(input.replaceAll("\0", ""));
30-
let normalized = resolved;
31-
try {
32-
normalized = fs.realpathSync.native(resolved);
33-
} catch {
34-
// Keep lexical path for non-existent directories.
35-
}
36-
if (process.platform === "win32") {
37-
return lowercasePreservingWhitespace(normalized);
38-
}
39-
return normalized;
40-
}
41-
4226
function workspacePathsOverlap(left: string, right: string): boolean {
43-
const normalizedLeft = normalizeWorkspacePathForComparison(left);
44-
const normalizedRight = normalizeWorkspacePathForComparison(right);
27+
const normalizedLeft = resolveCanonicalWorkspacePath(left.replaceAll("\0", ""));
28+
const normalizedRight = resolveCanonicalWorkspacePath(right.replaceAll("\0", ""));
4529
return (
4630
isPathInside(normalizedRight, normalizedLeft) || isPathInside(normalizedLeft, normalizedRight)
4731
);

‎src/agents/agent-scope.test.ts‎

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import { describe, expect, it } from "vitest";
66
import type { OpenClawConfig } from "../config/config.js";
77
import type { SessionEntry } from "../config/sessions.js";
88
import { withEnv } from "../test-utils/env.js";
9+
import { findOverlappingWorkspaceAgentIds } from "./agent-delete-safety.js";
910
import {
1011
clearAutoFallbackPrimaryProbeSelection,
1112
hasLegacyAutoFallbackWithoutOrigin,
@@ -1128,6 +1129,34 @@ describe("resolveAgentConfig", () => {
11281129
});
11291130

11301131
describe("resolveAgentIdByWorkspacePath", () => {
1132+
it.runIf(process.platform === "linux")(
1133+
"keeps distinct Unicode workspace directories under their own agents",
1134+
() => {
1135+
const root = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), "workspace-unicode-")));
1136+
const composed = path.join(root, "caf\u00e9");
1137+
const decomposed = path.join(root, "cafe\u0301");
1138+
try {
1139+
fs.mkdirSync(composed);
1140+
fs.mkdirSync(decomposed);
1141+
const cfg: OpenClawConfig = {
1142+
agents: {
1143+
entries: {
1144+
composed: { workspace: composed },
1145+
decomposed: { workspace: decomposed },
1146+
},
1147+
},
1148+
};
1149+
1150+
expect(fs.statSync(composed).ino).not.toBe(fs.statSync(decomposed).ino);
1151+
expect(resolveAgentIdByWorkspacePath(cfg, composed)).toBe("composed");
1152+
expect(resolveAgentIdByWorkspacePath(cfg, decomposed)).toBe("decomposed");
1153+
expect(findOverlappingWorkspaceAgentIds(cfg, "composed", composed)).toEqual([]);
1154+
} finally {
1155+
fs.rmSync(root, { recursive: true, force: true });
1156+
}
1157+
},
1158+
);
1159+
11311160
it("returns the most specific workspace match for a directory", () => {
11321161
const workspaceRoot = `/tmp/openclaw-agent-scope-${Date.now()}-root`;
11331162
const opsWorkspace = `${workspaceRoot}/projects/ops`;
@@ -1192,6 +1221,40 @@ describe("resolveAgentIdByWorkspacePath", () => {
11921221
fs.rmSync(tempRoot, { recursive: true, force: true });
11931222
}
11941223
});
1224+
1225+
it("matches a dangling workspace symlink to its vanished target", () => {
1226+
const tempRoot = fs.mkdtempSync(path.join(os.tmpdir(), "openclaw-agent-scope-dangling-"));
1227+
const workspaceDir = path.join(tempRoot, "vanished-workspace");
1228+
const workspaceAliasDir = path.join(tempRoot, "workspace-alias");
1229+
try {
1230+
fs.symlinkSync(
1231+
workspaceDir,
1232+
workspaceAliasDir,
1233+
process.platform === "win32" ? "junction" : "dir",
1234+
);
1235+
const cfg: OpenClawConfig = {
1236+
agents: { list: [{ id: "ops", workspace: workspaceAliasDir }] },
1237+
};
1238+
1239+
expect(resolveAgentIdByWorkspacePath(cfg, workspaceDir)).toBe("ops");
1240+
} finally {
1241+
fs.rmSync(tempRoot, { recursive: true, force: true });
1242+
}
1243+
});
1244+
1245+
it("keeps a cyclic workspace alias bounded and separate from unrelated paths", () => {
1246+
const root = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), "workspace-cycle-")));
1247+
const alias = path.join(root, "alias");
1248+
try {
1249+
fs.symlinkSync(alias, alias, process.platform === "win32" ? "junction" : "dir");
1250+
const cfg: OpenClawConfig = { agents: { entries: { ops: { workspace: alias } } } };
1251+
1252+
expect(resolveAgentIdByWorkspacePath(cfg, alias)).toBe("ops");
1253+
expect(resolveAgentIdByWorkspacePath(cfg, path.join(root, "other"))).toBeUndefined();
1254+
} finally {
1255+
fs.rmSync(root, { recursive: true, force: true });
1256+
}
1257+
});
11951258
});
11961259

11971260
describe("resolveAgentSkillsFilter", () => {

‎src/agents/agent-scope.ts‎

Lines changed: 3 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,5 @@
11
/** Higher-level agent scope helpers for model selection, fallbacks, skills, and workspaces. */
2-
import fs from "node:fs";
3-
import path from "node:path";
42
import {
5-
lowercasePreservingWhitespace,
63
normalizeLowercaseStringOrEmpty,
74
normalizeOptionalString,
85
resolvePrimaryStringValue,
@@ -24,7 +21,6 @@ import {
2421
resolveAgentIdFromSessionKey,
2522
} from "../routing/session-key.js";
2623
import { resolveEffectiveAgentSkillFilter } from "../skills/discovery/agent-filter.js";
27-
import { resolveUserPath } from "../utils.js";
2824
import {
2925
AgentSelectionRequiredError,
3026
listAgentIds,
@@ -34,6 +30,7 @@ import {
3430
resolveDefaultAgentId,
3531
tryResolveLegacyCompatibilityAgentId,
3632
} from "./agent-scope-config.js";
33+
import { resolveCanonicalWorkspacePath } from "./workspace-state-identity.js";
3734
export { hasSessionAutoModelFallbackProvenance } from "../config/sessions/model-override-provenance.js";
3835
export {
3936
listAgentEntries,
@@ -60,11 +57,6 @@ export {
6057
type ResolvedAgentConfig,
6158
} from "./agent-scope-config.js";
6259

63-
/** Strip null bytes from paths to prevent ENOTDIR errors. */
64-
function stripNullBytes(s: string): string {
65-
return s.split("\0").join("");
66-
}
67-
6860
const AUTO_FALLBACK_PRIMARY_PROBE_INTERVAL_MS = 5 * 60 * 1000;
6961
const AUTO_FALLBACK_PRIMARY_PROBE_MAX_KEYS = 4096;
7062
const autoFallbackPrimaryProbeState = new Map<string, number>();
@@ -607,32 +599,16 @@ export function resolveEffectiveModelFallbacks(params: {
607599
return agentFallbacksOverride ?? defaultFallbacks;
608600
}
609601

610-
function normalizePathForComparison(input: string): string {
611-
const resolved = path.resolve(stripNullBytes(resolveUserPath(input)));
612-
let normalized = resolved;
613-
// Prefer realpath when available to normalize aliases/symlinks (for example /tmp -> /private/tmp)
614-
// and canonical path case without forcing case-folding on case-sensitive macOS volumes.
615-
try {
616-
normalized = fs.realpathSync.native(resolved);
617-
} catch {
618-
// Keep lexical path for non-existent directories.
619-
}
620-
if (process.platform === "win32") {
621-
return lowercasePreservingWhitespace(normalized);
622-
}
623-
return normalized;
624-
}
625-
626602
export function resolveAgentIdByWorkspacePath(
627603
cfg: OpenClawConfig,
628604
workspacePath: string,
629605
): string | undefined {
630-
const normalizedWorkspacePath = normalizePathForComparison(workspacePath);
606+
const normalizedWorkspacePath = resolveCanonicalWorkspacePath(workspacePath.replaceAll("\0", ""));
631607
let matchedAgentId: string | undefined;
632608
let matchedWorkspaceLength = -1;
633609

634610
for (const id of listAgentIds(cfg)) {
635-
const workspaceDir = normalizePathForComparison(resolveAgentWorkspaceDir(cfg, id));
611+
const workspaceDir = resolveCanonicalWorkspacePath(resolveAgentWorkspaceDir(cfg, id));
636612
if (!isPathInside(workspaceDir, normalizedWorkspacePath)) {
637613
continue;
638614
}

‎src/agents/workspace-state-identity.ts‎

Lines changed: 17 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -18,8 +18,11 @@ function normalizeWorkspaceIdentityPath(value: string): string {
1818
return process.platform === "win32" ? normalized.toLowerCase() : normalized;
1919
}
2020

21-
function canonicalizeWorkspaceIdentityPath(workspaceDir: string): string {
22-
const fallback = normalizeWorkspaceIdentityPath(path.resolve(resolveUserPath(workspaceDir)));
21+
function canonicalizeWorkspacePath(
22+
workspaceDir: string,
23+
normalizePath: (value: string) => string,
24+
): string {
25+
const fallback = normalizePath(path.resolve(resolveUserPath(workspaceDir)));
2326
let candidate = fallback;
2427
const followedSymlinks = new Set<string>();
2528

@@ -28,7 +31,7 @@ function canonicalizeWorkspaceIdentityPath(workspaceDir: string): string {
2831
let current = candidate;
2932
while (true) {
3033
try {
31-
return normalizeWorkspaceIdentityPath(
34+
return normalizePath(
3235
path.join(fs.realpathSync.native(current), ...missingSegments.toReversed()),
3336
);
3437
} catch {
@@ -37,7 +40,7 @@ function canonicalizeWorkspaceIdentityPath(workspaceDir: string): string {
3740
}
3841
try {
3942
if (fs.lstatSync(current).isSymbolicLink()) {
40-
const normalizedLink = normalizeWorkspaceIdentityPath(current);
43+
const normalizedLink = normalizePath(current);
4144
if (followedSymlinks.has(normalizedLink)) {
4245
return fallback;
4346
}
@@ -63,6 +66,12 @@ function canonicalizeWorkspaceIdentityPath(workspaceDir: string): string {
6366
return fallback;
6467
}
6568

69+
// Filesystem ownership preserves path bytes; NFC state keys are a separate stored
70+
// contract and can identify distinct directories as equal on Linux.
71+
export function resolveCanonicalWorkspacePath(workspaceDir: string): string {
72+
return canonicalizeWorkspacePath(workspaceDir, path.normalize);
73+
}
74+
6675
export function createWorkspaceStateIdentity(workspacePath: string): WorkspaceStateIdentity {
6776
return {
6877
workspacePath,
@@ -72,10 +81,12 @@ export function createWorkspaceStateIdentity(workspacePath: string): WorkspaceSt
7281

7382
export function resolveWorkspaceStateAliases(workspaceDir: string): WorkspaceStateIdentity[] {
7483
const lexicalPath = normalizeWorkspaceIdentityPath(path.resolve(resolveUserPath(workspaceDir)));
75-
const canonicalPath = canonicalizeWorkspaceIdentityPath(workspaceDir);
84+
const canonicalPath = canonicalizeWorkspacePath(workspaceDir, normalizeWorkspaceIdentityPath);
7685
return [...new Set([lexicalPath, canonicalPath])].map(createWorkspaceStateIdentity);
7786
}
7887

7988
export function resolveWorkspaceStateIdentity(workspaceDir: string): WorkspaceStateIdentity {
80-
return createWorkspaceStateIdentity(canonicalizeWorkspaceIdentityPath(workspaceDir));
89+
return createWorkspaceStateIdentity(
90+
canonicalizeWorkspacePath(workspaceDir, normalizeWorkspaceIdentityPath),
91+
);
8192
}

‎src/memory-host-sdk/dreaming.test.ts‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -236,6 +236,21 @@ describe("memory dreaming host helpers", () => {
236236
]);
237237
});
238238

239+
it("uses canonical roster identities when agent aliases share a workspace", () => {
240+
const cfg = {
241+
agents: {
242+
list: [
243+
{ id: "Team Alpha", workspace: "/workspace/shared" },
244+
{ id: "team-alpha", workspace: "/workspace/shared" },
245+
],
246+
},
247+
} as OpenClawConfig;
248+
249+
expect(resolveMemoryDreamingWorkspaces(cfg)).toEqual([
250+
{ workspaceDir: "/workspace/shared", agentIds: ["team-alpha"] },
251+
]);
252+
});
253+
239254
it("does not require a default owner when no primary workspace is supplied", () => {
240255
const cfg = {
241256
agents: {

‎src/memory-host-sdk/dreaming.ts‎

Lines changed: 3 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ import {
1212
normalizeStringifiedOptionalString,
1313
} from "@openclaw/normalization-core/string-coerce";
1414
import {
15-
listAgentEntries,
15+
listAgentIds,
1616
resolveAgentWorkspaceDir,
1717
resolveDefaultAgentId,
1818
} from "../agents/agent-scope.js";
@@ -288,10 +288,6 @@ function resolveExecutionConfig(
288288
};
289289
}
290290

291-
function normalizePathForComparison(input: string): string {
292-
return resolveWorkspaceStateIdentity(input).workspacePath;
293-
}
294-
295291
function formatLocalIsoDay(epochMs: number): string {
296292
const date = new Date(epochMs);
297293
const year = date.getFullYear();
@@ -584,20 +580,7 @@ export function resolveMemoryDreamingWorkspaces(
584580
cfg: OpenClawConfig,
585581
options: MemoryDreamingWorkspaceOptions = {},
586582
): MemoryDreamingWorkspace[] {
587-
const configured = listAgentEntries(cfg);
588-
const agentIds: string[] = [];
589-
const seenAgents = new Set<string>();
590-
for (const entry of configured) {
591-
if (!entry || typeof entry !== "object" || typeof entry.id !== "string") {
592-
continue;
593-
}
594-
const id = normalizeOptionalLowercaseString(entry.id);
595-
if (!id || seenAgents.has(id)) {
596-
continue;
597-
}
598-
seenAgents.add(id);
599-
agentIds.push(id);
600-
}
583+
const agentIds = listAgentIds(cfg);
601584
if (agentIds.length === 0) {
602585
agentIds.push(resolveDefaultAgentId(cfg));
603586
}
@@ -609,7 +592,7 @@ export function resolveMemoryDreamingWorkspaces(
609592
return;
610593
}
611594
const agentId = normalizeOptionalLowercaseString(agentIdRaw) || resolveDefaultAgentId(cfg);
612-
const key = normalizePathForComparison(workspaceDir);
595+
const key = resolveWorkspaceStateIdentity(workspaceDir).workspacePath;
613596
const existing = byWorkspace.get(key);
614597
if (existing) {
615598
if (!existing.agentIds.includes(agentId)) {

0 commit comments

Comments
 (0)