Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(windows): route every durable flush through src/core/fs-durable.ts (#5595, #5475)

garrytan5c40fd812b4c
diff --git a/src/commands/extract-attendance-repair.ts b/src/commands/extract-attendance-repair.ts
index a3576572e3..0a5dd7b398 100644
--- a/src/commands/extract-attendance-repair.ts
+++ b/src/commands/extract-attendance-repair.ts
@@ -6,6 +6,7 @@ import type { BrainEngine } from '../core/engine.ts';
import type { EngineConfig } from '../core/types.ts';
import { loadConfig, isThinClient, toEngineConfig } from '../core/config.ts';
import { createEngine } from '../core/engine-factory.ts';
+import { flushDirectory } from '../core/fs-durable.ts';
import { resolveBrainId } from '../core/brain-resolver.ts';
import { loadMounts } from '../core/brain-registry.ts';
import { readRepairSidecar } from '../core/pglite-repair.ts';
@@ -146,8 +147,7 @@ export async function runAttendanceRepair(engine: BrainEngine, args: string[], a
finally { closeSync(fd); }
try { renameSync(temporary, checkpoint); }
catch (error) { unlinkSync(temporary); throw error; }
- const directory = openSync(dirname(checkpoint), constants.O_RDONLY);
- try { fsyncSync(directory); } finally { closeSync(directory); }
+ flushDirectory(dirname(checkpoint));
} });
process.stdout.write(JSON.stringify({ digest: preview.digest, ...result }) + '\n');
return result;
diff --git a/src/commands/source-reconcile.ts b/src/commands/source-reconcile.ts
index 3a2f10be57..20b27ffde3 100644
--- a/src/commands/source-reconcile.ts
+++ b/src/commands/source-reconcile.ts
@@ -3,6 +3,7 @@ import { closeSync, constants, fstatSync, fsyncSync, linkSync, lstatSync, openSy
import { basename, dirname, join, resolve } from 'node:path';
import type { BrainEngine } from '../core/engine.ts';
import { getCliOptions } from '../core/cli-options.ts';
+import { flushDirectory } from '../core/fs-durable.ts';
import { finishCliTeardown, setCliExitVerdict, writeStdoutFinal } from '../core/cli-force-exit.ts';
import { isThinClient, loadConfig, toEngineConfig } from '../core/config.ts';
import { loadMounts } from '../core/brain-registry.ts';
@@ -158,10 +159,7 @@ export function writeReconcilePreview(path: string, preview: unknown): void {
fd = undefined;
assertManagedFilesystemWrite(target);
linkSync(temporary, target);
- if (process.platform !== 'win32') {
- const directoryFd = openSync(directory, constants.O_RDONLY);
- try { fsyncSync(directoryFd); } finally { closeSync(directoryFd); }
- }
+ flushDirectory(directory);
} catch (error) {
if (error instanceof OperationError) throw error;
throw new OperationError('storage_error', 'Cannot create the private preview file. Use an existing directory outside the canonical worktree and a new filename.');
diff --git a/src/core/agent-install/state.ts b/src/core/agent-install/state.ts
index 9caaaf3509..a5c94be82a 100644
--- a/src/core/agent-install/state.ts
+++ b/src/core/agent-install/state.ts
@@ -3,6 +3,7 @@ import { createHash, randomUUID } from 'node:crypto';
import { closeSync, existsSync, fsyncSync, lstatSync, mkdirSync, openSync, readFileSync, renameSync, unlinkSync, writeFileSync } from 'node:fs';
import { dirname, isAbsolute, join, resolve, sep } from 'node:path';
import type { GBrainConfig } from '../config.ts';
+import { flushDirectory } from '../fs-durable.ts';
import { shouldDropAgentEnv } from './environment.ts';
import { shellQuote } from '../mcp-registration.ts';
import type { LocalSharedSkillsResult } from './shared-skills.ts';
@@ -103,18 +104,7 @@ export function confinedPath(root: string, relative: string): string {
return target;
}
-export function syncDirectory(path: string): void {
- let fd: number | undefined;
- try {
- fd = openSync(path, 'r');
- fsyncSync(fd);
- } catch (error) {
- const code = (error as NodeJS.ErrnoException).code;
- if (!(process.platform === 'win32' && ['EISDIR', 'EPERM', 'EINVAL', 'ENOTSUP'].includes(code ?? ''))) throw error;
- } finally {
- if (fd !== undefined) closeSync(fd);
- }
-}
+export { flushDirectory as syncDirectory } from '../fs-durable.ts';
export function privateWrite(path: string, contents: string | Uint8Array, mode = 0o600): void {
assertNoSymlinks(path);
@@ -127,7 +117,7 @@ export function privateWrite(path: string, contents: string | Uint8Array, mode =
fsyncSync(fd);
closeSync(fd); fd = undefined;
renameSync(tmp, path);
- syncDirectory(dirname(path));
+ flushDirectory(dirname(path));
} catch (error) {
if (fd !== undefined) closeSync(fd);
try { unlinkSync(tmp); } catch { /* no temporary file after a failed write */ }
diff --git a/src/core/atomic-write.ts b/src/core/atomic-write.ts
index 56d4a8bb4f..b89c5a0850 100644
--- a/src/core/atomic-write.ts
+++ b/src/core/atomic-write.ts
@@ -36,6 +36,7 @@ import {
import { randomBytes, randomUUID } from 'crypto';
import { dirname, isAbsolute, join, relative, resolve, sep } from 'path';
import { assertManagedFilesystemWrite } from './persistence/filesystem-guard.ts';
+import { flushDirectory } from './fs-durable.ts';
export interface AtomicWriteOpts {
/** Preallocated by a durable recovery journal before any filesystem sink. */
@@ -157,15 +158,9 @@ export function atomicWriteFileSync(filePath: string, content: string | Uint8Arr
renameSync(tmpPath, filePath);
// Durability of the RENAME itself: fsync the parent directory so a power
// loss can't silently drop the new directory entry (the target is never
- // corrupt either way — this closes the write-vanished window). Dir fsync
- // is unsupported on some platforms; best-effort by design.
- try {
- const dfd = openSync(dirname(filePath), 'r');
- try { fsyncSync(dfd); } finally { closeSync(dfd); }
- } catch (error) {
- const code = (error as NodeJS.ErrnoException).code;
- if (opts?.durable && !(process.platform === 'win32' && ['EISDIR', 'EPERM', 'EINVAL', 'ENOTSUP'].includes(code ?? ''))) throw error;
- }
+ // corrupt either way — this closes the write-vanished window). Journaled
+ // publication (`durable`) needs it; other writers keep it best-effort.
+ flushDirectory(dirname(filePath), { bestEffort: !opts?.durable });
} catch (err) {
try {
// A failed exclusive create owns nothing. A callback or another process
diff --git a/src/core/fs-durable.ts b/src/core/fs-durable.ts
new file mode 100644
index 0000000000..f700f51ac8
--- /dev/null
+++ b/src/core/fs-durable.ts
@@ -0,0 +1,74 @@
+/**
+ * Durable flush primitives for every canonical and private-state writer.
+ *
+ * The POSIX idiom `fsync(open(path, 'r'))` does not port: Windows
+ * `FlushFileBuffers` needs a handle with write access (a read-only handle
+ * fails with EPERM, #5595), and Windows cannot open a directory through the
+ * file-descriptor API at all (#5475). A writer that still holds the
+ * descriptor it wrote through sets the final mode with `fchmodSync(fd)` and
+ * fsyncs that descriptor before closing it (atomic-write.ts); these helpers
+ * cover the paths that have no descriptor. scripts/check-durable-flush.ts
+ * fails on an fsyncSync of a read-only descriptor anywhere else in src/.
+ */
+import { closeSync, fstatSync, fsyncSync, openSync, statSync } from 'node:fs';
+
+/** Errors Windows returns where it has no directory flush; the rename is already durable there. */
+const WIN32_NO_DIRECTORY_FLUSH = new Set(['EISDIR', 'EPERM', 'EINVAL', 'ENOTSUP']);
+
+const errorCode = (error: unknown): string => (error as NodeJS.ErrnoException)?.code ?? '';
+
+/**
+ * fsync a file nobody holds open. Windows needs a writable handle (`'r+'`);
+ * elsewhere `'r'` keeps a read-only (0444) file flushable. A read-only file on
+ * Windows cannot be opened writable at all, so its flush is left to the
+ * operating system rather than failing the caller.
+ */
+export function flushFile(path: string): void {
+ const win32 = process.platform === 'win32';
+ let fd: number;
+ try {
+ fd = openSync(path, win32 ? 'r+' : 'r');
+ } catch (error) {
+ if (win32 && ['EPERM', 'EACCES'].includes(errorCode(error)) && (statSync(path).mode & 0o200) === 0) return;
+ throw error;
+ }
+ try { fsyncSync(fd); } finally { closeSync(fd); }
+}
+
+export interface DirectoryFlushOptions {
+ /** Swallow every error: for callers whose directory flush is advisory, not part of their durability contract. */
+ bestEffort?: boolean;
+}
+
+/**
+ * fsync a directory so a create, rename or unlink inside it survives power
+ * loss. Strict by default: every error propagates except the Windows codes
+ * that mean the platform has no directory flush. A path that is not a
+ * directory fails with ENOTDIR instead of silently flushing a file.
+ */
+export function flushDirectory(path: string, options: DirectoryFlushOptions = {}): void {
+ let fd: number | undefined;
+ try {
+ fd = openSync(path, 'r');
+ if (!fstatSync(fd).isDirectory()) {
+ throw Object.assign(new Error(`ENOTDIR: not a directory, fsync '${path}'`), { code: 'ENOTDIR', syscall: 'fsync', path });
+ }
+ fsyncSync(fd);
+ } catch (error) {
+ if (options.bestEffort) return;
+ if (process.platform === 'win32' && WIN32_NO_DIRECTORY_FLUSH.has(errorCode(error))) return;
+ throw error;
+ } finally {
+ if (fd !== undefined) closeSync(fd);
+ }
+}
+
+/**
+ * Whether a file's observed permission bits match the mode it was published
+ * with. Windows keeps only a read-only attribute, which stat reports as 0444
+ * or 0666, so only the owner write bit is comparable there.
+ */
+export function sameFileMode(actual: number, expected: number): boolean {
+ if (process.platform === 'win32') return (actual & 0o200) === (expected & 0o200);
+ return (actual & 0o7777) === (expected & 0o7777);
+}
diff --git a/src/core/persistence/bundle-files.ts b/src/core/persistence/bundle-files.ts
index d190139926..110c6f8bb9 100644
--- a/src/core/persistence/bundle-files.ts
+++ b/src/core/persistence/bundle-files.ts
@@ -1,5 +1,6 @@
-import { chmodSync, closeSync, constants, fstatSync, fsyncSync, lstatSync, mkdirSync, openSync, readSync, realpathSync, renameSync, unlinkSync, writeSync } from 'node:fs';
+import { closeSync, constants, fchmodSync, fstatSync, fsyncSync, lstatSync, mkdirSync, openSync, readSync, realpathSync, renameSync, unlinkSync, writeSync } from 'node:fs';
import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
+import { flushDirectory, sameFileMode } from '../fs-durable.ts';
import { OperationError } from '../ops/contract.ts';
import { sha256 } from './digest.ts';
import type { BundleRecoveryRecord, FileRecoveryRecord, WriteRequest } from './model.ts';
@@ -125,22 +126,17 @@ export function bundleFileHash(record: FileRecoveryRecord): string | null {
const current = readBundleFile(record.path, record.root);
const hash = current ? sha256(current.bytes) : null;
const expectedMode = hash === record.beforeHash ? record.mode : record.afterMode ?? record.mode;
- if (current && expectedMode !== null && current.mode !== expectedMode) throw new OperationError('unexpected_file_bytes', 'A canonical skill file mode changed outside publication.');
+ if (current && expectedMode !== null && !sameFileMode(current.mode, expectedMode)) throw new OperationError('unexpected_file_bytes', 'A canonical skill file mode changed outside publication.');
return hash;
}
-function flushBundleDirectory(directory: string): void {
- const fd = openSync(directory, 'r');
- try { fsyncSync(fd); } finally { closeSync(fd); }
-}
-
export function stageBundleFile(file: MutationFile, record: FileRecoveryRecord): void {
if (file.content === null) return;
readBundleFile(file.path, file.root);
let parent = file.root;
for (const part of relative(file.root, dirname(file.path)).split(sep).filter(Boolean)) {
const next = join(parent, part);
- try { mkdirSync(next); flushBundleDirectory(parent); }
+ try { mkdirSync(next); flushDirectory(parent); }
catch (error) { if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error; }
const info = lstatSync(next);
if (!info.isDirectory() || info.isSymbolicLink()) throw unsafe();
@@ -159,10 +155,10 @@ export function stageBundleFile(file: MutationFile, record: FileRecoveryRecord):
offset += written;
}
const mode = record.afterMode ?? record.mode;
- if (mode !== null) chmodSync(stage.path, mode);
+ if (mode !== null) fchmodSync(fd, mode);
fsyncSync(fd);
} finally { closeSync(fd); }
- flushBundleDirectory(parent);
+ flushDirectory(parent);
}
export function publishStagedBundleFile(record: FileRecoveryRecord, boundary?: (phase: 'file_replaced' | 'directory_flushed') => void): void {
@@ -174,11 +170,12 @@ export function publishStagedBundleFile(record: FileRecoveryRecord, boundary?: (
const stage = record.staging?.publication;
if (!stage) throw unsafe();
const staged = readBundleFile(stage.path, record.root);
+ const mode = record.afterMode ?? record.mode;
if (!staged || staged.bytes.byteLength !== stage.bytes || sha256(staged.bytes) !== stage.hash
- || stage.hash !== record.afterHash || staged.mode !== (record.afterMode ?? record.mode)) throw unsafe();
+ || stage.hash !== record.afterHash || mode === null || !sameFileMode(staged.mode, mode)) throw unsafe();
renameSync(stage.path, record.path);
}
boundary?.('file_replaced');
- flushBundleDirectory(dirname(record.path));
+ flushDirectory(dirname(record.path));
boundary?.('directory_flushed');
}
diff --git a/src/core/persistence/coordinator.ts b/src/core/persistence/coordinator.ts
index 16d7763ea2..44be8a965e 100644
--- a/src/core/persistence/coordinator.ts
+++ b/src/core/persistence/coordinator.ts
@@ -1,8 +1,9 @@
-import { chmodSync, existsSync, mkdirSync, readFileSync, statSync, unlinkSync, openSync, fsyncSync, closeSync } from 'node:fs';
+import { existsSync, mkdirSync, readFileSync, statSync, unlinkSync } from 'node:fs';
import { dirname } from 'node:path';
import type { BrainEngine } from '../engine.ts';
import { OperationError } from '../ops/contract.ts';
import { atomicWriteFileSync, mkdirPrivate } from '../atomic-write.ts';
+import { flushDirectory } from '../fs-durable.ts';
import { isWriteTargetContained } from '../path-confine.ts';
import { sha256 } from './digest.ts';
import { authorizeStoredRequest } from './authority.ts';
@@ -53,16 +54,6 @@ export interface PublicationHooks {
| 'before_restore' | 'restoration_staging_flushed' | 'restoration_file_replaced' | 'restoration_directory_flushed' | 'after_restore', request: WriteRequest, index: number): void;
}
function fileHash(path: string): string | null { return existsSync(path) ? sha256(readFileSync(path)) : null; }
-function flushDirectory(path: string): void {
- let fd: number | undefined;
- try { fd = openSync(dirname(path), 'r'); fsyncSync(fd); }
- catch (error) {
- const code = (error as NodeJS.ErrnoException).code;
- // Windows cannot open a directory through Node's file descriptor API.
- // Its atomic replacement is handled by the platform filesystem primitive.
- if (!(process.platform === 'win32' && ['EISDIR','EPERM','EINVAL','ENOTSUP'].includes(code ?? ''))) throw error;
- } finally { if (fd !== undefined) closeSync(fd); }
-}
function publishFile(file: PageMutationFile, stagingPath?: string, afterStagingFlush?: () => void, mode?: number | null): void {
if (!isWriteTargetContained(file.path, file.root)) throw new OperationError('storage_error', 'Canonical file target escapes its source root.');
if (file.publishMode === undefined) mkdirSync(dirname(file.path), { recursive: true });
@@ -71,15 +62,8 @@ function publishFile(file: PageMutationFile, stagingPath?: string, afterStagingF
const openMode = mode ?? file.publishMode;
if (file.content === null) {
try { unlinkSync(file.path); } catch (error) { if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error; }
- } else atomicWriteFileSync(file.path, file.content, { durable: true, stagingPath, ...(openMode === undefined ? {} : { mode: openMode }), afterStagingFlush: () => {
- afterStagingFlush?.();
- if (mode !== undefined && mode !== null && stagingPath) {
- chmodSync(stagingPath, mode);
- const fd = openSync(stagingPath, 'r');
- try { fsyncSync(fd); } finally { closeSync(fd); }
- }
- } });
- flushDirectory(file.path);
+ } else atomicWriteFileSync(file.path, file.content, { durable: true, stagingPath, ...(openMode === undefined ? {} : { mode: openMode }), afterStagingFlush });
+ flushDirectory(dirname(file.path));
}
// Effect recovery uses the same confined durable publication primitive, under
// its own recovery record and native root capability.
diff --git a/src/core/persistence/identity.ts b/src/core/persistence/identity.ts
index 96fa50dded..0f0625a673 100644
--- a/src/core/persistence/identity.ts
+++ b/src/core/persistence/identity.ts
@@ -4,6 +4,7 @@ import { closeSync, existsSync, mkdirSync, openSync, readFileSync, writeFileSync
import { join } from 'node:path';
import type { BrainEngine } from '../engine.ts';
import { configDir } from '../config.ts';
+import { flushDirectory } from '../fs-durable.ts';
import { OperationError } from '../ops/contract.ts';
import { sha256 } from './digest.ts';
import type { Principal, SqlEngine } from './model.ts';
@@ -23,14 +24,6 @@ export async function withVerifiedLocalRegistration<T>(engine: SqlEngine, regist
const defaultGrant = (): LocalGrant => ({ sourceIds: ['*'], operations: null, scopes: ['read', 'write'], slugPrefixes: null });
export function persistenceHome(): string { return join(configDir(), 'persistence'); }
-function flushRegistrationDirectory(): void {
- let fd: number | undefined;
- try { fd = openSync(persistenceHome(), 'r'); fsyncSync(fd); }
- catch (error) {
- if (!(process.platform === 'win32' && ['EISDIR', 'EPERM', 'EINVAL', 'ENOTSUP'].includes((error as NodeJS.ErrnoException).code ?? ''))) throw error;
- } finally { if (fd !== undefined) closeSync(fd); }
-}
-
/** Exclusive create keeps simultaneous installations on one identity without replacing it. */
function privateJson<T>(path: string, create: () => T): T {
if (existsSync(path)) return JSON.parse(readFileSync(path, 'utf8')) as T;
@@ -98,7 +91,7 @@ async function rotateLocalWriter(engine: BrainEngine, lane: 'cli' | 'stdio', gra
const pending = `${path}.pending.${next.id}`;
const fd = openSync(pending, 'wx', 0o600);
try { writeFileSync(fd, JSON.stringify(next)); fsyncSync(fd); } finally { closeSync(fd); }
- flushRegistrationDirectory();
+ flushDirectory(persistenceHome());
let durable = false;
try {
await engine.transaction(async tx => {
@@ -114,7 +107,7 @@ async function rotateLocalWriter(engine: BrainEngine, lane: 'cli' | 'stdio', gra
durable = true;
linkSync(path, `${path}.revoked.${next.id}`);
renameSync(pending, path); // readers always see one complete credential document
- flushRegistrationDirectory();
+ flushDirectory(persistenceHome());
return next;
} catch (error) {
if (!durable) unlinkSync(pending);
diff --git a/src/core/persistence/physical-root-record.ts b/src/core/persistence/physical-root-record.ts
index 811e487136..bb1db4fbe9 100644
--- a/src/core/persistence/physical-root-record.ts
+++ b/src/core/persistence/physical-root-record.ts
@@ -2,6 +2,7 @@ import { randomUUID } from 'node:crypto';
import { closeSync, constants, existsSync, fstatSync, fsyncSync, lstatSync, openSync, readdirSync, readFileSync, realpathSync, renameSync, statSync, unlinkSync, writeFileSync } from 'node:fs';
import { dirname, isAbsolute, join, relative, sep } from 'node:path';
import { OperationError } from '../ops/contract.ts';
+import { flushDirectory } from '../fs-durable.ts';
import { digest, sha256 } from './digest.ts';
import { canonicalFilesystemPath } from './root-registry.ts';
@@ -23,12 +24,6 @@ export function isPhysicalRootMetadata(name: string): boolean {
export function physicalRootReservationPath(root: string): string {
return join(dirname(root), `${RESERVATION_PREFIX}${sha256(root)}.json`);
}
-function flushDirectory(path: string): void {
- let fd: number | undefined;
- try { fd = openSync(path, 'r'); fsyncSync(fd); }
- catch (error) { if (!(process.platform === 'win32' && ['EISDIR','EPERM','EINVAL','ENOTSUP'].includes((error as NodeJS.ErrnoException).code ?? ''))) throw error; }
- finally { if (fd !== undefined) closeSync(fd); }
-}
function readPrivate(path: string): unknown | null {
let fd: number | undefined;
try {
diff --git a/src/core/persistence/reconcile-backup.ts b/src/core/persistence/reconcile-backup.ts
index 7a6a6ce150..2385447e1d 100644
--- a/src/core/persistence/reconcile-backup.ts
+++ b/src/core/persistence/reconcile-backup.ts
@@ -3,6 +3,7 @@ import { randomUUID } from 'node:crypto';
import { dirname, isAbsolute, join } from 'node:path';
import type { BrainEngine } from '../engine.ts';
import { configDir } from '../config.ts';
+import { flushDirectory } from '../fs-durable.ts';
import { OperationError } from '../ops/contract.ts';
import { canonicalFilesystemPath } from './root-registry.ts';
import { containsPath } from './ownership.ts';
@@ -37,13 +38,6 @@ function privateDirectory(path: string): void {
throw new OperationError('permission_denied', 'The reconciliation backup directory must be private, owned, and free of symlinks.');
}
}
-function flushDirectory(path: string): void {
- let fd: number | undefined;
- try { fd = openSync(path, 'r'); fsyncSync(fd); }
- catch (error) {
- if (!(process.platform === 'win32' && ['EISDIR', 'EPERM', 'EINVAL', 'ENOTSUP'].includes((error as NodeJS.ErrnoException).code ?? ''))) throw error;
- } finally { if (fd !== undefined) closeSync(fd); }
-}
export async function assertReconcileSize(engine: BrainEngine, artifact: ReconcileArtifact): Promise<void> {
const limits = await readJournalLimits(engine);
if (jsonBytes(artifact) + 65536 > Math.min(PERSISTENCE_IPC_MAX_BYTES, limits.principalIntentBytes, limits.brainIntentBytes, limits.worktreeRecoveryBytes, limits.brainRecoveryBytes)) {
diff --git a/src/core/persistence/root-registry.ts b/src/core/persistence/root-registry.ts
index ede940af63..3b6a139607 100644
--- a/src/core/persistence/root-registry.ts
+++ b/src/core/persistence/root-registry.ts
@@ -2,6 +2,7 @@ import { createHash, randomUUID } from 'node:crypto';
import { chmodSync, closeSync, existsSync, fsyncSync, lstatSync, mkdirSync, openSync, readdirSync, readFileSync, realpathSync, renameSync, statSync, unlinkSync, writeFileSync } from 'node:fs';
import { basename, dirname, isAbsolute, join, resolve } from 'node:path';
import { configDir } from '../config.ts';
+import { flushDirectory } from '../fs-durable.ts';
import { OperationError } from '../ops/contract.ts';
export interface ManagedRootRecord {
@@ -29,20 +30,13 @@ function enclosingGitMetadata(root: string): string | null {
current = parent;
}
}
-function syncDirectory(directory: string): void {
- let fd: number | undefined;
- try { fd = openSync(directory, 'r'); fsyncSync(fd); }
- catch (error) {
- if (!(process.platform === 'win32' && ['EISDIR', 'EPERM', 'EINVAL', 'ENOTSUP'].includes((error as NodeJS.ErrnoException).code ?? ''))) throw error;
- } finally { if (fd !== undefined) closeSync(fd); }
-}
/** Returns whether the record changed; a changed record is already durable with its directory entry. */
function writePrivateRecord(file: string, value: string): boolean {
if (existsSync(file) && readFileSync(file, 'utf8') === value) { chmodSync(file, 0o600); return false; }
const temporary = `${file}.${randomUUID()}.tmp`;
const fd = openSync(temporary, 'wx', 0o600);
try { writeFileSync(fd, value); fsyncSync(fd); } finally { closeSync(fd); }
- try { renameSync(temporary, file); syncDirectory(dirname(file)); }
+ try { renameSync(temporary, file); flushDirectory(dirname(file)); }
finally { try { unlinkSync(temporary); } catch (error) { if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error; } }
return true;
}
@@ -115,7 +109,7 @@ export function recordManagedRoots(brainId: string, records: ManagedRootRecord[]
if (!existsSync(marker)) writePrivateRecord(marker, JSON.stringify({ version: 1, managed: true, brain_id: brainId, ...(modeEpoch !== undefined ? { mode_epoch: modeEpoch } : {}) }));
}
}
- if (changed) syncDirectory(directory);
+ if (changed) flushDirectory(directory);
}
/** Available before connect, including while another process owns local PGLite. */
export function registeredManagedRoots(): string[] {
diff --git a/src/core/persistence/staging.ts b/src/core/persistence/staging.ts
index 1175387a17..f42478192d 100644
--- a/src/core/persistence/staging.ts
+++ b/src/core/persistence/staging.ts
@@ -1,6 +1,7 @@
-import { closeSync, constants, fstatSync, fsyncSync, lstatSync, openSync, readFileSync, unlinkSync } from 'node:fs';
+import { closeSync, constants, fstatSync, lstatSync, openSync, readFileSync, unlinkSync } from 'node:fs';
import { dirname } from 'node:path';
import { atomicStagingPath, validateAtomicStagingPath } from '../atomic-write.ts';
+import { flushDirectory } from '../fs-durable.ts';
import { isWriteTargetContained } from '../path-confine.ts';
import { OperationError } from '../ops/contract.ts';
import { sha256 } from './digest.ts';
@@ -38,21 +39,13 @@ function statIfPresent(path: string) {
}
}
function flushParent(path: string): void {
- let fd: number | undefined;
- try {
- fd = openSync(dirname(path), 'r');
- // Publication can fail because an ancestor is a file. Flush the directory
- // containing that ancestor, rather than treating fsync(file) as fsync(dir).
- if (!fstatSync(fd).isDirectory()) {
- closeSync(fd); fd = undefined;
- flushParent(dirname(path)); return;
- }
- fsyncSync(fd);
- }
+ try { flushDirectory(dirname(path)); }
catch (error) {
+ // Publication can fail because an ancestor is a file or missing. Flush the
+ // nearest existing directory, rather than treating fsync(file) as fsync(dir).
if (['ENOENT', 'ENOTDIR'].includes((error as NodeJS.ErrnoException).code ?? '') && dirname(path) !== path) { flushParent(dirname(path)); return; }
- if (!(process.platform === 'win32' && ['EISDIR','EPERM','EINVAL','ENOTSUP'].includes((error as NodeJS.ErrnoException).code ?? ''))) throw error;
- } finally { if (fd !== undefined) closeSync(fd); }
+ throw error;
+ }
}
/** Called under the owner lock. Partial/unknown stages are preserved, never guessed. */
diff --git a/src/core/persistence/topology-filesystem.ts b/src/core/persistence/topology-filesystem.ts
index aafc891761..bb1e45e5ae 100644
--- a/src/core/persistence/topology-filesystem.ts
+++ b/src/core/persistence/topology-filesystem.ts
@@ -1,17 +1,13 @@
import { spawn } from 'node:child_process';
-import { closeSync, existsSync, fsyncSync, lstatSync, mkdirSync, mkdtempSync, openSync, readdirSync, rmSync } from 'node:fs';
+import { existsSync, lstatSync, mkdirSync, mkdtempSync, readdirSync, rmSync } from 'node:fs';
import { lstat, readdir } from 'node:fs/promises';
import { join } from 'node:path';
+import { flushDirectory, flushFile } from '../fs-durable.ts';
import { OperationError } from '../ops/contract.ts';
import { durableSsrfFlags, GIT_ENV, GIT_SSRF_SUBCOMMAND_FLAGS, parseRemoteUrl } from '../git-remote.ts';
import { persistenceHome } from './identity.ts';
-export function flushTopologyDirectory(path:string):void{
- let fd:number|undefined;
- try{fd=openSync(path,'r');fsyncSync(fd);}
- catch(error){if(!(process.platform==='win32'&&['EISDIR','EPERM','EINVAL','ENOTSUP'].includes((error as NodeJS.ErrnoException).code??'')))throw error;}
- finally{if(fd!==undefined)closeSync(fd);}
-}
+export { flushDirectory as flushTopologyDirectory } from '../fs-durable.ts';
export function topologyDirectoryIdentity(path:string):{device:string;inode:string;birthNs:string}{
const info=lstatSync(path,{bigint:true});
if(!info.isDirectory()||info.isSymbolicLink())throw new OperationError('recovery_required','The staging directory was substituted.');
@@ -37,9 +33,9 @@ export function flushTopologyTree(root:string):void{
if(info.isSymbolicLink())throw new OperationError('writer_manifest_unsafe','Canonical checkout recovery refuses symbolic links.');
if(info.isDirectory()){
for(const entry of readdirSync(path))visit(join(path,entry));
- flushTopologyDirectory(path);
+ flushDirectory(path);
}else if(info.isFile()){
- const fd=openSync(path,'r');try{fsyncSync(fd);}finally{closeSync(fd);}
+ flushFile(path);
}
};
visit(root);
diff --git a/test/bundle-files-windows-5475.test.ts b/test/bundle-files-windows-5475.test.ts
new file mode 100644
index 0000000000..34b0ded037
--- /dev/null
+++ b/test/bundle-files-windows-5475.test.ts
@@ -0,0 +1,108 @@
+/**
+ * #5475 parts 2-3: shared-skill publication on Windows.
+ *
+ * 2. `flushBundleDirectory` fsynced a directory handle with no platform
+ * guard; Windows has no directory flush (EPERM), so every bundle stage
+ * and publication failed.
+ * 3. Bundle recovery compared POSIX permission bits exactly, but Windows
+ * stat only reports a read-only attribute (0444 or 0666), so a file
+ * published 0644 never matched and publication refused it as unsafe.
+ *
+ * Simulated cases run on every OS; the native case runs the real stage and
+ * publish unmodified, including on the windows-latest row of the
+ * security-regressions job. The packaged-pack `gbrain init` path is covered
+ * end to end by test/init-packaged-skills-native.test.ts.
+ */
+import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
+import { chmodSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, statSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { bundleFileHash, prepareBundleRecovery, publishStagedBundleFile, stageBundleFile, type MutationFile } from '../src/core/persistence/bundle-files.ts';
+import type { FileRecoveryRecord, WriteRequest } from '../src/core/persistence/model.ts';
+import type { WorktreeBinding } from '../src/core/persistence/ownership.ts';
+import { sha256 } from '../src/core/persistence/digest.ts';
+import { sameFileMode } from '../src/core/fs-durable.ts';
+import { simulateReadOnlyFsyncEperm, withPlatform } from './helpers/win32-flush-semantics.ts';
+
+let root: string;
+beforeEach(() => { root = realpathSync(mkdtempSync(join(tmpdir(), 'gbrain-5475-'))); });
+afterEach(() => rmSync(root, { recursive: true, force: true }));
+
+function plan(relative: string[], content: string, before?: { bytes: string; mode: number }): { file: MutationFile; record: FileRecoveryRecord } {
+ const path = join(root, ...relative);
+ if (before) {
+ mkdirSync(join(root, ...relative.slice(0, -1)), { recursive: true });
+ writeFileSync(path, before.bytes);
+ chmodSync(path, before.mode);
+ }
+ const file: MutationFile = { path, root, content, expectedBeforeHash: before ? sha256(before.bytes) : null };
+ const binding = { local_path: root, relative_path: '', owner_epoch: '1' } as WorktreeBinding;
+ const { record } = prepareBundleRecovery([file], binding, { execution_token: 'attempt-5475' } as WriteRequest);
+ return { file, record: record.files[0] };
+}
+
+describe('#5475 part 2: bundle directory flushes', () => {
+ test('a nested skill stages and publishes when directory handles cannot be fsynced (Windows semantics)', () => {
+ const { file, record } = plan(['skills', 'capture', 'SKILL.md'], '# capture\n');
+ const simulation = simulateReadOnlyFsyncEperm({ directories: true });
+ try {
+ withPlatform('win32', () => {
+ stageBundleFile(file, record);
+ publishStagedBundleFile(record);
+ });
+ } finally { simulation.restore(); }
+ expect(simulation.readOnlyFsyncs).toBeGreaterThan(0);
+ expect(readFileSync(file.path, 'utf8')).toBe('# capture\n');
+ });
+
+ test.skipIf(process.platform === 'win32')('the same directory flush failure still fails publication off Windows', () => {
+ const { file, record } = plan(['skills', 'capture', 'SKILL.md'], '# capture\n');
+ const simulation = simulateReadOnlyFsyncEperm({ directories: true });
+ try {
+ expect(() => stageBundleFile(file, record)).toThrow(expect.objectContaining({ code: 'EPERM' }));
+ } finally { simulation.restore(); }
+ });
+});
+
+describe('#5475 part 3: Windows reports only a read-only attribute', () => {
+ test('a canonical file published 0644 and reported 0666 still matches its recovery record', () => {
+ const { record } = plan(['skills', 'capture', 'SKILL.md'], '# new\n', { bytes: '# old\n', mode: 0o644 });
+ chmodSync(record.path, 0o666);
+ expect(withPlatform('win32', () => bundleFileHash(record))).toBe(sha256('# old\n'));
+ });
+
+ test('a staged file chmod-ed 0644 and reported 0666 publishes', () => {
+ const { file, record } = plan(['skills', 'capture', 'SKILL.md'], '# new\n', { bytes: '# old\n', mode: 0o644 });
+ stageBundleFile(file, record);
+ chmodSync(record.staging!.publication!.path, 0o666);
+ chmodSync(record.path, 0o666);
+ withPlatform('win32', () => publishStagedBundleFile(record));
+ expect(readFileSync(record.path, 'utf8')).toBe('# new\n');
+ });
+
+ test('a read-only flip outside publication is still refused on Windows', () => {
+ const { record } = plan(['skills', 'capture', 'SKILL.md'], '# new\n', { bytes: '# old\n', mode: 0o644 });
+ chmodSync(record.path, 0o444);
+ try {
+ expect(() => withPlatform('win32', () => bundleFileHash(record))).toThrow(expect.objectContaining({ code: 'unexpected_file_bytes' }));
+ } finally { chmodSync(record.path, 0o644); }
+ });
+
+ test.skipIf(process.platform === 'win32')('POSIX still refuses any permission change', () => {
+ const { record } = plan(['skills', 'capture', 'SKILL.md'], '# new\n', { bytes: '# old\n', mode: 0o644 });
+ chmodSync(record.path, 0o664);
+ expect(() => bundleFileHash(record)).toThrow(expect.objectContaining({ code: 'unexpected_file_bytes' }));
+ });
+});
+
+test('native: a nested skill stages, publishes and keeps the recorded mode on this platform', () => {
+ const { file, record } = plan(['skills', 'capture', 'SKILL.md'], '# new\n', { bytes: '# old\n', mode: 0o644 });
+ stageBundleFile(file, record);
+ publishStagedBundleFile(record);
+ expect(readFileSync(record.path, 'utf8')).toBe('# new\n');
+ expect(sameFileMode(statSync(record.path).mode, 0o644)).toBe(true);
+ const created = plan(['skills', 'fresh', 'nested', 'SKILL.md'], '# fresh\n');
+ stageBundleFile(created.file, created.record);
+ publishStagedBundleFile(created.record);
+ expect(readFileSync(created.file.path, 'utf8')).toBe('# fresh\n');
+});
diff --git a/test/fs-durable.test.ts b/test/fs-durable.test.ts
new file mode 100644
index 0000000000..a200ce1060
--- /dev/null
+++ b/test/fs-durable.test.ts
@@ -0,0 +1,135 @@
+/**
+ * src/core/fs-durable.ts: the shared flush helpers behind every canonical
+ * writer (#5595, #5475). Native cases run on every OS row of the
+ * security-regressions job, windows-latest included; the simulated win32
+ * cases make the platform branches discriminate on Linux and macOS.
+ */
+import { afterEach, beforeEach, describe, expect, spyOn, test } from 'bun:test';
+import * as fs from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { flushDirectory, flushFile, sameFileMode } from '../src/core/fs-durable.ts';
+import { simulateReadOnlyFsyncEperm, withPlatform } from './helpers/win32-flush-semantics.ts';
+
+let dir: string;
+beforeEach(() => { dir = fs.mkdtempSync(join(tmpdir(), 'gbrain-fs-durable-')); });
+afterEach(() => {
+ try { for (const name of fs.readdirSync(dir)) fs.chmodSync(join(dir, name), 0o644); } catch { /* best-effort before removal */ }
+ fs.rmSync(dir, { recursive: true, force: true });
+});
+const errno = (code: string) => Object.assign(new Error(`${code}: simulated`), { code });
+
+describe('native flushes on this platform', () => {
+ test('a directory and a regular file flush without error', () => {
+ const file = join(dir, 'page.md');
+ fs.writeFileSync(file, 'bytes');
+ expect(() => flushDirectory(dir)).not.toThrow();
+ expect(() => flushFile(file)).not.toThrow();
+ expect(fs.readFileSync(file, 'utf8')).toBe('bytes');
+ });
+
+ test('a read-only file stays flushable and keeps its mode', () => {
+ const file = join(dir, 'frozen.md');
+ fs.writeFileSync(file, 'frozen');
+ fs.chmodSync(file, 0o444);
+ expect(() => flushFile(file)).not.toThrow();
+ expect(sameFileMode(fs.statSync(file).mode, 0o444)).toBe(true);
+ expect(fs.readFileSync(file, 'utf8')).toBe('frozen');
+ });
+
+ test('a file passed as a directory fails with ENOTDIR instead of flushing the file', () => {
+ const file = join(dir, 'not-a-directory');
+ fs.writeFileSync(file, 'x');
+ expect(() => flushDirectory(file)).toThrow(expect.objectContaining({ code: 'ENOTDIR' }));
+ });
+
+ test('a missing directory fails strictly and is swallowed best-effort', () => {
+ const missing = join(dir, 'missing');
+ expect(() => flushDirectory(missing)).toThrow(expect.objectContaining({ code: 'ENOENT' }));
+ expect(() => flushDirectory(missing, { bestEffort: true })).not.toThrow();
+ });
+});
+
+describe('Windows flush contract (simulated on POSIX hosts)', () => {
+ test('flushFile flushes through a writable handle on win32, so a read-only-handle EPERM never fires', () => {
+ const file = join(dir, 'page.md');
+ fs.writeFileSync(file, 'bytes');
+ const simulation = simulateReadOnlyFsyncEperm();
+ try {
+ expect(() => withPlatform('win32', () => flushFile(file))).not.toThrow();
+ expect(simulation.readOnlyFsyncs).toBe(0);
+ } finally { simulation.restore(); }
+ });
+
+ test('a raw read-only-handle fsync is what fails under the simulation', () => {
+ const file = join(dir, 'page.md');
+ fs.writeFileSync(file, 'bytes');
+ const simulation = simulateReadOnlyFsyncEperm();
+ try {
+ const fd = fs.openSync(file, 'r');
+ try { expect(() => fs.fsyncSync(fd)).toThrow(expect.objectContaining({ code: 'EPERM' })); } finally { fs.closeSync(fd); }
+ } finally { simulation.restore(); }
+ });
+
+ test('flushFile leaves a read-only file to the OS on win32 instead of failing the writer', () => {
+ const file = join(dir, 'frozen.md');
+ fs.writeFileSync(file, 'frozen');
+ fs.chmodSync(file, 0o444);
+ const opened = spyOn(fs, 'openSync').mockImplementation(() => { throw errno('EPERM'); });
+ try { expect(() => withPlatform('win32', () => flushFile(file))).not.toThrow(); } finally { opened.mockRestore(); }
+ });
+
+ test('flushFile still fails on win32 when a writable file refuses a writable handle', () => {
+ const file = join(dir, 'locked.md');
+ fs.writeFileSync(file, 'locked');
+ const opened = spyOn(fs, 'openSync').mockImplementation(() => { throw errno('EPERM'); });
+ try { expect(() => withPlatform('win32', () => flushFile(file))).toThrow(expect.objectContaining({ code: 'EPERM' })); } finally { opened.mockRestore(); }
+ });
+
+ for (const code of ['EISDIR', 'EPERM', 'EINVAL', 'ENOTSUP']) {
+ test(`strict directory flush tolerates the win32 no-directory-flush code ${code}`, () => {
+ const opened = spyOn(fs, 'openSync').mockImplementation(() => { throw errno(code); });
+ try {
+ expect(() => withPlatform('win32', () => flushDirectory(dir))).not.toThrow();
+ expect(() => withPlatform('linux', () => flushDirectory(dir))).toThrow(expect.objectContaining({ code }));
+ } finally { opened.mockRestore(); }
+ });
+ }
+
+ test.skipIf(process.platform === 'win32')('a directory handle that cannot be fsynced is tolerated on win32 only', () => {
+ const simulation = simulateReadOnlyFsyncEperm({ directories: true });
+ try {
+ expect(() => withPlatform('win32', () => flushDirectory(dir))).not.toThrow();
+ expect(() => withPlatform('linux', () => flushDirectory(dir))).toThrow(expect.objectContaining({ code: 'EPERM' }));
+ } finally { simulation.restore(); }
+ });
+
+ test('strict directory flush surfaces real I/O failures on every platform; best-effort swallows them', () => {
+ const opened = spyOn(fs, 'openSync').mockImplementation(() => { throw errno('EIO'); });
+ try {
+ expect(() => withPlatform('linux', () => flushDirectory(dir))).toThrow(expect.objectContaining({ code: 'EIO' }));
+ expect(() => withPlatform('win32', () => flushDirectory(dir))).toThrow(expect.objectContaining({ code: 'EIO' }));
+ expect(() => flushDirectory(dir, { bestEffort: true })).not.toThrow();
+ } finally { opened.mockRestore(); }
+ });
+});
+
+describe('sameFileMode', () => {
+ test('POSIX compares every permission bit', () => {
+ withPlatform('linux', () => {
+ expect(sameFileMode(0o100644, 0o644)).toBe(true);
+ expect(sameFileMode(0o100666, 0o644)).toBe(false);
+ expect(sameFileMode(0o100600, 0o644)).toBe(false);
+ });
+ });
+
+ test('win32 compares only the owner write bit it can represent', () => {
+ withPlatform('win32', () => {
+ expect(sameFileMode(0o666, 0o644)).toBe(true);
+ expect(sameFileMode(0o666, 0o600)).toBe(true);
+ expect(sameFileMode(0o444, 0o444)).toBe(true);
+ expect(sameFileMode(0o444, 0o644)).toBe(false);
+ expect(sameFileMode(0o666, 0o444)).toBe(false);
+ });
+ });
+});
diff --git a/test/helpers/win32-flush-semantics.ts b/test/helpers/win32-flush-semantics.ts
new file mode 100644
index 0000000000..a2075a69f9
--- /dev/null
+++ b/test/helpers/win32-flush-semantics.ts
@@ -0,0 +1,43 @@
+/**
+ * Windows flush semantics on a POSIX test host (#5595, #5475).
+ *
+ * Windows `FlushFileBuffers` needs write access, so fsyncSync on a descriptor
+ * opened read-only fails with EPERM there. `simulateReadOnlyFsyncEperm` makes
+ * fsyncSync of a read-only regular-file descriptor fail the same way, so a
+ * regression that flushes through an `'r'` handle fails on Linux and macOS
+ * too. `withPlatform` reports another `process.platform` around pure
+ * filesystem code (never around native locks or engines). Native behaviour is
+ * proven by the same suites on the windows-latest security-regressions row.
+ */
+import { spyOn } from 'bun:test';
+import * as fs from 'node:fs';
+
+export interface FlushSimulation { readOnlyFsyncs: number; restore(): void }
+
+export function simulateReadOnlyFsyncEperm(options: { directories?: boolean } = {}): FlushSimulation {
+ const readOnly = new Set<number>();
+ const open = fs.openSync, close = fs.closeSync, fsync = fs.fsyncSync, fstat = fs.fstatSync;
+ const simulation: FlushSimulation = { readOnlyFsyncs: 0, restore: () => {} };
+ const opened = spyOn(fs, 'openSync').mockImplementation(((path: fs.PathLike, flags: fs.OpenMode = 'r', mode?: fs.Mode | null) => {
+ const fd = open(path, flags, mode);
+ const writable = typeof flags === 'number' ? (flags & (fs.constants.O_WRONLY | fs.constants.O_RDWR)) !== 0 : /[wa+]/.test(flags);
+ if (writable) readOnly.delete(fd); else readOnly.add(fd);
+ return fd;
+ }) as typeof fs.openSync);
+ const closed = spyOn(fs, 'closeSync').mockImplementation(fd => { readOnly.delete(fd); close(fd); });
+ const synced = spyOn(fs, 'fsyncSync').mockImplementation(fd => {
+ if (readOnly.has(fd) && (options.directories || !fstat(fd).isDirectory())) {
+ simulation.readOnlyFsyncs++;
+ throw Object.assign(new Error('EPERM: operation not permitted, fsync'), { code: 'EPERM', syscall: 'fsync' });
+ }
+ fsync(fd);
+ });
+ simulation.restore = () => { opened.mockRestore(); closed.mockRestore(); synced.mockRestore(); };
+ return simulation;
+}
+
+export function withPlatform<T>(platform: NodeJS.Platform, run: () => T): T {
+ const descriptor = Object.getOwnPropertyDescriptor(process, 'platform')!;
+ Object.defineProperty(process, 'platform', { ...descriptor, value: platform });
+ try { return run(); } finally { Object.defineProperty(process, 'platform', descriptor); }
+}
diff --git a/test/init-packaged-skills-native.test.ts b/test/init-packaged-skills-native.test.ts
new file mode 100644
index 0000000000..deb1ea061d
--- /dev/null
+++ b/test/init-packaged-skills-native.test.ts
@@ -0,0 +1,37 @@
+/**
+ * #5475 end to end: a fresh `gbrain init --pglite` publishes the packaged
+ * memory skills through the canonical skill-bundle journal. On Windows the
+ * unguarded bundle directory flush and the exact POSIX mode compare failed
+ * this step ("Skill publication requires bounded regular files ..."), so
+ * init never completed. Runs natively on every OS row of the
+ * security-regressions job, windows-latest included.
+ */
+import { afterAll, expect, test } from 'bun:test';
+import { spawnSync } from 'node:child_process';
+import { mkdtempSync, readdirSync, rmSync, statSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+
+const home = mkdtempSync(join(tmpdir(), 'gbrain-init-skills-'));
+afterAll(() => rmSync(home, { recursive: true, force: true }));
+
+function skillFiles(dir: string): string[] {
+ const found: string[] = [];
+ for (const name of readdirSync(dir)) {
+ const path = join(dir, name);
+ if (statSync(path).isDirectory()) found.push(...skillFiles(path));
+ else if (name === 'SKILL.md') found.push(path);
+ }
+ return found;
+}
+
+test('fresh PGLite init publishes the packaged memory skills on this platform', () => {
+ const env: NodeJS.ProcessEnv = { ...process.env, GBRAIN_HOME: home };
+ for (const key of ['OPENAI_API_KEY', 'ANTHROPIC_API_KEY', 'VOYAGE_API_KEY', 'DATABASE_URL', 'GBRAIN_DATABASE_URL']) delete env[key];
+ const result = spawnSync(process.execPath, ['run', join(import.meta.dir, '..', 'src', 'cli.ts'), 'init', '--pglite', '--non-interactive', '--no-embedding'],
+ { env, encoding: 'utf8', timeout: 120_000 });
+ expect(`${result.stderr}`).not.toContain('Skill publication requires bounded regular files');
+ expect(result.status).toBe(0);
+ const skills = skillFiles(join(home, '.gbrain', 'content')).map(path => path.split(/[\\/]/).at(-2)).sort();
+ expect(skills).toEqual(expect.arrayContaining(['memory-recall']));
+}, 150_000);
diff --git a/test/persistence-windows-flush-5595.test.ts b/test/persistence-windows-flush-5595.test.ts
new file mode 100644
index 0000000000..7f62a50f8e
--- /dev/null
+++ b/test/persistence-windows-flush-5595.test.ts
@@ -0,0 +1,132 @@
+/**
+ * #5595 item 1: restoring a canonical page during publication recovery
+ * reapplied the recorded mode with a path chmod and then fsynced the staged
+ * file through a read-only handle. Windows refuses that flush (EPERM), so the
+ * recovery failed on every retry and the serial worktree queue wedged behind
+ * it. The staged file now gets its mode with fchmod and its flush on the
+ * descriptor it was written through.
+ *
+ * The simulated cases make an `'r'`-handle file flush fail with EPERM on
+ * every OS; the native cases run unmodified on the windows-latest
+ * security-regressions row. The 0444 case pins that a preserved read-only
+ * mode survives publication and recovery exactly (O-ENG-2).
+ */
+import { afterAll, beforeAll, expect, test } from 'bun:test';
+import { chmodSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import type { OperationContext } from '../src/core/ops/contract.ts';
+import { activatePersistence } from '../src/core/persistence/activation.ts';
+import { claimWorktree, type WorktreeBinding } from '../src/core/persistence/ownership.ts';
+import { localHostId, registerLocalWriter } from '../src/core/persistence/identity.ts';
+import { submissionAuthority } from '../src/core/persistence/authority.ts';
+import { admitWrite, claimNextWrite, completeWrite, prepareRecovery } from '../src/core/persistence/journal.ts';
+import { publishMutation, recoverPublication } from '../src/core/persistence/coordinator.ts';
+import { sha256 } from '../src/core/persistence/digest.ts';
+import { sameFileMode } from '../src/core/fs-durable.ts';
+import { withEnv } from './helpers/with-env.ts';
+import { simulateReadOnlyFsyncEperm } from './helpers/win32-flush-semantics.ts';
+
+interface Fixture { sourceId: string; root: string; path: string; binding: WorktreeBinding }
+let engine: BrainEngine;
+let hostId: string;
+let home: string;
+const fixtures: Fixture[] = [];
+const posixNonRoot = process.platform !== 'win32' && process.getuid?.() !== 0;
+
+beforeAll(async () => {
+ home = mkdtempSync(join(tmpdir(), 'gbrain-5595-'));
+ await withEnv({ GBRAIN_HOME: home }, async () => {
+ hostId = localHostId();
+ engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema();
+ for (let i = 0; i < 4; i++) {
+ const sourceId = `windows-flush-${i}`;
+ const root = join(home, `root-${i}`); mkdirSync(root);
+ const path = join(root, 'page.md'); writeFileSync(path, 'original');
+ await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', [sourceId, root]);
+ fixtures.push({ sourceId, root, path, binding: await claimWorktree(engine, sourceId, root, hostId) });
+ }
+ await registerLocalWriter(engine, 'cli');
+ await activatePersistence(engine, { confirmQuiesced: true });
+ });
+}, 120_000);
+afterAll(async () => {
+ await engine?.disconnect();
+ for (const f of fixtures) try { chmodSync(f.path, 0o644); } catch { /* removed below */ }
+ if (home) rmSync(home, { recursive: true, force: true });
+});
+
+async function accepted(f: Fixture) {
+ const authority = await submissionAuthority({ engine, remote: false, sourceId: f.sourceId } as OperationContext,
+ 'put_page', f.sourceId, f.binding.source_incarnation, 'page');
+ const current = await engine.readPageSnapshot('page', { sourceId: f.sourceId });
+ const row = await admitWrite(engine, { principal: authority.principal, authority, operation: 'put_page', sourceId: f.sourceId,
+ sourceIncarnation: f.binding.source_incarnation, slug: 'page', worktreeId: f.binding.worktree_id,
+ topologyGeneration: f.binding.topology_generation, pageId: current?.page.id ?? null,
+ callerIntent: { content: 'replacement' }, intent: { content: 'replacement' } });
+ const claimed = (await claimNextWrite(engine, hostId))!;
+ expect(claimed.id).toBe(row.id);
+ return { row: claimed, observedRevision: current?.revision ?? null };
+}
+
+/** A publication that renamed `replacement` over the file and then crashed: recovery must restore `original`. */
+async function interruptedPublication(f: Fixture, mode: number) {
+ const { row } = await accepted(f);
+ await prepareRecovery(engine, row, { version: 1, path: f.path, root: f.root, before: Buffer.from('original').toString('base64'),
+ beforeHash: sha256('original'), afterHash: sha256('replacement'), mode, ownerEpoch: String(f.binding.owner_epoch), attempt: row.execution_token! }, 4096);
+ writeFileSync(f.path, 'replacement');
+ return row;
+}
+const stages = (f: Fixture) => readdirSync(f.root).filter(name => name.includes('.tmp.'));
+
+test('#5595: recovery restores a moded page when read-only-handle file flushes fail (Windows semantics)', async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ const f = fixtures[0];
+ const row = await interruptedPublication(f, 0o600);
+ const simulation = simulateReadOnlyFsyncEperm();
+ let recovered;
+ try { recovered = await recoverPublication(engine, row.id, hostId); } finally { simulation.restore(); }
+ expect(simulation.readOnlyFsyncs).toBe(0);
+ expect(recovered.state).toBe('queued');
+ expect(recovered.recovery).toBeNull();
+ expect(readFileSync(f.path, 'utf8')).toBe('original');
+ expect(sameFileMode(statSync(f.path).mode, 0o600)).toBe(true);
+ expect(stages(f)).toEqual([]);
+ await engine.transaction(tx => completeWrite(tx, recovered, 'cancelled', {}));
+}));
+
+test('#5595: recovery restores a moded page natively on this platform', async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ const f = fixtures[1];
+ const row = await interruptedPublication(f, 0o644);
+ const recovered = await recoverPublication(engine, row.id, hostId);
+ expect(recovered.state).toBe('queued');
+ expect(recovered.recovery).toBeNull();
+ expect(readFileSync(f.path, 'utf8')).toBe('original');
+ expect(sameFileMode(statSync(f.path).mode, 0o644)).toBe(true);
+ expect(stages(f)).toEqual([]);
+ await engine.transaction(tx => completeWrite(tx, recovered, 'cancelled', {}));
+}));
+
+test.skipIf(!posixNonRoot)('a preserved 0444 page publishes and recovers with exact bytes and mode', async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ const f = fixtures[2];
+ chmodSync(f.path, 0o444);
+ const { row, observedRevision } = await accepted(f);
+ const done = await publishMutation(engine, row, { observedRevision, file: { path: f.path, root: f.root, content: 'replacement' },
+ apply: async (tx: BrainEngine) => {
+ await tx.putPage('page', { type: 'note', title: 'Frozen example', compiled_truth: 'replacement', frontmatter: {} }, { sourceId: f.sourceId });
+ return { slug: 'page' };
+ } }, hostId);
+ expect(done.state).toBe('committed');
+ expect(readFileSync(f.path, 'utf8')).toBe('replacement');
+ expect(statSync(f.path).mode & 0o7777).toBe(0o444);
+
+ const g = fixtures[3];
+ const interrupted = await interruptedPublication(g, 0o444);
+ const recovered = await recoverPublication(engine, interrupted.id, hostId);
+ expect(recovered.state).toBe('queued');
+ expect(readFileSync(g.path, 'utf8')).toBe('original');
+ expect(statSync(g.path).mode & 0o7777).toBe(0o444);
+ expect(stages(g)).toEqual([]);
+ await engine.transaction(tx => completeWrite(tx, recovered, 'cancelled', {}));
+}));