Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(sync): a root AGENTS.md or CLAUDE.md is scaffolding, not a page (#5186)
garrytanedbfb6c2a7bb
diff --git a/docs/architecture/key-files/files-and-sync-2.md b/docs/architecture/key-files/files-and-sync-2.mdindex a8fa6295b7..c9e593522f 100644--- a/docs/architecture/key-files/files-and-sync-2.md+++ b/docs/architecture/key-files/files-and-sync-2.md@@ -8,6 +8,6 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/sync-applicability.ts` — agent-first operator wave E4. `syncContentDirectory(engine, {sourceId, repoPath})` resolves the sync root exactly as `performSync` does and returns it when it is a gbrain-owned content directory (under `<GBRAIN_HOME>/.gbrain/content/`, or an owned `--content-root` recorded in the shared-skills setup receipt) with no `.git` at the root; null otherwise (fail-open). `performSync` calls `assertSyncApplicable` first, so such a source refuses with `sync_not_applicable` (reason `content_directory`, fix `gbrain import <dir> [--no-embed] --source <id>`, `git init` named only as an ask-the-user option) before the managed path or the legacy #2964 anchor self-heal could `git init` it. `sync --all` skips these sources with one line; the dream cycle's sync phase reports them `skipped` (`details.reason: sync_not_applicable`). The CLI `sync` record renders fix-carrying OperationErrors through `renderCliError` (`src/cli/commands/sync.ts`). Pinned by `test/sync-applicability.test.ts`.- `src/core/sync-upstream.ts` — upstream observation for remote-tracking sources (#5255/#5176). `observeUpstream(root, syncedCommit)` reads the checkout's `@{upstream}` commit, the newer of the `FETCH_HEAD` and upstream-ref reflog mtimes (the last fetch, pull or push by any process) and `rev-list --count` of upstream commits the synced commit lacks; `recordUpstreamObservation` (called by `performSync` in `src/commands/sync/perform.ts` after every non-dry-run legacy or managed sync, best-effort) writes them to `sources.upstream_checked_at` / `upstream_commit` / `upstream_behind`, which `managed_writer_guard` does not protect. `upstreamFreshness` is doctor `sync_freshness`'s separate "upstream checked" verdict (a `remote_url` source with no observation or one at least 24 h old is upstream unknown; any observed upstream lead is behind), DB-only so remote doctor runs it. `managedPullWarning` / `UpstreamRefresh` back the cycle sync phase (`runPhaseSync` in `src/core/cycle.ts`), which runs a managed `pull: true` as no-pull and reports `details.upstream_refresh` (`pulled|failed|skipped_managed|not_requested`) plus a `managed_pull_skipped` warning when the checkout tracks an upstream. A managed brain's fix (the warning and doctor's behind/unknown verdict) is `gbrain sources refresh <source>`; an unmanaged one's is `gbrain sync --source <source>`. Tests: `test/managed-cycle-pull-upstream.test.ts`, the pull row of `test/managed-phase-matrix.test.ts`.-- `src/core/sync.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 four canonical metafile basenames `schema.md`, `index.md`, `log.md`, `README.md`). `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.+- `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 `gbrain harden` 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.- `src/core/write-through.ts` — shared atomic disk write-through for the canonical ingestion path. `resolvePageWriteTarget(engine, slug, sourceId, { includeDeleted? })` (active rows by default; `includeDeleted: true` resolves a tombstone's recorded `source_path` for the purge remediation retry) is the exported single source of truth for the ONE file a (source, slug) pair lives in on disk: a source with its own `local_path` writes at that tree's ROOT (never nested under `.sources/`); a source without one nests under the host repo (`sync.repo_path`, default at root, non-default under `.sources/<id>/`) unless that path is another source's own working tree (leak guard → `source_repo_belongs_to_other_source`); the page's recorded `source_path` (or a contained absolute `file://` `source_uri`; a relative or host-only `file://` names no local file and is read as absent) is preferred over a slug-derived name so writes land in the file of record instead of minting a twin; and `isWriteTargetContained` rejects hostile rows escaping the tree (`path_escapes_source_root`). The ok-result also carries `sourcePathToBind` — the target expressed in the file scanner's `source_path` convention for the source's pinned `slug_root_mode` (or the mode its first sync would pin, via `scannerSlugRootMode`): GIT-ROOT-relative under `git-root` when the scan root sits inside a git repo, scan-root-relative under `source-root` and for non-git or git-root scan roots, so a put-born page binds the same form managed sync and delete-reconcile key on. Every recorded-path reader (write targets, takes, reconcile, audit, export restore, doctor) decodes with the same mode (`resolveSourceLocalFilePath(..., slugRootMode)`): under `source-root` the scope prefix is removed only from the legacy Git-root form whose remainder names the page slug, and basename rows resolve under the unstripped slug directory. The resolver is shared by `writePageThrough`, the facts fence writer (`src/core/facts/fence-write.ts`), and fence forget (`src/core/facts/forget.ts`) — the fence appends to the page's file, so all writers MUST compute the identical path or the fence lands in a file sync never reads back and the next extract_facts reconcile deletes the fence-owned DB rows. `writePageThrough(engine, slug, {sourceId?, frontmatterOverrides?, logger?, expectedFileBytes?})` resolves the target through it, re-reads the just-written DB row (`getPage`), renders it via `serializePageToMarkdown`, and writes the `.md` so the brain has a committable artifact that round-trips through `gbrain sync`. Rendering from the row keeps the serialized content consistent at write time. The fsync-backed `atomicWriteFileSync` stages and renames the file after required source-path bookkeeping; lock/lease checks run before publication. `put_page` holds the root lock before importing and invokes write-through inside its database transaction, so ordinary filesystem rejection rolls back existing content, tags, chunks, and versions. A crash or database COMMIT failure after rename can still leave canonical Markdown ahead of the index; this is not distributed ACID or a durable queue. Never throws — returns `WriteThroughResult { written, path?, skipped?: 'disabled_by_config' | 'no_repo_configured' | 'repo_not_found' | 'source_repo_belongs_to_other_source' | 'page_not_found_after_write' | 'path_escapes_source_root' | 'case_insensitive_collision' | 'file_changed', warning?, error? }` (`file_changed`: the caller's `expectedFileBytes` preimage, null for absent, no longer matches the file under the source filesystem lock, so the file is left untouched) so the caller decides messaging + exit codes. `withNoRepoWriteThroughWarning(result, sourceId)` decorates an unwritten `no_repo_configured` result with `warning` (the write landed only in the database; bind the token/server to a git-backed source or configure `local_path`/`sync.repo_path`); `put_page` applies it for untrusted callers only (`ctx.remote !== false`), so local CLI responses and the `disabled_by_config` operator opt-out stay silent. `isWriteThroughDisabled` (shared with the fence lane, ~30s per-engine cache) honors the `sync.write_through` opt-out. Trust gating (subagent sandbox, dry-run) stays at the CALLER. On a durability-hardened repo (`isDurabilityHardened` — the gbrain post-commit hook is installed, i.e. the user ran `gbrain sources harden`), a successful write is best-effort COMMITTED via `commitWriteThroughFile` (path-limited `git commit -- <file>`, never sweeps unrelated edits; the hook then background-pushes) so write-through content reaches git instead of accumulating uncommitted forever; result carries `committed?: boolean`. Unhardened repos keep write-only behavior. `deletePageThrough(engine, slug, {sourceId?, target?, logger?})` is the delete-side sink (sole caller: the `delete_page` op): resolves the same target, unlinks the `.md`, and on a hardened repo best-effort commits the removal path-limited through the same helper with subject `gbrain: delete write-through <slug>`, reporting `committed?: boolean` on `DeleteThroughResult` (absent when unhardened or when the commit did not land — the unlink still stands; a never-committed page leaves nothing to commit, so no empty commit). Pinned by `test/delete-write-through-commit.test.ts`. Consumers: `put_page` op and `gbrain brainstorm/lsd --save` via `persistSavedIdea`. Pinned by `test/write-through.test.ts` + `test/write-through-commit.test.ts`. The `put_page` op is that deciding caller for direct writes: a skip outside the deliberate DB-only set (`no_repo_configured`/`disabled_by_config`/`subagent_sandbox`/`dry_run`) throws `storage_error` inside the import transaction, rolling back the page revision, tags, chunks and version snapshot instead of deleting a just-created row afterward.diff --git a/src/commands/import.ts b/src/commands/import.tsindex c6857b2b95..b71e045c26 100644--- a/src/commands/import.ts+++ b/src/commands/import.ts@@ -24,7 +24,7 @@ import {matchesAnyGlob,pruneDir,isPathPruned,- SYNC_SKIP_FILES,+ isSyncMetafile,type SyncStrategy,} from '../core/sync.ts';import { sortNewestFirst } from '../core/sort-newest-first.ts';@@ -1255,7 +1255,8 @@ interface CollectOpts {* — preserve the walker semantic explicitly.** Closes #345: exclude `SYNC_SKIP_FILES` metafiles- * (`README.md` / `index.md` / `log.md` / `schema.md` / `RESOLVER.md`).+ * (`README.md` / `index.md` / `log.md` / `schema.md` / `RESOLVER.md`) and, since+ * #5186, the root-level `AGENTS.md` / `CLAUDE.md` (`SYNC_ROOT_SKIP_FILES`).* Incremental `sync` skips these via `isSyncable`, but the bulk-import* walker only filtered by extension — so a directory import imported every* directory README as a page, titled by its folder ("People", "Companies",@@ -1290,11 +1291,10 @@ function isCollectibleForWalker(if (hasMalformedPathSegment(path)) return false;// Metafiles are directory scaffolding (READMEs / index / log / schema /- // resolver), not typed brain pages — same exclusion `sync`'s `isSyncable`- // applies. Guards both the FS-walk and the git-fast-path collection routes.- const segments = path.split('/');- const basename = segments[segments.length - 1] || '';- if ((SYNC_SKIP_FILES as readonly string[]).includes(basename)) return false;+ // 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;switch (strategy) {case 'code':diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex c6be7b6d73..5aafbb2abf 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -381,6 +381,8 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }{ since: '0.60.156.0', text: 'A Git rename onto a slug a soft-deleted page still holds now moves the page onto that slug with its id, history, edges, facts and aliases in one transaction; the tombstone keeps its own history under `<slug>~purged-<id>`, a name no file can take, so nothing is hard-deleted. A rename whose destination a live page holds still imports the renamed content there, but the old row\'s edges, timeline, versions, facts, withdrawals and aliases now move to that page (with `[[old-slug]]` recorded as an alias) before the old row is soft-deleted, instead of being stranded on the tombstone. Any other database error on the rename fails the file and leaves the sync checkpoint where it was, where it used to be swallowed. The renamed page\'s `source_path` is repaired inside the rename transaction, so a later `gbrain sync --full` cannot read the live page as a removed file.' },// W14 PR1 P1.4 (#5200). `since` is a placeholder equal to the branch's VERSION until the merge-slot stamp.{ since: '0.60.156.0', text: '`gbrain sources archive`, `remove` and `purge` no longer walk and hash a canonical checkout that already has a verified manifest: they compare no bytes, so a symlink or submodule that appeared in the checkout after it was claimed no longer refuses them with `writer_manifest_unsafe` while their dry run said they would succeed. The stored manifest keeps its digest and gets a fresh `canonical_stamp`; a source claimed before activation, whose manifest was never recorded, still records it on retire. Claim, set-path (rebind), restore and reclone still hash the checkout, and every lifecycle dry run now reports `manifest_required`.' },+ // W14 PR1 P1.5b (#5186). `since` is a placeholder equal to the branch's VERSION until the merge-slot stamp.+ { since: '0.60.156.0', text: 'A root-level `AGENTS.md` or `CLAUDE.md` in a source (the agent instructions `gbrain harden` writes) is no longer imported as a page: sync and `gbrain import` classify it as a metafile like `README.md`, while the same file inside a directory is still a page. A root `agents` or `claude` page an earlier version indexed is kept, not deleted; `gbrain delete agents` removes it if it is unwanted.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/sync.ts b/src/core/sync.tsindex 1f8bd4e448..75155958d0 100644--- a/src/core/sync.ts+++ b/src/core/sync.ts@@ -539,6 +539,21 @@ export function sanitizePathForDisplay(path: string): string {*/export const SYNC_SKIP_FILES = ['schema.md', 'index.md', 'log.md', 'README.md', 'RESOLVER.md'] as const;+/**+ * #5186 (W14 P1.5b): `gbrain harden` scaffolds these at the source root as+ * agent instructions, not brain content. Metafiles at depth 0 only: a+ * `docs/AGENTS.md` is an ordinary page.+ */+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). */+export function isSyncMetafile(path: string): boolean {+ const segments = path.split('/');+ const basename = segments[segments.length - 1] || '';+ return (SYNC_SKIP_FILES as readonly string[]).includes(basename)+ || (segments.length === 1 && (SYNC_ROOT_SKIP_FILES as readonly string[]).includes(basename));+}+/*** Internal classifier. Returns null when the path IS syncable, or a tagged* SyncableReason explaining why it isn't. The single source of truth that@@ -566,9 +581,7 @@ function classifySync(path: string, opts: SyncableOptions = {}): SyncableReasonif (isPathPruned(path, opts.includeHidden)) return 'pruned-dir';// Skip meta files that aren't pages- const segments = path.split('/');- const basename = segments[segments.length - 1] || '';- if ((SYNC_SKIP_FILES as readonly string[]).includes(basename)) return 'metafile';+ if (isSyncMetafile(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/sync-root-agents-metafile.test.ts b/test/sync-root-agents-metafile.test.tsnew file mode 100644index 0000000000..72f5282a7f--- /dev/null+++ b/test/sync-root-agents-metafile.test.ts@@ -0,0 +1,78 @@+/**+ * #5186 (W14 P1.5b): `gbrain harden` scaffolds `AGENTS.md` / `CLAUDE.md` at the+ * source root as agent instructions, not brain content. Sync classifies the+ * root-level pair as `metafile` (depth 0 only; `docs/AGENTS.md` is still a+ * page), full import skips them the same way, and a root `agents` page an+ * earlier gbrain indexed survives re-sync under the #1433 metafile guard.+ */+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+import { execSync } from 'child_process';+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'fs';+import { tmpdir } from 'os';+import { join } from 'path';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { isSyncable, unsyncableReason } from '../src/core/sync.ts';+import { resetPgliteState } from './helpers/reset-pglite.ts';++describe('root AGENTS.md / CLAUDE.md classify as metafile', () => {+ test('depth 0 only', () => {+ for (const path of ['AGENTS.md', 'CLAUDE.md']) {+ expect(isSyncable(path)).toBe(false);+ expect(unsyncableReason(path)).toBe('metafile');+ }+ for (const path of ['docs/AGENTS.md', 'skills/CLAUDE.md', 'agents.md', 'AGENTS-notes.md']) {+ expect(isSyncable(path)).toBe(true);+ }+ });+});++describe('#5186 — a hardened root AGENTS.md is not imported, and an existing root page survives', () => {+ let engine: PGLiteEngine;+ let repoPath: string;+ 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-root-agents-'));+ execSync('git init && git config user.email "[email protected]" && git config user.name "Test"', { cwd: repoPath, stdio: 'pipe' });+ mkdirSync(join(repoPath, 'topics'), { recursive: true });+ mkdirSync(join(repoPath, 'docs'), { recursive: true });+ writeFileSync(join(repoPath, 'topics/foo.md'), '---\ntype: concept\ntitle: Foo\n---\n\nBaseline content.\n');+ writeFileSync(join(repoPath, 'AGENTS.md'), '# Agents working on this brain\n\nRecall before answering.\n');+ writeFileSync(join(repoPath, 'CLAUDE.md'), '# Claude\n\nRead AGENTS.md.\n');+ writeFileSync(join(repoPath, 'docs/AGENTS.md'), '---\ntype: concept\ntitle: Agents guide\n---\n\nA page about agents.\n');+ execSync('git add -A && git commit -m "initial"', { cwd: repoPath, stdio: 'pipe' });+ });+ afterEach(() => { if (repoPath) rmSync(repoPath, { recursive: true, force: true }); });++ test('full and incremental sync skip the root pair and keep the nested page', async () => {+ const { performSync } = await import('../src/commands/sync.ts');+ const first = await performSync(engine, { repoPath, full: true, noPull: true, noEmbed: true });+ expect(['first_sync', 'synced']).toContain(first.status);+ expect(await engine.getPage('agents')).toBeNull();+ expect(await engine.getPage('claude')).toBeNull();+ expect(await engine.getPage('docs/agents')).not.toBeNull();+ expect(await engine.getPage('topics/foo')).not.toBeNull();++ writeFileSync(join(repoPath, 'AGENTS.md'), '# Agents working on this brain\n\nRecall before answering. Save with provenance.\n');+ execSync('git add -A && git commit -m "edit agents"', { cwd: repoPath, stdio: 'pipe' });+ const second = await performSync(engine, { repoPath, noPull: true, noEmbed: true });+ expect(['synced', 'first_sync', 'up_to_date']).toContain(second.status);+ expect(await engine.getPage('agents')).toBeNull();+ }, 60_000);++ test('a root agents page indexed by an earlier gbrain survives re-sync (#1433 guard)', async () => {+ const { performSync } = await import('../src/commands/sync.ts');+ await performSync(engine, { repoPath, full: true, noPull: true, noEmbed: true });+ await engine.putPage('agents', { type: 'concept', title: 'Agents', compiled_truth: 'Pre-existing page that should survive re-sync.', timeline: '', frontmatter: { type: 'concept' } });+ expect(await engine.getPage('agents')).not.toBeNull();++ writeFileSync(join(repoPath, 'AGENTS.md'), '# Agents working on this brain\n\nEdited after indexing.\n');+ execSync('git add -A && git commit -m "edit agents"', { cwd: repoPath, stdio: 'pipe' });+ const second = await performSync(engine, { repoPath, noPull: true, noEmbed: true });+ expect(['synced', 'first_sync', 'blocked_by_failures', 'up_to_date']).toContain(second.status);+ const survivor = await engine.getPage('agents');+ expect(survivor).not.toBeNull();+ expect(survivor?.compiled_truth).toContain('Pre-existing page');+ }, 60_000);+});