Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(backup): the data-dir sweep probes and claims an owned socket the runtime cannot lstat; removal only through the native tag check
garrytan41790fe7675b
diff --git a/.github/workflows/test.yml b/.github/workflows/test.ymlindex f57a1fe817..8666568cc4 100644--- a/.github/workflows/test.yml+++ b/.github/workflows/test.yml@@ -221,8 +221,8 @@ jobs:# on this row once a Bun release carries that change.- name: Teardown bounds that used to park the Windows unit run (#5332)run: bun test --timeout 120000 test/postgres-disconnect-bounded.test.ts- - name: Backup archive round trip on this host (#5312)- run: bun test --timeout 60000 test/backup-archive-roundtrip-5312.test.ts+ - name: Backup archive round trip and stale AF_UNIX socket sweep on this host (#5312)+ run: bun test --timeout 60000 test/backup-archive-roundtrip-5312.test.ts test/backup-stale-socket-5312.test.ts- name: Hidden console windows from detached processes (#4992)run: bun test --timeout 300000 test/windows-hidden-console.test.ts test/spawn-windows-hide.test.ts test/scripts/windows-hide-guard.test.tsdiff --git a/docs/guides/in-agent-setup.md b/docs/guides/in-agent-setup.mdindex 8ecc6222fa..4a13e69d5f 100644--- a/docs/guides/in-agent-setup.md+++ b/docs/guides/in-agent-setup.md@@ -183,9 +183,11 @@ and publishes a checksummed archive with POSIX mode `0600`. On Windows, built-inWindows PowerShell establishes and verifies access for the current owner andSYSTEM before writing backup payloads. It protects only newly created backuppaths, never changes existing parent permissions, and refuses with-`private_backup_path_unavailable` if enforcement is unavailable. Use a new private-destination on a local filesystem with Windows ACL support and permitted-Windows PowerShell. A busy database or a+`private_backup_path_unavailable` when that protection could not be established+or verified at the destination (some locations' inherited permissions prevent+it; a new path inside your user profile works). The destination must be on a+local filesystem with Windows ACL support, with built-in Windows PowerShell+permitted. A busy database or achanging file fails the operation instead of publishing a success receipt.Before the dump, the command removes gbrain's own IPC socket files@@ -195,9 +197,12 @@ later backups; each removal is listed in the archive's `omitted` inventory.Any other socket, FIFO or symlink in the data dir is left alone and thecommand refuses with `backup_dump_failed` naming it: stop the process thatuses it (or move it out of the data dir) and run the same command again.-This cleanup is verified on Linux and macOS; on Windows a stale socket is-removed through the native lock binding and has not been exercised on a-native runner.+On Windows the runtime cannot inspect a stale AF_UNIX socket (`lstat` fails),+so the sweep probes and claims such an entry without classifying it and removes+it only through the native binding's tag check; an entry nothing can verify is+kept and named in the refusal (`an entry this runtime cannot inspect`), never+deleted blind. The Linux and macOS lanes cover the sweep; the `windows-latest`+row of `test.yml` runs the stale-socket test natively.| Included | Excluded or inventoried for reconnection || --- | --- |diff --git a/src/core/backup/private-path.ts b/src/core/backup/private-path.tsindex 279f162f9f..761c7f1ee5 100644--- a/src/core/backup/private-path.ts+++ b/src/core/backup/private-path.ts@@ -92,6 +92,8 @@ export async function protectNewBackupPath(path: string, kind: 'directory' | 'fi|| before.birthtimeNs !== after.birthtimeNs|| (kind === 'directory' ? readdirSync(path).length !== 0 : after.size !== 0n || after.nlink !== 1n)) throw new Error('Private path verification failed');} catch {- throw new AgentInstallError('private_backup_path_unavailable', 'Windows could not establish owner-only backup access (plus SYSTEM). No payload was written to this new path. Use a new private destination on a local filesystem with Windows ACL support, ensure built-in Windows PowerShell is available and permitted, then retry. Existing files and parent permissions were not changed.');+ // #5312 B(i): the text names what was observed (protection attempted and verified by the script above, and it+ // did not hold here), not a categorical rule about drive roots; the user profile is the destination that works.+ throw new AgentInstallError('private_backup_path_unavailable', "This destination's permissions prevented GBrain from establishing owner-only access (plus SYSTEM); use a new path inside your user profile. No payload was written to this new path. The destination must be on a local filesystem with Windows ACL support, with built-in Windows PowerShell available and permitted. Existing files and parent permissions were not changed.");}}diff --git a/src/core/backup/runtime-artefacts.ts b/src/core/backup/runtime-artefacts.tsindex 97fe8f76c8..c3f536351c 100644--- a/src/core/backup/runtime-artefacts.ts+++ b/src/core/backup/runtime-artefacts.ts@@ -11,14 +11,24 @@* blocks the dump instead of a bare WASI errno. Symlinks are never followed and* regular files are never deleted: the engine lock proves there is no PGLite* owner, not that an arbitrary endpoint belongs to a dead gbrain process.+ *+ * #5312 Windows half: Bun cannot `lstat` a stale AF_UNIX reparse point (EACCES),+ * so classifying first threw before the probe/claim/remove sequence ran. An+ * `unreadable` entry at one of gbrain's own socket paths skips the+ * symlink/socket classification and goes to the probe and the bind claim;+ * removal happens only through the native tag-verifying remover+ * (`binding.removeStaleWindowsSocket`, which opens the leaf with+ * FILE_FLAG_OPEN_REPARSE_POINT and checks IO_REPARSE_TAG_AF_UNIX). Without one+ * (POSIX, or a claim that offers none) the entry is `kept: unreadable`, never+ * unlinked. `fs` is imported as a namespace so a test can inject the EACCES.*/-import { lstatSync, readdirSync, unlinkSync } from 'node:fs';+import * as fs from 'node:fs';import { dirname, join, resolve } from 'node:path';import { resolveSocketPathForConfig, socketHasLiveListener } from '../context/resolve-ipc.ts';import { claimLocalIpcBinding } from '../context/ipc-path.ts';import { AgentInstallError } from '../agent-install/state.ts';-export type KeptArtefactReason = 'live_listener' | 'symlink' | 'not_a_socket' | 'foreign_socket' | 'foreign_fifo';+export type KeptArtefactReason = 'live_listener' | 'symlink' | 'not_a_socket' | 'foreign_socket' | 'foreign_fifo' | 'unreadable';export interface RuntimeArtefactSweep {/** gbrain runtime sockets whose holder was dead; unlinked before the dump. */@@ -29,9 +39,17 @@ export interface RuntimeArtefactSweep {const GBRAIN_SOCKET_KINDS = ['resolve', 'persistence'] as const;-function entryStat(path: string) {- try { return lstatSync(path); }- catch (error) { if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null; throw error; }+/** What the runtime reports for a stale Windows AF_UNIX reparse point (EACCES on Bun; the others are its neighbours). */+const UNREADABLE_CODES = new Set(['EACCES', 'EPERM', 'EINVAL', 'UNKNOWN']);++function entryStat(path: string): fs.Stats | 'missing' | 'unreadable' {+ try { return fs.lstatSync(path); }+ catch (error) {+ const code = (error as NodeJS.ErrnoException).code;+ if (code === 'ENOENT') return 'missing';+ if (code && UNREADABLE_CODES.has(code)) return 'unreadable';+ throw error;+ }}/** Remove gbrain's dead runtime sockets from `dataDir`; list every other non-regular top-level entry. Call only while holding the PGLite writer lock. */@@ -45,9 +63,11 @@ export async function sweepStaleRuntimeArtefacts(dataDir: string): Promise<Runtiif (!path || dirname(resolve(path)) !== dir) continue;owned.add(resolve(path));const stat = entryStat(path);- if (!stat) continue;- if (stat.isSymbolicLink()) { sweep.kept.push({ path, reason: 'symlink' }); continue; }- if (!stat.isSocket()) { sweep.kept.push({ path, reason: 'not_a_socket' }); continue; }+ if (stat === 'missing') continue;+ if (stat !== 'unreadable') {+ if (stat.isSymbolicLink()) { sweep.kept.push({ path, reason: 'symlink' }); continue; }+ if (!stat.isSocket()) { sweep.kept.push({ path, reason: 'not_a_socket' }); continue; }+ }// An accepted (or timed-out) probe connect means "not ours to remove"; the// bind claim a live serve retains for its whole lifetime is taken only for a// dead-looking socket, so removal is serialized with a serve starting up,@@ -57,17 +77,29 @@ export async function sweepStaleRuntimeArtefacts(dataDir: string): Promise<Runtiif (!binding) { sweep.kept.push({ path, reason: 'live_listener' }); continue; }try {if (await socketHasLiveListener(path)) { sweep.kept.push({ path, reason: 'live_listener' }); continue; }- if (binding.removeStaleWindowsSocket) binding.removeStaleWindowsSocket();- else unlinkSync(path);- sweep.removed.push(path);+ if (binding.removeStaleWindowsSocket) {+ // The native remover verifies the AF_UNIX reparse tag through the retained claim; a leaf it does not+ // recognise (or cannot open) is left in place, whatever lstat said about it.+ let removed = false;+ try { removed = binding.removeStaleWindowsSocket(); } catch { removed = false; }+ if (removed) sweep.removed.push(path);+ else sweep.kept.push({ path, reason: 'unreadable' });+ } else if (stat === 'unreadable') {+ // Nothing here can verify what the entry is: an unreadable owned path is never blindly unlinked.+ sweep.kept.push({ path, reason: 'unreadable' });+ } else {+ fs.unlinkSync(path);+ sweep.removed.push(path);+ }} finally { await binding.release(); }}- for (const name of readdirSync(dir).sort()) {+ for (const name of fs.readdirSync(dir).sort()) {const path = join(dir, name);if (owned.has(path)) continue;const stat = entryStat(path);- if (!stat) continue;- if (stat.isSymbolicLink()) sweep.kept.push({ path, reason: 'symlink' });+ if (stat === 'missing') continue;+ if (stat === 'unreadable') sweep.kept.push({ path, reason: 'unreadable' });+ else if (stat.isSymbolicLink()) sweep.kept.push({ path, reason: 'symlink' });else if (stat.isSocket()) sweep.kept.push({ path, reason: 'foreign_socket' });else if (stat.isFIFO()) sweep.kept.push({ path, reason: 'foreign_fifo' });}@@ -80,6 +112,7 @@ const KEPT_REASON_TEXT: Record<KeptArtefactReason, string> = {not_a_socket: 'a regular file where a gbrain socket is expected',foreign_socket: 'a socket gbrain does not own',foreign_fifo: 'a FIFO gbrain does not own',+ unreadable: 'an entry this runtime cannot inspect (on Windows, a stale gbrain socket the native verifier did not remove)',};/** The typed refusal for a `dumpDataDir` failure: the WASI errno plus every non-regular entry the sweep left in the data dir. */diff --git a/src/core/context/ipc-path.ts b/src/core/context/ipc-path.tsindex 16195beb98..6ea76ead78 100644--- a/src/core/context/ipc-path.ts+++ b/src/core/context/ipc-path.ts@@ -76,7 +76,9 @@ export function prepareLocalIpcPath(legacyPath: string, createParent = false, pr}/** A live server retains this kernel claim across probe/unlink/listen and until actual close. */-export async function claimLocalIpcBinding(legacyPath: string): Promise<{ socketPath: string; release(): Promise<void>; removeStaleWindowsSocket?(): void } | null> {+export async function claimLocalIpcBinding(legacyPath: string): Promise<{ socketPath: string; release(): Promise<void>;+ /** Windows only: verifies the leaf's AF_UNIX reparse tag through the retained claim and deletes it; false when the leaf is not such a socket (left in place). */+ removeStaleWindowsSocket?(): boolean } | null> {const socketPath = prepareLocalIpcPath(legacyPath, true);// Bun's older Windows pipe listener misclassifies a competing bind and can// crash during its failed-listen cleanup. Claim before any probe or listen.@@ -86,7 +88,7 @@ export async function claimLocalIpcBinding(legacyPath: string): Promise<{ socket}const lock = await tryAcquireNativeLock(`${resolve(socketPath)}.bind.lock`);return lock ? { socketPath, release: () => lock.release(),- ...(process.platform === 'win32' ? { removeStaleWindowsSocket: () => { removeNativeWindowsUnixSocket(resolve(socketPath), lock); } } : {}),+ ...(process.platform === 'win32' ? { removeStaleWindowsSocket: () => removeNativeWindowsUnixSocket(resolve(socketPath), lock) } : {}),} : null;}diff --git a/test/backup-private-path-text-5312.test.ts b/test/backup-private-path-text-5312.test.tsnew file mode 100644index 0000000000..9aca5d2b22--- /dev/null+++ b/test/backup-private-path-text-5312.test.ts@@ -0,0 +1,39 @@+/**+ * #5312 B(i): the Windows private-path refusal names what happened at this destination, not a categorical rule.+ *+ * The reporter hit `private_backup_path_unavailable` for a directory directly under a drive root while the same+ * command worked under the user profile. The mechanism was read, not run: a categorical "a directory directly under a+ * drive root does not work" overstates it, and a pre-check would re-run the `SetOwner` the script already runs and+ * refuse protectable paths without native positive and negative fixtures. So the text says that this destination's+ * permissions prevented protection and points at the user profile, and the script still attempts protection+ * unconditionally and verifies owner, rules and identity before trusting the path.+ */+import { expect, test } from 'bun:test';+import { readFileSync } from 'node:fs';+import { join } from 'node:path';++const source = readFileSync(join(import.meta.dir, '..', 'src', 'core', 'backup', 'private-path.ts'), 'utf8');+const refusal = source.match(/new AgentInstallError\('private_backup_path_unavailable', (["'])(.*?)\1\)/)?.[2] ?? '';++test('the refusal says the destination\'s permissions prevented protection and names the user profile as the fix', () => {+ expect(refusal).toContain("permissions prevented");+ expect(refusal).toContain('user profile');+ expect(refusal).toContain('No payload was written');+});++test('the refusal makes no categorical claim about drive roots or any other location class', () => {+ expect(refusal.toLowerCase()).not.toContain('drive root');+ expect(refusal.toLowerCase()).not.toContain('does not work');+ expect(refusal.toLowerCase()).not.toContain('never');+});++test('no pre-check gates protection: the script sets the owner unconditionally and verifies the result itself', () => {+ const script = source.slice(0, source.indexOf('export function __resetPowerShellWarmupForTests'));+ expect(script).toContain('$acl.SetOwner($user)');+ expect(script).toContain('$acl.SetAccessRuleProtection($true, $false)');+ expect(script).toContain("throw 'Owner or inheritance mismatch'");+ // Nothing inspects the inherited ACL before SetOwner.+ expect(script).not.toMatch(/GetAccessControl[\s\S]*?SetOwner/);+ expect(source).not.toContain('precheck');+ expect(source).not.toContain('preCheck');+});diff --git a/test/backup-stale-socket-5312.test.ts b/test/backup-stale-socket-5312.test.tsindex 64a78c96a9..4906fdc70a 100644--- a/test/backup-stale-socket-5312.test.ts+++ b/test/backup-stale-socket-5312.test.ts@@ -10,22 +10,31 @@* else at the top level (a live gbrain socket, a foreign socket or FIFO, a* symlink) stays, and the refusal is the typed `backup_dump_failed` naming it.*- * Linux-verified: the Windows AF_UNIX reparse-point branch (`removeStaleWindowsSocket`)- * is exercised only on a native Windows runner.+ * #5312 Windows half: Bun's `lstat` fails with EACCES on a stale AF_UNIX reparse point, so the sweep's+ * classification threw before the probe/claim/remove sequence ran and the backup stayed wedged. An `unreadable`+ * owned entry now skips the lstat classification and goes to the probe and the bind claim; removal happens only+ * through the native tag-verifying remover (`binding.removeStaleWindowsSocket`), and without one (POSIX) the entry is+ * `kept: unreadable`, never unlinked. The Linux cases below inject the EACCES through a spy on `fs.lstatSync`: they+ * prove the classification path and the fail-closed kept reason, not the native claim. The cases that `lstat` a+ * socket keep their POSIX gate; the Windows-only cases run on the `windows-latest` row of test.yml (a `native_only`+ * dispatch) and assert through the probe connect and the dump, never through `lstat`.*/-import { afterAll, beforeAll, expect, test } from 'bun:test';+import { afterAll, afterEach, beforeAll, expect, spyOn, test } from 'bun:test';import { createHash } from 'node:crypto';import { execFileSync, spawn } from 'node:child_process';+import * as fs from 'node:fs';import { existsSync, lstatSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, realpathSync, rmSync, statSync, symlinkSync, unlinkSync, writeFileSync } from 'node:fs';import * as net from 'node:net';import { tmpdir } from 'node:os';import { join } from 'node:path';import { privateWrite } from '../src/core/agent-install/state.ts';import { createPgliteBackup } from '../src/core/backup/snapshot.ts';+import { sweepStaleRuntimeArtefacts } from '../src/core/backup/runtime-artefacts.ts';import { PGLiteEngine } from '../src/core/pglite-engine.ts';import { resolveSocketPathForConfig } from '../src/core/context/resolve-ipc.ts';const posix = process.platform !== 'win32';+const windows = process.platform === 'win32';let temporary: string;let root: string;let dataDir: string;@@ -41,9 +50,39 @@ async function leaveStaleSocket(path: string): Promise<void> {const exited = new Promise(resolve => child.on('exit', resolve));child.kill('SIGKILL');await exited;- expect(lstatSync(path).isSocket()).toBe(true);+ // On Windows the stale AF_UNIX reparse point is exactly what lstat cannot read (#5312); the probe below is the witness there.+ if (posix) expect(lstatSync(path).isSocket()).toBe(true);}+/** True when something accepts a connection on `path` (the Windows-safe witness for "the endpoint is still there"). */+function accepts(path: string): Promise<boolean> {+ return new Promise(resolve => {+ const c = net.connect(path, () => { c.destroy(); resolve(true); });+ c.on('error', () => resolve(false));+ });+}++/**+ * The sweep's `fs.lstatSync(path)` throws `code` (what Bun reports for a stale Windows AF_UNIX reparse point); every+ * other caller and path is real. Call-site scoped on purpose: on Windows the probe (`probeSocketOwner`) is a plain+ * connect and never lstat's, while on POSIX `unixSocketProbeState` lstat's the same path and would read a blanket+ * failure as "unknown owner" (kept as `live_listener`), which is the POSIX contract but not the Windows path under test.+ */+function withUnreadable(path: string, code: string, fn: () => Promise<void>): Promise<void> {+ const original = fs.lstatSync;+ const probe = spyOn(fs, 'lstatSync').mockImplementation(((p: fs.PathLike, opts?: unknown) => {+ // The nearest production frame decides: the sweep's own entryStat, not ipc-path's probe state further down the chain.+ const caller = (new Error().stack ?? '').split('\n').find(line => line.includes('/src/core/')) ?? '';+ if (String(p) === path && caller.includes('runtime-artefacts.ts')) {+ throw Object.assign(new Error(`${code}: permission denied, lstat '${path}'`), { code, syscall: 'lstat', path });+ }+ return original(p, opts as never);+ }) as typeof fs.lstatSync);+ return fn().finally(() => probe.mockRestore());+}++afterEach(() => { for (const name of readdirSync(dataDir)) if (name === '.operator-tap.fifo' || name === '.gbrain-persistence.sock' || name === '.gbrain-resolve.sock') { try { unlinkSync(join(dataDir, name)); } catch { /* already gone */ } } });+/** Byte-level fingerprint of the regular files in the data dir top level plus the entry names: the "source intact" witness. */function dataDirFingerprint(): string {const hash = createHash('sha256');@@ -153,3 +192,120 @@ test.if(posix)('a dump failure leaves the data dir intact and the next backup ofexpect(manifest.entries.map(e => e.path)).toContain('database.tar');expect(statSync(output).size).toBeGreaterThan(0);});++// ---- #5312 Windows half, Linux-injected classification path (the native claim is the windows-latest row) ----++test.if(posix)('an owned socket the runtime cannot lstat is probed, claimed and, with no native remover, kept as unreadable (never unlinked); the dump refusal names it', async () => {+ const socket = join(dataDir, '.gbrain-persistence.sock');+ await leaveStaleSocket(socket);+ const before = dataDirFingerprint();+ await withUnreadable(socket, 'EACCES', async () => {+ const sweep = await sweepStaleRuntimeArtefacts(dataDir);+ expect(sweep.removed).toEqual([]);+ expect(sweep.kept).toEqual([{ path: socket, reason: 'unreadable' }]);+ const failure = await backupFailure();+ expect(failure.code).toBe('backup_dump_failed');+ expect(failure.message).toContain(socket);+ expect(failure.message).toContain('cannot inspect');+ });+ // The entry is untouched: still a socket, nothing else in the data dir changed.+ expect(lstatSync(socket).isSocket()).toBe(true);+ expect(dataDirFingerprint()).toBe(before);+ unlinkSync(socket);+});++test.if(posix)('an owned socket the runtime cannot lstat but something listens on is kept as live_listener and stays connectable', async () => {+ const socket = join(dataDir, '.gbrain-resolve.sock');+ const server = net.createServer();+ await new Promise<void>(resolve => server.listen(socket, () => resolve()));+ try {+ await withUnreadable(socket, 'EACCES', async () => {+ const sweep = await sweepStaleRuntimeArtefacts(dataDir);+ expect(sweep.removed).toEqual([]);+ expect(sweep.kept).toEqual([{ path: socket, reason: 'live_listener' }]);+ });+ expect(await accepts(socket)).toBe(true);+ } finally { await new Promise(resolve => server.close(resolve)); }+});++test.if(posix)('a foreign entry the runtime cannot lstat is kept as unreadable instead of failing the sweep', async () => {+ const fifo = join(dataDir, '.operator-tap.fifo');+ execFileSync('mkfifo', [fifo]);+ try {+ await withUnreadable(fifo, 'EPERM', async () => {+ const sweep = await sweepStaleRuntimeArtefacts(dataDir);+ expect(sweep.removed).toEqual([]);+ expect(sweep.kept).toEqual([{ path: fifo, reason: 'unreadable' }]);+ });+ expect(lstatSync(fifo).isFIFO()).toBe(true);+ } finally { unlinkSync(fifo); }+});++test.if(posix)('an lstat failure that is not an access or reparse-point class still fails the sweep (EIO is a real I/O fault)', async () => {+ const socket = join(dataDir, '.gbrain-persistence.sock');+ await leaveStaleSocket(socket);+ try {+ await withUnreadable(socket, 'EIO', async () => {+ await expect(sweepStaleRuntimeArtefacts(dataDir)).rejects.toMatchObject({ code: 'EIO' });+ });+ } finally { unlinkSync(socket); }+});++test('a regular file where a gbrain socket is expected is kept as not_a_socket and never removed (every platform)', async () => {+ const path = join(dataDir, '.gbrain-persistence.sock');+ writeFileSync(path, 'not a socket\n');+ try {+ const sweep = await sweepStaleRuntimeArtefacts(dataDir);+ expect(sweep.removed).toEqual([]);+ expect(sweep.kept).toEqual([{ path, reason: 'not_a_socket' }]);+ expect(readFileSync(path, 'utf8')).toBe('not a socket\n');+ } finally { unlinkSync(path); }+});++// ---- native Windows row (test.yml windows-latest, `native_only` dispatch): the stale AF_UNIX reparse point itself ----++test.if(windows)('Windows: a stale gbrain socket from a killed child is removed through the native tag check, omitted names it and the dump succeeds', async () => {+ const socket = resolveSocketPathForConfig({ engine: 'pglite', database_path: dataDir }, 'persistence')!;+ await leaveStaleSocket(socket);+ expect(await accepts(socket)).toBe(false); // dead holder: the probe connect is refused+ const output = nextOutput();+ const { manifest } = await createPgliteBackup({ output, root });+ expect(statSync(output).size).toBeGreaterThan(0);+ expect(manifest.entries.map(e => e.path)).toContain('database.tar');+ expect((manifest as unknown as { omitted: string[] }).omitted).toContain(`Removed stale runtime socket left by an exited gbrain process: ${socket}`);+ // Removed: a fresh listener can bind the same path again.+ const server = net.createServer();+ await new Promise<void>((resolve, reject) => { server.on('error', reject); server.listen(socket, () => resolve()); });+ await new Promise(resolve => server.close(resolve));+});++test.if(windows)('Windows: a live listener on a gbrain socket is kept, still accepts a connection and the dump refuses naming it', async () => {+ const socket = join(dataDir, '.gbrain-resolve.sock');+ const server = net.createServer();+ await new Promise<void>(resolve => server.listen(socket, () => resolve()));+ try {+ const sweep = await sweepStaleRuntimeArtefacts(dataDir);+ expect(sweep.removed).toEqual([]);+ expect(sweep.kept).toEqual([{ path: socket, reason: 'live_listener' }]);+ const failure = await backupFailure();+ expect(failure.code).toBe('backup_dump_failed');+ expect(failure.message).toContain(socket);+ expect(await accepts(socket)).toBe(true);+ } finally { await new Promise(resolve => server.close(resolve)); }+});++test.if(windows)('Windows: a directory junction where a gbrain socket is expected is not an AF_UNIX socket: kept, never removed, its target intact', async () => {+ const target = join(temporary, 'junction-target');+ mkdirSync(target, { recursive: true });+ writeFileSync(join(target, 'keep.txt'), 'keep');+ const link = join(dataDir, '.gbrain-persistence.sock');+ symlinkSync(target, link, 'junction');+ try {+ const sweep = await sweepStaleRuntimeArtefacts(dataDir);+ expect(sweep.removed).toEqual([]);+ expect(sweep.kept.map(k => k.path)).toEqual([link]);+ expect(['symlink', 'unreadable']).toContain(sweep.kept[0]!.reason);+ expect(readFileSync(join(target, 'keep.txt'), 'utf8')).toBe('keep');+ expect(existsSync(link)).toBe(true);+ } finally { rmSync(link, { recursive: false, force: true }); }+});