Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript
58.6 KB
Raw Blame

Canonical reconciliation

See generations and continued entries.

  • src/commands/sync-diagnostics.ts + src/core/persistence/{sync-run,verb-errors}.ts — bounded source/slug/path/reason diagnostics derive from immutable managed-sync receipts, including when the local failure ledger is unavailable. Direct and resident-owner JSON carry the same receipt; human memory errors lead with the specific write reason without widening frozen v1 error codes. Pending requests retain their original UUID, terminal corrections require a new UUID, and neither retry nor line-ending diagnostics bypasses raw-byte or skip guards.

  • src/core/persistence/reconcile*.ts — trusted-local exact-page reconciliation: loss-preserving semantic preview, explicit JSON Pointer choices, pinned identity/revision/raw-file/policy checks, durable private preimages and same-ID replay through the existing coordinator. Normal overwrite protection stays unchanged. The bounded audit reports source-scoped drift without repair or checkpoint changes; a database-only page (isDatabaseOnlyPage, with no file at its slug-derived path) counts as database_only with no reconcile suggestion, never as drift, while a legacy row that merely lacks source_path is audited as usual. src/commands/source-reconcile.ts provides strict CLI parsing, private artifact I/O, brain routing and resident-owner delegation; the operations stay outside public MCP. Operator flow: docs/guides/concurrent-writes.md. Tests cover merge choices, both engines, grants, stale previews, read-only audit, and private files. A database-only page (no source_path, no source_uri; isDatabaseOnlyPage in src/core/persistence/unbound-pages.ts) is matched to the canonical file at its slug-derived path (ReconcileState.origin: 'slug_derived'), and apply records that path as its source_path (the #5254 unbound collision; test/reconcile-unbound-collision.test.ts). Private fact rows (#6137): reconcile-prepare.ts privateFactViolation identifies a fact row by (row number, claim), as restoreHiddenFactRows does. A stored non-world row carried at its identity must be unchanged; a row at no stored identity may not carry a stored private claim under another visibility, and a world row may not carry (or newly gain) a stored private row's context of 24 or more characters verbatim; sources are not compared. The permission_denied refusal names only the row number, with a gbrain get read fix. It guards verbatim copies, not reworded text. #7897: the merged result imports with holdNoncanonicalPrivate, so a merge asking for private in a spelling page privacy does not read (a file's Visibility: private, which the protected lowercase visibility key does not cover) refuses visibility_not_applied at preview and apply (test/reconcile-private-hold-7897.test.ts). #6138: an --auto-additive preview classified no_drift asks Git (hardened-git.ts hardenedPathDirty: filter-free plumbing, never git status, so the checkout's clean/process filters never run; null when only repository config could decide) whether the canonical file differs from its last commit and returns git_dirty; a dirty file's next_action says the content agrees, the difference is only how it is written, reconcile does not commit, and names git -C <root> diff -- <file> (committing it is the user's decision; the managed commit path is deferred, D5). The "retry the original write" step is conditional on the preview coming from a refused write. Tests: test/persistence-reconcile-git-dirty-6138.test.ts. #6222/#6254: assertSoleFileClaim (reconcile-state.ts) refuses on any claimant findLiveFileClaimants (file-claims.ts) returns, naming the soft-delete exit (#6517). Its predicates (fileClaimCandidatesQuery) match the v219 expression indexes pages_source_path_name_idx and pages_file_uri_name_idx (built online, one statement per call). sources reconcile help says writes to one source publish one at a time. Tests: test/persistence-reconcile.test.ts, test/e2e/pages-reconcile-name-indexes-postgres.test.ts. #6394: readReconcileState(..., { adoptSlugPath }) lets a live page with no recorded origin and no database-only marker reconcile against the file at its slug path (slugDerivedOrigin, mode-aware), never for a declared db_only slug, a never-filed derive-phase page, a page with a source_uri or a mirror-only page; the CLI flag is gbrain sources reconcile … --preview --adopt-slug-path, and apply and the consumer's prepare adopt only when the preview's stored page recorded no origin (reconcilePreviewAdopts), with the pinned relative path and binding digest unchanged. The drift refusal names the flag for such a page. #6712 wave: a missing canonical file refuses source_changed / detail canonical_file_missing with the route canonicalDeletionState picks from bounded filter-free Git plumbing (missingFileRoute: still committed at HEAD → commit the deletion or gbrain repair ghost-pages; gone from HEAD, or no Git or no commit → gbrain repair file-drift --prefer database|file). readReconcileState(..., { fileGone }) instead returns an absent state for a recorded origin: empty preimage bytes, raw_file_hash pinned to ABSENT_FILE_HASH (all zeros, which no file hashes to, so a file that reappears is stale), the file side read as the page itself, and assertSoleFileClaim run with absent: true (file-claims.ts absentCanonicalPath, so a candidate recording the same missing path still claims it). reconcileReadOptions derives adoptSlugPath and fileGone from a stored preview for apply and the consumer's prepare, whose file target then expects no bytes (expectedBeforeHash: null). Test: test/repair-file-drift-deleted-6712.test.ts. readDeletedDriftTarget reads the deleted side of a held file that is present: a deleted page at the origin is tombstone_edited (id and revision), otherwise a deleted sync-origin-deleted marker is purged_differs (its value digested); a live claimant, a missing file, no deletion or bytes the marker held return changed.

  • src/core/persistence/reconcile-additive.ts (#5974) — pure structural drift classifier over the complete file/database delta: inserted whole lines (two-pointer subsequence, CRLF-normalized; fence, heading and table insertions excluded) are suggested; an append-only contacts list (or rows advancing a date), an allowlisted activity date moving forward, and one-sided ordinary fields are auto; policy/privacy/identity/tag changes and everything else are review. --auto-additive previews write take_file only for auto (and suggested with --accept-suggested), recorded as format-2 auto_decisions with an evidence digest that apply and owner preparation recheck. --audit --classify reports per-page verdicts and counts, never values; #5966 (W14 P1.7) adds the slug_rule_mismatch verdict (a legacy unstamped file of a slug the path cannot derive, fix: gbrain repair frontmatter) read from readReconcileState's refusal (detail: slug_rule_mismatch once the wave-13 reconcile-state.ts hunk lands; until then an invalid_params refusal on a non-fixed-point slug).

  • src/core/persistence/publication-failure.ts (#5974) — maps a P0001 from the managed-writer guard (which raises TABLE/SCHEMA, managed_writer_guard:<branch> and a JSON DETAIL) or another trigger to a bounded error_detail (origin, raiser, table, op, branch, relationship, stage, plus owner-only source ids and state and the attempt's build/host). Receipts expose only publicFailureDetail; sources writer status lists the full detail under recent_failures. #5929: ownerExceptionFailure (the coordinator requestError fallback) keeps an unexpected exception's class, errno and top src/...:line frame as origin: owner_exception (never an application error's message), so withAttempt stamps the build; #7112: a server-generated database error (a five-character SQLSTATE, a severity and a routine; never a PL/pgSQL RAISE or ASSERT or another class P0 error) also keeps error_text (its primary message, at most 240 characters; object names survive only in a known catalog message such as a not-null violation, or a syntax-error or does-not-exist message whose name the statement holds as an identifier; any other message loses everything from its first quote to its last, because Postgres does not escape quotes inside a value) and statement (the failing SQL tokenized: keywords, identifiers, parameter markers and operators, with every literal, E-string, dollar-quoted body, number and comment replaced or dropped, cut at anything unrecognized, at most 160 characters, never the parameters) and position, all owner-only; a trusted local gbrain write-request <id> returns the full error_detail; publicFailureDetail is an allow-list (origin, sqlstate, raiser, table, op, branch, relationship, reason, stage, fence), so error_class/errno/frame/error_text/statement/position, sources and attempt stay owner-only; ownerBuildMismatch drives the local owner_build receipt field (ops/persistence.ts) and the submit-time why/fix (page-mutations.ts), and ownerExceptionLogText the consumer log line. Wave 16 (GBRA-79, #6513 comments): an untyped refusal carries a CLOSED reason (PUBLICATION_REASONS: attribution_unclassified_table and trust_unclassified_table from the two stamp triggers' own "is not classified for table" raise, graduation_in_progress from the engine-graduation fence, which raises SQLSTATE 55000 and which databaseRefusal now recognizes, else unknown); the message decides nothing on its own (the same text from another raiser, or the fence's text under P0001, is unknown), the public message names only the enum (Publication failed (P0001 in <raiser>: <reason>)), and no part of the message is stored, owner-side included (#5974's rule). publicFailureDetail passes reason only as a member of the enum, whatever a stored detail holds. The projection rides the managed failure (sync-failures.ts ManagedSyncFailure.write_error_detail, recorded with the failure and re-read from the pending receipt by readManagedSyncFailures; publicationDetailText appends raiser= table= reason= to formatManagedSyncFailure, so the ledger mirror and doctor carry it) and gbrain sync status --json (last_error.write_error_detail, last_error.detail = the reason, which classifySyncFault refines by: graduation_in_progress is connection / retry / no human in sync-fault-class.ts). Tests: test/publication-failure-reason-6513.test.ts (mapping, privacy negatives, allow-list), test/sync-status-failure-detail-6513.test.ts (both engines, a real operator trigger).

  • src/core/cycle/extract-atoms-page-state.ts — derived page scan/failure state keyed by source incarnation, stable page identity and content hash. Compare-and-swap stamps never update canonical frontmatter. Reviewed reconciliation can carry matching state across removal of legacy bookkeeping fields. Unmanaged atom items complete as one generation; managed extraction uses journaled publication and a durable completion receipt after trusted local source-wide authority checks and, for filesystem publication, owner preflight.

  • src/core/persistence/managed-mode.ts — the one reader of the brain's persistence mode (#6482). readManagedMode / readPersistenceBrain accept exactly one persistence_brain row with a boolean enabled (optionally FOR SHARE / FOR UPDATE) and refuse anything else (storage_error, detail: persistence_mode_unknown, fix gbrain sources writer status --probe --json); only a well-formed enabled: false row selects the unmanaged path, so a missing, duplicated or malformed row can never route a write around the owner. Every non-test reader of the mode goes through it (test/persistence-mode-reader-guard.test.ts lists the few schema and admin-intent files allowed their own statement); ownership.ts re-exports it for callers that already import ownership.

  • src/core/persistence/sync-slices.ts — #6349 path-sliced staging for a managed target that exceeds the cursor bound with no commit axis to stage on (a first sync, a --full tree walk, one commit above the bound). sliceEntries cuts the whole resolved manifest in (phase, code-unit path) order: every import slice, then bounded deletion slices, the longest prefix the bound admits. The slice cursor { phase, after, head, target } lives in op_checkpoints (managed-sync-slice, keyed by source, incarnation and the run's cursor options so a resumed invocation with other exclusions starts over), written or cleared by the slice's checkpoint in the same transaction that leaves last_commit untouched until the last slice settles; sync-discovery.ts resumes an unfinished target pinned at its recorded commit.

  • src/core/persistence/sync-discovery.ts + sync-origin.ts — managed owner-only Git discovery with source-relative exclusions and one-statement page identity/revision/liveness snapshots. A non-Git root refuses sync_not_applicable. #6517: selectOriginClaimant (sync-origin.ts) is the one origin rule, applied by the discovery census and by assertSyncPageOrigin at preparation and publication: a live page wins over tombstones, several live pages refuse page_identity_changed naming the soft-delete exit (sharedOriginExit), a single tombstone may be reused, several tombstones stay ambiguous. Reserved skillpack paths (skills/ at any depth and skillpack.json, src/core/skill-reserved-paths.ts) never enter discovery: the shared skill publisher owns them and managedImportContent refuses them, so a seeded pack cannot block a sync. Nested full discovery filters source scope before slicing paths. Windows separator aliases retain their page identity; ambiguous aliases refuse, while POSIX backslashes/case remain exact. Under source-root mode a stored <scope>/<path> origin (the Git-root form older write-through minted from the slug, recognized because <path> names the page slug) is accepted as <path> at discovery, freeze, preparation and the page-origin query, and an import rewrites it in place; when both readings name existing files the stored origin refuses with detail: ambiguous_source_path. A genuine origin mismatch refuses with detail: sync_origin_mismatch and the filled paths. Deletions must be absent from the pinned Git target or their explicitly selected working tree. Deleting a file that no page records as its origin while its slug's page keeps another origin commits an explicit no-op receipt (unownedDeletion, outcome reason unowned_deleted_path) that preserves that live page or tombstone; freeze and publication re-prove that no page owns the path and that the file is still absent. Existing cursors reuse their accepted manifests, with unknown old deletion provenance refused rather than rewritten. Active Git holds of the source are re-screened when their blob or working bytes changed, the file left, a sources retry-held request names them, the hold predates the current RECOVERY_VERSION, or the code is frontmatter_slug_conflict, file_too_large, rename_held or parser_regression; holds of now-excluded paths are released at the checkpoint. #6278 (B7): retryTaken lists every scheduled path the discovery read (screened as an entry, as a candidate, or no longer eligible); sync-run.ts clears them in the transaction that saves the fresh cursor. A held rename destination (or a held path renamed again) carries the hold's renameFrom when the old page is unchanged, else renameHeld (held as rename_held / rename_source_changed), and a full walk never deletes an origin a hold's rename_from names. Imports whose origin has no page claim their slug together: a live page whose own file is still in the tree keeps the slug, otherwise the file named like the slug (else the first path) wins, and the losers leave the manifest and are reported as slugCollisions (the library path's slug_collision skip) instead of failing the run. A winner whose slug is held by a page with a vanished or deleted origin takes that page over (renameFrom, same slug). A Git-detected rename to an unoccupied slug becomes one import carrying renameFrom in place of a delete plus a create. Origins for one slug that differ only by case or separator spelling refuse, except a case-only respelling whose old file the same sync removes. Code files keep exact per-origin identity. On Windows a path containing : is reported in SyncDiscovery.fileRefusals (code colon_slug_windows_write_through, with its filled gbrain sync --source <id> --no-pull hint) and kept out of the run and its origin checks (#5032). resolveManagedSyncContext refuses skipFailed / includeGitignored on a managed source with managed_sync_flag_refused (managed-sync-flags.ts, detail = the flag, fix = the same gbrain sync argv without it), the one refusal jobs, MCP and the cycle reach; gbrain sync raises it at parse, before the legacy ledger acknowledgement and the cost gate, --all included (#6696). #6865: the per-path eligibility (scope, sync.exclude, sync.include_hidden, strategy, reserved skillpack paths) and the origin a path maps to under the slug mode come from one exported loadSyncEligibility(engine, context, opts?, company?), which the unindexed-file detector shares.

  • src/core/hardened-git.ts (#6712 additions; base entry in persistence-stalls) — assertHardenedGitArgs checks exact options in every wrapper: cat-file with at most --batch (never --filters, --textconv or --batch-command), hash-object --no-filters optionally with --stdin-paths, check-attr/check-ignore with -z/--stdin, and diff-tree only as -r -z --no-renames. hardenedGitStream is a third wrapper: it spawns async, streams stdout to a callback, feeds stdin with backpressure, SIGKILLs past its timeout or byte cap and rejects when the consumer or stdin iterable throws; NulRecordSplitter and hardenedStreamComplete give the completeness rule (exit 0, no signal, output ending at a NUL or empty). Tests: test/hardened-git-stream-6712.test.ts, test/hardened-git-filters.test.ts.

  • src/core/persistence/sync-git-stream.ts — the managed-sync reconcile's Git level reads (#6712), all through hardenedGitStream (allow-listed, filter-free plumbing; the checkout's clean/process filters and textconv never run) and parsed as they stream, so memory is the result maps. readTreeLevel (ls-tree -r -z <commit> -- <scope>: blobs plus symlinks and gitlinks with their mode), readIndexLevel (ls-files -s -z, the index only; a conflicted path keeps its highest stage) and readRenameHints (diff-tree -r -z --no-renames: a deleted and an added regular file paired only when their blob OID is unique to them; hints, never candidates) throw SyncTreeReadIncomplete (code reconcile_read_incomplete) unless Git exited 0, was not signalled and its output ended at a NUL. readBlobs reads contents through one cat-file --batch, leaving out missing, oversized and over-total objects. probeDirtiness is the batched hardenedPathDirty (Dp): per batch of 2,000 paths one hash-object --no-filters --stdin-paths and one check-attr -z --stdin, presence and bytes from readSyncFile; verdicts in order untracked, staged (index and tree differ in OID or mode, a non-zero stage, or one side missing), deleted, unknown (symlink or gitlink, unreadable file, a path with a newline or a leading quote, any Git failure, an OID that disagrees with the bytes read), then clean (raw OID equals the tree with the executable bit matching), clean_eol (only text/eol set and the CRLF-folded bytes hash to the tree), clean_lfs (a valid pointer whose sha256 and size match the bytes) or modified; another filter, working-tree-encoding, an executable-bit-only change or CRLF bytes that fold to the tree with no attribute are unknown, never clean. Tests: test/hardened-git-stream-6712.test.ts (every verdict, completeness, and a forced probe that 1,000 passes of every read never run a configured filter or textconv while git status/git diff on the same checkout do). Working mode: probeDirtiness(..., { working: true }) never reads the index (a path with no file is deleted, a present file outside the tree untracked with its raw OID, every other present file judged from its bytes against the tree through the same clean_eol/clean_lfs domains), so a staged edit, a staged new file, git rm --cached, a staged deletion and a staged file removed from disk probe as the same disk does with a pristine index: the working level is the physical bytes (design v3.2 §2.1). hashWorkingLevel hashes every path of a working round that way with hash-then-restat (a path whose bigint lstat moved across the hash is rehashed, up to three attempts) and returns the stat cache it leaves: WorkingStatCache is plain JSON ({v: 1, root, entries: {path: 'dev:ino:mode:uid:size:mtime_ns:ctime_ns' | 'absent'}}), an entry is written only for a stable stat whose mtime and ctime are older than 2 s before the attempt began (Git's racy rule) and a probe with a level, and at most WORKING_STAT_CACHE_MAX_ENTRIES (100,000) entries are kept in path order. workingChanged(cache, paths) is the idle tick's check: a path the cache does not hold, a moved stat, a failed stat, a zero ctime, a missing cache or a moved root all read as changed, never as unchanged. parseWorkingStatCache validates a serialized copy (junk is null, so everything reads changed); rememberWorkingStatCache/recallWorkingStatCache keep up to 64 caches per process. Working-mode tests: test/sync-working-level-6712.test.ts (probe 41, on the Git reads and on a managed PGLite pass), test/sync-working-stat-cache-6712.test.ts (probe 42); the probe 28 marker test also runs hashWorkingLevel.

  • src/core/persistence/sync-classify.ts — the managed-sync level classifier (#6712 PR 4, design v3.2 §2.3): pure (no I/O), total, ordered, first match over one path's facts (SyncPathState: mode, T[p], the level L, presence, Dp, the page and its import record, the attestation of its revision, hold, deletion marker, baseline blob, open work). Rows in order: held, spelling, untracked, kept (and an absent db_only page), delete, delete_drift, gone, deleted_same, deleted_edited, legacy_same, dirty, matched, adopt, reparse, db_ahead (sub-labels pending/db_only/unproven; keep_db writes only db_only on a clean committed path; an open full obligation skips db_only/unproven), import, legacy_unverified, keep_db, drift (side both or unknown); then the overlay (unsettled with open work is in_flight). syncClassAction is the glossary tag (none, owner, repair); syncPassKind decides idle, hold_only or full from the converged state and every obligation. Tests: test/sync-classify-6712.test.ts (each row, and a cross product against a reference model).

  • src/core/persistence/sync-pass.ts — the read-only shadow of the level-triggered pass (#6712 PR 4a): readShadowLevel reads one managed source's level (T via readTreeLevel, X, working-mode untracked files, Dp for committed candidates only or every path in working mode, pages keyset on pages.id with the import record by a LATERAL primary-key probe and the revision's attestation in the same statement, holds and retry rows, open requests and pending Git effects, deletion markers) and classifies every path with sync-classify.ts; it writes and admits nothing. Postgres reads share one REPEATABLE READ, READ ONLY transaction; PGLite runs bounded 2,000-row statements. A company-brain source returns null (it keeps its frozen manifest). shadowConvergence wraps it in the receipt, dryRunConvergence backs gbrain sync --dry-run --json's convergence (with the read-only screen), statusConvergence backs sync status --detail and doctor, and idleTickProbe times the idle tick's reads for the bench (scripts/bench/sync-convergence.ts). Tests: test/sync-pass-shadow-6712.test.ts.

  • src/core/persistence/sync-convergence.ts — the convergence receipt (#6712 PR 4a, schema convergence/1, always dry_run: true): per-class counts and classes with action tags (in_flight, keep_db_pending beyond 200 per pass, and deletes_withheld when #2828's valve trips are classes too), predicted decisions by side after readOnlySameContentScreen (the dry run's sameContentAtOrigin: a screening request through prepareManagedSyncMutation(..., { unsaved: true }), at most 200 paths; one call's preparations share group-publish.ts's preparationReads memo plus the binding, trust-config and purge-tombstone reads, read their pages through importGroupReads' batch (reread), and answer each page's origin, timeline, take-collision and safe-chunk-fence reads from one read per kind per call (sliceReads), so a call costs a constant, not a statement per page (GBRA-108); equal content is same_content_noops, unscreened is screen_unknown), would_hold, db_ahead by prefix, legacy_unverified, legacy_pageless, deletes with the valve verdict and set hash, up to 20 samples per non-matched class, timings and statement count. --redact-paths replaces paths with sha256 prefixes and drops slugs.

  • src/core/persistence/sync-dry-run-writer.ts — #7167: readDryRunWriterState(engine, sourceId), the writer state a managed dry run reports (SyncResult.writer: open queued/running/recovering requests of the source, the oldest one's age, and gbrain sources writer status as the next step) instead of waiting on the writer. A CLI dry run runs once outside the drain (commands/sync/perform.ts), so the drain's no-progress governor never abandons a long read as a writer stall, and a dry run that is not delegated to a serve says it previews in this process (commands/sync-delegate.ts). Test: test/sync-dry-run-drain-7167.test.ts.

  • src/core/persistence/sync-pass-run.ts — the live level-triggered pass of a managed, non-company source (#6712 PR 4b, design v3.2 §2.2, §3.1–§3.5, §8, §9), run under the source's drain lease. runSyncPass retires an unfinished legacy cursor first (its options seed the episode), pins the pass row (sync.admission, HEAD, the mode; the row is written with the lease token), decides the kind (idle stamps only last_sync_at as up_to_date; hold_only; full), then runs at most PASS_MAX_ROUNDS (4) rounds: read and classify the level (sync-pass.ts), admit C_k = unsettled − S in batches of at most PASS_BATCH_MAX (10,000; deletes, then imports) through sync-run.ts's cursor machinery on an in-memory batch, and add each settled (path, level) to S (never admitted twice in one pass). With nothing unsettled and nothing in flight it stamps through applyPassCheckpoint; four rounds without converging stop resumable / not_converged. Every stop records its outcome, stop reason, settled and remaining on the pass row (a stop mid-batch counts the entries its batch passed); a blocked page refusal is replayed with no new request while nothing that decided it changed. #7149: a requested re-screen (the sync-hold-retry row) is consumed as soon as the pass settles its path (the batch carrying it drained, or the round classified it settled), not only by the stamp, so a pass that stops before its stamp leaves no imported file reported as waiting. Tests: test/sync-pass-live-6712.test.ts, test/unindexed-files-convergence-7149.test.ts, test/sync-pass-completion-6712.test.ts, test/sync-pass-outcomes-6712.test.ts.

  • src/core/persistence/sync-pass-row.ts — the pass row and the rows beside it (#6712 PR 4b, design §3.4), free of heavy imports so doctor, status, the lease, compaction and GC read it without loading the pass. managed-sync-pass (fingerprint <source>:<incarnation>) holds obligations (baseline, episode, cost, the converged state, mismatch and not-converged streaks, page faults, a blocked request to replay) and telemetry (the newest pass's kind, round, outcome, stop reason, candidates, settled, remaining, counts, timings). writePassRow writes it at pin under assertDrainLease and afterwards only WHERE lease_token = $token; an onlyOpen stop never inserts. Readers use the database clock (passReadClock). Beside it: sync-origin-deleted (deletion markers), sync-deletes-withheld (the mass-delete trip) and sync-pass-cost (one reservation per group); SYNC_PASS_ROW_OPS lists the ops the checkpoint GC keeps for a live incarnation. passHealth is the one health rule (blocked, not_converged, settle_mismatch, open_stalled, nothing_pending); SETTLE_MISMATCH_STREAK and NOT_CONVERGED_REPORT_STREAK are 3.

  • src/core/persistence/sync-pass-readers.ts — the pass row as the former cursor readers see it (#6712 PR 4b, design §3.7): doctor's movement, git-holds and terminal-failure checks, the drain backlog (readManagedSyncBacklog), the blocked-run reader and sources status read a non-company source's pass row through readPassReadings (passHealth plus the checkout HEAD from a hardened rev-parse on this host; no checkout means head: null and the recorded converged target is trusted). passResumeArgs is the plain sync that continues the pass, with the open episode's inherited options; passStopCode and passStuckSince name a stuck pass. Company sources and unretired legacy cursors keep their cursor arm in each reader. Tests: test/sync-pass-readers-6712.test.ts, test/sync-pass-reader-gaps-6712.test.ts.

  • src/core/persistence/sync-pass-apply.ts — what a live pass round does besides admitting one-sided imports and deletes (#6712 PR 4b, design v3.2 §2.5–§2.7, §3.1, §5): holds with side and state for the two-sided and deleted rows (file_drift with side, tombstone_edited, purged_differs, file_gone), the settle_mismatch hold after three passes at one level, arm-1 adoption of a record without a revision on fileSame, the bounded legacy sweep (500 per round) that records equal legacy pages on the first full round (GBRA-108: in slices of LEGACY_SWEEP_SLICE (100) whose records commit before the next slice, each followed by a pass-row save and a managed_sync.legacy_swept progress event the drain's in-pass governor counts, so a pass stopped mid-sweep keeps its slices and the next pass sweeps only the rest; seam sync:legacy_slice; tests test/sync-legacy-sweep-gbra108.test.ts and its Postgres twin), the mass-delete valve (one sync-deletes-withheld record; imports and the stamp proceed), keep_db admission (200 per pass), deletion-marker retirement in full rounds, and the remote ending (reconcile_host_required: one-sided work commits, drift stays unsettled with no hold). Entry points: applyPassRound, finishPassApply, summarizeRound. Tests: test/sync-pass-completion-6712.test.ts.

  • src/core/persistence/sync-pass-episode.ts — pass episodes and cost (#6712 PR 4b, design §6, §7): episodeClosure closes an episode by inclusion or at the configured selection (a narrower episode never stamps chunker_version; a widened one releases its extra paths), passCostDecision defers paid embedding when the envelope is unknown or spent, and reservePassCost writes one sync-pass-cost row per admitted group (fingerprint <source>:<incarnation>:<episode_or_pass_id>:<group_id>, insert-once) inside the group's admission transaction, so a kill keeps the reservation and a replay adds nothing. Tests: test/sync-pass-completion-6712.test.ts.

  • src/core/persistence/sync-pass-status.ts — the live convergence block of gbrain sync status (#6712 PR 4b, design §9, dry_run: false): built from the pass row (one primary-key read), the withheld-delete record and syncAdmissionStatus, plus passStatusState, which keeps a source off synced while its newest pass is open or ended unconverged (reasons pass_unfinished, pass_terminated (GST-2869: a SIGTERM or SIGHUP stopped the pass and it recorded terminated), not_converged, settle_mismatch, deletes_withheld, selection_scoped, admission_paused, and writeback_failed: a writeback the stamp recorded in converged.writeback whose Git effect failed or parked, next step gbrain sources writer retry-effects --dry-run). Tests: test/sync-pass-completion-6712.test.ts, test/sync-pass-writeback-fold-6712.test.ts.

  • src/core/persistence/sync-markers.ts — the deletion marker and the withheld mass-delete record of a managed Git source (#6712 PR 4b). writeOriginDeletedMarker runs in the transaction of every page-row deletion of a managed source (page-purge.ts, the purge-mirror replay; test/page-row-deleters-guard-6712.test.ts refuses any other deleter) and writes sync-origin-deleted (<source>:<incarnation>:<origin>, value {kind:'deleted', blob_oids, page_id, slug} from the import record) only when it can matter: the origin is in the last_commit tree (hardened ls-tree) or a file backs it on disk, no other live page records it, and the source is bound and not a company brain; an unreadable checkout counts as present. retireOriginDeletedMarker is compare-and-delete on the value read. writeDeletesWithheld / readDeletesWithheld / clearDeletesWithheld keep one sync-deletes-withheld record per incarnation ({target, count, reconcilable, ratio, set_hash, samples≤20}, deleteSetHash: sha256 over the sorted NUL-joined set). Seam: purge:marker_written.

  • src/commands/doctor/checks/managed-sync-convergence.ts — doctor managed_sync_convergence (#6712 PR 4a, deep tier): the convergence shadow's counts for each managed source this host owns; always ok (informational), read-only. Tests: test/doctor-managed-sync-convergence.test.ts.

  • src/core/persistence/file-claims.ts — the recorded-origin census shared by reconcile and the shared-origin delete (#6517): fileClaimCandidatesQuery (the paged same-name query and its binds, built per platform so every bound placeholder is referenced (#6659: an unreferenced bind failed every Windows delete_page with 42P18), 100 rows per batch below the source's highest page id, served by the v219 name indexes; source_path in any spelling or a file: URI; tombstones excluded) and findLiveFileClaimants, realpath deciding each candidate. In page-prepare.ts, a delete_page whose file another live page records (prepareFileTarget with sharedOrigin, before the byte comparison) owns no file: a soft delete publishes database-only with receipt write_through.skipped: 'shared_origin' and a warning ("hidden … does not erase", the gbrain repair file-drift --source <id> --slug <survivor> --prefer file that imports the kept file into the survivor; #6712 PR 1: sync holds a survivor that differs from the file file_drift, and that hold's fix leads with the same command), validate re-runs the census under the publication guards (validateSharedOrigin: the file moved or removed, or a different claimant set, refuses source_changed and never removes the file), and the surviving slug is named only when slugDisclosable (authority.ts: the local owner, or a remote writer whose prefix grant, delegated namespace and visibility cover it). An owner purge of a shared-origin page refuses and names the soft delete (the retention purge for a tombstone). #7311: the retention purge of a shared-origin tombstone is database-only like an origin_twin page's (sharedRetention: no file target, applied with source_path/source_uri forgotten, so no deletion marker names the survivor's file); validate re-runs the census, and a changed one refuses revision_conflict (sharedTombstoneChanged, a purge deferral), so the next run takes the normal path. Tests: test/purge-shared-origin-tombstone-7311.test.ts (Postgres: test/e2e/purge-shared-origin-tombstone-7311-postgres.test.ts), test/page-prepare-shared-origin-6517.test.ts, test/sync-origin-live-wins-6517.test.ts, test/e2e/managed-sync-shared-origin-6517.test.ts.

  • src/core/persistence/drift-conflicts.ts — the source_changed / file_database_drift conflict pile (#6643). auditDriftConflicts groups conflict receipts by slug over a bounded window of request sequences (default 100,000, at most 1,000,000), paginated by slug with a complete flag; it backs gbrain sources reconcile <source> --audit --conflicts (reconcile-audit.ts) and MCP list_write_conflicts (ops/persistence.ts). The window ends at the source's own newest request (current incarnation, the (source_incarnation, sequence) index; a cursor never reads past it), and a source the caller may not read returns before anything is computed; the MCP op refuses an out-of-grant source_id through resolveRequestedScope. Remote callers get database-derived fields only, with source grant, slug fence and visibility filtered in the aggregating SQL; liveFileDrift (the prepareFileTarget comparison; reason canonical_file_missing for a live page whose canonical file is gone, file_missing for any other source_changed) and driftClass (the reconcile-additive.ts verdict) run only for a trusted local caller on the canonical owner, and such a row carries the compared file path. submitMaintenance (prepared-maintenance.ts, maintenanceDriftRefusal) refuses a drifted page before admission, and synthesize_concepts skips a drifted concept before spend, recording it in dream.concepts.drift_skips (per-entry atomic updates, released when the sides agree). Tests: test/maintenance-file-drift-6643.test.ts (PGLite; Postgres via test/e2e/maintenance-file-drift-6643-postgres.test.ts).

  • src/core/repair/file-drift.ts — gbrain repair file-drift (#6643): explicit-only, preview-bound resolution of drifted pages through reconcileCanonical with one side preferred (preferSideDecisions) inside reconcile's protections; driftExceptions lists where the result differs from the preferred side. The preview writes a private artifact under configDir()/repair-previews/file-drift/<hash>.json and saves the approved set; apply runs runReconcileApply per page under request ids derived from the hash and slug, so an interrupted apply resumes. --all-drifted refuses mixed drift classes unless --class keeps one. Repeatable --only/--skip over the source-relative canonical file path (src/core/repair/path-glob.ts matchesRepairPath: a value without * is an exact path, as every kind's --only; with * it is a glob, file-drift only: * within a segment, ** across) narrow the selection before the class check, the 1,000-page bound and any preview work (not_selected residual); they join the selection digest only when given (so earlier hashes are unchanged) and appear in every printed preview and apply command. prepareDriftPage builds one page's ready reconcile preview for a preferred side; the plan and the keep_db policy share it. --keep is refused at parse in src/commands/repair.ts with the same command rewritten to --prefer database. reconcile-prepare.ts keeps the file bytes when they already parse to the result digest. Doctor maintenance_write_drift (src/commands/doctor/checks/maintenance-drift.ts) counts what remains and, on the owner host, echoes each declared storage.keep_db policy as keep_db_policy (prefixes, matched drifted pages among those checked live, unchecked, receipt cost from keepDbReceiptCost). #6712 wave: a selected page whose liveFileDrift reason is canonical_file_missing goes through fileGonePage (ghostPageNow for the path, revision and owner; canonicalDeletionState for the route): still committed at HEAD is listed deletion_uncommitted, gone from HEAD becomes a prepareDriftPage(..., { fileGone: true }) recreate (file_gone, details action: 'recreate_file'; a warning when gitDurabilityPolicy is not durable, since an uncommitted recreated file loses to the committed deletion on the next sync) or a SoftDeletePage applied through retireGhost (exported from repair/ghost-pages.ts, under the file-drift request id) with the ghost-pages mass valve; --all-drifted never selects missing files. --held [--side both|unknown|deleted [--state tombstone_edited|purged_differs|file_gone]] (#6712 PR 4b) selects the source's held file_drift pages of one Decision (selectHeld, side from fileDriftSide): several sides or states without --side refuse file_drift_mixed_selection, a deleted side without --state refuses file_drift_state_required, and holds with no side (sides: database) list legacy_side. Both/unknown and file_gone pages take the paths above; tombstone_edited and purged_differs go through deletedPage over readDeletedDriftTarget: --prefer database is a RemoveFilePage applied as the managed_maintenance_file_drift_remove intent (prepareDriftFileRemoval, dispatched from prepared-maintenance.ts: a page file target with no bytes bound to the previewed hash, the tombstone revision or marker value re-checked under the publication guard, the hold cleared in the publishing transaction, the page row untouched), --prefer file an ImportFilePage applied through submitManagedFileRepair with the file's own bytes (restores the tombstone, or creates the page; the deletion marker stays for sync to retire). Each details.pages entry carries verb (fileDriftActionVerb), printed by render. The Decision is the hold's meta.side / meta.state (sync-holds.ts: fileDriftSide reads older holds' sides; gitHoldItem lists both; a deleted hold's fix previews heldDriftPreviewArgv for its path and names each option's verb). Test: test/repair-file-drift-held-6712.test.ts. GBRA-133: an agreeing hold is a ReleasePage (release_hold; apply re-checks the pins, then requestGitHoldRetry for its path); a page with no file origin (recordsNoFileOrigin) adopts slugPathFile (the spelling sync imports); file wins writes fileWinsContent (file bytes plus appended protected keys and timeline rows) or refuses file_wins_rewrite. Test: test/sync-holds-wave-gbra133.test.ts.

  • src/core/ghost-pages.ts — #6696 B5, the one ghost-page classifier: a ghost is a live page for which liveFileDrift returns reason canonical_file_missing on the source's canonical owner host (prepareFileTarget tags that refusal detail: 'canonical_file_missing'). scanGhostSource reads a source's live pages in id order (at most GHOST_SCAN_LIMIT), resolves each recorded canonical path exactly as prepareFileTarget does and stats it, skips publishesDatabaseOnly and legacy slugs, and runs the full check on at most candidateLimit candidates; it returns the ghosts, inspected, file_backed (the mass-delete valve's population), truncated and the owner it ran under (host, worktree, owner epoch, incarnation). Off the owner host a source is not_applicable (not_owner_host, or not_applicable with no binding); a missing root is unknown (storage_unavailable), a stat error, invalid gbrain.yml or inconclusive check unknown (ambiguous_storage). ghostPageNow re-checks one page (the repair's recheck); readGhostPages(engine, { sourceIds?, sampleLimit? }) is the counts-and-samples summary for doctor and the read-scope health op. Tests: test/ghost-pages-6696.test.ts.

  • src/core/repair/ghost-pages.ts — gbrain repair ghost-pages --source <id> (#6696 B5): explicit-only, preview-bound, destructive consent (GHOST_CONSENT_TEXT: the 72 h purge fuse, the per-slug gbrain restore <slug> --force undo, and the keep path of restoring the file and syncing). The preview binds the ghost set to the owner and each page's revision and path; the apply refuses not_owner_host, ghost_storage_unknown, preview_changed on an owner change, and ghost_mass_delete_refused (massGhosts: the sync valve, MASS_RECONCILE_RATIO over more than MASS_RECONCILE_MIN_PAGES file-backed pages, unless massReconcileAllowed()). Each page re-checks with ghostPageNow, then a managed brain submits one managed_maintenance_retire_ghost_page request (prepareGhostPageRetirement, dispatched from prepared-maintenance.ts: re-check, delete_page with allowMissingFile, refusal unless the prepared file target, a code or image ghost's recorded file (#7967), is the approved path with no bytes, so publication refuses a file that appeared later); an unmanaged brain soft-deletes in one transaction after the same check. Outcomes soft_deleted, file_restored (asks for a new preview), changed_since_preview. Doctor ghost_pages (src/commands/doctor/checks/ghost-pages.ts, BRAIN, after fence_integrity) reports the count, samples and coverage with the preview as its fix, ok + info off the owner host, unknown on an unreadable checkout; gbrain pages ghosts (src/commands/pages-ghosts.ts) lists them read-only.

  • src/core/repair/legacy-twins.ts — gbrain repair legacy-twins --source <id> (#6885): explicit-only, preview-bound, destructive consent (LEGACY_TWINS_CONSENT_TEXT). scanLegacyTwins reads a source's live pages with no recorded origin and no database_only_reason in id batches (at most LEGACY_TWINS_SCAN_LIMIT), keeps those whose slug slugifyPath folds differently, and pairs each with the live page at the folded slug that records a file (at most LEGACY_TWINS_LIMIT pairs and decisions). pairVerdict lists a pair as a decision (never merged) for differing content_hash, several legacy candidates, a twin file liveFileDrift does not call agrees, a file at the twin's own slug path, twin withdrawals, a legacy file: URI or a twin slug outside the op grammar. The preview binds pairs to the owner (host, worktree, owner epoch, incarnation) and both pages' ids, slugs and revisions; the apply refuses not_owner_host, legacy_twins_storage_unknown, preview_changed and legacy_twin_mass_merge_refused (massTwins, the sync valve). Each pair re-checks with pairNow, then a managed brain submits one managed_maintenance_merge_legacy_twin request on the twin (prepareLegacyTwinMerge, dispatched from prepared-maintenance.ts: no file target, databaseOnlyReason: 'shared_origin', the legacy key in additionalPageKeys, pairLocked under the publication locks); an unmanaged brain merges in maintenanceTransaction under both page locks. applyTwinMerge records the twin's source_path on the legacy page, clears the twin's origin (so its tombstone's retention purge is database-only, never a shared_origin refusal), moves links (deduplicated; pair links stay), timeline rows, raw data, attachments, page aliases and facts about the twin, records the twin slug as a slug_aliases row, versions and soft-deletes the twin, and moves the twin's sync-import-provenance record to the legacy page at its post-write revision. Outcomes merged, changed_since_preview. Tests: test/repair-legacy-twins-6885.test.ts (Postgres: test/e2e/repair-legacy-twins-6885-postgres.test.ts).

  • src/core/persistence/unindexed-files.ts — #6865 the unindexed-file detector: findUnindexedFiles(engine, sourceId, opts) streams git ls-tree -r -l -z of the source's last synced commit, filters it through discovery's own loadSyncEligibility, and in batches (one pages.source_path = ANY read on pages_source_path_idx, one hold read by fingerprint) keeps files with no live page recording their origin (source-path space, with the legacy Git-root spelling in source-root mode), no hold and no scheduled re-screen (readGitHoldRetryPaths; those count as scheduled); a committed symlink whose target does not exist (danglingLink in sync-entry-fault.ts) is skipped by sync on every pass, so it is never unindexed; a file whose path slug belongs to a live page with another or no origin is still unindexed and counted slug_taken. Found files are screened read-only with screenImportContent (at most 2,000 per pass, the rest unscreened). Folder-scaffolding names sync skips on purpose (isSyncMetafile) that would otherwise be eligible (checked against a probe name in the same directory plus sync.exclude and the reserved skill paths) and carry a frontmatter type: or title: are counted apart as metafile_skipped (only under sync.metafile_pages off: under the default typed the eligibility predicate admits a nested one, so it is an ordinary unindexed file; each tree batch primes its metafile heads) with samples, and never scheduled. A time or count budget stops it with complete: false and a cursor (the last Git path, compared in byte order, which is Git's recursive tree order). refreshUnindexedFiles continues an incomplete stored result of the same incarnation and eligibility also after the source's commit moved (#7149): it first re-examines the paths before the cursor that changed between the two commits (git diff-tree; more than UNINDEXED_REVISIT_CAP, or an unreadable old commit, starts over), then resumes after the cursor. It schedules the found paths (requestGitHoldRetry, a scheduling write only) and stores one op_checkpoints row per source (op unindexed-files, fingerprint the source id; the 7-day checkpoint purge applies). unindexedScanBudgetMs sizes one pass's budget: 60 s per started 100k live pages, at most 5 min. judgeUnindexedFiles is doctor's read without scanning: a scheduled path with a page or a hold is settled even while the retry row still names it (#7149); of the rest, those in the retry row wait for a sync and the others are still unindexed. Tests: test/unindexed-files.test.ts, test/unindexed-files-convergence-7149.test.ts.

  • src/commands/doctor/checks/unindexed-files.ts — #6865 doctor unindexed_files (BRAIN, after missing_recorded_files): reads judgeUnindexedFiles for each bound managed Git source; ok when every result is complete, recent and nothing is missing; warn with counts by code, samples and age when files are unindexed (fix gbrain sources retry-held <id> --unindexed, then the follow-up sync from gitFollowUpSync, verify gbrain doctor --only unindexed_files --json) or scheduled and waiting (fix the sync); info unknown when a result is missing, older than 7 days or incomplete with nothing found, naming the maintenance phase and the command; info not_applicable on a classic brain. metafile_skipped files are named in the message and details and never make it warn; alone they are info degraded with a user fix (rename the file, then the sync). Test: test/unindexed-files.test.ts.

  • src/commands/doctor/checks/missing-recorded-files.ts — #6609 doctor missing_recorded_files (BRAIN, after ghost_pages): the classic-brain counterpart of ghost_pages. Read-only; per source with a checkout on this host and managed persistence off it runs scanMissingRecordedFiles (src/core/persistence/detached-pages.ts) and warns with counts, samples and an ask_user fix (put the file back and sync, or gbrain delete then gbrain restore <slug> --source-id <id> --detach) for live pages whose recorded file a gbrain sync --full would not find; ok + not_applicable when no source qualifies. Test: test/restore-detach-6609.test.ts.

  • src/core/persistence/overwritten-edits.ts — #6712 follow-up: scanOverwrittenEdits finds live pages whose database-only revision a managed-sync import replaced with different content and no hold, from durable rows only (it survives receipt compaction): page_versions.write_request_id / archived_write_request_id, the writer's committed receipt (outcome.persistence.mode = 'database', not an import, no git effect for that revision, not a read-only mirror write), the archiving request recognised as a managed-sync import by intent kind or, once compacted, by operation submit_job + outcome.imported_file without connector_database, and contentCanonical digests (reconcileCanonical without the write gate's database-only markers, #9511; the import's own revision differs; no later revision holds the edit again). high or unknown (no_persistence_outcome, import_content_unreadable, segmented); the newest open overwrite per page; at most OVERWRITE_SCAN_LIMIT candidate versions per source. Revisions with no recorded writer are not reported.

  • src/commands/doctor/checks/overwritten-edits.ts — doctor sync_overwritten_db_edits (BRAIN, after missing_recorded_files): per source count and first slugs from scanOverwrittenEdits; warn only for high findings, with the read-only gbrain repair overwritten-edits --source <id> preview as an ask_user fix; unknown findings are counted in details and never warn.

  • src/core/repair/overwritten-edits.ts — gbrain repair overwritten-edits, explicit-only and preview-bound (--slug narrows): the preview lists each high page with a diff of the live page against the archived edit and saves the set; --apply --expect <hash> rechecks the page revision and version digest, then submits revert_version with expected_revision and databaseOnly: 'overwrite_restore' (page-mutations.ts: no worktree, receipt write_through.skipped: overwrite_restore), so the committed file is never rewritten; when this host owns the checkout and the committed HEAD blob differs from the restored page (fileMatchesSnapshot), it writes a file_drift hold (fileDriftHold + writeGitHold, page_revision = the restored revision). On another host, or for a file over the read bound, the outcome is restored_file_unheld with next naming the owner host's gbrain repair file-drift --prefer database; an apply whose restore request already committed replays it and writes the hold. Outcomes restored, restored_file_held, restored_file_unheld, changed_since_preview. Test: test/overwritten-edits-6712.test.ts (PGLite and Postgres).

  • src/core/persistence/detached-pages.ts — #6609 (D5) restore of a page whose recorded canonical file is gone. assertRestoreOrigin (called by submitPageMutation for restore_page, publishesFile = write-through on and a file target) refuses a restore that writes no file of a soft-deleted page whose source_path file inSyncableTree does not find (tracked or untracked-not-ignored) with source_changed / detail canonical_file_absent (not retryable), docs storage-tiering.md#restoring-a-page-whose-file-is-gone and an ask_user fix (gbrain restore <slug> --source-id <id> --detach, MCP restore_page detach: true); detach: true with nothing to detach refuses invalid_params; on a declared db_only page it is database-only even with write-through (#7324). detachRestoredPage runs in the restore publication (from classifyUnboundPage) and clears source_path, stamping pages.database_only_reason='detached'; the page upsert (engine-sql/pages.ts) clears that stamp when sync writes a source_path again. scanMissingRecordedFiles (at most MISSING_FILES_SCAN_LIMIT live pages per source, collectSyncableFiles + scannerSlugRootMode path resolution) feeds doctor missing_recorded_files. Test: test/restore-detach-6609.test.ts.

  • src/core/repair/keep-db-policy.ts — the opt-in storage.keep_db policy (#6696 C7), since #6712 PR 4b an admission of the managed sync pass (design v3.2 §4, d1b option C); the consumer's keep_db worker and its 10-minute timer are gone. readKeepDbPolicy reads a source's keep_db prefixes from the gbrain.yml of its canonical checkout, only when the given host owns the active binding; doctor maintenance_write_drift reads it and keepDbReceiptCost. freezeKeepDbReconcile builds the --prefer database artifact (prepareDriftPage) for a path the pass classified keep_db (row 18) or db_ahead/db_only under keep_db (row 15), committed mode with Dp = clean, under this host's policy on a source that is not mirror-read-only, and refuses ({ refused }) unless the artifact's own read matches the frozen page id, revision, file bytes (sha256 = preconditions.raw_file_hash) and path. admitKeepDbReconcile (trusted local pass only, remote: false) admits it through admitReconcileArtifact (persistence/reconcile.ts, the core runReconcileApply shares) under this installation's own CLI writer registration as a background producer, without waiting for publication; inside the admission transaction it re-reads sync.admission (admission_paused when not normal) and runs the pass's inTx fence, whose error rolls back and is rethrown as is. The request id derives from the page revision and frozen bytes (one drift, one request), skipping an id whose request sync.admission cancelled or that holds a retained backup but no request; the intent carries keepDb: { passId }, and its publication re-reads sync.admission and completes cancelled/admission_paused with nothing written (reconcile-prepare.ts, coordinator.ts failureState). releaseMatchedDriftSkips releases the concept drift skips of pages the pass classified matched. Tests: test/keep-db-pass-admission.test.ts (probes 26, 27, 47, 51; Postgres via test/e2e/keep-db-pass-admission-postgres.test.ts), test/keep-db-consumer-retired.test.ts, test/file-drift-bulk-reconcile.test.ts (PGLite; Postgres via test/e2e/file-drift-bulk-reconcile-postgres.test.ts).

  • src/core/persistence/sync-origin-evidence.ts — #7130: whether a missing file is deletion evidence. readOriginEvidence(gitRoot, tips, paths) answers committed / never_committed / ignored / unknown per Git-root-relative path from one cached history walk per tip (historyIndex: git log --full-history --name-status, extended past a cached ancestor; 600 s) and git check-ignore --no-index -z --stdin per 500-path batch; a failed read is unknown, which the classifier holds. readDeletionProvenance reads the same walk. gitIgnoresUntracked is the write-through test (page-prepare.ts keeps a managed write into an ignored path database-only; classic sync/full.ts keeps a stale page whose ignored file is still on disk). Read by sync-pass.ts (reclassifyByOrigin, delete and delete_drift paths only), sync-discovery.ts (tree-absent deletes) and the doctor scanner src/core/uncommitted-deletions.ts. Test: test/sync-uncommitted-origin-7130.test.ts.

  • src/core/persistence/sync-delete-tombstones.ts — #7130: the record a managed_sync_delete apply writes in its own transaction (op sync-delete-tombstone, fingerprint = page id, deleted_at equal to the page row's), the syncDeleteOrigin SQL predicate (record, or the uncompacted committed receipt) and readUnreviewedSyncTombstones (sync tombstones with no live twin by content_hash). purge-deleted.ts holds that set when automatic (cycle purge phase, purge job; blocked code sync_delete_unreviewed) and only counts it for the consented manual purge; purgeStaleCheckpoints keeps a record while its tombstone exists. Test: test/purge-sync-tombstone-hold-7130.test.ts.

  • src/core/uncommitted-deletions.ts — #7130: the one bounded scanner of tombstones whose recorded file Git never held (ignored, or never committed and absent), sync deletions first; read by doctor uncommitted_sync_deletions (src/commands/doctor/checks/uncommitted-sync-deletions.ts) and by the repair.

  • src/core/repair/uncommitted-deletions.ts — gbrain repair uncommitted-deletions --source <id>: explicit-only, preview-bound (--apply --expect <hash> --yes) and consented; restores each page through a database-only restore_page with detach (databaseOnly: 'detached'). Never runs on upgrade, --all or maintenance. Tests: test/repair-uncommitted-deletions-7130.test.ts, test/e2e/repair-uncommitted-deletions-7130-postgres.test.ts.