Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript
51.7 KB
Raw Blame

Key files: Files And Sync (2/2)

Subsystem index. Read only the entries relevant to your change. Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.

  • src/core/persistence/visibility-request.ts — the private-request guard. readPrivateRequest(content, parse) reads whether content asks for visibility: private: a frontmatter line in any case, or the parse reading a visibility key of any case as private (block scalars, lists, flow mappings and merge keys count). Page writes (put_page, edit_page, capture; privateRequestGuarded) refuse a request the stored frontmatter would not keep as exactly visibility: private (assertPrivateRequestKept, visibility_not_applied); an unmanaged ingest_capture job takes the same refusal (privateRequestRefusal) after importFromContent's screen holds the content (holdNoncanonicalPrivate), and dead-letters without a retry (#7880). File ingestion holds the same case as visibility_noncanonical (noncanonicalPrivateHold): classic sync and legacy gbrain import through importFromFile and screenLegacyFile, managed sync and import through screenImportContent's holdNoncanonicalPrivate, and through importFromContent's opt-in of the same name: ingest_capture, company-brain imports (importCompanyBrainFile) and the GitHub and Google connectors' database-only imports (#7880), gbrain repair url-clone-fences (a held HEAD previews under its code and applies as held), and the unmanaged brainstorm --save and sources reconcile, which turn the hold into visibility_not_applied (#7897), streamed large files unless they are a page write, with or without a Git checkout. Doctor git_held_files counts those holds and the live stored pages noncanonicalPrivateRequest('', frontmatter) reads as asking for private (details.visibility_noncanonical); nothing rewrites them. Derived writers never refuse. Tests: test/put-visibility-private-7841.test.ts, test/visibility-noncanonical-hold-7848.test.ts, test/ingest-capture-private-hold-7880.test.ts, test/company-brain-private-hold-7880.test.ts, test/{url-clone-fences,brainstorm,reconcile}-private-hold-7897.test.ts (Postgres: the matching test/e2e/*-postgres.test.ts wrappers). test/import-private-hold-callers-7897.test.ts lists every importFromContent / screenImportContent call that does not opt in, with why it is held or derived, and fails on a new one.

  • src/core/sync-concurrency.ts — single source of truth for the parallel-sync policy. Exports autoConcurrency(engine, fileCount, override?) (PGLite always serial; explicit override clamped to >=1; auto path returns DEFAULT_PARALLEL_WORKERS=4 when fileCount > AUTO_CONCURRENCY_FILE_THRESHOLD=100), shouldRunParallel(workers, fileCount, explicit) (explicit --workers bypasses the >50-file floor), and parseWorkers(s) (rejects '0', '-3', 'foo', '1.5', trailing chars). Used by performSync, performFullSync, runImport, and the Minion sync handler so the sites can't drift. DEFAULT_PARALLEL_SOURCES = 4 is a SEPARATE constant for the per-source fan-out under gbrain sync --all — kept distinct from DEFAULT_PARALLEL_WORKERS because total live Postgres connections per wave ≈ DEFAULT_PARALLEL_SOURCES × DEFAULT_PARALLEL_WORKERS × 2 (per-file pool) = 32 at both defaults (each per-file worker opens its own PostgresEngine with poolSize = min(2, resolvePoolSize(2))); sync.ts warns when parallel × workers × 2 > 16. resolveWorkersWithClamp(engine, override, commandName, fileCount) wraps autoConcurrency with a per-command stderr clamp warning on PGLite (per-(command, requested) dedup via module-scoped warned-once set with _resetWorkersClampWarningsForTest() seam) and is the canonical surface for every bulk-command --workers N flag (extract-conversation-facts, extract, edges-backfill, reindex-multimodal, reindex, reindex-code); embed.ts deliberately bypasses it and keeps GBRAIN_EMBED_CONCURRENCY || 20. resolveMaxConnections() (reads GBRAIN_MAX_CONNECTIONS, undefined when unset) + clampWorkersForConnectionBudget(workers, perWorkerPool, maxConnections, parentPool) back the opt-in single-sync connection-footprint clamp so a big sync stays under a low pooler cap (parent_pool + workers×perWorkerPool ≤ budget); gbrain doctor's pool_budget check (computePoolBudgetCheck / checkPoolBudget in src/commands/doctor/checks/consolidation-cycle.ts, re-exported by src/commands/doctor.ts) warns when the budget leaves no room for a worker, pointing at GBRAIN_POOL_SIZE=2. Pinned by test/pglite-workers-clamp.test.ts.

  • src/core/sync-embed-backfill.ts — Sync command’s engine-aware embedding-delivery seam. It derives separate worker-backed deferral and multi-source fan-out eligibility, keeps automatic-submission policy distinct from capability, invokes the shared cost gate for --all and single-source runs, propagates intrinsic large-sync deferral into final delivery outcomes, resolves backfill results through the centralized submitter, formats one truthful human status, and builds the single-source JSON envelope. syncProducedEmbeddableContent is the one content gate every automatic submit site (sync --all, single-source autodefer, the jobs sync handler) applies on top of status: a sweep-only or delete-only run reports synced but wrote no chunks, and minting a backfill for it would only arm the per-source cooldown against the next real import (the handler reports embed_skip_reason: 'no_new_content'). Keeping these pieces together prevents cost-gate, queue, human, and machine surfaces from drifting while the size-ratcheted src/commands/sync.ts façade stays at its committed ceiling.

  • src/core/sync-failure-ledger.ts — the bounded auto-skip sync failure ledger. A LEAF module (imports only fs/path/crypto/config) so sync.ts can re-export it without a circular dependency. State lives in ~/.gbrain/sync-failures.jsonl, one JSON object per line, keyed by (source_id, path) with a per-key attempts count and a 3-state machine: open (fresh/blocking) → auto_skipped (chronic, still doctor-visible) or acknowledged (human resolved via gbrain sync --skip-failed from either unresolved state). classifyErrorCode(errorMsg) regex classifier with 23 named codes (RENAME_RECONCILE, SLUG_MISMATCH, DB_DUPLICATE_KEY, STATEMENT_TIMEOUT, YAML_PARSE, YAML_DUPLICATE_KEY, MISSING_OPEN, MISSING_CLOSE, EMPTY_FRONTMATTER, NULL_BYTES, NESTED_QUOTES, INVALID_UTF8, FILE_TOO_LARGE, SYMLINK_NOT_ALLOWED, TAKES_TABLE_MALFORMED, TAKES_HOLDER_INVALID, EMBEDDING_NO_CREDS, EMBEDDING_NO_TOUCHPOINT, EMBEDDING_TIMEOUT, EMBEDDING_RATE_LIMIT, EMBEDDING_QUOTA, EMBEDDING_OVERSIZE, PAGE_JUNK_PATTERN) plus UNKNOWN (the default fallthrough); summarizeFailuresByCode(failures) returns sorted [{code, count}]; MISSING_OPEN/EMPTY_FRONTMATTER regexes match the markdown.ts validator strings; MISSING_CLOSE's regex is stale against current markdown.ts output — it matches the no-heading-hint case (No closing --- delimiter found) but not the heading-hint case (No closing --- before heading at line N), which falls through to UNKNOWN. FILE_TOO_LARGE covers import-file.ts:395, 1236, 1436 (markdown/text, plain-file, and code-file import paths), SYMLINK_NOT_ALLOWED covers :1231, 2038 (file and image import paths). EMBEDDING_INFRA_CODES is the subset (EMBEDDING_TIMEOUT/EMBEDDING_RATE_LIMIT/EMBEDDING_QUOTA) that means the embedding PROVIDER is unhealthy rather than the file being poison — isEmbeddingInfraCode(code) is consulted inside decideGateAction's chronic-eligibility loop so these three are never counted toward auto-skip (treated as fresh, forcing block instead of advance_then_autoskip); an explicit --skip-failed still advances past them like any other failure, since that check runs before the loop. All mutations run under withLedgerLock (cross-process file lock) with an atomic rename write. The auto-skip threshold resolves via resolveAutoSkipThreshold() from GBRAIN_SYNC_AUTOSKIP_AFTER (default DEFAULT_AUTOSKIP_AFTER = 3; 0 disables the valve = pure fail-closed). Two pure decision functions are the unit-test surface: decideGateAction({fileFailures, sentinels, attemptsByPath, threshold, skipFailed}) returns hard_block | block | advance | advance_then_autoskip (sentinels like <head> ALWAYS hard-block, even with --skip-failed, so a history rewrite can't auto-skip; any FRESH failure with attempts < threshold blocks fail-closed; only when ALL failures are chronic does it advance_then_autoskip), and decideSyncFailureSeverity({entries, nowMs, failHours}) returns the sync_failures doctor status (ok when zero unresolved; fail when ≥10 OPEN-blocking or the oldest OPEN failure's ts (last attempt, NOT first_seen) is older than failHours — a failure retried inside that window keeps refreshing ts and never trips this leg even if first_seen is much older; otherwise warn — auto_skipped-only rows stay WARN-visible regardless of count because the bookmark already advanced). applySyncFailureGate(input) is the one orchestrator BOTH sync paths (incremental + full/runImport) call: it records/clears ledger rows, runs decideGateAction, then executes effects in the crash-safe order (advance the bookmark FIRST via the injected advance() callback, THEN auto-skip the chronic set) so a crash can never mark a file skipped while leaving sync wedged. isSkippablePath rejects <…> sentinels. Pinned by test/sync-failure-ledger.serial.test.ts + test/sync-failures.test.ts. GBRA-130 A-18: the module imports BILLING_MESSAGE_RE/RATE_MESSAGE_RE from the import-free ai/errors.ts (still a leaf). classifyErrorCode(msg, path?) never reads path text as a provider error: errno-led messages map to PERMISSION_DENIED (EACCES/EPERM) or FILE_UNREADABLE (ENOENT and other file errnos), and the infra regexes run on the message with the embed envelope, the path and its tokens stripped, so billing/q3.md or http-429.md no longer read as EMBEDDING_QUOTA/EMBEDDING_RATE_LIMIT. syncFailureCode(error, path) takes the structured errno first (the import paths pass SyncFailedFile.code). SyncGateInput gains code, imported and systemic: a run where files imported records infra_isolated_runs on an open infra row, and decideGateAction treats an infra row with infra_isolated_runs >= threshold as chronic, auto-skipped with code EMBEDDING_INFRA_ISOLATED; a run where nothing imported never counts toward it. A systemic run (the sync.import_files ItemRun breaker, most files failing) adds no attempt to open rows, starts new rows at 1, blocks, and finalize.ts prints a blocked message naming --skip-failed. Pinned by test/pathological/a18-ledger-path-text.test.ts (both engines).

  • src/core/sync-git.ts:resolveSlugByPathOrSourcePath — Resolves a slug by pages.source_path first (returns the stored slug for frontmatter-fallback pages whose path doesn't derive a slug), then falls back to resolveSlugForPath(path). Three call sites: the un-syncable cleanup (which passes opts.sourceId), and the bare no-sourceId delete and rename-source paths; when sourceId IS set the delete and rename loops batch through engine.resolveSlugsByPaths instead. The source_path lookup is scoped to the DEFAULT source on the bare path, matching every write that path performs (updateSlug, deletePage, the rename bookkeeping repair are all default-scoped) — an unscoped lookup could return a row from another source sharing the source_path, and the rename loop consumes this value directly as its cheap-move source slug. Without the helper, emoji-only / Thai / Arabic filenames whose slug came from frontmatter would orphan on delete/rename (that path would compute the wrong path-derived slug). Best-effort query — pre-migration brains fall through to the legacy path.

  • src/core/import-chunk-reuse.ts — reuseStoredChunkVectors: A13 vector reuse for one markdown page import, shared by the inline import (before its transaction, to decide which chunks reach the provider) and every import's transaction (under the page lock, importFromContent in import-file.ts). It copies each stored vector the reuse gate admits onto its matching new chunk and maps the chunk to the stored row id when that row already holds exactly what the chunk would insert, so the import keeps it in place and deletes and writes only the rest; with keepUnembedded (the in-transaction pass) an identical never-embedded row stays under a new chunk that carries no vector either. Inline, --no-embed and prepared imports all keep rows; a prepared import reuses nothing from a page stored under per-chunk synopsis. With requireRecordedInput (set by importFromContent when the old or new body holds a protected fence, #6961) only a stored vector with a recorded embedding input is admitted, never the legacy raw-text match. Pinned by test/fenced-embed-reuse-6961.test.ts, test/import-inline-chunk-keep.test.ts (both engines) and test/persistence-edit-embedding-reuse.test.ts. reuseSegmentChunkVectors (Wave B) reads only the rows of the retired occurrences with their vectors and applies the same gate and chunk_source\0chunk_text plan, so an unchanged chunk inside a rewritten tail keeps its vector.

  • src/core/sync-policy.ts — isSyncDisabledConfig(config): the one predicate for config.syncEnabled === false ("excluded from AUTOMATIC/bulk sync"), unwrapping PGLite's JSON-string config scalar via parseSourceConfig. Read by the sync --all fan-out filter (src/commands/sync.ts), autopilot's per-source freshness dispatcher (src/commands/autopilot.ts, skip before queue.add('sync')) and the full-cycle fan-out (src/commands/autopilot-fanout.ts, which drops the sync phase + pull from a disabled source's autopilot-cycle payload but keeps lint/backlinks/extract and the freshness stamp) and the sync_enabled column of buildSyncStatusReport (src/core/sync-status-report.ts, whose callers pass RAW SELECT config rows — a JSON string on PGLite — so a raw cast there contradicted the fan-out filter). Doctor's checkSyncFreshness also applies this predicate, including the legacy query fallback: disabled sources contribute neither warnings nor freshness counts; only boolean false disables, not the string 'false'. checkCycleFreshness still monitors their maintenance cycles. Pinned by test/doctor-sync-policy.test.ts and test/doctor-cycle-freshness.test.ts. Deliberately does NOT gate performSync(): an explicit gbrain sync --source <id> still runs; sync-cost-gate.ts keeps its own inline check because it also feeds the explicit single-source cost preview. Pinned by test/sync-policy.test.ts, the #4399 cases in test/autopilot-fanout-wiring.test.ts (source-text) and test/autopilot-fanout.test.ts (stubbed dispatch).

  • src/core/sync-applicability.ts — agent-first operator wave E4. syncContentDirectory(engine, {sourceId, repoPath}) resolves the sync root exactly as performSync does and returns it when it is a gbrain-owned content directory (under <GBRAIN_HOME>/.gbrain/content/, or an owned --content-root recorded in the shared-skills setup receipt) with no .git at the root; null otherwise (fail-open). assertSyncAnchorAbsolute refuses sync_anchor_relative (syncAnchorRelativeError: exit 3, an ask_user fix naming gbrain sources set-path <id> <absolute-directory>, or gbrain config set sync.repo_path with no source) when the stored anchor (sources.local_path, else sync.repo_path) is not absolute on this host (isHostAbsolutePath: on win32 only a drive or UNC path) and no absolute repoPath, or relative one resolving elsewhere, was passed; sync --all --json puts the refusal's code, why and fix in the source's entry, and the sync Minion job completes as a skip carrying them; single-source and --all CLI syncs refuse it before the cost gate walks the directory, and a cycle whose directory matches no source checks default and fails its sync phase with that code. A path absolute only on another operating system (a Windows drive path read on Linux or macOS) gets the same code with a set-path-only fix, since --clear refuses it. src/core/sync-anchor.ts never proves ownership from a relative anchor: isAnchorOwnedSyncPath, ownsSourceSyncAnchor and sourceCommitAnchorAllowed treat it as not owned, and for default the commit-anchor check skips a relative sync.repo_path and judges the row's local_path (a null row falls back to that relative key and refuses), so an explicit absolute --repo never advances the commit anchor of a source whose stored path is relative. performSync calls assertSyncApplicable first (the anchor check, then the content-directory check), so a content-directory source refuses with sync_not_applicable (reason content_directory, fix gbrain import <dir> [--no-embed] --source <id>, git init named only as an ask-the-user option) before the managed path or the legacy #2964 anchor self-heal could git init it. sync --all skips these sources with one line; the dream cycle's sync phase reports them skipped (details.reason: sync_not_applicable). The CLI sync record renders fix-carrying OperationErrors through renderCliError (src/cli/commands/sync.ts). Pinned by test/sync-applicability.test.ts and test/sync-relative-anchor-refusal-7630.test.ts.

  • src/core/sync-upstream.ts — upstream observation for remote-tracking sources (#5255/#5176). observeUpstream(root, syncedCommit) reads the checkout's @{upstream} commit, the newer of the FETCH_HEAD and upstream-ref reflog mtimes (the last fetch, pull or push by any process) and rev-list --count of upstream commits the synced commit lacks; recordUpstreamObservation (called by performSync in src/commands/sync/perform.ts after every non-dry-run legacy or managed sync, best-effort) writes them to sources.upstream_checked_at / upstream_commit / upstream_behind, which managed_writer_guard does not protect. upstreamFreshness is doctor sync_freshness's separate "upstream checked" verdict (a remote_url source with no observation or one at least 24 h old is upstream unknown; any observed upstream lead is behind), DB-only so remote doctor runs it. managedPullWarning / UpstreamRefresh back the cycle sync phase (runPhaseSync in src/core/cycle.ts), which runs a managed pull: true as no-pull and reports details.upstream_refresh (pulled|failed|skipped_managed|not_requested) plus a managed_pull_skipped warning when the checkout tracks an upstream. A managed brain's fix (the warning and doctor's behind/unknown verdict) is gbrain sources refresh <source>; an unmanaged one's is gbrain sync --source <source>. Tests: test/managed-cycle-pull-upstream.test.ts, the pull row of test/managed-phase-matrix.test.ts.

  • src/core/sync-upstream-rewrite.ts — classic sync's upstream watch for a source that syncs with pull (GBRA-133 S-58/S-59). recordUpstreamBeforeFetch (called by src/commands/sync/preflight.ts before every pull) stores in sources.config.upstream_baseline the upstream commit HEAD contains, only when HEAD contains it, so a rewritten upstream fetched earlier never replaces it; settleUpstreamAfterPull records the new baseline and clears sources.config.upstream_divergence after a pull that fast-forwarded or was up to date, and after a pull that failed with HEAD and @{upstream} diverged stores upstream_rewritten (baseline not an ancestor of the new upstream), upstream_unknown (no baseline or its object is gone) or upstream_diverged (baseline contained: plain local commits); nothing is classified while a rebase, merge, cherry-pick or revert marker (GIT_OPERATION_MARKERS in src/core/git/commit-push.ts) exists. Best effort: it never throws into the sync and never writes a sync-failure ledger row. upstreamFix is the typed next step (ask_user reset bound to the observed SHAs for rewritten/unknown, never a merge; gbrain git commit-push --pull for diverged; both then the sync). Read by performSyncInner (result.upstream), buildSingleSyncJsonEnvelope, gbrain sources status --json (upstream) and doctor sync_failures (details.upstream, warn, local fix; remote callers get counts only). Pinned by test/pathological/s-58-upstream-rewrite.test.ts.

  • src/core/sync-attempt.ts + src/commands/doctor/sync-outcome.ts — doctor sync_freshness for a source with no successful sync (last_sync_at NULL, #4960). readLastSyncAttempt reads, read-only, the newest sync Minions job of the source and, on a managed brain, readSyncStatus (holds, last error, cursor, its next); nothing found is no_attempt, an unreadable read is no_attempt with unreadable. A live first-sync lock inside the staleness ceiling is warn (sync_first_run_in_progress, fix next: wait); no lock is fail (sync_no_successful_sync) naming last attempt, result and held count, with a per-reason fix (attempt_queued wait, holds_pending the managed next or sync status, last_attempt_unsuccessful inspect the job then retry, no_attempt retry; content_directory, a root only a content-setup receipt claims on a brain with persistence off, sync refuses: receiptContentDirectory names the sync_not_applicable import fix, test test/doctor-sync-freshness-receipt-root.test.ts). Entries land in details.no_successful_sync[]; these sources stay in stale_count. Test: test/doctor-sync-freshness-outcome-4960.test.ts.

  • src/core/sync.ts — Pure sync functions (manifest parsing, filtering, slug conversion). Exported pruneDir(name: string): boolean is the single source of truth for descent-time directory exclusion across walkers — blocks node_modules (no leading dot, so a naive walker would descend into it and inflate MISSING_OPEN counts via vendor packages), vendor/dist/build/venv, dot-prefix dirs, and *.raw sidecars — NOT ops/, which is ordinary user content (the bundled daily-task-manager stores ops/tasks there); isSyncable applies it per path segment, and walkMarkdownFiles in src/commands/extract.ts + listTextFiles in src/core/cycle/transcript-discovery.ts consult it BEFORE recursing to save the IO of walking thousands of vendor files. manageGitignore worktree discriminator matches the gitdir path segment (/modules/<name> = submodule, /worktrees/<name> = worktree, per Git's documented layout) so Conductor worktrees (first-class repos) get .gitignore management for storage-tiering. The sync-failure ledger (failure store, error classifier, the shared bookmark gate, and the doctor severity rule) lives in src/core/sync-failure-ledger.ts; sync.ts re-exports classifyErrorCode, summarizeFailuresByCode, loadSyncFailures, unacknowledgedSyncFailures, acknowledgeSyncFailures, recordSyncFailures, decideSyncFailureSeverity, applySyncFailureGate, and the SyncFailure type for backward-compatible imports — see its entry below. isSyncable factored through private classifySync(path, opts): SyncableReason | null; exported companion unsyncableReason(path, opts) returns the same tagged reason or null when syncable. SYNC_SKIP_FILES is a named export (the canonical metafile basenames schema.md, index.md, log.md, README.md, RESOLVER.md, skipped at any depth unless SyncableOptions.metafilePage says a nested one is a page: metafileIsPage(path, head, mode) is true for an isNestedSkipMetafile path whose closed leading frontmatter has a non-empty top-level type: or title: under sync.metafile_pages typed and no top-level slug: naming another page (#7341: such a file stays scaffolding instead of being held frontmatter_slug_conflict), the one default DEFAULT_METAFILE_PAGES_MODE; off skips every metafile; readMetafilePagesMode reads the key); SYNC_ROOT_SKIP_FILES (#5186, W14 P1.5b) adds the bootstrap scaffolding AGENTS.md / CLAUDE.md at depth 0 only, and isSyncMetafile(path) is the one predicate classifySync and the bulk-import collector (commands/import.ts) share (the managed effect scan's isMetafilePage in persistence/effects.ts adds the head of the file on disk, so a typed nested metafile page is mirrored and published like any page), so an earlier-indexed root agents page survives under the #1433 guard (test/sync-root-agents-metafile.test.ts). SyncableReason union: 'metafile' | 'strategy' | 'pruned-dir' | 'include-glob-miss' | 'exclude-glob-hit' | 'malformed-path'. Malformed filenames are TWO-TIER: hasMalformedPathSegment (ADMISSION — control chars on any path; square brackets on .md/.mdx paths only, so code-strategy lanes keep indexing app/[id]/page.tsx framework layouts) vs isPoisonedPath (DESTRUCTION — only the injection signature ]( or control chars; sync's row-DELETING lanes gate on this so a bare-bracket markdown row already in the DB survives reconcile while its file exists). sanitizePathForDisplay scrubs control bytes + caps length before echoing such paths. The un-syncable cleanup loop (sweepUnsyncableModified in src/commands/sync/deletes.ts) guards on unsyncableReason(path) being 'metafile' OR 'pruned-dir' so previously-indexed metafile pages AND deliberately put-created pages under pruned dirs survive every re-sync. Does NOT cover manifest.deleted (the upstream filter already strips metafiles). Pinned by test/sync-isSyncable-shape.test.ts (15 cases, duality contract) + test/sync-metafile-skip.test.ts (3 PGLite cases incl. the renamed .md → .txt negative). pruneDir: pruneDir(name, parentDir?) extended with optional parentDir. When provided, additionally rejects directories containing .git as a FILE — the git submodule gitfile pattern (regular repos have .git as a DIRECTORY; submodules as a file pointing into the parent's .git/modules/). Sync + extract walkers thread parentDir so the gitfile-as-FILE check fires per descend step. Best-effort: statSync failures fall through and treat as a normal dir. Prevents phantom imports from a worktree-with-submodules sync walking into submodule trees. Pinned by test/sync-walker-submodule.test.ts. The legacy failure ledger re-export is distinct from managed cursor-keyed mirrors: repeat managed observation does not inflate attempts, success clears only the matching cursor, and managed failures cannot be acknowledged or auto-skipped. isMultimodalEnabled(env) (GBRAIN_EMBEDDING_MULTIMODAL=true) is the one predicate managed discovery, the hold re-screen, embed --stale, the blocked-projection hint and doctor image_embedding_coverage read for whether images are imported and embedded.

  • src/core/sync-metafile-pages.ts — the head readers behind sync.metafile_pages: metafilePagePredicate(mode, read, rootRelative) (memoized, the SyncableOptions.metafilePage every classifying caller passes), diskMetafileHeads(root) (regular files only, never a symlink), gitMetafileHeads(gitRoot, commits) (first commit that has the path; prime batch-reads blobs a caller already streams through one cat-file --batch-check plus one --batch), firstMetafileHead (disk, then the last synced blob, so a deleted file is judged as last committed), listMetafileNamedBlobs (one ls-tree), and the classic backfill marker sync.metafile_pages.applied.<source> (metafileBackfillDue / recordMetafilePagesApplied, written with the bookmark): a source that has not finished a sync under typed adds its tree's nested metafile-named files to the next delta once. Managed sync instead folds the mode into the pass selection fingerprint (sync-pass-run.ts; unchanged under off). Only metafile-named paths are ever read. config set sync.metafile_pages refuses a value outside typed | off (src/commands/config/sync-metafile-pages-value.ts); the restore check and doctor missing_recorded_files (persistence/detached-pages.ts) judge a recorded nested metafile with the same disk-then-last-synced predicate sync --full uses. Pinned by test/sync-metafile-pages.test.ts (classic) and test/persistence-sync-metafile-pages.test.ts (managed, PGLite and Postgres).

  • src/core/sync-rename-identity.ts — the one confirmation stage for inexact Git renames (#6729). confirmRenameIdentities reads committed sides through one git cat-file --batch stream (64 KiB heads; GST-2331: under HARDENED_GIT_ARGS and NO_LAZY_FETCH_ENV, so a side a partial clone lacks reads as no identity and the pair is downgraded) and the dirty tree's working side from disk, with id and slug: from the frontmatter and the title by parseMarkdown precedence (frontmatter, then the first H1, no filename fallback; markdown.ts explicitMarkdownTitle), the old side taking the title its page row stores; it keeps an R<100 pair on a same-slug respelling, a unique shared id, or with no id on either side a unique slug: line or title (titles also unique among live pages). explicitIdVeto is the one explicit-id veto the managed takeovers consult (also the #6727 legacy-slug adoption in sync-discovery.ts: two different explicit ids hold legacy_slug_conflict, reason explicit_id_conflict). An add whose id uniquely matches a delete in the range becomes a rename only with continuity (same file name, title or bytes; digest is the sha256 of a file that fits the head read), as decideImportIdentity asks of a move. Downgraded pairs record read.from / read.to. A dirty-tree verdict is bound to the bytes it read: each kept rename carries identityHead (sha256 of the first 64 KiB), classic applyRename re-checks it before the identity moves and managed readSyncContent refuses source_changed on frozen bytes that differ. GBRA-133 S-51: an id, slug: or title holding U+0000 or a lone surrogate is absent before any SQL (never normalized), so the pair takes the ordinary unconfirmed-rename rules; both identity reads batch every path and, on SQLSTATE 22021/22P05 only, retry path by path, and the inexact pairs carrying a refused value come back in heldRenames (classic preflight.ts holds them as rename_identity_unreadable, keeping the old page; with holdUnreadable unset, as in managed discovery, the error is rethrown). redecideHeldRename decides a held pair again from the kept page's stored id and title once its file changes. Any other error propagates. Pinned by test/pathological/s-51-rename-identity-unreadable.test.ts.

  • src/core/sync-identity-downgrades.ts — durable records of downgraded pairs (op_checkpoints op sync-identity-downgrade, fingerprint = old page id, open until a disposition is set or the old page is restored or purged; no time window; the checkpoint sweep keeps open records), the purge-hold SQL predicate, the live list (new slug read live), the report lines and the restore argv; the per-pair remedy every surface prints (identityRemedyParts, identityRemedy, withIdentityRemedies, renameIdentityPreviewArgv, remedyAction; on a managed brain the remedy is --close with carry_unavailable: managed_remedy_unavailable); settleIdentityDowngrade (sets completed_keys[0].disposition = { kind: remedied | closed, at } on an open record); identityRestoreAvailable (the decideUnboundWrite rule) keeps the restore off the report and doctor on an unbound Postgres source with a checkout, where it would refuse owner_unavailable.

  • src/core/repair/rename-identity.ts — gbrain repair rename-identity (#6729), explicit-only, preview-bound, destructive. plan selects one open pair (--slug/--from), hashes identityRemedyParts (brain, pair, both page ids and revisions, disposition) and saves the approved set; with no pair named it lists the open pairs. On a managed brain a carry preview returns no items with details.code: managed_remedy_unavailable and the --close preview, and an apply refuses with that code. carryIdentity (classic only): one maintenance transaction under both page locks re-checks the hash, the open record and fenceRowChecks, merges matching fence rows onto the old rows, retires the provisional page under purgedSlug, moves the old page to the new slug (updateSlug redirect), moves the provisional's page-id rows (movePageIdReferences), imports the new file, settles the record remedied. --close settles closed. Refusals: fact_rows_collide, managed_remedy_unavailable, changed_since_preview, preview_changed, invalid_params.

  • src/core/persistence/sync-prescreen.ts — #6712 PR 1 (L1): the discovery prescreen and drift baseline. After discoverManagedSync freezes identities, prescreenSyncEntries reads the pinned blobs (readTreeBlobs, one recursive listing for a large set) and the import provenance of every Git import of an existing page, and classifyBaseline marks each prescreened (disk blob, revision and syncImportParserFor fingerprint all match; bypassed under --full and for held paths) or drift (database: the page moved, the file did not; both/unknown in a tree walk or for a file_drift hold). A page whose current revision a committed managed-sync request wrote, or whose writer's publication wrote to its file (a write-through git effect), is not guarded (fileBackedRevisions), and drifted pages under storage.keep_db prefixes leave the manifest as drift candidates (releaseKeepDbDrift, recordDriftSkip). The run passes prescreened entries through waivePrescreenedRun (sync-waivers.ts); freezeEntry holds a drifted import file_drift (fileDriftHold, sync-page-fault.ts) unless sameContentAtOrigin proves it a no-op. movedDriftHolds re-screens drift holds whose page moved. Tests: test/sync-prescreen-drift-6712.test.ts (both engines).

  • src/core/persistence/sync-image.ts — #6529: managed sync's image branch. With multimodal embedding on, freezeEntry (sync-run.ts) freezes an image entry as its bytes in base64 (frozenImageIntent; rawHash stays the file sha256, so the working-tree check and the hash no-op are unchanged) and prepareManagedSyncMutation (sync-prepare.ts) hands it to prepareManagedSyncImage, which runs importImageFile with prepare (the coordinated path gbrain import uses in import-prepare.ts): the importer decides the hash no-op, OCRs and embeds the image at preparation inside the sync budget (--no-embed skips both; the caption chunk's text vector is deferred to embed --stale), and the apply records source_path, releases the path's hold and re-reads the snapshot. A company plan refuses (profile_incompatible), a screening preparation (sameContentAtOrigin, the no-op waiver in sync-waivers.ts and unchangedManagedImport in import-mutations.ts return early for images) is refused rather than paid for, newer working-tree bytes or a vanished file refuse source_changed, and a Git rename publishes the new slug and soft-deletes the old page. import-file.ts records source_path on the legacy importer's hash-skip path too (refreshSourcePath), so no image import leaves it NULL. Tests: test/managed-sync-images-5493.test.ts (both engines), test/embed-stale-images-managed-6529.test.ts.

  • src/core/persistence/sync-streamed.ts — Wave B PR 2: managed sync of a Markdown file over the 24 MiB single-string ceiling. With pages.segmented_storage on, freezeEntry (sync-run.ts) freezes such a file by reference instead of holding it by its size: streamedSyncBodyRef hashes the sha256 and the Git blob id as a stream (sha1 or sha256 by the pinned commit's length) into intent.body_ref (git_blob, or input_file for an uncommitted working-tree file); the journal carries no content, and a committed entry whose working tree does not hold its pinned blob, a file over pages.max_bytes or a non-Markdown file is held as before. prepareManagedSyncMutation (sync-prepare.ts) hands it to prepareManagedSyncStreamed, which streams it through importStreamedMarkdownFile (page-body/streamed-import.ts, coordinated; moved on a rename keeps an implicit type following the new path; slug is the admitted page, the one recording the file as its origin, as the inline import targets) and publishes database-only, recording the origin through bindOrigin (B-14: a renamed page keeping its origin takes the file, no twin at the path's slug); a rename moves the page first and re-seals an unchanged body (sealSegmentedPage). A file the streamed path refuses (a facts fence) fails its request with the refusal's code and the run holds it (streamedRefusalHold in sync-screen.ts); a dry run lists it in screen_skipped as page_body_segmented; groupableIntent (sync-group.ts) keeps it out of bulk groups. Tests: test/large-pages/managed-sync-streamed.test.ts (both engines), managed-sync-streamed-crash.test.ts (owner killed at consumer:prepared), managed-sync-streamed-memory.slow.test.ts (VmHWM), streamed-sync-origin-b14.test.ts (both engines).

  • src/core/persistence/sync-entry-fault.ts — GBRA-133 (#6712 PR 4b): the per-entry faults of a managed sync freeze, so one odd file never stops its source. nullBytesRefusal holds a Markdown text with U+0000 content_null_bytes (line of the first NUL; a UTF-16 byte order mark says save as UTF-8), from screenFrozenImport with holds on and as a typed run stop under sync.holds=fail. filterOwnedRefusal (GST-2312, #9024), checked first on the same two paths, holds content_filter_owned a blob starting with git-crypt's header or a committed blob whose path names a Git filter driver other than lfs, configured here or not (pinnedFilterDriver in sync-screen.ts, at the pinned commit or a company plan's revision, read with readFilterDrivers' batched git check-attr --source on git 2.40+, or read-tree into a temporary index and check-attr --cached on an older git; with HARDENED_GIT_ARGS and GIT_NO_LAZY_FETCH=1, so the attribute read runs no repository program and fetches nothing; it first checks with ls-tree and cat-file --batch-check that each .gitattributes that applies is present, and a path under a missing one makes pinnedFilterDriver throw git_object_missing via missingAttributesRefusal; GST-2331: every read of sync-blobs.ts runs with HARDENED_GIT_ARGS and NO_LAZY_FETCH_ENV, so the blob reads fetch nothing either and an object a partial clone lacks reads as missing). committedContentOrMissing (called by pinnedContent when the pinned read fails) imports a committed file whose blob object is gone from working-tree bytes that hash to that blob id, else throws git_object_missing (GST-2331: in a partial clone (syncPartialClone in sync-discovery.ts: a promisor remote or extensions.partialClone), the message names the partial clone and the fix is git cat-file -p <blob>, and a partial clone that lacks a tree of the synced commit stops the run instead (partialCloneTreeRefusal, from the tree walk and from sync-pass-run.ts's reconcile level read, fix git ls-tree -r -d <commit>); otherwise git fsck --connectivity-only); a committed name with U+FFFD that names nothing on disk (a name that is not UTF-8) throws path_not_utf8 first. directoryAt lets a deletion whose name became a directory apply (freeze and the owner's raw-hash check). freezeFaultHold is freezeEntry's catch (sync-run.ts wraps freezeEntryOnce): git_object_missing and path_not_utf8 are held under their codes; a page-body fault (PAGE_BODY_FAULT_CODES: page_body_segmented, page_body_rows_unreadable, e.g. a segmented page whose segment rows don't cover its body) is held page_write_failed with write_failure.code set to that code, which sync status classifies by the freeze_page_body_* rows of SYNC_FAULT_TABLE; any other OperationError and every run-scoped error (classifyItemFailure scope run, connection, statement timeout, lock, back-pressure, abort) rethrows, and an unexpected throw is held page_write_failed with write_failure.origin: 'freeze' and request_id: null, re-tested by every sync until held HOLD_ATTEMPTS_NEEDS_HUMAN times; a run with ITEM_BREAKER_MIN_ITEMS faults and no more clean freezes than faults is systemic and rethrows.

  • src/core/tag-limit.ts — TAG_MAX_BYTES (2688, the longest tag both btree indexes on tags store, in UTF-8 bytes) and tagLengthHold, the tag_too_long hold classifyImportHold returns, so every content screen, file import and legacy sync hold refuses it; prepareSegmentedTagMutation throws it before an add_tag flip. The message names the tag's position and size, never its text (#7052). Pinned by test/tag-length-7052.test.ts.

  • src/core/url-clone.ts — gbrain-owned sources add --url clones (#6946, GBRA-130 C-2). isOwnedClone (config managed_clone or a local_path under the default clone dir) and defaultCloneDir; urlCloneReadOnly is the one predicate (owned clone on a brain without managed persistence) the fence writer (fence-write.ts, databaseOnlyReason: 'url_clone'), write-through (skipped: 'url_clone'), timeline write-through, unfenced-facts adoption, the empty-fence guard and sourceMirrorReadOnly consult, so nothing gbrain writes lands in a checkout it updates with git pull --ff-only. urlClonePullBlock reads the tracked changes of a clone whose pull failed and returns pull_blocked_local_changes with an ask_user fix naming the preview gbrain repair url-clone-fences --source <id>; formatUrlClonePullBlock renders it for sync's stderr (sync/preflight.ts) and cycle.ts puts it in the sync phase detail as pull_blocked. Test: test/pathological/c2-url-clone-fences.test.ts. gbrain itself never writes into an owned clone on an unmanaged brain, but local commits someone else makes there are published by gbrain sources git-reconcile (src/commands/sources-git-reconcile.ts, autopilot each tick: secret scan, rewritten-upstream refusal, repository-root check); sources.refresh_publish_diverged false or gbrain sources set-sync <id> off keeps them local.

  • src/core/url-source-origin.ts, src/commands/sources-record-origin.ts and src/commands/doctor/checks/url-source-origin.ts — who added a URL source (sources.config.added_by_remote_caller). Both add paths write it (true for a remote caller, false for the local operator); only an explicit true reads as remote. URL sources added before that record existed carry none, and nothing stored tells a remote caller's add from the local operator's (same row, same default clone directory); a clone outside $GBRAIN_HOME/clones/<id> (or a clones/<id> under an earlier home) proves a local add. A URL clone counts when isOwnedClone accepts it, so an unmarked clone at the default directory is listed too. urlSourcesWithoutOrigin (read-only) feeds the wave check url_source_origin (host-only, resolution: 'operator', warn with an ask_user fix whose argv is the preview). recordSourceOrigin(engine, ids, { origin, apply, remote }) backs gbrain sources record-origin <id>... --remote|--local [--apply] [--json]: it throws trusted_local_only unless remote === false, previews unless apply, writes true (--remote) or false (--local) in one transaction that re-reads the row FOR UPDATE and refuses source_changed if its path or URL moved; on a managed brain that transaction runs inside withTopologyLocks after lockTopologyRows, the locks a reclone takes (a held lock refuses the id source_busy), and runManagedSourceClone takes the config it clones with from its own locked admission read, so a record and a reclone never interleave. --remote --apply also writes LFS_OFF_CLONE_CONFIG into the repository's shared config (--git-common-dir; git config --file, not run in the checkout) before the row, reads the effective values back (lockDownGaps) and throws when a worktree-scoped or included setting overrides one, and locks down an already-remote source whose checkout lacks it (no git-lfs refusal for it unless Git cannot place the checkout, lfs_unknown); each key's existing values are removed before its one value is written, in a config.lock copy renamed over the config in one step; a throw is reported for its id as write_failed and the batch continues. It never removes a true, and refuses --remote for a checkout with any tracked filter=lfs path or a committed .gitattributes declaring filter=lfs outside a comment line (lfs_tracked, worded per case; read with hardenedGitSync ls-files -- ':(attr:filter=lfs)' plus every committed .gitattributes blob from ls-tree -z records split at their first tab, then cat-file, so clone-local attributes cannot hide one, and read again under the locks), or one it cannot inspect (lfs_unknown, whose reason names the cause: checkout missing, not its own repository's top level by a realpath comparison, owned by another user (safe.directory), or a Git read failed), because a lock-down reclone would not match the stored writer manifest there. An unborn HEAD with an empty index (a clone of an empty repository) has no committed attributes and passes. Without git-lfs files the tracked bytes are the same, so no manifest is written. Pinned by test/url-source-origin.test.ts (PGLite and Postgres).

  • src/core/write-through.ts — shared atomic disk write-through for the canonical ingestion path. resolvePageWriteTarget(engine, slug, sourceId, { includeDeleted? }) (active rows by default; includeDeleted: true resolves a tombstone's recorded source_path for the purge remediation retry) is the exported single source of truth for the ONE file a (source, slug) pair lives in on disk: a source with its own local_path writes at that tree's ROOT (never nested under .sources/); a source without one nests under the host repo (sync.repo_path, default at root, non-default under .sources/<id>/) unless that path is another source's own working tree (leak guard → source_repo_belongs_to_other_source; a live source whose local_path is relative counts as owning every tree, one absolute only on another OS does not, and a local_path or sync.repo_path target not absolute on this host (isHostAbsolutePath) is repo_not_found); the page's recorded source_path (or a contained absolute file:// source_uri; a relative or host-only file:// names no local file and is read as absent) is preferred over a slug-derived name so writes land in the file of record instead of minting a twin; and isWriteTargetContained rejects hostile rows escaping the tree (path_escapes_source_root). The ok-result also carries sourcePathToBind — the target expressed in the file scanner's source_path convention for the source's pinned slug_root_mode (or the mode its first sync would pin, via scannerSlugRootMode): GIT-ROOT-relative under git-root when the scan root sits inside a git repo, scan-root-relative under source-root and for non-git or git-root scan roots, so a put-born page binds the same form managed sync and delete-reconcile key on. Every recorded-path reader (write targets, takes, reconcile, audit, export restore, doctor) decodes with the same mode (resolveSourceLocalFilePath(..., slugRootMode)): under source-root the scope prefix is removed only from the legacy Git-root form whose remainder names the page slug, and basename rows resolve under the unstripped slug directory. The resolver is shared by writePageThrough, the facts fence writer (src/core/facts/fence-write.ts), and fence forget (src/core/facts/forget.ts) — the fence appends to the page's file, so all writers MUST compute the identical path or the fence lands in a file sync never reads back and the next extract_facts reconcile deletes the fence-owned DB rows. writePageThrough(engine, slug, {sourceId?, frontmatterOverrides?, inlineOnly?, logger?, expectedFileBytes?, deferCommit?}) resolves the target through it, re-reads the just-written DB row (getPage), renders an inline page via serializePageToMarkdown, and writes the .md. A page stored in segments is never rendered whole: its file is measured from its segments at the snapshot's revision (unreadPageFile; a page that moved since refuses revision_conflict), checked against PUSH_SCAN_MAX_FILE_BYTES before source_path is bound (a body already over the cap by body_bytes is refused without streaming), streamed through stageStreamedContent on the engine it was given (so a caller inside a transaction works) keeping the existing file's mode, and renamed over the target after the file-changed check; frontmatterOverrides on such a page return an error result, and inlineOnly (the derived writer) skips it as segmented_page so the brain has a committable artifact that round-trips through gbrain sync. Rendering from the row keeps the serialized content consistent at write time. The fsync-backed atomicWriteFileSync stages and renames the file after required source-path bookkeeping; lock/lease checks run before publication. put_page holds the root lock before importing and invokes write-through inside its database transaction, so ordinary filesystem rejection rolls back existing content, tags, chunks, and versions. A crash or database COMMIT failure after rename can still leave canonical Markdown ahead of the index; this is not distributed ACID or a durable queue. Never throws — returns WriteThroughResult { written, path?, content? (the bytes written; inline pages only), skipped?: 'disabled_by_config' | 'url_clone' | 'no_repo_configured' | 'repo_not_found' | 'source_repo_belongs_to_other_source' | 'page_not_found_after_write' | 'path_escapes_source_root' | 'case_insensitive_collision' | 'file_changed' | 'over_push_scan_cap' | 'segmented_page', warning?, error? } (file_changed: the caller's expectedFileBytes preimage, null for absent, no longer matches the file under the source filesystem lock, so the file is left untouched) so the caller decides messaging + exit codes. withNoRepoWriteThroughWarning(result, sourceId) decorates an unwritten no_repo_configured result (and a relative_root one, naming sources set-path) with warning (the write landed only in the database; bind the token/server to a git-backed source or configure local_path/sync.repo_path); put_page applies it for untrusted callers only (ctx.remote !== false), so local CLI responses and the disabled_by_config operator opt-out stay silent. isWriteThroughDisabled (shared with the fence lane, ~30s per-engine cache) honors the sync.write_through opt-out. Trust gating (subagent sandbox, dry-run) stays at the CALLER. On a durability-hardened repo (isDurabilityHardened — the gbrain post-commit hook is installed, i.e. the user ran gbrain sources harden), a successful write is best-effort COMMITTED via commitWriteThroughFile (path-limited git commit -- <file>, never sweeps unrelated edits; the hook then background-pushes) unless the caller passes deferCommit (the derived write-through commits its batch itself, #8073; deletePageThrough takes it too) so write-through content reaches git instead of accumulating uncommitted forever; result carries committed?: boolean. Unhardened repos keep write-only behavior. deletePageThrough(engine, slug, {sourceId?, target?, logger?}) is the delete-side sink (sole caller: the delete_page op): resolves the same target, unlinks the .md, and on a hardened repo best-effort commits the removal path-limited through the same helper with subject gbrain: delete write-through <slug>, reporting committed?: boolean on DeleteThroughResult (absent when unhardened or when the commit did not land — the unlink still stands; a never-committed page leaves nothing to commit, so no empty commit). Pinned by test/delete-write-through-commit.test.ts. Consumers: put_page op and gbrain brainstorm/lsd --save via persistSavedIdea. Pinned by test/write-through.test.ts + test/write-through-commit.test.ts. The put_page op is that deciding caller for direct writes: a skip outside the deliberate DB-only set (no_repo_configured/disabled_by_config/subagent_sandbox/dry_run) throws storage_error inside the import transaction, rolling back the page revision, tags, chunks and version snapshot instead of deleting a just-created row afterward. #6946/#7098: on a read-only checkout (readOnlyCheckout in mirror-read-only.ts: a mirror-readonly source, or a gbrain-owned --url clone of an unmanaged brain), writePageThrough returns skipped: 'mirror_read_only' | 'url_clone' and deletePageThrough returns removed: false with the same skip; timeline-write-through.ts, the fact fence writer, forget and the unfenced-fact pass skip the same way.