Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(backup): refuse unarchivable PGLite brains up front with a physical-copy runbook (#6649)
garrytand05883bbbc32
diff --git a/docs/architecture/key-files/google-and-loops.md b/docs/architecture/key-files/google-and-loops.mdindex 2a4843d848..f74f4ca8ae 100644--- a/docs/architecture/key-files/google-and-loops.md+++ b/docs/architecture/key-files/google-and-loops.md@@ -39,6 +39,7 @@ Historical Gmail repair selects explicit nested MIME metadata fields, excluding- `src/core/agent-install/` + `scripts/setup-in-agent.sh` — Package-versioned non-root installation into a verified persistent root. Absolute launchers isolate ambient routing and credentials; local launchers pin the host brain and installed source, while thin-client launchers leave unqualified routing to the remote grant and preserve explicit CLI arguments. Receipts track ownership, pending enablement, non-secret failure codes, and an exact repair command, and repair retains database contents. Upgrades journal pending schema migrations before switching runtime metadata; retries use schema-only initialization without invoking host orchestration. Busy results remain structured and retryable without deleting live locks. Native instructions/routines remain pending until observed in the actual harness.- `src/core/backup/{archive,snapshot,quarantine,private-path}.ts` — bounded full-PGLite snapshots with checksums, credential-reference exclusions and fresh-root restoration. Portable entry validation rejects traversal, Windows aliases and case/normalization/file-directory collisions independently of native confinement. Recorded path flavor controls nested managed-path rebasing; unrecognized absolute page origins stay unchanged with reconnect guidance. Hold the database lock, detect changing inventories, detach external roots and quarantine unfinished jobs without deleting spending evidence. Windows uses direct .NET file/directory security APIs through bounded built-in PowerShell, without cmdlets, to protect new empty work/root/archive-temp paths before payload writes. Readback requires the current owner, protected DACL and exact deduplicated owner-plus-SYSTEM full-control rules, inheritance and propagation; unavailable enforcement refuses without changing existing parents or source data. Never replace the source installation. `backup-portability-native.serial.test.ts` checks real restore, fresh-process reopen, failure preservation and platform-native access controls with an independent read-only ACL inspector.+- `src/core/backup/preflight.ts` — #6649: before `createPgliteBackup` takes the lock, `pgliteBackupPreflight` refuses a flat or symlinked data dir (`unmanaged_database_path`) and an estimated archive over `BACKUP_ARCHIVE_MAX_BYTES` (`backup_too_large`: `estimatedTarBytes` counts tar headers and padding, plus managed files), both with the ask-user physical-copy runbook fix. `backup.ts` renders those two codes as their own envelope (legacy `reason` kept) instead of `storage_error`. Doctor's `pglite_data_dir` (`backupSizeCheck` in `checks/db-connection.ts`) warns on a healthy PGLite brain from 75% of the cap. `test/backup-preflight-6649.test.ts` uses sparse files and runs the restore drill.- `src/core/harness/registry.ts` — Canonical adapter identities, supported transports, credential-delivery mechanisms, guide links and dated evidence; legacy connection/register vocabularies derive their facts here. `scripts/build-harness-docs.ts` emits the user-facing adapter reference. A `manual` adapter such as `hermes` (stdio, `docs/mcp/HERMES.md`) installs as `pending` with its guide; no adapter claims a runtime-tested session without dated evidence.- `src/core/harness/credentials.ts` + `delivery.ts` + `install.ts` — Private credential handoff and host delivery journal, ownership-preserving native configuration and isolated thin launchers. A committed active client and matching current secret are prerequisites for recovery. Machine handoffs preserve optional POST/Basic authentication methods. Native setup is a distinct nested-client artifact; metadata reads never access journals or SDK client objects containing hashes. Configuration removal and server revocation are separate actions.diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.mdindex 247a20b476..705fcfda08 100644--- a/docs/guides/error-codes.md+++ b/docs/guides/error-codes.md@@ -178,6 +178,16 @@ More: [docs/guides/google-connect.md#troubleshooting](../../docs/guides/google-cMore: [docs/guides/in-agent-setup.md#6-back-up-the-complete-local-database](../../docs/guides/in-agent-setup.md#6-back-up-the-complete-local-database)+### backup_too_large++<a id="backup_too_large"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| `gbrain backup create` refused before writing anything: the PGLite brain's estimated archive size is over the 8 GiB backup-archive cap. | The archive format holds at most 8 GiB of payload and the dump is materialized in memory; refusing up front avoids a long dump that cannot be published. | Take a quiesced physical copy of the data directory instead (stop writers, copy, open the copy in an isolated GBRAIN_HOME, verify with gbrain doctor --json). Run: gbrain doctor --json | agent | `gbrain doctor --json` | 1 | no |++More: [docs/guides/in-agent-setup.md#large-or-non-standard-brains-quiesced-physical-copy](../../docs/guides/in-agent-setup.md#large-or-non-standard-brains-quiesced-physical-copy)+### benchmark_duplicate_task_id<a id="benchmark_duplicate_task_id"></a>@@ -3378,6 +3388,16 @@ More: [docs/guides/write-refusals.md#unclosed_ambiguous_tail](../../docs/guides/|---|---|---|---|---|---|---|| The caller's transport could not be identified. | A capability this request needs is not configured or not reachable on this brain. | A required capability is not available on this brain. Run `gbrain doctor --json` to see what is missing. | agent | `gbrain doctor --json` | 1 | no |+### unmanaged_database_path++<a id="unmanaged_database_path"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| `gbrain backup create` refused before writing anything: the PGLite data directory is not the managed `<root>/.gbrain/brain.pglite` (a flat config home, or a path reached through a symlink). | The archive records the managed root it can restore into and refuses to follow a symlink out of it, so a flat or aliased layout cannot be archived without risking a restore into the wrong place. | Take a quiesced physical copy into a new managed root (`<new-home>/.gbrain/brain.pglite`); the copy is then a normal layout that `gbrain backup create` accepts while it is under the 8 GiB cap. Run: gbrain doctor --json | agent | `gbrain doctor --json` | 1 | no |++More: [docs/guides/in-agent-setup.md#large-or-non-standard-brains-quiesced-physical-copy](../../docs/guides/in-agent-setup.md#large-or-non-standard-brains-quiesced-physical-copy)+### unmanaged_path<a id="unmanaged_path"></a>diff --git a/docs/guides/in-agent-setup.md b/docs/guides/in-agent-setup.mdindex 4a13e69d5f..56515524c7 100644--- a/docs/guides/in-agent-setup.md+++ b/docs/guides/in-agent-setup.md@@ -226,6 +226,44 @@ PostgreSQL 17 PGLite clusters, and at most 8 GiB of payload. `backup status` and`backup check` report file coverage; neither creates this snapshot. Markdownexports alone cannot recover facts that exist only in the database.+`backup create` checks both limits before it takes the lock or writes anything.+A data directory that is not `<root>/.gbrain/brain.pglite`, or one reached+through a symlink (for example a `.gbrain` alias to another volume), refuses+with `unmanaged_database_path`. A data directory whose estimated archive size+is over 8 GiB refuses with `backup_too_large`. Doctor's `pglite_data_dir` check+warns once the estimate passes 6 GiB, so you can plan before the refusal. Both+refusals point at the runbook below.++### Large or non-standard brains: quiesced physical copy++For a brain over the cap or in a flat or symlinked layout, the supported+recovery artifact is a physical copy of the stopped data directory. Ask the+user before step 1: it stops their memory service.++1. **Stop every writer.** Stop `gbrain serve`, autopilot and jobs workers, and+ any agent session using this brain. Then run `gbrain doctor --json`: doctor+ opens the brain only when no other gbrain process holds its PGLite lock, so+ a `pglite_data_dir` warning that names a live PID means a writer is still+ running.+2. **Copy.** Resolve the real data directory through any alias+ (`realpath ~/.gbrain/brain.pglite`) and copy it whole, with `config.json`,+ into a new isolated home, laid out as `<new-home>/.gbrain/brain.pglite` and+ `<new-home>/.gbrain/config.json`. Do not copy while anything runs against+ the brain, and do not start writers again until the copy finishes.+3. **Point the copy at itself.** Set `database_path` in the copied+ `config.json` to the copied data directory.+4. **Verify in isolation.** Run `GBRAIN_HOME=<new-home> gbrain doctor --json`+ and an entity recall against the copy before relying on it. The copy is the+ managed layout, so while it is under the cap, `GBRAIN_HOME=<new-home>+ gbrain backup create --output <new archive>` also archives it.++The restore drill in `test/backup-preflight-6649.test.ts` runs these steps on a+`.gbrain` alias to another directory: it copies the stopped brain, opens the+copy in its own home with the data intact, archives the copy and restores that+archive into a third root. Archives over 8 GiB are not supported yet; this+runbook is the recovery route until a streaming format ships+([#6649](https://github.com/garrytan/gbrain/issues/6649)).+## 7. Restore into a new rootUse an available GBrain runtime and a destination that **does not exist**:@@ -332,6 +370,7 @@ hosted access, also revoke that installation's grant on the host.| `pglite_busy` | Wait for the active command to finish and retry; stop a long-lived server through its owning process before using finite CLI mode | agent | none | retry the read-only command || Fresh conversation cannot recall the test | Inspect the native skill attachment and exact launcher invocation, then run explicit entity recall | user (reloads the native skill) | none | a `recall` from a fresh conversation || Backup says files changed | Pause the writer and create a new snapshot; do not treat the failed output as a backup | agent | none | the new snapshot's verification output |+| `unmanaged_database_path` or `backup_too_large` from `backup create` | Ask the user, then follow the [quiesced physical copy](#large-or-non-standard-brains-quiesced-physical-copy) runbook | user stops writers; agent copies and verifies | user agrees to stop writers | `GBRAIN_HOME=<new-home> gbrain doctor --json` || Restore target already exists | Choose another absent root; restore never overwrites existing state | agent | none | the restore output || A package or host URL is blocked | Complete the app's normal approval flow; preserve the error if access is denied | user | none | retry after approval |diff --git a/docs/guides/troubleshooting.md b/docs/guides/troubleshooting.mdindex 13beefaa46..3c126d44cd 100644--- a/docs/guides/troubleshooting.md+++ b/docs/guides/troubleshooting.md@@ -71,9 +71,12 @@| [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 |+| [`gbrain backup create` refuses with `unmanaged_database_path` or `backup_too_large`, or doctor's `pglite_data_dir` warns `backup_too_large`](#backup-too-large) | the brain is outside what the archive holds (a flat or symlinked layout, or over 8 GiB); ask the user, stop every writer, then take the [quiesced physical copy](in-agent-setup.md#large-or-non-standard-brains-quiesced-physical-copy) into a new isolated home | user stops writers; agent copies and verifies | user agrees to stop writers | `GBRAIN_HOME=<new-home> gbrain doctor --json` |<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="backup-too-large"></a>**`gbrain backup create` refuses with `unmanaged_database_path` or `backup_too_large`?** The PGLite backup archive holds one managed layout, `<root>/.gbrain/brain.pglite` with no symlink on its path, and at most 8 GiB of payload. The command now checks both before it takes the lock or writes anything, so nothing partial is left behind. A flat config home or a `.gbrain` alias to another volume gets `unmanaged_database_path`; a brain whose estimated archive is over the cap gets `backup_too_large`, and doctor's `pglite_data_dir` check warns from 6 GiB. The recovery for both is the [quiesced physical copy](in-agent-setup.md#large-or-non-standard-brains-quiesced-physical-copy): stop every writer, copy the real data directory and `config.json` into a new isolated home, point the copy's `database_path` at itself, and verify it with `GBRAIN_HOME=<new-home> gbrain doctor --json`. **Say to your agent:** *"My brain backup refuses; take a stopped physical copy and verify it."*+<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).diff --git a/src/commands/backup.ts b/src/commands/backup.tsindex 2b4566f0f3..1cea0e874c 100644--- a/src/commands/backup.ts+++ b/src/commands/backup.ts@@ -193,6 +193,11 @@ export async function runBackupCli(writeCliError(error, 'backup', { json, legacy: { ok: false, reason: 'invalid_params', message: error.message } });return { exitCode: 2 };}+ if (error instanceof OperationError && (error.code === 'backup_too_large' || error.code === 'unmanaged_database_path')) {+ const { writeCliError } = await import('../cli/cli-error.ts');+ writeCliError(error, 'backup', { json, legacy: { ok: false, reason: error.code, message: error.message } });+ return { exitCode: 1 };+ }const detail = (typeof error === 'object' && error !== null ? error : {}) as { code?: unknown; retryable?: unknown };const reason = typeof detail.code === 'string' && SAFE_ERROR_FIELD.test(detail.code) ? detail.code : 'backup_failed';const message = backupFailureMessage(error);diff --git a/src/commands/doctor/checks/db-connection.ts b/src/commands/doctor/checks/db-connection.tsindex 7a5f002910..00de3c0e1e 100644--- a/src/commands/doctor/checks/db-connection.ts+++ b/src/commands/doctor/checks/db-connection.ts@@ -1,6 +1,7 @@/*** Database reachability: the PGLite data-dir diagnosis and scratch-store probe- * that run when the connect failed, the connection check itself (live, or+ * that run when the connect failed, the near-backup-cap size warning on a+ * healthy PGLite brain (#6649), the connection check itself (live, or* synthesized when there is no engine), and the two early stops that end the* run before the DB checks.*@@ -17,6 +18,8 @@ import { exclusiveFix, liveServeOwner } from '../../../core/exclusive-fix.ts';import { startHeartbeat } from '../../../core/progress.ts';import { checkPgliteScratchProbe } from './core-health.ts';import { computePgliteDataDirCheck } from './pglite-worker.ts';+import { BACKUP_ARCHIVE_MAX_BYTES } from '../../../core/backup/archive.ts';+import { BACKUP_SIZE_WARN_RATIO, PHYSICAL_COPY_RUNBOOK, estimatedTarBytes, formatGiB, physicalCopyFix } from '../../../core/backup/preflight.ts';import type { Check } from '../../doctor.ts';import { classifyPgAccessError } from '../../../core/pg-access-classify.ts';import { dbRepairRecurrenceCheck } from './engine-fit.ts';@@ -63,6 +66,17 @@ async function runPgliteDataDir(ctx: DoctorContext): Promise<Check[]> {}}+ // #6649: a healthy PGLite brain nearing the backup-archive cap is warned before `gbrain backup create` refuses.+ if (engine && !fastMode && cfgForProbe?.engine === 'pglite' && cfgForProbe.database_path) {+ try {+ const { resolve } = await import('node:path');+ const sizeCheck = backupSizeCheck(resolve(cfgForProbe.database_path));+ if (sizeCheck) checks.push(sizeCheck);+ } catch {+ // Best-effort: an unreadable data dir must not stop doctor.+ }+ }+const dirExplainsFailure = dirVerdict === 'locked' || dirVerdict === 'missing';if (probeRequested || (pgliteInitFailed && !dirExplainsFailure)) {progress.start('doctor.pglite_probe');@@ -88,6 +102,26 @@ async function runPgliteDataDir(ctx: DoctorContext): Promise<Check[]> {return checks;}+/**+ * #6649: `pglite_data_dir` warns once the data dir's estimated archive size+ * passes BACKUP_SIZE_WARN_RATIO of the 8 GiB backup cap, naming+ * `backup_too_large` and the physical-copy runbook. Null below the ratio.+ * `estimatedBytes` is injectable so tests need not write gigabytes.+ */+export function backupSizeCheck(dataDir: string, estimatedBytes?: number): Check | null {+ const bytes = estimatedBytes ?? estimatedTarBytes(dataDir);+ if (bytes < BACKUP_ARCHIVE_MAX_BYTES * BACKUP_SIZE_WARN_RATIO) return null;+ const over = bytes > BACKUP_ARCHIVE_MAX_BYTES;+ return {+ name: 'pglite_data_dir',+ status: 'warn',+ message: `backup_too_large: this PGLite brain needs about ${formatGiB(bytes)} in a backup archive, ${over ? 'over' : 'near'} the ${formatGiB(BACKUP_ARCHIVE_MAX_BYTES)} cap, ` ++ `so \`gbrain backup create\` ${over ? 'refuses it' : 'will refuse it soon'}. Plan a quiesced physical copy (${PHYSICAL_COPY_RUNBOOK}).`,+ details: { code: 'backup_too_large', data_dir: dataDir, estimated_bytes: bytes, limit_bytes: BACKUP_ARCHIVE_MAX_BYTES, over_limit: over },+ fix: physicalCopyFix(),+ };+}+export const pgliteDataDirEntry: DoctorEntry = {name: 'pglite_data_dir',emits: ['pglite_data_dir', 'pglite_scratch_probe'],diff --git a/src/core/backup/archive.ts b/src/core/backup/archive.tsindex 5879f6c228..bfa9cc9748 100644--- a/src/core/backup/archive.ts+++ b/src/core/backup/archive.ts@@ -7,7 +7,9 @@ import { protectNewBackupPath } from './private-path.ts';const MAGIC = Buffer.from('GBRAIN-BACKUP-1\n');const MAX_MANIFEST = 8 * 1024 * 1024;-const MAX_BYTES = 8 * 1024 * 1024 * 1024;+/** The archive's total payload cap (8 GiB); `gbrain backup create` checks it up front (#6649). */+export const BACKUP_ARCHIVE_MAX_BYTES = 8 * 1024 * 1024 * 1024;+const MAX_BYTES = BACKUP_ARCHIVE_MAX_BYTES;const MAX_FILES = 100_000;export interface ArchiveEntry { path: string; size: number; sha256: string }export interface ArchiveManifest { format_version: 1; entries: ArchiveEntry[]; [key: string]: unknown }diff --git a/src/core/backup/preflight.ts b/src/core/backup/preflight.tsnew file mode 100644index 0000000000..f6fe933515--- /dev/null+++ b/src/core/backup/preflight.ts@@ -0,0 +1,91 @@+/**+ * #6649: `gbrain backup create` on PGLite checks, before it takes the writer+ * lock or opens the database, that this recovery format can hold the brain:+ * the data dir must be the managed `<root>/.gbrain/brain.pglite` with no+ * symlink on the way (a flat or symlinked home is `unmanaged_database_path`),+ * and its estimated archive size must fit the 8 GiB cap (`backup_too_large`).+ * Both refusals name the same recovery: the quiesced physical-copy runbook.+ * Doctor's `pglite_data_dir` uses the same size estimate to warn early.+ */+import { lstatSync, readdirSync } from 'node:fs';+import { dirname, join, resolve } from 'node:path';+import type { Action } from '../agent-output.ts';+import { opError, type OperationError } from '../ops/contract.ts';+import { BACKUP_ARCHIVE_MAX_BYTES } from './archive.ts';++export const PHYSICAL_COPY_RUNBOOK = 'docs/guides/in-agent-setup.md#large-or-non-standard-brains-quiesced-physical-copy';+/** Doctor warns once the data dir's estimated archive size passes this share of the cap. */+export const BACKUP_SIZE_WARN_RATIO = 0.75;++const TAR_BLOCK = 512;++/**+ * Bytes `dumpDataDir` would write for `dir`: every regular file's apparent+ * size rounded up to a 512-byte tar block plus its header block, a header per+ * directory, and the two closing blocks. Symlinks are not followed.+ */+export function estimatedTarBytes(dir: string): number {+ let total = 2 * TAR_BLOCK;+ const walk = (path: string): void => {+ const stat = lstatSync(path);+ if (stat.isDirectory()) {+ total += TAR_BLOCK;+ for (const name of readdirSync(path)) walk(join(path, name));+ } else if (stat.isFile()) {+ total += TAR_BLOCK + Math.ceil(stat.size / TAR_BLOCK) * TAR_BLOCK;+ }+ };+ walk(dir);+ return total;+}++export type PgliteBackupLayout = 'managed' | 'flat' | 'symlinked';++/** Where the configured data dir sits relative to the managed `<root>/.gbrain/brain.pglite`. */+export function pgliteBackupLayout(root: string, dbPath: string): PgliteBackupLayout {+ const managed = join(root, '.gbrain', 'brain.pglite');+ if (resolve(dbPath) !== managed) return 'flat';+ for (let path = managed; path !== root && dirname(path) !== path; path = dirname(path)) {+ try { if (lstatSync(path).isSymbolicLink()) return 'symlinked'; } catch { /* missing: reported by the caller */ }+ }+ return 'managed';+}++const RUNBOOK_STEPS = 'Take a quiesced physical copy instead: stop every gbrain writer on this brain (gbrain serve, jobs and autopilot, agent sessions), ' ++ 'copy the whole data directory and config.json into a new, isolated GBRAIN_HOME, point that config\'s database_path at the copy, ' ++ `then verify the copy with gbrain doctor --json run with GBRAIN_HOME set to it before relying on it (runbook: ${PHYSICAL_COPY_RUNBOOK}).`;++/** The runbook needs the user (writers stop, a copy is made); the agent then runs doctor read-only. */+export function physicalCopyFix(): Action {+ return {+ ask_user: true, argv: ['gbrain', 'doctor', '--json'], consent: [], actor: 'agent', requires_exclusive: false, docs: PHYSICAL_COPY_RUNBOOK,+ why: 'Read-only, after the user agrees to the physical copy: doctor opens the brain only when no other gbrain process holds it, so a clean run shows the writers are stopped.',+ user_message: RUNBOOK_STEPS, verify: { argv: ['gbrain', 'doctor', '--json'] },+ };+}++/**+ * The refusal for a brain this recovery format cannot hold, or null when it can.+ * Reads only file metadata; `managedFileBytes` runs only for a managed layout.+ */+export function pgliteBackupPreflight(root: string, dbPath: string, managedFileBytes: () => number): OperationError | null {+ const layout = pgliteBackupLayout(root, dbPath);+ if (layout !== 'managed') {+ return opError('unmanaged_database_path',+ layout === 'flat'+ ? `This recovery format requires the data directory at ${join(root, '.gbrain', 'brain.pglite')}; this brain's database_path is ${dbPath}. Nothing was written.`+ : `This recovery format requires a data directory with no symlink on its path; ${join(root, '.gbrain', 'brain.pglite')} reaches the data through a symlink. Nothing was written.`,+ RUNBOOK_STEPS,+ { why: 'The archive records the managed root it can restore and refuses to follow a symlink out of it.', fix: physicalCopyFix(), docs: PHYSICAL_COPY_RUNBOOK, detail: `layout=${layout}` });+ }+ const bytes = estimatedTarBytes(dbPath) + managedFileBytes();+ if (bytes <= BACKUP_ARCHIVE_MAX_BYTES) return null;+ return opError('backup_too_large',+ `This brain needs about ${formatGiB(bytes)} in a backup archive (${bytes} bytes), over the archive's ${formatGiB(BACKUP_ARCHIVE_MAX_BYTES)} cap. Nothing was written.`,+ RUNBOOK_STEPS,+ { why: 'The archive format holds at most 8 GiB of payload; refusing before the dump avoids hours of work and a partial archive.', fix: physicalCopyFix(), docs: PHYSICAL_COPY_RUNBOOK, detail: `bytes=${bytes} limit=${BACKUP_ARCHIVE_MAX_BYTES}` });+}++export function formatGiB(bytes: number): string {+ return `${(bytes / 1024 ** 3).toFixed(2)} GiB`;+}diff --git a/src/core/backup/snapshot.ts b/src/core/backup/snapshot.tsindex 8e246a8c49..49605416ec 100644--- a/src/core/backup/snapshot.ts+++ b/src/core/backup/snapshot.ts@@ -15,6 +15,7 @@ import { quarantineRestoredExecution, rebaseRestorePath, relativeBackupPath, typimport { quarantineSharedSkillRestore, validateSharedSkillRestoreMode, type SharedSkillRestore, type SharedSkillRestoreOptions } from '../shared-skills/restore.ts';import { isPhysicalRootMetadata } from '../persistence/physical-root-record.ts';import { protectNewBackupPath } from './private-path.ts';+import { pgliteBackupPreflight } from './preflight.ts';interface SourceInventory { id: string; local_path: string | null; managed_relative_path: string | null }interface BackupMetadata {@@ -137,9 +138,13 @@ export async function createPgliteBackup(options: { output: string; root?: strinthrow new AgentInstallError('pglite_required', 'Full local snapshots require an existing file-configured PGLite brain.');}const dbPath = state.config.database_path;- if (typeof dbPath !== 'string' || resolve(dbPath) !== join(root, '.gbrain', 'brain.pglite') || !existsSync(dbPath)) {+ if (typeof dbPath !== 'string' || !existsSync(dbPath)) {throw new AgentInstallError('unmanaged_database_path', 'This recovery format requires .gbrain/brain.pglite within the selected root.');}+ // #6649: refuse a layout or a size this format cannot hold before the lock, the dump and the archive write.+ const refusal = pgliteBackupPreflight(root, dbPath, () => checkedManagedPaths(root, readInstallReceipt(root)?.managed_paths ?? [])+ .flatMap(path => walkFiles(root, path)).reduce((sum, path) => sum + lstatSync(confinedPath(root, path)).size, 0));+ if (refusal) throw refusal;confinedPath(root, '.gbrain/brain.pglite');const lock = await acquireBootstrapLock(root);let work: string | undefined;diff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex da1e082622..4106f70742 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -63,6 +63,7 @@ export const CODES = {autopilot_job_owned_by_other_brain: { class: 'caller', summary: "The autopilot job is bound to a different brain." },budget_below_recent_runtime: { class: 'unavailable', summary: "The cycle's remaining budget fits fewer reflections than dream patterns needs at the recorded runtime, so the in-cycle run was skipped before any spend.", why: 'An in-cycle patterns run is sized from dream.patterns.last_run; a run that cannot finish in the budget would spend tokens and be killed.', docs: 'docs/guides/dream-patterns.md#budget-sizing', suggestion: 'Run `gbrain dream --phase patterns` outside the cycle after the user agrees to the paid run (it is not budget-limited and records its cost), or reset the record with `gbrain config unset dream.patterns.last_run`.' },backup_dump_failed: { class: 'host_only', summary: "`gbrain backup create` could not dump the PGLite data dir: an entry PGLite cannot read (a socket, FIFO or symlink that is not a dead gbrain socket) is still inside it.", why: "The backup removes only gbrain's own IPC sockets, and only when nothing listens on them; a live gbrain socket, a foreign socket or FIFO, or a symlink is left in place and named in the message, because the database lock proves no other PGLite owner, not who owns an arbitrary endpoint.", docs: 'docs/guides/in-agent-setup.md#6-back-up-the-complete-local-database', suggestion: 'Stop the process that uses each named entry (or move the entry out of the data dir), then rerun the same `gbrain backup create` command. Do not delete an entry something is still listening on.', fix: { argv: ['gbrain', 'doctor', '--json'], consent: [], actor: 'agent', why: "Read-only: reports the brain's lock holders and storage state so the user can see what still runs against the data dir.", requires_exclusive: false, verify: { argv: ['gbrain', 'doctor', '--json'] } } },+ backup_too_large: { class: 'host_only', summary: "`gbrain backup create` refused before writing anything: the PGLite brain's estimated archive size is over the 8 GiB backup-archive cap.", why: 'The archive format holds at most 8 GiB of payload and the dump is materialized in memory; refusing up front avoids a long dump that cannot be published.', docs: 'docs/guides/in-agent-setup.md#large-or-non-standard-brains-quiesced-physical-copy', suggestion: 'Take a quiesced physical copy of the data directory instead (stop writers, copy, open the copy in an isolated GBRAIN_HOME, verify with gbrain doctor --json).', fix: { ask_user: true, argv: ['gbrain', 'doctor', '--json'], consent: [], actor: 'agent', why: "Read-only, after the user agrees to the physical copy: doctor opens the brain only when no other gbrain process holds it, so a clean run shows the writers are stopped.", user_message: "This brain is outside what `gbrain backup create` can archive. Stop every gbrain writer on it (gbrain serve, jobs, autopilot, agent sessions), copy the whole data directory and config.json into a new isolated GBRAIN_HOME, point the copy's database_path at the copied data directory, then run gbrain doctor --json with GBRAIN_HOME set to the copy before relying on it.", requires_exclusive: false, verify: { argv: ['gbrain', 'doctor', '--json'] } } },benchmark_duplicate_task_id: { class: 'caller', summary: "Benchmark duplicate task id." },benchmark_empty: { class: 'caller', summary: "The benchmark file has no tasks." },benchmark_exists: { class: 'caller', summary: "A benchmark already exists at the target path." },@@ -519,6 +520,7 @@ export const CODES = {unknown_tool: { class: 'caller', summary: "The named tool does not exist or is not callable on this connection.", legacy_error: 'unknown_operation' },unknown_transport: { class: 'unavailable', summary: "The caller's transport could not be identified." },unpriced_model: { class: 'caller', summary: "The configured decide model has no price, so its spend cannot be metered; nothing was sent.", why: 'A `typesafe:<model>` id that gbrain ships no tariff for (a gateway-fronted or self-hosted Jev) would otherwise be admitted as $0 against `decide.budget.daily_usd` and its remote share, and the spend ledger would record $0 for a real bill (#5980).', docs: 'docs/guides/system-one.md#unpriced_model', suggestion: 'Register the price the endpoint bills with `gbrain pricing set typesafe:<model> --rate <usd-per-1M-input-tokens> --source <pricing-page-url>`, then `gbrain decide probe`.', fix: { argv: ['gbrain', 'pricing', 'list', '--json'], consent: [], actor: 'agent', why: 'Read-only: shows the operator prices already registered, so the missing `typesafe:<model>` row is visible before anything is written.', requires_exclusive: false, verify: { argv: ['gbrain', 'config', 'get', 'pricing.overrides'] } } },+ unmanaged_database_path: { class: 'host_only', summary: "`gbrain backup create` refused before writing anything: the PGLite data directory is not the managed `<root>/.gbrain/brain.pglite` (a flat config home, or a path reached through a symlink).", why: 'The archive records the managed root it can restore into and refuses to follow a symlink out of it, so a flat or aliased layout cannot be archived without risking a restore into the wrong place.', docs: 'docs/guides/in-agent-setup.md#large-or-non-standard-brains-quiesced-physical-copy', suggestion: 'Take a quiesced physical copy into a new managed root (`<new-home>/.gbrain/brain.pglite`); the copy is then a normal layout that `gbrain backup create` accepts while it is under the 8 GiB cap.', fix: { ask_user: true, argv: ['gbrain', 'doctor', '--json'], consent: [], actor: 'agent', why: "Read-only, after the user agrees to the physical copy: doctor opens the brain only when no other gbrain process holds it, so a clean run shows the writers are stopped.", user_message: "This brain is outside what `gbrain backup create` can archive. Stop every gbrain writer on it (gbrain serve, jobs, autopilot, agent sessions), copy the whole data directory and config.json into a new isolated GBRAIN_HOME, point the copy's database_path at the copied data directory, then run gbrain doctor --json with GBRAIN_HOME set to the copy before relying on it.", requires_exclusive: false, verify: { argv: ['gbrain', 'doctor', '--json'] } } },unmanaged_path: { class: 'caller', summary: "Reclone only replaces a checkout created and managed by GBrain." },unsupported_export_data: { class: 'unavailable', summary: "The source contains data this export path cannot carry." },unsupported_mutation_protocol: { class: 'unavailable', summary: "Prepared mutation does not match its accepted target." },diff --git a/test/backup-cli.serial.test.ts b/test/backup-cli.serial.test.tsindex 1cbf7b130e..269b50131e 100644--- a/test/backup-cli.serial.test.ts+++ b/test/backup-cli.serial.test.ts@@ -34,6 +34,7 @@ import {} from '../src/core/backup/status-file.ts';import { surfaceSource } from './helpers/source-surface.ts';import * as snapshot from '../src/core/backup/snapshot.ts';+import { pgliteBackupPreflight } from '../src/core/backup/preflight.ts';import * as fs from 'node:fs';/** The exact literal thrown by src/core/pglite-engine.ts on lock contention.@@ -528,6 +529,25 @@ describe('runBackupCli create — failure diagnostic for message-less errors (#5}});+ test('#6649: a preflight refusal keeps its own code, fix and legacy reason instead of becoming storage_error', async () => {+ const dir = mkdtempSync(join(tmpdir(), 'g6649-cli-'));+ try {+ const refusal = pgliteBackupPreflight(dir, join(dir, 'elsewhere', 'brain.pglite'), () => 0)!;+ for (const json of [true, false]) {+ const r = await failCreate(refusal, json);+ expect(r.exitCode).toBe(1);+ if (json) {+ const doc = JSON.parse(r.stdout.trim());+ expect(doc).toMatchObject({ ok: false, reason: 'unmanaged_database_path', code: 'unmanaged_database_path', class: 'host_only' });+ expect(doc.fix).toMatchObject({ next: 'ask_user', verify: { argv: ['gbrain', 'doctor', '--json'] } });+ expect(doc.fix.user_message).toContain('stop every gbrain writer');+ } else {+ expect(r.stderr).toContain('Error [unmanaged_database_path]');+ }+ }+ } finally { rmSync(dir, { recursive: true, force: true }); }+ });+test('an error message keeps its text with URL credentials redacted; retryable is preserved', async () => {const err = Object.assign(new Error('dump failed for postgres://alice-example:[email protected]/brain'), { code: 'writers_active', retryable: true });const r = await failCreate(err, true);diff --git a/test/backup-preflight-6649.test.ts b/test/backup-preflight-6649.test.tsnew file mode 100644index 0000000000..32ec870e39--- /dev/null+++ b/test/backup-preflight-6649.test.ts@@ -0,0 +1,187 @@+/**+ * #6649: `gbrain backup create` on PGLite refuses a brain its archive format+ * cannot hold before it takes the writer lock or opens the database:+ *+ * - a flat config home or a data dir reached through a symlink is+ * `unmanaged_database_path` (before: a flat home got a one-line refusal and+ * a symlinked `.gbrain` alias got the generic `symlink_path`, neither naming+ * a recovery);+ * - an estimated archive over the 8 GiB cap is `backup_too_large` (before: the+ * dump ran, was materialized in memory, and failed late or opaquely).+ *+ * Both name the quiesced physical-copy runbook, and the restore drill below+ * runs that runbook end to end: stop writers, copy the data dir and config+ * into a new isolated managed home, verify the copy opens with the data, and+ * show the copy is a normal layout that `backup create` then archives and+ * `backup restore` restores. Oversize inputs are sparse files (apparent size,+ * no disk use), so no test writes gigabytes.+ */+import { afterAll, afterEach, beforeAll, describe, expect, test } from 'bun:test';+import { cpSync, existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, realpathSync, rmSync, symlinkSync, truncateSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { privateWrite } from '../src/core/agent-install/state.ts';+import { BACKUP_ARCHIVE_MAX_BYTES } from '../src/core/backup/archive.ts';+import { estimatedTarBytes, pgliteBackupLayout, pgliteBackupPreflight } from '../src/core/backup/preflight.ts';+import { createPgliteBackup, restorePgliteBackup } from '../src/core/backup/snapshot.ts';+import { backupSizeCheck } from '../src/commands/doctor/checks/db-connection.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { codeEntry } from '../src/core/error-catalogue.ts';++let temporary: string;++async function makeBrain(dataDir: string, configFile: string): Promise<void> {+ mkdirSync(join(dataDir, '..'), { recursive: true, mode: 0o700 });+ privateWrite(configFile, JSON.stringify({ engine: 'pglite', database_path: dataDir, embedding_disabled: true }));+ const engine = new PGLiteEngine();+ await engine.connect({ engine: 'pglite', database_path: dataDir });+ try {+ await engine.initSchema();+ await engine.putPage('people/alice-example', { type: 'person', title: 'Alice Example', compiled_truth: 'Survives the physical copy.' });+ } finally { await engine.disconnect(); }+}++async function failure(promise: Promise<unknown>): Promise<{ code: string; message: string; fix?: { user_message?: string; docs?: string; ask_user?: boolean; verify?: { argv?: string[] } } }> {+ try { await promise; } catch (error) { return error as never; }+ throw new Error('backup unexpectedly succeeded');+}++beforeAll(() => { temporary = realpathSync(mkdtempSync(join(tmpdir(), 'g6649-'))); });+afterAll(() => { rmSync(temporary, { recursive: true, force: true }); });++describe('layout preflight', () => {+ test('a symlinked .gbrain alias (the reported layout) is unmanaged_database_path with the runbook, not symlink_path, and writes nothing', async () => {+ const physical = join(temporary, 'volume', 'brain-home');+ const root = join(temporary, 'alias-user');+ await makeBrain(join(physical, 'brain.pglite'), join(physical, 'config.json'));+ mkdirSync(root);+ symlinkSync(physical, join(root, '.gbrain'), process.platform === 'win32' ? 'junction' : 'dir');+ privateWrite(join(physical, 'config.json'), JSON.stringify({ engine: 'pglite', database_path: join(root, '.gbrain', 'brain.pglite'), embedding_disabled: true }));+ expect(pgliteBackupLayout(root, join(root, '.gbrain', 'brain.pglite'))).toBe('symlinked');+ const output = join(temporary, 'alias.gbrain-backup');+ const error = await failure(createPgliteBackup({ root, output }));+ expect(error.code).toBe('unmanaged_database_path');+ expect(error.message).toContain('symlink');+ expect(error.fix?.ask_user).toBe(true);+ expect(error.fix?.user_message).toContain('stop every gbrain writer');+ expect(error.fix?.docs).toContain('quiesced-physical-copy');+ expect(error.fix?.verify?.argv).toEqual(['gbrain', 'doctor', '--json']);+ expect(existsSync(output)).toBe(false);+ expect(readdirSync(join(physical, 'brain.pglite'))).not.toContain('.gbrain-lock');+ });++ test('a flat config home whose database_path is outside <root>/.gbrain is unmanaged_database_path', async () => {+ const root = join(temporary, 'flat');+ mkdirSync(join(root, '.gbrain'), { recursive: true });+ const elsewhere = join(temporary, 'flat-data', 'brain.pglite');+ mkdirSync(elsewhere, { recursive: true });+ privateWrite(join(root, '.gbrain', 'config.json'), JSON.stringify({ engine: 'pglite', database_path: elsewhere }));+ const error = await failure(createPgliteBackup({ root, output: join(temporary, 'flat.gbrain-backup') }));+ expect(error.code).toBe('unmanaged_database_path');+ expect(error.message).toContain(elsewhere);+ });++ test('both refusals are registered codes with a runbook fix, so `gbrain errors` and the contract cover them', () => {+ for (const code of ['unmanaged_database_path', 'backup_too_large']) {+ const entry = codeEntry(code);+ expect(entry?.class).toBe('host_only');+ expect(entry?.docs).toContain('quiesced-physical-copy');+ expect(entry?.fix?.verify?.argv).toEqual(['gbrain', 'doctor', '--json']);+ }+ });+});++describe('size preflight', () => {+ let root: string;+ let dataDir: string;+ const sparse = () => join(dataDir, 'base', 'sparse-6649');++ beforeAll(async () => {+ root = join(temporary, 'large');+ dataDir = join(root, '.gbrain', 'brain.pglite');+ await makeBrain(dataDir, join(root, '.gbrain', 'config.json'));+ });+ afterEach(() => { rmSync(sparse(), { force: true }); });++ test('the estimate counts tar headers and 512-byte padding for every file', () => {+ const dir = join(temporary, 'estimate');+ mkdirSync(join(dir, 'sub'), { recursive: true });+ writeFileSync(join(dir, 'a'), 'x');+ writeFileSync(join(dir, 'sub', 'b'), Buffer.alloc(513));+ // closing blocks + 2 directories + (header + 1 block) + (header + 2 blocks)+ expect(estimatedTarBytes(dir)).toBe(512 * (2 + 2 + 2 + 3));+ });++ test('a data dir over the 8 GiB cap is refused as backup_too_large before the lock, the dump or any output', async () => {+ writeFileSync(sparse(), '');+ truncateSync(sparse(), BACKUP_ARCHIVE_MAX_BYTES + 1);+ const output = join(temporary, 'large.gbrain-backup');+ const started = Date.now();+ const error = await failure(createPgliteBackup({ root, output }));+ expect(error.code).toBe('backup_too_large');+ expect(error.message).toContain('8.00 GiB cap');+ expect(error.fix?.user_message).toContain('copy the whole data directory and config.json into a new, isolated GBRAIN_HOME');+ expect(Date.now() - started).toBeLessThan(10_000);+ expect(existsSync(output)).toBe(false);+ expect(readdirSync(temporary).some(name => name.startsWith('.gbrain-backup-'))).toBe(false);+ expect(readdirSync(dataDir)).not.toContain('.gbrain-lock');+ });++ test('managed files count toward the cap', () => {+ expect(pgliteBackupPreflight(root, dataDir, () => 0)).toBeNull();+ expect(pgliteBackupPreflight(root, dataDir, () => BACKUP_ARCHIVE_MAX_BYTES)?.code).toBe('backup_too_large');+ });+});++describe('doctor pglite_data_dir near-cap warning', () => {+ test('silent below 75% of the cap, warns near it and over it with the runbook fix', () => {+ const dir = join(temporary, 'doctor');+ expect(backupSizeCheck(dir, Math.floor(BACKUP_ARCHIVE_MAX_BYTES * 0.74))).toBeNull();+ const near = backupSizeCheck(dir, Math.ceil(BACKUP_ARCHIVE_MAX_BYTES * 0.8))!;+ expect(near).toMatchObject({ name: 'pglite_data_dir', status: 'warn', details: { code: 'backup_too_large', over_limit: false } });+ expect(near.message).toContain('will refuse it soon');+ const over = backupSizeCheck(dir, BACKUP_ARCHIVE_MAX_BYTES + 1)!;+ expect(over.details).toMatchObject({ over_limit: true, limit_bytes: BACKUP_ARCHIVE_MAX_BYTES });+ expect((over.fix as { verify?: { argv?: string[] } }).verify?.argv).toEqual(['gbrain', 'doctor', '--json']);+ });+});++describe('restore drill: the quiesced physical-copy runbook', () => {+ test('stop writers, copy into an isolated managed home, verify, then archive and restore the copy', async () => {+ // The reported layout: a physical home on another volume reached through a .gbrain alias.+ const physical = join(temporary, 'drill-volume', 'brain-home');+ const aliasRoot = join(temporary, 'drill-user');+ await makeBrain(join(physical, 'brain.pglite'), join(physical, 'config.json'));+ mkdirSync(aliasRoot);+ symlinkSync(physical, join(aliasRoot, '.gbrain'), process.platform === 'win32' ? 'junction' : 'dir');++ // 1. Writers stopped: nothing holds the PGLite lock (makeBrain disconnected), so a fresh open would succeed.+ expect(readdirSync(join(physical, 'brain.pglite'))).not.toContain('.gbrain-lock');++ // 2. Copy the physical data dir (resolved through the alias) and config into a new isolated managed home.+ const copyRoot = join(temporary, 'drill-copy');+ const copyData = join(copyRoot, '.gbrain', 'brain.pglite');+ mkdirSync(join(copyRoot, '.gbrain'), { recursive: true, mode: 0o700 });+ cpSync(realpathSync(join(aliasRoot, '.gbrain', 'brain.pglite')), copyData, { recursive: true });+ const config = JSON.parse(readFileSync(join(physical, 'config.json'), 'utf8'));+ privateWrite(join(copyRoot, '.gbrain', 'config.json'), JSON.stringify({ ...config, database_path: copyData }));++ // 3. Verify the copy opens in its isolated home with the data intact.+ const engine = new PGLiteEngine();+ await engine.connect({ engine: 'pglite', database_path: copyData });+ try {+ expect((await engine.getPage('people/alice-example'))?.compiled_truth).toContain('Survives the physical copy.');+ } finally { await engine.disconnect(); }++ // 4. The copy is the managed layout: backup create archives it and restore brings it back in a third root.+ expect(pgliteBackupLayout(copyRoot, copyData)).toBe('managed');+ const archive = join(temporary, 'drill.gbrain-backup');+ await createPgliteBackup({ root: copyRoot, output: archive });+ const restored = await restorePgliteBackup({ archive, into: join(temporary, 'drill-restored') });+ const check = new PGLiteEngine();+ await check.connect({ engine: 'pglite', database_path: join(restored.root, '.gbrain', 'brain.pglite') });+ try {+ expect((await check.getPage('people/alice-example'))?.compiled_truth).toContain('Survives the physical copy.');+ } finally { await check.disconnect(); }+ }, 120_000);+});