Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(sync): nested typed metafiles become pages (sync.metafile_pages)

garrytanb904504cda61
diff --git a/docs/architecture/key-files/canonical-reconciliation.md b/docs/architecture/key-files/canonical-reconciliation.md
index 64744c0580..093dd6c128 100644
--- a/docs/architecture/key-files/canonical-reconciliation.md
+++ b/docs/architecture/key-files/canonical-reconciliation.md
@@ -35,7 +35,7 @@
- `src/core/ghost-pages.ts` — #6696 B5, the one ghost-page classifier: a ghost is a live page for which `liveFileDrift` returns reason `canonical_file_missing` on the source's canonical owner host (`prepareFileTarget` tags that refusal `detail: 'canonical_file_missing'`). `scanGhostSource` reads a source's live pages in id order (at most `GHOST_SCAN_LIMIT`), resolves each recorded canonical path exactly as `prepareFileTarget` does and stats it, skips `publishesDatabaseOnly` and legacy slugs, and runs the full check on at most `candidateLimit` candidates; it returns the ghosts, `inspected`, `file_backed` (the mass-delete valve's population), `truncated` and the owner it ran under (host, worktree, owner epoch, incarnation). Off the owner host a source is `not_applicable` (`not_owner_host`, or `not_applicable` with no binding); a missing root is `unknown` (`storage_unavailable`), a stat error, invalid gbrain.yml or inconclusive check `unknown` (`ambiguous_storage`). `ghostPageNow` re-checks one page (the repair's recheck); `readGhostPages(engine, { sourceIds?, sampleLimit? })` is the counts-and-samples summary for doctor and the read-scope health op. Tests: `test/ghost-pages-6696.test.ts`.
- `src/core/repair/ghost-pages.ts` — `gbrain repair ghost-pages --source <id>` (#6696 B5): explicit-only, preview-bound, destructive consent (`GHOST_CONSENT_TEXT`: the 72 h purge fuse, the per-slug `gbrain restore <slug> --force` undo, and the keep path of restoring the file and syncing). The preview binds the ghost set to the owner and each page's revision and path; the apply refuses `not_owner_host`, `ghost_storage_unknown`, `preview_changed` on an owner change, and `ghost_mass_delete_refused` (`massGhosts`: the sync valve, `MASS_RECONCILE_RATIO` over more than `MASS_RECONCILE_MIN_PAGES` file-backed pages, unless `massReconcileAllowed()`). Each page re-checks with `ghostPageNow`, then a managed brain submits one `managed_maintenance_retire_ghost_page` request (`prepareGhostPageRetirement`, dispatched from `prepared-maintenance.ts`: re-check, `delete_page` with `allowMissingFile`, refusal unless the prepared file target is the approved path with no bytes, so filesystem publication refuses a file that appeared later); an unmanaged brain soft-deletes in one transaction after the same check. Outcomes `soft_deleted`, `file_restored` (asks for a new preview), `changed_since_preview`. Doctor `ghost_pages` (`src/commands/doctor/checks/ghost-pages.ts`, BRAIN, after `fence_integrity`) reports the count, samples and coverage with the preview as its fix, `ok` + info off the owner host, unknown on an unreadable checkout; `gbrain pages ghosts` (`src/commands/pages-ghosts.ts`) lists them read-only.
- `src/core/repair/legacy-twins.ts` — `gbrain repair legacy-twins --source <id>` (#6885): explicit-only, preview-bound, destructive consent (`LEGACY_TWINS_CONSENT_TEXT`). `scanLegacyTwins` reads a source's live pages with no recorded origin and no `database_only_reason` in id batches (at most `LEGACY_TWINS_SCAN_LIMIT`), keeps those whose slug `slugifyPath` folds differently, and pairs each with the live page at the folded slug that records a file (at most `LEGACY_TWINS_LIMIT` pairs and decisions). `pairVerdict` lists a pair as a decision (never merged) for differing `content_hash`, several legacy candidates, a twin file `liveFileDrift` does not call `agrees`, a file at the twin's own slug path, twin withdrawals, a legacy `file:` URI or a twin slug outside the op grammar. The preview binds pairs to the owner (host, worktree, owner epoch, incarnation) and both pages' ids, slugs and revisions; the apply refuses `not_owner_host`, `legacy_twins_storage_unknown`, `preview_changed` and `legacy_twin_mass_merge_refused` (`massTwins`, the sync valve). Each pair re-checks with `pairNow`, then a managed brain submits one `managed_maintenance_merge_legacy_twin` request on the twin (`prepareLegacyTwinMerge`, dispatched from `prepared-maintenance.ts`: no file target, `databaseOnlyReason: 'shared_origin'`, the legacy key in `additionalPageKeys`, `pairLocked` under the publication locks); an unmanaged brain merges in `maintenanceTransaction` under both page locks. `applyTwinMerge` records the twin's `source_path` on the legacy page, clears the twin's origin (so its tombstone's retention purge is database-only, never a `shared_origin` refusal), moves links (deduplicated; pair links stay), timeline rows, raw data, attachments, page aliases and facts about the twin, records the twin slug as a `slug_aliases` row, versions and soft-deletes the twin, and moves the twin's `sync-import-provenance` record to the legacy page at its post-write revision. Outcomes `merged`, `changed_since_preview`. Tests: `test/repair-legacy-twins-6885.test.ts` (Postgres: `test/e2e/repair-legacy-twins-6885-postgres.test.ts`).
-- `src/core/persistence/unindexed-files.ts` — #6865 the unindexed-file detector: `findUnindexedFiles(engine, sourceId, opts)` streams `git ls-tree -r -l -z` of the source's last synced commit, filters it through discovery's own `loadSyncEligibility`, and in batches (one `pages.source_path = ANY` read on `pages_source_path_idx`, one hold read by fingerprint) keeps files with no live page recording their origin (source-path space, with the legacy Git-root spelling in source-root mode), no hold and no scheduled re-screen (`readGitHoldRetryPaths`; those count as `scheduled`); a file whose path slug belongs to a live page with another or no origin is still unindexed and counted `slug_taken`. Found files are screened read-only with `screenImportContent` (at most 2,000 per pass, the rest `unscreened`). Folder-scaffolding names sync skips on purpose (`isSyncMetafile`) that would otherwise be eligible (checked against a probe name in the same directory plus `sync.exclude` and the reserved skill paths) and carry a frontmatter `type:` or `title:` are counted apart as `metafile_skipped` with samples, and never scheduled. A time or count budget stops it with `complete: false` and a cursor (the last Git path, compared in byte order, which is Git's recursive tree order). `refreshUnindexedFiles` continues an incomplete stored result, schedules the found paths (`requestGitHoldRetry`, a scheduling write only) and stores one `op_checkpoints` row per source (op `unindexed-files`, fingerprint the source id; the 7-day checkpoint purge applies). `judgeUnindexedFiles` is doctor's read: unscheduled finds, scheduled paths still in the retry row (waiting for a sync), and consumed paths that still have no page and no hold, without scanning. Test: `test/unindexed-files.test.ts`.
+- `src/core/persistence/unindexed-files.ts` — #6865 the unindexed-file detector: `findUnindexedFiles(engine, sourceId, opts)` streams `git ls-tree -r -l -z` of the source's last synced commit, filters it through discovery's own `loadSyncEligibility`, and in batches (one `pages.source_path = ANY` read on `pages_source_path_idx`, one hold read by fingerprint) keeps files with no live page recording their origin (source-path space, with the legacy Git-root spelling in source-root mode), no hold and no scheduled re-screen (`readGitHoldRetryPaths`; those count as `scheduled`); a file whose path slug belongs to a live page with another or no origin is still unindexed and counted `slug_taken`. Found files are screened read-only with `screenImportContent` (at most 2,000 per pass, the rest `unscreened`). Folder-scaffolding names sync skips on purpose (`isSyncMetafile`) that would otherwise be eligible (checked against a probe name in the same directory plus `sync.exclude` and the reserved skill paths) and carry a frontmatter `type:` or `title:` are counted apart as `metafile_skipped` (only under `sync.metafile_pages off`: under the default `typed` the eligibility predicate admits a nested one, so it is an ordinary unindexed file; each tree batch primes its metafile heads) with samples, and never scheduled. A time or count budget stops it with `complete: false` and a cursor (the last Git path, compared in byte order, which is Git's recursive tree order). `refreshUnindexedFiles` continues an incomplete stored result, schedules the found paths (`requestGitHoldRetry`, a scheduling write only) and stores one `op_checkpoints` row per source (op `unindexed-files`, fingerprint the source id; the 7-day checkpoint purge applies). `judgeUnindexedFiles` is doctor's read: unscheduled finds, scheduled paths still in the retry row (waiting for a sync), and consumed paths that still have no page and no hold, without scanning. Test: `test/unindexed-files.test.ts`.
- `src/commands/doctor/checks/unindexed-files.ts` — #6865 doctor `unindexed_files` (BRAIN, after `missing_recorded_files`): reads `judgeUnindexedFiles` for each bound managed Git source; `ok` when every result is complete, recent and nothing is missing; `warn` with counts by code, samples and age when files are unindexed (fix `gbrain sources retry-held <id> --unindexed`, `then` the follow-up sync from `gitFollowUpSync`, verify `gbrain doctor --only unindexed_files --json`) or scheduled and waiting (fix the sync); info `unknown` when a result is missing, older than 7 days or incomplete with nothing found, naming the maintenance phase and the command; info `not_applicable` on a classic brain. `metafile_skipped` files are named in the message and details and never make it warn; alone they are info `degraded` with a `user` fix (rename the file, then the sync). Test: `test/unindexed-files.test.ts`.
- `src/commands/doctor/checks/missing-recorded-files.ts` — #6609 doctor `missing_recorded_files` (BRAIN, after `ghost_pages`): the classic-brain counterpart of `ghost_pages`. Read-only; per source with a checkout on this host and managed persistence off it runs `scanMissingRecordedFiles` (`src/core/persistence/detached-pages.ts`) and warns with counts, samples and an `ask_user` fix (put the file back and sync, or `gbrain delete` then `gbrain restore <slug> --source-id <id> --detach`) for live pages whose recorded file a `gbrain sync --full` would not find; `ok` + `not_applicable` when no source qualifies. Test: `test/restore-detach-6609.test.ts`.
- `src/core/persistence/overwritten-edits.ts` — #6712 follow-up: `scanOverwrittenEdits` finds live pages whose database-only revision a managed-sync import replaced with different content and no hold, from durable rows only (it survives receipt compaction): `page_versions.write_request_id` / `archived_write_request_id`, the writer's committed receipt (`outcome.persistence.mode = 'database'`, not an import, no `git` effect for that revision, not a read-only mirror write), the archiving request recognised as a managed-sync import by intent kind or, once compacted, by operation `submit_job` + `outcome.imported_file` without `connector_database`, and `reconcileCanonical` digests (the import's own revision differs; no later revision holds the edit again). `high` or `unknown` (`no_persistence_outcome`, `import_content_unreadable`, `segmented`); the newest open overwrite per page; at most `OVERWRITE_SCAN_LIMIT` candidate versions per source. Revisions with no recorded writer are not reported.
diff --git a/docs/architecture/key-files/files-and-sync-2.md b/docs/architecture/key-files/files-and-sync-2.md
index 09ca49bb77..20574aadcc 100644
--- a/docs/architecture/key-files/files-and-sync-2.md
+++ b/docs/architecture/key-files/files-and-sync-2.md
@@ -14,7 +14,8 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/sync-upstream-rewrite.ts` — classic sync's upstream watch for a source that syncs with pull (GBRA-133 S-58/S-59). `recordUpstreamBeforeFetch` (called by `src/commands/sync/preflight.ts` before every pull) stores in `sources.config.upstream_baseline` the upstream commit HEAD contains, only when HEAD contains it, so a rewritten upstream fetched earlier never replaces it; `settleUpstreamAfterPull` records the new baseline and clears `sources.config.upstream_divergence` after a pull that fast-forwarded or was up to date, and after a pull that failed with HEAD and `@{upstream}` diverged stores `upstream_rewritten` (baseline not an ancestor of the new upstream), `upstream_unknown` (no baseline or its object is gone) or `upstream_diverged` (baseline contained: plain local commits); nothing is classified while a rebase, merge, cherry-pick or revert marker (`GIT_OPERATION_MARKERS` in `src/core/git/commit-push.ts`) exists. Best effort: it never throws into the sync and never writes a sync-failure ledger row. `upstreamFix` is the typed next step (`ask_user` reset bound to the observed SHAs for rewritten/unknown, never a merge; `gbrain git commit-push --pull` for diverged; both `then` the sync). Read by `performSyncInner` (`result.upstream`), `buildSingleSyncJsonEnvelope`, `gbrain sources status --json` (`upstream`) and doctor `sync_failures` (`details.upstream`, warn, local fix; remote callers get counts only). Pinned by `test/pathological/s-58-upstream-rewrite.test.ts`.
- `src/core/sync-attempt.ts` + `src/commands/doctor/sync-outcome.ts` — doctor `sync_freshness` for a source with no successful sync (`last_sync_at` NULL, #4960). `readLastSyncAttempt` reads, read-only, the newest `sync` Minions job of the source and, on a managed brain, `readSyncStatus` (holds, last error, cursor, its `next`); nothing found is `no_attempt`, an unreadable read is `no_attempt` with `unreadable`. A live first-sync lock inside the staleness ceiling is `warn` (`sync_first_run_in_progress`, fix `next: wait`); no lock is `fail` (`sync_no_successful_sync`) naming last attempt, result and held count, with a per-`reason` fix (`attempt_queued` wait, `holds_pending` the managed `next` or `sync status`, `last_attempt_unsuccessful` inspect the job then retry, `no_attempt` retry). Entries land in `details.no_successful_sync[]`; these sources stay in `stale_count`. Test: `test/doctor-sync-freshness-outcome-4960.test.ts`.
-- `src/core/sync.ts` — Pure sync functions (manifest parsing, filtering, slug conversion). Exported `pruneDir(name: string): boolean` is the single source of truth for descent-time directory exclusion across walkers — blocks `node_modules` (no leading dot, so a naive walker would descend into it and inflate MISSING_OPEN counts via vendor packages), `vendor`/`dist`/`build`/`venv`, dot-prefix dirs, and `*.raw` sidecars — NOT `ops/`, which is ordinary user content (the bundled daily-task-manager stores `ops/tasks` there); `isSyncable` applies it per path segment, and `walkMarkdownFiles` in `src/commands/extract.ts` + `listTextFiles` in `src/core/cycle/transcript-discovery.ts` consult it BEFORE recursing to save the IO of walking thousands of vendor files. `manageGitignore` worktree discriminator matches the gitdir path segment (`/modules/<name>` = submodule, `/worktrees/<name>` = worktree, per Git's documented layout) so Conductor worktrees (first-class repos) get `.gitignore` management for storage-tiering. The sync-failure ledger (failure store, error classifier, the shared bookmark gate, and the doctor severity rule) lives in `src/core/sync-failure-ledger.ts`; `sync.ts` re-exports `classifyErrorCode`, `summarizeFailuresByCode`, `loadSyncFailures`, `unacknowledgedSyncFailures`, `acknowledgeSyncFailures`, `recordSyncFailures`, `decideSyncFailureSeverity`, `applySyncFailureGate`, and the `SyncFailure` type for backward-compatible imports — see its entry below. `isSyncable` factored through private `classifySync(path, opts): SyncableReason | null`; exported companion `unsyncableReason(path, opts)` returns the same tagged reason or null when syncable. `SYNC_SKIP_FILES` is a named export (the canonical metafile basenames `schema.md`, `index.md`, `log.md`, `README.md`, `RESOLVER.md`, skipped at any depth); `SYNC_ROOT_SKIP_FILES` (#5186, W14 P1.5b) adds the bootstrap scaffolding `AGENTS.md` / `CLAUDE.md` at depth 0 only, and `isSyncMetafile(path)` is the one predicate `classifySync` and the bulk-import collector (`commands/import.ts`) share (the managed effect scan's `isMetafilePage` in `persistence/effects.ts` still reads `SYNC_SKIP_FILES` directly), so an earlier-indexed root `agents` page survives under the #1433 guard (`test/sync-root-agents-metafile.test.ts`). `SyncableReason` union: `'metafile' | 'strategy' | 'pruned-dir' | 'include-glob-miss' | 'exclude-glob-hit' | 'malformed-path'`. Malformed filenames are TWO-TIER: `hasMalformedPathSegment` (ADMISSION — control chars on any path; square brackets on `.md`/`.mdx` paths only, so code-strategy lanes keep indexing `app/[id]/page.tsx` framework layouts) vs `isPoisonedPath` (DESTRUCTION — only the injection signature `](` or control chars; sync's row-DELETING lanes gate on this so a bare-bracket markdown row already in the DB survives reconcile while its file exists). `sanitizePathForDisplay` scrubs control bytes + caps length before echoing such paths. The un-syncable cleanup loop (`sweepUnsyncableModified` in `src/commands/sync/deletes.ts`) guards on `unsyncableReason(path)` being `'metafile'` OR `'pruned-dir'` so previously-indexed metafile pages AND deliberately put-created pages under pruned dirs survive every re-sync. Does NOT cover `manifest.deleted` (the upstream filter already strips metafiles). Pinned by `test/sync-isSyncable-shape.test.ts` (15 cases, duality contract) + `test/sync-metafile-skip.test.ts` (3 PGLite cases incl. the renamed `.md → .txt` negative). `pruneDir`: `pruneDir(name, parentDir?)` extended with optional `parentDir`. When provided, additionally rejects directories containing `.git` as a FILE — the git submodule gitfile pattern (regular repos have `.git` as a DIRECTORY; submodules as a file pointing into the parent's `.git/modules/`). Sync + extract walkers thread `parentDir` so the gitfile-as-FILE check fires per descend step. Best-effort: `statSync` failures fall through and treat as a normal dir. Prevents phantom imports from a worktree-with-submodules sync walking into submodule trees. Pinned by `test/sync-walker-submodule.test.ts`. The legacy failure ledger re-export is distinct from managed cursor-keyed mirrors: repeat managed observation does not inflate attempts, success clears only the matching cursor, and managed failures cannot be acknowledged or auto-skipped. `isMultimodalEnabled(env)` (`GBRAIN_EMBEDDING_MULTIMODAL=true`) is the one predicate managed discovery, the hold re-screen, `embed --stale`, the blocked-projection hint and doctor `image_embedding_coverage` read for whether images are imported and embedded.
+- `src/core/sync.ts` — Pure sync functions (manifest parsing, filtering, slug conversion). Exported `pruneDir(name: string): boolean` is the single source of truth for descent-time directory exclusion across walkers — blocks `node_modules` (no leading dot, so a naive walker would descend into it and inflate MISSING_OPEN counts via vendor packages), `vendor`/`dist`/`build`/`venv`, dot-prefix dirs, and `*.raw` sidecars — NOT `ops/`, which is ordinary user content (the bundled daily-task-manager stores `ops/tasks` there); `isSyncable` applies it per path segment, and `walkMarkdownFiles` in `src/commands/extract.ts` + `listTextFiles` in `src/core/cycle/transcript-discovery.ts` consult it BEFORE recursing to save the IO of walking thousands of vendor files. `manageGitignore` worktree discriminator matches the gitdir path segment (`/modules/<name>` = submodule, `/worktrees/<name>` = worktree, per Git's documented layout) so Conductor worktrees (first-class repos) get `.gitignore` management for storage-tiering. The sync-failure ledger (failure store, error classifier, the shared bookmark gate, and the doctor severity rule) lives in `src/core/sync-failure-ledger.ts`; `sync.ts` re-exports `classifyErrorCode`, `summarizeFailuresByCode`, `loadSyncFailures`, `unacknowledgedSyncFailures`, `acknowledgeSyncFailures`, `recordSyncFailures`, `decideSyncFailureSeverity`, `applySyncFailureGate`, and the `SyncFailure` type for backward-compatible imports — see its entry below. `isSyncable` factored through private `classifySync(path, opts): SyncableReason | null`; exported companion `unsyncableReason(path, opts)` returns the same tagged reason or null when syncable. `SYNC_SKIP_FILES` is a named export (the canonical metafile basenames `schema.md`, `index.md`, `log.md`, `README.md`, `RESOLVER.md`, skipped at any depth unless `SyncableOptions.metafilePage` says a nested one is a page: `metafileIsPage(path, head, mode)` is true for an `isNestedSkipMetafile` path whose closed leading frontmatter has a non-empty top-level `type:` or `title:` under `sync.metafile_pages` `typed`, the one default `DEFAULT_METAFILE_PAGES_MODE`; `off` skips every metafile; `readMetafilePagesMode` reads the key); `SYNC_ROOT_SKIP_FILES` (#5186, W14 P1.5b) adds the bootstrap scaffolding `AGENTS.md` / `CLAUDE.md` at depth 0 only, and `isSyncMetafile(path)` is the one predicate `classifySync` and the bulk-import collector (`commands/import.ts`) share (the managed effect scan's `isMetafilePage` in `persistence/effects.ts` adds the head of the file on disk, so a typed nested metafile page is mirrored and published like any page), so an earlier-indexed root `agents` page survives under the #1433 guard (`test/sync-root-agents-metafile.test.ts`). `SyncableReason` union: `'metafile' | 'strategy' | 'pruned-dir' | 'include-glob-miss' | 'exclude-glob-hit' | 'malformed-path'`. Malformed filenames are TWO-TIER: `hasMalformedPathSegment` (ADMISSION — control chars on any path; square brackets on `.md`/`.mdx` paths only, so code-strategy lanes keep indexing `app/[id]/page.tsx` framework layouts) vs `isPoisonedPath` (DESTRUCTION — only the injection signature `](` or control chars; sync's row-DELETING lanes gate on this so a bare-bracket markdown row already in the DB survives reconcile while its file exists). `sanitizePathForDisplay` scrubs control bytes + caps length before echoing such paths. The un-syncable cleanup loop (`sweepUnsyncableModified` in `src/commands/sync/deletes.ts`) guards on `unsyncableReason(path)` being `'metafile'` OR `'pruned-dir'` so previously-indexed metafile pages AND deliberately put-created pages under pruned dirs survive every re-sync. Does NOT cover `manifest.deleted` (the upstream filter already strips metafiles). Pinned by `test/sync-isSyncable-shape.test.ts` (15 cases, duality contract) + `test/sync-metafile-skip.test.ts` (3 PGLite cases incl. the renamed `.md → .txt` negative). `pruneDir`: `pruneDir(name, parentDir?)` extended with optional `parentDir`. When provided, additionally rejects directories containing `.git` as a FILE — the git submodule gitfile pattern (regular repos have `.git` as a DIRECTORY; submodules as a file pointing into the parent's `.git/modules/`). Sync + extract walkers thread `parentDir` so the gitfile-as-FILE check fires per descend step. Best-effort: `statSync` failures fall through and treat as a normal dir. Prevents phantom imports from a worktree-with-submodules sync walking into submodule trees. Pinned by `test/sync-walker-submodule.test.ts`. The legacy failure ledger re-export is distinct from managed cursor-keyed mirrors: repeat managed observation does not inflate attempts, success clears only the matching cursor, and managed failures cannot be acknowledged or auto-skipped. `isMultimodalEnabled(env)` (`GBRAIN_EMBEDDING_MULTIMODAL=true`) is the one predicate managed discovery, the hold re-screen, `embed --stale`, the blocked-projection hint and doctor `image_embedding_coverage` read for whether images are imported and embedded.
+- `src/core/sync-metafile-pages.ts` — the head readers behind `sync.metafile_pages`: `metafilePagePredicate(mode, read, rootRelative)` (memoized, the `SyncableOptions.metafilePage` every classifying caller passes), `diskMetafileHeads(root)` (regular files only, never a symlink), `gitMetafileHeads(gitRoot, commits)` (first commit that has the path; `prime` batch-reads blobs a caller already streams through one `cat-file --batch-check` plus one `--batch`), `firstMetafileHead` (disk, then the last synced blob, so a deleted file is judged as last committed), `listMetafileNamedBlobs` (one `ls-tree`), and the classic backfill marker `sync.metafile_pages.applied.<source>` (`metafileBackfillDue` / `recordMetafilePagesApplied`, written with the bookmark): a source that has not finished a sync under `typed` adds its tree's nested metafile-named files to the next delta once. Managed sync instead folds the mode into the pass selection fingerprint (`sync-pass-run.ts`; unchanged under `off`). Only metafile-named paths are ever read. `config set sync.metafile_pages` refuses a value outside `typed | off` (`src/commands/config/sync-metafile-pages-value.ts`); the restore check and doctor `missing_recorded_files` (`persistence/detached-pages.ts`) judge a recorded nested metafile with the same disk-then-last-synced predicate `sync --full` uses. Pinned by `test/sync-metafile-pages.test.ts` (classic) and `test/persistence-sync-metafile-pages.test.ts` (managed, PGLite and Postgres).
- `src/core/sync-rename-identity.ts` — the one confirmation stage for inexact Git renames (#6729). `confirmRenameIdentities` reads committed sides through one `git cat-file --batch` stream (64 KiB heads) and the dirty tree's working side from disk, with id and `slug:` from the frontmatter and the title by parseMarkdown precedence (frontmatter, then the first H1, no filename fallback; `markdown.ts` `explicitMarkdownTitle`), the old side taking the title its page row stores; it keeps an R<100 pair on a same-slug respelling, a unique shared `id`, or with no id on either side a unique `slug:` line or title (titles also unique among live pages). `explicitIdVeto` is the one explicit-id veto the managed takeovers consult (also the #6727 legacy-slug adoption in `sync-discovery.ts`: two different explicit ids hold `legacy_slug_conflict`, reason `explicit_id_conflict`). An add whose id uniquely matches a delete in the range becomes a rename only with continuity (same file name, title or bytes; `digest` is the sha256 of a file that fits the head read), as decideImportIdentity asks of a move. Downgraded pairs record `read.from` / `read.to`. A dirty-tree verdict is bound to the bytes it read: each kept rename carries `identityHead` (sha256 of the first 64 KiB), classic `applyRename` re-checks it before the identity moves and managed `readSyncContent` refuses `source_changed` on frozen bytes that differ. GBRA-133 S-51: an id, `slug:` or title holding U+0000 or a lone surrogate is absent before any SQL (never normalized), so the pair takes the ordinary unconfirmed-rename rules; both identity reads batch every path and, on SQLSTATE 22021/22P05 only, retry path by path, and the inexact pairs carrying a refused value come back in `heldRenames` (classic `preflight.ts` holds them as `rename_identity_unreadable`, keeping the old page; with `holdUnreadable` unset, as in managed discovery, the error is rethrown). `redecideHeldRename` decides a held pair again from the kept page's stored id and title once its file changes. Any other error propagates. Pinned by `test/pathological/s-51-rename-identity-unreadable.test.ts`.
diff --git a/docs/guides/live-sync.md b/docs/guides/live-sync.md
index 993aeb8895..8f8d912627 100644
--- a/docs/guides/live-sync.md
+++ b/docs/guides/live-sync.md
@@ -142,7 +142,8 @@ Timing knobs the drain uses:
- **Tunables** you set and keep: `sync.bulk_size`, `sync.lanes`, `sync.exclude`, `sync.include_hidden`,
`sync.include_working_tree`, `sync.holds`, `sync.write_through`, `sync.cost_gate_min_usd`, `sync.on_commit`,
- `sync.freshness_target_seconds` ([on-commit sync](on-commit-sync.md)).
+ `sync.freshness_target_seconds` ([on-commit sync](on-commit-sync.md)), `sync.metafile_pages`
+ ([what gets synced](#what-gets-synced)).
- **Rollback keys**, the way back a notice or migration promised: `sync.job_drain`, `sync.foreground_priority`,
`sync.federated_v2`, `sync.waive_batch`, `sync.bulk`. Each one set to `false` restores the earlier behavior, and
stays honored until at least 2027-01-14 (`CONFIG_ROLLBACK_WINDOWS` in `src/core/wire-skew.ts`). They are not
@@ -331,7 +332,20 @@ Triggers sync on push events for instant sync (<5s).
Sync only indexes "syncable" markdown files. These are excluded by design:
- Hidden paths (`.git/`, `.raw/`, etc.) and vendored/generated trees
(`node_modules/`, `dist/`, `build/`, `venv/`)
-- Meta files: `README.md`, `index.md`, `schema.md`, `log.md`, `RESOLVER.md`
+- Meta files: `README.md`, `index.md`, `schema.md`, `log.md`, `RESOLVER.md` at any depth
+ (and `AGENTS.md`, `CLAUDE.md` at the source root), unless the file is a typed page (below)
+
+A meta-named file below the source root whose frontmatter has a `type:` or
+`title:` (for example `projects/acme-example/index.md` starting with
+`---\ntype: project\n---`) is an ordinary page: incremental sync, `sync --full`,
+the bulk import and managed sync all import it, edits refresh it and deleting
+the file soft-deletes its page. A bare one (no frontmatter, or neither key) and
+every meta file at the source root stay skipped, and a page an older gbrain
+indexed at such a path is kept (#1433). This is `sync.metafile_pages`:
+`typed` (the default) or `off`, which skips every meta file as before
+(`gbrain config set sync.metafile_pages off`). The first sync after the upgrade,
+or after setting it back to `typed`, imports the typed files already in the
+tree once; it deletes or rewrites nothing else.
A dot-directory you deliberately keep content in (say `.decisions/`) can be
waived back in with `--include-hidden '<glob>'` on `gbrain sync` — the glob
diff --git a/docs/guides/repair.md b/docs/guides/repair.md
index f0cffb1ff1..eefd350add 100644
--- a/docs/guides/repair.md
+++ b/docs/guides/repair.md
@@ -2661,7 +2661,9 @@ clean while incomplete) and schedules a re-screen; doctor
(the page was deleted while the file stayed committed) are never scheduled:
rename one of the two files, or delete the file or restore the page.
`metafile_skipped` (never scheduled) lists titled scaffolding files sync skips
-on purpose (`index.md`, `README.md`, ...): rename one
+on purpose (`index.md`, `README.md`, ...) under `sync.metafile_pages off`; under
+the default `typed` a nested titled one is an ordinary unindexed file. To keep
+`off` and still import one, rename it
(`investors/fund-a/index.md` to `investors/fund-a.md`), commit and sync.
## Resume
diff --git a/llms-full.txt b/llms-full.txt
index d135b6eff3..d295138486 100644
--- a/llms-full.txt
+++ b/llms-full.txt
@@ -6910,7 +6910,8 @@ Timing knobs the drain uses:
- **Tunables** you set and keep: `sync.bulk_size`, `sync.lanes`, `sync.exclude`, `sync.include_hidden`,
`sync.include_working_tree`, `sync.holds`, `sync.write_through`, `sync.cost_gate_min_usd`, `sync.on_commit`,
- `sync.freshness_target_seconds` ([on-commit sync](on-commit-sync.md)).
+ `sync.freshness_target_seconds` ([on-commit sync](on-commit-sync.md)), `sync.metafile_pages`
+ ([what gets synced](#what-gets-synced)).
- **Rollback keys**, the way back a notice or migration promised: `sync.job_drain`, `sync.foreground_priority`,
`sync.federated_v2`, `sync.waive_batch`, `sync.bulk`. Each one set to `false` restores the earlier behavior, and
stays honored until at least 2027-01-14 (`CONFIG_ROLLBACK_WINDOWS` in `src/core/wire-skew.ts`). They are not
@@ -7099,7 +7100,20 @@ Triggers sync on push events for instant sync (<5s).
Sync only indexes "syncable" markdown files. These are excluded by design:
- Hidden paths (`.git/`, `.raw/`, etc.) and vendored/generated trees
(`node_modules/`, `dist/`, `build/`, `venv/`)
-- Meta files: `README.md`, `index.md`, `schema.md`, `log.md`, `RESOLVER.md`
+- Meta files: `README.md`, `index.md`, `schema.md`, `log.md`, `RESOLVER.md` at any depth
+ (and `AGENTS.md`, `CLAUDE.md` at the source root), unless the file is a typed page (below)
+
+A meta-named file below the source root whose frontmatter has a `type:` or
+`title:` (for example `projects/acme-example/index.md` starting with
+`---\ntype: project\n---`) is an ordinary page: incremental sync, `sync --full`,
+the bulk import and managed sync all import it, edits refresh it and deleting
+the file soft-deletes its page. A bare one (no frontmatter, or neither key) and
+every meta file at the source root stay skipped, and a page an older gbrain
+indexed at such a path is kept (#1433). This is `sync.metafile_pages`:
+`typed` (the default) or `off`, which skips every meta file as before
+(`gbrain config set sync.metafile_pages off`). The first sync after the upgrade,
+or after setting it back to `typed`, imports the typed files already in the
+tree once; it deletes or rewrites nothing else.
A dot-directory you deliberately keep content in (say `.decisions/`) can be
waived back in with `--include-hidden '<glob>'` on `gbrain sync` — the glob
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index 1da2fb613d..5991261486 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -36,7 +36,7 @@ src/core/embedding-migration.ts 1587 ratchet new row: crossed 1500 in v0.46.25.0
src/core/github-source.ts 1530 ratchet new row: crossed the 1500 unlisted cap in v0.46.23.0 review fix wave (scope-state gating, client hardening, symlink containment); merged reliability/shared-skills source integration; managed sweep lease wrapper; fix wave 3 lane A: config parser peeled to github-source-config.ts (-47), +account pin wiring and pinned-installation refresh
src/commands/hook.ts 1932 ratchet cathedral-5 heartbeat extraction offsets part of the BrainBench-seam growth; grown v0.46.26.0 megawave hooks-ipc (#4245); +108 monthly backup check: banner + gated session-start note + detached spawn (backup/status-file readers); +28 ship-review egress hardening: per-harness capture dispatch (capture-spec), memorable gate + receipt + relay block, fail-closed unscanned/newest-guess skips; +79 ambient-writeback WP4: hookStop bank step (gate -> bankWritebackTurn -> IPC flush; gate/bank logic live in core/facts + corpus-segments); +41 adversarial fix wave: wide-tail retry when the 128KB window misses the user turn, by-design heartbeat outcome classes, source-in-name banking; +11 #5413 session-end skips claude-cli self-transcripts; +11 #5701: hook lanes pass allowOversize so a long session reaches the bounded tail read; +1 #5371: the stop-hook dirty probe ignores physical-root ownership metadata (root-metadata.ts, engine-free); 2 core memory: user-prompt context-pressure notice wiring (logic in core/context/pressure.ts; session-start composition in core/context/session-start-output.ts); +3 fix wave 11 W2.1 #6091: PreCompact/SessionEnd capture-time consent record calls (logic in core/context/capture-consent.ts); +5 fix wave 11 W2.9 #6083: the three detached-push call sites skip a managed canonical worktree (push_managed_coordinator) + import; +2 fix wave 11 integration: W1 router help guard import beside the W2 managed-root import; +2 fix wave 13 P4.9 #6399: a header-only Codex rollout ends empty_session, not parser_drift; +3 W14 P4.16 (#5799): banner and SessionStart note read livePushStatuses (predicate in core/workspace-push.ts); +1 W15 P5.7 (#4992): gitChildEnv import for the hook git probes (launches moved onto core/spawn.ts)
src/core/chunkers/code.ts 1602 ratchet new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (decorated-python defs #3821, version-gate + timeout chunker fixes); grown wave-g (#4511): named defs never folded into merged chunks; grown #4669: skip WASM parse for languages without TOP_LEVEL_TYPES; +6 N13-1: CodeChunkMetadata.definesFunction field + merge-guard stamp (predicate lives in def-types.ts); +10 Lua grammar swap: GRAMMAR_REVISIONS + chunkerStamp() (per-language re-chunk gate); +4: CodeChunkOptions.timeoutMs (per-call parse cap; markdown fences parse under a short cap) and the "Parsing failed" → ChunkerTimeoutError mapping in parseWithTimeout
-src/core/config.ts 1989 ratchet +2 W5: search.page_rank_cut / page_rank_cut_factor KNOWN_CONFIG_KEYS rows (read in search/page-rank-cut.ts); +3 W3 confidence-gated reranking: search.reranker.gate / gate_min_gap KNOWN_CONFIG_KEYS rows (values parsed in search/crag.ts); re-summed at the W3 merge onto master v0.60.169.0 (1951 measured); +1 budgeted delivery PR 1: the search.auto_packing KNOWN_CONFIG_KEYS row (values validated in search/evidence-packing.ts); +1 #6278: persistence.sync_preparation_ms/maintenance_preparation_ms/preparation_ceiling_ms/max_preparation_attempts/preparation_deadlines key row (logic in persistence/preparation-budget.ts, switches.ts); +22 fix wave 11 W6.2/W6.3 (#5989, #6132): search.cjk_keyword_deadline_ms and search.hnsw_iterative_scan type fields, KNOWN_CONFIG_KEYS rows and the mergeSearchScanKnobs helper that keeps loadConfigWithEngine under its function-size baseline (logic in search/cjk-keyword-deadline.ts, search/hnsw-iterative-scan.ts); +8 #5988: sync.holds/hold_cap/hold_escalate_count/hold_escalate_pct/parser_regression key registration (read by persistence/sync-holds.ts); +3 agent operator wave A4: GBrainConfig.consent file-plane slot + 2 consent.preapprove.* key rows (logic in core/consent.ts); +1 System One v1: decide.* key prefix (validated by ai/decide/config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (spend-controls hint #3703, config-set validation); +3 wave G #3974: sync.include_working_tree key; grown wave-g (#4540 #4494 #4415): extractor caps + intent-pattern config keys; +1 chat-connectors: connectors. config prefix; wave-k: config-table snapshot serving the DB-plane reads (#3980 + #2119 merge); +8: loadConfig hook for ~/.gbrain/.env, loader lives in gbrain-env-file.ts (#3893); +17: litellm/together key-fold slots (#3904 reimpl: two GBrainConfig fields + KNOWN_CONFIG_KEYS rows); +1: link_resolution.cross_source key (#3908); +4 v0.47 gmail-loops: loops.extraction_enabled key; +1: pricing.overrides key (#4633 adoption); +7 #4667 adoption: sync.exclude key registration; +4: eval fix wave keys (quote_verify + 3 rescue knobs); +memorable file-plane key registration (integrations.memorable.enabled + consent-event doc); +33 ambient-writeback: memory.* + brain.audience key registration + GBrainConfig.memory mirror slot (resolvers live in facts/writeback-config.ts); +38 2026-08 wave: retrieval_reflex_volunteer key + env mapping (volunteer-arm kill switch) + E5a registration of the 10 adaptive_return*/autocut*/crag_* search (incl. adversarial batch isEnvDisabled dedup); ambient-writeback (master merge): facts/writeback-config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave; prior growth: sync/intent/chat-connectors/litellm/pricing/loops key folds; +34: #4702 content_sanity.disabled_patterns (type + DB-plane parse/merge + key registration); composition true-up (fix-wave multi-train) | merged v0.48.1.0: master #4788 writeback keys + wave #4702/#4748 keys; master: | merged v0.48.1.0 true-up; ranker wave v0.48.4.0: +4 KNOWN_CONFIG_KEYS rows (+8); +5 #4895: CWD_DOTENV_FILES gains the per-NODE_ENV .local variants Bun auto-loads; +2 #5003: sync.include_hidden key registration; +57 #4605: search.* registry reconciled to the keys mode.ts reads (+20 knob rows, +4 direct-read singletons) + GBrainConfig.search slot + adaptive_return* DB-plane merge; +2 pre-landing review: fts.reindex_in_progress key registration (#4795 marker escape hatch); +4 #4987: auto_timeline key registration (the documented off switch was rejected as unknown); lowered to 1793: GHSA wave v0.50.5.0 moved CWD_DOTENV_FILES + dotenvValuesForKey into core/env-trust.ts (-49, re-exported); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; evidence delivery: 5 registered config keys + comment (+7); +2 #5691: embedding_query_prefix key registration; evidence delivery auto v2: search.return_budget_conversation key row (+1); +1 #5836: facts.entity_inference key row; +6 #5824: search.vector_legacy_guard key row + GBrainConfig.search slot + DB-plane merge; +3 wave 8 lane D1 #5885: takes.auto_embed key row; +3 #5232: GBrainConfig.persistence.write_wait_ms file-plane slot + key row (resolver in persistence/write-wait.ts); +2 F4b: planner.* and import.analyze_every_pages keys; +3 cat40 cost wave C1 (garrytan/gbrain-evals#57 follow-ups): mcp.result_rows GBrainConfig slot + key row (resolver in mcp/result-rows.ts); v0.60.46.0 merge: both waves' +3 compose (1824 + 3 = 1827 measured); +4 #5984: sync.bulk, sync.bulk_size, sync.bulk_max_txn_ms known keys; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (1838 measured); +3 retrieval feedback: the feedback keys in KNOWN_CONFIG_KEYS; 2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x engine graduation composition: both deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); P3 x aow-followup composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); +2 entity mention index: mentions.auto_link, mentions.entity_types, mentions.ignore key rows (resolver in core/mentions/policy.ts); cat40 entity wave merge with v0.60.61.0 (1853 measured); P3 x cat40-entity-wave composition: deltas re-summed at the merge; +6 fix wave lane B3: chat_fallback_on_refusal (GBrainConfig slot, GBRAIN_CHAT_FALLBACK_ON_REFUSAL env fold, known key); +2 W-B4: shared_skills.inventory.* known keys (logic in shared-skills/inventory-limits.ts); +2 fix wave 9 lane B #4921: ai.chat.per_turn_timeout_ms known key; +1 wave 9 lane W #5363: cycle.consolidate.cluster_threshold key row; +1 #5984 lanes: sync.lanes key registration; +2 P8: dream.quote_verify and think.quote_verify known keys; +2 P8: GBrainConfig.mcp.advertised_surface interface slot (resolver in mcp/surface.ts); +2 fix wave 10 lane L1 #4907: cycle.synthesize_concepts.budget_usd registered (validation in cycle/phase-config-values.ts); +2 #5958: dream.propose_takes.call_timeout_ms registered; 3 core memory: memory.core.* and memory.pressure.* known keys; +15 P5: wanted_pages.enabled/remote, line_grammar.enabled/allow_undeclared_types/effective_ranges and put_page.similar_pages key rows (logic in wanted-links.ts, line-grammar.ts, similar-pages.ts); +1 P2 extraction.date_grounding / facts.attribution keys; +1 #6188: fences.normalize registered in KNOWN_CONFIG_KEYS; +2 #6188: fences.repair.max_usd_per_page/per_day key rows; +1 fix wave 12 W2.3 #6231: facts.page_write_notability_filter key row (resolver in facts/notability-filter.ts); +1 #6317: persistence.single_consumer key row (logic in persistence/switches.ts, consumer-election.ts); +2 newer mentions on context_pack cards: mentions.newer_on_cards key row (logic in mentions/newer-mentions.ts); master v0.60.136.0 merge into #5575 memory trust (both sides kept); +1 #5329 (W14 PR3): chronicle.max_events_per_page registered in KNOWN_CONFIG_KEYS (validation in chronicle/config.ts); +2 C1/C2 memory proof wave: search.evidence_date_header + facts.candidate_fusion registry rows; +1 facts.supersession_thresholds registry row (per-model supersession calibration); +1 C4: models.standing_questions key row; +1 search.entity_anchoring key registration (default off; search/entity-anchor.ts); +1 search.query_facts_arm key registration (default off; search/facts-arm.ts); re-summed at the master 6ccf30c3e merge (1871 integration + 1868 master - 1865 base); +1 search.temporal_fact_reserve key registration (default off; search/facts-arm.ts); +1 fix wave 13 PR2: persistence.publication_ceiling_ms (P2.1/P2.3); v0.60.165.0 merge: W14 PR4 +7 and master +2 compose (1947 measured); +1 memory proof wave 2 W1: the recall.question_admission KNOWN_CONFIG_KEYS row (values validated in facts/question-recall.ts); +2 Cat 40 Hard fix wave (#6271) on top: mentions.alias_deny/multiword_aliases/sibling_merge and search.alias_fanout_max/demote_generated KNOWN_CONFIG_KEYS rows (1950 measured); +1 wave 15 P7.1 #5213: cycle.propose_takes.types KNOWN_CONFIG_KEYS row (parse + filter live in cycle/propose-takes.ts); +1 wave 15 P7.2 #6451: autopilot.git_pull KNOWN_CONFIG_KEYS row (read in persistence/automatic-sync-policy.ts); +1 wave 15 P7.3 #6369: cycle.lint.enabled KNOWN_CONFIG_KEYS row (read in cycle/lint-fix-setting.ts); +2 wave 15 P7.4 #5461: think.pages_budget_chars / think.excerpt_ceiling_chars KNOWN_CONFIG_KEYS rows (validation in think/pages-budget.ts); +6 wave 16 G5.1 (#6495): search.keyword_statement_timeout_ms type field, DB merge and KNOWN_CONFIG_KEYS row, toEngineConfig carries it (range + resolver live in postgres-engine/keyword-statement-timeout.ts); +1 GBRA-81 item 1: search.mode_source registered; +1 GBRA-60 S1: search.diverse_pool_depth in the known search keys; +3 #6643: sync.knock_on_refreeze_limit / sync.knock_on_run_limit KNOWN_CONFIG_KEYS rows (read by persistence/sync-run.ts knockOnLimits); +3 #6696: KNOWN_CONFIG_KEYS rows for persistence.maintenance.compaction_stale_hours and refusal_breaker_threshold; +1 wave 5 D5: context.proactive_brief KNOWN_CONFIG_KEYS row (read in context/proactive-brief.ts); +3 Cat 40 next wave part 1: KNOWN_CONFIG_KEYS rows for entity.names_references + entity.record_types + entity.row_page_status (one line), mcp.instructions_governing_rule and search.long_page_unit (re-summed at the 0.60.242.0 merge: master 1975 + 3); +1 wave 17 (#6667): cycle.consolidate.enabled KNOWN_CONFIG_KEYS row (read in cycle/phases/consolidate.ts); +2 Wave B PR 1: pages.segmented_storage and the segmented ceiling/retention keys (page-body/limits.ts); merge v0.60.249.0: Wave B PR 1 and master growth compose at 1981; +1 #6297: dream.patterns.min_interval_hours / child_read_budget_kb known keys; +1 #5012: loops.updates_require_reciprocity known key; +1 wave 18b lane 2 (#6495): search.keyword_timeout_negative_cache_seconds KNOWN_CONFIG_KEYS row; integrated at wave 18b: master 1981 + 4 (lanes 2, 3, 5 known keys); +1 #6948: sync.origin_twins.auto_resolve KNOWN_CONFIG_KEYS row (read in repair/origin-twins-heal.ts); +1 #6948 sweep C-9: facts.absorb_retry.max_resubmits KNOWN_CONFIG_KEYS row (read in facts/dead-absorb-retry.ts); +1 #6907: backup.remote_timeout_ms KNOWN_CONFIG_KEYS row (resolver in backup/repository.ts); +1 at the #6712 PR 4b merge onto master v0.60.310.0 (both sides added a key)
+src/core/config.ts 1990 ratchet +2 W5: search.page_rank_cut / page_rank_cut_factor KNOWN_CONFIG_KEYS rows (read in search/page-rank-cut.ts); +3 W3 confidence-gated reranking: search.reranker.gate / gate_min_gap KNOWN_CONFIG_KEYS rows (values parsed in search/crag.ts); re-summed at the W3 merge onto master v0.60.169.0 (1951 measured); +1 budgeted delivery PR 1: the search.auto_packing KNOWN_CONFIG_KEYS row (values validated in search/evidence-packing.ts); +1 #6278: persistence.sync_preparation_ms/maintenance_preparation_ms/preparation_ceiling_ms/max_preparation_attempts/preparation_deadlines key row (logic in persistence/preparation-budget.ts, switches.ts); +22 fix wave 11 W6.2/W6.3 (#5989, #6132): search.cjk_keyword_deadline_ms and search.hnsw_iterative_scan type fields, KNOWN_CONFIG_KEYS rows and the mergeSearchScanKnobs helper that keeps loadConfigWithEngine under its function-size baseline (logic in search/cjk-keyword-deadline.ts, search/hnsw-iterative-scan.ts); +8 #5988: sync.holds/hold_cap/hold_escalate_count/hold_escalate_pct/parser_regression key registration (read by persistence/sync-holds.ts); +3 agent operator wave A4: GBrainConfig.consent file-plane slot + 2 consent.preapprove.* key rows (logic in core/consent.ts); +1 System One v1: decide.* key prefix (validated by ai/decide/config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (spend-controls hint #3703, config-set validation); +3 wave G #3974: sync.include_working_tree key; grown wave-g (#4540 #4494 #4415): extractor caps + intent-pattern config keys; +1 chat-connectors: connectors. config prefix; wave-k: config-table snapshot serving the DB-plane reads (#3980 + #2119 merge); +8: loadConfig hook for ~/.gbrain/.env, loader lives in gbrain-env-file.ts (#3893); +17: litellm/together key-fold slots (#3904 reimpl: two GBrainConfig fields + KNOWN_CONFIG_KEYS rows); +1: link_resolution.cross_source key (#3908); +4 v0.47 gmail-loops: loops.extraction_enabled key; +1: pricing.overrides key (#4633 adoption); +7 #4667 adoption: sync.exclude key registration; +4: eval fix wave keys (quote_verify + 3 rescue knobs); +memorable file-plane key registration (integrations.memorable.enabled + consent-event doc); +33 ambient-writeback: memory.* + brain.audience key registration + GBrainConfig.memory mirror slot (resolvers live in facts/writeback-config.ts); +38 2026-08 wave: retrieval_reflex_volunteer key + env mapping (volunteer-arm kill switch) + E5a registration of the 10 adaptive_return*/autocut*/crag_* search (incl. adversarial batch isEnvDisabled dedup); ambient-writeback (master merge): facts/writeback-config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave; prior growth: sync/intent/chat-connectors/litellm/pricing/loops key folds; +34: #4702 content_sanity.disabled_patterns (type + DB-plane parse/merge + key registration); composition true-up (fix-wave multi-train) | merged v0.48.1.0: master #4788 writeback keys + wave #4702/#4748 keys; master: | merged v0.48.1.0 true-up; ranker wave v0.48.4.0: +4 KNOWN_CONFIG_KEYS rows (+8); +5 #4895: CWD_DOTENV_FILES gains the per-NODE_ENV .local variants Bun auto-loads; +2 #5003: sync.include_hidden key registration; +57 #4605: search.* registry reconciled to the keys mode.ts reads (+20 knob rows, +4 direct-read singletons) + GBrainConfig.search slot + adaptive_return* DB-plane merge; +2 pre-landing review: fts.reindex_in_progress key registration (#4795 marker escape hatch); +4 #4987: auto_timeline key registration (the documented off switch was rejected as unknown); lowered to 1793: GHSA wave v0.50.5.0 moved CWD_DOTENV_FILES + dotenvValuesForKey into core/env-trust.ts (-49, re-exported); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; evidence delivery: 5 registered config keys + comment (+7); +2 #5691: embedding_query_prefix key registration; evidence delivery auto v2: search.return_budget_conversation key row (+1); +1 #5836: facts.entity_inference key row; +6 #5824: search.vector_legacy_guard key row + GBrainConfig.search slot + DB-plane merge; +3 wave 8 lane D1 #5885: takes.auto_embed key row; +3 #5232: GBrainConfig.persistence.write_wait_ms file-plane slot + key row (resolver in persistence/write-wait.ts); +2 F4b: planner.* and import.analyze_every_pages keys; +3 cat40 cost wave C1 (garrytan/gbrain-evals#57 follow-ups): mcp.result_rows GBrainConfig slot + key row (resolver in mcp/result-rows.ts); v0.60.46.0 merge: both waves' +3 compose (1824 + 3 = 1827 measured); +4 #5984: sync.bulk, sync.bulk_size, sync.bulk_max_txn_ms known keys; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (1838 measured); +3 retrieval feedback: the feedback keys in KNOWN_CONFIG_KEYS; 2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x engine graduation composition: both deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); P3 x aow-followup composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); +2 entity mention index: mentions.auto_link, mentions.entity_types, mentions.ignore key rows (resolver in core/mentions/policy.ts); cat40 entity wave merge with v0.60.61.0 (1853 measured); P3 x cat40-entity-wave composition: deltas re-summed at the merge; +6 fix wave lane B3: chat_fallback_on_refusal (GBrainConfig slot, GBRAIN_CHAT_FALLBACK_ON_REFUSAL env fold, known key); +2 W-B4: shared_skills.inventory.* known keys (logic in shared-skills/inventory-limits.ts); +2 fix wave 9 lane B #4921: ai.chat.per_turn_timeout_ms known key; +1 wave 9 lane W #5363: cycle.consolidate.cluster_threshold key row; +1 #5984 lanes: sync.lanes key registration; +2 P8: dream.quote_verify and think.quote_verify known keys; +2 P8: GBrainConfig.mcp.advertised_surface interface slot (resolver in mcp/surface.ts); +2 fix wave 10 lane L1 #4907: cycle.synthesize_concepts.budget_usd registered (validation in cycle/phase-config-values.ts); +2 #5958: dream.propose_takes.call_timeout_ms registered; 3 core memory: memory.core.* and memory.pressure.* known keys; +15 P5: wanted_pages.enabled/remote, line_grammar.enabled/allow_undeclared_types/effective_ranges and put_page.similar_pages key rows (logic in wanted-links.ts, line-grammar.ts, similar-pages.ts); +1 P2 extraction.date_grounding / facts.attribution keys; +1 #6188: fences.normalize registered in KNOWN_CONFIG_KEYS; +2 #6188: fences.repair.max_usd_per_page/per_day key rows; +1 fix wave 12 W2.3 #6231: facts.page_write_notability_filter key row (resolver in facts/notability-filter.ts); +1 #6317: persistence.single_consumer key row (logic in persistence/switches.ts, consumer-election.ts); +2 newer mentions on context_pack cards: mentions.newer_on_cards key row (logic in mentions/newer-mentions.ts); master v0.60.136.0 merge into #5575 memory trust (both sides kept); +1 #5329 (W14 PR3): chronicle.max_events_per_page registered in KNOWN_CONFIG_KEYS (validation in chronicle/config.ts); +2 C1/C2 memory proof wave: search.evidence_date_header + facts.candidate_fusion registry rows; +1 facts.supersession_thresholds registry row (per-model supersession calibration); +1 C4: models.standing_questions key row; +1 search.entity_anchoring key registration (default off; search/entity-anchor.ts); +1 search.query_facts_arm key registration (default off; search/facts-arm.ts); re-summed at the master 6ccf30c3e merge (1871 integration + 1868 master - 1865 base); +1 search.temporal_fact_reserve key registration (default off; search/facts-arm.ts); +1 fix wave 13 PR2: persistence.publication_ceiling_ms (P2.1/P2.3); v0.60.165.0 merge: W14 PR4 +7 and master +2 compose (1947 measured); +1 memory proof wave 2 W1: the recall.question_admission KNOWN_CONFIG_KEYS row (values validated in facts/question-recall.ts); +2 Cat 40 Hard fix wave (#6271) on top: mentions.alias_deny/multiword_aliases/sibling_merge and search.alias_fanout_max/demote_generated KNOWN_CONFIG_KEYS rows (1950 measured); +1 wave 15 P7.1 #5213: cycle.propose_takes.types KNOWN_CONFIG_KEYS row (parse + filter live in cycle/propose-takes.ts); +1 wave 15 P7.2 #6451: autopilot.git_pull KNOWN_CONFIG_KEYS row (read in persistence/automatic-sync-policy.ts); +1 wave 15 P7.3 #6369: cycle.lint.enabled KNOWN_CONFIG_KEYS row (read in cycle/lint-fix-setting.ts); +2 wave 15 P7.4 #5461: think.pages_budget_chars / think.excerpt_ceiling_chars KNOWN_CONFIG_KEYS rows (validation in think/pages-budget.ts); +6 wave 16 G5.1 (#6495): search.keyword_statement_timeout_ms type field, DB merge and KNOWN_CONFIG_KEYS row, toEngineConfig carries it (range + resolver live in postgres-engine/keyword-statement-timeout.ts); +1 GBRA-81 item 1: search.mode_source registered; +1 GBRA-60 S1: search.diverse_pool_depth in the known search keys; +3 #6643: sync.knock_on_refreeze_limit / sync.knock_on_run_limit KNOWN_CONFIG_KEYS rows (read by persistence/sync-run.ts knockOnLimits); +3 #6696: KNOWN_CONFIG_KEYS rows for persistence.maintenance.compaction_stale_hours and refusal_breaker_threshold; +1 wave 5 D5: context.proactive_brief KNOWN_CONFIG_KEYS row (read in context/proactive-brief.ts); +3 Cat 40 next wave part 1: KNOWN_CONFIG_KEYS rows for entity.names_references + entity.record_types + entity.row_page_status (one line), mcp.instructions_governing_rule and search.long_page_unit (re-summed at the 0.60.242.0 merge: master 1975 + 3); +1 wave 17 (#6667): cycle.consolidate.enabled KNOWN_CONFIG_KEYS row (read in cycle/phases/consolidate.ts); +2 Wave B PR 1: pages.segmented_storage and the segmented ceiling/retention keys (page-body/limits.ts); merge v0.60.249.0: Wave B PR 1 and master growth compose at 1981; +1 #6297: dream.patterns.min_interval_hours / child_read_budget_kb known keys; +1 #5012: loops.updates_require_reciprocity known key; +1 wave 18b lane 2 (#6495): search.keyword_timeout_negative_cache_seconds KNOWN_CONFIG_KEYS row; integrated at wave 18b: master 1981 + 4 (lanes 2, 3, 5 known keys); +1 #6948: sync.origin_twins.auto_resolve KNOWN_CONFIG_KEYS row (read in repair/origin-twins-heal.ts); +1 #6948 sweep C-9: facts.absorb_retry.max_resubmits KNOWN_CONFIG_KEYS row (read in facts/dead-absorb-retry.ts); +1 #6907: backup.remote_timeout_ms KNOWN_CONFIG_KEYS row (resolver in backup/repository.ts); +1 at the #6712 PR 4b merge onto master v0.60.310.0 (both sides added a key); +1 GBRA-150: sync.metafile_pages KNOWN_CONFIG_KEYS row (read in core/sync.ts)
src/core/persistence/sync-run.ts 1681 ratchet new row: crossed the 1500 unlisted cap in #6643 (knock-on re-freeze, checkpoint revival, root cause and the truthful --retry-failed wait all drive the private cursor/gate machinery: holdUnderGate, freezeEntry, saveCursor); classification lives in sync-knock-on.ts, the checkpoint clause in checkpoint-validation.ts; peel the settle path (settleFailedRequest and its recoveries) into a sibling module next; +3 #6722: committed pages' size_state tallied into the cursor and the sync receipt size_states (logic in page-embedding-budget.ts addSizeState); merge v0.60.240.0: large pages and master growth compose at 1687; +2 #6694: the slug-mode checkpoint revival import and its doc line (predicate lives in persistence/sync-slug-mode.ts); +11 #6712 PR 3 (L7): a plain sync retries the recorded failure --retry-failed used to (retryRecordedFailure; the unchanged-refusal replay lives in persistence/sync-stop-class.ts replaysUnchangedRefusal), the moved-checkpoint and company content-refusal exceptions; #6712 PR 3 integration: lanes L7 (retryRecordedFailure, +19) and L8 (#6727 legacy-slug refusal line, #6735 timeout revival, +6) compose at 1762; +2 wave 18a integration: #6729 (lane 2, written against the 1745 ceiling) records identity downgrades in performManagedPass through noteIdentityDowngrades (logic in core/sync-identity-downgrades.ts), composed with master 1762; +14 Wave B PR 2: freezeEntry freezes a Markdown file over the read bound by reference (body_ref) and holdFailedFenceRequest holds a streamed refusal; both set freezeEntry/holdFailedFenceRequest locals (blob, oversize, rawHash) so they stay here, the hashing and preparation live in persistence/sync-streamed.ts and the hold in sync-screen.ts streamedRefusalHold; integrated at the master 4e29d0904 merge: master 1764 + Wave B PR 2 14 = 1778 measured; +4 #6948: freezeEntry holds an entry several live pages claim (hold in sync-screen.ts originConflictHold, verdict in persistence/origin-twins.ts)
src/core/bootstrap/harness.ts 2592 ratchet +29 live-PGLite-serve lane: LIVE_SERVE refusal ahead of source resolution + unpinned --token hooks (CI e2e fix); +46 wave review: resolveHookSource dep (serve-parity resolver + federated grant), --source shape validation, loud SOURCE_UNRESOLVED instead of a silent 'default'; +10: #4574 parseCodexBlockBearer http_headers shape + legacy bearer_token fallback; +4 at megawave/wave-k merge; +codex hooks lane: step-7 codex hooks.json + config.toml trust pair, removeHarness arm; +234 ambient-writeback WP3: kind:'instructions' targets (plan/apply/converge-off/remove/status probes, OV-A4 override pre-check) — splice/render mechanics live in instructions-block.ts; +59 adversarial fix wave: registrar-mode block suppression, converge-failure receipt tracking, MCP-confirmed guard before block install; +26 round-3 fixes: codex-lane MCP-confirmed guard + smoke-rollback block strip; master: | merged v0.48.1.0 true-up; +41 #4897 resolveImplicitSource dep + defaultResolveImplicitSource: hooks/token/receipt bind to the serve's implicit default source when --source is omitted; +23 #4586 statusHarness live claude-code mcp verdict (URL mismatch or same-scope non-HTTP registration reads failed, receipt untouched); shared-skills integration on company-ingestion base; +18 #5671: logAmbientPostureNotes helper (registrar note moved out of applyHarness + pre-consent warning when an explicit private facts default meets the HTTP harness; text shared with doctor in facts/writeback-config.ts); +24 #5893: rotation grant carry wiring and its rotationCarry/withheldOperationsNote helpers (carry rules live in token-mint.ts carryLegacyGrant); +6 #5878: --refresh-skills flag and status epoch line (refresh logic lives in harness-skills.ts); +7 #4618 seat: HarnessFlags.seat field, --seat/--no-seat parse via hooks.ts parseSeatFlags, GBRAIN_SEAT in the hook env; -119 #6082: plugin-lane detectors moved to plugin-lanes.ts (re-exported); +18 #6092/#6171: hook ownership identity on write/remove/converge, permission ownership carry, --remove --dry-run and the --status hook census (logic in hooks.ts + harness-hooks.ts); +5 D8 Codex slice: the Codex SessionEnd capture hook obeys the recorded consent (wireCodexCapture: hooks on, capture accepted, never registrar mode) and is disclosed in the consent block; -31 #6743: cleanup gate moved to harness-cleanup.ts; +8 #6798: supersededEnrollments dep (interface field + default) and the --status epoch hint printed only for a superseded enrollment (the brain read lives in harness-skills.ts brainSupersededEnrollments)
src/core/oauth-provider.ts 1236 ratchet new row: crossed the 1500 unlisted cap absorbing #3819 (DCR 400 invalid_client_metadata + scope filtering + custom-scheme redirect_uris + pseudo-scheme guard); merged v0.49: transactional grant enforcement shared with hosted grant policies; +1 #5222 resourceUrl option
@@ -45,5 +45,5 @@ src/core/search/mode.ts 1669 ratchet +53 W3 confidence-gated reranking: reranker
src/commands/eval-longmemeval.ts 1544 ratchet new row: crossed the 1500 unlisted cap in fw3-search (#5092 benchmark-brain recycling: configureBrain split + recycler wiring + test seams; the recycler itself lives in src/eval/longmemeval/harness.ts); +1 P6: tokenmax synopsis-tier wiring (logic in eval/longmemeval/synopsis-tier.ts); +13 GBRA-81 lane A: --via-operation query|search (flags, per-call expansion pin, the run's expectExpansion, the op branch in runOneQuestion, row field, via_operation_summary and its FAIL line; logic in eval/longmemeval/via-operation.ts); +12 --call-plan FILE / --call-plan-gate CMD: two LME_FLAGS entries (CLI help lines), two ParsedArgs fields, the parseArgs pairing check and the header invariant (planner lives in eval/longmemeval/call-plan.ts; runEvalLongMemEval is one line shorter)
src/commands/doctor/checks/extraction-sync.ts 1499 ratchet +7 GBRA-130 A-1: links_extraction_lag held bucket and its retry fix (logic in core/extraction-lag.ts heldExtractionReport); +1 undeclared_db_only_pages computes the source Git scope once per source (logic in core/markdown.ts sourceGitScope); new row: crossed the 1500 unlisted cap at the fix wave 9 merge: +7 lane W #5028 (extract_atoms freshness judged by the phase itself) and +3 lane F #5863 (extract_health dates a high halt rate by its last halt), each under the cap alone; +7 #5019: content_hash_duplicates fix pins the pairs' source (GBRAIN_SOURCE) and names a delete that runs; +1 fix wave 10 lane L1 #5556: links_extraction_lag denominator excludes quarantined pages (quarantineFilterFragment import); +11 fix wave 15 P2.8 (#5495): extract_health reads the 7-day halt reasons per kind (halt_reasons, top_halt_reason in details and the top reason in the warn line); the read, the unknown bucket and the ranking live in core/extract/rollup-writer.ts; +20 wave 18b lane 1: links_extraction_lag names the columns its pre-migration degrade reads (#6599 strict predicate), sync_freshness separates sync outcome from freshness for a source with no successful sync (#4960; verdict text, fixes and the attempt read live in doctor/sync-outcome.ts and core/sync-attempt.ts) and exempts read-only skill-pack catalogs (#6076; core/shared-skills/adopted-packs.ts); -51 #6803 (D1): links_extraction_lag reads its counts and verdict from core/extraction-lag.ts (shared with the sync nudge)
src/core/search/evidence-delivery.ts 1712 ratchet +5 W5: EvidencePlan.rankCut resolved with the plan (logic in search/page-rank-cut.ts); +20 W5 whole_pages: wholeCost prices a block as delivery would emit it whole (needs the private Block/enrichBlock internals) and the cut is wired before allocate (cutWholePages lives in search/page-rank-cut.ts); new row: crossed the 1500 unlisted cap at the #6367 merge (master 1479, its explicit-budget cap) by the C1 date header threaded through every block path, cap included; pagePlanHits (search/page-plan-hits.ts) and the header loader (evidence-date.ts blockDateHeaders) were peeled first; peel candidate: allocateCapped; +8 at the #6396 merge: page evidence text cut through the fence-chunk trust overlay and the caller minTrust floor (re-summed: our 1504 + master +8); +119 Cat 40 next wave F2: the search.long_page_unit policy (withLongPagePolicy, selectLongPages size preflight with page/byte/deadline limits) and the long-page fetch and fallback in deliverEvidence, kept in the shared seam the plan names (gbrain-evals docs/plans/2026-10-11-cat40-next-wave, F2); +17 F2 rework to the frozen-comparison policy: search.long_page_min_chars (rendered-body characters, default 20,000) read in withLongPagePolicy, a character count in the preflight, the rendered-body confirmation in deliverEvidence, and the long-page row exemption in capDeliveredSnippets (re-summed at the 0.60.225.0 merge: master 1537 + F2 136); +39 Wave B PR 2 lane 2b: planSegmentedBlock joins the windows search/segmented-evidence.ts reads around a segmented page's hits into one run-marked document (needs the private Doc/Piece/buildDoc/locateAnchor internals), planBlock's unit cut split into blockFromDoc for both, sections bounded by their run, selectionCost counts a gap between runs, and the fetch skips the whole-body fence overlay for a segmented page
-src/commands/config.ts 1515 ratchet new row: crossed the 1500 unlisted cap in wave 15 P7.4 #5461: set-time validation of think.pages_budget_chars / think.excerpt_ceiling_chars (range + parser live in core/think/pages-budget.ts), mirroring the cycle.consolidate.cluster_threshold hook; +1 wave 16 G5.1 (#6495): set-time refusal hook for search.keyword_statement_timeout_ms (check lives in commands/config/keyword-timeout-value.ts); +1 wave 18b lane 5 (#5012 item 6): search.contextual_retrieval prints the existing-pages hint after the write (text lives in commands/config/contextual-mode-hint.ts); +1 #6712 PR 2: retired/rollback sync key dispatch line (logic in core/sync-config-keys.ts handleSyncKeyConfig); +1 #6865: sync.slug_conflicts.auto_remove boolean validation at set time (refusal text in repair/slug-autoheal.ts); +1 #6948: sync.origin_twins.auto_resolve boolean validation at set time (refusal text in repair/origin-twins-heal.ts); +2 #6795: config set chat_model/expansion_model help line and the model-pin import (shadow report and file-pin unset live in commands/config/model-pin-shadow.ts); +1 #6712 PR 4b: sync.admission set-time hook (value logic in commands/config/sync-admission-value.ts)
+src/commands/config.ts 1516 ratchet new row: crossed the 1500 unlisted cap in wave 15 P7.4 #5461: set-time validation of think.pages_budget_chars / think.excerpt_ceiling_chars (range + parser live in core/think/pages-budget.ts), mirroring the cycle.consolidate.cluster_threshold hook; +1 wave 16 G5.1 (#6495): set-time refusal hook for search.keyword_statement_timeout_ms (check lives in commands/config/keyword-timeout-value.ts); +1 wave 18b lane 5 (#5012 item 6): search.contextual_retrieval prints the existing-pages hint after the write (text lives in commands/config/contextual-mode-hint.ts); +1 #6712 PR 2: retired/rollback sync key dispatch line (logic in core/sync-config-keys.ts handleSyncKeyConfig); +1 #6865: sync.slug_conflicts.auto_remove boolean validation at set time (refusal text in repair/slug-autoheal.ts); +1 #6948: sync.origin_twins.auto_resolve boolean validation at set time (refusal text in repair/origin-twins-heal.ts); +2 #6795: config set chat_model/expansion_model help line and the model-pin import (shadow report and file-pin unset live in commands/config/model-pin-shadow.ts); +1 #6712 PR 4b: sync.admission set-time hook (value logic in commands/config/sync-admission-value.ts); +1 GBRA-150: sync.metafile_pages set-time hook (value logic in commands/config/sync-metafile-pages-value.ts)
src/commands/mcp-expose.ts 1512 ratchet hosted_option: Session carries the gbrain.io coaching notice on the first-receipt run and Tailscale/service friction exits (copy, refs and gating live in core/onboard/hosted-option.ts)
diff --git a/src/commands/config.ts b/src/commands/config.ts
index 41d0d6f2e6..f486c7bf2e 100644
--- a/src/commands/config.ts
+++ b/src/commands/config.ts
@@ -380,6 +380,7 @@ const setLineGrammarConfig = async (engine: BrainEngine, key: string, value: str
async function setConfigWithDecideHooks(engine: BrainEngine, key: string, value: string, force = false): Promise<void> {
if (await setLineGrammarConfig(engine, key, value)) return;
if (key === 'sync.admission') return (await import('./config/sync-admission-value.ts')).setSyncAdmissionValue(engine, value);
+ if (key === 'sync.metafile_pages') return (await import('./config/sync-metafile-pages-value.ts')).setMetafilePagesValue(engine, value);
if (key.startsWith('decide.')) {
const { validateDecideConfigValue } = await import('../core/ai/decide/config.ts');
const err = validateDecideConfigValue(key, value);
diff --git a/src/commands/config/sync-metafile-pages-value.ts b/src/commands/config/sync-metafile-pages-value.ts
new file mode 100644
index 0000000000..6a682e575b
--- /dev/null
+++ b/src/commands/config/sync-metafile-pages-value.ts
@@ -0,0 +1,21 @@
+/**
+ * GBRA-150: `config set sync.metafile_pages`. A value outside `typed | off` is refused as a usage error (exit 2) and
+ * nothing is written: sync reads any other stored value as the default (`typed`), so a misspelled `of` would
+ * silently keep importing typed metafiles.
+ */
+import type { BrainEngine } from '../../core/engine.ts';
+import { DEFAULT_METAFILE_PAGES_MODE, METAFILE_PAGES_MODES, SYNC_METAFILE_PAGES_KEY } from '../../core/sync.ts';
+import { inertText } from '../../core/agent-output.ts';
+import { exitCliError, usageError } from '../../cli/cli-error.ts';
+
+export async function setMetafilePagesValue(engine: BrainEngine, value: string): Promise<void> {
+ const normalized = value.trim().toLowerCase();
+ if (!(METAFILE_PAGES_MODES as readonly string[]).includes(normalized)) {
+ exitCliError(usageError(`${SYNC_METAFILE_PAGES_KEY} is one of ${METAFILE_PAGES_MODES.join(', ')}; "${inertText(value, 40)}" is not. Nothing was written.`,
+ `Re-run with one of them: gbrain config set ${SYNC_METAFILE_PAGES_KEY} off keeps every folder-scaffolding file out of the brain; ${DEFAULT_METAFILE_PAGES_MODE} (the default) imports a nested one whose frontmatter has type: or title:.`, {
+ why: `Sync reads any other stored value as ${DEFAULT_METAFILE_PAGES_MODE}.`,
+ fix: { argv: ['gbrain', 'config', 'get', SYNC_METAFILE_PAGES_KEY], consent: [], actor: 'agent', why: 'Shows the value in effect; nothing was written.', requires_exclusive: false },
+ }), 'config');
+ }
+ await engine.setConfig(SYNC_METAFILE_PAGES_KEY, normalized);
+}
diff --git a/src/commands/doctor/checks/slug-collisions.ts b/src/commands/doctor/checks/slug-collisions.ts
index b799772e89..541f978b77 100644
--- a/src/commands/doctor/checks/slug-collisions.ts
+++ b/src/commands/doctor/checks/slug-collisions.ts
@@ -14,7 +14,7 @@ import { relative } from 'path';
import type { BrainEngine } from '../../../core/engine.ts';
import type { Check } from '../../doctor.ts';
import { collectSyncableFiles } from '../../import.ts';
-import { resolveSlugForPath, type SyncStrategy } from '../../../core/sync.ts';
+import { readMetafilePagesMode, resolveSlugForPath, type SyncStrategy } from '../../../core/sync.ts';
import { isImageFilePath } from '../../../core/import-file.ts';
export async function slugCollisionsCheck(engine: BrainEngine): Promise<Check> {
@@ -23,11 +23,12 @@ export async function slugCollisionsCheck(engine: BrainEngine): Promise<Check> {
`SELECT id, local_path, config FROM sources WHERE archived IS NOT TRUE AND local_path IS NOT NULL ORDER BY id`);
const groups: Array<{ source: string; slug: string; paths: string[]; indexed?: string }> = [];
let walked = 0;
+ const metafilePages = await readMetafilePagesMode(engine);
for (const source of sources) {
if (!source.local_path || !existsSync(source.local_path)) continue;
walked++;
const bySlug = new Map<string, string[]>();
- for (const file of collectSyncableFiles(source.local_path, { strategy: source.config?.strategy ?? 'markdown' })) {
+ for (const file of collectSyncableFiles(source.local_path, { strategy: source.config?.strategy ?? 'markdown', metafilePages })) {
const rel = relative(source.local_path, file).replace(/\\/g, '/');
const slug = isImageFilePath(rel) ? rel.toLowerCase() : resolveSlugForPath(rel);
bySlug.set(slug, [...(bySlug.get(slug) ?? []), rel]);
diff --git a/src/commands/extract.ts b/src/commands/extract.ts
index 5697295079..68ecfccec7 100644
--- a/src/commands/extract.ts
+++ b/src/commands/extract.ts
@@ -76,7 +76,8 @@ import { managedPersistenceEnabled } from '../core/persistence/ownership.ts';
import { addProjectedTimelineBatch, addProjectedTimelineEntry } from '../core/trust/timeline-projection.ts';
import { createProgress } from '../core/progress.ts';
import { getCliOptions, cliOptsToProgressOptions } from '../core/cli-options.ts';
-import { pathToSlug, slugifyPath, slugifySegment, pruneDir, isSyncable } from '../core/sync.ts';
+import { pathToSlug, slugifyPath, slugifySegment, pruneDir, isSyncable, readMetafilePagesMode, DEFAULT_METAFILE_PAGES_MODE, type MetafilePagesMode } from '../core/sync.ts';
+import { diskMetafileHeads, metafilePagePredicate } from '../core/sync-metafile-pages.ts';
// v0.41.18.0: withRetry + isRetryableConnError + WithRetryOpts moved to
// src/core/retry.ts as the canonical primitive. Engine methods
// (addLinksBatch/addTimelineEntriesBatch/upsertChunks) now self-retry via
@@ -287,7 +288,7 @@ interface ExtractResult {
// --- Shared walker ---
-export function walkMarkdownFiles(dir: string): { path: string; relPath: string }[] {
+export function walkMarkdownFiles(dir: string, metafilePages: MetafilePagesMode = DEFAULT_METAFILE_PAGES_MODE): { path: string; relPath: string }[] {
// Descent-time pruning + emit-time isSyncable filter (closes #923, #202).
// Pre-fix, this walker had only an ad-hoc dot-prefix exclusion and didn't
// call isSyncable at all — so it descended into `node_modules/`, emitted
@@ -295,7 +296,7 @@ export function walkMarkdownFiles(dir: string): { path: string; relPath: string
// (`.raw/`, README.md, etc.). Now: pruneDir skips entire vendor
// subtrees before recursion (saving IO), and isSyncable filters the emit
// set against the canonical markdown-strategy rules.
- const files: { path: string; relPath: string }[] = [];
+ const files: { path: string; relPath: string }[] = [], metafilePage = metafilePagePredicate(metafilePages, diskMetafileHeads(dir));
function walk(d: string) {
for (const entry of readdirSync(d)) {
const full = join(d, entry);
@@ -308,7 +309,7 @@ export function walkMarkdownFiles(dir: string): { path: string; relPath: string
walk(full);
} else if (entry.endsWith('.md') && !entry.startsWith('_')) {
const rel = relative(dir, full);
- if (!isSyncable(rel, { strategy: 'markdown' })) continue;
+ if (!isSyncable(rel, { strategy: 'markdown', metafilePage })) continue;
files.push({ path: full, relPath: rel });
}
} catch { /* skip unreadable */ }
@@ -814,7 +815,7 @@ export async function runExtractCore(engine: BrainEngine, opts: ExtractOpts): Pr
let stampRefs: Array<{ slug: string; source_id: string; extractedAt: string }> = [];
if (!dryRun && opts.mode === 'all') {
const stampSourceId = opts.sourceId ?? 'default';
- const walkRefs = walkMarkdownFiles(opts.dir)
+ const walkRefs = walkMarkdownFiles(opts.dir, await readMetafilePagesMode(engine))
.map(f => ({ slug: pathToSlug(f.relPath), source_id: stampSourceId }));
stampRefs = refsWithSnapshotStamps(walkRefs, await snapshotStampTimes(engine, walkRefs));
}
@@ -1355,7 +1356,7 @@ async function extractForSlugs(
const lost = new LostWrites();
const stdoutQuiet = jsonMode || quiet;
// Build the full slug set for link resolution (fast: just readdir, no file reads)
- const allFiles = walkMarkdownFiles(brainDir);
+ const allFiles = walkMarkdownFiles(brainDir, await readMetafilePagesMode(engine));
// Same real-path resolution the sync hooks use (see buildSlugPathIndex).
// Rebuilding `slug + '.md'` here made the cycle's incremental extract treat
// every non-slug filename as a deleted file and skip it without a word.
@@ -1531,7 +1532,7 @@ async function extractLinksFromDir(
lost: LostWrites = new LostWrites(),
): Promise<{ created: number; pages: number; processed: string[] }> {
const stdoutQuiet = jsonMode || quiet;
- const files = walkMarkdownFiles(brainDir);
+ const files = walkMarkdownFiles(brainDir, await readMetafilePagesMode(engine));
const allSlugs = new Set(files.map(f => pathToSlug(f.relPath)));
const quarantined = await quarantinedSlugs(engine, sourceId ?? 'default');
@@ -1621,7 +1622,7 @@ async function extractTimelineFromDir(
): Promise<{ created: number; pages: number; processed: string[] }> {
const processed: string[] = [];
const stdoutQuiet = jsonMode || quiet;
- const files = walkMarkdownFiles(brainDir);
+ const files = walkMarkdownFiles(brainDir, await readMetafilePagesMode(engine));
const quarantined = await quarantinedSlugs(engine, sourceId ?? 'default');
const progress = createProgress(cliOptsToProgressOptions(getCliOptions()));
@@ -1727,7 +1728,7 @@ export async function extractLinksForSlugs(
slugs: string[],
opts?: { sourceId?: string; includeFrontmatter?: boolean },
): Promise<ExtractForSlugsResult> {
- const allFiles = walkMarkdownFiles(repoPath);
+ const allFiles = walkMarkdownFiles(repoPath, await readMetafilePagesMode(engine));
// Resolve each requested slug to its REAL path (see buildSlugPathIndex).
// The old reconstructed path missed any file whose name is not already a
// slug: `existsSync` was false, the page was skipped in silence, and the
diff --git a/src/commands/frontmatter.ts b/src/commands/frontmatter.ts
index 05e9165306..ca42f49b67 100644
--- a/src/commands/frontmatter.ts
+++ b/src/commands/frontmatter.ts
@@ -36,7 +36,7 @@ import {
autoFixFrontmatter,
repairRecoverableFrontmatter,
createFrontmatterBackup,
- isFrontmatterScannablePath,
+ frontmatterScannableUnder,
makeFrontmatterBackupRunId,
scanBrainSources,
type AuditReport,
@@ -609,7 +609,8 @@ export function collectFiles(
return isMarkdownFilePath(basename(target)) ? [target] : [];
}
- const gitFiles = collectGitVisibleFiles(target, isFrontmatterScannablePath);
+ const scannable = frontmatterScannableUnder(target);
+ const gitFiles = collectGitVisibleFiles(target, scannable);
if (gitFiles) {
if (visitDir) visitDir(target);
return gitFiles;
@@ -643,7 +644,7 @@ export function collectFiles(
stack.push(full);
} else if (entryStat.isFile()) {
const rel = relative(target, full);
- if (isFrontmatterScannablePath(rel)) {
+ if (scannable(rel)) {
out.push(full);
}
}
@@ -766,6 +767,7 @@ async function runGenerate(args: string[]): Promise<void> {
}
const results: GenerateResult[] = [];
+ const scannable = frontmatterScannableUnder(brainRoot);
let scanned = 0;
let skipped = 0;
let skippedCatchAll = 0;
@@ -775,7 +777,7 @@ async function runGenerate(args: string[]): Promise<void> {
function processFile(absPath: string, relPath: string) {
scanned++;
- if (!isFrontmatterScannablePath(relPath)) return;
+ if (!scannable(relPath)) return;
// Skip symlinks
try { if (lstatSync(absPath).isSymbolicLink()) return; } catch { return; }
diff --git a/src/commands/import.ts b/src/commands/import.ts
index dd69d8b0dd..e7f6b27757 100644
--- a/src/commands/import.ts
+++ b/src/commands/import.ts
@@ -26,8 +26,10 @@ import {
pruneDir,
isPathPruned,
isSyncMetafile,
+ DEFAULT_METAFILE_PAGES_MODE, readMetafilePagesMode, type MetafilePagesMode,
type SyncStrategy,
} from '../core/sync.ts';
+import { diskMetafileHeads, metafilePagePredicate } from '../core/sync-metafile-pages.ts';
import { sortNewestFirst } from '../core/sort-newest-first.ts';
import {
loadCheckpoint,
@@ -578,7 +580,7 @@ export async function runImport(
let allFiles = company ? company.plan.manifest.filter(entry => entry.disposition === 'included').map(entry => join(dir, entry.path))
: singleFile ? [dir] : collectSyncableFiles(dir, {
strategy, includeGitignored,
- includeHidden: opts.includeHidden,
+ includeHidden: opts.includeHidden, metafilePages: await readMetafilePagesMode(engine),
onExcluded: (rel) => { malformedExcluded.push(rel); },
});
console.error(
@@ -1260,6 +1262,7 @@ interface CollectOpts {
onExcluded?: (relPath: string) => void;
/** See `RunImportOpts.includeHidden` — same repeatable-glob semantics. */
includeHidden?: string[];
+ metafilePages?: MetafilePagesMode; // GBRA-150: `sync.metafile_pages`, whether a typed nested metafile under `dir` is collected
}
/**
@@ -1285,6 +1288,7 @@ function isCollectibleForWalker(
strategy: SyncStrategy,
multimodalOn: boolean,
includeHidden?: string[],
+ metafilePage?: (relPath: string) => boolean, relPath = path,
): boolean {
// #2607: apply the SAME segment-level prune gate as incremental sync's
// `classifySync` (core/sync.ts) — via the shared `isPathPruned`, so this
@@ -1308,8 +1312,8 @@ function isCollectibleForWalker(
// Metafiles are directory scaffolding (READMEs / index / log / schema /
// resolver, and the root AGENTS.md / CLAUDE.md harden writes), not typed
// brain pages — same exclusion `sync`'s `isSyncable` applies. Guards both
- // the FS-walk and the git-fast-path collection routes.
- if (isSyncMetafile(path)) return false;
+ // the FS-walk and the git-fast-path collection routes. GBRA-150: a nested typed one is a page (dir-relative depth).
+ if (isSyncMetafile(path) && !metafilePage?.(relPath)) return false;
switch (strategy) {
case 'code':
@@ -1354,6 +1358,7 @@ function gitListSyncableFiles(
multimodalOn: boolean,
onExcluded?: (relPath: string) => void,
includeHidden?: string[],
+ metafilePage?: (relPath: string) => boolean,
): string[] | null {
const stdout = gitLsFiles(dir, ['--cached', '--others', '--exclude-standard', '-z']);
if (stdout === null) return null; // not a git work tree, or git not on PATH → FS-walk fallback
@@ -1367,7 +1372,7 @@ function gitListSyncableFiles(
// exclusion is reportable — other filters (strategy, prune, metafile)
// are silent by design; this one hides renameable content.
if (hasMalformedPathSegment(rel)) { onExcluded?.(rel); continue; }
- if (!isCollectibleForWalker(rel, strategy, multimodalOn, includeHidden)) continue;
+ if (!isCollectibleForWalker(rel, strategy, multimodalOn, includeHidden, metafilePage)) continue;
const full = join(dir, rel);
let st;
try {
@@ -1401,6 +1406,7 @@ function gitListSyncableFiles(
export function collectSyncableFiles(dir: string, opts: CollectOpts = {}): string[] {
const strategy: SyncStrategy = opts.strategy ?? 'markdown';
const multimodalOn = process.env.GBRAIN_EMBEDDING_MULTIMODAL === 'true';
+ const metafilePage = metafilePagePredicate(opts.metafilePages ?? DEFAULT_METAFILE_PAGES_MODE, diskMetafileHeads(dir));
// v0.42.x (#1159 --respect-gitignore / #1483 .gbrainignore): when `dir` is a
// git work tree, enumerate via `git ls-files` so the walk honors
@@ -1412,7 +1418,7 @@ export function collectSyncableFiles(dir: string, opts: CollectOpts = {}): strin
// PLUS untracked-not-ignored, so uncommitted source is still indexed. Non-git
// dirs (or git unavailable) fall through to the FS walk below.
if (!opts.includeGitignored) {
- const gitFiles = gitListSyncableFiles(dir, strategy, multimodalOn, opts.onExcluded, opts.includeHidden);
+ const gitFiles = gitListSyncableFiles(dir, strategy, multimodalOn, opts.onExcluded, opts.includeHidden, metafilePage);
if (gitFiles) return gitFiles;
}
@@ -1474,7 +1480,7 @@ export function collectSyncableFiles(dir: string, opts: CollectOpts = {}): strin
// bracket directory segment above a clean-named markdown file).
const rel = relative(dir, full);
if (hasMalformedPathSegment(rel)) { opts.onExcluded?.(rel); continue; }
- if (!isCollectibleForWalker(entry, strategy, multimodalOn)) continue;
+ if (!isCollectibleForWalker(entry, strategy, multimodalOn, undefined, metafilePage, rel.split(sep).join('/'))) continue;
files.push(full);
}
}
diff --git a/src/commands/sync/finalize.ts b/src/commands/sync/finalize.ts
index c7dbb5a151..4106391001 100644
--- a/src/commands/sync/finalize.ts
+++ b/src/commands/sync/finalize.ts
@@ -10,6 +10,7 @@ import type { BrainEngine } from '../../core/engine.ts';
import { clearOpCheckpoint } from '../../core/op-checkpoint.ts';
import { commitTimeMs } from '../../core/source-health.ts';
import { writeSyncAnchor, writeChunkerVersion } from '../../core/sync-anchor.ts';
+import { recordMetafilePagesApplied } from '../../core/sync-metafile-pages.ts';
import { git } from '../../core/sync-git.ts';
import { buildPartialResult } from '../../core/sync-lock.ts';
import {
@@ -34,10 +35,10 @@ import type { SyncPlan, SyncRun } from './sync-run.ts';
export async function finishWithoutChanges(
engine: BrainEngine,
- plan: Pick<SyncPlan, 'opts' | 'company' | 'gitContextRoot' | 'lastCommit' | 'pin' | 'pullFailed' | 'ckpt' | 'malformedSkipped' | 'totalChanges' | 'holds' | 'gitlinks'>,
+ plan: Pick<SyncPlan, 'opts' | 'company' | 'gitContextRoot' | 'lastCommit' | 'pin' | 'pullFailed' | 'ckpt' | 'malformedSkipped' | 'totalChanges' | 'holds' | 'gitlinks' | 'metafilePages'>,
swept: number,
): Promise<SyncResult | undefined> {
- const { opts, company, gitContextRoot, lastCommit, pin, pullFailed, ckpt, malformedSkipped, totalChanges } = plan;
+ const { opts, company, gitContextRoot, lastCommit, pin, pullFailed, ckpt, malformedSkipped, totalChanges, metafilePages } = plan;
if (totalChanges === 0) {
await settleLegacyHolds(engine, plan.holds);
// #3068: same guard as the git-HEAD-equality gate above — a failed pull
@@ -69,6 +70,7 @@ export async function finishWithoutChanges(
await writeSyncAnchor(engine, opts.sourceId, 'last_commit', pin, commitTimeMs(gitContextRoot, pin), gitContextRoot);
await engine.setConfig('sync.last_run', new Date().toISOString());
await writeChunkerVersion(engine, opts.sourceId, chunkerStamp());
+ if (!company) await recordMetafilePagesApplied(engine, opts.sourceId ?? DEFAULT_SOURCE_ID, metafilePages);
if (!company) { await clearOpCheckpoint(engine, ckpt.paths); await clearOpCheckpoint(engine, ckpt.target); }
// A commit whose ONLY changes are malformed filenames lands here with
// totalChanges === 0 — the anchor advances past those files forever, so
@@ -282,11 +284,11 @@ function verifyPinnedHead(run: SyncRun, plan: Pick<SyncPlan, 'company' | 'gitCon
async function applyBookmarkGate(
run: SyncRun,
- plan: Pick<SyncPlan, 'opts' | 'company' | 'gitContextRoot' | 'anchorPath' | 'lastCommit' | 'pin' | 'ckpt' | 'filtered' | 'holds'>,
+ plan: Pick<SyncPlan, 'opts' | 'company' | 'gitContextRoot' | 'anchorPath' | 'lastCommit' | 'pin' | 'ckpt' | 'filtered' | 'holds' | 'metafilePages'>,
headVerificationSucceeded: boolean,
): Promise<{ done: SyncResult } | { gate: Awaited<ReturnType<typeof applySyncFailureGate>> }> {
const { engine, succeededPaths, failedFiles, pagesAffected } = run;
- const { opts, company, gitContextRoot, anchorPath, lastCommit, pin, ckpt, filtered } = plan;
+ const { opts, company, gitContextRoot, anchorPath, lastCommit, pin, ckpt, filtered, metafilePages } = plan;
// issue #1939 — gate the bookmark through the shared failure ledger.
// • Fresh failures still BLOCK (fail-closed): the next sync re-walks the
// diff and re-attempts. Escape hatch: --skip-failed.
@@ -309,6 +311,7 @@ async function applyBookmarkGate(
await engine.setConfig('sync.last_run', new Date().toISOString());
await writeSyncAnchor(engine, opts.sourceId, 'repo_path', anchorPath);
await writeChunkerVersion(engine, opts.sourceId, chunkerStamp());
+ if (!company) await recordMetafilePagesApplied(engine, opts.sourceId ?? DEFAULT_SOURCE_ID, metafilePages);
if (!company) { await clearOpCheckpoint(engine, ckpt.paths); await clearOpCheckpoint(engine, ckpt.target); }
};
diff --git a/src/commands/sync/full.ts b/src/commands/sync/full.ts
index 328b7321b0..83d1b4f145 100644
--- a/src/commands/sync/full.ts
+++ b/src/commands/sync/full.ts
@@ -22,7 +22,10 @@ import {
isEmbeddingInfraCode,
DEFAULT_SOURCE_ID,
RENAME_SENTINEL_PREFIX,
+ readMetafilePagesMode,
+ type MetafilePagesMode,
} from '../../core/sync.ts';
+import { diskMetafileHeads, firstMetafileHead, gitMetafileHeads, metafilePagePredicate, recordMetafilePagesApplied } from '../../core/sync-metafile-pages.ts';
import { chunkerStamp } from '../../core/chunkers/code.ts';
import { autoConcurrency } from '../../core/sync-concurrency.ts';
import { slog, serr } from '../../core/console-prefix.ts';
@@ -78,7 +81,11 @@ export async function performFullSync(
// files were waiting.
// #5988: paths are relative to the slug base, the same keys holds and the ledger use.
const holdRoot = slugRoot ?? syncScopeRoot;
- if (opts.dryRun) return fullSyncDryRun(engine, syncScopeRoot, headCommit, opts, { holds, holdRoot });
+ // GBRA-150: one sync.metafile_pages read for every walk below; the commit a gone file was last synced at is read
+ // before the bookmark advances, so the reconcile judges a deleted typed metafile by its last synced bytes.
+ const metafilePages = await readMetafilePagesMode(engine);
+ const previousCommit = await readSyncAnchor(engine, opts.sourceId, 'last_commit');
+ if (opts.dryRun) return fullSyncDryRun(engine, syncScopeRoot, headCommit, { ...opts, metafilePages }, { holds, holdRoot });
// v0.22.13 (PR #490 A1 + Q5): full sync is always "large" by definition
// (entire working tree). Auto-concurrency fires unconditionally for Postgres;
@@ -150,7 +157,7 @@ export async function performFullSync(
const fullFailureSet = new Set(result.failures.map(f => f.path));
if (holds?.existing.size || holds?.retryPaths.size) {
const walked = new Set(collectSyncableFiles(syncScopeRoot, { strategy: opts.strategy ?? 'markdown', includeGitignored: opts.includeGitignored,
- includeHidden: opts.includeHidden }).map(abs => relative(holdRoot, abs)));
+ includeHidden: opts.includeHidden, metafilePages }).map(abs => relative(holdRoot, abs)));
await settleFullSyncHolds(engine, holds, { root: holdRoot, walked, failed: fullFailureSet });
}
const fullSucceeded = loadSyncFailures()
@@ -163,6 +170,7 @@ export async function performFullSync(
await engine.setConfig('sync.last_run', new Date().toISOString());
await writeSyncAnchor(engine, opts.sourceId, 'repo_path', anchorPath);
await writeChunkerVersion(engine, opts.sourceId, chunkerStamp());
+ await recordMetafilePagesApplied(engine, fullSourceId, metafilePages);
};
const fullGate = await applySyncFailureGate({
@@ -192,7 +200,7 @@ export async function performFullSync(
);
}
- const reconciledDeletes = await reconcileFullSyncDeletes(engine, opts, { company, gitContextRoot, syncScopeRoot, slugRoot });
+ const reconciledDeletes = await reconcileFullSyncDeletes(engine, opts, { company, gitContextRoot, syncScopeRoot, slugRoot, metafilePages, previousCommit });
// #3479 blocker 2 — the post-gate sweep above ran BEFORE this reconcile,
// so a `<rename:…>` sentinel whose stale row the reconcile just removed
@@ -246,7 +254,7 @@ export async function performFullSync(
};
}
-async function fullSyncDryRun(engine: BrainEngine, syncScopeRoot: string, headCommit: string, opts: SyncOpts,
+async function fullSyncDryRun(engine: BrainEngine, syncScopeRoot: string, headCommit: string, opts: SyncOpts & { metafilePages: MetafilePagesMode },
hold: { holds: LegacyHolds | null; holdRoot: string }): Promise<SyncResult> {
const dryRunMalformed: string[] = [];
let allFiles = collectSyncableFiles(syncScopeRoot, {
@@ -254,6 +262,7 @@ async function fullSyncDryRun(engine: BrainEngine, syncScopeRoot: string, headCo
includeGitignored: opts.includeGitignored,
onExcluded: (rel) => { dryRunMalformed.push(rel); },
includeHidden: opts.includeHidden,
+ metafilePages: opts.metafilePages,
});
if (opts.exclude && opts.exclude.length > 0) {
allFiles = allFiles.filter(abs => !matchesAnyGlob(relative(syncScopeRoot, abs), opts.exclude));
@@ -359,9 +368,10 @@ async function reportBlockedFullSync(
async function reconcileFullSyncDeletes(
engine: BrainEngine,
opts: SyncOpts,
- input: { company: ReturnType<typeof currentCompanyBrainSync>; gitContextRoot: string; syncScopeRoot: string; slugRoot: string | undefined },
+ input: { company: ReturnType<typeof currentCompanyBrainSync>; gitContextRoot: string; syncScopeRoot: string; slugRoot: string | undefined;
+ metafilePages: MetafilePagesMode; previousCommit: string | null },
): Promise<number> {
- const { company, gitContextRoot, syncScopeRoot, slugRoot } = input;
+ const { company, gitContextRoot, syncScopeRoot, slugRoot, metafilePages, previousCommit } = input;
// #1970 (F-A): runImport is import-only — it never purges pages whose backing
// file was deleted since the last sync. A full re-import is authoritative for
// the whole tree, so reconcile deletes here too (this is what makes the
@@ -384,7 +394,15 @@ async function reconcileFullSyncDeletes(
let reconciledDeletes = 0;
if (opts.sourceId) {
const sid = opts.sourceId;
- const reconcileSyncOpts = opts.strategy ? { strategy: opts.strategy } : undefined;
+ // GBRA-150: a metafile-named row is reconcilable exactly when the walk would collect its file: its bytes on disk, or,
+ // for a file gone since the last sync, its blob at that commit. A bare or root one keeps its page (#1433).
+ const scopeGitPath = gitRelativePath(gitContextRoot, syncScopeRoot);
+ const rowRoot = slugRoot ?? syncScopeRoot;
+ const lastSynced = gitMetafileHeads(gitContextRoot, [previousCommit]);
+ const metafilePage = metafilePagePredicate(metafilePages,
+ firstMetafileHead(diskMetafileHeads(rowRoot), path => lastSynced.read(slugRoot || !scopeGitPath ? path : `${scopeGitPath}/${path}`)),
+ path => slugRoot && scopeGitPath && path.startsWith(`${scopeGitPath}/`) ? path.slice(scopeGitPath.length + 1) : path);
+ const reconcileSyncOpts = { ...(opts.strategy ? { strategy: opts.strategy } : {}), metafilePage };
// collectSyncableFiles returns ABSOLUTE paths; source_path is stored
// repo-relative (importFile uses `relative(dir, filePath)`), so relativize
// to the same form before membership-testing — otherwise every page looks
@@ -406,8 +424,9 @@ async function reconcileFullSyncDeletes(
strategy: opts.strategy ?? 'markdown',
includeGitignored: opts.includeGitignored,
includeHidden: opts.includeHidden,
+ metafilePages,
})
- .map(abs => relative(slugRoot ?? syncScopeRoot, abs));
+ .map(abs => relative(rowRoot, abs));
// #5988 (E13): the old page of a held rename keeps its origin until the
// renamed file imports; its file being gone does not make it stale.
const heldOrigins = await heldRenameOrigins(engine, sid);
diff --git a/src/commands/sync/preflight.ts b/src/commands/sync/preflight.ts
index 2c231369e2..185a6136f9 100644
--- a/src/commands/sync/preflight.ts
+++ b/src/commands/sync/preflight.ts
@@ -43,8 +43,11 @@ import {
unsyncableReason,
isPoisonedPath,
sanitizePathForDisplay,
+ isNestedSkipMetafile,
+ readMetafilePagesMode,
} from '../../core/sync.ts';
-import type { SyncManifest } from '../../core/sync.ts';
+import type { MetafilePagesMode, SyncManifest } from '../../core/sync.ts';
+import { diskMetafileHeads, firstMetafileHead, gitMetafileHeads, listMetafileNamedBlobs, metafileBackfillDue, metafilePagePredicate } from '../../core/sync-metafile-pages.ts';
import type { SyncResult, SyncOpts } from '../sync.ts';
import { syncCheckpointKeys, resolveSyncCheckpointEvery } from './checkpoint.ts';
import { runConnectorSync } from './connector.ts';
@@ -132,10 +135,14 @@ export async function preflightIncrementalSync(engine: BrainEngine, opts: SyncOp
const { ckpt, checkpointEvery, pin, completedPaths } = await resolveCheckpointPin(engine, opts, company, gitContextRoot, lastCommit, headCommit);
+ // GBRA-150: a typed nested metafile is a page; the source backfills its existing ones once per mode it has not applied.
+ const metafilePages = await readMetafilePagesMode(engine);
+ const metafileBackfill = !company && await metafileBackfillDue(engine, opts.sourceId ?? DEFAULT_SOURCE_ID, metafilePages);
const {
storedVersion, currentVersion, versionMismatch, versionNeverSet, importWorkingTree, workingTreeManifest, workingTreeBytes,
hasWorkingTreeChanges, uncommittedDrift, inScope, scopeRel, isSelectedForRun, excluded, syncOpts,
- } = await resolveWorkingTreeScope(engine, opts, { company, gitContextRoot, detachedHead, scoped, syncScopeRelPath, holdUnreadable: !!holds?.active });
+ } = await resolveWorkingTreeScope(engine, opts, { company, gitContextRoot, detachedHead, scoped, syncScopeRelPath, holdUnreadable: !!holds?.active,
+ metafilePages, commits: [pin, lastCommit] });
// #5988: held files re-screen even when Git did not touch them; a run with
// nothing else to do still re-screens them, and clears holds of gone files.
@@ -148,7 +155,7 @@ export async function preflightIncrementalSync(engine: BrainEngine, opts: SyncOp
}
const holdWork = !!holds && holds.rescreen.length + holds.gone.length + holds.retryTaken.length > 0;
- if (lastCommit === headCommit && !versionMismatch && !versionNeverSet && !(importWorkingTree && hasWorkingTreeChanges) && !holdWork) {
+ if (lastCommit === headCommit && !versionMismatch && !versionNeverSet && !(importWorkingTree && hasWorkingTreeChanges) && !holdWork && !metafileBackfill) {
// #3068: the pull failed and nothing local advanced — this run imported
// NOTHING and the remote may hold commits we could not fetch. Reporting
// `up_to_date` here (and bumping the heartbeat below) is exactly the
@@ -226,6 +233,7 @@ export async function preflightIncrementalSync(engine: BrainEngine, opts: SyncOp
const delta = await computeFilteredDelta(engine, opts, {
company, gitContextRoot, syncScopeRoot, lastCommit, headCommit, pin, fullSyncRoots, importWorkingTree,
workingTreeManifest, workingTreeBytes, detachedHead, scoped, slugRootMode, inScope, scopeRel, excluded, isSelectedForRun, syncOpts, holds,
+ metafileBackfill, syncScopeRelPath,
});
if ('done' in delta) return delta;
const { manifest, filtered, malformedSkipped, syncImportRoot, modePath, heldRenames, bytePaths } = delta;
@@ -254,7 +262,7 @@ export async function preflightIncrementalSync(engine: BrainEngine, opts: SyncOp
plan: {
opts, company, repoPath, gitContextRoot, anchorPath, syncImportRoot, syncActivePack, lastCommit, headCommit, pin,
pullFailed, ckpt, completedPaths, checkpointEvery, manifest, filtered, malformedSkipped, totalChanges,
- uncommittedDrift, inScope, isSelectedForRun, syncOpts, modePath, holds, gitlinks: bytePaths.gitlinks,
+ uncommittedDrift, inScope, isSelectedForRun, syncOpts, modePath, holds, gitlinks: bytePaths.gitlinks, metafilePages,
},
};
}
@@ -847,9 +855,12 @@ async function resolveWorkingTreeScope(
syncScopeRelPath: string;
/** GBRA-133 S-51: the run can hold a rename pair whose identity the database refused to read. */
holdUnreadable: boolean;
+ metafilePages: MetafilePagesMode;
+ /** Where a metafile gone from the checkout was last committed: the pinned target, then the bookmark. */
+ commits: Array<string | null>;
},
) {
- const { company, gitContextRoot, detachedHead, scoped, syncScopeRelPath, holdUnreadable } = input;
+ const { company, gitContextRoot, detachedHead, scoped, syncScopeRelPath, holdUnreadable, metafilePages, commits } = input;
// v0.20.0 Cathedral II Layer 12 (codex SP-1 fix): before returning
// 'up_to_date' on git-HEAD equality, check the chunker version gate.
// If sources.chunker_version mismatches CURRENT_CHUNKER_VERSION, force
@@ -930,7 +941,11 @@ async function resolveWorkingTreeScope(
// #4027: includeHidden must ride along wherever isSyncable() consults these
// opts — dropping it here silently disables --include-hidden on the whole
// delta path (and the #3974 drift counter) while the flag still parses.
- const syncOpts = { strategy: opts.strategy, includeHidden: opts.includeHidden };
+ // GBRA-150: manifest paths are Git-root relative; a metafile is judged by the bytes the importer reads (the checkout),
+ // or, gone from it, by its last committed blob, at its depth below the source root.
+ const metafilePage = metafilePagePredicate(metafilePages,
+ firstMetafileHead(diskMetafileHeads(gitContextRoot), gitMetafileHeads(gitContextRoot, commits).read), scopeRel);
+ const syncOpts = { strategy: opts.strategy, includeHidden: opts.includeHidden, metafilePage };
// Filtered working-tree counts. Renames decompose as add(to) + delete(from)
// — the same decomposition the import path applies — so a rename-only dirty
@@ -993,6 +1008,9 @@ async function computeFilteredDelta(
isSelectedForRun: SyncPlan['isSelectedForRun'];
syncOpts: SyncPlan['syncOpts'];
holds: LegacyHolds | null;
+ /** GBRA-150: the source has not applied `sync.metafile_pages typed`: its tree's metafile-named files join the delta once. */
+ metafileBackfill: boolean;
+ syncScopeRelPath: string;
},
): Promise<
| { done: SyncResult }
@@ -1002,6 +1020,7 @@ async function computeFilteredDelta(
const {
company, gitContextRoot, syncScopeRoot, lastCommit, headCommit, pin, fullSyncRoots, importWorkingTree,
workingTreeManifest, workingTreeBytes, detachedHead, scoped, slugRootMode, inScope, scopeRel, excluded, isSelectedForRun, syncOpts, holds,
+ metafileBackfill, syncScopeRelPath,
} = input;
// Diff using git diff (net result, not per-commit). v0.42.x (#1794): diff
// against the PINNED target, not live HEAD. With a fixed (lastCommit, pin)
@@ -1037,6 +1056,13 @@ async function computeFilteredDelta(
manifest.deleted.push(...manifest.renamed.map(rename => rename.from));
manifest.renamed = [];
}
+ if (metafileBackfill) {
+ // A Git delta never names an unchanged file, so the nested metafiles already in the tree join it once; the filters
+ // below keep the typed ones, and an unchanged page re-imports as a content-hash no-op.
+ const named = new Set([...manifest.added, ...manifest.modified, ...manifest.deleted, ...manifest.renamed.flatMap(rename => [rename.from, rename.to])]);
+ manifest.added.push(...listMetafileNamedBlobs(gitContextRoot, pin, scoped ? syncScopeRelPath : '')
+ .map(blob => blob.path).filter(path => !named.has(path) && isNestedSkipMetafile(scopeRel(path))));
+ }
// Scope/exclude/isSyncable filter lambdas (`inScope`/`scopeRel`/`excluded`/
// `syncOpts`) are hoisted above the up_to_date gate — the untracked-gap
diff --git a/src/commands/sync/sync-run.ts b/src/commands/sync/sync-run.ts
index dc258ab634..8d15021b40 100644
--- a/src/commands/sync/sync-run.ts
+++ b/src/commands/sync/sync-run.ts
@@ -17,7 +17,7 @@
*/
import type { BrainEngine } from '../../core/engine.ts';
import type { currentCompanyBrainSync } from '../../core/company-brain/profile.ts';
-import type { SyncManifest, isSyncable } from '../../core/sync.ts';
+import type { MetafilePagesMode, SyncManifest, isSyncable } from '../../core/sync.ts';
import type { TypeWarningCount } from '../../core/schema-pack/type-usage.ts';
import { appendCompleted, appendCompletedOnce, type OpCheckpointKey } from '../../core/op-checkpoint.ts';
import { registerCleanup } from '../../core/process-cleanup.ts';
@@ -70,7 +70,9 @@ export interface SyncPlan {
readonly uncommittedDrift: { added: number; modified: number; deleted: number } | undefined;
readonly inScope: (p: string) => boolean;
readonly isSelectedForRun: (path: string, options?: SyncOptionsForFilter) => boolean;
- readonly syncOpts: { strategy: SyncOpts['strategy']; includeHidden: SyncOpts['includeHidden'] };
+ readonly syncOpts: { strategy: SyncOpts['strategy']; includeHidden: SyncOpts['includeHidden']; metafilePage: (path: string) => boolean };
+ /** GBRA-150: the run's `sync.metafile_pages`, recorded with the bookmark so a mode the source has not applied backfills once. */
+ readonly metafilePages: MetafilePagesMode;
/** Manifest path -> the mode's canonical page path (slug/source_path base). */
readonly modePath: (p: string) => string;
/** #5988: the run's content holds (null for company-brain sources); its re-screen paths join the import drain. */
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 1cb43d132a..322ac4ae78 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -1019,6 +1019,8 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;
// #7112 (Postgres 15 SQL compatibility, owner-exception error text). `since` is restamped at the merge slot.
{ since: '0.60.326.0', text: 'Managed sync, put_page, source config updates, archive and restore, and the dream-breaker reset work again on Postgres 15: they used the Postgres 16+ `IS JSON` predicate (and doctor jsonb_integrity and `gbrain repair-jsonb` used `pg_input_is_valid`), a syntax error (42601) on Postgres 15 that failed every managed sync checkpoint. They now use a new `gbrain_try_jsonb(text)` function (migration v263) on every server. The same guard no longer fails a config merge or a dream-breaker reset whose stored text is JSON but not jsonb (a \\u0000 escape); that value now reads as an empty object, like other unparseable text.' },
{ since: '0.60.326.0', text: 'A write that ends `storage_error` on an unexpected database server error now keeps, owner-side in the receipt, the server message with any quoted value replaced by … (`error_text`; object names stay only in known catalog messages or when the statement names them), the failing statement with every literal, number and comment replaced and never its parameters (`statement`), and the error position; a PL/pgSQL RAISE or ASSERT keeps no text. On the brain host `gbrain write-request <id> --json` now prints the receipt\'s `error_detail`, and the persistence consumer log line adds `error_text=`, `statement=` and `position=`. Remote readers see no new field.' },
+ // GBRA-150 (nested typed metafiles become pages): maintainer-approved default (2026-10-20). `since` is stamped at the merge slot.
+ { since: 'TBD', text: 'Sync now imports a folder-scaffolding file below a source\'s root (`index.md`, `README.md`, `log.md`, `schema.md` or `RESOLVER.md`) as a page when its frontmatter has `type:` or `title:`, for example `projects/acme-example/index.md`. A bare one at any depth and every one at the source root stay skipped. The first sync after the upgrade imports the existing typed files once and deletes or rewrites nothing else; deleting such a file later soft-deletes its page. `gbrain config set sync.metafile_pages off` restores the old skip.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/brain-writer.ts b/src/core/brain-writer.ts
index 593cc9c1ab..566305034c 100644
--- a/src/core/brain-writer.ts
+++ b/src/core/brain-writer.ts
@@ -34,13 +34,20 @@ import {
yamlAliasesWithinLimit,
yamlBlockError,
} from './markdown.ts';
-import { isMarkdownFilePath, isSyncable, pruneDir, slugifyPath } from './sync.ts';
+import { DEFAULT_METAFILE_PAGES_MODE, isMarkdownFilePath, isSyncable, pruneDir, readMetafilePagesMode, slugifyPath, type MetafilePagesMode } from './sync.ts';
+import { diskMetafileHeads, metafilePagePredicate } from './sync-metafile-pages.ts';
export type { ParseValidationCode };
/** Frontmatter validation is defined only for Markdown page files. */
-export function isFrontmatterScannablePath(path: string): boolean {
- return isMarkdownFilePath(path) && isSyncable(path, { strategy: 'markdown' });
+export function isFrontmatterScannablePath(path: string, metafilePage?: (path: string) => boolean): boolean {
+ return isMarkdownFilePath(path) && isSyncable(path, { strategy: 'markdown', metafilePage });
+}
+
+/** GBRA-150: `isFrontmatterScannablePath` for paths relative to `root`, where a typed nested metafile is a page under `mode`. */
+export function frontmatterScannableUnder(root: string, mode: MetafilePagesMode = DEFAULT_METAFILE_PAGES_MODE): (path: string) => boolean {
+ const metafilePage = metafilePagePredicate(mode, diskMetafileHeads(root));
+ return path => isFrontmatterScannablePath(path, metafilePage);
}
export interface AuditFix {
@@ -642,6 +649,7 @@ export async function scanBrainSources(
opts: ScanOpts = {},
): Promise<AuditReport> {
const sources = await listSources(engine, opts.sourceId);
+ const metafilePages = await readMetafilePagesMode(engine);
const totals: Partial<Record<ParseValidationCode, number>> = {};
const recoverabilityTotals: RecoverabilityByCode = {};
const perSource: PerSourceReport[] = [];
@@ -767,7 +775,7 @@ export async function scanBrainSources(
break;
}
- const report = scanOneSource(src.id, src.local_path, opts);
+ const report = scanOneSource(src.id, src.local_path, opts, metafilePages);
report.db_page_count = dbPageCount;
perSource.push(report);
grandTotal += report.total;
@@ -808,12 +816,14 @@ function scanOneSource(
sourceId: string,
sourcePath: string,
opts: ScanOpts,
+ metafilePages: MetafilePagesMode,
): PerSourceReport {
const errorsByCode: Partial<Record<ParseValidationCode, number>> = {};
const recoverability: RecoverabilityByCode = {};
const sample: PerSourceReport['sample'] = [];
const repairable: RepairableReport = { files: 0, by_code: {}, sample: [] };
const rootResolved = resolve(sourcePath);
+ const scannable = frontmatterScannableUnder(rootResolved, metafilePages);
let scanned = 0;
let total = 0;
let ignoredMissingOpen = 0;
@@ -837,7 +847,7 @@ function scanOneSource(
// Frontmatter is a Markdown-only contract. Multimodal sync deliberately
// admits images under the markdown strategy, but parsing JPEG/PNG bytes as
// UTF-8 turns ordinary binary NULs into false NULL_BYTES findings.
- if (!isFrontmatterScannablePath(relPath)) return true;
+ if (!scannable(relPath)) return true;
scanned++;
let content: string;
try {
@@ -889,7 +899,7 @@ function scanOneSource(
return true;
};
- const gitFiles = collectGitVisibleFiles(rootResolved, (rel) => isSyncable(rel, { strategy: 'markdown' }));
+ const gitFiles = collectGitVisibleFiles(rootResolved, scannable);
if (gitFiles) {
if (opts.visitDir) opts.visitDir(rootResolved);
for (const absPath of gitFiles) {
diff --git a/src/core/config.ts b/src/core/config.ts
index 8c86e9d9a7..36ea8f8094 100644
--- a/src/core/config.ts
+++ b/src/core/config.ts
@@ -1727,6 +1727,7 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = [
'sync.admission', // #6712 PR 4b: normal | imports_only | classify_only, what a managed pass admits (persistence/sync-admission.ts)
'sync.federated_v2',
'sync.include_working_tree',
+ 'sync.metafile_pages', // GBRA-150: typed (default) | off, whether a nested folder-scaffolding file with type:/title: frontmatter is a page (core/sync.ts)
// #5984: managed Postgres sync publishes pages in bulk groups (on by default; each page keeps its own request).
'sync.bulk',
'sync.bulk_size',
diff --git a/src/core/cycle/extract-takes.ts b/src/core/cycle/extract-takes.ts
index d80540a8dd..b2b4681b45 100644
--- a/src/core/cycle/extract-takes.ts
+++ b/src/core/cycle/extract-takes.ts
@@ -37,6 +37,7 @@ import { bodyBlocks } from '../page-body/segment-blocks.ts';
import { parseTakesFenceBlocks, type StreamedTakes } from '../page-body/segment-takes.ts';
import type { BodyStorage } from '../page-body/types.ts';
import { walkMarkdownFiles } from '../../commands/extract.ts';
+import { readMetafilePagesMode } from '../sync.ts';
import { takesPreparation } from '../takes-write.ts';
import { withWriteTrust } from '../persistence/context.ts';
import { derivedWriteTrust, recordTaintEdges } from '../trust/taint.ts';
@@ -257,7 +258,7 @@ export async function extractTakesFromFs(
const dryRun = opts.dryRun ?? false;
const slugFilter = opts.slugs && opts.slugs.length > 0 ? new Set(opts.slugs) : null;
- const files = walkMarkdownFiles(opts.repoPath);
+ const files = walkMarkdownFiles(opts.repoPath, await readMetafilePagesMode(engine));
const buffer: TakeBatchInput[] = [];
for (const { path, relPath } of files) {
diff --git a/src/core/fence-repair/census.ts b/src/core/fence-repair/census.ts
index 056eb61605..26e70f6cf3 100644
--- a/src/core/fence-repair/census.ts
+++ b/src/core/fence-repair/census.ts
@@ -30,7 +30,8 @@ import type { BrainEngine } from '../engine.ts';
import { parseMarkdown } from '../markdown.ts';
import { screenFenceCtx } from '../import-screen.ts';
import { collectGitVisibleFiles, knownOutsideGitRepo, noteGitFailure } from '../git-visible-files.ts';
-import { isFrontmatterScannablePath, walkDir } from '../brain-writer.ts';
+import { frontmatterScannableUnder, walkDir } from '../brain-writer.ts';
+import { readMetafilePagesMode, type MetafilePagesMode } from '../sync.ts';
import { sha256 } from '../persistence/digest.ts';
import { readGitSourceHolds, type GitHoldRecord } from '../persistence/sync-holds.ts';
import { FENCE_RULES_VERSION } from './normalize.ts';
@@ -44,7 +45,7 @@ import {
import type { FenceCtx, FencePage, FenceReason, FenceTier } from './types.ts';
import { gitChildEnv } from '../git-env.ts';
-type Exec = Pick<BrainEngine, 'executeRaw'>;
+type Exec = Pick<BrainEngine, 'executeRaw' | 'getConfig'>;
export const FENCE_TIERS: readonly FenceTier[] = ['deterministic', 'resolver', 'llm', 'manual'];
/** The fence rules a stored finding was judged with; a change restarts the scans. */
@@ -186,11 +187,12 @@ const gitHead = (root: string) => git(root, ['rev-parse', '--verify', '-q', 'HEA
const nulList = (out: string) => out.split('\0').filter(Boolean).map(path => path.replace(/\\/g, '/'));
/** Every file the walk judges, source-root relative and sorted (Git-visible files in a checkout, else a pruned walk). */
-function eligibleFiles(root: string): string[] {
- const git = collectGitVisibleFiles(root, isFrontmatterScannablePath);
+function eligibleFiles(root: string, mode: MetafilePagesMode): string[] {
+ const scannable = frontmatterScannableUnder(root, mode);
+ const git = collectGitVisibleFiles(root, scannable);
const absolute: string[] = git ?? [];
if (!git) walkDir(root, path => { absolute.push(path); });
- return [...new Set(absolute.map(path => relative(root, path).replace(/\\/g, '/')).filter(isFrontmatterScannablePath))].sort();
+ return [...new Set(absolute.map(path => relative(root, path).replace(/\\/g, '/')).filter(scannable))].sort();
}
const mtimeMs = (path: string): number | null => { try { return lstatSync(path).mtimeMs; } catch { return null; } };
@@ -201,7 +203,7 @@ const mtimeMs = (path: string): number | null => { try { return lstatSync(path).
* (mtime for non-Git sources), and every stored file candidate. Null when
* the walked commit is gone, so the caller walks everything again.
*/
-function changedFiles(root: string, walked: NonNullable<ScanRecord['files']>['walked'] & object, stored: readonly string[]): string[] | null {
+function changedFiles(root: string, walked: NonNullable<ScanRecord['files']>['walked'] & object, stored: readonly string[], mode: MetafilePagesMode): string[] | null {
const since = Date.parse(walked.at) - MTIME_SKEW_MS;
const fresh = (rel: string) => (mtimeMs(join(root, rel)) ?? Infinity) >= since;
let paths: string[];
@@ -211,9 +213,9 @@ function changedFiles(root: string, walked: NonNullable<ScanRecord['files']>['wa
const untracked = git(root, ['ls-files', '--others', '--exclude-standard', '-z']) ?? '';
paths = [...nulList(diff), ...nulList(untracked).filter(fresh)];
} else {
- paths = eligibleFiles(root).filter(fresh);
+ paths = eligibleFiles(root, mode).filter(fresh);
}
- return [...new Set([...paths, ...stored])].filter(isFrontmatterScannablePath).sort();
+ return [...new Set([...paths, ...stored])].filter(frontmatterScannableUnder(root, mode)).sort();
}
/** Judges one working-tree file: its page slug and finding, or null when it is clean or unreadable (gone). */
@@ -238,11 +240,12 @@ function judgeFile(root: string, rel: string, at: string): { key: string | null;
async function scanFiles(engine: Exec, source: CensusSource, progress: ScanProgress, stored: Map<string, string>, opts: { deadline: number; now: () => Date }): Promise<boolean> {
const root = resolve(source.local_path!);
const files = progress.record.files ??= { pass: null, walked: null };
- const changed = files.walked && files.pass?.mode !== 'full' ? changedFiles(root, files.walked, [...stored.keys()]) : null;
+ const metafilePages = await readMetafilePagesMode(engine);
+ const changed = files.walked && files.pass?.mode !== 'full' ? changedFiles(root, files.walked, [...stored.keys()], metafilePages) : null;
files.pass ??= { mode: changed ? 'changed' : 'full', after: null, started_at: opts.now().toISOString(), commit: gitHead(root) };
const pass = files.pass;
if (pass.mode === 'changed' && !changed) pass.mode = 'full';
- const list = pass.mode === 'changed' ? changed! : eligibleFiles(root);
+ const list = pass.mode === 'changed' ? changed! : eligibleFiles(root, metafilePages);
const ids = { sourceId: source.id, incarnation: source.incarnation };
let since = 0;
for (const rel of list) {
diff --git a/src/core/multi-source-drift.ts b/src/core/multi-source-drift.ts
index 16649224ce..a617d08628 100644
--- a/src/core/multi-source-drift.ts
+++ b/src/core/multi-source-drift.ts
@@ -45,7 +45,8 @@
import { readdirSync, lstatSync, statSync } from 'fs';
import { join, relative } from 'path';
import type { BrainEngine } from './engine.ts';
-import { pathToSlug, unsyncableReason } from './sync.ts';
+import { pathToSlug, readMetafilePagesMode, unsyncableReason } from './sync.ts';
+import { diskMetafileHeads, metafilePagePredicate } from './sync-metafile-pages.ts';
import { readSlugRootMode } from './sync-anchor.ts';
import { git } from './sync-git.ts';
@@ -248,6 +249,7 @@ export async function findMisroutedPages(
const sample: MisroutedSample[] = [];
const gitRootSkipped: string[] = [];
const unreadable: MisroutedResult['unreadable_sources'] = [];
+ const metafilePages = await readMetafilePagesMode(engine);
for (const src of sources) {
if (src.id === 'default') continue;
@@ -274,9 +276,12 @@ export async function findMisroutedPages(
// Sync refuses metafiles (root AGENTS.md/CLAUDE.md, README.md, ...), pruned
// dirs and malformed names, so they never become pages in this source and
// a same-slug page on default is not a misroute (#6681).
+ // A typed nested metafile is a page (GBRA-150), judged on its file below the source root.
+ const heads = diskMetafileHeads(src.local_path);
+ const metafilePage = metafilePagePredicate(metafilePages, path => heads(path.slice(prefix.length)), path => path.slice(prefix.length));
const slugs = Array.from(new Set(files
.map(f => prefix + f.relPath)
- .filter(path => unsyncableReason(path, { strategy: 'markdown' }) === null)
+ .filter(path => unsyncableReason(path, { strategy: 'markdown', metafilePage }) === null)
.map(path => pathToSlug(path))));
const existenceMap = await batchProbeExistence(engine, slugs, src.id);
diff --git a/src/core/persistence/detached-pages.ts b/src/core/persistence/detached-pages.ts
index 2e6f9e43ec..fa2936c81d 100644
--- a/src/core/persistence/detached-pages.ts
+++ b/src/core/persistence/detached-pages.ts
@@ -16,11 +16,12 @@
*/
import { execFileSync } from '../spawn.ts';
import { gitChildEnv } from '../git-env.ts';
-import { existsSync, statSync } from 'node:fs';
-import { basename, dirname, join, resolve } from 'node:path';
+import { existsSync, realpathSync, statSync } from 'node:fs';
+import { basename, dirname, join, relative, resolve } from 'node:path';
import type { BrainEngine } from '../engine.ts';
import { opError } from '../ops/contract.ts';
-import { isSyncable, type SyncStrategy } from '../sync.ts';
+import { isNestedSkipMetafile, isSyncable, readMetafilePagesMode, type MetafilePagesMode, type SyncStrategy } from '../sync.ts';
+import { diskMetafileHeads, firstMetafileHead, gitMetafileHeads, metafilePagePredicate } from '../sync-metafile-pages.ts';
import { resolveSourceLocalFilePath } from '../markdown.ts';
import { resolvePageWriteTarget, scannerSlugRootMode } from '../write-through.ts';
import { managedPersistenceEnabled } from './ownership.ts';
@@ -53,9 +54,16 @@ export function inSyncableTree(path: string): boolean {
*/
export async function absentRecordedFile(engine: BrainEngine, sourceId: string, page: { slug: string; source_path?: string | null }): Promise<string | null> {
const sourcePath = page.source_path?.trim();
- if (!sourcePath || !isSyncable(sourcePath)) return null;
+ if (!sourcePath || !isSyncable(sourcePath, { metafilePage: isNestedSkipMetafile })) return null;
const target = await resolvePageWriteTarget(engine, page.slug, sourceId, { includeDeleted: true });
- return target.ok && !inSyncableTree(target.filePath) ? sourcePath : null;
+ if (!target.ok || inSyncableTree(target.filePath)) return null;
+ if (!isNestedSkipMetafile(sourcePath)) return sourcePath;
+ // GBRA-150: a nested metafile's page is reconciled only when it is typed (as last committed, since its file is gone).
+ const [source] = await engine.executeRaw<{ local_path: string | null; last_commit: string | null }>('SELECT local_path, last_commit FROM sources WHERE id=$1', [sourceId]);
+ const root = source?.local_path;
+ if (!root || !existsSync(root)) return null;
+ const metafilePage = recordedMetafilePage(await readMetafilePagesMode(engine), root, source.last_commit, () => relative(root, target.filePath).split('\\').join('/'));
+ return metafilePage(sourcePath) ? sourcePath : null;
}
/**
@@ -100,6 +108,20 @@ export const MISSING_FILES_SCAN_LIMIT = 50_000;
export interface MissingRecordedFiles { source_id: string; pages: Array<{ slug: string; source_path: string }>; inspected: number; truncated: boolean }
+/**
+ * GBRA-150: whether a recorded nested metafile is a page the way `sync --full` judges it: its file under `root`, else its
+ * blob at the source's last synced commit. `toFile` maps a recorded `source_path` to its root-relative file.
+ */
+function recordedMetafilePage(metafilePages: MetafilePagesMode, root: string, lastCommit: string | null, toFile: (path: string) => string): (path: string) => boolean {
+ let gitRoot: string | null = null;
+ try { gitRoot = execFileSync('git', ['-C', root, 'rev-parse', '--show-toplevel'], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], env: gitChildEnv() }).trim(); } catch { /* not a checkout */ }
+ const lastSynced = gitRoot ? gitMetafileHeads(gitRoot, [lastCommit]) : null;
+ const rootInGit = gitRoot ? relative(gitRoot, realpathSync(root)).split('\\').join('/') : '';
+ const disk = diskMetafileHeads(root);
+ return metafilePagePredicate(metafilePages, firstMetafileHead(path => disk(toFile(path)),
+ path => lastSynced?.read(rootInGit ? `${rootInGit}/${toFile(path)}` : toFile(path))), toFile);
+}
+
/**
* #6609: the live pages of a classic source (a `local_path` checkout on this
* host, managed persistence off) whose recorded file is not in the files
@@ -108,8 +130,8 @@ export interface MissingRecordedFiles { source_id: string; pages: Array<{ slug:
*/
export async function scanMissingRecordedFiles(engine: BrainEngine, sourceId: string): Promise<MissingRecordedFiles | null> {
if (await managedPersistenceEnabled(engine)) return null;
- const [source] = await engine.executeRaw<{ local_path: string | null; strategy: SyncStrategy | null }>(
- "SELECT local_path, config->>'strategy' AS strategy FROM sources WHERE id=$1 AND archived IS NOT TRUE", [sourceId]);
+ const [source] = await engine.executeRaw<{ local_path: string | null; strategy: SyncStrategy | null; last_commit: string | null }>(
+ "SELECT local_path, config->>'strategy' AS strategy, last_commit FROM sources WHERE id=$1 AND archived IS NOT TRUE", [sourceId]);
const root = source?.local_path;
if (!root || !existsSync(root) || !statSync(root).isDirectory()) return null;
const strategy = source.strategy ?? 'markdown';
@@ -117,15 +139,18 @@ export async function scanMissingRecordedFiles(engine: BrainEngine, sourceId: st
`SELECT slug, source_path FROM pages WHERE source_id=$1 AND deleted_at IS NULL AND NULLIF(btrim(source_path), '') IS NOT NULL
ORDER BY id LIMIT ${MISSING_FILES_SCAN_LIMIT + 1}`, [sourceId]);
const truncated = rows.length > MISSING_FILES_SCAN_LIMIT;
- const inspected = rows.slice(0, MISSING_FILES_SCAN_LIMIT).filter(row => isSyncable(row.source_path, { strategy }));
+ const mode = await scannerSlugRootMode(engine, sourceId, root);
+ const fileOf = (row: { slug: string; source_path: string }) => resolveSourceLocalFilePath(root, row.source_path, row.slug, mode) ?? join(root, row.source_path);
+ const files = new Map(rows.map(row => [row.source_path, relative(root, fileOf(row)).split('\\').join('/')]));
+ const metafilePages = await readMetafilePagesMode(engine);
+ const metafilePage = recordedMetafilePage(metafilePages, root, source.last_commit, path => files.get(path) ?? path);
+ const inspected = rows.slice(0, MISSING_FILES_SCAN_LIMIT).filter(row => isSyncable(row.source_path, { strategy, metafilePage }));
const result: MissingRecordedFiles = { source_id: sourceId, pages: [], inspected: inspected.length, truncated };
if (!inspected.length) return result;
const { collectSyncableFiles } = await import('../../commands/import.ts');
- const mode = await scannerSlugRootMode(engine, sourceId, root);
- const present = new Set(collectSyncableFiles(root, { strategy }).map(file => resolve(file)));
+ const present = new Set(collectSyncableFiles(root, { strategy, metafilePages }).map(file => resolve(file)));
for (const row of inspected) {
- const path = resolveSourceLocalFilePath(root, row.source_path, row.slug, mode) ?? join(root, row.source_path);
- if (!present.has(resolve(path))) result.pages.push({ slug: row.slug, source_path: row.source_path });
+ if (!present.has(resolve(fileOf(row)))) result.pages.push({ slug: row.slug, source_path: row.source_path });
}
return result;
}
diff --git a/src/core/persistence/effects.ts b/src/core/persistence/effects.ts
index 99a9a6ee15..3a26cd8f21 100644
--- a/src/core/persistence/effects.ts
+++ b/src/core/persistence/effects.ts
@@ -47,7 +47,10 @@ import { dispatchFactsBackstopEffect } from './effect-facts.ts';
import { runLinksEffect } from './effect-links.ts';
import { PARK_AFTER_FAILURES, WITHHELD_BY_MIRROR, type EffectRecovery, type GitCommitNote, type PersistenceEffect, type SkippedTarget } from './effect-model.ts';
import { fileContentHash } from './large-file.ts';
-import { isSyncMetafile } from '../sync.ts';
+import { isSyncMetafile, metafileIsPage, readMetafilePagesMode } from '../sync.ts';
+import { diskMetafileHeads } from '../sync-metafile-pages.ts';
+import { resolveSourceLocalFilePath } from '../markdown.ts';
+import { scannerSlugRootMode } from '../write-through.ts';
import { recoveryStagingFile } from './staging.ts';
import { selectEffectRecoveries } from './effect-recovery-scan.ts';
import { nativeFileTarget } from './native-file-target.ts';
@@ -164,11 +167,19 @@ async function skipTarget(engine: BrainEngine, effect: PersistenceEffect, snapsh
}
/**
- * #5396: sync never imports a metafile (RESOLVER.md carries the managed durability block by design),
- * so its legacy page and file diverge; a scan never publishes either one to the other.
+ * #5396: sync never imports a scaffolding metafile (RESOLVER.md carries the managed durability block by design),
+ * so its legacy page and file diverge; a scan never publishes either one to the other. GBRA-150: a nested one whose
+ * file on disk is typed (`sync.metafile_pages typed`) is an ordinary synced page, published like any other.
*/
-function isMetafilePage(snapshot: PageSnapshot): boolean {
- return !!snapshot.page.source_path && isSyncMetafile(snapshot.page.source_path);
+async function isMetafilePage(engine: BrainEngine, sourceId: string, snapshot: PageSnapshot, binding: WorktreeBinding | null | undefined): Promise<boolean> {
+ const sourcePath = snapshot.page.source_path;
+ if (!sourcePath || !isSyncMetafile(sourcePath)) return false;
+ if (!binding?.local_path) return true;
+ const root = join(binding.local_path, binding.relative_path);
+ const file = resolveSourceLocalFilePath(root, sourcePath, snapshot.page.slug, await scannerSlugRootMode(engine, sourceId, root));
+ if (!file) return true;
+ const path = relative(root, file).split(sep).join('/');
+ return !metafileIsPage(path, diskMetafileHeads(root)(path), await readMetafilePagesMode(engine));
}
function isFileDatabaseDrift(error: unknown): boolean {
@@ -220,7 +231,7 @@ async function mirrorPage(engine: BrainEngine, effect: PersistenceEffect, bindin
if (snapshot.sourceIncarnation !== effect.source_incarnation) throw opError('source_changed', 'The mirror source was replaced.',
`Source ${effect.source_id} was replaced after this withdrawal mirror was queued, so the effect ends without writing; the new source has its own effects. Check the owner if files still look stale.`,
{ fix: effectStatusFix(effect) });
- if (isMetafilePage(snapshot)) { await materializeAndAdvance(engine, effect, snapshot, opts.hostId, 'metafile'); return; }
+ if (await isMetafilePage(engine, effect.source_id, snapshot, binding)) { await materializeAndAdvance(engine, effect, snapshot, opts.hostId, 'metafile'); return; }
// A segmented page's file is streamed from its segments (unreadPageFile), never rendered as one string, and only once
// the page has a file to rewrite: its comparison reads the stored body, never the rendered file.
const segmented = isSegmentedPage(snapshot.page);
@@ -337,7 +348,7 @@ async function publishGitPage(engine: BrainEngine, effect: PersistenceEffect, bi
attempt.target = snapshot.page.slug;
const verdict = await mirrorVerdict(engine, effect, attempt, snapshot.page.slug);
if (verdict === 'handled') return;
- if (isMetafilePage(snapshot)) { await skipTarget(engine, effect, snapshot, 'metafile'); return; }
+ if (await isMetafilePage(engine, effect.source_id, snapshot, binding)) { await skipTarget(engine, effect, snapshot, 'metafile'); return; }
const keep = effectClaimKeeper(engine, effect, effectRenewalIntervalMs);
const content = snapshot.page.deleted_at || isSegmentedPage(snapshot.page) ? null : serializePageToMarkdown(snapshot.page, snapshot.tags);
let file: Awaited<ReturnType<typeof prepareFileTarget>>;
diff --git a/src/core/persistence/sync-discovery.ts b/src/core/persistence/sync-discovery.ts
index 1c8917dbd6..b73f1f5fd3 100644
--- a/src/core/persistence/sync-discovery.ts
+++ b/src/core/persistence/sync-discovery.ts
@@ -11,7 +11,8 @@ import type { Action } from '../agent-output.ts';
import type { RegistryCode } from '../error-registry.ts';
import { buildDetachedWorkingTreeManifest, computeSyncDelta } from '../sync-delta.ts';
import { confirmedSyncDelta, confirmRenameIdentities, explicitIdVeto, frontmatterIdentity, identityHeadDigest } from '../sync-rename-identity.ts';
-import { isSyncable, isCodeFilePath, isImageFilePath, matchesAnyGlob, resolveSlugForPath, slugifyPath, type DowngradedRename, type SyncManifest } from '../sync.ts';
+import { isSyncable, isSyncMetafile, isCodeFilePath, isImageFilePath, matchesAnyGlob, readMetafilePagesMode, resolveSlugForPath, slugifyPath, type DowngradedRename, type SyncManifest } from '../sync.ts';
+import { diskMetafileHeads, firstMetafileHead, gitMetafileHeads, listMetafileNamedBlobs, metafilePagePredicate, type GitMetafileHeads } from '../sync-metafile-pages.ts';
import { databaseOnlyPageSql } from './unbound-pages.ts';
import { validateSlug } from '../utils.ts';
import { resolveSlugRootMode } from '../sync-anchor.ts';
@@ -255,14 +256,18 @@ export async function resolveManagedSyncContext(engine: BrainEngine, opts: SyncO
}
/** #6865: which Git paths of one managed source sync admits, and the page origin each maps to under the source's slug mode. */
export interface SyncEligibility { scope: string; slugMode: 'git-root' | 'source-root'; nativeRoot: string; nativeGitRoot: string;
- eligible: (gitPath: string) => boolean; sourcePath: (gitPath: string) => string; }
+ eligible: (gitPath: string) => boolean; sourcePath: (gitPath: string) => string;
+ /** GBRA-150: the blob heads `eligible` judges a metafile-named path by; a caller streaming a tree primes them in batches. */
+ metafileHeads: GitMetafileHeads; }
/**
* #6865: the eligibility rules managed discovery applies to a Git path (the source's scope, `sync.exclude`, `sync.include_hidden`,
* the strategy and reserved skillpack paths) and the origin a path maps to under the slug mode. Discovery and the unindexed-file
* detector share this one definition, so a file the detector reports is a file a sync would screen.
*/
export async function loadSyncEligibility(engine: BrainEngine, context: Pick<ManagedSyncContext, 'root' | 'gitRoot' | 'sourceId' | 'source'>,
- opts: Pick<SyncOpts, 'strategy' | 'exclude' | 'includeHidden' | 'srcSubpath'> = {}, company = !!currentCompanyBrainSync(context.sourceId)): Promise<SyncEligibility> {
+ opts: Pick<SyncOpts, 'strategy' | 'exclude' | 'includeHidden' | 'srcSubpath'> = {}, company = !!currentCompanyBrainSync(context.sourceId),
+ /** GBRA-150: the bytes a metafile-named path is judged by: the commits it is read at (default the source's last synced commit), the checkout first in working mode. */
+ metafileRead: { commits?: Array<string | null | undefined>; working?: boolean } = {}): Promise<SyncEligibility> {
const strategy = opts.strategy ?? context.source.config?.strategy ?? 'markdown';
const nativeRoot = realpathSync.native(context.root), nativeGitRoot = realpathSync.native(context.gitRoot);
const scope = relative(nativeGitRoot, nativeRoot).split(sep).join('/');
@@ -273,11 +278,16 @@ export async function loadSyncEligibility(engine: BrainEngine, context: Pick<Man
const exclude = await syncExcludePatterns(engine, opts.exclude);
const includeHidden = [...new Set([...(opts.includeHidden ?? []), ...(await engine.getConfig('sync.include_hidden') ?? '')
.split(/[\n,]/).map(v => v.trim()).filter(Boolean)].map(v => v.endsWith('/') ? `${v}**` : v))];
+ // GBRA-150: a typed nested metafile is a page, judged at its depth below the source root by the bytes the import reads.
+ const metafileHeads = gitMetafileHeads(context.gitRoot, metafileRead.commits ?? [context.source.last_commit]);
+ const metafilePage = metafilePagePredicate(await readMetafilePagesMode(engine),
+ metafileRead.working ? firstMetafileHead(diskMetafileHeads(nativeGitRoot), metafileHeads.read) : metafileHeads.read,
+ path => scope && path.startsWith(`${scope}/`) ? path.slice(scope.length + 1) : path);
// Reserved skillpack paths belong to the shared skill publisher; the managed importer always refuses them.
const eligible = (path: string) => (!scope || path.startsWith(`${scope}/`)) &&
!matchesAnyGlob(scope ? path.slice(scope.length + 1) : path, exclude) && !isReservedSkillBundlePath(sourcePath(path)) &&
- isSyncable(path, { strategy: strategy as 'markdown', includeHidden });
- return { scope, slugMode, nativeRoot, nativeGitRoot, eligible, sourcePath };
+ isSyncable(path, { strategy: strategy as 'markdown', includeHidden, metafilePage });
+ return { scope, slugMode, nativeRoot, nativeGitRoot, eligible, sourcePath, metafileHeads };
}
/** The cursor bound: entries and serialized bytes one frozen manifest may hold. */
let cursorBound = { entries: 100_000, bytes: 16 * 1024 ** 2 };
@@ -332,14 +342,17 @@ export async function discoverManagedSync(engine: BrainEngine, opts: SyncOpts, c
stage?: { target: string; head: string; slice?: Pick<SyncSliceCursor, 'phase' | 'after'> }, walk = false): Promise<SyncDiscovery> {
const { binding, root, gitRoot, sourceId, incarnation, source } = context ?? await resolveManagedSyncContext(engine, opts);
const company = currentCompanyBrainSync(sourceId);
- const { scope, slugMode, nativeRoot, nativeGitRoot, eligible, sourcePath } = await loadSyncEligibility(engine, { root, gitRoot, sourceId, source }, opts, !!company);
- const originScope: SyncOriginScope = { sourceId, root, scope, slugMode };
const target = stage?.target ?? company?.plan.revision?.commit ?? syncGit(gitRoot, ['rev-parse', 'HEAD']).trim();
const head = stage?.head ?? target;
const slicing = stage?.slice ?? null;
const detached = !company && syncGit(gitRoot, ['rev-parse', '--abbrev-ref', 'HEAD']).trim() === 'HEAD';
// #6349: a staged run stops at a commit, so uncommitted working-tree changes wait for the stage that reaches HEAD.
const working = !company && !stage && (detached || (opts.workingTree ?? (await engine.getConfig('sync.include_working_tree') === 'true')));
+ // GBRA-150: a metafile is judged by the bytes this run imports (the target's blob, the checkout in working mode) or,
+ // deleted, by the blob it was last synced from.
+ const { scope, slugMode, nativeRoot, nativeGitRoot, eligible, sourcePath, metafileHeads } = await loadSyncEligibility(engine, { root, gitRoot, sourceId, source }, opts, !!company,
+ { commits: [target, source.last_commit], working });
+ const originScope: SyncOriginScope = { sourceId, root, scope, slugMode };
// #6729: inexact renames keep their page identity only when confirmed (an imported dirty tree reads its target side from the working tree).
const confirm = { sourceId, sourcePathOf: sourcePath }, built: SyncManifest = company ? { added: [], modified: [], deleted: [], renamed: [] } : buildDetachedWorkingTreeManifest(gitRoot);
const dirty = working ? await confirmRenameIdentities(engine, gitRoot, 'HEAD', null, built, confirm) : built;
@@ -394,6 +407,7 @@ export async function discoverManagedSync(engine: BrainEngine, opts: SyncOpts, c
const paths = listed.filter(path => !refuse(path));
assertDistinctSyncOrigins(paths);
const present = new Set(paths.map(path => syncOriginPath(sourcePath(path))));
+ if (paths.some(isSyncMetafile)) metafileHeads.prime(listMetafileNamedBlobs(gitRoot, target, scope));
for (const path of paths) put(path, 'import');
const livePages = await engine.executeRaw<{ id: number; slug: string; source_path: string }>('SELECT slug,source_path,id FROM pages WHERE source_id=$1 AND deleted_at IS NULL AND source_path IS NOT NULL', [sourceId]);
const gitPathOf = (origin: string) => slugMode === 'source-root' && scope ? `${scope}/${origin}` : origin;
diff --git a/src/core/persistence/sync-pass-episode.ts b/src/core/persistence/sync-pass-episode.ts
index 3222e4d3be..f141632356 100644
--- a/src/core/persistence/sync-pass-episode.ts
+++ b/src/core/persistence/sync-pass-episode.ts
@@ -19,7 +19,8 @@ import { relative, sep } from 'node:path';
import type { BrainEngine } from '../engine.ts';
import { estimateCostFromChars } from '../embedding-pricing.ts';
import { isReservedSkillBundlePath } from '../skill-reserved-paths.ts';
-import { isSyncable, matchesAnyGlob } from '../sync.ts';
+import { isSyncable, matchesAnyGlob, type MetafilePagesMode } from '../sync.ts';
+import { gitMetafileHeads, metafilePagePredicate } from '../sync-metafile-pages.ts';
import { parseUsdLimit } from '../spend-posture.ts';
import { digest } from './digest.ts';
import { faultPointNow } from './fault-points.ts';
@@ -36,13 +37,13 @@ function universeOf(selection: SyncSelection, scope: string) {
const sameUniverse = (a: SyncSelection, b: SyncSelection, scope: string) => JSON.stringify(universeOf(a, scope)) === JSON.stringify(universeOf(b, scope));
/** Whether a Git-root path is in the universe of `selection` (the eligibility of sync-pass.ts `readShadowLevel`). */
-export function selectionEligible(selection: SyncSelection, scope: string, slugMode: 'git-root' | 'source-root'): (gitPath: string) => boolean {
+export function selectionEligible(selection: SyncSelection, scope: string, slugMode: 'git-root' | 'source-root', metafilePage?: (gitPath: string) => boolean): (gitPath: string) => boolean {
const { sub, includeHidden, strategy } = universeOf(selection, scope);
return gitPath => {
if (sub && !gitPath.startsWith(`${sub}/`)) return false;
const sourceRelative = sub ? gitPath.slice(sub.length + 1) : gitPath;
return !matchesAnyGlob(sourceRelative, selection.exclude) && !isReservedSkillBundlePath(slugMode === 'source-root' ? sourceRelative : gitPath)
- && isSyncable(gitPath, { strategy: strategy as 'markdown', includeHidden });
+ && isSyncable(gitPath, { strategy: strategy as 'markdown', includeHidden, metafilePage });
};
}
@@ -55,14 +56,16 @@ export interface EpisodeClosure {
released: number;
}
-type ClosureInput = { episode: SyncSelection; pass: SyncSelection; configuredSelection: SyncSelection; configured: boolean; scope: string; slugMode: 'git-root' | 'source-root' };
+type ClosureInput = { episode: SyncSelection; pass: SyncSelection; configuredSelection: SyncSelection; configured: boolean; scope: string; slugMode: 'git-root' | 'source-root';
+ /** GBRA-150: whether a metafile-named path of `T` is a page (`sync.metafile_pages`); the same answer in every universe. */
+ metafilePage?: (gitPath: string) => boolean };
interface ClosureTally { included: boolean; covers: boolean; released: number }
/** One stretch of design §6's closure test: `paths` folded into `tally`. */
function tallyClosure(input: ClosureInput, paths: Iterable<string>, tally: ClosureTally): ClosureTally {
- const inE = selectionEligible(input.episode, input.scope, input.slugMode);
- const inPass = selectionEligible(input.pass, input.scope, input.slugMode);
- const inConfig = selectionEligible(input.configuredSelection, input.scope, input.slugMode);
+ const inE = selectionEligible(input.episode, input.scope, input.slugMode, input.metafilePage);
+ const inPass = selectionEligible(input.pass, input.scope, input.slugMode, input.metafilePage);
+ const inConfig = selectionEligible(input.configuredSelection, input.scope, input.slugMode, input.metafilePage);
for (const path of paths) {
const e = inE(path), c = inConfig(path);
if (e && !inPass(path)) tally.included = false;
@@ -89,11 +92,13 @@ export function episodeClosure(input: ClosureInput & { treePaths: Iterable<strin
* every path answers alike on both sides, so the closure is known without the walk.
*/
export async function passEpisodeClosure(input: { gitRoot: string; root: string; head: string; slugMode: 'git-root' | 'source-root'; episode: PassEpisode; pass: SyncSelection;
- configuredSelection: SyncSelection; configured: boolean;
+ configuredSelection: SyncSelection; configured: boolean; metafilePages?: MetafilePagesMode;
/** The walk of `head`'s tree (default `walkTreeLevel`); a test replays one recorded listing instead of a `git` process per call. */
walk?: (visit: (path: string) => void) => Promise<void> }): Promise<EpisodeClosure> {
const scope = relative(realpathSync.native(input.gitRoot), realpathSync.native(input.root)).split(sep).join('/');
- const closure: ClosureInput = { episode: input.episode.selection, pass: input.pass, configuredSelection: input.configuredSelection, configured: input.configured, scope, slugMode: input.slugMode };
+ const closure: ClosureInput = { episode: input.episode.selection, pass: input.pass, configuredSelection: input.configuredSelection, configured: input.configured, scope, slugMode: input.slugMode,
+ metafilePage: metafilePagePredicate(input.metafilePages ?? 'off', gitMetafileHeads(input.gitRoot, [input.head]).read,
+ path => scope && path.startsWith(`${scope}/`) ? path.slice(scope.length + 1) : path) };
const tally: ClosureTally = { included: true, covers: true, released: 0 };
if (sameUniverse(closure.episode, input.configured ? closure.configuredSelection : closure.pass, scope)) return closureOf(input.configured, tally);
let stretch: string[] = [];
@@ -114,7 +119,7 @@ const CLOSURE_STRETCH = 2_048;
export function passClosureMemo(): typeof passEpisodeClosure {
let last: { key: string; closure: Promise<EpisodeClosure> } | null = null;
return input => {
- const key = JSON.stringify([input.gitRoot, input.root, input.head, input.slugMode, input.episode.selection, input.pass, input.configured, input.configuredSelection]);
+ const key = JSON.stringify([input.gitRoot, input.root, input.head, input.slugMode, input.episode.selection, input.pass, input.configured, input.configuredSelection, input.metafilePages]);
if (last?.key !== key) last = { key, closure: passEpisodeClosure(input) };
return last.closure;
};
diff --git a/src/core/persistence/sync-pass-run.ts b/src/core/persistence/sync-pass-run.ts
index 84c40ab0c7..191a3ad6a9 100644
--- a/src/core/persistence/sync-pass-run.ts
+++ b/src/core/persistence/sync-pass-run.ts
@@ -50,7 +50,7 @@ import { managedCursorKey, passFailureKeys, resolveManagedCursor, retireManagedC
import { withCoordinatedWrite } from './context.ts';
import { pipelined } from '../page-state/transactions.ts';
import { principalAttribution } from './attribution.ts';
-import { isCodeFilePath, resolveSlugForPath } from '../sync.ts';
+import { isCodeFilePath, readMetafilePagesMode, resolveSlugForPath } from '../sync.ts';
import { syncOriginPath } from './sync-origin.ts';
import { databaseOnlyPageSql } from './unbound-pages.ts';
import { originMarkerFingerprint } from './sync-markers.ts';
@@ -362,7 +362,10 @@ async function pinPass(engine: BrainEngine, input: SyncPassInput, lease: NonNull
const configured = !remote && !opts.exclude?.length && !opts.includeHidden?.length && opts.srcSubpath === undefined
&& (opts.strategy === undefined || opts.strategy === ((context.source.config?.strategy as string | undefined) ?? 'markdown'))
&& (detached || opts.workingTree === undefined || opts.workingTree === (configuredWorking === 'true'));
- const selectionFp = digest(selection), parserFp = parserFingerprint();
+ // GBRA-150: `sync.metafile_pages typed` widens the level's universe, so it joins the selection fingerprint (`off` keeps
+ // the fingerprint an older pass stamped): the first pass after the upgrade or a flip reads the whole level once.
+ const metafilePages = await readMetafilePagesMode(engine);
+ const selectionFp = digest(metafilePages === 'off' ? selection : { ...selection, metafile_pages: metafilePages }), parserFp = parserFingerprint();
const obligations: ManagedSyncPassValue['obligations'] = prior ? structuredClone(prior.value.obligations)
: { baseline_commit: context.source.last_commit, mismatch: {}, not_converged_streak: 0, faults: {} };
obligations.mismatch ??= {}; obligations.faults ??= {}; obligations.not_converged_streak ??= 0;
@@ -549,6 +552,7 @@ async function passStampFor(engine: BrainEngine, input: { context: ManagedSyncCo
const { context, episode, configured, counts } = input;
// Design §6: an open episode closes by inclusion (a) or at the configured selection (b); chunker_version only by (b) over U_config.
const closure = episode ? await input.closures({ gitRoot: context.gitRoot, root: context.root, head: input.head, slugMode: input.slugMode, episode, pass: input.selection, configured,
+ metafilePages: await readMetafilePagesMode(engine),
configuredSelection: passSelection(await selectionPatterns(engine, { sourceId: context.sourceId } as SyncOpts), { sourceId: context.sourceId } as SyncOpts, context, input.mode) }) : null;
const closesEpisode = closure?.closes === true;
if (closure?.released) counts.episodeReleased = closure.released;
diff --git a/src/core/persistence/sync-pass.ts b/src/core/persistence/sync-pass.ts
index 9da787cec7..c8d4a8b692 100644
--- a/src/core/persistence/sync-pass.ts
+++ b/src/core/persistence/sync-pass.ts
@@ -18,7 +18,8 @@ import { realpathSync } from 'node:fs';
import { relative, sep } from 'node:path';
import type { BrainEngine } from '../engine.ts';
import { hardenedGitStream, hardenedStreamComplete, NulRecordSplitter } from '../hardened-git.ts';
-import { matchesAnyGlob, isSyncable } from '../sync.ts';
+import { matchesAnyGlob, isSyncable, readMetafilePagesMode } from '../sync.ts';
+import { levelMetafilePages } from '../sync-metafile-pages.ts';
import { isReservedSkillBundlePath } from '../skill-reserved-paths.ts';
import { resolveSlugRootMode } from '../sync-anchor.ts';
import { resolveSlugForPath } from '../sync.ts';
@@ -582,12 +583,13 @@ export async function readShadowLevel(engine: BrainEngine, input: { sourceId: st
const settings = await readLevelSettings(engine, context, scope, input);
timings.setup = t();
if (!settings) return null;
- const { slugMode, exclude, pack, mirror, strategy, includeHidden, keepDbPrefixes, workingConfig } = settings;
+ const { slugMode, exclude, pack, mirror, strategy, includeHidden, keepDbPrefixes, workingConfig, metafilePages } = settings;
const sourceRelative = (gitPath: string) => (scope ? gitPath.slice(scope.length + 1) : gitPath);
+ let metafilePage: (gitPath: string) => boolean = () => false;
// Eligibility of a path outside the cached tree (every path of the tree is eligible); origins validate per call: a
// 600k-path level keeps no per-path memo of either.
const selected = (gitPath: string) => (!scope || gitPath.startsWith(`${scope}/`)) && !matchesAnyGlob(sourceRelative(gitPath), exclude)
- && !isReservedSkillBundlePath(slugMode === 'source-root' ? sourceRelative(gitPath) : gitPath) && isSyncable(gitPath, { strategy: strategy as 'markdown', includeHidden });
+ && !isReservedSkillBundlePath(slugMode === 'source-root' ? sourceRelative(gitPath) : gitPath) && isSyncable(gitPath, { strategy: strategy as 'markdown', includeHidden, metafilePage });
// #5032: a Windows-unstorable ':' path, and the other side of a rename touching one, take no part in the level.
let colonRefused = new Set<string>();
const eligible = (gitPath: string) => selected(gitPath) && !isWindowsColonTarget(gitPath) && !colonRefused.has(gitPath);
@@ -610,9 +612,11 @@ export async function readShadowLevel(engine: BrainEngine, input: { sourceId: st
const working = detached || (input.workingTree ?? workingConfig === 'true');
const mode: 'committed' | 'working' = working ? 'working' : 'committed';
timings.rev_parse = t();
+ const levelMetafiles = levelMetafilePages(metafilePages, gitRoot, [head, context.source.last_commit], working ? nativeGitRoot : null, scope);
+ metafilePage = levelMetafiles.metafilePage;
// A commit's tree never changes: the pass's next round at the same commit and selection reuses the eligible tree.
- const treeKey = JSON.stringify([gitRoot, head, scope, slugMode, strategy, exclude, includeHidden]);
+ const treeKey = JSON.stringify([gitRoot, head, scope, slugMode, strategy, exclude, includeHidden, metafilePages, mode]);
const cache = input.pass?.cache;
// The previous round's classification leaves the cache before anything can fail (only a complete round's is stored).
let priorClassified = cache?.classified?.treeKey === treeKey ? cache.classified : undefined;
@@ -623,7 +627,7 @@ export async function readShadowLevel(engine: BrainEngine, input: { sourceId: st
if (cache?.tree?.key === treeKey) return cache.tree;
if (cache) cache.tree = undefined;
const tree = new Map<string, GitTreeEntry>(), colon: string[] = [];
- for (const [path, entry] of await readTreeLevel(gitRoot, head, scope, step)) {
+ for (const [path, entry] of levelMetafiles.primeTree(await readTreeLevel(gitRoot, head, scope, step))) {
if (isWindowsColonTarget(path)) colon.push(path);
else if (eligible(path)) tree.set(path, entry);
if (step.due()) await step.pause();
@@ -869,7 +873,7 @@ export async function readShadowLevel(engine: BrainEngine, input: { sourceId: st
/** The level's settings, one round trip each and all in flight together; null for a company-brain source. */
async function readLevelSettings(engine: BrainEngine, context: ManagedSyncContext, scope: string, input: { workingTree?: boolean; pass?: PassLevelInput }) {
const { sourceId, root } = context;
- const [company, slugModeRead, excludeRead, includeHiddenRead, workingRead, packRead, mirrorRead] = await Promise.allSettled([
+ const [company, slugModeRead, excludeRead, includeHiddenRead, workingRead, packRead, mirrorRead, metafilePagesRead] = await Promise.allSettled([
currentCompanyBrainSync(sourceId) ? Promise.resolve(true) : getCompanyBrainProfile(engine, sourceId).then(profile => !!profile),
scope && input.pass?.slugMode ? Promise.resolve(input.pass.slugMode) : scope ? resolveSlugRootMode(engine, { sourceId, explicitGitRoot: false, slugPrefix: resolveSlugForPath(join(scope, 'x.md')).slice(0, -2), dryRun: true }) : Promise.resolve('git-root' as const),
syncExcludePatterns(engine, [...input.pass?.exclude ?? []]),
@@ -877,11 +881,12 @@ async function readLevelSettings(engine: BrainEngine, context: ManagedSyncContex
input.workingTree === undefined ? engine.getConfig('sync.include_working_tree') : Promise.resolve(null),
input.pass?.noSchemaPack ? Promise.resolve(null) : loadActivePackForEngine(engine, { remote: false, sourceId }).catch(() => null),
sourceMirrorReadOnly(engine, sourceId),
+ readMetafilePagesMode(engine),
]);
const settled = <T>(read: PromiseSettledResult<T>): T => { if (read.status === 'rejected') throw read.reason; return read.value; };
if (settled(company)) return null;
return { slugMode: settled(slugModeRead), exclude: settled(excludeRead), pack: settled(packRead), mirror: settled(mirrorRead), workingConfig: settled(workingRead),
- strategy: input.pass?.strategy ?? (context.source.config?.strategy as string | undefined) ?? 'markdown',
+ metafilePages: settled(metafilePagesRead), strategy: input.pass?.strategy ?? (context.source.config?.strategy as string | undefined) ?? 'markdown',
includeHidden: [...new Set([...input.pass?.includeHidden ?? [], ...(settled(includeHiddenRead) ?? '').split(/[\n,]/).map(v => v.trim()).filter(Boolean)].map(v => v.endsWith('/') ? `${v}**` : v))],
keepDbPrefixes: (() => { try { return loadStorageConfig(root)?.keep_db ?? []; } catch { return []; } })() };
}
diff --git a/src/core/persistence/unindexed-files.ts b/src/core/persistence/unindexed-files.ts
index 0655a4c0ca..01f9fbdaaa 100644
--- a/src/core/persistence/unindexed-files.ts
+++ b/src/core/persistence/unindexed-files.ts
@@ -21,6 +21,8 @@
* `README.md` and the other `isSyncMetafile` names) that would otherwise be eligible
* and whose frontmatter has a `type:` or `title:` is counted separately as
* `metafile_skipped`: read-only, never scheduled, because sync skips it again.
+ * That happens only under `sync.metafile_pages off` (GBRA-150): under the default
+ * `typed` such a nested file is eligible, so it is found and scheduled like any file.
* Each found file is screened read-only (the import screen's codes, or
* `clean`) up to a cap. A time or count budget stops the scan with
* `complete: false` and a cursor (the last Git path examined, in tree order),
@@ -42,9 +44,8 @@ import type { BrainEngine } from '../engine.ts';
import type { SyncOpts } from '../../commands/sync.ts';
import { spawn } from '../spawn.ts';
import { gitChildEnv } from '../git-env.ts';
-import { isSyncMetafile, matchesAnyGlob, resolveSlugForPath } from '../sync.ts';
+import { isSyncMetafile, matchesAnyGlob, metafileIsPage, resolveSlugForPath } from '../sync.ts';
import { screenImportContent } from '../import-screen.ts';
-import { parseMarkdownHead } from '../markdown.ts';
import { isReservedSkillBundlePath } from '../skill-reserved-paths.ts';
import { loadSyncEligibility, resolveManagedSyncContext, syncExcludePatterns, type ManagedSyncContext } from './sync-discovery.ts';
import { heldGitPaths, readGitHoldRetryPaths, requestGitHoldRetry } from './sync-holds.ts';
@@ -182,7 +183,7 @@ export async function findUnindexedFiles(engine: BrainEngine, sourceId: string,
const now = opts.now ?? Date.now;
const keep = opts.keep ?? UNINDEXED_SCHEDULE_CAP;
const screenLimit = opts.screenLimit ?? UNINDEXED_SCREEN_LIMIT;
- const { scope, slugMode, eligible, sourcePath } = await loadSyncEligibility(engine, context);
+ const { scope, slugMode, eligible, sourcePath, metafileHeads } = await loadSyncEligibility(engine, context);
const exclude = await syncExcludePatterns(engine);
const scan: UnindexedScan = { source_id: sourceId, incarnation, target: context.source.last_commit, eligibility: eligibilityKey(scope, slugMode, exclude), complete: true, cursor: null, scanned: 0, unindexed: 0,
slug_taken: 0, deleted_page: 0, scheduled: 0, by_code: {}, samples: [], metafile_skipped: 0, metafile_samples: [], files: [], scheduled_paths: [] };
@@ -193,6 +194,7 @@ export async function findUnindexedFiles(engine: BrainEngine, sourceId: string,
const pastDeadline = () => opts.deadlineAt !== undefined && now() >= opts.deadlineAt;
let screened = 0;
for await (const batch of treeBatches(gitRoot, scan.target, scope, opts.cursor ?? null, opts.batch ?? BATCH)) {
+ metafileHeads.prime(batch);
const rows = batch.filter(entry => eligible(entry.path) && !isWindowsColonTarget(entry.path)).map(entry => {
const root = scope ? entry.path.slice(scope.length + 1) : entry.path;
return { ...entry, root, origin: sourcePath(entry.path), legacy: slugMode === 'source-root' && scope ? entry.path : null };
@@ -205,8 +207,7 @@ export async function findUnindexedFiles(engine: BrainEngine, sourceId: string,
const unread = metafiles.filter(entry => !indexed.has(sourcePath(entry.path))).slice(0, Math.max(0, screenLimit - screened));
screened += unread.length;
visitBlobSlices(gitRoot, unread, (entry, content) => {
- const frontmatter = parseMarkdownHead(content ?? '').frontmatter;
- if (frontmatter.type == null && frontmatter.title == null) return;
+ if (!metafileIsPage(scope ? entry.path.slice(scope.length + 1) : entry.path, content, 'typed')) return;
scan.metafile_skipped++;
if (scan.metafile_samples.length < UNINDEXED_SAMPLE_LIMIT) scan.metafile_samples.push(scope ? entry.path.slice(scope.length + 1) : entry.path);
}, () => false);
diff --git a/src/core/sync-config-keys.ts b/src/core/sync-config-keys.ts
index e963a48226..88d412ca48 100644
--- a/src/core/sync-config-keys.ts
+++ b/src/core/sync-config-keys.ts
@@ -14,7 +14,8 @@ import { CONFIG_ROLLBACK_WINDOWS, type ConfigRollbackWindow } from './wire-skew.
import type { BrainEngine } from './engine.ts';
export const SYNC_TUNABLE_KEYS = ['sync.bulk_size', 'sync.lanes', 'sync.exclude', 'sync.include_hidden', 'sync.include_working_tree', 'sync.holds',
- 'sync.write_through', 'sync.cost_gate_min_usd', 'sync.on_commit', 'sync.freshness_target_seconds', 'sync.admission'] as const;
+ 'sync.write_through', 'sync.cost_gate_min_usd', 'sync.on_commit', 'sync.freshness_target_seconds', 'sync.admission',
+ 'sync.metafile_pages'] as const;
/**
* #6858 ask 6, option C (Garry's "rec", via GBRA-108): a resident serve starts a managed source's sync when its
diff --git a/src/core/sync-cost-gate.ts b/src/core/sync-cost-gate.ts
index d271affd98..e878800746 100644
--- a/src/core/sync-cost-gate.ts
+++ b/src/core/sync-cost-gate.ts
@@ -8,7 +8,8 @@ import { join } from 'path';
import { promptYesNo } from './confirm-prompt.ts';
import type { BrainEngine } from './engine.ts';
import { collectSyncableFiles } from '../commands/import.ts';
-import { isSyncable } from './sync.ts';
+import { DEFAULT_METAFILE_PAGES_MODE, isSyncable, readMetafilePagesMode, type MetafilePagesMode } from './sync.ts';
+import { diskMetafileHeads, metafilePagePredicate } from './sync-metafile-pages.ts';
// v0.42.42.0 (#2139): `buildDetachedWorkingTreeManifest` relocated to
// `src/core/sync-delta.ts` (re-imported below) so the inline cost estimator
// prices detached sources through the same code the executor imports them with.
@@ -232,7 +233,7 @@ export function estimateInlineNewTokens(
chunker_version: string | null;
}>,
currentChunkerVersion: string,
- opts: { forceFullTree?: boolean; chunkerDriftWalks?: boolean } = {},
+ opts: { forceFullTree?: boolean; chunkerDriftWalks?: boolean; metafilePages?: MetafilePagesMode } = {},
): InlineEstimate {
let tokens = 0;
let changedSources = 0;
@@ -316,7 +317,7 @@ export function estimateInlineNewTokens(
ceiling(localPath, strategy, 'git_unavailable');
continue;
}
- const syncOpts = { strategy };
+ const syncOpts = { strategy, metafilePage: metafilePagePredicate(opts.metafilePages ?? DEFAULT_METAFILE_PAGES_MODE, diskMetafileHeads(localPath)) };
const changedPaths = unique([
...delta.manifest.added.filter(p => isSyncable(p, syncOpts)),
...delta.manifest.modified.filter(p => isSyncable(p, syncOpts)),
@@ -551,6 +552,7 @@ export async function runInlineCostGate(
const inline = estimateInlineNewTokens(sources, chunkerStamp(), {
forceFullTree: ctx.includeGitignored === true,
chunkerDriftWalks: full === true || !(await readManagedMode(engine).catch(() => false)),
+ metafilePages: await readMetafilePagesMode(engine),
});
// D7A: `--full` runs `performFullSync` → `runEmbedCore({stale:true})`, which
// sweeps the pre-existing stale backlog INLINE on top of the delta. Price it.
diff --git a/src/core/sync-metafile-pages.ts b/src/core/sync-metafile-pages.ts
new file mode 100644
index 0000000000..cbffb69aa3
--- /dev/null
+++ b/src/core/sync-metafile-pages.ts
@@ -0,0 +1,173 @@
+/**
+ * GBRA-150: the readers behind `sync.metafile_pages`. A nested file named like scaffolding (`index.md`, `README.md`,
+ * …; `isNestedSkipMetafile`) is a page when its head carries a `type:` or `title:` (`metafileIsPage` in sync.ts), so a
+ * caller that classifies paths builds one `metafilePagePredicate` from the bytes its importer reads: the checkout on
+ * disk (`diskMetafileHeads`) or blobs of a commit (`gitMetafileHeads`, batch-primed from a tree listing the caller
+ * already streams), chained with `firstMetafileHead` so a deleted file reads as it was last committed. Only
+ * metafile-named paths are ever read.
+ */
+import { execFileSync } from './spawn.ts';
+import { closeSync, lstatSync, openSync, readSync } from 'node:fs';
+import { join } from 'node:path';
+import { gitChildEnv } from './git-env.ts';
+import { readBlobBytes, type TreeBlob } from './persistence/sync-blobs.ts';
+import type { BrainEngine } from './engine.ts';
+import { isNestedSkipMetafile, metafileIsPage, METAFILE_HEAD_BYTES, SYNC_METAFILE_PAGES_KEY, SYNC_SKIP_FILES, type MetafilePagesMode } from './sync.ts';
+
+/** The head text of the file at a path, or undefined when there is none (absent, unreadable, not a regular file). */
+export type MetafileHeadReader = (path: string) => string | undefined;
+
+/** The predicate `SyncableOptions.metafilePage` takes, memoized per path. `rootRelative` maps a caller's path to its source-root form. */
+export function metafilePagePredicate(mode: MetafilePagesMode, read: MetafileHeadReader, rootRelative: (path: string) => string = path => path): (path: string) => boolean {
+ if (mode === 'off') return () => false;
+ const memo = new Map<string, boolean>();
+ return path => {
+ let page = memo.get(path);
+ if (page === undefined) {
+ const relative = rootRelative(path);
+ page = isNestedSkipMetafile(relative) && metafileIsPage(relative, read(path), mode);
+ memo.set(path, page);
+ }
+ return page;
+ };
+}
+
+/** The first reader that finds the file. */
+export function firstMetafileHead(...readers: MetafileHeadReader[]): MetafileHeadReader {
+ return path => {
+ for (const read of readers) {
+ const head = read(path);
+ if (head !== undefined) return head;
+ }
+ return undefined;
+ };
+}
+
+/** Reads the head of a regular file (never a symlink) under `root`. */
+export function diskMetafileHeads(root: string): MetafileHeadReader {
+ return path => {
+ const absolute = join(root, path);
+ try {
+ if (!lstatSync(absolute).isFile()) return undefined;
+ const fd = openSync(absolute, 'r');
+ try {
+ const buffer = Buffer.alloc(METAFILE_HEAD_BYTES);
+ return buffer.subarray(0, readSync(fd, buffer, 0, METAFILE_HEAD_BYTES, 0)).toString('utf8');
+ } finally { closeSync(fd); }
+ } catch { return undefined; }
+ };
+}
+
+const nameOf = (path: string) => path.slice(path.lastIndexOf('/') + 1);
+const metafileNamed = (path: string) => (SYNC_SKIP_FILES as readonly string[]).includes(nameOf(path));
+
+function git(gitRoot: string, args: string[], input: string, maxBuffer = 64 * 1024 ** 2): Buffer {
+ return execFileSync('git', ['-c', 'core.quotepath=false', '-C', gitRoot, ...args], { env: gitChildEnv(), timeout: 60_000, maxBuffer, input, stdio: ['pipe', 'pipe', 'pipe'] });
+}
+
+/** Blob ids and sizes of `<commit>:<path>`-style object names through one `cat-file --batch-check`; missing names are absent. */
+function batchCheck(gitRoot: string, names: string[]): Map<string, TreeBlob> {
+ const out = new Map<string, TreeBlob>();
+ if (!names.length) return out;
+ const asked = names.filter(name => !name.includes('\n'));
+ if (!asked.length) return out;
+ const lines = git(gitRoot, ['cat-file', '--batch-check'], asked.join('\n') + '\n').toString('utf8').split('\n');
+ asked.forEach((name, i) => {
+ const match = /^([0-9a-f]{40,64}) blob (\d+)$/.exec(lines[i] ?? '');
+ if (match) out.set(name, { oid: match[1]!, size: Number(match[2]) });
+ });
+ return out;
+}
+
+export interface GitMetafileHeads {
+ read: MetafileHeadReader;
+ /** Batch-reads the metafile-named entries of a tree listing the caller streams (one `cat-file` per call, none for other names). */
+ prime(entries: Iterable<{ path: string; oid: string; size?: number }>): void;
+}
+
+/**
+ * Heads of blobs at the first of `commits` that has the path (a later one names where a deleted file was last seen).
+ * A primed path costs nothing more; an unprimed one costs one `cat-file --batch-check` and one `cat-file --batch`.
+ * A Git failure reads as no file.
+ */
+export function gitMetafileHeads(gitRoot: string, commits: ReadonlyArray<string | null | undefined>): GitMetafileHeads {
+ const chain = [...new Set(commits.filter((commit): commit is string => !!commit))];
+ const cache = new Map<string, string | undefined>();
+ const load = (blobs: Map<string, TreeBlob>) => {
+ let bytes: Map<string, Buffer>;
+ try { bytes = readBlobBytes(gitRoot, [...blobs.values()]); } catch { bytes = new Map(); }
+ for (const [path, blob] of blobs) cache.set(path, bytes.get(blob.oid)?.subarray(0, METAFILE_HEAD_BYTES).toString('utf8'));
+ };
+ return {
+ read: path => {
+ if (cache.has(path)) return cache.get(path);
+ if (!chain.length || !metafileNamed(path)) return undefined;
+ try {
+ const found = batchCheck(gitRoot, chain.map(commit => `${commit}:${path}`));
+ const blob = chain.map(commit => found.get(`${commit}:${path}`)).find(Boolean);
+ if (blob) load(new Map([[path, blob]]));
+ else cache.set(path, undefined);
+ } catch { cache.set(path, undefined); }
+ return cache.get(path);
+ },
+ prime: entries => {
+ const wanted = new Map<string, { oid: string; size?: number }>();
+ for (const entry of entries) if (metafileNamed(entry.path) && !cache.has(entry.path)) wanted.set(entry.path, entry);
+ if (!wanted.size) return;
+ try {
+ const unsized = [...wanted.values()].filter(entry => entry.size === undefined).map(entry => entry.oid);
+ const sizes = batchCheck(gitRoot, unsized);
+ load(new Map([...wanted].flatMap(([path, entry]) => {
+ const size = entry.size ?? sizes.get(entry.oid)?.size;
+ return size === undefined ? [] : [[path, { oid: entry.oid, size }] as [string, TreeBlob]];
+ })));
+ } catch { /* an unread entry is read on demand */ }
+ },
+ };
+}
+
+/**
+ * A managed level's predicate over Git-root paths (depth judged below `scope`, the source root): blobs at `commits` (a deleted file as last committed), the checkout first when `checkout`
+ * is set (working mode). `primeTree` batch-reads the metafile-named entries of the level's tree listing and returns it.
+ */
+export function levelMetafilePages(mode: MetafilePagesMode, gitRoot: string, commits: ReadonlyArray<string | null | undefined>, checkout: string | null,
+ scope: string): { metafilePage: (path: string) => boolean; primeTree<L extends Iterable<[string, { oid: string }]>>(level: L): L } {
+ const heads = gitMetafileHeads(gitRoot, commits);
+ return {
+ metafilePage: metafilePagePredicate(mode, checkout ? firstMetafileHead(diskMetafileHeads(checkout), heads.read) : heads.read,
+ path => scope && path.startsWith(`${scope}/`) ? path.slice(scope.length + 1) : path),
+ primeTree: level => { if (mode !== 'off') heads.prime((function* () { for (const [path, entry] of level) yield { path, oid: entry.oid }; })()); return level; },
+ };
+}
+
+/** The metafile-named blobs of `commit`'s tree under `scope` (one `ls-tree`), Git-root relative. */
+export function listMetafileNamedBlobs(gitRoot: string, commit: string, scope = ''): Array<{ path: string; oid: string; size: number }> {
+ const rows = git(gitRoot, ['--literal-pathspecs', 'ls-tree', '-r', '-l', '-z', commit, ...(scope ? ['--', scope] : [])], '', 512 * 1024 ** 2).toString('utf8').split('\0');
+ const out: Array<{ path: string; oid: string; size: number }> = [];
+ for (const row of rows) {
+ const tab = row.indexOf('\t');
+ const path = row.slice(tab + 1);
+ if (tab < 0 || !metafileNamed(path)) continue;
+ const [, kind, oid, size] = row.slice(0, tab).split(/\s+/);
+ if (kind === 'blob') out.push({ path, oid: oid!, size: Number(size) });
+ }
+ return out;
+}
+
+/** The mode a classic source last finished a sync under (one config row per source), so a mode it has not applied yet backfills once. */
+const appliedKey = (sourceId: string) => `${SYNC_METAFILE_PAGES_KEY}.applied.${sourceId}`;
+
+/**
+ * Whether the next classic sync of `sourceId` must visit the typed nested metafiles already in its tree: the brain runs
+ * `typed` and the source has not finished a sync under it (an upgrade, or `off` flipped back), since a Git delta never
+ * names a file that did not change.
+ */
+export async function metafileBackfillDue(engine: Pick<BrainEngine, 'getConfig'>, sourceId: string, mode: MetafilePagesMode): Promise<boolean> {
+ if (mode !== 'typed') return false;
+ try { return (await engine.getConfig(appliedKey(sourceId))) !== mode; } catch { return false; }
+}
+
+/** Records the mode a classic sync of `sourceId` just advanced under (written with its bookmark). */
+export async function recordMetafilePagesApplied(engine: Pick<BrainEngine, 'getConfig' | 'setConfig'>, sourceId: string, mode: MetafilePagesMode): Promise<void> {
+ if ((await engine.getConfig(appliedKey(sourceId))) !== mode) await engine.setConfig(appliedKey(sourceId), mode);
+}
diff --git a/src/core/sync.ts b/src/core/sync.ts
index 33af8da1d7..c8c471fae9 100644
--- a/src/core/sync.ts
+++ b/src/core/sync.ts
@@ -64,6 +64,12 @@ interface SyncableOptions {
* and isn't waivable.
*/
includeHidden?: string[];
+ /**
+ * Whether a path named like scaffolding (`isSyncMetafile`) is imported as a page all the same: a caller's
+ * `metafilePagePredicate` (`sync-metafile-pages.ts`), which reads the file's head under the brain's
+ * `sync.metafile_pages`. Consulted only for metafile-named paths; absent, every one is skipped.
+ */
+ metafilePage?: (path: string) => boolean;
}
// v0.19.0 shipped a 9-extension allowlist (ts/tsx/js/jsx/mjs/cjs/py/rb/go). The
@@ -566,7 +572,10 @@ export const SYNC_SKIP_FILES = ['schema.md', 'index.md', 'log.md', 'README.md',
*/
export const SYNC_ROOT_SKIP_FILES = ['AGENTS.md', 'CLAUDE.md'] as const;
-/** Whether a repo-relative path is directory scaffolding sync never imports (`SYNC_SKIP_FILES` anywhere, `SYNC_ROOT_SKIP_FILES` at the root). */
+/**
+ * Whether a repo-relative path is named like directory scaffolding (`SYNC_SKIP_FILES` anywhere, `SYNC_ROOT_SKIP_FILES`
+ * at the root). Sync skips such a file unless `metafileIsPage` says its head makes it a page.
+ */
export function isSyncMetafile(path: string): boolean {
const segments = path.split('/');
const basename = segments[segments.length - 1] || '';
@@ -574,6 +583,60 @@ export function isSyncMetafile(path: string): boolean {
|| (segments.length === 1 && (SYNC_ROOT_SKIP_FILES as readonly string[]).includes(basename));
}
+/**
+ * GBRA-150 (maintainer-approved default, 2026-10-20): `sync.metafile_pages` decides whether a nested
+ * `SYNC_SKIP_FILES` file whose frontmatter has a `type:` or `title:` is a page. `typed` imports it like any page;
+ * `off` skips every metafile as before. Root-level metafiles and bare scaffolding are skipped in both modes.
+ */
+export const SYNC_METAFILE_PAGES_KEY = 'sync.metafile_pages';
+export type MetafilePagesMode = 'typed' | 'off';
+export const METAFILE_PAGES_MODES: readonly MetafilePagesMode[] = ['typed', 'off'];
+/** The one default: flipping it back to `'off'` restores the skip-every-metafile behavior everywhere. */
+export const DEFAULT_METAFILE_PAGES_MODE: MetafilePagesMode = 'typed';
+/** Bytes of a file's head the decision reads; a frontmatter block that does not close within it reads as bare. */
+export const METAFILE_HEAD_BYTES = 64 * 1024;
+
+/** A stored `sync.metafile_pages` value as a mode (case-insensitive); anything else is the default. */
+export function parseMetafilePagesMode(value: string | null | undefined): MetafilePagesMode {
+ const normalized = value?.trim().toLowerCase();
+ return (METAFILE_PAGES_MODES as readonly string[]).includes(normalized ?? '') ? normalized as MetafilePagesMode : DEFAULT_METAFILE_PAGES_MODE;
+}
+
+/** The brain's `sync.metafile_pages` mode; an unreadable config reads as the default. */
+export async function readMetafilePagesMode(engine: Pick<BrainEngine, 'getConfig'>): Promise<MetafilePagesMode> {
+ try { return parseMetafilePagesMode(await engine.getConfig(SYNC_METAFILE_PAGES_KEY)); } catch { return DEFAULT_METAFILE_PAGES_MODE; }
+}
+
+/** A `SYNC_SKIP_FILES` name below the root of its source: the only metafiles whose head can make them pages. */
+export function isNestedSkipMetafile(path: string): boolean {
+ const segments = path.split('/');
+ return segments.length > 1 && (SYNC_SKIP_FILES as readonly string[]).includes(segments[segments.length - 1] ?? '');
+}
+
+const METAFILE_PAGE_KEY_RE = /^(?:type|title|"type"|"title"|'type'|'title')[ \t]*:(?:[ \t]+(.*))?$/;
+
+/**
+ * Whether the file at `path` (relative to its source root) is imported as a page although it is named like scaffolding:
+ * a non-root `SYNC_SKIP_FILES` name under mode `typed` whose head opens with a closed frontmatter fence holding a
+ * top-level `type:` or `title:` key with a value. `head` is the file's text (only the first `METAFILE_HEAD_BYTES`
+ * characters are read); undefined (absent or unreadable) is bare. Every other path returns false.
+ */
+export function metafileIsPage(path: string, head: string | undefined, mode: MetafilePagesMode): boolean {
+ if (mode !== 'typed' || head === undefined || !isNestedSkipMetafile(path)) return false;
+ const lines = head.slice(0, METAFILE_HEAD_BYTES).replace(/^\uFEFF/, '').split(/\r?\n/);
+ let i = 0;
+ while (i < lines.length && lines[i]!.trim() === '') i++;
+ if (lines[i]?.trimEnd() !== '---') return false;
+ let typed = false;
+ for (i++; i < lines.length; i++) {
+ const line = lines[i]!;
+ if (/^---[ \t]*$/.test(line)) return typed;
+ const value = METAFILE_PAGE_KEY_RE.exec(line)?.[1]?.trim();
+ if (value && !value.startsWith('#') && !/^(?:null|~)$/i.test(value)) typed = true;
+ }
+ return false;
+}
+
/**
* Internal classifier. Returns null when the path IS syncable, or a tagged
* SyncableReason explaining why it isn't. The single source of truth that
@@ -600,8 +663,8 @@ function classifySync(path: string, opts: SyncableOptions = {}): SyncableReason
// `isPathPruned`'s doc comment for exactly what is and isn't waivable.
if (isPathPruned(path, opts.includeHidden)) return 'pruned-dir';
- // Skip meta files that aren't pages
- if (isSyncMetafile(path)) return 'metafile';
+ // Skip meta files that aren't pages (a typed nested one is a page when the caller's predicate says so)
+ if (isSyncMetafile(path) && !opts.metafilePage?.(path)) return 'metafile';
if (opts.include && opts.include.length > 0 && !matchesAnyGlob(path, opts.include)) return 'include-glob-miss';
if (opts.exclude && opts.exclude.length > 0 && matchesAnyGlob(path, opts.exclude)) return 'exclude-glob-hit';
diff --git a/test/helpers/config-reader-registry.ts b/test/helpers/config-reader-registry.ts
index 1b6a0c6cb9..0023b4b023 100644
--- a/test/helpers/config-reader-registry.ts
+++ b/test/helpers/config-reader-registry.ts
@@ -44,6 +44,7 @@ export const INTERNAL_CONFIG_STATE: readonly InternalConfigState[] = [
{ key: 'persistence.database_only_sources', reason: 'list maintained by gbrain sources writer activate/deactivate; config unset (which takes any key) is the documented escape hatch' },
{ key: 'persistence.maintenance.last_compaction', reason: 'receipt compaction pass cursor (compaction-pass.ts)' },
{ key: 'persistence.true_up.compacted_through', reason: 'receipt true-up cursor (receipt-true-up.ts)' },
+ { key: 'sync.metafile_pages.applied.', prefix: true, reason: 'per-source marker of the sync.metafile_pages mode a classic sync last applied, so a flip to typed backfills once (sync-metafile-pages.ts)' },
{ key: 'sync.slug_root_mode', reason: 'legacy unsourced slug-root mode stamped by sync (sync-anchor.ts); sourced brains keep it on the sources row' },
{ key: 'transcripts.secret_audit', reason: 'cached transcript secret-audit result (transcripts/secret-audit.ts)' },
{ key: 'trust.backfill_completed_at', reason: 'memory-trust backfill completion marker' },
diff --git a/test/persistence-sync-metafile-pages.test.ts b/test/persistence-sync-metafile-pages.test.ts
new file mode 100644
index 0000000000..483462d8b5
--- /dev/null
+++ b/test/persistence-sync-metafile-pages.test.ts
@@ -0,0 +1,111 @@
+/**
+ * GBRA-150: managed sync under `sync.metafile_pages`. A typed nested metafile is a page for the managed level pass
+ * (sync-pass.ts), discovery and the unindexed-file detector; a bare one is outside the level, so it never counts as
+ * missing and the pass converges. A deleted typed metafile soft-deletes its page, an existing typed file imports on the
+ * first sync after the upgrade, and `off` keeps the detector's metafile_skipped report.
+ */
+import { afterAll, beforeAll, expect, test } from 'bun:test';
+import { execFileSync } from 'node:child_process';
+import { randomUUID } from 'node:crypto';
+import { mkdirSync, mkdtempSync, rmSync, unlinkSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import type { BrainEngine } from '../src/core/engine.ts';
+import type { SyncOpts } from '../src/commands/sync.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { claimWorktree } from '../src/core/persistence/ownership.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { performManagedSync } from '../src/core/persistence/sync-run.ts';
+import { shadowConvergence } from '../src/core/persistence/sync-pass.ts';
+import { findUnindexedFiles } from '../src/core/persistence/unindexed-files.ts';
+import { SYNC_METAFILE_PAGES_KEY } from '../src/core/sync.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { testBackends } from './helpers/test-backends.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const backends = testBackends();
+const home = mkdtempSync(join(tmpdir(), 'gbrain-metafile-managed-'));
+const engines: BrainEngine[] = [];
+let closePostgres: (() => Promise<void>) | undefined;
+const env = { GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home };
+const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();
+const commit = (root: string) => { git(root, 'add', '-A'); git(root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', 'content'); return git(root, 'rev-parse', 'HEAD'); };
+const TYPED_INDEX = '---\ntype: project\ntitle: Acme Example\n---\n\nThe project hub for acme-example.\n';
+const BARE_README = '# Notes\n\nScaffolding that lists the folder.\n';
+const note = (title: string) => '---\ntitle: ' + title + '\n---\nA synthetic observation.\n';
+
+beforeAll(async () => {
+ if (backends.includes('pglite')) { const engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); engines.push(engine); }
+ if (backends.includes('postgres')) { const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!); engines.push(pg.engine); closePostgres = pg.close; }
+}, 120_000);
+
+afterAll(async () => {
+ for (const engine of engines) { await disposePersistenceConsumer(engine); await engine.disconnect(); }
+ await closePostgres?.(); rmSync(home, { recursive: true, force: true });
+});
+
+async function source(engine: BrainEngine, files: Record<string, string>) {
+ const id = 'metafile-' + randomUUID().replace(/-/g, '').slice(0, 20), repo = join(home, id);
+ const write = (path: string, content: string) => { mkdirSync(join(repo, path, '..'), { recursive: true }); writeFileSync(join(repo, path), content); };
+ mkdirSync(repo, { recursive: true }); git(repo, 'init', '-q');
+ for (const [path, content] of Object.entries(files)) write(path, content);
+ commit(repo);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ await engine.executeRaw('INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,$3::text::jsonb)', [id, repo, '{}']);
+ await claimWorktree(engine, id, repo);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ const sync = (extra: Partial<SyncOpts> = {}) => performManagedSync(engine, { sourceId: id, noPull: true, noEmbed: true, noExtract: true, ...extra });
+ const live = async (slug: string) => (await engine.executeRaw<{ deleted_at: string | null }>('SELECT deleted_at FROM pages WHERE source_id=$1 AND slug=$2', [id, slug]))[0];
+ const convergence = async () => (await shadowConvergence(engine, { sourceId: id }))!;
+ return { id, repo, write, sync, live, convergence, commit: () => commit(repo) };
+}
+
+async function each(run: (engine: BrainEngine) => Promise<void>) {
+ await withEnv(env, async () => {
+ for (const engine of engines) {
+ try { await run(engine); } finally { await engine.executeRaw('DELETE FROM config WHERE key=$1', [SYNC_METAFILE_PAGES_KEY]); await disposePersistenceConsumer(engine); }
+ }
+ });
+}
+
+test('managed sync imports a typed nested index.md, skips bare and root metafiles, and the level pass converges', () => each(async engine => {
+ const s = await source(engine, { 'notes/a.md': note('A'), 'projects/acme-example/index.md': TYPED_INDEX, 'notes/README.md': BARE_README, 'index.md': TYPED_INDEX });
+ const first = await s.sync();
+ expect(first.status).toBe('first_sync');
+ expect(await engine.getPage('projects/acme-example/index', { sourceId: s.id })).not.toBeNull();
+ expect(await engine.getPage('notes/readme', { sourceId: s.id })).toBeNull();
+ expect(await engine.getPage('index', { sourceId: s.id })).toBeNull();
+ const level = await s.convergence();
+ expect(level.counts).toEqual({ matched: 2 });
+ expect((await s.sync()).status).toBe('up_to_date');
+}), 240_000);
+
+test('deleting a typed nested metafile soft-deletes its page in managed sync; a bare one is never in the level', () => each(async engine => {
+ const s = await source(engine, { 'notes/a.md': note('A'), 'projects/acme-example/index.md': TYPED_INDEX, 'notes/README.md': BARE_README });
+ await s.sync();
+ unlinkSync(join(s.repo, 'projects/acme-example/index.md'));
+ unlinkSync(join(s.repo, 'notes/README.md'));
+ s.commit();
+ const result = await s.sync();
+ expect(result.deleted).toBe(1);
+ expect((await s.live('projects/acme-example/index'))?.deleted_at).not.toBeNull();
+ expect((await s.convergence()).counts).toEqual({ matched: 1 });
+}), 240_000);
+
+test('an existing typed file imports on the first managed sync after the upgrade; the unindexed detector schedules it instead of metafile_skipped', () => each(async engine => {
+ await engine.setConfig(SYNC_METAFILE_PAGES_KEY, 'off');
+ const s = await source(engine, { 'notes/a.md': note('A'), 'projects/acme-example/index.md': TYPED_INDEX, 'notes/README.md': BARE_README });
+ await s.sync();
+ expect(await engine.getPage('projects/acme-example/index', { sourceId: s.id })).toBeNull();
+ expect(await findUnindexedFiles(engine, s.id)).toMatchObject({ unindexed: 0, metafile_skipped: 1, metafile_samples: ['projects/acme-example/index.md'] });
+ await engine.executeRaw('DELETE FROM config WHERE key=$1', [SYNC_METAFILE_PAGES_KEY]);
+ const scan = await findUnindexedFiles(engine, s.id);
+ expect(scan).toMatchObject({ unindexed: 1, metafile_skipped: 0 });
+ expect(scan.files.map(file => file.path)).toEqual(['projects/acme-example/index.md']);
+ const upgraded = await s.sync();
+ expect(['synced', 'first_sync']).toContain(upgraded.status);
+ expect(upgraded.deleted ?? 0).toBe(0);
+ expect(await engine.getPage('projects/acme-example/index', { sourceId: s.id })).not.toBeNull();
+ expect(await engine.getPage('notes/readme', { sourceId: s.id })).toBeNull();
+ expect((await s.convergence()).counts).toEqual({ matched: 2 });
+}), 240_000);
diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txt
index 15d79af331..f53c741c3d 100644
--- a/test/postgres-unit-arms.txt
+++ b/test/postgres-unit-arms.txt
@@ -351,6 +351,7 @@ test/persistence-sync-cursor-strategy-6696.test.ts
test/persistence-sync-fence-holds.test.ts
test/persistence-sync-holds.test.ts
test/persistence-sync-lease.test.ts
+test/persistence-sync-metafile-pages.test.ts
test/persistence-write-interrupted.test.ts
test/persistence-write-stall.test.ts
test/persistence-writer-fences.test.ts
diff --git a/test/restore-detach-6609.test.ts b/test/restore-detach-6609.test.ts
index 02fb91284b..65cd6b8157 100644
--- a/test/restore-detach-6609.test.ts
+++ b/test/restore-detach-6609.test.ts
@@ -48,20 +48,20 @@ afterAll(async () => {
for (const dir of dirs) rmSync(dir, { recursive: true, force: true });
}, 60_000);
-/** A classic source `id` whose checkout holds `people/<name>.md`, synced, then the file untracked and ignored, and synced again (page soft-deleted). */
-async function untrackedPage(id: string, name: string): Promise<{ dir: string; slug: string }> {
+/** A classic source `id` whose checkout holds `people/<name>.md` (or `<file>`), synced, then the file untracked and ignored, and synced again (page soft-deleted). */
+async function untrackedPage(id: string, name: string, file = `people/${name}.md`): Promise<{ dir: string; slug: string }> {
const dir = mkdtempSync(join(tmpdir(), 'restore-detach-'));
dirs.push(dir);
execSync('git init -q && git config user.email [email protected] && git config user.name t', { cwd: dir });
- mkdirSync(join(dir, 'people'), { recursive: true });
- writeFileSync(join(dir, 'people', `${name}.md`), `---\ntype: person\ntitle: ${name}\n---\n# ${name}\n\nA fixture.\n`);
+ mkdirSync(join(dir, file, '..'), { recursive: true });
+ writeFileSync(join(dir, file), `---\ntype: person\ntitle: ${name}\n---\n# ${name}\n\nA fixture.\n`);
execSync('git add -A && git commit -qm seed', { cwd: dir });
await runSources(engine, ['add', id, '--path', dir, '--no-federated']);
await performSync(engine, { repoPath: dir, sourceId: id, noPull: true, noEmbed: true });
- appendFileSync(join(dir, '.gitignore'), `/people/${name}.md\n`);
- execSync(`git rm -q --cached people/${name}.md && git add .gitignore && git commit -qm untrack`, { cwd: dir });
+ appendFileSync(join(dir, '.gitignore'), `/${file}\n`);
+ execSync(`git rm -q --cached ${file} && git add .gitignore && git commit -qm untrack`, { cwd: dir });
await performSync(engine, { repoPath: dir, sourceId: id, noPull: true, noEmbed: true });
- return { dir, slug: `people/${name}` };
+ return { dir, slug: file.replace(/\.md$/, '').toLowerCase() };
}
function ctx(sourceId: string): OperationContext {
@@ -99,6 +99,15 @@ describe('#6609 restore of a page whose recorded file is gone', () => {
expect(await pageRow('refuse', slug)).toEqual({ source_path: `${slug}.md`, database_only_reason: null, live: false });
}, 60_000);
+ test('GBRA-150: a typed nested metafile page (sync.metafile_pages typed) refuses the same way', async () => {
+ const { slug } = await untrackedPage('metafile', 'acme-example', 'projects/acme-example/index.md');
+ expect(await pageRow('metafile', slug)).toEqual({ source_path: 'projects/acme-example/index.md', database_only_reason: null, live: false });
+ const error = await refusal(restore('metafile', slug));
+ expect(error.code).toBe('source_changed');
+ expect(error.detail).toBe('canonical_file_absent');
+ expect(await pageRow('metafile', slug)).toEqual({ source_path: 'projects/acme-example/index.md', database_only_reason: null, live: false });
+ }, 60_000);
+
test('detach restores it database-only, a full sync keeps it live, and its file synced back re-binds it', async () => {
const { dir, slug } = await untrackedPage('detach', 'bob-example');
const restored = await restore('detach', slug, { detach: true });
diff --git a/test/sync-include-hidden.test.ts b/test/sync-include-hidden.test.ts
index 004f4b1b54..472712608f 100644
--- a/test/sync-include-hidden.test.ts
+++ b/test/sync-include-hidden.test.ts
@@ -121,7 +121,8 @@ describe('sync.ts delta path threads includeHidden (#4027 merge guard)', () => {
// cover behavior; this covers the wiring the classifier can't see).
test('the hoisted syncOpts literal carries includeHidden', () => {
const src = surfaceSource('sync');
- expect(src).toMatch(/const syncOpts = \{ strategy: opts\.strategy, includeHidden: opts\.includeHidden \}/);
+ // GBRA-150: the literal also carries the sync.metafile_pages predicate.
+ expect(src).toMatch(/const syncOpts = \{ strategy: opts\.strategy, includeHidden: opts\.includeHidden, metafilePage \}/);
// The strategy-only form is the regression shape (pre-#4027 master): its
// reappearance means a merge resolved the hoist without the threading.
expect(src).not.toMatch(/const syncOpts = opts\.strategy \? \{ strategy: opts\.strategy \} : undefined/);
diff --git a/test/sync-metafile-pages.test.ts b/test/sync-metafile-pages.test.ts
new file mode 100644
index 0000000000..1cdb880d24
--- /dev/null
+++ b/test/sync-metafile-pages.test.ts
@@ -0,0 +1,182 @@
+/**
+ * GBRA-150: `sync.metafile_pages` (default `typed`). A nested file named like folder scaffolding (index.md,
+ * README.md, schema.md, log.md, RESOLVER.md) whose frontmatter has a type: or title: is an ordinary page for classic
+ * sync (incremental, --full and the bulk import walker); bare scaffolding at any depth and every root-level metafile
+ * stay skipped, and off restores the skip-every-metafile behavior. A deleted typed nested metafile soft-deletes its
+ * page, a legacy page at a typed path refreshes on edit, and the first sync after the upgrade imports existing typed files.
+ */
+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import { execSync } from 'child_process';
+import { mkdirSync, mkdtempSync, rmSync, unlinkSync, writeFileSync } from 'fs';
+import { tmpdir } from 'os';
+import { join } from 'path';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { DEFAULT_METAFILE_PAGES_MODE, isSyncable, metafileIsPage, SYNC_METAFILE_PAGES_KEY, unsyncableReason } from '../src/core/sync.ts';
+import { metafilePagePredicate } from '../src/core/sync-metafile-pages.ts';
+import { collectSyncableFiles } from '../src/commands/import.ts';
+import { resetPgliteState } from './helpers/reset-pglite.ts';
+
+const TYPED_INDEX = '---\ntype: project\ntitle: Acme Example\n---\n\nThe project hub for acme-example.\n';
+const TITLED_README = '---\ntitle: Widgets overview\n---\n\nWhat lives in this folder.\n';
+const BARE_README = '# Notes\n\nScaffolding that lists the folder.\n';
+
+describe('metafileIsPage', () => {
+ test('nested SYNC_SKIP_FILES names with a typed or titled closed frontmatter are pages under typed', () => {
+ expect(DEFAULT_METAFILE_PAGES_MODE).toBe('typed');
+ expect(SYNC_METAFILE_PAGES_KEY).toBe('sync.metafile_pages');
+ for (const path of ['projects/acme-example/index.md', 'a/README.md', 'a/b/schema.md', 'a/log.md', 'a/RESOLVER.md']) {
+ expect(metafileIsPage(path, TYPED_INDEX, 'typed')).toBe(true);
+ expect(metafileIsPage(path, TITLED_README, 'typed')).toBe(true);
+ expect(metafileIsPage(path, TYPED_INDEX, 'off')).toBe(false);
+ }
+ expect(metafileIsPage('a/index.md', '\n\n---\r\ntype: hub\r\n---\r\nbody', 'typed')).toBe(true);
+ expect(metafileIsPage('a/index.md', '\uFEFF---\n"title": Quoted\n---\n', 'typed')).toBe(true);
+ });
+
+ test('bare, unclosed, empty-valued, nested-key and root metafiles are not pages', () => {
+ expect(metafileIsPage('a/README.md', BARE_README, 'typed')).toBe(false);
+ expect(metafileIsPage('a/README.md', undefined, 'typed')).toBe(false);
+ expect(metafileIsPage('a/README.md', '---\ntype: hub\n', 'typed')).toBe(false);
+ expect(metafileIsPage('a/README.md', '---\ntype:\ntitle: ~\n---\n', 'typed')).toBe(false);
+ expect(metafileIsPage('a/README.md', '---\ntype: # comment\n---\n', 'typed')).toBe(false);
+ expect(metafileIsPage('a/README.md', '---\nmeta:\n type: hub\n---\n', 'typed')).toBe(false);
+ expect(metafileIsPage('a/README.md', '# Title\n---\ntype: hub\n---\n', 'typed')).toBe(false);
+ expect(metafileIsPage('index.md', TYPED_INDEX, 'typed')).toBe(false);
+ expect(metafileIsPage('README.md', TYPED_INDEX, 'typed')).toBe(false);
+ expect(metafileIsPage('AGENTS.md', TYPED_INDEX, 'typed')).toBe(false);
+ expect(metafileIsPage('docs/AGENTS.md', TYPED_INDEX, 'typed')).toBe(false);
+ expect(metafileIsPage('a/notes.md', TYPED_INDEX, 'typed')).toBe(false);
+ });
+
+ test('isSyncable consults the predicate for metafile names only', () => {
+ const heads: Record<string, string> = { 'a/index.md': TYPED_INDEX, 'a/README.md': BARE_README, 'index.md': TYPED_INDEX };
+ const read: string[] = [];
+ const metafilePage = metafilePagePredicate('typed', path => { read.push(path); return heads[path]; });
+ expect(isSyncable('a/index.md', { metafilePage })).toBe(true);
+ expect(unsyncableReason('a/README.md', { metafilePage })).toBe('metafile');
+ expect(unsyncableReason('index.md', { metafilePage })).toBe('metafile');
+ expect(isSyncable('a/notes.md', { metafilePage })).toBe(true);
+ expect(isSyncable('a/index.md')).toBe(false);
+ expect(read.sort()).toEqual(['a/README.md', 'a/index.md']);
+ expect(isSyncable('a/index.md', { metafilePage: metafilePagePredicate('off', path => heads[path]) })).toBe(false);
+ });
+});
+
+let engine: PGLiteEngine;
+let repoPath: string;
+const commit = (message: string) => execSync('git add -A && git commit -qm "' + message + '"', { cwd: repoPath, stdio: 'pipe' });
+const write = (path: string, content: string) => { mkdirSync(join(repoPath, path, '..'), { recursive: true }); writeFileSync(join(repoPath, path), content); };
+const sync = async (extra: Record<string, unknown> = {}) => (await import('../src/commands/sync.ts')).performSync(engine, { repoPath, noPull: true, noEmbed: true, ...extra });
+const page = (slug: string) => engine.getPage(slug);
+const live = async (slug: string) => (await engine.executeRaw<{ deleted_at: string | null }>('SELECT deleted_at FROM pages WHERE slug=$1', [slug]))[0];
+const relativeFiles = (opts: Parameters<typeof collectSyncableFiles>[1]) => collectSyncableFiles(repoPath, opts).map(path => path.slice(repoPath.length + 1)).sort();
+
+describe('classic sync imports typed nested metafiles', () => {
+ beforeAll(async () => { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); }, 60_000);
+ afterAll(async () => { if (engine) await engine.disconnect(); }, 60_000);
+ beforeEach(async () => {
+ await resetPgliteState(engine);
+ repoPath = mkdtempSync(join(tmpdir(), 'gbrain-metafile-pages-'));
+ execSync('git init -q && git config user.email "[email protected]" && git config user.name "Test"', { cwd: repoPath, stdio: 'pipe' });
+ write('topics/foo.md', '---\ntype: concept\ntitle: Foo\n---\n\nBaseline content.\n');
+ write('index.md', TYPED_INDEX);
+ commit('initial');
+ });
+ afterEach(() => { if (repoPath) rmSync(repoPath, { recursive: true, force: true }); });
+
+ test('incremental sync imports a typed nested index.md and README.md; bare nested README.md and a typed root index.md stay skipped', async () => {
+ await sync({ full: true });
+ write('projects/acme-example/index.md', TYPED_INDEX);
+ write('widgets/README.md', TITLED_README);
+ write('notes/README.md', BARE_README);
+ write('index.md', TYPED_INDEX.replace('hub', 'hub, edited'));
+ commit('metafiles');
+ const result = await sync();
+ expect(result.status).toBe('synced');
+ expect((await page('projects/acme-example/index'))?.title).toBe('Acme Example');
+ expect((await page('widgets/readme'))?.title).toBe('Widgets overview');
+ expect(await page('notes/readme')).toBeNull();
+ expect(await page('index')).toBeNull();
+ expect(await page('topics/foo')).not.toBeNull();
+ }, 60_000);
+
+ test('the bulk import walker and sync --full agree with incremental sync', async () => {
+ write('projects/acme-example/index.md', TYPED_INDEX);
+ write('notes/README.md', BARE_README);
+ commit('metafiles');
+ expect(relativeFiles({ strategy: 'markdown' })).toEqual(['projects/acme-example/index.md', 'topics/foo.md']);
+ expect(relativeFiles({ strategy: 'markdown', includeGitignored: true })).toEqual(['projects/acme-example/index.md', 'topics/foo.md']);
+ expect(relativeFiles({ strategy: 'markdown', metafilePages: 'off' })).toEqual(['topics/foo.md']);
+ const first = await sync({ full: true });
+ expect(['first_sync', 'synced']).toContain(first.status);
+ expect(await page('projects/acme-example/index')).not.toBeNull();
+ expect(await page('notes/readme')).toBeNull();
+ expect(await page('index')).toBeNull();
+ // A second full sync keeps the typed page (its reconcile reads the file) and the bare one stays out.
+ await sync({ full: true });
+ expect((await live('projects/acme-example/index'))?.deleted_at).toBeNull();
+ }, 60_000);
+
+ test('sync.metafile_pages off restores the skip for every metafile', async () => {
+ await engine.setConfig(SYNC_METAFILE_PAGES_KEY, 'off');
+ await sync({ full: true });
+ write('projects/acme-example/index.md', TYPED_INDEX);
+ commit('typed');
+ await sync();
+ expect(await page('projects/acme-example/index')).toBeNull();
+ await sync({ full: true });
+ expect(await page('projects/acme-example/index')).toBeNull();
+ }, 60_000);
+
+ test('deleting a typed nested metafile soft-deletes its page; a bare legacy metafile page is kept (#1433)', async () => {
+ write('projects/acme-example/index.md', TYPED_INDEX);
+ write('notes/README.md', BARE_README);
+ commit('metafiles');
+ await sync({ full: true });
+ expect(await page('projects/acme-example/index')).not.toBeNull();
+ await engine.putPage('notes/readme', { type: 'concept', title: 'Notes', compiled_truth: 'Indexed by an older gbrain.', timeline: '', frontmatter: { type: 'concept' } });
+ unlinkSync(join(repoPath, 'projects/acme-example/index.md'));
+ unlinkSync(join(repoPath, 'notes/README.md'));
+ commit('remove metafiles');
+ const result = await sync();
+ expect(result.status).toBe('synced');
+ expect((await live('projects/acme-example/index'))?.deleted_at).not.toBeNull();
+ expect((await live('notes/readme'))?.deleted_at).toBeNull();
+ }, 60_000);
+
+ test('a legacy page at a typed nested metafile path refreshes when its file is edited', async () => {
+ write('projects/acme-example/index.md', TYPED_INDEX);
+ commit('typed');
+ await engine.setConfig(SYNC_METAFILE_PAGES_KEY, 'off');
+ await sync({ full: true });
+ await engine.putPage('projects/acme-example/index', { type: 'project', title: 'Acme Example', compiled_truth: 'Stale text an older gbrain indexed.', timeline: '',
+ frontmatter: { type: 'project', title: 'Acme Example' } });
+ await engine.executeRaw("UPDATE pages SET source_path='projects/acme-example/index.md' WHERE slug='projects/acme-example/index'");
+ await engine.setConfig(SYNC_METAFILE_PAGES_KEY, 'typed');
+ write('projects/acme-example/index.md', TYPED_INDEX.replace('The project hub', 'The edited project hub'));
+ commit('edit typed');
+ await sync();
+ expect((await page('projects/acme-example/index'))?.compiled_truth).toContain('The edited project hub');
+ }, 60_000);
+
+ test('the first sync after the upgrade imports existing typed files and rewrites nothing else', async () => {
+ write('projects/acme-example/index.md', TYPED_INDEX);
+ write('notes/README.md', BARE_README);
+ commit('metafiles');
+ // The brain synced under the old behavior: every metafile skipped.
+ await engine.setConfig(SYNC_METAFILE_PAGES_KEY, 'off');
+ await sync({ full: true });
+ expect(await page('projects/acme-example/index')).toBeNull();
+ const before = await engine.executeRaw<{ updated_at: string }>("SELECT updated_at::text FROM pages WHERE slug='topics/foo'");
+ await engine.executeRaw('DELETE FROM config WHERE key=$1', [SYNC_METAFILE_PAGES_KEY]);
+ // No new commit: the upgrade alone makes the typed file a page.
+ const upgraded = await sync();
+ expect(upgraded.status).toBe('synced');
+ expect(upgraded.deleted).toBe(0);
+ expect(await page('projects/acme-example/index')).not.toBeNull();
+ expect(await page('notes/readme')).toBeNull();
+ expect(await engine.executeRaw<{ updated_at: string }>("SELECT updated_at::text FROM pages WHERE slug='topics/foo'")).toEqual(before);
+ // Once applied, a quiet sync is up to date again.
+ expect((await sync()).status).toBe('up_to_date');
+ }, 60_000);
+});
diff --git a/test/unindexed-files.test.ts b/test/unindexed-files.test.ts
index e1a7e4f907..ea9cabe634 100644
--- a/test/unindexed-files.test.ts
+++ b/test/unindexed-files.test.ts
@@ -27,6 +27,7 @@ import { unindexedFilesEntry } from '../src/commands/doctor/checks/unindexed-fil
import { runUnindexedFilesPhase } from '../src/core/cycle/unindexed-files.ts';
import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
import { testBackends } from './helpers/test-backends.ts';
+import { SYNC_METAFILE_PAGES_KEY } from '../src/core/sync.ts';
import { withEnv } from './helpers/with-env.ts';
const backends = testBackends();
@@ -171,7 +172,13 @@ test('a file whose path slug belongs to a database-only page is not indexed: it
expect(scan).toMatchObject({ unindexed: 1, slug_taken: 1, samples: [{ path: 'notes/db-only.md', code: 'clean', slug_taken: true }] });
}), 240_000);
-test('a titled file named like folder scaffolding is reported as metafile_skipped, never scheduled, and only an info finding with a user fix', () => each(async engine => {
+test('under sync.metafile_pages off, a titled file named like folder scaffolding is reported as metafile_skipped, never scheduled, and only an info finding with a user fix', () => each(async engine => {
+ // GBRA-150: the default (typed) imports such a file; off keeps the old skip, which this report names.
+ await engine.setConfig(SYNC_METAFILE_PAGES_KEY, 'off');
+ try { await titledScaffoldingSkipped(engine); } finally { await engine.executeRaw('DELETE FROM config WHERE key=$1', [SYNC_METAFILE_PAGES_KEY]); }
+}), 240_000);
+
+async function titledScaffoldingSkipped(engine: BrainEngine) {
const s = await source(engine, { 'notes/a.md': note('A') });
await s.sync();
await s.legacy({ 'investors/fund-a/index.md': '---\ntitle: Fund A\ntype: company\n---\nA synthetic fund overview.\n', 'notes/README.md': 'Plain scaffolding, no frontmatter.\n' });
@@ -186,6 +193,23 @@ test('a titled file named like folder scaffolding is reported as metafile_skippe
expect(fix).toMatchObject({ actor: 'user', argv: ['gbrain', 'sync', '--source', s.id, '--no-pull'] });
expect(fix.user_message).toContain('investors/fund-a/index.md -> investors/fund-a.md');
expect(fix.user_message).toContain('on purpose');
+ git(s.repo, 'mv', 'investors/fund-a/index.md', 'investors/fund-a.md');
+ commit(s.repo);
+ await runSyncStep(engine, s.id, fix, s.sync);
+ expect(await engine.getPage('investors/fund-a', { sourceId: s.id })).not.toBeNull();
+}
+
+test('under the default sync.metafile_pages typed, a titled nested index.md is an unindexed file a sync imports, not metafile_skipped', () => each(async engine => {
+ const s = await source(engine, { 'notes/a.md': note('A') });
+ await s.sync();
+ await s.legacy({ 'investors/fund-a/index.md': '---\ntitle: Fund A\ntype: company\n---\nA synthetic fund overview.\n', 'notes/README.md': 'Plain scaffolding, no frontmatter.\n' });
+ const scan = await findUnindexedFiles(engine, s.id);
+ expect(scan).toMatchObject({ complete: true, scanned: 2, unindexed: 1, metafile_skipped: 0, metafile_samples: [] });
+ expect(scan.files.map(file => file.path)).toEqual(['investors/fund-a/index.md']);
+ expect(await retryUnindexed(engine, s.id)).toMatchObject({ scheduled: 1 });
+ await s.sync();
+ expect(await engine.getPage('investors/fund-a/index', { sourceId: s.id })).not.toBeNull();
+ expect(await engine.getPage('notes/readme', { sourceId: s.id })).toBeNull();
}), 240_000);
test('a bounded scan that stops early is incomplete and never clean; later passes resume and cover the late paths', () => each(async engine => {