Garry's Opinionated OpenClaw/Hermes Agent Brain
Key files: Files And Sync (1/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/audit-week-file.ts— single source of truth for ISO-week audit JSONL filename math. ExportsisoWeek(d),isoWeekFilename(prefix, now?),resolveAuditDir()(honorsGBRAIN_AUDIT_DIR). Year-boundary correctness pinned by tests at 2020-W53 (the 53-week year), 2025-W01 rolling in from 2024-12-30 (Monday), 2026-W01. Four call sites:src/core/minions/handlers/shell-audit.ts,src/core/facts/phantom-audit.ts,src/core/audit-slug-fallback.ts,src/core/cycle/budget-meter.ts. Each keeps itscompute<X>AuditFilenamethin wrapper.src/core/brain-repo-durability.ts+src/commands/sources-harden.ts— brain-repo git durability.hardenBrainRepo(opts)makes a brain's working tree durable, idempotently: divergence-safe pull, a LOCAL untracked.git/hooks/post-commitauto-push safety net (never committed — a pulled commit can't rewrite executed code next to the token; installed into the activecore.hooksPathdir and excluded via.git/info/excludewhen that dir is tracked), a committedscripts/brain-commit-push.shdelegating togbrain git commit-push(src/core/git/commit-push.ts, #6530; guidedocs/guides/shared-checkout-git.md) that never exits 0 without a confirmed push, and a hook running the harden-captured CLI with--push-only --require-clean(both# gbrain-protocol: 2; harden never downgrades), durability rules patched into the active resolver file (findResolverFile→ RESOLVER.md > AGENTS.md; taxonomy: repo_brain-filing-rules.json, else top folders, else bundled, #7629), a minimal DB-free pull cron (launchd/crontab runninggbrain sources pull --path <dir>so it never opens the PGLite single-writer lock), and a push-probe verify (no heartbeat commit). Credential is REPO-scoped (acceptPatfrom--pat-file/GBRAIN_GITHUB_PAT, warns on loose perms; reuses an existing repo-localcredential.helper, else a0600store wired via repo-local config); the token is redacted everywhere viaredactSecretsInTextand never enters the repo, remote URL, logs, orDurabilityReport.unhardenBrainReporemoves the cron/hook/credential wiring (ownership-fingerprinted);sources removeruns it only AFTER the source row's DELETE commits (a refused or raced delete leaves the scaffolding intact; post-commit teardown failure is loud but non-fatal). CLI:gbrain sources harden <id|--all>/pull <id>|--path <dir>/unharden <id>; auto-harden fires onsources add --url ... --pat-filefor managed clones (--no-hardenopts out).sources pull --pathis dispatched insrc/cli.tsBEFOREconnectEngineso the cron stays DB-free. CLI-only (writes executables + an OS cron + a credential helper on the host); never exposed over MCP.isDurabilityHardened(repoPath)(the durability hook banner is installed) andcommitWriteThroughFile(repoPath, absPath, slug, action = 'write-through')are the shared helpers every write-through sink (page write/delete, facts fence, timeline, lint --fix) uses to best-effort commit ONE file path-limited on a hardened repo — never throws, false on any failure;actiononly labels the subject (gbrain: <action> <slug>;'delete write-through'for removals).isDurabilityHardenedAsync(repoPath)is the owners' non-blocking probe (#6210: rejectsgit_unavailablewhen unsure); it and the persistence Git runner (effect-git.ts) spawn throughexecFileBounded(defined in the import-freesrc/core/bounded-child-exec.tsand re-exported here;git-remote.tspullReposhares it), which settles at its deadline or on abort from its own timer because Bun can drop a child's pipe events and, before 1.3.14, its exit event (oven-sh/bun#30301) when bun:testexpect().resolves/.rejectsre-enters the event loop; an unbounded wait there strandeddisposePersistenceConsumerand hung every later test in the file (test:test/bounded-child-exec.test.ts). Tests:test/brain-repo-durability.serial.test.ts,test/git-remote-durable.serial.test.ts,test/brain-durability-hook.serial.test.ts,test/durability-cron.test.ts.brain_remote_contains_commitchecks the exactrefs/heads/<branch>at every effective push URL, fetches each advertised tip without writingFETCH_HEAD, and proves ancestry of the captured commit; branch existence, a different fetch destination, or a stale tracking ref is not enough. Probe diagnostics are suppressed, ambiguous URL resolution fails closed, and recovery is skipped if local HEAD has moved since the failed push. This check runs after a rejected push and after retry failure, loggingok-already-on-remoteon confirmation;getLastPushOutcomerecognizes it as success. Existing unmanaged installations must rerungbrain sources harden <source-id>to refresh both the local hook and committed helper; upgrading the CLI alone does not rewrite those scripts. Managed worktrees retain the persistence outbox as their Git writer; generated legacy helpers refuse to bypass it. Locks, waits, outcomes and the per-checkout conflict record: the guide. Tests:test/git-commit-push-6530.serial.test.ts.src/core/classic-file-holds.ts— classic sync's deterministic per-file refusals as holds in the shared hold store.classifyClassicFile(root, relPath, gitRoot)reads metadata only (lstat, the symlink target's realpath, an open+close of a regular file; for a missing pathgit ls-tree HEADandgit ls-files -vwith optional locks off) and returnsfile_unreadable(symlink_in_repo,symlink_outside_root,symlink_dangling,symlink_loop,permission_denied,not_regular_file),absent_from_worktree(skip_worktree,deleted_locally), or null (a readable file, a directory, a path HEAD lacks, any other error, all left to the drain's existing paths).classicFileHoldFixisgitHoldFix's builder for both codes: the user's step for a symlink or permission,ask_userbetween restore and committing the deletion for an absent file;<checkout>is aninputsplaceholder. Pinned bytest/pathological/s-classic-file-holds.test.ts(+ its Postgres wrapper).src/core/classic-rename-holds.ts—gitHoldFix's builder for classic sync's two rename holds (GBRA-133):rename_identity_unreadable(S-51; the database refused to compare a renamed file's title or id, so the new file waits and the old page stays whole; written byholdUnreadableRenamesinsrc/commands/sync/holds.tsand decided again byredecideUnreadableRenameswhen the file changes) andrename_reconcile_failed(S-67; therenames.tsreconcile threw something other than its unprovable verdict or a transient database error while finding stale rows, so the rename is held with the error's class and code only; a failed delete keeps the<rename:…>marker). Both fixes are the user's. Pinned bytest/pathological/s-51-rename-identity-unreadable.test.tsandtest/pathological/s-70-classifier-origin.test.ts.src/core/content-sanity-literals.ts— operator literal-substring loader. Reads~/.gbrain/junk-substrings.txt, one literal per non-comment non-blank line; optional# name=<id>header pairs an identifier with the following literal so audit JSONL groups by site (linkedin_auth_wall,reddit_blocked, etc.). Fail-soft on ENOENT (missing file = empty array). Loaded on every ingest. Deliberately literal substrings (NOT regex) to defeat ReDoS. Pinned bytest/content-sanity-literals.test.ts.src/core/content-sanity.ts— pure assessor for the content-sanity defense.assessContent(content, opts): SanityVerdictreturns one ofok | warn_oversize | hard_block_junk_pattern | soft_block_oversizewith{reason, bytes, matched_pattern_name?}. Six built-in junk patterns (Cloudflare challenge dumps, CAPTCHAs, 403 dumps, bare error-page titles) compiled at module load; operator literal substrings vialoadOperatorLiterals()fromsrc/core/content-sanity-literals.ts.ContentSanityBlockErrortagged class is the typed throw shape every wrapper site (gbrain import,put_pageMCP op,gbrain sync,/ingestwebhook) catches via the existing exception flow. The bytes-parity contract pinsBuffer.byteLength(content, 'utf8')against the embedder's actual byte count so a 499K-byte page can't be soft-blocked on assessment then overflow on embed. Knob resolution chain env > file (~/.gbrain/config.json) > DB > defaults. Four knobs:content_sanity.bytes_warn(50_000),content_sanity.bytes_block(500_000),content_sanity.junk_patterns_enabled(true),content_sanity.disabled(false;GBRAIN_NO_SANITY=1is the loud-stderr kill-switch).assessContentSanity(opts): SanityAssessmentreturns the three-tier disposition (shouldQuarantine/shouldFlag+ reason/detail) consumed byimportFromContentandgbrain quarantine scan; adds the fuzzy prose-vs-markup ratio pass (markup chars / total abovemax_markup_ratio; code pages exempt; gated byprose_check_enabled) on top of the byte + junk-pattern passes. Three more knobs:content_sanity.junk_disposition(quarantinedefault |reject; no env override — a destructive flip belongs in explicit config),content_sanity.max_markup_ratio(0.85, envGBRAIN_MAX_MARKUP_RATIO, clamped(0,1]),content_sanity.prose_check_enabled(true). Pinned bytest/content-sanity.test.ts. Per-pattern opt-out without the kill-switch:content_sanity.disabled_patternsnames built-in junk patterns to skip (a JSON array["access_denied"]or a comma listaccess_denied,error_title; malformed JSON falls back to the comma parse so a hand-typed value still lands) — the file plane takes the array, the DB plane the string.src/core/data-frontmatter.ts— shared data-only YAML/JSON parsing and serialization. Rejects unsupported language selectors before parsing, uses js-yaml safe schema (exportedFRONTMATTER_SCHEMA) with existing scalar types (a calendar-invalid timestamp such as2024-02-30stays a string instead of rolling over to March 1), sanitizes parser errors, and keeps body text opaque.loadBoundedYamlis the only js-yamlloadcall for content gbrain did not write (frontmatter, recovery, brain-writer, skill and rename-identity readers): after load it sizes the value as if every alias were copied out, memoized and cycle-safe, and throwsYamlAliasBoundError(js-yaml-shapedreasonandmarkat the first alias) past text length +MAX_YAML_ALIAS_EXPANSION(65,536), so an alias bomb is a YAML_PARSE /invalid_frontmatterrefusal before anything serializes it. Used by markdown, capture, recipes, plugins, and greenfield ingestion. Independent fixtures:test/data-frontmatter.test.ts,test/frontmatter-security.test.ts,test/pathological/s-47-yaml-alias-bomb.test.ts.src/core/default-source-path-check.ts— pureassessDefaultSourcePath(input)verdict for thedefault_source_local_pathdoctor check (no DB/FS access — caller supplies gathered inputs, the npm-squat-check.ts shape). INVARIANT:default.local_path: nullis the DESIGNED fallback topology (write-through nests undersync.repo_path), NOT an error — a null pointer warns ONLY when it provably breaks something: the fallback repo is another source's own working tree (the leak-guard collision: every unscoped default write-through silently skipped), or default has file-backed pages and no resolvable root. It also warns when a setlocal_path, or behind a null onesync.repo_path, is relative (not absolute on this host): sync refuses itsync_anchor_relative. Everything else (no pages, resolvable fallback, deliberate DB-only brain) is ok. The repair it names is the non-destructivegbrain sources set-path default <path>.src/core/disk-walk.ts—walkBrainRepo(repoPath)returnsMap<slug, {size, mtimeMs}>from one recursivereaddirSync. Skips dot-dirs,node_modules, non-.mdfiles. Used bygbrain storage statusinstead of per-pageexistsSync + statSync(~400K syscalls on 200K-page brains → tens).src/core/file-resolver.ts— File resolution with fallback chain (local -> .redirect.yaml -> .redirect -> .supabase).src/core/frontmatter-recovery.ts—recoverFrontmatter(block)(RECOVERY_VERSION): rules touch only the suspect run at the parser's error mark, keep CRLF per line, and never rewrite, fold into or guess aPROTECTED_FRONTMATTER_KEYSkey or resolve a duplicatedIDENTITY_FRONTMATTER_KEYSkey.quoteis safe;fold/dup/unclosedclassifyneeds_interpretationwith the proposed block kept.frontmatterKeyHazard(swallowed or pre-quoted protected keys),unclosedFenceProtectedKey,commentValueKeys. Tests:test/frontmatter-recovery.test.ts.src/core/git-head.ts— local git HEAD freshness probe forgbrain doctor.isSourceUnchangedSinceSync(localPath, lastCommit, opts?)returns true ifflocalPathis a git repo whose current HEAD matcheslastCommit; whenopts.requireCleanWorkingTreeis true also requires a clean working tree (mirrorsgbrain sync's force-walk gate atsync.ts:1075so doctor and sync agree on "is there work to do?").requireCleanWorkingTreeisboolean | 'ignore-untracked'— in'ignore-untracked'mode the clean probe runsgit status --porcelain --untracked-files=noso a quiet repo with stray untracked dirs (?? companies/,?? media/) is still "unchanged" (sync's incremental path keys off the commit diff and does not import untracked files by default — it counts them asuncommitteddrift with a stderr warning;--working-treeopts into importing them);GitCleanProbegains anignoreUntracked?second arg. Two probe seams (_setGitHeadProbeForTests,_setGitCleanProbeForTests) keep unit tests R2-compliant (nomock.module). UsesexecFileSyncwith array args so shell metachars inlocal_pathcannot escape to a shell (the test runs realexecFileSyncagainst'/nonexistent/$(touch <sentinel>)/repo'and asserts the sentinel is never created). Fail-open on every error (missing path, not a git repo, git not installed, timeout, NULL inputs, dirty-probe errored → false) so the caller falls back to its time-based check. The chunker-version-match check lives in the caller (doctor.ts) because it depends on engine state (sources.chunker_versionvsCHUNKER_VERSIONfromsrc/core/chunkers/code.ts). Pinned bytest/core/git-head.test.ts(incl. the shell-injection guard).src/core/git-remote.ts— SSRF-hardened git invocations for remote-sourcecloneRepo,pullRepo, andfetchRemote(repoPath, branch)(the sync cost-estimator's fetch-first path, with the same hardened flags). Exports two distinct flag constants becausegit's argv grammar treats them differently:GIT_SSRF_FLAGS(3-cconfig flags —http.followRedirects=false,protocol.file.allow=never,protocol.ext.allow=never) is global config, spread BEFORE the subcommand verb;GIT_SSRF_SUBCOMMAND_FLAGS = ['--no-recurse-submodules']is subcommand-scoped, spread AFTER the verb (before the verb, git exits 129).cloneRepoargv:git <GIT_SSRF_FLAGS> clone <GIT_SSRF_SUBCOMMAND_FLAGS> --depth=1 [--branch X] <url> <dir>;skipLfs(URL sources a remote caller adds;recloneIfMissingfollows theiradded_by_remote_caller) writeslfs.fetchexclude=*,core.hooksPath=/dev/nullandlfs.locksverify=falseinto the clone's config (LFS_OFF_CLONE_CONFIG, also used by the managed clone inpersistence/topology-filesystem.ts).pullRepoargv:git -C <dir> <durableSsrfFlags()> pull <GIT_SSRF_SUBCOMMAND_FLAGS> --ff-only—durableSsrfFlags(), not the hardcodedGIT_SSRF_FLAGS: identical-cflags exceptprotocol.file.allowhonors theGBRAIN_GIT_ALLOW_FILE_TRANSPORT=1escape hatch.pullRepo(repoPath, { timeoutMs?, signal? })runs git throughexecFileBounded, so the caller's event loop keeps running; an abortedsignalor thetimeoutMsdeadline (300 s by default) stops it, andisStoppedGitPull(err)separates that stop from a real git failure by reading theGitOperationErrorcause (ETIMEDOUT,ABORT_ERRorSIGTERM). Onlygit pullitself is signalled; thegit fetchand transport it spawned are not.fetchRemoteuses the same helper. Pinned bytest/git-remote.test.tsposition-anchored guard (argv.indexOf('--no-recurse-submodules') > argv.indexOf(verb)). Also exports the durability-side helpers that powergbrain sources harden/pull:GIT_ENV_AUTH(the no-prompt env minus the askpass/bin/falseoverrides, so an auth'd push/fetch can consult the repo's configured credential helper whileGIT_TERMINAL_PROMPT=0still fails fast on a missing credential),divergenceSafePull(repoPath, branch)(fetch +pull --rebase; returnsskipped_dirtyon a dirty tree,conflict_abortedon ANYpull --rebasefailure after up to two best-effortrebase --abortattempts, elseup_to_date/advanced),detectDefaultBranch(origin/HEAD → current branch →main),pushProbe(repoPath, branch)(authenticatedpush --dry-runthat proves push access and classifiesauth/protected/unreachable), andisWorkingTreeDirty. These auth'd paths route theirprotocol.file.allowthroughGBRAIN_GIT_ALLOW_FILE_TRANSPORT(defaultnever; set=1for self-hosted filesystem remotes), unlikecloneRepo, which still uses the hardcodedGIT_SSRF_FLAGSand stays strict.src/core/import-checkpoint.ts—loadCheckpoint(path, currentDir),saveCheckpoint(path, cp),resumeFilter(allFiles, dir, completed),clearCheckpoint(path),resolveImportTargetDir(dir), and theImportCheckpointtype. Payload:{schema_version: 1, owner: 'gbrain', kind: 'import', dir, completedPaths, timestamp};diris the absolute realpath of the import target, never the caller's CWD. Paths record successful/unchanged progress, not content identity; ordinaryrunImportrevalidates all current files viaimportFile's existing content-hash comparison rather than usingresumeFilter. Company-brain ingestion uses separate protected database checkpoints for an immutable approved manifest. The exported pure filter returns a path array and skips completed paths for company-brain manifest resume; by itself it is not proof that mutable file content is unchanged.loadCheckpointreturnsnullfor missing/malformed payloads, target mismatch, invalid path/timestamp fields, or incompatible producer metadata; absent producer fields in legacy path-set checkpoints remain accepted. Old positional checkpoints log a stderr diagnostic before discard.saveCheckpointsorts paths and atomically writes via.tmp+rename(); save/clear failures are non-fatal and silent. The caller supplies the checkpoint path viagbrainPath(), preservingGBRAIN_HOMEisolation. Pinned bytest/import-checkpoint.test.ts,test/import-resume.test.ts, andtest/import-json-stdout.test.ts.src/core/import-screen.ts—screenImportContent: the one content screen (published exemption, size, frontmatter hold, slug conflict, Tier 1: a fixable fence is admitted normalized, a residual refuses typed (coordinated) or warns (lenient); optional sanity reject;holdNoncanonicalPrivate:visibility_noncanonical) shared byimportFromContent, managed import and managed sync publication.contentRefusalErrorkeeps each site's wireerror;isContentRefusal(code, message)matches new codes and exact pre-upgrade strings, never capacity or transient refusals;contentRefusalFromReceiptrestores code, reason, key and line on receipt replies.PAGE_OVER_LIMIT_SUGGESTIONis the one next step of a page write over the page limit (put_page receipts andpage-prepare.ts): it names the limit and says only content over it becomes several pages. Tests:test/import-screen.test.ts,test/sync-frontmatter-recovery.test.ts,test/put-page-recoverable-frontmatter.test.ts. #6259 marker strip: quarantine cluster.src/core/import-file.ts— importFromFile + importFromContent (chunk + embed + tags). Every markdown import resolves and stampscontextual_retrieval_modeandcorpus_generationwith the canonical write,--no-embedincluded (#5621), so later embed passes reproduce the page's wrapping; a failed source-policy read fails the import unless the row or table is missing (SourceRowNotFoundError,isUndefinedTableError). Unchanged markdown or code content whose page is below the safe-chunk fence is re-sealed projection-only (direct imports install it; coordinatedprepareimports stay no-ops and queue asafe_chunk_resealprojection job), with no page write or admission. Freshly embedded chunks carryembedding_input_hashfor the tier they were built under. ThebeforeCommithook runs inside the guarded canonical transaction so a rejected file write rolls back its projections; optional legacy source-path repair uses a savepoint. Deferred importer embedding callbacks capture the committed text projection and indexing context, then install with an UPDATE-only revision/chunk/hash check. Tests:test/import-publication-guards.test.ts. Coordinatedprepareimports resolve and atomically stamp the page/source/global contextual wrapping mode even withnoEmbed:true; the durable outbox later embeds that revision. The existing paid-synopsis title fallback and mount trust gate remain in force, while embedding signatures only certify completed vectors.test/persistence-contextual-embedding.test.tscovers both engines, policy precedence, deferred provider execution, and a competing title replacement.importFromContentandimportCodeFilestamppages.embedding_signatureviasetPageEmbeddingSignature(slug, {sourceId, signature: currentEmbeddingSignature()})when the import actually embedded (not--no-embed) so a model/dims swap is detectable as stale;importCodeFileonly stamps when every chunk was freshly embedded this call (needsEmbedIndexes.length === chunks.length), mixed reuse-by-hash pages stay unstamped (reindex --code --force/embed --stalehandle those).importFromContentreconciles tags by provenance (tags.tag_source, migration v175): frontmatter tags go throughaddTag(..., { tagSource: 'frontmatter' }), and a row still marked 'frontmatter' whose tag left the frontmatter is deleted in the import transaction. Every otheraddTagstamps 'added' (add_tag, enrichment, the code importer) and is never import-deleted, sogbrain reindex --markdownkeeps enrichment tags; legacy NULL rows are adopted only while the frontmatter still lists them; prepared (managed) imports keep add-only tags, matching the union their canonical file renders. Pinned bytest/reindex-preserve-tags.test.ts,test/import-frontmatter-tag-removal.test.ts+test/import-file.test.ts. identity decisions live insrc/core/import-identity.ts(decideImportIdentity,collidingSlugOwner; pure reads, the importer applies them). The dedup pre-check callsengine.findDuplicatePage?.(sourceId, {hash, frontmatterId, excludeSlug})(optional?so test doubles compile; the caller's own slug never matches, and afrontmatter.idmatch ranks ahead of a bare hash match). Posture: MOVE when thefrontmatter.idmatches and the other page's OWN origin proves it moved (#5675): that origin is thefile://pathimportFromFilerecords inpages.source_uri(never replacing non-file provenance), else the source's configured root (local_path, or the default source's legacysync.repo_path). An origin that still exists moves only when it is this very file under another relative path (overlapping roots converge); a gone origin needs this file under that same root, and differing content also needs the same file name or title, so a missing path under another root, or a new note reusing a deleted note's template id, never renames a live page.updateSlugcarries the row (page id, links, facts incl.entity_slug/source_markdown_slug,page_aliases, timeline, plus a rename alias) and the new content imports onto it, so a full sync's delete-reconcile has nothing live to remove; SKIP only when the id AND the content (content_hash, or title and body for a row written outside the importer) both match while the recorded file still exists (overlapping ingest roots); IMPORT with a warning when the id matches but content differs (templates, copy-paste; an edit is never frozen by the other page); WARN-ALWAYS on a bare content_hash collision; FAIL CLOSED on lookup error; bypass via--force-rechunk. Content-only callers (put_page, transcripts) never move a page. Soft-deleted pages excluded at the engine layer so tombstones don't block legitimate re-imports under new slugs. Slug collisions: when another live file (existing.source_path, realpath-distinct) already owns the slug, the incoming file is skipped withskip_reason: 'slug_collision'and a stderr warning, unless the incoming file is named exactly<slug>.md(the file the link extractor reads for that slug), so two spellings never overwrite each other. An embedding failure never blocks the text write: chunks commit with NULL vectors, no embedding signature is stamped, the result carriesembedding_deferred: true, and the stale sweep embeds them later (a code file whose embed failed is not stamped either). An inline markdown re-import embeds only chunks whose embedding input changed:planEmbeddingReuse(keyed on chunk source + exact text) reuses a stored vector when the old index is sealed (requireSafeChunks), the page'sembedding_signature, contextual mode,corpus_generationand (under the title wrapper) sanitized title are unchanged, and a fenced page has a recorded input (#6961);--force-rechunkand post-commit-embedding imports reuse nothing (test/import-markdown-embedding-reuse.test.ts); identical rows stay put (import-chunk-reuse.ts). Offset-less frontmatter datetimes are read in the brain'sbrain.timezone(IANA, validated bygbrain config set; unset or invalid = UTC; the YAML parser tags naive timestamps withNAIVE_DATETIMEso the wall-clock reading survives), while date-only values stay UTC calendar dates (test/effective-date-brain-timezone.test.ts).effective_datefor an undated page falls back tofallbackCreatedAt(stored fallback date, else the earliest of the file's birth/modification time and — whensync.git_first_commit_datesis on — its git first-commit date viafileTimes, else now;src/core/git-first-commit.tsmaps paths in onegit log --diff-filter=Apass perrunImport, skipping shallow clones;test/effective-date-git-first-commit.test.ts), never the latest write. Pinned bytest/import-dedup-frontmatter-id.test.ts,test/import-identity-move.test.ts,test/import-slug-collision.test.ts,test/import-embed-outage.test.tsandtest/effective-date-calendar.test.ts.importFromContentis the narrow waist every ingest path passes through (gbrain import,gbrain sync,put_pageMCP,/ingestwebhook). It runs a three-tier content-quality disposition viaassessContentSanityfromsrc/core/content-sanity.tsBEFORE chunking: (1) high-confidence junk (built-in Cloudflare/CAPTCHA interstitial patterns + operator literals) → QUARANTINE (stamps thequarantinefrontmatter marker, writes ZERO chunks, hides the page from search) OR REJECT (throw → sync-failure) whencontent_sanity.junk_dispositionisreject; (2) fuzzy markup-heavy (prose-vs-markup ratio abovecontent_sanity.max_markup_ratio, warn-tier byte window, code pages exempt) →content_flag:markup_heavymarker (page stays fully searchable, marker rides search results + get_page to warn the agent); (3) oversize →embed_skipsoft-block viabuildEmbedSkipMarker()PLUS acontent_flag:oversizedmarker, AND deletes any pre-existing chunks in the same transaction so search can't surface stale chunks. Gate-owned markers (quarantine,content_flag) are STRIPPED from untrusted (remote MCP,ctx.remote !== false) frontmatter so a write-scoped client can't hide pages or forge the warning channel; markers are excluded fromcontent_hashso a flagged page doesn't re-embed every sync, but anembed_skiptransition (present vs absent) defeats both unchanged fast paths so a threshold change rebuilds or removes chunks without--force. A trusted import whose content the gate no longer blocks drops an incomingembed_skip(and acontent_flag) whose reason isoversized; other skip reasons, quarantined pages and the sanity bypass keep them.gbrain importhonorserrors > 0for non-zero exit.classifyErrorCodeinsrc/core/sync.tsrecognizes thePAGE_JUNK_PATTERNcode so sync-failures.jsonl grouping bins these.extractEntityRefs(canonical; matches both[Name](../people/slug)markdown links and Obsidian[[people/slug|Name]]wikilinks),extractPageLinks,inferLinkTypeheuristics (attended/works_at/invested_in/founded/advises/source/mentions),parseTimelineEntries,isAutoLinkEnabledconfig helper. Link candidates match any dir-shaped path (existence-checked at persist). Used by extract.ts, operations.ts auto-link post-hook, and backlinks.ts. Pinned bytest/import-file-content-sanity.test.ts.importImageFilerecordssource_pathon every image page and skips an unchanged image only when its index is complete for the run: a visual vector when embedding is on, and OCR (ocr_status: 'done'in frontmatter, or legacy stored OCR text) when OCR is enabled, so an image first imported under--no-embedor an OCR skip is rebuilt on its next import (test/import-image-retry.test.ts).importCodeFilewritessource_path: relativePathon every code page (the same repo-relative path markdown imports record) so the full-sync reconcile — which only considerssource_path IS NOT NULLrows — can retire a deleted code file's page;putPageCOALESCEs the column, so rows imported before this keep NULL until the file changes,sync --force, orgbrain reindex-code --force. A frontmatterslug:that would become the page identity and ends in.md/.mdxis held asfrontmatter_slug_conflictunless that exact (source_id, slug) page is live (persistence/suffixed-slug.ts).src/core/link-source-check-repair.ts— schema-drift self-heal for thelinks_link_source_checkCHECK constraint (third instance of thetimeline-dedup-repair.ts/pages-upsert-arbiter.tsclass). Migration v114 openedlink_sourcefrom a closed allowlist to the kebab-case gate; the migrator trusts the version ledger, so a brain stamped >= 114 whose live constraint reverted to the pre-v114 allowlist (drifted restore, manual DDL) rejects every kebab provenance write (atom-provenance,concept-provenance) while the ledger reads current.LINK_SOURCE_KEBAB_REis the ONE exported copy of the regex (a drift-guard test pins it to the literal in migrate.ts v114,schema.sql,pglite-schema.ts).checkLinkSourceCheck(engine)probespg_constraint(pg_get_constraintdef+convalidated) and classifies the drift asabsent/wrong_def/not_validated(read-only; powers thelinks_link_source_checkdoctor check indoctor/checks/core-health.ts, whose severity follows what writes do: onlywrong_defrejects kebab writes → fail;absent/not_validatedstill accept them → warn).repairLinkSourceCheck(engine)first COUNTs rows that fail the gate and returnsreason: 'violations'WITHOUT any DDL when there are any (the prior constraint survives; rows are never touched; a brain with a bad row never pays for a failing ALTER at every engine open), then restores v114's definition mirroring the migration's engine split: Postgres runs DROP +ADD ... NOT VALIDin oneengine.transaction(atomic, no scan) andVALIDATE CONSTRAINTas a separateengine.runMigrationoutside it (SHARE UPDATE EXCLUSIVE, never a plain ADD's ACCESS EXCLUSIVE + full-table scan), with anot_validateddrift getting the VALIDATE only; PGLite keeps the one-shot DROP+ADD transaction. A DDL failure re-counts violators (a row written between probe and ALTER) and rethrows when there are none.LINK_SOURCE_GATE_MIGRATION_VERSION(114) is the ledger gaterunMigrationsapplies before calling it. Pinned bytest/link-source-check-repair.test.ts(PGLite, incl. a recording-engine assertion that violators trigger no DDL and that a sub-114 ledger never probes) and the DATABASE_URL-gatedtest/e2e/link-source-check-repair-postgres.test.ts(two-phase DDL sequence on real Postgres).src/core/markdown.ts— Frontmatter parsing + body splitter.coerceFrontmatterString(v)coerces a non-stringtitle/slug/typeto a deterministic string at parse time so a YAML-typed value never reaches.toLowerCase()and throws (title: 2024-06-01parses as aDate,title: 1458as a number, and a throw would block the sync bookmark from advancing); aDatebecomes its UTC ISO date (2024-06-01, machine-independent and matching the on-disk token, unlikeString(date)),null/undefinedbecome'', everything else usesString().splitBodyrequires an explicit timeline sentinel (<!-- timeline -->,--- timeline ---, or---immediately before## Timeline/## History). Plain---in body text is a markdown horizontal rule, not a separator.inferTypeauto-types/wiki/analysis/→ analysis,/wiki/guides/→ guide,/wiki/hardware/→ hardware,/wiki/architecture/→ architecture,/writing/→ writing (plus existing people/companies/deals/etc heuristics).resolveSourceLocalFilePathmaps Git-root-relativepages.source_pathvalues into a source whoselocal_pathscopes a repo subdirectory; it finds the Git root with filesystem checks only, strips the exact root-relative scope, rejects unsafe/non-markdown paths, and when given a slug it tolerates historical basename-relativesource_pathrows by checking the slug directory only after the direct path is absent. It leaves write containment to the caller. After its pre-quote pass, a block the strict parse refuses goes torecoverFrontmatter; onlyquoterecoveries are applied. Undervalidate, YAML_PARSE stays inerrors(location-only message,recoverableplus a content-freerecoveryrecord), advisories go towarnings(FRONTMATTER_RECOVERED,FRONTMATTER_COMMENT_VALUE), andrecoverycarries interpretive, protected-key and identity-key findings.HOLD_CODESandclassifyImportHold(parsed, ctx)define the ingestion hold set once;isFrontmatterHoldMessagerecognizes its exact messages. Tests:test/frontmatter-recovery.test.tsStreamed form (parseMarkdownHead+parsedMarkdownFields):page-body/body-scan.ts.src/core/quarantine.ts— the two frontmatter markers the content-quality gate writes, sibling ofsrc/core/embed-skip.ts(same JSONB-object marker and?existence check on both engines; no migration).quarantine(keyQUARANTINE_KEY) HIDES: set ONLY for high-confidence junk, writes zero chunks, excluded from search viaquarantineFilterFragment(pageAlias)/QUARANTINE_FILTER_FRAGMENT(thep-aliased constant), the single source of truthbuildVisibilityClausecalls so the search filter and marker key can't drift.content_flag(keyCONTENT_FLAG_KEY) WARNS, does NOT hide: set for fuzzy markup-heavy / oversize, page stays searchable, marker is READ INTO search/get_page output — deliberately NO SQL filter fragment. Three markers, three reasons:embed_skip= oversized-but-clean,quarantine= junk hidden,content_flag= odd-examine-still-here; a page can carry more than one (oversize → embed_skip + content_flag:oversized) and each clears independently. ExportsbuildQuarantineMarker/isQuarantined/filterOutQuarantined,buildContentFlagMarker/getContentFlag/hasContentFlag, plus the two key constants. Pinned bytest/quarantine.test.ts. #6259: quarantine cluster. A quarantined page is skipped by every derived-data scan (stale listing via the engine-sql stale predicate, NER, meeting timeline projection, file walks viaquarantinedSlugs, DB walks, the managed link derivation) and is not in thelinks_extraction_lagdenominator. Pinned bytest/quarantine-extraction.test.ts.src/core/repo-root.ts— SharedfindRepoRoot(startDir?): walks up fromstartDir(defaultprocess.cwd()) looking forskills/RESOLVER.md. Zero-dependency, imported bydoctor.tsandcheck-resolvable.ts; parameterizedstartDirmakes tests hermetic. Read-path / write-path split:autoDetectSkillsDir(shared, read+write-safe) has tier-0$GBRAIN_SKILLS_DIRoperator override ahead of the 4-tier chain.autoDetectSkillsDirReadOnlywraps it with a tier-5 install-path fallback that walks up fromfileURLToPath(import.meta.url)and gates onisGbrainRepoRootso unrelated repos can't false-positive. Read-path callers (doctor,check-resolvable,routing-eval) use the read-only variant; write-path callers (skillpack install,skillify scaffold,post-install-advisory) stay on the shared function so install-from-~can't retarget the bundled gbrainskills/instead of the user's workspace.SkillsDirSourcevariants'env_explicit','install_path';AUTO_DETECT_HINT_READ_ONLYdocuments the extra tier. The--fixsafety gate indoctor.ts+check-resolvable.tsrefuses auto-repair whendetected.source === 'install_path'.src/core/resolver-filenames.ts— central list of accepted routing filenames (RESOLVER.md,AGENTS.md). Shared byfindRepoRoot,check-resolvable, and skillpack install so every code path walks the same fallback chain.src/core/source-config-sql.ts+src/core/sources-load.ts— canonical recovery for non-objectsources.configvalues. The application reader unwraps nested JSON strings and merges recoverable array fragments left-to-right; the shared SQL expression mirrors that policy atomically for both engines, source config updates, archive/restore, and the paste-readysource_config_shapedoctor repair.localFederatedSourceIdsreads config through the same parser so stdio/CLI federation cannot silently disagree withsources list.sourceConfigHasRemoteUrluses that parser for autopilot pull policy, including PGLite's JSON-string config shape. Invalid fragments degrade to{}rather than throwing: each string layer goes throughgbrain_try_jsonb(text)(v263; jsonb or NULL, never raises), portable to Postgres 15 unlike theIS JSONit replaced (#7112).test/postgres15-sql-compat-7112.test.tspins the function on both engines and fails when Postgres 16+ only SQL appears insrc/. Pinned bytest/sources-load.test.ts,test/job-pull-policy.test.ts,test/list-all-sources.test.ts,test/local-federated-search-scope.test.ts,test/destructive-guard.test.ts, andtest/doctor-source-config-shape.test.ts.src/core/source-health.ts— per-source health metrics forgbrain sources status+ doctor'sfederation_health. Commit-relative staleness:newestCommitMs(localPath)= HEAD committer time viagit log -1 --format=%ct(fail-open null; NO working-tree mtime parsing — committed content only, robust against the porcelain-mtime bug farm);lagFromContentMs(contentMs|null, lastSyncMs|null, nowMs, ceilingSeconds?)= remote/column comparator (null lastSync → null; negative wall-clock → skew passthrough;contentMs <= lastSync→max(0, wallClock - ceiling); else/null-content → wall-clock). Core logic is pure; only the DEFAULTceilingSecondsreads env, viaresolveStalenessCeilingSeconds()(GBRAIN_STALENESS_CEILING_HOURSoverridingGBRAIN_SYNC_FRESHNESS_FAIL_HOURS, default 72) — pass the 4th arg for determinism. The caught-up branch RAMPS rather than returning a flat 0: a flat 0 meant a source whose clone vanished reported fresh forever (the dead-daemon class), while a hard step to the ceiling would tripfederation_health(24h) andsync_freshness(24h/72h) in the same instant and skip the warn tier — the alert-storm shape the caught-up branch exists to prevent. Ramping keeps the escalation ordered.computeAllSourceMetrics(engine, sources, {probeContent?}): LOCAL (probeContent:true,gbrain sources status) →probeSourceGitStateHEAD only (an uncommitted tracked edit is not lag)? 0 :the age of the reflog entry that moved HEAD offlast_commit, else of the commit notifier's persistedfirst_due_at, else wall-clock sincelast_sync_at(GBRA-133 2b.5,src/core/sync-pending.ts; the live commit-hash catches HEAD moving to an old-dated commit a timestamp compare would miss); REMOTE (default,federation_healthon the HTTP MCP path) →lagFromContentMs(row.newest_content_at, ...)raised tofirst_due_at's age, NO git subprocess (trust boundary). Tests:test/pathological/s-truthful-sync-status.test.ts+ its Postgres twin.commitTimeMs(localPath, sha)is thenewestCommitMssibling pinned to an arbitrary commit (committer time viagit show -s --format=%ct <sha>, fail-open null, execFileSync array args) — the resumable sync stampsnewest_content_atagainst its pinned target commit, not whatever HEAD raced to. Pinned bytest/source-health.test.ts.loadSyncFreshnessSources(engine)loads doctorsync_freshness's sync-eligible sources with their upstream observation columns, falling back for brains without them.src/core/source-id.ts— single canonical source_id validation, dependency-free by design (imported by both engines, cycle, source-resolver, sources-ops).SOURCE_ID_RE(strict: 1-32 lowercase alnum, interior hyphens only, no edge hyphens);isValidSourceId(boolean — for tiers that silently fall back: dotfile, brain_default) vsassertValidSourceId(throws — for tiers that must reject loudly: explicit--source,GBRAIN_SOURCE,cycleLockIdFor);ALL_SOURCES = '__all__'sentinel (deliberately NOT a valid id so it can never collide with a real source or leak into lock ids/path joins;sourceScopeOptstranslates it to an unscoped read for trusted local callers and keeps it unsatisfiable for remote callers, fail-closed);NO_SOURCES = '__none__'is the explicit no-source legacy-token grant, refused rather than translated.normalizeSourceInput/normalizeFederatedReadInputnormalize the/admin/api/register-clientHTTP body, mirroring the CLI's--source/--federated-readflags: omittedsource→'default'; omittedfederatedRead→undefinedsoregisterClientManualapplies its own[sourceId]default; present-but-invalid values throw so the route returns a structured 400 (invalid_source) instead of failing at INSERT time. Pinned bytest/register-client-source-normalize.test.ts.src/core/source-resolver.ts— 6-tier source resolution.resolveSourceWithTier(engine, explicit, cwd)returns{ source_id, tier: SourceTier, detail? }alongsideresolveSourceId()(unchanged).SOURCE_TIER_NAMES = ['flag', 'env', 'dotfile', 'local_path', 'sole_non_default', 'brain_default', 'seed_default'](7 entries; order matches priority). Tiersole_non_defaultslots betweenlocal_pathandbrain_default: when NOsources.defaultconfig is set AND exactly one registered source haslocal_pathAND isn't'default'AND the'default'source holds no active pages (the emptiness guard — the tier's charter is rescuing brains whose'default'is empty; when'default'carries an established corpus, auto-routing would hijack every bare write into the side-source, so the resolver falls through toseed_defaultand prints a one-line stderr notice naming both sides so the suppressed flip is diagnosable, sameGBRAIN_NO_SOLE_NON_DEFAULT_NUDGE=1suppression knob as the routing nudge; a failed pages probe on an exotic/legacy schema keeps the auto-route), auto-route to it; archived sources and the storage shelf (config.rolestorage_manifest) excluded (try/catch for pre-v34 brains); privatepickSoleNonDefaultSource(engine)shared by both resolver entry points so they cannot drift. ExportedformatSoleNonDefaultNudge(sourceId): string | nullbuilds the user-facing stderr nudge (null whenGBRAIN_NO_SOLE_NON_DEFAULT_NUDGE=1).resolveCliSyncSourceinsrc/commands/sync/run.tscallsresolveSourceWithTierunconditionally so the tier fires;src/commands/import.ts:96-128mirrors with the tier-gated nudge. Consumed bygbrain sources current,import --source-id,extract --source-id, and thesource_routing_healthdoctor check. Pinned bytest/source-resolver-with-tier.test.ts(withEnv()per test-isolation lint),test/source-resolver-sole-non-default.test.ts(20 cases incl. both-ways emptiness-guard + probe-failure fallback),test/sync-sole-non-default-routing.test.ts(3 PGLite cases driving realrunSync),test/pages-source-scoping-4329.test.ts(real-engine both-ways guard coverage). Also exportsnoGrantFederatedScope(engine, hasSourceGrant, sourceId), the widening decision transports share: returnslocalFederatedSourceIds(..., 'seed_default')ONLY whenhasSourceGrant === false(the legacy-bearer no-grant floor),undefinedfor a granted token, for an OAuth client (flagundefined— a falsy gate here would widen every OAuth client), and when the resolver throws (best-effort; the scalar scope stands rather than failing the request). Called bysrc/commands/serve-http.ts; pinned bytest/no-grant-federated-scope.test.ts(6 cases).explicitReadBinding(engine, sourceId, tier)(#5081) is the explicit-tier twin used by the stdio transport forGBRAIN_SOURCE(env) and.gbrain-source(dotfile) bindings:{ sourceId, via, sourceIds, optedOut }, wheresourceIdsis the same setlocalFederatedSourceIdscomputes (sharedfederatedSetFor, so an isolated anchor admits only itself) andoptedOutlistsfederated === falsesources for the denial hint;undefinedfor every other tier. Pinned bytest/explicit-read-admission-5081.test.ts. Unscoped default-write guard family (theseed_defaulttier is the only one that actually lands a write in'default'):assessDefaultWriteGuard(engine)→DefaultWriteAssessment { shouldGuard, defaultPages, nonDefaultPages, nonDefaultSources, failed? }— an unindexed full-pagesaggregate;shouldGuardwhen ≥1 non-default source holds pages AND non-default pages outnumber default's; a query failure returns the fail-open no-guard verdict stampedfailed: true, which cachers/latchers must not treat as settled.assessDefaultWriteGuardOnce(engine)is the per-engine WeakMap memo (arms on the first SUCCESSFUL assessment whatever its verdict, forgets a failed attempt so the next caller retries, coalesces concurrent callers;__resetDefaultWriteGuardMemois the test seam).assessUnscopedDefaultWrite(engine, tier, mutating)→{ warning, assessed }(assessed: falseonly when the aggregate failed);formatDefaultWriteWarning(a, sourceFlag?)/formatDefaultWriteRefusal(cmd, a)render the two surfaces;defaultWriteAllowedByEnv()is theGBRAIN_ALLOW_DEFAULT_WRITE=1escape hatch. Consumers:syncrefuses (dry-run warns),importwarns via the memo, MCP stdio'screateDefaultWriteAdvisoryprints once. Also exportsisResolverUserError(e)— the ONE predicate for this module's user-facing throws (Source "…" not found./not found or is archived.,Invalid --source value,Invalid GBRAIN_SOURCE value), consumed by dream.ts, agent.ts and code-scope.ts so a CLI command turns an unknown/archived source into a clean stderr line + exit 1 while anything else keeps propagating. A request snapshot serves tiers 4, 5.5 (its rows carry the 'default' emptiness probe,default_has_pages),assertSourceExistsand the federated set from one sources read, sent with the config table (resolveSourceWithTierreads tier 5's key beside the tier-4 listing) (GBRA-156).src/core/source-delete.ts—deleteSourceRow: every unmanaged source delete (sources remove/purge,sources_remove, expired-archive purge) deletes thesourcesrow, that incarnation'spersistence_source_bindingsrow and itsmanaged-synccursors inop_checkpoints(#8741) in one statement (neither has an FK tosources). #9068: that statement also runsremovedSourceScrubCtes(the managedremove/purgeinsource-lifecycle.tsruns them in its final transaction too), which delete the source'sretrieval_event_pages,retrieval_event_links,retrieval_feedbackandcontext_volunteer_eventsrows and strip fromeval_candidates.retrieved_slugseach slug no other source the candidate covers has a page for (retrieval_weightsandmention_gazetteer_entriescascade fromsources); a second statement runs them again, for a feedback write or capture that held a page row while the delete waited, unless a source with the same id exists again (so a re-created source keeps its rows). Pinned bytest/purge-scrub-followups-9068.test.ts. Other incarnations' bindings go togbrain repair orphan-bindings(src/core/persistence/orphan-bindings.ts, doctororphan_persistence_bindings). The unmanaged claim check (sync-authority.ts) and doctorunbound_sourcecount only the current incarnation's binding.EXPIRED_ARCHIVE_SQLis the one purge-eligibility predicate (unmanaged sweep, its per-row DELETE and the managedexpiredOnlypurge): both archive timestamps must be later than the epoch and the expiry past;UNVERIFIED_ARCHIVE_SQLlists archived rows with a missing or epoch timestamp, which the sweep reports blocked with restore-then-archive guidance, never purged. A source that still has pages is deleted only when the pages -> sources ON DELETE CASCADE fires on this brain (the same statement checks the foreign key and its delete trigger); otherwise nothing is deleted andsource_pages_remainis thrown (#7072,test/source-purge-stranded-pages-7072.test.ts); the expired-archive sweep reports the source inblockedwith that code. The managed remove and purge delete the pages themselves in bounded batches first (#7702/#8905).src/core/sources-ops.ts— Multi-source registration + clone-lifecycle ops (addSource,recloneIfMissing,defaultCloneDir,isOwnedClone,unownedHint). Reclone-ownership invariant (must-never-violate): gbrain may only delete/re-clone a clone it created, NEVER a user working tree.recloneIfMissingdeleteslocal_path, so it gates onisOwnedClone(src)and throws aSourceOpError('unmanaged_path', ...)BEFORE any filesystem op when ownership is unprovable — fail-closed. Ownership is proven byconfig.managed_clone === true(written byaddSource's--urlpath, covering default-location and--clone-dirclones) ORlocal_path === defaultCloneDir(id)(back-compat for pre-marker clones, via exact normalized-path equality, symlink-free). A row withremote_url+ an unownedlocal_path(a user-registered working tree, e.g.sources add --path) is refused untouched; re-add with--urlto regain auto-reclone. The reclone is EXDEV-safe: clone into a SIBLING temp oflocal_path(not the sharedclones/.tmp, which may sit on a different mount than a--clone-dirtarget), then swap (move old aside → move new in → drop old) solocal_pathis never left missing-and-unrecoverable; on swap failure the original is restored, and if restore fails the error names theasidepath so it's never reflexively deleted. A TOCTOU re-check re-confirms ownership immediately before the destructive move and rejects a symlink leaf swapped in after the entry check (symlink_escape).unownedHint(src, state)is the shared recovery message used by both the core error and thegbrain sync --sourceCLI error;gbrain sources restorespecial-casesunmanaged_pathto print "DB row restored; gbrain syncs this path read-only" instead of the misleading "try sync to recover" guidance.SourceOpErrorCodeincludesunmanaged_path. Pinned bytest/sources-ops.test.ts,test/sources-resync-recovery.test.ts.assertNoOverlappingPath(engine, id, path)is the ONE overlapping-path guard shared by every surface that binds alocal_path(addSource,gbrain sources set-path): a path equal to, nested inside, or enclosing another source'slocal_paththrowsSourceOpError('overlapping_path')— overlapping trees make sync/write-through attribute files to the wrong source, so no add or repair path may skip it. The guard compares by spelling AND by realpath (both the candidate and each siblinglocal_patharerealpathSync'd when they exist, fail-open to the spelling otherwise), so a symlink resolving into or over another source's tree cannot slip past it; the stored pointer and the error message keep the operator's spelling. #6946:isOwnedClone/defaultCloneDirlive insrc/core/url-clone.ts, re-exported here.src/core/sync-cost-gate.ts+sync-git.ts+sync-anchor.ts+sync-lock.ts+sync-reconcile.ts+sync-status-report.ts— six pure-function clusters behind thesrc/commands/sync.tsfaçade, which re-exports them;facadeExpansioninscripts/generate-flag-registry.tskeeps exactly these six (NOT the othersync-*siblings, which are ordinary deps) on the sync command's flag-scan surface.sync-cost-gate.ts: the inline-embed cost gate + token estimation forgbrain sync.sync-git.ts: git plumbing — invocation building, repo discovery, baseline-commit self-heal, path-containment guards, OS-relative paths normalized to Git slash form bygitRelativePath, and the delete/rename slug resolvers (resolveSlugByPathOrSourcePath— see its dedicated entry above — plus the verifiedresolveSlugsForRemovedPaths/resolveRemovedPathSlug).sync-anchor.ts: sync anchor + chunker-version state helpers (source-scoped vs legacy global-config storage).sync-lock.ts: the lock layer — typed lock-busy error, the rich busy message,--break-lockhandling, the partial-result envelope (performSyncitself stays in the façade).sync-reconcile.ts: full-sync reconcile planning (the mass-delete valve and ever-committed gate), with stored paths normalized before scope filtering, plus sync deadline/stall resolution (the default and env deadlines are progress-aware;syncWatchdogPlanandsyncDeadlineStopNoticebuild the watchdog options and its stdout stop notice — see theprocess-watchdog.tsentry).sync-status-report.ts: the per-source sync status report backinggbrain sources statusand theget_status_snapshotop. Its queue context is engine-aware: only an explicitly worker-backed surface may promise job deferral; otherwise non-interactive cost deferral returnsmanual_drain_requiredwith exact per-sourcegbrain embed --stale --source <id>commands and never writes or claims an embed-backfill row. GBRA-133 2b.3: a--no-pullestimate (estimateInlineNewTokens/CostGateContext.noPull) prices local HEAD and never fetches origin.sync-git.tsaddsgitAsync/discoverGitRootAsync/isDetachedHeadAsync, which classic sync preflight, finalize, the lossless delta, upstream observation and the source filesystem lock now use, so a resident sync spawns no synchronous Git.src/core/sync-delta.ts— the single "what changed since last_commit" helper, consumed by BOTHperformSyncInner(sync executor) andestimateInlineNewTokens(cost estimator) so the gate's dollar figure can't drift from what the sync imports.computeSyncDelta(repoPath, fromCommit, toCommit, {detachedManifest?, detached?})→{status:'ok', manifest}|{status:'unavailable', reason:'anchor_missing'|'diff_failed'}. Anchor reachability viagit cat-file -t(a gc'd bookmark isanchor_missing, but a present-but-non-ancestor bookmark is still diffed tree-to-tree), thengit diff --name-status -M from..toparsed bybuildSyncManifest; merges the detached working-tree manifest when detached (buildDetachedWorkingTreeManifest). NO dirty/untracked probe in the estimator — pricing dirty files would create phantom costs on a busy brain. The executor imports only the commit diff on attached HEADs BY DEFAULT, but counts uncommitted working-tree files (untracked + dirty) asSyncResult.uncommitteddrift and, with--working-tree/ configsync.include_working_tree, merges the working-tree manifest into the delta so attached repos can import uncommitted state (the estimator does not price that opt-in).execFileSyncarray-args (shell-injection safe), 30s / 100 MiB budget,GIT_OPTIONAL_LOCKS=0(git-env.tsGIT_READ_ENV: sync's Git reads never takeindex.lock). GST-2331: runs withHARDENED_GIT_ARGSandNO_LAZY_FETCH_ENV. Test seam_setGitRunnerForTests. Pinned bytest/sync-delta.test.ts. Classic sync reads the same delta as bytes instead:computeLosslessSyncDelta/buildLosslessWorkingTreeManifestrungit diff --raw -z -M(andls-files -z --others) into a Buffer andparseRawDiffZkeeps each name exactly as Git has it (no trim, no unquoting); a name that is not UTF-8 or holds a control character goes tounsupported(present) orgone(left the tree) instead of the manifest, and a gitlink (mode 160000) that appears goes togitlinks, never the manifest (seam_setGitBytesRunnerForTests). Managed discovery and the cost estimator keepcomputeSyncDelta. Pinned bytest/pathological/s-classic-byte-paths.test.ts.src/core/sync-byte-paths.ts— classic sync's byte-exact names (GBRA-133).classifyGitPathBytes(strict UTF-8 with the BOM kept, no[\x00-\x1f\x7f], elsenot_utf8/control_character); theunsupported_pathhold keyencodeBytePathKey(/gbrain-bytes/+ the path with each byte outside a printable UTF-8 character, and%, as%XX; Git never emits a leading/, so it never equals a path) anddecodeBytePathKey(canonical keys only, else null);displayBytePath(C escapes, 200-character cap);bytePathItemId(first 16 hex of the bytes' sha256);bytePathRenameCommand(printf octal escapes piped NUL-terminated toxargs -0 git mv, plain ASCII);bytePathHoldGone(lstat of the exact bytes; null for an ordinary key), read bycommands/sync/holds.tsre-screen and full-sync settle;unsupportedPathHoldFix, dispatched bygitHoldFix(ask_user rename, argv a read-onlysources status, thensync --no-pull).src/commands/sync/unsupported-paths.ts— classic sync's routing of the lossless delta's extras:selectBytePathsapplies the manifest's scope / exclude / syncability filters (name probed with U+FFFD for bad bytes and_for control characters) and makes paths mode-relative;holdUnsupportedPathswrites eachunsupported_pathhold (writeGitHold, mode legacy, slug and page null, never gating the bookmark), schedules the holds ofgonenames to clear and prints onegitlink_not_followedline;gitlinkFieldsputsgitlinks_not_followedon the result (declared onSyncResultby module augmentation here) for the run that advances past them.