Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
Commit door wave 2: dry runs check paths, older binaries keep off a newer schema, literal pathspecs everywhere
garrytanacc9a38975b4
diff --git a/docs/architecture/key-files/core-persistence-graduation.md b/docs/architecture/key-files/core-persistence-graduation.mdindex 95981bf038..4bb639911e 100644--- a/docs/architecture/key-files/core-persistence-graduation.md+++ b/docs/architecture/key-files/core-persistence-graduation.md@@ -19,4 +19,5 @@ Verified engine graduation, PGLite to Postgres ([operator guide](../../guides/mo- `src/core/repair/missing-tables.ts` — `gbrain repair missing-tables` (#6911), explicit-only and preview-bound (`--apply --expect <hash>`), brain-wide, DDL only. The preview lists the missing rebuildable caches `readMissingTables` reports (`recreate`), plus `user_data_tables` and `other_tables` residuals it never recreates; the hash covers the brain id, `LATEST_VERSION` and the tables. Apply refuses when the brain schema is newer than the client, leaves a table that already exists alone (`already_present`, no DDL), runs `recreateStep` in one transaction per table under the migration statement and lock timeouts (`schemaLockBlockedError` on a lock timeout), maps 42501 to `schema_owner_required` (approval kept) and 23505/42P07 races to `already_present`, and retires the approved set with the last item. Tests: `test/purge-missing-cache-6911.test.ts`, `test/schema-missing-tables.test.ts`.- `src/core/repair/url-clone-fences.ts` — `gbrain repair url-clone-fences` (#6946, GBRA-130 C-2): explicit-only, preview-bound, destructive consent; unmanaged brains only (a managed brain gets a warning naming `sources mirror-readonly`). The survey lists every tracked file of each owned clone in scope that differs from HEAD (`trackedChanges`) and proves per file (`proveFenceRowsOnly`) that HEAD's fence rows are an unchanged prefix of the working copy's and that re-rendering HEAD with the working fence matches byte for byte (`fence_rows_only`); anything else is listed as `non_fence_edit` / `unparsed_fence` / `staged_change` / `deleted` / `not_in_head` / `unreadable_checkout` and never touched; a file whose HEAD would not import (`headHold`, the import screen with `holdNoncanonicalPrivate`) is listed under the hold's code, and at apply its rows still go database-only and the file is restored (so the clone can pull) but HEAD is not imported; the import opts in too, and a held file reports `held` with the code instead of `restored` (#7897). The preview hash binds the approved set (preview-approval, keyed by the command string). The apply, per file under the source filesystem lock and page lock, rechecks both sides (`changed_since_preview`), backs the file up under `~/.gbrain/backups/url-clone-fences/`, clears `row_num`/`source_markdown_slug` on the appended rows in one `maintenanceTransaction` (inserting database-only any row the database lost), imports HEAD's bytes as the page through `importFromContent`, and only then restores the file from HEAD; each step is idempotent. Tests: `test/pathological/c2-url-clone-fences.test.ts`, `test/url-clone-fences-private-hold-7897.test.ts`.- `src/core/schema-missing-tables.ts` — #6911 expected-table check. `readMissingTables`: at head every graduation-inventory table for the engine, below head only the recreatable caches whose creating migration (`CREATED_BY`) already ran, `skipped` (`client_behind`) when the brain is newer; each missing table carries its inventory class and `loss_kind`. `recreateStep` (own-key lookup, rebuild class only) rebuilds `query_cache` (v055 DDL sized from the live `facts.embedding` shape, then the v056/v090/v091 statements) and `code_traversal_cache` (v059), then on Postgres enables RLS on the recreated table through v275's `protectTables` (a role that does not bypass RLS or own the table leaves it RLS-off and names it on stderr). `test/schema-missing-tables.test.ts` pins each recreated table's columns and indexes to the migrated brain's on both engines and checks that every inventory rebuild table is either in `RECREATABLE_TABLES` or defined by the base schema (so `init --migrate-only` recreates it). Doctor `schema_missing_tables` (`src/commands/doctor/checks/schema-health.ts`) renders it: warn for caches (repair preview fix) and tables without user data, fail for `user_data` tables.+- `src/commands/doctor/checks/schema-function-bodies.ts` — `schema_function_bodies` (#7776, META, after `schema_version`): every function this binary's schema blob defines (`SCHEMA_SQL` or the PGLite template, parsed, never hand-listed; the writer-fence guards v197, v272 and v278 replace among them) must have its body installed, compared after whitespace and FTS-configuration normalization. Checked only at head (`skipped` with `client_behind` above it, `migrations_pending` below); a mismatch fails, names the functions and points at `gbrain init --migrate-only` after every gbrain on the database is upgraded. `test/doctor-schema-function-bodies.test.ts` pins that a fresh install matches.- `src/core/persistence/rebuildable-cache.ts` — #6911 purge-side skip: `isRebuildableCache` (inventory class `rebuild`), `relationExists` (`to_regclass` on the connection's search path), and `clearRebuildableCache(tx, table)`, which returns the rows deleted or null when the cache table is absent; the existence check runs first because a 42P01 aborts a Postgres transaction. Callers: page purge (`purge.missing_caches`) and fact purge.diff --git a/docs/architecture/key-files/engines-2.md b/docs/architecture/key-files/engines-2.mdindex 806a02c2dd..5ce3f5ae62 100644--- a/docs/architecture/key-files/engines-2.md+++ b/docs/architecture/key-files/engines-2.md@@ -51,6 +51,8 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/search/connection-budget.ts` — per-op pooled-connection budget for `search` and `query`. `SEARCH_CONNECTION_LIMIT` (4) is the most connections one op holds at once. `withSearchConnectionBudget` opens the scope; the ops' `metered` wrapper in `src/core/ops/search.ts` and `dispatchToolCall` (`src/mcp/dispatch.ts`, so pre-op reads and the response-meta hook count too) both enter it, and a nested call shares the enclosing budget. `holdSearchConnection` is called at the engine's two connection seams, `PostgresEngine#transactionOn` (a top-level transaction, held until its COMMIT settles even when a read transaction answers early) and `runUnsafe` (one statement). Work inside a held slot runs outside the scope, so statements on a transaction's own connection never wait on a second slot. A read started under `withUrgentSearchConnections` (hybrid search's lexical, relational and vector arms, `hybrid/arms.ts`) takes the next free slot ahead of waiting ordinary reads (the keyword count and entity resolution an op starts early for its response; GBRA-156, `test/search-connection-budget-urgent.test.ts`). Outside a scope, and on PGLite, nothing waits. These reads use the ordinary read pool (the transaction pooler behind a split route), never the direct/session lane. Pinned on Postgres at the wire by `test/e2e/search-connection-budget-postgres.test.ts`.Size ceiling: `scripts/module-size-limits.tsv` (per-change raise history: `git log -p` on that file). The ceiling covers every BrainEngine method whose SQL has not moved to `src/core/engine-sql/` (rows in `scripts/engine-sql-baseline.tsv`), written as parity twins of the PGLite methods (search arms, graph traversal caps, source-scoped stats and health, page lifecycle and soft delete, chunk writes, transaction routing). Migrated domains are one-line delegations over the private `engineSql` getter (a fresh adapter over `this.sql` on every access); reads that were RLS-scoped on master keep their own `withScopedReadTransaction` call and hand engine-sql `scopedRead(this.engineSqlOn(tx))`, an adapter over the scoped handle; `runUnsafe` forwards `prepare`/`simple` only when the engine-sql adapter sets them.+- `src/core/schema-client-behind.ts` — #7776: `assertSchemaNotAhead(query)` runs on the schema-setup connection before both engines' schema replay: a `config.version` above `LATEST_SCHEMA_VERSION` refuses `client_behind` (fix `gbrain upgrade`, `host_admin`) before the bootstrap and replay, so an older binary never reinstalls its superseded function bodies over a newer schema. No config table or no version row (a fresh install) is not behind. `apply-migrations` refuses the same way before any orchestrator and before a `--force-schema`/`--force-all` schema pass, whose drift repairs would rewrite newer objects (`schemaAheadRefusal`, `connectForForcedSchema` in `apply-migrations-schema.ts`). Pinned by `test/init-schema-client-behind.test.ts` and its Postgres e2e twin.+- `src/core/snapshot-schema-inputs.ts` — the inputs of the PGLite snapshot schema hash (`computeSnapshotSchemaHash` in `pglite-engine.ts` hashes each file's raw bytes). Computed, not hand-kept: the static import closure (`import`, `export ... from`; type-only imports skipped) of `SNAPSHOT_SCHEMA_ROOTS` (`pglite-schema.ts`, `schema-migrations/registry.generated.ts`, `migrate.ts`, `engine-sql/bootstrap.ts`) plus `SNAPSHOT_SCHEMA_LEAVES`; every literal dynamic `import()` inside the closure must be classified as a leaf or in `SNAPSHOT_DYNAMIC_IMPORTS_NOT_HASHED`. Pure (the caller supplies file access). `test/snapshot-inputs-closure.test.ts` names any missing file and checks every `pglite-snapshot-*` CI cache key covers the same inputs.- `src/core/sql-trace.ts` — env-gated wire-level SQL trace for benchmarks. `traceSqlOptions(options, pool)` returns the postgres.js options untouched unless `GBRAIN_SQL_TRACE=<file.jsonl>` is set; then it supplies a tracing socket and sets `application_name` to `gbrain:<GBRAIN_SQL_TRACE_LABEL or command>:<pid>:<pool>`. All four pool construction sites use it (`db.ts` module singleton, `PostgresEngine` instance pool, `ConnectionManager` read and direct pools), so `executeRaw`, `tx.unsafe`, the engine-sql adapter and tagged templates are all seen. Each Sync, simple Query or describe Flush and its reply is one JSONL record (statement text without parameter values, start, duration, process, pool, client connection, backend pid, SQLSTATE on error); a `connect` record covers TCP plus the startup handshake. TLS connections are recorded once as `tls_untraced`. Records are buffered and flushed every second and at exit. Consumed by `scripts/bench/managed-sync-catchup.ts` ([record](../../eval/managed-sync-catchup.md)); pinned by `test/sql-trace.test.ts` and `test/e2e/sql-trace-postgres.test.ts`.diff --git a/docs/architecture/key-files/graph-and-facts.md b/docs/architecture/key-files/graph-and-facts.mdindex 44d6c0297d..345d2d8b6b 100644--- a/docs/architecture/key-files/graph-and-facts.md+++ b/docs/architecture/key-files/graph-and-facts.md@@ -94,7 +94,7 @@ rejection of serve-only flags before a brain opens.- `src/core/extract-frontmatter.ts` — `resolveIncludeFrontmatter(engine, explicit?)`: the single answer for "extract `related:`/`sources:` frontmatter link edges too?" (`autopilot.incremental_extract_include_frontmatter`; explicit flag > file plane > DB plane via `isConfigTruthy` > false, fail-closed on an unreadable config table). Resolved INSIDE the shared helpers — `extractLinksForSlugs` and `extractStaleFromDB` default `opts.includeFrontmatter` through it, the same in-helper pattern as `isGlobalBasenameEnabled` — so sync's inline extract, the GitHub/Google source inline extracts, the `extract_stale` minion, `gbrain maintain`, the cycle's extract phase and `gbrain extract --stale` (flag absent → configured knob) all agree; no caller passes a literal `false`. Pinned by `test/extract-include-frontmatter-config.serial.test.ts` (resolver precedence + a source-text guard on the call sites + a PGLite link-row test through `extractLinksForSlugs`).-- `src/core/extract/receipt-writer.ts` + `src/core/extract/rollup-writer.ts` + `src/commands/extract-status.ts` + `src/commands/extract-explain.ts` + `src/commands/extract-benchmark.ts` + `src/core/schema-pack/scaffold-extractable.ts` — unified extract operator surface. Every shipped extractor (deterministic `facts.conversation` in `src/commands/extract-conversation-facts.ts` + three LLM-backed cycle phases at `src/core/cycle/{extract-atoms,synthesize-concepts,propose-takes,extract-facts}.ts`) writes ONE receipt page per run (`writeReceipt`) + UPSERTs a row to `extract_rollup_7d` (`upsertExtractRollup`). Receipt slug `extracts/{date}/{kind}/{source_id}/{run_id_short}/round-{N}.md`; frontmatter stamps BOTH `type: extract_receipt` AND `dream_generated: true` (belt+suspenders against extraction-loop guard drift). `extract_receipt` joins `ALL_PAGE_TYPES` in `src/core/types.ts`; `extracts/` prefix gets a 0.3x source-boost demote in `src/core/search/source-boost.ts`. Migration v104 adds `extract_rollup_7d (kind, source_id, day, cost_usd, halt_count, eval_pass_count, eval_fail_count, round_completed_count, rollup_write_failures, updated_at)` with PK `(kind, source_id, day)` + `idx_extract_rollup_7d_day`. Rollup writes best-effort with process-scoped error-dedup so transient DB failures bump `rollup_write_failures` instead of crashing the cycle. Migration v239 adds `halt_reasons JSONB NOT NULL DEFAULT '{}'` (DDL only, no backfill): `classifyRunStop({ error })` takes `true` (an unclassified halt) or one word of the closed `HALT_REASONS` vocabulary (`provider_auth`, `provider_billing`, `provider_rate_limit`, `provider_model_not_found`, `no_pricing`, `integrity_guard`, `item_error`; a budget or deadline cap is an expected stop, never a reason), and the same UPSERT increments that key with bound parameters (`$N::text`, `jsonb_set`). `unknown` is never stored: the doctor read computes it as `halt_count - sum(halt_reasons)` (`haltReasonsWithUnknown`), so pre-v239 rows and older w... (line truncated to 2000 chars)+- `src/core/extract/receipt-writer.ts` + `src/core/extract/rollup-writer.ts` + `src/commands/extract-status.ts` + `src/commands/extract-explain.ts` + `src/commands/extract-benchmark.ts` + `src/core/schema-pack/scaffold-extractable.ts` — unified extract operator surface. Every shipped extractor (deterministic `facts.conversation` in `src/commands/extract-conversation-facts.ts` + three LLM-backed cycle phases at `src/core/cycle/{extract-atoms,synthesize-concepts,propose-takes,extract-facts}.ts`) writes ONE sealed DB-only receipt per run (`writeReceipt`) + UPSERTs a row to `extract_rollup_7d` (`upsertExtractRollup`). Receipt slug `extracts/{date}/{kind}/{source_id}/{run_id_short}/round-{N}.md`; frontmatter stamps BOTH `type: extract_receipt` AND `dream_generated: true` (belt+suspenders against loop-guard drift). `extract_receipt` joins `ALL_PAGE_TYPES` in `src/core/types.ts`; `extracts/` prefix gets a 0.3x source-boost demote in `src/core/search/source-boost.ts`. Migration v104 adds `extract_rollup_7d (kind, source_id, day, cost_usd, halt_count, eval_pass_count, eval_fail_count, round_completed_count, rollup_write_failures, updated_at)` with PK `(kind, source_id, day)` + `idx_extract_rollup_7d_day`. Rollup writes best-effort with process-scoped error-dedup so transient DB failures bump `rollup_write_failures` instead of crashing the cycle. Migration v239 adds `halt_reasons JSONB NOT NULL DEFAULT '{}'` (DDL only, no backfill): `classifyRunStop({ error })` takes `true` (an unclassified halt) or one word of the closed `HALT_REASONS` vocabulary (`provider_auth`, `provider_billing`, `provider_rate_limit`, `provider_model_not_found`, `no_pricing`, `integrity_guard`, `item_error`; a budget or deadline cap is an expected stop, never a reason), and the same UPSERT increments that key with bound parameters (`$N::text`, `jsonb_set`). `unknown` is never stored: the doctor read computes it as `halt_count - sum(halt_reasons)` (`haltReasonsWithUnknown`), so pre-v239 rows and older w... (line truncated to 2000 chars)- `src/core/extraction-review.ts` — Extraction quarantine lane markers, sibling of `src/core/quarantine.ts` / `embed-skip.ts` (frontmatter-key pattern, no schema migration). Auto-extracted stubs from untrusted input carry the PAIR `provenance: 'auto-extracted'` + `status: 'unverified'` (both required — user pages with their own `status`/`provenance` never match). Exports `quarantineMarkers()`, `isUnverifiedExtraction()` (JS predicate) and `unverifiedExtractionFragment(alias)` — the single SQL source of truth consumed by `buildSourceFactorCase` (namespace source-boost guard), both engines' `getUnverifiedExtractionPageIds`, the `extraction_pending` op, and the `unverified_extractions` doctor check, so filter and marker keys can never drift. Consequences: unverified stubs are excluded from the compiled-truth fusion boost + the `people/`/`companies/` source-boost (rank as ordinary content), stamped `unverified: true` in search results (`stampUnverifiedExtractions`, hybrid.ts), listed by `extraction_pending`, promoted (status → `verified`, provenance kept for audit) or rejected (soft-delete) by the owner-only `extraction_review` op, which also records `distinct` decisions (`distinct_from`); every decision publishes through the page door (Git first on a repository source, the database on a repo-less one) under `persistence/publication-guard.ts`, with the revision it read. Pinned by `test/extraction-review.test.ts` (PGLite) + `test/e2e/extraction-review-postgres.test.ts` (live Postgres parity).diff --git a/docs/architecture/key-files/security.md b/docs/architecture/key-files/security.mdindex fc76613272..7d7a94ecc0 100644--- a/docs/architecture/key-files/security.md+++ b/docs/architecture/key-files/security.md@@ -43,6 +43,6 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/write-gate-scan.ts` + `scripts/trust-dry-run-scan.ts` — read-only exposure scan: keyset batches over pages, facts, takes and timeline entries, tier projected from deterministic signals (connector source, webhook/clipper page, `mcp:*`/capture/transcript page, agent fact lanes, `persistence_requests` operation and authority; none -> `unknown`), flag/quarantine counts and families per tier and table, counts and pattern names only. The script runs it in a REPEATABLE READ READ ONLY transaction (PGLite: on a copy of the data directory). Test: `test/write-gate-scan.test.ts`.-- `src/core/git-env.ts` + `src/core/hardened-git.ts` — #7584, the operator's `safe.directory` in scrubbed Git environments: `hardenedGitEnvironment` still drops system and global config and every `GIT_*` variable, but carries the operator's `safe.directory` entries (system and global, read from `/` with `git config --includes --show-scope` and cached for 30 s, then `GIT_CONFIG_*`) as environment config, so a source repository owned by another user reads once the operator allows it. `gitChildEnv` carries the environment entries the same way (`envSafeDirectories`, `safeDirectoryEnv`). Every other key in those places stays out. `gitChildEnv` also drops Git's global pathspec switches (`GIT_PATHSPEC_ENV_VARS`: `GIT_LITERAL_PATHSPECS`, `GIT_GLOB_PATHSPECS`, `GIT_NOGLOB_PATHSPECS`, `GIT_ICASE_PATHSPECS`; `extra` can still set one). gbrain's writers mark each path literal with `literalPathspecs` (`:(literal)<path>`), never `git --literal-pathspecs`, which Git exports to every hook and child as `GIT_LITERAL_PATHSPECS=1`, where a hook's glob pathspec then matches nothing. GST-2331: `NO_LAZY_FETCH_ENV` (`GIT_NO_LAZY_FETCH=1` and an empty `GIT_ALLOW_PROTOCOL`) is what a managed-sync read that runs under `gitChildEnv` adds beside `HARDENED_GIT_ARGS`, so a partial clone fetches nothing (Git before 2.45 ignores the first; the empty allowlist allows no transport on any Git): `syncGit`/`syncGitAsync`, every read in `sync-blobs.ts`, `sync-delta.ts`'s text runner (a rename whose old blob the clone lacks fails the diff, `diff_failed`, and discovery walks the whole tree), `sync-rename-identity.ts`, `sync-metafile-pages.ts`, `sync-origin-evidence.ts`, `sync-held-deletions.ts`, `unindexed-files.ts` and `pending-import.ts`. Tests: `test/hardened-git-safe-directory-7584.test.ts` (ownership forced with `GIT_TEST_ASSUME_DIFFERENT_OWNER` through a `git` wrapper on PATH), `test/git-literal-pathspec-hooks-7759.test.ts`, `test/sync-partial-clone-2331.test.ts`.+- `src/core/git-env.ts` + `src/core/hardened-git.ts` — #7584, the operator's `safe.directory` in scrubbed Git environments: `hardenedGitEnvironment` still drops system and global config and every `GIT_*` variable, but carries the operator's `safe.directory` entries (system and global, read from `/` with `git config --includes --show-scope` and cached for 30 s, then `GIT_CONFIG_*`) as environment config, so a source repository owned by another user reads once the operator allows it. `gitChildEnv` carries the environment entries the same way (`envSafeDirectories`, `safeDirectoryEnv`). Every other key in those places stays out. `gitChildEnv` also drops Git's global pathspec switches (`GIT_PATHSPEC_ENV_VARS`: `GIT_LITERAL_PATHSPECS`, `GIT_GLOB_PATHSPECS`, `GIT_NOGLOB_PATHSPECS`, `GIT_ICASE_PATHSPECS`; `extra` can still set one). gbrain's writers and readers mark each path literal with `literalPathspecs` (`:(literal)<path>`; an empty path throws, since `:(literal)` alone matches the whole tree, #7793), never `git --literal-pathspecs`, which Git exports to every hook, textconv and filter helper as `GIT_LITERAL_PATHSPECS=1`, where a hook's glob pathspec then matches nothing; `test/git-env-guard.test.ts` rejects a global pathspec switch (flag or env) anywhere in `src`. GST-2331: `NO_LAZY_FETCH_ENV` (`GIT_NO_LAZY_FETCH=1` and an empty `GIT_ALLOW_PROTOCOL`) is what a managed-sync read that runs under `gitChildEnv` adds beside `HARDENED_GIT_ARGS`, so a partial clone fetches nothing (Git before 2.45 ignores the first; the empty allowlist allows no transport on any Git): `syncGit`/`syncGitAsync`, every read in `sync-blobs.ts`, `sync-delta.ts`'s text runner (a rename whose old blob the clone lacks fails the diff, `diff_failed`, and discovery walks the whole tree), `sync-rename-identity.ts`, `sync-metafile-pages.ts`, `sync-origin-evidence.ts`, `sync-held-deletions.ts`, `unindexed-files.ts` and `pending-import.ts`. Tests: `test/hardened-git-safe-directory-7584.test.ts` (ownership forced with `GIT_TEST_ASSUME_DIFFERENT_OWNER` through a `git` wrapper on PATH), `test/git-literal-pathspec-hooks-7759.test.ts`, `test/git-literal-pathspecs-7793.test.ts`, `test/sync-partial-clone-2331.test.ts`.- `src/core/outside-content.ts` — GBRA-221: `neutralizeOutsideText(text)`, the one neutralizer for text a third party wrote before it lands in a page body (Gmail/Calendar/Contacts renders in `google-render.ts`, GitHub `renderItemPage`/`renderRepoCard`, chat transcripts in `transcripts/render.ts`, `book-mirror` chapter output). It escapes every `gbrain<ws>:<ws><name>` marker token to `gbrain\:<name>` (case-insensitive), `[Source:` to `[Source\:`, and backslash-prefixes each timeline sentinel, bare `## Timeline`/`## History` heading, dated timeline row or heading, transcript message anchor and date heading, using the parsers' own predicates. Idempotent and readable; apply it per outside field (or a composed line holding one), never to a whole page that may hold gbrain's own fences or citations. Also owns `escapeAnchorLines` and `MESSAGE_ANCHOR_RE` (re-exported by `transcripts/render.ts`). New connectors use it.diff --git a/docs/architecture/key-files/workspace-push-and-backup.md b/docs/architecture/key-files/workspace-push-and-backup.mdindex 13dccfabd6..294644c8d7 100644--- a/docs/architecture/key-files/workspace-push-and-backup.md+++ b/docs/architecture/key-files/workspace-push-and-backup.md@@ -12,7 +12,7 @@ Key files:## Shared-checkout git writer-- `src/core/git/commit-push.ts` + `src/core/git/commit-guard.ts` — writer safety in a shared checkout (#7381). `integrate` replaces the tip 3-way merge when any local commit is patch-equivalent to an upstream one (`rev-list --cherry-mark`): it replays the local commits onto the remote tip in memory (`merge-tree --merge-base` on git 2.40+, a 3-way `read-tree` otherwise), leaving out the equivalent ones and clean merges, so a copy the remote edited never conflicts and one it reverted is never re-applied; the merge message lists what it left out. `supersededPaths` resolves a content conflict to ours when the remote's blob is one the same path held earlier in ours' history (last 200 commits touching it) and a different blob replaced it there; the push reports them as `superseded_remote_paths`, and `integrate_conflict` lists only the rest (`detail.superseded` names them). `commitPaths` refuses a path outside the source roots (`configuredSourceRoots`, git config `gbrain.sourceRoot`, recorded by `sources harden`'s `recordSourceRoot`) and a file another writer staged under a named directory (`commit_prestaged_paths`), stages named tracked paths with `add -u` and visible untracked ones with `add -A` (a tracked deletion under an ignored directory commits, #7984; any other path keeps git's `commit_paths_invalid`), and restores the exact index entries (`update-index --index-info`) when git refuses the commit. After the commit step (and its index restore) `commitPaths` returns the named paths HEAD still lacks (`unstagedPaths`: a modified entry flagged assume-unchanged or skip-worktree, a named file git did not index such as one inside a nested repository, and unstaged status entries under a named directory; a skip-worktree entry absent from disk, a flagged gitlink and ignored files under a named directory are left out) and keeps an unindexed file out of `commit --only`; `commitAndPush` (classic, managed and remoteless) and `commitPathsLocked` then throw `commit_paths_skipped`, or `writer_coordinator_required` for a page in a managed worktree (its `put_page` fix names the managed source), once the rest is committed and, on a classic checkout, pushed (`detail`: `skipped`, `committed`, `pushed`, `branch`, and `publish` when the push failed too). Every commit gbrain makes carries `GBRAIN_COMMIT_VIA=<lock path>`. Every pathspec it passes goes through `literalPathspecs` (`git-env.ts`), never `git --literal-pathspecs`, so the commit's hooks keep Git's normal pathspec rules: a pre-commit guard that selects files by glob still sees and can refuse them (`git_unavailable`, paths unstaged). `commitPathsLocked` (write-through) never commits without the lock: a busy lock or refused commit notes the file in `brain-writethrough-pending.log` (git dir, O_APPEND lines), which the next locked write-through and `commit-push --pending` commit and `settlePending` prunes. `notePending` is exported: the derived and dream write-through (`cycle/derived-write-through.ts`, #8073) records each file it writes before its batch commit, so a crash in between leaves the file for that sweep. A publish refuses local non-merge commits outside the roots (`commit_outside_source_root`; `--allow-outside-source-root` lifts both refusals, and `sources harden` passes it for its root scaffolding). With git config `gbrain.quarantine` (opt-in) a content conflict publishes the remote's version of each conflicted file plus every other local change, names the local commit under `refs/gbrain/quarantine/<time>-<sha>` and appends it to `brain-quarantine.log` (`readQuarantine` lists entries whose ref still exists); structural conflicts still refuse. `commit-guard.ts` installs the opt-in `prepare-commit-msg` guard (`gbrain git guard`), which admits only commits naming a held commit lock, passes merges and in-progress operations, and honors `GBRAIN_COMMIT_GUARD=off`. The helper's no-gbrain fallback (`renderCommitPushHelper`) marks children with the absolute lock path and releases the commit lock before pushing under `brain-publish.lock`; it runs the same skipped-path check after its commit and reports `commit_paths_skipped` after the push (exit 1, or 4 when the push failed). The CLI (`src/commands/git.ts`) refuses `checkout_not_a_source` before staging when this brain home's managed-root registry records source checkouts and the resolved checkout is none of them and has no `gbrain.sourceRoot` (#8662); a registered checkout must contain the resolved one, or be a subdirectory its HEAD tracks, so a repository that only encloses one is refused, and a registry that cannot be listed refuses `writer_coordinator_required` (GST-1623). `--untrack` (#7753, GST-2519): `untrackPaths` removes the files HEAD holds under the named paths (`untrackTargets`; skip-worktree files refuse) with `git rm --cached` and commits from HEAD in a temporary index, taking back a commit that changed anything else; in a managed canonical worktree `untrackAdmitted` first requires each file to sit under a `storage.db_only` dir that `gbrain.yml` at HEAD declares and that `.gitignore` ignores (`untrack_not_db_only`, index untouched), and the commit stays local like every managed commit; `previewUntrack` is the dry run. A not_staged path that is a hand-staged `git rm --cached` names `--untrack` in the `commit_paths_skipped` fix. Tests: `test/git-writer-safety-7381.serial.test.ts`, `test/git-literal-pathspec-hooks-7759.test.ts`, `test/git-commit-push-not-a-source-8662.test.ts`, `test/git-commit-push-skipped-paths-gst2116.test.ts`, `test/git-commit-push-untrack-gst2519.test.ts`.+- `src/core/git/commit-push.ts` + `src/core/git/commit-guard.ts` — writer safety in a shared checkout (#7381). `integrate` replaces the tip 3-way merge when any local commit is patch-equivalent to an upstream one (`rev-list --cherry-mark`): it replays the local commits onto the remote tip in memory (`merge-tree --merge-base` on git 2.40+, a 3-way `read-tree` otherwise), leaving out the equivalent ones and clean merges, so a copy the remote edited never conflicts and one it reverted is never re-applied; the merge message lists what it left out. `supersededPaths` resolves a content conflict to ours when the remote's blob is one the same path held earlier in ours' history (last 200 commits touching it) and a different blob replaced it there; the push reports them as `superseded_remote_paths`, and `integrate_conflict` lists only the rest (`detail.superseded` names them). `commitPaths` refuses a path outside the source roots (`configuredSourceRoots`, git config `gbrain.sourceRoot`, recorded by `sources harden`'s `recordSourceRoot`) and a file another writer staged under a named directory (`commit_prestaged_paths`), stages named tracked paths with `add -u` and visible untracked ones with `add -A` (a tracked deletion under an ignored directory commits, #7984; any other path keeps git's `commit_paths_invalid`), and restores the exact index entries (`update-index --index-info`) when git refuses the commit. After the commit step (and its index restore) `commitPaths` returns the named paths HEAD still lacks (`unstagedPaths`: a modified entry flagged assume-unchanged or skip-worktree, a named file git did not index such as one inside a nested repository, and unstaged status entries under a named directory; a skip-worktree entry absent from disk, a flagged gitlink and ignored files under a named directory are left out) and keeps an unindexed file out of `commit --only`; `commitAndPush` (classic, managed and remoteless) and `commitPathsLocked` then throw `commit_paths_skipped`, or `writer_coordinator_required` for a page in a managed worktree (its `put_page` fix names the managed source), once the rest is committed and, on a classic checkout, pushed (`detail`: `skipped`, `committed`, `pushed`, `branch`, and `publish` when the push failed too). Every commit gbrain makes carries `GBRAIN_COMMIT_VIA=<lock path>`. Every pathspec it passes goes through `literalPathspecs` (`git-env.ts`), never `git --literal-pathspecs`, so the commit's hooks keep Git's normal pathspec rules: a pre-commit guard that selects files by glob still sees and can refuse them (`git_unavailable`, paths unstaged). `commitPathsLocked` (write-through) never commits without the lock: a busy lock or refused commit notes the file in `brain-writethrough-pending.log` (git dir, O_APPEND lines), which the next locked write-through and `commit-push --pending` commit and `settlePending` prunes. `notePending` is exported: the derived and dream write-through (`cycle/derived-write-through.ts`, #8073) records each file it writes before its batch commit, so a crash in between leaves the file for that sweep. A publish refuses local non-merge commits outside the roots (`commit_outside_source_root`; `--allow-outside-source-root` lifts both refusals, and `sources harden` passes it for its root scaffolding). With git config `gbrain.quarantine` (opt-in) a content conflict publishes the remote's version of each conflicted file plus every other local change, names the local commit under `refs/gbrain/quarantine/<time>-<sha>` and appends it to `brain-quarantine.log` (`readQuarantine` lists entries whose ref still exists); structural conflicts still refuse. `commit-guard.ts` installs the opt-in `prepare-commit-msg` guard (`gbrain git guard`), which admits only commits naming a held commit lock, passes merges and in-progress operations, and honors `GBRAIN_COMMIT_GUARD=off`. The helper's no-gbrain fallback (`renderCommitPushHelper`) marks children with the absolute lock path, passes each path as `:(literal)<path>` (a glob-named path never commits another file, #7792) and releases the commit lock before pushing under `brain-publish.lock`; it runs the same skipped-path check after its commit and reports `commit_paths_skipped` after the push (exit 1, or 4 when the push failed). The CLI (`src/commands/git.ts`) refuses `checkout_not_a_source` before staging when this brain home's managed-root registry records source checkouts and the resolved checkout is none of them and has no `gbrain.sourceRoot` (#8662); a registered checkout must contain the resolved one, or be a subdirectory its HEAD tracks, so a repository that only encloses one is refused, and a registry that cannot be listed refuses `writer_coordinator_required` (GST-1623). `--untrack` (#7753, GST-2519): `untrackPaths` removes the files HEAD holds under the named paths (`untrackTargets`; skip-worktree files refuse) with `git rm --cached` and commits from HEAD in a temporary index, taking back a commit that changed anything else; in a managed canonical worktree `untrackAdmitted` first requires each file to sit under a `storage.db_only` dir that `gbrain.yml` at HEAD declares and that `.gitignore` ignores (`untrack_not_db_only`, index untouched), and the commit stays local like every managed commit; `previewUntrack` is the dry run. The dry run of a commit is `previewPaths` (#7752): `admitPaths` (shared with `commitPaths`: source roots, `--base`, pre-staged files), the real staging (`stagePaths`) as `git add -n` against a copy of the index, and a staged rename's partner, so each refusal carries the real run's code and text, with no lock and no write. A not_staged path that is a hand-staged `git rm --cached` names `--untrack` in the `commit_paths_skipped` fix. Tests: `test/git-writer-safety-7381.serial.test.ts`, `test/git-literal-pathspec-hooks-7759.test.ts`, `test/git-commit-push-not-a-source-8662.test.ts`, `test/git-commit-push-skipped-paths-gst2116.test.ts`, `test/git-commit-push-untrack-gst2519.test.ts`, `test/git-commit-push-door-wave2.test.ts`.- `src/core/git/range-secret-scan.ts` — `scanRange(root, from, to, timeoutMs, progress)`, the secret gate for every push gbrain makes: `gbrain git commit-push` in every mode, `--untrack` included where it pushes (the CLI always sets `scanSecrets`; the post-commit hook, `scripts/brain-commit-push.sh` and the child `gbrain sources refresh` runs all go through it) scans `trackingRef..target` under the publish lock, right before a push that never follows tags or recurses into submodules (`--no-follow-tags --recurse-submodules=no`, on the `sources push` and `bootstrap repo` pushes too). Plumbing only (`rev-list`, then `cat-file --batch` and `diff-tree --stdin -p --root --cc` over batches of 256 commits, so the temporary patch file stays one batch in size), so log, diff and attribute settings never change what is scanned. The budget is 300 s unless `--scan-timeout` sets it; `progress` gets `secret scan:` lines (at once for a whole history, then every 10 s), and with `retryArgv` a timed-out scan refuses `publish_scan_unreadable` whose agent fix is that command with `--scan-timeout` four times longer (at least 1200 s). Commit messages, added lines and merge resolutions go through `scanText` with the `.gbrain-scan-allow` allowlist; a finding, added text over the scan cap or a change to `.gbrain-scan-allow`/`.gitattributes` refuses `publish_secret_found` (file, line, rule, commit, never the value), and a range it cannot read in full (git failure, unrecognised output, 300 s budget) refuses `publish_scan_unreadable`. Commits the commit ledger records as page writes are not scanned: door and hosted-repository commits, and Git effect commits recorded `verified` (`effectCommit` in `effect-git.ts` builds the commit with `commit-tree` and moves HEAD with an `update-ref` compare-and-swap, so the recorded sha is gbrain's own; `verified` when each staged blob is the bytes whose sha256 the effect recorded); adopted records, records without `verified` and an unreadable ledger leave the commits scanned. Doctor `git_convergence`'s agent push fixes pass `--scan-secrets` too. `stagedScanPublishRefusal(root, base, target, opts)` is the same refusal for `gbrain sources push` (`workspace-push.ts`: origin's tip read from origin itself with `ls-remote` and a fetch, since the pull may follow another upstream remote, then `<tip>..HEAD` scanned and that exact sha pushed leased on the tip, no push when the local branch lacks the tip; a refusal is the `blocked_history` result, exit 5, printed by `--json` too) and both first pushes of `gbrain bootstrap repo` (`bootstrap/repo.ts`, the whole history; `scanHistory` is the runner-fake seam), with gate changes exempt in commits the ledger records as `workspace_push` or `bootstrap`, whose blobs those writers scanned staged with the same allowlist. The access-policy commit (`access/policy-git.ts`, which reports a scan refusal as `committed_not_pushed` with the refusal in its note) and the durability-scaffolding commit (`brain-repo-durability.ts`) publish through `commitAndPush` with `scanSecrets` (#8902). The helper's no-gbrain fallback commits and never pushes. `gbrain git scan` (`runScan` in `src/commands/git.ts`) runs `scanRange` and `rangeSecretRefusal` over `--from..--to` (default `@{upstream}..HEAD`) and writes nothing: the read-only preview of what a push would refuse, with each finding's fingerprint. Tests: `test/unmanaged-push-history-scan-8902.serial.test.ts`, `test/unmanaged-push-every-site-gst2456.serial.test.ts`.- `src/commands/doctor/checks/git-writer.ts` — `checkout_lagging`, `dirty_age`, `commits_outside_source_root`, `quarantined_changes` (#7381, brain category, after `git_convergence`): over the unmanaged source checkouts with an upstream (`sourceRoots` from git-convergence, grouped by toplevel with each source's toplevel-relative root), never fetching, every git call bounded at 5 s. Lagging warns when `HEAD..@{u}` holds a commit over an hour old (fix: `gbrain git commit-push --pull --path <top>`, agent). Dirty age warns on pending write-through files older than 30 minutes (`pendingWriteThroughStillDirty`; fix: `commit-push --pending`, agent) and on files staged that long (ask_user: unstage or commit by name). Outside-root warns on unpushed non-merge commits that change files outside the DB source roots plus `gbrain.sourceRoot` (`localCommitsOutsideRoots`; ask_user fix with `--allow-outside-source-root`), and says when the checkout has no root recorded. Test: `test/doctor-git-writer-7381.test.ts`.- `src/core/git/commit-ledger.ts` — the commit ledger (PR B, docs/designs/REFRESH_WRITE_BARRIER.md part 3): `<git common dir>/gbrain/commit-ledger.jsonl`, one O_APPEND JSON line under 1 KiB per record, under its own flock `commit-ledger.lock` (start line, append, 4 MiB rotation to `commit-ledger.1.jsonl`). `recordCommit`/`recordCommitAsync` take the sha and writer kind (`commit_push`, `door`, `merge`, `replay`, `effect`, `sync_init`, `workspace_push`, `bootstrap`, `hosted_repo`); porcelain sites call `recordIntent` (head_before, `messageDigest` of the message) before `git commit`, plumbing sites record the `commit-tree` sha before the ref moves. A failed append never fails the commit (logged once); a directory outside git records nothing. `readLedger` reads both files; only a missing file reads as empty, any other read error throws (GST-1623). Tests: `test/commit-ledger.test.ts`.diff --git a/docs/designs/GIT_CANONICAL_MEMORY.md b/docs/designs/GIT_CANONICAL_MEMORY.mdindex 8c384abaf2..7c4a9c0318 100644--- a/docs/designs/GIT_CANONICAL_MEMORY.md+++ b/docs/designs/GIT_CANONICAL_MEMORY.md@@ -43,7 +43,7 @@ Some content deliberately has no file. In strict mode each such class is declare| Class | Handling ||---|---|| Private, alias-private and lineage-private pages | Never committed. Making a page private is a door commit that removes its file, and the row stays database-only; making it public writes the file through the door. Content pushed before it became private stays in git history. Conversion withholds a private page whose committed file differs from it; one whose committed file still equals it keeps that file in HEAD, as before the conversion (see Conversion). |-| `storage.db_only` prefixes and the derive-phase folders (`DERIVE_PHASE_DB_ONLY_DEFAULTS`, `src/core/storage-config.ts:425`) | The door refuses to commit under them and the indexer ignores them. |+| `storage.db_only` prefixes and the derive-phase folders (`DERIVE_PHASE_DB_ONLY_DEFAULTS`, `src/core/storage-config.ts:425`) | The door refuses to commit under them and the indexer ignores them. Extract receipts (`extracts/`) are bookkeeping, never content, on every brain with or without a repository: the writer refuses a slug that holds content or a file, and seals the receipt in the transaction that writes it, so it is never exported to Git, never adopted or discarded by conversion, and never counted as database ahead of Git. || Paths the checkout's Git ignores (for example archived images) | Never committed and never given a Git effect, so they cannot park. || Database-only sources (no checkout, `sync.write_through=false`, unbound) | Outside strict mode; the whole source is the class. || Derived data (chunks, embeddings, mention links, rows parsed from fences and timelines, receipts) | Rebuilt from git or kept as metadata; never content of record. |diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.mdindex 8d6a62a3d7..7522623a64 100644--- a/docs/guides/error-codes.md+++ b/docs/guides/error-codes.md@@ -714,6 +714,14 @@ More: [docs/guides/troubleshooting.md#embedding-state](../../docs/guides/troubleMore: [docs/guides/google-connect.md#troubleshooting](../../docs/guides/google-connect.md#troubleshooting)+### client_behind++<a id="client_behind"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| Schema setup (initSchema, which gbrain init, init --migrate-only and upgrade run, and apply-migrations before its orchestrators) refused because the brain's schema version is newer than this gbrain binary's newest migration; nothing in its schema ran and nothing changed. | initSchema replays the binary's whole schema, CREATE OR REPLACE FUNCTION included, before it runs migrations. An older binary sharing the database with a newer one (another host, a lagging cron running apply-migrations or upgrade) used to reinstall its own superseded function bodies, the writer-fence guards among them, over the newer ones and then apply nothing (#7776). Reads do not run schema setup and keep working on the older binary; doctor schema_function_bodies names bodies an older replay already reverted. | Upgrade gbrain on this host (gbrain upgrade) to the release that migrated the database or newer, then rerun the command. Run: gbrain doctor --only schema_version --json | host_admin | `gbrain doctor --json` | 1 | no |+### client_json_unreadable<a id="client_json_unreadable"></a>diff --git a/docs/guides/memory-boundaries.md b/docs/guides/memory-boundaries.mdindex 0fc053529e..63e3e634f5 100644--- a/docs/guides/memory-boundaries.md+++ b/docs/guides/memory-boundaries.md@@ -423,7 +423,7 @@ mention after the real fence. Pinned by `test/fence-marker-code-context.test.ts`("remote privacy boundary" and "remote page replacement").Markdown export is a portable view of pages, **not a full database backup**.-DB-only facts and pages, revision history, the belief ledger (what the brain+DB-only facts and pages (extract receipts included), revision history, the belief ledger (what the brainhad recorded, and when; `gbrain beliefs`), withdrawal state, jobs, settings,and authentication records may not be recoverable from Markdown. Use the engine'sfull backup/restore path and verify a restore into a separate location. Treatdiff --git a/docs/guides/shared-checkout-git.md b/docs/guides/shared-checkout-git.mdindex a234ff9973..9a76e1db30 100644--- a/docs/guides/shared-checkout-git.md+++ b/docs/guides/shared-checkout-git.md@@ -110,7 +110,8 @@ gbrain git commit-push --pending# Stop tracking files and keep them on disk (see "Untrack" below)gbrain git commit-push --untrack -m "stop tracking the archive" -- archive-example-# Preview: prints the paths, branch and lock it would use; takes no lock, writes nothing+# Preview: runs the real run's path checks (a path outside the source root, a sparse-checkout+# exclusion and the rest refuse here too), prints the paths, branch and lock it would use; takes no lock, writes nothinggbrain git commit-push --dry-run -m "people: add alice-example" -- people/alice-example.md```@@ -211,7 +212,7 @@ Follow the error's `fix.next` as the| `pushed_checkout_lagging` | 0 | The push landed but this checkout was not advanced; a `[gbrain notice]` names the files that blocked it. Change nothing: the next commit-push or `--pull` catches the checkout up. Never stash or reset to "fix" it. || `commit_lock_busy` | 1 | Another writer held the lock for the whole wait; nothing was committed. Retry once. If it is still busy, tell the user which checkout and lock path the message names and stop. || <a id="checkout_not_a_source"></a>`checkout_not_a_source` | 1 | The checkout commit-push resolved from the working directory (no `--path`) is not one of the brain's source checkouts on this host, typically a wrapper that changed into another repository; nothing was staged. The message lists the brain's checkouts. Tell the user to make the script pass `--path` with the absolute brain checkout. A repository that only encloses a source checkout (a brain cloned inside another repository) is not one; a source registered at a subdirectory its checkout tracks is. A host whose brain records no source checkout, or a checkout with `gbrain.sourceRoot` set, is never refused this way. |-| `commit_paths_invalid` | 1 | No paths, a path outside the checkout, the checkout root itself, or a path git would not stage. Name the explicit files you wrote and rerun. |+| `commit_paths_invalid` | 1 | No paths, a path outside the checkout, the checkout root itself, or a path git would not stage (one outside a sparse-checkout definition included). Name the explicit files you wrote and rerun. || <a id="commit_paths_skipped"></a>`commit_paths_skipped` | 1 | Git left a named path out of the commit: a modified file flagged assume-unchanged or skip-worktree (`reason` `assume_unchanged`, `skip_worktree`) or a file inside a nested Git repository (`not_staged`). The other named paths were committed (and, on a classic checkout, pushed); `detail` lists each skipped path, the commit and the pushed head, or the push failure (`publish`) when the push failed too. Check the flags with `git ls-files -v -- <path>`; clear them only after the user agrees, one flag per call (`git update-index --no-assume-unchanged -- <path>`, `git update-index --no-skip-worktree -- <path>`; given both, git clears only the first), and remember skip-worktree is often set on purpose to keep local edits out of commits, or move the file out of the nested repository, then rerun. A skip-worktree file absent from disk (a sparse checkout), a flagged gitlink and ignored files under a named directory are not reported. || `commit_prestaged_paths` | 1 | Another writer staged files under a directory you named; nothing was staged or committed. Name your own files explicitly. Unstage the others (`git restore --staged -- <file>`, which keeps their bytes) only after the user agrees. || `commit_outside_source_root` | 1 | The commit, or a local commit about to be published, changes files outside the brain's [source root](#source-roots); nothing was pushed. Show the user `git show --stat <sha>`; rerun with `--allow-outside-source-root` only if they want it published. |diff --git a/scripts/structural-suites.tsv b/scripts/structural-suites.tsvindex 3c321d6b43..c9ecb72305 100644--- a/scripts/structural-suites.tsv+++ b/scripts/structural-suites.tsv@@ -207,6 +207,7 @@ test/fts-cjk-boundary.test.ts one copy of the DDL 2 readFileSynctest/gbrain-owned-page-types.test.ts #5881 gbrain-owned page types are declared by gbrain-base-v2 3 readFileSynctest/get-page-federated-scope.test.ts #2555 get_chunks federated scope 5 source-surface-helpertest/get-page-federated-scope.test.ts #4275 alias hop scope: archived sources, include_deleted, fuzzy precedence, grant precedence 5 source-surface-helper+test/git-env-guard.test.ts (file-level) 5 readFileSynctest/grant-execution-prerequisites.test.ts execution prerequisite table 1 readFileSynctest/harness-onboarding.test.ts harness identity and private handoff 6 readFileSynctest/hook-command.serial.test.ts user-prompt 18 source-surface-helperdiff --git a/src/commands/apply-migrations-schema.ts b/src/commands/apply-migrations-schema.tsindex 68fa9be2b7..8e3c34ef74 100644--- a/src/commands/apply-migrations-schema.ts+++ b/src/commands/apply-migrations-schema.ts@@ -69,6 +69,36 @@ async function pendingAbove(version: number | null): Promise<{ latest: number; preturn { latest: LATEST_VERSION, pending };}+/**+ * #7776: `client_behind` when the brain's schema is newer than this binary, so an older binary runs no orchestrator (or+ * its schema replay) there. Postgres reuses the pre-flight's version; PGLite is read here, before any orchestrator opens+ * the datastore. An unreadable PGLite datastore is left to the orchestrators, as before.+ */+export async function schemaAheadRefusal(cfg: GBrainConfig, preflightVersion: number | null): Promise<OperationError | null> {+ let version = preflightVersion;+ if (version === null && cfg.engine === 'pglite' && cfg.database_path && existsSync(cfg.database_path)) {+ try {+ const { engine, close } = await connectMigrationEngine(cfg);+ try { version = parseInt(await engine.getConfig('version') || '0', 10); } finally { await close(); }+ } catch { return null; }+ }+ const { clientBehindError } = await import('../core/schema-client-behind.ts');+ const { latest } = await pendingAbove(null);+ return version !== null && version > latest ? clientBehindError(version) : null;+}++/**+ * #7776: the connection for `--force-schema` / `--force-all`, whose runMigrations pass (under the lease) runs drift+ * repairs that would rewrite a newer schema's objects. `behind` is client_behind, with the engine already closed, when+ * the schema is newer than this binary, so the forced run refuses as the pre-flight does.+ */+export async function connectForForcedSchema(cfg: GBrainConfig): Promise<{ engine: BrainEngine; version: number; behind: OperationError | null }> {+ const conn = await connectAtSchemaVersion(cfg);+ const behind = await schemaAheadRefusal(cfg, conn.version);+ if (behind) await conn.engine.disconnect();+ return { ...conn, behind };+}+/** The pre-flight's finding when it saw the schema behind and did not bring it to head. */export async function schemaBehindAtPreflight(version: number, authorized: boolean, timeout?: MigrationTimeoutRecord): Promise<SchemaPending> {return { reason: authorized ? 'still_behind' : 'not_applied', current: version, ...(await pendingAbove(version)), ...(authorized && timeout ? { timeout } : {}) };diff --git a/src/commands/apply-migrations.ts b/src/commands/apply-migrations.tsindex 5fdc386e58..866d27d6ce 100644--- a/src/commands/apply-migrations.ts+++ b/src/commands/apply-migrations.ts@@ -48,8 +48,10 @@ import { exitCliError, usageError, writeCliError } from '../cli/cli-error.ts';import {checkSchemaAfterOrchestrators,connectAtSchemaVersion,+ connectForForcedSchema,redactDbError,reportDatabaseUnreachable,+ schemaAheadRefusal,schemaBehindAtPreflight,schemaPendingError,type SchemaPending,@@ -696,7 +698,8 @@ async function runLockedMigrations(fail('failed', opError('no_brain', 'No brain configured for --force-schema.', 'Create a brain first: `gbrain init` (`gbrain init --help` lists the options).'));return 2;}- const { engine: eng, version } = await connectAtSchemaVersion(cfg);+ const { engine: eng, version, behind } = await connectForForcedSchema(cfg);+ if (behind) { fail('refused', behind); return 1; }console.log('Running schema migrations from current config.version...');const result = await migrateSchema(eng, version);console.log(`Applied ${result.applied} schema migration(s); now at v${result.current}.`);@@ -708,8 +711,7 @@ async function runLockedMigrations('Fix the database error above, then run `gbrain apply-migrations --force-schema` again.', { reason: 'schema_failed' }));return 1;}- if (cli.forceSchema && !cli.forceAll) return;- if (cli.forceAll) return; // both surfaces flushed+ return; // --force-schema alone, or --force-all with both surfaces flushed}// Pre-flight: schema drift (#1530) and the DB probe (#4364); see preflightSchema.@@ -1016,6 +1018,9 @@ async function preflightSchema(access: classifyPgAccessError(err, { url: cfg?.database_url ?? null }).reason,};}+ // #7776: an older binary runs no orchestrator (or its schema replay) on a database a newer gbrain migrated.+ const behind = cfg && !cli.list && !cli.dryRun ? await schemaAheadRefusal(cfg, dbProbe.status === 'connected' ? dbProbe.schemaVer : null) : null;+ if (behind) throw behind;return { schemaBehind, dbProbe, schemaTimeout };}diff --git a/src/commands/doctor/checks/schema-function-bodies.ts b/src/commands/doctor/checks/schema-function-bodies.tsnew file mode 100644index 0000000000..fba8d1a6f3--- /dev/null+++ b/src/commands/doctor/checks/schema-function-bodies.ts@@ -0,0 +1,73 @@+/**+ * schema_function_bodies doctor check (#7776): every function this gbrain's schema defines has this gbrain's body.+ *+ * initSchema replays the schema with CREATE OR REPLACE FUNCTION, so an older gbrain sharing the database reinstalled its+ * superseded bodies over a newer schema (among them the writer-fence guards that v197, v272 and v278 replace). A current+ * binary refuses that replay (client_behind), but bodies an older one already reverted stay until the next replay of a+ * current schema. The expected bodies are the ones this binary's schema installs, which a fresh install also ends at+ * (pinned on both engines by test/doctor-schema-function-bodies.test.ts and the #7776 e2e file), so the set is derived+ * from the schema, never hand-listed. Checked only at head: below it pending migrations differ legitimately, above it+ * the newer gbrain's bodies are the right ones. FTS configuration literals are ignored (GBRAIN_FTS_LANGUAGE stamps+ * them; fts_reindex covers that). Read-only.+ */++import type { BrainEngine } from '../../../core/engine.ts';+import type { Check } from '../../doctor.ts';+import { LATEST_VERSION } from '../../../core/migrate.ts';+import { agentFix, checkError } from '../check-fix.ts';+import { connectedEngine, type DoctorContext, type DoctorEntry } from '../context.ts';++export type FunctionBodyDrift = { status: 'checked'; checked: number; differing: string[] }+ | { status: 'skipped'; reason: 'client_behind' | 'migrations_pending'; version: number; latest: number };++const FUNCTION_DEFINITION = /CREATE\s+(?:OR\s+REPLACE\s+)?FUNCTION\s+(?:public\.)?([a-z_][a-z0-9_]*)\s*\([\s\S]*?\bAS\s+(\$[a-z_]*\$)([\s\S]*?)\2/gi;+const normalize = (body: string) => body.replace(/to_tsvector\('[a-z][a-z0-9_]*'/g, "to_tsvector('?'").replace(/\s+/g, ' ').trim();++/** Which functions of this binary's schema have another body installed (or none); skipped off head. */+export async function schemaFunctionBodyDrift(engine: BrainEngine): Promise<FunctionBodyDrift> {+ const version = parseInt((await engine.getConfig('version')) || '0', 10);+ if (version !== LATEST_VERSION) return { status: 'skipped', reason: version > LATEST_VERSION ? 'client_behind' : 'migrations_pending', version, latest: LATEST_VERSION };+ const schema = engine.kind === 'postgres'+ ? (await import('../../../core/schema-embedded.generated.ts')).SCHEMA_SQL+ : (await import('../../../core/pglite-schema.generated.ts')).PGLITE_SCHEMA_SQL_TEMPLATE;+ const expected = new Map([...schema.matchAll(FUNCTION_DEFINITION)].map(m => [m[1]!, normalize(m[3]!)]));+ const rows = await engine.executeRaw<{ proname: string; prosrc: string }>(+ `SELECT p.proname, p.prosrc FROM pg_proc p JOIN pg_namespace n ON n.oid = p.pronamespace+ WHERE n.nspname = 'public' AND p.proname = ANY($1::text[])`, [[...expected.keys()]]);+ const differing = [...expected].filter(([name, body]) => {+ const installed = rows.filter(r => r.proname === name);+ return installed.length === 0 || installed.some(r => normalize(r.prosrc) !== body);+ }).map(([name]) => name).sort();+ return { status: 'checked', checked: expected.size, differing };+}++async function runSchemaFunctionBodies(ctx: DoctorContext): Promise<Check[]> {+ const engine = connectedEngine(ctx);+ const checks: Check[] = [];+ ctx.progress.heartbeat('schema_function_bodies');+ try {+ const drift = await schemaFunctionBodyDrift(engine);+ if (drift.status === 'skipped') {+ checks.push({ name: 'schema_function_bodies', status: 'ok', message: drift.reason === 'client_behind'+ ? `Skipped: the brain schema is v${drift.version}, newer than this client (v${drift.latest}); upgrade gbrain to check it.`+ : `Skipped: the brain schema is v${drift.version} with migrations to v${drift.latest} pending (schema_version covers it).` });+ } else if (drift.differing.length === 0) {+ checks.push({ name: 'schema_function_bodies', status: 'ok', message: `Every function this gbrain's schema defines has its body` });+ } else {+ checks.push({+ name: 'schema_function_bodies',+ status: 'fail',+ message: `${drift.differing.length} function(s) have a body other than this gbrain's schema installs (${drift.differing.join(', ')}), so an older body, `+ + `most likely replayed by an older gbrain sharing this database (#7776), is in force. Upgrade every gbrain that uses this database, then run gbrain init --migrate-only to reinstall this version's bodies.`,+ details: { differing: drift.differing, checked: drift.checked },+ fix: agentFix(['gbrain', 'init', '--migrate-only'], "Replays this gbrain's schema, which reinstalls its function bodies and changes no rows. Upgrade older gbrain processes on this database first, or their next schema setup reverts the bodies again.",+ 'schema_function_bodies', { requires_exclusive: true }),+ });+ }+ } catch (e) {+ checks.push(checkError('schema_function_bodies', 'compare schema function bodies', e));+ }+ return checks;+}++export const schemaFunctionBodiesEntry: DoctorEntry = { name: 'schema_function_bodies', emits: ['schema_function_bodies'], run: runSchemaFunctionBodies };diff --git a/src/commands/doctor/registry.ts b/src/commands/doctor/registry.tsindex caa61be819..e0e62f4604 100644--- a/src/commands/doctor/registry.ts+++ b/src/commands/doctor/registry.ts@@ -44,6 +44,7 @@ import { ipcSocketPathEntry } from './checks/local-ipc.ts';import { functionSearchPathEntry } from './checks/function-search-path.ts';import { postgresTlsEntry } from './checks/postgres-tls.ts';import { databaseEncodingEntry } from './checks/database-encoding.ts';+import { schemaFunctionBodiesEntry } from './checks/schema-function-bodies.ts';import {pgvectorEntry,rlsEntry,@@ -240,6 +241,7 @@ export const DOCTOR_CHECK_REGISTRY: readonly DoctorEntry[] = [functionSearchPathEntry,databaseEncodingEntry,schemaVersionEntry,+ schemaFunctionBodiesEntry,rlsEventTriggerEntry,embeddingsEntry,embeddingProviderEntry,diff --git a/src/commands/frontmatter.ts b/src/commands/frontmatter.tsindex 09aecd7731..fcfa9c7e60 100644--- a/src/commands/frontmatter.ts+++ b/src/commands/frontmatter.ts@@ -43,6 +43,7 @@ import {type AuditFix,} from '../core/brain-writer.ts';import { collectGitVisibleFiles } from '../core/git-visible-files.ts';+import { literalPathspecs } from '../core/git-env.ts';import { isMarkdownFilePath, pruneDir, slugifyPath } from '../core/sync.ts';import { isPathContained } from '../core/path-confine.ts';@@ -282,13 +283,13 @@ function findBrainRoot(start: string): string {*/function readStagedBlobs(paths: string[], cwd = process.cwd()): { root: string; files: Array<{ rel: string; content: string | null }> } {const git = (args: string[], input?: string): Buffer =>- execFileSync('git', ['--literal-pathspecs', ...args], { cwd, input, maxBuffer: 1 << 30, env: process.env, stdio: ['pipe', 'pipe', 'pipe'] });+ execFileSync('git', args, { cwd, input, maxBuffer: 1 << 30, env: process.env, stdio: ['pipe', 'pipe', 'pipe'] });const root = git(['rev-parse', '--show-toplevel']).toString('utf8').trim();const listed = paths.length > 0- ? git(['ls-files', '--stage', '--full-name', '-z', '--', ...paths])+ ? git(['ls-files', '--stage', '--full-name', '-z', '--', ...literalPathspecs(paths)]): (() => {const names = git(['-C', root, 'diff', '--cached', '--name-only', '-z', '--diff-filter=ACM']).toString('utf8').split('\0').filter(isMarkdownFilePath);- return names.length > 0 ? git(['-C', root, 'ls-files', '--stage', '-z', '--', ...names]) : Buffer.alloc(0);+ return names.length > 0 ? git(['-C', root, 'ls-files', '--stage', '-z', '--', ...literalPathspecs(names)]) : Buffer.alloc(0);})();const entries = listed.toString('utf8').split('\0').filter(Boolean).map(record => /^\d+ ([0-9a-f]+) (\d)\t(.*)$/s.exec(record))diff --git a/src/commands/git.ts b/src/commands/git.tsindex 9e82f134d8..1a185a9196 100644--- a/src/commands/git.ts+++ b/src/commands/git.ts@@ -15,7 +15,7 @@*/import { existsSync, realpathSync } from 'node:fs';import { isAbsolute, join, relative, sep } from 'node:path';-import { commitAndPush, checkoutRoot, previewUntrack, pullShared, scopePaths, COMMIT_LOCK_NAME, SOURCE_ROOT_CONFIG, type Resolution } from '../core/git/commit-push.ts';+import { commitAndPush, checkoutRoot, previewPaths, previewUntrack, pullShared, scopePaths, COMMIT_LOCK_NAME, SOURCE_ROOT_CONFIG, type Resolution } from '../core/git/commit-push.ts';import { guardStatus, installGuard, uninstallGuard } from '../core/git/commit-guard.ts';import { appendPushLog } from '../core/brain-repo-durability.ts';import { opError } from '../core/ops/contract.ts';@@ -78,7 +78,8 @@ Flags:.gitignore ignores; it commits there and never pushes.--dry-run Print the paths, branch and lock that would be used, and the marker that makes thecheckout a managed canonical worktree (or none); take no lock, write nothing.- With --untrack, the real run's path checks run first and refuse as it would.+ The real run's path checks run first and refuse as it would (a path outside the+ source root or a sparse-checkout definition, a moved --base, another writer's file).--json One JSON result (or the error envelope) on stdout.Paths are relative to --path when it is given (like git -C), else to the current@@ -268,6 +269,7 @@ export async function runGit(args: string[]): Promise<number> {const paths = p.pull || p.pushOnly || !p.paths.length ? [] : scopePaths(repo, p.paths, cwd);const managed = managedFilesystemRootFor(repo);const untracked = p.untrack && paths.length ? previewUntrack(repo, paths, { allowOutsideSourceRoot: p.allowOutside }) : undefined;+ if (!p.untrack && paths.length) previewPaths(repo, paths, { allowOutsideSourceRoot: p.allowOutside, bases, cwd });emit(json, { dry_run: true, repo, branch, lock, paths, mode: p.pull ? 'pull' : p.pushOnly ? 'push-only' : p.untrack ? 'untrack' : 'commit-push', managed, ...(untracked ? { untracked } : {}) },`dry run: ${p.pull ? 'pull' : p.pushOnly ? 'push-only' : `${p.untrack ? 'untrack' : 'commit'} ${paths.join(' ')}`} on ${branch} in ${repo} (lock ${lock}); ${managed ? `managed canonical worktree (${managed.evidence})` : 'not a managed worktree'}; nothing written`);return 0;diff --git a/src/commands/init.ts b/src/commands/init.tsindex 3a5a1db584..77dd4d067f 100644--- a/src/commands/init.ts+++ b/src/commands/init.ts@@ -861,7 +861,7 @@ async function initMigrateOnly(opts: { jsonOutput: boolean }) {}} catch (e) {// Preserve the CLI's shared retryable busy envelope for migration callers.- if (e instanceof PgliteBusyError) throw e;+ if (e instanceof PgliteBusyError || (e as { code?: unknown }).code === 'client_behind') throw e;const isNoConfig = e instanceof MigrateOnlyError && e.message.startsWith('No brain configured');const msg = e instanceof Error ? e.message : String(e);if (opts.jsonOutput) process.exit(initJsonError({ status: 'error', reason: isNoConfig ? 'no_config' : 'migrate_failed', message: msg },diff --git a/src/commands/pages-status.ts b/src/commands/pages-status.tsindex 03f63e286d..bbbb0a3721 100644--- a/src/commands/pages-status.ts+++ b/src/commands/pages-status.ts@@ -25,6 +25,7 @@ import { quoteIdentifier, resolveActiveEmbeddingColumnFromEngine } from '../coreimport { effectiveBytesBlock } from '../core/import-screen.ts';import { loadSyncEligibility, syncGit } from '../core/persistence/sync-discovery.ts';import { fenceAutoRepairFor, gitHoldFix, readGitHold } from '../core/persistence/sync-holds.ts';+import { literalPathspecs } from '../core/git-env.ts';export const PAGES_STATUS_USAGE = 'Usage: gbrain pages status <slug...> [--source <id>] [--json]';/** Slugs one call reads. */@@ -145,7 +146,7 @@ async function readGitView(engine: BrainEngine, sourceId: string, source: { localet synced: Set<string> | null = null;if (source.last_commit && mapped.length) {try {- const listed = syncGit(gitRoot, ['--literal-pathspecs', 'ls-tree', '-z', '--name-only', source.last_commit, '--', ...mapped.map(m => m.gitPath)]);+ const listed = syncGit(gitRoot, ['ls-tree', '-z', '--name-only', source.last_commit, '--', ...literalPathspecs(mapped.map(m => m.gitPath))]);synced = new Set(listed.split('\0').filter(Boolean));} catch { /* the synced commit is not in this checkout */ }}diff --git a/src/commands/upgrade.ts b/src/commands/upgrade.tsindex 4cf5f4e4d2..b0a335aae0 100644--- a/src/commands/upgrade.ts+++ b/src/commands/upgrade.ts@@ -1092,7 +1092,7 @@ export async function runPostUpgrade(args: string[] = []): Promise<void> {console.warn(`\nSchema auto-apply skipped: ${msg}`);report.schema = 'skipped';report.warnings.push(`schema auto-apply skipped: ${msg}`);- console.warn('Run `gbrain init --migrate-only` manually if your brain is wedged.');+ if ((e as { code?: unknown }).code !== 'client_behind') console.warn('Run `gbrain init --migrate-only` manually if your brain is wedged.');}// v0.25.1: agent-readable advisory listing recommended skills thediff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 590ab065e6..4d347214de 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -1563,6 +1563,11 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;{ since: '0.60.693.0', id: 'member_save_withdrawn_scope_gst2346', text: 'A remote `remember` onto a member\'s own page (`memory/members/<id>`) is refused `fact_withdrawn` only when that member could read what was withdrawn: a fact on its own page, its own copy withdrawn by the brain host, or for the brain owner a fact it reads. A claim withdrawn by the brain host or the owner that the member never read no longer refuses its save: the fact saves as the member\'s own active row with the same reply as a new claim. A schema migration makes the database insert guards mark a row on a member page only by that page\'s own withdrawals; a withdrawal still expires matching rows on member pages when it is made, and strikes them in the page\'s file, so an import of a member page\'s file no longer marks a row withdrawn by a withdrawal of another subject. The same holds for each item of a `remember` batch (`items`), a replay with the same `request_id`, a `replaces` and the write receipt (`get_write_request`). Trusted local saves keep the check they had.' },{ since: '0.60.694.0', id: 'owner_labels_guarded_gst2521', text: 'Labels the owner sets with `gbrain repair visibility` (or its `--readers` setter, or `gbrain repair private-labels`) now raise the page\'s label guard to operator_curated, so a later local agent write at the page\'s own tier that drops or widens them is held like a write over an owner page, with a `lower_page` item. A local write below operator_curated whose `readable_by` would leave the brain owner out of a page the owner reads now publishes with the owner kept in the readers (the rest of the narrowing applies), and its item records the requested readers. Accepting such an item (`gbrain trust confirm tp<id>`) on a page whose own tier is an agent\'s writes only the labels and keeps the agent\'s tier; on an owner page it still endorses the edit at the owner\'s tier. The guard is stored in the database (`page_label_guards`) and set only by label repairs run after the upgrade, so labels set earlier, and a managed Git brain rebuilt from a clone, start unguarded; re-running `gbrain repair visibility --slug` or `--readers` on a page that already has those labels raises the guard without changing them. The owner\'s own label writes, synced owner edits, agent narrowing that keeps the owner, and brains with `access.owner_reads_restricted` on are unchanged.' },{ since: '0.60.694.0', id: 'page_label_widening_held_gst2518', text: 'A local agent write (`put_page`, `capture`, `edit_page`, `append_page`, `revert_version`, `restore_page`) less trusted than a page that drops or widens its `visibility`, `access`, `confidentiality` or `readable_by` now publishes with the page\'s earlier labels kept, in the database and in the committed file, and its receipt lists them under `privacy_labels_kept`; so does a maintenance job\'s derived page publication, and a page whose tier is still `unknown` counts as the owner\'s. A soft delete no longer lowers the page\'s tier. Before, the page became readable to remote callers and other members at once, and only a `lower_page` item waited for the owner. That item now records the requested labels: `gbrain trust confirm tp<id>` applies them if the page has not changed since, `gbrain trust drop tp<id>` keeps the earlier ones, and undoing a confirm restores them while the page is unchanged since. Narrowing writes, label-neutral writes, writers at or above the page\'s tier, synced owner edits and `gbrain repair visibility` are unchanged.' },+ // #7620 extract receipts sealed in their writing transaction. `since` is stamped at the merge slot.+ { since: 'TBD', id: 'extract_receipt_sealed_7620', text: 'An extraction run\'s receipt page (type `extract_receipt`, under `extracts/`) is now chunked and sealed in the transaction that writes it. Remote/MCP `search` and `query` on the extracted source no longer report `safe_index_pending` or `projection_pending` after every extraction, doctor `safe_index_pending` no longer counts new receipts, and remote readers can now find receipts like other generated pages (demoted in ranking). Receipts an earlier release wrote stay unsealed until `gbrain repair safe-chunks --apply`. A receipt is database-only bookkeeping on every brain, with or without a Git repository: when its slug already holds a content page or a page with a file in Git, the receipt is not written (the extraction logs a warning and carries on) instead of overwriting that page.' },+ // GBRA-230 lane G (#7752). `since` is stamped at the merge slot.+ { since: 'TBD', id: 'commit_push_dry_run_checks_paths', text: '`gbrain git commit-push --dry-run` now asks git about the planned paths the way the real run stages them, and runs the real run\'s checks before staging, so it exits 1 with the real run\'s code and text where that run would refuse (`commit_outside_source_root` for a path outside `gbrain.sourceRoot` unless `--allow-outside-source-root` is passed, `commit_prestaged_paths`, and `commit_paths_invalid` for a path outside a sparse-checkout definition or one that matches nothing) instead of exiting 0 and listing it. It still takes no lock and writes nothing.' },+ { since: 'TBD', id: 'schema_client_behind_7776', text: 'A gbrain binary older than the brain\'s schema (the database\'s schema version is above its newest migration because a newer gbrain on another host or install migrated it) now refuses schema setup with `client_behind` and changes nothing: `gbrain init` and `init --migrate-only`, the schema step of `gbrain upgrade`, and `gbrain apply-migrations` (before any orchestrator runs, and before the schema pass of `--force-schema` or `--force-all`; `--list` and `--dry-run` still work). Before, it replayed its own older schema, which reinstalled superseded function bodies (the writer-fence guards among them) over the newer ones, and reported success. Reads and ordinary commands on the older binary are unchanged; the fix is `gbrain upgrade` on that host. A new doctor check, `schema_function_bodies`, fails when a function of this gbrain\'s schema has another body installed (what an older replay leaves behind) and names each one: upgrade every gbrain that shares the database, then run `gbrain init --migrate-only`. PGLite and Postgres alike, with or without a git repo.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/brain-repo-durability.ts b/src/core/brain-repo-durability.tsindex 84f415b0db..6a1cf17e93 100644--- a/src/core/brain-repo-durability.ts+++ b/src/core/brain-repo-durability.ts@@ -352,10 +352,15 @@ case "\${1:-}" in*)_msg="\${1:?usage: brain-commit-push.sh <message> <path> [paths...]}"; shift[ "$#" -gt 0 ] || { echo "refusing a repo-wide commit: pass explicit path(s)" >&2; exit 2; }- git add -A -- "$@"+ _specs=()+ for _p in "$@"; do+ [ -n "$_p" ] || { echo "refusing a repo-wide commit: empty path" >&2; exit 2; }+ _specs+=(":(literal)$_p")+ done+ git add -A -- "\${_specs[@]}"_commit=()_orphans="$(_unindexed "$@")"- for _p in "$@"; do printf '%s\\n' "$_orphans" | grep -xF -- "$_p" >/dev/null || _commit+=("$_p"); done+ for _p in "$@"; do printf '%s\\n' "$_orphans" | grep -xF -- "$_p" >/dev/null || _commit+=(":(literal)$_p"); doneif [ "\${#_commit[@]}" -eq 0 ] || git diff --cached --quiet -- "\${_commit[@]}"; then echo "nothing to commit"; else git commit --only -m "$_msg" -- "\${_commit[@]}"; fi_skipped="$(_unstaged "$@" | sort -u)" ;;esacdiff --git a/src/core/classic-file-holds.ts b/src/core/classic-file-holds.tsindex d3b28bf00f..79f144c993 100644--- a/src/core/classic-file-holds.ts+++ b/src/core/classic-file-holds.ts@@ -17,7 +17,7 @@ import { closeSync, lstatSync, openSync, realpathSync } from 'node:fs';import { join } from 'node:path';import { execFileSync } from './spawn.ts';import type { Action } from './agent-output.ts';-import { gitChildEnv } from './git-env.ts';+import { gitChildEnv, literalPathspecs } from './git-env.ts';import { buildGitInvocation, isWithinRoot } from './sync-git.ts';import type { GitHoldRecord } from './persistence/sync-holds.ts';@@ -49,16 +49,16 @@ function hold(code: ClassicFileHoldCode, reason: ClassicFileHoldReason, relPath:/** Read-only Git plumbing in the source root: optional locks off, literal pathspecs, null on any failure. */function gitRead(root: string, args: string[]): string | null {try {- return execFileSync('git', buildGitInvocation(root, args), { env: gitChildEnv({ GIT_OPTIONAL_LOCKS: '0', GIT_LITERAL_PATHSPECS: '1' }),+ return execFileSync('git', buildGitInvocation(root, args), { env: gitChildEnv({ GIT_OPTIONAL_LOCKS: '0' }),encoding: 'utf-8', timeout: 10_000, stdio: ['ignore', 'pipe', 'ignore'] });} catch { return null; }}/** A committed file missing on disk: skip_worktree when the index marks it so, deleted_locally otherwise; null when HEAD has no blob there. */function absentFromWorktree(root: string, relPath: string): ClassicFileHold | null {- const tree = gitRead(root, ['ls-tree', '-z', 'HEAD', '--', relPath]);+ const tree = gitRead(root, ['ls-tree', '-z', 'HEAD', '--', ...literalPathspecs([relPath])]);if (!tree || !/^(100644|100755|120000) blob /.test(tree)) return null;- const flag = gitRead(root, ['ls-files', '-z', '-v', '--', relPath])?.charAt(0);+ const flag = gitRead(root, ['ls-files', '-z', '-v', '--', ...literalPathspecs([relPath])])?.charAt(0);return hold('absent_from_worktree', flag === 'S' ? 'skip_worktree' : 'deleted_locally', relPath);}diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.tsindex cca0fb7231..f75c16fec6 100644--- a/src/core/cli-flag-registry.generated.ts+++ b/src/core/cli-flag-registry.generated.ts@@ -52,7 +52,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'db-repair': ['--accept-pending', '--apply', '--apply-rewrites', '--as', '--background', '--brain', '--break-lock', '--db-url', '--dry-run', '--explain', '--filter', '--follow', '--force', '--force-retry', '--format', '--help', '--http', '--json', '--legacy-lock', '--locks', '--name', '--no-accept-pending', '--path', '--prefer-postgres', '--probe', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--restart', '--skip-verify', '--source', '--statement-timeout', '--supabase', '--timeout', '--timings', '--undo-last-rewrite', '--url', '--version', '--wait', '--yes'],'decide': ['--accept-all', '--all', '--all-from', '--apply', '--brain', '--call-site', '--claims', '--dataset', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--expect', '--from', '--help', '--include-withdrawals', '--input', '--items-out', '--json', '--kind', '--limit', '--max-cost', '--max-usd', '--min', '--non-interactive', '--out', '--provenance', '--provider', '--query', '--rate', '--reason', '--reason-family', '--recommended', '--remove', '--shadow', '--since', '--slot', '--source', '--status', '--suite', '--target', '--threshold', '--trust', '--undo', '--uri-prefix', '--version', '--what-if-threshold', '--yes'],'diag': ['--access', '--add', '--all', '--allowed-operations', '--apply', '--as', '--asof', '--body', '--bound-slug-prefixes', '--brain', '--budget-ms', '--client', '--count', '--cursor', '--date', '--dated-since', '--days', '--detach', '--entities', '--expect', '--expected-revision', '--federated-read', '--filter', '--follow', '--format', '--from-index', '--full', '--fuzzy', '--group-by', '--held', '--help', '--http', '--id', '--include', '--include-ambiguous', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--no-pull', '--no-walk', '--of', '--only', '--page', '--params', '--path', '--phase', '--prefer', '--preview', '--purge', '--query', '--recent', '--refresh-operations', '--replace', '--restart-only', '--reverse', '--row', '--scopes', '--session', '--side', '--since', '--slug', '--slugs', '--source', '--source-id', '--sources', '--stale', '--state', '--surface', '--to', '--updated-after', '--url', '--yes'],- 'doctor': ['--abandon', '--abbrev-ref', '--abort', '--absolute-git-dir', '--accept-all', '--accept-capabilities', '--accept-pending', '--access', '--access-policy', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt', '--adopt-columns', '--adopt-permissions', '--advertise', '--after', '--agent', '--aggressive', '--aliases', '--all', '--all-drifted', '--all-from', '--allow-old-serve', '--allow-outside-source-root', '--allow-shell-jobs', '--allow-unverified-remote', '--allow-without-owner', '--allowed-operations', '--anchor', '--applied', '--apply', '--apply-rewrites', '--approval-out', '--approved', '--as', '--assign-corpus', '--assume-unchanged', '--attest-actor', '--attest-ops', '--attest-read', '--attest-sources', '--audit', '--auto', '--auto-additive', '--auto-fix', '--autostash', '--background', '--base', '--batch', '--batch-check', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-policy', '--budget-tokens', '--budget-usd', '--bundled', '--by-mention', '--cached', '--cacheinfo', '--call-site', '--catalog', '--catch-up', '--channel', '--check', '--check-downgrade', '--check-only', '--cherry-mark', '--claims', '--class', '--claude-plugins', '--clear', '--clear-never-installed', '--cli-socket', '--client', '--close', '--code', '--concurrency', '--confidence', '--config', '--confirm', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--content-root', '--continue', '--conversation', '--count', '--credentials-file', '--cursor', '--cwd', '--dataset', '--day', '--db-url', '--deadline', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--delete-brain', '--dest', '--detach', '--detail', '--diff-filter', '--dim', '--dimensions', '--dir', '--disable', '--drain', '--drain-timeout', '--dry-run', '--egress', '--email', '--embedding-dimensions', '--embedding-model', '--enable', '--enable-dcr', '--end-of-options', '--entity', '--env', '--env-file', '--error-unmatch', '--exclude', '--exclude-standard', '--exit-code', '--expand', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--filter', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-remove', '--force-retry', '--force-schema', '--force-with-lease', '--format', '--fresh', '--fresh-token', '--from', '--from-json', '--from-meetings', '--from-pages', '--full', '--full-tree', '--fuzzy', '--gbrain-bin', '--generation', '--get', '--get-all', '--get-regexp', '--get-url', '--git-common-dir', '--git-dir', '--git-path', '--grammar', '--group', '--group-by', '--hard', '--hard-deadline', '--harness', '--heads', '--held', '--help', '--hold-state', '--holds', '--home', '--http', '--id', '--if-version', '--ignore-env-override', '--ignore-missing', '--ignore-unmatch', '--images', '--import', '--include-ambiguous', '--include-covered', '--include-cross-entity', '--include-deleted', '--include-failures', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--include-withdrawals', '--index-audit', '--index-info', '--infer-dates', '--init', '--input', '--input-type', '--install', '--instructions', '--instructions-only', '--is-ancestor', '--is-bare-repository', '--is-inside-work-tree', '--is-shallow-repository', '--items-out', '--job-isolation', '--jq', '--json', '--keep', '--keep-checkout', '--key', '--kind', '--label-lowerings', '--lanes', '--lang', '--left-right', '--legacy-lock', '--limit', '--link', '--link-source', '--link-type', '--list', '--list-out', '--literal-pathspecs', '--local', '--local-env-vars', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-count', '--max-facts', '--max-jobs', '--max-requests', '--max-rss', '--max-runtime', '--max-usd', '--max-waiting', '--may-act-for', '--mcp-only', '--member', '--members', '--members-file', '--merge-base', '--migrate-legacy', '--migrate-only', '--migration', '--min', '--min-n', '--mode', '--model', '--multimodal', '--name', '--name-only', '--name-status', '--nice', '--no-accept-pending', '--no-assume-unchanged', '--no-autopilot-install', '--no-autostash', '--no-capture', '--no-commit-id', '--no-confirm', '--no-cron', '--no-delegate', '--no-edit', '--no-embed', '--no-embed-cache', '--no-embedding', '--no-expand', '--no-extract', '--no-federated', '--no-filters', '--no-follow-tags', '--no-gpg-sign', '--no-hooks', '--no-index', '--no-instructions', '--no-lanes', '--no-llm', '--no-merges', '--no-migrate', '--no-optional-locks', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-restart', '--no-schema-pack', '--no-seat', '--no-skip-worktree', '--no-stdio-member', '--no-tags', '--no-verify', '--no-walk', '--no-write-fetch-head', '--non-interactive', '--not', '--now', '--of', '--older-than', '--once', '--only', '--operation', '--operations', '--others', '--out', '--output', '--oversized', '--overwrite', '--page', '--parallel', '--params', '--parents', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--path-format', '--pending', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer', '--prefer-postgres', '--prefix', '--preload', '--preset', '--preview', '--principal', '--private-pages', '--probe', '--probe-pglite', '--profile', '--progress-interval', '--progress-json', '--project', '--provenance', '--provider', '--providers', '--prune-orphans', '--public-url', '--pull', '--pure', '--purge', '--push', '--push-only', '--qm', '--query', '--question', '--queue', '--quiet', '--rate', '--raw-only', '--reader-mode', '--readers', '--reason', '--reauth', '--rebase', '--rebuild', '--recommended', '--recurse-submodules', '--redact-paths', '--reference-date', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--relative', '--relower', '--remediate', '--remediation-plan', '--remote', '--remove', '--remove-core', '--repair', '--repair-unknown-markers', '--replace', '--repo', '--request', '--request-id', '--require', '--require-clean', '--reranker', '--reset', '--reset-checkpoint', '--reset-default', '--reset-session', '--resolve', '--restart-only', '--restore-only', '--resume', '--retire', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--reverse', '--review-lower', '--revision', '--right-only', '--rollback-to-source', '--root', '--routing', '--rules', '--run', '--runtime', '--safe', '--sample', '--save', '--scan-secrets', '--scan-timeout', '--scope', '--scopes', '--search-mode', '--seat', '--section', '--segmented', '--select', '--self-transfer', '--semantic', '--serves', '--session', '--session-id', '--set', '--set-upstream-to', '--shadow', '--shared-skills', '--short', '--show-current', '--show-object-format', '--show-prefix', '--show-token', '--show-toplevel', '--side', '--since', '--since-last-run', '--skill-loading', '--skills-dir', '--skills-index-only', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--skip-worktree', '--slot', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--slugs', '--slugs-file', '--source', '--source-id', '--source-ids', '--sources', '--squash', '--src-subpath', '--staged', '--stale', '--stat', '--state', '--statement-timeout', '--status', '--stdin', '--stdio-member', '--stop-mcp', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--swap-only', '--symbol-kind', '--symbolic-full-name', '--tags', '--take', '--takes-holders', '--target', '--target-score', '--threshold', '--tier', '--timeout', '--timings', '--to', '--token', '--token-ttl', '--top-k', '--topo-order', '--trust', '--tsconfig-override', '--type', '--types', '--unindexed', '--uninstall', '--unsafe-bypass-dream-guard', '--unset', '--unset-all', '--unsettle', '--unshallow', '--untrack', '--untracked-files', '--url', '--url-env', '--user', '--vacuum', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--warn-only', '--watch', '--what-if-threshold', '--where', '--window', '--workers', '--working-tree', '--workspace', '--worktree', '--write-tree', '--yes'],+ 'doctor': ['--abandon', '--abbrev-ref', '--abort', '--absolute-git-dir', '--accept-all', '--accept-capabilities', '--accept-pending', '--access', '--access-policy', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt', '--adopt-columns', '--adopt-permissions', '--advertise', '--after', '--agent', '--aggressive', '--aliases', '--all', '--all-drifted', '--all-from', '--all-sources', '--allow-old-serve', '--allow-outside-source-root', '--allow-shell-jobs', '--allow-unverified-remote', '--allow-without-owner', '--allowed-operations', '--anchor', '--applied', '--apply', '--apply-rewrites', '--approval-out', '--approved', '--as', '--assign-corpus', '--assume-unchanged', '--attest-actor', '--attest-ops', '--attest-read', '--attest-sources', '--audit', '--auto', '--auto-additive', '--auto-fix', '--autostash', '--background', '--base', '--batch', '--batch-check', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-policy', '--budget-tokens', '--budget-usd', '--bundled', '--by-mention', '--cached', '--cacheinfo', '--call-site', '--catalog', '--catch-up', '--channel', '--check', '--check-downgrade', '--check-only', '--cherry-mark', '--claims', '--class', '--claude-plugins', '--clear', '--clear-never-installed', '--cli-socket', '--client', '--close', '--code', '--concurrency', '--confidence', '--config', '--confirm', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--content-root', '--continue', '--conversation', '--count', '--credentials-file', '--cursor', '--cwd', '--dataset', '--day', '--db-url', '--deadline', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--delete-brain', '--dest', '--detach', '--detail', '--diff-filter', '--dim', '--dimensions', '--dir', '--disable', '--drain', '--drain-timeout', '--dry-run', '--egress', '--email', '--embedding-dimensions', '--embedding-model', '--enable', '--enable-dcr', '--end-of-options', '--entity', '--env', '--env-file', '--error-unmatch', '--exclude', '--exclude-standard', '--exit-code', '--expand', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--filter', '--first-parent', '--fix', '--follow', '--force', '--force-all', '--force-break-lock', '--force-rechunk', '--force-remove', '--force-retry', '--force-schema', '--force-with-lease', '--format', '--fresh', '--fresh-token', '--from', '--from-json', '--from-meetings', '--from-pages', '--full', '--full-tree', '--fuzzy', '--gbrain-bin', '--generation', '--get', '--get-all', '--get-regexp', '--get-url', '--git-common-dir', '--git-dir', '--git-path', '--grammar', '--group', '--group-by', '--hard', '--hard-deadline', '--harness', '--heads', '--held', '--help', '--history', '--hold-state', '--holds', '--home', '--http', '--id', '--if-version', '--ignore-env-override', '--ignore-missing', '--ignore-unmatch', '--images', '--import', '--include-ambiguous', '--include-covered', '--include-cross-entity', '--include-deleted', '--include-failures', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--include-withdrawals', '--index-audit', '--index-info', '--infer-dates', '--init', '--input', '--input-type', '--install', '--instructions', '--instructions-only', '--is-ancestor', '--is-bare-repository', '--is-inside-work-tree', '--is-shallow-repository', '--items-out', '--job-isolation', '--jq', '--json', '--keep', '--keep-checkout', '--key', '--kind', '--label-lowerings', '--lanes', '--lang', '--left-right', '--legacy-lock', '--limit', '--link', '--link-source', '--link-type', '--list', '--list-out', '--local', '--local-env-vars', '--locks', '--log-noop', '--manifest', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-count', '--max-facts', '--max-jobs', '--max-requests', '--max-rss', '--max-runtime', '--max-usd', '--max-waiting', '--may-act-for', '--mcp-only', '--member', '--members', '--members-file', '--merge-base', '--migrate-legacy', '--migrate-only', '--migration', '--min', '--min-n', '--mode', '--model', '--multimodal', '--name', '--name-only', '--name-status', '--nice', '--no-accept-pending', '--no-assume-unchanged', '--no-autopilot-install', '--no-autostash', '--no-capture', '--no-commit-id', '--no-confirm', '--no-cron', '--no-delegate', '--no-edit', '--no-embed', '--no-embed-cache', '--no-embedding', '--no-expand', '--no-extract', '--no-federated', '--no-filters', '--no-follow-tags', '--no-gpg-sign', '--no-hooks', '--no-index', '--no-instructions', '--no-lanes', '--no-llm', '--no-merges', '--no-migrate', '--no-optional-locks', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-restart', '--no-schema-pack', '--no-seat', '--no-skip-worktree', '--no-stdio-member', '--no-tags', '--no-verify', '--no-walk', '--no-write-fetch-head', '--non-interactive', '--not', '--now', '--of', '--older-than', '--once', '--only', '--operation', '--operations', '--others', '--out', '--output', '--oversized', '--overwrite', '--page', '--parallel', '--params', '--parents', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--path-format', '--pending', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer', '--prefer-postgres', '--prefix', '--preload', '--preset', '--preview', '--principal', '--priority', '--private-pages', '--probe', '--probe-pglite', '--profile', '--progress-interval', '--progress-json', '--project', '--provenance', '--provider', '--providers', '--prune-orphans', '--public-url', '--pull', '--pure', '--purge', '--push', '--push-only', '--qm', '--query', '--question', '--queue', '--quiet', '--rate', '--raw-only', '--reader-mode', '--readers', '--reason', '--reauth', '--rebase', '--rebuild', '--recommended', '--recurse-submodules', '--redact-paths', '--reference-date', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--relative', '--relower', '--remediate', '--remediation-plan', '--remote', '--remove', '--remove-core', '--repair', '--repair-unknown-markers', '--replace', '--repo', '--request', '--request-id', '--require', '--require-clean', '--reranker', '--reset', '--reset-checkpoint', '--reset-default', '--reset-session', '--resolve', '--restart-only', '--restore-only', '--resume', '--retire', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--reverse', '--review-lower', '--revision', '--right-only', '--rollback-to-source', '--root', '--routing', '--rules', '--run', '--runtime', '--safe', '--sample', '--save', '--scan-secrets', '--scan-timeout', '--scope', '--scopes', '--search-mode', '--seat', '--section', '--segmented', '--select', '--self-transfer', '--semantic', '--serves', '--session', '--session-id', '--set', '--set-upstream-to', '--shadow', '--shared-skills', '--short', '--show-current', '--show-object-format', '--show-prefix', '--show-token', '--show-toplevel', '--side', '--since', '--since-last-run', '--skill-loading', '--skills-dir', '--skills-index-only', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--skip-worktree', '--slot', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--slugs', '--slugs-file', '--source', '--source-id', '--source-ids', '--sources', '--squash', '--src-subpath', '--staged', '--stale', '--stat', '--state', '--statement-timeout', '--status', '--stdin', '--stdio-member', '--stop-mcp', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--swap-only', '--symbol-kind', '--symbolic-full-name', '--tags', '--take', '--takes-holders', '--target', '--target-score', '--threshold', '--tier', '--timeout', '--timings', '--to', '--token', '--token-ttl', '--top-k', '--topo-order', '--trust', '--tsconfig-override', '--type', '--types', '--unindexed', '--uninstall', '--unsafe-bypass-dream-guard', '--unset', '--unset-all', '--unsettle', '--unshallow', '--untrack', '--untracked-files', '--url', '--url-env', '--user', '--vacuum', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--warn-only', '--watch', '--what-if-threshold', '--where', '--window', '--workers', '--working-tree', '--workspace', '--worktree', '--write-tree', '--yes'],'dream': ['--audit-rejects', '--brain', '--cancel-unmatched', '--date', '--dir', '--drain', '--dry-run', '--eval-run', '--force', '--from', '--help', '--input', '--install', '--json', '--limit', '--list', '--max-usd', '--once', '--phase', '--probe', '--pull', '--reconcile-queue', '--since', '--source', '--source-id', '--threshold', '--to', '--unsafe-bypass-dream-guard', '--window', '--yes'],'edge-proposals': ['--access', '--add', '--all', '--all-applied', '--all-held', '--allowed-operations', '--as', '--asof', '--body', '--bound-slug-prefixes', '--brain', '--client', '--cursor', '--date', '--dated-since', '--days', '--entities', '--federated-read', '--follow', '--from-index', '--full', '--fuzzy', '--group-by', '--help', '--http', '--id', '--include', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--of', '--only', '--page', '--params', '--path', '--phase', '--prefer', '--purge', '--recent', '--refresh-operations', '--row', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--status', '--surface', '--to', '--updated-after', '--url', '--yes'],'edges-backfill': ['--all-sources', '--brain', '--concurrency', '--help', '--json', '--max-chunks', '--source', '--workers'],@@ -72,16 +72,16 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'forget': ['--all-subjects', '--brain', '--continue', '--dry-run', '--help', '--json', '--match', '--purge', '--reason', '--reason-scan-limit', '--request-id', '--source', '--status', '--vacuum', '--yes'],'founder': ['--brain', '--help', '--json', '--mcp-only', '--request-id', '--since', '--source', '--until'],'friction': ['--agent', '--base', '--brain', '--compare', '--help', '--hint', '--json', '--kind', '--message', '--no-redact', '--phase', '--run-id', '--severity', '--source', '--transcript-path', '--transcripts'],- 'frontmatter': ['--allow-catch-all', '--batch', '--brain', '--cached', '--diff-filter', '--dry-run', '--exclude-standard', '--fix', '--force', '--full-name', '--get', '--git-common-dir', '--help', '--importable', '--include-ambiguous', '--include-catch-all', '--json', '--literal-pathspecs', '--local', '--name-only', '--no-verify', '--others', '--path', '--show-prefix', '--show-toplevel', '--source', '--stage', '--staged', '--stdin', '--type', '--uninstall'],+ 'frontmatter': ['--allow-catch-all', '--batch', '--brain', '--cached', '--diff-filter', '--dry-run', '--exclude-standard', '--fix', '--force', '--full-name', '--get', '--git-common-dir', '--help', '--importable', '--include-ambiguous', '--include-catch-all', '--json', '--local', '--name-only', '--no-verify', '--others', '--path', '--show-prefix', '--show-toplevel', '--source', '--stage', '--staged', '--stdin', '--type', '--uninstall'],'git': ['--abbrev-ref', '--absolute-git-dir', '--add', '--aggressive', '--all', '--allow-outside-source-root', '--assume-unchanged', '--attr-source', '--autostash', '--base', '--batch', '--batch-check', '--before', '--brain', '--branch', '--cached', '--cacheinfo', '--cc', '--cherry-mark', '--combined', '--count', '--diff-filter', '--dry-run', '--dst-prefix', '--enable', '--end-of-options', '--error-unmatch', '--exclude-standard', '--exit-code', '--expect-remote', '--ff-only', '--file', '--force', '--force-remove', '--force-with-lease', '--format', '--from', '--full-index', '--get', '--get-all', '--get-regexp', '--get-url', '--git', '--git-common-dir', '--git-dir', '--git-path', '--hard', '--help', '--ignore-unmatch', '--index-info', '--install', '--is-ancestor', '--is-inside-work-tree', '--json', '--keep-checkout', '--local', '--local-env-vars', '--max-count', '--merge-base', '--message', '--mode', '--name-only', '--name-status', '--no-assume-unchanged', '--no-autostash', '--no-color', '--no-commit-id', '--no-cron', '--no-ext-diff', '--no-follow-tags', '--no-gpg-sign', '--no-index', '--no-merges', '--no-optional-locks', '--no-recurse-submodules', '--no-renames', '--no-skip-worktree', '--no-tags', '--no-textconv', '--no-verify', '--no-write-fetch-head', '--not', '--only', '--others', '--parents', '--pat-file', '--path', '--path-format', '--pending', '--porcelain', '--pull', '--push', '--push-only', '--quiet', '--rebase', '--recurse-submodules', '--repo', '--request-id', '--require-clean', '--resolve', '--reverse', '--right-only', '--root', '--scan-secrets', '--scan-timeout', '--short', '--show-toplevel', '--skip-worktree', '--source', '--source-id', '--src-prefix', '--staged', '--stat', '--stdin', '--to', '--topo-order', '--type', '--unified', '--uninstall', '--unset', '--unset-all', '--untrack', '--untracked-files', '--verify', '--worktree', '--write-tree'],'google': ['--access', '--account', '--allow-create-db', '--allow-docker', '--brain', '--calendar-id', '--chat-model', '--client-id', '--client-json', '--client-secret', '--code', '--consent-state', '--content-root', '--db-only', '--embedding-dimensions', '--embedding-model', '--expansion-model', '--force', '--git', '--grant-types', '--help', '--history-days', '--http', '--issuer-url', '--json', '--key', '--kind', '--limit', '--local-postgres', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--no-browser', '--no-embed', '--no-embedding', '--no-git', '--no-probe', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--paste', '--path', '--pglite', '--plan', '--port', '--prefer-postgres', '--probe', '--provenance', '--purge-client', '--query', '--reauth', '--retry-failed', '--schema-pack', '--scopes', '--search-mode', '--services', '--skip-embed-check', '--source', '--status', '--supabase', '--surface', '--sync-budget-ms', '--timeout-ms', '--to', '--token-command', '--url', '--version', '--via', '--yes'],'graph-query': ['--brain', '--depth', '--direction', '--help', '--hop', '--include-foreign', '--json', '--mcp-only', '--request-id', '--source', '--type'],'hook': ['--allow-unverified-remote', '--auto', '--batch-check', '--brain', '--branch', '--cached', '--catalog', '--count', '--diff-filter', '--dir', '--enable', '--end-of-options', '--env', '--force-with-lease', '--gbrain-bin', '--get', '--harness', '--heads', '--help', '--instructions', '--instructions-only', '--is-ancestor', '--jq', '--json', '--limit', '--name-only', '--no-follow-tags', '--no-instructions', '--no-tags', '--only', '--others', '--pat-file', '--path', '--porcelain', '--print', '--pure', '--quiet', '--recurse-submodules', '--remove', '--scope', '--seat', '--session', '--show-current', '--show-toplevel', '--since', '--source', '--source-ids', '--verify', '--workspace', '--yes'],- 'import': ['--accept-pending', '--access-policy', '--admin-intent', '--allow-empty', '--allow-noncanonical-root', '--apply', '--as', '--background', '--batch-check', '--brain', '--cached', '--confirm-relocated-root', '--diff-filter', '--dim', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--expected-epoch', '--expected-state', '--explain', '--follow', '--force', '--force-rechunk', '--format', '--fresh', '--help', '--include-gitignored', '--is-shallow-repository', '--json', '--literal-pathspecs', '--log-noop', '--manifest', '--name-only', '--no-accept-pending', '--no-embed', '--no-embedding', '--no-gpg-sign', '--no-pull', '--no-renames', '--no-verify', '--only', '--others', '--path', '--probe', '--progress-interval', '--progress-json', '--quiet', '--self-transfer', '--show-toplevel', '--skip-failed', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--timeout', '--timings', '--to', '--url', '--verify', '--wait', '--workers', '--yes'],- 'init': ['--abandon', '--absolute-git-dir', '--accept-all', '--accept-capabilities', '--access', '--access-policy', '--acknowledge-managed', '--adopt', '--advertise', '--after', '--aliases', '--all', '--all-drifted', '--allow-create-db', '--allow-docker', '--allow-outside-source-root', '--allow-without-owner', '--anchor', '--applied', '--apply', '--approval-out', '--approved', '--as', '--assign-corpus', '--attest-actor', '--attest-ops', '--attest-read', '--attest-sources', '--audit', '--auto', '--auto-additive', '--background', '--base', '--batch', '--bound-slug-prefixes', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-policy', '--budget-tokens', '--budget-usd', '--by-mention', '--cached', '--catch-up', '--channel', '--chat-model', '--check', '--check-downgrade', '--class', '--clear', '--clear-never-installed', '--cli-socket', '--client', '--close', '--code', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--content-root', '--continue', '--conversation', '--cursor', '--db-only', '--deadline', '--decisions', '--dest', '--detach', '--detail', '--dim', '--disable', '--drain', '--email', '--embedding-dimensions', '--embedding-model', '--enable', '--entity', '--exclude', '--expand', '--expansion-model', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--explain', '--facts', '--fast', '--federated', '--file', '--filter', '--first-parent', '--fix', '--force', '--force-retry', '--force-schema', '--format', '--fresh-token', '--from', '--from-meetings', '--from-pages', '--full', '--git', '--grammar', '--grant-types', '--group-by', '--harness', '--held', '--help', '--hold-state', '--holds', '--http', '--id', '--images', '--include-ambiguous', '--include-covered', '--include-cross-entity', '--include-failures', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--infer-dates', '--input', '--install', '--instructions-only', '--issuer-url', '--job-isolation', '--json', '--keep', '--keep-checkout', '--key', '--kind', '--label-lowerings', '--lanes', '--legacy-lock', '--limit', '--link', '--list', '--list-out', '--local', '--local-postgres', '--markdown', '--max-cost-usd', '--max-facts', '--max-requests', '--max-rss', '--max-usd', '--may-act-for', '--mcp-only', '--mcp-url', '--member', '--members', '--members-file', '--migrate-only', '--migration', '--min-n', '--mode', '--model', '--no-autopilot-install', '--no-autostash', '--no-delegate', '--no-embed', '--no-embedding', '--no-expand', '--no-extract', '--no-federated', '--no-filters', '--no-git', '--no-hooks', '--no-instructions', '--no-lanes', '--no-llm', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-restart', '--no-schema-pack', '--no-stdio-member', '--no-verify', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--of', '--older-than', '--once', '--only', '--operation', '--output', '--oversized', '--page', '--params', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--pending', '--pglite', '--phase', '--plan', '--prefer', '--prefer-postgres', '--prefix', '--preview', '--private-pages', '--probe', '--profile', '--provenance', '--providers', '--pull', '--purge', '--push-only', '--qm', '--query', '--question', '--quiet', '--readers', '--reason', '--rebase', '--rebuild', '--redact-paths', '--reference-date', '--remediate', '--remote', '--remove', '--repair', '--repair-unknown-markers', '--repo', '--request', '--request-id', '--require-clean', '--reset', '--resolve', '--restart-only', '--resume', '--retire', '--retry-failed', '--retry-parked', '--runtime', '--safe', '--save', '--scan-secrets', '--scan-timeout', '--schema-pack', '--scope', '--scopes', '--search-mode', '--section', '--segmented', '--self-transfer', '--semantic', '--serves', '--session', '--session-id', '--shared-skills', '--show-toplevel', '--side', '--since', '--since-last-run', '--skip', '--skip-embed-check', '--skip-failed', '--slug', '--slugs', '--slugs-file', '--source', '--source-id', '--sources', '--squash', '--src-subpath', '--stale', '--state', '--status', '--stdin', '--stdio-member', '--stop-mcp', '--strategy', '--supabase', '--surface', '--swap-only', '--take', '--tier', '--timeout', '--to', '--token', '--touchpoint', '--type', '--types', '--uninstall', '--unsettle', '--untrack', '--url', '--url-env', '--user', '--vacuum', '--verbose', '--version', '--wait', '--warn-only', '--watch', '--working-tree', '--workspace', '--yes'],+ 'import': ['--accept-pending', '--access-policy', '--admin-intent', '--allow-empty', '--allow-noncanonical-root', '--apply', '--as', '--background', '--batch-check', '--brain', '--cached', '--confirm-relocated-root', '--diff-filter', '--dim', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--expected-epoch', '--expected-state', '--explain', '--follow', '--force', '--force-rechunk', '--format', '--fresh', '--help', '--include-gitignored', '--is-shallow-repository', '--json', '--log-noop', '--manifest', '--name-only', '--no-accept-pending', '--no-embed', '--no-embedding', '--no-gpg-sign', '--no-pull', '--no-renames', '--no-verify', '--only', '--others', '--path', '--probe', '--progress-interval', '--progress-json', '--quiet', '--self-transfer', '--show-toplevel', '--skip-failed', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--timeout', '--timings', '--to', '--url', '--verify', '--wait', '--workers', '--yes'],+ 'init': ['--abandon', '--absolute-git-dir', '--accept-all', '--accept-capabilities', '--access', '--access-policy', '--acknowledge-managed', '--adopt', '--advertise', '--after', '--aliases', '--all', '--all-drifted', '--allow-create-db', '--allow-docker', '--allow-outside-source-root', '--allow-without-owner', '--anchor', '--applied', '--apply', '--approval-out', '--approved', '--as', '--assign-corpus', '--attest-actor', '--attest-ops', '--attest-read', '--attest-sources', '--audit', '--auto', '--auto-additive', '--background', '--base', '--batch', '--bound-slug-prefixes', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-policy', '--budget-tokens', '--budget-usd', '--by-mention', '--cached', '--catch-up', '--channel', '--chat-model', '--check', '--check-downgrade', '--class', '--clear', '--clear-never-installed', '--cli-socket', '--client', '--close', '--code', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--content-root', '--continue', '--conversation', '--cursor', '--db-only', '--deadline', '--decisions', '--dest', '--detach', '--detail', '--dim', '--disable', '--drain', '--email', '--embedding-dimensions', '--embedding-model', '--enable', '--entity', '--exclude', '--expand', '--expansion-model', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--explain', '--facts', '--fast', '--federated', '--file', '--filter', '--first-parent', '--fix', '--force', '--force-all', '--force-retry', '--force-schema', '--format', '--fresh-token', '--from', '--from-meetings', '--from-pages', '--full', '--git', '--grammar', '--grant-types', '--group-by', '--harness', '--held', '--help', '--hold-state', '--holds', '--http', '--id', '--images', '--include-ambiguous', '--include-covered', '--include-cross-entity', '--include-failures', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--infer-dates', '--input', '--install', '--instructions-only', '--issuer-url', '--job-isolation', '--json', '--keep', '--keep-checkout', '--key', '--kind', '--label-lowerings', '--lanes', '--legacy-lock', '--limit', '--link', '--list', '--list-out', '--local', '--local-postgres', '--markdown', '--max-cost-usd', '--max-facts', '--max-requests', '--max-rss', '--max-usd', '--may-act-for', '--mcp-only', '--mcp-url', '--member', '--members', '--members-file', '--migrate-only', '--migration', '--min-n', '--mode', '--model', '--no-autopilot-install', '--no-autostash', '--no-delegate', '--no-embed', '--no-embedding', '--no-expand', '--no-extract', '--no-federated', '--no-filters', '--no-git', '--no-hooks', '--no-instructions', '--no-lanes', '--no-llm', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-restart', '--no-schema-pack', '--no-stdio-member', '--no-verify', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--of', '--older-than', '--once', '--only', '--operation', '--output', '--oversized', '--page', '--params', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--pending', '--pglite', '--phase', '--plan', '--prefer', '--prefer-postgres', '--prefix', '--preview', '--private-pages', '--probe', '--profile', '--provenance', '--providers', '--pull', '--purge', '--push-only', '--qm', '--query', '--question', '--quiet', '--readers', '--reason', '--rebase', '--rebuild', '--redact-paths', '--reference-date', '--remediate', '--remote', '--remove', '--repair', '--repair-unknown-markers', '--repo', '--request', '--request-id', '--require-clean', '--reset', '--resolve', '--restart-only', '--resume', '--retire', '--retry-failed', '--retry-parked', '--runtime', '--safe', '--save', '--scan-secrets', '--scan-timeout', '--schema-pack', '--scope', '--scopes', '--search-mode', '--section', '--segmented', '--self-transfer', '--semantic', '--serves', '--session', '--session-id', '--shared-skills', '--show-toplevel', '--side', '--since', '--since-last-run', '--skip', '--skip-embed-check', '--skip-failed', '--slug', '--slugs', '--slugs-file', '--source', '--source-id', '--sources', '--squash', '--src-subpath', '--stale', '--state', '--status', '--stdin', '--stdio-member', '--stop-mcp', '--strategy', '--supabase', '--surface', '--swap-only', '--take', '--tier', '--timeout', '--to', '--token', '--touchpoint', '--type', '--types', '--uninstall', '--unsettle', '--untrack', '--url', '--url-env', '--user', '--vacuum', '--verbose', '--version', '--wait', '--warn-only', '--watch', '--working-tree', '--workspace', '--yes'],'integrations': ['--auto', '--brain', '--dry-run', '--help', '--json', '--overwrite', '--refresh', '--source', '--target'],'integrity': ['--accept-pending', '--as', '--auto', '--backend', '--background', '--body', '--brain', '--check', '--confidence', '--cost', '--dry-run', '--explain', '--follow', '--fresh', '--help', '--json', '--limit', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--review-lower', '--skip-bare-tweet', '--skip-urls', '--source', '--timeout', '--timings', '--type', '--wait'],- 'jobs': ['--abbrev-ref', '--access', '--access-policy', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt-slug-path', '--agent', '--aliases', '--all', '--all-sources', '--allow-empty', '--allow-shell-jobs', '--allowed-operations', '--apply', '--approval-out', '--approved', '--as', '--asof', '--assign-corpus', '--attest-actor', '--attest-ops', '--auto', '--background', '--backoff-delay', '--backoff-jitter', '--backoff-type', '--base', '--batch-size', '--body', '--bound-slug-prefixes', '--brain', '--break-lock', '--budget-ms', '--bundled', '--by-mention', '--cached', '--catalog', '--catch-up', '--channel', '--check', '--check-downgrade', '--check-only', '--clear', '--cli-path', '--client', '--close', '--cluster-errors', '--code', '--concurrency', '--confidence', '--confirm-destructive', '--confirm-relocated-root', '--cost-estimate', '--cursor', '--date', '--dated-since', '--days', '--decisions', '--delay', '--detach', '--detail', '--diff-filter', '--dir', '--drain', '--drain-timeout', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--enable', '--entities', '--exclude', '--exclude-standard', '--expect', '--expect-catalog', '--expect-local', '--expect-upstream', '--expected-state', '--explain', '--facts', '--federated-read', '--ff-only', '--file', '--filter', '--filters', '--finished-since', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-retry', '--force-schema', '--format', '--fresh', '--from-index', '--from-json', '--from-meetings', '--full', '--full-history', '--fuzzy', '--git', '--grammar', '--grammar-diagnostics', '--group', '--group-by', '--hard-deadline', '--health-interval', '--held', '--help', '--hold-state', '--http', '--id', '--idempotency-key', '--ids', '--images', '--include', '--include-ambiguous', '--include-content', '--include-deleted', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--infer-dates', '--inject-bootstrap', '--inline', '--input', '--input-json', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--job-id', '--job-isolation', '--json', '--keep', '--kind', '--lanes', '--legacy-lock', '--limit', '--list', '--local', '--lock-duration-ms', '--log-noop', '--markdown', '--max-age', '--max-attempts', '--max-cost', '--max-cost-usd', '--max-crashes', '--max-rss', '--max-sources', '--max-stalled', '--max-usd', '--max-waiting', '--may-act-for', '--mcp-only', '--member', '--members', '--members-file', '--migration', '--min-context', '--missing-path', '--mode', '--model', '--multimodal', '--name', '--name-only', '--ner', '--nice', '--no-assume-unchanged', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-confirm', '--no-delegate', '--no-embed', '--no-embedding', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-inject', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-restart', '--no-schema-pack', '--no-skip-worktree', '--no-verify', '--no-worker', '--non-interactive', '--now', '--of', '--older-than', '--once', '--only', '--order', '--others', '--output', '--override-disabled', '--oversized', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--parked-code', '--pat-file', '--path', '--pause', '--pglite', '--phase', '--pid-file', '--plan', '--port', '--prefer', '--preview', '--priority', '--probe', '--prune-orphans', '--pull', '--purge', '--qm', '--question', '--queue', '--queue-only', '--quiet', '--rate', '--readers', '--reason', '--reason-scan-limit', '--rebuild', '--recent', '--record', '--redact-paths', '--redact-secrets', '--reenrich-after', '--refresh-ms', '--refresh-operations', '--remediate', '--repo', '--request-id', '--reset-checkpoint', '--restart-only', '--resume', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--review-lower', '--routing', '--row', '--save', '--scope', '--scopes', '--section', '--segment-limit', '--segmented', '--select', '--self-transfer', '--serial', '--serves', '--session', '--show-toplevel', '--side', '--sigkill-rescue', '--since', '--skill-loading', '--skills-index-only', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--sleep', '--slug', '--slugs', '--source', '--source-guard', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--state', '--statement-timeout', '--status', '--stdio-member', '--stop-mcp', '--strategy', '--suites', '--surface', '--swap-only', '--target', '--text', '--thin', '--thin-threshold', '--tier', '--timeout', '--timeout-ms', '--to', '--token', '--token-env', '--trust', '--type', '--types', '--uninstall', '--untrack', '--updated-after', '--url', '--user', '--vectors', '--verbose', '--verify', '--version', '--watch', '--wedge-rescue', '--workers', '--working-tree', '--yes'],+ 'jobs': ['--abbrev-ref', '--access', '--access-policy', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt-slug-path', '--agent', '--aliases', '--all', '--all-sources', '--allow-empty', '--allow-shell-jobs', '--allowed-operations', '--apply', '--approval-out', '--approved', '--as', '--asof', '--assign-corpus', '--attest-actor', '--attest-ops', '--auto', '--background', '--backoff-delay', '--backoff-jitter', '--backoff-type', '--base', '--batch-size', '--body', '--bound-slug-prefixes', '--brain', '--break-lock', '--budget-ms', '--bundled', '--by-mention', '--cached', '--catalog', '--catch-up', '--channel', '--check', '--check-downgrade', '--check-only', '--clear', '--cli-path', '--client', '--close', '--cluster-errors', '--code', '--concurrency', '--confidence', '--confirm-destructive', '--confirm-relocated-root', '--cost-estimate', '--cursor', '--date', '--dated-since', '--days', '--decisions', '--delay', '--detach', '--detail', '--diff-filter', '--dir', '--drain', '--drain-timeout', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--enable', '--entities', '--exclude', '--exclude-standard', '--expect', '--expect-catalog', '--expect-local', '--expect-upstream', '--expected-state', '--explain', '--facts', '--federated-read', '--ff-only', '--file', '--filter', '--filters', '--finished-since', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-retry', '--force-schema', '--format', '--fresh', '--from-index', '--from-json', '--from-meetings', '--full', '--full-history', '--fuzzy', '--git', '--grammar', '--grammar-diagnostics', '--group', '--group-by', '--hard-deadline', '--health-interval', '--held', '--help', '--hold-state', '--http', '--id', '--idempotency-key', '--ids', '--images', '--include', '--include-ambiguous', '--include-content', '--include-deleted', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--infer-dates', '--inject-bootstrap', '--inline', '--input', '--input-json', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--job-id', '--job-isolation', '--json', '--keep', '--kind', '--lanes', '--legacy-lock', '--limit', '--list', '--local', '--lock-duration-ms', '--log-noop', '--markdown', '--max-age', '--max-attempts', '--max-cost', '--max-cost-usd', '--max-crashes', '--max-rss', '--max-sources', '--max-stalled', '--max-usd', '--max-waiting', '--may-act-for', '--mcp-only', '--member', '--members', '--members-file', '--migrate-only', '--migration', '--min-context', '--missing-path', '--mode', '--model', '--multimodal', '--name', '--name-only', '--ner', '--nice', '--no-assume-unchanged', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-confirm', '--no-delegate', '--no-embed', '--no-embedding', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-inject', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-restart', '--no-schema-pack', '--no-skip-worktree', '--no-verify', '--no-worker', '--non-interactive', '--now', '--of', '--older-than', '--once', '--only', '--order', '--others', '--output', '--override-disabled', '--oversized', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--parked-code', '--pat-file', '--path', '--pause', '--pglite', '--phase', '--pid-file', '--plan', '--port', '--prefer', '--preview', '--priority', '--probe', '--prune-orphans', '--pull', '--purge', '--qm', '--question', '--queue', '--queue-only', '--quiet', '--rate', '--readers', '--reason', '--reason-scan-limit', '--rebuild', '--recent', '--record', '--redact-paths', '--redact-secrets', '--reenrich-after', '--refresh-ms', '--refresh-operations', '--remediate', '--repo', '--request-id', '--reset-checkpoint', '--restart-only', '--resume', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--review-lower', '--routing', '--row', '--save', '--scope', '--scopes', '--section', '--segment-limit', '--segmented', '--select', '--self-transfer', '--serial', '--serves', '--session', '--show-toplevel', '--side', '--sigkill-rescue', '--since', '--skill-loading', '--skills-index-only', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--sleep', '--slug', '--slugs', '--source', '--source-guard', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--state', '--statement-timeout', '--status', '--stdio-member', '--stop-mcp', '--strategy', '--suites', '--surface', '--swap-only', '--target', '--text', '--thin', '--thin-threshold', '--tier', '--timeout', '--timeout-ms', '--to', '--token', '--token-env', '--trust', '--type', '--types', '--uninstall', '--untrack', '--updated-after', '--url', '--user', '--vectors', '--verbose', '--verify', '--version', '--watch', '--wedge-rescue', '--workers', '--working-tree', '--yes'],'lint': ['--abbrev-ref', '--accept-pending', '--add', '--admin-intent', '--adopt-slug-path', '--as', '--audit', '--autostash', '--background', '--brain', '--branch', '--cached', '--client', '--confirm-relocated-root', '--conflicts', '--dry-run', '--enable', '--error-unmatch', '--exclude', '--expect-remote', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--ff-only', '--file', '--fix', '--follow', '--force', '--get', '--get-all', '--git-dir', '--git-path', '--grammar-diagnostics', '--hard', '--help', '--id', '--infer-entity', '--is-inside-work-tree', '--json', '--keep', '--keep-checkout', '--local', '--local-env-vars', '--manifest', '--max-cost-usd', '--no-accept-pending', '--no-assume-unchanged', '--no-autostash', '--no-cron', '--no-pull', '--no-renames', '--no-skip-worktree', '--no-tags', '--no-verify', '--older-than', '--only', '--pat-file', '--path', '--porcelain', '--prefer', '--preview', '--probe', '--progress-interval', '--progress-json', '--provenance', '--pull', '--purge', '--push-only', '--quiet', '--readers', '--rebase', '--require-clean', '--resolve', '--scan-secrets', '--scan-timeout', '--scopes', '--self-transfer', '--short', '--show-toplevel', '--slug', '--slugs', '--source', '--source-id', '--stdin', '--timeout', '--timings', '--unset-all', '--untracked-files', '--verify', '--wait', '--yes'],'loops': ['--all', '--as-of', '--brain', '--dry-run', '--fail-fast', '--help', '--json', '--note', '--source', '--stale-ok', '--status', '--tools-json', '--top', '--type'],'lsd': ['--brain', '--force-resume', '--help', '--json', '--judge-model', '--limit', '--list-runs', '--max-cost', '--max-far-set', '--max-ideas-per-judge-call', '--max-usd', '--no-save', '--resume', '--save', '--source', '--strict-budget', '--yes'],@@ -95,7 +95,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'notices': ['--brain', '--help', '--json', '--source'],'onboard': ['--access', '--add', '--all', '--allowed-operations', '--apply', '--as', '--asof', '--auto', '--body', '--bound-slug-prefixes', '--brain', '--check', '--client', '--cursor', '--date', '--dated-since', '--days', '--entities', '--explain', '--federated-read', '--follow', '--from-index', '--from-pages', '--full', '--fuzzy', '--group-by', '--help', '--history', '--http', '--id', '--images', '--include', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--of', '--only', '--page', '--params', '--path', '--phase', '--prefer', '--probe', '--purge', '--recent', '--refresh-operations', '--remediate', '--remediation-plan', '--resume', '--row', '--save', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--surface', '--target-score', '--to', '--updated-after', '--url', '--yes'],'orphans': ['--accept-pending', '--all', '--as', '--background', '--brain', '--count', '--cursor', '--explain', '--follow', '--force', '--help', '--include-pseudo', '--json', '--limit', '--mode', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--source', '--timeout', '--timings', '--wait'],- 'pages': ['--brain', '--dry-run', '--force', '--help', '--json', '--limit', '--literal-pathspecs', '--name-only', '--older-than', '--quiet', '--retry-parked', '--show-toplevel', '--source', '--source-id', '--state', '--verify', '--yes'],+ 'pages': ['--brain', '--dry-run', '--force', '--help', '--json', '--limit', '--name-only', '--older-than', '--quiet', '--retry-parked', '--show-toplevel', '--source', '--source-id', '--state', '--verify', '--yes'],'pglite-repair': ['--brain', '--break-lock', '--dry-run', '--expect', '--help', '--http', '--json', '--legacy-lock', '--path', '--probe', '--source', '--vectors', '--yes'],'post-upgrade': ['--accept-reviewed-inventory', '--acknowledge-no-backup', '--admin-intent', '--all', '--all-applied', '--apply', '--apply-clean-hunks', '--backup-confirmed', '--brain', '--catch-up', '--changed', '--channel', '--check', '--check-only', '--concurrency', '--confirm-quiesced', '--confirm-relocated-root', '--content-root', '--cost-estimate', '--embedding-dimensions', '--embedding-model', '--exit-code', '--expand', '--expected-epoch', '--expected-state', '--explain', '--export-db-only', '--export-source', '--ff-only', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--format', '--held', '--help', '--host-dir', '--images', '--inject-bootstrap', '--inline', '--install', '--instructions-only', '--interval', '--is-ancestor', '--json', '--limit', '--list', '--manifest', '--markdown', '--max-rss', '--max-usd', '--migrate-only', '--migration', '--mode', '--multimodal', '--name', '--name-only', '--no-autopilot-install', '--no-bun-floor-check', '--no-embed', '--no-expand', '--no-inject', '--no-restart', '--no-worker', '--non-interactive', '--now', '--once', '--only', '--oversized', '--path', '--pause', '--phase', '--quiet', '--reason', '--refs', '--remediation-plan', '--repo', '--require-db', '--restart-only', '--resume', '--retry-global', '--scope', '--search-mode', '--segmented', '--self-transfer', '--skills-dir', '--skip-verify', '--slug', '--source', '--stale', '--statement-timeout', '--status', '--stop-mcp', '--swap-only', '--tags', '--target', '--uninstall', '--user', '--vectors', '--verify', '--version', '--workers', '--yes'],'pricing': ['--brain', '--help', '--input', '--json', '--max-cost', '--max-runtime', '--output', '--rate', '--source'],@@ -135,7 +135,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'status': ['--abbrev-ref', '--acknowledge-managed', '--all', '--allow-empty', '--apply', '--brain', '--break-lock', '--cached', '--check', '--code', '--concurrency', '--confirm-destructive', '--count', '--cursor', '--deadline-ms', '--delete', '--detail', '--diff-filter', '--empty', '--enable', '--exclude', '--exclude-standard', '--fast', '--filters', '--fix', '--force-break-lock', '--format', '--full', '--full-history', '--funnel', '--hard-deadline', '--help', '--hold-state', '--include-gitignored', '--include-hidden', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--lanes', '--limit', '--max-age', '--max-sources', '--mcp-only', '--missing-path', '--name-only', '--no-auto-embed', '--no-bulk', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--no-walk', '--others', '--parallel', '--path', '--prefer', '--preview', '--priority', '--quiet', '--reason', '--redact-paths', '--repo', '--request-id', '--reset-checkpoint', '--retry-failed', '--retry-held', '--reverse', '--section', '--serial', '--show-toplevel', '--skip-failed', '--slug', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--status', '--strategy', '--timeout', '--url', '--verify', '--watch', '--workers', '--working-tree', '--yes'],'storage': ['--brain', '--help', '--json', '--plan', '--repo', '--restore-only', '--source', '--to'],'sweep': ['--accept-pending', '--apply', '--as', '--assign-corpus', '--background', '--batch-limit', '--brain', '--budget-ms', '--delete-brain', '--explain', '--follow', '--help', '--home', '--json', '--no-accept-pending', '--no-delegate', '--once', '--only', '--progress-interval', '--progress-json', '--quiet', '--retry-failed', '--session', '--source', '--source-id', '--stale', '--timeout', '--timings', '--wait'],- 'sync': ['--abbrev-ref', '--absolute-git-dir', '--accept-pending', '--access-policy', '--account', '--acknowledge-managed', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--after', '--all', '--allow-empty', '--allow-outside-source-root', '--apply', '--apply-rewrites', '--as', '--assign-corpus', '--attest-read', '--audit', '--auto', '--background', '--batch', '--batch-check', '--batch-size', '--brain', '--branch', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--check', '--check-only', '--class', '--clear', '--client', '--close', '--code', '--concurrency', '--config', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--continue', '--conversation', '--count', '--cursor', '--cwd', '--db-url', '--delete-brain', '--depth', '--detach', '--detail', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--enable', '--end-of-options', '--entity', '--exclude', '--exclude-standard', '--expect', '--expect-local', '--expect-upstream', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--ff-only', '--filter', '--filters', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-meetings', '--full', '--full-history', '--get-regexp', '--git-dir', '--git-path', '--grammar', '--group-by', '--hard-deadline', '--harness', '--held', '--help', '--hold-state', '--home', '--http', '--id', '--ignore-missing', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--include-repairs', '--index-audit', '--infer-dates', '--input', '--install', '--instructions-only', '--interval', '--is-ancestor', '--is-bare-repository', '--is-inside-work-tree', '--is-shallow-repository', '--json', '--keep-checkout', '--kind', '--lanes', '--lang', '--left-right', '--legacy-lock', '--limit', '--link-source', '--link-type', '--list', '--literal-pathspecs', '--local', '--locks', '--log-noop', '--manifest', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-sources', '--max-usd', '--may-act-for', '--migrate-legacy', '--migrate-only', '--missing-path', '--multimodal', '--name', '--name-only', '--name-status', '--ner', '--no-accept-pending', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-capture', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-instructions', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--no-walk', '--once', '--only', '--operations', '--others', '--output', '--oversized', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--path-format', '--pending', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--prefer', '--prefer-postgres', '--prefix', '--preview', '--priority', '--probe', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--providers', '--prune-orphans', '--pull', '--purge', '--push-only', '--query', '--question', '--queue', '--quiet', '--raw', '--raw-only', '--reader-mode', '--readers', '--reauth', '--rebase', '--rebuild', '--redact-paths', '--refresh', '--regenerate', '--relative', '--remediate', '--remediation-plan', '--remote', '--remove', '--remove-core', '--replace', '--repo', '--request-id', '--reset', '--reset-checkpoint', '--reset-default', '--restart-only', '--restore-only', '--resume', '--retry-failed', '--retry-held', '--retry-parked', '--reverse', '--scan-secrets', '--scope', '--scopes', '--self-transfer', '--serial', '--serves', '--session', '--short', '--show-current', '--show-toplevel', '--side', '--since', '--skill-loading', '--skills-dir', '--skills-index-only', '--skip', '--skip-failed', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--stat', '--state', '--status', '--stdin', '--strategy', '--supabase', '--surface', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--tier', '--timeout', '--timings', '--to', '--token', '--token-env', '--top-k', '--type', '--unindexed', '--unshallow', '--untracked-files', '--url', '--url-env', '--verbose', '--verify', '--version', '--wait', '--watch', '--where', '--window', '--workers', '--working-tree', '--workspace', '--yes'],+ 'sync': ['--abbrev-ref', '--absolute-git-dir', '--accept-pending', '--access-policy', '--account', '--acknowledge-managed', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--after', '--all', '--allow-empty', '--allow-outside-source-root', '--apply', '--apply-rewrites', '--as', '--assign-corpus', '--attest-read', '--audit', '--auto', '--background', '--batch', '--batch-check', '--batch-size', '--brain', '--branch', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--check', '--check-only', '--class', '--clear', '--client', '--close', '--code', '--concurrency', '--config', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--continue', '--conversation', '--count', '--cursor', '--cwd', '--db-url', '--delete-brain', '--depth', '--detach', '--detail', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--enable', '--end-of-options', '--entity', '--exclude', '--exclude-standard', '--expect', '--expect-local', '--expect-upstream', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--ff-only', '--filter', '--filters', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-meetings', '--full', '--full-history', '--get-regexp', '--git-dir', '--git-path', '--grammar', '--group-by', '--hard-deadline', '--harness', '--held', '--help', '--hold-state', '--home', '--http', '--id', '--ignore-missing', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--include-repairs', '--index-audit', '--infer-dates', '--input', '--install', '--instructions-only', '--interval', '--is-ancestor', '--is-bare-repository', '--is-inside-work-tree', '--is-shallow-repository', '--json', '--keep-checkout', '--kind', '--lanes', '--lang', '--left-right', '--legacy-lock', '--limit', '--link-source', '--link-type', '--list', '--local', '--locks', '--log-noop', '--manifest', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-sources', '--max-usd', '--may-act-for', '--migrate-legacy', '--migrate-only', '--missing-path', '--multimodal', '--name', '--name-only', '--name-status', '--ner', '--no-accept-pending', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-capture', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-instructions', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--no-walk', '--once', '--only', '--operations', '--others', '--output', '--oversized', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--path-format', '--pending', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--prefer', '--prefer-postgres', '--prefix', '--preview', '--priority', '--probe', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--providers', '--prune-orphans', '--pull', '--purge', '--push-only', '--query', '--question', '--queue', '--quiet', '--raw', '--raw-only', '--reader-mode', '--readers', '--reauth', '--rebase', '--rebuild', '--redact-paths', '--refresh', '--regenerate', '--relative', '--remediate', '--remediation-plan', '--remote', '--remove', '--remove-core', '--replace', '--repo', '--request-id', '--reset', '--reset-checkpoint', '--reset-default', '--restart-only', '--restore-only', '--resume', '--retry-failed', '--retry-held', '--retry-parked', '--reverse', '--scan-secrets', '--scope', '--scopes', '--self-transfer', '--serial', '--serves', '--session', '--short', '--show-current', '--show-toplevel', '--side', '--since', '--skill-loading', '--skills-dir', '--skills-index-only', '--skip', '--skip-failed', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--stat', '--state', '--status', '--stdin', '--strategy', '--supabase', '--surface', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--tier', '--timeout', '--timings', '--to', '--token', '--token-env', '--top-k', '--type', '--unindexed', '--unshallow', '--untracked-files', '--url', '--url-env', '--verbose', '--verify', '--version', '--wait', '--watch', '--where', '--window', '--workers', '--working-tree', '--workspace', '--yes'],'takes': ['--about', '--accept', '--applied', '--apply', '--batch-size', '--before', '--brain', '--bucket-size', '--by', '--claim', '--date', '--dim', '--dir', '--domain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--evidence', '--expected-revision', '--expired', '--failed', '--force', '--from-pages', '--group-by', '--help', '--holder', '--include-covered', '--json', '--kind', '--limit', '--max-pages', '--min-confidence', '--min-n', '--no-embed', '--no-embedding', '--offset', '--outcome', '--path', '--quality', '--reject', '--request-id', '--retry-failed', '--row', '--semantic', '--since', '--slug', '--sort', '--source', '--source-id', '--stale', '--state', '--status', '--supabase', '--to', '--unapplied', '--unit', '--until', '--value', '--verdict', '--weight', '--who', '--yes'],'think': ['--anchor', '--brain', '--calibration-holder', '--help', '--images', '--json', '--mcp-only', '--model', '--only', '--reference-date', '--request-id', '--rounds', '--save', '--since', '--source', '--source-id', '--stale', '--take', '--until', '--with-calibration'],'transcripts': ['--accept-pending', '--all', '--all-discovery', '--apply', '--as', '--background', '--brain', '--days', '--dry-run', '--embed', '--explain', '--facts', '--follow', '--format', '--full', '--help', '--include-self', '--json', '--limit', '--max-bytes', '--max-cost-usd', '--no-accept-pending', '--only', '--progress-interval', '--progress-json', '--purge', '--quiet', '--since', '--source', '--source-id', '--timeout', '--timings', '--wait'],diff --git a/src/core/doctor-categories.ts b/src/core/doctor-categories.tsindex 4013a71284..b4798e4ab0 100644--- a/src/core/doctor-categories.ts+++ b/src/core/doctor-categories.ts@@ -506,6 +506,8 @@ export const META_CHECK_NAMES: ReadonlySet<string> = new Set([// #5216: the resumable pages.knowledge_revision backfill (resumed by apply-migrations --force-schema).'revision_backfill','schema_columns',+ // #7776: function bodies an older gbrain's schema replay reverted (init --migrate-only reinstalls them).+ 'schema_function_bodies',// #6911: tables the applied migrations created that are missing (repair missing-tables recreates rebuildable caches).'schema_missing_tables','schema_pack_active',diff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex 5de3c80547..de906e3675 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -154,6 +154,7 @@ export const CODES = {checkpoint_missing: { class: 'caller', summary: "The approved source plan is missing; do not restart from a different revision." },checkpoint_validation_timeout: { class: 'retryable', summary: "Validating the managed-sync checkpoint timed out." },claim_already_used: { class: 'caller', summary: "Google connect credential error: claim already used.", docs: 'docs/guides/google-connect.md#troubleshooting' },+ client_behind: { class: 'host_only', retryable: false, actor: 'host_admin', summary: "Schema setup (initSchema, which gbrain init, init --migrate-only and upgrade run, and apply-migrations before its orchestrators) refused because the brain's schema version is newer than this gbrain binary's newest migration; nothing in its schema ran and nothing changed.", why: "initSchema replays the binary's whole schema, CREATE OR REPLACE FUNCTION included, before it runs migrations. An older binary sharing the database with a newer one (another host, a lagging cron running apply-migrations or upgrade) used to reinstall its own superseded function bodies, the writer-fence guards among them, over the newer ones and then apply nothing (#7776). Reads do not run schema setup and keep working on the older binary; doctor schema_function_bodies names bodies an older replay already reverted.", suggestion: 'Upgrade gbrain on this host (gbrain upgrade) to the release that migrated the database or newer, then rerun the command.', fix: { argv: ['gbrain', 'doctor', '--only', 'schema_version', '--json'], consent: [], actor: 'agent', why: "Read-only: shows the brain's schema version beside this binary's newest migration.", requires_exclusive: false } },client_json_unreadable: { class: 'caller', summary: "Google connect credential error: client json unreadable.", docs: 'docs/guides/google-connect.md#troubleshooting' },client_json_wrong_type: { class: 'caller', summary: "Google connect credential error: client json wrong type.", docs: 'docs/guides/google-connect.md#troubleshooting' },client_not_found: { class: 'caller', summary: "No OAuth client with this id is registered on this brain, so nothing was read or changed.", why: 'A client id is matched exactly; a revoked, deleted or mistyped id has no grant to read or edit.', suggestion: 'List the clients with `gbrain auth clients --json` and retry with an existing client id. Do not register a replacement client or rotate credentials for a lookup miss.', fix: { argv: ['gbrain', 'auth', 'clients', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Read-only: lists the OAuth clients registered on this brain.', verify: { argv: ['gbrain', 'auth', 'clients', '--json'] } } },diff --git a/src/core/extract/receipt-writer.ts b/src/core/extract/receipt-writer.tsindex 2ed7105295..98d927b278 100644--- a/src/core/extract/receipt-writer.ts+++ b/src/core/extract/receipt-writer.ts@@ -38,6 +38,9 @@import type { BrainEngine } from '../engine.ts';import type { Page } from '../types.ts';import { maintenanceTransaction } from '../persistence/attribution.ts';+import { isNeverFiledDerivedPage } from '../persistence/git-declared.ts';+import { resealSafeChunks } from '../page-state/projections.ts';+import { SAFE_FENCE_CHUNKER_VERSION } from '../search/safe-chunks.ts';/*** Round identifier. Matches the progressive-batch primitive's Stage@@ -195,6 +198,15 @@ function buildReceiptFrontmatter(input: ExtractReceiptInput): Record<string, unk* frontmatter. Threads sourceId so federated brains route the receipt* to the same source the extraction targeted.*+ * #7620: a receipt is database-only derived bookkeeping, never content: a+ * never-filed page under the derive-phase `extracts/` folder (the+ * `derive_folder` class of docs/designs/GIT_CANONICAL_MEMORY.md), so the+ * write refuses a slug that holds a content page or a page with a file.+ * Its chunks are installed and sealed at the safe-chunk fence in the same+ * transaction as the page (resealSafeChunks), so no reader sees it unsealed+ * (remote search would report safe_index_pending) and a rollback leaves+ * neither.+ ** Re-running with the same run_id + round overwrites the prior receipt* (idempotent on resume). The op-checkpoint id is stable across* resumes per src/core/op-checkpoint.ts, so this is the desired@@ -209,26 +221,39 @@ export async function writeReceipt(const frontmatter = buildReceiptFrontmatter(input);const compiled_truth = buildReceiptBody(input);- const page = await maintenanceTransaction(engine, tx => tx.putPage(- slug,- {- type: 'extract_receipt',- title,- compiled_truth,- frontmatter,- },- { sourceId: input.source_id },- ));-- // #4009: receipts are audit artifacts — deliberately never run through- // the contextual-retrieval ladder. Born with a NULL- // contextual_retrieval_mode they tripped doctor's- // contextual_retrieval_coverage warn on every extraction run right- // after a reindex. Stamp mode 'none' so receipts are born CR-evaluated.- // NOT permanent: a reindex that takes the DB fallback clears the stamp- // and it recurs per receipt — the doctor check also excludes- // type='extract_receipt' from mode_null (belt+braces).- await engine.updatePageContextualRetrievalState(slug, input.source_id, 'none', null);+ const page = await maintenanceTransaction(engine, async tx => {+ await tx.lockPageKeys([{ sourceId: input.source_id, slug }]);+ const [prior] = await tx.executeRaw<{ type: string | null; source_path: string | null; source_uri: string | null; withheld_source_path: string | null }>(+ 'SELECT type, source_path, source_uri, withheld_source_path FROM pages WHERE source_id=$1 AND slug=$2', [input.source_id, slug]);+ if (!isNeverFiledDerivedPage(slug, prior ?? {}) || (prior && prior.type !== 'extract_receipt')) {+ throw new Error(`Extract receipt ${slug} (source ${input.source_id}) was not written: that slug holds a content page or a page with a file in Git, and a receipt is database-only bookkeeping.`);+ }+ const written = await tx.putPage(+ slug,+ {+ type: 'extract_receipt',+ title,+ compiled_truth,+ frontmatter,+ },+ { sourceId: input.source_id },+ );+ await resealSafeChunks(tx, slug, input.source_id);+ const [sealed] = await tx.executeRaw<{ sealed: boolean }>(+ `SELECT chunker_version >= ${SAFE_FENCE_CHUNKER_VERSION} AND text_projection_revision = knowledge_revision AS sealed FROM pages WHERE source_id=$1 AND slug=$2`,+ [input.source_id, slug]);+ if (sealed?.sealed !== true) throw new Error(`Extract receipt ${slug} (source ${input.source_id}) was not written: its chunks could not be sealed in the writing transaction.`);+ // #4009: receipts are audit artifacts — deliberately never run through+ // the contextual-retrieval ladder. Born with a NULL+ // contextual_retrieval_mode they tripped doctor's+ // contextual_retrieval_coverage warn on every extraction run right+ // after a reindex. Stamp mode 'none' so receipts are born CR-evaluated.+ // NOT permanent: a reindex that takes the DB fallback clears the stamp+ // and it recurs per receipt — the doctor check also excludes+ // type='extract_receipt' from mode_null (belt+braces).+ await tx.updatePageContextualRetrievalState(slug, input.source_id, 'none', null);+ return written;+ });return { slug, page };}diff --git a/src/core/facts/purge-verify.ts b/src/core/facts/purge-verify.tsindex ac2291d35f..7e36876f64 100644--- a/src/core/facts/purge-verify.ts+++ b/src/core/facts/purge-verify.ts@@ -25,7 +25,7 @@ import { gbrainPath } from '../config.ts';import type { WriteRequest } from '../persistence/model.ts';import { DELETION_INVENTORY, DELETION_INVENTORY_BY_TABLE, OUT_OF_REACH_RESIDUALS, type InventoryEntry } from '../deletion-inventory.ts';import type { PurgePlan, PurgeTarget } from './purge.ts';-import { gitChildEnv } from '../git-env.ts';+import { gitChildEnv, literalPathspecs } from '../git-env.ts';import { segmentedBodyContains } from '../page-body/segment-rewrite.ts';import { derivationAfterSql, derivationBatchRows, derivationNeedles, derivationPurgeState, recordDerivationStatement,type DerivationKey, type DerivationPendingReason, type DerivationStallReason, type DerivationSweepState } from '../page-body/segment-derive.ts';@@ -405,7 +405,7 @@ export async function gitResidualCommits(root: string, paths: readonly string[],if (!paths.length || !existsSync(join(root, '.git'))) return { store: 'git_history', status: 'out_of_reach', reason: 'no_repository', detail: 'No brain repository is recorded for these pages.' };const needles = [escapeFenceCell(claim).toLowerCase(), claim.toLowerCase()];return new Promise(resolve => {- const child = spawn('git', ['-C', root, '--literal-pathspecs', 'log', '--all', '--format=commit %H %cI', '-p', '--no-color', '--no-ext-diff', '--', ...paths],+ const child = spawn('git', ['-C', root, 'log', '--all', '--format=commit %H %cI', '-p', '--no-color', '--no-ext-diff', '--', ...literalPathspecs(paths)],{ stdio: ['ignore', 'pipe', 'ignore'], env: gitChildEnv({ GIT_TERMINAL_PROMPT: '0', GIT_CONFIG_NOSYSTEM: '1' }) });const commits: Array<{ commit: string; committed_at: string }> = [];let current: { commit: string; committed_at: string } | null = null, bytes = 0, tail = '', bounded: string | null = null;diff --git a/src/core/git-env.ts b/src/core/git-env.tsindex 50da7a603a..fa6e0c0eea 100644--- a/src/core/git-env.ts+++ b/src/core/git-env.ts@@ -23,8 +23,13 @@ const DROPPED = new Set<string>([...GIT_LOCAL_ENV_VARS, ...GIT_PATHSPEC_ENV_VARS/*** #7759: each path as a literal pathspec. Use this instead of the global `--literal-pathspecs` flag, which Git exports* as GIT_LITERAL_PATHSPECS=1 to hooks and children, where a hook's glob pathspec then silently matches nothing.+ * #7793: an empty path throws (`:(literal)` alone matches the whole tree; Git itself refuses an empty pathspec). `.` stays+ * allowed: it is the explicit whole-tree scope of a read, and every writer's paths pass `scopePaths`, which refuses it.*/-export const literalPathspecs = (paths: readonly string[]): string[] => paths.map(path => `:(literal)${path}`);+export const literalPathspecs = (paths: readonly string[]): string[] => paths.map(path => {+ if (path === '') throw new Error('literalPathspecs: an empty path would match the whole tree');+ return `:(literal)${path}`;+});/*** Extra env for a Git call that only reads (diff, ls-files, cat-file, rev-parse, status): `GIT_OPTIONAL_LOCKS=0` stops Gitdiff --git a/src/core/git/commit-push.ts b/src/core/git/commit-push.tsindex d631a96046..bcb9941bd3 100644--- a/src/core/git/commit-push.ts+++ b/src/core/git/commit-push.ts@@ -25,7 +25,7 @@* (#7010; the owner's Git effects publish this way). CLI-only; never exposed* over MCP (it pushes with host credentials).*/-import { appendFileSync, existsSync, lstatSync, mkdtempSync, readFileSync, readlinkSync, realpathSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs';+import { appendFileSync, copyFileSync, existsSync, lstatSync, mkdtempSync, readFileSync, readlinkSync, realpathSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';import { rangeSecretRefusal, scanRange } from './range-secret-scan.ts';import { isAbsolute, join, relative, resolve, sep } from 'node:path';@@ -388,8 +388,8 @@ function withIndexRetry(root: string, args: string[], what: string, env?: NodeJS}/** A staged rename (`git mv`) commits both sides: committing only the new name would publish a duplicate and leave the deletion staged for another writer's commit. */-function withRenamePartners(root: string, rel: string[]): string[] {- const fields = git(root, ['diff', '--cached', '-M', '--name-status', '-z']).stdout.split('\0');+function withRenamePartners(root: string, rel: string[], env?: NodeJS.ProcessEnv): string[] {+ const fields = git(root, ['diff', '--cached', '-M', '--name-status', '-z'], { env }).stdout.split('\0');const out = new Set(rel);for (let i = 0; i < fields.length;) {const status = fields[i];@@ -601,16 +601,13 @@ function scopeBases(root: string, opts: CommitPushOptions, rel: string[]): Map<s}/**- * Stage and commit exactly `rel` (the caller holds the commit lock). Refused- * before anything is staged: a path outside the source root(s), and a file- * another writer already staged under a named directory (name it to claim- * it). A commit git refuses leaves the index as it found it. `skipped` lists- * the named paths git left out (GST-2116); the rest are still committed.+ * What commitPaths refuses before anything is staged (and the dry run with it): a path outside the source root(s), a+ * `--base` blob HEAD no longer holds, and a file another writer already staged under a named directory (name it to claim it).*/-function commitPaths(root: string, rel: string[], message: string, scope: CommitScope): { sha: string | null; skipped: SkippedPath[] } {- const outside = rel.filter(p => !insideSourceRoots(p, scope.roots));- if (outside.length) throw outsideRootError(root, scope.roots, outside, 'Refusing to commit');- for (const [path, base] of scope.bases ?? []) {+function admitPaths(root: string, rel: string[], roots: string[], bases?: ReadonlyMap<string, string>): void {+ const outside = rel.filter(p => !insideSourceRoots(p, roots));+ if (outside.length) throw outsideRootError(root, roots, outside, 'Refusing to commit');+ for (const [path, base] of bases ?? []) {const head = git(root, ['rev-parse', '--verify', '-q', `HEAD:${path}`]).stdout.trim() || 'absent';if (head !== base) throw opError('commit_base_moved', `${path} changed at HEAD since the writer read it (base ${base}, HEAD ${head}).`,`Nothing was staged or committed. Read ${path} at HEAD again (git -C ${root} show HEAD:${path}), redo the change on it, and rerun with --base ${path}=${head}.`,@@ -622,36 +619,58 @@ function commitPaths(root: string, rel: string[], message: string, scope: Committhrow opError('commit_prestaged_paths', `${swept.length} file(s) under the named path(s) were already staged by another writer: ${list}.`,'Nothing was staged or committed. If they are yours, name each file explicitly; otherwise leave them to the writer that staged them, or unstage them with the user\'s agreement (git restore --staged -- <file>; the working tree keeps its bytes). Files a parked gbrain Git effect left staged are gbrain\'s own: gbrain sources writer status lists the parked effects with their source and request id, and gbrain sources writer retry-effects with that source and --request-id commits them.',{ detail: JSON.stringify({ paths: swept }), fix: { ask_user: true, consent: [], actor: 'user', requires_exclusive: false,- argv: ['git', '-C', root, 'restore', '--staged', '--', ...swept],+ argv: ['git', '-C', root, 'restore', '--staged', '--', ...literalPathspecs(swept)],why: 'Another writer staged these files; committing them would publish whatever that writer had in progress, and unstaging them drops its staging.',user_message: `Files already staged by another writer sit under the path you asked to commit (${list}). Commit only the files you name, or unstage those (their bytes stay on disk)?`,docs: 'docs/guides/shared-checkout-git.md#outcomes' } });}- const dirtyBefore = directoryStatus(root, rel);- const before = indexEntries(root, rel);- const flagged = gitOk(root, ['ls-files', '-v', '-z', '--', ...literalPathspecs(rel)], 'ls-files -v').split('\0').filter(entry => /^[a-zS] /.test(entry));- if (scope.untrack) return { sha: untrackPaths(root, rel, message, scope, before, flagged), skipped: [] };+}++/** The named paths' `ls-files -v` records that carry the assume-unchanged or skip-worktree flag. */+function flaggedEntries(root: string, rel: string[]): string[] {+ return gitOk(root, ['ls-files', '-v', '-z', '--', ...literalPathspecs(rel)], 'ls-files -v').split('\0').filter(entry => /^[a-zS] /.test(entry));+}++/**+ * Stage `rel` for a commit; returns the named skip-worktree files on disk it left out. GST-2118: git add refuses a named+ * skip-worktree file that is on disk; it is left to the skipped-path check, so the other paths still commit. #7984: a+ * tracked path stages with `add -u`, because `add -A` refuses a deletion whose only match left is an ignored path;+ * visible untracked files stage with `add -A`; a path already staged as deleted is staged. Any other path keeps git's own+ * refusal (missing, or only an ignored untracked file). `dryRun` (#7752) asks git with `add -n` against `env`'s index.+ */+function stagePaths(root: string, rel: string[], before: string[], flagged: string[], env?: NodeJS.ProcessEnv, dryRun = false): Set<string> {const skipWorktree = new Set(flagged.filter(entry => /^[sS] /.test(entry)).map(entry => entry.slice(2)));- // GST-2118: git add refuses a named skip-worktree file that is on disk; it is left to the skipped-path check, so the other paths still commit.const sparse = new Set([...skipWorktree].filter(p => rel.includes(p) && existsSync(join(root, p))));const live = rel.filter(p => !sparse.has(p));- // #7984: a tracked path stages with `add -u`, because `add -A` refuses a deletion whose only match left is an ignored- // path; visible untracked files stage with `add -A`; a path already staged as deleted is staged. Any other path keeps- // git's own refusal (missing, or only an ignored untracked file).- const listed = (args: string[]) => live.length ? git(root, [...args, '-z', '--', ...literalPathspecs(live)]).stdout.split('\0').filter(Boolean) : [];+ const listed = (args: string[]) => live.length ? git(root, [...args, '-z', '--', ...literalPathspecs(live)], { env }).stdout.split('\0').filter(Boolean) : [];const tracked = before.map(line => line.slice(line.indexOf('\t') + 1)).filter(p => !skipWorktree.has(p));const untracked = listed(['ls-files', '--others', '--exclude-standard']);const deleted = listed(['diff', '--cached', '--no-renames', '--name-only', '--diff-filter=D']);const matching = (paths: string[]) => live.filter(spec => paths.some(p => covers(spec, p)));const matched = new Set(matching([...tracked, ...untracked, ...deleted]));const unmatched = live.filter(spec => !matched.has(spec));+ for (const [mode, specs] of [['-u', matching(tracked)], ['-A', matching(untracked)], ['-A', unmatched]] as const) {+ if (!specs.length) continue;+ const args = ['add', mode, ...(dryRun ? ['-n'] : []), '--', ...literalPathspecs(specs)];+ const add = dryRun ? git(root, args, { env }) : withIndexRetry(root, args, 'git add', env);+ if (add.code !== 0) throw opError('commit_paths_invalid', 'git add refused the given paths.', add.stderr.trim().slice(0, 300) || 'Check the paths exist or are tracked.');+ }+ return sparse;+}++/**+ * Stage and commit exactly `rel` (the caller holds the commit lock), after admitPaths. A commit git refuses leaves the+ * index as it found it. `skipped` lists the named paths git left out (GST-2116); the rest are still committed.+ */+function commitPaths(root: string, rel: string[], message: string, scope: CommitScope): { sha: string | null; skipped: SkippedPath[] } {+ admitPaths(root, rel, scope.roots, scope.bases);+ const dirtyBefore = directoryStatus(root, rel);+ const before = indexEntries(root, rel);+ const flagged = flaggedEntries(root, rel);+ if (scope.untrack) return { sha: untrackPaths(root, rel, message, scope, before, flagged), skipped: [] };let landed: { committed: boolean; paths: string[]; listed: string[] };try {- for (const [mode, specs] of [['-u', matching(tracked)], ['-A', matching(untracked)], ['-A', unmatched]] as const) {- if (!specs.length) continue;- const add = withIndexRetry(root, ['add', mode, '--', ...literalPathspecs(specs)], 'git add');- if (add.code !== 0) throw opError('commit_paths_invalid', 'git add refused the given paths.', add.stderr.trim().slice(0, 300) || 'Check the paths exist or are tracked.');- }+ const sparse = stagePaths(root, rel, before, flagged);const paths = withRenamePartners(root, rel);const partners = paths.filter(p => !insideSourceRoots(p, scope.roots));if (partners.length) throw outsideRootError(root, scope.roots, partners, 'A staged rename would commit');@@ -740,17 +759,45 @@ export function untrackAdmitted(root: string, rel: string[], managed: ManagedFilreturn files;}+/** The source roots a dry run checks paths against; a managed canonical worktree refuses --allow-outside-source-root as its real run does. */+function previewRoots(root: string, allowOutsideSourceRoot?: boolean): { managed: ManagedFilesystemRoot | null; roots: string[] } {+ const managed = managedFilesystemRootFor(root);+ if (managed && allowOutsideSourceRoot) {+ throw opError('commit_paths_invalid', `${root} is the managed canonical worktree${managed.sourceId ? ` of source ${managed.sourceId}` : ''}: commit-push there only commits the paths you name.`,+ `Run gbrain git commit-push with only -m and the page paths after --; gbrain sources refresh${managed.sourceId ? ` ${managed.sourceId}` : ''} brings remote commits in.`);+ }+ return { managed, roots: allowOutsideSourceRoot ? [''] : configuredSourceRoots(root) };+}++/**+ * #7752: `--dry-run` of a commit runs the real run's path checks in its order: the source roots, `--base` and files+ * another writer staged (admitPaths), the real run's staging (stagePaths, as `git add -n`) and the source roots of a staged+ * rename's other side. Git is asked against a copy of the index, so the preview takes no lock and writes nothing; each+ * refusal carries the real run's code and text.+ */+export function previewPaths(root: string, rel: string[], opts: { allowOutsideSourceRoot?: boolean; bases?: Map<string, string>; cwd?: string } = {}): void {+ const { roots } = previewRoots(root, opts.allowOutsideSourceRoot);+ admitPaths(root, rel, roots, scopeBases(root, { repo: root, bases: opts.bases, cwd: opts.cwd }, rel));+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-preview-'));+ try {+ const index = join(dir, 'index');+ const live = absGitPath(root, 'index');+ if (existsSync(live)) copyFileSync(live, index);+ const env = { GIT_INDEX_FILE: index };+ stagePaths(root, rel, indexEntries(root, rel), flaggedEntries(root, rel), env, true);+ const partners = withRenamePartners(root, rel, env).filter(p => !insideSourceRoots(p, roots));+ if (partners.length) throw outsideRootError(root, roots, partners, 'A staged rename would commit');+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+}+/*** `--dry-run --untrack`: the real run's path checks (source roots, the files HEAD holds, and in a managed canonical* worktree the storage.db_only admission) with no lock taken and nothing written; each refusal is the real run's.*/export function previewUntrack(root: string, rel: string[], opts: { allowOutsideSourceRoot?: boolean } = {}): string[] {- const managed = managedFilesystemRootFor(root);- if (managed && opts.allowOutsideSourceRoot) {- throw opError('commit_paths_invalid', `${root} is the managed canonical worktree${managed.sourceId ? ` of source ${managed.sourceId}` : ''}: commit-push there only commits the paths you name.`,- `Run gbrain git commit-push with only -m and the page paths after --; gbrain sources refresh${managed.sourceId ? ` ${managed.sourceId}` : ''} brings remote commits in.`);- }- const roots = opts.allowOutsideSourceRoot ? [''] : configuredSourceRoots(root);+ const { managed, roots } = previewRoots(root, opts.allowOutsideSourceRoot);const outside = rel.filter(p => !insideSourceRoots(p, roots));if (outside.length) throw outsideRootError(root, roots, outside, 'Refusing to commit');return managed ? untrackAdmitted(root, rel, managed) : untrackTargets(root, rel);diff --git a/src/core/persistence/git-door.ts b/src/core/persistence/git-door.tsindex 8fdd19370f..0814675a23 100644--- a/src/core/persistence/git-door.ts+++ b/src/core/persistence/git-door.ts@@ -376,10 +376,10 @@ function indexConflict(root: string, staged: Target[]): OperationError {return opError('git_index_conflict', `${paths.join(', ')} in ${root} has a staged change that is not committed, so this write committed nothing and the index was left as it was.`,'Commit the staged change, or unstage it (git restore --staged -- <path> keeps the file on disk), then retry the write with a new request_id.', {detail: paths.join(','),- fix: { ask_user: true, argv: ['git', '-C', root, 'restore', '--staged', '--', ...paths], consent: [], actor: 'user', requires_exclusive: false,+ fix: { ask_user: true, argv: ['git', '-C', root, 'restore', '--staged', '--', ...literalPathspecs(paths)], consent: [], actor: 'user', requires_exclusive: false,why: 'The door commits a path only while its index entry equals HEAD\'s, so a staged change is never overwritten or committed under a gbrain commit. Unstaging keeps the file on disk; committing it publishes that change.',user_message: `${paths.join(', ')} in ${root} has a staged change that is not committed, so gbrain did not commit its write there. Commit the staged change, or unstage it (its bytes stay on disk), then retry the write?`,- verify: { argv: ['git', '-C', root, 'diff', '--cached', '--name-only', '--', ...paths] } },+ verify: { argv: ['git', '-C', root, 'diff', '--cached', '--name-only', '--', ...literalPathspecs(paths)] } },});}diff --git a/src/core/persistence/resolve-paths.ts b/src/core/persistence/resolve-paths.tsindex 79d174dfd5..7aa313fa22 100644--- a/src/core/persistence/resolve-paths.ts+++ b/src/core/persistence/resolve-paths.ts@@ -26,6 +26,7 @@*/import type { BrainEngine } from '../engine.ts';import type { Action } from '../agent-output.ts';+import { literalPathspecs } from '../git-env.ts';import { existsSync, realpathSync } from 'node:fs';import { isAbsolute } from 'node:path';import { opError } from '../ops/contract.ts';@@ -90,7 +91,7 @@ interface TreeRow { path: string; oid: string; size: number }function lsTree(gitRoot: string, commit: string | null, paths: string[]): Map<string, TreeRow> {const out = new Map<string, TreeRow>();if (!commit || !paths.length) return out;- const raw = syncGit(gitRoot, ['--literal-pathspecs', 'ls-tree', '-l', '-z', commit, '--', ...paths]);+ const raw = syncGit(gitRoot, ['ls-tree', '-l', '-z', commit, '--', ...literalPathspecs(paths)]);for (const row of raw.split('\0')) {const tab = row.indexOf('\t');if (tab < 0) continue;diff --git a/src/core/persistence/sync-blobs.ts b/src/core/persistence/sync-blobs.tsindex 961efcac35..65dd32f228 100644--- a/src/core/persistence/sync-blobs.ts+++ b/src/core/persistence/sync-blobs.ts@@ -12,7 +12,7 @@ import { execFileSync } from 'node:child_process';import { mkdtempSync, rmSync } from 'node:fs';import { tmpdir } from 'node:os';import { join } from 'node:path';-import { gitChildEnv } from '../git-env.ts';+import { gitChildEnv, literalPathspecs } from '../git-env.ts';import { HARDENED_GIT_ARGS, noLazyFetchEnv } from '../hardened-git.ts';import { PAGE_MAX_BYTES } from '../page-size-policy.ts';@@ -22,7 +22,7 @@ export const SYNC_READ_BOUND = PAGE_MAX_BYTES;export interface TreeBlob { oid: string; size: number }function git(gitRoot: string, args: string[], input?: string, maxBuffer = 32 * 1024 ** 2, env: NodeJS.ProcessEnv = {}): Buffer {- return execFileSync('git', ['-c', 'core.quotepath=false', ...HARDENED_GIT_ARGS, '--literal-pathspecs', '-C', gitRoot, ...args],+ return execFileSync('git', ['-c', 'core.quotepath=false', ...HARDENED_GIT_ARGS, '-C', gitRoot, ...args],{ env: gitChildEnv({ ...noLazyFetchEnv(), ...env }), timeout: 60_000, maxBuffer, stdio: ['pipe', 'pipe', 'pipe'], ...(input !== undefined ? { input } : {}) });}@@ -34,7 +34,7 @@ export function readTreeBlobs(gitRoot: string, target: string, gitPaths: string[const whole = gitPaths.length >= WHOLE_TREE_AT, wanted = whole ? new Set(gitPaths) : null;for (let i = 0; i < gitPaths.length; i += 500) {const rows = (whole ? git(gitRoot, ['ls-tree', '-r', '-l', '-z', target], undefined, 512 * 1024 ** 2)- : git(gitRoot, ['ls-tree', '-l', '-z', target, '--', ...gitPaths.slice(i, i + 500)])).toString('utf8').split('\0');+ : git(gitRoot, ['ls-tree', '-l', '-z', target, '--', ...literalPathspecs(gitPaths.slice(i, i + 500))])).toString('utf8').split('\0');for (const row of rows) {const tab = row.indexOf('\t');if (tab < 0 || wanted && !wanted.has(row.slice(tab + 1))) continue;diff --git a/src/core/persistence/sync-origin-evidence.ts b/src/core/persistence/sync-origin-evidence.tsindex f09aa0c922..c71283d286 100644--- a/src/core/persistence/sync-origin-evidence.ts+++ b/src/core/persistence/sync-origin-evidence.ts@@ -13,7 +13,7 @@*/import { execFile, spawn } from '../spawn.ts';import { promisify } from 'node:util';-import { gitChildEnv } from '../git-env.ts';+import { gitChildEnv, literalPathspecs } from '../git-env.ts';import { HARDENED_GIT_ARGS, NO_LAZY_FETCH_ENV, NulRecordSplitter } from '../hardened-git.ts';import { ignoreCandidates } from './ignore-rules.ts';@@ -31,10 +31,10 @@ const WALK_TIMEOUT_MS = 600_000;const INDEXES_PER_ROOT = 2;const GIT_MAX_BUFFER = 64 * 1024 ** 2;-/** `literal`: the paths are pathspecs read literally (`log`); `check-ignore` takes plain pathnames and refuses the magic. GST-2331: every read here fetches nothing in a partial clone. */-async function git(gitRoot: string, args: string[], literal = false): Promise<{ code: number; stdout: string }> {+/** `ls-tree` paths pass `literalPathspecs`; `check-ignore` takes plain pathnames and refuses the magic. GST-2331: every read here fetches nothing in a partial clone. */+async function git(gitRoot: string, args: string[]): Promise<{ code: number; stdout: string }> {try {- const { stdout } = await execFileAsync('git', ['-c', 'core.quotepath=false', ...HARDENED_GIT_ARGS, ...(literal ? ['--literal-pathspecs'] : []), '-C', gitRoot, ...args],+ const { stdout } = await execFileAsync('git', ['-c', 'core.quotepath=false', ...HARDENED_GIT_ARGS, '-C', gitRoot, ...args],{ env: gitChildEnv(NO_LAZY_FETCH_ENV), encoding: 'utf8', timeout: GIT_TIMEOUT_MS, maxBuffer: GIT_MAX_BUFFER });return { code: 0, stdout };} catch (error) {@@ -236,7 +236,7 @@ export async function readDeletionProvenance(root: string, paths: readonly strin// ls-tree from `root` names the paths HEAD still holds, relative to it.const inHead = new Set<string>();for (let i = 0; i < unique.length; i += BATCH) {- const listed = await git(root, ['ls-tree', '-r', '-z', '--name-only', 'HEAD', '--', ...unique.slice(i, i + BATCH)], true);+ const listed = await git(root, ['ls-tree', '-r', '-z', '--name-only', 'HEAD', '--', ...literalPathspecs(unique.slice(i, i + BATCH))]);if (listed.code !== 0) return provenance;for (const path of listed.stdout.split('\0')) if (path) inHead.add(path);}diff --git a/src/core/persistence/unindexed-files.ts b/src/core/persistence/unindexed-files.tsindex ab307f67d1..c897fc8d92 100644--- a/src/core/persistence/unindexed-files.ts+++ b/src/core/persistence/unindexed-files.ts@@ -50,7 +50,7 @@import type { BrainEngine } from '../engine.ts';import type { SyncOpts } from '../../commands/sync.ts';import { spawn } from '../spawn.ts';-import { gitChildEnv } from '../git-env.ts';+import { gitChildEnv, literalPathspecs } from '../git-env.ts';import { HARDENED_GIT_ARGS, NO_LAZY_FETCH_ENV } from '../hardened-git.ts';import { isSyncMetafile, matchesAnyGlob, metafileIsPage, resolveSlugForPath } from '../sync.ts';import { screenImportContent } from '../import-screen.ts';@@ -161,7 +161,7 @@ function visitBlobSlices<T extends TreeBlob>(gitRoot: string, entries: T[], visi/** The blobs of `target` under `scope` in tree order, after `after`, in batches; the child stops when the consumer does. */async function* treeBatches(gitRoot: string, target: string, scope: string, after: string | null, size: number, revisit?: ReadonlySet<string>): AsyncGenerator<TreeEntry[]> {- const child = spawn('git', ['-c', 'core.quotepath=false', ...HARDENED_GIT_ARGS, '--literal-pathspecs', '-C', gitRoot, 'ls-tree', '-r', '-l', '-z', target, ...(scope ? ['--', scope] : [])],+ const child = spawn('git', ['-c', 'core.quotepath=false', ...HARDENED_GIT_ARGS, '-C', gitRoot, 'ls-tree', '-r', '-l', '-z', target, ...(scope ? ['--', ...literalPathspecs([scope])] : [])],{ env: gitChildEnv(NO_LAZY_FETCH_ENV), stdio: ['ignore', 'pipe', 'pipe'] });let stderr = '';child.stderr!.on('data', (chunk: Buffer) => { stderr = (stderr + chunk.toString('utf8')).slice(0, 2000); });@@ -289,7 +289,7 @@ export function unindexedBudgetForPages(pages: number): number {/** Git paths at or before `cursor` that differ between `from` and `to`; null when Git cannot list them or they number more than `UNINDEXED_REVISIT_CAP`. */function changedBefore(gitRoot: string, from: string, to: string, scope: string, cursor: string): Set<string> | null {let listed: string;- try { listed = syncGit(gitRoot, ['--literal-pathspecs', 'diff-tree', '-r', '-z', '--no-renames', '--name-only', from, to, ...(scope ? ['--', scope] : [])]); } catch { return null; }+ try { listed = syncGit(gitRoot, ['diff-tree', '-r', '-z', '--no-renames', '--name-only', from, to, ...(scope ? ['--', ...literalPathspecs([scope])] : [])]); } catch { return null; }const floor = Buffer.from(cursor, 'utf8');const paths = new Set(listed.split('\0').filter(path => path && Buffer.compare(Buffer.from(path, 'utf8'), floor) <= 0));return paths.size > UNINDEXED_REVISIT_CAP ? null : paths;diff --git a/src/core/pglite-engine.ts b/src/core/pglite-engine.tsindex 139a57c8fc..dc33058044 100644--- a/src/core/pglite-engine.ts+++ b/src/core/pglite-engine.ts@@ -171,6 +171,7 @@ import { searchKeywordCJK } from './engine-sql/cjk-search.ts';import * as titlesImpl from './engine-sql/titles.ts';import * as keywordPagesImpl from './engine-sql/keyword-pages.ts';import { applyForwardReferenceBootstrap, pgliteBootstrapTarget } from './engine-sql/bootstrap.ts';+import { assertSchemaNotAhead } from './schema-client-behind.ts';import { wellFormedJson } from './text-safe.ts';import { ENGINE_ROOT } from './engine-root.ts';import { insertEvalCandidate } from './feedback/store.ts';@@ -1167,6 +1168,7 @@ export class PGLiteEngine implements BrainEngine {}const { runMigrations, withSchemaMigrationLock } = await import('./migrate.ts'); // engine-dynamic-import-ok: initSchema only, keeps the ~220 migration modules off every connectawait withSchemaMigrationLock(this, async () => {+ await assertSchemaNotAhead(async (q) => (await this.db.query<Record<string, unknown>>(q)).rows); // #7776await this.applyForwardReferenceBootstrap();await this.db.exec(getPGLiteSchema(dims, model));diff --git a/src/core/postgres-engine.ts b/src/core/postgres-engine.tsindex a88d2376cb..a43ec65a1f 100644--- a/src/core/postgres-engine.ts+++ b/src/core/postgres-engine.ts@@ -133,6 +133,7 @@ import { DELETE_BATCH_SIZE, TRAVERSE_PATH_ROW_CAP, TRAVERSE_WALK_ROW_CAP } fromimport { PageMissingError } from './engine-errors.ts';import { EMBED_SKIP_FILTER_FRAGMENT } from './embed-skip.ts';import { holdSchemaMigrationSessionLock, holdSchemaMigrationTransactionLock } from './postgres-engine/init-schema-lock.ts';+import { assertSchemaNotAhead } from './schema-client-behind.ts';import { isPipelinableSearchRead, SEARCH_JIT_OFF, withSearchJitOff, withSearchSettings, type SearchSettings } from './postgres-engine/search-settings.ts';import { loadKeywordStatementTimeout } from './postgres-engine/keyword-statement-timeout.ts';import { applyPostgresForwardReferenceBootstrap } from './engine-sql/bootstrap.ts';@@ -616,6 +617,7 @@ export class PostgresEngine implements BrainEngine {});try {await withSchemaMigrationLock(this, async () => {+ await assertSchemaNotAhead((q) => pool.unsafe(q)); // #7776: an older binary never replays its schema over a newer one// Another initSchema may have recorded an identity between the read above and this lock: check it again here.const lockedIdentity = storedIdentity ? null : await readStoredEmbeddingIdentity(this);if (lockedIdentity?.model) {diff --git a/src/core/schema-client-behind.ts b/src/core/schema-client-behind.tsnew file mode 100644index 0000000000..a7207598d0--- /dev/null+++ b/src/core/schema-client-behind.ts@@ -0,0 +1,30 @@+/**+ * #7776: initSchema replays the binary's whole schema (CREATE OR REPLACE FUNCTION ...) before runMigrations. On a+ * database a newer gbrain migrated, an older binary's replay reinstalled its own superseded function bodies (the+ * writer-fence guards among them) and then applied nothing. Both engines call this before the replay: a schema version+ * above this binary's newest migration refuses with `client_behind`, so nothing in the schema runs. A database with no+ * config table or no version row (a fresh install) is not behind. Same rule as schema-missing-tables.ts's skip.+ */+import { opError, type OperationError } from './ops/contract.ts';+import { LATEST_SCHEMA_VERSION } from './schema-migrations/latest.generated.ts';++type Query = (sql: string) => Promise<ReadonlyArray<Record<string, unknown>>>;++export function clientBehindError(version: number): OperationError {+ return opError('client_behind',+ `The brain schema is at v${version}, newer than this gbrain binary (v${LATEST_SCHEMA_VERSION}); schema setup refused before replaying this binary's schema, so nothing changed.`,+ 'Upgrade gbrain on this host (gbrain upgrade) to the release that migrated the database or newer, then rerun the command; reads keep working on this binary meanwhile.',+ { fix: { argv: ['gbrain', 'upgrade'], consent: [], actor: 'host_admin', requires_exclusive: false,+ why: "An older binary's schema replay would reinstall superseded function bodies over the newer schema; a current binary replays matching ones.",+ verify: { argv: ['gbrain', 'doctor', '--only', 'schema_version', '--json'] } } });+}++/** Throws `client_behind` when the database's schema version is newer than this binary. */+// engine-sql-ok: a two-statement version probe both engines run on their DDL connection before the schema replay+export async function assertSchemaNotAhead(query: Query): Promise<void> {+ const [probe] = await query(`SELECT to_regclass('config') IS NOT NULL AS present`);+ if (!probe?.present) return;+ const [row] = await query(`SELECT value FROM config WHERE key = 'version'`);+ const version = parseInt(String(row?.value ?? '0'), 10);+ if (version > LATEST_SCHEMA_VERSION) throw clientBehindError(version);+}diff --git a/src/core/storage-config.ts b/src/core/storage-config.tsindex 0a97a93044..67856c47e7 100644--- a/src/core/storage-config.ts+++ b/src/core/storage-config.ts@@ -474,6 +474,7 @@ export const DERIVE_PHASE_DB_ONLY_DEFAULTS: readonly string[] = [// storage.db_only) so installations that do file-back concepts are never// auto-gitignored by manageGitignore.'concepts/',+ // Extract receipts (extract/receipt-writer.ts): derived bookkeeping, never content; the writer refuses a slug that holds content or a file.'extracts/','dream-cycle-summaries/',];diff --git a/src/core/sync-metafile-pages.ts b/src/core/sync-metafile-pages.tsindex d6834bb23a..e43733d8d0 100644--- a/src/core/sync-metafile-pages.ts+++ b/src/core/sync-metafile-pages.ts@@ -9,7 +9,7 @@import { execFileSync } from './spawn.ts';import { closeSync, lstatSync, openSync, readSync } from 'node:fs';import { join } from 'node:path';-import { gitChildEnv } from './git-env.ts';+import { gitChildEnv, literalPathspecs } from './git-env.ts';import { HARDENED_GIT_ARGS, NO_LAZY_FETCH_ENV } from './hardened-git.ts';import { readBlobBytes, type TreeBlob } from './persistence/sync-blobs.ts';import type { BrainEngine } from './engine.ts';@@ -144,7 +144,7 @@ export function levelMetafilePages(mode: MetafilePagesMode, gitRoot: string, com/** The metafile-named blobs of `commit`'s tree under `scope` (one `ls-tree`), Git-root relative. */export function listMetafileNamedBlobs(gitRoot: string, commit: string, scope = ''): Array<{ path: string; oid: string; size: number }> {- const rows = git(gitRoot, ['--literal-pathspecs', 'ls-tree', '-r', '-l', '-z', commit, ...(scope ? ['--', scope] : [])], '', 512 * 1024 ** 2).toString('utf8').split('\0');+ const rows = git(gitRoot, ['ls-tree', '-r', '-l', '-z', commit, ...(scope ? ['--', ...literalPathspecs([scope])] : [])], '', 512 * 1024 ** 2).toString('utf8').split('\0');const out: Array<{ path: string; oid: string; size: number }> = [];for (const row of rows) {const tab = row.indexOf('\t');diff --git a/test/doctor-schema-function-bodies.test.ts b/test/doctor-schema-function-bodies.test.tsnew file mode 100644index 0000000000..f79d7744b3--- /dev/null+++ b/test/doctor-schema-function-bodies.test.ts@@ -0,0 +1,52 @@+/**+ * schema_function_bodies doctor check (#7776): every function this gbrain's schema defines has this gbrain's body.+ * An older gbrain's initSchema replay reinstalls its superseded bodies over a newer schema; the check names each one.+ * Read-only. The cold replay that clears it is in test/init-schema-client-behind.test.ts; Postgres in+ * test/e2e/init-schema-client-behind-postgres.test.ts.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { LATEST_VERSION } from '../src/core/migrate.ts';+import { schemaFunctionBodiesEntry, schemaFunctionBodyDrift } from '../src/commands/doctor/checks/schema-function-bodies.ts';+import type { DoctorContext } from '../src/commands/doctor/context.ts';+import type { Check } from '../src/commands/doctor.ts';+import { installNewerBody } from './helpers/guard-body-drift.ts';++describe('schema_function_bodies doctor check (#7776)', () => {+ let engine: PGLiteEngine;+ const run = async () => ((await schemaFunctionBodiesEntry.run({ engine, progress: { heartbeat: () => {} } } as unknown as DoctorContext)) as Check[])[0]!;+ beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ }, 120_000);+ afterAll(async () => { await engine?.disconnect(); });++ test('a fresh install matches every body', async () => {+ const drift = await schemaFunctionBodyDrift(engine);+ expect(drift.status).toBe('checked');+ if (drift.status !== 'checked') return;+ expect(drift.differing).toEqual([]);+ expect(drift.checked).toBeGreaterThanOrEqual(5);+ expect((await run()).status).toBe('ok');+ });++ test('a drifted guard body fails, names the function and points at the replay', async () => {+ await installNewerBody(engine, 'gbrain_guard_effect_protocol');+ await installNewerBody(engine, 'gbrain_count_git_canonical_sources');+ const check = await run();+ expect(check.status).toBe('fail');+ expect(check.message).toContain('gbrain_count_git_canonical_sources, gbrain_guard_effect_protocol');+ expect(check.details).toMatchObject({ differing: ['gbrain_count_git_canonical_sources', 'gbrain_guard_effect_protocol'] });+ expect(check.fix).toMatchObject({ argv: ['gbrain', 'init', '--migrate-only'] });+ });++ test('skips when the brain is newer than this binary or has migrations pending', async () => {+ await engine.setConfig('version', String(LATEST_VERSION + 1));+ expect(await schemaFunctionBodyDrift(engine)).toEqual({ status: 'skipped', reason: 'client_behind', version: LATEST_VERSION + 1, latest: LATEST_VERSION });+ expect((await run()).status).toBe('ok');+ await engine.setConfig('version', String(LATEST_VERSION - 1));+ expect(await schemaFunctionBodyDrift(engine)).toEqual({ status: 'skipped', reason: 'migrations_pending', version: LATEST_VERSION - 1, latest: LATEST_VERSION });+ await engine.setConfig('version', String(LATEST_VERSION));+ });+});diff --git a/test/e2e/extract-receipt-sealed-7620-postgres.test.ts b/test/e2e/extract-receipt-sealed-7620-postgres.test.tsnew file mode 100644index 0000000000..1bfe1fe1e7--- /dev/null+++ b/test/e2e/extract-receipt-sealed-7620-postgres.test.ts@@ -0,0 +1,3 @@+import { registerPostgresTests } from '../helpers/test-backends.ts';++await registerPostgresTests(() => import('../extract-receipt-sealed-7620.test.ts'));diff --git a/test/e2e/init-schema-client-behind-postgres.test.ts b/test/e2e/init-schema-client-behind-postgres.test.tsnew file mode 100644index 0000000000..dac62087ee--- /dev/null+++ b/test/e2e/init-schema-client-behind-postgres.test.ts@@ -0,0 +1,95 @@+/**+ * #7776 on Postgres: an older binary's initSchema replayed its whole schema (CREATE OR REPLACE FUNCTION ...) over a+ * database a newer gbrain migrated, reinstalling superseded writer-fence guard bodies, then applied nothing. initSchema+ * now refuses with client_behind under the schema lock, before anything in the schema runs, and doctor's+ * schema_function_bodies check names bodies an older replay already reverted. A forced schema run of apply-migrations+ * (runMigrations under the orchestration lease) refuses the same way before its drift repairs touch the newer schema. PGLite (repo-less default):+ * test/init-schema-client-behind.test.ts and test/doctor-schema-function-bodies.test.ts.+ * Run: DATABASE_URL=... bun test test/e2e/init-schema-client-behind-postgres.test.ts+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import postgres from '#postgres';+import { assertSafeE2eDatabaseUrl } from '../helpers/db-guard.ts';+import { PostgresEngine } from '../../src/core/postgres-engine.ts';+import { LATEST_VERSION } from '../../src/core/migrate.ts';+import { schemaFunctionBodyDrift } from '../../src/commands/doctor/checks/schema-function-bodies.ts';+import { forceSchemaRun, functionBody, installNewerBody, installNewerLinkSourceCheck, linkSourceCheckDef, NEWER_BODY_MARKER } from '../helpers/guard-body-drift.ts';++const DATABASE_URL = process.env.DATABASE_URL;+const describeE2E = DATABASE_URL ? describe : describe.skip;+const GUARDS = ['gbrain_count_git_canonical_sources', 'gbrain_guard_effect_protocol', 'gbrain_guard_protocol_activation',+ 'gbrain_guard_request_protocol', 'gbrain_require_managed_writer'];++describeE2E('initSchema on a database newer than the binary (#7776, Postgres)', () => {+ let admin: ReturnType<typeof postgres>;+ let engine: PostgresEngine;+ let url = '';+ const name = `gbrain_test_behind_${randomUUID().replaceAll('-', '')}`;++ beforeAll(async () => {+ assertSafeE2eDatabaseUrl(DATABASE_URL!);+ admin = postgres(DATABASE_URL!, { max: 1, prepare: false, onnotice: () => {} });+ await admin.unsafe(`CREATE DATABASE ${name}`);+ const parsed = new URL(DATABASE_URL!);+ parsed.pathname = `/${name}`;+ url = parsed.toString();+ engine = new PostgresEngine();+ await engine.connect({ database_url: url });+ await engine.initSchema();+ }, 180_000);++ afterAll(async () => {+ await engine?.disconnect();+ if (admin) {+ await admin.unsafe(`DROP DATABASE IF EXISTS ${name} WITH (FORCE)`);+ await admin.end();+ }+ });++ test('a fresh database (no config row) initializes, and every function has this binary\'s body', async () => {+ expect(await engine.getConfig('version')).toBe(String(LATEST_VERSION));+ const drift = await schemaFunctionBodyDrift(engine);+ expect(drift).toMatchObject({ status: 'checked', differing: [] });+ if (drift.status === 'checked') expect(drift.checked).toBeGreaterThanOrEqual(GUARDS.length);+ });++ test('refuses client_behind and leaves the newer guard bodies and the version alone', async () => {+ for (const guard of GUARDS) await installNewerBody(engine, guard);+ await engine.setConfig('version', String(LATEST_VERSION + 1));+ const error = await engine.initSchema().then(() => null, (e: unknown) => e as { code?: string; fix?: { argv?: string[]; actor?: string } });+ for (const guard of GUARDS) expect(await functionBody(engine, guard)).toContain(NEWER_BODY_MARKER);+ expect(error?.code).toBe('client_behind');+ expect(error?.fix).toMatchObject({ argv: ['gbrain', 'upgrade'], actor: 'host_admin' });+ expect(await engine.getConfig('version')).toBe(String(LATEST_VERSION + 1));+ expect(await schemaFunctionBodyDrift(engine)).toEqual({ status: 'skipped', reason: 'client_behind', version: LATEST_VERSION + 1, latest: LATEST_VERSION });+ }, 60_000);++ test('apply-migrations --force-schema (lease held) refuses client_behind and its drift repair leaves the newer constraint alone', async () => {+ await installNewerLinkSourceCheck(engine);+ const before = await linkSourceCheckDef(engine);+ const home = mkdtempSync(join(tmpdir(), 'gbrain-force-schema-'));+ try {+ mkdirSync(join(home, '.gbrain'), { recursive: true });+ writeFileSync(join(home, '.gbrain', 'config.json'), JSON.stringify({ engine: 'postgres', database_url: url }));+ const run = await forceSchemaRun(home);+ expect(run.doc?.code ?? run.out).toBe('client_behind');+ expect(run.exitCode).not.toBe(0);+ } finally {+ rmSync(home, { recursive: true, force: true });+ }+ expect(await linkSourceCheckDef(engine)).toBe(before);+ expect(await engine.getConfig('version')).toBe(String(LATEST_VERSION + 1));+ }, 120_000);++ test('at head doctor names each drifted body, and the replay of this binary (lock released) clears them', async () => {+ await engine.setConfig('version', String(LATEST_VERSION));+ expect(await schemaFunctionBodyDrift(engine)).toMatchObject({ status: 'checked', differing: GUARDS });+ await engine.initSchema();+ for (const guard of GUARDS) expect(await functionBody(engine, guard)).not.toContain(NEWER_BODY_MARKER);+ expect(await schemaFunctionBodyDrift(engine)).toMatchObject({ status: 'checked', differing: [] });+ }, 120_000);+});diff --git a/test/extract-receipt-sealed-7620.test.ts b/test/extract-receipt-sealed-7620.test.tsnew file mode 100644index 0000000000..e4d98260e0--- /dev/null+++ b/test/extract-receipt-sealed-7620.test.ts@@ -0,0 +1,238 @@+/**+ * #7620: extract receipts are sealed in the transaction that writes them, and+ * stay database-only derived bookkeeping.+ *+ * Protects: `writeReceipt` (src/core/extract/receipt-writer.ts) installs the+ * receipt's chunks and seals it at the safe-chunk fence inside the same+ * transaction as the page write, so a remote/MCP search or query on the+ * extracted source no longer reports `safe_index_pending` and doctor's+ * safe_index_pending count stays 0; a failure after the page write rolls back+ * page and chunks together. The receipt writer only writes a never-filed+ * `extract_receipt` page under the derive-phase `extracts/` folder (the+ * `derive_folder` declared class of docs/designs/GIT_CANONICAL_MEMORY.md):+ * it refuses to overwrite a content page or a page with a file in Git. On a+ * repo-less source the receipt is part of the `database_only_source` class; on+ * a repo source it is `derive_folder`, never database_ahead or adopted by a+ * conversion, and a Git-wins re-derive of the page an extraction read leaves+ * the receipt as it was (a receipt names a run and a source, never a page; the+ * source's removal cascades to it).+ * Fails when: the receipt is committed unsealed, the probe is satisfied by+ * exempting pages instead of sealing them (the unsealed content-page control+ * still has to warn), a failed seal leaves a receipt, the writer overwrites+ * content, or a conversion adopts or discards a receipt.+ * PGLite always; Postgres when DATABASE_URL is set+ * (test/e2e/extract-receipt-sealed-7620-postgres.test.ts).+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { execFileSync } from 'node:child_process';+import { existsSync, mkdirSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';+import type { BrainEngine } from '../src/core/engine.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { operations, type OperationContext } from '../src/core/operations.ts';+import { receiptSlug, writeReceipt, type ExtractReceiptInput } from '../src/core/extract/receipt-writer.ts';+import { importFromContent } from '../src/core/import-file.ts';+import { safeIndexPendingCheck } from '../src/commands/doctor/checks/safe-index.ts';+import { SAFE_FENCE_CHUNKER_VERSION } from '../src/core/search/safe-chunks.ts';+import { declaredDatabaseOnly } from '../src/core/persistence/git-gap.ts';+import { censusGitGap } from '../src/commands/sources-git-gap.ts';+import { removeSource } from '../src/core/sources-ops.ts';+import { performManagedSync } from '../src/core/persistence/sync-run.ts';+import { applyGitConversion, planGitConversion } from '../src/core/persistence/git-conversion.ts';+import { managedBrain } from './helpers/managed-brain.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';+import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';++const RECEIPT: Omit<ExtractReceiptInput, 'source_id' | 'run_id'> = {+ kind: 'facts.conversation', round: 'full', extracted_at: '2026-05-27T14:30:00.000Z', total_rows: 3, cost_usd: 0,+ summary: 'Extracted 3 facts from 1/1 eligible pages.',+};+const receipt = (sourceId: string, runId: string): ExtractReceiptInput => ({ ...RECEIPT, source_id: sourceId, run_id: runId });+const note = (title: string, body: string) => `---\ntype: note\ntitle: ${title}\n---\n\n${body}\n`;++/** The engine, with every directly issued statement matching `pattern` throwing, in nested transactions too. */+function failingAt(engine: BrainEngine, pattern: RegExp): BrainEngine {+ return new Proxy(engine, {+ get(target, prop) {+ if (prop === 'executeRaw') return async (sql: string, params?: unknown[]) => {+ if (pattern.test(sql)) throw new Error('injected failure after the receipt page write');+ return target.executeRaw(sql, params);+ };+ if (prop === 'transaction') return (fn: (tx: BrainEngine) => Promise<unknown>, opts?: unknown) =>+ target.transaction(tx => fn(failingAt(tx, pattern)), opts as never);+ const value = Reflect.get(target, prop, target);+ return typeof value === 'function' ? value.bind(target) : value;+ },+ });+}++for (const backend of testBackends()) describe(`[${backend}] #7620 extract receipts are sealed database-only bookkeeping`, () => {+ let engine: BrainEngine;+ let closePostgres: (() => Promise<void>) | undefined;+ let lastMeta: Record<string, any> | null = null;+ const remoteCtx = (sourceId: string): OperationContext => ({+ engine, config: {} as never, logger: { info() {}, warn() {}, error() {} } as never, dryRun: false, remote: true, sourceId,+ emitResponseMeta: (key: string, value: unknown) => { if (key === 'retrieval') lastMeta = value as Record<string, any>; },+ }) as OperationContext;+ const op = (name: string) => operations.find(o => o.name === name)!;+ /** The degraded stages of a remote search and a remote query on the source. */+ const remoteStages = async (sourceId: string) => {+ const stages: string[][] = [];+ for (const [name, params] of [['search', { query: 'walrus' }], ['query', { query: 'walrus', expand: false }]] as const) {+ lastMeta = null;+ await op(name).handler(remoteCtx(sourceId), params);+ expect(lastMeta).not.toBeNull();+ stages.push(((lastMeta!.degraded ?? []) as Array<{ stage: string }>).map(d => d.stage));+ }+ return stages;+ };+ const addSource = (id: string) => engine.executeRaw('INSERT INTO sources(id,name) VALUES($1,$1) ON CONFLICT DO NOTHING', [id]);+ const sealedContent = (sourceId: string) => importFromContent(engine, 'notes/walrus', note('Walrus', 'The walrus pricing note.'), { sourceId, noEmbed: true });+ const pageRow = async (sourceId: string, slug: string) => (await engine.executeRaw<{ id: number; chunker_version: number; sealed: boolean; body: string; type: string }>(+ `SELECT id, chunker_version, text_projection_revision = knowledge_revision AS sealed, compiled_truth AS body, type FROM pages WHERE source_id=$1 AND slug=$2`, [sourceId, slug]))[0];+ const chunkCount = async (sourceId: string, slug: string) => Number((await engine.executeRaw<{ n: number }>(+ 'SELECT count(*)::int AS n FROM content_chunks c JOIN pages p ON p.id=c.page_id WHERE p.source_id=$1 AND p.slug=$2', [sourceId, slug]))[0]!.n);++ beforeAll(async () => {+ if (backend === 'postgres') { const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!); engine = pg.engine; closePostgres = pg.close; }+ else { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); }+ await engine.setConfig('search.mcp_keyword_only', 'true');+ }, 120_000);+ afterAll(async () => { if (closePostgres) await closePostgres(); else await engine.disconnect(); });++ test('repo-less: after an extraction writes its receipt, remote search and query on the source report no safe_index_pending and doctor counts 0', async () => {+ await addSource('source-a');+ await sealedContent('source-a');+ const before = await remoteStages('source-a');+ for (const stages of before) expect(stages).not.toContain('safe_index_pending');+ const { slug } = await writeReceipt(engine, receipt('source-a', 'run-a-0001'));++ const after = await remoteStages('source-a');+ for (const stages of after) expect(stages).not.toContain('safe_index_pending');+ expect(after).toEqual(before);+ const doctor = await safeIndexPendingCheck(engine, ['source-a']);+ expect(doctor).toMatchObject({ status: 'ok', details: { pages_pending: 0, kept_pages: 0 } });+ const row = (await pageRow('source-a', slug))!;+ expect(row.type).toBe('extract_receipt');+ expect(row.chunker_version).toBeGreaterThanOrEqual(SAFE_FENCE_CHUNKER_VERSION);+ expect(row.sealed).toBe(true);+ expect(await chunkCount('source-a', slug)).toBeGreaterThan(0);++ // A source with no checkout: the receipt is in the database_only_source class, nothing is database_ahead.+ const census = await censusGitGap(engine, 'source-a', { sample: 0 });+ expect(census.states).toMatchObject({ database_ahead: 0, undeclared_database_only: 0 });+ expect(census.declared.database_only_source).toBe(2);++ // Re-running the same run and round overwrites the receipt and it stays sealed.+ await writeReceipt(engine, { ...receipt('source-a', 'run-a-0001'), total_rows: 4 });+ expect(await pageRow('source-a', slug)).toMatchObject({ sealed: true });+ expect((await pageRow('source-a', slug))!.chunker_version).toBeGreaterThanOrEqual(SAFE_FENCE_CHUNKER_VERSION);+ expect((await safeIndexPendingCheck(engine, ['source-a'])).details).toMatchObject({ pages_pending: 0 });+ });++ test('negative control: an unsealed content page still raises safe_index_pending and counts in doctor, receipt or not', async () => {+ await addSource('source-b');+ await sealedContent('source-b');+ await writeReceipt(engine, receipt('source-b', 'run-b-0001'));+ await engine.putPage('notes/unsealed', { type: 'note', title: 'Unsealed', compiled_truth: 'A walrus page written without its chunks.', timeline: '' }, { sourceId: 'source-b' });+ expect((await pageRow('source-b', 'notes/unsealed'))!.chunker_version).toBeLessThan(SAFE_FENCE_CHUNKER_VERSION);+ for (const stages of await remoteStages('source-b')) expect(stages).toContain('safe_index_pending');+ expect(await safeIndexPendingCheck(engine, ['source-b'])).toMatchObject({ status: 'warn', details: { pages_pending: 1 } });+ });++ test('a failure after the receipt page write rolls back the page and its chunks together', async () => {+ await addSource('source-c');+ const input = receipt('source-c', 'run-c-0001');+ await expect(writeReceipt(failingAt(engine, /SET chunker_version=/), input)).rejects.toThrow('injected failure');+ expect(await pageRow('source-c', receiptSlug(input))).toBeUndefined();+ expect(await chunkCount('source-c', receiptSlug(input))).toBe(0);+ });++ test('the receipt writer writes only a never-filed receipt: it refuses to overwrite a content page or a page with a file', async () => {+ await addSource('source-d');+ const filed = receipt('source-d', 'd1-run');+ const filedSlug = receiptSlug(filed);+ await engine.putPage(filedSlug, { type: 'extract_receipt', title: 'Committed', compiled_truth: 'A receipt file someone committed to Git.', timeline: '',+ source_path: `${filedSlug}.md` }, { sourceId: 'source-d' });+ await expect(writeReceipt(engine, filed)).rejects.toThrow(/receipt/);+ expect((await pageRow('source-d', filedSlug))!.body).toBe('A receipt file someone committed to Git.');++ const content = receipt('source-d', 'd2-run');+ const contentSlug = receiptSlug(content);+ await engine.putPage(contentSlug, { type: 'note', title: 'Hand-written', compiled_truth: 'A note a person wrote under extracts/.', timeline: '' }, { sourceId: 'source-d' });+ await expect(writeReceipt(engine, content)).rejects.toThrow(/receipt/);+ expect((await pageRow('source-d', contentSlug))!).toMatchObject({ type: 'note', body: 'A note a person wrote under extracts/.' });++ // What it does write is declared database-only on a repo source: the derive-phase folder class.+ const { page } = await writeReceipt(engine, receipt('source-d', 'd3-run'));+ const repoPolicy = { mirror: false, dbOnly: () => false, ignored: new Set<string>() };+ expect(declaredDatabaseOnly({ ...page, database_only_reason: null }, `${page.slug}.md`, repoPolicy)).toBe('derive_folder');+ });++ test('removing the source removes its receipts: a receipt never outlives what it describes', async () => {+ await addSource('source-e');+ const { slug } = await writeReceipt(engine, receipt('source-e', 'run-e-0001'));+ expect(await pageRow('source-e', slug)).toBeDefined();+ await removeSource(engine, { id: 'source-e', yes: true, confirmDestructive: true } as never);+ expect(await pageRow('source-e', slug)).toBeUndefined();+ expect(await chunkCount('source-e', slug)).toBe(0);+ });+});++const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, '-c', 'commit.gpgsign=false', ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();+const OPTS = { sourceId: 'default', noPull: true, noEmbed: true, noExtract: true };++for (const backend of testBackends()) describe(`[${backend}] #7620 a repo source: receipts are derive_folder bookkeeping through conversion and Git-wins re-derives`, () => {+ const databaseUrl = backend === 'postgres' ? requirePostgresTestDatabase() : undefined;+ let receiptPath = '';++ test('a conversion neither adopts nor discards the receipt, and a Git-wins re-derive of the page it read leaves it sealed and unchanged', () => managedBrain(async ({ engine, root }) => {+ const slug = receiptPath;+ const receiptRow = async () => (await engine.executeRaw<{ revision: string; sealed: boolean; chunker_version: number; source_path: string | null }>(+ `SELECT knowledge_revision::text AS revision, text_projection_revision = knowledge_revision AS sealed, chunker_version, source_path+ FROM pages WHERE source_id='default' AND slug=$1 AND deleted_at IS NULL`, [slug]))[0];+ expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');+ const written = (await receiptRow())!;+ expect(written).toMatchObject({ sealed: true, source_path: null });+ expect(written.chunker_version).toBeGreaterThanOrEqual(SAFE_FENCE_CHUNKER_VERSION);++ // Git moves the page the extraction read; Git wins and the page is re-derived from the committed blob.+ writeFileSync(join(root, 'notes/alice-example.md'), note('Alice example', 'The committed edit of the conversation.'));+ git(root, 'commit', '-qam', 'edit the conversation');+ const census = await censusGitGap(engine, 'default', { sample: 20 });+ expect(census.states).toMatchObject({ database_ahead: 0, undeclared_database_only: 0 });+ expect(census.declared.derive_folder).toBe(1);+ const { preview } = await planGitConversion(engine, 'default');+ expect(preview).toMatchObject({ adopt: { count: 0 }, discard: { count: 0 }, declared: { by: { derive_folder: 1 } }, git_wins: { count: 1 } });+ expect(preview.adopt.sample).not.toContain(`${slug}.md`);++ const result = await applyGitConversion(engine, 'default', preview.preview_hash, { noEmbed: true, noExtract: true });+ expect(result).toMatchObject({ status: 'converted', after: { remaining: 0, strict: true } });+ expect((await engine.executeRaw<{ body: string }>("SELECT compiled_truth AS body FROM pages WHERE source_id='default' AND slug='notes/alice-example'"))[0]!.body)+ .toContain('The committed edit of the conversation.');+ expect(await receiptRow()).toEqual(written);+ expect(existsSync(join(root, `${slug}.md`))).toBe(false);+ expect(git(root, 'ls-files', 'extracts')).toBe('');+ // A receipt names its run and source, never a page: no edge ties it to the re-derived page.+ expect((await engine.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM links l JOIN pages p ON p.id IN (l.from_page_id, l.to_page_id)+ WHERE p.source_id='default' AND p.slug=$1`, [slug]))[0]!.n).toBe(0);+ expect((await safeIndexPendingCheck(engine, ['default'])).details).toMatchObject({ pages_pending: 0 });++ // A later strict pass that re-derives the page again still leaves the receipt as it was.+ writeFileSync(join(root, 'notes/alice-example.md'), note('Alice example', 'A second committed edit.'));+ git(root, 'commit', '-qam', 'edit again');+ await performManagedSync(engine, OPTS);+ expect(await receiptRow()).toEqual(written);+ expect((await censusGitGap(engine, 'default', { sample: 0 })).declared.derive_folder).toBe(1);+ }, { databaseUrl, setup: async ({ engine, root }) => {+ mkdirSync(join(root, 'notes'), { recursive: true }); git(root, 'init', '-q');+ git(root, 'config', 'user.name', 'Example Writer'); git(root, 'config', 'user.email', '[email protected]');+ writeFileSync(join(root, 'notes/alice-example.md'), note('Alice example', 'The committed conversation.'));+ git(root, 'add', '-A'); git(root, 'commit', '-qm', 'notes');+ // The extraction ran while the brain was unmanaged (receipts are written on unmanaged brains only).+ receiptPath = (await writeReceipt(engine, receipt('default', 'run-default-1'))).slug;+ // Sealed by its own write, before any sync or repair could re-seal it.+ expect((await engine.executeRaw<{ sealed: boolean }>(`SELECT chunker_version >= ${SAFE_FENCE_CHUNKER_VERSION} AND text_projection_revision = knowledge_revision AS sealed+ FROM pages WHERE source_id='default' AND slug=$1`, [receiptPath]))[0]!.sealed).toBe(true);+ } }), 240_000);+});diff --git a/test/fixtures/goldens/doctor/content-pglite-json.json b/test/fixtures/goldens/doctor/content-pglite-json.jsonindex 7b9a5d1f5d..8d9b42a741 100644--- a/test/fixtures/goldens/doctor/content-pglite-json.json+++ b/test/fixtures/goldens/doctor/content-pglite-json.json@@ -1153,6 +1153,13 @@"name": "schema_missing_tables","status": "ok"},+ {+ "category": "meta",+ "elapsed_ms": "<volatile>",+ "message": "Every function this gbrain's schema defines has its body",+ "name": "schema_function_bodies",+ "status": "ok"+ },{"category": "ops","elapsed_ms": "<volatile>",diff --git a/test/fixtures/goldens/doctor/hot-checks-pglite-json.json b/test/fixtures/goldens/doctor/hot-checks-pglite-json.jsonindex 1a48759622..e57caa69ce 100644--- a/test/fixtures/goldens/doctor/hot-checks-pglite-json.json+++ b/test/fixtures/goldens/doctor/hot-checks-pglite-json.json@@ -1224,6 +1224,13 @@"name": "schema_missing_tables","status": "ok"},+ {+ "category": "meta",+ "elapsed_ms": "<volatile>",+ "message": "Every function this gbrain's schema defines has its body",+ "name": "schema_function_bodies",+ "status": "ok"+ },{"category": "ops","elapsed_ms": "<volatile>",@@ -6347,6 +6354,13 @@"name": "schema_missing_tables","status": "ok"},+ {+ "category": "meta",+ "elapsed_ms": "<volatile>",+ "message": "Every function this gbrain's schema defines has its body",+ "name": "schema_function_bodies",+ "status": "ok"+ },{"category": "ops","elapsed_ms": "<volatile>",diff --git a/test/fixtures/goldens/doctor/hot-checks-postgres-json.json b/test/fixtures/goldens/doctor/hot-checks-postgres-json.jsonindex ffab954553..572010f1c4 100644--- a/test/fixtures/goldens/doctor/hot-checks-postgres-json.json+++ b/test/fixtures/goldens/doctor/hot-checks-postgres-json.json@@ -1227,6 +1227,13 @@"name": "schema_missing_tables","status": "ok"},+ {+ "category": "meta",+ "elapsed_ms": "<volatile>",+ "message": "Every function this gbrain's schema defines has its body",+ "name": "schema_function_bodies",+ "status": "ok"+ },{"category": "ops","elapsed_ms": "<volatile>",@@ -6358,6 +6365,13 @@"name": "schema_missing_tables","status": "ok"},+ {+ "category": "meta",+ "elapsed_ms": "<volatile>",+ "message": "Every function this gbrain's schema defines has its body",+ "name": "schema_function_bodies",+ "status": "ok"+ },{"category": "ops","elapsed_ms": "<volatile>",diff --git a/test/fixtures/goldens/doctor/json-pglite-degraded.json b/test/fixtures/goldens/doctor/json-pglite-degraded.jsonindex 33216de7b1..0a7ee65bc2 100644--- a/test/fixtures/goldens/doctor/json-pglite-degraded.json+++ b/test/fixtures/goldens/doctor/json-pglite-degraded.json@@ -1066,6 +1066,13 @@"name": "schema_missing_tables","status": "ok"},+ {+ "category": "meta",+ "elapsed_ms": "<volatile>",+ "message": "Every function this gbrain's schema defines has its body",+ "name": "schema_function_bodies",+ "status": "ok"+ },{"category": "ops","elapsed_ms": "<volatile>",diff --git a/test/fixtures/goldens/doctor/json-pglite-fresh.json b/test/fixtures/goldens/doctor/json-pglite-fresh.jsonindex 932946be75..1935ac19ac 100644--- a/test/fixtures/goldens/doctor/json-pglite-fresh.json+++ b/test/fixtures/goldens/doctor/json-pglite-fresh.json@@ -1113,6 +1113,13 @@"name": "schema_missing_tables","status": "ok"},+ {+ "category": "meta",+ "elapsed_ms": "<volatile>",+ "message": "Every function this gbrain's schema defines has its body",+ "name": "schema_function_bodies",+ "status": "ok"+ },{"category": "ops","elapsed_ms": "<volatile>",diff --git a/test/fixtures/goldens/doctor/json-postgres-fresh.json b/test/fixtures/goldens/doctor/json-postgres-fresh.jsonindex 038abf31ee..52cebe9019 100644--- a/test/fixtures/goldens/doctor/json-postgres-fresh.json+++ b/test/fixtures/goldens/doctor/json-postgres-fresh.json@@ -1116,6 +1116,13 @@"name": "schema_missing_tables","status": "ok"},+ {+ "category": "meta",+ "elapsed_ms": "<volatile>",+ "message": "Every function this gbrain's schema defines has its body",+ "name": "schema_function_bodies",+ "status": "ok"+ },{"category": "ops","elapsed_ms": "<volatile>",diff --git a/test/fixtures/goldens/doctor/registry-build-checks.json b/test/fixtures/goldens/doctor/registry-build-checks.jsonindex e159fdc11e..764e63fe5c 100644--- a/test/fixtures/goldens/doctor/registry-build-checks.json+++ b/test/fixtures/goldens/doctor/registry-build-checks.json@@ -445,6 +445,10 @@"category": "meta","name": "schema_missing_tables"},+ {+ "category": "meta",+ "name": "schema_function_bodies"+ },{"category": "ops","name": "rls_event_trigger"diff --git a/test/git-commit-push-door-wave2.test.ts b/test/git-commit-push-door-wave2.test.tsnew file mode 100644index 0000000000..80ebf7eab4--- /dev/null+++ b/test/git-commit-push-door-wave2.test.ts@@ -0,0 +1,266 @@+/**+ * GBRA-230 lane G: the commit-push door.+ * Protects:+ * - #7752: `gbrain git commit-push --dry-run` runs the real run's path checks. On a non-cone sparse checkout a path+ * outside the sparse-checkout definition refuses `commit_paths_invalid` with the real run's fix text, takes no lock+ * and writes nothing (red before: the dry run exited 0 and listed the path the real run refuses). Cone mode and a+ * checkout without sparse checkout keep answering what their real run does. The dry run also refuses what the real+ * run refuses before staging: a path outside gbrain.sourceRoot (red before: exit 0), another writer's staged file+ * under a named directory, a staged rename's other side outside the root; its envelope equals the real run's.+ * - #7984: a tracked file deleted or modified under a wildcard ignore (`*`), the deletion on disk only or already+ * staged, commits and pushes through the door (master's staging since 68da83db4f), and the dry run agrees: a named+ * ignored new file, or a path that matches nothing, refuses in both runs, and a refusal leaves the index as it was.+ * (#7753's --untrack cases live in test/git-commit-push-untrack-gst2519.test.ts.)+ * - #7793 item 2: the fix and verify commands printed for a staged file read each path literally.+ * Repo-less: commit-push needs a checkout, so nothing here reaches a brain without one.+ * Seams: none; real repositories and a bare remote, the real CLI for the flags.+ */+import { afterEach, describe, expect, test } from 'bun:test';+import { execFileSync } from 'node:child_process';+import { existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, unlinkSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { dirname, join } from 'node:path';+import { commitAndPush } from '../src/core/git/commit-push.ts';+import { commitThroughDoor } from '../src/core/persistence/git-door.ts';+import { sha256 } from '../src/core/persistence/digest.ts';+import { gitChildEnv } from '../src/core/git-env.ts';+import { runCli } from './helpers/cli-spawn.ts';++const env = gitChildEnv();+const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], env }).trim();+const dirs: string[] = [];+const scratch = (name: string) => { const dir = realpathSync(mkdtempSync(join(tmpdir(), `gbrain-door2-${name}-`))); dirs.push(dir); return dir; };+afterEach(() => { for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }); });++function put(root: string, path: string, body: string): void {+ mkdirSync(dirname(join(root, path)), { recursive: true });+ writeFileSync(join(root, path), body);+}++/** A checkout on main with `files` committed, its own core.hooksPath, and (unless `remote` is false) a bare origin it pushed to. */+function checkout(files: Record<string, string>, remote = true): { root: string; bare: string | null; hooks: string } {+ const dir = scratch('repo');+ const root = join(dir, 'work');+ const hooks = join(dir, 'hooks');+ git(dir, 'init', '-q', '-b', 'main', root);+ git(root, 'config', 'user.name', 'Example Writer'); git(root, 'config', 'user.email', '[email protected]');+ git(root, 'config', 'core.hooksPath', hooks);+ for (const [path, body] of Object.entries({ 'seed.md': 'seed\n', ...files })) put(root, path, body);+ git(root, 'add', '-A'); git(root, 'commit', '-qm', 'seed');+ if (!remote) return { root, bare: null, hooks };+ const bare = join(dir, 'origin.git');+ git(dir, 'init', '-q', '--bare', '-b', 'main', bare);+ git(root, 'remote', 'add', 'origin', bare);+ git(root, 'push', '-q', '-u', 'origin', 'main');+ return { root, bare, hooks };+}++const cli = (root: string, args: string[], extra: Record<string, string> = {}) =>+ runCli(['git', 'commit-push', '--path', root, '--json', ...args], { home: scratch('home'), env: { GBRAIN_GIT_ALLOW_FILE_TRANSPORT: '1', ...extra } });+const status = (root: string) => execFileSync('git', ['-C', root, 'status', '--porcelain', '--untracked-files=all'], { encoding: 'utf8', env }).split('\n').filter(Boolean).sort();+const changed = (root: string, rev = 'HEAD') => git(root, 'diff-tree', '-r', '--no-commit-id', '--no-renames', '--name-status', '-z', rev).split('\0').filter(Boolean);+const refusalOf = (fn: () => unknown): { code?: string; message?: string; fix?: { argv: string[] } } => {+ try { fn(); } catch (e) { return e as { code?: string; message?: string }; }+ throw new Error('expected a refusal');+};+const indexBytes = (root: string) => readFileSync(join(root, '.git', 'index')).toString('base64');++describe('#7752: --dry-run runs the real run\'s path checks', () => {+ /** notes/a and notes/b committed, then a sparse checkout of notes/a only, and a new file in each. */+ function sparse(cone: boolean): { root: string; bare: string } {+ const { root, bare } = checkout({ 'notes/a/one.md': 'one\n', 'notes/b/two.md': 'two\n' });+ if (cone) git(root, 'sparse-checkout', 'set', '--cone', 'notes/a');+ else git(root, 'sparse-checkout', 'set', '--no-cone', '/notes/a/');+ put(root, 'notes/b/new.md', 'outside the sparse definition\n');+ put(root, 'notes/a/new.md', 'inside the sparse definition\n');+ return { root, bare: bare! };+ }++ for (const cone of [false, true]) {+ test(`${cone ? 'cone' : 'non-cone'} sparse checkout: a path outside the definition refuses like the real run; no lock, nothing written`, async () => {+ const { root, bare } = sparse(cone);+ const head = git(root, 'rev-parse', 'HEAD');+ const index = indexBytes(root);+ const preview = await cli(root, ['--dry-run', '-m', 'test', '--', 'notes/b/new.md']);+ expect(preview.exitCode).toBe(1);+ const previewed = JSON.parse(preview.stdout) as { code: string; message: string; suggestion: string };+ expect(previewed.code).toBe('commit_paths_invalid');+ expect(previewed.suggestion).toContain('outside of your sparse-checkout definition');+ expect(existsSync(join(root, '.git', 'brain-commit.lock'))).toBe(false);+ expect(indexBytes(root)).toBe(index);+ expect(git(root, 'rev-parse', 'HEAD')).toBe(head);++ const real = await cli(root, ['-m', 'test', '--', 'notes/b/new.md']);+ expect(real.exitCode).toBe(1);+ expect(JSON.parse(real.stdout)).toMatchObject({ code: 'commit_paths_invalid', message: previewed.message, suggestion: previewed.suggestion });+ expect(git(bare, 'rev-parse', 'main')).toBe(head);++ const inside = await cli(root, ['--dry-run', '-m', 'test', '--', 'notes/a/new.md']);+ expect(inside.exitCode).toBe(0);+ expect(JSON.parse(inside.stdout)).toMatchObject({ dry_run: true, mode: 'commit-push', paths: ['notes/a/new.md'] });+ expect((await cli(root, ['-m', 'test', '--', 'notes/a/new.md'])).exitCode).toBe(0);+ expect(git(bare, 'show', 'main:notes/a/new.md')).toBe('inside the sparse definition');+ });+ }++ test('a checkout without sparse checkout: the dry run lists the path and the real run commits it; a held index lock does not stop the preview', async () => {+ const { root, bare } = checkout({});+ put(root, 'notes/b/new.md', 'new\n');+ writeFileSync(join(root, '.git', 'index.lock'), '');+ const preview = await cli(root, ['--dry-run', '-m', 'test', '--', 'notes/b/new.md']);+ expect(preview.exitCode).toBe(0);+ expect(JSON.parse(preview.stdout)).toMatchObject({ dry_run: true, paths: ['notes/b/new.md'] });+ unlinkSync(join(root, '.git', 'index.lock'));+ expect(status(root)).toEqual(['?? notes/b/new.md']);+ expect((await cli(root, ['-m', 'test', '--', 'notes/b/new.md'])).exitCode).toBe(0);+ expect(git(bare!, 'show', 'main:notes/b/new.md')).toBe('new');+ });+});++describe('#7752: the dry run refuses what the real run refuses before staging (source roots, staged files, rename partners)', () => {+ /** A checkout whose source root (git config gbrain.sourceRoot) is brain/, with x.md outside it. */+ function rooted(): { root: string; bare: string } {+ const { root, bare } = checkout({ 'x.md': 'outside v1\n', 'brain/page.md': 'page v1\n' });+ git(root, 'config', '--add', 'gbrain.sourceRoot', 'brain');+ return { root, bare: bare! };+ }+ const envelope = async (root: string, args: string[]) => { const r = await cli(root, args); return { exit: r.exitCode, body: JSON.parse(r.stdout) as Record<string, unknown> }; };++ test('a path outside the source root, in commit and --untrack modes: the dry-run envelope equals the real run\'s; --allow-outside-source-root lifts both', async () => {+ const { root, bare } = rooted();+ put(root, 'x.md', 'outside edit\n');+ const head = git(root, 'rev-parse', 'HEAD');+ for (const mode of [[], ['--untrack']]) {+ const preview = await envelope(root, ['--dry-run', ...mode, '-m', 'm', '--', 'x.md']);+ expect(preview).toMatchObject({ exit: 1, body: { code: 'commit_outside_source_root' } });+ expect(await envelope(root, [...mode, '-m', 'm', '--', 'x.md'])).toEqual(preview);+ }+ expect(git(bare, 'rev-parse', 'main')).toBe(head);+ expect(status(root)).toEqual([' M x.md']);+ expect(await envelope(root, ['--dry-run', '--allow-outside-source-root', '-m', 'm', '--', 'x.md'])).toMatchObject({ exit: 0, body: { dry_run: true, paths: ['x.md'] } });+ expect((await envelope(root, ['--allow-outside-source-root', '-m', 'm', '--', 'x.md'])).exit).toBe(0);+ expect(git(bare, 'show', 'main:x.md')).toBe('outside edit');+ });++ test('a staged rename whose other side is outside the source root, and a file another writer staged under a named directory', async () => {+ const { root } = rooted();+ git(root, 'mv', 'x.md', 'brain/x.md');+ const rename = await envelope(root, ['--dry-run', '-m', 'm', '--', 'brain/x.md']);+ expect(rename).toMatchObject({ exit: 1, body: { code: 'commit_outside_source_root', message: expect.stringContaining('A staged rename would commit x.md') } });+ expect(await envelope(root, ['-m', 'm', '--', 'brain/x.md'])).toEqual(rename);+ expect(status(root)).toEqual(['R x.md -> brain/x.md']);++ git(root, 'mv', 'brain/x.md', 'x.md');+ put(root, 'brain/theirs.md', 'staged by another writer\n'); git(root, 'add', 'brain/theirs.md');+ put(root, 'brain/page.md', 'mine\n');+ const swept = await envelope(root, ['--dry-run', '-m', 'm', '--', 'brain']);+ expect(swept).toMatchObject({ exit: 1, body: { code: 'commit_prestaged_paths' } });+ expect(await envelope(root, ['-m', 'm', '--', 'brain'])).toEqual(swept);+ expect(status(root)).toEqual([' M brain/page.md', 'A brain/theirs.md']);+ });+});++describe('#7793 item 2: printed fix and verify commands read each path literally', () => {+ test('commit-push\'s commit_prestaged_paths fix unstages only the swept files, not the files their glob or magic reading names', () => {+ const { root } = checkout({ 'daily/a.md': 'a\n', 'daily/b.md': 'b\n', 'd/theirs.md': 'decoy\n' });+ put(root, 'daily/[ab].md', 'staged by another writer\n');+ put(root, ':d/theirs.md', 'staged by another writer\n');+ put(root, 'daily/a.md', 'a staged\n'); put(root, 'daily/b.md', 'b staged\n'); put(root, 'd/theirs.md', 'decoy staged\n');+ git(root, 'add', '--', ':(literal)daily/[ab].md', ':(literal):d/theirs.md', 'daily/a.md', 'daily/b.md', 'd/theirs.md');+ const refused = refusalOf(() => commitAndPush({ repo: root, cwd: root, paths: ['daily', ':d', 'daily/a.md', 'daily/b.md'], message: 'm' }));+ expect(refused.code).toBe('commit_prestaged_paths');+ const [cmd, ...args] = refused.fix!.argv;+ execFileSync(cmd, args, { env, stdio: 'ignore' });+ expect(status(root)).toEqual(['?? :d/theirs.md', '?? daily/[ab].md', 'M d/theirs.md', 'M daily/a.md', 'M daily/b.md']);+ });++ test('the door\'s git_index_conflict fix unstages only the targets, and its verify reads only the targets', async () => {+ const { root } = checkout({ 'notes/[ab].md': 'literal\n', 'notes/a.md': 'a\n', ':lead.md': 'colon\n', 'lead.md': 'decoy\n' }, false);+ for (const path of ['notes/[ab].md', 'notes/a.md', ':lead.md', 'lead.md']) put(root, path, `${path} staged\n`);+ git(root, 'add', '-A');+ for (const path of ['notes/[ab].md', ':lead.md']) put(root, path, `${path} door\n`);+ const error = await commitThroughDoor(root, ['notes/[ab].md', ':lead.md'].map(path => ({ path: join(root, path), planned: sha256(`${path} door\n`) })))+ .then(() => null, (e: { code?: string; fix?: { argv: string[]; verify: { argv: string[] } } }) => e);+ expect(error?.code).toBe('git_index_conflict');+ const run = (argv: string[]) => execFileSync(argv[0], argv.slice(1), { env, encoding: 'utf8' }).trim();+ expect(run(error!.fix!.verify.argv).split('\n').sort()).toEqual([':lead.md', 'notes/[ab].md']);+ run(error!.fix!.argv);+ expect(run(error!.fix!.verify.argv)).toBe('');+ expect(status(root)).toEqual([' M :lead.md', ' M notes/[ab].md', 'M lead.md', 'M notes/a.md']);+ });+});++describe('#7984: a tracked deletion or modification under a wildcard ignore publishes; ignored new files still refuse', () => {+ /** art/x.txt and art/y.txt committed, then a committed .gitignore that ignores everything but itself. */+ function ignoredAll(): { root: string; bare: string } {+ const { root, bare } = checkout({ 'art/x.txt': 'x\n', 'art/y.txt': 'y\n' });+ put(root, '.gitignore', '*\n!.gitignore\n');+ git(root, 'add', '.gitignore'); git(root, 'commit', '-qm', 'ignore everything'); git(root, 'push', '-q', 'origin', 'main');+ return { root, bare: bare! };+ }++ for (const staged of [false, true]) {+ test(`a deletion ${staged ? 'already staged' : 'on disk only'}: the dry run and the real run agree, and the commit carries only the deletion`, async () => {+ const { root, bare } = ignoredAll();+ if (staged) git(root, 'rm', '-q', 'art/x.txt'); else unlinkSync(join(root, 'art/x.txt'));+ const before = indexBytes(root);+ const preview = await cli(root, ['--dry-run', '-m', 'drop x', '--', 'art/x.txt']);+ expect(preview.exitCode).toBe(0);+ expect(indexBytes(root)).toBe(before);+ const run = await cli(root, ['-m', 'drop x', '--', 'art/x.txt']);+ expect(run.exitCode).toBe(0);+ expect(changed(bare, 'main')).toEqual(['D', 'art/x.txt']);+ expect(git(root, 'rev-parse', 'HEAD')).toBe(git(bare, 'rev-parse', 'main'));+ expect(git(bare, 'show', 'main:art/y.txt')).toBe('y');+ expect(status(root)).toEqual([]);+ });+ }++ test('a tracked modification: the dry run and the real run agree, and the commit carries only the modification', async () => {+ const { root, bare } = ignoredAll();+ put(root, 'art/y.txt', 'y edited\n');+ put(root, 'art/new.txt', 'ignored and untracked\n');+ const before = indexBytes(root);+ const preview = await cli(root, ['--dry-run', '-m', 'edit y', '--', 'art/y.txt']);+ expect(preview.exitCode).toBe(0);+ expect(JSON.parse(preview.stdout)).toMatchObject({ dry_run: true, paths: ['art/y.txt'] });+ expect(indexBytes(root)).toBe(before);+ expect((await cli(root, ['-m', 'edit y', '--', 'art/y.txt'])).exitCode).toBe(0);+ expect(changed(bare, 'main')).toEqual(['M', 'art/y.txt']);+ expect(git(bare, 'show', 'main:art/y.txt')).toBe('y edited');+ expect(git(root, 'ls-files').split('\n')).toEqual(['.gitignore', 'art/x.txt', 'art/y.txt', 'seed.md']);+ expect(status(root)).toEqual([]);+ });++ test('an ignored new file named beside the deletion refuses in both runs; the index, HEAD and remote stay as they were', async () => {+ const { root, bare } = ignoredAll();+ unlinkSync(join(root, 'art/x.txt'));+ put(root, 'art/new.txt', 'ignored and untracked\n');+ const head = git(root, 'rev-parse', 'HEAD');+ const before = git(root, 'ls-files', '-s');+ for (const paths of [['art/new.txt'], ['art/x.txt', 'art/new.txt']]) {+ const preview = await cli(root, ['--dry-run', '-m', 'm', '--', ...paths]);+ const run = await cli(root, ['-m', 'm', '--', ...paths]);+ expect(preview.exitCode).toBe(1);+ expect(JSON.parse(preview.stdout)).toMatchObject({ code: 'commit_paths_invalid' });+ expect(JSON.parse(run.stdout)).toEqual(JSON.parse(preview.stdout));+ expect(git(root, 'ls-files', '-s')).toBe(before);+ expect(status(root)).toEqual([' D art/x.txt']);+ }+ expect(git(root, 'rev-parse', 'HEAD')).toBe(head);+ expect(git(bare, 'rev-parse', 'main')).toBe(head);+ expect(git(root, 'ls-files').split('\n')).toEqual(['.gitignore', 'art/x.txt', 'art/y.txt', 'seed.md']);+ });++ test('a path that is not on disk, staged or in the last commit refuses before anything changes', async () => {+ const { root, bare } = ignoredAll();+ const head = git(root, 'rev-parse', 'HEAD');+ for (const mode of [['--dry-run'], []]) {+ const r = await cli(root, [...mode, '-m', 'm', '--', 'art/never.txt']);+ expect(r.exitCode).toBe(1);+ expect(JSON.parse(r.stdout)).toMatchObject({ code: 'commit_paths_invalid' });+ }+ expect(git(bare, 'rev-parse', 'main')).toBe(head);+ expect(status(root)).toEqual([]);+ });+});diff --git a/test/git-door-planned-state.test.ts b/test/git-door-planned-state.test.tsindex 1356f0b1d0..3c1fea5125 100644--- a/test/git-door-planned-state.test.ts+++ b/test/git-door-planned-state.test.ts@@ -291,7 +291,7 @@ describe('door plumbing: the planned state', () => {put(root, 'notes/b.md', 'b\n');const error = await refusal(publishAt(root, 'notes/b.md', 'door\n')) as { code?: string; fix?: { argv?: string[]; verify?: { argv?: string[] } } };expect(error).toMatchObject({ code: 'git_index_conflict' });- expect(error.fix).toMatchObject({ argv: ['git', '-C', root, 'restore', '--staged', '--', 'notes/b.md'], verify: { argv: ['git', '-C', root, 'diff', '--cached', '--name-only', '--', 'notes/b.md'] } });+ expect(error.fix).toMatchObject({ argv: ['git', '-C', root, 'restore', '--staged', '--', ':(literal)notes/b.md'], verify: { argv: ['git', '-C', root, 'diff', '--cached', '--name-only', '--', ':(literal)notes/b.md'] } });expect(git(root, 'rev-parse', 'HEAD')).toBe(head);expect(git(root, 'rev-parse', ':notes/b.md')).toBe(staged);git(root, 'restore', '--staged', '--', 'notes/b.md');diff --git a/test/git-env-guard.test.ts b/test/git-env-guard.test.tsindex cb3e123688..e85c969b3d 100644--- a/test/git-env-guard.test.ts+++ b/test/git-env-guard.test.ts@@ -74,6 +74,36 @@ test('the guard catches implicit and explicit process.env inheritance and acceptexpect(unscrubbedGitSpawns('x.ts', "execSync(`git ${args.join(' ')}`, { env: gitChildEnv(), cwd: root });")).toEqual([]);});+/**+ * #7793: Git exports a global pathspec switch (`--literal-pathspecs` and friends, or GIT_LITERAL_PATHSPECS and friends in a+ * spawn's env) to every hook, textconv and filter helper the command starts, so a pathspec gbrain builds is made literal+ * per path with `literalPathspecs` instead. `git-env.ts` names the switches to strip them from the environment, and a step may+ * pin one off (`GIT_GLOB_PATHSPECS: '0'`).+ */+const GLOBAL_PATHSPEC_SWITCH = /--(?:literal|glob|noglob|icase)-pathspecs\b|\bGIT_(?:LITERAL|GLOB|NOGLOB|ICASE)_PATHSPECS\b(?!\s*:\s*'0')/;++export function globalPathspecSwitches(path: string, source: string): string[] {+ return source.split('\n').flatMap((line, i) => /^\s*(\*|\/\/|\/\*)/.test(line) || !GLOBAL_PATHSPEC_SWITCH.test(line) ? [] : [`${path}:${i + 1}`]);+}++test('no Git call under src passes a global pathspec switch', () => {+ const offenders = files(join(ROOT, 'src')).flatMap(file => {+ const rel = relative(ROOT, file).split('\\').join('/');+ return rel === 'src/core/git-env.ts' ? [] : globalPathspecSwitches(rel, readFileSync(file, 'utf8'));+ });+ expect(offenders).toEqual([]);+});++test('the global-switch guard catches flags and env spellings and skips comments', () => {+ expect(globalPathspecSwitches('x.ts', "execFileSync('git', ['--literal-pathspecs', 'log', '-p'], opts);")).toEqual(['x.ts:1']);+ expect(globalPathspecSwitches('x.ts', "spawn('git', ['-C', root, '--glob-pathspecs', 'ls-files']);")).toEqual(['x.ts:1']);+ expect(globalPathspecSwitches('x.ts', "const env = gitChildEnv({ GIT_LITERAL_PATHSPECS: '1' });")).toEqual(['x.ts:1']);+ expect(globalPathspecSwitches('x.ts', "const env = { GIT_GLOB_PATHSPECS: '0', GIT_ICASE_PATHSPECS: '0' };")).toEqual([]);+ expect(globalPathspecSwitches('x.ts', "const a = 1;\nargs.push('--icase-pathspecs');")).toEqual(['x.ts:2']);+ expect(globalPathspecSwitches('x.ts', "// never --literal-pathspecs here\n/** or GIT_LITERAL_PATHSPECS */\n * nor --noglob-pathspecs")).toEqual([]);+ expect(globalPathspecSwitches('x.ts', "git(root, ['ls-tree', '--', ...literalPathspecs(paths)]);")).toEqual([]);+});+test('PENDING names only files that still need the hunk', () => {for (const rel of PENDING) expect({ rel, unscrubbed: unscrubbedGitSpawns(rel, readFileSync(join(ROOT, rel), 'utf8')).length > 0 }).toEqual({ rel, unscrubbed: true });});diff --git a/test/git-literal-pathspecs-7793.test.ts b/test/git-literal-pathspecs-7793.test.tsnew file mode 100644index 0000000000..1192a0aa37--- /dev/null+++ b/test/git-literal-pathspecs-7793.test.ts@@ -0,0 +1,66 @@+/**+ * #7793 (items 1 and 3): `literalPathspecs` fails closed on an empty path, and the read paths that used git's global+ * `--literal-pathspecs` flag build per-path `:(literal)` pathspecs instead, with the same meaning: a path named with glob+ * characters or a leading colon selects only that file. Real repositories, no seams. Repo-less brains never reach these+ * calls (no repository, no git read), so nothing here changes them.+ */+import { afterEach, describe, expect, test } from 'bun:test';+import { execFileSync } from 'node:child_process';+import { mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { gitChildEnv, literalPathspecs } from '../src/core/git-env.ts';+import { gitResidualCommits } from '../src/core/facts/purge-verify.ts';+import { readTreeBlobs } from '../src/core/persistence/sync-blobs.ts';++const env = gitChildEnv();+const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, '-c', '[email protected]', '-c', 'user.name=a', ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], env }).trim();+const dirs: string[] = [];+afterEach(() => { for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }); });++function repo(files: Record<string, string>): string {+ const root = realpathSync(mkdtempSync(join(tmpdir(), 'gbrain-7793-')));+ dirs.push(root);+ git(root, 'init', '-q', '-b', 'main');+ for (const [name, body] of Object.entries(files)) {+ writeFileSync(join(root, name), body);+ git(root, 'add', '-A');+ git(root, 'commit', '-qm', `add ${name}`);+ }+ return root;+}++describe('literalPathspecs', () => {+ test('prefixes each path and keeps the order', () => {+ expect(literalPathspecs(['a.md', '[ab].md', ':x.md', 'dir/*'])).toEqual([':(literal)a.md', ':(literal)[ab].md', ':(literal):x.md', ':(literal)dir/*']);+ expect(literalPathspecs([])).toEqual([]);+ });++ test('an empty path throws, because `:(literal)` alone matches the whole tree', () => {+ const root = repo({ 'a.md': 'one\n' });+ writeFileSync(join(root, 'a.md'), 'two\n');+ expect(git(root, 'status', '--porcelain', '--', ':(literal)')).toBe('M a.md');+ expect(() => literalPathspecs([''])).toThrow('empty path');+ expect(() => literalPathspecs(['a.md', ''])).toThrow('empty path');+ });++ test('. stays the explicit whole-tree scope that read callers use', () => {+ expect(literalPathspecs(['.'])).toEqual([':(literal).']);+ });+});++describe('converted read paths keep glob and leading-colon names literal', () => {+ test('readTreeBlobs returns only the named blobs', () => {+ const root = repo({ 'a.md': 'a\n', '[ab].md': 'glob\n', ':colon.md': 'colon\n' });+ const blobs = readTreeBlobs(root, 'HEAD', ['[ab].md', ':colon.md']);+ expect([...blobs.keys()].sort()).toEqual([':colon.md', '[ab].md']);+ });++ test('gitResidualCommits reads the history of the named file only', async () => {+ const root = repo({ 'a.md': 'the secret claim\n', '[ab].md': 'harmless\n', ':colon.md': 'the secret claim again\n' });+ const glob = await gitResidualCommits(root, ['[ab].md'], 'secret claim');+ expect(glob).toMatchObject({ status: 'out_of_reach', remaining: 0 });+ const colon = await gitResidualCommits(root, [':colon.md'], 'secret claim');+ expect(colon).toMatchObject({ remaining: 1 });+ });+});diff --git a/test/git-writer-safety-7381.serial.test.ts b/test/git-writer-safety-7381.serial.test.tsindex 72c3ee618c..18630d5e52 100644--- a/test/git-writer-safety-7381.serial.test.ts+++ b/test/git-writer-safety-7381.serial.test.ts@@ -350,4 +350,26 @@ describe('the helper\'s no-gbrain fallback', () => {expect(git(a, 'show', 'HEAD:x.md')).toBe('via the fallback');expect(git(bare, 'rev-parse', 'main')).toBe(before);}, 30_000);++ test('a path with glob characters is a literal pathspec: [ab].md never commits a concurrent edit to a.md (#7792)', () => {+ const { bare, a } = setup();+ mkdirSync(join(a, 'scripts'), { recursive: true });+ writeFileSync(join(a, 'scripts', 'brain-commit-push.sh'), renderCommitPushHelper(), { mode: 0o755 });+ writeFileSync(join(a, 'a.md'), 'a v1\n');+ git(a, 'add', 'a.md'); git(a, 'commit', '-qm', 'seed a'); git(a, 'push', '-q', 'origin', 'main');+ writeFileSync(join(a, 'a.md'), 'a concurrent edit\n');+ writeFileSync(join(a, '[ab].md'), 'the literal name\n');+ const run = (...paths: string[]) => spawnSync('bash', [join(a, 'scripts', 'brain-commit-push.sh'), 'glob name', ...paths], {+ cwd: a, encoding: 'utf8', env: { ...process.env, PATH: '/usr/bin:/bin', GIT_CONFIG_PARAMETERS: "'protocol.file.allow=always'" } });+ const pushed = git(bare, 'rev-parse', 'main');+ const result = run('[ab].md');+ expect(result.status).toBe(4);+ expect(git(a, 'show', '--name-only', '--format=', 'HEAD')).toBe('[ab].md');+ expect(git(a, 'show', 'HEAD:[ab].md')).toBe('the literal name');+ expect(git(a, 'show', 'HEAD:a.md')).toBe('a v1');+ expect(git(bare, 'rev-parse', 'main')).toBe(pushed);+ expect(status(a)).toBe(' M a.md\n?? scripts/');+ expect(run('').status).toBe(2);+ expect(status(a)).toBe(' M a.md\n?? scripts/');+ }, 30_000);});diff --git a/test/helpers/guard-body-drift.ts b/test/helpers/guard-body-drift.tsnew file mode 100644index 0000000000..8a9f64dd41--- /dev/null+++ b/test/helpers/guard-body-drift.ts@@ -0,0 +1,53 @@+/**+ * #7776 fixtures: install a "newer" body for a schema function (its live definition plus a marker comment, the shape a+ * newer gbrain's migration leaves) and read a body back, on either engine; the same for links_link_source_check, which+ * runMigrations' drift repair rewrites, and a forced schema run of apply-migrations in a child process.+ */+import { resolve } from 'node:path';+import type { BrainEngine } from '../../src/core/engine.ts';++const CLI = resolve(import.meta.dir, '..', '..', 'src', 'cli.ts');++export const NEWER_BODY_MARKER = '-- body installed by a newer gbrain (#7776 fixture)';++/** The live body (prosrc) of a public function, or null when it is not installed. */+export async function functionBody(engine: BrainEngine, name: string): Promise<string | null> {+ const rows = await engine.executeRaw<{ prosrc: string }>(+ `SELECT p.prosrc FROM pg_proc p JOIN pg_namespace n ON n.oid = p.pronamespace WHERE n.nspname = 'public' AND p.proname = $1`, [name]);+ return rows[0]?.prosrc ?? null;+}++/** Re-creates `name` with its current definition plus NEWER_BODY_MARKER before the closing quote. */+export async function installNewerBody(engine: BrainEngine, name: string): Promise<void> {+ const [row] = await engine.executeRaw<{ def: string }>(+ `SELECT pg_get_functiondef(p.oid) AS def FROM pg_proc p JOIN pg_namespace n ON n.oid = p.pronamespace WHERE n.nspname = 'public' AND p.proname = $1`, [name]);+ if (!row) throw new Error(`function ${name} is not installed`);+ const end = row.def.lastIndexOf('$function$');+ await engine.runMigration(0, `${row.def.slice(0, end)}${NEWER_BODY_MARKER}\n${row.def.slice(end)}`);+}++const NEWER_LINK_SOURCE_CHECK = 'CHECK (link_source IS NULL OR char_length(link_source) <= 128)';++/** Re-creates links_link_source_check in a shape a newer gbrain could leave (one the v114 drift repair would rewrite). */+export async function installNewerLinkSourceCheck(engine: BrainEngine): Promise<void> {+ await engine.runMigration(0, `ALTER TABLE links DROP CONSTRAINT IF EXISTS links_link_source_check;+ ALTER TABLE links ADD CONSTRAINT links_link_source_check ${NEWER_LINK_SOURCE_CHECK};`);+}++export async function linkSourceCheckDef(engine: BrainEngine): Promise<string | null> {+ const rows = await engine.executeRaw<{ def: string }>(+ `SELECT pg_get_constraintdef(oid) AS def FROM pg_constraint WHERE conrelid = to_regclass('links') AND conname = 'links_link_source_check'`);+ return rows[0]?.def ?? null;+}++/** Runs \`gbrain apply-migrations --force-schema --json\` in a child against the brain configured under \`home\`. */+export async function forceSchemaRun(home: string): Promise<{ exitCode: number; doc: { code?: string; error?: string } | null; out: string }> {+ const child = Bun.spawn([process.execPath, '--no-env-file', CLI, 'apply-migrations', '--force-schema', '--json'], {+ cwd: home, env: { HOME: home, GBRAIN_HOME: home, PATH: process.env.PATH ?? '/usr/bin:/bin', GBRAIN_SKIP_REFERENCE_SWEEP: '1' }, stdout: 'pipe', stderr: 'pipe',+ });+ const [stdout, stderr, exitCode] = await Promise.all([new Response(child.stdout).text(), new Response(child.stderr).text(), child.exited]);+ const start = stdout.indexOf('{');+ let doc: { code?: string; error?: string } | null = null;+ try { doc = start >= 0 ? JSON.parse(stdout.slice(start)) : null; } catch { doc = null; }+ return { exitCode, doc, out: stderr + stdout };+}diff --git a/test/init-schema-client-behind.test.ts b/test/init-schema-client-behind.test.tsnew file mode 100644index 0000000000..d0e4728503--- /dev/null+++ b/test/init-schema-client-behind.test.ts@@ -0,0 +1,82 @@+/**+ * #7776: initSchema replays the binary's whole schema (CREATE OR REPLACE FUNCTION ...) before runMigrations. On a+ * database a newer gbrain migrated, an older binary's replay reinstalled its own superseded function bodies (the+ * writer-fence guards among them) and then applied nothing. initSchema now refuses with client_behind before anything+ * in the schema runs; apply-migrations refuses the same way before any orchestrator and before a forced schema run+ * (whose drift repairs would otherwise rewrite the newer schema's links_link_source_check). PGLite (the default keyless, repo-less brain); a cold on-disk engine, because a loaded test+ * snapshot skips the replay. Postgres: test/e2e/init-schema-client-behind-postgres.test.ts.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { LATEST_VERSION } from '../src/core/migrate.ts';+import type { GBrainConfig } from '../src/core/config.ts';+import { schemaAheadRefusal } from '../src/commands/apply-migrations-schema.ts';+import { schemaFunctionBodyDrift } from '../src/commands/doctor/checks/schema-function-bodies.ts';+import { forceSchemaRun, functionBody, installNewerBody, installNewerLinkSourceCheck, linkSourceCheckDef, NEWER_BODY_MARKER } from './helpers/guard-body-drift.ts';++const GUARD = 'gbrain_require_managed_writer';++describe('initSchema on a database newer than the binary (#7776, PGLite)', () => {+ let dir: string;+ let engine: PGLiteEngine;+ beforeAll(async () => {+ dir = mkdtempSync(join(tmpdir(), 'gbrain-client-behind-'));+ engine = new PGLiteEngine();+ await engine.connect({ database_path: join(dir, 'brain.pglite') });+ await engine.initSchema();+ }, 120_000);+ afterAll(async () => {+ await engine?.disconnect();+ rmSync(dir, { recursive: true, force: true });+ });++ test('refuses client_behind and leaves the newer guard body and the version alone', async () => {+ await installNewerBody(engine, GUARD);+ await engine.setConfig('version', String(LATEST_VERSION + 1));+ const error = await engine.initSchema().then(() => null, (e: unknown) => e as { code?: string; fix?: { argv?: string[]; actor?: string } });+ expect(await functionBody(engine, GUARD)).toContain(NEWER_BODY_MARKER);+ expect(error?.code).toBe('client_behind');+ expect(error?.fix).toMatchObject({ argv: ['gbrain', 'upgrade'], actor: 'host_admin' });+ expect(await engine.getConfig('version')).toBe(String(LATEST_VERSION + 1));+ }, 60_000);++ test('apply-migrations reads the closed datastore and refuses before any orchestrator runs', async () => {+ await engine.disconnect();+ try {+ const refusal = await schemaAheadRefusal({ engine: 'pglite', database_path: join(dir, 'brain.pglite') } as GBrainConfig, null);+ expect(refusal?.code).toBe('client_behind');+ expect(await schemaAheadRefusal({ engine: 'postgres' } as GBrainConfig, LATEST_VERSION)).toBeNull();+ } finally {+ await engine.connect({ database_path: join(dir, 'brain.pglite') });+ }+ }, 60_000);++ test('apply-migrations --force-schema refuses client_behind and its drift repair leaves the newer constraint alone', async () => {+ await installNewerLinkSourceCheck(engine);+ const before = await linkSourceCheckDef(engine);+ await engine.disconnect();+ try {+ const home = join(dir, 'home');+ mkdirSync(join(home, '.gbrain'), { recursive: true });+ writeFileSync(join(home, '.gbrain', 'config.json'), JSON.stringify({ engine: 'pglite', database_path: join(dir, 'brain.pglite') }));+ const run = await forceSchemaRun(home);+ expect(run.doc?.code ?? run.out).toBe('client_behind');+ expect(run.exitCode).not.toBe(0);+ } finally {+ await engine.connect({ database_path: join(dir, 'brain.pglite') });+ }+ expect(await linkSourceCheckDef(engine)).toBe(before);+ expect(await engine.getConfig('version')).toBe(String(LATEST_VERSION + 1));+ }, 120_000);++ test('at head the doctor check names the drifted body, and the replay of this binary clears it', async () => {+ await engine.setConfig('version', String(LATEST_VERSION));+ expect(await schemaFunctionBodyDrift(engine)).toMatchObject({ status: 'checked', differing: [GUARD] });+ await engine.initSchema();+ expect(await functionBody(engine, GUARD)).not.toContain(NEWER_BODY_MARKER);+ expect(await schemaFunctionBodyDrift(engine)).toMatchObject({ status: 'checked', differing: [] });+ }, 60_000);+});