Garry's Opinionated OpenClaw/Hermes Agent Brain
Key files: Files And Sync (2/2)
Subsystem index. Read only the entries relevant to your change. Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.
src/core/persistence/visibility-request.ts— the private-request guard.readPrivateRequest(content, parse)reads whether content asks forvisibility: private: a frontmatter line in any case, or the parse reading a visibility key of any case as private (block scalars, lists, flow mappings and merge keys count). Page writes (put_page,edit_page,capture;privateRequestGuarded) refuse a request the stored frontmatter would not keep as exactlyvisibility: private(assertPrivateRequestKept,visibility_not_applied); an unmanagedingest_capturejob takes the same refusal (privateRequestRefusal) afterimportFromContent's screen holds the content (holdNoncanonicalPrivate), and dead-letters without a retry (#7880). File ingestion holds the same case asvisibility_noncanonical(noncanonicalPrivateHold): classic sync and legacygbrain importthroughimportFromFileandscreenLegacyFile, managed sync and import throughscreenImportContent'sholdNoncanonicalPrivate, and throughimportFromContent's opt-in of the same name:ingest_capture, company-brain imports (importCompanyBrainFile) and the GitHub and Google connectors' database-only imports (#7880),gbrain repair url-clone-fences(a held HEAD previews under its code and applies asheld), and the unmanagedbrainstorm --saveandsources reconcile, which turn the hold intovisibility_not_applied(#7897), streamed large files unless they are a page write, with or without a Git checkout. Doctorgit_held_filescounts those holds and the live stored pagesnoncanonicalPrivateRequest('', frontmatter)reads as asking for private (details.visibility_noncanonical); nothing rewrites them. Derived writers never refuse. Tests:test/put-visibility-private-7841.test.ts,test/visibility-noncanonical-hold-7848.test.ts,test/ingest-capture-private-hold-7880.test.ts,test/company-brain-private-hold-7880.test.ts,test/{url-clone-fences,brainstorm,reconcile}-private-hold-7897.test.ts(Postgres: the matchingtest/e2e/*-postgres.test.tswrappers).test/import-private-hold-callers-7897.test.tslists everyimportFromContent/screenImportContentcall that does not opt in, with why it is held or derived, and fails on a new one.src/core/sync-concurrency.ts— single source of truth for the parallel-sync policy. ExportsautoConcurrency(engine, fileCount, override?)(PGLite always serial; explicit override clamped to >=1; auto path returnsDEFAULT_PARALLEL_WORKERS=4whenfileCount > AUTO_CONCURRENCY_FILE_THRESHOLD=100),shouldRunParallel(workers, fileCount, explicit)(explicit--workersbypasses the >50-file floor), andparseWorkers(s)(rejects'0','-3','foo','1.5', trailing chars). Used byperformSync,performFullSync,runImport, and the Minionsynchandler so the sites can't drift.DEFAULT_PARALLEL_SOURCES = 4is a SEPARATE constant for the per-source fan-out undergbrain sync --all— kept distinct fromDEFAULT_PARALLEL_WORKERSbecause total live Postgres connections per wave ≈DEFAULT_PARALLEL_SOURCES × DEFAULT_PARALLEL_WORKERS × 2 (per-file pool)= 32 at both defaults (each per-file worker opens its ownPostgresEnginewithpoolSize = min(2, resolvePoolSize(2)));sync.tswarns whenparallel × workers × 2 > 16.resolveWorkersWithClamp(engine, override, commandName, fileCount)wrapsautoConcurrencywith a per-command stderr clamp warning on PGLite (per-(command, requested) dedup via module-scoped warned-once set with_resetWorkersClampWarningsForTest()seam) and is the canonical surface for every bulk-command--workers Nflag (extract-conversation-facts, extract, edges-backfill, reindex-multimodal, reindex, reindex-code); embed.ts deliberately bypasses it and keepsGBRAIN_EMBED_CONCURRENCY || 20.resolveMaxConnections()(readsGBRAIN_MAX_CONNECTIONS, undefined when unset) +clampWorkersForConnectionBudget(workers, perWorkerPool, maxConnections, parentPool)back the opt-in single-sync connection-footprint clamp so a big sync stays under a low pooler cap (parent_pool + workers×perWorkerPool ≤ budget);gbrain doctor'spool_budgetcheck (computePoolBudgetCheck/checkPoolBudgetinsrc/commands/doctor/checks/consolidation-cycle.ts, re-exported bysrc/commands/doctor.ts) warns when the budget leaves no room for a worker, pointing atGBRAIN_POOL_SIZE=2. Pinned bytest/pglite-workers-clamp.test.ts.src/core/sync-embed-backfill.ts— Sync command’s engine-aware embedding-delivery seam. It derives separate worker-backed deferral and multi-source fan-out eligibility, keeps automatic-submission policy distinct from capability, invokes the shared cost gate for--alland single-source runs, propagates intrinsic large-sync deferral into final delivery outcomes, resolves backfill results through the centralized submitter, formats one truthful human status, and builds the single-source JSON envelope.syncProducedEmbeddableContentis the one content gate every automatic submit site (sync --all, single-source autodefer, the jobssynchandler) applies on top of status: a sweep-only or delete-only run reportssyncedbut wrote no chunks, and minting a backfill for it would only arm the per-source cooldown against the next real import (the handler reportsembed_skip_reason: 'no_new_content'). Keeping these pieces together prevents cost-gate, queue, human, and machine surfaces from drifting while the size-ratchetedsrc/commands/sync.tsfaçade stays at its committed ceiling.src/core/sync-failure-ledger.ts— the bounded auto-skip sync failure ledger. A LEAF module (imports only fs/path/crypto/config) sosync.tscan re-export it without a circular dependency. State lives in~/.gbrain/sync-failures.jsonl, one JSON object per line, keyed by(source_id, path)with a per-keyattemptscount and a 3-state machine:open(fresh/blocking) →auto_skipped(chronic, still doctor-visible) oracknowledged(human resolved viagbrain sync --skip-failedfrom either unresolved state).classifyErrorCode(errorMsg)regex classifier with 23 named codes (RENAME_RECONCILE,SLUG_MISMATCH,DB_DUPLICATE_KEY,STATEMENT_TIMEOUT,YAML_PARSE,YAML_DUPLICATE_KEY,MISSING_OPEN,MISSING_CLOSE,EMPTY_FRONTMATTER,NULL_BYTES,NESTED_QUOTES,INVALID_UTF8,FILE_TOO_LARGE,SYMLINK_NOT_ALLOWED,TAKES_TABLE_MALFORMED,TAKES_HOLDER_INVALID,EMBEDDING_NO_CREDS,EMBEDDING_NO_TOUCHPOINT,EMBEDDING_TIMEOUT,EMBEDDING_RATE_LIMIT,EMBEDDING_QUOTA,EMBEDDING_OVERSIZE,PAGE_JUNK_PATTERN) plusUNKNOWN(the default fallthrough);summarizeFailuresByCode(failures)returns sorted[{code, count}];MISSING_OPEN/EMPTY_FRONTMATTERregexes match themarkdown.tsvalidator strings;MISSING_CLOSE's regex is stale against currentmarkdown.tsoutput — it matches the no-heading-hint case (No closing --- delimiter found) but not the heading-hint case (No closing --- before heading at line N), which falls through toUNKNOWN.FILE_TOO_LARGEcoversimport-file.ts:395, 1236, 1436(markdown/text, plain-file, and code-file import paths),SYMLINK_NOT_ALLOWEDcovers:1231, 2038(file and image import paths).EMBEDDING_INFRA_CODESis the subset (EMBEDDING_TIMEOUT/EMBEDDING_RATE_LIMIT/EMBEDDING_QUOTA) that means the embedding PROVIDER is unhealthy rather than the file being poison —isEmbeddingInfraCode(code)is consulted insidedecideGateAction's chronic-eligibility loop so these three are never counted toward auto-skip (treated as fresh, forcingblockinstead ofadvance_then_autoskip); an explicit--skip-failedstill advances past them like any other failure, since that check runs before the loop. All mutations run underwithLedgerLock(cross-process file lock) with an atomic rename write. The auto-skip threshold resolves viaresolveAutoSkipThreshold()fromGBRAIN_SYNC_AUTOSKIP_AFTER(defaultDEFAULT_AUTOSKIP_AFTER = 3;0disables the valve = pure fail-closed). Two pure decision functions are the unit-test surface:decideGateAction({fileFailures, sentinels, attemptsByPath, threshold, skipFailed})returnshard_block | block | advance | advance_then_autoskip(sentinels like<head>ALWAYS hard-block, even with--skip-failed, so a history rewrite can't auto-skip; any FRESH failure withattempts < thresholdblocks fail-closed; only when ALL failures are chronic does itadvance_then_autoskip), anddecideSyncFailureSeverity({entries, nowMs, failHours})returns thesync_failuresdoctor status (okwhen zero unresolved;failwhen ≥10 OPEN-blocking or the oldest OPEN failure'sts(last attempt, NOTfirst_seen) is older thanfailHours— a failure retried inside that window keeps refreshingtsand never trips this leg even iffirst_seenis much older; otherwisewarn—auto_skipped-only rows stay WARN-visible regardless of count because the bookmark already advanced).applySyncFailureGate(input)is the one orchestrator BOTH sync paths (incremental + full/runImport) call: it records/clears ledger rows, runsdecideGateAction, then executes effects in the crash-safe order (advance the bookmark FIRST via the injectedadvance()callback, THEN auto-skip the chronic set) so a crash can never mark a file skipped while leaving sync wedged.isSkippablePathrejects<…>sentinels. Pinned bytest/sync-failure-ledger.serial.test.ts+test/sync-failures.test.ts. GBRA-130 A-18: the module importsBILLING_MESSAGE_RE/RATE_MESSAGE_REfrom the import-freeai/errors.ts(still a leaf).classifyErrorCode(msg, path?)never reads path text as a provider error: errno-led messages map toPERMISSION_DENIED(EACCES/EPERM) orFILE_UNREADABLE(ENOENT and other file errnos), and the infra regexes run on the message with the embed envelope, the path and its tokens stripped, sobilling/q3.mdorhttp-429.mdno longer read asEMBEDDING_QUOTA/EMBEDDING_RATE_LIMIT.syncFailureCode(error, path)takes the structured errno first (the import paths passSyncFailedFile.code).SyncGateInputgainscode,importedandsystemic: a run where files imported recordsinfra_isolated_runson an open infra row, anddecideGateActiontreats an infra row withinfra_isolated_runs >= thresholdas chronic, auto-skipped with codeEMBEDDING_INFRA_ISOLATED; a run where nothing imported never counts toward it. A systemic run (thesync.import_filesItemRun breaker, most files failing) adds no attempt to open rows, starts new rows at 1, blocks, andfinalize.tsprints a blocked message naming--skip-failed. Pinned bytest/pathological/a18-ledger-path-text.test.ts(both engines).src/core/sync-git.ts:resolveSlugByPathOrSourcePath— Resolves a slug bypages.source_pathfirst (returns the stored slug for frontmatter-fallback pages whose path doesn't derive a slug), then falls back toresolveSlugForPath(path). Three call sites: the un-syncable cleanup (which passesopts.sourceId), and the bare no-sourceIddelete and rename-source paths; whensourceIdIS set the delete and rename loops batch throughengine.resolveSlugsByPathsinstead. Thesource_pathlookup is scoped to the DEFAULT source on the bare path, matching every write that path performs (updateSlug,deletePage, the rename bookkeeping repair are all default-scoped) — an unscoped lookup could return a row from another source sharing thesource_path, and the rename loop consumes this value directly as its cheap-move source slug. Without the helper, emoji-only / Thai / Arabic filenames whose slug came from frontmatter would orphan on delete/rename (that path would compute the wrong path-derived slug). Best-effort query — pre-migration brains fall through to the legacy path.src/core/import-chunk-reuse.ts—reuseStoredChunkVectors: A13 vector reuse for one markdown page import, shared by the inline import (before its transaction, to decide which chunks reach the provider) and every import's transaction (under the page lock,importFromContentinimport-file.ts). It copies each stored vector the reuse gate admits onto its matching new chunk and maps the chunk to the stored row id when that row already holds exactly what the chunk would insert, so the import keeps it in place and deletes and writes only the rest; withkeepUnembedded(the in-transaction pass) an identical never-embedded row stays under a new chunk that carries no vector either. Inline,--no-embedand prepared imports all keep rows; a prepared import reuses nothing from a page stored under per-chunk synopsis. WithrequireRecordedInput(set byimportFromContentwhen the old or new body holds a protected fence, #6961) only a stored vector with a recorded embedding input is admitted, never the legacy raw-text match. Pinned bytest/fenced-embed-reuse-6961.test.ts,test/import-inline-chunk-keep.test.ts(both engines) andtest/persistence-edit-embedding-reuse.test.ts.reuseSegmentChunkVectors(Wave B) reads only the rows of the retired occurrences with their vectors and applies the same gate andchunk_source\0chunk_textplan, so an unchanged chunk inside a rewritten tail keeps its vector.src/core/sync-policy.ts—isSyncDisabledConfig(config): the one predicate forconfig.syncEnabled === false("excluded from AUTOMATIC/bulk sync"), unwrapping PGLite's JSON-string config scalar viaparseSourceConfig. Read by thesync --allfan-out filter (src/commands/sync.ts), autopilot's per-source freshness dispatcher (src/commands/autopilot.ts, skip beforequeue.add('sync')) and the full-cycle fan-out (src/commands/autopilot-fanout.ts, which drops thesyncphase + pull from a disabled source'sautopilot-cyclepayload but keeps lint/backlinks/extract and the freshness stamp) and thesync_enabledcolumn ofbuildSyncStatusReport(src/core/sync-status-report.ts, whose callers pass RAWSELECT configrows — a JSON string on PGLite — so a raw cast there contradicted the fan-out filter). Doctor'scheckSyncFreshnessalso applies this predicate, including the legacy query fallback: disabled sources contribute neither warnings nor freshness counts; only booleanfalsedisables, not the string'false'.checkCycleFreshnessstill monitors their maintenance cycles. Pinned bytest/doctor-sync-policy.test.tsandtest/doctor-cycle-freshness.test.ts. Deliberately does NOT gateperformSync(): an explicitgbrain sync --source <id>still runs;sync-cost-gate.tskeeps its own inline check because it also feeds the explicit single-source cost preview. Pinned bytest/sync-policy.test.ts, the#4399cases intest/autopilot-fanout-wiring.test.ts(source-text) andtest/autopilot-fanout.test.ts(stubbed dispatch).src/core/sync-applicability.ts— agent-first operator wave E4.syncContentDirectory(engine, {sourceId, repoPath})resolves the sync root exactly asperformSyncdoes and returns it when it is a gbrain-owned content directory (under<GBRAIN_HOME>/.gbrain/content/, or an owned--content-rootrecorded in the shared-skills setup receipt) with no.gitat the root; null otherwise (fail-open).assertSyncAnchorAbsoluterefusessync_anchor_relative(syncAnchorRelativeError: exit 3, anask_userfix naminggbrain sources set-path <id> <absolute-directory>, orgbrain config set sync.repo_pathwith no source) when the stored anchor (sources.local_path, elsesync.repo_path) is not absolute on this host (isHostAbsolutePath: on win32 only a drive or UNC path) and no absoluterepoPath, or relative one resolving elsewhere, was passed;sync --all --jsonputs the refusal'scode,whyandfixin the source's entry, and thesyncMinion job completes as a skip carrying them; single-source and--allCLI syncs refuse it before the cost gate walks the directory, and a cycle whose directory matches no source checksdefaultand fails its sync phase with that code. A path absolute only on another operating system (a Windows drive path read on Linux or macOS) gets the same code with aset-path-only fix, since--clearrefuses it.src/core/sync-anchor.tsnever proves ownership from a relative anchor:isAnchorOwnedSyncPath,ownsSourceSyncAnchorandsourceCommitAnchorAllowedtreat it as not owned, and fordefaultthe commit-anchor check skips a relativesync.repo_pathand judges the row'slocal_path(a null row falls back to that relative key and refuses), so an explicit absolute--reponever advances the commit anchor of a source whose stored path is relative.performSynccallsassertSyncApplicablefirst (the anchor check, then the content-directory check), so a content-directory source refuses withsync_not_applicable(reasoncontent_directory, fixgbrain import <dir> [--no-embed] --source <id>,git initnamed only as an ask-the-user option) before the managed path or the legacy #2964 anchor self-heal couldgit initit.sync --allskips these sources with one line; the dream cycle's sync phase reports themskipped(details.reason: sync_not_applicable). The CLIsyncrecord renders fix-carrying OperationErrors throughrenderCliError(src/cli/commands/sync.ts). Pinned bytest/sync-applicability.test.tsandtest/sync-relative-anchor-refusal-7630.test.ts.src/core/sync-upstream.ts— upstream observation for remote-tracking sources (#5255/#5176).observeUpstream(root, syncedCommit)reads the checkout's@{upstream}commit, the newer of theFETCH_HEADand upstream-ref reflog mtimes (the last fetch, pull or push by any process) andrev-list --countof upstream commits the synced commit lacks;recordUpstreamObservation(called byperformSyncinsrc/commands/sync/perform.tsafter every non-dry-run legacy or managed sync, best-effort) writes them tosources.upstream_checked_at/upstream_commit/upstream_behind, whichmanaged_writer_guarddoes not protect.upstreamFreshnessis doctorsync_freshness's separate "upstream checked" verdict (aremote_urlsource with no observation or one at least 24 h old is upstream unknown; any observed upstream lead is behind), DB-only so remote doctor runs it.managedPullWarning/UpstreamRefreshback the cycle sync phase (runPhaseSyncinsrc/core/cycle.ts), which runs a managedpull: trueas no-pull and reportsdetails.upstream_refresh(pulled|failed|skipped_managed|not_requested) plus amanaged_pull_skippedwarning when the checkout tracks an upstream. A managed brain's fix (the warning and doctor's behind/unknown verdict) isgbrain sources refresh <source>; an unmanaged one's isgbrain sync --source <source>. Tests:test/managed-cycle-pull-upstream.test.ts, the pull row oftest/managed-phase-matrix.test.ts.src/core/sync-upstream-rewrite.ts— classic sync's upstream watch for a source that syncs with pull (GBRA-133 S-58/S-59).recordUpstreamBeforeFetch(called bysrc/commands/sync/preflight.tsbefore every pull) stores insources.config.upstream_baselinethe upstream commit HEAD contains, only when HEAD contains it, so a rewritten upstream fetched earlier never replaces it;settleUpstreamAfterPullrecords the new baseline and clearssources.config.upstream_divergenceafter a pull that fast-forwarded or was up to date, and after a pull that failed with HEAD and@{upstream}diverged storesupstream_rewritten(baseline not an ancestor of the new upstream),upstream_unknown(no baseline or its object is gone) orupstream_diverged(baseline contained: plain local commits); nothing is classified while a rebase, merge, cherry-pick or revert marker (GIT_OPERATION_MARKERSinsrc/core/git/commit-push.ts) exists. Best effort: it never throws into the sync and never writes a sync-failure ledger row.upstreamFixis the typed next step (ask_userreset bound to the observed SHAs for rewritten/unknown, never a merge;gbrain git commit-push --pullfor diverged; boththenthe sync). Read byperformSyncInner(result.upstream),buildSingleSyncJsonEnvelope,gbrain sources status --json(upstream) and doctorsync_failures(details.upstream, warn, local fix; remote callers get counts only). Pinned bytest/pathological/s-58-upstream-rewrite.test.ts.src/core/sync-attempt.ts+src/commands/doctor/sync-outcome.ts— doctorsync_freshnessfor a source with no successful sync (last_sync_atNULL, #4960).readLastSyncAttemptreads, read-only, the newestsyncMinions job of the source and, on a managed brain,readSyncStatus(holds, last error, cursor, itsnext); nothing found isno_attempt, an unreadable read isno_attemptwithunreadable. A live first-sync lock inside the staleness ceiling iswarn(sync_first_run_in_progress, fixnext: wait); no lock isfail(sync_no_successful_sync) naming last attempt, result and held count, with a per-reasonfix (attempt_queuedwait,holds_pendingthe managednextorsync status,last_attempt_unsuccessfulinspect the job then retry,no_attemptretry;content_directory, a root only a content-setup receipt claims on a brain with persistence off, sync refuses:receiptContentDirectorynames thesync_not_applicableimport fix, testtest/doctor-sync-freshness-receipt-root.test.ts). Entries land indetails.no_successful_sync[]; these sources stay instale_count. Test:test/doctor-sync-freshness-outcome-4960.test.ts.src/core/sync.ts— Pure sync functions (manifest parsing, filtering, slug conversion). ExportedpruneDir(name: string): booleanis the single source of truth for descent-time directory exclusion across walkers — blocksnode_modules(no leading dot, so a naive walker would descend into it and inflate MISSING_OPEN counts via vendor packages),vendor/dist/build/venv, dot-prefix dirs, and*.rawsidecars — NOTops/, which is ordinary user content (the bundled daily-task-manager storesops/tasksthere);isSyncableapplies it per path segment, andwalkMarkdownFilesinsrc/commands/extract.ts+listTextFilesinsrc/core/cycle/transcript-discovery.tsconsult it BEFORE recursing to save the IO of walking thousands of vendor files.manageGitignoreworktree discriminator matches the gitdir path segment (/modules/<name>= submodule,/worktrees/<name>= worktree, per Git's documented layout) so Conductor worktrees (first-class repos) get.gitignoremanagement for storage-tiering. The sync-failure ledger (failure store, error classifier, the shared bookmark gate, and the doctor severity rule) lives insrc/core/sync-failure-ledger.ts;sync.tsre-exportsclassifyErrorCode,summarizeFailuresByCode,loadSyncFailures,unacknowledgedSyncFailures,acknowledgeSyncFailures,recordSyncFailures,decideSyncFailureSeverity,applySyncFailureGate, and theSyncFailuretype for backward-compatible imports — see its entry below.isSyncablefactored through privateclassifySync(path, opts): SyncableReason | null; exported companionunsyncableReason(path, opts)returns the same tagged reason or null when syncable.SYNC_SKIP_FILESis a named export (the canonical metafile basenamesschema.md,index.md,log.md,README.md,RESOLVER.md, skipped at any depth unlessSyncableOptions.metafilePagesays a nested one is a page:metafileIsPage(path, head, mode)is true for anisNestedSkipMetafilepath whose closed leading frontmatter has a non-empty top-leveltype:ortitle:undersync.metafile_pagestypedand no top-levelslug:naming another page (#7341: such a file stays scaffolding instead of being heldfrontmatter_slug_conflict), the one defaultDEFAULT_METAFILE_PAGES_MODE;offskips every metafile;readMetafilePagesModereads the key);SYNC_ROOT_SKIP_FILES(#5186, W14 P1.5b) adds the bootstrap scaffoldingAGENTS.md/CLAUDE.mdat depth 0 only, andisSyncMetafile(path)is the one predicateclassifySyncand the bulk-import collector (commands/import.ts) share (the managed effect scan'sisMetafilePageinpersistence/effects.tsadds the head of the file on disk, so a typed nested metafile page is mirrored and published like any page), so an earlier-indexed rootagentspage survives under the #1433 guard (test/sync-root-agents-metafile.test.ts).SyncableReasonunion:'metafile' | 'strategy' | 'pruned-dir' | 'include-glob-miss' | 'exclude-glob-hit' | 'malformed-path'. Malformed filenames are TWO-TIER:hasMalformedPathSegment(ADMISSION — control chars on any path; square brackets on.md/.mdxpaths only, so code-strategy lanes keep indexingapp/[id]/page.tsxframework layouts) vsisPoisonedPath(DESTRUCTION — only the injection signature](or control chars; sync's row-DELETING lanes gate on this so a bare-bracket markdown row already in the DB survives reconcile while its file exists).sanitizePathForDisplayscrubs control bytes + caps length before echoing such paths. The un-syncable cleanup loop (sweepUnsyncableModifiedinsrc/commands/sync/deletes.ts) guards onunsyncableReason(path)being'metafile'OR'pruned-dir'so previously-indexed metafile pages AND deliberately put-created pages under pruned dirs survive every re-sync. Does NOT covermanifest.deleted(the upstream filter already strips metafiles). Pinned bytest/sync-isSyncable-shape.test.ts(15 cases, duality contract) +test/sync-metafile-skip.test.ts(3 PGLite cases incl. the renamed.md → .txtnegative).pruneDir:pruneDir(name, parentDir?)extended with optionalparentDir. When provided, additionally rejects directories containing.gitas a FILE — the git submodule gitfile pattern (regular repos have.gitas a DIRECTORY; submodules as a file pointing into the parent's.git/modules/). Sync + extract walkers threadparentDirso the gitfile-as-FILE check fires per descend step. Best-effort:statSyncfailures fall through and treat as a normal dir. Prevents phantom imports from a worktree-with-submodules sync walking into submodule trees. Pinned bytest/sync-walker-submodule.test.ts. The legacy failure ledger re-export is distinct from managed cursor-keyed mirrors: repeat managed observation does not inflate attempts, success clears only the matching cursor, and managed failures cannot be acknowledged or auto-skipped.isMultimodalEnabled(env)(GBRAIN_EMBEDDING_MULTIMODAL=true) is the one predicate managed discovery, the hold re-screen,embed --stale, the blocked-projection hint and doctorimage_embedding_coverageread for whether images are imported and embedded.src/core/sync-metafile-pages.ts— the head readers behindsync.metafile_pages:metafilePagePredicate(mode, read, rootRelative)(memoized, theSyncableOptions.metafilePageevery classifying caller passes),diskMetafileHeads(root)(regular files only, never a symlink),gitMetafileHeads(gitRoot, commits)(first commit that has the path;primebatch-reads blobs a caller already streams through onecat-file --batch-checkplus one--batch),firstMetafileHead(disk, then the last synced blob, so a deleted file is judged as last committed),listMetafileNamedBlobs(onels-tree), and the classic backfill markersync.metafile_pages.applied.<source>(metafileBackfillDue/recordMetafilePagesApplied, written with the bookmark): a source that has not finished a sync undertypedadds its tree's nested metafile-named files to the next delta once. Managed sync instead folds the mode into the pass selection fingerprint (sync-pass-run.ts; unchanged underoff). Only metafile-named paths are ever read.config set sync.metafile_pagesrefuses a value outsidetyped | off(src/commands/config/sync-metafile-pages-value.ts); the restore check and doctormissing_recorded_files(persistence/detached-pages.ts) judge a recorded nested metafile with the same disk-then-last-synced predicatesync --fulluses. Pinned bytest/sync-metafile-pages.test.ts(classic) andtest/persistence-sync-metafile-pages.test.ts(managed, PGLite and Postgres).src/core/sync-rename-identity.ts— the one confirmation stage for inexact Git renames (#6729).confirmRenameIdentitiesreads committed sides through onegit cat-file --batchstream (64 KiB heads; GST-2331: underHARDENED_GIT_ARGSandNO_LAZY_FETCH_ENV, so a side a partial clone lacks reads as no identity and the pair is downgraded) and the dirty tree's working side from disk, with id andslug:from the frontmatter and the title by parseMarkdown precedence (frontmatter, then the first H1, no filename fallback;markdown.tsexplicitMarkdownTitle), the old side taking the title its page row stores; it keeps an R<100 pair on a same-slug respelling, a unique sharedid, or with no id on either side a uniqueslug:line or title (titles also unique among live pages).explicitIdVetois the one explicit-id veto the managed takeovers consult (also the #6727 legacy-slug adoption insync-discovery.ts: two different explicit ids holdlegacy_slug_conflict, reasonexplicit_id_conflict). An add whose id uniquely matches a delete in the range becomes a rename only with continuity (same file name, title or bytes;digestis the sha256 of a file that fits the head read), as decideImportIdentity asks of a move. Downgraded pairs recordread.from/read.to. A dirty-tree verdict is bound to the bytes it read: each kept rename carriesidentityHead(sha256 of the first 64 KiB), classicapplyRenamere-checks it before the identity moves and managedreadSyncContentrefusessource_changedon frozen bytes that differ. GBRA-133 S-51: an id,slug:or title holding U+0000 or a lone surrogate is absent before any SQL (never normalized), so the pair takes the ordinary unconfirmed-rename rules; both identity reads batch every path and, on SQLSTATE 22021/22P05 only, retry path by path, and the inexact pairs carrying a refused value come back inheldRenames(classicpreflight.tsholds them asrename_identity_unreadable, keeping the old page; withholdUnreadableunset, as in managed discovery, the error is rethrown).redecideHeldRenamedecides a held pair again from the kept page's stored id and title once its file changes. Any other error propagates. Pinned bytest/pathological/s-51-rename-identity-unreadable.test.ts.src/core/sync-identity-downgrades.ts— durable records of downgraded pairs (op_checkpointsopsync-identity-downgrade, fingerprint = old page id, open until a disposition is set or the old page is restored or purged; no time window; the checkpoint sweep keeps open records), the purge-hold SQL predicate, the live list (new slug read live), the report lines and the restore argv; the per-pair remedy every surface prints (identityRemedyParts,identityRemedy,withIdentityRemedies,renameIdentityPreviewArgv,remedyAction; on a managed brain the remedy is--closewithcarry_unavailable: managed_remedy_unavailable);settleIdentityDowngrade(setscompleted_keys[0].disposition = { kind: remedied | closed, at }on an open record);identityRestoreAvailable(the decideUnboundWrite rule) keeps the restore off the report and doctor on an unbound Postgres source with a checkout, where it would refuseowner_unavailable.src/core/repair/rename-identity.ts—gbrain repair rename-identity(#6729), explicit-only, preview-bound, destructive.planselects one open pair (--slug/--from), hashesidentityRemedyParts(brain, pair, both page ids and revisions, disposition) and saves the approved set; with no pair named it lists the open pairs. On a managed brain a carry preview returns no items withdetails.code: managed_remedy_unavailableand the--closepreview, and an apply refuses with that code.carryIdentity(classic only): one maintenance transaction under both page locks re-checks the hash, the open record andfenceRowChecks, merges matching fence rows onto the old rows, retires the provisional page underpurgedSlug, moves the old page to the new slug (updateSlugredirect), moves the provisional's page-id rows (movePageIdReferences), imports the new file, settles the recordremedied.--closesettlesclosed. Refusals:fact_rows_collide,managed_remedy_unavailable,changed_since_preview,preview_changed,invalid_params.src/core/persistence/sync-prescreen.ts— #6712 PR 1 (L1): the discovery prescreen and drift baseline. AfterdiscoverManagedSyncfreezes identities,prescreenSyncEntriesreads the pinned blobs (readTreeBlobs, one recursive listing for a large set) and the import provenance of every Git import of an existing page, andclassifyBaselinemarks eachprescreened(disk blob, revision andsyncImportParserForfingerprint all match; bypassed under--fulland for held paths) ordrift(database: the page moved, the file did not;both/unknownin a tree walk or for afile_drifthold). A page whose current revision a committed managed-sync request wrote, or whose writer's publication wrote to its file (a write-throughgiteffect), is not guarded (fileBackedRevisions), and drifted pages understorage.keep_dbprefixes leave the manifest as drift candidates (releaseKeepDbDrift,recordDriftSkip). The run passes prescreened entries throughwaivePrescreenedRun(sync-waivers.ts);freezeEntryholds a drifted importfile_drift(fileDriftHold,sync-page-fault.ts) unlesssameContentAtOriginproves it a no-op.movedDriftHoldsre-screens drift holds whose page moved. Tests:test/sync-prescreen-drift-6712.test.ts(both engines).src/core/persistence/sync-image.ts— #6529: managed sync's image branch. With multimodal embedding on,freezeEntry(sync-run.ts) freezes an image entry as its bytes in base64 (frozenImageIntent;rawHashstays the file sha256, so the working-tree check and the hash no-op are unchanged) andprepareManagedSyncMutation(sync-prepare.ts) hands it toprepareManagedSyncImage, which runsimportImageFilewithprepare(the coordinated pathgbrain importuses inimport-prepare.ts): the importer decides the hash no-op, OCRs and embeds the image at preparation inside the sync budget (--no-embedskips both; the caption chunk's text vector is deferred toembed --stale), and the apply recordssource_path, releases the path's hold and re-reads the snapshot. A company plan refuses (profile_incompatible), a screening preparation (sameContentAtOrigin, the no-op waiver insync-waivers.tsandunchangedManagedImportinimport-mutations.tsreturn early for images) is refused rather than paid for, newer working-tree bytes or a vanished file refusesource_changed, and a Git rename publishes the new slug and soft-deletes the old page.import-file.tsrecordssource_pathon the legacy importer's hash-skip path too (refreshSourcePath), so no image import leaves it NULL. Tests:test/managed-sync-images-5493.test.ts(both engines),test/embed-stale-images-managed-6529.test.ts.src/core/persistence/sync-streamed.ts— Wave B PR 2: managed sync of a Markdown file over the 24 MiB single-string ceiling. Withpages.segmented_storageon,freezeEntry(sync-run.ts) freezes such a file by reference instead of holding it by its size:streamedSyncBodyRefhashes the sha256 and the Git blob id as a stream (sha1 or sha256 by the pinned commit's length) intointent.body_ref(git_blob, orinput_filefor an uncommitted working-tree file); the journal carries no content, and a committed entry whose working tree does not hold its pinned blob, a file overpages.max_bytesor a non-Markdown file is held as before.prepareManagedSyncMutation(sync-prepare.ts) hands it toprepareManagedSyncStreamed, which streams it throughimportStreamedMarkdownFile(page-body/streamed-import.ts,coordinated;movedon a rename keeps an implicit type following the new path;slugis the admitted page, the one recording the file as its origin, as the inline import targets) and publishes database-only, recording the origin throughbindOrigin(B-14: a renamed page keeping its origin takes the file, no twin at the path's slug); a rename moves the page first and re-seals an unchanged body (sealSegmentedPage). A file the streamed path refuses (a facts fence) fails its request with the refusal's code and the run holds it (streamedRefusalHoldinsync-screen.ts); a dry run lists it inscreen_skippedaspage_body_segmented;groupableIntent(sync-group.ts) keeps it out of bulk groups. Tests:test/large-pages/managed-sync-streamed.test.ts(both engines),managed-sync-streamed-crash.test.ts(owner killed atconsumer:prepared),managed-sync-streamed-memory.slow.test.ts(VmHWM),streamed-sync-origin-b14.test.ts(both engines).src/core/persistence/sync-entry-fault.ts— GBRA-133 (#6712 PR 4b): the per-entry faults of a managed sync freeze, so one odd file never stops its source.nullBytesRefusalholds a Markdown text with U+0000content_null_bytes(line of the first NUL; a UTF-16 byte order mark says save as UTF-8), fromscreenFrozenImportwith holds on and as a typed run stop undersync.holds=fail.filterOwnedRefusal(GST-2312, #9024), checked first on the same two paths, holdscontent_filter_owneda blob starting with git-crypt's header or a committed blob whose path names a Git filter driver other thanlfs, configured here or not (pinnedFilterDriverinsync-screen.ts, at the pinned commit or a company plan's revision, read withreadFilterDrivers' batchedgit check-attr --sourceon git 2.40+, orread-treeinto a temporary index andcheck-attr --cachedon an older git; withHARDENED_GIT_ARGSandGIT_NO_LAZY_FETCH=1, so the attribute read runs no repository program and fetches nothing; it first checks withls-treeandcat-file --batch-checkthat each.gitattributesthat applies is present, and a path under a missing one makespinnedFilterDriverthrowgit_object_missingviamissingAttributesRefusal; GST-2331: every read ofsync-blobs.tsruns withHARDENED_GIT_ARGSandNO_LAZY_FETCH_ENV, so the blob reads fetch nothing either and an object a partial clone lacks reads as missing).committedContentOrMissing(called bypinnedContentwhen the pinned read fails) imports a committed file whose blob object is gone from working-tree bytes that hash to that blob id, else throwsgit_object_missing(GST-2331: in a partial clone (syncPartialClonein sync-discovery.ts: a promisor remote orextensions.partialClone), the message names the partial clone and the fix isgit cat-file -p <blob>, and a partial clone that lacks a tree of the synced commit stops the run instead (partialCloneTreeRefusal, from the tree walk and from sync-pass-run.ts's reconcile level read, fixgit ls-tree -r -d <commit>); otherwisegit fsck --connectivity-only); a committed name with U+FFFD that names nothing on disk (a name that is not UTF-8) throwspath_not_utf8first.directoryAtlets a deletion whose name became a directory apply (freeze and the owner's raw-hash check).freezeFaultHoldisfreezeEntry's catch (sync-run.tswrapsfreezeEntryOnce):git_object_missingandpath_not_utf8are held under their codes; a page-body fault (PAGE_BODY_FAULT_CODES:page_body_segmented,page_body_rows_unreadable, e.g. a segmented page whose segment rows don't cover its body) is heldpage_write_failedwithwrite_failure.codeset to that code, whichsync statusclassifies by thefreeze_page_body_*rows ofSYNC_FAULT_TABLE; any otherOperationErrorand every run-scoped error (classifyItemFailurescope run, connection, statement timeout, lock, back-pressure, abort) rethrows, and an unexpected throw is heldpage_write_failedwithwrite_failure.origin: 'freeze'andrequest_id: null, re-tested by every sync until heldHOLD_ATTEMPTS_NEEDS_HUMANtimes; a run withITEM_BREAKER_MIN_ITEMSfaults and no more clean freezes than faults is systemic and rethrows.src/core/tag-limit.ts—TAG_MAX_BYTES(2688, the longest tag both btree indexes ontagsstore, in UTF-8 bytes) andtagLengthHold, thetag_too_longholdclassifyImportHoldreturns, so every content screen, file import and legacy sync hold refuses it;prepareSegmentedTagMutationthrows it before anadd_tagflip. The message names the tag's position and size, never its text (#7052). Pinned bytest/tag-length-7052.test.ts.src/core/url-clone.ts— gbrain-ownedsources add --urlclones (#6946, GBRA-130 C-2).isOwnedClone(configmanaged_cloneor alocal_pathunder the default clone dir) anddefaultCloneDir;urlCloneReadOnlyis the one predicate (owned clone on a brain without managed persistence) the fence writer (fence-write.ts,databaseOnlyReason: 'url_clone'), write-through (skipped: 'url_clone'), timeline write-through, unfenced-facts adoption, the empty-fence guard andsourceMirrorReadOnlyconsult, so nothing gbrain writes lands in a checkout it updates withgit pull --ff-only.urlClonePullBlockreads the tracked changes of a clone whose pull failed and returnspull_blocked_local_changeswith anask_userfix naming the previewgbrain repair url-clone-fences --source <id>;formatUrlClonePullBlockrenders it for sync's stderr (sync/preflight.ts) andcycle.tsputs it in the sync phase detail aspull_blocked. Test:test/pathological/c2-url-clone-fences.test.ts. gbrain itself never writes into an owned clone on an unmanaged brain, but local commits someone else makes there are published bygbrain sources git-reconcile(src/commands/sources-git-reconcile.ts, autopilot each tick: secret scan, rewritten-upstream refusal, repository-root check);sources.refresh_publish_diverged falseorgbrain sources set-sync <id> offkeeps them local.src/core/url-source-origin.ts,src/commands/sources-record-origin.tsandsrc/commands/doctor/checks/url-source-origin.ts— who added a URL source (sources.config.added_by_remote_caller). Both add paths write it (truefor a remote caller,falsefor the local operator); only an explicittruereads as remote. URL sources added before that record existed carry none, and nothing stored tells a remote caller's add from the local operator's (same row, same default clone directory); a clone outside$GBRAIN_HOME/clones/<id>(or aclones/<id>under an earlier home) proves a local add. A URL clone counts whenisOwnedCloneaccepts it, so an unmarked clone at the default directory is listed too.urlSourcesWithoutOrigin(read-only) feeds the wave checkurl_source_origin(host-only,resolution: 'operator',warnwith anask_userfix whose argv is the preview).recordSourceOrigin(engine, ids, { origin, apply, remote })backsgbrain sources record-origin <id>... --remote|--local [--apply] [--json]: it throwstrusted_local_onlyunlessremote === false, previews unlessapply, writestrue(--remote) orfalse(--local) in one transaction that re-reads the rowFOR UPDATEand refusessource_changedif its path or URL moved; on a managed brain that transaction runs insidewithTopologyLocksafterlockTopologyRows, the locks a reclone takes (a held lock refuses the idsource_busy), andrunManagedSourceClonetakes the config it clones with from its own locked admission read, so a record and a reclone never interleave.--remote --applyalso writesLFS_OFF_CLONE_CONFIGinto the repository's shared config (--git-common-dir;git config --file, not run in the checkout) before the row, reads the effective values back (lockDownGaps) and throws when a worktree-scoped or included setting overrides one, and locks down an already-remote source whose checkout lacks it (no git-lfs refusal for it unless Git cannot place the checkout,lfs_unknown); each key's existing values are removed before its one value is written, in aconfig.lockcopy renamed over the config in one step; a throw is reported for its id aswrite_failedand the batch continues. It never removes atrue, and refuses--remotefor a checkout with any trackedfilter=lfspath or a committed.gitattributesdeclaringfilter=lfsoutside a comment line (lfs_tracked, worded per case; read withhardenedGitSyncls-files -- ':(attr:filter=lfs)'plus every committed.gitattributesblob fromls-tree -zrecords split at their first tab, thencat-file, so clone-local attributes cannot hide one, and read again under the locks), or one it cannot inspect (lfs_unknown, whose reason names the cause: checkout missing, not its own repository's top level by a realpath comparison, owned by another user (safe.directory), or a Git read failed), because a lock-down reclone would not match the stored writer manifest there. An unborn HEAD with an empty index (a clone of an empty repository) has no committed attributes and passes. Without git-lfs files the tracked bytes are the same, so no manifest is written. Pinned bytest/url-source-origin.test.ts(PGLite and Postgres).src/core/write-through.ts— shared atomic disk write-through for the canonical ingestion path.resolvePageWriteTarget(engine, slug, sourceId, { includeDeleted? })(active rows by default;includeDeleted: trueresolves a tombstone's recordedsource_pathfor the purge remediation retry) is the exported single source of truth for the ONE file a (source, slug) pair lives in on disk: a source with its ownlocal_pathwrites at that tree's ROOT (never nested under.sources/); a source without one nests under the host repo (sync.repo_path, default at root, non-default under.sources/<id>/) unless that path is another source's own working tree (leak guard →source_repo_belongs_to_other_source; a live source whoselocal_pathis relative counts as owning every tree, one absolute only on another OS does not, and alocal_pathorsync.repo_pathtarget not absolute on this host (isHostAbsolutePath) isrepo_not_found); the page's recordedsource_path(or a contained absolutefile://source_uri; a relative or host-onlyfile://names no local file and is read as absent) is preferred over a slug-derived name so writes land in the file of record instead of minting a twin; andisWriteTargetContainedrejects hostile rows escaping the tree (path_escapes_source_root). The ok-result also carriessourcePathToBind— the target expressed in the file scanner'ssource_pathconvention for the source's pinnedslug_root_mode(or the mode its first sync would pin, viascannerSlugRootMode): GIT-ROOT-relative undergit-rootwhen the scan root sits inside a git repo, scan-root-relative undersource-rootand for non-git or git-root scan roots, so a put-born page binds the same form managed sync and delete-reconcile key on. Every recorded-path reader (write targets, takes, reconcile, audit, export restore, doctor) decodes with the same mode (resolveSourceLocalFilePath(..., slugRootMode)): undersource-rootthe scope prefix is removed only from the legacy Git-root form whose remainder names the page slug, and basename rows resolve under the unstripped slug directory. The resolver is shared bywritePageThrough, the facts fence writer (src/core/facts/fence-write.ts), and fence forget (src/core/facts/forget.ts) — the fence appends to the page's file, so all writers MUST compute the identical path or the fence lands in a file sync never reads back and the next extract_facts reconcile deletes the fence-owned DB rows.writePageThrough(engine, slug, {sourceId?, frontmatterOverrides?, inlineOnly?, logger?, expectedFileBytes?, deferCommit?})resolves the target through it, re-reads the just-written DB row (getPage), renders an inline page viaserializePageToMarkdown, and writes the.md. A page stored in segments is never rendered whole: its file is measured from its segments at the snapshot's revision (unreadPageFile; a page that moved since refusesrevision_conflict), checked againstPUSH_SCAN_MAX_FILE_BYTESbeforesource_pathis bound (a body already over the cap bybody_bytesis refused without streaming), streamed throughstageStreamedContenton the engine it was given (so a caller inside a transaction works) keeping the existing file's mode, and renamed over the target after the file-changed check;frontmatterOverrideson such a page return an error result, andinlineOnly(the derived writer) skips it assegmented_pageso the brain has a committable artifact that round-trips throughgbrain sync. Rendering from the row keeps the serialized content consistent at write time. The fsync-backedatomicWriteFileSyncstages and renames the file after required source-path bookkeeping; lock/lease checks run before publication.put_pageholds the root lock before importing and invokes write-through inside its database transaction, so ordinary filesystem rejection rolls back existing content, tags, chunks, and versions. A crash or database COMMIT failure after rename can still leave canonical Markdown ahead of the index; this is not distributed ACID or a durable queue. Never throws — returnsWriteThroughResult { written, path?, content? (the bytes written; inline pages only), skipped?: 'disabled_by_config' | 'url_clone' | 'no_repo_configured' | 'repo_not_found' | 'source_repo_belongs_to_other_source' | 'page_not_found_after_write' | 'path_escapes_source_root' | 'case_insensitive_collision' | 'file_changed' | 'over_push_scan_cap' | 'segmented_page', warning?, error? }(file_changed: the caller'sexpectedFileBytespreimage, null for absent, no longer matches the file under the source filesystem lock, so the file is left untouched) so the caller decides messaging + exit codes.withNoRepoWriteThroughWarning(result, sourceId)decorates an unwrittenno_repo_configuredresult (and arelative_rootone, namingsources set-path) withwarning(the write landed only in the database; bind the token/server to a git-backed source or configurelocal_path/sync.repo_path);put_pageapplies it for untrusted callers only (ctx.remote !== false), so local CLI responses and thedisabled_by_configoperator opt-out stay silent.isWriteThroughDisabled(shared with the fence lane, ~30s per-engine cache) honors thesync.write_throughopt-out. Trust gating (subagent sandbox, dry-run) stays at the CALLER. On a durability-hardened repo (isDurabilityHardened— the gbrain post-commit hook is installed, i.e. the user rangbrain sources harden), a successful write is best-effort COMMITTED viacommitWriteThroughFile(path-limitedgit commit -- <file>, never sweeps unrelated edits; the hook then background-pushes) unless the caller passesdeferCommit(the derived write-through commits its batch itself, #8073;deletePageThroughtakes it too) so write-through content reaches git instead of accumulating uncommitted forever; result carriescommitted?: boolean. Unhardened repos keep write-only behavior.deletePageThrough(engine, slug, {sourceId?, target?, logger?})is the delete-side sink (sole caller: thedelete_pageop): resolves the same target, unlinks the.md, and on a hardened repo best-effort commits the removal path-limited through the same helper with subjectgbrain: delete write-through <slug>, reportingcommitted?: booleanonDeleteThroughResult(absent when unhardened or when the commit did not land — the unlink still stands; a never-committed page leaves nothing to commit, so no empty commit). Pinned bytest/delete-write-through-commit.test.ts. Consumers:put_pageop andgbrain brainstorm/lsd --saveviapersistSavedIdea. Pinned bytest/write-through.test.ts+test/write-through-commit.test.ts. Theput_pageop is that deciding caller for direct writes: a skip outside the deliberate DB-only set (no_repo_configured/disabled_by_config/subagent_sandbox/dry_run) throwsstorage_errorinside the import transaction, rolling back the page revision, tags, chunks and version snapshot instead of deleting a just-created row afterward. #6946/#7098: on a read-only checkout (readOnlyCheckoutinmirror-read-only.ts: amirror-readonlysource, or a gbrain-owned--urlclone of an unmanaged brain),writePageThroughreturnsskipped: 'mirror_read_only' | 'url_clone'anddeletePageThroughreturnsremoved: falsewith the same skip;timeline-write-through.ts, the fact fence writer,forgetand the unfenced-fact pass skip the same way.