Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(atomic-write): stage long filenames through a short hashed sibling (#5861, D-NEW-3)
time-attackda26259d9f52
diff --git a/docs/architecture/key-files/schema-mutation.md b/docs/architecture/key-files/schema-mutation.mdindex 766ece4543..13ad9a5bd5 100644--- a/docs/architecture/key-files/schema-mutation.md+++ b/docs/architecture/key-files/schema-mutation.md@@ -6,9 +6,9 @@ The schema-pack mutation surface: six foundation modules + a mutate skeleton +stats/sync data plane + CLI verbs + MCP ops + a first-class agent skill.Key files:-- `src/core/persistence/staging.ts` — journaled same-directory staging descriptors reserve names, expected sizes and full hashes before any sink. Owner-locked recovery removes only known complete regular files; partial/unexpected bytes keep the root and recovery quota blocked, including committed receipt cleanup. Legacy records acquire durable staging descriptors before any new restoration. Final accounting requires verified absence and parent-directory durability. A regular-file ancestor proves an uncreated staging leaf is absent; recovery flushes the containing directory and settles the storage failure without deleting that ancestor or retaining a false recovery fence. Tests: `atomic-write.test.ts`, `persistence-staging.test.ts`, and eight-boundary process-crash harness.+- `src/core/persistence/staging.ts` — journaled same-directory staging descriptors reserve names, expected sizes and full hashes before any sink. Owner-locked recovery removes only known complete regular files; partial/unexpected bytes keep the root and recovery quota blocked, including committed receipt cleanup. Legacy records acquire durable staging descriptors before any new restoration. Final accounting requires verified absence and parent-directory durability. A regular-file ancestor proves an uncreated staging leaf is absent; recovery flushes the containing directory and settles the storage failure without deleting that ancestor or retaining a false recovery fence. Tests: `atomic-write.test.ts`, `atomic-long-staging.test.ts`, `persistence-staging.test.ts`, and eight-boundary process-crash harness.- `src/core/fs-durable.ts` — the shared durable-flush leaf (imports only `node:fs`). `flushFile(path)` fsyncs a file nobody holds open through `'r+'` on win32 (Windows `FlushFileBuffers` needs write access) and `'r'` elsewhere (a 0444 file stays flushable); a read-only file on win32 cannot be opened writable and is left to the OS. `flushDirectory(path, { bestEffort })` is strict by default: every error propagates except the win32 no-directory-flush codes (`EISDIR`/`EPERM`/`EINVAL`/`ENOTSUP`), a non-directory path fails `ENOTDIR`, and `bestEffort` swallows everything. `sameFileMode(actual, expected)` compares every permission bit on POSIX and only the owner write bit on win32, whose stat reports 0444/0666. A writer that still holds its descriptor sets the mode with `fchmodSync(fd)` and fsyncs that descriptor instead (atomic-write, skill-bundle staging). Callers: atomic-write, the persistence coordinator, identity, root registry, physical-root records, reconcile backups, recovery staging, topology checkouts (`flushTopologyDirectory` re-export, `flushTopologyTree`), skill bundles, agent-install state (`syncDirectory` re-export), `sources reconcile` previews and attendance-repair checkpoints. `scripts/check-durable-flush.ts` keeps new read-handle flushes out of `src/` (docs/TESTING.md#durable-flush-guard). Tests: `test/fs-durable.test.ts`, `test/persistence-windows-flush-5595.test.ts`, `test/bundle-files-windows-5475.test.ts`, `test/init-packaged-skills-native.test.ts`, run natively on windows-latest in the test.yml security-regressions job.-- `src/core/atomic-write.ts` — the shared atomic file writer for brain-repo markdown writers: unique tmp sibling (`.tmp.<pid>.<rand>`) → write loop until every byte lands (writeSync may legally short-write under disk pressure; a silent short write could atomically install truncated content) → fsync → close → synchronous staging boundary → optional `verify(onDiskBytes)` callback (throw = abort, tmp removed, target untouched) → atomic rename → parent-directory fsync through `fs-durable.ts` `flushDirectory` (rename durability; strict under `durable`, the journaled-publication flag, best-effort otherwise). The stage is opened with its final mode and `fchmod`-ed on the descriptor past the umask before any byte is written: `AtomicWriteOpts.mode` sets exact bits and reasserts them over an existing target's mode (a legacy 0644 file tightens on its next write); omitted, the target's existing mode is preserved, else 0644 & ~umask. `mkdirPrivate(dir, root = dir)` creates gbrain-private directories: a missing `root` gets default-permission ancestors and is itself made exactly 0700, each missing directory between `root` and `dir` is created 0700 (`O_NOFOLLOW` fchmod), and a directory that already exists, possibly one the user chose, is never chmod-ed; `dir` outside `root` throws. Consumers of the private modes: the Google connector (`google-source.ts`, `sources-ops.ts` Google add) and the persistence coordinator's Google publication. Consumed by `src/commands/backlinks.ts` (which verifies with `parseMarkdown({validate:true})` before the rename). Rename prevents torn writes, NOT lost updates — read-modify-write callers pair it with `withPageLock` (backlinks does). Unifying the per-module copies (skillopt/apply-edits, write-through, lint) is a filed TODO.+- `src/core/atomic-write.ts` — the shared atomic file writer for brain-repo markdown writers: unique short hidden tmp sibling from `atomicStagingPath` (`.<sha256(full target path)>.tmp.<uuid>`, so a valid basename near NAME_MAX still stages, #5861; `validateAtomicStagingPath` also accepts the historical `<target>.tmp.<uuid>` journal form, and recovery (`persistence/staging.ts` `upgradeRecoveryStaging`) durably swaps in a short stage only for a recorded historical leaf that returns ENAMETOOLONG; `timeline-write-through.ts` reuses the same allocator) → write loop until every byte lands (writeSync may legally short-write under disk pressure; a silent short write could atomically install truncated content) → fsync → close → synchronous staging boundary → optional `verify(onDiskBytes)` callback (throw = abort, tmp removed, target untouched) → atomic rename → parent-directory fsync through `fs-durable.ts` `flushDirectory` (rename durability; strict under `durable`, the journaled-publication flag, best-effort otherwise). The stage is opened with its final mode and `fchmod`-ed on the descriptor past the umask before any byte is written: `AtomicWriteOpts.mode` sets exact bits and reasserts them over an existing target's mode (a legacy 0644 file tightens on its next write); omitted, the target's existing mode is preserved, else 0644 & ~umask. `mkdirPrivate(dir, root = dir)` creates gbrain-private directories: a missing `root` gets default-permission ancestors and is itself made exactly 0700, each missing directory between `root` and `dir` is created 0700 (`O_NOFOLLOW` fchmod), and a directory that already exists, possibly one the user chose, is never chmod-ed; `dir` outside `root` throws. Consumers of the private modes: the Google connector (`google-source.ts`, `sources-ops.ts` Google add) and the persistence coordinator's Google publication. Consumed by `src/commands/backlinks.ts` (which verifies with `parseMarkdown({validate:true})` before the rename). Rename prevents torn writes, NOT lost updates — read-modify-write callers pair it with `withPageLock` (backlinks does). Unifying the per-module copies (skillopt/apply-edits, write-through, lint) is a filed TODO.- `src/core/schema-pack/pack-lock.ts` — Atomic `O_CREAT|O_EXCL` per-pack lock. DELIBERATELY NOT the `existsSync + writeFileSync` TOCTOU shape from `src/core/page-lock.ts`. Default 60s TTL, refresh every 10s while `withPackLock(fn)` runs, `--force` semantics = "steal stale lock" NOT "skip locking." Lock path per-pack so two packs never block each other.- `src/core/schema-pack/write-vocabulary.ts` — write-time pack-vocabulary enforcement shared by the write surfaces (capture op, `add_link` op, `gbrain capture` CLI). `loadActivePackForWriteVocabulary(ctx)` pairs the engine's DB-plane `schema_pack` key with FILE-ONLY config (the `loadActivePackForLocalEngine` posture) while threading `remote` (fail-closed: anything not strictly false is remote) + `sourceId`; NEVER throws — null means "no resolvable pack", which callers MUST treat as "no vocabulary to enforce" (the write proceeds exactly as before). `packDeclaresPageType`/`packDeclaresLinkType` + message/suggestion formatters reject an EXPLICIT undeclared name with the pack's declared vocabulary in the error so agents self-correct without a `gbrain schema explain` round-trip. The DEFAULT `note` path is never checked here — callers validate EXPLICIT names only, so bare `gbrain capture` works under a pack that doesn't declare `note`. `loadActivePackForWriteVocabulary` also swallows a rejecting `getConfig`; `previewNames` bounds the vocabulary preview in the error (the first 12 names + `(N total)`). Pinned by `test/write-vocabulary.test.ts`.- `src/core/schema-pack/mutate-audit.ts` — ISO-week JSONL at `~/.gbrain/audit/schema-mutations-YYYY-Www.jsonl`. Privacy-redacted: type names → sha8, prefixes → first slug segment only, matches `candidate-audit.ts` privacy posture. Logs BOTH success AND failure events so a future `schema_pack_writability` doctor check has signal. `summarizeMutations()` is the cross-surface parity primitive.diff --git a/docs/wave9/sg.md b/docs/wave9/sg.mdnew file mode 100644index 0000000000..95b595d18e--- /dev/null+++ b/docs/wave9/sg.md@@ -0,0 +1,13 @@+# Wave 9 lane SG: CHANGELOG lines and upgrade-note rows++Integrator: fold these into CHANGELOG.md and docs/UPGRADING_DOWNSTREAM_AGENTS.md at release time.++## CHANGELOG lines++- **Long page filenames publish again (#5861).** Atomic and journaled writes stage through a short hidden sibling (`.<sha256 of the target path>.tmp.<uuid>`) instead of appending a suffix to the full basename, so a valid basename near the 255-byte limit no longer fails with ENAMETOOLONG or leaves a write request recovering. Recovery still accepts historical stage names and, under the owner lock, durably swaps in a short name only for a recorded stage the filesystem cannot name. Timeline write-through uses the same allocator (D-NEW-3).++## Upgrade-note rows++| Change | Who is affected | Doctor / check | How to opt back |+|---|---|---|---|+| Staging files are now hidden `.<hash>.tmp.<uuid>` siblings (#5861) | Anyone with page basenames over ~214 bytes; operators who glob for `*.tmp.*` leftovers (the new names still contain `.tmp.`) | `gbrain sources writer status --json` shows any recovery that still holds a stage | None needed; historical journals keep working |diff --git a/src/core/atomic-write.ts b/src/core/atomic-write.tsindex b89c5a0850..809e7f3815 100644--- a/src/core/atomic-write.ts+++ b/src/core/atomic-write.ts@@ -7,7 +7,9 @@* The rename is atomic on POSIX filesystems, so readers never observe a torn* file; a crash mid-write leaves only a tmp sibling, never a corrupt target.*- * The tmp name embeds pid + random bytes so concurrent writers (two fixers,+ * The tmp name is a short hidden sibling, `.<sha256(target)>.tmp.<uuid>`, so+ * a valid target basename near NAME_MAX still gets a valid stage name (#5861),+ * the stage stays bound to its full target path, and concurrent writers (two fixers,* a fixer racing a render) can never collide on the tmp path itself. Note the* rename does NOT prevent lost updates between two read-modify-write writers —* callers that need that take the per-page lock (src/core/page-lock.ts).@@ -33,7 +35,7 @@ import {unlinkSync,writeSync,} from 'fs';-import { randomBytes, randomUUID } from 'crypto';+import { createHash, 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';@@ -99,7 +101,11 @@ export function mkdirPrivate(dir: string, root: string = dir): void {export function atomicStagingPath(filePath: string): string {// nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- internal name allocation only; coordinator checks owner-root containment before staging and publication.- return `${resolve(filePath)}.tmp.${randomUUID()}`;+ return `${stagingPrefix(resolve(filePath))}${randomUUID()}`;+}++function stagingPrefix(target: string): string {+ return join(dirname(target), `.${createHash('sha256').update(target).digest('hex')}.tmp.`);}export function validateAtomicStagingPath(filePath: string, stagingPath: string): void {@@ -107,8 +113,9 @@ export function validateAtomicStagingPath(filePath: string, stagingPath: string)const target = resolve(filePath);// nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- normalized only to reject non-sibling stages below; recovery also checks symlink-aware root containment before file access.const staged = resolve(stagingPath);- if (dirname(target) !== dirname(staged) || !staged.startsWith(`${target}.tmp.`)- || !/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/.test(staged.slice(target.length + 5))) {+ const prefix = [stagingPrefix(target), `${target}.tmp.`].find(candidate => staged.startsWith(candidate));+ if (dirname(target) !== dirname(staged) || !prefix+ || !/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/.test(staged.slice(prefix.length))) {throw new Error('atomic-write: invalid journaled staging path');}}@@ -116,7 +123,7 @@ export function validateAtomicStagingPath(filePath: string, stagingPath: string)export function atomicWriteFileSync(filePath: string, content: string | Uint8Array, opts?: AtomicWriteOpts): void {assertManagedFilesystemWrite(filePath);if (opts?.stagingPath) validateAtomicStagingPath(filePath, opts.stagingPath);- const tmpPath = opts?.stagingPath ?? `${filePath}.tmp.${process.pid}.${randomBytes(4).toString('hex')}`;+ const tmpPath = opts?.stagingPath ?? atomicStagingPath(filePath);const buf = typeof content === 'string' ? Buffer.from(content, 'utf-8') : Buffer.from(content);let created: ReturnType<typeof fstatSync> | undefined;diff --git a/src/core/persistence/coordinator.ts b/src/core/persistence/coordinator.tsindex a73c8eae4c..ba03efdf72 100644--- a/src/core/persistence/coordinator.ts+++ b/src/core/persistence/coordinator.ts@@ -384,7 +384,7 @@ export async function recoverPublication(engine: BrainEngine, id: string, hostIdWHERE id=$1::uuid AND recovery IS NOT NULL AND state IN ('running','recovering') AND ${PERSISTENCE_PROTOCOL_PREDICATE} RETURNING *`, [id]);return blocked ?? row;}- if (row.recovery.version === 1 && !row.recovery.staging && !isTerminal(row)) await upgradeRecoveryStaging(engine, 'persistence_requests', id, row.worktree_id!, 'restore');+ if (!isTerminal(row)) await upgradeRecoveryStaging(engine, 'persistence_requests', id, row.worktree_id!, 'restore');row = await engine.transaction(async tx => {await declareDurablePersistence(tx);await tx.executeRaw('SELECT id FROM persistence_worktrees WHERE id=$1::uuid FOR SHARE', [row!.worktree_id]);diff --git a/src/core/persistence/effect-recovery.ts b/src/core/persistence/effect-recovery.tsindex ab5e6ebd47..7df3982df9 100644--- a/src/core/persistence/effect-recovery.ts+++ b/src/core/persistence/effect-recovery.ts@@ -105,7 +105,7 @@ export async function recoverEffectPublication(engine: BrainEngine, effect: Pers`Every publication slot of the writer pool is busy, so mirror recovery for source ${effect.source_id} has not started; the worker tries again once a slot frees. Nothing needs resubmitting.`,{ fix: effectStatusFix(effect) });try {- if (effect.recovery && !effect.recovery.staging) await upgradeRecoveryStaging(engine, 'persistence_effects', effect.id, effect.worktree_id!, 'forward');+ if (effect.recovery) await upgradeRecoveryStaging(engine, 'persistence_effects', effect.id, effect.worktree_id!, 'forward');await engine.transaction(async tx => {await tx.executeRaw("SELECT set_config('synchronous_commit','on',true),set_config('lock_timeout','1s',true),set_config('statement_timeout','5s',true)");const binding = await guardEffectSource(tx, effect, hostId);diff --git a/src/core/persistence/staging.ts b/src/core/persistence/staging.tsindex 1ef253d335..78f8fc3e67 100644--- a/src/core/persistence/staging.ts+++ b/src/core/persistence/staging.ts@@ -12,6 +12,8 @@ import { declarePersistenceProtocol } from './protocol.ts';export interface RecoveryStagingFile { path: string; hash: string; bytes: number }export interface RecoveryStaging { publication?: RecoveryStagingFile; restoration?: RecoveryStagingFile }interface StagedRecovery { path: string; root: string; staging?: RecoveryStaging }+interface StoredFileRecovery extends StagedRecovery { before?: string | null; after?: string | null }+type StoredRecovery = StoredFileRecovery | { files: StoredFileRecovery[] };/** Allocate names only. The caller durably reserves these before any open/mkdir. */export function recoveryStagingFile(path: string, bytes: string | Uint8Array): RecoveryStagingFile {@@ -35,8 +37,9 @@ function stages(record: StagedRecovery): RecoveryStagingFile[] {function statIfPresent(path: string) {try { return lstatSync(path); }catch (error) {- // A regular-file ancestor also proves that this staging leaf is absent.- if (['ENOENT', 'ENOTDIR'].includes((error as NodeJS.ErrnoException).code ?? '')) return null;+ // A regular-file ancestor also proves that this staging leaf is absent, and+ // a historical stage name longer than NAME_MAX can never have been created.+ if (['ENOENT', 'ENOTDIR', 'ENAMETOOLONG'].includes((error as NodeJS.ErrnoException).code ?? '')) return null;throw error;}}@@ -78,6 +81,30 @@ export function assertRecoveryStagingAbsent(record: StagedRecovery): void {}}+/** Reserve a stage for an unstaged record; replace only historical leaves the filesystem cannot name (#5861). */+function upgradeFileStaging(record: StoredFileRecovery, mode: 'restore' | 'forward'): StoredFileRecovery {+ if (!record.staging) {+ const encoded = mode === 'restore' ? record.before : record.after;+ return { ...record, staging: encoded == null ? {} : {+ [mode === 'restore' ? 'restoration' : 'publication']: recoveryStagingFile(record.path, Buffer.from(encoded, 'base64')),+ } };+ }+ stages(record);+ let changed = false;+ const staging = { ...record.staging };+ for (const key of ['publication', 'restoration'] as const) {+ const stage = staging[key];+ if (!stage) continue;+ try { lstatSync(stage.path); }+ catch (error) {+ const code = (error as NodeJS.ErrnoException).code;+ if (code === 'ENAMETOOLONG') { staging[key] = { ...stage, path: atomicStagingPath(record.path) }; changed = true; }+ else if (code !== 'ENOENT' && code !== 'ENOTDIR') throw error;+ }+ }+ return changed ? { ...record, staging } : record;+}+/** Old records remain readable; reserve new names before an old recovery writes. */export async function upgradeRecoveryStaging(engine: BrainEngine, table: 'persistence_requests' | 'persistence_effects',id: string | number, worktreeId: string, mode: 'restore' | 'forward'): Promise<void> {@@ -87,16 +114,16 @@ export async function upgradeRecoveryStaging(engine: BrainEngine, table: 'persisawait declarePersistenceProtocol(tx);await tx.executeRaw("SELECT set_config('synchronous_commit','on',true),set_config('lock_timeout','1s',true),set_config('statement_timeout','5s',true)");const counters = await lockCounters(tx, ['brain', `worktree:${worktreeId}`]);- const [row] = await tx.executeRaw<{ recovery_bytes: number | string; recovery: (StagedRecovery & { before?: string | null; after?: string }) | null }>(+ const [row] = await tx.executeRaw<{ recovery_bytes: number | string; recovery: StoredRecovery | null }>(`SELECT recovery,recovery_bytes FROM ${table} WHERE id=$1 FOR UPDATE`, [id]);- if (!row?.recovery || row.recovery.staging) return;+ if (!row?.recovery) return;const record = row.recovery;- const encoded = mode === 'restore' ? record.before : record.after;- const staging: RecoveryStaging = encoded == null ? {} : {- [mode === 'restore' ? 'restoration' : 'publication']: recoveryStagingFile(record.path, Buffer.from(encoded, 'base64')),- };- const updated = { ...record, staging };- const minimum = Buffer.byteLength(JSON.stringify(updated)) + Object.values(staging).reduce((sum, stage) => sum + stage.bytes, 0) + 4096;+ const prior = 'files' in record ? record.files : [record];+ const files = prior.map(file => upgradeFileStaging(file, mode));+ if (files.every((file, index) => file === prior[index])) return;+ const updated = 'files' in record ? { ...record, files } : files[0];+ const staged = files.reduce((sum, file) => sum + Object.values(file.staging ?? {}).reduce((bytes, stage) => bytes + stage.bytes, 0), 0);+ const minimum = Buffer.byteLength(JSON.stringify(updated)) + staged + 4096;const extra = Math.max(0, minimum - Number(row.recovery_bytes));for (const counter of counters) if (Number(counter.recovery_bytes) + extra > (counter.key === 'brain' ? limits.brainRecoveryBytes : limits.worktreeRecoveryBytes)) {throw opError('queue_capacity', 'Recovery is waiting for capacity to durably record its staging paths.',diff --git a/src/core/timeline-write-through.ts b/src/core/timeline-write-through.tsindex ff5ee7194b..6796eee6d3 100644--- a/src/core/timeline-write-through.ts+++ b/src/core/timeline-write-through.ts@@ -47,7 +47,6 @@ import { bodyWriteChunkVersion } from './search/safe-chunks.ts';import { existsSync, readFileSync, writeFileSync, renameSync, unlinkSync, readdirSync } from 'node:fs';import { basename, dirname } from 'node:path';-import { randomBytes } from 'node:crypto';import type { BrainEngine } from './engine.ts';import { sanitizeForJsonb } from './batch-rows.ts';import {@@ -57,6 +56,7 @@ import {type WriteThroughResult,} from './write-through.ts';import { withPageLock } from './page-lock.ts';+import { atomicStagingPath } from './atomic-write.ts';import { maintenanceTransaction } from './persistence/attribution.ts';import { assertSourceFilesystemActive, hasSourceFilesystemLock, withSourceFilesystemLock } from './minions/source-filesystem.ts';import { findTimelineSplitIndex } from './markdown.ts';@@ -372,7 +372,7 @@ export async function writeTimelineEntryThrough(// Atomic write: unique temp sibling + rename (writePageThrough's// convention). Clean the temp up on failure — never leak a stray.- const tmpPath = `${filePath}.tmp.${process.pid}.${randomBytes(4).toString('hex')}`;+ const tmpPath = atomicStagingPath(filePath);try {assertSourceFilesystemActive();writeFileSync(tmpPath, afterText, 'utf8');diff --git a/test/atomic-long-staging.test.ts b/test/atomic-long-staging.test.tsnew file mode 100644index 0000000000..5adbc9e383--- /dev/null+++ b/test/atomic-long-staging.test.ts@@ -0,0 +1,68 @@+import { afterEach, expect, test } from 'bun:test';+import { mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { basename, join } from 'node:path';+import { createHash } from 'node:crypto';+import { atomicStagingPath, atomicWriteFileSync, validateAtomicStagingPath } from '../src/core/atomic-write.ts';+import { assertRecoveryStagingAbsent, cleanupRecoveryStaging } from '../src/core/persistence/staging.ts';++const dirs: string[] = [];+afterEach(() => { for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }); });+function fixture() { const dir = mkdtempSync(join(tmpdir(), 'gbrain-long-stage-')); dirs.push(dir); return dir; }++test('journaled publication replaces a valid 215-byte target name (#5861)', () => {+ const dir = fixture();+ const target = join(dir, 'm'.repeat(212) + '.md');+ writeFileSync(target, 'original');+ const stage = atomicStagingPath(target);+ expect(Buffer.byteLength(basename(stage))).toBeLessThan(255);+ let flushed = false;+ atomicWriteFileSync(target, 'replacement', { stagingPath: stage, durable: true, afterStagingFlush() {+ flushed = true;+ expect(readFileSync(stage, 'utf8')).toBe('replacement');+ expect(readFileSync(target, 'utf8')).toBe('original');+ } });+ expect(flushed).toBe(true);+ expect(readFileSync(target, 'utf8')).toBe('replacement');+ expect(readdirSync(dir)).toEqual([basename(target)]);+});++test('ordinary atomic writes replace a valid 253-byte target name (#5861)', () => {+ const dir = fixture();+ const target = join(dir, 'm'.repeat(250) + '.md');+ writeFileSync(target, 'original');+ atomicWriteFileSync(target, 'replacement');+ expect(readFileSync(target, 'utf8')).toBe('replacement');+ expect(readdirSync(dir)).toEqual([basename(target)]);+});++test('short stages stay bound to one target and historical stages stay valid', () => {+ const dir = fixture();+ const target = join(dir, 'page.md');+ const stage = atomicStagingPath(target);+ expect(() => validateAtomicStagingPath(target, stage)).not.toThrow();+ expect(() => validateAtomicStagingPath(join(dir, 'other.md'), stage)).toThrow();+ expect(() => validateAtomicStagingPath(target, join(fixture(), basename(stage)))).toThrow();+ expect(() => validateAtomicStagingPath(target, `${target}.tmp.00000000-0000-0000-0000-000000000000`)).not.toThrow();+ expect(() => validateAtomicStagingPath(target, `${stage}.extra`)).toThrow();+});++test('recovery cleanup removes matching short stages, keeps foreign bytes, and treats impossible legacy leaves as absent', () => {+ const dir = fixture();+ const target = join(dir, 'm'.repeat(212) + '.md');+ writeFileSync(target, 'prior');+ const stage = atomicStagingPath(target);+ const hash = createHash('sha256').update('ready').digest('hex');+ const record = { path: target, root: dir, staging: { publication: { path: stage, hash, bytes: 5 } } };+ writeFileSync(stage, 'wrong');+ expect(() => cleanupRecoveryStaging(record)).toThrow('unexpected');+ expect(readFileSync(stage, 'utf8')).toBe('wrong');+ writeFileSync(stage, 'ready');+ cleanupRecoveryStaging(record);+ expect(() => assertRecoveryStagingAbsent(record)).not.toThrow();+ const legacy = { ...record, staging: { publication: { ...record.staging.publication,+ path: `${target}.tmp.00000000-0000-0000-0000-000000000000` } } };+ expect(() => cleanupRecoveryStaging(legacy)).not.toThrow();+ expect(() => assertRecoveryStagingAbsent(legacy)).not.toThrow();+ expect(readFileSync(target, 'utf8')).toBe('prior');+});diff --git a/test/persistence-staging.test.ts b/test/persistence-staging.test.tsindex 9a8814d14f..4f10f13af7 100644--- a/test/persistence-staging.test.ts+++ b/test/persistence-staging.test.ts@@ -1,6 +1,6 @@import { afterAll, beforeAll, expect, test } from 'bun:test';import { randomUUID } from 'node:crypto';-import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, unlinkSync, writeFileSync } from 'node:fs';+import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, realpathSync, rmSync, unlinkSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';import { join } from 'node:path';import type { BrainEngine } from '../src/core/engine.ts';@@ -31,7 +31,7 @@ let hostId: string;let home: string;let closePostgres: (() => Promise<void>) | undefined;beforeAll(async () => {- home = mkdtempSync(join(tmpdir(), 'gbrain-staging-tests-'));+ home = realpathSync(mkdtempSync(join(tmpdir(), 'gbrain-staging-tests-')));await withEnv({ GBRAIN_HOME: home }, async () => {hostId = localHostId();const engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); engines.push(engine);@@ -40,7 +40,7 @@ beforeAll(async () => {}for (const engine of engines) {const cases: Fixture[] = [];- for (let i = 0; i < 9; i++) {+ for (let i = 0; i < 12; i++) {const sourceId = `staging-case-${i}`;const root = join(home, `${engine.kind}-${i}`); mkdirSync(root);const path = join(root, 'page.md'); writeFileSync(path, 'original');@@ -277,3 +277,75 @@ test('withdrawal mirror staging preserves unexpected bytes and only finishes for} finally { await lock!.release(); }}}));++test('journaled long target name commits file and page and releases recovery accounting (#5861)', async () => withEnv({ GBRAIN_HOME: home }, async () => {+ for (const cases of fixtures) {+ const f = cases[9];+ f.path = join(f.root, 'm'.repeat(212) + '.md');+ writeFileSync(f.path, 'original');+ const { row, prepared } = await accepted(f);+ const done = await publishMutation(f.engine, row, prepared, hostId);+ expect(done.state).toBe('committed');+ expect(readFileSync(f.path, 'utf8')).toBe('replacement');+ expect((await f.engine.readPageSnapshot('page', { sourceId: f.sourceId }))!.page.compiled_truth).toBe('replacement');+ expect(temporaryFiles(f)).toEqual([]);+ expect(await bytes(f)).toBe(0);+ expect((await getWriteRequestById(f.engine, row.id))!.recovery).toBeNull();+ }+}));++test('populated legacy deletion journal reserves a short restoration stage before restoring (#5861)', async () => withEnv({ GBRAIN_HOME: home }, async () => {+ for (const cases of fixtures) {+ const f = cases[10];+ f.path = join(f.root, 'm'.repeat(212) + '.md');+ writeFileSync(f.path, 'original');+ const { row } = await accepted(f);+ const legacy = `${f.path}.tmp.${randomUUID()}`;+ await prepareRecovery(f.engine, row, { version: 1, path: f.path, root: f.root,+ before: Buffer.from('original').toString('base64'), beforeHash: sha256('original'), afterHash: null,+ mode: 0o600, ownerEpoch: String(f.binding.owner_epoch), attempt: row.execution_token!,+ staging: { restoration: { path: legacy, hash: sha256('original'), bytes: 8 } } }, 8192);+ unlinkSync(f.path);+ let durableStage = false;+ const recovered = await recoverPublication(f.engine, row.id, hostId, false, undefined, false, {+ fileBoundary: (name, current) => {+ if (name !== 'before_restore') return;+ expect(current.recovery!.staging!.restoration!.path).not.toBe(legacy);+ durableStage = true;+ },+ });+ expect(durableStage).toBe(true); expect(recovered.state).toBe('queued'); expect(recovered.recovery).toBeNull();+ expect(readFileSync(f.path, 'utf8')).toBe('original'); expect(temporaryFiles(f)).toEqual([]); expect(await bytes(f)).toBe(0);+ await f.engine.transaction(tx => completeWrite(tx, recovered, 'cancelled', {}));+ }+}));++test('populated legacy withdrawal journal reserves a short stage and finishes only forward (#5861)', async () => withEnv({ GBRAIN_HOME: home }, async () => {+ for (const cases of fixtures) {+ const f = cases[11];+ f.path = join(f.root, 'm'.repeat(212) + '.md'); writeFileSync(f.path, 'original');+ const { row } = await accepted(f);+ await f.engine.transaction(tx => withCoordinatedWrite(tx, [f.sourceId], () => tx.putPage('page',+ { type: 'note', title: 'Withdrawn example', compiled_truth: 'Current sanitized content.', frontmatter: {} }, { sourceId: f.sourceId }), TEST_WRITE_ATTRIBUTION));+ const snapshot = (await f.engine.readPageSnapshot('page', { sourceId: f.sourceId }))!;+ await f.engine.transaction(tx => completeWrite(tx, row, 'committed', { revision: snapshot.revision }));+ const [effect] = await f.engine.executeRaw<PersistenceEffect>(`INSERT INTO persistence_effects+ (request_id,kind,revision,data,source_id,source_incarnation,worktree_id,state,execution_token)+ VALUES($1::uuid,'withdrawal-mirror',$2::uuid,'{"source_scan":true}',$3,$4::uuid,$5::uuid,'running',$6::uuid) RETURNING *`,+ [row.id, snapshot.revision, f.sourceId, f.binding.source_incarnation, f.binding.worktree_id, randomUUID()]);+ const after = serializePageToMarkdown(snapshot.page, snapshot.tags);+ const legacy = `${f.path}.tmp.${randomUUID()}`;+ const record: EffectRecovery = { version: 1, kind: 'withdrawal-mirror', path: f.path, root: f.root,+ beforeHash: sha256('original'), afterHash: sha256(after), after: Buffer.from(after).toString('base64'), mode: 0o600,+ ownerEpoch: String(f.binding.owner_epoch), pageId: snapshot.page.id, sourceIncarnation: snapshot.sourceIncarnation,+ slug: 'page', revision: snapshot.revision, staging: { publication: { path: legacy, hash: sha256(after), bytes: Buffer.byteLength(after) } } };+ const lock = await acquireWorktree(f.binding); expect(lock).not.toBeNull();+ try {+ await reserveEffectRecovery(f.engine, effect, record, 8192, hostId);+ const [retry] = await f.engine.executeRaw<PersistenceEffect>('SELECT * FROM persistence_effects WHERE id=$1', [effect.id]);+ await recoverEffectPublication(f.engine, retry, hostId);+ expect(readFileSync(f.path, 'utf8')).toBe(after); expect(temporaryFiles(f)).toEqual([]); expect(await bytes(f)).toBe(0);+ expect((await f.engine.readPageSnapshot('page', { sourceId: f.sourceId }))!.revision).toBe(snapshot.revision);+ } finally { await lock!.release(); }+ }+}));diff --git a/test/timeline-write-through.test.ts b/test/timeline-write-through.test.tsindex 525f0615ef..2d41890699 100644--- a/test/timeline-write-through.test.ts+++ b/test/timeline-write-through.test.ts@@ -130,6 +130,24 @@ describe('add_timeline_entry on an FS-canonical brain (#1856)', () => {expect(page?.timeline ?? '').toContain('Manual milestone added via timeline-add');});+ test('helper splices into a canonical file whose basename is near NAME_MAX (D-NEW-3, #5861)', async () => {+ await engine.setConfig('sync.repo_path', brainDir);+ const slug = `notes/${'a'.repeat(240)}`;+ const filePath = await seedPage(slug);+ expect(Buffer.byteLength(path.basename(filePath))).toBe(243);++ const out = await writeTimelineEntryThrough(engine, slug, 'default', {+ date: '2026-07-15',+ summary: 'Milestone on a long page name',+ source: 'meetings/2026-07-15',+ });++ expect(out.error).toBeUndefined();+ expect(out.handled).toBe(true);+ expect(fs.readFileSync(filePath, 'utf8')).toContain('Milestone on a long page name');+ expect(fs.readdirSync(path.dirname(filePath)).filter((name) => name.includes('.tmp.'))).toEqual([]);+ });+test('FS→DB rebuild recovers the entry from the file (the P0 loss mode)', async () => {await engine.setConfig('sync.repo_path', brainDir);const slug = 'notes/rebuild-example';