Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(git-canonical): G1 read-only git-gap census and db_ahead_of_git doctor check
garrytan8098c52fc70a
diff --git a/docs/architecture/key-files/canonical-reconciliation.md b/docs/architecture/key-files/canonical-reconciliation.mdindex c80eafd12e..2bdb63853d 100644--- a/docs/architecture/key-files/canonical-reconciliation.md+++ b/docs/architecture/key-files/canonical-reconciliation.md@@ -18,7 +18,7 @@ See [generations](generations.md).- `src/core/persistence/sync-slices.ts` — #6349 path-sliced staging for a managed target that exceeds the cursor bound with no commit axis to stage on (a first sync, a `--full` tree walk, one commit above the bound). `sliceEntries` cuts the whole resolved manifest in `(phase, code-unit path)` order: every import slice, then bounded deletion slices, the longest prefix the bound admits. The slice cursor `{ phase, after, head, target }` lives in `op_checkpoints` (`managed-sync-slice`, keyed by source, incarnation and the run's cursor options so a resumed invocation with other exclusions starts over), written or cleared by the slice's checkpoint in the same transaction that leaves `last_commit` untouched until the last slice settles; `sync-discovery.ts` resumes an unfinished target pinned at its recorded commit.- **`src/core/persistence/sync-discovery.ts`** + **`sync-origin.ts`** — managed owner-only Git discovery with source-relative exclusions and one-statement page identity/revision/liveness snapshots. #6517: `selectOriginClaimant` (sync-origin.ts) is the one origin rule, applied by the discovery census and by `assertSyncPageOrigin` at preparation and publication: a live page wins over tombstones, several live pages refuse `page_identity_changed` naming the soft-delete exit (`sharedOriginExit`), a single tombstone may be reused, several tombstones stay ambiguous. Reserved skillpack paths (`skills/` at any depth and `skillpack.json`, `src/core/skill-reserved-paths.ts`) never enter discovery: the shared skill publisher owns them and `managedImportContent` refuses them, so a seeded pack cannot block a sync. Nested full discovery filters source scope before slicing paths. Windows separator aliases retain their page identity; ambiguous aliases refuse, while POSIX backslashes/case remain exact. Under `source-root` mode a stored `<scope>/<path>` origin (the Git-root form older write-through minted from the slug, recognized because `<path>` names the page slug) is accepted as `<path>` at discovery, freeze, preparation and the page-origin query, and an import rewrites it in place; when both readings name existing files the stored origin refuses with `detail: ambiguous_source_path`. A genuine origin mismatch refuses with `detail: sync_origin_mismatch` and the filled paths. Deletions must be absent from the pinned Git target or their explicitly selected working tree. Deleting a file that no page records as its origin (for example a skipped slug twin) while its slug's page keeps another origin commits an explicit no-op receipt (`unownedDeletion`, outcome reason `unowned_deleted_path`) that preserves that live page or tombstone; freeze and publication re-prove that no page owns the path and that the file is still absent. Existing cursors reuse their accepted manifests, with unknown old deletion provenance refused rather than rewritten. Active Git holds of the source are re-screened when their blob or working bytes changed, the file left, a `sources retry-held` request names them, the hold predates the current `RECOVERY_VERSION`, or the code is `frontmatter_slug_conflict`, `file_too_large`, `rename_held` or `parser_regression`; holds of now-excluded paths are released at the checkpoint. #6278 (B7): `retryTaken` lists every scheduled path the discovery read (screened as an entry, as a candidate, or no longer eligible); `sync-run.ts` clears them in the transaction that saves the fresh cursor. A held rename destination (or a held path renamed again) carries the hold's `renameFrom` when the old page is unchanged, else `renameHeld` (held as `rename_held` / `rename_source_changed`), and a full walk never deletes an origin a hold's `rename_from` names. Imports whose origin has no page claim their slug together: a live page whose own file is still in the tree keeps the slug, otherwise the file named like the slug (else the first path) wins, and the losers leave the manifest and are reported as `slugCollisions` (the library path's `slug_collision` skip) instead of failing the run. A winner whose slug is held by a page with a vanished or deleted origin takes that page over (`renameFrom`, same slug). A Git-detected rename to an unoccupied slug becomes one import carrying `renameFrom` in place of a delete plus a create. Origins for one slug that differ only by case or separator spelling refuse, except a case-only respelling whose old file the same sync removes. Code files keep exact per-origin identity. On Windows a path containing `:` is reported in `SyncDiscovery.fileRefusals` (code `colon_slug_windows_write_through`, with its filled `gbrain sync --source <id> --no-pull` hint) and kept out of the run and its origin checks, so one such file no longer fails the whole sync (#5032). `resolveManagedSyncContext` refuses `skipFailed` / `includeGitignored` on a managed source with `managed_sync_flag_refused` (`managed-sync-flags.ts`, `detail` = the flag, fix = the same `gbrain sync` argv without it), the one refusal jobs, MCP and the cycle reach; `gbrain sync` raises it at parse, before the legacy ledger acknowledgement and the cost gate, `--all` included (#6696). #6865: the per-path eligibility (scope, `sync.exclude`, `sync.include_hidden`, strategy, reserved skillpack paths) and the origin a path maps to under the slug mode come from one exported `loadSyncEligibility(engine, context, opts?, company?)`, which the unindexed-file detector shares.-- `src/core/hardened-git.ts` (#6712 additions; base entry in [persistence-stalls](persistence-stalls.md)) — `assertHardenedGitArgs` now checks exact options in every wrapper: `cat-file` with at most `--batch` (never `--filters`, `--textconv` or `--batch-command`), `hash-object --no-filters` optionally with `--stdin-paths`, `check-attr` with `-z`/`--stdin`, and `diff-tree` only as `-r -z --no-renames`. `hardenedGitStream` is the third wrapper: it spawns asynchronously, streams stdout to a callback, feeds stdin with backpressure, SIGKILLs past its timeout or byte cap and rejects when the consumer or the stdin iterable throws; `NulRecordSplitter` and `hardenedStreamComplete` give the completeness rule (exit 0, no signal, output ending at a NUL or empty). Tests: `test/hardened-git-stream-6712.test.ts`, `test/hardened-git-filters.test.ts`.+- `src/core/hardened-git.ts` (#6712 additions; base entry in [persistence-stalls](persistence-stalls.md)) — `assertHardenedGitArgs` checks exact options in every wrapper: `cat-file` with at most `--batch` (never `--filters`, `--textconv` or `--batch-command`), `hash-object --no-filters` optionally with `--stdin-paths`, `check-attr`/`check-ignore` with `-z`/`--stdin`, and `diff-tree` only as `-r -z --no-renames`. `hardenedGitStream` is a third wrapper: it spawns async, streams stdout to a callback, feeds stdin with backpressure, SIGKILLs past its timeout or byte cap and rejects when the consumer or stdin iterable throws; `NulRecordSplitter` and `hardenedStreamComplete` give the completeness rule (exit 0, no signal, output ending at a NUL or empty). Tests: `test/hardened-git-stream-6712.test.ts`, `test/hardened-git-filters.test.ts`.- `src/core/persistence/sync-git-stream.ts` — the managed-sync reconcile's Git level reads (#6712), all through `hardenedGitStream` (allow-listed, filter-free plumbing; the checkout's clean/process filters and textconv never run) and parsed as they stream, so memory is the result maps. `readTreeLevel` (`ls-tree -r -z <commit> -- <scope>`: blobs plus symlinks and gitlinks with their mode), `readIndexLevel` (`ls-files -s -z`, the index only; a conflicted path keeps its highest stage) and `readRenameHints` (`diff-tree -r -z --no-renames`: a deleted and an added regular file paired only when their blob OID is unique to them; hints, never candidates) throw `SyncTreeReadIncomplete` (code `reconcile_read_incomplete`) unless Git exited 0, was not signalled and its output ended at a NUL. `readBlobs` reads contents through one `cat-file --batch`, leaving out missing, oversized and over-total objects. `probeDirtiness` is the batched `hardenedPathDirty` (`Dp`): per batch of 2,000 paths one `hash-object --no-filters --stdin-paths` and one `check-attr -z --stdin`, presence and bytes from `readSyncFile`; verdicts in order `untracked`, `staged` (index and tree differ in OID or mode, a non-zero stage, or one side missing), `deleted`, `unknown` (symlink or gitlink, unreadable file, a path with a newline or a leading quote, any Git failure, an OID that disagrees with the bytes read), then `clean` (raw OID equals the tree with the executable bit matching), `clean_eol` (only `text`/`eol` set and the CRLF-folded bytes hash to the tree), `clean_lfs` (a valid pointer whose sha256 and size match the bytes) or `modified`; another filter, `working-tree-encoding`, an executable-bit-only change or CRLF bytes that fold to the tree with no attribute are `unknown`, never clean. Tests: `test/hardened-git-stream-6712.test.ts` (every verdict, completeness, and a forced probe that 1,000 passes of every read never run a configured filter or textconv while `git status`/`git diff` on the same checkout do). Working mode: `probeDirtiness(..., { working: true })` never reads the index (a path with no file is `deleted`, a present file outside the tree `untracked` with its raw OID, every other present file judged from its bytes against the tree through the same `clean_eol`/`clean_lfs` domains), so a staged edit, a staged new file, `git rm --cached`, a staged deletion and a staged file removed from disk probe as the same disk does with a pristine index: the working level is the physical bytes (design v3.2 §2.1). `hashWorkingLevel` hashes every path of a working round that way with hash-then-restat (a path whose bigint `lstat` moved across the hash is rehashed, up to three attempts) and returns the stat cache it leaves: `WorkingStatCache` is plain JSON (`{v: 1, root, entries: {path: 'dev:ino:mode:uid:size:mtime_ns:ctime_ns' | 'absent'}}`), an entry is written only for a stable stat whose `mtime` and `ctime` are older than 2 s before the attempt began (Git's racy rule) and a probe with a level, and at most `WORKING_STAT_CACHE_MAX_ENTRIES` (100,000) entries are kept in path order. `workingChanged(cache, paths)` is the idle tick's check: a path the cache does not hold, a moved stat, a failed stat, a zero `ctime`, a missing cache or a moved root all read as changed, never as unchanged. `parseWorkingStatCache` validates a serialized copy (junk is null, so everything reads changed); `rememberWorkingStatCache`/`recallWorkingStatCache` keep up to 64 caches per process. Working-mode tests: `test/sync-working-level-6712.test.ts` (probe 41, on the Git reads and on a managed PGLite pass), `test/sync-working-stat-cache-6712.test.ts` (probe 42); the probe 28 marker test also runs `hashWorkingLevel`.- `src/core/persistence/sync-classify.ts` — the managed-sync level classifier (#6712 PR 4, design v3.2 §2.3): pure (no I/O), total, ordered, first match over one path's facts (`SyncPathState`: mode, `T[p]`, the level `L`, presence, `Dp`, the page and its import record, the attestation of its revision, hold, deletion marker, baseline blob, open work). Rows in order: `held`, `spelling`, `untracked`, `kept`, `delete`, `delete_drift`, `gone`, `deleted_same`, `deleted_edited`, `legacy_same`, `dirty`, `matched`, `adopt`, `reparse`, `db_ahead` (sub-labels `pending`/`db_only`/`unproven`; keep_db writes only `db_only` on a clean committed path; an open full obligation skips `db_only`/`unproven`), `import`, `legacy_unverified`, `keep_db`, `drift` (side `both` or `unknown`); then the overlay (unsettled with open work is `in_flight`). `syncClassAction` is the glossary tag (`none`, `owner`, `repair`); `syncPassKind` decides `idle`, `hold_only` or `full` from the converged state and every obligation. Tests: `test/sync-classify-6712.test.ts` (each row, and the cross product against a reference model built from the state space).- `src/core/persistence/sync-pass.ts` — the read-only shadow of the level-triggered pass (#6712 PR 4a): `readShadowLevel` reads one managed source's level (`T` via `readTreeLevel`, `X`, working-mode untracked files, `Dp` for committed candidates only or every path in working mode, pages keyset on `pages.id` with the import record by a LATERAL primary-key probe and the revision's attestation in the same statement, holds and retry rows, open requests and pending Git effects, deletion markers) and classifies every path with `sync-classify.ts`; it writes and admits nothing. Postgres reads share one `REPEATABLE READ, READ ONLY` transaction; PGLite runs bounded 2,000-row statements. A company-brain source returns null (it keeps its frozen manifest). `shadowConvergence` wraps it in the receipt, `dryRunConvergence` backs `gbrain sync --dry-run --json`'s `convergence` (with the read-only screen), `statusConvergence` backs `sync status --detail` and doctor, and `idleTickProbe` times the idle tick's reads for the bench (`scripts/bench/sync-convergence.ts`). Tests: `test/sync-pass-shadow-6712.test.ts`.diff --git a/docs/architecture/key-files/commands-3.md b/docs/architecture/key-files/commands-3.mdindex 6b293739a5..fe2e1d17b7 100644--- a/docs/architecture/key-files/commands-3.md+++ b/docs/architecture/key-files/commands-3.md@@ -27,7 +27,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/commands/eval.ts` — `gbrain eval` command: single-run table + A/B config comparison. Sub-subcommand dispatch on `args[0]` routes `gbrain eval export` + `gbrain eval prune` + `gbrain eval replay` into session-capture handlers; bare `gbrain eval --qrels …` fall-through preserves the legacy IR-metrics flow. `gbrain eval cross-modal` is in the dispatch (the user-facing path is the cli.ts no-DB branch — `src/commands/eval.ts:cross-modal` only fires when callers re-enter with an existing engine).-- `src/commands/export.ts` + `src/core/export-snapshot.ts` + `src/core/export-stage.ts` + `src/core/export-publish.ts` — local Markdown export collects source/page/canonical-withdrawal/tag/raw state in one export-scoped repeatable-read read-only transaction, using 256-key ID batches and private disk-backed SQLite staging. Primary-key page reads reuse the canonical withdrawal overlay without source-wide slug scans under stale planner statistics. Each 256-key batch groups by source and retains only one capacity-checked withdrawal ledger at a time; bodies with no literal `gbrain:facts:` marker skip normalization, while malformed/orphan markers still use canonical SQL fingerprinting. No engine defaults or shared migration iterators change. Explicit source selection is validated; restore-only selects one source through `resolveRestoreTarget` (`src/core/restore-target.ts`, shared with `gbrain storage status`) and checks its recorded file path through the existing native path resolver. The manifest rejects unsafe paths, same/cross-source aliases, case/Unicode and file-prefix collisions before destination output, preserving the `<slug>.md` and `.raw/<name>.json` layout. Existing planned paths refuse rather than overwrite. The portable first-party native addon anchors no-follow directories and publishes leaves with atomic no-replace operations, retaining an exclusive persistent `.gbrain-export-status` marker; success requires flushed data and a final COMPLETE line. Unsupported native capabilities fail closed without a pathname fallback. A fresh destination is the retry path; unrelated files are never pruned. Fixed capacity/time limits fail visibly, never truncate. This is a historical snapshot, not a database backup or a sandbox against another same-user process renaming directories. See [safe export](../../storage-tiering.md#safe-export). Engine-free `export --help` documents scope, no-overwrite publication and incomplete-output recovery. Wave B PR 2: a segmented page streams (`segmentedExportMarkdown`: serializeMarkdown's head, the trusted stored body through `readBodyRange` under a body ledger, here `exportBodyLedger`, the same withdrawal overlay; `restore_page` of a page over the single-string ceiling passes its snapshot's ledger; the timeline separator before the first timeline byte) into its own stage file (`ExportStage.addStream`, a full collection per 1 MiB read), published with the native path API; its payload estimate is `body_bytes`, the per-page limit is `exportPayloadLimit(pages.max_bytes)` (32 MiB while segmented storage is off), a streamed page adds 1 ms per KiB to the 10-minute snapshot deadline and stage files must leave 512 MiB free on the staging filesystem (`test/e2e/large-pages-export.test.ts`: inline vs segmented same bytes at 2 and 20 MiB, export(import(F)) == F, a gated 128 MiB memory arm). `exportPagePath` writes a page whose slug is not a portable file name under an escaped name with its `slug:` line (`:` and other Windows-unsafe characters become `~`, a reserved device name or trailing dot/space gets `~` appended, an over-budget segment is cut with a `~<8 hex>` hash and marked not restorable); `runExport` returns an `ExportReport`, prints the escaped pages, and collects every `ExportPathCollision` into one refusal whose lines name each fix (`test/pathological/b5-export-unsafe-slugs.test.ts`). Pinned by both-engine export safety/independent-roundtrip/snapshot/failure-release suites, the 100001-page scale fixture with staging bytes and full export SQL statement accounting, the native publication/compiled-wrapper suite, actual CLI help tests, and the PostgreSQL export E2E wrapper.+- `src/commands/export.ts` + `src/core/export-snapshot.ts` + `src/core/export-stage.ts` + `src/core/export-publish.ts` — local Markdown export collects source/page/canonical-withdrawal/tag/raw state in one export-scoped repeatable-read read-only transaction, using 256-key ID batches and private disk-backed SQLite staging. Primary-key page reads reuse the canonical withdrawal overlay without source-wide slug scans under stale planner statistics. Each 256-key batch groups by source and retains only one capacity-checked withdrawal ledger at a time; bodies with no literal `gbrain:facts:` marker skip normalization, while malformed/orphan markers still use canonical SQL fingerprinting. No engine defaults or shared migration iterators change. Explicit source selection is validated; restore-only selects one source through `resolveRestoreTarget` (`src/core/restore-target.ts`, shared with `gbrain storage status`) and checks its recorded file path through the existing native path resolver. The manifest rejects unsafe paths, same/cross-source aliases, case/Unicode and file-prefix collisions before destination output, preserving the `<slug>.md` and `.raw/<name>.json` layout. Existing planned paths refuse rather than overwrite. The portable first-party native addon anchors no-follow directories and publishes leaves with atomic no-replace operations, retaining an exclusive persistent `.gbrain-export-status` marker; success requires flushed data and a final COMPLETE line. Unsupported native capabilities fail closed without a pathname fallback. A fresh destination is the retry path; unrelated files are never pruned. Fixed capacity/time limits fail visibly, never truncate. This is a historical snapshot, not a database backup or a sandbox against another same-user process renaming directories. See [safe export](../../storage-tiering.md#safe-export). Engine-free `export --help` documents scope, no-overwrite publication and incomplete-output recovery. Wave B PR 2: a segmented page streams (`segmentedExportMarkdown`: serializeMarkdown's head, the trusted stored body through `readBodyRange` under a body ledger, here `exportBodyLedger`, the same withdrawal overlay; `restore_page` of a page over the single-string ceiling passes its snapshot's ledger; the timeline separator before the first timeline byte) into its own stage file (`ExportStage.addStream`, a full collection per 1 MiB read), published with the native path API; its payload estimate is `body_bytes`, the per-page limit is `exportPayloadLimit(pages.max_bytes)` (32 MiB while segmented storage is off), a streamed page adds 1 ms per KiB to the 10-minute snapshot deadline and stage files must leave 512 MiB free on the staging filesystem (`test/e2e/large-pages-export.test.ts`: inline vs segmented same bytes at 2 and 20 MiB, export(import(F)) == F, a gated 128 MiB memory arm). `exportPagePath` writes a page whose slug is not a portable file name under an escaped name with its `slug:` line (`:` and other Windows-unsafe characters become `~`, a reserved device name or trailing dot/space gets `~` appended, an over-budget segment is cut with a `~<8 hex>` hash and marked not restorable); `runExport` returns an `ExportReport`, prints the escaped pages, and collects every `ExportPathCollision` into one refusal whose lines name each fix (`test/pathological/b5-export-unsafe-slugs.test.ts`). Pinned by both-engine export safety/independent-roundtrip/snapshot/failure-release suites, the 100001-page scale fixture with staging bytes and full export SQL statement accounting, the native publication/compiled-wrapper suite, actual CLI help tests, and the PostgreSQL export E2E wrapper. A page's file is rendered by `export-snapshot.ts` (`inlineExportMarkdown`, `segmentedExportHead` for `segmentedExportMarkdown`; frontmatter with the #5966 slug stamp), which the git-gap equality contract (`persistence/git-gap.ts`) shares.- `src/commands/extract-conversation-facts.ts` + `src/core/cycle/conversation-facts-backfill.ts` — bulk fact extraction for long-form conversation pages. Walks conversation/meeting/slack/email/imessage/imessage-daily pages, splits them into bounded windows via `src/core/facts/conversation-windows.ts` (#6267: eligibility per 30-min gap group of ≥2 messages decided before windowing; windows close at 30 messages or when the rendered text with its header would exceed 6,500 chars; oversized turns split at sentence boundaries with the speaker prefix repeated; a trailing single reply of an eligible group is its own window, never glued across a gap; nothing is clipped and an unrepresentable header fails the page before prior-fact cleanup; a page's frontmatter `conversation_segment_gap_minutes`, an integer from 1 to 10080, overrides the gap for that page, and any other value is ignored with a stderr warning naming the accepted range), prepends a topical/temporal header, and uses the strict `extractFactsFromTurnWithOutcome()` path so provider and output failures remain retryable instead of becoming successful empty pages. Invariants: **strict per-source core** (`runExtractConversationFactsCore({sourceId, ...})` always takes one sourceId; CLI + cycle phase each do their own multi-source iteration because `PHASE_SCOPE='source'` is taxonomy-only); **bounded two-phase enumeration** (paginated `listPages({type, sourceId, limit:10})`; per-page body cap `MAX_PAGE_BODY_BYTES` = `CONVERSATION_BODY_MAX_BYTES` in `conversation-parser/body.ts`, `PAGE_MAX_BYTES` + 1 MiB = 25 MiB, measured on the parser input; `readConversationBodyForParsing` stats a `raw_transcript` sidecar and throws `ConversationBodyTooLargeError` over the cap before any read, the snapshot carries `oversizedSidecarBytes`, and a size skip writes a `skipped_too_large` receipt to `page_extraction_state` (doctor `extraction_input_truncated`) that a later run under the cap clears; test `test/conversation-facts-oversized-sidecar.test.ts`; a segmented page is read in ranges; one over `CONVERSATION_WINDOW_BYTES` with no conversation facts is extracted from its newest window (day-header date, `tail_window` receipt, `window_rule: no_prior_facts`); one with facts is skipped with nothing cleared (`skipped_too_large`, `window_rule: prior_facts_kept`), since the run clears prior facts the window may not see, until PR 4's window anchors (test `test/large-pages/segmented-conversation-facts.test.ts`)); **page-global `row_num` accumulator** (the facts unique index is `(source_id, source_markdown_slug, row_num)`); **versioned snapshot-bound outcomes** (`cli:extract-conversation-facts:terminal:v2` for complete pages and a separate `non-extractable:v2` source for recognized pages with no eligible segment); **operation checkpoints are scheduling hints only** and never suppress a replay without a matching v2 outcome; **optional `opts.budgetTracker?`** is used as-is, while an absent tracker is created with `maxCostUsd` (a DEFAULT cap is dropped with a warning when the extraction or parser chat model is unpriced, via `src/core/facts/conversation-budget.ts` `conversationFactsCostCap` (#5823); explicit CLI/caller/cycle caps stay fail-closed and a `no_pricing` stop reports `budget_reason`/`budget_model`, exits 1 and names `pricing.overrides`); **body reads cover compiled truth, timeline, and configured raw-transcript sidecars**; **`facts.extraction_enabled` kill-switch** with `--override-disabled`; **`--types LIST` allowlist** (`conversation,meeting,slack,email,imessage,imessage-daily`); **`--background` via `maybeBackground`**; and **speaker-shaped-fold decline** — when the parse reports `unrecognized_headings` containing a speaker-shaped label (1-2 title-cased words, not in the doc-heading stoplist — the stoplist gates the DECLINE only, so a miss is warn-noise, never data loss) AND the parse produced fewer than two distinct speakers, the page is declined instead of extracted under wrong attribution: counted in `pages_skipped_unrecognized_speaker` (Result/CLI/cycle surfaces), warned to stderr with the folding pattern id, and deliberately NON-terminal (no durable audit row and no orphan cleanup, so a future parser/pattern fix retries the page); multi-speaker pages with folds proceed warn-only. `publishConversationFacts` skips a non-outcome row an active conversation fact of the source already states (`findCaptureDuplicate`, no time bound; `duplicates_skipped`, #7043). The companion `conversation_facts_backfill` cycle phase is default-off, iterates every source except `cycle.conversation_facts_backfill.exclude_sources` (reported as `sources_excluded`), and enforces per-source plus brain-wide cost and wall-time caps. Migration v94 provides the partial facts index used by outcome lookups. `computeConversationFactsBacklogCheck` reports fresh completed, scanned-not-extractable, and unfinished counts separately, warning when more than 10 eligible pages lack a fresh v2 outcome. `sources audit` exposes `facts_backfill_estimate: {pages, est_segments, est_cost_usd, types}`. `--workers N` for LLM-bound fact extraction over conversation pages, with a per-page advisory lock via `src/core/db-lock.ts:withRefreshingLock` (lock id `extract-conversation-facts:<source>:<slug>`, TTL `PER_PAGE_LOCK_TTL_MINUTES=2` with 20s refresh via `Math.max(15s, 120s/6)`; `LockUnavailableError` triggers skip-and-continue with rate-limited log per (source, minute) + `pages_lock_skipped` counter + CLI exits 3 when non-zero AND no hard failures). A page's rows are buffered and published once after its last segment (`publishPageFacts` on an unmanaged brain, one `writeDerivedFacts` transaction; the managed batch otherwise), through `publishConversationFacts` (facts/conversation-publication.ts), so a crashed, failed, empty or partial run never removes the prior batch and a terminal audit row commits only with its page's facts (#7013); a run's `scope` is `partial` when fewer segments than in scope ran, `window` when `--since` dropped messages, else `full`, and a page that changed mid-run keeps an unmanaged run's facts as a `partial` batch. `assertFactsEmbeddingDimMatchesConfig(engine)` is the startup preflight (throws `FactsEmbeddingDimMismatchError` with paste-ready ALTER hint BEFORE the first insert; cached per engine via WeakMap). Result type carries `pages_lock_skipped` + `orphan_facts_cleaned`. Additive `pages_skipped_unparsed`, `pages_skipped_type_mismatch`, `pages_skipped_insufficient_turns`, and `pages_skipped_since` explain the unchanged `pages_skipped` aggregate across core, CLI, workers, and cycle sources; durable completion remains separate. `--dry-run` stops after segmentation, with no parser-fallback, extractor, or embedding calls and no durable knowledge/checkpoint/receipt/rollup writes. The narrow `python-dict-utterance` registry format and its quoted/nested-example rejection are documented in [conversation parser patterns](../conversation-parser-patterns.md). Checkpoint state is a shared `cpMap: Map<slug, endIso>` (NOT a per-page-mutated `cpEntries: string[]`) so atomic `Map.set` survives parallel workers. Minion handler `extract-conversation-facts` in `src/commands/jobs.ts` round-trips `workers` via `job.data.workers` for `--background --workers 20`. Cycle config key `cycle.conversation_facts_backfill.workers` (default 1; opt-in concurrency under brain-wide cost + walltime caps). Pinned by `test/extract-conversation-facts-diagnostics.serial.test.ts` (pool workers, per-page lock skip + exit 3, replay replacing a prior partial run's facts, D15 preflight, `--workers` round-trip). `src/commands/doctor.ts` reads the same outcomes, which survive checkpoint GC. Each outcome is bound to the exact parsed snapshot: regular pages use `content_hash` plus the UTC effective date; raw-conversation sidecars and legacy null-hash pages use a canonical SHA-256 over every parser-relevant input. Selection checks the token before locking, refetches under the lock, and verifies it again before writing the outcome, so an edit cannot be certified by stale work. The strict extraction path treats provider, refusal, truncation, malformed/schema-invalid output, segment-write, cleanup, and terminal-write failures as unfinished work; bulk failures increment `pages_failed`, affect CLI/cycle receipts and exit status, and never advance the legacy checkpoint. Explicit `slugs` batches contain page failures like the pool (cancellation and budget stops halt); logs carry only the closed reason and a retry command. Completion requires every in-scope segment (exactly `--segment-limit` counts). Extracted rows take `facts.default_visibility` (resolved once per run); audit rows stay private. Each page's own entities go to the extractor as `entityHints` (slugs, `src/core/facts/conversation-entity-hints.ts`, computed once per page, cap `CONVERSATION_ENTITY_HINTS_CAP` = 40 through `ExtractInput.entityHintsCap`): authored edges only (the page's frontmatter edges with the page as origin, then outgoing markdown, wikilink-resolved and manual links), same source, live fact-entity pages, and a private entity only when the run's facts are private; the `extract_facts` op keeps its 5-hint cap and prompt. Pinned by `test/conversation-entity-hints.test.ts`. Checkpoints are only a scheduling hint: a slug without a matching v2 outcome is replayed. `no_match`, errors, cancellation, and dry runs never become durable negatives, bar `facts/conversation-skip.ts` (prose meetings, single emails, undated turns). Result, CLI, cycle, and doctor surfaces keep completed, scanned-not-extractable, unfinished, failed, and lock-skipped counts separate. See [Conversation backfill durable outcomes](../../operations/conversation-backfill-outcomes.md) for the operator and maintainer contract. Pinned by `test/extract-conversation-facts.test.ts` and `test/doctor-conversation-facts-backlog.test.ts`. On a managed brain the core runs `managedDerivedFactsPreflight` (local writer, active source) before any provider work, and a page's facts and terminal (or non-extractable) audit row are buffered, then published in its receipted batch after source activity, page id, revision and parser-input snapshot are rechecked under the page lock, so a failed or raced re-extraction keeps the prior batch; the CLI no longer refuses up front and receipt pages are skipped. Tests: `test/managed-facts-writers.test.ts`, `test/managed-unsupported-preflight.serial.test.ts` (refusal before spend for an unaccepted writer).diff --git a/docs/architecture/key-files/core-persistence-continued.md b/docs/architecture/key-files/core-persistence-continued.mdindex da598cc42c..b6423a26b5 100644--- a/docs/architecture/key-files/core-persistence-continued.md+++ b/docs/architecture/key-files/core-persistence-continued.md@@ -5,6 +5,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGELThe #6188 fence check and fence repair live in [fence repair](core-fence-repair.md). Managed connector ingestion, connector item holds and the no-op kernel (checkpoint validation and the fault seams: [request indexes and fault seams](core-persistence-request-indexes.md)). Also the persistence verb types and errors, database-write and manual links, write attribution and loop-fact retirement; the managed purge of deleted pages is under [memory purge](memory-purge.md).- `src/core/persistence/{worktree-refresh,worktree-refresh-schema}.ts` — `gbrain sources refresh` (F0), the one sanctioned managed Git writer. `persistence_worktree_refreshes` holds one row per refresh with a partial unique index (one active refresh per worktree; its 23505 maps to `refresh_in_progress`). `refreshWorktree` prechecks with no database state (managed, owner host, upstream, no active refresh, no recovery, no unexhausted managed-sync cursor, hardened `git fetch` bounded by `sources.refresh_fetch_timeout_ms`, ancestry, dirty paths intersected with the incoming diff), then: `draining` (inserted under `withTopologyLocks` + `lockTopologyRows`; admission in `journal.ts` refuses `worktree_refreshing` for every request with that `worktree_id`, and `assertManagedSyncAllowed` refuses a managed sync before discovery), poll until no queued/running/recovering request, no queued/running `git`/`withdrawal-mirror` effect and no recovery record remain (else `refresh_drain_timeout`, aborted), `fenced` (both native locks held, rechecked in one transaction; `refreshFenceClear` stops request and effect claims), HEAD verified, dirt rechecked, `git merge --ff-only`, HEAD verified again, then one transaction `merged` + upstream observation + `syncing`; native locks are released and the managed `--no-pull` sync runs per member (only `managed_sync_*` `submit_job` admissions pass during `syncing`); `completed` when every member's `last_commit` is the target or descends from it, or with `outcome.sync_blocked` when a member sync blocks. A per-worktree `refresh-<worktree>.lock` held for the whole run proves liveness: `resumeWorktreeRefreshes` (called from `recoverSourceTopologies`, so on owner start) touches only interrupted `draining`/`fenced`/`merged` rows whose lock is free and applies the section 1.5 table (draining or fenced at the old HEAD abort; HEAD at the verified target moves to `syncing`; anything else is `recovery_required`, which admission refuses with `refresh_recovery_required`). Admission also completes a `syncing` row whose members all reached the target. `--resume` converges and runs the member syncs; `--abandon` lifts a fence only with HEAD back at the start commit. `gbrain sources writer status` lists active refreshes as `worktree_refreshes` (state, heads, the next command), which the refusal hints point at. Doctor `worktree_refresh_stuck` lists rows active over 15 minutes. CLI body: `src/commands/sources-refresh.ts`; while a resident PGLite owner (`gbrain serve`, stdio MCP) holds the database, `src/commands/sources-refresh-delegate.ts` runs the refresh inside it through the `writer_refresh` administration operation (trusted CLI registration only) and prints the same result or refusal. The consumer's idle probe applies `refreshFenceClear` to effects like the claims, so a fenced worktree's queued effects do not wake it. Tests: `test/persistence-worktree-refresh.test.ts`, `test/persistence-worktree-refresh-restart.test.ts` (child-process crash after merge), Postgres via `test/e2e/worktree-refresh-postgres.test.ts`, owner delegation in `test/persistence-sync-stdio-owner.test.ts`.+- `src/core/persistence/git-gap.ts` + `src/commands/sources-git-gap.ts` + `src/commands/doctor/checks/db-ahead-of-git.ts` — git-canonical memory, wave G1 (`docs/designs/GIT_CANONICAL_MEMORY.md#the-git-gap-census`), read-only. `declaredDatabaseOnly` is the one predicate for pages that may not have a tracked file, tested in order: a read-only mirror source, a private page (`isPrivatePage`), an alias-private page (`isDerivationPrivate`), lineage-private (computed in SQL from `privatePagesFilterFragment`), `database_only_reason`, a `storage.db_only` prefix (`isSourceDbOnlySlug`, refusing an invalid gbrain.yml), a never-filed derive-phase page (page-prepare.ts `isNeverFiledDerivedPage`: no `source_path`/`source_uri` under `DERIVE_PHASE_DB_ONLY_DEFAULTS`), a path the checkout's Git ignores (`ignoredPaths`: filter-free `check-ignore -z --stdin`, tracked files never reported, exit 1 = none, null when Git cannot answer). The equality contract compares a committed blob with the page's export view (`readExportPage`, withdrawals overlaid): an inline blob parsed as reconcile parses a canonical file, aligned with the stored type, subtype and #6429 stamp and compared by `reconcileCanonical` digest; a segmented page by the Git blob id of its streamed export. HEAD is read with hardened plumbing only (`readHeadTree`: one `ls-tree -r -l -z --full-tree` under the source's directory; `readBlobs`: `cat-file --batch` in calls of at most 64 MiB) and the working tree by hashing raw bytes (`worktreeBlobOid`), never `git status`/`git diff`, so no repository filter, textconv or fsmonitor runs. `gbrain sources git-gap <id> [--sample n] [--json]` (trusted local CLI, not an MCP op) puts every live page in one state (`equal`, `database_ahead`, `git_ahead` when the sync import record's `blob_oid`/`disk_blob_oid` differs from HEAD, else folded into `database_ahead` and counted in `database_ahead_without_import_record`, `declared_database_only` per class, `undeclared_database_only`, `worktree_only`, `unparseable`, `unsafe_path`), reports the working tree separately, and counts rows with no Git home (unfenced active facts, fenced facts on a missing page or a page without a committed file, links whose `link_source` is not in `DERIVED_LINK_SOURCES`, timeline rows on pages without a file), open `sync-hold` records by code and parked effect targets by kind and code. Each 256-page batch reads in its own read-only transaction. Doctor `db_ahead_of_git` runs the census per non-archived source whose directory is a Git checkout (others are only counted) under `GBRAIN_DOCTOR_GIT_GAP_TIMEOUT_MS` (default 10 s) and the entry deadline; it is always `ok` (informational) and lists totals only, a source the budget stopped or never reached as partial. Tests: `test/git-gap-census.test.ts` (PGLite and Postgres).- `src/core/persistence/{types,params,preconditions,verb-errors}.ts` — public mutation receipt states, error reasons and revision/idempotency parameter contracts. Receipt serialization explicitly selects public fields; queued content and execution credentials stay internal. `frozenVerbWriteError` uses MEMORY_VERBS v1's existing error enum with additive `write_request`/`write_error`; `page_body_segmented` is a write error code, so a verb refused by a segmented target keeps it as `write_error` and canonical code under the frozen `invalid_params` (caller class, not retryable) on both the receipt and the pre-admission path (`runMemoryWrite`). `remember` reads a segmented entity page up to PAGE_MAX_BYTES back whole (`materializedPage`) for its inferred-target checks and fence write; over it, a named or inferred entity refuses before admission with `segmentedRememberRefusal` (fix: remember with `infer_entity: false`), never a silent `NO_ENTITY` (`test/large-pages/segmented-remember-refusal.test.ts`); `committedVerbOutcome` refuses pending or failed receipts. `OperationError` and the thin MCP client preserve this metadata, including when a timeout races an already-received receipt. The registry-safe parameter/schema leaf never imports operation values. Pinned by `test/persistence-write-contracts.test.ts`, `test/mcp-client-hardening.test.ts` and a real HTTP envelope in `test/mcp-client.test.ts`.- `src/core/persistence/{database-write,manual-links}.ts` — `coordinatedDatabaseWrite` is the managed path for rows with no canonical file; `coordinatedManualLinkWrite` (`add_link` / `remove_link`) and `ontology_propose` (one entity page key) use it. On a managed brain it checks the caller's durable write authority for the authority page (`submissionAuthority`, then `authorizeWrite` FOR SHARE inside the transaction), revalidates the source incarnation and commits inside `withCoordinatedWrite` holding the given page keys (both link endpoints). Unmanaged brains keep the engine calls. Manual edges (`link_source` `manual` or a custom tag) survive re-derivation and republication because automatic reconciliation only replaces derived provenances. Tests: `test/managed-writers-w3.test.ts`, `test/managed-ontology-propose.test.ts`.diff --git a/docs/designs/GIT_CANONICAL_MEMORY.md b/docs/designs/GIT_CANONICAL_MEMORY.mdindex f4e7e5b7c5..69136400b5 100644--- a/docs/designs/GIT_CANONICAL_MEMORY.md+++ b/docs/designs/GIT_CANONICAL_MEMORY.md@@ -70,7 +70,26 @@ A write from a remote MCP caller or a thin client becomes a journal request that## Conversion-A source changes mode only through a preview-bound verb. The preview is the git-gap census: every page whose row differs from its committed blob, every page with no file that is not in a declared class, held items and parked effects, by category. The operator chooses per category to commit the database content through the door, declare it, or let git win. The preview lists any database content that git-wins would discard, and the apply binds to that preview. A source can return to its previous mode.+A source changes mode only through a preview-bound verb. The preview is the [git-gap census](#the-git-gap-census): every page whose row differs from its committed blob, every page with no file that is not in a declared class, held items and parked effects, by category. The operator chooses per category to commit the database content through the door, declare it, or let git win. The preview lists any database content that git-wins would discard, and the apply binds to that preview. A source can return to its previous mode.++## The git-gap census++`gbrain sources git-gap <source-id> [--sample n] [--json]` is the read-only preview conversion will bind to, and doctor `db_ahead_of_git` reports its totals per source with a Git checkout (informational in G1: always ok). It compares every live page with the blob committed at HEAD, read with hardened plumbing (`ls-tree`, `cat-file --batch`, `check-ignore`), so no repository filter, textconv or hook runs. It never reads `git status` or `git diff`. Each page lands in exactly one state:++| State | Meaning | What conversion does with it |+|---|---|---|+| `equal` | The row equals the HEAD blob under the export equality contract (fact withdrawals overlaid; a segmented page byte for byte). | Nothing; the indexer would derive the same row. |+| `database_ahead` | A blob exists at HEAD and the row differs; the sample lists the differing field paths. | The operator commits the database content through the door or lets git win; the preview lists what git-wins would discard. |+| `git_ahead` | The HEAD blob is not the blob the page last imported, per its sync import record (`blob_oid` / `disk_blob_oid`), so git moved since the import. `git_ahead_database_also_moved` counts pages whose row moved too. | Git wins: the indexer imports the committed blob. Where both moved, the preview lists the database edit git-wins would discard. |+| `declared_database_only` | A declared class (counted per class): `mirror_source`, `private`, `alias_private`, `lineage_private`, `database_only` (`database_only_reason`), `db_only_prefix` (`storage.db_only`), `derive_folder` (a never-filed page under the derive-phase defaults), `git_ignored`. `declared_with_head_blob` counts those whose file is still committed, such as a page that turned private. | They stay out of git. A still-committed file of a private page is removed by a door commit; earlier commits keep it. |+| `undeclared_database_only` | No blob at HEAD and no declared reason. | Commit it through the door, declare its class, or delete it. Strict mode refuses it until then. |+| `worktree_only` | A file exists in the working tree but not at HEAD. | Commit it through the door or remove it; a strict indexer reads only commits. |+| `unparseable` | The committed blob is not UTF-8 Markdown the importer accepts, or is a symlink. | A person fixes the file; conversion refuses the page until then. |+| `unsafe_path` | The recorded `source_path` maps to no safe file path. | Reconcile the path first. |++Without an import record (classic sync, or a page imported before records were written) the census cannot tell which side moved, so a page whose file changed in git counts as `database_ahead`; `database_ahead_without_import_record` says how many. The working tree is reported separately by raw bytes against HEAD (`clean`, `modified`, `deleted`, `untracked`, `absent`); a checkout whose attributes convert line endings reads as modified. In strict mode an uncommitted change means nothing.++The census also counts rows with no Git home, which G4 and G5 give a file form: active facts with no fence row, fenced facts whose fence page is missing or has no committed file, links whose `link_source` is not one a file derives (`markdown`, `frontmatter`, `mentions`, `wikilink-resolved`; `manual`, custom tags, `concept-provenance`, `atom-provenance` and legacy NULL rows all count), and timeline rows on pages with no committed file. Open sync holds are counted by code and parked effect targets by kind and code; strict mode retires both in G8.## Wavesdiff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex 17c888fef9..2925c05d61 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -30,7 +30,7 @@ src/commands/integrations.ts 1739 ratchet grown v0.46.26.0 megawave (#4039 connesrc/core/minions/handlers/subagent.ts 1925 ratchet merged: master v131 settle rework + dream-wave C5 peel + C6 accounting + C7 lease heartbeats/lost-lease aborts + C9 oneshot dispatch + adversarial fix batches; grown by #4078 subagent-loop capability fix; +6 lines (reasoning-item replay: adaptContentBlocksToChatBlocks handles 'reasoning' blocks); +3 wave G #4514: Anthropic-via-OpenRouter allowed on the subagent loop; +36 lines (code review, same PR): isPromptTooLongError walks a bounded .cause chain so it still matches post-normalizeAIError() wrapping, plus extractPromptTooLongDetail so the dead-lettered job's error carries the matched provider detail instead of the generic normalizeAIError() wrapper text; master integration: harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; #5105: +13 call-site wiring to shared tool-write-identity helper across fresh and replay dispatch; +7 fix wave 9 lane B #4921: ai.chat.per_turn_timeout_ms read once and passed to the oneshot and gateway-loop paths (resolver lives in minions/handler-timeouts.ts)src/commands/bootstrap.ts 2147 ratchet grandfathered at merge (grew past the 1500 cap on master); raised for #4066 HOME_WORKSPACE_GUARD_EXEMPT (status/uninstall/harness); +5 for the harnessDetect test seam (bulk lives in core/bootstrap/harness.ts); +23 for the contract subcommand dispatcher glue (#4105 absorb — bulk lives in core/bootstrap/contract.ts); +codex hooks-consent gate + mcp+hooks receipt registration + uninstall arm; +42 ambient-writeback WP8: interview-time SURFACE_MULTIUSER audience apply (pre-init ordering) + applyDeclaredAudienceFromInterview; +3 #4897 harness usage clause documenting --source ID semantics; +5 #5878: --refresh-skills dispatch and usage lines (logic in core/bootstrap/harness-skills.ts); +11 #5488: SUBCOMMAND_HELP harness entry (gate on --help / -h / help) — CLI help line, cannot move; +11 #4618 seat: --seat/--no-seat help lines and the runHooks parse (parse + notes live in core/bootstrap/hooks.ts parseSeatFlags); +13 #4082: runAdoptHooks (the --adopt branch of the hooks subcommand, kept out of runHooks for the function-size ratchet) and its two help lines (adoption logic lives in core/bootstrap/adopt-connection.ts + adopted-connections.ts)src/core/minions/worker.ts 1795 ratchet grandfathered at merge (grew past the 1500 cap on master, #4170); grown v0.46.11.0 five-issue wave; security: durable queued authority and confined filesystem dispatch; typed readiness, configuration-blocked lifecycle and bounded release; post-validation readiness publication and confirmed isolated-execution stop evidence; latch typed lock-renewal faults before generic retry; +9 Lane D: JobDeferredError routing (deferJob helper); +1 spend authorization: runWithJobSpend import (both handler seams call it in place of the bare handler); +3 watchdog: gracefulShutdown records its reason and launchJob aborts a claim committed before it fired; +5 GBRA-130 A-30: watchdog-attribution import, InFlightJob.shared (interface field), the suspect-alone claim gate and option, and the watchdog settle call in the executeJob catch (logic in minions/watchdog-attribution.ts); +6 GBRA-133 2a.4 sync-queue wake: IdleWaiter import and field, claimStarted before each claim, the idle poll through it, and stop/requestShutdown ending its wait (logic in minions/idle-wait.ts); +1 GBRA-158 #7239: refusal.ts import (a deterministic refusal ends the job at once; classification in minions/refusal.ts); +3 #7242 lane reservation: lanes import and the longJobNames/shortJobReservedSlots defaults (the claim passes claimExclusions; policy in minions/lanes.ts); +2 #7242 terminal hook: onJobSettled default and the settle call (logic in terminal-hook.ts); #7252 x #7249 merge: both sides grew the file, re-summed (1794 measured); GBRA-151 #7183/#7187/#7188 re-summed at the v0.60.402.0 merge (1795 measured)-src/commands/sources.ts 2077 ratchet +5 PR #5955 / fix wave 14 P2.7: sources set-strategy dispatch and help row, the strategy field of sources list --json (body in sources-strategy.ts); +5 #5988: sources status/retry-held help rows describe Git holds (help lines cannot move); +2 #5988: sources status <id> filter and Git held files (view in persistence/connector-status.ts); +5 F0: sources refresh dispatch and help rows (command body in sources-refresh.ts, protocol in persistence/worktree-refresh.ts); +6 fix wave 5 #5409: mirror-readonly/mirror-writable dispatch, help rows and the list --json mirror_read_only field (body in sources-mirror.ts); grown v0.46.22.0 phone wave: github source kind (#4104); +129 v0.47 gmail-loops: google source-kind flags + vault preflight + duplicate-account warn + access-mode validation; +8 set-path dispatch + help rows (#4739 — command body peeled to sources-set-path.ts); +29 #4698 adoption: --calendar-id flag + duplicate-account warn scoped to overlapping services; #5105: trusted writer administration route; company handlers and receipt status wiring; parsing stays in dedicated modules; canonical reconciliation: +5 engine-free sibling-command dispatch and help row, implementation remains in source-reconcile.ts; +4 fix wave 3 lane A: sources status connector recovery state and run counts (view lives in persistence/connector-status.ts); +3 fix wave 4 lane B: sources retry-held dispatch and help row (command body in sources-retry-held.ts) and the connector first-sync note on add; bodies in source-delete.ts and sources-set-path.ts); +4 #5984: sources status shows the managed sync backlog (logic in persistence/sync-drain.ts); v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (2031 measured); +11 W-B4: sources shared-skills dispatch, its --help guard and help rows, and the shared_skills field/lines in sources status (body in sources-shared-skills.ts, view in shared-skills/source-opt-out.ts); +4 #6188: uncommitted legacy fence-repair notices in sources status (logic in fence-repair/uncommitted.ts); +7 #6317: data_moving/movement_state on sources status and its human line (reader in persistence/sync-movement.ts), writer movement help row; +1 GBRA-133: sources reset-upstream help row (body in sources-reset-upstream.ts); fix wave 20 integration: lane 3 (#6827) and master growth compose at 2062 measured; +3 GBRA-150: sources resolve-path dispatch and help rows (body in sources-resolve-path.ts); +10 #7326: sources status parses --holds/--limit/--cursor and passes the git_holds listing mode, plus 4 help lines (bounding logic in persistence/connector-status.ts gitHoldStatusJson); +2 GBRA-133 Q1: sources set-sync dispatch and help row (body in sources-sync-enabled.ts)+src/commands/sources.ts 2081 ratchet +5 PR #5955 / fix wave 14 P2.7: sources set-strategy dispatch and help row, the strategy field of sources list --json (body in sources-strategy.ts); +5 #5988: sources status/retry-held help rows describe Git holds (help lines cannot move); +2 #5988: sources status <id> filter and Git held files (view in persistence/connector-status.ts); +5 F0: sources refresh dispatch and help rows (command body in sources-refresh.ts, protocol in persistence/worktree-refresh.ts); +6 fix wave 5 #5409: mirror-readonly/mirror-writable dispatch, help rows and the list --json mirror_read_only field (body in sources-mirror.ts); grown v0.46.22.0 phone wave: github source kind (#4104); +129 v0.47 gmail-loops: google source-kind flags + vault preflight + duplicate-account warn + access-mode validation; +8 set-path dispatch + help rows (#4739 — command body peeled to sources-set-path.ts); +29 #4698 adoption: --calendar-id flag + duplicate-account warn scoped to overlapping services; #5105: trusted writer administration route; company handlers and receipt status wiring; parsing stays in dedicated modules; canonical reconciliation: +5 engine-free sibling-command dispatch and help row, implementation remains in source-reconcile.ts; +4 fix wave 3 lane A: sources status connector recovery state and run counts (view lives in persistence/connector-status.ts); +3 fix wave 4 lane B: sources retry-held dispatch and help row (command body in sources-retry-held.ts) and the connector first-sync note on add; bodies in source-delete.ts and sources-set-path.ts); +4 #5984: sources status shows the managed sync backlog (logic in persistence/sync-drain.ts); v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (2031 measured); +11 W-B4: sources shared-skills dispatch, its --help guard and help rows, and the shared_skills field/lines in sources status (body in sources-shared-skills.ts, view in shared-skills/source-opt-out.ts); +4 #6188: uncommitted legacy fence-repair notices in sources status (logic in fence-repair/uncommitted.ts); +7 #6317: data_moving/movement_state on sources status and its human line (reader in persistence/sync-movement.ts), writer movement help row; +1 GBRA-133: sources reset-upstream help row (body in sources-reset-upstream.ts); fix wave 20 integration: lane 3 (#6827) and master growth compose at 2062 measured; +3 GBRA-150: sources resolve-path dispatch and help rows (body in sources-resolve-path.ts); +10 #7326: sources status parses --holds/--limit/--cursor and passes the git_holds listing mode, plus 4 help lines (bounding logic in persistence/connector-status.ts gitHoldStatusJson); +2 GBRA-133 Q1: sources set-sync dispatch and help row (body in sources-sync-enabled.ts); +4 G1 git-canonical: sources git-gap dispatch, doc line and help rows (body in sources-git-gap.ts)src/core/link-extraction.ts 2421 ratchet grown v0.46.26.0 megawave: link-aware timeline split + delimiter-outside-links (#3957 #4062 #3737); +37 wave-k #3908 reimpl: isCrossSourceLinksEnabled config ladder; +10 wave #4277: parseTimelineEntries skips generated backlink receipts; +17 #4855: latin-fold in normalizeBasename + dir-hint step tries both slug grammars; +17: #4855 Latin stroke-letter fold; +5: #4873 ./-relative markdown links kept as live references; +34 wave review: `../y.md` sibling links resolve on the DB path + folded bare-wikilink grammar (#4873 class); +62 #4977: role-prior suppression in machine-list sections (rolePriorSuppressedRanges, EntityRef.index); +3 composed with #4985 (variation-selector strip) in the same wave; +4 #4995: markdown-link anchor strip + lowercase-candidate rationale comments; +6 pre-landing review: #4977 suppression on code-stripped content + truthful watermark/section-list comments; T2: source-qualified inference and atomic origin-scoped derived links; canonical attendance evidence, source-qualified orientation, strict attendee resolution, and relocated filesystem link scanner (command export preserved); +4: pack-owned fallback and ambiguous attendee guards Display-label attendance exclusion, indexed evidence membership, and bounded strict resolver caching; attendance-boundary review.; complete attendance resolution and fence-safe evidence traversal; frontmatter discovery, canonical basename admission and code-aware attendance comment masking; exclude inline HTML comment spans from admitted attendance ranges; +17 write-path wave: same-name rule for entity fuzzy matches + rename-alias fallback in makeResolver; +1 #5567: materialized marker ends bullet detail; +30 #5749: unique global-basename step before fuzzy and live keyword resolution (ResolveOptions, watermark note); #5765: bold **Attendees:** label accepted + LINK_EXTRACTOR_VERSION_TS bump note; +10 eval-wave N9-2/N9-3/N12-7: pack frontmatter mappings inherit FRONTMATTER_LINK_MAP direction, page-type-bound pack attended follows canonical attendance, LINK_EXTRACTOR_VERSION_TS bump note; +1 #5623: normalizeBasename collapses hyphen runs like slugifySegment (extractor watermark note); +11 #5562: parseTimelineEntries accepts dated ### headings (FS-extractor parity); +3 eval-wave N12-6: Participants accepted as attendance evidence + LINK_EXTRACTOR_VERSION_TS bump note; +22 P5 wanted pages: AuthoredRef on body link candidates; -33 lowered: P5 moved machine-section ranges to core/machine-sections.ts and stated relation types to core/line-grammar.ts; +7 P5: ExtractPageLinksOptions interface + wikilinkAuthoredRef helper (keeps extractPageLinks under the function-size limit); +32 P5: per-edge verb attachment (attachedVerb, VERB_RULES) + joined-as works_at + extractor watermark note; P5 x temporal-edges merge: verb attachment reads the verb at the link's own position in the window (excerptAnchor) and the within-page dedup (now dedupeCandidates) drops a mention of a target the page also links with a typed edge; links joined only by commas/conjunctions share the verb before the first (coordinated); board roles (BOARD_RE, BOARD_AFTER_RE) resolve to invested_in for an investor page and advises otherwise, never works_at; +1 fix wave 11 #6191: imports targetTakesVerb (role-verb target guard lives in link-target-roles.ts); v0.60.105.0 merge: #5984 Phase 5 link preparation (+6) re-summed over wave 11 at 2211; +109 Q2 Track C: stable verb-rule ids, traceLinkType/explainLinkType (reasons for every typing decision), per-occurrence typer hoisted out of extractPageLinks (makeTypeFor); unit logic lives in core/link-typing-units.ts; +25 Q2 Track C: typing-unit verb rules and vetoes in attachedVerb/traceLinkType, validity stints in explainLinkType; +4 U3: board-seat rule split out of INVESTED_RE (same verb and precedence) and investor-prior/link offsets passed to unit vetoes; +11 U2: locateLink shared by attachedVerb and the U2 post-pass in traceLinkType; -11 lowered: Q2 verdict reverted U2 (locateLink and the post-pass); +21 fix wave 13 P4.10 #6266: resolveSameDirSlug + exported resolveMarkdownLinkSlug, shared with the link validator; +41 Wave B PR 2 lane 2e: extractPageLinks split into extractBodyLinks (window-scoped, offset-shifted, pass-tagged candidates) and frontmatterLinks, plus entityRefPasses, candidateKey, rolePriorPhrases and the roleText/regexBudget/window options, so a segmented page streams through the same extractor (window and merge logic in core/page-body/segment-links.ts); +1 at the #6869 gate-ahead merge: the #6803 wave EXTRACTOR_BUMP_NOTES comment composed with lane 2e (2420 + 1)src/core/embedding-migration.ts 1587 ratchet new row: crossed 1500 in v0.46.25.0 fix waves (#4305 #4306 chunk-model truth helpers); retired provider integration removed; safety wave: canonical projection readiness and fact-aware completion; file configuration publication retains lease-row locks; +8 transactional retained-vector rebuildability checks before destructive migration boundaries; archived eligibility: source-locked reconciliation and live/current smoke revalidation; +2 #5680: authorization_generation field and its carry-forward on same-target re-apply (settle idempotency); +10 #5226: plan carries chunks_to_restamp beside chunks_to_embed; +9 #5088: schema transition defers HNSW builds into the marker (deferred_ann_indexes), carry-forward on re-apply, verify blocks on pending/INVALID ANN indexes (build phase in embedding-ann-build.ts); +10 #5088: dim-pinned tables (query_cache, facts, and any later entry of TEXT_EMBEDDING_DIM_PINNED_TABLES) defer their HNSW through the same worklist (DEFERRED_ANN_TABLES, recordDeferredAnnIndexes); +25 wave 8 lane D1 #5885: takes in the dim-pinned column list, plan (takes_to_embed), status (takes_pending) and completion verify; +17 #5334: smoke check samples one representative chunk per distinct page (bounded index-ordered batch walk, longest chunk re-read under the page lock, title-prefixed bounded query); +1 #5334: the smoke-query length limits are shared with the worst-case budgetsrc/core/github-source.ts 1530 ratchet new row: crossed the 1500 unlisted cap in v0.46.23.0 review fix wave (scope-state gating, client hardening, symlink containment); merged reliability/shared-skills source integration; managed sweep lease wrapper; fix wave 3 lane A: config parser peeled to github-source-config.ts (-47), +account pin wiring and pinned-installation refreshdiff --git a/scripts/page-body-readers-baseline.tsv b/scripts/page-body-readers-baseline.tsvindex 61f57b4f08..0669c2a5e1 100644--- a/scripts/page-body-readers-baseline.tsv+++ b/scripts/page-body-readers-baseline.tsv@@ -28,8 +28,6 @@ src/commands/doctor/checks/graph-health.ts runGraphCoverage field NONE not the psrc/commands/doctor/checks/graph-health.ts runGraphCoverage sql NONE not the page body: timeline coverage count aliassrc/commands/enrich.ts enrichOneLocked call:serializeMarkdown SEGWsrc/commands/enrich.ts enrichOneLocked field SEGW-src/commands/export.ts runExport call:serializeMarkdown SEGW-src/commands/export.ts runExport field STREAMsrc/commands/export.ts runExport sql STREAMsrc/commands/extract-conversation-facts.ts regularPageVersionToken field STREAMsrc/commands/extract-mentions-explain.ts explainMention field STREAM@@ -194,6 +192,9 @@ src/core/engine-sql/salience.ts listEnrichCandidates sql METAsrc/core/engine-sql/timeline.ts getTimeline sql NONE not the page body: SELECT * FROM pages inside a LATERAL used for the page id onlysrc/core/enrichment-service.ts enrichEntity call:putPage INLINEsrc/core/enrichment-service.ts enrichEntity call:serializeMarkdown INLINE+src/core/export-snapshot.ts inlineExportMarkdown call:serializeMarkdown SEGW+src/core/export-snapshot.ts inlineExportMarkdown field STREAM+src/core/export-snapshot.ts segmentedExportHead call:serializeMarkdown NONE not the page body: the frontmatter head, rendered with an empty bodysrc/core/export-snapshot.ts readExportPage field STREAM inline pages only: a segmented page skips the overlay here and streams through segmentedExportMarkdown (readBodyRange, trusted stored)src/core/export-snapshot.ts readExportPage sql STREAMsrc/core/extract-ner.ts extractNerLinks field STREAMdiff --git a/src/commands/doctor/checks/db-ahead-of-git.ts b/src/commands/doctor/checks/db-ahead-of-git.tsnew file mode 100644index 0000000000..3fe09cd40e--- /dev/null+++ b/src/commands/doctor/checks/db-ahead-of-git.ts@@ -0,0 +1,63 @@+/**+ * `db_ahead_of_git` (git-canonical memory, wave G1, docs/designs/GIT_CANONICAL_MEMORY.md): for each source with a+ * checkout, the totals of the read-only git-gap census (`gbrain sources git-gap`, commands/sources-git-gap.ts): pages+ * equal to their committed blob at HEAD, database_ahead or git_ahead of it, declared or undeclared database-only, only in+ * the working tree, unparseable. Informational in this release: always ok whatever the gap, because nothing converts a+ * source yet. Bounded by `GBRAIN_DOCTOR_GIT_GAP_TIMEOUT_MS` (default 10 s) and the entry's deadline; a source the budget+ * stopped or never reached is listed as partial; a source whose directory is not a Git checkout is only counted. Totals+ * only, never a slug or path.+ */+import { existsSync } from 'node:fs';+import type { Check } from '../../doctor.ts';+import { scanDeadline } from '../budget.ts';+import { connectedEngine, type DoctorContext, type DoctorEntry } from '../context.ts';+import { censusGitGap, GIT_GAP_DOCS, type GitGapCensus } from '../../sources-git-gap.ts';+import { isGitCheckout } from '../../../core/persistence/git-gap.ts';++/** `GBRAIN_DOCTOR_GIT_GAP_TIMEOUT_MS` (default 10 s): the wall-clock bound of the census across every source. */+export function gitGapScanTimeoutMs(): number {+ const n = parseInt(process.env.GBRAIN_DOCTOR_GIT_GAP_TIMEOUT_MS ?? '', 10);+ return Number.isFinite(n) && n > 0 ? n : 10_000;+}++type SourceTotals = Pick<GitGapCensus, 'source_id' | 'head' | 'complete' | 'pages' | 'states' | 'declared' | 'worktree'>;++const nonzero = (record: Record<string, number>) => Object.entries(record).filter(([, n]) => n > 0).map(([k, n]) => `${n} ${k}`).join(', ') || 'no pages';++async function runDbAheadOfGit(ctx: DoctorContext): Promise<Check[]> {+ const engine = connectedEngine(ctx);+ const checks: Check[] = [];+ ctx.progress.heartbeat('db_ahead_of_git');+ const deadlineAt = scanDeadline(ctx, gitGapScanTimeoutMs());+ try {+ const rows = await engine.executeRaw<{ id: string; local_path: string | null }>('SELECT id, local_path FROM sources WHERE NOT archived ORDER BY id');+ const withCheckout = rows.filter(row => row.local_path && existsSync(row.local_path) && isGitCheckout(row.local_path));+ const sources: SourceTotals[] = [], unread: string[] = [], errors: Array<{ source_id: string; message: string }> = [];+ for (const row of withCheckout) {+ if (Date.now() >= deadlineAt) { unread.push(row.id); continue; }+ try {+ const { source_id, head, complete, pages, states, declared, worktree } = await censusGitGap(engine, row.id, { sample: 0, deadlineAt });+ sources.push({ source_id, head, complete, pages, states, declared, worktree });+ } catch (error) {+ errors.push({ source_id: row.id, message: error instanceof Error ? error.message : String(error) });+ }+ }+ const partial = [...sources.filter(source => !source.complete).map(source => source.source_id), ...unread];+ const details = { informational: true, sources, partial_sources: partial, errors, sources_without_git_checkout: rows.length - withCheckout.length,+ timeout_ms: gitGapScanTimeoutMs(), docs: GIT_GAP_DOCS };+ const listed = sources.map(source => `${source.source_id}: ${nonzero(source.states)}${source.complete ? '' : ' (partial)'}`);+ const message = withCheckout.length+ ? `Informational, nothing to do: the database compared with the commit at HEAD, per source with a Git checkout.${listed.length ? ` ${listed.join('; ')}.` : ''}`+ + `${unread.length ? ` Not reached within the ${details.timeout_ms / 1000}s budget: ${unread.join(', ')}.` : ''}`+ + `${errors.length ? ` Could not compare: ${errors.map(e => `${e.source_id} (${e.message})`).join('; ')}.` : ''}`+ + ` Page detail: gbrain sources git-gap <source-id>.`+ : 'No source has a Git checkout, so there is no commit to compare the database with.';+ checks.push({ name: 'db_ahead_of_git', status: 'ok', details, message });+ } catch (error) {+ checks.push({ name: 'db_ahead_of_git', status: 'ok', details: { informational: true, health: 'unknown', docs: GIT_GAP_DOCS },+ message: `Informational: the git-gap census could not run (${error instanceof Error ? error.message : String(error)}); run gbrain sources git-gap <source-id> for one source.` });+ }+ return checks;+}++export const dbAheadOfGitEntry: DoctorEntry = { name: 'db_ahead_of_git', emits: ['db_ahead_of_git'], run: runDbAheadOfGit };diff --git a/src/commands/doctor/registry.ts b/src/commands/doctor/registry.tsindex cb6198e38c..f667754f72 100644--- a/src/commands/doctor/registry.ts+++ b/src/commands/doctor/registry.ts@@ -122,6 +122,7 @@ import { chatFallbackChainEntry } from './checks/chat-fallback.ts';import { providerConsentEntry } from './checks/provider-consent.ts';import { behaviorChangesEntry } from './checks/behavior-changes.ts';import { fenceIntegrityEntry } from './checks/fence-integrity.ts';+import { dbAheadOfGitEntry } from './checks/db-ahead-of-git.ts';import { syncConfigKeysEntry } from './checks/sync-config-keys.ts';import { ghostPagesEntry } from './checks/ghost-pages.ts';import { originTwinsEntry } from './checks/origin-twins.ts';@@ -285,6 +286,8 @@ export const DOCTOR_CHECK_REGISTRY: readonly DoctorEntry[] = [managedSyncConvergenceEntry,// #7160: title-prefixed person pages next to the unprefixed page (read-only, preview-first).personTitleDuplicatesEntry,+ // Git-canonical G1: the read-only git-gap census totals per source with a checkout (informational, always ok).+ dbAheadOfGitEntry,fenceIntegrityEntry,searchModeEntry,];diff --git a/src/commands/export.ts b/src/commands/export.tsindex 05b2c930cb..f2f85ba7c0 100644--- a/src/commands/export.ts+++ b/src/commands/export.ts@@ -1,6 +1,5 @@import { existsSync } from 'node:fs';import type { BrainEngine } from '../core/engine.ts';-import { serializeMarkdown, slugStampedFrontmatter } from '../core/markdown.ts';import { scannerSlugRootMode } from '../core/write-through.ts';import { createProgress } from '../core/progress.ts';import { getCliOptions, cliOptsToProgressOptions } from '../core/cli-options.ts';@@ -12,7 +11,7 @@ import { ExportPathCollision, ExportStage, EXPORT_PAYLOAD_LIMIT, EXPORT_SNAPSHOTimport { slugPortabilityProblem } from '../core/portable-slug.ts';import { publishExport } from '../core/export-publish.ts';import { nativeFileTarget } from '../core/persistence/native-file-target.ts';-import { exportBodyLedger, readExportPage, readExportWithdrawals, segmentedExportMarkdown } from '../core/export-snapshot.ts';+import { exportBodyLedger, inlineExportMarkdown, readExportPage, readExportWithdrawals, segmentedExportHead, segmentedExportMarkdown } from '../core/export-snapshot.ts';import { segmentedPageCeiling } from '../core/page-body/limits.ts';import { isSegmentedPage } from '../core/page-body/page-shape.ts';@@ -148,18 +147,14 @@ a fresh directory. See docs/storage-tiering.md#safe-export.`);if (Number(key.bytes) > (key.segmented ? segmentedLimit : EXPORT_PAYLOAD_LIMIT)) throw new Error('Export page payload limit exceeded. No destination output was published.');const snapshot = await readExportPage(tx, key, withdrawals);const page = snapshot.page;- // #5966: the slug stamp rule lives in slugStampedFrontmatter (markdown.ts), shared with every render; an- // escaped file always carries its slug.- const frontmatter = target.escaped ? { ...(page.frontmatter ?? {}), slug: page.slug } : slugStampedFrontmatter(page.slug, page.frontmatter ?? {});- const meta = { type: page.type, title: page.title, tags: snapshot.tags };const label = `${page.source_id}:${page.slug}`;const raw = Number(key.raw_count) ? await tx.getRawData(page.slug, undefined, { sourceId: page.source_id, includeDeleted: true }) : [];try {if (isSegmentedPage(page)) {streamedBytes += Number(key.bytes);- const head = serializeMarkdown(frontmatter, '', '', meta).slice(0, -1);- await staged.addStream(target.path, Number(key.bytes), segmentedLimit, segmentedExportMarkdown(tx, page, exportBodyLedger(page.slug, withdrawals), head));- } else staged.add(target.path, 'file', serializeMarkdown(frontmatter, page.compiled_truth, page.timeline, meta));+ await staged.addStream(target.path, Number(key.bytes), segmentedLimit,+ segmentedExportMarkdown(tx, page, exportBodyLedger(page.slug, withdrawals), segmentedExportHead(snapshot, target.escaped)));+ } else staged.add(target.path, 'file', inlineExportMarkdown(snapshot, target.escaped));owners.set(target.path, { source_id: page.source_id, label });if (raw.length) {staged.add(target.rawPath, 'file', JSON.stringify(Object.fromEntries(raw.map(row => [row.source, row.data])), null, 2) + '\n');diff --git a/src/commands/sources-git-gap.ts b/src/commands/sources-git-gap.tsnew file mode 100644index 0000000000..c4da4138bc--- /dev/null+++ b/src/commands/sources-git-gap.ts@@ -0,0 +1,335 @@+/**+ * `gbrain sources git-gap <source-id>` (git-canonical memory, wave G1, docs/designs/GIT_CANONICAL_MEMORY.md): a read-only+ * census of how far one source's database is from the commit its checkout has at HEAD. Every live page lands in exactly+ * one state: equal to its committed blob, database_ahead or git_ahead of it, declared database-only (with its class),+ * undeclared database-only (no blob at HEAD and no declared reason), worktree_only (a file that is not committed),+ * unparseable or unsafe_path. The working tree is reported separately. It also counts the rows that have no Git home+ * (unfenced facts, fenced facts on pages with no file, links no file derives, timeline rows on pages with no file), the+ * source's open sync holds by code and its parked effect targets by code.+ *+ * Nothing is written. Each 256-page batch reads in its own read-only transaction; Git runs only as hardened plumbing+ * (persistence/git-gap.ts), so no repository filter or textconv ever runs. Trusted local CLI only, not an MCP operation:+ * it prints slugs and paths. Doctor `db_ahead_of_git` runs the same census within its budget.+ */+import { existsSync, realpathSync } from 'node:fs';+import { relative, sep } from 'node:path';+import type { BrainEngine } from '../core/engine.ts';+import { setCliExitVerdict } from '../core/cli-force-exit.ts';+import { OperationError } from '../core/ops/contract.ts';+import { cliRenderContext, toAgentError } from '../core/agent-output.ts';+import { readExportPage, readExportWithdrawals, type ExportWithdrawal } from '../core/export-snapshot.ts';+import { RestoreTargetError, restoreFilePath } from '../core/restore-target.ts';+import { privatePagesFilterFragment, readHonorAliases } from '../core/search/private-visibility.ts';+import { resolveSourceId } from '../core/source-resolver.ts';+import { sourceMirrorReadOnly } from '../core/persistence/mirror-read-only.ts';+import { isSourceDbOnlySlug } from '../core/persistence/source-storage.ts';+import { GIT_HOLD_OP, readSyncImportProvenances } from '../core/persistence/sync-holds.ts';+import { DERIVED_LINK_SOURCES } from '../core/persistence/twin-merge.ts';+import { scannerSlugRootMode, scannerSourcePath } from '../core/write-through.ts';+import { compareInlineExportFile, compareSegmentedExportBlob, DECLARED_CLASSES, declaredDatabaseOnly, ignoredPaths, readBlobs, readHeadTree, worktreeBlobOid,+ type DeclaredClass, type ExportFileComparison, type HeadTree, type TreeBlob } from '../core/persistence/git-gap.ts';++const USAGE = 'Usage: gbrain sources git-gap <source-id> [--sample <n>] [--json]';+export const GIT_GAP_DOCS = 'docs/designs/GIT_CANONICAL_MEMORY.md#the-git-gap-census';+const BATCH = 256;++export const PAGE_STATES = ['equal', 'database_ahead', 'git_ahead', 'declared_database_only', 'undeclared_database_only', 'worktree_only', 'unparseable', 'unsafe_path'] as const;+export type PageState = typeof PAGE_STATES[number];+export const WORKTREE_STATES = ['clean', 'modified', 'deleted', 'untracked', 'absent'] as const;+export type WorktreeState = typeof WORKTREE_STATES[number];++export interface GitGapSample { slug: string; path: string; state: PageState; fields?: string[]; declared?: DeclaredClass; basis?: 'import_record' | 'no_import_record'; worktree?: WorktreeState }++export interface GitGapCensus {+ status: 'census';+ source_id: string;+ checkout: string | null;+ /** The commit compared against; null when the source has no checkout or its branch has no commit. */+ head: string | null;+ /** False when a doctor budget stopped the page scan; the counts cover the pages read so far. */+ complete: boolean;+ pages: number;+ states: Record<PageState, number>;+ declared: Record<DeclaredClass, number>;+ /** Declared pages whose file is still committed at HEAD (for example a page that turned private). */+ declared_with_head_blob: number;+ /** database_ahead pages with no import record, so the side that moved is unknown (see the design doc). */+ database_ahead_without_import_record: number;+ /** git_ahead pages whose row also moved since its last import: both sides changed. */+ git_ahead_database_also_moved: number;+ /** Pages of a source without a checkout that are not declared: nothing to compare them with. */+ not_compared: number;+ /** Working-tree files of the pages that may have a tracked file, by their raw bytes against HEAD; null without a checkout. */+ worktree: Record<WorktreeState, number> | null;+ rows_without_git_home: {+ facts_unfenced: number;+ facts_fence_page_missing: number;+ facts_on_pages_without_file: { undeclared: number; declared: number };+ links: { total: number; by_link_source: Record<string, number> };+ timeline_on_pages_without_file: { undeclared: number; declared: number };+ };+ holds: Record<string, number>;+ parked_effects: Array<{ kind: string; code: string; targets: number }>;+ sample: GitGapSample[];+ next: string;+}++export function parseGitGapArgs(args: string[]): { sourceId: string; json: boolean; sample: number } {+ const positional: string[] = [];+ let sample = 20;+ for (let i = 0; i < args.length; i++) {+ const arg = args[i]!;+ if (arg === '--sample') {+ const raw = args[++i];+ sample = Number(raw);+ if (raw === undefined || !Number.isInteger(sample) || sample < 0 || sample > 1000) {+ throw new OperationError('invalid_params', `--sample needs a whole number from 0 to 1000; got ${raw ?? 'nothing'}.`, USAGE);+ }+ continue;+ }+ if (arg.startsWith('-')) {+ if (arg !== '--json') throw new OperationError('invalid_params', `Unknown sources git-gap flag: ${arg}.`, USAGE);+ continue;+ }+ positional.push(arg);+ }+ if (positional.length !== 1) throw new OperationError('invalid_params', 'sources git-gap needs exactly one source id.', USAGE);+ return { sourceId: positional[0]!, json: args.includes('--json'), sample };+}++type Key = { id: string; slug: string; source_id: string; source_path: string | null; source_path_bytes: number; source_uri: string | null; type: string;+ frontmatter: unknown; database_only_reason: string | null; segmented: boolean; lineage_private: boolean; revision: string | null };++const zeros = <K extends string>(keys: readonly K[]) => Object.fromEntries(keys.map(key => [key, 0])) as Record<K, number>;++function emptyCensus(sourceId: string, root: string | null, head: HeadTree | null): GitGapCensus {+ return { status: 'census', source_id: sourceId, checkout: root, head: head?.commit ?? null, complete: true, pages: 0, states: zeros(PAGE_STATES),+ declared: zeros(DECLARED_CLASSES), declared_with_head_blob: 0, database_ahead_without_import_record: 0, git_ahead_database_also_moved: 0, not_compared: 0,+ worktree: root ? zeros(WORKTREE_STATES) : null,+ rows_without_git_home: { facts_unfenced: 0, facts_fence_page_missing: 0, facts_on_pages_without_file: { undeclared: 0, declared: 0 },+ links: { total: 0, by_link_source: {} }, timeline_on_pages_without_file: { undeclared: 0, declared: 0 } },+ holds: {}, parked_effects: [], sample: [],+ next: `Nothing changed. This release only reports the gap; converting a source to git-canonical arrives in a later release (${GIT_GAP_DOCS}).` };+}++/** The checkout side of a census: the source root, HEAD, the slug root mode and the source's directory inside the checkout. */+interface Checkout { root: string; head: HeadTree; mode: Awaited<ReturnType<typeof scannerSlugRootMode>>; scope: string }++const refuse = (message: string, suggestion: string) => new OperationError('storage_error', message, suggestion, GIT_GAP_DOCS);++export async function censusGitGap(engine: BrainEngine, sourceId: string, opts: { sample: number; deadlineAt?: number }): Promise<GitGapCensus> {+ await resolveSourceId(engine, sourceId, undefined, { skipLocalSignals: true });+ const [source] = await engine.executeRaw<{ local_path: string | null; incarnation: string }>('SELECT local_path, incarnation::text AS incarnation FROM sources WHERE id=$1', [sourceId]);+ const root = source?.local_path && existsSync(source.local_path) ? source.local_path : null;+ const mirror = await sourceMirrorReadOnly(engine, sourceId);+ if (root) isSourceDbOnlySlug(root, '', 'refuse');+ await readHonorAliases(engine);+ let checkout: Checkout | null = null;+ if (root) {+ const head = await readHeadTree(root);+ if (!head) throw refuse(`Git could not list HEAD of the checkout at ${root}, so nothing can be compared.`,+ `Nothing changed. Check that ${root} is a Git checkout (git -C ${root} rev-parse HEAD), then rerun gbrain sources git-gap ${sourceId}.`);+ const scope = relative(head.gitRoot, realpathSync(root)).split(sep).join('/');+ checkout = { root, head, mode: await scannerSlugRootMode(engine, sourceId, root), scope };+ }+ const census = emptyCensus(sourceId, root, checkout?.head ?? null);+ const policy = { mirror, dbOnly: (slug: string) => root !== null && isSourceDbOnlySlug(root, slug, 'refuse'), ignored: new Set<string>() };+ for (let cursor = '0'; ;) {+ if (opts.deadlineAt !== undefined && Date.now() >= opts.deadlineAt) { census.complete = false; break; }+ const done = await engine.transaction(async tx => {+ await tx.executeRaw('SET TRANSACTION READ ONLY');+ const batch = await tx.executeRaw<Key>(`SELECT id::text, slug, source_id, source_path, octet_length(source_path) AS source_path_bytes, source_uri, type, frontmatter,+ database_only_reason, body_storage='segmented' AS segmented, knowledge_revision::text AS revision, NOT ${privatePagesFilterFragment('pages')} AS lineage_private+ FROM pages WHERE source_id=$1 AND deleted_at IS NULL AND pages.id > $2::bigint ORDER BY pages.id LIMIT ${BATCH}`, [sourceId, cursor]);+ if (batch.length) { await censusBatch(tx, batch, census, { checkout, policy, incarnation: source!.incarnation, sample: opts.sample }); cursor = batch[batch.length - 1]!.id; }+ return batch.length < BATCH;+ });+ if (done) break;+ }+ await engine.transaction(async tx => {+ await tx.executeRaw('SET TRANSACTION READ ONLY');+ await countSourceRows(tx, census);+ });+ return census;+}++interface BatchContext { checkout: Checkout | null; policy: { mirror: boolean; dbOnly: (slug: string) => boolean; ignored: Set<string> }; incarnation: string; sample: number }++function note(census: GitGapCensus, limit: number, item: GitGapSample): void {+ if (census.sample.length < limit) census.sample.push(item);+}++/** One batch: classify every page, compare the ones with a committed blob, and count the rows of the pages without a file. */+async function censusBatch(tx: BrainEngine, batch: Key[], census: GitGapCensus, ctx: BatchContext): Promise<void> {+ const { checkout } = ctx;+ const target = (key: Key): string | null => {+ try { return restoreFilePath(checkout!.root, key.slug, key.source_path, Number(key.source_path_bytes), checkout!.mode); }+ catch (error) { if (error instanceof RestoreTargetError) return null; throw error; }+ };+ const rows = batch.map(key => {+ const path = checkout ? target(key) : null;+ return { key, path, rel: path ? relative(checkout!.root, path).split(sep).join('/') : null };+ });+ if (checkout) {+ const ignored = await ignoredPaths(checkout.root, rows.flatMap(row => row.rel === null ? [] : [row.rel]));+ if (!ignored) throw refuse(`Git could not say which paths the checkout at ${checkout.root} ignores, so the declared classes are unknown.`,+ `Nothing changed. Check that ${checkout.root} is a Git checkout (git -C ${checkout.root} rev-parse HEAD), then rerun gbrain sources git-gap ${batch[0]!.source_id}.`);+ ctx.policy.ignored = ignored;+ }+ const noFile = { undeclared: [] as Key[], declared: [] as Key[] };+ const compare: Array<{ key: Key; path: string; rel: string; blob: TreeBlob; worktree: WorktreeState }> = [];+ for (const { key, path, rel } of rows) {+ census.pages++;+ const frontmatter = typeof key.frontmatter === 'string' ? JSON.parse(key.frontmatter) : key.frontmatter;+ const declared = declaredDatabaseOnly({ ...key, frontmatter }, rel, ctx.policy);+ const blob = checkout && rel !== null ? checkout.head.blobs.get(checkout.scope ? `${checkout.scope}/${rel}` : rel) : undefined;+ if (declared) {+ census.declared[declared]++;+ census.states.declared_database_only++;+ if (blob) { census.declared_with_head_blob++; note(census, ctx.sample, { slug: key.slug, path: rel!, state: 'declared_database_only', declared }); }+ else if (checkout) noFile.declared.push(key);+ continue;+ }+ if (!checkout) { census.not_compared++; continue; }+ if (!path || rel === null) {+ census.states.unsafe_path++;+ noFile.undeclared.push(key);+ note(census, ctx.sample, { slug: key.slug, path: key.source_path ?? '', state: 'unsafe_path' });+ continue;+ }+ const oid = await worktreeBlobOid(path, checkout.head.format);+ if (!blob) {+ const state: PageState = oid === null ? 'undeclared_database_only' : 'worktree_only';+ census.worktree![oid === null ? 'absent' : 'untracked']++;+ census.states[state]++;+ noFile.undeclared.push(key);+ note(census, ctx.sample, { slug: key.slug, path: rel, state, worktree: oid === null ? 'absent' : 'untracked' });+ continue;+ }+ const worktree: WorktreeState = oid === null ? 'deleted' : oid === blob.oid ? 'clean' : 'modified';+ census.worktree![worktree]++;+ if (blob.mode !== '100644' && blob.mode !== '100755') {+ census.states.unparseable++;+ note(census, ctx.sample, { slug: key.slug, path: rel, state: 'unparseable', worktree });+ continue;+ }+ compare.push({ key, path, rel, blob, worktree });+ }+ if (compare.length) await compareBatch(tx, compare, census, ctx);+ await countRowsWithoutFile(tx, batch[0]!.source_id, noFile, census);+}++async function compareBatch(tx: BrainEngine, compare: Array<{ key: Key; path: string; rel: string; blob: TreeBlob; worktree: WorktreeState }>, census: GitGapCensus,+ ctx: BatchContext): Promise<void> {+ const checkout = ctx.checkout!;+ const sourceId = compare[0]!.key.source_id;+ const blobs = await readBlobs(checkout.root, compare.filter(item => !item.key.segmented).map(item => item.blob));+ if (!blobs) throw refuse(`Git could not read committed files of the checkout at ${checkout.root}.`,+ `Nothing changed. Check the checkout with git -C ${checkout.root} fsck, then rerun gbrain sources git-gap ${sourceId}.`);+ const withdrawals: ExportWithdrawal[] = await readExportWithdrawals(tx, sourceId);+ const differs: Array<{ key: Key; rel: string; blob: TreeBlob; worktree: WorktreeState; fields: string[] }> = [];+ for (const item of compare) {+ const snapshot = await readExportPage(tx, item.key, withdrawals);+ const compared: ExportFileComparison = item.key.segmented ? await compareSegmentedExportBlob(tx, snapshot, withdrawals, item.blob, checkout.head.format)+ : compareInlineExportFile(blobs.get(item.blob.oid)!, scannerSourcePath(checkout.root, item.path, checkout.mode), snapshot);+ if (compared.state === 'equal') { census.states.equal++; continue; }+ if (compared.state === 'unparseable') {+ census.states.unparseable++;+ note(census, ctx.sample, { slug: item.key.slug, path: item.rel, state: 'unparseable', worktree: item.worktree });+ continue;+ }+ differs.push({ ...item, fields: compared.paths });+ }+ if (!differs.length) return;+ const records = await readSyncImportProvenances(tx, sourceId, ctx.incarnation, differs.map(item => Number(item.key.id)));+ for (const item of differs) {+ const record = records.get(Number(item.key.id));+ const imported = [record?.blob_oid, record?.disk_blob_oid].filter((oid): oid is string => typeof oid === 'string' && oid.length > 0);+ const gitMoved = imported.length > 0 && !imported.includes(item.blob.oid);+ const state: PageState = gitMoved ? 'git_ahead' : 'database_ahead';+ census.states[state]++;+ if (!imported.length) census.database_ahead_without_import_record++;+ if (gitMoved && record?.revision != null && String(record.revision) !== String(item.key.revision)) census.git_ahead_database_also_moved++;+ note(census, ctx.sample, { slug: item.key.slug, path: item.rel, state, fields: item.fields, basis: imported.length ? 'import_record' : 'no_import_record', worktree: item.worktree });+ }+}++/** Fenced fact rows and timeline rows of this batch's pages that have no committed file. */+async function countRowsWithoutFile(tx: BrainEngine, sourceId: string, noFile: { undeclared: Key[]; declared: Key[] }, census: GitGapCensus): Promise<void> {+ const rows = census.rows_without_git_home;+ for (const side of ['undeclared', 'declared'] as const) {+ const keys = noFile[side];+ if (!keys.length) continue;+ const [facts] = await tx.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM facts WHERE source_id=$1 AND row_num IS NOT NULL AND source_markdown_slug = ANY($2::text[])`,+ [sourceId, keys.map(key => key.slug)]);+ const [timeline] = await tx.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM timeline_entries WHERE page_id = ANY($1::int[])', [keys.map(key => Number(key.id))]);+ rows.facts_on_pages_without_file[side] += Number(facts?.n ?? 0);+ rows.timeline_on_pages_without_file[side] += Number(timeline?.n ?? 0);+ }+}++/**+ * Source-wide rows with no Git home and the source's open holds and parked targets. A link has a Git home only when a+ * file derives it (DERIVED_LINK_SOURCES: markdown, frontmatter, mentions, wikilink-resolved); every other provenance+ * (manual, a custom tag, concept-provenance, atom-provenance, a legacy NULL) is counted, by provenance.+ */+async function countSourceRows(tx: BrainEngine, census: GitGapCensus): Promise<void> {+ const sourceId = census.source_id;+ const rows = census.rows_without_git_home;+ const [unfenced] = await tx.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM facts WHERE source_id=$1 AND row_num IS NULL AND expired_at IS NULL', [sourceId]);+ rows.facts_unfenced = Number(unfenced?.n ?? 0);+ const [missing] = await tx.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM facts f WHERE f.source_id=$1 AND f.row_num IS NOT NULL+ AND NOT EXISTS (SELECT 1 FROM pages p WHERE p.source_id=f.source_id AND p.slug=f.source_markdown_slug AND p.deleted_at IS NULL)`, [sourceId]);+ rows.facts_fence_page_missing = Number(missing?.n ?? 0);+ const links = await tx.executeRaw<{ link_source: string; n: number }>(`SELECT COALESCE(l.link_source, '(none)') AS link_source, count(*)::int AS n+ FROM links l JOIN pages p ON p.id=l.from_page_id WHERE p.source_id=$1 AND p.deleted_at IS NULL AND (l.link_source IS NULL OR NOT (l.link_source = ANY($2::text[])))+ GROUP BY 1 ORDER BY 1`, [sourceId, DERIVED_LINK_SOURCES]);+ rows.links = { total: links.reduce((sum, row) => sum + Number(row.n), 0), by_link_source: Object.fromEntries(links.map(row => [row.link_source, Number(row.n)])) };+ const holds = await tx.executeRaw<{ code: string; n: number }>(`SELECT h.completed_keys->0->>'code' AS code, count(*)::int AS n FROM op_checkpoints h+ JOIN sources s ON s.id=h.completed_keys->0->>'source_id' AND s.incarnation::text=h.completed_keys->0->>'incarnation'+ WHERE h.op=$1 AND s.id=$2 GROUP BY 1 ORDER BY 1`, [GIT_HOLD_OP, sourceId]);+ census.holds = Object.fromEntries(holds.map(row => [row.code ?? 'unknown', Number(row.n)]));+ const parked = await tx.executeRaw<{ kind: string; code: string | null; targets: number }>(`SELECT e.kind, p->>'error_code' AS code, count(*)::int AS targets+ FROM persistence_effects e CROSS JOIN LATERAL jsonb_array_elements(CASE WHEN jsonb_typeof(e.data->'parked')='array' THEN e.data->'parked' ELSE '[]'::jsonb END) p+ WHERE e.source_id=$1 GROUP BY 1, 2 ORDER BY 1, 2`, [sourceId]);+ census.parked_effects = parked.map(row => ({ kind: row.kind, code: row.code ?? 'unknown', targets: Number(row.targets) }));+}++const counts = (record: Record<string, number>) => Object.entries(record).filter(([, n]) => n > 0).map(([k, n]) => `${k} ${n}`).join(', ') || 'none';++export function describeGitGap(census: GitGapCensus): string {+ const lines = [`Git gap of source ${census.source_id} (read-only): ${census.pages} live page(s)${census.head ? `, compared with HEAD ${census.head.slice(0, 12)}` : ''}.`];+ if (!census.checkout) lines.push(`The source has no checkout, so ${census.not_compared} page(s) were not compared.`);+ else if (!census.head) lines.push('The checkout has no commit yet, so no page has a committed file.');+ lines.push(`Pages: ${counts(census.states)}.`, `Declared database-only: ${counts(census.declared)}${census.declared_with_head_blob ? ` (${census.declared_with_head_blob} still committed at HEAD)` : ''}.`);+ if (census.database_ahead_without_import_record) lines.push(`${census.database_ahead_without_import_record} database_ahead page(s) have no import record, so the side that moved is unknown.`);+ if (census.git_ahead_database_also_moved) lines.push(`${census.git_ahead_database_also_moved} git_ahead page(s) also changed in the database since their last import.`);+ if (census.worktree) lines.push(`Working tree against HEAD: ${counts(census.worktree)}.`);+ const rows = census.rows_without_git_home;+ lines.push(`Rows with no Git home: facts unfenced ${rows.facts_unfenced}, fenced on a missing page ${rows.facts_fence_page_missing}, `+ + `fenced on a page without a file ${rows.facts_on_pages_without_file.undeclared} (+${rows.facts_on_pages_without_file.declared} declared); `+ + `links ${rows.links.total} (${counts(rows.links.by_link_source)}); timeline rows on a page without a file ${rows.timeline_on_pages_without_file.undeclared} `+ + `(+${rows.timeline_on_pages_without_file.declared} declared).`);+ lines.push(`Open sync holds: ${counts(census.holds)}. Parked effect targets: ${census.parked_effects.map(p => `${p.kind} ${p.code} ${p.targets}`).join(', ') || 'none'}.`);+ for (const item of census.sample) {+ lines.push(` ${item.state}${item.declared ? ` (${item.declared})` : ''}: ${item.slug} (${item.path})${item.fields ? ` fields ${item.fields.join(', ')}` : ''}${item.worktree ? ` worktree ${item.worktree}` : ''}`);+ }+ if (!census.complete) lines.push('PARTIAL: the scan stopped at its time budget, so the counts cover only the pages read.');+ lines.push(census.next);+ return lines.join('\n');+}++export async function runSourcesGitGap(engine: BrainEngine, args: string[]): Promise<void> {+ const json = args.includes('--json');+ if (args.includes('--help') || args.includes('-h')) { console.log(`${USAGE}\nRead-only: compares each page of the source with its committed file at HEAD (${GIT_GAP_DOCS}).`); return; }+ try {+ const parsed = parseGitGapArgs(args);+ const census = await censusGitGap(engine, parsed.sourceId, { sample: parsed.sample });+ console.log(json ? JSON.stringify(census) : describeGitGap(census));+ } catch (error) {+ if (!(error instanceof OperationError)) throw error;+ const env = toAgentError(error, { transport: 'cli', command: 'sources git-gap', render: cliRenderContext() });+ console.log(json ? JSON.stringify({ status: 'refused', ...env }) : `Census refused (${error.code}): ${error.message}\nFix: ${error.suggestion ?? USAGE}`);+ setCliExitVerdict(1);+ }+}diff --git a/src/commands/sources.ts b/src/commands/sources.tsindex 6409b3e667..103dc22d13 100644--- a/src/commands/sources.ts+++ b/src/commands/sources.ts@@ -20,6 +20,7 @@* gbrain sources unfederate <id> — sources.config.federated = false* gbrain sources mirror-readonly|mirror-writable <id> — sources.config.mirror_read_only (#5409)* gbrain sources refresh <id> — drained worktree-wide ff-only refresh on a managed brain (F0)+ * gbrain sources git-gap <id> — read-only census of the database against the commit at HEAD (sources-git-gap.ts)* gbrain sources push [<id>|--path <dir>] — scan-gated add→commit→pull→push* (agent-bootstrap; core in src/core/workspace-push.ts)*@@ -1907,6 +1908,7 @@ export async function runSources(engine: BrainEngine, args: string[]): Promise<vcase 'set-pull-strategy': return (await import('./sources-pull-strategy.ts')).runSetPullStrategy(engine, rest);case 'set-sync': return (await import('./sources-sync-enabled.ts')).runSetSync(engine, rest);case 'refresh': return (await import('./sources-refresh.ts')).runSourcesRefresh(engine, rest);+ case 'git-gap': return (await import('./sources-git-gap.ts')).runSourcesGitGap(engine, rest);case 'archive': return runArchive(engine, rest);case 'restore': return runRestore(engine, rest);case 'purge': return runPurge(engine, rest);@@ -2011,6 +2013,8 @@ Subcommands:Managed brains: drain writes to the source's worktree, fast-forwardit to its upstream (git merge --ff-only) and sync every source boundto it. --dry-run fetches and previews only.+ git-gap <id> [--sample <n>] [--json]+ Read-only: how far the database is from the commit at HEAD, page by page.set-cr-mode <id> <none|title|per_chunk_synopsis>Per-source contextual retrieval modeoverride (v0.40.3.0). Pass "unset" ordiff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.tsindex 2011131857..3a2df4715b 100644--- a/src/core/cli-flag-registry.generated.ts+++ b/src/core/cli-flag-registry.generated.ts@@ -50,7 +50,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'db-repair': ['--accept-pending', '--apply', '--apply-rewrites', '--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', '--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', '--asof', '--body', '--bound-slug-prefixes', '--brain', '--budget-ms', '--client', '--count', '--cursor', '--date', '--dated-since', '--days', '--detach', '--entities', '--expect', '--expected-revision', '--federated-read', '--format', '--from-index', '--full', '--fuzzy', '--group-by', '--held', '--help', '--http', '--id', '--include-ambiguous', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--no-pull', '--no-walk', '--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', '--accept-pending', '--access', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt', '--adopt-columns', '--adopt-permissions', '--after', '--aggressive', '--aliases', '--all', '--all-drifted', '--all-from', '--allow-old-serve', '--allow-outside-source-root', '--allow-shell-jobs', '--allow-unverified-remote', '--allowed-operations', '--applied', '--apply', '--apply-rewrites', '--assign-corpus', '--audit', '--auto', '--auto-additive', '--auto-fix', '--autostash', '--background', '--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', '--by-mention', '--cached', '--cacheinfo', '--call-site', '--catch-up', '--channel', '--check', '--cherry-mark', '--class', '--clear', '--clear-never-installed', '--cli-socket', '--client', '--close', '--concurrency', '--confidence', '--confirm', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--content-root', '--conversation', '--count', '--cursor', '--dataset', '--day', '--db-url', '--delegated-namespace', '--delegated-slug-prefixes', '--delete-brain', '--dest', '--detach', '--detail', '--diff-filter', '--dim', '--dimensions', '--dir', '--disable', '--drain', '--drain-timeout', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--enable', '--enable-dcr', '--end-of-options', '--entity', '--env', '--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-read', '--fetch-timeout-ms', '--ff-only', '--file', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-remove', '--force-retry', '--force-schema', '--format', '--fresh', '--fresh-token', '--from', '--from-meetings', '--from-pages', '--full', '--fuzzy', '--generation', '--get', '--get-all', '--get-url', '--git-common-dir', '--git-dir', '--git-path', '--group', '--group-by', '--hard', '--hard-deadline', '--harness', '--held', '--help', '--hold-state', '--holds', '--home', '--http', '--id', '--if-version', '--ignore-env-override', '--images', '--include-ambiguous', '--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', '--install', '--is-ancestor', '--is-inside-work-tree', '--items-out', '--job-isolation', '--jq', '--json', '--keep', '--keep-checkout', '--key', '--kind', '--lanes', '--lang', '--left-right', '--legacy-lock', '--limit', '--link-source', '--link-type', '--list', '--literal-pathspecs', '--local', '--local-env-vars', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-count', '--max-facts', '--max-jobs', '--max-rss', '--max-runtime', '--max-usd', '--max-waiting', '--mcp-only', '--merge-base', '--migrate-legacy', '--migrate-only', '--migration', '--min', '--min-n', '--mode', '--model', '--multimodal', '--name', '--name-only', '--name-status', '--nice', '--no-accept-pending', '--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-filters', '--no-gpg-sign', '--no-hooks', '--no-lanes', '--no-llm', '--no-merges', '--no-migrate', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-restart', '--no-schema-pack', '--no-seat', '--no-tags', '--no-verify', '--no-walk', '--no-write-fetch-head', '--non-interactive', '--not', '--now', '--older-than', '--once', '--only', '--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', '--preset', '--preview', '--probe', '--probe-pglite', '--profile', '--progress-interval', '--progress-json', '--project', '--provenance', '--provider', '--providers', '--prune-orphans', '--public-url', '--pull', '--pure', '--purge', '--push', '--push-only', '--query', '--question', '--queue', '--quiet', '--rate', '--reader-mode', '--reauth', '--rebase', '--rebuild', '--recommended', '--redact-paths', '--reference-date', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--relative', '--relower', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--repair', '--repair-unknown-markers', '--replace', '--repo', '--request', '--request-id', '--require-clean', '--reranker', '--reset', '--reset-checkpoint', '--reset-default', '--resolve', '--restart-only', '--restore-only', '--resume', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--reverse', '--review-lower', '--revision', '--right-only', '--rollback-to-source', '--root', '--run', '--save', '--scope', '--scopes', '--search-mode', '--seat', '--section', '--select', '--self-transfer', '--semantic', '--session', '--session-id', '--set', '--set-upstream-to', '--shadow', '--short', '--show-current', '--show-prefix', '--show-token', '--show-toplevel', '--side', '--since', '--since-last-run', '--skills-dir', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--stat', '--state', '--statement-timeout', '--status', '--stdin', '--stop-mcp', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--swap-only', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--tier', '--timeout', '--timings', '--to', '--token', '--token-ttl', '--top-k', '--topo-order', '--trust', '--type', '--unindexed', '--uninstall', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--url-env', '--user', '--vacuum', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--warn-only', '--watch', '--what-if-threshold', '--window', '--workers', '--working-tree', '--workspace', '--write-tree', '--yes'],+ 'doctor': ['--abandon', '--abbrev-ref', '--accept-pending', '--access', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt', '--adopt-columns', '--adopt-permissions', '--after', '--aggressive', '--aliases', '--all', '--all-drifted', '--all-from', '--allow-old-serve', '--allow-outside-source-root', '--allow-shell-jobs', '--allow-unverified-remote', '--allowed-operations', '--applied', '--apply', '--apply-rewrites', '--assign-corpus', '--audit', '--auto', '--auto-additive', '--auto-fix', '--autostash', '--background', '--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', '--by-mention', '--cached', '--cacheinfo', '--call-site', '--catch-up', '--channel', '--check', '--cherry-mark', '--class', '--clear', '--clear-never-installed', '--cli-socket', '--client', '--close', '--concurrency', '--confidence', '--confirm', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--content-root', '--conversation', '--count', '--cursor', '--dataset', '--day', '--db-url', '--delegated-namespace', '--delegated-slug-prefixes', '--delete-brain', '--dest', '--detach', '--detail', '--diff-filter', '--dim', '--dimensions', '--dir', '--disable', '--drain', '--drain-timeout', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--enable', '--enable-dcr', '--end-of-options', '--entity', '--env', '--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-read', '--fetch-timeout-ms', '--ff-only', '--file', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-remove', '--force-retry', '--force-schema', '--format', '--fresh', '--fresh-token', '--from', '--from-meetings', '--from-pages', '--full', '--full-tree', '--fuzzy', '--generation', '--get', '--get-all', '--get-url', '--git-common-dir', '--git-dir', '--git-path', '--group', '--group-by', '--hard', '--hard-deadline', '--harness', '--held', '--help', '--hold-state', '--holds', '--home', '--http', '--id', '--if-version', '--ignore-env-override', '--images', '--include-ambiguous', '--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', '--install', '--is-ancestor', '--is-inside-work-tree', '--items-out', '--job-isolation', '--jq', '--json', '--keep', '--keep-checkout', '--key', '--kind', '--lanes', '--lang', '--left-right', '--legacy-lock', '--limit', '--link-source', '--link-type', '--list', '--literal-pathspecs', '--local', '--local-env-vars', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-count', '--max-facts', '--max-jobs', '--max-rss', '--max-runtime', '--max-usd', '--max-waiting', '--mcp-only', '--merge-base', '--migrate-legacy', '--migrate-only', '--migration', '--min', '--min-n', '--mode', '--model', '--multimodal', '--name', '--name-only', '--name-status', '--nice', '--no-accept-pending', '--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-filters', '--no-gpg-sign', '--no-hooks', '--no-lanes', '--no-llm', '--no-merges', '--no-migrate', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-restart', '--no-schema-pack', '--no-seat', '--no-tags', '--no-verify', '--no-walk', '--no-write-fetch-head', '--non-interactive', '--not', '--now', '--older-than', '--once', '--only', '--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', '--preset', '--preview', '--probe', '--probe-pglite', '--profile', '--progress-interval', '--progress-json', '--project', '--provenance', '--provider', '--providers', '--prune-orphans', '--public-url', '--pull', '--pure', '--purge', '--push', '--push-only', '--query', '--question', '--queue', '--quiet', '--rate', '--reader-mode', '--reauth', '--rebase', '--rebuild', '--recommended', '--redact-paths', '--reference-date', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--relative', '--relower', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--repair', '--repair-unknown-markers', '--replace', '--repo', '--request', '--request-id', '--require-clean', '--reranker', '--reset', '--reset-checkpoint', '--reset-default', '--resolve', '--restart-only', '--restore-only', '--resume', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--reverse', '--review-lower', '--revision', '--right-only', '--rollback-to-source', '--root', '--run', '--sample', '--save', '--scope', '--scopes', '--search-mode', '--seat', '--section', '--select', '--self-transfer', '--semantic', '--session', '--session-id', '--set', '--set-upstream-to', '--shadow', '--short', '--show-current', '--show-object-format', '--show-prefix', '--show-token', '--show-toplevel', '--side', '--since', '--since-last-run', '--skills-dir', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--stat', '--state', '--statement-timeout', '--status', '--stdin', '--stop-mcp', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--swap-only', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--tier', '--timeout', '--timings', '--to', '--token', '--token-ttl', '--top-k', '--topo-order', '--trust', '--type', '--unindexed', '--uninstall', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--url-env', '--user', '--vacuum', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--warn-only', '--watch', '--what-if-threshold', '--window', '--workers', '--working-tree', '--workspace', '--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', '--path', '--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', '--asof', '--body', '--bound-slug-prefixes', '--brain', '--client', '--cursor', '--date', '--dated-since', '--days', '--entities', '--federated-read', '--from-index', '--full', '--fuzzy', '--group-by', '--help', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--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'],@@ -113,7 +113,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'repair': ['--accept-pending', '--acknowledge-managed', '--after', '--all', '--all-drifted', '--apply', '--background', '--brain', '--break-lock', '--class', '--client', '--close', '--cursor', '--day', '--diff', '--expect', '--explain', '--ff-only', '--follow', '--force', '--force-break-lock', '--from', '--full', '--full-history', '--generation', '--held', '--help', '--id', '--include-ambiguous', '--include-cross-entity', '--include-failures', '--include-repairs', '--json', '--keep', '--key', '--kind', '--limit', '--max-cost', '--max-cost-usd', '--max-usd', '--mode', '--no-accept-pending', '--no-delegate', '--no-embed', '--no-llm', '--older-than', '--only', '--prefer', '--probe', '--progress-interval', '--progress-json', '--provenance', '--quiet', '--remediate', '--remediation-plan', '--request', '--request-id', '--reset-checkpoint', '--retry-failed', '--run', '--scopes', '--side', '--since', '--skip', '--skip-failed', '--slug', '--slugs', '--source', '--stale', '--state', '--timeout', '--timings', '--url', '--wait', '--yes'],'repair-jsonb': ['--accept-pending', '--background', '--brain', '--dry-run', '--explain', '--follow', '--help', '--json', '--no-accept-pending', '--probe', '--progress-interval', '--progress-json', '--quiet', '--source', '--supabase', '--timeout', '--timings', '--url', '--wait'],'report': ['--brain', '--content', '--dir', '--help', '--json', '--source', '--title', '--type'],- 'repos': ['--abandon', '--abbrev-ref', '--abort', '--accept-suggested', '--access', '--account', '--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--adopt-slug-path', '--after', '--all', '--all-new', '--allow-unverified-remote', '--allowed-operations', '--app-id', '--app-install', '--app-pem', '--apply', '--audit', '--auto-additive', '--autostash', '--backups', '--batch-check', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-usd-per-day', '--cached', '--calendar-id', '--category', '--classify', '--cleanup-dead-local-locks', '--clear', '--client', '--clone-dir', '--code', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--count', '--cursor', '--days', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--depth', '--detect', '--diff-filter', '--dir', '--disable', '--dry-run', '--enable', '--error-unmatch', '--exclude', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--expected-epoch', '--expected-incarnation', '--expected-state', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--force', '--format', '--from', '--full', '--future-days', '--get', '--get-all', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--group-by', '--hard', '--help', '--history-days', '--holds', '--http', '--id', '--if-version', '--include', '--include-warns', '--is-ancestor', '--is-inside-work-tree', '--json', '--keep', '--keep-checkout', '--keep-storage', '--kind', '--lanes', '--limit', '--local', '--local-env-vars', '--loops-exclude-labels', '--manifest', '--max-cost-usd', '--message', '--migrate-legacy', '--migration', '--min-trust', '--name', '--name-only', '--no-autostash', '--no-cron', '--no-embed', '--no-federate', '--no-federated', '--no-harden', '--no-lanes', '--no-pull', '--no-tags', '--no-verify', '--not', '--only', '--operations', '--origin', '--others', '--out', '--params', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--path-format', '--plan', '--porcelain', '--preview', '--probe', '--profile', '--pull', '--push-only', '--quiet', '--read-sources', '--rebase', '--redirect-uri', '--refresh-operations', '--remove-backup', '--repair', '--replace', '--repos', '--request-id', '--require-clean', '--reset-checkpoint', '--reset-default', '--resolve', '--resume', '--retry-failed', '--scope', '--scopes', '--secret', '--self-transfer', '--services', '--set', '--set-upstream-to', '--shared-skills', '--short', '--show-toplevel', '--since', '--slug-prefixes', '--source', '--source-id', '--source-ids', '--sources', '--stale', '--state', '--status', '--stdin', '--surface', '--symbolic-full-name', '--takes-holders', '--token', '--token-command', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--unindexed', '--unset-all', '--untracked-files', '--url', '--usage', '--verify', '--wait', '--wait-drain', '--warn-only', '--window', '--yes'],+ 'repos': ['--abandon', '--abbrev-ref', '--abort', '--accept-suggested', '--access', '--account', '--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--adopt-slug-path', '--after', '--all', '--all-new', '--allow-unverified-remote', '--allowed-operations', '--app-id', '--app-install', '--app-pem', '--apply', '--audit', '--auto-additive', '--autostash', '--backups', '--batch-check', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-usd-per-day', '--cached', '--calendar-id', '--category', '--classify', '--cleanup-dead-local-locks', '--clear', '--client', '--clone-dir', '--code', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--count', '--cursor', '--days', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--depth', '--detect', '--diff-filter', '--dir', '--disable', '--dry-run', '--enable', '--error-unmatch', '--exclude', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--expected-epoch', '--expected-incarnation', '--expected-state', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--force', '--format', '--from', '--full', '--future-days', '--get', '--get-all', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--group-by', '--hard', '--help', '--history-days', '--holds', '--http', '--id', '--if-version', '--include', '--include-warns', '--is-ancestor', '--is-inside-work-tree', '--json', '--keep', '--keep-checkout', '--keep-storage', '--kind', '--lanes', '--limit', '--local', '--local-env-vars', '--loops-exclude-labels', '--manifest', '--max-cost-usd', '--message', '--migrate-legacy', '--migration', '--min-trust', '--name', '--name-only', '--no-autostash', '--no-cron', '--no-embed', '--no-federate', '--no-federated', '--no-harden', '--no-lanes', '--no-pull', '--no-tags', '--no-verify', '--not', '--only', '--operations', '--origin', '--others', '--out', '--params', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--path-format', '--plan', '--porcelain', '--preview', '--probe', '--profile', '--pull', '--push-only', '--quiet', '--read-sources', '--rebase', '--redirect-uri', '--refresh-operations', '--remove-backup', '--repair', '--replace', '--repos', '--request-id', '--require-clean', '--reset-checkpoint', '--reset-default', '--resolve', '--resume', '--retry-failed', '--sample', '--scope', '--scopes', '--secret', '--self-transfer', '--services', '--set', '--set-upstream-to', '--shared-skills', '--short', '--show-toplevel', '--since', '--slug-prefixes', '--source', '--source-id', '--source-ids', '--sources', '--stale', '--state', '--status', '--stdin', '--surface', '--symbolic-full-name', '--takes-holders', '--token', '--token-command', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--unindexed', '--unset-all', '--untracked-files', '--url', '--usage', '--verify', '--wait', '--wait-drain', '--warn-only', '--window', '--yes'],'resolvers': ['--backend', '--brain', '--cost', '--help', '--json', '--source'],'retrieval-upgrade': ['--accept-pending', '--all', '--background', '--batch-size', '--brain', '--catch-up', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--facts', '--follow', '--force', '--held', '--help', '--ignore-env-override', '--images', '--include-null-signature', '--json', '--max-cost-usd', '--max-usd', '--no-accept-pending', '--no-embed', '--non-interactive', '--only', '--oversized', '--pace', '--pace-max-concurrency', '--plan', '--priority', '--progress-interval', '--progress-json', '--quiet', '--replace', '--reranker', '--retarget', '--slugs', '--source', '--stale', '--status', '--timeout', '--timings', '--to', '--wait', '--yes'],'routing-eval': ['--brain', '--help', '--json', '--llm', '--skills-dir', '--source'],@@ -127,7 +127,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'skillpack': ['--all', '--apply-clean-hunks', '--author', '--auto', '--brain', '--dest', '--dry-run', '--env', '--exit-code', '--fast', '--fix', '--force-unlock', '--format', '--from', '--full', '--harness', '--help', '--homepage', '--json', '--license', '--list', '--minimal', '--name-only', '--no-cache', '--no-lint', '--note', '--out', '--overwrite-local', '--persona', '--probe', '--pure', '--push', '--quick', '--quiet', '--refresh', '--repo', '--schema-pack', '--scope', '--short', '--since', '--skill', '--skills', '--skills-dir', '--skip-doctor', '--source', '--strict', '--stub', '--supabase', '--target', '--tier', '--trust', '--url', '--verify', '--version', '--workspace', '--yes'],'skillpack-check': ['--accept-pending', '--background', '--brain', '--explain', '--fast', '--follow', '--help', '--json', '--list', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--source', '--strict', '--timeout', '--timings', '--wait', '--yes'],'smoke-test': ['--brain', '--help', '--json', '--source'],- 'sources': ['--abandon', '--abbrev-ref', '--abort', '--accept-pending', '--accept-suggested', '--access', '--account', '--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--adopt-slug-path', '--after', '--all', '--all-new', '--allow-unverified-remote', '--allowed-operations', '--app-id', '--app-install', '--app-pem', '--apply', '--audit', '--auto-additive', '--autostash', '--background', '--backups', '--batch-check', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-usd-per-day', '--cached', '--calendar-id', '--category', '--classify', '--cleanup-dead-local-locks', '--clear', '--client', '--clone-dir', '--code', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--count', '--cursor', '--days', '--db-url', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--depth', '--detect', '--diff-filter', '--dir', '--disable', '--dry-run', '--enable', '--error-unmatch', '--exclude', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--expected-epoch', '--expected-incarnation', '--expected-state', '--explain', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--format', '--from', '--full', '--future-days', '--get', '--get-all', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--group-by', '--hard', '--help', '--history-days', '--holds', '--http', '--id', '--if-version', '--include', '--include-warns', '--is-ancestor', '--is-inside-work-tree', '--json', '--keep', '--keep-checkout', '--keep-storage', '--kind', '--lanes', '--legacy-lock', '--limit', '--local', '--local-env-vars', '--loops-exclude-labels', '--manifest', '--max-cost-usd', '--message', '--migrate-legacy', '--migration', '--min-trust', '--name', '--name-only', '--no-accept-pending', '--no-autostash', '--no-cron', '--no-embed', '--no-federate', '--no-federated', '--no-harden', '--no-lanes', '--no-pull', '--no-tags', '--no-verify', '--not', '--only', '--operations', '--origin', '--others', '--out', '--params', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--path-format', '--plan', '--porcelain', '--preview', '--probe', '--profile', '--progress-interval', '--progress-json', '--pull', '--push-only', '--quiet', '--read-sources', '--rebase', '--redirect-uri', '--refresh-operations', '--remove-backup', '--repair', '--replace', '--repos', '--request-id', '--require-clean', '--reset-checkpoint', '--reset-default', '--resolve', '--resume', '--retry-failed', '--scope', '--scopes', '--secret', '--self-transfer', '--services', '--set', '--set-upstream-to', '--shared-skills', '--short', '--show-toplevel', '--since', '--slug-prefixes', '--source', '--source-id', '--source-ids', '--sources', '--stale', '--state', '--status', '--stdin', '--surface', '--symbolic-full-name', '--takes-holders', '--timeout', '--timings', '--token', '--token-command', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--unindexed', '--unset-all', '--untracked-files', '--url', '--usage', '--verify', '--wait', '--wait-drain', '--warn-only', '--window', '--yes'],+ 'sources': ['--abandon', '--abbrev-ref', '--abort', '--accept-pending', '--accept-suggested', '--access', '--account', '--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--adopt-slug-path', '--after', '--all', '--all-new', '--allow-unverified-remote', '--allowed-operations', '--app-id', '--app-install', '--app-pem', '--apply', '--audit', '--auto-additive', '--autostash', '--background', '--backups', '--batch-check', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-usd-per-day', '--cached', '--calendar-id', '--category', '--classify', '--cleanup-dead-local-locks', '--clear', '--client', '--clone-dir', '--code', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--count', '--cursor', '--days', '--db-url', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--depth', '--detect', '--diff-filter', '--dir', '--disable', '--dry-run', '--enable', '--error-unmatch', '--exclude', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--expected-epoch', '--expected-incarnation', '--expected-state', '--explain', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--format', '--from', '--full', '--future-days', '--get', '--get-all', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--group-by', '--hard', '--help', '--history-days', '--holds', '--http', '--id', '--if-version', '--include', '--include-warns', '--is-ancestor', '--is-inside-work-tree', '--json', '--keep', '--keep-checkout', '--keep-storage', '--kind', '--lanes', '--legacy-lock', '--limit', '--local', '--local-env-vars', '--loops-exclude-labels', '--manifest', '--max-cost-usd', '--message', '--migrate-legacy', '--migration', '--min-trust', '--name', '--name-only', '--no-accept-pending', '--no-autostash', '--no-cron', '--no-embed', '--no-federate', '--no-federated', '--no-harden', '--no-lanes', '--no-pull', '--no-tags', '--no-verify', '--not', '--only', '--operations', '--origin', '--others', '--out', '--params', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--path-format', '--plan', '--porcelain', '--preview', '--probe', '--profile', '--progress-interval', '--progress-json', '--pull', '--push-only', '--quiet', '--read-sources', '--rebase', '--redirect-uri', '--refresh-operations', '--remove-backup', '--repair', '--replace', '--repos', '--request-id', '--require-clean', '--reset-checkpoint', '--reset-default', '--resolve', '--resume', '--retry-failed', '--sample', '--scope', '--scopes', '--secret', '--self-transfer', '--services', '--set', '--set-upstream-to', '--shared-skills', '--short', '--show-toplevel', '--since', '--slug-prefixes', '--source', '--source-id', '--source-ids', '--sources', '--stale', '--state', '--status', '--stdin', '--surface', '--symbolic-full-name', '--takes-holders', '--timeout', '--timings', '--token', '--token-command', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--unindexed', '--unset-all', '--untracked-files', '--url', '--usage', '--verify', '--wait', '--wait-drain', '--warn-only', '--window', '--yes'],'status': ['--abbrev-ref', '--acknowledge-managed', '--all', '--allow-empty', '--apply', '--body', '--brain', '--break-lock', '--cached', '--check', '--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', '--redact-paths', '--repo', '--request-id', '--reset-checkpoint', '--retry-failed', '--retry-held', '--reverse', '--section', '--serial', '--show-toplevel', '--skip-failed', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--status', '--strategy', '--timeout', '--url', '--verify', '--watch', '--workers', '--working-tree', '--yes'],'storage': ['--brain', '--fix', '--help', '--json', '--plan', '--repo', '--restore-only', '--source', '--to'],'sweep': ['--accept-pending', '--apply', '--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'],diff --git a/src/core/doctor-categories.ts b/src/core/doctor-categories.tsindex 40b6afb4fe..65f60a4f24 100644--- a/src/core/doctor-categories.ts+++ b/src/core/doctor-categories.ts@@ -208,6 +208,8 @@ export const BRAIN_CHECK_NAMES: ReadonlySet<string> = new Set(['unlinked_facts',// #7160: title-prefixed person pages that likely duplicate an unprefixed page (preview only).'person_title_duplicates',+ // Git-canonical G1: the database compared with the commit at HEAD per source, informational (doctor/checks/db-ahead-of-git.ts).+ 'db_ahead_of_git','edge_validity','text_projection_readiness','timeline_coverage',diff --git a/src/core/export-snapshot.ts b/src/core/export-snapshot.tsindex 309841181a..7e1d905626 100644--- a/src/core/export-snapshot.ts+++ b/src/core/export-snapshot.ts@@ -7,6 +7,7 @@ import { isSegmentedPage } from './page-body/page-shape.ts';import { openSegmentedBody, readBodyRange, type BodyLedger } from './page-body/read-range.ts';import { TIMELINE_SEPARATOR } from './page-window/document.ts';import type { Page } from './types.ts';+import { serializeMarkdown, slugStampedFrontmatter } from './markdown.ts';const EXPORT_COLLECT_BYTES = 1024 * 1024;@@ -40,6 +41,30 @@ export async function readExportPage(tx: BrainEngine, key: { id: string; source_return { page, tags: row.export_tags as string[] };}+export type ExportSnapshot = Awaited<ReturnType<typeof readExportPage>>;++/**+ * The frontmatter and header fields of a page's exported file. #5966: the slug stamp rule lives in+ * slugStampedFrontmatter (markdown.ts), shared with every render; an escaped file always carries its slug.+ */+function exportHeader(snapshot: ExportSnapshot, escaped: boolean) {+ const { page } = snapshot;+ const frontmatter = escaped ? { ...(page.frontmatter ?? {}), slug: page.slug } : slugStampedFrontmatter(page.slug, page.frontmatter ?? {});+ return { frontmatter, meta: { type: page.type, title: page.title, tags: snapshot.tags } };+}++/** The exported Markdown of an inline page read by readExportPage, so its withdrawal overlay is applied. */+export function inlineExportMarkdown(snapshot: ExportSnapshot, escaped = false): string {+ const { frontmatter, meta } = exportHeader(snapshot, escaped);+ return serializeMarkdown(frontmatter, snapshot.page.compiled_truth, snapshot.page.timeline, meta);+}++/** The `head` segmentedExportMarkdown starts a segmented page's file with. */+export function segmentedExportHead(snapshot: ExportSnapshot, escaped = false): string {+ const { frontmatter, meta } = exportHeader(snapshot, escaped);+ return serializeMarkdown(frontmatter, '', '', meta).slice(0, -1);+}+/** The ledger an export overlays one page's body with: the source's withdrawals that apply to the page. */export function exportBodyLedger(slug: string, withdrawals: ExportWithdrawal[]): BodyLedger {return { withdrawals: applicableWithdrawals(slug, withdrawals) };diff --git a/src/core/hardened-git.ts b/src/core/hardened-git.tsindex bbd7371b2d..8e3259cf9e 100644--- a/src/core/hardened-git.ts+++ b/src/core/hardened-git.ts@@ -45,6 +45,7 @@ const ALLOWED_OPTIONS: ReadonlyMap<string, ReadonlySet<string>> = new Map([['cat-file', new Set(['--batch'])],['hash-object', new Set(['--no-filters', '--stdin-paths'])],['check-attr', new Set(['-z', '--stdin'])],+ ['check-ignore', new Set(['-z', '--stdin'])],['diff-index', new Set(['--cached', '--quiet'])],['diff-tree', new Set(['-r', '-z', '--no-renames'])],]);diff --git a/src/core/persistence/git-gap.ts b/src/core/persistence/git-gap.tsnew file mode 100644index 0000000000..d95264f321--- /dev/null+++ b/src/core/persistence/git-gap.ts@@ -0,0 +1,209 @@+/**+ * Git-canonical memory, wave G1 (docs/designs/GIT_CANONICAL_MEMORY.md): the read-only pieces the git-gap census+ * (`gbrain sources git-gap`, commands/sources-git-gap.ts) and doctor `db_ahead_of_git` share. The one predicate for which+ * pages may have a tracked file (`declaredDatabaseOnly`), the equality contract between a page's export view+ * (readExportPage, so fact withdrawals are overlaid) and a committed blob, and filter-free reads of HEAD and the working+ * tree. Git runs only as hardened plumbing (`ls-tree`, `cat-file --batch`, `check-ignore`, `rev-parse`), which never runs+ * a repository's clean/smudge filter or textconv; the working tree is hashed here, never through `git status` or `git diff`.+ * Nothing here writes.+ */+import { createHash } from 'node:crypto';+import { createReadStream, lstatSync, realpathSync } from 'node:fs';+import type { BrainEngine } from '../engine.ts';+import { hardenedGitStream, hardenedGitSync, NulRecordSplitter } from '../hardened-git.ts';+import { exportBodyLedger, segmentedExportHead, segmentedExportMarkdown, type ExportSnapshot, type ExportWithdrawal } from '../export-snapshot.ts';+import { parseMarkdown } from '../markdown.ts';+import { isDerivationPrivate, isPrivatePage } from '../search/private-visibility.ts';+import { alignWithStored } from './align-stored.ts';+import { digest } from './digest.ts';+import { isNeverFiledDerivedPage } from './page-prepare.ts';+import { classifyDrift } from './reconcile-additive.ts';+import { reconcileCanonical } from './reconcile-merge.ts';+import { reconcileFileReading } from './reconcile-state.ts';++/** Why a page has no tracked file on purpose, in the order `declaredDatabaseOnly` tests them. */+export const DECLARED_CLASSES = ['mirror_source', 'private', 'alias_private', 'lineage_private', 'database_only', 'db_only_prefix', 'derive_folder', 'git_ignored'] as const;+export type DeclaredClass = typeof DECLARED_CLASSES[number];++/**+ * What decides a declared class beyond the page itself: whether the source is a read-only mirror (sourceMirrorReadOnly),+ * whether a slug sits under a `storage.db_only` dir (isSourceDbOnlySlug, which refuses an invalid gbrain.yml) and the+ * paths the checkout's Git ignores.+ */+export interface GitHomePolicy { mirror: boolean; dbOnly: (slug: string) => boolean; ignored: ReadonlySet<string> }++/**+ * Why a page may not have a tracked file, or null when it may. gbrain never writes a read-only mirror's checkout (#5409);+ * private and alias-private pages never reach a remote; a page the database keeps on purpose (`database_only_reason`) or+ * under a `storage.db_only` prefix stays there; a derive-phase page that never recorded a file (page-prepare.ts+ * `isNeverFiledDerivedPage`, DERIVE_PHASE_DB_ONLY_DEFAULTS) publishes database-only; a path the checkout's Git ignores+ * can never be committed. `lineage_private` is what privatePagesFilterFragment adds over the row's own fields; the caller+ * computes it in SQL. Callers load `visibility.honor_aliases` (readHonorAliases) first.+ */+export function declaredDatabaseOnly(page: { slug: string; type?: string | null; frontmatter?: unknown; database_only_reason?: string | null;+ lineage_private?: boolean; source_path?: string | null; source_uri?: string | null }, relativePath: string | null, policy: GitHomePolicy): DeclaredClass | null {+ if (policy.mirror) return 'mirror_source';+ if (isPrivatePage(page)) return 'private';+ if (isDerivationPrivate(page)) return 'alias_private';+ if (page.lineage_private) return 'lineage_private';+ if (page.database_only_reason) return 'database_only';+ if (policy.dbOnly(page.slug)) return 'db_only_prefix';+ if (isNeverFiledDerivedPage(page.slug, page)) return 'derive_folder';+ if (relativePath !== null && policy.ignored.has(relativePath)) return 'git_ignored';+ return null;+}++/**+ * The paths among `relativePaths` (relative to `root`) that the checkout's ignore rules exclude, read with filter-free+ * `git check-ignore -z --stdin`; tracked files are never reported (Git commits them whatever the rules say). Exit 1+ * means none matched. Null when Git could not answer, so a caller never reads a failed check as "nothing ignored".+ */+export async function ignoredPaths(root: string, relativePaths: string[]): Promise<Set<string> | null> {+ const ignored = new Set<string>();+ if (!relativePaths.length) return ignored;+ const splitter = new NulRecordSplitter();+ const result = await hardenedGitStream(root, ['check-ignore', '-z', '--stdin'], {+ stdin: relativePaths.map(path => path + '\0'), timeoutMs: 120_000, maxBytes: 64 * 1024 * 1024,+ onChunk: chunk => { for (const record of splitter.push(chunk)) ignored.add(record.toString('utf8')); } });+ if (result.ok) return result.endsWithNul || result.bytes === 0 ? ignored : null;+ return result.reason === 'exit' && result.status === 1 && ignored.size === 0 ? ignored : null;+}++export type ExportFileComparison = { state: 'equal' } | { state: 'differs'; paths: string[] } | { state: 'unparseable' };++/**+ * The equality contract for an inline page: the file, parsed the way reconcile parses a canonical file (aligned with the+ * stored type, subtype and the #6429 grandfather stamp), carries the same canonical fields as the page's export view.+ * `importPath` is the file's path as sync keys it (scannerSourcePath).+ */+export function compareInlineExportFile(raw: Buffer, importPath: string, snapshot: ExportSnapshot): ExportFileComparison {+ const { page, tags } = snapshot;+ const text = raw.toString('utf8');+ if (!Buffer.from(text).equals(raw)) return { state: 'unparseable' };+ const reading = reconcileFileReading(text, importPath, page);+ const parsed = parseMarkdown(reading.content, `${page.slug}.md`, { validate: true, expectedSlug: page.slug });+ if (parsed.errors?.some(e => !['MISSING_OPEN', 'EMPTY_FRONTMATTER'].includes(e.code))) return { state: 'unparseable' };+ if (parsed.slug !== page.slug) return { state: 'differs', paths: ['/slug'] };+ alignWithStored(parsed, page, reading.inferred);+ const file = reconcileCanonical(parsed, parsed.tags), database = reconcileCanonical(page, tags);+ if (digest(file) === digest(database)) return { state: 'equal' };+ return { state: 'differs', paths: classifyDrift(file, database).paths.map(p => p.path) };+}++export type ObjectFormat = 'sha1' | 'sha256';+export interface TreeBlob { oid: string; size: number; mode: string }++/**+ * A segmented page's body cannot be read whole (page-body/page-shape.ts), so it compares byte for byte: the Git blob id+ * of its streamed export (`blob <size>\0` + the export, in the repository's object format) against the committed blob's.+ * An export longer than the blob differs without hashing further.+ */+export async function compareSegmentedExportBlob(tx: BrainEngine, snapshot: ExportSnapshot, withdrawals: ExportWithdrawal[], blob: TreeBlob,+ format: ObjectFormat): Promise<ExportFileComparison> {+ const hash = createHash(format).update(`blob ${blob.size}\0`);+ let bytes = 0;+ for await (const piece of segmentedExportMarkdown(tx, snapshot.page, exportBodyLedger(snapshot.page.slug, withdrawals), segmentedExportHead(snapshot))) {+ bytes += typeof piece === 'string' ? Buffer.byteLength(piece) : piece.length;+ if (bytes > blob.size) return { state: 'differs', paths: ['/body'] };+ hash.update(piece);+ }+ return bytes === blob.size && hash.digest('hex') === blob.oid ? { state: 'equal' } : { state: 'differs', paths: ['/body'] };+}++export interface HeadTree {+ /** The checkout's top level (real path); tree paths are relative to it. */+ gitRoot: string;+ format: ObjectFormat;+ /** The HEAD commit, or null on an unborn branch (nothing is committed). */+ commit: string | null;+ /** Every blob under the source's directory at HEAD, keyed by its path relative to `gitRoot`. */+ blobs: Map<string, TreeBlob>;+}++const GIT_LIMITS = { timeoutMs: 30_000, maxBytes: 64 * 1024 };+function gitLine(root: string, args: string[]): string | null {+ const result = hardenedGitSync(root, args, GIT_LIMITS);+ return result.ok ? result.stdout.toString('utf8').replace(/\n$/, '') : null;+}++/** Whether `root` is inside a Git working tree (hardened `rev-parse --show-toplevel`). */+export function isGitCheckout(root: string): boolean {+ return gitLine(root, ['rev-parse', '--show-toplevel']) !== null;+}++/**+ * HEAD of the checkout at `root`, listed once with `ls-tree -r -l -z --full-tree` under the source's directory. Null when+ * Git cannot answer (not a checkout, a failed or truncated read).+ */+export async function readHeadTree(root: string): Promise<HeadTree | null> {+ const top = gitLine(root, ['rev-parse', '--show-toplevel']);+ const format = gitLine(root, ['rev-parse', '--show-object-format']);+ if (top === null || (format !== 'sha1' && format !== 'sha256')) return null;+ const gitRoot = realpathSync(top), real = realpathSync(root);+ const head = hardenedGitSync(root, ['rev-parse', '--verify', '--quiet', 'HEAD^{commit}'], GIT_LIMITS);+ if (!head.ok) return head.reason === 'exit' && head.status === 1 ? { gitRoot, format, commit: null, blobs: new Map() } : null;+ const commit = head.stdout.toString('utf8').trim();+ const scope = real === gitRoot ? '' : real.slice(gitRoot.length + 1);+ const blobs = new Map<string, TreeBlob>();+ const splitter = new NulRecordSplitter();+ const result = await hardenedGitStream(root, ['ls-tree', '-r', '-l', '-z', '--full-tree', commit, '--', ...(scope ? [`:(literal)${scope}`] : [])], {+ timeoutMs: 300_000, maxBytes: 1024 * 1024 * 1024,+ onChunk: chunk => {+ for (const record of splitter.push(chunk)) {+ const text = record.toString('utf8'), tab = text.indexOf('\t');+ const [mode = '', type = '', oid = '', size = ''] = text.slice(0, tab).split(/ +/);+ if (type === 'blob') blobs.set(text.slice(tab + 1), { oid, size: Number(size), mode });+ }+ } });+ if (!result.ok || !(result.bytes === 0 || result.endsWithNul)) return null;+ return { gitRoot, format, commit, blobs };+}++/** The bytes one `cat-file --batch` call reads at most, so a call holds a bounded batch of committed files. */+const CAT_FILE_BATCH_BYTES = 64 * 1024 * 1024;++/**+ * The raw bytes of committed blobs keyed by blob id, read with `cat-file --batch` (no `--filters`, no `--textconv`:+ * exactly what Git stores). Calls are split so each reads at most CAT_FILE_BATCH_BYTES (a larger blob is read alone).+ * Null when Git could not answer or a blob was missing.+ */+export async function readBlobs(root: string, blobs: readonly TreeBlob[]): Promise<Map<string, Buffer> | null> {+ const out = new Map<string, Buffer>();+ for (let start = 0; start < blobs.length;) {+ let end = start, bytes = 0;+ while (end < blobs.length && (end === start || bytes + blobs[end]!.size <= CAT_FILE_BATCH_BYTES)) bytes += blobs[end++]!.size;+ const chunk = blobs.slice(start, end);+ const pieces: Buffer[] = [];+ const result = await hardenedGitStream(root, ['cat-file', '--batch'], { stdin: chunk.map(blob => blob.oid + '\n').join(''), timeoutMs: 300_000,+ maxBytes: bytes + chunk.length * 160 + 1024, onChunk: piece => { pieces.push(piece); } });+ if (!result.ok) return null;+ const output = Buffer.concat(pieces);+ let offset = 0;+ for (const blob of chunk) {+ const newline = output.indexOf(0x0a, offset);+ if (newline < 0) return null;+ const [oid, type, size] = output.subarray(offset, newline).toString('utf8').split(' ');+ if (oid !== blob.oid || type !== 'blob' || Number(size) !== blob.size || output.length < newline + 1 + blob.size) return null;+ out.set(blob.oid, output.subarray(newline + 1, newline + 1 + blob.size));+ offset = newline + 1 + blob.size + 1;+ }+ start = end;+ }+ return out;+}++/**+ * The Git blob id of the working-tree file at `path` from its raw bytes (no filters, so a checkout whose attributes+ * convert line endings reads as modified); null when nothing is there, `other` for a symlink or other non-regular entry.+ */+export async function worktreeBlobOid(path: string, format: ObjectFormat): Promise<string | 'other' | null> {+ let size: number;+ try {+ const stat = lstatSync(path);+ if (!stat.isFile()) return 'other';+ size = stat.size;+ } catch { return null; }+ const hash = createHash(format).update(`blob ${size}\0`);+ for await (const chunk of createReadStream(path)) hash.update(chunk as Buffer);+ return hash.digest('hex');+}diff --git a/src/core/persistence/page-prepare.ts b/src/core/persistence/page-prepare.tsindex 2403634ed6..79f9f836ef 100644--- a/src/core/persistence/page-prepare.ts+++ b/src/core/persistence/page-prepare.ts@@ -150,7 +150,7 @@ function putProvenance(row: WriteRequest, snapshot: PageSnapshot | null, parsed:return stamp;}/** A derive-phase page (DERIVE_PHASE_DB_ONLY_DEFAULTS) that never recorded a canonical file. */-function isNeverFiledDerivedPage(slug: string, page: { source_path?: string | null; source_uri?: string | null }): boolean {+export function isNeverFiledDerivedPage(slug: string, page: { source_path?: string | null; source_uri?: string | null }): boolean {return !page.source_path && !page.source_uri && DERIVE_PHASE_DB_ONLY_DEFAULTS.some(prefix => slug.startsWith(prefix));}/**diff --git a/test/fixtures/goldens/doctor/content-pglite-human.json b/test/fixtures/goldens/doctor/content-pglite-human.jsonindex 7f5e134f92..94c52f1fdf 100644--- a/test/fixtures/goldens/doctor/content-pglite-human.json+++ b/test/fixtures/goldens/doctor/content-pglite-human.json@@ -228,6 +228,7 @@" [OK] sync_overwritten_db_edits: No page shows a database edit that a sync import overwrote."," [OK] sync_config_keys: No retired sync config key is stored on this brain."," [OK] person_title_duplicates: No title-prefixed person page pairs with an unprefixed page (0 titled page(s) examined).",+ " [OK] db_ahead_of_git: Informational, nothing to do: the database compared with the commit at HEAD, per source with a Git checkout. notes: 5 equal. Page detail: gbrain sources git-gap <source-id>."," [OK] fence_integrity: No malformed facts or takes fence is held, stored or waiting in a checkout (2 source(s) scanned)."," [OK] search_mode: Mode: conservative (no per-key overrides — mode bundle is canonical)."," [OK] hidden_by_search_policy: No pages hidden by search-exclude policy.",diff --git a/test/fixtures/goldens/doctor/content-pglite-json.json b/test/fixtures/goldens/doctor/content-pglite-json.jsonindex 2ce794420a..ed627462e0 100644--- a/test/fixtures/goldens/doctor/content-pglite-json.json+++ b/test/fixtures/goldens/doctor/content-pglite-json.json@@ -3489,6 +3489,56 @@"name": "person_title_duplicates","status": "ok"},+ {+ "category": "brain",+ "details": {+ "docs": "docs/designs/GIT_CANONICAL_MEMORY.md#the-git-gap-census",+ "errors": [],+ "informational": true,+ "partial_sources": [],+ "sources": [+ {+ "complete": true,+ "declared": {+ "alias_private": 0,+ "database_only": 0,+ "db_only_prefix": 0,+ "derive_folder": 0,+ "git_ignored": 0,+ "lineage_private": 0,+ "mirror_source": 0,+ "private": 0+ },+ "head": "83e82926ae7b6963557e0071b0e3165248fb815b",+ "pages": 5,+ "source_id": "notes",+ "states": {+ "database_ahead": 0,+ "declared_database_only": 0,+ "equal": 5,+ "git_ahead": 0,+ "undeclared_database_only": 0,+ "unparseable": 0,+ "unsafe_path": 0,+ "worktree_only": 0+ },+ "worktree": {+ "absent": 0,+ "clean": 0,+ "deleted": 0,+ "modified": 5,+ "untracked": 0+ }+ }+ ],+ "sources_without_git_checkout": 1,+ "timeout_ms": "<volatile>"+ },+ "elapsed_ms": "<volatile>",+ "message": "Informational, nothing to do: the database compared with the commit at HEAD, per source with a Git checkout. notes: 5 equal. Page detail: gbrain sources git-gap <source-id>.",+ "name": "db_ahead_of_git",+ "status": "ok"+ },{"category": "brain","details": {diff --git a/test/fixtures/goldens/doctor/hot-checks-pglite-json.json b/test/fixtures/goldens/doctor/hot-checks-pglite-json.jsonindex f155d2fae3..11baddfbf6 100644--- a/test/fixtures/goldens/doctor/hot-checks-pglite-json.json+++ b/test/fixtures/goldens/doctor/hot-checks-pglite-json.json@@ -3712,6 +3712,56 @@"name": "person_title_duplicates","status": "ok"},+ {+ "category": "brain",+ "details": {+ "docs": "docs/designs/GIT_CANONICAL_MEMORY.md#the-git-gap-census",+ "errors": [],+ "informational": true,+ "partial_sources": [],+ "sources": [+ {+ "complete": true,+ "declared": {+ "alias_private": 0,+ "database_only": 0,+ "db_only_prefix": 0,+ "derive_folder": 0,+ "git_ignored": 0,+ "lineage_private": 0,+ "mirror_source": 0,+ "private": 0+ },+ "head": "1c068d3facec1879b1763dd6f98d3849133473da",+ "pages": 19,+ "source_id": "notes",+ "states": {+ "database_ahead": 4,+ "declared_database_only": 0,+ "equal": 11,+ "git_ahead": 0,+ "undeclared_database_only": 0,+ "unparseable": 4,+ "unsafe_path": 0,+ "worktree_only": 0+ },+ "worktree": {+ "absent": 0,+ "clean": 18,+ "deleted": 0,+ "modified": 1,+ "untracked": 0+ }+ }+ ],+ "sources_without_git_checkout": 2,+ "timeout_ms": "<volatile>"+ },+ "elapsed_ms": "<volatile>",+ "message": "Informational, nothing to do: the database compared with the commit at HEAD, per source with a Git checkout. notes: 11 equal, 4 database_ahead, 4 unparseable. Page detail: gbrain sources git-gap <source-id>.",+ "name": "db_ahead_of_git",+ "status": "ok"+ },{"category": "brain","details": {@@ -8354,6 +8404,56 @@"name": "person_title_duplicates","status": "ok"},+ {+ "category": "brain",+ "details": {+ "docs": "docs/designs/GIT_CANONICAL_MEMORY.md#the-git-gap-census",+ "errors": [],+ "informational": true,+ "partial_sources": [],+ "sources": [+ {+ "complete": true,+ "declared": {+ "alias_private": 0,+ "database_only": 0,+ "db_only_prefix": 0,+ "derive_folder": 0,+ "git_ignored": 0,+ "lineage_private": 0,+ "mirror_source": 0,+ "private": 0+ },+ "head": "1c068d3facec1879b1763dd6f98d3849133473da",+ "pages": 19,+ "source_id": "notes",+ "states": {+ "database_ahead": 4,+ "declared_database_only": 0,+ "equal": 11,+ "git_ahead": 0,+ "undeclared_database_only": 0,+ "unparseable": 4,+ "unsafe_path": 0,+ "worktree_only": 0+ },+ "worktree": {+ "absent": 0,+ "clean": 18,+ "deleted": 0,+ "modified": 1,+ "untracked": 0+ }+ }+ ],+ "sources_without_git_checkout": 2,+ "timeout_ms": "<volatile>"+ },+ "elapsed_ms": "<volatile>",+ "message": "Informational, nothing to do: the database compared with the commit at HEAD, per source with a Git checkout. notes: 11 equal, 4 database_ahead, 4 unparseable. Page detail: gbrain sources git-gap <source-id>.",+ "name": "db_ahead_of_git",+ "status": "ok"+ },{"category": "brain","details": {diff --git a/test/fixtures/goldens/doctor/json-pglite-degraded.json b/test/fixtures/goldens/doctor/json-pglite-degraded.jsonindex a199e65b75..cf60802c8d 100644--- a/test/fixtures/goldens/doctor/json-pglite-degraded.json+++ b/test/fixtures/goldens/doctor/json-pglite-degraded.json@@ -3191,6 +3191,22 @@"name": "person_title_duplicates","status": "ok"},+ {+ "category": "brain",+ "details": {+ "docs": "docs/designs/GIT_CANONICAL_MEMORY.md#the-git-gap-census",+ "errors": [],+ "informational": true,+ "partial_sources": [],+ "sources": [],+ "sources_without_git_checkout": 1,+ "timeout_ms": "<volatile>"+ },+ "elapsed_ms": "<volatile>",+ "message": "No source has a Git checkout, so there is no commit to compare the database with.",+ "name": "db_ahead_of_git",+ "status": "ok"+ },{"category": "brain","details": {diff --git a/test/fixtures/goldens/doctor/json-pglite-fresh.json b/test/fixtures/goldens/doctor/json-pglite-fresh.jsonindex b44b131002..57ee07cb05 100644--- a/test/fixtures/goldens/doctor/json-pglite-fresh.json+++ b/test/fixtures/goldens/doctor/json-pglite-fresh.json@@ -3234,6 +3234,22 @@"name": "person_title_duplicates","status": "ok"},+ {+ "category": "brain",+ "details": {+ "docs": "docs/designs/GIT_CANONICAL_MEMORY.md#the-git-gap-census",+ "errors": [],+ "informational": true,+ "partial_sources": [],+ "sources": [],+ "sources_without_git_checkout": 1,+ "timeout_ms": "<volatile>"+ },+ "elapsed_ms": "<volatile>",+ "message": "No source has a Git checkout, so there is no commit to compare the database with.",+ "name": "db_ahead_of_git",+ "status": "ok"+ },{"category": "brain","details": {diff --git a/test/fixtures/goldens/doctor/json-postgres-fresh.json b/test/fixtures/goldens/doctor/json-postgres-fresh.jsonindex a332f77889..6901603e00 100644--- a/test/fixtures/goldens/doctor/json-postgres-fresh.json+++ b/test/fixtures/goldens/doctor/json-postgres-fresh.json@@ -3237,6 +3237,22 @@"name": "person_title_duplicates","status": "ok"},+ {+ "category": "brain",+ "details": {+ "docs": "docs/designs/GIT_CANONICAL_MEMORY.md#the-git-gap-census",+ "errors": [],+ "informational": true,+ "partial_sources": [],+ "sources": [],+ "sources_without_git_checkout": 1,+ "timeout_ms": "<volatile>"+ },+ "elapsed_ms": "<volatile>",+ "message": "No source has a Git checkout, so there is no commit to compare the database with.",+ "name": "db_ahead_of_git",+ "status": "ok"+ },{"category": "brain","details": {diff --git a/test/fixtures/goldens/doctor/registry-build-checks.json b/test/fixtures/goldens/doctor/registry-build-checks.jsonindex 522dbb15b2..71cff66a21 100644--- a/test/fixtures/goldens/doctor/registry-build-checks.json+++ b/test/fixtures/goldens/doctor/registry-build-checks.json@@ -981,6 +981,10 @@"category": "brain","name": "person_title_duplicates"},+ {+ "category": "brain",+ "name": "db_ahead_of_git"+ },{"category": "brain","name": "fence_integrity"diff --git a/test/git-gap-census.test.ts b/test/git-gap-census.test.tsnew file mode 100644index 0000000000..78258b7a41--- /dev/null+++ b/test/git-gap-census.test.ts@@ -0,0 +1,347 @@+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+import { execFileSync } from 'node:child_process';+import { existsSync, mkdirSync, mkdtempSync, realpathSync, rmSync, unlinkSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { dirname, join } from 'node:path';+import { randomUUID } from 'node:crypto';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { PostgresEngine } from '../src/core/postgres-engine.ts';+import type { BrainEngine } from '../src/core/engine.ts';+import { inlineExportMarkdown, readExportPage, readExportWithdrawals, segmentedExportHead, segmentedExportMarkdown, exportBodyLedger, type ExportSnapshot } from '../src/core/export-snapshot.ts';+import { parseFactsFence, renderFactsTable } from '../src/core/facts-fence.ts';+import { gitBlobOid } from '../src/core/persistence/digest.ts';+import { recordSyncImportProvenance } from '../src/core/persistence/sync-holds.ts';+import { compareInlineExportFile, compareSegmentedExportBlob, declaredDatabaseOnly, ignoredPaths } from '../src/core/persistence/git-gap.ts';+import { censusGitGap, describeGitGap, parseGitGapArgs } from '../src/commands/sources-git-gap.ts';+import { dbAheadOfGitEntry } from '../src/commands/doctor/checks/db-ahead-of-git.ts';+import { OperationError } from '../src/core/ops/contract.ts';+import { createSegmentedPage } from './helpers/segmented-page.ts';+import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';+import { withEnv } from './helpers/with-env.ts';++const policy = { mirror: false, dbOnly: () => false, ignored: new Set<string>() };+const fact = (claim: string) => ({ rowNum: 1, claim, kind: 'fact' as const, confidence: 1, visibility: 'world' as const, notability: 'medium' as const, active: true, context: '' });++function git(root: string, ...args: string[]): string {+ return execFileSync('git', ['-C', root, ...args], { env: { ...process.env, GIT_CONFIG_GLOBAL: '/dev/null', GIT_CONFIG_NOSYSTEM: '1', GIT_AUTHOR_NAME: 'Test',+ GIT_AUTHOR_EMAIL: '[email protected]', GIT_COMMITTER_NAME: 'Test', GIT_COMMITTER_EMAIL: '[email protected]' } }).toString();+}++function put(root: string, rel: string, content: string | Buffer): void {+ mkdirSync(dirname(join(root, rel)), { recursive: true });+ writeFileSync(join(root, rel), content);+}++function commitAll(root: string, message: string): void {+ git(root, 'add', '-A');+ git(root, 'commit', '-qm', message);+}++for (const backend of testBackends()) describe(`git-gap census (git-canonical G1): ${backend}`, () => {+ let engine: BrainEngine;+ const dirs: string[] = [];+ const tempDir = (prefix: string) => { const dir = realpathSync(mkdtempSync(join(tmpdir(), prefix))); dirs.push(dir); return dir; };+ beforeAll(async () => {+ engine = backend === 'postgres' ? new PostgresEngine() : new PGLiteEngine();+ await engine.connect(backend === 'postgres' ? { database_url: requirePostgresTestDatabase() } : {});+ await engine.initSchema();+ }, 60000);+ afterAll(async () => { await engine.disconnect(); for (const dir of dirs) rmSync(dir, { recursive: true, force: true }); });+ beforeEach(async () => {+ await engine.executeRaw('DELETE FROM pages');+ await engine.executeRaw("DELETE FROM facts WHERE source_id='default'");+ await engine.executeRaw("DELETE FROM fact_withdrawals WHERE source_id='default'");+ await engine.executeRaw("DELETE FROM op_checkpoints WHERE op IN ('sync-hold','sync-import-provenance')");+ await engine.executeRaw("UPDATE sources SET local_path=NULL, config='{}'::jsonb WHERE id='default'");+ });++ const snapshotOf = (slug: string) => engine.transaction(async tx => {+ const [key] = await tx.executeRaw<{ id: string; source_id: string; slug: string }>("SELECT id::text, source_id, slug FROM pages WHERE source_id='default' AND slug=$1", [slug]);+ return readExportPage(tx, key!, await readExportWithdrawals(tx, 'default'));+ });+ const rendered = async (slug: string) => inlineExportMarkdown(await snapshotOf(slug));+ const pageId = async (slug: string) => Number((await engine.executeRaw<{ id: number }>("SELECT id FROM pages WHERE source_id='default' AND slug=$1", [slug]))[0]!.id);+ const useCheckout = async (root: string) => { await engine.executeRaw("UPDATE sources SET local_path=$1 WHERE id='default'", [root]); };++ test('the export rendering of every page shape compares equal to its export view (the equality contract)', async () => {+ const shapes: Array<[string, Parameters<BrainEngine['putPage']>[1], string[]]> = [+ ['eq/empty', { type: 'note', title: 'Empty fields', compiled_truth: '', timeline: '' }, []],+ ['eq/body-and-timeline', { type: 'concept', title: 'Synthetic concept', compiled_truth: 'Body line one.\n\nBody line two.', timeline: '- 2026-01-02: an event' }, ['alpha', 'beta']],+ ['eq/rich-frontmatter', { type: 'person', title: 'Alice Example', compiled_truth: 'Notes.', timeline: '',+ frontmatter: { aliases: ['A. Example'], score: 3, nested: { a: [1, 'two', { three: true }] }, empty: '', validate: false } }, ['people']],+ ['eq/double--hyphen', { type: 'note', title: 'Stamped slug', compiled_truth: 'Needs a slug stamp.', timeline: '' }, []],+ ['eq/facts', { type: 'note', title: 'Facts', compiled_truth: renderFactsTable([fact('A synthetic claim')]), timeline: '' }, []],+ ];+ for (const [slug, page, tags] of shapes) {+ await engine.putPage(slug, page);+ for (const tag of tags) await engine.addTag(slug, tag);+ const snapshot = await snapshotOf(slug);+ expect([slug, compareInlineExportFile(Buffer.from(inlineExportMarkdown(snapshot)), `${slug}.md`, snapshot)]).toEqual([slug, { state: 'equal' }]);+ }+ });++ test('an edited, a broken, a non-UTF-8 and a stamp-less file compare as the contract says', async () => {+ await engine.putPage('cmp/page', { type: 'note', title: 'Compared', compiled_truth: 'Original body.', timeline: '', frontmatter: { validate: false } });+ const snapshot = await snapshotOf('cmp/page');+ const text = inlineExportMarkdown(snapshot);+ expect(compareInlineExportFile(Buffer.from(text.replace('Original body.', 'Edited body.')), 'cmp/page.md', snapshot)).toEqual({ state: 'differs', paths: ['/compiled_truth'] });+ expect(compareInlineExportFile(Buffer.from('---\ntitle: [unclosed\n---\nBody\n'), 'cmp/page.md', snapshot)).toEqual({ state: 'unparseable' });+ expect(compareInlineExportFile(Buffer.from([0xff, 0xfe, 0x00]), 'cmp/page.md', snapshot)).toEqual({ state: 'unparseable' });+ expect(compareInlineExportFile(Buffer.from(text.replace('validate: false\n', '')), 'cmp/page.md', snapshot)).toEqual({ state: 'equal' });+ });++ test('a forgotten fact renders withdrawn, and a file still showing it active differs', async () => {+ await engine.putPage('forget/inline', { type: 'note', title: 'Inline', compiled_truth: renderFactsTable([fact('Forgotten synthetic claim')]), timeline: '' });+ const before = await rendered('forget/inline');+ await engine.executeRaw("INSERT INTO fact_withdrawals(source_id,visibility,fact_hash) VALUES ('default','world',gbrain_fact_fingerprint($1))", ['Forgotten synthetic claim']);+ const after = await snapshotOf('forget/inline');+ expect(parseFactsFence(before).facts[0]!.active).toBe(true);+ expect(parseFactsFence(inlineExportMarkdown(after)).facts[0]!.active).toBe(false);+ expect(compareInlineExportFile(Buffer.from(inlineExportMarkdown(after)), 'forget/inline.md', after)).toEqual({ state: 'equal' });+ expect(compareInlineExportFile(Buffer.from(before), 'forget/inline.md', after).state).toBe('differs');+ });++ test('a segmented page compares by the Git blob id of its streamed export, withdrawals included', async () => {+ await createSegmentedPage(engine, { slug: 'seg/page', truth: renderFactsTable([fact('Segmented synthetic claim')]) + '\n' + 'Segmented filler line.\n'.repeat(50),+ timeline: '- 2026-01-02: segmented event\n' });+ const exported = async (snapshot: ExportSnapshot) => engine.transaction(async tx => {+ const chunks: Buffer[] = [];+ for await (const piece of segmentedExportMarkdown(tx, snapshot.page, exportBodyLedger(snapshot.page.slug, await readExportWithdrawals(tx, 'default')), segmentedExportHead(snapshot))) chunks.push(Buffer.from(piece));+ return Buffer.concat(chunks);+ });+ const blobOf = (bytes: Buffer) => ({ oid: gitBlobOid(bytes, 'sha1'), size: bytes.length, mode: '100644' });+ const compare = (bytes: Buffer, snapshot: ExportSnapshot) => engine.transaction(async tx => compareSegmentedExportBlob(tx, snapshot, await readExportWithdrawals(tx, 'default'), blobOf(bytes), 'sha1'));+ const before = await exported(await snapshotOf('seg/page'));+ expect(await compare(before, await snapshotOf('seg/page'))).toEqual({ state: 'equal' });+ expect(await compare(Buffer.concat([before, Buffer.from('x')]), await snapshotOf('seg/page'))).toEqual({ state: 'differs', paths: ['/body'] });+ await engine.executeRaw("INSERT INTO fact_withdrawals(source_id,visibility,subject,fact_hash) VALUES ('default','world','*',gbrain_fact_fingerprint($1))", ['Segmented synthetic claim']);+ const after = await snapshotOf('seg/page');+ expect(await compare(before, after)).toEqual({ state: 'differs', paths: ['/body'] });+ expect(await compare(await exported(after), after)).toEqual({ state: 'equal' });+ });++ test('declared classes: mirrors, private, alias-private, lineage-private, database-only, db_only prefixes, derive folders and ignored paths', () => {+ const page = (frontmatter: Record<string, unknown> = {}, extra: Record<string, unknown> = {}) => ({ slug: 'notes/x', type: 'note', frontmatter, ...extra });+ expect(declaredDatabaseOnly(page(), 'notes/x.md', policy)).toBeNull();+ expect(declaredDatabaseOnly(page(), 'notes/x.md', { ...policy, mirror: true })).toBe('mirror_source');+ expect(declaredDatabaseOnly(page({ visibility: 'private' }), 'notes/x.md', policy)).toBe('private');+ expect(declaredDatabaseOnly(page({}, { lineage_private: true }), 'notes/x.md', policy)).toBe('lineage_private');+ expect(declaredDatabaseOnly(page({}, { database_only_reason: 'detached' }), 'notes/x.md', policy)).toBe('database_only');+ expect(declaredDatabaseOnly(page(), 'notes/x.md', { ...policy, dbOnly: slug => slug.startsWith('notes/') })).toBe('db_only_prefix');+ expect(declaredDatabaseOnly({ slug: 'atoms/a1', type: 'note', frontmatter: {} }, 'atoms/a1.md', policy)).toBe('derive_folder');+ expect(declaredDatabaseOnly({ slug: 'atoms/a1', type: 'note', frontmatter: {}, source_path: 'atoms/a1.md' }, 'atoms/a1.md', policy)).toBeNull();+ expect(declaredDatabaseOnly({ slug: 'concepts/c1', type: 'note', frontmatter: {}, source_uri: 'x://y' }, 'concepts/c1.md', policy)).toBeNull();+ expect(declaredDatabaseOnly(page(), 'notes/x.md', { ...policy, ignored: new Set(['notes/x.md']) })).toBe('git_ignored');+ });++ test('ignoredPaths reads the ignore rules with filter-free plumbing and never reports a tracked file', async () => {+ const root = tempDir('git-gap-ignore-');+ git(root, 'init', '-q');+ put(root, '.gitignore', 'images/\n');+ put(root, 'images/tracked.md', 'x');+ git(root, 'add', '-f', '.gitignore', 'images/tracked.md');+ git(root, 'commit', '-qm', 'init');+ expect(await ignoredPaths(root, ['images/a.md', 'images/tracked.md', 'notes/b.md'])).toEqual(new Set(['images/a.md']));+ expect(await ignoredPaths(root, ['notes/b.md'])).toEqual(new Set());+ });++ test('the census puts every page in one state, compares with HEAD and reports the working tree separately', async () => {+ const root = tempDir('git-gap-census-');+ git(root, 'init', '-q');+ await useCheckout(root);+ const body = (slug: string, text: string) => engine.putPage(slug, { type: 'note', title: slug.split('/').pop()!, compiled_truth: text, timeline: '' });+ for (const slug of ['notes/equal', 'notes/edited-later', 'notes/deleted-later', 'notes/db-edited', 'notes/git-edited', 'notes/db-with-record', 'notes/missing', 'notes/untracked', 'notes/broken']) {+ await body(slug, `Body of ${slug}.`);+ }+ await engine.putPage('notes/turned-private', { type: 'note', title: 'Turned private', compiled_truth: 'Was public.', timeline: '' });+ await engine.putPage('images/scan', { type: 'note', title: 'Ignored', compiled_truth: 'Image note.', timeline: '' });+ await engine.putPage('atoms/a1', { type: 'note', title: 'Atom', compiled_truth: 'Derived.', timeline: '' });+ await engine.putPage('notes/detached', { type: 'note', title: 'Detached', compiled_truth: 'Kept in the database.', timeline: '' });+ await engine.executeRaw("UPDATE pages SET database_only_reason='detached' WHERE slug='notes/detached'");+ put(root, '.gitignore', 'images/\n');+ for (const slug of ['notes/equal', 'notes/edited-later', 'notes/deleted-later', 'notes/db-edited', 'notes/git-edited', 'notes/db-with-record', 'notes/turned-private']) put(root, `${slug}.md`, await rendered(slug));+ put(root, 'notes/broken.md', '---\ntitle: [unclosed\n---\nBody\n');+ put(root, 'images/scan.md', await rendered('images/scan'));+ commitAll(root, 'init');+ const original = (slug: string) => gitBlobOid(Buffer.from(git(root, 'cat-file', 'blob', `HEAD:${slug}.md`)), 'sha1');+ const revisionOf = async (slug: string) => (await engine.executeRaw<{ r: string }>("SELECT knowledge_revision::text AS r FROM pages WHERE source_id='default' AND slug=$1", [slug]))[0]!.r;+ const [{ incarnation }] = await engine.executeRaw<{ incarnation: string }>("SELECT incarnation::text AS incarnation FROM sources WHERE id='default'");+ const record = async (slug: string, blob: string, revision: string) => {+ const id = await pageId(slug);+ await engine.transaction(async tx => recordSyncImportProvenance(tx, { source_id: 'default', incarnation,+ page_id: id, origin: `${slug}.md`, raw_sha256: 'x', blob_oid: blob, disk_blob_oid: blob, gbrain_version: 'test', revision }));+ };+ const imported = original('notes/git-edited');+ await record('notes/git-edited', imported, await revisionOf('notes/git-edited'));+ await record('notes/db-with-record', original('notes/db-with-record'), 'an-older-revision');+ put(root, 'notes/git-edited.md', (await rendered('notes/git-edited')).replace('Body of notes/git-edited.', 'Edited in Git.'));+ commitAll(root, 'edit in git');+ await body('notes/db-edited', 'Edited in the database.');+ await body('notes/db-with-record', 'Edited in the database too.');+ await engine.putPage('notes/turned-private', { type: 'note', title: 'Turned private', compiled_truth: 'Was public.', timeline: '', frontmatter: { visibility: 'private' } });+ put(root, 'notes/edited-later.md', 'uncommitted edit\n');+ unlinkSync(join(root, 'notes/deleted-later.md'));+ put(root, 'notes/untracked.md', await rendered('notes/untracked'));++ const census = await censusGitGap(engine, 'default', { sample: 50 });+ expect(census).toMatchObject({ status: 'census', checkout: root, head: git(root, 'rev-parse', 'HEAD').trim(), complete: true, pages: 13,+ states: { equal: 3, database_ahead: 2, git_ahead: 1, declared_database_only: 4, undeclared_database_only: 1, worktree_only: 1, unparseable: 1, unsafe_path: 0 },+ declared: { private: 1, git_ignored: 1, derive_folder: 1, database_only: 1, mirror_source: 0, alias_private: 0, lineage_private: 0, db_only_prefix: 0 },+ declared_with_head_blob: 1, database_ahead_without_import_record: 1, git_ahead_database_also_moved: 0, not_compared: 0,+ worktree: { clean: 5, modified: 1, deleted: 1, untracked: 1, absent: 1 } });+ const bySlug = Object.fromEntries(census.sample.map(item => [item.slug, item]));+ expect(bySlug['notes/db-edited']).toEqual({ slug: 'notes/db-edited', path: 'notes/db-edited.md', state: 'database_ahead', fields: ['/compiled_truth'], basis: 'no_import_record', worktree: 'clean' });+ expect(bySlug['notes/db-with-record']).toMatchObject({ state: 'database_ahead', basis: 'import_record' });+ expect(bySlug['notes/git-edited']).toMatchObject({ state: 'git_ahead', basis: 'import_record', fields: ['/compiled_truth'] });+ expect(bySlug['notes/turned-private']).toEqual({ slug: 'notes/turned-private', path: 'notes/turned-private.md', state: 'declared_database_only', declared: 'private' });+ expect(bySlug['notes/missing']).toMatchObject({ state: 'undeclared_database_only', worktree: 'absent' });+ expect(bySlug['notes/untracked']).toMatchObject({ state: 'worktree_only', worktree: 'untracked' });+ expect(bySlug['notes/broken']).toMatchObject({ state: 'unparseable' });+ expect(bySlug['notes/equal']).toBeUndefined();+ expect(describeGitGap(census)).toContain('Working tree against HEAD: clean 5, modified 1, deleted 1, untracked 1, absent 1.');++ await record('notes/git-edited', imported, 'an-older-revision');+ expect((await censusGitGap(engine, 'default', { sample: 0 })).git_ahead_database_also_moved).toBe(1);+ await engine.executeRaw("UPDATE sources SET config=jsonb_build_object('mirror_read_only',true) WHERE id='default'");+ expect((await censusGitGap(engine, 'default', { sample: 0 })).declared.mirror_source).toBe(13);+ }, 120000);++ test('a repository filter, textconv or fsmonitor never runs: HEAD and the working tree are read without them', async () => {+ const root = tempDir('git-gap-filter-');+ git(root, 'init', '-q');+ await useCheckout(root);+ await engine.putPage('notes/a', { type: 'note', title: 'A', compiled_truth: 'Body A.', timeline: '' });+ put(root, 'notes/a.md', await rendered('notes/a'));+ commitAll(root, 'init');+ const marker = join(root, '..', `${root.split('/').pop()}-driver-ran`);+ dirs.push(marker);+ put(root, '.gitattributes', '*.md filter=trap diff=trap\n');+ for (const [key, value] of [['filter.trap.clean', `sh -c 'touch ${marker}; cat'`], ['filter.trap.smudge', `sh -c 'touch ${marker}; cat'`],+ ['filter.trap.process', `sh -c 'touch ${marker}'`], ['filter.trap.required', 'true'], ['diff.trap.textconv', `sh -c 'touch ${marker}; cat'`],+ ['core.fsmonitor', `sh -c 'touch ${marker}'`]]) git(root, 'config', key!, value!);+ put(root, 'notes/a.md', (await rendered('notes/a')) + 'worktree edit\n');+ put(root, 'notes/b.md', 'untracked\n');+ const census = await censusGitGap(engine, 'default', { sample: 0 });+ expect(census.states.equal).toBe(1);+ expect(census.worktree).toMatchObject({ modified: 1 });+ expect(existsSync(marker)).toBe(false);+ });++ test('an unborn branch has no committed file, so a written file is worktree_only', async () => {+ const root = tempDir('git-gap-unborn-');+ git(root, 'init', '-q');+ await useCheckout(root);+ await engine.putPage('notes/a', { type: 'note', title: 'A', compiled_truth: 'Body A.', timeline: '' });+ await engine.putPage('notes/b', { type: 'note', title: 'B', compiled_truth: 'Body B.', timeline: '' });+ put(root, 'notes/a.md', await rendered('notes/a'));+ expect(await censusGitGap(engine, 'default', { sample: 0 })).toMatchObject({ head: null, states: { worktree_only: 1, undeclared_database_only: 1 } });+ });++ test('rows with no Git home: unfenced and stranded facts, links no file derives, timeline rows, holds and parked targets', async () => {+ const root = tempDir('git-gap-rows-');+ git(root, 'init', '-q');+ await useCheckout(root);+ for (const slug of ['notes/filed', 'notes/unfiled', 'atoms/a1']) await engine.putPage(slug, { type: 'note', title: slug, compiled_truth: 'Body.', timeline: '' });+ put(root, 'notes/filed.md', await rendered('notes/filed'));+ commitAll(root, 'init');+ const insertFact = (claim: string, rowNum: number | null, slug: string | null, expired = false) => engine.executeRaw(+ `INSERT INTO facts (source_id, fact, source, row_num, source_markdown_slug, entity_slug, expired_at) VALUES ('default', $1, 'test', $2, $3, $3, ${expired ? 'now()' : 'NULL'})`, [claim, rowNum, slug]);+ await insertFact('unfenced active', null, null);+ await insertFact('unfenced expired', null, null, true);+ await insertFact('fenced on a gone page', 1, 'notes/gone');+ await insertFact('fenced on an unfiled page', 1, 'notes/unfiled');+ await insertFact('fenced on a derived page', 1, 'atoms/a1');+ await insertFact('fenced on a filed page', 1, 'notes/filed');+ const ids = Object.fromEntries(await Promise.all(['notes/filed', 'notes/unfiled', 'atoms/a1'].map(async slug => [slug, await pageId(slug)] as const)));+ const link = (from: string, to: string, source: string | null) => engine.executeRaw('INSERT INTO links (from_page_id, to_page_id, link_type, link_source) VALUES ($1, $2, $3, $4)',+ [ids[from], ids[to], `t-${source ?? 'none'}`, source]);+ for (const source of ['markdown', 'frontmatter', 'mentions', 'wikilink-resolved', 'manual', 'citation-graph', 'concept-provenance', null]) await link('notes/filed', 'notes/unfiled', source);+ const timeline = (slug: string, summary: string) => engine.executeRaw("INSERT INTO timeline_entries (page_id, date, summary) VALUES ($1, '2026-01-02', $2)", [ids[slug], summary]);+ await timeline('notes/filed', 'on a filed page');+ await timeline('notes/unfiled', 'on an unfiled page');+ await timeline('atoms/a1', 'on a derived page');+ const [{ incarnation }] = await engine.executeRaw<{ incarnation: string }>("SELECT incarnation::text AS incarnation FROM sources WHERE id='default'");+ for (const [path, code] of [['notes/x.md', 'file_drift'], ['notes/y.md', 'file_drift'], ['notes/z.md', 'invalid_fence']]) {+ await engine.executeRaw("INSERT INTO op_checkpoints(op,fingerprint,completed_keys) VALUES ('sync-hold',$1,$2::text::jsonb)",+ [`default:${incarnation}:${path}`, JSON.stringify([{ source_id: 'default', incarnation, path, code, page_id: null, meta: {} }])]);+ }+ await engine.transaction(async tx => {+ await tx.executeRaw("SELECT set_config('gbrain.persistence_protocol','2',true)");+ const [request] = await tx.executeRaw<{ id: string }>(`INSERT INTO persistence_requests(principal_kind,principal_id,request_id,operation,source_id,source_incarnation,slug,digest,authority,+ intent_bytes,terminal_reservation) VALUES ('local_cli','test',$1::uuid,'put_page','default',$2::uuid,'notes/filed','x','{}'::jsonb,0,0) RETURNING id::text`, [randomUUID(), incarnation]);+ await tx.executeRaw(`INSERT INTO persistence_effects(request_id,kind,data,state,source_id,source_incarnation) VALUES ($1::uuid,'git',$2::text::jsonb,'failed','default',$3::uuid)`,+ [request!.id, JSON.stringify({ parked: [{ slug: 'notes/filed', error_code: 'git_target_ignored' }, { slug: 'notes/unfiled', error_code: 'git_target_ignored' }] }), incarnation]);+ });+ const census = await censusGitGap(engine, 'default', { sample: 0 });+ expect(census.rows_without_git_home).toEqual({ facts_unfenced: 1, facts_fence_page_missing: 1, facts_on_pages_without_file: { undeclared: 1, declared: 1 },+ links: { total: 4, by_link_source: { '(none)': 1, 'citation-graph': 1, 'concept-provenance': 1, manual: 1 } }, timeline_on_pages_without_file: { undeclared: 1, declared: 1 } });+ expect(census.holds).toEqual({ file_drift: 2, invalid_fence: 1 });+ expect(census.parked_effects).toEqual([{ kind: 'git', code: 'git_target_ignored', targets: 2 }]);+ await engine.executeRaw("DELETE FROM persistence_effects WHERE source_id='default'");+ await engine.executeRaw("DELETE FROM persistence_requests WHERE source_id='default'");+ await engine.executeRaw("DELETE FROM links");+ await engine.executeRaw("DELETE FROM timeline_entries");+ });++ test('a source without a checkout counts declared pages and compares nothing, across batches whatever the ids sort like as text', async () => {+ await engine.executeRaw("SELECT setval(pg_get_serial_sequence('pages','id'), 1, false)");+ for (let i = 0; i < 300; i++) await engine.putPage(`notes/n${i}`, { type: 'note', title: `N${i}`, compiled_truth: 'Body.', timeline: '' });+ await engine.putPage('notes/secret', { type: 'note', title: 'Secret', compiled_truth: 'Secret.', timeline: '', frontmatter: { visibility: 'private' } });+ const [{ min, max }] = await engine.executeRaw<{ min: string; max: string }>('SELECT min(id)::text AS min, max(id)::text AS max FROM pages');+ expect(min.length).toBeLessThan(max.length);+ expect(await censusGitGap(engine, 'default', { sample: 0 })).toMatchObject({ checkout: null, head: null, pages: 301, not_compared: 300, worktree: null,+ states: { declared_database_only: 1, equal: 0 }, declared: { private: 1 } });+ expect((await censusGitGap(engine, 'default', { sample: 0, deadlineAt: Date.now() - 1 })).complete).toBe(false);+ }, 120000);++ test('the census fails closed: a directory that is not a checkout or an unresolvable db_only refuses; lineage and db_only prefixes are declared', async () => {+ await engine.putPage('notes/x', { type: 'note', title: 'X', compiled_truth: 'Body.', timeline: '' });+ const plain = tempDir('git-gap-plain-');+ await useCheckout(plain);+ await expect(censusGitGap(engine, 'default', { sample: 0 })).rejects.toMatchObject({ code: 'storage_error' });+ const root = tempDir('git-gap-policy-');+ git(root, 'init', '-q');+ await useCheckout(root);+ put(root, 'gbrain.yml', 'storage:\n db_only: [notes/]\n');+ await expect(censusGitGap(engine, 'default', { sample: 0 })).rejects.toMatchObject({ code: 'storage_error' });+ put(root, 'gbrain.yml', 'storage:\n db_only:\n - Notes/\n');+ expect((await censusGitGap(engine, 'default', { sample: 0 })).declared.db_only_prefix).toBe(1);+ rmSync(join(root, 'gbrain.yml'));+ await engine.putPage('private/origin', { type: 'note', title: 'Origin', compiled_truth: 'Secret.', timeline: '', frontmatter: { visibility: 'private' } });+ await engine.putPage('notes/summary', { type: 'note', title: 'Summary', compiled_truth: 'Digest.', timeline: '', frontmatter: { derived_from: ['private/origin'] } });+ expect(await censusGitGap(engine, 'default', { sample: 0 })).toMatchObject({ pages: 3, declared: { private: 1, lineage_private: 1 }, states: { undeclared_database_only: 1 } });+ });++ test('doctor db_ahead_of_git is informational: always ok, totals per source with a checkout, partial past its budget', async () => {+ const ctx = { engine, progress: { heartbeat: () => {} } } as never;+ expect(await dbAheadOfGitEntry.run(ctx)).toMatchObject([{ name: 'db_ahead_of_git', status: 'ok', details: { sources: [] } }]);+ await useCheckout(tempDir('git-gap-doctor-plain-'));+ const [plain] = await dbAheadOfGitEntry.run(ctx) as Array<{ status: string; details: any }>;+ expect(plain).toMatchObject({ status: 'ok', details: { sources: [], errors: [] } });+ expect(plain!.details.sources_without_git_checkout).toBeGreaterThanOrEqual(1);+ const root = tempDir('git-gap-doctor-');+ git(root, 'init', '-q');+ await useCheckout(root);+ await engine.putPage('notes/a', { type: 'note', title: 'A', compiled_truth: 'Body A.', timeline: '' });+ await engine.putPage('notes/b', { type: 'note', title: 'B', compiled_truth: 'Body B.', timeline: '' });+ put(root, 'notes/a.md', await rendered('notes/a'));+ commitAll(root, 'init');+ const [check] = await dbAheadOfGitEntry.run(ctx) as Array<{ status: string; message: string; details: any }>;+ expect(check!.status).toBe('ok');+ expect(check!.details.sources.find((s: { source_id: string }) => s.source_id === 'default')).toMatchObject({ pages: 2, complete: true,+ states: { equal: 1, undeclared_database_only: 1 } });+ expect(check!.message).toContain('default: 1 equal, 1 undeclared_database_only');+ expect(check!.message).not.toContain('notes/');+ const [late] = await withEnv({ GBRAIN_DOCTOR_GIT_GAP_TIMEOUT_MS: '1' }, () =>+ dbAheadOfGitEntry.run({ engine, progress: { heartbeat: () => {} }, entryDeadlineAt: Date.now() } as never)) as Array<{ status: string; details: any }>;+ expect(late).toMatchObject({ status: 'ok', details: { partial_sources: ['default'] } });+ });+});++describe('sources git-gap arguments', () => {+ test('one source id, --json and a bounded --sample', () => {+ expect(parseGitGapArgs(['default', '--json', '--sample', '5'])).toEqual({ sourceId: 'default', json: true, sample: 5 });+ expect(parseGitGapArgs(['default'])).toEqual({ sourceId: 'default', json: false, sample: 20 });+ for (const args of [[], ['a', 'b'], ['default', '--apply'], ['default', '--sample', '-1'], ['default', '--sample']]) expect(() => parseGitGapArgs(args)).toThrow(OperationError);+ });+});diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txtindex 557d5fde77..0717a76d77 100644--- a/test/postgres-unit-arms.txt+++ b/test/postgres-unit-arms.txt@@ -78,6 +78,7 @@ test/file-drift-soft-delete-hold-release-gbra133.test.tstest/forecast-journal.test.tstest/frontmatter-reserved-keys-6454.test.tstest/get-chunks-paging.test.ts+test/git-gap-census.test.tstest/google-connector-facts-fence-7292.test.tstest/grade-takes-window.test.tstest/graduation-copy.test.ts