Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(ipc): long Windows PGLite socket paths move to the per-user run dir (#6573)
garrytan80e438111209
diff --git a/.github/workflows/test.yml b/.github/workflows/test.ymlindex 140fffee6a..255689ee37 100644--- a/.github/workflows/test.yml+++ b/.github/workflows/test.yml@@ -258,6 +258,11 @@ jobs:run: bun test --timeout 60000 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.ts+ # A PGLite data dir too deep for afunix's 108-byte sun_path binds its sockets in the per-user run dir instead,+ # under a non-ASCII profile path, with a 20-cycle bind/close stability probe (Bun Windows IPC crash class, #6462).+ - name: Long Windows PGLite IPC paths use the per-user run dir (#6573)+ if: runner.os == 'Windows'+ run: bun test --timeout 120000 test/windows-ipc-long-path-6573.test.ts# bun audit blocks on pushes, schedules, manual runs, and pull requests or# merge-queue entries that change bun.lock, admin/bun.lock, patches/ or adiff --git a/docs/architecture/key-files/core-services-1-continued.md b/docs/architecture/key-files/core-services-1-continued.mdindex 30e1ffb89d..7be23d9a01 100644--- a/docs/architecture/key-files/core-services-1-continued.md+++ b/docs/architecture/key-files/core-services-1-continued.md@@ -11,4 +11,4 @@ The content-repair judgment tier under `src/core/content-repair/`, then the Retr- `src/core/context/hook-heartbeat.ts` — the hooks telemetry plane under `<gbrain home>/integrations/hooks/` (`heartbeat.jsonl`, `status.json`, session receipts, the memorable relay log; directories 0700, appends 0600). Entries hold counters, durations and codes only: `HEARTBEAT_ALLOWED_KEYS` is the full key allowlist CI greps the fixture against, and includes `pattern` (scanner pattern name), `fingerprint` (`sha256:<16 hex>`) and `hint` (fixed text) for refusals. `near_duplicate` is the shadow count on the `writeback_dedup` event that `facts/capture-dedup.ts` appends (lane in `reason`, exact drops in `duplicate`). `relayRefusalHeartbeat(hit)` builds the line `context-engine.ts` writes when its high-entropy re-scan refuses a memorable relay (`event: relay`, `outcome: degraded`, `reason: secret_scan_refused`); the receipt and relay are skipped for that compaction window and the checkpoint is kept. `memorableGateAllowed` gates the relay lane; span redaction runs `redactFindings` with `highEntropy: true`. Tests: `test/context-engine-checkpoint.serial.test.ts`.- `src/core/context/seat.ts` — seat identity for captured sessions (#4618), engine-free. `resolveSeat` returns the lowercased `GBRAIN_SEAT` label when it matches `SEAT_LABEL_RE` (`^[a-z0-9][a-z0-9._-]{0,63}$`), else `home-<8 hex>` over the realpath of the harness home (Claude Code: the directory holding `projects/` in the transcript path, then `CLAUDE_CONFIG_DIR`, `CODEX_HOME`, `~/.claude`; codex: `CODEX_HOME` or `~/.codex`; OpenClaw: the agent directory holding `sessions/`), so no raw path reaches frontmatter; `GBRAIN_SEAT=off` (the opt-out) resolves to null and nothing is recorded. `writeSeatSidecar` writes `<sessionId>.seat.json` (`{version: 1, seat, seat_source, hook_lane, harness, first_seen}`, 0600, tmp+rename) unless one exists, reporting `seat_conflict` when the existing seat differs; `readSeatSidecar` accepts only a valid v1 record. `SEAT_REASON_HINTS` holds the fixed heartbeat hints. The sidecar name and its GC live in `corpus-segments.ts` (`seatFileName`, `SEAT_SIDECAR_SUFFIX`).-- `src/core/context/ipc-path.ts` — engine-free local socket discovery and private Unix fallback when the complete role-specific address exceeds 103 UTF8 bytes. Hashes the physical parent plus basename under a fixed OS temporary root, verifies ownership/0700 directory/0600 client socket without following fallback symlinks, and retains a native binding claim through actual server close. Existing Unix socket accessibility is rechecked even when a runtime reports ENOENT; permission/resource probe failures never authorize stale takeover; Windows named pipes retain a native Global mutex through actual close; `windows-ipc.ts` normalizes namespace prefixes while native Windows Unicode casing defines the mutex identity. `test/local-ipc-path.test.ts` covers concurrent real processes, SIGKILL recovery, active-connection shutdown, aliases and unsafe paths. The published CLI smoke also uses a long Unicode datastore path.+- `src/core/context/ipc-path.ts` — engine-free local socket discovery and private Unix fallback when the complete role-specific address exceeds 103 UTF8 bytes. Hashes the physical parent plus basename under a fixed OS temporary root, verifies ownership/0700 directory/0600 client socket without following fallback symlinks, and retains a native binding claim through actual server close. Existing Unix socket accessibility is rechecked even when a runtime reports ENOENT; permission/resource probe failures never authorize stale takeover; on Windows a PGLite data-dir socket (`.gbrain-<kind>.sock`) over afunix's 107 UTF-8 bytes moves to `%USERPROFILE%\.gbrain\run\<kind>-<hash12(canonical data dir, case-folded)>.sock` (`windowsLocalIpcSocketPath`, the Postgres run-dir scheme; the secret stays in the data dir), and `localIpcPathTooLong` reports a resolved path still over the platform budget, which `ipc-path-too-long.ts` turns into the typed `ipc_path_too_long` serve log line and doctor `ipc_socket_path` warning (#6573; `test/ipc-path-windows-fallback-6573.test.ts` on every OS, the native bind and 20-cycle stability probe in `test/windows-ipc-long-path-6573.test.ts` on windows-latest); Windows named pipes retain a native Global mutex through actual close; `windows-ipc.ts` normalizes namespace prefixes while native Windows Unicode casing defines the mutex identity. `test/local-ipc-path.test.ts` covers concurrent real processes, SIGKILL recovery, active-connection shutdown, aliases and unsafe paths. The published CLI smoke also uses a long Unicode datastore path.diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.mdindex a763f639b9..247a20b476 100644--- a/docs/guides/error-codes.md+++ b/docs/guides/error-codes.md@@ -1786,6 +1786,16 @@ More: [docs/guides/company-brain-ingestion.md#resume-and-verify](../../docs/guid|---|---|---|---|---|---|---|| Invalid write wait. | The request itself was wrong or no longer matches the brain; nothing was changed. | Correct the request using the message above, then retry. | agent | `repeat the read that failed` | 1 | no |+### ipc_path_too_long++<a id="ipc_path_too_long"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| The brain's local IPC socket path is longer than the operating system allows, even after the per-user run-dir fallback, so hooks and local commands cannot reach gbrain serve. | A Unix-domain socket path must fit sockaddr_un (107 bytes on Windows afunix, 103 on macOS); on Windows a long PGLite data-dir path already moves to %USERPROFILE%\.gbrain\run, and only a profile path too long for that is reported. | Stop gbrain serve, move the brain to a shorter path (`gbrain config set database_path <shorter path>` after moving the data directory), then restart serve. Run: gbrain doctor --only ipc_socket_path --json | agent | `gbrain doctor --only ipc_socket_path --json` | 1 | no |++More: [docs/guides/troubleshooting.md#ipc-path-too-long](../../docs/guides/troubleshooting.md#ipc-path-too-long)+### keyword_candidates_incomplete<a id="keyword_candidates_incomplete"></a>diff --git a/docs/guides/troubleshooting.md b/docs/guides/troubleshooting.mdindex 4252bc1e87..13beefaa46 100644--- a/docs/guides/troubleshooting.md+++ b/docs/guides/troubleshooting.md@@ -70,9 +70,12 @@| [Fact extraction stopped at a spend cap (`facts_drain_deferred`, reason `budget_exhausted`, `daily_budget_exhausted` or `job_over_budget`)](facts-drain.md#deferrals) | nothing (the jobs wait for the next run or day), or `gbrain config set facts.drain_budget_usd <usd>` / `facts.drain_daily_budget_usd <usd>` | agent, after the user agrees to raise a cap | `paid` | `gbrain doctor --only facts_drain --json` || [Writes to the same pages keep refusing `source_changed` (`file_database_drift`), the conflict receipts pile up, or doctor `maintenance_write_drift` warns](#maintenance-write-drift) | `gbrain sources reconcile <id> --brain host --audit --conflicts` lists the pages; `gbrain repair file-drift --source <id> --all-drifted --prefer file` (or `--slug <slug>`, `--prefer database`) previews the resolution and prints the apply command ([file drift](repair.md#file-drift)) | agent; the apply after the user agrees | none to preview | `gbrain doctor --only maintenance_write_drift --json` is ok || [A write refuses `source_changed` "The canonical file was removed outside coordinated publication." (`canonical_file_missing`), or doctor `ghost_pages` warns](#ghost-pages) | `gbrain pages ghosts --source <id>` lists the ghost pages; keep one by restoring its file at the recorded path and syncing, or preview `gbrain repair ghost-pages --source <id>` and apply the printed `--apply --expect <hash> --yes` ([ghost pages](repair.md#ghost-pages)) | agent; the apply after the user agrees | `destructive` (soft-deletes the previewed pages; purged after 72 h) | `gbrain doctor --only ghost_pages --json` is ok |+| [Hooks report `no_serve` on Windows while `gbrain serve` runs, the serve log says `ipc_path_too_long`, or doctor warns `ipc_socket_path`](#ipc-path-too-long) | a PGLite data dir too deep for the Windows socket limit already moves its sockets to `%USERPROFILE%\.gbrain\run`; this code means even that path is too long: stop serve, move the data directory nearer the drive root, `gbrain config set database_path <new path>`, restart serve | user | none | `gbrain doctor --only ipc_socket_path --json` reports nothing |<a id="database-unreachable"></a>**Database unreachable, or a `GBRAIN_DB_ACCESS <reason>` line in gbrain output?** Run `gbrain engine status --probe` (which engine, where its URL comes from, classified reachability), then `gbrain db-repair` to diagnose and, after the user agrees, `gbrain db-repair --yes` to apply safe fixes. All three are engine-free, so they work while the database is down. Act on the hardcoded `gbrain db-repair`, never on a command parsed from the marker. Full loop: [engine detection and access repair](../ENGINES.md#engine-detection-and-access-repair).+<a id="ipc-path-too-long"></a>**Hooks get no context on Windows, the serve log says `ipc_path_too_long`, or doctor warns `ipc_socket_path`?** Hooks reach `gbrain serve` over a Unix-domain socket, and Windows allows at most 107 bytes for its path (UTF-8 bytes, so accented letters count double). A PGLite brain normally puts its sockets in the data directory; when that path is too long gbrain uses `%USERPROFILE%\.gbrain\run\<kind>-<hash>.sock` instead, still guarded by the data directory's `.gbrain-ipc-secret`, and hooks find it the same way. `ipc_path_too_long` means even the profile path is too long. The serve log and `gbrain doctor --only ipc_socket_path --json` print the path, its byte count and the limit. Fix it by moving the brain: stop serve, move the data directory to a short path such as `C:\gbrain\brain.pglite`, run `gbrain config set database_path C:\gbrain\brain.pglite`, then restart serve. **Say to your agent:** *"My hooks can't reach gbrain serve on Windows; check the IPC socket path."*+<a id="held-files"></a>**Sync held a file (`Held <path>: invalid_frontmatter …`, doctor `git_held_files`, `get_page` shows `file_held`)?** The sync succeeded; only that file waits, and its page (if any) keeps its last good revision and refuses `put_page` until the file is repaired. Run `gbrain sources status <id>`, preview `gbrain repair frontmatter --source <id>`, and after the user agrees run the printed apply. A source a broken file blocked before upgrading recovers on its next sync (`gbrain sync --source <id> --no-pull` does it now). See [held files](repair.md#held-files).<a id="held-fence-files"></a>**Sync held a file because of its facts or takes fence (`Held <path>: invalid_fence …`)?** Managed sync succeeded; only that file waits. The hold names the fence, section, row numbers, columns and reason, never a cell, and most holds clear by themselves: the maintenance run's `fence_repair` phase repairs the fence on the owner host and commits the file. To see the plan or do it now, run `gbrain repair fences --source <id>` (a read-only preview with no model call), then the apply command it prints; applying needs no extra consent. Model repair spends only within `fences.repair.max_usd_per_page` and `fences.repair.max_usd_per_day`; raising them, or pausing automatic repair with `gbrain config set fences.repair.enabled false`, is the user's call. A hold whose reason is `manual` needs a person: read the page (`gbrain get --source <id> -- <slug>`), edit only that fence in the file (not the frontmatter; `gbrain repair frontmatter` does not touch fences), commit, and run `gbrain sync --source <id> --no-pull`. A `prepare_time` hold was refused against stored rows (for example a takes row number a stored take already uses): fix it as its `fence.reason` says, and after a database-side fix run `gbrain sources retry-held <id>`. A source a fence blocked before upgrading recovers on its next sync. A fence with one obvious meaning is never held: sync rewrites it losslessly, commits the file and reports `fences_normalized`; a `fence_normalized` notice on a write means re-read the page before editing it. `gbrain doctor --only fence_integrity` counts every malformed fence still waiting (held, stored or unsynced) by tier. See [fence holds](write-refusals.md#invalid_fence), [fence repair](repair.md#fences) and the [fence format](fence-format.md).diff --git a/src/commands/doctor/checks/local-ipc.ts b/src/commands/doctor/checks/local-ipc.tsnew file mode 100644index 0000000000..202bd77c72--- /dev/null+++ b/src/commands/doctor/checks/local-ipc.ts@@ -0,0 +1,36 @@+/**+ * #6573: the brain's local IPC socket paths (resolve and, on PGLite,+ * persistence) fit the platform's AF_UNIX budget. On Windows a long PGLite+ * data-dir path moves to the per-user run dir; only a path still too long+ * there is reported, as `ipc_path_too_long`. Silent when every path fits.+ */+import { loadConfig } from '../../../core/config.ts';+import { resolveSocketPathForConfig } from '../../../core/context/resolve-ipc.ts';+import { findIpcPathTooLong, ipcPathTooLongFix, ipcPathTooLongMessage } from '../../../core/context/ipc-path-too-long.ts';+import type { Check } from '../../doctor.ts';+import type { DoctorContext, DoctorEntry } from '../context.ts';++async function runIpcSocketPath(_ctx: DoctorContext): Promise<Check[]> {+ const checks: Check[] = [];+ let cfg: ReturnType<typeof loadConfig> = null;+ try { cfg = loadConfig(); } catch { return checks; }+ if (!cfg) return checks;+ let paths: Array<string | null>;+ try { paths = [resolveSocketPathForConfig(cfg), resolveSocketPathForConfig(cfg, 'persistence')]; } catch { return checks; }+ const problem = findIpcPathTooLong(paths);+ if (!problem) return checks;+ checks.push({+ name: 'ipc_socket_path',+ status: 'warn',+ message: ipcPathTooLongMessage(problem),+ details: { ...problem },+ fix: ipcPathTooLongFix(),+ });+ return checks;+}++export const ipcSocketPathEntry: DoctorEntry = {+ name: 'ipc_socket_path',+ emits: ['ipc_socket_path'],+ run: runIpcSocketPath,+};diff --git a/src/commands/doctor/registry.ts b/src/commands/doctor/registry.tsindex 13da7fe1d3..937d2b4acf 100644--- a/src/commands/doctor/registry.ts+++ b/src/commands/doctor/registry.ts@@ -40,6 +40,7 @@ import {connectionEntry,connectionGateEntry,} from './checks/db-connection.ts';+import { ipcSocketPathEntry } from './checks/local-ipc.ts';import {pgvectorEntry,rlsEntry,@@ -148,6 +149,7 @@ export const DOCTOR_CHECK_REGISTRY: readonly DoctorEntry[] = [harnessWiringDoctorEntry,agentContractEntry,pgliteDataDirEntry,+ ipcSocketPathEntry,projectionResidentEntry,offlineConnectionEntry,dbChecksGateEntry,diff --git a/src/core/context/ipc-path-too-long.ts b/src/core/context/ipc-path-too-long.tsnew file mode 100644index 0000000000..0b368dd028--- /dev/null+++ b/src/core/context/ipc-path-too-long.ts@@ -0,0 +1,42 @@+/**+ * #6573: one wording for a local IPC socket path that does not fit the+ * platform's AF_UNIX budget even after the per-user run-dir fallback, shared+ * by the serve's startup log and doctor's `ipc_socket_path` check.+ */+import type { Action } from '../agent-output.ts';+import { localIpcPathTooLong } from './ipc-path.ts';++export interface IpcPathTooLong {+ code: 'ipc_path_too_long';+ path: string;+ bytes: number;+ limit: number;+}++/** The first of `paths` (resolved socket paths) that is still too long, as a typed report. */+export function findIpcPathTooLong(paths: ReadonlyArray<string | null | undefined>): IpcPathTooLong | null {+ for (const path of paths) {+ if (!path) continue;+ const problem = localIpcPathTooLong(path);+ if (problem) return { code: 'ipc_path_too_long', ...problem };+ }+ return null;+}++export function ipcPathTooLongMessage(problem: IpcPathTooLong): string {+ return `ipc_path_too_long: the local IPC socket path ${problem.path} is ${problem.bytes} bytes, over this platform's ${problem.limit}-byte limit, ` ++ 'so hooks and local commands cannot reach gbrain serve on this brain. Move the brain to a shorter path, then restart serve.';+}++export function ipcPathTooLongFix(): Action {+ return {+ argv: ['gbrain', 'config', 'set', 'database_path', '<SHORTER_DATA_DIR>'],+ inputs: [{ name: 'SHORTER_DATA_DIR', how: 'Stop gbrain serve, move the PGLite data directory to a path near the drive root (for example C:\\gbrain\\brain.pglite), and pass that new path.' }],+ consent: [],+ actor: 'user',+ why: 'The socket path is derived from the data directory; a shorter data directory gives a socket path the operating system accepts.',+ verify: { argv: ['gbrain', 'doctor', '--only', 'ipc_socket_path', '--json'] },+ docs: 'docs/guides/troubleshooting.md#ipc-path-too-long',+ requires_exclusive: true,+ };+}diff --git a/src/core/context/ipc-path.ts b/src/core/context/ipc-path.tsindex 6ea76ead78..60f8e8bbf6 100644--- a/src/core/context/ipc-path.ts+++ b/src/core/context/ipc-path.ts@@ -1,13 +1,19 @@import { createHash } from 'node:crypto';import { accessSync, chmodSync, constants, lstatSync, mkdirSync, realpathSync } from 'node:fs';-import { basename, dirname, join, resolve } from 'node:path';+import { homedir } from 'node:os';+import { basename, dirname, join, resolve, win32 } from 'node:path';import { removeNativeWindowsUnixSocket, tryAcquireNativeIpcMutex, tryAcquireNativeLock } from '../persistence/native-lock.ts';import { windowsPipeName } from './windows-ipc.ts';// Darwin sockaddr_un.sun_path is 104 bytes including the terminating NUL.// https://github.com/apple-oss-distributions/xnu/blob/main/bsd/sys/un.hexport const UNIX_SOCKET_PATH_MAX_BYTES = 103;-function pipe(path: string): boolean { return process.platform === 'win32' && /^[\\/]{2}[.?][\\/]pipe[\\/]/i.test(path); }+// Windows afunix.sys sockaddr_un.sun_path is 108 bytes including the+// terminating NUL; Bun copies the path into it as UTF-8, so a non-ASCII+// profile or data-dir path costs more bytes than characters.+export const WINDOWS_UNIX_SOCKET_PATH_MAX_BYTES = 107;+const PIPE_PREFIX = /^[\\/]{2}[.?][\\/]pipe[\\/]/i;+function pipe(path: string): boolean { return process.platform === 'win32' && PIPE_PREFIX.test(path); }function systemRoot(): string { return process.platform === 'darwin' ? '/private/tmp' : '/tmp'; }function uid(): number {const value = process.getuid?.();@@ -25,9 +31,22 @@ function canonicalPath(path: string): string {}}-/** Discovery is read-only and independent of HOME/TMPDIR and the database engine. */+/**+ * Discovery is read-only and independent of HOME/TMPDIR and the database+ * engine. Every caller (serve, hooks, reflex, delegates, bootstrap verify)+ * derives its path here, so server and client agree on the fallback.+ *+ * POSIX: a path over the Unix byte budget moves to the private+ * `/tmp/gbi-<uid>-<sha256>/s` fallback. Windows (#6573): a PGLite data-dir+ * socket (`<data dir>\.gbrain-<kind>.sock`) over the afunix budget moves to+ * the per-user run dir, `%USERPROFILE%\.gbrain\run\<kind>-<hash12(canonical+ * data dir)>.sock`, the scheme Postgres brains use; the turn_context secret+ * stays `.gbrain-ipc-secret` in the data dir. A path that is still too long+ * there is reported by `localIpcPathTooLong` (`ipc_path_too_long`).+ */export function localIpcSocketPath(legacyPath: string): string {- if (process.platform === 'win32' || fallback(legacyPath)) return legacyPath;+ if (process.platform === 'win32') return windowsLocalIpcSocketPath(legacyPath, windowsProfileDir(), canonicalPath);+ if (fallback(legacyPath)) return legacyPath;const canonical = canonicalPath(legacyPath);if (Buffer.byteLength(canonical) <= UNIX_SOCKET_PATH_MAX_BYTES) {return Buffer.byteLength(legacyPath) <= UNIX_SOCKET_PATH_MAX_BYTES ? legacyPath : canonical;@@ -37,6 +56,35 @@ export function localIpcSocketPath(legacyPath: string): string {if (Buffer.byteLength(path) > UNIX_SOCKET_PATH_MAX_BYTES) throw new Error('Local IPC fallback exceeds the Unix socket path budget.');return path;}+function windowsProfileDir(): string { return process.env.USERPROFILE || homedir(); }++/**+ * The Windows socket path for `legacyPath`: the data-dir path when it fits+ * afunix, else the per-user run-dir path for a `.gbrain-<kind>.sock` socket.+ * Any other path (a named pipe, a Postgres run-dir socket) is returned as is.+ * Pure over its inputs so the selection is testable off Windows.+ */+export function windowsLocalIpcSocketPath(legacyPath: string, profileDir: string, canonical: (path: string) => string): string {+ if (PIPE_PREFIX.test(legacyPath)) return legacyPath;+ if (Buffer.byteLength(legacyPath, 'utf8') <= WINDOWS_UNIX_SOCKET_PATH_MAX_BYTES) return legacyPath;+ const kind = /^\.gbrain-([a-z]+)\.sock$/.exec(win32.basename(legacyPath))?.[1];+ if (!kind) return legacyPath;+ const dataDir = win32.dirname(canonical(legacyPath)).toLowerCase();+ const key = createHash('sha256').update(dataDir).digest('hex').slice(0, 12);+ return win32.join(profileDir, '.gbrain', 'run', `${kind}-${key}.sock`);+}++/** #6573: the resolved socket path, when it is still over this platform's AF_UNIX byte budget. */+export function localIpcPathTooLong(legacyPath: string): { path: string; bytes: number; limit: number } | null {+ let path: string;+ try { path = localIpcSocketPath(legacyPath); }+ catch { return { path: legacyPath, bytes: Buffer.byteLength(legacyPath, 'utf8'), limit: UNIX_SOCKET_PATH_MAX_BYTES }; }+ if (pipe(path)) return null;+ const limit = process.platform === 'win32' ? WINDOWS_UNIX_SOCKET_PATH_MAX_BYTES : UNIX_SOCKET_PATH_MAX_BYTES;+ const bytes = Buffer.byteLength(path, 'utf8');+ return bytes > limit ? { path, bytes, limit } : null;+}+function fallback(path: string): boolean {return process.platform !== 'win32' && [systemRoot(), ...(process.platform === 'darwin' ? ['/tmp'] : [])].includes(dirname(dirname(path)))&& /^gbi-\d+-[a-f0-9]{64}$/.test(basename(dirname(path))) && basename(path) === 's';diff --git a/src/core/doctor-categories.ts b/src/core/doctor-categories.tsindex 85ba5b7973..054e2cabfb 100644--- a/src/core/doctor-categories.ts+++ b/src/core/doctor-categories.ts@@ -294,6 +294,8 @@ export const OPS_CHECK_NAMES: ReadonlySet<string> = new Set(['writer_version','pgbouncer_prepare','pglite_data_dir',+ // #6573: a local IPC socket path over the platform's AF_UNIX budget (doctor/checks/local-ipc.ts).+ 'ipc_socket_path',// db-availability loop: engine-fit + repair-recurrence signals.'pglite_scale','db_repair_recurrence',diff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex 01178a9914..da1e082622 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -278,6 +278,7 @@ export const CODES = {invalid_source_uri: { class: 'caller', summary: "The page has a stored file source_uri that cannot be resolved to a local filesystem path." },invalid_token: { class: 'host_only', summary: "The bearer token is missing, invalid, or revoked." },invalid_write_wait: { class: 'caller', summary: "Invalid write wait." },+ ipc_path_too_long: { class: 'host_only', summary: "The brain's local IPC socket path is longer than the operating system allows, even after the per-user run-dir fallback, so hooks and local commands cannot reach gbrain serve.", why: 'A Unix-domain socket path must fit sockaddr_un (107 bytes on Windows afunix, 103 on macOS); on Windows a long PGLite data-dir path already moves to %USERPROFILE%\\.gbrain\\run, and only a profile path too long for that is reported.', docs: 'docs/guides/troubleshooting.md#ipc-path-too-long', suggestion: 'Stop gbrain serve, move the brain to a shorter path (`gbrain config set database_path <shorter path>` after moving the data directory), then restart serve.', fix: { argv: ['gbrain', 'doctor', '--only', 'ipc_socket_path', '--json'], consent: [], actor: 'agent', why: 'Read-only: reports the socket path, its byte count and the limit.', requires_exclusive: false, verify: { argv: ['gbrain', 'doctor', '--only', 'ipc_socket_path', '--json'] } } },legacy_job_selection_invalid: { class: 'caller', summary: "The legacy job selection is invalid." },legacy_jobs_active: { class: 'caller', summary: "Legacy jobs are still active." },local_conflict: { class: 'caller', summary: "A local file or registration conflicts with the requested change." },diff --git a/src/mcp/resolve-ipc-binding.ts b/src/mcp/resolve-ipc-binding.tsindex 14d59f8c5e..655857f60a 100644--- a/src/mcp/resolve-ipc-binding.ts+++ b/src/mcp/resolve-ipc-binding.ts@@ -40,6 +40,7 @@ import { makeContextPackIpcHandler } from './context-pack-handler.ts';import { logBriefDeliveryFireAndForget, logTurnContextDeliveryFireAndForget } from '../core/context/volunteer-events.ts';import { persistenceSocketPathForConfig, startPersistenceIpcServer, type PersistenceIpcProvider, type PersistenceIpcBinding } from '../core/persistence/ipc.ts';import { residentPersistenceConfig } from '../core/persistence/local-client.ts';+import { findIpcPathTooLong, ipcPathTooLongMessage } from '../core/context/ipc-path-too-long.ts';export interface ResolveIpcBinding {/** The bound listener for this serve's own resolve socket, or null while it is not bound (best-effort). */@@ -153,11 +154,19 @@ export async function bindResolveIpcForServe(const legacySocket = resolveSocketPathForConfig(cfg);if (!resolveSocket || !legacySocket) return NULL_BINDING;+ // #6573: a socket path the OS cannot bind (even after the per-user+ // run-dir fallback) is reported once, typed, and never retried.+ const tooLong = (path: string | null) => {+ const problem = findIpcPathTooLong([path]);+ if (problem) process.stderr.write(`[resolve-ipc] ${ipcPathTooLongMessage(problem)}\n`);+ return problem !== null;+ };+// The owner socket follows the brain the engine opened, which may be a mount (#5237).const owner = residentPersistenceConfig(cfg);if (persistenceProvider && owner?.engine === 'pglite') {const persistenceSocket = persistenceSocketPathForConfig(owner);- if (persistenceSocket) {+ if (persistenceSocket && !tooLong(persistenceSocket)) {try { persistence = await startPersistenceIpcServer(persistenceSocket, persistenceProvider); }catch {process.stderr.write('[persistence-ipc] listener unavailable; local callers will receive owner_unavailable.\n');@@ -305,6 +314,7 @@ export async function bindResolveIpcForServe(// that completes after close() is closed at once. Persistence is never// re-set-up here.const slots = [resolveSocket, ...(legacySocket === resolveSocket ? [] : [legacySocket])]+ .filter(path => !tooLong(path)).map(path => ({ path, server: null as Server | null, timer: undefined as ReturnType<typeof setTimeout> | undefined }));const rebindDelayMs = opts.rebindDelayMs ?? defaultRebindDelayMs;let closed = false;@@ -328,10 +338,10 @@ export async function bindResolveIpcForServe(};await serialized(async () => { for (const slot of slots) await bind(slot, false); });- const own = slots[0]!;+ const own = slots.find(slot => slot.path === resolveSocket);return {- get server() { return own.server; },- get socketPath() { return own.server ? resolveSocket : null; },+ get server() { return own?.server ?? null; },+ get socketPath() { return own?.server ? resolveSocket : null; },...(persistence ? { persistence } : {}),close: () => {if (closed) return;diff --git a/test/fixtures/goldens/doctor/registry-build-checks.json b/test/fixtures/goldens/doctor/registry-build-checks.jsonindex f3fc37b7ba..27b783cc3d 100644--- a/test/fixtures/goldens/doctor/registry-build-checks.json+++ b/test/fixtures/goldens/doctor/registry-build-checks.json@@ -233,6 +233,10 @@"category": "brain","name": "pglite_scratch_probe"},+ {+ "category": "ops",+ "name": "ipc_socket_path"+ },{"category": "brain","name": "text_projection_readiness"diff --git a/test/ipc-path-windows-fallback-6573.test.ts b/test/ipc-path-windows-fallback-6573.test.tsnew file mode 100644index 0000000000..0f3ffaf04b--- /dev/null+++ b/test/ipc-path-windows-fallback-6573.test.ts@@ -0,0 +1,133 @@+/**+ * #6573: on Windows a PGLite data-dir socket path over afunix's 108-byte `sun_path` (107 bytes plus NUL, measured as+ * the UTF-8 bytes Bun copies into it) moves to the per-user run dir, `%USERPROFILE%\.gbrain\run\<kind>-<hash12>.sock`,+ * the scheme Postgres brains use; a path still too long there is reported as `ipc_path_too_long` by the serve log and+ * doctor's `ipc_socket_path` check, with byte counts and the fix.+ *+ * Protects the selection rules (pure `windowsLocalIpcSocketPath`): short paths and named pipes stay; a long path and a+ * short-in-characters but long-in-bytes non-ASCII path move; the key is the canonical data dir, case-folded, per kind;+ * the turn_context secret stays in the data dir. Off Windows the end-to-end cases force `process.platform` to win32+ * (the platform is read per call); the native bind, round trip and stability probe live in+ * test/windows-ipc-long-path-6573.test.ts on the windows-latest row. Fails on master: the win32 branch returned the+ * data-dir path unchanged, so every listen() on a long data dir failed and only GBRAIN_DEBUG said why.+ */+import { afterEach, describe, expect, test } from 'bun:test';+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join, win32 } from 'node:path';+import { createHash } from 'node:crypto';+import { localIpcPathTooLong, localIpcSocketPath, windowsLocalIpcSocketPath, WINDOWS_UNIX_SOCKET_PATH_MAX_BYTES } from '../src/core/context/ipc-path.ts';+import { ipcSecretPathForConfig, resolveSocketPathForConfig } from '../src/core/context/resolve-ipc.ts';+import { findIpcPathTooLong, ipcPathTooLongMessage } from '../src/core/context/ipc-path-too-long.ts';+import { ipcSocketPathEntry } from '../src/commands/doctor/checks/local-ipc.ts';+import type { DoctorContext } from '../src/commands/doctor/context.ts';+import { withEnv } from './helpers/with-env.ts';++const PROFILE = String.raw`C:\Users\alice-example`;+const identity = (path: string) => path;+const key = (dir: string) => createHash('sha256').update(dir.toLowerCase()).digest('hex').slice(0, 12);+const bytes = (path: string) => Buffer.byteLength(path, 'utf8');++const dirs: string[] = [];+afterEach(() => { for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }); });++async function asWindows<T>(fn: () => Promise<T>): Promise<T> {+ if (process.platform === 'win32') return fn();+ const original = Object.getOwnPropertyDescriptor(process, 'platform')!;+ Object.defineProperty(process, 'platform', { ...original, value: 'win32' });+ try { return await fn(); } finally { Object.defineProperty(process, 'platform', original); }+}++describe('windowsLocalIpcSocketPath (#6573)', () => {+ test('a data-dir socket that fits afunix stays where it is', () => {+ const path = String.raw`C:\gbrain\brain.pglite\.gbrain-resolve.sock`;+ expect(windowsLocalIpcSocketPath(path, PROFILE, identity)).toBe(path);+ });++ test('a long data-dir socket moves to the per-user run dir, keyed by kind and data dir', () => {+ const dir = 'C:\\Users\\alice-example\\Documents\\Projects\\' + 'nested-folder\\'.repeat(5) + 'brain.pglite';+ const resolve = `${dir}\\.gbrain-resolve.sock`, persistence = `${dir}\\.gbrain-persistence.sock`;+ expect(bytes(resolve)).toBeGreaterThan(WINDOWS_UNIX_SOCKET_PATH_MAX_BYTES);+ expect(windowsLocalIpcSocketPath(resolve, PROFILE, identity)).toBe(`${PROFILE}\\.gbrain\\run\\resolve-${key(dir)}.sock`);+ expect(windowsLocalIpcSocketPath(persistence, PROFILE, identity)).toBe(`${PROFILE}\\.gbrain\\run\\persistence-${key(dir)}.sock`);+ // Windows paths are case-insensitive: one brain, one socket.+ expect(windowsLocalIpcSocketPath(resolve.toUpperCase().replace('.GBRAIN-RESOLVE.SOCK', '.gbrain-resolve.sock'), PROFILE, identity))+ .toBe(windowsLocalIpcSocketPath(resolve, PROFILE, identity));+ // The canonical (realpath) data dir is the key, not the spelling the config used.+ const longJunction = 'C:\\junction\\' + 'x'.repeat(100) + String.raw`\.gbrain-resolve.sock`;+ expect(windowsLocalIpcSocketPath(longJunction, PROFILE, () => resolve)).toBe(`${PROFILE}\\.gbrain\\run\\resolve-${key(dir)}.sock`);+ });++ test('the budget is UTF-8 bytes: a path short in characters but long in bytes moves', () => {+ const dir = 'C:\\Users\\' + 'é'.repeat(40) + String.raw`\brain.pglite`;+ const path = `${dir}\\.gbrain-resolve.sock`;+ expect(path.length).toBeLessThanOrEqual(WINDOWS_UNIX_SOCKET_PATH_MAX_BYTES);+ expect(bytes(path)).toBeGreaterThan(WINDOWS_UNIX_SOCKET_PATH_MAX_BYTES);+ expect(windowsLocalIpcSocketPath(path, PROFILE, identity)).toBe(`${PROFILE}\\.gbrain\\run\\resolve-${key(dir)}.sock`);+ });++ test('named pipes and already-keyed run-dir sockets are never rewritten', () => {+ const pipe = String.raw`\\.\pipe\gbrain-` + 'p'.repeat(120);+ expect(windowsLocalIpcSocketPath(pipe, PROFILE, identity)).toBe(pipe);+ const runDir = 'C:\\Users\\alice-example\\' + 'deep\\'.repeat(20) + String.raw`.gbrain\run\resolve-0123456789ab.sock`;+ expect(windowsLocalIpcSocketPath(runDir, PROFILE, identity)).toBe(runDir);+ });+});++describe('Windows long PGLite paths end to end, platform forced off Windows (#6573)', () => {+ function brain(depth: number): { home: string; profile: string; dataDir: string } {+ const root = mkdtempSync(join(tmpdir(), 'gb-6573-'));+ dirs.push(root);+ const dataDir = join(root, 'd'.repeat(depth), 'brain.pglite');+ mkdirSync(dataDir, { recursive: true });+ const home = join(root, 'home');+ mkdirSync(join(home, '.gbrain'), { recursive: true });+ writeFileSync(join(home, '.gbrain', 'config.json'), JSON.stringify({ engine: 'pglite', database_path: dataDir }));+ return { home, profile: join(root, 'pröfile'), dataDir };+ }++ test('server and client resolve the same run-dir socket; the secret stays in the data dir', async () => {+ const { profile, dataDir } = brain(90);+ await withEnv({ USERPROFILE: profile }, () => asWindows(async () => {+ const cfg = { engine: 'pglite' as const, database_path: dataDir };+ const legacy = join(dataDir, '.gbrain-resolve.sock');+ expect(bytes(legacy)).toBeGreaterThan(WINDOWS_UNIX_SOCKET_PATH_MAX_BYTES);+ const resolved = resolveSocketPathForConfig(cfg)!;+ const runDir = win32.join(profile, '.gbrain', 'run');+ expect(resolved.startsWith(`${runDir}\\resolve-`)).toBe(true);+ expect(bytes(resolved)).toBeLessThanOrEqual(WINDOWS_UNIX_SOCKET_PATH_MAX_BYTES);+ expect(localIpcSocketPath(legacy)).toBe(resolved);+ expect(localIpcSocketPath(resolved)).toBe(resolved);+ expect(resolveSocketPathForConfig(cfg, 'persistence')!.startsWith(`${runDir}\\persistence-`)).toBe(true);+ expect(ipcSecretPathForConfig(cfg)).toBe(join(dataDir, '.gbrain-ipc-secret'));+ expect(localIpcPathTooLong(legacy)).toBeNull();+ }));+ });++ test('a run-dir path that is still too long is reported, typed, with byte counts and the fix', async () => {+ const { home, dataDir } = brain(90);+ const profile = join(dirs[0]!, 'p'.repeat(90));+ await withEnv({ USERPROFILE: profile, GBRAIN_HOME: home, GBRAIN_DATABASE_URL: undefined, DATABASE_URL: undefined }, () => asWindows(async () => {+ const legacy = join(dataDir, '.gbrain-resolve.sock');+ const problem = findIpcPathTooLong([localIpcSocketPath(legacy)]);+ expect(problem).toMatchObject({ code: 'ipc_path_too_long', limit: WINDOWS_UNIX_SOCKET_PATH_MAX_BYTES });+ expect(problem!.bytes).toBe(bytes(problem!.path));+ expect(problem!.bytes).toBeGreaterThan(WINDOWS_UNIX_SOCKET_PATH_MAX_BYTES);+ expect(ipcPathTooLongMessage(problem!)).toContain(`${problem!.bytes} bytes`);++ const checks = await ipcSocketPathEntry.run({} as DoctorContext) as Array<{ name: string; status: string; details?: Record<string, unknown>; fix?: { argv?: string[]; verify?: { argv?: string[] }; actor?: string } }>;+ expect(checks).toHaveLength(1);+ expect(checks[0]).toMatchObject({ name: 'ipc_socket_path', status: 'warn', details: { code: 'ipc_path_too_long', limit: WINDOWS_UNIX_SOCKET_PATH_MAX_BYTES } });+ expect(checks[0]!.fix?.argv?.slice(0, 4)).toEqual(['gbrain', 'config', 'set', 'database_path']);+ expect(checks[0]!.fix?.actor).toBe('user');+ expect(checks[0]!.fix?.verify?.argv).toEqual(['gbrain', 'doctor', '--only', 'ipc_socket_path', '--json']);+ }));+ });++ test('doctor stays silent when every socket path fits', async () => {+ const { home, profile } = brain(10);+ await withEnv({ USERPROFILE: profile, GBRAIN_HOME: home, GBRAIN_DATABASE_URL: undefined, DATABASE_URL: undefined }, () => asWindows(async () => {+ expect(await ipcSocketPathEntry.run({} as DoctorContext)).toEqual([]);+ }));+ });+});diff --git a/test/windows-ipc-long-path-6573.test.ts b/test/windows-ipc-long-path-6573.test.tsnew file mode 100644index 0000000000..247b0cd6cf--- /dev/null+++ b/test/windows-ipc-long-path-6573.test.ts@@ -0,0 +1,139 @@+/**+ * #6573, native Windows only (its own step on the windows-latest security-regressions row): a PGLite brain whose data+ * directory is deep enough that `<data dir>\.gbrain-resolve.sock` passes afunix's 108-byte `sun_path` still serves+ * hooks, through the per-user run-dir socket `%USERPROFILE%\.gbrain\run\<kind>-<hash12>.sock`, under a profile path+ * with non-ASCII characters (afunix receives the UTF-8 bytes Bun copies).+ *+ * Protects: the resolve listener binds at the run-dir path and answers resolve and an authenticated turn_context (the+ * secret stays `.gbrain-ipc-secret` in the data dir); the persistence listener binds and answers capabilities; 20+ * bind / round-trip / close cycles stay stable. Servers and this file's own clients are closed from the test body,+ * after a macrotask turn, never inside a socket callback: Bun 1.4.x on Windows frees a socket closed during a nested+ * libuv tick while the outer dispatch still holds it (#6462, oven-sh/bun#40023). Off Windows every case is skipped;+ * the selection logic is covered on every OS by test/ipc-path-windows-fallback-6573.test.ts.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import net, { type Server } from 'node:net';+import { once } from 'node:events';+import { mkdirSync, mkdtempSync, realpathSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { WINDOWS_UNIX_SOCKET_PATH_MAX_BYTES } from '../src/core/context/ipc-path.ts';+import {+ ensureIpcSecretForConfig,+ ipcSecretPathForConfig,+ IPC_UNAVAILABLE,+ readIpcSecretForConfig,+ requestTurnContext,+ resolveSocketPathForConfig,+ resolveViaIpc,+ startResolveIpcServer,+} from '../src/core/context/resolve-ipc.ts';+import { persistenceSocketPathForConfig, requestPersistenceCapabilities, startPersistenceIpcServer } from '../src/core/persistence/ipc.ts';++const NATIVE = process.platform === 'win32';+const BRAIN = '10000000-0000-4000-8000-000000000001';+let root = '';+let priorProfile: string | undefined;+let cfg: { engine: 'pglite'; database_path: string };++const turn = () => new Promise<void>(resolve => setTimeout(resolve, 0));+async function closeServer(server: Server): Promise<void> {+ await turn();+ const closed = once(server, 'close');+ server.close();+ await closed;+ await turn();+}++/** One request line, one response line, with the client destroyed from a later macrotask. */+async function rawRoundTrip(path: string, line: string): Promise<unknown> {+ const socket = net.createConnection(path);+ try {+ await once(socket, 'connect');+ socket.write(`${line}\n`);+ let buffer = '';+ for await (const chunk of socket) {+ buffer += String(chunk);+ const nl = buffer.indexOf('\n');+ if (nl >= 0) return JSON.parse(buffer.slice(0, nl));+ }+ return null;+ } finally {+ await turn();+ socket.destroy();+ await turn();+ }+}++describe.skipIf(!NATIVE)('Windows long PGLite IPC paths use the per-user run dir (#6573)', () => {+ beforeAll(() => {+ root = mkdtempSync(join(realpathSync.native(tmpdir()), 'gb-6573-'));+ priorProfile = process.env.USERPROFILE;+ const profile = join(root, 'prøfile-é');+ mkdirSync(profile, { recursive: true });+ process.env.USERPROFILE = profile;+ const dataDir = join(root, 'b'.repeat(80), 'brain.pglite');+ mkdirSync(dataDir, { recursive: true });+ cfg = { engine: 'pglite', database_path: dataDir };+ });+ afterAll(() => {+ if (priorProfile === undefined) delete process.env.USERPROFILE; else process.env.USERPROFILE = priorProfile;+ rmSync(root, { recursive: true, force: true });+ });++ test('the data-dir path is over the afunix budget and the run-dir path fits it', () => {+ const legacy = join(cfg.database_path, '.gbrain-resolve.sock');+ expect(Buffer.byteLength(legacy, 'utf8')).toBeGreaterThan(WINDOWS_UNIX_SOCKET_PATH_MAX_BYTES);+ const resolved = resolveSocketPathForConfig(cfg)!;+ expect(resolved.startsWith(join(process.env.USERPROFILE!, '.gbrain', 'run', 'resolve-'))).toBe(true);+ expect(Buffer.byteLength(resolved, 'utf8')).toBeLessThanOrEqual(WINDOWS_UNIX_SOCKET_PATH_MAX_BYTES);+ expect(ipcSecretPathForConfig(cfg)).toBe(join(cfg.database_path, '.gbrain-ipc-secret'));+ });++ test('resolve and authenticated turn_context reach a listener bound at the run-dir path', async () => {+ const path = resolveSocketPathForConfig(cfg)!;+ const secret = ensureIpcSecretForConfig(cfg)!;+ const server = await startResolveIpcServer(path, {+ resolve: async () => null,+ turn_context: async () => ({ text: 'ok', pointers: [], volunteered: [] } as never),+ }, { secret, boundSourceId: 'default' });+ expect(server).not.toBeNull();+ try {+ expect(await resolveViaIpc(path, { candidates: [] })).toBeNull();+ const reply = await requestTurnContext(path, { secret: readIpcSecretForConfig(cfg)!, window: [{ role: 'user', text: 'hello' }] }, { timeoutMs: 5_000 });+ expect(reply).not.toBe(IPC_UNAVAILABLE);+ expect(reply).toMatchObject({ ok: true, protocol: 2 });+ } finally {+ await closeServer(server!);+ }+ });++ test('the persistence listener binds at its run-dir path and answers capabilities', async () => {+ const path = persistenceSocketPathForConfig(cfg)!;+ expect(path.startsWith(join(process.env.USERPROFILE!, '.gbrain', 'run', 'persistence-'))).toBe(true);+ const binding = await startPersistenceIpcServer(path, { brainId: BRAIN, dispatch: async () => ({}) });+ expect(binding).not.toBeNull();+ try {+ expect((await requestPersistenceCapabilities(path)).brain_id).toBe(BRAIN);+ } finally {+ await turn();+ const closed = once(binding!.server, 'close');+ binding!.close();+ await closed;+ await turn();+ }+ });++ test('20 bind / round-trip / close cycles at the run-dir path stay stable', async () => {+ const path = resolveSocketPathForConfig(cfg)!;+ for (let i = 0; i < 20; i++) {+ const server = await startResolveIpcServer(path, { resolve: async () => null }, { boundSourceId: 'default' });+ expect(server).not.toBeNull();+ try {+ expect(await rawRoundTrip(path, JSON.stringify({ kind: 'resolve', candidates: [] }))).toEqual({ ok: true, block: null });+ } finally {+ await closeServer(server!);+ }+ }+ }, 120_000);+});