Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(sync): G3 completes: sources reindex --from-git, doctor git_index_lag, and a kept listing never crosses a canonical flip
garrytand6b13b7ed3fe
diff --git a/docs/designs/GIT_CANONICAL_MEMORY.md b/docs/designs/GIT_CANONICAL_MEMORY.mdindex 69136400b5..05cffa11a0 100644--- a/docs/designs/GIT_CANONICAL_MEMORY.md+++ b/docs/designs/GIT_CANONICAL_MEMORY.md@@ -30,7 +30,9 @@ flowchart LR1. **One door.** `publishMutation` stays the single write path. For a strict source it commits the written paths locally (the path-only commit `gbrain git commit-push` already performs) between the file rename and the database transaction, and stamps the commit on the receipt. The Git effect becomes push-only. Writes that arrive while a commit is in flight join the next commit (group commit), so commit cost is paid per group, not per write.2. **Recovery follows git.** A crash after the commit and before the database transaction is finished by indexing the committed file, not by restoring the previous bytes.-3. **The indexer reads commits, not the worktree.** For a strict source sync walks `diff-tree` from the last indexed commit with hardened plumbing and imports each changed blob unconditionally, keyed by path and blob id so replays are idempotent. A committed removal deletes the page. An uncommitted absence means nothing. There is no hold classification, because there is nothing to classify: git is right by definition.+3. **The indexer reads commits, not the worktree.** For a strict source the managed sync pass reads the level at HEAD alone and imports each committed blob the database does not hold, keyed by path and blob id so replays are idempotent: a database version sync never saw, a drifted page and a page under an uncommitted edit all take the committed bytes, and the edit stays on disk. A committed removal deletes the page. An uncommitted absence means nothing. There is no hold classification, because there is nothing to classify: git is right by definition. The pass refuses `--working-tree`, the level it keeps between passes is dropped when `canonical` flips, and a pass that runs between a door commit and its database transaction leaves that write's replay to finish it (the door's own bytes are already committed, so the replay publishes them once). `gbrain sources reindex <id> --from-git` previews every database version Git replaces, bound to HEAD by a hash, and `--apply --expect <hash>` runs that pass; doctor `git_index_lag` reports how many commits and seconds a strict source's index trails HEAD.++ The one place the working tree reaches Git on a strict source is the door commit itself. `commitThroughDoor` stages each written path as it stands in the working tree (a path-only commit under the writer lock), so an uncommitted edit made to that path after the write's rename and before its commit is committed by the write that owns the path. That is deliberate: the writer lock holds the path, and the commit is the write's own. Nothing else, sync included, reads the working tree of a strict source.4. **Push is off the write path.** Pushes are batched, integrate a moved remote in memory, and skip changes that are patch-equivalent to commits this checkout already made. A genuine two-sided conflict on a page path parks only the push; local commits and writes continue, and doctor reports it.5. **Enforced in the database.** For a strict source, a page-content change that does not come from the door or the indexer is refused, so an older binary cannot write database-first.diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex 69360009d3..77a7d714ee 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -30,14 +30,14 @@ 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 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/commands/sources.ts 2085 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); +4 G3 git-canonical: sources reindex dispatch, doc line and help rows (body in sources-reindex.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 refreshsrc/commands/hook.ts 1932 ratchet cathedral-5 heartbeat extraction offsets part of the BrainBench-seam growth; grown v0.46.26.0 megawave hooks-ipc (#4245); +108 monthly backup check: banner + gated session-start note + detached spawn (backup/status-file readers); +28 ship-review egress hardening: per-harness capture dispatch (capture-spec), memorable gate + receipt + relay block, fail-closed unscanned/newest-guess skips; +79 ambient-writeback WP4: hookStop bank step (gate -> bankWritebackTurn -> IPC flush; gate/bank logic live in core/facts + corpus-segments); +41 adversarial fix wave: wide-tail retry when the 128KB window misses the user turn, by-design heartbeat outcome classes, source-in-name banking; +11 #5413 session-end skips claude-cli self-transcripts; +11 #5701: hook lanes pass allowOversize so a long session reaches the bounded tail read; +1 #5371: the stop-hook dirty probe ignores physical-root ownership metadata (root-metadata.ts, engine-free); 2 core memory: user-prompt context-pressure notice wiring (logic in core/context/pressure.ts; session-start composition in core/context/session-start-output.ts); +3 fix wave 11 W2.1 #6091: PreCompact/SessionEnd capture-time consent record calls (logic in core/context/capture-consent.ts); +5 fix wave 11 W2.9 #6083: the three detached-push call sites skip a managed canonical worktree (push_managed_coordinator) + import; +2 fix wave 11 integration: W1 router help guard import beside the W2 managed-root import; +2 fix wave 13 P4.9 #6399: a header-only Codex rollout ends empty_session, not parser_drift; +3 W14 P4.16 (#5799): banner and SessionStart note read livePushStatuses (predicate in core/workspace-push.ts); +1 W15 P5.7 (#4992): gitChildEnv import for the hook git probes (launches moved onto core/spawn.ts)src/core/chunkers/code.ts 1602 ratchet new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (decorated-python defs #3821, version-gate + timeout chunker fixes); grown wave-g (#4511): named defs never folded into merged chunks; grown #4669: skip WASM parse for languages without TOP_LEVEL_TYPES; +6 N13-1: CodeChunkMetadata.definesFunction field + merge-guard stamp (predicate lives in def-types.ts); +10 Lua grammar swap: GRAMMAR_REVISIONS + chunkerStamp() (per-language re-chunk gate); +4: CodeChunkOptions.timeoutMs (per-call parse cap; markdown fences parse under a short cap) and the "Parsing failed" → ChunkerTimeoutError mapping in parseWithTimeoutsrc/core/config.ts 2009 ratchet +2 W5: search.page_rank_cut / page_rank_cut_factor KNOWN_CONFIG_KEYS rows (read in search/page-rank-cut.ts); +3 W3 confidence-gated reranking: search.reranker.gate / gate_min_gap KNOWN_CONFIG_KEYS rows (values parsed in search/crag.ts); re-summed at the W3 merge onto master v0.60.169.0 (1951 measured); +1 budgeted delivery PR 1: the search.auto_packing KNOWN_CONFIG_KEYS row (values validated in search/evidence-packing.ts); +1 #6278: persistence.sync_preparation_ms/maintenance_preparation_ms/preparation_ceiling_ms/max_preparation_attempts/preparation_deadlines key row (logic in persistence/preparation-budget.ts, switches.ts); +22 fix wave 11 W6.2/W6.3 (#5989, #6132): search.cjk_keyword_deadline_ms and search.hnsw_iterative_scan type fields, KNOWN_CONFIG_KEYS rows and the mergeSearchScanKnobs helper that keeps loadConfigWithEngine under its function-size baseline (logic in search/cjk-keyword-deadline.ts, search/hnsw-iterative-scan.ts); +8 #5988: sync.holds/hold_cap/hold_escalate_count/hold_escalate_pct/parser_regression key registration (read by persistence/sync-holds.ts); +3 agent operator wave A4: GBrainConfig.consent file-plane slot + 2 consent.preapprove.* key rows (logic in core/consent.ts); +1 System One v1: decide.* key prefix (validated by ai/decide/config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (spend-controls hint #3703, config-set validation); +3 wave G #3974: sync.include_working_tree key; grown wave-g (#4540 #4494 #4415): extractor caps + intent-pattern config keys; +1 chat-connectors: connectors. config prefix; wave-k: config-table snapshot serving the DB-plane reads (#3980 + #2119 merge); +8: loadConfig hook for ~/.gbrain/.env, loader lives in gbrain-env-file.ts (#3893); +17: litellm/together key-fold slots (#3904 reimpl: two GBrainConfig fields + KNOWN_CONFIG_KEYS rows); +1: link_resolution.cross_source key (#3908); +4 v0.47 gmail-loops: loops.extraction_enabled key; +1: pricing.overrides key (#4633 adoption); +7 #4667 adoption: sync.exclude key registration; +4: eval fix wave keys (quote_verify + 3 rescue knobs); +memorable file-plane key registration (integrations.memorable.enabled + consent-event doc); +33 ambient-writeback: memory.* + brain.audience key registration + GBrainConfig.memory mirror slot (resolvers live in facts/writeback-config.ts); +38 2026-08 wave: retrieval_reflex_volunteer key + env mapping (volunteer-arm kill switch) + E5a registration of the 10 adaptive_return*/autocut*/crag_* search (incl. adversarial batch isEnvDisabled dedup); ambient-writeback (master merge): facts/writeback-config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave; prior growth: sync/intent/chat-connectors/litellm/pricing/loops key folds; +34: #4702 content_sanity.disabled_patterns (type + DB-plane parse/merge + key registration); composition true-up (fix-wave multi-train) | merged v0.48.1.0: master #4788 writeback keys + wave #4702/#4748 keys; master: | merged v0.48.1.0 true-up; ranker wave v0.48.4.0: +4 KNOWN_CONFIG_KEYS rows (+8); +5 #4895: CWD_DOTENV_FILES gains the per-NODE_ENV .local variants Bun auto-loads; +2 #5003: sync.include_hidden key registration; +57 #4605: search.* registry reconciled to the keys mode.ts reads (+20 knob rows, +4 direct-read singletons) + GBrainConfig.search slot + adaptive_return* DB-plane merge; +2 pre-landing review: fts.reindex_in_progress key registration (#4795 marker escape hatch); +4 #4987: auto_timeline key registration (the documented off switch was rejected as unknown); lowered to 1793: GHSA wave v0.50.5.0 moved CWD_DOTENV_FILES + dotenvValuesForKey into core/env-trust.ts (-49, re-exported); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; evidence delivery: 5 registered config keys + comment (+7); +2 #5691: embedding_query_prefix key registration; evidence delivery auto v2: search.return_budget_conversation key row (+1); +1 #5836: facts.entity_inference key row; +6 #5824: search.vector_legacy_guard key row + GBrainConfig.search slot + DB-plane merge; +3 wave 8 lane D1 #5885: takes.auto_embed key row; +3 #5232: GBrainConfig.persistence.write_wait_ms file-plane slot + key row (resolver in persistence/write-wait.ts); +2 F4b: planner.* and import.analyze_every_pages keys; +3 cat40 cost wave C1 (garrytan/gbrain-evals#57 follow-ups): mcp.result_rows GBrainConfig slot + key row (resolver in mcp/result-rows.ts); v0.60.46.0 merge: both waves' +3 compose (1824 + 3 = 1827 measured); +4 #5984: sync.bulk, sync.bulk_size, sync.bulk_max_txn_ms known keys; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (1838 measured); +3 retrieval feedback: the feedback keys in KNOWN_CONFIG_KEYS; 2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x engine graduation composition: both deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); P3 x aow-followup composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); +2 entity mention index: mentions.auto_link, mentions.entity_types, mentions.ignore key rows (resolver in core/mentions/policy.ts); cat40 entity wave merge with v0.60.61.0 (1853 measured); P3 x cat40-entity-wave composition: deltas re-summed at the merge; +6 fix wave lane B3: chat_fallback_on_refusal (GBrainConfig slot, GBRAIN_CHAT_FALLBACK_ON_REFUSAL env fold, known key); +2 W-B4: shared_skills.inventory.* known keys (logic in shared-skills/inventory-limits.ts); +2 fix wave 9 lane B #4921: ai.chat.per_turn_timeout_ms known key; +1 wave 9 lane W #5363: cycle.consolidate.cluster_threshold key row; +1 #5984 lanes: sync.lanes key registration; +2 P8: dream.quote_verify and think.quote_verify known keys; +2 P8: GBrainConfig.mcp.advertised_surface interface slot (resolver in mcp/surface.ts); +2 fix wave 10 lane L1 #4907: cycle.synthesize_concepts.budget_usd registered (validation in cycle/phase-config-values.ts); +2 #5958: dream.propose_takes.call_timeout_ms registered; 3 core memory: memory.core.* and memory.pressure.* known keys; +15 P5: wanted_pages.enabled/remote, line_grammar.enabled/allow_undeclared_types/effective_ranges and put_page.similar_pages key rows (logic in wanted-links.ts, line-grammar.ts, similar-pages.ts); +1 P2 extraction.date_grounding / facts.attribution keys; +1 #6188: fences.normalize registered in KNOWN_CONFIG_KEYS; +2 #6188: fences.repair.max_usd_per_page/per_day key rows; +1 fix wave 12 W2.3 #6231: facts.page_write_notability_filter key row (resolver in facts/notability-filter.ts); +1 #6317: persistence.single_consumer key row (logic in persistence/switches.ts, consumer-election.ts); +2 newer mentions on context_pack cards: mentions.newer_on_cards key row (logic in mentions/newer-mentions.ts); master v0.60.136.0 merge into #5575 memory trust (both sides kept); +1 #5329 (W14 PR3): chronicle.max_events_per_page registered in KNOWN_CONFIG_KEYS (validation in chronicle/config.ts); +2 C1/C2 memory proof wave: search.evidence_date_header + facts.candidate_fusion registry rows; +1 facts.supersession_thresholds registry row (per-model supersession calibration); +1 C4: models.standing_questions key row; +1 search.entity_anchoring key registration (default off; search/entity-anchor.ts); +1 search.query_facts_arm key registration (default off; search/facts-arm.ts); re-summed at the master 6ccf30c3e merge (1871 integration + 1868 master - 1865 base); +1 search.temporal_fact_reserve key registration (default off; search/facts-arm.ts); +1 fix wave 13 PR2: persistence.publication_ceiling_ms (P2.1/P2.3); v0.60.165.0 merge: W14 PR4 +7 and master +2 compose (1947 measured); +1 memory proof wave 2 W1: the recall.question_admission KNOWN_CONFIG_KEYS row (values validated in facts/question-recall.ts); +2 Cat 40 Hard fix wave (#6271) on top: mentions.alias_deny/multiword_aliases/sibling_merge and search.alias_fanout_max/demote_generated KNOWN_CONFIG_KEYS rows (1950 measured); +1 wave 15 P7.1 #5213: cycle.propose_takes.types KNOWN_CONFIG_KEYS row (parse + filter live in cycle/propose-takes.ts); +1 wave 15 P7.2 #6451: autopilot.git_pull KNOWN_CONFIG_KEYS row (read in persistence/automatic-sync-policy.ts); +1 wave 15 P7.3 #6369: cycle.lint.enabled KNOWN_CONFIG_KEYS row (read in cycle/lint-fix-setting.ts); +2 wave 15 P7.4 #5461: think.pages_budget_chars / think.excerpt_ceiling_chars KNOWN_CONFIG_KEYS rows (validation in think/pages-budget.ts); +6 wave 16 G5.1 (#6495): search.keyword_statement_timeout_ms type field, DB merge and KNOWN_CONFIG_KEYS row, toEngineConfig carries it (range + resolver live in postgres-engine/keyword-statement-timeout.ts); +1 GBRA-81 item 1: search.mode_source registered; +1 GBRA-60 S1: search.diverse_pool_depth in the known search keys; +3 #6643: sync.knock_on_refreeze_limit / sync.knock_on_run_limit KNOWN_CONFIG_KEYS rows (read by persistence/sync-run.ts knockOnLimits); +3 #6696: KNOWN_CONFIG_KEYS rows for persistence.maintenance.compaction_stale_hours and refusal_breaker_threshold; +1 wave 5 D5: context.proactive_brief KNOWN_CONFIG_KEYS row (read in context/proactive-brief.ts); +3 Cat 40 next wave part 1: KNOWN_CONFIG_KEYS rows for entity.names_references + entity.record_types + entity.row_page_status (one line), mcp.instructions_governing_rule and search.long_page_unit (re-summed at the 0.60.242.0 merge: master 1975 + 3); +1 wave 17 (#6667): cycle.consolidate.enabled KNOWN_CONFIG_KEYS row (read in cycle/phases/consolidate.ts); +2 Wave B PR 1: pages.segmented_storage and the segmented ceiling/retention keys (page-body/limits.ts); merge v0.60.249.0: Wave B PR 1 and master growth compose at 1981; +1 #6297: dream.patterns.min_interval_hours / child_read_budget_kb known keys; +1 #5012: loops.updates_require_reciprocity known key; +1 wave 18b lane 2 (#6495): search.keyword_timeout_negative_cache_seconds KNOWN_CONFIG_KEYS row; integrated at wave 18b: master 1981 + 4 (lanes 2, 3, 5 known keys); +1 #6948: sync.origin_twins.auto_resolve KNOWN_CONFIG_KEYS row (read in repair/origin-twins-heal.ts); +1 #6948 sweep C-9: facts.absorb_retry.max_resubmits KNOWN_CONFIG_KEYS row (read in facts/dead-absorb-retry.ts); +1 #6907: backup.remote_timeout_ms KNOWN_CONFIG_KEYS row (resolver in backup/repository.ts); +1 at the #6712 PR 4b merge onto master v0.60.310.0 (both sides added a key); +3 #7130: sync.max_deletes / sync.max_delete_ratio / purge.retention_hours KNOWN_CONFIG_KEYS rows and the two per-source cap prefixes (parsers live in core/sync-reconcile.ts); +2 GBRA-154: search.collapse / search.rank_priors KNOWN_CONFIG_KEYS rows (read in search/mode.ts); +1 GBRA-150: sync.metafile_pages KNOWN_CONFIG_KEYS row (read in core/sync.ts); +1 GBRA-159: visibility.honor_aliases KNOWN_CONFIG_KEYS row (read in search/private-visibility.ts); +4 GBRA-156 warm CLI socket: GBrainConfig.serve_cli_socket slot and the published-config.ts import/re-export (snapshot-only merge and MERGED_CONFIG_BY_ENGINE live in core/published-config.ts); re-summed at the GBRA-159 hotfix merge (2000 measured); +2 #7242 GBrainConfig.minions.terminal_hook (interface field); #7252 merge of master v0.60.343.0: both sides grew the file, re-summed (2002 measured); +1 GBRA-155: entity.name_variants KNOWN_CONFIG_KEYS row (read in verbs/entity-variants.ts); +2 GBRA-161: the generations.* KNOWN_CONFIG_KEYS rows and their comment (bounds and reader in generations/config.ts); +1 GBRA-156: search.evidence_tail_trim KNOWN_CONFIG_KEYS row (read in search/evidence-tail-trim.ts); +2 GBRA-175: self_upgrade.channel (the GBrainConfig field and its KNOWN_CONFIG_KEYS row; resolved in core/self-upgrade.ts); re-summed at the master 440eeef6 merge (2009 measured)-src/core/persistence/sync-run.ts 1682 ratchet new row: crossed the 1500 unlisted cap in #6643 (knock-on re-freeze, checkpoint revival, root cause and the truthful --retry-failed wait all drive the private cursor/gate machinery: holdUnderGate, freezeEntry, saveCursor); classification lives in sync-knock-on.ts, the checkpoint clause in checkpoint-validation.ts; peel the settle path (settleFailedRequest and its recoveries) into a sibling module next; +3 #6722: committed pages' size_state tallied into the cursor and the sync receipt size_states (logic in page-embedding-budget.ts addSizeState); merge v0.60.240.0: large pages and master growth compose at 1687; +2 #6694: the slug-mode checkpoint revival import and its doc line (predicate lives in persistence/sync-slug-mode.ts); +11 #6712 PR 3 (L7): a plain sync retries the recorded failure --retry-failed used to (retryRecordedFailure; the unchanged-refusal replay lives in persistence/sync-stop-class.ts replaysUnchangedRefusal), the moved-checkpoint and company content-refusal exceptions; #6712 PR 3 integration: lanes L7 (retryRecordedFailure, +19) and L8 (#6727 legacy-slug refusal line, #6735 timeout revival, +6) compose at 1762; +2 wave 18a integration: #6729 (lane 2, written against the 1745 ceiling) records identity downgrades in performManagedPass through noteIdentityDowngrades (logic in core/sync-identity-downgrades.ts), composed with master 1762; +14 Wave B PR 2: freezeEntry freezes a Markdown file over the read bound by reference (body_ref) and holdFailedFenceRequest holds a streamed refusal; both set freezeEntry/holdFailedFenceRequest locals (blob, oversize, rawHash) so they stay here, the hashing and preparation live in persistence/sync-streamed.ts and the hold in sync-screen.ts streamedRefusalHold; integrated at the master 4e29d0904 merge: master 1764 + Wave B PR 2 14 = 1778 measured; +4 #6948: freezeEntry holds an entry several live pages claim (hold in sync-screen.ts originConflictHold, verdict in persistence/origin-twins.ts); +1 #7167: managedDryRun reports the writer state (the import of persistence/sync-dry-run-writer.ts, where the read lives)+src/core/persistence/sync-run.ts 1686 ratchet new row: crossed the 1500 unlisted cap in #6643 (knock-on re-freeze, checkpoint revival, root cause and the truthful --retry-failed wait all drive the private cursor/gate machinery: holdUnderGate, freezeEntry, saveCursor); classification lives in sync-knock-on.ts, the checkpoint clause in checkpoint-validation.ts; peel the settle path (settleFailedRequest and its recoveries) into a sibling module next; +3 #6722: committed pages' size_state tallied into the cursor and the sync receipt size_states (logic in page-embedding-budget.ts addSizeState); merge v0.60.240.0: large pages and master growth compose at 1687; +2 #6694: the slug-mode checkpoint revival import and its doc line (predicate lives in persistence/sync-slug-mode.ts); +11 #6712 PR 3 (L7): a plain sync retries the recorded failure --retry-failed used to (retryRecordedFailure; the unchanged-refusal replay lives in persistence/sync-stop-class.ts replaysUnchangedRefusal), the moved-checkpoint and company content-refusal exceptions; #6712 PR 3 integration: lanes L7 (retryRecordedFailure, +19) and L8 (#6727 legacy-slug refusal line, #6735 timeout revival, +6) compose at 1762; +2 wave 18a integration: #6729 (lane 2, written against the 1745 ceiling) records identity downgrades in performManagedPass through noteIdentityDowngrades (logic in core/sync-identity-downgrades.ts), composed with master 1762; +14 Wave B PR 2: freezeEntry freezes a Markdown file over the read bound by reference (body_ref) and holdFailedFenceRequest holds a streamed refusal; both set freezeEntry/holdFailedFenceRequest locals (blob, oversize, rawHash) so they stay here, the hashing and preparation live in persistence/sync-streamed.ts and the hold in sync-screen.ts streamedRefusalHold; integrated at the master 4e29d0904 merge: master 1764 + Wave B PR 2 14 = 1778 measured; +4 #6948: freezeEntry holds an entry several live pages claim (hold in sync-screen.ts originConflictHold, verdict in persistence/origin-twins.ts); +1 #7167: managedDryRun reports the writer state (the import of persistence/sync-dry-run-writer.ts, where the read lives); +4 G3 git-canonical: freezeEntry reads a strict source's entry from its commit (pinnedBlob) and carries committedOnly to publication; both use freezeEntry locals (rule in persistence/sync-classify.ts)src/core/bootstrap/harness.ts 2592 ratchet +29 live-PGLite-serve lane: LIVE_SERVE refusal ahead of source resolution + unpinned --token hooks (CI e2e fix); +46 wave review: resolveHookSource dep (serve-parity resolver + federated grant), --source shape validation, loud SOURCE_UNRESOLVED instead of a silent 'default'; +10: #4574 parseCodexBlockBearer http_headers shape + legacy bearer_token fallback; +4 at megawave/wave-k merge; +codex hooks lane: step-7 codex hooks.json + config.toml trust pair, removeHarness arm; +234 ambient-writeback WP3: kind:'instructions' targets (plan/apply/converge-off/remove/status probes, OV-A4 override pre-check) — splice/render mechanics live in instructions-block.ts; +59 adversarial fix wave: registrar-mode block suppression, converge-failure receipt tracking, MCP-confirmed guard before block install; +26 round-3 fixes: codex-lane MCP-confirmed guard + smoke-rollback block strip; master: | merged v0.48.1.0 true-up; +41 #4897 resolveImplicitSource dep + defaultResolveImplicitSource: hooks/token/receipt bind to the serve's implicit default source when --source is omitted; +23 #4586 statusHarness live claude-code mcp verdict (URL mismatch or same-scope non-HTTP registration reads failed, receipt untouched); shared-skills integration on company-ingestion base; +18 #5671: logAmbientPostureNotes helper (registrar note moved out of applyHarness + pre-consent warning when an explicit private facts default meets the HTTP harness; text shared with doctor in facts/writeback-config.ts); +24 #5893: rotation grant carry wiring and its rotationCarry/withheldOperationsNote helpers (carry rules live in token-mint.ts carryLegacyGrant); +6 #5878: --refresh-skills flag and status epoch line (refresh logic lives in harness-skills.ts); +7 #4618 seat: HarnessFlags.seat field, --seat/--no-seat parse via hooks.ts parseSeatFlags, GBRAIN_SEAT in the hook env; -119 #6082: plugin-lane detectors moved to plugin-lanes.ts (re-exported); +18 #6092/#6171: hook ownership identity on write/remove/converge, permission ownership carry, --remove --dry-run and the --status hook census (logic in hooks.ts + harness-hooks.ts); +5 D8 Codex slice: the Codex SessionEnd capture hook obeys the recorded consent (wireCodexCapture: hooks on, capture accepted, never registrar mode) and is disclosed in the consent block; -31 #6743: cleanup gate moved to harness-cleanup.ts; +8 #6798: supersededEnrollments dep (interface field + default) and the --status epoch hint printed only for a superseded enrollment (the brain read lives in harness-skills.ts brainSupersededEnrollments)src/core/oauth-provider.ts 1236 ratchet new row: crossed the 1500 unlisted cap absorbing #3819 (DCR 400 invalid_client_metadata + scope filtering + custom-scheme redirect_uris + pseudo-scheme guard); merged v0.49: transactional grant enforcement shared with hosted grant policies; +1 #5222 resourceUrl optionsrc/core/ops/pages.ts 728 ratchet crossed the unlisted 1500 cap in the fix wave: pack-vocabulary enforcement on capture (#4721) + get_page alias follow (#4275) landed together; next growth should peel a pages-ops submodule; +3: alias hop reads the canonical in the owning source (ship-review); +5: explicit source_id liveness check in get_page/list_pages (#4620); +3: #4857 total-order slug sort + list_pages source_id parse; +5: #4620 explicit removed-source id fails loudly; master integration: +4: authenticated delegated private-write boundary and auto-link suppression; #5105: canonical page mutations peeled into persistence modules; +2 v0.50.5.0 purge parameter and shared preflight call; preparation composes through the persistence modules; +7: source-qualified deep-research fetch authorization and ambiguity refusal (codec lives in deep-research-id.ts); +1 #5567: remote get_page keeps materialized markers; +1 #5622: trusted local capture file parameter; +5 #5709: get_page include_timeline_entries (rows via get_timeline's read policy); +8 GBRA-36 security wave: required outputRedaction policy on each pages op; +1 #5154: list_pages passes listColumnsOnly; +17 #5641: list_pages exposes the updated_after_slug keyset cursor and updated_at_iso; +8 agent operator wave A2: every op declares mutating + idempotent (tags only); +7 F3b (#5954): list_pages pagination meta + listing_truncated notice for MCP callers (logic in ops/list-pages-pagination.ts); +4 #5988: get_page file_held (one indexed hold lookup; logic in persistence/held-reads.ts); +6 #6103: list_pages maps an unreadable updated_after (SQLSTATE 22007/22008) to invalid_params; wave 10 collector: #6103 (+6) and #4807 (+2) compose; +1 wave 11 W4.3 (#5969 D3): put_page drop_timeline param; +1 wave 11 security review: purge_deleted_pages yes param + trusted-CLI guard (consent logic in persistence/purge-deleted.ts); +1 Q2 parser gaps: get_page grammar_diagnostics param (report logic in core/line-grammar-report.ts); master v0.60.136.0 merge into #5575 memory trust (both sides kept); +21 large pages (Wave A): get_page body-mode dispatch, fetch window branch, put_page large-page admission and allow_shrink param, description text (logic in ops/get-page-body.ts and persistence/large-page-guard.ts); +1 D8 funnel: committed put_page records a save when the opt-in funnel is on; +1 #6609: restore_page detach param (logic in persistence/detached-pages.ts); +1 Wave B gem A: post-batch auto-link reads a segmented page materialized (helpers in persistence/segmented-apply.ts); merge v0.60.249.0: composes at 707; +4 Wave B PR 2: get_page refuses a segmented page whole and fetch windows one (logic in ops/get-page-body.ts and page-window/segmented.ts); +2 Wave B PR 2 lane F: get_page and fetch pin segmented reads to the authorized snapshot (pin logic in ops/get-page-body.ts authorizedReadPin); +3 W2 page-at-time: get_page known_as_of param and dispatch (logic in ops/known-as-of.ts and belief/page-at-time.ts); GBRA-151 retrieval P0 x operability wave merge: both sides grew the file, re-summed (721 measured); GBRA-151 #7147 follow-up re-summed at the v0.60.334.0 merge (727 measured); +1 #7305: capture dry run applies the hyphen-run slug admission (logic in persistence/suffixed-slug.ts)diff --git a/src/commands/doctor/checks/git-index-lag.ts b/src/commands/doctor/checks/git-index-lag.tsnew file mode 100644index 0000000000..7496c8125e--- /dev/null+++ b/src/commands/doctor/checks/git-index-lag.ts@@ -0,0 +1,69 @@+/**+ * `git_index_lag` (git-canonical memory, G3, docs/designs/GIT_CANONICAL_MEMORY.md): for each strict source+ * (`config.canonical = "git"`) with a checkout, how far its index trails the commit at HEAD: the commits after the last+ * commit a finished sync pass indexed (`sources.last_commit`) and the seconds since the oldest of them was committed+ * (sync-freshness.ts `readGitBehind`). Warns when that oldest commit is older than+ * `GBRAIN_DOCTOR_GIT_INDEX_LAG_WARN_SECONDS` (default 900) or the source was never indexed; the fix is the sync that indexes+ * it. A source that is not strict is not read. Counts and seconds only, never a sha or path.+ */+import { existsSync } from 'node:fs';+import type { Check } from '../../doctor.ts';+import { connectedEngine, type DoctorContext, type DoctorEntry } from '../context.ts';+import { doctorVerify } from '../check-fix.ts';+import { readGitBehind } from '../../../core/persistence/sync-freshness.ts';+import { isGitCheckout } from '../../../core/persistence/git-gap.ts';++const DOCS = 'docs/designs/GIT_CANONICAL_MEMORY.md#the-model';++/** `GBRAIN_DOCTOR_GIT_INDEX_LAG_WARN_SECONDS` (default 900): how old the oldest unindexed commit of a strict source may get before a warning. */+export function gitIndexLagWarnSeconds(): number {+ const n = parseInt(process.env.GBRAIN_DOCTOR_GIT_INDEX_LAG_WARN_SECONDS ?? '', 10);+ return Number.isFinite(n) && n > 0 ? n : 900;+}++interface SourceLag { source_id: string; indexed: boolean; commits_behind: number | null; seconds_behind: number | null }++async function runGitIndexLag(ctx: DoctorContext): Promise<Check[]> {+ const engine = connectedEngine(ctx);+ ctx.progress.heartbeat('git_index_lag');+ const warnSeconds = gitIndexLagWarnSeconds();+ const checks: Check[] = [];+ try {+ const rows = await engine.executeRaw<{ id: string; local_path: string | null; last_commit: string | null }>(+ `SELECT id, local_path, last_commit FROM sources WHERE NOT archived AND COALESCE(config->>'canonical','')='git' ORDER BY id`);+ const sources: SourceLag[] = [];+ for (const row of rows) {+ if (!row.local_path || !existsSync(row.local_path) || !isGitCheckout(row.local_path)) { sources.push({ source_id: row.id, indexed: !!row.last_commit, commits_behind: null, seconds_behind: null }); continue; }+ if (!row.last_commit) { sources.push({ source_id: row.id, indexed: false, commits_behind: null, seconds_behind: null }); continue; }+ const lag = await readGitBehind(row.local_path, row.last_commit).catch(() => null);+ sources.push({ source_id: row.id, indexed: true, commits_behind: lag?.commits ?? null,+ seconds_behind: lag?.oldest == null ? (lag ? 0 : null) : Math.max(0, Math.round(Date.now() / 1000 - lag.oldest)) });+ }+ const late = sources.filter(source => !source.indexed || (source.seconds_behind ?? 0) > warnSeconds);+ const details = { sources, warn_seconds: warnSeconds, docs: DOCS };+ if (!rows.length) {+ checks.push({ name: 'git_index_lag', status: 'ok', details, message: 'No source is strict (git-canonical), so no index trails a commit.' });+ return checks;+ }+ const describe = (source: SourceLag) => !source.indexed ? `${source.source_id}: never indexed`+ : source.commits_behind === null ? `${source.source_id}: Git could not count the commits after the last indexed one`+ : `${source.source_id}: ${source.commits_behind} commit(s) behind HEAD${source.commits_behind ? `, the oldest committed ${source.seconds_behind}s ago` : ''}`;+ if (!late.length) {+ checks.push({ name: 'git_index_lag', status: 'ok', details, message: `Every strict source's index is within ${warnSeconds}s of HEAD: ${sources.map(describe).join('; ')}.` });+ return checks;+ }+ const first = late[0]!.source_id;+ checks.push({ name: 'git_index_lag', status: 'warn', details,+ message: `The index of ${late.length} strict source(s) trails its commits by more than ${warnSeconds}s: ${late.map(describe).join('; ')}. `+ + 'Git holds these commits and the database has not indexed them yet, so search and reads show older content until a sync pass indexes them.',+ fix: { argv: ['gbrain', 'sync', '--source', first, '--no-pull'], consent: [], actor: 'agent', requires_exclusive: false,+ why: `Indexes the commits of ${first} that the database has not read yet; the sync reads committed blobs only and Git wins. Repeat for each source in details.sources.`,+ verify: doctorVerify('git_index_lag') } });+ } catch (error) {+ checks.push({ name: 'git_index_lag', status: 'ok', details: { health: 'unknown', docs: DOCS },+ message: `Could not read the index lag of strict sources (${error instanceof Error ? error.message : String(error)}); gbrain sources status --json shows each source's watermark.` });+ }+ return checks;+}++export const gitIndexLagEntry: DoctorEntry = { name: 'git_index_lag', emits: ['git_index_lag'], run: runGitIndexLag };diff --git a/src/commands/doctor/registry.ts b/src/commands/doctor/registry.tsindex f667754f72..796ad5c074 100644--- a/src/commands/doctor/registry.ts+++ b/src/commands/doctor/registry.ts@@ -123,6 +123,7 @@ 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 { gitIndexLagEntry } from './checks/git-index-lag.ts';import { syncConfigKeysEntry } from './checks/sync-config-keys.ts';import { ghostPagesEntry } from './checks/ghost-pages.ts';import { originTwinsEntry } from './checks/origin-twins.ts';@@ -288,6 +289,8 @@ export const DOCTOR_CHECK_REGISTRY: readonly DoctorEntry[] = [personTitleDuplicatesEntry,// Git-canonical G1: the read-only git-gap census totals per source with a checkout (informational, always ok).dbAheadOfGitEntry,+ // Git-canonical G3: how far each strict source's index trails the commit at HEAD.+ gitIndexLagEntry,fenceIntegrityEntry,searchModeEntry,];diff --git a/src/commands/sources-reindex.ts b/src/commands/sources-reindex.tsnew file mode 100644index 0000000000..81d3e3d7ba--- /dev/null+++ b/src/commands/sources-reindex.ts@@ -0,0 +1,99 @@+/**+ * `gbrain sources reindex <source-id> --from-git` (git-canonical memory, G3, docs/designs/GIT_CANONICAL_MEMORY.md): the+ * re-derive verb of a strict source (`config.canonical = "git"`). The default `--dry-run` reads the level a full sync pass+ * would classify (sync-pass.ts `readShadowLevel`, read-only) and lists every page where Git's verdict replaces what the+ * database holds: an import over a database version sync never saw, a drifted page, a keep_db page or an edited tombstone,+ * and the deletion of a page whose file a commit removed. It prints a preview hash bound to HEAD and that list.+ * `--apply --expect <hash>` reads the level again, refuses `preview_changed` when it differs, and then runs the full sync+ * pass that applies Git's verdict (`gbrain sync --source <id> --no-pull --full`, with `--no-embed` and `--no-extract` passed on). A source that is not strict is refused,+ * because Git wins only where the source says so. Trusted local CLI only: it prints slugs and paths.+ */+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 { resolveSourceId } from '../core/source-resolver.ts';+import { previewChangedError, previewHash } from '../core/persistence/preview-approval.ts';+import { readShadowLevel } from '../core/persistence/sync-pass.ts';+import type { SyncClass } from '../core/persistence/sync-classify.ts';++const USAGE = 'Usage: gbrain sources reindex <source-id> --from-git [--dry-run | --apply --expect <hash> [--no-embed] [--no-extract]] [--json]';+const DOCS = 'docs/designs/GIT_CANONICAL_MEMORY.md#the-model';++export interface ReindexOverwrite { path: string; slug: string | null; action: 'import' | 'delete'; replaces: SyncClass }++export interface ReindexPreview {+ status: 'preview';+ source_id: string;+ /** The commit the level was read at. */+ head: string;+ /** Every page whose database version Git's verdict replaces, by path. */+ overwrites: ReindexOverwrite[];+ /** The other paths the pass imports or deletes, where the database holds nothing Git lacks. */+ imports: number;+ deletes: number;+ preview_hash: string;+ apply: string[];+}++export function parseReindexArgs(args: string[]): { sourceId: string; apply: boolean; expect: string | null; json: boolean; processing: string[] } {+ const positional: string[] = [];+ let expect: string | null = null, apply = false, fromGit = false;+ for (let i = 0; i < args.length; i++) {+ const arg = args[i]!;+ if (arg === '--expect') { expect = args[++i] ?? null; if (!expect) throw new OperationError('invalid_params', '--expect needs the preview hash.', USAGE); continue; }+ if (arg === '--apply') { apply = true; continue; }+ if (arg === '--from-git') { fromGit = true; continue; }+ if (arg === '--dry-run' || arg === '--json' || arg === '--no-embed' || arg === '--no-extract') continue;+ if (arg.startsWith('-')) throw new OperationError('invalid_params', `Unknown sources reindex flag: ${arg}.`, USAGE);+ positional.push(arg);+ }+ if (positional.length !== 1) throw new OperationError('invalid_params', 'sources reindex needs exactly one source id.', USAGE);+ if (!fromGit) throw new OperationError('invalid_params', 'sources reindex re-derives from Git only: pass --from-git.', USAGE);+ if (apply && args.includes('--dry-run')) throw new OperationError('invalid_params', '--apply and --dry-run exclude each other.', USAGE);+ if (apply && !expect) throw new OperationError('invalid_params', '--apply needs --expect <hash> from the --dry-run preview.', USAGE);+ return { sourceId: positional[0]!, apply, expect, json: args.includes('--json'), processing: args.filter(arg => arg === '--no-embed' || arg === '--no-extract') };+}++/** The read-only preview: what the next full pass of a strict source replaces in the database. */+export async function previewReindex(engine: BrainEngine, sourceId: string): Promise<ReindexPreview> {+ await resolveSourceId(engine, sourceId, undefined, { skipLocalSignals: true });+ const [source] = await engine.executeRaw<{ strict: boolean }>(`SELECT COALESCE(config->>'canonical','')='git' AS strict FROM sources WHERE id=$1`, [sourceId]);+ if (!source?.strict) throw new OperationError('invalid_params', `Source ${sourceId} is not strict (git-canonical), so Git does not win there and nothing was read.`,+ `Only a source with config.canonical = "git" re-derives from Git. gbrain sources git-gap ${sourceId} shows how far its database is from HEAD.`, DOCS);+ const level = await readShadowLevel(engine, { sourceId, full: true });+ if (!level) throw new OperationError('invalid_params', `Source ${sourceId} keeps an approved company-brain manifest, so it has no level to re-derive.`, USAGE, DOCS);+ const unsettled = level.paths.filter(entry => !entry.result.settled && !entry.result.inFlight && (entry.result.action === 'import' || entry.result.action === 'delete'));+ const overwrites = unsettled.filter(entry => entry.result.gitWins)+ .map(entry => ({ path: entry.path, slug: entry.slug, action: entry.result.action as 'import' | 'delete', replaces: entry.result.gitWins!, revision: entry.revision, level: entry.state.level }));+ const preview_hash = previewHash({ source: sourceId, head: level.head, overwrites: overwrites.map(o => [o.path, o.action, o.revision, o.level]) });+ return { status: 'preview', source_id: sourceId, head: level.head, overwrites: overwrites.map(({ path, slug, action, replaces }) => ({ path, slug, action, replaces })),+ imports: unsettled.filter(entry => !entry.result.gitWins && entry.result.action === 'import').length,+ deletes: unsettled.filter(entry => !entry.result.gitWins && entry.result.action === 'delete').length,+ preview_hash, apply: ['gbrain', 'sources', 'reindex', sourceId, '--from-git', '--apply', '--expect', preview_hash] };+}++function describe(preview: ReindexPreview): string {+ const lines = [`Source ${preview.source_id} at ${preview.head.slice(0, 12)}: Git's verdict replaces ${preview.overwrites.length} database version(s); the pass also imports ${preview.imports} and deletes ${preview.deletes} page(s) Git moved.`];+ for (const o of preview.overwrites) lines.push(` ${o.action} ${o.path}${o.slug ? ` (page ${o.slug})` : ''}: replaces ${o.replaces}`);+ lines.push(`Nothing changed. To apply: ${preview.apply.join(' ')}`);+ return lines.join('\n');+}++export async function runSourcesReindex(engine: BrainEngine, args: string[]): Promise<void> {+ const json = args.includes('--json');+ if (args.includes('--help') || args.includes('-h')) { console.log(`${USAGE}\nPreview first: lists every database version Git's verdict replaces on a strict source (${DOCS}).`); return; }+ try {+ const parsed = parseReindexArgs(args);+ const preview = await previewReindex(engine, parsed.sourceId);+ if (!parsed.apply) { console.log(json ? JSON.stringify(preview) : describe(preview)); return; }+ if (preview.preview_hash !== parsed.expect) throw previewChangedError(parsed.expect!, `gbrain sources reindex ${parsed.sourceId} --from-git --dry-run`);+ const { runSync } = await import('./sync.ts');+ await runSync(engine, ['--source', parsed.sourceId, '--no-pull', '--full', ...parsed.processing, ...(json ? ['--json'] : [])]);+ } catch (error) {+ if (!(error instanceof OperationError)) throw error;+ const env = toAgentError(error, { transport: 'cli', command: 'sources reindex', render: cliRenderContext() });+ console.log(json ? JSON.stringify({ status: 'refused', ...env }) : `Reindex refused (${error.code}): ${error.message}\nFix: ${error.suggestion ?? USAGE}`);+ setCliExitVerdict(1);+ }+}diff --git a/src/commands/sources.ts b/src/commands/sources.tsindex 103dc22d13..3a07aa5093 100644--- a/src/commands/sources.ts+++ b/src/commands/sources.ts@@ -21,6 +21,7 @@* 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 reindex <id> --from-git — a strict source's re-derive from Git, preview then apply (sources-reindex.ts)* gbrain sources push [<id>|--path <dir>] — scan-gated add→commit→pull→push* (agent-bootstrap; core in src/core/workspace-push.ts)*@@ -1909,6 +1910,7 @@ export async function runSources(engine: BrainEngine, args: string[]): Promise<vcase '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 'reindex': return (await import('./sources-reindex.ts')).runSourcesReindex(engine, rest);case 'archive': return runArchive(engine, rest);case 'restore': return runRestore(engine, rest);case 'purge': return runPurge(engine, rest);@@ -2015,6 +2017,8 @@ Subcommands:to 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.+ reindex <id> --from-git [--dry-run | --apply --expect <hash>] [--json]+ Strict source: preview, then apply, the full pass where Git wins.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 8a53771a80..b5f3d85e60 100644--- a/src/core/cli-flag-registry.generated.ts+++ b/src/core/cli-flag-registry.generated.ts@@ -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', '--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'],+ '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', '--from-git', '--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', '--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'],+ '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', '--from-git', '--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 65f60a4f24..863bfa37a4 100644--- a/src/core/doctor-categories.ts+++ b/src/core/doctor-categories.ts@@ -210,6 +210,8 @@ export const BRAIN_CHECK_NAMES: ReadonlySet<string> = new Set(['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',+ // Git-canonical G3: how far each strict source's index trails HEAD (doctor/checks/git-index-lag.ts).+ 'git_index_lag','edge_validity','text_projection_readiness','timeline_coverage',diff --git a/src/core/persistence/git-door.ts b/src/core/persistence/git-door.tsindex 7f4b3be892..3242f56995 100644--- a/src/core/persistence/git-door.ts+++ b/src/core/persistence/git-door.ts@@ -26,11 +26,6 @@ export async function sourceCanonicalGit(engine: SqlEngine, sourceId: string, loreturn row?.strict === true;}-/** Whether a managed sync context's source row is strict (G3: the sync level is its commit alone, and Git wins). */-export function sourceStrict(context: { source: { config: Record<string, unknown> | null } }): boolean {- return context.source.config?.canonical === 'git';-}-/** The door marker a strict publication's recovery record carries: the checkout it commits in and the HEAD it started from. */export async function doorMarker(root: string): Promise<NonNullable<FileRecoveryRecord['door']>> {return { root, head: await headCommit(root) };diff --git a/src/core/persistence/sync-pass-run.ts b/src/core/persistence/sync-pass-run.tsindex e7ecdd2bb2..9ed708e77a 100644--- a/src/core/persistence/sync-pass-run.ts+++ b/src/core/persistence/sync-pass-run.ts@@ -31,7 +31,6 @@ import { OPEN_AT_STAMP_CAP, passFingerprint, readPassRow, SYNC_ORIGIN_DELETED_OPtype PassKind, type PassOutcome, type SyncSelection } from './sync-pass-row.ts';import { readSyncAdmission, type SyncAdmission } from './sync-admission.ts';import { faultPoint } from './fault-points.ts';-import { sourceStrict } from './git-door.ts';import { passFoldBase, passIdleProbe, readShadowLevel, workingIdleChange, type PassLevelCache, type ShadowLevel, type ShadowPath } from './sync-pass.ts';import { ownWritebackCommit, type PassFold } from './sync-pass-fold.ts';import { openPassRequests, settleCarried } from './sync-pass-carried.ts';@@ -388,7 +387,7 @@ async function pinPass(engine: BrainEngine, input: SyncPassInput, lease: NonNullconst head = headLine!.trim();const detached = refLine?.trim() === 'HEAD';// G3: a strict source's pass reads its commit alone, a detached HEAD's too (sync-pass.ts).- const strict = sourceStrict(context);+ const strict = context.source.config?.canonical === 'git';const mode: SyncSelection['mode'] = !strict && (detached || (opts.workingTree ?? configuredWorking === 'true')) ? 'working' : 'committed';const selection = passSelection(patterns, opts, context, mode);const configured = !remote && !opts.exclude?.length && !opts.includeHidden?.length && opts.srcSubpath === undefineddiff --git a/src/core/persistence/sync-pass.ts b/src/core/persistence/sync-pass.tsindex eb6cea31cd..8215eeba62 100644--- a/src/core/persistence/sync-pass.ts+++ b/src/core/persistence/sync-pass.ts@@ -46,7 +46,6 @@ import { MANAGED_SYNC_PASS_OP, SYNC_ORIGIN_DELETED_OP, type SyncSelection } fromimport { faultPoint } from './fault-points.ts';import { filterYielding, loopYield, progressYield, sortYielding, turnYield, whileActive, type LoopYield } from './sync-yield.ts';import { countsMatch, proveConfirm, readLevelMark, type ConfirmProof, type LevelMark } from './sync-pass-confirm.ts';-import { sourceStrict } from './git-door.ts';import { domainCache, levelDomain, narrowedWalk, walkAttestations, type LevelDomainCache } from './sync-pass-narrow.ts';export { MANAGED_SYNC_PASS_OP, SYNC_ORIGIN_DELETED_OP };@@ -671,7 +670,7 @@ export async function readShadowLevel(engine: BrainEngine, input: { sourceId: stconst eligibleTree = async (): Promise<{ tree: Map<string, GitTreeEntry>; colon: string[] }> => {if (cache?.tree?.key === treeKey) return cache.tree;if (cache) cache.tree = undefined;- const { tree, colon, reuse } = await eligibleListing(gitRoot, head, scope, { key: [sourceId, incarnation], allowed: input.pass?.levelReuse === true, step, eligible,+ const { tree, colon, reuse } = await eligibleListing(gitRoot, head, scope, { key: [sourceId, incarnation], canonical: strict ? 'git' : 'mixed', allowed: input.pass?.levelReuse === true, step, eligible,prime: listing => levelMetafiles.primeTree(listing) });treeReuse = reuse;if (cache) cache.tree = { key: treeKey, tree, colon };@@ -928,9 +927,9 @@ function scopedPageOrigin(recorded: string, slug: string, originScope: SyncOrigi/** The level's settings, one round trip each and all in flight together; null for a company-brain source. *//** `T`'s eligible entries and its ':' paths (#5032: refused, never part of the level), walked from the listing the last pass may have kept (sync-tree-reuse.ts). */-async function eligibleListing(gitRoot: string, head: string, scope: string, opts: { key: string[]; allowed: boolean; step: LoopYield; eligible: (path: string) => boolean;+async function eligibleListing(gitRoot: string, head: string, scope: string, opts: { key: string[]; canonical: string; allowed: boolean; step: LoopYield; eligible: (path: string) => boolean;prime: (listing: Map<string, GitTreeEntry>) => Map<string, GitTreeEntry> }): Promise<{ tree: Map<string, GitTreeEntry>; colon: string[]; reuse: TreeReuse }> {- const listed = await readTreeLevelReusing(gitRoot, head, scope, { key: opts.key, allowed: opts.allowed, shared: opts.step });+ const listed = await readTreeLevelReusing(gitRoot, head, scope, { key: opts.key, canonical: opts.canonical, allowed: opts.allowed, shared: opts.step });const tree = new Map<string, GitTreeEntry>(), colon: string[] = [];for (const [path, entry] of opts.prime(listed.tree)) {if (isWindowsColonTarget(path)) colon.push(path);@@ -956,7 +955,7 @@ async function readLevelSettings(engine: BrainEngine, context: ManagedSyncContexconst settled = <T>(read: PromiseSettledResult<T>): T => { if (read.status === 'rejected') throw read.reason; return read.value; };if (settled(company)) return null;return { slugMode: settled(slugModeRead), exclude: settled(excludeRead), pack: settled(packRead), mirror: settled(mirrorRead), workingConfig: settled(workingRead),- metafilePages: settled(metafilePagesRead), strict: sourceStrict(context), strategy: input.pass?.strategy ?? (context.source.config?.strategy as string | undefined) ?? 'markdown',+ metafilePages: settled(metafilePagesRead), strict: context.source.config?.canonical === 'git', strategy: input.pass?.strategy ?? (context.source.config?.strategy as string | undefined) ?? 'markdown',includeHidden: [...new Set([...input.pass?.includeHidden ?? [], ...(settled(includeHiddenRead) ?? '').split(/[\n,]/).map(v => v.trim()).filter(Boolean)].map(v => v.endsWith('/') ? `${v}**` : v))],keepDbPrefixes: (() => { try { return loadStorageConfig(root)?.keep_db ?? []; } catch { return []; } })() };}diff --git a/src/core/persistence/sync-tree-reuse.ts b/src/core/persistence/sync-tree-reuse.tsindex b323ee658e..f7c20a3dcf 100644--- a/src/core/persistence/sync-tree-reuse.ts+++ b/src/core/persistence/sync-tree-reuse.ts@@ -7,7 +7,8 @@** Fails closed to a whole read: another process starts empty; an entry leaves the cache while a pass uses it and comes* back only after that pass walked it whole (a failed or concurrent pass finds none); an entry idle for- * TREE_REUSE_MAX_AGE_MS is dropped; the key is the source, its incarnation, the Git root and the scope; a scope with+ * TREE_REUSE_MAX_AGE_MS is dropped; the key is the source, its incarnation, the Git root and the scope, and an entry kept+ * under the other canonical mode (G3: `config.canonical` flipped since) is dropped; a scope with* pathspec magic, a diff larger than a quarter of the tree, a change `readTreeLevel` would not list, and any Git* failure read whole. `sync.level_reuse false` turns reuse off (docs/guides/live-sync.md). With* GBRAIN_SYNC_LEVEL_REUSE_VERIFY=1 (tests and the nightly freshness cell) every reused listing is compared with a whole@@ -22,7 +23,7 @@ export const TREE_REUSE_MAX_AGE_MS = 10 * 60_000;/** A diff of more paths than this (and a quarter of the tree) reads the tree whole. */const TREE_REUSE_MIN_DIFF_BOUND = 2_000;-interface TreeReuseEntry { head: string; tree: Map<string, GitTreeEntry>; at: number; expiry: ReturnType<typeof setTimeout> }+interface TreeReuseEntry { head: string; canonical?: string; tree: Map<string, GitTreeEntry>; at: number; expiry: ReturnType<typeof setTimeout> }const entries = new Map<string, TreeReuseEntry>();/**@@ -51,14 +52,14 @@ export type TreeReuse = 'read' | 'same' | 'patched';* `T` at `head` under `scope`, from the last listing this process kept for `key` when `allowed`; `keep` stores it for the* next pass once the caller has walked it (until then the next pass reads whole), and the caller must not change it.*/-export async function readTreeLevelReusing(gitRoot: string, head: string, scope: string, opts: { key: readonly string[]; allowed: boolean; shared?: LoopYield }):+export async function readTreeLevelReusing(gitRoot: string, head: string, scope: string, opts: { key: readonly string[]; canonical?: string; allowed: boolean; shared?: LoopYield }):Promise<{ tree: Map<string, GitTreeEntry>; reuse: TreeReuse; keep: () => void }> {const key = JSON.stringify([...opts.key, gitRoot, scope]);const prior = opts.allowed ? entries.get(key) : undefined;if (prior) { clearTimeout(prior.expiry); entries.delete(key); }- const keep = (tree: Map<string, GitTreeEntry>) => () => { entries.set(key, { head, tree, at: Date.now(), expiry: dropWhenIdle(entries, key, 'tree', tree) }); };+ const keep = (tree: Map<string, GitTreeEntry>) => () => { entries.set(key, { head, canonical: opts.canonical, tree, at: Date.now(), expiry: dropWhenIdle(entries, key, 'tree', tree) }); };const whole = async () => { const tree = await readTreeLevel(gitRoot, head, scope, opts.shared); return { tree, reuse: 'read' as const, keep: opts.allowed ? keep(tree) : () => {} }; };- if (!opts.allowed || !prior || Date.now() - prior.at > TREE_REUSE_MAX_AGE_MS || /[\\[*?]|^:/.test(scope)) return whole();+ if (!opts.allowed || !prior || prior.canonical !== opts.canonical || Date.now() - prior.at > TREE_REUSE_MAX_AGE_MS || /[\\[*?]|^:/.test(scope)) return whole();let reuse: TreeReuse = 'same';if (prior.head !== head) {const changes = await readTreeChanges(gitRoot, prior.head, head, scope, opts.shared).catch(() => null);diff --git a/test/fixtures/goldens/doctor/content-pglite-human.json b/test/fixtures/goldens/doctor/content-pglite-human.jsonindex 94c52f1fdf..b463734b77 100644--- a/test/fixtures/goldens/doctor/content-pglite-human.json+++ b/test/fixtures/goldens/doctor/content-pglite-human.json@@ -229,6 +229,7 @@" [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] git_index_lag: No source is strict (git-canonical), so no index trails a commit."," [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 0db03da0af..2aee8d3c41 100644--- a/test/fixtures/goldens/doctor/content-pglite-json.json+++ b/test/fixtures/goldens/doctor/content-pglite-json.json@@ -3538,6 +3538,18 @@"name": "db_ahead_of_git","status": "ok"},+ {+ "category": "brain",+ "details": {+ "docs": "docs/designs/GIT_CANONICAL_MEMORY.md#the-model",+ "sources": [],+ "warn_seconds": 900+ },+ "elapsed_ms": "<volatile>",+ "message": "No source is strict (git-canonical), so no index trails a commit.",+ "name": "git_index_lag",+ "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 f9df03b86b..bed1ae230d 100644--- a/test/fixtures/goldens/doctor/hot-checks-pglite-json.json+++ b/test/fixtures/goldens/doctor/hot-checks-pglite-json.json@@ -3761,6 +3761,18 @@"name": "db_ahead_of_git","status": "ok"},+ {+ "category": "brain",+ "details": {+ "docs": "docs/designs/GIT_CANONICAL_MEMORY.md#the-model",+ "sources": [],+ "warn_seconds": 900+ },+ "elapsed_ms": "<volatile>",+ "message": "No source is strict (git-canonical), so no index trails a commit.",+ "name": "git_index_lag",+ "status": "ok"+ },{"category": "brain","details": {@@ -8452,6 +8464,18 @@"name": "db_ahead_of_git","status": "ok"},+ {+ "category": "brain",+ "details": {+ "docs": "docs/designs/GIT_CANONICAL_MEMORY.md#the-model",+ "sources": [],+ "warn_seconds": 900+ },+ "elapsed_ms": "<volatile>",+ "message": "No source is strict (git-canonical), so no index trails a commit.",+ "name": "git_index_lag",+ "status": "ok"+ },{"category": "brain","details": {diff --git a/test/fixtures/goldens/doctor/hot-checks-postgres-json.json b/test/fixtures/goldens/doctor/hot-checks-postgres-json.jsonindex a93ad6facd..619b8f4b9e 100644--- a/test/fixtures/goldens/doctor/hot-checks-postgres-json.json+++ b/test/fixtures/goldens/doctor/hot-checks-postgres-json.json@@ -3764,6 +3764,18 @@"name": "db_ahead_of_git","status": "ok"},+ {+ "category": "brain",+ "details": {+ "docs": "docs/designs/GIT_CANONICAL_MEMORY.md#the-model",+ "sources": [],+ "warn_seconds": 900+ },+ "elapsed_ms": "<volatile>",+ "message": "No source is strict (git-canonical), so no index trails a commit.",+ "name": "git_index_lag",+ "status": "ok"+ },{"category": "brain","details": {@@ -8456,6 +8468,18 @@"name": "db_ahead_of_git","status": "ok"},+ {+ "category": "brain",+ "details": {+ "docs": "docs/designs/GIT_CANONICAL_MEMORY.md#the-model",+ "sources": [],+ "warn_seconds": 900+ },+ "elapsed_ms": "<volatile>",+ "message": "No source is strict (git-canonical), so no index trails a commit.",+ "name": "git_index_lag",+ "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 cf60802c8d..50bf6dc38c 100644--- a/test/fixtures/goldens/doctor/json-pglite-degraded.json+++ b/test/fixtures/goldens/doctor/json-pglite-degraded.json@@ -3207,6 +3207,18 @@"name": "db_ahead_of_git","status": "ok"},+ {+ "category": "brain",+ "details": {+ "docs": "docs/designs/GIT_CANONICAL_MEMORY.md#the-model",+ "sources": [],+ "warn_seconds": 900+ },+ "elapsed_ms": "<volatile>",+ "message": "No source is strict (git-canonical), so no index trails a commit.",+ "name": "git_index_lag",+ "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 57ee07cb05..e96daece8a 100644--- a/test/fixtures/goldens/doctor/json-pglite-fresh.json+++ b/test/fixtures/goldens/doctor/json-pglite-fresh.json@@ -3250,6 +3250,18 @@"name": "db_ahead_of_git","status": "ok"},+ {+ "category": "brain",+ "details": {+ "docs": "docs/designs/GIT_CANONICAL_MEMORY.md#the-model",+ "sources": [],+ "warn_seconds": 900+ },+ "elapsed_ms": "<volatile>",+ "message": "No source is strict (git-canonical), so no index trails a commit.",+ "name": "git_index_lag",+ "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 6901603e00..55e4ed636e 100644--- a/test/fixtures/goldens/doctor/json-postgres-fresh.json+++ b/test/fixtures/goldens/doctor/json-postgres-fresh.json@@ -3253,6 +3253,18 @@"name": "db_ahead_of_git","status": "ok"},+ {+ "category": "brain",+ "details": {+ "docs": "docs/designs/GIT_CANONICAL_MEMORY.md#the-model",+ "sources": [],+ "warn_seconds": 900+ },+ "elapsed_ms": "<volatile>",+ "message": "No source is strict (git-canonical), so no index trails a commit.",+ "name": "git_index_lag",+ "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 71cff66a21..19502ddb58 100644--- a/test/fixtures/goldens/doctor/registry-build-checks.json+++ b/test/fixtures/goldens/doctor/registry-build-checks.json@@ -985,6 +985,10 @@"category": "brain","name": "db_ahead_of_git"},+ {+ "category": "brain",+ "name": "git_index_lag"+ },{"category": "brain","name": "fence_integrity"diff --git a/test/git-canonical-indexer-g3.test.ts b/test/git-canonical-indexer-g3.test.tsindex a255eadc31..96dff41744 100644--- a/test/git-canonical-indexer-g3.test.ts+++ b/test/git-canonical-indexer-g3.test.ts@@ -8,6 +8,8 @@* where a source that is not strict holds `worktree_dirty`;* - deletes a page whose file a commit removed while an untracked copy stays on disk, as a page imported from Git does;* - refuses `--working-tree` with `managed_sync_flag_refused`.+ * `gbrain sources reindex --from-git` previews every database version that pass replaces and applies it under its hash;+ * doctor `git_index_lag` reports how far a strict source's index trails HEAD.*/import { describe, expect, test } from 'bun:test';import { execFileSync } from 'node:child_process';@@ -15,8 +17,14 @@ import { randomUUID } from 'node:crypto';import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';import { join } from 'node:path';import type { BrainEngine } from '../src/core/engine.ts';+import { operations } from '../src/core/operations.ts';+import { installFaultHook } from '../src/core/persistence/fault-points.ts';import { withCoordinatedWrite } from '../src/core/persistence/context.ts';import { performManagedSync } from '../src/core/persistence/sync-run.ts';+import { __resetTreeReuseForTests } from '../src/core/persistence/sync-tree-reuse.ts';+import { previewReindex, runSourcesReindex } from '../src/commands/sources-reindex.ts';+import { gitIndexLagEntry } from '../src/commands/doctor/checks/git-index-lag.ts';+import { _resetCliExitVerdictForTests } from '../src/core/cli-force-exit.ts';import { managedBrain } from './helpers/managed-brain.ts';import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';import { TEST_WRITE_ATTRIBUTION } from './helpers/write-attribution.ts';@@ -26,6 +34,7 @@ const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', rootconst note = (slug: string, body: string) => `---\ntype: concept\ntitle: ${slug}\n---\n\n${body}\n`;const OPTS = { sourceId: 'default', noPull: true, noEmbed: true, noExtract: true };const SLUGS = ['notes/ahead', 'notes/drift', 'notes/dirty', 'notes/removed'];+const putPage = operations.find(op => op.name === 'put_page')!;const holds = async (engine: BrainEngine) => (await engine.executeRaw<{ r: { path: string; code: string } }>("SELECT completed_keys->0 AS r FROM op_checkpoints WHERE op='sync-hold' ORDER BY fingerprint")).map(({ r }) => `${r.path} ${r.code}`);@@ -90,4 +99,111 @@ for (const backend of testBackends()) describe(`[${backend}] G3: a strict sourceawait expect(performManagedSync(engine, { ...OPTS, workingTree: true })).rejects.toMatchObject({ code: 'managed_sync_flag_refused', detail: '--working-tree' });expect((await page(engine, 'notes/ahead'))!.body).toContain('The committed body of notes/ahead.');}, { databaseUrl, setup }), 180_000);++ test('sources reindex --from-git previews what Git replaces, refuses a stale hash, and its apply leaves nothing to replace', () => managedBrain(async ({ engine, root }) => {+ await diverge(engine, root);+ await expect(previewReindex(engine, 'default')).rejects.toMatchObject({ code: 'invalid_params' });+ await strict(engine);+ const preview = await previewReindex(engine, 'default');+ expect(preview.overwrites).toEqual(expect.arrayContaining([+ { path: 'notes/ahead.md', slug: 'notes/ahead', action: 'import', replaces: 'db_ahead' },+ { path: 'notes/drift.md', slug: 'notes/drift', action: 'import', replaces: 'drift' },+ ]));+ expect(preview.overwrites).toHaveLength(2);+ expect(preview).toMatchObject({ imports: 1, deletes: 1 });+ expect((await page(engine, 'notes/ahead'))!.body).toContain('Written to the database alone.');+ const log = console.log;+ try {+ console.log = () => {};+ await runSourcesReindex(engine, ['default', '--from-git', '--apply', '--expect', 'stale', '--no-embed', '--no-extract']);+ expect((await page(engine, 'notes/ahead'))!.body).toContain('Written to the database alone.');+ _resetCliExitVerdictForTests();+ await runSourcesReindex(engine, ['default', '--from-git', '--apply', '--expect', preview.preview_hash, '--no-embed', '--no-extract']);+ } finally { console.log = log; _resetCliExitVerdictForTests(); }+ expect((await page(engine, 'notes/ahead'))!.body).toContain('The committed body of notes/ahead.');+ expect((await page(engine, 'notes/removed'))!.deleted).toBe(true);+ expect((await previewReindex(engine, 'default')).overwrites).toEqual([]);+ }, { databaseUrl, setup }), 180_000);++ test('doctor git_index_lag reads strict sources only and warns when an unindexed commit is older than its bound', () => managedBrain(async ({ engine, root }) => {+ const ctx = { engine, progress: { heartbeat: () => {} } } as never;+ expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');+ expect(await gitIndexLagEntry.run(ctx)).toMatchObject([{ name: 'git_index_lag', status: 'ok', details: { sources: [] } }]);+ await strict(engine);+ expect(await gitIndexLagEntry.run(ctx)).toMatchObject([{ status: 'ok', details: { sources: [{ source_id: 'default', indexed: true, commits_behind: 0 }] } }]);+ writeFileSync(join(root, 'notes/ahead.md'), note('notes/ahead', 'An old commit sync has not read.'));+ execFileSync('git', ['-C', root, '-c', 'user.name=Example', '-c', '[email protected]', '-c', 'commit.gpgsign=false', 'commit', '-qam', 'old edit'],+ { env: { ...process.env, GIT_COMMITTER_DATE: '2020-01-01T00:00:00Z', GIT_AUTHOR_DATE: '2020-01-01T00:00:00Z' }, stdio: 'ignore' });+ const [late] = await gitIndexLagEntry.run(ctx) as Array<{ status: string; details: any; fix?: { argv: string[] } }>;+ expect(late).toMatchObject({ status: 'warn', details: { sources: [{ source_id: 'default', commits_behind: 1 }] }, fix: { argv: ['gbrain', 'sync', '--source', 'default', '--no-pull'] } });+ expect(late!.details.sources[0].seconds_behind).toBeGreaterThan(900);+ await performManagedSync(engine, OPTS);+ expect(await gitIndexLagEntry.run(ctx)).toMatchObject([{ status: 'ok', details: { sources: [{ commits_behind: 0 }] } }]);+ }, { databaseUrl, setup }), 180_000);++ test('flipping canonical between two passes on the same HEAD reads the level again each way', () => managedBrain(async ({ engine }) => {+ __resetTreeReuseForTests();+ await engine.setConfig('sync.level_reuse', 'true');+ const listings: string[] = [];+ let pass = 0;+ installFaultHook((point, detail) => {+ if (point === 'sync:level_read' && detail.round === 1) listings.push(`${pass}:${(detail.level?.shadow as { treeReuse?: string } | undefined)?.treeReuse}`);+ });+ try {+ pass = 1; expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');+ await databaseOnlyEdit(engine, 'notes/ahead', 'Written to the database alone.');+ pass = 2; await performManagedSync(engine, OPTS);+ expect((await page(engine, 'notes/ahead'))!.body).toContain('Written to the database alone.');+ await strict(engine);+ pass = 3; await performManagedSync(engine, OPTS);+ expect((await page(engine, 'notes/ahead'))!.body).toContain('The committed body of notes/ahead.');+ await engine.executeRaw(`UPDATE sources SET config = config - 'canonical' WHERE id='default'`);+ await databaseOnlyEdit(engine, 'notes/ahead', 'Written to the database alone, again.');+ pass = 4; await performManagedSync(engine, OPTS);+ expect((await page(engine, 'notes/ahead'))!.body).toContain('Written to the database alone, again.');+ await strict(engine);+ pass = 5; await performManagedSync(engine, OPTS);+ expect((await page(engine, 'notes/ahead'))!.body).toContain('The committed body of notes/ahead.');+ pass = 6; await performManagedSync(engine, OPTS);+ } finally { installFaultHook(undefined); __resetTreeReuseForTests(); }+ // Every pass is at one HEAD, and passes 2 and 6 change nothing Git holds (they read no level): each pass after a flip+ // reads the listing whole instead of taking the one the last pass of that mode kept.+ expect(listings).toEqual(['1:read', '3:read', '4:read', '5:read']);+ expect(await holds(engine)).toEqual([]);+ }, { databaseUrl, setup }), 180_000);++ test('a sync pass that runs between a door commit and its replay leaves the replay to complete it, once', () => managedBrain(async ({ engine, ctx, root }) => {+ expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');+ await strict(engine);+ const before = await page(engine, 'notes/ahead');+ const [{ revision }] = await engine.executeRaw<{ revision: string }>("SELECT knowledge_revision::text AS revision FROM pages WHERE source_id='default' AND slug='notes/ahead'");+ const initial = git(root, 'log', '--format=%H', '--', 'notes/ahead.md');+ const requestId = randomUUID();+ let thrown = 0, crashedAt = '';+ let syncing: Promise<unknown> | undefined;+ installFaultHook(async (point, detail) => {+ if (detail.requestId !== requestId) return;+ if (point === 'publication:before_commit' && !thrown) { thrown++; crashedAt = git(root, 'rev-parse', 'HEAD'); throw Object.assign(new Error('database interruption'), { code: 'CONNECTION_CLOSED' }); }+ // The replay: PGLite claims it again (consumer:preparing); Postgres retries the group's publication (publication:prepared).+ if ((point === 'consumer:preparing' || point === 'publication:prepared') && thrown && !syncing) {+ // The pass starts while the door commit has landed and its row has not: it classifies the page in flight (its request is+ // open) or reads the level after the replay, and never imports over the replay.+ syncing = performManagedSync(engine, OPTS);+ }+ });+ try {+ const done = await putPage.handler(ctx, { slug: 'notes/ahead', content: note('notes/ahead', 'Written through the door.'), request_id: requestId, wait_ms: 30_000, expected_revision: revision }) as Record<string, any>;+ expect(done).toMatchObject({ state: 'committed' });+ await syncing;+ } finally { installFaultHook(undefined); }+ expect(thrown).toBe(1);+ expect(before!.body).toContain('The committed body of notes/ahead.');+ expect(git(root, 'show', `${crashedAt}:notes/ahead.md`)).toContain('Written through the door.');+ expect(git(root, 'log', '--format=%H', '--', 'notes/ahead.md').split('\n')).toEqual([crashedAt, initial]);+ expect((await page(engine, 'notes/ahead'))!.body).toContain('Written through the door.');+ await performManagedSync(engine, OPTS);+ expect((await page(engine, 'notes/ahead'))!.body).toContain('Written through the door.');+ expect(git(root, 'status', '--porcelain', '--', 'notes/ahead.md')).toBe('');+ expect(await holds(engine)).toEqual([]);+ }, { databaseUrl, setup }), 180_000);});diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txtindex 6ae31ddb4e..11c95f50da 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-canonical-indexer-g3.test.tstest/git-door-strict-gbra133.test.tstest/git-gap-census.test.tstest/google-connector-facts-fence-7292.test.ts