Skip to content

Commit c50533f

Browse files
authored
refactor(infra): share path existence policy (#134630)
1 parent 765c0cd commit c50533f

12 files changed

Lines changed: 67 additions & 97 deletions

‎config/assertion-safety-baseline.txt‎

Lines changed: 3 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2103,7 +2103,7 @@ src/agents/transcript-redact.ts 2
21032103
src/agents/transport-message-transform.ts 2
21042104
src/agents/utils/frontmatter.ts 2
21052105
src/agents/utils/tools-manager.ts 2
2106-
src/agents/workspace-legacy-state.ts 3
2106+
src/agents/workspace-legacy-state.ts 2
21072107
src/agents/workspace-state-store.ts 1
21082108
src/agents/workspace.ts 9
21092109
src/agents/worktrees/git.ts 2
@@ -3074,7 +3074,6 @@ src/infra/delivery-queue-sqlite-namespace.ts 3
30743074
src/infra/delivery-queue-sqlite.ts 4
30753075
src/infra/delivery-queue-sqlite.types.ts 1
30763076
src/infra/delivery-recovery.shared.ts 4
3077-
src/infra/device-identity.ts 1
30783077
src/infra/device-pairing-store.ts 6
30793078
src/infra/diagnostic-event-listener-presence.ts 3
30803079
src/infra/diagnostic-events.ts 13
@@ -3092,7 +3091,6 @@ src/infra/exec-approval-reply.ts 2
30923091
src/infra/exec-approvals-allowlist.ts 7
30933092
src/infra/exec-approvals-config.ts 4
30943093
src/infra/exec-approvals-effective.ts 3
3095-
src/infra/exec-approvals-migration-gate.ts 1
30963094
src/infra/exec-approvals-resolver.ts 2
30973095
src/infra/exec-approvals-socket.ts 1
30983096
src/infra/exec-approvals-store.ts 1
@@ -3174,7 +3172,7 @@ src/infra/provider-usage.fetch.minimax.ts 2
31743172
src/infra/push-apns-http2.ts 1
31753173
src/infra/push-apns.relay.ts 1
31763174
src/infra/push-apns.ts 7
3177-
src/infra/push-web.ts 3
3175+
src/infra/push-web.ts 2
31783176
src/infra/question-gateway-resolver.ts 3
31793177
src/infra/question-reaction-runtime.ts 3
31803178
src/infra/restart-coordinator.ts 1
@@ -3216,7 +3214,6 @@ src/infra/state-migrations.channel-pairing.ts 5
32163214
src/infra/state-migrations.config-machine-state.ts 1
32173215
src/infra/state-migrations.cron-run-logs.ts 4
32183216
src/infra/state-migrations.debug-proxy.ts 5
3219-
src/infra/state-migrations.device-identity-repair.ts 1
32203217
src/infra/state-migrations.doctor.ts 7
32213218
src/infra/state-migrations.exec-approvals.ts 1
32223219
src/infra/state-migrations.fs.ts 1
@@ -3232,7 +3229,6 @@ src/infra/state-migrations.node-host.ts 2
32323229
src/infra/state-migrations.runtime-state.ts 7
32333230
src/infra/state-migrations.session-store.ts 12
32343231
src/infra/state-migrations.shared-auth-store.ts 1
3235-
src/infra/state-migrations.source-snapshot.ts 1
32363232
src/infra/state-migrations.state-dir.ts 1
32373233
src/infra/state-migrations.storage.ts 21
32383234
src/infra/state-migrations.task-sidecar-rows.ts 8
@@ -3570,7 +3566,7 @@ src/plugins/trusted-tool-policy.ts 1
35703566
src/plugins/uninstall-config.ts 3
35713567
src/plugins/uninstall-package-config.ts 2
35723568
src/plugins/uninstall-package-plan.ts 1
3573-
src/plugins/uninstall.ts 4
3569+
src/plugins/uninstall.ts 3
35743570
src/plugins/update-channel.ts 2
35753571
src/plugins/update-config.ts 2
35763572
src/plugins/update-installed.ts 5

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

Lines changed: 4 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import path from "node:path";
66
import { formatCliCommand } from "../cli/command-format.js";
77
import { resolveLegacyStateDirs, resolveStateDir } from "../config/paths.js";
88
import { root } from "../infra/fs-safe.js";
9+
import { pathMayExistSync } from "../infra/path-existence.js";
910
import { resolveUserPath } from "../utils.js";
1011
import { resolveWorkspaceStateIdentity } from "./workspace-state-identity.js";
1112

@@ -108,17 +109,9 @@ export function resolveLegacyWorkspaceSourcePaths(
108109
}
109110

110111
function pathOrClaimExists(filePath: string): boolean {
111-
for (const candidate of [filePath, `${filePath}${WORKSPACE_DOCTOR_CLAIM_SUFFIX}`]) {
112-
try {
113-
fs.lstatSync(candidate);
114-
return true;
115-
} catch (error) {
116-
if ((error as NodeJS.ErrnoException).code !== "ENOENT") {
117-
return true;
118-
}
119-
}
120-
}
121-
return false;
112+
return (
113+
pathMayExistSync(filePath) || pathMayExistSync(`${filePath}${WORKSPACE_DOCTOR_CLAIM_SUFFIX}`)
114+
);
122115
}
123116

124117
function siblingPathIsOwnedMarker(filePath: string): boolean {

‎src/infra/device-identity.ts‎

Lines changed: 5 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
// Gateway/device Ed25519 identity API backed by canonical shared SQLite state.
22
import crypto from "node:crypto";
3-
import fs from "node:fs";
43
import path from "node:path";
54
import { resolveOpenClawStateDirForDatabasePath } from "../state/openclaw-state-db.paths.js";
65
import { acquireDeviceIdentityCoordinator } from "./device-identity-coordinator.js";
@@ -22,6 +21,7 @@ import {
2221
verifyEd25519Signature,
2322
} from "./ed25519-signature.js";
2423
import { pruneMapToMaxSize } from "./map-size.js";
24+
import { pathMayExistSync } from "./path-existence.js";
2525
import { createSqliteLifecycleAggregateError } from "./sqlite-coordinator.js";
2626

2727
export type { DeviceIdentity } from "./device-identity-store.js";
@@ -38,15 +38,6 @@ function toDeviceIdentity(stored: StoredDeviceIdentity): DeviceIdentity {
3838
};
3939
}
4040

41-
function pathMayExist(filePath: string): boolean {
42-
try {
43-
fs.lstatSync(filePath);
44-
return true;
45-
} catch (error) {
46-
return (error as NodeJS.ErrnoException).code !== "ENOENT";
47-
}
48-
}
49-
5041
/** Exact retired file owned by Doctor migration code. */
5142
function resolveLegacyDeviceIdentityPath(options: DeviceIdentityStoreOptions = {}): string {
5243
const { databasePath } = resolveDeviceIdentityStore(options);
@@ -64,9 +55,9 @@ function assertNoPendingLegacyIdentity(options: DeviceIdentityStoreOptions): voi
6455
const legacyPath = resolveLegacyDeviceIdentityPath(options);
6556
if (
6657
// Claims first, source last: both migration owners restore claim -> source atomically.
67-
pathMayExist(`${legacyPath}${DOCTOR_CLAIM_SUFFIX}`) ||
68-
pathMayExist(`${legacyPath}${NATIVE_CLAIM_SUFFIX}`) ||
69-
pathMayExist(legacyPath)
58+
pathMayExistSync(`${legacyPath}${DOCTOR_CLAIM_SUFFIX}`) ||
59+
pathMayExistSync(`${legacyPath}${NATIVE_CLAIM_SUFFIX}`) ||
60+
pathMayExistSync(legacyPath)
7061
) {
7162
throw new Error(
7263
`Legacy device identity exists at ${legacyPath}. Run "openclaw doctor --fix" before starting the gateway or connecting this client.`,
@@ -120,7 +111,7 @@ function loadOrCreateDeviceIdentityOwned(options: DeviceIdentityStoreOptions): D
120111
const { databasePath } = resolveDeviceIdentityStore(options);
121112
// A downgrade can recreate retired JSON after SQLite migration. Once this profile has
122113
// a canonical row, keep it authoritative and leave the retired source for Doctor.
123-
const existing = pathMayExist(databasePath) ? readStoredDeviceIdentity(options) : null;
114+
const existing = pathMayExistSync(databasePath) ? readStoredDeviceIdentity(options) : null;
124115
if (existing) {
125116
return toDeviceIdentity(existing);
126117
}

‎src/infra/exec-approvals-migration-gate.ts‎

Lines changed: 2 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
// Blocks runtime use while retired exec approval state still awaits Doctor import.
2-
import fs from "node:fs";
32
import path from "node:path";
43
import { resolveExecApprovalsPath } from "./exec-approvals-config.js";
4+
import { pathMayExistSync } from "./path-existence.js";
55

66
const DOCTOR_CLAIM_SUFFIX = ".doctor-importing";
77
// Doctor usually runs in another process, so cache only the steady-state absence;
@@ -30,15 +30,6 @@ export class ExecApprovalsMigrationRequiredError extends Error {
3030
}
3131
}
3232

33-
function pathMayExist(filePath: string): boolean {
34-
try {
35-
fs.lstatSync(filePath);
36-
return true;
37-
} catch (error) {
38-
return (error as NodeJS.ErrnoException).code !== "ENOENT";
39-
}
40-
}
41-
4233
/** Refuse runtime access until Doctor owns the one-time legacy import. */
4334
export function assertNoPendingLegacyExecApprovals(
4435
options: { pathMayExist?: (filePath: string) => boolean } = {},
@@ -47,7 +38,7 @@ export function assertNoPendingLegacyExecApprovals(
4738
if (legacyAbsenceCache.has(sourcePath)) {
4839
return;
4940
}
50-
const probe = options.pathMayExist ?? pathMayExist;
41+
const probe = options.pathMayExist ?? pathMayExistSync;
5142
// Bound both Doctor rename directions: source -> claim and claim -> source.
5243
const sourceBefore = probe(sourcePath);
5344
const claim = probe(`${sourcePath}${DOCTOR_CLAIM_SUFFIX}`);

‎src/infra/path-existence.test.ts‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
import fs from "node:fs";
2+
import os from "node:os";
3+
import path from "node:path";
4+
import { expect, it } from "vitest";
5+
import { pathMayExistSync } from "./path-existence.js";
6+
7+
it("distinguishes definite absence from paths that may still exist", () => {
8+
const root = fs.mkdtempSync(path.join(os.tmpdir(), "openclaw-path-existence-"));
9+
try {
10+
const present = path.join(root, "present");
11+
fs.writeFileSync(present, "");
12+
expect(pathMayExistSync(present)).toBe(true);
13+
expect(pathMayExistSync(path.join(root, "missing"))).toBe(false);
14+
15+
const dangling = path.join(root, "dangling");
16+
fs.symlinkSync("missing-target", dangling);
17+
expect(pathMayExistSync(dangling)).toBe(true);
18+
const blockedByFile = path.join(present, "child");
19+
expect(() => fs.lstatSync(blockedByFile)).toThrow(expect.objectContaining({ code: "ENOTDIR" }));
20+
expect(pathMayExistSync(blockedByFile)).toBe(true);
21+
} finally {
22+
fs.rmSync(root, { force: true, recursive: true });
23+
}
24+
});

‎src/infra/path-existence.ts‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
import fs from "node:fs";
2+
import { hasErrnoCode } from "./errno.js";
3+
4+
/** Only a definite missing leaf permits callers to treat a path as absent. */
5+
export function pathMayExistSync(filePath: string): boolean {
6+
try {
7+
fs.lstatSync(filePath);
8+
return true;
9+
} catch (error) {
10+
return !hasErrnoCode(error, "ENOENT");
11+
}
12+
}

‎src/infra/push-web.ts‎

Lines changed: 2 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
11
// Stores and verifies web push subscriptions and delivery payloads.
22
import { randomUUID } from "node:crypto";
3-
import fs from "node:fs";
43
import path from "node:path";
54
import { expectDefined, normalizeOptionalString } from "@openclaw/normalization-core";
65
import { resolveStateDir } from "../config/paths.js";
76
import { createLazyRuntimeModule } from "../shared/lazy-runtime.js";
7+
import { pathMayExistSync } from "./path-existence.js";
88
import {
99
WebPushSubscriptionBindingError,
1010
createWebPushVapidKeyPair,
@@ -63,27 +63,14 @@ const loadWebPushRuntime = createLazyRuntimeModule(() =>
6363
import("web-push").then((mod: WebPushRuntimeModule) => mod.default ?? mod),
6464
);
6565

66-
function legacyWebPushPathMayExist(filePath: string): boolean {
67-
try {
68-
fs.lstatSync(filePath);
69-
return true;
70-
} catch (error) {
71-
// Only a definite absence permits creating a new signing identity.
72-
return (error as NodeJS.ErrnoException).code !== "ENOENT";
73-
}
74-
}
75-
7666
// Production callers run under the Gateway's lifetime state/config lock. Doctor must
7767
// acquire those same locks before claiming legacy files, so this check remains stable
7868
// through the following SQLite operation or asynchronous delivery fan-out.
7969
function assertLegacyWebPushMigrationComplete(baseDir?: string): void {
8070
const stateDir = baseDir ?? resolveStateDir();
8171
const pendingLegacyPath = LEGACY_WEB_PUSH_PATHS.find((relativePath) => {
8272
const sourcePath = path.join(stateDir, relativePath);
83-
return (
84-
legacyWebPushPathMayExist(sourcePath) ||
85-
legacyWebPushPathMayExist(`${sourcePath}.doctor-importing`)
86-
);
73+
return pathMayExistSync(sourcePath) || pathMayExistSync(`${sourcePath}.doctor-importing`);
8774
});
8875
if (pendingLegacyPath) {
8976
throw new Error(

‎src/infra/state-migrations.device-identity-repair.ts‎

Lines changed: 7 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
// Owner-authorized detection and Doctor-only replacement for invalid device identity rows.
2-
import fs from "node:fs";
32
import path from "node:path";
43
import {
54
DeviceIdentityStorageError,
@@ -8,6 +7,7 @@ import {
87
repairInvalidStoredDeviceIdentity,
98
} from "./device-identity-store.js";
109
import { formatErrorMessage } from "./errors.js";
10+
import { pathMayExistSync } from "./path-existence.js";
1111
import type { LegacyDeviceIdentityDetection } from "./state-migrations.device-identity.types.js";
1212
import type { MigrationMessages } from "./state-migrations.types.js";
1313

@@ -16,15 +16,6 @@ const DOCTOR_CLAIM_SUFFIX = ".doctor-importing";
1616
const NATIVE_CLAIM_SUFFIX = ".native-importing";
1717
const IDENTITY_KEY = "primary";
1818

19-
function pathMayExist(filePath: string): boolean {
20-
try {
21-
fs.lstatSync(filePath);
22-
return true;
23-
} catch (error) {
24-
return (error as NodeJS.ErrnoException).code !== "ENOENT";
25-
}
26-
}
27-
2819
/** Detect retired paths for an authorized importer; only Doctor may rotate invalid SQLite state. */
2920
export function detectLegacyDeviceIdentity(params: {
3021
stateDir: string;
@@ -54,16 +45,18 @@ export function detectLegacyDeviceIdentity(params: {
5445
nativeClaimPath,
5546
hasLegacy:
5647
importAuthorized &&
57-
(pathMayExist(claimPath) || pathMayExist(nativeClaimPath) || pathMayExist(sourcePath)),
48+
(pathMayExistSync(claimPath) ||
49+
pathMayExistSync(nativeClaimPath) ||
50+
pathMayExistSync(sourcePath)),
5851
hasInvalidCanonical,
5952
};
6053
}
6154

6255
export function hasLegacyDeviceIdentityPath(detected: LegacyDeviceIdentityDetection): boolean {
6356
return (
64-
pathMayExist(detected.claimPath) ||
65-
pathMayExist(detected.nativeClaimPath) ||
66-
pathMayExist(detected.sourcePath)
57+
pathMayExistSync(detected.claimPath) ||
58+
pathMayExistSync(detected.nativeClaimPath) ||
59+
pathMayExistSync(detected.sourcePath)
6760
);
6861
}
6962

‎src/infra/state-migrations.mcp-oauth.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import {
1111
executeSqliteQueryTakeFirstSync,
1212
getNodeSqliteKysely,
1313
} from "./kysely-sync.js";
14+
import { pathMayExistSync } from "./path-existence.js";
1415
import { withLegacyMigrationStateLock } from "./state-migrations.lock.js";
1516
import { parseLegacyMcpOAuthStore } from "./state-migrations.mcp-oauth-format.js";
1617
import { withRootBoundedLegacyFileLock } from "./state-migrations.mcp-oauth-lock.js";
@@ -25,7 +26,6 @@ import {
2526
} from "./state-migrations.receipts.js";
2627
import {
2728
LegacyMigrationSourceClaim,
28-
legacyMigrationPathMayExist,
2929
legacyMigrationSourceSnapshotsMatch as snapshotsMatch,
3030
readLegacyMigrationSourceSnapshot,
3131
resolveLegacyMigrationRelativePath,
@@ -101,7 +101,7 @@ export function detectLegacyMcpOAuthStores(params: {
101101
const sourcePaths = listLegacySourcePaths(sourceDir);
102102
return { sourceDir, sourcePaths, hasLegacy: sourcePaths.length > 0 };
103103
} catch {
104-
return { sourceDir, sourcePaths: [], hasLegacy: legacyMigrationPathMayExist(sourceDir) };
104+
return { sourceDir, sourcePaths: [], hasLegacy: pathMayExistSync(sourceDir) };
105105
}
106106
}
107107

‎src/infra/state-migrations.source-snapshot.ts‎

Lines changed: 2 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import { createHash, randomUUID } from "node:crypto";
22
import fs from "node:fs";
33
import path from "node:path";
44
import type { Root } from "@openclaw/fs-safe";
5+
import { pathMayExistSync } from "./path-existence.js";
56

67
/** The stable source identity every doctor-owned import verifies before cleanup. */
78
export type LegacyMigrationSourceSnapshot = {
@@ -180,24 +181,11 @@ export async function claimLegacyMigrationSourceClaims<
180181
}
181182
}
182183

183-
/** A source may be inaccessible; only a proven absence permits skipping repair. */
184-
export function legacyMigrationPathMayExist(filePath: string): boolean {
185-
try {
186-
fs.lstatSync(filePath);
187-
return true;
188-
} catch (error) {
189-
return (error as NodeJS.ErrnoException).code !== "ENOENT";
190-
}
191-
}
192-
193184
export function legacyMigrationSourceOrClaimMayExist(
194185
sourcePath: string,
195186
claimSuffix = ".doctor-importing",
196187
): boolean {
197-
return (
198-
legacyMigrationPathMayExist(sourcePath) ||
199-
legacyMigrationPathMayExist(`${sourcePath}${claimSuffix}`)
200-
);
188+
return pathMayExistSync(sourcePath) || pathMayExistSync(`${sourcePath}${claimSuffix}`);
201189
}
202190

203191
/** Constrain migration reads and moves to the original trusted state root. */

0 commit comments

Comments
 (0)