Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(storage): print a restore command that restores exactly the listed files (#5539)
garrytan0bc48f2b452f
diff --git a/docs/architecture/key-files/commands-3.md b/docs/architecture/key-files/commands-3.mdindex 5c7c84d90a..12ddc9c92d 100644--- a/docs/architecture/key-files/commands-3.md+++ b/docs/architecture/key-files/commands-3.md@@ -27,7 +27,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/commands/eval.ts` — `gbrain eval` command: single-run table + A/B config comparison. Sub-subcommand dispatch on `args[0]` routes `gbrain eval export` + `gbrain eval prune` + `gbrain eval replay` into session-capture handlers; bare `gbrain eval --qrels …` fall-through preserves the legacy IR-metrics flow. `gbrain eval cross-modal` is in the dispatch (the user-facing path is the cli.ts no-DB branch — `src/commands/eval.ts:cross-modal` only fires when callers re-enter with an existing engine).-- `src/commands/export.ts` + `src/core/export-snapshot.ts` + `src/core/export-stage.ts` + `src/core/export-publish.ts` — local Markdown export collects source/page/canonical-withdrawal/tag/raw state in one export-scoped repeatable-read read-only transaction, using 256-key ID batches and private disk-backed SQLite staging. Primary-key page reads reuse the canonical withdrawal overlay without source-wide slug scans under stale planner statistics. Each 256-key batch groups by source and retains only one capacity-checked withdrawal ledger at a time; bodies with no literal `gbrain:facts:` marker skip normalization, while malformed/orphan markers still use canonical SQL fingerprinting. No engine defaults or shared migration iterators change. Explicit source selection is validated; restore-only selects one source and checks its recorded file path through the existing native path resolver. The manifest rejects unsafe paths, same/cross-source aliases, case/Unicode and file-prefix collisions before destination output, preserving the `<slug>.md` and `.raw/<name>.json` layout. Existing planned paths refuse rather than overwrite. The portable first-party native addon anchors no-follow directories and publishes leaves with atomic no-replace operations, retaining an exclusive persistent `.gbrain-export-status` marker; success requires flushed data and a final COMPLETE line. Unsupported native capabilities fail closed without a pathname fallback. A fresh destination is the retry path; unrelated files are never pruned. Fixed capacity/time limits fail visibly, never truncate. This is a historical snapshot, not a database backup or a sandbox against another same-user process renaming directories. See [safe export](../../storage-tiering.md#safe-export). Engine-free `export --help` documents scope, no-overwrite publication and incomplete-output recovery. Pinned by both-engine export safety/independent-roundtrip/snapshot/failure-release suites, the 100001-page scale fixture with staging bytes and full export SQL statement accounting, the native publication/compiled-wrapper suite, actual CLI help tests, and the PostgreSQL export E2E wrapper.+- `src/commands/export.ts` + `src/core/export-snapshot.ts` + `src/core/export-stage.ts` + `src/core/export-publish.ts` — local Markdown export collects source/page/canonical-withdrawal/tag/raw state in one export-scoped repeatable-read read-only transaction, using 256-key ID batches and private disk-backed SQLite staging. Primary-key page reads reuse the canonical withdrawal overlay without source-wide slug scans under stale planner statistics. Each 256-key batch groups by source and retains only one capacity-checked withdrawal ledger at a time; bodies with no literal `gbrain:facts:` marker skip normalization, while malformed/orphan markers still use canonical SQL fingerprinting. No engine defaults or shared migration iterators change. Explicit source selection is validated; restore-only selects one source through `resolveRestoreTarget` (`src/core/restore-target.ts`, shared with `gbrain storage status`) and checks its recorded file path through the existing native path resolver. The manifest rejects unsafe paths, same/cross-source aliases, case/Unicode and file-prefix collisions before destination output, preserving the `<slug>.md` and `.raw/<name>.json` layout. Existing planned paths refuse rather than overwrite. The portable first-party native addon anchors no-follow directories and publishes leaves with atomic no-replace operations, retaining an exclusive persistent `.gbrain-export-status` marker; success requires flushed data and a final COMPLETE line. Unsupported native capabilities fail closed without a pathname fallback. A fresh destination is the retry path; unrelated files are never pruned. Fixed capacity/time limits fail visibly, never truncate. This is a historical snapshot, not a database backup or a sandbox against another same-user process renaming directories. See [safe export](../../storage-tiering.md#safe-export). Engine-free `export --help` documents scope, no-overwrite publication and incomplete-output recovery. Pinned by both-engine export safety/independent-roundtrip/snapshot/failure-release suites, the 100001-page scale fixture with staging bytes and full export SQL statement accounting, the native publication/compiled-wrapper suite, actual CLI help tests, and the PostgreSQL export E2E wrapper.- `src/commands/extract-conversation-facts.ts` + `src/core/cycle/conversation-facts-backfill.ts` — bulk fact extraction for long-form conversation pages. Walks conversation/meeting/slack/email/imessage/imessage-daily pages, splits them into time-windowed segments (30-min gap or 30-msg cap), prepends a topical/temporal header, and uses the strict `extractFactsFromTurnWithOutcome()` path so provider and output failures remain retryable instead of becoming successful empty pages. Invariants: **strict per-source core** (`runExtractConversationFactsCore({sourceId, ...})` always takes one sourceId; CLI + cycle phase each do their own multi-source iteration because `PHASE_SCOPE='source'` is taxonomy-only); **bounded two-phase enumeration** (paginated `listPages({type, sourceId, limit:10})`; per-page body cap `MAX_PAGE_BODY_BYTES=25MB`); **page-global `row_num` accumulator** (the facts unique index is `(source_id, source_markdown_slug, row_num)`); **versioned snapshot-bound outcomes** (`cli:extract-conversation-facts:terminal:v2` for complete pages and a separate `non-extractable:v2` source for recognized pages with no eligible segment); **operation checkpoints are scheduling hints only** and never suppress a replay without a matching v2 outcome; **optional `opts.budgetTracker?`** is used as-is, while an absent tracker is created with `maxCostUsd` (a DEFAULT cap is dropped with a warning when the extraction or parser chat model is unpriced, via `src/core/facts/conversation-budget.ts` `conversationFactsCostCap` (#5823); explicit CLI/caller/cycle caps stay fail-closed and a `no_pricing` stop reports `budget_reason`/`budget_model`, exits 1 and names `pricing.overrides`); **body reads cover compiled truth, timeline, and configured raw-transcript sidecars**; **`facts.extraction_enabled` kill-switch** with `--override-disabled`; **`--types LIST` allowlist** (`conversation,meeting,slack,email,imessage,imessage-daily`); **`--background` via `maybeBackground`**; and **speaker-shaped-fold decline** — when the parse reports `unrecognized_headings` containing a speaker-shaped label (1-2 title-cased words, not in the doc-heading stoplist — the stoplist gates the DECLINE only, so a miss is warn-noise, never data loss) AND the parse produced fewer than two distinct speakers, the page is declined instead of extracted under wrong attribution: counted in `pages_skipped_unrecognized_speaker` (Result/CLI/cycle surfaces), warned to stderr with the folding pattern id, and deliberately NON-terminal (no durable audit row and no orphan cleanup, so a future parser/pattern fix retries the page); multi-speaker pages with folds proceed warn-only. The companion `conversation_facts_backfill` cycle phase is default-off, iterates every source, and enforces per-source plus brain-wide cost and wall-time caps. Migration v94 provides the partial facts index used by outcome lookups. `computeConversationFactsBacklogCheck` reports fresh completed, scanned-not-extractable, and unfinished counts separately, warning when more than 10 eligible pages lack a fresh v2 outcome. `sources audit` exposes `facts_backfill_estimate: {pages, est_segments, est_cost_usd, types}`. Pinned by `test/extract-conversation-facts.test.ts` and `test/doctor-conversation-facts-backlog.test.ts`. `--workers N` for LLM-bound fact extraction over conversation pages, with a per-page advisory lock via `src/core/db-lock.ts:withRefreshingLock` (lock id `extract-conversation-facts:<source>:<slug>`, TTL `PER_PAGE_LOCK_TTL_MINUTES=2` with 20s refresh via `Math.max(15s, 120s/6)`; `LockUnavailableError` triggers skip-and-continue with rate-limited log per (source, minute) + `pages_lock_skipped` counter + CLI exits 3 when non-zero AND no hard failures). `deleteOrphanFactsForPage(engine, sourceId, slug)` provides delete-orphans-first replay safety — wipes facts from a prior crashed run for this (sourceId, slug) before re-extracting, so a terminal audit row can never certify a partial insertFacts failure. `assertFactsEmbeddingDimMatchesConfig(engine)` is the startup preflight (throws `FactsEmbeddingDimMismatchError` with paste-ready ALTER hint BEFORE the first insert; cached per engine via WeakMap). Result type carries `pages_lock_skipped` + `orphan_facts_cleaned`. Additive `pages_skipped_unparsed`, `pages_skipped_type_mismatch`, `pages_skipped_insufficient_turns`, and `pages_skipped_since` explain the unchanged `pages_skipped` aggregate across core, CLI, workers, and cycle sources; durable completion remains separate. `--dry-run` stops after segmentation, with no parser-fallback, extractor, or embedding calls and no durable knowledge/checkpoint/receipt/rollup writes. The narrow `python-dict-utterance` registry format and its quoted/nested-example rejection are documented in [conversation parser patterns](../conversation-parser-patterns.md). Checkpoint state is a shared `cpMap: Map<slug, endIso>` (NOT a per-page-mutated `cpEntries: string[]`) so atomic `Map.set` survives parallel workers. Minion handler `extract-conversation-facts` in `src/commands/jobs.ts` round-trips `workers` via `job.data.workers` for `--background --workers 20`. Cycle config key `cycle.conversation_facts_backfill.workers` (default 1; opt-in concurrency under brain-wide cost + walltime caps). Pinned by `test/extract-conversation-facts-diagnostics.serial.test.ts` (pool workers, per-page lock skip + exit 3, delete-orphans-first replay, D15 preflight, `--workers` round-trip) + the existing extract-conversation-facts behavioral tests. with `src/commands/doctor.ts` durable outcome authority: page completion survives operation-checkpoint GC through versioned terminal audit rows (`cli:extract-conversation-facts:terminal:v2`), while recognized pages with no eligible segment use the separate `cli:extract-conversation-facts:non-extractable:v2` source. Each outcome is bound to the exact parsed snapshot: regular pages use `content_hash` plus the UTC effective date; raw-conversation sidecars and legacy null-hash pages use a canonical SHA-256 over every parser-relevant input. Selection checks the token before locking, refetches under the lock, and verifies it again before writing the outcome, so an edit cannot be certified by stale work. The strict extraction path treats provider, refusal, truncation, malformed/schema-invalid output, segment-write, cleanup, and terminal-write failures as unfinished work; bulk failures increment `pages_failed`, affect CLI/cycle receipts and exit status, and never advance the legacy checkpoint. Checkpoints are only a scheduling hint: a slug without a matching v2 outcome is replayed delete-first. `no_match`, errors, cancellation, and dry runs never become durable negatives. Result, CLI, cycle, and doctor surfaces keep completed, scanned-not-extractable, unfinished, failed, and lock-skipped counts separate. See [Conversation backfill durable outcomes](../../operations/conversation-backfill-outcomes.md) for the operator and maintainer contract. Pinned by `test/extract-conversation-facts.test.ts` and `test/doctor-conversation-facts-backlog.test.ts`. On a managed brain the core runs `managedDerivedFactsPreflight` (local writer, active source) before any provider work, and a page's facts and terminal (or non-extractable) audit row are buffered, then replace the prior extractor batch in one `replaceDerivedFactsForPage` transaction after source activity, page id, revision and parser-input snapshot are rechecked under the page lock, so a failed or raced re-extraction keeps the prior batch; the CLI no longer refuses up front and receipt pages are skipped. Tests: `test/managed-facts-writers.test.ts`, `test/managed-unsupported-preflight.serial.test.ts` (refusal before spend for an unaccepted writer).diff --git a/docs/architecture/key-files/commands-5.md b/docs/architecture/key-files/commands-5.mdindex cce9d227eb..97deeb1127 100644--- a/docs/architecture/key-files/commands-5.md+++ b/docs/architecture/key-files/commands-5.md@@ -37,4 +37,4 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/commands/sources.ts` — `gbrain sources {list,add,remove,archive,restore,archived,purge,current,status,audit}`. `current [--json]` calls `resolveSourceWithTier()` and prints `source_id`, `tier` (`flag | env | dotfile | local_path | brain_default | seed_default`), and optional `detail` (decision table in `skills/conventions/brain-routing.md`). `status [--json]` — read-only per-source dashboard (last sync, staleness, page count, embedding coverage, unacked failures); thin wrapper around `buildSyncStatusReport` + `printSyncStatusReport` from `src/commands/sync.ts`; `--json` emits stable `{schema_version: 1, sources, ...}` on stdout; filters input to `local_path IS NOT NULL AND archived IS NOT TRUE`. `audit <id> [--json]` — read-only dry-run disk scan for size distribution + would-blocks + junk-pattern hits WITHOUT touching the DB; walks `sources.local_path`, reads each markdown file, runs `assessContent()` from `src/core/content-sanity.ts`, aggregates by verdict (`ok | warn_oversize | hard_block_junk_pattern`). The live `runStatus` health table gains a `BACKFILL` column between `EMBED` and `FAILS` (`active(N)` beats `queued(N)` beats `idle`, from `SourceMetrics.backfill_active` / `backfill_queued` in `src/core/source-health.ts`) so operators see deferred `embed-backfill` minion work after `sync --all` exits 0; `jobCountsBySource` in `source-health.ts` widens its `minion_jobs` SQL with two `COUNT(*) FILTER (WHERE name = 'embed-backfill' AND ...)` aggregates (best-effort, all-0 on pre-minions brains). `remove` pre-checks OAuth-client referents (guided refusal via `formatClientReferentsBlock` — the raw FK violation never reaches the operator), then commits the row DELETE atomically with an in-tx referents re-check (a registration racing the pre-check maps to the same guided refusal); durability-scaffolding teardown (`unhardenBrainRepo`: hook/cron/credential) runs only AFTER the commit, so a refused delete leaves the scaffolding intact. `purge` runs the same referents pre-check before its hard DELETE. Pinned by `test/content-sanity.test.ts`, `test/import-file-content-sanity.test.ts`, `test/source-health.test.ts`.-- `src/commands/storage.ts` — `gbrain storage status [--repo P] [--json]`. Split into pure data (`getStorageStatus`) + JSON formatter + human formatter (ASCII-only) matching the `orphans.ts` pattern. `PageCountsByTier` and `DiskUsageByTier` are distinct nominal types so swaps fail at compile time.+- `src/commands/storage.ts` — `gbrain storage status [--repo P] [--json]`. Split into pure data (`getStorageStatus`) + JSON formatter + human formatter (ASCII-only) matching the `orphans.ts` pattern. `PageCountsByTier` and `DiskUsageByTier` are distinct nominal types so swaps fail at compile time. The repo and the counted source come from `resolveRestoreTarget` (`src/core/restore-target.ts`, the `export --restore-only` rule), and a page is listed missing exactly when that export would restore it (`isDbOnly`, then `restoreFilePath` in the page source's `scannerSlugRootMode` and `nativeFileTarget`: the recorded `source_path`, else `<slug>.md`, absent; the repo walk answers without a per-page syscall whenever it saw that exact file as a regular file under real directories, and a recorded path starting with the repo's path inside its git checkout, which export re-anchors, takes the full check), so the printed `Use: gbrain export --restore-only --source <id> --repo <path>` (the path passed through `shellQuote`, `src/core/shell-quote.ts`) writes exactly the listed files into `--dir` (default `./export`, not the repo). An unsafe recorded path or a symlinked/ambiguous file target (`OperationError` from `nativeFileTarget`) becomes one warning per reason (lowest slug plus a count of further pages) plus the refusal export would give, printed even when no file is missing; a repo whose own owner (`resolveSourceForRepoPath`: dotfile, then longest registered `local_path`) is archived is refused too (unless an active source is registered at the repo's exact path, which owns it outright), although export's exact-path rule would fall back to the only active source; a refused rule prints `Cannot suggest a restore command:` and falls back to the `--repo` / default-source path, counting the active repo owner's pages (dotfile, then longest registered `local_path`) or every source's pages when no active source owns it. `restoreSource` / `restoreRefusal` carry this in the JSON result. Pinned by `test/storage-restore-hint.test.ts`.diff --git a/docs/architecture/key-files/core-utilities-2.md b/docs/architecture/key-files/core-utilities-2.mdindex 8853a8c8f6..6031af254a 100644--- a/docs/architecture/key-files/core-utilities-2.md+++ b/docs/architecture/key-files/core-utilities-2.md@@ -8,9 +8,13 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/repair/extractor-facts.ts` — `gbrain repair extractor-facts` (#5731), explicit-only and preview-bound. `classifyExtractorFacts` (read-only; also the doctor check's count) takes conversation-extractor facts with `expired_at` set and `row_num` NULL and classes each: `excluded` (page missing or deleted, `superseded_by` set, withdrawn, an active same-text fact on the page, or an earlier same-text candidate), `ambiguous` (unmanaged brain; no committed request of the page with `completed_at = expired_at`, compared in SQL as microsecond UTC text, which only a same-transaction completion satisfies on Postgres; a consumer at or above v0.60.11.0; or the page has ever held fence-projected facts) or `evidenced`. The preview lists every candidate, hashes them with the selection (`--include-ambiguous`) and saves one approved item per page (with its request id) through `preview-approval.ts`; the apply loads only that set, skips pages whose request already committed or whose facts are active again, and restores each still-identical fact with a fresh `row_num` above the page's facts and fence rows. Managed brains publish one database-only `managed_maintenance_restore_extractor_facts` request per page (`submitDatabaseMaintenanceIntent`, dispatched by `prepareMaintenanceMutation` to `prepareExtractorFactsRestore`, which reclassifies under the page lock); unmanaged brains run the same restore in one locked transaction. Previews warn, naming the host, when a consumer older than this release published after `writer_version_cutoff`. On PGLite `now()` has millisecond resolution, so the same-transaction rule is millisecond-exact there.- `src/core/persistence/mirror-read-only.ts` and `src/commands/sources-mirror.ts` — #5409 read-only mirror sources. `sourceMirrorReadOnly(engine, sourceId)` reads `sources.config.mirror_read_only` (default false). When true, `prepareFileTarget` (`page-prepare.ts`) returns no file for any coordinated page write into the source (receipt `write_through.skipped: 'mirror_read_only'`, `storage: 'database_only'`, set in `coordinator.ts`), and managed sync (`sync-prepare.ts`) imports an overlay (canonical form differs from the file bytes) database-only: no `file`, no newer-working-tree refusal, and `contentUnchanged` ignores the overlay. A page created that way with no recorded file is stamped `pages.database_only_reason='mirror_read_only'` (`classifyMirrorPage`, in the publication) and stays database-only after the flag is cleared; the coordinator refuses (`source_changed`) a file target prepared before the flag was set (rechecked under the publication with the source row `FOR SHARE`); `gitPage` (`effects.ts`) completes a mirror source's Git effects as skipped. `gbrain sources mirror-readonly|mirror-writable <id>` set and clear the key like `federate`/`unfederate`; `sources list --json` reports `mirror_read_only`.+- `src/core/restore-target.ts` -- `resolveRestoreTarget(engine, source, repo)`: the source and repo `gbrain export --restore-only` restores, shared with `gbrain storage status` so its printed restore command restores exactly the files it lists. An explicit source (already resolved) wins; a repo without a source selects the one active source registered at that exact path, refuses a repo registered only to an archived source, else selects the only active source; neither selects the flagless resolver chain's source and its `local_path` (the legacy `sync.repo_path` answers for `default` only). `restoreFilePath(repo, slug, sourcePath, sourcePathBytes, slugRootMode)` is the file whose absence makes the restore write a page: the recorded `source_path` resolved in the repo in the source's slug-root mode (`scannerSlugRootMode`), else `<slug>.md`; an over-long or unsafe recorded path throws. Refusals throw `RestoreTargetError`; resolver and database errors propagate unchanged.+- `src/core/runtime-version.ts` — Bun 1.4.0 minimum (`MINIMUM_BUN_VERSION`; the lowest 1.4 release, carrying the Linux child-exit fix oven-sh/bun#30301). `unsupportedBunMessage` names the found and required versions and the fix (`bun upgrade`, restart, `gbrain post-upgrade` for an interrupted upgrade). `exitOnUnsupportedBun` is the CLI entrypoint gate: every command below the floor exits 1 before dispatch (`--version` still prints, exit 0, so an older gbrain's upgrade can verify the swap; `autopilot` also writes the refusal to stdout, its service log); `scripts/postinstall.ts` prints it when an install lands on an older Bun; the guarded HTTP transport asserts it; doctor reports it as `bun_runtime`. Package engines, runtime checks and the CI minimum-version lanes share the same floor (`test/scripts/ci-pr-scope.test.ts`).+- `src/core/shell-quote.ts` -- `shellQuote(arg)`: POSIX single-quotes any argument that is not already shell-safe, so `$()`, backticks and quotes stay inert when a printed command is pasted. A leaf module (no imports), so a command importing it adds no other module's `--flag` text to its generated flag-registry scan; `src/core/mcp-registration.ts` re-exports it unchanged. Used by the `gbrain storage status` restore hint.+- `src/core/sort-newest-first.ts` — single source of truth for the descending-lex sort that `gbrain import` and `gbrain sync` both apply. Mutates in place (Array.prototype.sort semantics), returns the same array reference for fluent chaining. Empty/single-element inputs short-circuit. Future ordering changes flip one line here instead of touching two CLI commands. Pinned by `test/sort-newest-first.test.ts` (descending order, mixed prefixes, empty, single-element, in-place-mutation contract).- `src/core/sql-query.ts` — engine-aware tagged-template SQL adapter for OAuth/admin/auth infrastructure. `sqlQueryForEngine(engine)` returns a `SqlQuery` (`(strings, ...values) => Promise<rows[]>`) that walks the template, builds `$N` positional SQL, asserts every value is a `SqlValue` (string | number | bigint | boolean | Date | null), and routes through `engine.executeRaw(sql, params)` (Postgres via postgres.js `unsafe(sql, params)`, PGLite via `db.query(sql, params)`). Deliberately narrower than postgres.js's `sql` tag: no nested fragments, `sql.json()`, `sql.unsafe()`, `sql.begin()`, or array binding — the narrow scalar-only surface is the feature (keeps it from drifting into a partial postgres.js clone). JSONB writes go through `executeRawJsonb(engine, sql, scalarParams, jsonbParams)` which composes positional `$N::jsonb` casts and passes JS **objects** through; an object reaches the wire with the correct type oid, so executeRawJsonb is safe (verified by `test/sql-query.test.ts` on PGLite, `test/e2e/auth-permissions.test.ts:67` on Postgres). Positional binding is NOT universally immune, though: binding a `JSON.stringify(x)` **string** to a bare `$N::jsonb` via `unsafe()` double-encodes it into a jsonb string scalar on real Postgres (PGLite hides it). Fixes: pass a raw object (executeRawJsonb / `sql.json`), or cast through `$N::text::jsonb`. `scripts/check-jsonb-pattern.sh` (template grep) doesn't fire on `executeRawJsonb(...)` because it passes objects; the positional `$N::jsonb` + `JSON.stringify` form is caught by `scripts/check-jsonb-params.mjs`. Also exports `FILES_METADATA_MERGE_SQL`, the one `ON CONFLICT (storage_path)` merge fragment every files upsert (`src/commands/files.ts` x4, `src/core/ops/files.ts` `file_upload`) interpolates: it resets a non-object `files.metadata` to `{}` before the jsonb `||` merge, because `||` array-wraps a non-object left operand and would turn a legacy string-scalar row into `["{}", {...}]` that `gbrain repair-jsonb` can no longer see (pinned by `test/file-upload-fail-closed.test.ts`). Consumed by `src/commands/auth.ts`, `src/commands/serve-http.ts`, `src/core/oauth-provider.ts`, `src/commands/files.ts`, `src/mcp/http-transport.ts` so all five work uniformly against PGLite and Postgres.diff --git a/docs/storage-tiering.md b/docs/storage-tiering.mdindex 9ffbbeddad..344178fa9d 100644--- a/docs/storage-tiering.md+++ b/docs/storage-tiering.md@@ -117,6 +117,7 @@ Output includes:- Total page counts by storage tier.- Disk usage breakdown by tier.- Missing files that need restoration (top 10 shown; full list in `--json`).+- The `gbrain export --restore-only` command that restores them.- Configuration validation warnings.- Current tier directory listing.@@ -146,7 +147,7 @@ Missing Files (need restore):media/x/tweet-0987654321... and 47 more-Use: gbrain export --restore-only --repo "/data/brain"+Use: gbrain export --restore-only --source default --repo /data/brainConfiguration:--------------@@ -161,6 +162,24 @@ DB-only directories:- meetings/transcripts/```+Status picks the repo and source with the same rule as `gbrain export+--restore-only`, counts only that source's pages, and lists a page as missing+exactly when that export would restore it: the page is under a `db_only`+directory (even one nested in a `db_tracked` directory) and its recorded source+file, else `<slug>.md`, is absent from the repo. The `Use:` command therefore+writes exactly the listed files, into `--dir` (default `./export` under the+current directory, not into the repo). The repo path is shell-quoted, so the+line is safe to paste. Export refuses the whole restore when a page's recorded+path is unsafe or its file path runs through a symlink or has no unambiguous+native identity; status then names those pages under warnings (one line per+reason, with the first slug and a count) and prints the refusal instead of a+command, also when no file is left missing. When the source rule refuses (for example, a `--repo`+that no single active source owns, one registered only to an archived+source, or one inside an archived source's tree), status prints `Cannot suggest a restore command:` with the reason. It+then counts the pages of the active source that owns the repo path (its+`.gbrain-source` or the longest registered `local_path` containing it), or+every source's pages when no active source owns it.+## Validation`loadStorageConfig` runs `normalizeAndValidateStorageConfig` after parsing:diff --git a/src/commands/export.ts b/src/commands/export.tsindex 51a026ae2d..02a397d1e9 100644--- a/src/commands/export.ts+++ b/src/commands/export.ts@@ -1,7 +1,6 @@import { existsSync } from 'node:fs';-import { join, resolve } from 'node:path';import type { BrainEngine } from '../core/engine.ts';-import { resolveSourceLocalFilePath, serializeMarkdown } from '../core/markdown.ts';+import { serializeMarkdown } from '../core/markdown.ts';import { scannerSlugRootMode } from '../core/write-through.ts';import { createProgress } from '../core/progress.ts';import { getCliOptions, cliOptsToProgressOptions } from '../core/cli-options.ts';@@ -9,6 +8,7 @@ import { loadStorageConfig, isDbOnly } from '../core/storage-config.ts';import { slugifyPath } from '../core/sync.ts';import { resolveSourceId } from '../core/source-resolver.ts';import { ALL_SOURCES, assertValidSourceId } from '../core/source-id.ts';+import { resolveRestoreTarget, restoreFilePath } from '../core/restore-target.ts';import { ExportStage, EXPORT_PAYLOAD_LIMIT, EXPORT_SNAPSHOT_MS, exportPathKey } from '../core/export-stage.ts';import { publishExport } from '../core/export-publish.ts';import { nativeFileTarget } from '../core/persistence/native-file-target.ts';@@ -63,25 +63,7 @@ a fresh directory. See docs/storage-tiering.md#safe-export.`);await tx.executeRaw('SET LOCAL statement_timeout = 60000');let source = requested ? await resolveSourceId(tx, requested) : undefined;let repo = explicitRepo;- if (restoreOnly) {- if (source === ALL_SOURCES) throw new Error('--restore-only requires one source; pass --source <id>.');- if (!source && repo) {- const matches = await tx.executeRaw<{ id: string }>('SELECT id FROM sources WHERE archived IS NOT TRUE AND local_path=$1 LIMIT 2', [resolve(repo)]);- if (matches.length === 1) source = matches[0].id;- else {- const owners = await tx.executeRaw<{ id: string }>('SELECT id FROM sources WHERE archived IS NOT TRUE ORDER BY id LIMIT 2');- if (!matches.length && owners.length === 1) source = owners[0].id;- else throw new Error('The restore repo does not identify exactly one source. Pass --source <id> and --repo <path> for that source.');- }- }- source ??= await resolveSourceId(tx, undefined);- if (source === ALL_SOURCES) throw new Error('--restore-only requires one source; pass --source <id>.');- if (!repo) {- const [owner] = await tx.executeRaw<{ local_path: string | null }>('SELECT local_path FROM sources WHERE id=$1', [source]);- repo = owner?.local_path ?? (source === 'default' ? await tx.getConfig('sync.repo_path') : undefined) ?? undefined;- }- if (!repo) throw new Error('--restore-only requires --repo <path> or a configured default source with a local_path.');- }+ if (restoreOnly) ({ source, repo } = await resolveRestoreTarget(tx, source, repo));const storage = restoreOnly && repo ? loadStorageConfig(repo) : null;if (restoreOnly && !storage) throw new Error('--restore-only requires a storage tiering config (gbrain.yml with a storage section).');let cursor = '0';@@ -108,10 +90,7 @@ a fresh directory. See docs/storage-tiering.md#safe-export.`);exportPathKey(key.slug + '.md');if (restoreOnly && storage && repo) {if (!isDbOnly(key.slug, storage)) continue;- if (Number(key.source_path_bytes) > 4096) throw new Error('The recorded restore path exceeds the safe path limit.');- const recorded = resolveSourceLocalFilePath(repo, key.source_path, key.slug, await scannerSlugRootMode(tx, batchSource, repo));- if (key.source_path && !recorded) throw new Error('The recorded restore file path is unsafe. Reconcile it before exporting.');- if (existsSync(nativeFileTarget(repo, recorded ?? join(repo, key.slug + '.md')))) continue;+ if (existsSync(nativeFileTarget(repo, restoreFilePath(repo, key.slug, key.source_path, Number(key.source_path_bytes), await scannerSlugRootMode(tx, batchSource, repo))))) continue;}if (Number(key.bytes) > EXPORT_PAYLOAD_LIMIT) throw new Error('Export page payload limit exceeded. No destination output was published.');const snapshot = await readExportPage(tx, key, withdrawals);diff --git a/src/commands/storage.ts b/src/commands/storage.tsindex 162c16da82..a841b97a7b 100644--- a/src/commands/storage.ts+++ b/src/commands/storage.ts@@ -1,9 +1,16 @@-import { join } from 'path';+import { existsSync } from 'fs';+import { dirname, join, relative, resolve, sep } from 'path';import type { BrainEngine } from '../core/engine.ts';-import { loadStorageConfig, validateStorageConfig, getStorageTier } from '../core/storage-config.ts';+import { loadStorageConfig, validateStorageConfig, getStorageTier, isDbOnly } from '../core/storage-config.ts';import type { StorageConfig, StorageTier } from '../core/storage-config.ts';import { walkBrainRepo, type DiskFileEntry } from '../core/disk-walk.ts';-import { getDefaultSourcePath, resolveSourceForRepoPath } from '../core/source-resolver.ts';+import { getDefaultSourcePath, isResolverUserError, resolveSourceForRepoPath } from '../core/source-resolver.ts';+import { resolveRestoreTarget, restoreFilePath, RestoreTargetError } from '../core/restore-target.ts';+import { shellQuote } from '../core/shell-quote.ts';+import { scannerSlugRootMode } from '../core/write-through.ts';+import type { SlugRootMode } from '../core/sync-anchor.ts';+import { nativeFileTarget } from '../core/persistence/native-file-target.ts';+import { OperationError } from '../core/ops/contract.ts';/*** Distinct nominal types for the two tier-keyed numeric maps. Both shapes@@ -24,6 +31,13 @@ export type DiskUsageByTier = Record<StorageTier, number> & { __brand?: 'disk-byexport interface StorageStatusResult {config: StorageConfig | null;repoPath: string | null;+ /**+ * The source `gbrain export --restore-only` restores for this repo; the+ * counts cover only its pages. Null when no restore target was resolved.+ */+ restoreSource: string | null;+ /** Why the restore target was refused; null when it was not. */+ restoreRefusal: string | null;totalPages: number;pagesByTier: PageCountsByTier;missingFiles: Array<{ slug: string; expectedPath: string }>;@@ -73,16 +87,39 @@ async function runStorageStatus(engine: BrainEngine, args: string[]): Promise<vowarnIfPGLite(engine);// Resolution chain (D5, Issue #3): explicit --repo → typed accessor → null.- // No cwd fallback. The original silent footgun is dead.- let repoPath: string | null = null;+ // No cwd fallback. The original silent footgun is dead. The repo and source+ // come from export's restore-only rule, so the printed restore command+ // restores the files listed as missing; a refused rule keeps the chain.const repoIdx = args.indexOf('--repo');- if (repoIdx !== -1 && args[repoIdx + 1]) {- repoPath = args[repoIdx + 1];- } else {- repoPath = await getDefaultSourcePath(engine);+ const explicitRepo = repoIdx !== -1 && args[repoIdx + 1] ? args[repoIdx + 1] : undefined;+ let repoPath: string | null;+ let restore: StorageRestoreTarget;+ try {+ const target = await resolveRestoreTarget(engine, undefined, explicitRepo);+ // Export matches an archived owner on the exact path only; a repo inside+ // an archived source's tree (dotfile or longest registered local_path)+ // stays a refusal here, as status always refused it. An active source+ // registered at the repo's exact path owns it outright: skip the check,+ // whose prefix match does not prefer active sources over archived ones.+ const [activeOwner] = await engine.executeRaw<{ id: string }>(+ 'SELECT id FROM sources WHERE archived IS NOT TRUE AND local_path = $1 LIMIT 1', [resolve(target.repo)]);+ if (!activeOwner) {+ try {+ await resolveSourceForRepoPath(engine, target.repo);+ } catch (e) {+ if (!isResolverUserError(e)) throw e;+ throw new RestoreTargetError((e as Error).message);+ }+ }+ repoPath = target.repo;+ restore = { source: target.source };+ } catch (e) {+ if (!(e instanceof RestoreTargetError)) throw e;+ repoPath = explicitRepo ?? (await getDefaultSourcePath(engine));+ restore = { refusal: e.message };}- const result = await getStorageStatus(engine, repoPath);+ const result = await getStorageStatus(engine, repoPath, restore);if (args.includes('--json')) {console.log(formatStorageStatusJson(result));@@ -120,6 +157,46 @@ export function __resetPGLiteWarn(): void {// ── Pure data ─────────────────────────────────────────────+/**+ * The repo's path inside its enclosing git checkout, as a `dir/` prefix+ * (empty when the repo is the checkout root or in none). A recorded+ * source_path starting with it is re-anchored by resolveSourceLocalFilePath,+ * so the repo walk cannot answer for it.+ */+function gitScopePrefix(repoPath: string): string {+ const repo = resolve(repoPath);+ for (let cursor = repo; ; cursor = dirname(cursor)) {+ if (existsSync(join(cursor, '.git'))) {+ const scope = relative(cursor, repo).split(sep).filter(Boolean).join('/');+ return scope ? scope + '/' : '';+ }+ if (dirname(cursor) === cursor) return '';+ }+}++/** The restore-only source for the repo, or why it was refused. */+export type StorageRestoreTarget = { source: string } | { refusal: string };++/**+ * The source whose pages count when no restore source was resolved: the one+ * owning repoPath (dotfile, then longest registered local_path), else none+ * (every source counts). After a refused restore target, an owner the+ * resolver rejects (an archived source) counts every source too: the refusal+ * already tells the user why no restore command fits.+ */+async function repoOwner(+ engine: BrainEngine,+ repoPath: string,+ restore: StorageRestoreTarget | undefined,+): Promise<string | null> {+ try {+ return (await resolveSourceForRepoPath(engine, repoPath))?.source_id ?? null;+ } catch (e) {+ if (restore && 'refusal' in restore && isResolverUserError(e)) return null;+ throw e;+ }+}+/*** Compute the storage status against the given engine + brain repo path.*@@ -129,10 +206,14 @@ export function __resetPGLiteWarn(): void {* Returns null `config` when no gbrain.yml is present at repoPath. In that* case pagesByTier is all zeros for db_tracked/db_only and totals roll up* into unspecified.+ *+ * `restore` with a source counts only that source's pages; without one, the+ * pages of the source that owns repoPath are counted.*/export async function getStorageStatus(engine: BrainEngine,repoPath: string | null,+ restore?: StorageRestoreTarget,): Promise<StorageStatusResult> {const config = repoPath ? loadStorageConfig(repoPath) : null;const warnings = config ? validateStorageConfig(config) : [];@@ -146,27 +227,71 @@ export async function getStorageStatus(// per directory + one stat per .md file, plus O(1) lookups below.const fileMap: Map<string, DiskFileEntry> = repoPath ? walkBrainRepo(repoPath) : new Map();- const source = repoPath ? await resolveSourceForRepoPath(engine, repoPath) : null;+ const restoreSource = restore && 'source' in restore ? restore.source : null;+ const sourceId = restoreSource ?? (repoPath ? await repoOwner(engine, repoPath, restore) : null);const pages = await engine.listPages({limit: 1_000_000,- ...(source ? { sourceId: source.source_id } : {}),+ ...(sourceId ? { sourceId } : {}),});+ // Pages export would refuse the whole restore on, grouped per reason (with+ // the lowest slug named) so a symlinked db_only dir yields one warning,+ // not one line per page.+ const refusedPages = new Map<string, { first: string; count: number }>();+ const scopePrefix = repoPath ? gitScopePrefix(repoPath) : '';+ const slugRootModes = new Map<string, SlugRootMode>();for (const page of pages) {const tier = config ? getStorageTier(page.slug, config) : 'unspecified';pagesByTier[tier]++;if (!repoPath) continue;const entry = fileMap.get(page.slug);- if (entry) {- diskUsageByTier[tier] += entry.size;- } else if (config && tier === 'db_only') {- missingFiles.push({ slug: page.slug, expectedPath: join(repoPath, page.slug + '.md') });+ if (entry) diskUsageByTier[tier] += entry.size;+ // Missing means what `export --restore-only` restores: any page under a+ // db_only dir (a db_tracked parent dir does not exempt it) whose recorded+ // source_path, else <slug>.md, is absent, checked the way export checks.+ if (!config || !isDbOnly(page.slug, config)) continue;+ const sourcePath = page.source_path ?? null;+ // Fast path, no per-page syscall: the walk saw the exact file export+ // checks as a regular file under real (non-symlink) directories, so+ // export's check finds it too. A recorded path that export would+ // re-anchor (it starts with the repo's path inside its git checkout)+ // takes the full check.+ const walkedKey = sourcePath === null ? page.slug+ : sourcePath.endsWith('.md') && !(scopePrefix && sourcePath.startsWith(scopePrefix)) ? sourcePath.slice(0, -3) : null;+ if (walkedKey !== null && fileMap.has(walkedKey)) continue;+ let expectedPath: string;+ let present: boolean;+ try {+ if (!slugRootModes.has(page.source_id)) slugRootModes.set(page.source_id, await scannerSlugRootMode(engine, page.source_id, repoPath));+ expectedPath = restoreFilePath(repoPath, page.slug, sourcePath, sourcePath ? Buffer.byteLength(sourcePath) : 0, slugRootModes.get(page.source_id)!);+ present = existsSync(nativeFileTarget(repoPath, expectedPath));+ } catch (e) {+ // Export refuses the whole restore on this page (unsafe recorded path,+ // symlinked or ambiguous file target); report that refusal.+ if (!(e instanceof RestoreTargetError) && !(e instanceof OperationError)) throw e;+ const group = refusedPages.get(e.message);+ if (!group) refusedPages.set(e.message, { first: page.slug, count: 1 });+ else {+ group.count++;+ if (page.slug < group.first) group.first = page.slug;+ }+ continue;}+ if (!present) missingFiles.push({ slug: page.slug, expectedPath });+ }++ // Ordered by each group's lowest slug, so warnings and the printed refusal+ // are the same run to run whatever order the pages were listed in.+ const refusals = [...refusedPages].sort(([, a], [, b]) => (a.first < b.first ? -1 : a.first > b.first ? 1 : 0));+ for (const [reason, { first, count }] of refusals) {+ warnings.push(count === 1 ? `${first}: ${reason}` : `${first} and ${count - 1} more page(s): ${reason}`);}return {config,repoPath,+ restoreSource,+ restoreRefusal: restore && 'refusal' in restore ? restore.refusal : (refusals[0]?.[0] ?? null),totalPages: pages.length,pagesByTier,missingFiles,@@ -232,6 +357,11 @@ export function formatStorageStatusHuman(result: StorageStatusResult): string {}}+ if (result.missingFiles.length === 0 && result.restoreRefusal) {+ lines.push('');+ lines.push(`Cannot suggest a restore command: ${result.restoreRefusal}`);+ }+if (result.missingFiles.length > 0) {lines.push('');lines.push('Missing Files (need restore):');@@ -243,7 +373,14 @@ export function formatStorageStatusHuman(result: StorageStatusResult): string {lines.push(` ... and ${result.missingFiles.length - 10} more`);}lines.push('');- lines.push(`Use: gbrain export --restore-only --repo "${result.repoPath}"`);+ if (result.restoreRefusal) {+ lines.push(`Cannot suggest a restore command: ${result.restoreRefusal}`);+ } else {+ const source = result.restoreSource ? ` --source ${result.restoreSource}` : '';+ // Shell-quoted: the line is meant to be pasted, and a repo path may hold+ // quotes, `$(...)` or backticks.+ lines.push(`Use: gbrain export --restore-only${source} --repo ${shellQuote(result.repoPath ?? '')}`);+ }}if (result.warnings.length > 0) {diff --git a/src/core/mcp-registration.ts b/src/core/mcp-registration.tsindex c95267d6ec..ea713cf2fa 100644--- a/src/core/mcp-registration.ts+++ b/src/core/mcp-registration.ts@@ -6,6 +6,10 @@* and tests are unchanged.*/+import { shellQuote } from './shell-quote.ts';++export { shellQuote };+export const REDACTED = '***';export const NAME_RE = /^[a-z0-9][a-z0-9_-]*$/;@@ -151,16 +155,6 @@ export function buildOpencodeMcpAddArgv(p: { name: string; url: string; envVar:return ['mcp', 'add', p.name, '--url', p.url, '--header', `Authorization=Bearer {env:${p.envVar}}`];}-/**- * POSIX single-quote any arg that isn't already shell-safe, so `$()`, backticks,- * etc. in a token are inert literals when the block is pasted into a shell- * (double-quoting would still allow command substitution).- */-export function shellQuote(arg: string): string {- if (/^[A-Za-z0-9_.:/@-]+$/.test(arg)) return arg;- return `'${arg.replace(/'/g, "'\\''")}'`;-}-/** Render `<binary> <argv...>` as a copy-pasteable, shell-safe command string. */export function cmdString(binary: string, argv: string[]): string {return `${binary} ${argv.map(shellQuote).join(' ')}`;diff --git a/src/core/restore-target.ts b/src/core/restore-target.tsnew file mode 100644index 0000000000..9a09b681c8--- /dev/null+++ b/src/core/restore-target.ts@@ -0,0 +1,64 @@+import { join, resolve } from 'node:path';+import type { BrainEngine } from './engine.ts';+import { resolveSourceLocalFilePath } from './markdown.ts';+import { resolveSourceId } from './source-resolver.ts';+import { ALL_SOURCES } from './source-id.ts';+import type { SlugRootMode } from './sync-anchor.ts';++/** The restore request does not identify exactly one source and its repo. */+export class RestoreTargetError extends Error {}++/**+ * The source and repo `gbrain export --restore-only` restores. `gbrain+ * storage status` resolves its restore hint with the same rule, so the files+ * it lists as missing are the ones the hint restores.+ *+ * `source` is an explicit --source already passed through resolveSourceId;+ * `repo` is an explicit --repo. A repo without a source selects the one+ * active source registered at that exact path; a repo registered only to an+ * archived source refuses; otherwise the only active source is selected.+ * Neither selects the flagless resolver chain's source and its local_path+ * (the legacy sync.repo_path answers for `default` only).+ */+export async function resolveRestoreTarget(+ engine: BrainEngine,+ source: string | undefined,+ repo: string | undefined,+): Promise<{ source: string; repo: string }> {+ if (source === ALL_SOURCES) throw new RestoreTargetError('--restore-only requires one source; pass --source <id>.');+ if (!source && repo) {+ const matches = await engine.executeRaw<{ id: string }>('SELECT id FROM sources WHERE archived IS NOT TRUE AND local_path=$1 LIMIT 2', [resolve(repo)]);+ if (matches.length === 1) source = matches[0].id;+ else {+ // A repo registered only to an archived source is that source's repo;+ // restoring another source's pages from it would be wrong.+ const [archived] = matches.length ? [] : await engine.executeRaw<{ id: string }>('SELECT id FROM sources WHERE archived IS TRUE AND local_path=$1 ORDER BY id LIMIT 1', [resolve(repo)]);+ if (archived) throw new RestoreTargetError(`The restore repo belongs to archived source "${archived.id}". Run gbrain sources restore ${archived.id} first. Or pass --source <id> and --repo <path> for an active source.`);+ const owners = await engine.executeRaw<{ id: string }>('SELECT id FROM sources WHERE archived IS NOT TRUE ORDER BY id LIMIT 2');+ if (!matches.length && owners.length === 1) source = owners[0].id;+ else throw new RestoreTargetError('The restore repo does not identify exactly one source. Pass --source <id> and --repo <path> for that source.');+ }+ }+ source ??= await resolveSourceId(engine, undefined);+ if (source === ALL_SOURCES) throw new RestoreTargetError('--restore-only requires one source; pass --source <id>.');+ if (!repo) {+ const [owner] = await engine.executeRaw<{ local_path: string | null }>('SELECT local_path FROM sources WHERE id=$1', [source]);+ repo = owner?.local_path ?? (source === 'default' ? await engine.getConfig('sync.repo_path') : undefined) ?? undefined;+ }+ if (!repo) throw new RestoreTargetError('--restore-only requires --repo <path> or a configured default source with a local_path.');+ return { source, repo };+}++/**+ * The repo file whose absence makes `export --restore-only` restore a db_only+ * page: its recorded source_path when it has one (resolved in the source's+ * slug-root mode, `scannerSlugRootMode`), else `<slug>.md`. Throws+ * RestoreTargetError when the recorded path is too long or unsafe (export+ * then refuses the whole restore).+ */+export function restoreFilePath(repo: string, slug: string, sourcePath: string | null, sourcePathBytes: number, slugRootMode: SlugRootMode): string {+ if (sourcePathBytes > 4096) throw new RestoreTargetError('The recorded restore path exceeds the safe path limit.');+ const recorded = resolveSourceLocalFilePath(repo, sourcePath, slug, slugRootMode);+ if (sourcePath && !recorded) throw new RestoreTargetError('The recorded restore file path is unsafe. Reconcile it before exporting.');+ return recorded ?? join(repo, slug + '.md');+}diff --git a/src/core/shell-quote.ts b/src/core/shell-quote.tsnew file mode 100644index 0000000000..8f47e46bf9--- /dev/null+++ b/src/core/shell-quote.ts@@ -0,0 +1,10 @@+/**+ * POSIX single-quote any arg that isn't already shell-safe, so `$()`, backticks,+ * etc. in a token are inert literals when the block is pasted into a shell+ * (double-quoting would still allow command substitution). A leaf module:+ * importing it adds no other module's text to a command's flag-registry scan.+ */+export function shellQuote(arg: string): string {+ if (/^[A-Za-z0-9_.:/@-]+$/.test(arg)) return arg;+ return `'${arg.replace(/'/g, "'\\''")}'`;+}diff --git a/test/storage-restore-hint.test.ts b/test/storage-restore-hint.test.tsnew file mode 100644index 0000000000..9814e43770--- /dev/null+++ b/test/storage-restore-hint.test.ts@@ -0,0 +1,416 @@+/**+ * #5532: the restore command `gbrain storage status` prints must restore the+ * files it lists as missing. Status counted the source that owns the repo+ * path (dotfile, then longest registered prefix, else every source) while+ * `gbrain export --restore-only` picks its source by another rule, so on a+ * multi-source brain the printed command restored another source's pages or+ * refused. Each row runs `storage status`, follows its `Use:` line (with an+ * output dir appended), and compares the restored files with the list.+ *+ * In-memory PGLite; the export destination is a physical path because export+ * publication refuses symlinked ancestors (macOS /var).+ */++import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+import { mkdirSync, mkdtempSync, readdirSync, realpathSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';+import { join, relative } from 'node:path';+import { tmpdir } from 'node:os';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { runStorage, __resetPGLiteWarn } from '../src/commands/storage.ts';+import { runExport } from '../src/commands/export.ts';+import { __resetMissingStorageWarning } from '../src/core/storage-config.ts';+import { withEnv } from './helpers/with-env.ts';+import { writeSlugRootMode } from '../src/core/sync-anchor.ts';++let engine: PGLiteEngine;+let dir: string;+let repo: string;+let out: string;+let logged: string[];+const original = { log: console.log, error: console.error, warn: console.warn, exit: process.exit };++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+});++afterAll(async () => {+ await engine.disconnect();+});++beforeEach(async () => {+ dir = realpathSync(mkdtempSync(join(tmpdir(), 'storage-restore-hint-')));+ repo = join(dir, 'repo');+ out = join(dir, 'out');+ mkdirSync(repo);+ writeFileSync(join(repo, 'gbrain.yml'), 'storage:\n db_tracked: []\n db_only:\n - media/x/\n');+ __resetMissingStorageWarning();+ __resetPGLiteWarn();+ await engine.executeRaw('DELETE FROM pages');+ await engine.executeRaw("DELETE FROM sources WHERE id <> 'default'");+ await engine.executeRaw("UPDATE sources SET local_path = NULL WHERE id = 'default'");+ await engine.executeRaw("DELETE FROM config WHERE key = 'sync.repo_path'");+ await engine.executeRaw(+ "INSERT INTO sources (id, name, local_path) VALUES ('connector-a', 'Connector A', NULL)",+ );+ logged = [];+ console.log = console.error = (...args: unknown[]) => { logged.push(args.map(String).join(' ')); };+ console.warn = () => {};+ process.exit = ((code: number) => { throw new Error(`EXIT:${code}`); }) as never;+});++afterEach(() => {+ console.log = original.log;+ console.error = original.error;+ console.warn = original.warn;+ process.exit = original.exit;+ rmSync(dir, { recursive: true, force: true });+});++async function dbOnlyPage(slug: string, sourceId: string): Promise<void> {+ await engine.putPage(slug, { type: 'note', title: slug, compiled_truth: `body-${sourceId}`, timeline: '' }, { sourceId });+}++/** A default-source db_only page whose recorded file path is `sourcePath`. */+async function recordedPage(slug: string, sourcePath: string): Promise<void> {+ await dbOnlyPage(slug, 'default');+ await engine.executeRaw("UPDATE pages SET source_path = $1 WHERE source_id = 'default' AND slug = $2", [sourcePath, slug]);+}++function writeRepoFile(path: string): void {+ mkdirSync(join(repo, path, '..'), { recursive: true });+ writeFileSync(join(repo, path), 'file bytes\n');+}++/** `storage status` output: the listed missing slugs, the warnings and the printed hint. */+async function storageStatus(args: string[]): Promise<{ missing: string[]; warnings: string[]; hint: string }> {+ logged = [];+ await runStorage(engine, ['status', ...args, '--json']);+ const json = JSON.parse(logged.join('\n')) as { missingFiles: Array<{ slug: string }>; warnings: string[] };+ const missing = json.missingFiles.map((m) => m.slug).sort();+ logged = [];+ await runStorage(engine, ['status', ...args]);+ const hint = logged.join('\n').split('\n')+ .find((line) => line.startsWith('Use: ') || line.startsWith('Cannot suggest')) ?? '';+ return { missing, warnings: json.warnings, hint };+}++/** Run the hint's command into `out`; the page slugs it restored. */+/** Split a POSIX shell command line: bare words, '...' and backslash escapes. */+function shellWords(line: string): string[] {+ const words: string[] = [];+ let word: string | null = null;+ for (let i = 0; i < line.length; i++) {+ const c = line[i];+ if (c === ' ') {+ if (word !== null) words.push(word);+ word = null;+ } else if (c === "'") {+ const end = line.indexOf("'", i + 1);+ word = (word ?? '') + line.slice(i + 1, end);+ i = end;+ } else if (c === '\\') {+ word = (word ?? '') + line[++i];+ } else {+ word = (word ?? '') + c;+ }+ }+ if (word !== null) words.push(word);+ return words;+}++async function followHint(hint: string): Promise<string[]> {+ const argv = shellWords(hint.replace(/^Use: gbrain export /, ''));+ logged = [];+ await runExport(engine, [...argv, '--dir', out]);+ const files: string[] = [];+ const walk = (at: string): void => {+ for (const entry of readdirSync(at, { withFileTypes: true })) {+ if (entry.isDirectory()) walk(join(at, entry.name));+ else if (entry.name.endsWith('.md')) files.push(relative(out, join(at, entry.name)).replace(/\.md$/, ''));+ }+ };+ walk(out);+ return files.sort();+}++describe('storage status names a restore command that restores its list (#5532)', () => {+ test.each([+ {+ name: 'legacy sync.repo_path brain with a second source, no --repo',+ args: () => [],+ seed: async () => {+ await engine.setConfig('sync.repo_path', repo);+ },+ },+ {+ name: 'a .gbrain-source in the repo naming another source',+ args: () => ['--repo', repo],+ seed: async () => {+ await engine.executeRaw("UPDATE sources SET local_path = $1 WHERE id = 'default'", [repo]);+ writeFileSync(join(repo, '.gbrain-source'), 'connector-a\n');+ },+ },+ {+ // Control row: master already restores the listed file here; it differs+ // only in the hint text (no --source). It pins that the single-owner+ // case keeps working.+ name: 'control: the repo registered to the default source',+ args: () => ['--repo', repo],+ seed: async () => {+ await engine.executeRaw("UPDATE sources SET local_path = $1 WHERE id = 'default'", [repo]);+ },+ },+ ])('$name', async ({ args, seed }) => {+ await seed();+ await dbOnlyPage('media/x/default-clip', 'default');+ await dbOnlyPage('media/x/connector-clip', 'connector-a');++ await withEnv({ GBRAIN_SOURCE: undefined }, async () => {+ const status = await storageStatus(args());+ // Only the default source's page: connector-a's never lived in this repo.+ expect(status.missing).toEqual(['media/x/default-clip']);+ expect(status.hint).toStartWith('Use: gbrain export --restore-only --source default ');+ expect(await followHint(status.hint)).toEqual(['media/x/default-clip']);+ });+ });++ test.each([+ {+ name: 'a repo that identifies no single source',+ seed: async () => {+ await engine.setConfig('sync.repo_path', repo);+ await dbOnlyPage('media/x/default-clip', 'default');+ await dbOnlyPage('media/x/connector-clip', 'connector-a');+ },+ reason: 'The restore repo does not identify exactly one source. '+ + 'Pass --source <id> and --repo <path> for that source.',+ },+ {+ name: 'a repo registered only to an archived source',+ seed: async () => {+ await engine.executeRaw("DELETE FROM sources WHERE id = 'connector-a'");+ await engine.executeRaw(+ "INSERT INTO sources (id, name, local_path, archived) VALUES ('old', 'Old', $1, true)", [repo],+ );+ await dbOnlyPage('media/x/default-clip', 'default');+ },+ reason: 'The restore repo belongs to archived source "old". '+ + 'Run gbrain sources restore old first. Or pass --source <id> and --repo <path> for an active source.',+ },+ ])('$name: status prints the refusal and export refuses it', async ({ seed, reason }) => {+ await seed();++ await withEnv({ GBRAIN_SOURCE: undefined }, async () => {+ const status = await storageStatus(['--repo', repo]);+ expect(status.hint).toBe(`Cannot suggest a restore command: ${reason}`);++ logged = [];+ await expect(runExport(engine, ['--restore-only', '--repo', repo, '--dir', out])).rejects.toThrow('EXIT:1');+ expect(logged.join('\n')).toContain(`Export failed: ${reason}`);+ });+ });++ // Export's rule matches an archived owner on the exact path only, so for a+ // subdirectory of an archived source's tree it falls back to the only+ // active source. Status keeps refusing that repo, as master's status did.+ test('a repo inside an archived source\'s tree prints a refusal', async () => {+ await engine.executeRaw("DELETE FROM sources WHERE id = 'connector-a'");+ await engine.executeRaw(+ "INSERT INTO sources (id, name, local_path, archived) VALUES ('old', 'Old', $1, true)", [dir],+ );+ await dbOnlyPage('media/x/default-clip', 'default');++ await withEnv({ GBRAIN_SOURCE: undefined }, async () => {+ const status = await storageStatus(['--repo', repo]);+ expect(status.hint).toStartWith('Cannot suggest a restore command: Source "old" not found or is archived.');+ });+ });++ test('an active source re-added at an archived source\'s path is restored, not refused', async () => {+ await engine.executeRaw("DELETE FROM sources WHERE id = 'connector-a'");+ await engine.executeRaw(+ "INSERT INTO sources (id, name, local_path, archived) VALUES ('old', 'Old', $1, true)", [repo],+ );+ await engine.executeRaw("INSERT INTO sources (id, name, local_path) VALUES ('fresh', 'Fresh', $1)", [repo]);+ await dbOnlyPage('media/x/fresh-clip', 'fresh');++ await withEnv({ GBRAIN_SOURCE: undefined }, async () => {+ const status = await storageStatus(['--repo', repo]);+ expect(status.missing).toEqual(['media/x/fresh-clip']);+ expect(status.hint).toStartWith('Use: gbrain export --restore-only --source fresh ');+ expect(await followHint(status.hint)).toEqual(['media/x/fresh-clip']);+ });+ });++ // Export decides "missing" by the page's recorded source_path when it has+ // one, else <slug>.md, for every page under a db_only directory. Status+ // must list exactly those pages.+ test.each([+ {+ name: 'a file present at its recorded source_path is not missing',+ seed: async () => {+ await recordedPage('media/x/my-clip', 'Media/X/My Clip.md');+ writeRepoFile('Media/X/My Clip.md');+ await dbOnlyPage('media/x/gone', 'default');+ },+ missing: ['media/x/gone'] as string[],+ },+ {+ name: 'a <slug>.md file does not stand in for an absent recorded source_path',+ seed: async () => {+ await recordedPage('media/x/moved', 'archive/moved-clip.md');+ writeRepoFile('media/x/moved.md');+ },+ missing: ['media/x/moved'] as string[],+ },+ {+ // The repo is a subdirectory of a git checkout: a recorded path that+ // starts with the repo's path inside the checkout resolves without that+ // prefix, so the same-named file one level deeper does not count.+ name: 'a recorded path carrying the repo prefix inside its git checkout',+ seed: async () => {+ mkdirSync(join(dir, '.git'));+ writeFileSync(join(repo, 'gbrain.yml'), 'storage:\n db_tracked: []\n db_only:\n - repo/x/\n');+ await recordedPage('repo/x/clip', 'repo/x/clip.md');+ writeRepoFile('repo/x/clip.md');+ },+ missing: ['repo/x/clip'] as string[],+ },+ {+ name: 'a db_only directory nested in a db_tracked one',+ seed: async () => {+ writeFileSync(join(repo, 'gbrain.yml'), 'storage:\n db_tracked:\n - media/\n db_only:\n - media/x/\n');+ await dbOnlyPage('media/x/nested', 'default');+ },+ missing: ['media/x/nested'] as string[],+ },+ ])('$name', async ({ seed, missing }) => {+ await engine.executeRaw("DELETE FROM sources WHERE id = 'connector-a'");+ await engine.executeRaw("UPDATE sources SET local_path = $1 WHERE id = 'default'", [repo]);+ await seed();++ await withEnv({ GBRAIN_SOURCE: undefined }, async () => {+ const status = await storageStatus(['--repo', repo]);+ expect(status.missing).toEqual(missing);+ expect(await followHint(status.hint)).toEqual(missing);+ });+ });++ // A source pinned to source-root slugs keeps a recorded path that starts+ // with the repo's checkout prefix when the stripped path is not the page's+ // slug; export resolves it in that mode, so status must too.+ test('a source-root source: the recorded path is checked in its slug-root mode', async () => {+ await engine.executeRaw("DELETE FROM sources WHERE id = 'connector-a'");+ await engine.executeRaw("UPDATE sources SET local_path = $1 WHERE id = 'default'", [repo]);+ await writeSlugRootMode(engine, 'default', 'source-root');+ try {+ mkdirSync(join(dir, '.git'));+ writeFileSync(join(repo, 'gbrain.yml'), 'storage:\n db_tracked: []\n db_only:\n - repo/x/\n');+ await recordedPage('repo/x/clip', 'repo/x/clip.md');+ writeRepoFile('repo/x/clip.md');+ await dbOnlyPage('repo/x/gone', 'default');++ await withEnv({ GBRAIN_SOURCE: undefined }, async () => {+ const status = await storageStatus(['--repo', repo]);+ expect(status.missing).toEqual(['repo/x/gone']);+ expect(await followHint(status.hint)).toEqual(['repo/x/gone']);+ });+ } finally {+ await engine.executeRaw("UPDATE sources SET config = config - 'slug_root_mode' WHERE id = 'default'");+ }+ });++ // Export refuses the whole restore on these; status must print that+ // refusal (and name the page under warnings) instead of a command.+ test.each([+ {+ name: 'an unsafe recorded source_path',+ seed: async () => {+ await recordedPage('media/x/escape', '../escape.md');+ },+ slug: 'media/x/escape',+ reason: 'The recorded restore file path is unsafe. Reconcile it before exporting.',+ },+ {+ name: 'a symlinked directory on the restore path',+ seed: async () => {+ mkdirSync(join(dir, 'external-media', 'x'), { recursive: true });+ symlinkSync(join(dir, 'external-media'), join(repo, 'media'));+ await dbOnlyPage('media/x/clip', 'default');+ },+ slug: 'media/x/clip',+ reason: 'The canonical file target has no unambiguous native identity.',+ },+ ])('$name: status prints the refusal export gives', async ({ seed, slug, reason }) => {+ await engine.executeRaw("DELETE FROM sources WHERE id = 'connector-a'");+ await engine.executeRaw("UPDATE sources SET local_path = $1 WHERE id = 'default'", [repo]);+ // A second db_only dir holds a page that is plainly missing, so status+ // has a missing list to print the refusal under.+ writeFileSync(join(repo, 'gbrain.yml'), 'storage:\n db_tracked: []\n db_only:\n - media/x/\n - archive/\n');+ await seed();+ await dbOnlyPage('archive/gone', 'default');++ await withEnv({ GBRAIN_SOURCE: undefined }, async () => {+ const status = await storageStatus(['--repo', repo]);+ expect(status.missing).toContain('archive/gone');+ expect(status.hint).toBe(`Cannot suggest a restore command: ${reason}`);+ expect(status.warnings).toContain(`${slug}: ${reason}`);++ logged = [];+ await expect(runExport(engine, ['--restore-only', '--repo', repo, '--dir', out])).rejects.toThrow('EXIT:1');+ expect(logged.join('\n')).toContain(`Export failed: ${reason}`);+ });+ });++ test('a symlinked directory over every db_only page: one grouped warning and the refusal', async () => {+ await engine.executeRaw("DELETE FROM sources WHERE id = 'connector-a'");+ await engine.executeRaw("UPDATE sources SET local_path = $1 WHERE id = 'default'", [repo]);+ mkdirSync(join(dir, 'external-media', 'x'), { recursive: true });+ symlinkSync(join(dir, 'external-media'), join(repo, 'media'));+ for (const name of ['a', 'b', 'c']) await dbOnlyPage(`media/x/${name}`, 'default');+ const reason = 'The canonical file target has no unambiguous native identity.';++ await withEnv({ GBRAIN_SOURCE: undefined }, async () => {+ const status = await storageStatus(['--repo', repo]);+ expect(status.missing).toEqual([]);+ expect(status.warnings).toEqual([`media/x/a and 2 more page(s): ${reason}`]);+ expect(status.hint).toBe(`Cannot suggest a restore command: ${reason}`);+ });+ });++ test('two refusal reasons: warnings and the printed refusal follow the lowest slug, not listing order', async () => {+ await engine.executeRaw("DELETE FROM sources WHERE id = 'connector-a'");+ await engine.executeRaw("UPDATE sources SET local_path = $1 WHERE id = 'default'", [repo]);+ writeFileSync(join(repo, 'gbrain.yml'), 'storage:\n db_tracked: []\n db_only:\n - media/x/\n - archive/\n');+ mkdirSync(join(dir, 'external-archive'));+ symlinkSync(join(dir, 'external-archive'), join(repo, 'archive'));+ // Written first, so the newest-first page listing returns it last.+ await dbOnlyPage('archive/a', 'default');+ await recordedPage('media/x/z-escape', '../escape.md');+ const symlinked = 'The canonical file target has no unambiguous native identity.';+ const unsafe = 'The recorded restore file path is unsafe. Reconcile it before exporting.';++ await withEnv({ GBRAIN_SOURCE: undefined }, async () => {+ const status = await storageStatus(['--repo', repo]);+ expect(status.warnings).toEqual([`archive/a: ${symlinked}`, `media/x/z-escape: ${unsafe}`]);+ expect(status.hint).toBe(`Cannot suggest a restore command: ${symlinked}`);+ });+ });++ test('a repo path with shell metacharacters round-trips through the quoted hint', async () => {+ const oddRepo = join(dir, `b"r$(touch pwned)\`id\`'s repo`);+ mkdirSync(oddRepo);+ writeFileSync(join(oddRepo, 'gbrain.yml'), 'storage:\n db_tracked: []\n db_only:\n - media/x/\n');+ await engine.executeRaw("DELETE FROM sources WHERE id = 'connector-a'");+ await engine.executeRaw("UPDATE sources SET local_path = $1 WHERE id = 'default'", [oddRepo]);+ await dbOnlyPage('media/x/default-clip', 'default');++ await withEnv({ GBRAIN_SOURCE: undefined }, async () => {+ const status = await storageStatus(['--repo', oddRepo]);+ expect(status.hint).toEndWith(`--repo '${oddRepo.replace(/'/g, "'\\''")}'`);+ expect(await followHint(status.hint)).toEqual(['media/x/default-clip']);+ });+ });+});diff --git a/test/storage-status.test.ts b/test/storage-status.test.tsindex 9127f29b46..dc81246d0f 100644--- a/test/storage-status.test.ts+++ b/test/storage-status.test.ts@@ -19,6 +19,8 @@ const baseResult: StorageStatusResult = {db_only: ['media/x/', 'media/articles/'],},repoPath: '/data/brain',+ restoreSource: null,+ restoreRefusal: null,totalPages: 12500,pagesByTier: { db_tracked: 2156, db_only: 10100, unspecified: 244 },missingFiles: [],@@ -79,7 +81,29 @@ describe('formatStorageStatusHuman', () => {expect(out).toContain('media/x/tweet-9'); // 10thexpect(out).not.toContain('media/x/tweet-10'); // 11th truncatedexpect(out).toContain('and 15 more');- expect(out).toContain('gbrain export --restore-only --repo "/data/brain"');+ expect(out).toContain('gbrain export --restore-only --repo /data/brain');+ });++ test.each([+ { name: 'names the restore source', restore: { restoreSource: 'connector-a' },+ has: 'Use: gbrain export --restore-only --source connector-a --repo /data/brain', lacks: 'Cannot suggest' },+ // Pasting the hint must not run anything the repo path spells.+ { name: 'shell-quotes a repo path with quotes and substitutions',+ restore: { restoreSource: 'default', repoPath: "/data/b\"r$(touch x)`id`'s brain" },+ has: "Use: gbrain export --restore-only --source default --repo '/data/b\"r$(touch x)`id`'\\''s brain'", lacks: 'Cannot suggest' },+ { name: 'prints a refused restore target instead of a command', restore: { restoreRefusal: 'Pass --source <id>.' },+ has: 'Cannot suggest a restore command: Pass --source <id>.', lacks: 'Use: gbrain export' },+ ])('restore hint: $name', ({ restore, has, lacks }) => {+ const missingFiles = [{ slug: 'media/x/clip', expectedPath: '/data/brain/media/x/clip.md' }];+ const out = formatStorageStatusHuman({ ...baseResult, ...restore, missingFiles });+ expect(out).toContain(has);+ expect(out).not.toContain(lacks);+ });++ test('prints a restore refusal even when no file is missing', () => {+ const out = formatStorageStatusHuman({ ...baseResult, restoreRefusal: 'Pass --source <id>.', missingFiles: [] });+ expect(out).toContain('Cannot suggest a restore command: Pass --source <id>.');+ expect(out).not.toContain('Missing Files');});test('shows configuration listing for both tiers', () => {