Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript
57.7 KB
Raw Blame

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. Exports isoWeek(d), isoWeekFilename(prefix, now?), resolveAuditDir() (honors GBRAIN_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 its compute<X>AuditFilename thin 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-commit auto-push safety net (never committed — a pulled commit can't rewrite executed code next to the token; installed into the active core.hooksPath dir and excluded via .git/info/exclude when that dir is tracked), a committed scripts/brain-commit-push.sh delegating to gbrain git commit-push (src/core/git/commit-push.ts, #6530; guide docs/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 running gbrain 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 (acceptPat from --pat-file/GBRAIN_GITHUB_PAT, warns on loose perms; reuses an existing repo-local credential.helper, else a 0600 store wired via repo-local config); the token is redacted everywhere via redactSecretsInText and never enters the repo, remote URL, logs, or DurabilityReport. unhardenBrainRepo removes the cron/hook/credential wiring (ownership-fingerprinted); sources remove runs 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 on sources add --url ... --pat-file for managed clones (--no-harden opts out). sources pull --path is dispatched in src/cli.ts BEFORE connectEngine so 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) and commitWriteThroughFile(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; action only labels the subject (gbrain: <action> <slug>; 'delete write-through' for removals). isDurabilityHardenedAsync(repoPath) is the owners' non-blocking probe (#6210: rejects git_unavailable when unsure); it and the persistence Git runner (effect-git.ts) spawn through execFileBounded (defined in the import-free src/core/bounded-child-exec.ts and re-exported here; git-remote.ts pullRepo shares 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:test expect().resolves/.rejects re-enters the event loop; an unbounded wait there stranded disposePersistenceConsumer and 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_commit checks the exact refs/heads/<branch> at every effective push URL, fetches each advertised tip without writing FETCH_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, logging ok-already-on-remote on confirmation; getLastPushOutcome recognizes it as success. Existing unmanaged installations must rerun gbrain 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 path git ls-tree HEAD and git ls-files -v with optional locks off) and returns file_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). classicFileHoldFix is gitHoldFix's builder for both codes: the user's step for a symlink or permission, ask_user between restore and committing the deletion for an absent file; <checkout> is an inputs placeholder. Pinned by test/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 by holdUnreadableRenames in src/commands/sync/holds.ts and decided again by redecideUnreadableRenames when the file changes) and rename_reconcile_failed (S-67; the renames.ts reconcile 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 by test/pathological/s-51-rename-identity-unreadable.test.ts and test/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 by test/content-sanity-literals.test.ts.

  • src/core/content-sanity.ts — pure assessor for the content-sanity defense. assessContent(content, opts): SanityVerdict returns one of ok | warn_oversize | hard_block_junk_pattern | soft_block_oversize with {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 via loadOperatorLiterals() from src/core/content-sanity-literals.ts. ContentSanityBlockError tagged class is the typed throw shape every wrapper site (gbrain import, put_page MCP op, gbrain sync, /ingest webhook) catches via the existing exception flow. The bytes-parity contract pins Buffer.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=1 is the loud-stderr kill-switch). assessContentSanity(opts): SanityAssessment returns the three-tier disposition (shouldQuarantine / shouldFlag + reason/detail) consumed by importFromContent and gbrain quarantine scan; adds the fuzzy prose-vs-markup ratio pass (markup chars / total above max_markup_ratio; code pages exempt; gated by prose_check_enabled) on top of the byte + junk-pattern passes. Three more knobs: content_sanity.junk_disposition (quarantine default | reject; no env override — a destructive flip belongs in explicit config), content_sanity.max_markup_ratio (0.85, env GBRAIN_MAX_MARKUP_RATIO, clamped (0,1]), content_sanity.prose_check_enabled (true). Pinned by test/content-sanity.test.ts. Per-pattern opt-out without the kill-switch: content_sanity.disabled_patterns names built-in junk patterns to skip (a JSON array ["access_denied"] or a comma list access_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 (exported FRONTMATTER_SCHEMA) with existing scalar types (a calendar-invalid timestamp such as 2024-02-30 stays a string instead of rolling over to March 1), sanitizes parser errors, and keeps body text opaque. loadBoundedYaml is the only js-yaml load call 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 throws YamlAliasBoundError (js-yaml-shaped reason and mark at the first alias) past text length + MAX_YAML_ALIAS_EXPANSION (65,536), so an alias bomb is a YAML_PARSE / invalid_frontmatter refusal 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 — pure assessDefaultSourcePath(input) verdict for the default_source_local_path doctor check (no DB/FS access — caller supplies gathered inputs, the npm-squat-check.ts shape). INVARIANT: default.local_path: null is the DESIGNED fallback topology (write-through nests under sync.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 set local_path, or behind a null one sync.repo_path, is relative (not absolute on this host): sync refuses it sync_anchor_relative. Everything else (no pages, resolvable fallback, deliberate DB-only brain) is ok. The repair it names is the non-destructive gbrain sources set-path default <path>.

  • src/core/disk-walk.ts — walkBrainRepo(repoPath) returns Map<slug, {size, mtimeMs}> from one recursive readdirSync. Skips dot-dirs, node_modules, non-.md files. Used by gbrain storage status instead of per-page existsSync + 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 a PROTECTED_FRONTMATTER_KEYS key or resolve a duplicated IDENTITY_FRONTMATTER_KEYS key. quote is safe; fold/dup/unclosed classify needs_interpretation with 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 for gbrain doctor. isSourceUnchangedSinceSync(localPath, lastCommit, opts?) returns true iff localPath is a git repo whose current HEAD matches lastCommit; when opts.requireCleanWorkingTree is true also requires a clean working tree (mirrors gbrain sync's force-walk gate at sync.ts:1075 so doctor and sync agree on "is there work to do?"). requireCleanWorkingTree is boolean | 'ignore-untracked' — in 'ignore-untracked' mode the clean probe runs git status --porcelain --untracked-files=no so 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 as uncommitted drift with a stderr warning; --working-tree opts into importing them); GitCleanProbe gains an ignoreUntracked? second arg. Two probe seams (_setGitHeadProbeForTests, _setGitCleanProbeForTests) keep unit tests R2-compliant (no mock.module). Uses execFileSync with array args so shell metachars in local_path cannot escape to a shell (the test runs real execFileSync against '/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_version vs CHUNKER_VERSION from src/core/chunkers/code.ts). Pinned by test/core/git-head.test.ts (incl. the shell-injection guard).

  • src/core/git-remote.ts — SSRF-hardened git invocations for remote-source cloneRepo, pullRepo, and fetchRemote(repoPath, branch) (the sync cost-estimator's fetch-first path, with the same hardened flags). Exports two distinct flag constants because git's argv grammar treats them differently: GIT_SSRF_FLAGS (3 -c config 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). cloneRepo argv: git <GIT_SSRF_FLAGS> clone <GIT_SSRF_SUBCOMMAND_FLAGS> --depth=1 [--branch X] <url> <dir>; skipLfs (URL sources a remote caller adds; recloneIfMissing follows their added_by_remote_caller) writes lfs.fetchexclude=*, core.hooksPath=/dev/null and lfs.locksverify=false into the clone's config (LFS_OFF_CLONE_CONFIG, also used by the managed clone in persistence/topology-filesystem.ts). pullRepo argv: git -C <dir> <durableSsrfFlags()> pull <GIT_SSRF_SUBCOMMAND_FLAGS> --ff-only — durableSsrfFlags(), not the hardcoded GIT_SSRF_FLAGS: identical -c flags except protocol.file.allow honors the GBRAIN_GIT_ALLOW_FILE_TRANSPORT=1 escape hatch. pullRepo(repoPath, { timeoutMs?, signal? }) runs git through execFileBounded, so the caller's event loop keeps running; an aborted signal or the timeoutMs deadline (300 s by default) stops it, and isStoppedGitPull(err) separates that stop from a real git failure by reading the GitOperationError cause (ETIMEDOUT, ABORT_ERR or SIGTERM). Only git pull itself is signalled; the git fetch and transport it spawned are not. fetchRemote uses the same helper. Pinned by test/git-remote.test.ts position-anchored guard (argv.indexOf('--no-recurse-submodules') > argv.indexOf(verb)). Also exports the durability-side helpers that power gbrain sources harden/pull: GIT_ENV_AUTH (the no-prompt env minus the askpass /bin/false overrides, so an auth'd push/fetch can consult the repo's configured credential helper while GIT_TERMINAL_PROMPT=0 still fails fast on a missing credential), divergenceSafePull(repoPath, branch) (fetch + pull --rebase; returns skipped_dirty on a dirty tree, conflict_aborted on ANY pull --rebase failure after up to two best-effort rebase --abort attempts, else up_to_date/advanced), detectDefaultBranch (origin/HEAD → current branch → main), pushProbe(repoPath, branch) (authenticated push --dry-run that proves push access and classifies auth/protected/unreachable), and isWorkingTreeDirty. These auth'd paths route their protocol.file.allow through GBRAIN_GIT_ALLOW_FILE_TRANSPORT (default never; set =1 for self-hosted filesystem remotes), unlike cloneRepo, which still uses the hardcoded GIT_SSRF_FLAGS and stays strict.

  • src/core/import-checkpoint.ts — loadCheckpoint(path, currentDir), saveCheckpoint(path, cp), resumeFilter(allFiles, dir, completed), clearCheckpoint(path), resolveImportTargetDir(dir), and the ImportCheckpoint type. Payload: {schema_version: 1, owner: 'gbrain', kind: 'import', dir, completedPaths, timestamp}; dir is the absolute realpath of the import target, never the caller's CWD. Paths record successful/unchanged progress, not content identity; ordinary runImport revalidates all current files via importFile's existing content-hash comparison rather than using resumeFilter. 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. loadCheckpoint returns null for 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. saveCheckpoint sorts paths and atomically writes via .tmp + rename(); save/clear failures are non-fatal and silent. The caller supplies the checkpoint path via gbrainPath(), preserving GBRAIN_HOME isolation. Pinned by test/import-checkpoint.test.ts, test/import-resume.test.ts, and test/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 by importFromContent, managed import and managed sync publication. contentRefusalError keeps each site's wire error; isContentRefusal(code, message) matches new codes and exact pre-upgrade strings, never capacity or transient refusals; contentRefusalFromReceipt restores code, reason, key and line on receipt replies. PAGE_OVER_LIMIT_SUGGESTION is the one next step of a page write over the page limit (put_page receipts and page-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 stamps contextual_retrieval_mode and corpus_generation with the canonical write, --no-embed included (#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; coordinated prepare imports stay no-ops and queue a safe_chunk_reseal projection job), with no page write or admission. Freshly embedded chunks carry embedding_input_hash for the tier they were built under. The beforeCommit hook 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. Coordinated prepare imports resolve and atomically stamp the page/source/global contextual wrapping mode even with noEmbed: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.ts covers both engines, policy precedence, deferred provider execution, and a competing title replacement. importFromContent and importCodeFile stamp pages.embedding_signature via setPageEmbeddingSignature(slug, {sourceId, signature: currentEmbeddingSignature()}) when the import actually embedded (not --no-embed) so a model/dims swap is detectable as stale; importCodeFile only stamps when every chunk was freshly embedded this call (needsEmbedIndexes.length === chunks.length), mixed reuse-by-hash pages stay unstamped (reindex --code --force / embed --stale handle those). importFromContent reconciles tags by provenance (tags.tag_source, migration v175): frontmatter tags go through addTag(..., { tagSource: 'frontmatter' }), and a row still marked 'frontmatter' whose tag left the frontmatter is deleted in the import transaction. Every other addTag stamps 'added' (add_tag, enrichment, the code importer) and is never import-deleted, so gbrain reindex --markdown keeps 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 by test/reindex-preserve-tags.test.ts, test/import-frontmatter-tag-removal.test.ts + test/import-file.test.ts. identity decisions live in src/core/import-identity.ts (decideImportIdentity, collidingSlugOwner; pure reads, the importer applies them). The dedup pre-check calls engine.findDuplicatePage?.(sourceId, {hash, frontmatterId, excludeSlug}) (optional ? so test doubles compile; the caller's own slug never matches, and a frontmatter.id match ranks ahead of a bare hash match). Posture: MOVE when the frontmatter.id matches and the other page's OWN origin proves it moved (#5675): that origin is the file:// path importFromFile records in pages.source_uri (never replacing non-file provenance), else the source's configured root (local_path, or the default source's legacy sync.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. updateSlug carries 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 with skip_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 carries embedding_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's embedding_signature, contextual mode, corpus_generation and (under the title wrapper) sanitized title are unchanged, and a fenced page has a recorded input (#6961); --force-rechunk and 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's brain.timezone (IANA, validated by gbrain config set; unset or invalid = UTC; the YAML parser tags naive timestamps with NAIVE_DATETIME so the wall-clock reading survives), while date-only values stay UTC calendar dates (test/effective-date-brain-timezone.test.ts). effective_date for an undated page falls back to fallbackCreatedAt (stored fallback date, else the earliest of the file's birth/modification time and — when sync.git_first_commit_dates is on — its git first-commit date via fileTimes, else now; src/core/git-first-commit.ts maps paths in one git log --diff-filter=A pass per runImport, skipping shallow clones; test/effective-date-git-first-commit.test.ts), never the latest write. Pinned by test/import-dedup-frontmatter-id.test.ts, test/import-identity-move.test.ts, test/import-slug-collision.test.ts, test/import-embed-outage.test.ts and test/effective-date-calendar.test.ts. importFromContent is the narrow waist every ingest path passes through (gbrain import, gbrain sync, put_page MCP, /ingest webhook). It runs a three-tier content-quality disposition via assessContentSanity from src/core/content-sanity.ts BEFORE chunking: (1) high-confidence junk (built-in Cloudflare/CAPTCHA interstitial patterns + operator literals) → QUARANTINE (stamps the quarantine frontmatter marker, writes ZERO chunks, hides the page from search) OR REJECT (throw → sync-failure) when content_sanity.junk_disposition is reject; (2) fuzzy markup-heavy (prose-vs-markup ratio above content_sanity.max_markup_ratio, warn-tier byte window, code pages exempt) → content_flag:markup_heavy marker (page stays fully searchable, marker rides search results + get_page to warn the agent); (3) oversize → embed_skip soft-block via buildEmbedSkipMarker() PLUS a content_flag:oversized marker, 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 from content_hash so a flagged page doesn't re-embed every sync, but an embed_skip transition (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 incoming embed_skip (and a content_flag) whose reason is oversized; other skip reasons, quarantined pages and the sanity bypass keep them. gbrain import honors errors > 0 for non-zero exit. classifyErrorCode in src/core/sync.ts recognizes the PAGE_JUNK_PATTERN code so sync-failures.jsonl grouping bins these. extractEntityRefs (canonical; matches both [Name](../people/slug) markdown links and Obsidian [[people/slug|Name]] wikilinks), extractPageLinks, inferLinkType heuristics (attended/works_at/invested_in/founded/advises/source/mentions), parseTimelineEntries, isAutoLinkEnabled config 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 by test/import-file-content-sanity.test.ts. importImageFile records source_path on 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-embed or an OCR skip is rebuilt on its next import (test/import-image-retry.test.ts). importCodeFile writes source_path: relativePath on every code page (the same repo-relative path markdown imports record) so the full-sync reconcile — which only considers source_path IS NOT NULL rows — can retire a deleted code file's page; putPage COALESCEs the column, so rows imported before this keep NULL until the file changes, sync --force, or gbrain reindex-code --force. A frontmatter slug: that would become the page identity and ends in .md/.mdx is held as frontmatter_slug_conflict unless that exact (source_id, slug) page is live (persistence/suffixed-slug.ts).

  • src/core/link-source-check-repair.ts — schema-drift self-heal for the links_link_source_check CHECK constraint (third instance of the timeline-dedup-repair.ts / pages-upsert-arbiter.ts class). Migration v114 opened link_source from 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_RE is 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) probes pg_constraint (pg_get_constraintdef + convalidated) and classifies the drift as absent / wrong_def / not_validated (read-only; powers the links_link_source_check doctor check in doctor/checks/core-health.ts, whose severity follows what writes do: only wrong_def rejects kebab writes → fail; absent / not_validated still accept them → warn). repairLinkSourceCheck(engine) first COUNTs rows that fail the gate and returns reason: '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 VALID in one engine.transaction (atomic, no scan) and VALIDATE CONSTRAINT as a separate engine.runMigration outside it (SHARE UPDATE EXCLUSIVE, never a plain ADD's ACCESS EXCLUSIVE + full-table scan), with a not_validated drift 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 gate runMigrations applies before calling it. Pinned by test/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-gated test/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-string title/slug/type to a deterministic string at parse time so a YAML-typed value never reaches .toLowerCase() and throws (title: 2024-06-01 parses as a Date, title: 1458 as a number, and a throw would block the sync bookmark from advancing); a Date becomes its UTC ISO date (2024-06-01, machine-independent and matching the on-disk token, unlike String(date)), null/undefined become '', everything else uses String(). splitBody requires an explicit timeline sentinel (<!-- timeline -->, --- timeline ---, or --- immediately before ## Timeline/## History). Plain --- in body text is a markdown horizontal rule, not a separator. inferType auto-types /wiki/analysis/ → analysis, /wiki/guides/ → guide, /wiki/hardware/ → hardware, /wiki/architecture/ → architecture, /writing/ → writing (plus existing people/companies/deals/etc heuristics). resolveSourceLocalFilePath maps Git-root-relative pages.source_path values into a source whose local_path scopes 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-relative source_path rows 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 to recoverFrontmatter; only quote recoveries are applied. Under validate, YAML_PARSE stays in errors (location-only message, recoverable plus a content-free recovery record), advisories go to warnings (FRONTMATTER_RECOVERED, FRONTMATTER_COMMENT_VALUE), and recovery carries interpretive, protected-key and identity-key findings. HOLD_CODES and classifyImportHold(parsed, ctx) define the ingestion hold set once; isFrontmatterHoldMessage recognizes its exact messages. Tests: test/frontmatter-recovery.test.ts Streamed form (parseMarkdownHead + parsedMarkdownFields): page-body/body-scan.ts.

  • src/core/quarantine.ts — the two frontmatter markers the content-quality gate writes, sibling of src/core/embed-skip.ts (same JSONB-object marker and ? existence check on both engines; no migration). quarantine (key QUARANTINE_KEY) HIDES: set ONLY for high-confidence junk, writes zero chunks, excluded from search via quarantineFilterFragment(pageAlias) / QUARANTINE_FILTER_FRAGMENT (the p-aliased constant), the single source of truth buildVisibilityClause calls so the search filter and marker key can't drift. content_flag (key CONTENT_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. Exports buildQuarantineMarker / isQuarantined / filterOutQuarantined, buildContentFlagMarker / getContentFlag / hasContentFlag, plus the two key constants. Pinned by test/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 via quarantinedSlugs, DB walks, the managed link derivation) and is not in the links_extraction_lag denominator. Pinned by test/quarantine-extraction.test.ts.

  • src/core/repo-root.ts — Shared findRepoRoot(startDir?): walks up from startDir (default process.cwd()) looking for skills/RESOLVER.md. Zero-dependency, imported by doctor.ts and check-resolvable.ts; parameterized startDir makes tests hermetic. Read-path / write-path split: autoDetectSkillsDir (shared, read+write-safe) has tier-0 $GBRAIN_SKILLS_DIR operator override ahead of the 4-tier chain. autoDetectSkillsDirReadOnly wraps it with a tier-5 install-path fallback that walks up from fileURLToPath(import.meta.url) and gates on isGbrainRepoRoot so 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 gbrain skills/ instead of the user's workspace. SkillsDirSource variants 'env_explicit', 'install_path'; AUTO_DETECT_HINT_READ_ONLY documents the extra tier. The --fix safety gate in doctor.ts + check-resolvable.ts refuses auto-repair when detected.source === 'install_path'.

  • src/core/resolver-filenames.ts — central list of accepted routing filenames (RESOLVER.md, AGENTS.md). Shared by findRepoRoot, 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-object sources.config values. 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-ready source_config_shape doctor repair. localFederatedSourceIds reads config through the same parser so stdio/CLI federation cannot silently disagree with sources list. sourceConfigHasRemoteUrl uses that parser for autopilot pull policy, including PGLite's JSON-string config shape. Invalid fragments degrade to {} rather than throwing: each string layer goes through gbrain_try_jsonb(text) (v263; jsonb or NULL, never raises), portable to Postgres 15 unlike the IS JSON it replaced (#7112). test/postgres15-sql-compat-7112.test.ts pins the function on both engines and fails when Postgres 16+ only SQL appears in src/. Pinned by test/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, and test/doctor-source-config-shape.test.ts.

  • src/core/source-health.ts — per-source health metrics for gbrain sources status + doctor's federation_health. Commit-relative staleness: newestCommitMs(localPath) = HEAD committer time via git 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 DEFAULT ceilingSeconds reads env, via resolveStalenessCeilingSeconds() (GBRAIN_STALENESS_CEILING_HOURS overriding GBRAIN_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 trip federation_health (24h) and sync_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) → probeSourceGitState HEAD only (an uncommitted tracked edit is not lag) ? 0 : the age of the reflog entry that moved HEAD off last_commit, else of the commit notifier's persisted first_due_at, else wall-clock since last_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_health on the HTTP MCP path) → lagFromContentMs(row.newest_content_at, ...) raised to first_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 the newestCommitMs sibling pinned to an arbitrary commit (committer time via git show -s --format=%ct <sha>, fail-open null, execFileSync array args) — the resumable sync stamps newest_content_at against its pinned target commit, not whatever HEAD raced to. Pinned by test/source-health.test.ts. loadSyncFreshnessSources(engine) loads doctor sync_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) vs assertValidSourceId (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; sourceScopeOpts translates 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/normalizeFederatedReadInput normalize the /admin/api/register-client HTTP body, mirroring the CLI's --source/--federated-read flags: omitted source → 'default'; omitted federatedRead → undefined so registerClientManual applies 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 by test/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? } alongside resolveSourceId() (unchanged). SOURCE_TIER_NAMES = ['flag', 'env', 'dotfile', 'local_path', 'sole_non_default', 'brain_default', 'seed_default'] (7 entries; order matches priority). Tier sole_non_default slots between local_path and brain_default: when NO sources.default config is set AND exactly one registered source has local_path AND 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 to seed_default and prints a one-line stderr notice naming both sides so the suppressed flip is diagnosable, same GBRAIN_NO_SOLE_NON_DEFAULT_NUDGE=1 suppression 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.role storage_manifest) excluded (try/catch for pre-v34 brains); private pickSoleNonDefaultSource(engine) shared by both resolver entry points so they cannot drift. Exported formatSoleNonDefaultNudge(sourceId): string | null builds the user-facing stderr nudge (null when GBRAIN_NO_SOLE_NON_DEFAULT_NUDGE=1). resolveCliSyncSource in src/commands/sync/run.ts calls resolveSourceWithTier unconditionally so the tier fires; src/commands/import.ts:96-128 mirrors with the tier-gated nudge. Consumed by gbrain sources current, import --source-id, extract --source-id, and the source_routing_health doctor check. Pinned by test/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 real runSync), test/pages-source-scoping-4329.test.ts (real-engine both-ways guard coverage). Also exports noGrantFederatedScope(engine, hasSourceGrant, sourceId), the widening decision transports share: returns localFederatedSourceIds(..., 'seed_default') ONLY when hasSourceGrant === false (the legacy-bearer no-grant floor), undefined for a granted token, for an OAuth client (flag undefined — 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 by src/commands/serve-http.ts; pinned by test/no-grant-federated-scope.test.ts (6 cases). explicitReadBinding(engine, sourceId, tier) (#5081) is the explicit-tier twin used by the stdio transport for GBRAIN_SOURCE (env) and .gbrain-source (dotfile) bindings: { sourceId, via, sourceIds, optedOut }, where sourceIds is the same set localFederatedSourceIds computes (shared federatedSetFor, so an isolated anchor admits only itself) and optedOut lists federated === false sources for the denial hint; undefined for every other tier. Pinned by test/explicit-read-admission-5081.test.ts. Unscoped default-write guard family (the seed_default tier is the only one that actually lands a write in 'default'): assessDefaultWriteGuard(engine) → DefaultWriteAssessment { shouldGuard, defaultPages, nonDefaultPages, nonDefaultSources, failed? } — an unindexed full-pages aggregate; shouldGuard when ≥1 non-default source holds pages AND non-default pages outnumber default's; a query failure returns the fail-open no-guard verdict stamped failed: 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; __resetDefaultWriteGuardMemo is the test seam). assessUnscopedDefaultWrite(engine, tier, mutating) → { warning, assessed } (assessed: false only when the aggregate failed); formatDefaultWriteWarning(a, sourceFlag?) / formatDefaultWriteRefusal(cmd, a) render the two surfaces; defaultWriteAllowedByEnv() is the GBRAIN_ALLOW_DEFAULT_WRITE=1 escape hatch. Consumers: sync refuses (dry-run warns), import warns via the memo, MCP stdio's createDefaultWriteAdvisory prints once. Also exports isResolverUserError(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), assertSourceExists and the federated set from one sources read, sent with the config table (resolveSourceWithTier reads 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 the sources row, that incarnation's persistence_source_bindings row and its managed-sync cursors in op_checkpoints (#8741) in one statement (neither has an FK to sources). #9068: that statement also runs removedSourceScrubCtes (the managed remove/purge in source-lifecycle.ts runs them in its final transaction too), which delete the source's retrieval_event_pages, retrieval_event_links, retrieval_feedback and context_volunteer_events rows and strip from eval_candidates.retrieved_slugs each slug no other source the candidate covers has a page for (retrieval_weights and mention_gazetteer_entries cascade from sources); 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 by test/purge-scrub-followups-9068.test.ts. Other incarnations' bindings go to gbrain repair orphan-bindings (src/core/persistence/orphan-bindings.ts, doctor orphan_persistence_bindings). The unmanaged claim check (sync-authority.ts) and doctor unbound_source count only the current incarnation's binding. EXPIRED_ARCHIVE_SQL is the one purge-eligibility predicate (unmanaged sweep, its per-row DELETE and the managed expiredOnly purge): both archive timestamps must be later than the epoch and the expiry past; UNVERIFIED_ARCHIVE_SQL lists 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 and source_pages_remain is thrown (#7072, test/source-purge-stranded-pages-7072.test.ts); the expired-archive sweep reports the source in blocked with 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. recloneIfMissing deletes local_path, so it gates on isOwnedClone(src) and throws a SourceOpError('unmanaged_path', ...) BEFORE any filesystem op when ownership is unprovable — fail-closed. Ownership is proven by config.managed_clone === true (written by addSource's --url path, covering default-location and --clone-dir clones) OR local_path === defaultCloneDir(id) (back-compat for pre-marker clones, via exact normalized-path equality, symlink-free). A row with remote_url + an unowned local_path (a user-registered working tree, e.g. sources add --path) is refused untouched; re-add with --url to regain auto-reclone. The reclone is EXDEV-safe: clone into a SIBLING temp of local_path (not the shared clones/.tmp, which may sit on a different mount than a --clone-dir target), then swap (move old aside → move new in → drop old) so local_path is never left missing-and-unrecoverable; on swap failure the original is restored, and if restore fails the error names the aside path 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 the gbrain sync --source CLI error; gbrain sources restore special-cases unmanaged_path to print "DB row restored; gbrain syncs this path read-only" instead of the misleading "try sync to recover" guidance. SourceOpErrorCode includes unmanaged_path. Pinned by test/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 a local_path (addSource, gbrain sources set-path): a path equal to, nested inside, or enclosing another source's local_path throws SourceOpError('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 sibling local_path are realpathSync'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/defaultCloneDir live in src/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 the src/commands/sync.ts façade, which re-exports them; facadeExpansion in scripts/generate-flag-registry.ts keeps exactly these six (NOT the other sync-* siblings, which are ordinary deps) on the sync command's flag-scan surface. sync-cost-gate.ts: the inline-embed cost gate + token estimation for gbrain 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 by gitRelativePath, and the delete/rename slug resolvers (resolveSlugByPathOrSourcePath — see its dedicated entry above — plus the verified resolveSlugsForRemovedPaths/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-lock handling, the partial-result envelope (performSync itself 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; syncWatchdogPlan and syncDeadlineStopNotice build the watchdog options and its stdout stop notice — see the process-watchdog.ts entry). sync-status-report.ts: the per-source sync status report backing gbrain sources status and the get_status_snapshot op. Its queue context is engine-aware: only an explicitly worker-backed surface may promise job deferral; otherwise non-interactive cost deferral returns manual_drain_required with exact per-source gbrain embed --stale --source <id> commands and never writes or claims an embed-backfill row. GBRA-133 2b.3: a --no-pull estimate (estimateInlineNewTokens / CostGateContext.noPull) prices local HEAD and never fetches origin. sync-git.ts adds gitAsync / 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 BOTH performSyncInner (sync executor) and estimateInlineNewTokens (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 via git cat-file -t (a gc'd bookmark is anchor_missing, but a present-but-non-ancestor bookmark is still diffed tree-to-tree), then git diff --name-status -M from..to parsed by buildSyncManifest; 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) as SyncResult.uncommitted drift and, with --working-tree / config sync.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). execFileSync array-args (shell-injection safe), 30s / 100 MiB budget, GIT_OPTIONAL_LOCKS=0 (git-env.ts GIT_READ_ENV: sync's Git reads never take index.lock). GST-2331: runs with HARDENED_GIT_ARGS and NO_LAZY_FETCH_ENV. Test seam _setGitRunnerForTests. Pinned by test/sync-delta.test.ts. Classic sync reads the same delta as bytes instead: computeLosslessSyncDelta / buildLosslessWorkingTreeManifest run git diff --raw -z -M (and ls-files -z --others) into a Buffer and parseRawDiffZ keeps each name exactly as Git has it (no trim, no unquoting); a name that is not UTF-8 or holds a control character goes to unsupported (present) or gone (left the tree) instead of the manifest, and a gitlink (mode 160000) that appears goes to gitlinks, never the manifest (seam _setGitBytesRunnerForTests). Managed discovery and the cost estimator keep computeSyncDelta. Pinned by test/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], else not_utf8 / control_character); the unsupported_path hold key encodeBytePathKey (/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) and decodeBytePathKey (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 to xargs -0 git mv, plain ASCII); bytePathHoldGone (lstat of the exact bytes; null for an ordinary key), read by commands/sync/holds.ts re-screen and full-sync settle; unsupportedPathHoldFix, dispatched by gitHoldFix (ask_user rename, argv a read-only sources status, then sync --no-pull).

  • src/commands/sync/unsupported-paths.ts — classic sync's routing of the lossless delta's extras: selectBytePaths applies the manifest's scope / exclude / syncability filters (name probed with U+FFFD for bad bytes and _ for control characters) and makes paths mode-relative; holdUnsupportedPaths writes each unsupported_path hold (writeGitHold, mode legacy, slug and page null, never gating the bookmark), schedules the holds of gone names to clear and prints one gitlink_not_followed line; gitlinkFields puts gitlinks_not_followed on the result (declared on SyncResult by module augmentation here) for the run that advances past them.