Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
test(pathological): C-2 url clone probe on PGLite and Postgres; key-files entries (GBRA-130 C-2)
garrytanb06b3d9aa167
diff --git a/docs/architecture/key-files/core-cycle.md b/docs/architecture/key-files/core-cycle.mdindex 3b5848ed16..dd091a7bcf 100644--- a/docs/architecture/key-files/core-cycle.md+++ b/docs/architecture/key-files/core-cycle.md@@ -27,7 +27,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGELBoth paths prevent LLM-chosen titles that drift between extractions from piling up.Atom identity: page-derived atoms fold the source-page slug into the slug hash (8 chars, NUL-separated) so two same-date pages emitting the same title get DISTINCT slugs; the source CONTENT hash is deliberately NOT folded (a reworded source still upserts rather than duping); transcript atoms keep the legacy title-only 6-char hash. `resolvePageAtomSlug` adopts a legacy-slug atom with a compatible binding in place on re-extraction (upgrade idempotency — no migration, no duplicate), while `assertAtomImportBinding` fail-closed refuses to reuse a slug bound to a DIFFERENT source locator. Both share `isCompatibleAtomBinding(frontmatter, sourcePageSlug)` — the ONE definition of compatible: bound to THIS source page, or carrying no `source_slug`/`source_path` at all (pre-binding-era adoption, not a clobber); a `source_path`-bound legacy transcript atom or a different `source_slug` is a different origin, and a non-atom page squatting on the slug is refused. `source_quote` is verified at extraction time against the exact `truncateUtf8` prompt prefix the model saw (`locateQuote` advances by full code points): located quotes persist original characters + [start,end) offsets + `source_quote_verified`; unlocatable quotes are dropped with the atom kept. Edges write before the completion flip; per-item drain failures stay typed (bounded, sanitized, reconcilable). Transcript items carry the same failure-count/tombstone machinery as pages, in the `extract_atoms_transcript_state` table (keyed `(source_id, file_path, content_hash)`, 16-char hash prefix, so an edit is a new row): `recordItemFailureCount` counts a transcript's malformed output or prompt-level provider block (`providerContentBlockReason`; never feeds the outage halt) toward `MAX_DETERMINISTIC_FAILURES`, a zero-yield transcript tombstones immediately (as pages do), and `tombstonedTranscriptsForHashes` is the batch read-side gate mirroring `atomsExistingForHashes` (fail-open on error). Reported as `tombstoned_transcripts` (paths), separate from the page-slug `tombstoned_for_failures`. Malformed managed output requires a newly approved protected-job retry identity; publication retry reuses retained output and original/current grants.-- `src/core/cycle/extract-facts.ts` — source-scoped `## Facts` fence reconciliation. Rows are keyed by fence row number, never by claim text: a DB row whose `(row_num, claim)` is still in the fence keeps its id and has its other cells updated in place (ids from recall stay valid for forget; `source_session`, `created_at`, consolidation state and vectors survive), a row whose number left the fence or whose claim was rewritten is expired and detached (`row_num` NULL), never deleted, and only new row numbers insert. Duplicate ACTIVE rows with the same claim and source index once; a struck history row never collapses onto an active row with the same text, so a claim that reverts (NYC → SF → NYC) stays active. `superseded by #N` links resolve on every hop of a chain (`supersede-resolve.ts`; forgotten targets and cycles still resolve to NULL with a warning). Each run first fences the source's unfenced rows (`row_num IS NULL`, live entity page, never ontology observations: `dimension IS NULL`, #6264) through `facts/unfenced-facts.ts` and adds those pages to the run's reconcile set (`unfencedRowsFenced`); rows it cannot fence this run (canonical file not on this host, malformed fence, held page lock, a claim the fence codec cannot render) are named as `FACTS_FENCE_FAILED: <slug> (<reason>)` and keep their own page out of the destructive reconcile (the empty-fence guard, per page since #6278: `pendingLegacyRows` lists the pages, `legacyRowsPending` and `legacyPages` report them, and every other page of the source still reconciles; the page keeps its fact index because reconciliation would classify its `row_num IS NULL` rows as stale and expire them). The phantom-redirect pass moves rows by fence position and so still waits until the source has no unfenced rows. `runPhaseExtractFacts` (`cycle.ts`) then reports the reconcile counts of the pages that did reconcile and names the skipped pages in its summary. Rows with no backing page or checkout, and ontology observations, never gate. It then expires (without detaching) the active fence-owned rows of soft-deleted pages in the source; restoring the page re-activates them on its next reconcile. Previously embedded fact rows and their text/provenance remain intact when a full valid replacement embedding batch is unavailable; old vectors are never transplanted to changed text/model. Restrictive fence changes still expire removed/withdrawn claims and tighten visibility before deferral. Provider cancellation within database writes rolls back rather than publishing half a replacement. Keyless initial fact insertion remains supported; conversation-origin facts without a fence are not wiped by fence reconciliation. Each page reconciles in isolation: a page whose writes the database rejects rolls back, is reported as `<slug>: FACTS_RECONCILE_FAILED: …` (counted in `pagesFailed`, booked as a halt in the rollup), and later pages still reconcile. `facts.superseded_by` is `ON DELETE SET NULL`. On an unmanaged brain each reconcile records its outcome in `page_facts_reconcile` (`src/core/facts/reconcile-watermark.ts`): a complete reconcile (including a no-op) stamps the page's `knowledge_revision` inside the write transaction, after a `FOR SHARE` lock and a revision recheck (a moved page writes nothing and stays due); `deferred` (lock, stale cache, embedding deferral, rejected write), `invalid` (malformed or misplaced fence, not retried until the page changes) and `cancelled` leave it due. The dream cycle passes `drain`, so an incremental run also reconciles up to 250 due pages within 60 s, never-attempted first then oldest attempt, after settling in bulk the due pages with no fence marker and no fence rows; a fence imported by a standalone sync or removed from a page is therefore reconciled even when the cycle's own sync changed nothing. A direct call with `slugs: []` and no `drain` still reconciles nothing. Doctor's `extract_health` names unreconciled fence pages and unreadable fences on unmanaged brains. Tests: `test/extract-facts-reconcile-drain.test.ts` (Postgres race through `test/e2e/extract-facts-reconcile-drain-postgres.test.ts`), `test/e2e/fact-vector-repair-parity.test.ts`, `test/extract-facts-phase.test.ts`, `test/extract-facts-unfenced-rows.test.ts` (a mixed page, on PGLite and through the Postgres E2E), `test/extract-facts-poison-page.test.ts`, `test/extract-facts-stable-identity.test.ts`. On a managed brain the same reconcile runs after `managedDerivedFactsPreflight` (local writer, active source, before any embedding call): each page transaction and the deleted-page expiry commit inside `withDerivedFactsWrite` (coordinator source capability, page key locked); the facts receipt page is skipped, the rollup is still booked. Each deleted page's expiry is one item (ItemRun site `extract_facts.expire_deleted`, src/core/item-failure.ts): a refused expiry is a `FACTS_EXPIRE_FAILED: <slug>: <code>: …` warning (the phase warns) retried by the next run, a page the refusal breaker holds back is a `FACTS_EXPIRE_SKIPPED` warning, and run-scoped errors or most pages failing (`item_failures_systemic`) still fail the phase; test `test/pathological/a21-facts-expire-deleted.test.ts`. It is distinct from the coordinated `extract_facts` operation and durable page backstop. Tests: `test/managed-facts-writers.test.ts`. Wave B PR 2 (lane 2e2): a segmented page reconciles like an inline one, its fences read from its marker segments (`segmentedFactsFenceView`), its write guarded by content hash and size, and its stale-cache check streamed against the canonical file (`segmentedBodyMatchesFile`, page-body/segment-facts.ts); test `test/large-pages/segmented-facts-reconcile.test.ts`. #6259: it and `extract-takes.ts` (both the DB walk and the file walk, which checks the stored page) skip a quarantined page, leaving rows projected before it was quarantined as they are. Test: `test/quarantine-fence-projection.test.ts`.+- `src/core/cycle/extract-facts.ts` — source-scoped `## Facts` fence reconciliation. Rows are keyed by fence row number, never by claim text: a DB row whose `(row_num, claim)` is still in the fence keeps its id and has its other cells updated in place (ids from recall stay valid for forget; `source_session`, `created_at`, consolidation state and vectors survive), a row whose number left the fence or whose claim was rewritten is expired and detached (`row_num` NULL), never deleted, and only new row numbers insert. Duplicate ACTIVE rows with the same claim and source index once; a struck history row never collapses onto an active row with the same text, so a claim that reverts (NYC → SF → NYC) stays active. `superseded by #N` links resolve on every hop of a chain (`supersede-resolve.ts`; forgotten targets and cycles still resolve to NULL with a warning). Each run first fences the source's unfenced rows (`row_num IS NULL`, live entity page, never ontology observations: `dimension IS NULL`, #6264) through `facts/unfenced-facts.ts` and adds those pages to the run's reconcile set (`unfencedRowsFenced`); rows it cannot fence this run (canonical file not on this host, malformed fence, held page lock, a claim the fence codec cannot render) are named as `FACTS_FENCE_FAILED: <slug> (<reason>)` and keep their own page out of the destructive reconcile (the empty-fence guard, per page since #6278: `pendingLegacyRows` lists the pages, `legacyRowsPending` and `legacyPages` report them, and every other page of the source still reconciles; the page keeps its fact index because reconciliation would classify its `row_num IS NULL` rows as stale and expire them). The phantom-redirect pass moves rows by fence position and so still waits until the source has no unfenced rows. `runPhaseExtractFacts` (`cycle.ts`) then reports the reconcile counts of the pages that did reconcile and names the skipped pages in its summary. Rows with no backing page or checkout, and ontology observations, never gate. It then expires (without detaching) the active fence-owned rows of soft-deleted pages in the source; restoring the page re-activates them on its next reconcile. Previously embedded fact rows and their text/provenance remain intact when a full valid replacement embedding batch is unavailable; old vectors are never transplanted to changed text/model. Restrictive fence changes still expire removed/withdrawn claims and tighten visibility before deferral. Provider cancellation within database writes rolls back rather than publishing half a replacement. Keyless initial fact insertion remains supported; conversation-origin facts without a fence are not wiped by fence reconciliation. Each page reconciles in isolation: a page whose writes the database rejects rolls back, is reported as `<slug>: FACTS_RECONCILE_FAILED: …` (counted in `pagesFailed`, booked as a halt in the rollup), and later pages still reconcile. `facts.superseded_by` is `ON DELETE SET NULL`. On an unmanaged brain each reconcile records its outcome in `page_facts_reconcile` (`src/core/facts/reconcile-watermark.ts`): a complete reconcile (including a no-op) stamps the page's `knowledge_revision` inside the write transaction, after a `FOR SHARE` lock and a revision recheck (a moved page writes nothing and stays due); `deferred` (lock, stale cache, embedding deferral, rejected write), `invalid` (malformed or misplaced fence, not retried until the page changes) and `cancelled` leave it due. The dream cycle passes `drain`, so an incremental run also reconciles up to 250 due pages within 60 s, never-attempted first then oldest attempt, after settling in bulk the due pages with no fence marker and no fence rows; a fence imported by a standalone sync or removed from a page is therefore reconciled even when the cycle's own sync changed nothing. A direct call with `slugs: []` and no `drain` still reconciles nothing. Doctor's `extract_health` names unreconciled fence pages and unreadable fences on unmanaged brains. Tests: `test/extract-facts-reconcile-drain.test.ts` (Postgres race through `test/e2e/extract-facts-reconcile-drain-postgres.test.ts`), `test/e2e/fact-vector-repair-parity.test.ts`, `test/extract-facts-phase.test.ts`, `test/extract-facts-unfenced-rows.test.ts` (a mixed page, on PGLite and through the Postgres E2E), `test/extract-facts-poison-page.test.ts`, `test/extract-facts-stable-identity.test.ts`. On a managed brain the same reconcile runs after `managedDerivedFactsPreflight` (local writer, active source, before any embedding call): each page transaction and the deleted-page expiry commit inside `withDerivedFactsWrite` (coordinator source capability, page key locked); the facts receipt page is skipped, the rollup is still booked. Each deleted page's expiry is one item (ItemRun site `extract_facts.expire_deleted`, src/core/item-failure.ts): a refused expiry is a `FACTS_EXPIRE_FAILED: <slug>: <code>: …` warning (the phase warns) retried by the next run, a page the refusal breaker holds back is a `FACTS_EXPIRE_SKIPPED` warning, and run-scoped errors or most pages failing (`item_failures_systemic`) still fail the phase; test `test/pathological/a21-facts-expire-deleted.test.ts`. It is distinct from the coordinated `extract_facts` operation and durable page backstop. Tests: `test/managed-facts-writers.test.ts`. Wave B PR 2 (lane 2e2): a segmented page reconciles like an inline one, its fences read from its marker segments (`segmentedFactsFenceView`), its write guarded by content hash and size, and its stale-cache check streamed against the canonical file (`segmentedBodyMatchesFile`, page-body/segment-facts.ts); test `test/large-pages/segmented-facts-reconcile.test.ts`. #6259: it and `extract-takes.ts` (both the DB walk and the file walk, which checks the stored page) skip a quarantined page, leaving rows projected before it was quarantined as they are. Test: `test/quarantine-fence-projection.test.ts`. #6946: a gbrain-owned `--url` clone on an unmanaged brain never gates the empty-fence guard (its facts are database-only by design).- `src/core/cycle/inline-drain.ts` — the dream cycle's private-queue drain. `runSubagentsInline(engine, queue, queueName, yieldDuringPhase?, handler?, lockMs?, concurrency?)` runs N independent `drainLoop`s (`dream.synthesize.inline_concurrency`, clamp [1,8], PGLite forced serial at the callsite) sharing the queue via the same SKIP-LOCKED claim fencing workers use — everything job-scoped (lockToken, abort, timeout timer, keepalive, renewTimer, outcome recording) stays loop-local. Pool hygiene: global housekeeping sweeps are leader-only (loop 0) while `promoteDelayed` runs in every loop; idle claim-poll backs off 1s→5s; a NON-retryable loop-level failure aborts siblings after their current child (a failing child is a job outcome, never a drain crash). Exit only when the queue holds no active/waiting/delayed child (a lease-full bounce's delayed backoff must not strand a child). Outcome routing mirrors the worker: `UnrecoverableError` → dead immediately; `RateLeaseUnavailableError` → `releaseLeaseFullJob` requeue without burning an attempt; timeout terminal. Handler invocation is wrapped in `withChatPhase('job:<name>')` (worker.ts parity) so each drained child's gateway spend is attributed to the CHILD — a bare `await handler(context)` inherits the caller's AsyncLocalStorage phase, and a cycle phase that wraps its own work (dream synthesize wraps `phase:synthesize`) would absorb every child's spend into the phase tag. `runDrainRenewalTick` (per-call AbortSignal + timeout + re-entrancy guard) and the null-safe nearest-rank `percentile()` telemetry helper are exported. Pinned by `test/cycle-synthesize-inline-concurrency.test.ts` (loop semantics) + `test/e2e/dream-synthesize-concurrency-postgres.test.ts` (real-Postgres exact-once + lease-ceiling).diff --git a/docs/architecture/key-files/core-persistence-graduation.md b/docs/architecture/key-files/core-persistence-graduation.mdindex 7b5708aa6e..3445d29134 100644--- a/docs/architecture/key-files/core-persistence-graduation.md+++ b/docs/architecture/key-files/core-persistence-graduation.md@@ -17,5 +17,6 @@ Verified engine graduation, PGLite to Postgres ([operator guide](../../guides/mo- `src/commands/migrate-graduation.ts` — the `gbrain migrate` graduation CLI, routed before connect from `routeEngineFreeSubcommands` in `src/cli.ts` when `routesToGraduation` holds (run-scoped verbs and `--plan` always; a bare `--to postgres|supabase` on a durable PGLite config unless `migrate.graduation` is false or the host is Windows). Without `--yes --expect` it plans and returns the `confirmation_required` payload (effects egress and destructive, what moves and what stays, `plan_hash`, the `--plan` preview; no stdin prompt); `--plan`/`--dry-run` prints the plan; the run reports the receipt, retained copy, target doctor, `gbrain mcp expose` and the MCP restart note. Exit codes 0/1/2/3, 11 for a progressing drain stop (1 when a blocker needs a person), 75 for `graduation_in_progress`, 130 after SIGINT (stops at the next batch boundary). `--json` prints one document; progress goes to stderr per table and batch. Test: `test/migrate-graduation-cli.serial.test.ts`.- `src/commands/doctor/checks/engine-graduation.ts` — `graduationStateCheck`, emitted from the filesystem lane of `local-audits.ts`: `graduation_interrupted` fails when a manifest or marker is non-terminal with no live owner (fix `gbrain migrate --resume`, rollback named) or a stray brain sits at the old path, is `ok` while a live run owns it, exempts the run named by `GBRAIN_GRADUATION_RUN`, and emits nothing on a brain that never graduated. The retained `.graduated-*` copy is reported by `pglite_leftovers` (`src/core/pglite-leftovers-check.ts`), silent while a manifest is non-terminal.- `src/core/repair/missing-tables.ts` — `gbrain repair missing-tables` (#6911), explicit-only and preview-bound (`--apply --expect <hash>`), brain-wide, DDL only. The preview lists the missing rebuildable caches `readMissingTables` reports (`recreate`), plus `user_data_tables` and `other_tables` residuals it never recreates; the hash covers the brain id, `LATEST_VERSION` and the tables. Apply refuses when the brain schema is newer than the client, leaves a table that already exists alone (`already_present`, no DDL), runs `recreateStep` in one transaction per table under the migration statement and lock timeouts (`schemaLockBlockedError` on a lock timeout), maps 42501 to `schema_owner_required` (approval kept) and 23505/42P07 races to `already_present`, and retires the approved set with the last item. Tests: `test/purge-missing-cache-6911.test.ts`, `test/schema-missing-tables.test.ts`.+- `src/core/repair/url-clone-fences.ts` — `gbrain repair url-clone-fences` (#6946, GBRA-130 C-2): explicit-only, preview-bound, destructive consent; unmanaged brains only (a managed brain gets a warning naming `sources mirror-readonly`). The survey lists every tracked file of each owned clone in scope that differs from HEAD (`trackedChanges`) and proves per file (`proveFenceRowsOnly`) that HEAD's fence rows are an unchanged prefix of the working copy's and that re-rendering HEAD with the working fence matches byte for byte (`fence_rows_only`); anything else is listed as `non_fence_edit` / `unparsed_fence` / `staged_change` / `deleted` / `not_in_head` / `unreadable_checkout` and never touched. The preview hash binds the approved set (preview-approval, keyed by the command string). The apply, per file under the source filesystem lock and page lock, rechecks both sides (`changed_since_preview`), backs the file up under `~/.gbrain/backups/url-clone-fences/`, clears `row_num`/`source_markdown_slug` on the appended rows in one `maintenanceTransaction` (inserting database-only any row the database lost), imports HEAD's bytes as the page through `importFromContent`, and only then restores the file from HEAD; each step is idempotent. Test: `test/pathological/c2-url-clone-fences.test.ts`.- `src/core/schema-missing-tables.ts` — #6911 expected-table check. `readMissingTables`: at head every graduation-inventory table for the engine, below head only the recreatable caches whose creating migration (`CREATED_BY`) already ran, `skipped` (`client_behind`) when the brain is newer; each missing table carries its inventory class and `loss_kind`. `recreateStep` (own-key lookup, rebuild class only) rebuilds `query_cache` (v055 DDL sized from the live `facts.embedding` shape, then the v056/v090/v091 statements) and `code_traversal_cache` (v059). `test/schema-missing-tables.test.ts` pins each recreated table's columns and indexes to the migrated brain's on both engines and checks that every inventory rebuild table is either in `RECREATABLE_TABLES` or defined by the base schema (so `init --migrate-only` recreates it). Doctor `schema_missing_tables` (`src/commands/doctor/checks/schema-health.ts`) renders it: warn for caches (repair preview fix) and tables without user data, fail for `user_data` tables.- `src/core/persistence/rebuildable-cache.ts` — #6911 purge-side skip: `isRebuildableCache` (inventory class `rebuild`), `relationExists` (`to_regclass` on the connection's search path), and `clearRebuildableCache(tx, table)`, which returns the rows deleted or null when the cache table is absent; the existence check runs first because a 42P01 aborts a Postgres transaction. Callers: page purge (`purge.missing_caches`) and fact purge.diff --git a/docs/architecture/key-files/files-and-sync-1.md b/docs/architecture/key-files/files-and-sync-1.mdindex fdc63fc89f..5e332cbf13 100644--- a/docs/architecture/key-files/files-and-sync-1.md+++ b/docs/architecture/key-files/files-and-sync-1.md@@ -50,7 +50,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/source-resolver.ts` — 6-tier source resolution. `resolveSourceWithTier(engine, explicit, cwd)` returns `{ source_id, tier: SourceTier, detail? }` alongside `resolveSourceId()` (unchanged). `SOURCE_TIER_NAMES = ['flag', 'env', 'dotfile', 'local_path', 'sole_non_default', 'brain_default', 'seed_default']` (7 entries; order matches priority). Tier `sole_non_default` slots between `local_path` and `brain_default`: when NO `sources.default` config is set AND exactly one registered source has `local_path` AND isn't `'default'` AND the `'default'` source holds no active pages (the emptiness guard — the tier's charter is rescuing brains whose `'default'` is empty; when `'default'` carries an established corpus, auto-routing would hijack every bare write into the side-source, so the resolver falls through to `seed_default` and prints a one-line stderr notice naming both sides so the suppressed flip is diagnosable, same `GBRAIN_NO_SOLE_NON_DEFAULT_NUDGE=1` suppression knob as the routing nudge; a failed pages probe on an exotic/legacy schema keeps the auto-route), auto-route to it; archived sources excluded (try/catch for pre-v34 brains); private `pickSoleNonDefaultSource(engine)` shared by both resolver entry points so they cannot drift. Exported `formatSoleNonDefaultNudge(sourceId): string | null` builds the user-facing stderr nudge (null when `GBRAIN_NO_SOLE_NON_DEFAULT_NUDGE=1`). `resolveCliSyncSource` in `src/commands/sync/run.ts` calls `resolveSourceWithTier` unconditionally so the tier fires; `src/commands/import.ts:96-128` mirrors with the tier-gated nudge. Consumed by `gbrain sources current`, `import --source-id`, `extract --source-id`, and the `source_routing_health` doctor check. Pinned by `test/source-resolver-with-tier.test.ts` (`withEnv()` per test-isolation lint), `test/source-resolver-sole-non-default.test.ts` (20 cases incl. both-ways emptiness-guard + probe-failure fallback), `test/sync-sole-non-default-routing.test.ts` (3 PGLite cases driving real `runSync`), `test/pages-source-scoping-4329.test.ts` (real-engine both-ways guard coverage). Also exports `noGrantFederatedScope(engine, hasSourceGrant, sourceId)`, the widening decision transports share: returns `localFederatedSourceIds(..., 'seed_default')` ONLY when `hasSourceGrant === false` (the legacy-bearer no-grant floor), `undefined` for a granted token, for an OAuth client (flag `undefined` — a falsy gate here would widen every OAuth client), and when the resolver throws (best-effort; the scalar scope stands rather than failing the request). Called by `src/commands/serve-http.ts`; pinned by `test/no-grant-federated-scope.test.ts` (6 cases). `explicitReadBinding(engine, sourceId, tier)` (#5081) is the explicit-tier twin used by the stdio transport for `GBRAIN_SOURCE` (`env`) and `.gbrain-source` (`dotfile`) bindings: `{ sourceId, via, sourceIds, optedOut }`, where `sourceIds` is the same set `localFederatedSourceIds` computes (shared `federatedSetFor`, so an isolated anchor admits only itself) and `optedOut` lists `federated === false` sources for the denial hint; `undefined` for every other tier. Pinned by `test/explicit-read-admission-5081.test.ts`. Unscoped default-write guard family (the `seed_default` tier is the only one that actually lands a write in `'default'`): `assessDefaultWriteGuard(engine)` → `DefaultWriteAssessment { shouldGuard, defaultPages, nonDefaultPages, nonDefaultSources, failed? }` — an unindexed full-`pages` aggregate; `shouldGuard` when ≥1 non-default source holds pages AND non-default pages outnumber default's; a query failure returns the fail-open no-guard verdict stamped `failed: true`, which cachers/latchers must not treat as settled. `assessDefaultWriteGuardOnce(engine)` is the per-engine WeakMap memo (arms on the first SUCCESSFUL assessment whatever its verdict, forgets a failed attempt so the next caller retries, coalesces concurrent callers; `__resetDefaultWriteGuardMemo` is the test seam). `assessUnscopedDefaultWrite(engine, tier, mutating)` → `{ warning, assessed }` (`assessed: false` only when the aggregate failed); `formatDefaultWriteWarning(a, sourceFlag?)` / `formatDefaultWriteRefusal(cmd, a)` render the two surfaces; `defaultWriteAllowedByEnv()` is the `GBRAIN_ALLOW_DEFAULT_WRITE=1` escape hatch. Consumers: `sync` refuses (dry-run warns), `import` warns via the memo, MCP stdio's `createDefaultWriteAdvisory` prints once. Also exports `isResolverUserError(e)` — the ONE predicate for this module's user-facing throws (`Source "…" not found.` / `not found or is archived.`, `Invalid --source value`, `Invalid GBRAIN_SOURCE value`), consumed by dream.ts, agent.ts and code-scope.ts so a CLI command turns an unknown/archived source into a clean stderr line + exit 1 while anything else keeps propagating.- `src/core/source-delete.ts` — `deleteSourceRow`: every unmanaged source delete (`sources remove`, `sources purge`, the `sources_remove` op, expired-archive purge) deletes the `sources` row and that incarnation's `persistence_source_bindings` row in one statement; bindings have no FK to `sources`. Bindings of other incarnations are left to `gbrain repair orphan-bindings` (`src/core/persistence/orphan-bindings.ts`, doctor `orphan_persistence_bindings`). The unmanaged claim check (`sync-authority.ts`) and doctor `unbound_source` count only a binding of the source's current incarnation. `EXPIRED_ARCHIVE_SQL` is the one purge-eligibility predicate (unmanaged sweep, its per-row DELETE and the managed `expiredOnly` purge): both archive timestamps must be later than the epoch and the expiry past; `UNVERIFIED_ARCHIVE_SQL` lists archived rows with a missing or epoch timestamp, which the sweep reports blocked with restore-then-archive guidance instead of purging.-- `src/core/sources-ops.ts` — Multi-source registration + clone-lifecycle ops (`addSource`, `recloneIfMissing`, `defaultCloneDir`, `isOwnedClone`, `unownedHint`). **Reclone-ownership invariant (must-never-violate): gbrain may only delete/re-clone a clone it created, NEVER a user working tree.** `recloneIfMissing` deletes `local_path`, so it gates on `isOwnedClone(src)` and throws a `SourceOpError('unmanaged_path', ...)` BEFORE any filesystem op when ownership is unprovable — fail-closed. Ownership is proven by `config.managed_clone === true` (written by `addSource`'s `--url` path, covering default-location and `--clone-dir` clones) OR `local_path === defaultCloneDir(id)` (back-compat for pre-marker clones, via exact normalized-path equality, symlink-free). A row with `remote_url` + an unowned `local_path` (a user-registered working tree, e.g. `sources add --path`) is refused untouched; re-add with `--url` to regain auto-reclone. The reclone is EXDEV-safe: clone into a SIBLING temp of `local_path` (not the shared `clones/.tmp`, which may sit on a different mount than a `--clone-dir` target), then swap (move old aside → move new in → drop old) so `local_path` is never left missing-and-unrecoverable; on swap failure the original is restored, and if restore fails the error names the `aside` path so it's never reflexively deleted. A TOCTOU re-check re-confirms ownership immediately before the destructive move and rejects a symlink leaf swapped in after the entry check (`symlink_escape`). `unownedHint(src, state)` is the shared recovery message used by both the core error and the `gbrain sync --source` CLI error; `gbrain sources restore` special-cases `unmanaged_path` to print "DB row restored; gbrain syncs this path read-only" instead of the misleading "try sync to recover" guidance. `SourceOpErrorCode` includes `unmanaged_path`. Pinned by `test/sources-ops.test.ts`, `test/sources-resync-recovery.test.ts`. `assertNoOverlappingPath(engine, id, path)` is the ONE overlapping-path guard shared by every surface that binds a `local_path` (`addSource`, `gbrain sources set-path`): a path equal to, nested inside, or enclosing another source's `local_path` throws `SourceOpError('overlapping_path')` — overlapping trees make sync/write-through attribute files to the wrong source, so no add or repair path may skip it. The guard compares by spelling AND by realpath (both the candidate and each sibling `local_path` are `realpathSync`'d when they exist, fail-open to the spelling otherwise), so a symlink resolving into or over another source's tree cannot slip past it; the stored pointer and the error message keep the operator's spelling.+- `src/core/sources-ops.ts` — Multi-source registration + clone-lifecycle ops (`addSource`, `recloneIfMissing`, `defaultCloneDir`, `isOwnedClone`, `unownedHint`). **Reclone-ownership invariant (must-never-violate): gbrain may only delete/re-clone a clone it created, NEVER a user working tree.** `recloneIfMissing` deletes `local_path`, so it gates on `isOwnedClone(src)` and throws a `SourceOpError('unmanaged_path', ...)` BEFORE any filesystem op when ownership is unprovable — fail-closed. Ownership is proven by `config.managed_clone === true` (written by `addSource`'s `--url` path, covering default-location and `--clone-dir` clones) OR `local_path === defaultCloneDir(id)` (back-compat for pre-marker clones, via exact normalized-path equality, symlink-free). A row with `remote_url` + an unowned `local_path` (a user-registered working tree, e.g. `sources add --path`) is refused untouched; re-add with `--url` to regain auto-reclone. The reclone is EXDEV-safe: clone into a SIBLING temp of `local_path` (not the shared `clones/.tmp`, which may sit on a different mount than a `--clone-dir` target), then swap (move old aside → move new in → drop old) so `local_path` is never left missing-and-unrecoverable; on swap failure the original is restored, and if restore fails the error names the `aside` path so it's never reflexively deleted. A TOCTOU re-check re-confirms ownership immediately before the destructive move and rejects a symlink leaf swapped in after the entry check (`symlink_escape`). `unownedHint(src, state)` is the shared recovery message used by both the core error and the `gbrain sync --source` CLI error; `gbrain sources restore` special-cases `unmanaged_path` to print "DB row restored; gbrain syncs this path read-only" instead of the misleading "try sync to recover" guidance. `SourceOpErrorCode` includes `unmanaged_path`. Pinned by `test/sources-ops.test.ts`, `test/sources-resync-recovery.test.ts`. `assertNoOverlappingPath(engine, id, path)` is the ONE overlapping-path guard shared by every surface that binds a `local_path` (`addSource`, `gbrain sources set-path`): a path equal to, nested inside, or enclosing another source's `local_path` throws `SourceOpError('overlapping_path')` — overlapping trees make sync/write-through attribute files to the wrong source, so no add or repair path may skip it. The guard compares by spelling AND by realpath (both the candidate and each sibling `local_path` are `realpathSync`'d when they exist, fail-open to the spelling otherwise), so a symlink resolving into or over another source's tree cannot slip past it; the stored pointer and the error message keep the operator's spelling. #6946: `isOwnedClone`/`defaultCloneDir` live in `src/core/url-clone.ts`, re-exported here.- `src/core/sync-concurrency.ts` — single source of truth for the parallel-sync policy. Exports `autoConcurrency(engine, fileCount, override?)` (PGLite always serial; explicit override clamped to >=1; auto path returns `DEFAULT_PARALLEL_WORKERS=4` when `fileCount > AUTO_CONCURRENCY_FILE_THRESHOLD=100`), `shouldRunParallel(workers, fileCount, explicit)` (explicit `--workers` bypasses the >50-file floor), and `parseWorkers(s)` (rejects `'0'`, `'-3'`, `'foo'`, `'1.5'`, trailing chars). Used by `performSync`, `performFullSync`, `runImport`, and the Minion `sync` handler so the sites can't drift. `DEFAULT_PARALLEL_SOURCES = 4` is a SEPARATE constant for the per-source fan-out under `gbrain sync --all` — kept distinct from `DEFAULT_PARALLEL_WORKERS` because total live Postgres connections per wave ≈ `DEFAULT_PARALLEL_SOURCES × DEFAULT_PARALLEL_WORKERS × 2 (per-file pool)` = 32 at both defaults (each per-file worker opens its own `PostgresEngine` with `poolSize = min(2, resolvePoolSize(2))`); `sync.ts` warns when `parallel × workers × 2 > 16`. `resolveWorkersWithClamp(engine, override, commandName, fileCount)` wraps `autoConcurrency` with a per-command stderr clamp warning on PGLite (per-(command, requested) dedup via module-scoped warned-once set with `_resetWorkersClampWarningsForTest()` seam) and is the canonical surface for every bulk-command `--workers N` flag (extract-conversation-facts, extract, edges-backfill, reindex-multimodal, reindex, reindex-code); embed.ts deliberately bypasses it and keeps `GBRAIN_EMBED_CONCURRENCY || 20`. `resolveMaxConnections()` (reads `GBRAIN_MAX_CONNECTIONS`, undefined when unset) + `clampWorkersForConnectionBudget(workers, perWorkerPool, maxConnections, parentPool)` back the opt-in single-sync connection-footprint clamp so a big sync stays under a low pooler cap (`parent_pool + workers×perWorkerPool ≤ budget`); `gbrain doctor`'s `pool_budget` check (`computePoolBudgetCheck` / `checkPoolBudget` in `src/commands/doctor/checks/consolidation-cycle.ts`, re-exported by `src/commands/doctor.ts`) warns when the budget leaves no room for a worker, pointing at `GBRAIN_POOL_SIZE=2`. Pinned by `test/pglite-workers-clamp.test.ts`.diff --git a/docs/architecture/key-files/files-and-sync-2.md b/docs/architecture/key-files/files-and-sync-2.mdindex 2e8a7a4958..f4f9d05607 100644--- a/docs/architecture/key-files/files-and-sync-2.md+++ b/docs/architecture/key-files/files-and-sync-2.md@@ -19,4 +19,5 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/persistence/sync-image.ts` — #6529: managed sync's image branch. With multimodal embedding on, `freezeEntry` (`sync-run.ts`) freezes an image entry as its bytes in base64 (`frozenImageIntent`; `rawHash` stays the file sha256, so the working-tree check and the hash no-op are unchanged) and `prepareManagedSyncMutation` (`sync-prepare.ts`) hands it to `prepareManagedSyncImage`, which runs `importImageFile` with `prepare` (the coordinated path `gbrain import` uses in `import-prepare.ts`): the importer decides the hash no-op, OCRs and embeds the image at preparation inside the sync budget (`--no-embed` skips both; the caption chunk's text vector is deferred to `embed --stale`), and the apply records `source_path`, releases the path's hold and re-reads the snapshot. A company plan refuses (`profile_incompatible`), a screening preparation (`sameContentAtOrigin`, the no-op waiver in `sync-waivers.ts` and `unchangedManagedImport` in `import-mutations.ts` return early for images) is refused rather than paid for, newer working-tree bytes or a vanished file refuse `source_changed`, and a Git rename publishes the new slug and soft-deletes the old page. `import-file.ts` records `source_path` on the legacy importer's hash-skip path too (`refreshSourcePath`), so no image import leaves it NULL. Tests: `test/managed-sync-images-5493.test.ts` (both engines), `test/embed-stale-images-managed-6529.test.ts`.- `src/core/persistence/sync-streamed.ts` — Wave B PR 2: managed sync of a Markdown file over the 24 MiB single-string ceiling. With `pages.segmented_storage` on, `freezeEntry` (`sync-run.ts`) freezes such a file by reference instead of holding it by its size: `streamedSyncBodyRef` hashes the sha256 and the Git blob id as a stream (sha1 or sha256 by the pinned commit's length) into `intent.body_ref` (`git_blob`, or `input_file` for an uncommitted working-tree file); the journal carries no content, and a committed entry whose working tree does not hold its pinned blob, a file over `pages.max_bytes` or a non-Markdown file is held as before. `prepareManagedSyncMutation` (`sync-prepare.ts`) hands it to `prepareManagedSyncStreamed`, which streams it through `importStreamedMarkdownFile` (`page-body/streamed-import.ts`, `coordinated`; `moved` on a rename keeps an implicit type following the new path) and publishes database-only; a rename moves the page first and re-seals an unchanged body (`sealSegmentedPage`). A file the streamed path refuses (a facts fence) fails its request with the refusal's code and the run holds it (`streamedRefusalHold` in `sync-screen.ts`); a dry run lists it in `screen_skipped` as `page_body_segmented`; `groupableIntent` (`sync-group.ts`) keeps it out of bulk groups. Tests: `test/large-pages/managed-sync-streamed.test.ts` (both engines), `managed-sync-streamed-crash.test.ts` (owner killed at `consumer:prepared`), `managed-sync-streamed-memory.slow.test.ts` (VmHWM).-- `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.+- `src/core/url-clone.ts` — gbrain-owned `sources add --url` clones (#6946, GBRA-130 C-2). `isOwnedClone` (config `managed_clone` or a `local_path` under the default clone dir) and `defaultCloneDir`; `urlCloneReadOnly` is the one predicate (owned clone on a brain without managed persistence) the fence writer (`fence-write.ts`, `databaseOnlyReason: 'url_clone'`), write-through (`skipped: 'url_clone'`), timeline write-through, unfenced-facts adoption, the empty-fence guard and `sourceMirrorReadOnly` consult, so nothing gbrain writes lands in a checkout it updates with `git pull --ff-only`. `urlClonePullBlock` reads the tracked changes of a clone whose pull failed and returns `pull_blocked_local_changes` with an `ask_user` fix naming the preview `gbrain repair url-clone-fences --source <id>`; `formatUrlClonePullBlock` renders it for sync's stderr (`sync/preflight.ts`) and `cycle.ts` puts it in the sync phase detail as `pull_blocked`. Test: `test/pathological/c2-url-clone-fences.test.ts`.+- `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. #6946: on a gbrain-owned `--url` clone of an unmanaged brain (`urlCloneReadOnly`), `writePageThrough` returns `skipped: 'url_clone'` and `deletePageThrough` returns `removed: false, skipped: 'url_clone'`; `timeline-write-through.ts` skips the same way.diff --git a/docs/architecture/key-files/google-and-loops-continued.md b/docs/architecture/key-files/google-and-loops-continued.mdindex af3a41a736..22be322e9c 100644--- a/docs/architecture/key-files/google-and-loops-continued.md+++ b/docs/architecture/key-files/google-and-loops-continued.md@@ -24,8 +24,8 @@- `src/core/facts/withdrawal-overlay.ts` — pure legacy-fence enumeration and withdrawal rendering shared by coherent snapshots, stale imports and physical forget mirrors. The shared snapshot overlay and import pre-publication validator recognize canonical prefixed/inline markers and distinguish malformed live segments. Discovery refuses matching ambiguous claims before mutation. `partialFenceRuns` finds the fence runs a forced segment cut splits. Fingerprints match independently in each fence, including inactive history, against both the folded (v174) and exact legacy hashes; parser-recognized markers precede preserved evidence context and earlier expiry remains intact. Regression: `test/withdrawal-overlay-concurrency.test.ts` on both engines.- **`src/commands/sync-persistence-delegate.ts` + `src/core/persistence/{sync-wire,sync-administration}.ts`** — pre-connect authenticated CLI sync ingress for any resident PGLite owner, including stdio MCP. The CLI JSON renderer shares the direct sync envelope. Strict options preserve source/brain selection and filtering; only current CLI credentials can advance bounded durable cursor slices. Unactivated delegation also forces import-only work and queues the owner embed drain, preserving the inline cost gate; backlogs are per-engine source sets and shutdown waits for actual provider settlement before releasing datastore ownership; the real serve E2E observes a committed receipt before SIGKILL and proves same-ID cursor recovery without breaking locks. The env and default deadlines stay progress-aware across slices (`DelegatedSyncDeadline`): past the deadline the client keeps re-entering while a slice advanced the managed cursor within one progress window, and each slice gets at least one window; `--timeout` and `--hard-deadline` stay strict. Legacy shared-secret sync refuses managed brains. `test/persistence-sync-stdio-owner.test.ts` starts a real stdio owner and exercises CLI import/read/admin, remote-lane denial and revocation without a competing datastore open. #6712 PR 1: the wire still validates an older CLI's `explicitProcessing` list by shape, then ignores it (`WIRE_SKEW_WINDOWS.explicitProcessing` in `src/core/wire-skew.ts`, floor 0.60.255.0, accepted until 2026-11-14); the cursor's opt-outs are inherited (`test/sync-owner-lane-processing-6696.test.ts`). #6712 PR 2: the owner lane's flag tables are views of `SYNC_FLAGS` (`src/core/sync-flags.ts`); `--lanes N`/`--no-lanes` are accepted and not sent, and a dropped retired field prints `retiredWireNotice`.-- `src/core/facts/backstop.ts` + `src/core/entities/resolve-on-save.ts` — saved facts retain their content and provenance but use a NULL entity target when resolution falls back to slugification. Legacy extraction uses the shared exact source/entity/visibility fingerprint decision before identity-gated cosine candidates, so old facts without vector provenance still deduplicate identical text without relabeling their vectors. The conversation save caller also clears the target on ordinary resolution errors, preserves diagnostic counters, and propagates abort/budget failures. It never treats an invented slug as a verified page. #5836: `src/core/facts/subject-infer-write.ts` `inferMissingSubjects` links facts with no or fallback-only entity via `inferFactSubject` (remote callers: written page only, readable pages, caller fences, managed grant), never on the unmanaged DB-only branch, marks `entity_inferred` (context note; exact-text dedup only in both writers); `test/facts-backstop-entity-inference.test.ts`, `test/managed-facts-entity-inference.test.ts`. #6159: every writer (both backstop buckets, the fence writes and `persistence/facts-maintenance.ts`) dates a fact with `facts/event-time.ts` `factEventTime` (extractor date, then `validFrom`, then `turnAt`, then now) and the extraction prompt's observation date falls back to `turnAt`; the sweep's corpus pass sets `turnAt` from the session file's write time, vetted by `context/corpus-windows.ts` `corpusFactTime` (finite, from 2000, at most 60 s ahead; otherwise logged and dated at extraction) (`test/sweep-corpus-fact-time.test.ts`). #6113: `resolveManagedFactsEmbedding` (`persistence/facts-maintenance.ts`) reads the brain's DB-plane model only; a legacy row without a provider refuses `embedding_configuration` naming `gbrain migrate embeddings --to <gateway provider>:<model> --dry-run` (the read-only preview; applying it needs paid authorization). Test: `test/facts-embedding-bare-model.serial.test.ts`. The notability-filter vocabulary (`NOTABILITY_FILTERS`, `coerceNotabilityFilter`) lives in import-light `src/core/facts/notability-filter.ts` (re-exported here) beside the page-write key resolver. The unmanaged pipeline counts entity groups held on a facts fence that does not parse cleanly as `fence_refused` (nothing written for them). Large pages A7: the page entry (`runPipeline`) plans with the `facts_backstop` watermark (`src/core/extraction-watermark.ts`, cap `MAX_TURN_TEXT_CHARS`): past a matching watermark the extractor reads only the appended text (`PipelineInput.extractText`; `turnText` stays the full body, which the managed preparer compares with the page), an unchanged long page makes no model call, and a head or tail-window read returns `input_truncated` on the inline result; the plan commits after an extraction that neither failed nor aborted. Test: `test/extraction-watermark-facts.test.ts`.-- `src/commands/migrations/v0_32_2.ts` + `src/core/facts/unfenced-facts.ts` — Phase B is the shared core pass `planUnfencedFacts` / `fenceUnfencedFacts`, which the `extract_facts` cycle phase also runs on every cycle (#5299). It fences live unfenced facts (`row_num IS NULL`) only onto an existing source-scoped page, and never ontology observations (`dimension IS NOT NULL`, #6264: they belong to the ontology, keyed by their own provenance) and its recorded canonical file; a managed brain publishes each page as one coordinator `managed_maintenance_adopt_fact_fence` request (database-only pages included; a read-only pre-pass of `planManagedPage` counts the pages that will submit for the up-front lifetime-ID check, so suppressed or unadoptable pages never refuse the step, and the submit loop replans each page right before it submits; `test/fact-fence-adoption-exits.test.ts`), and an unmanaged page is written under the source filesystem lock and page lock (`.tmp` + parse + rename), mirrored into `pages` and stamped in one maintenance transaction, and committed when the checkout is durability-hardened. Missing pages/files are counted as `skipped_no_page` (a recorded canonical file absent on this host is also listed in `missing_files`), never materialized as stubs. #6610: an unmanaged database-only page (no `source_path`/`source_uri`, no file at its slug path) is fenced in its database body through the coordinator (`fenceDatabaseOnlyPage`, no file target) when `resolveFactWriteTarget` makes the write database-only; an unbound source without `persistence.unbound_write=database_only` leaves its rows in `unbound_refused`, which `extract_facts` holds out of reconciliation without gating and doctor `fence_integrity` reports as `unbound_legacy_facts` with the opt-in (`ask_user`). The migration adds a dirty-tree refusal that stays inside the source subdirectory; fence row allocation respects both database-owned row numbers and the parsed fence, preserving idempotent recovery without collisions. Dry runs use the same eligibility checks, and historical drift remains visible rather than silently repaired. #6278: `planFence` uses the fence codec as the oracle (`adoptableClaim`): a legacy row adopts only when `parseFactsFence(renderFactsTable([row]))` hands its claim back active and non-empty with the same kind, visibility, validity and source, differing from the stored text by whitespace and line endings alone (trim, CRLF/CR to LF, NBSP), and the parsed text is written into `facts.fact` with the row number on both the managed and the unmanaged path, so the projection keeps the row's id, vectors and provenance. A row the codec would change further (whitespace-only, `~~x~~`, a literal `<br>`) or a second row whose normalized claim, source and visibility the page already carries stays a legacy row exactly as it is, recorded as an `UnadoptableFactRecord` (source, page, fact id, reason class; never the claim text) and named in `failed_pages` as `FACTS_FENCE_FAILED: <slug> (fence_unrenderable: N row(s), <class>)` in the cycle and the migration output; the page's other rows still adopt. Tests: `test/facts-fence-adoption-roundtrip.test.ts`, `test/extract-facts-unfenced-rows.test.ts`, `test/migrations-v0_32_2-managed.test.ts`.+- `src/core/facts/backstop.ts` + `src/core/entities/resolve-on-save.ts` — saved facts retain their content and provenance but use a NULL entity target when resolution falls back to slugification. Legacy extraction uses the shared exact source/entity/visibility fingerprint decision before identity-gated cosine candidates, so old facts without vector provenance still deduplicate identical text without relabeling their vectors. The conversation save caller also clears the target on ordinary resolution errors, preserves diagnostic counters, and propagates abort/budget failures. It never treats an invented slug as a verified page. #5836: `src/core/facts/subject-infer-write.ts` `inferMissingSubjects` links facts with no or fallback-only entity via `inferFactSubject` (remote callers: written page only, readable pages, caller fences, managed grant), never on the unmanaged DB-only branch, marks `entity_inferred` (context note; exact-text dedup only in both writers); `test/facts-backstop-entity-inference.test.ts`, `test/managed-facts-entity-inference.test.ts`. #6159: every writer (both backstop buckets, the fence writes and `persistence/facts-maintenance.ts`) dates a fact with `facts/event-time.ts` `factEventTime` (extractor date, then `validFrom`, then `turnAt`, then now) and the extraction prompt's observation date falls back to `turnAt`; the sweep's corpus pass sets `turnAt` from the session file's write time, vetted by `context/corpus-windows.ts` `corpusFactTime` (finite, from 2000, at most 60 s ahead; otherwise logged and dated at extraction) (`test/sweep-corpus-fact-time.test.ts`). #6113: `resolveManagedFactsEmbedding` (`persistence/facts-maintenance.ts`) reads the brain's DB-plane model only; a legacy row without a provider refuses `embedding_configuration` naming `gbrain migrate embeddings --to <gateway provider>:<model> --dry-run` (the read-only preview; applying it needs paid authorization). Test: `test/facts-embedding-bare-model.serial.test.ts`. The notability-filter vocabulary (`NOTABILITY_FILTERS`, `coerceNotabilityFilter`) lives in import-light `src/core/facts/notability-filter.ts` (re-exported here) beside the page-write key resolver. The unmanaged pipeline counts entity groups held on a facts fence that does not parse cleanly as `fence_refused` (nothing written for them). Large pages A7: the page entry (`runPipeline`) plans with the `facts_backstop` watermark (`src/core/extraction-watermark.ts`, cap `MAX_TURN_TEXT_CHARS`): past a matching watermark the extractor reads only the appended text (`PipelineInput.extractText`; `turnText` stays the full body, which the managed preparer compares with the page), an unchanged long page makes no model call, and a head or tail-window read returns `input_truncated` on the inline result; the plan commits after an extraction that neither failed nor aborted. Test: `test/extraction-watermark-facts.test.ts`. #6946: `fence-write.ts` returns `legacyFallback: true, databaseOnlyReason: 'url_clone'` for a gbrain-owned `--url` clone on an unmanaged brain, and the backstop does not warn `facts:fence-write-unexpected-fallback` for it.+- `src/commands/migrations/v0_32_2.ts` + `src/core/facts/unfenced-facts.ts` — Phase B is the shared core pass `planUnfencedFacts` / `fenceUnfencedFacts`, which the `extract_facts` cycle phase also runs on every cycle (#5299). It fences live unfenced facts (`row_num IS NULL`) only onto an existing source-scoped page, and never ontology observations (`dimension IS NOT NULL`, #6264: they belong to the ontology, keyed by their own provenance) and its recorded canonical file; a managed brain publishes each page as one coordinator `managed_maintenance_adopt_fact_fence` request (database-only pages included; a read-only pre-pass of `planManagedPage` counts the pages that will submit for the up-front lifetime-ID check, so suppressed or unadoptable pages never refuse the step, and the submit loop replans each page right before it submits; `test/fact-fence-adoption-exits.test.ts`), and an unmanaged page is written under the source filesystem lock and page lock (`.tmp` + parse + rename), mirrored into `pages` and stamped in one maintenance transaction, and committed when the checkout is durability-hardened. Missing pages/files are counted as `skipped_no_page` (a recorded canonical file absent on this host is also listed in `missing_files`), never materialized as stubs. #6610: an unmanaged database-only page (no `source_path`/`source_uri`, no file at its slug path) is fenced in its database body through the coordinator (`fenceDatabaseOnlyPage`, no file target) when `resolveFactWriteTarget` makes the write database-only; an unbound source without `persistence.unbound_write=database_only` leaves its rows in `unbound_refused`, which `extract_facts` holds out of reconciliation without gating and doctor `fence_integrity` reports as `unbound_legacy_facts` with the opt-in (`ask_user`). The migration adds a dirty-tree refusal that stays inside the source subdirectory; fence row allocation respects both database-owned row numbers and the parsed fence, preserving idempotent recovery without collisions. Dry runs use the same eligibility checks, and historical drift remains visible rather than silently repaired. #6278: `planFence` uses the fence codec as the oracle (`adoptableClaim`): a legacy row adopts only when `parseFactsFence(renderFactsTable([row]))` hands its claim back active and non-empty with the same kind, visibility, validity and source, differing from the stored text by whitespace and line endings alone (trim, CRLF/CR to LF, NBSP), and the parsed text is written into `facts.fact` with the row number on both the managed and the unmanaged path, so the projection keeps the row's id, vectors and provenance. A row the codec would change further (whitespace-only, `~~x~~`, a literal `<br>`) or a second row whose normalized claim, source and visibility the page already carries stays a legacy row exactly as it is, recorded as an `UnadoptableFactRecord` (source, page, fact id, reason class; never the claim text) and named in `failed_pages` as `FACTS_FENCE_FAILED: <slug> (fence_unrenderable: N row(s), <class>)` in the cycle and the migration output; the page's other rows still adopt. Tests: `test/facts-fence-adoption-roundtrip.test.ts`, `test/extract-facts-unfenced-rows.test.ts`, `test/migrations-v0_32_2-managed.test.ts`. #6946: a gbrain-owned `--url` clone on an unmanaged brain is never fenced (`skipped_url_clone`); its rows stay database-only.- `src/core/google/loop-catchup.ts` — open-loop recovery passes the Gmail sweep runs (#5867, #5868). Grace holds: `recordGraceVerdict` keeps each thread `detectThreadLoop` grace-held (and `loopExtractionEligibility` passes) in connector state `loop_grace_holds` (cap `GRACE_HOLDS_CAP` 2,000, oldest pruned and logged; prose sanitized for jsonb), separate from connector item holds, so `connector_held_items` and `waiting` coverage never count them. `settleDueGraceHolds` opens a due hold from its stored spec when the page still carries the newest message id it was computed from (no Gmail read), otherwise re-fetches through `processThread` (at most `GRACE_REFETCH_PER_SWEEP` 100 per sweep; a 404 drops the hold, a failure keeps it due). `seedGraceBackfill` seeds holds once for email pages active in the last 14 days with no open deterministic loop, from stored pages only; the sweep sets `loop_grace_backfill_done` after a non-aborted sweep. Catch-up (managed sources only): `runLoopsCatchup` re-candidates email pages whose newest message is in the last 30 days; a page is settled by a revision-bound outcome (`recordLoopsExtractOutcome`, written by the `loops_extract` handler into `op_checkpoints` op `loops-extract-outcomes`, one statement, pruned past the window), not by job completion. It skips pages this sweep or a pending sweep job already queues, checks eligibility on the live thread, enqueues under its own key `loops-catchup:<source>:<slug>:<rev>` inside the waiting-depth ceiling, retries a dead-lettered job once (`:retry`) then settles it, honors the kill switch and chat availability, and sets `loops_catchup.done` only when every candidate is settled. `seedLoopRechecks` (#5012) seeds spec-less due holds for unmute re-checks and once for the newest thread of the top 500 senders with open reply-owed loops; `recordWithheldVerdict` keeps `loop_withheld_senders` (cap 2,000). Tests: `test/google-loops-recovery.serial.test.ts` (+ Postgres twin).- `src/core/cycle/connector-extract.ts` — the extract phase of a cycle with no on-disk checkout (connector sources, Postgres brains without `--dir`; #5875): `runPhaseExtractDatabaseOnly` runs the bounded, source-scoped `extractStaleFromDB` drain (`CYCLE_STALE_DRAIN_BUDGET_MS`; brain-wide when the cycle has no source id; managed brains route to `extractManagedStaleLinks`) and reports `extract: ok` with `database_only: true` and the stale counters, or `warn` naming the first failed page, its code and fix (`staleDrainFailures`, shared with `cycle.ts`); a dry run reports `skipped`. Tests: `test/connector-cycle-extract.test.ts` (+ Postgres twin), no `runCycle` mock.diff --git a/test/pathological/c2-url-clone-fences.test.ts b/test/pathological/c2-url-clone-fences.test.tsnew file mode 100644index 0000000000..7cd71a7136--- /dev/null+++ b/test/pathological/c2-url-clone-fences.test.ts@@ -0,0 +1,284 @@+/**+ * C-2 (GBRA-130, #6946): gbrain never writes into a `gbrain sources add --url`+ * clone it pulls with `git pull --ff-only`, and a clone an older release+ * dirtied has an exit.+ *+ * Protects: on an unmanaged brain, a fact about a page of a gbrain-owned clone+ * stays database-only (recallable, `row_num` NULL) instead of landing in a+ * `## Facts` fence in the clone, and a page write-through skips the clone, so+ * the next upstream change to that file still fast-forwards. A clone an older+ * release already dirtied makes sync print the typed refusal+ * `pull_blocked_local_changes` (ask_user, naming the preview-first repair), and+ * `gbrain repair url-clone-fences` proves per file that the diff against HEAD+ * is only appended fence rows, backs the file up, moves those rows+ * database-only (the database side commits first), restores the file from+ * HEAD and leaves a file with any other edit untouched and named. A run-scoped+ * failure in the database step stops the repair before any file is restored.+ * Fails when: the fence writer or write-through writes into an owned clone,+ * the pull failure stays an untyped "Fix the pull", or the repair restores a+ * file whose diff it did not prove, restores before the database side+ * commits, or loses a fact row.+ * Seams: `sources add --url` accepts https:// only, so the clone is a plain+ * `git clone` of a local upstream registered with the row `addSource` writes+ * (`managed_clone: true`, `remote_url` = the clone's origin) and pulled under+ * GBRAIN_GIT_ALLOW_FILE_TRANSPORT=1. The pre-fix dirty state comes from the+ * real fence writer while the row's ownership marker is lifted, then restored.+ * Run-scoped errors come from an engine wrapper. PGLite always, Postgres when+ * DATABASE_URL is set.+ */+import { describe, expect, test } from 'bun:test';+import { execFileSync } from 'node:child_process';+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import type { BrainEngine } from '../../src/core/engine.ts';+import { gbrainPath, type GBrainConfig } from '../../src/core/config.ts';+import { operations, type OperationContext } from '../../src/core/operations.ts';+import { writeSingleFact } from '../../src/core/facts/write-single.ts';+import { FACTS_FENCE_BEGIN } from '../../src/core/facts-fence.ts';+import { writePageThrough, _resetWriteThroughCacheForTest } from '../../src/core/write-through.ts';+import { resolveRepairScope, type RepairKind, type RepairResult } from '../../src/core/repair/core.ts';+import { repairRunner } from '../../src/core/repair/registry.ts';+import { isolatedSharedSkillsEngine } from '../helpers/shared-skills-engine.ts';+import { withEnv } from '../helpers/with-env.ts';+import { expectItemFailure, expectOthersUnchanged, expectUnitNotAborted, pathologicalArms, runScopedErrors, snapshotItems } from './harness.ts';++const SOURCE = 'acme-docs';+const ALICE = 'people/alice-example';+const BOB = 'people/bob-example';+const NOTE = 'notes/acme-example';+const KIND = 'url-clone-fences' as RepairKind;+const ALICE_FACT = 'Alice Example leads the platform team at Acme Example.';+const BOB_FACT = 'Bob Example runs the Acme Example design studio.';++const personMd = (title: string, body: string) => `---\ntype: person\ntitle: ${title}\n---\n\n# ${title}\n\n${body}\n`;+const git = (dir: string, args: string[]) => execFileSync('git', ['-C', dir, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] });++type SyncResult = Awaited<ReturnType<typeof import('../../src/commands/sync.ts').performSync>>;+interface FactRow { id: number; row_num: number | null; expired: boolean; fact: string }+interface Clone {+ engine: BrainEngine;+ root: string;+ /** `git status` of tracked files in the clone ('' when clean). */+ dirty(): string;+ /** Commit a change to `rel` upstream. */+ push(rel: string, content: string): void;+ /** Sync the clone source (pull enabled), with stderr captured. */+ sync(): Promise<{ result: SyncResult; stderr: string }>;+ /** A fact about `slug` written by the real fence writer as an older release did (ownership marker lifted for the write). */+ legacyFence(slug: string, fact: string): Promise<number>;+ facts(slug: string): Promise<FactRow[]>;+}++async function withClone(databaseUrl: string | undefined, run: (c: Clone) => Promise<void>): Promise<void> {+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-c2-'));+ try {+ await withEnv({ GBRAIN_HOME: join(dir, 'home'), GBRAIN_GIT_ALLOW_FILE_TRANSPORT: '1', DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined }, async () => {+ _resetWriteThroughCacheForTest();+ const upstream = join(dir, 'upstream');+ mkdirSync(join(upstream, 'people'), { recursive: true });+ mkdirSync(join(upstream, 'notes'), { recursive: true });+ git(upstream, ['init', '-q', '-b', 'main']);+ git(upstream, ['config', 'user.email', '[email protected]']);+ git(upstream, ['config', 'user.name', 't']);+ writeFileSync(join(upstream, `${ALICE}.md`), personMd('Alice Example', 'Alice Example works at Acme Example.'));+ writeFileSync(join(upstream, `${BOB}.md`), personMd('Bob Example', 'Bob Example works at Acme Example.'));+ writeFileSync(join(upstream, `${NOTE}.md`), '---\ntype: note\ntitle: Acme Example\n---\n\n# Acme Example\n\nA company note.\n');+ git(upstream, ['add', '-A']);+ git(upstream, ['commit', '-q', '-m', 'initial']);+ const root = join(dir, 'clones', SOURCE);+ execFileSync('git', ['clone', '-q', `file://${upstream}`, root], { stdio: 'pipe' });+ const { engine, close } = await isolatedSharedSkillsEngine(databaseUrl);+ const config = { remote_url: `file://${upstream}`, managed_clone: true };+ const setConfig = (value: Record<string, unknown>) => engine.executeRaw('UPDATE sources SET config = $1::text::jsonb WHERE id = $2', [JSON.stringify(value), SOURCE]);+ try {+ await engine.executeRaw('INSERT INTO sources (id, name, local_path, config) VALUES ($1, $1, $2, $3::text::jsonb)', [SOURCE, root, JSON.stringify(config)]);+ const c: Clone = {+ engine, root,+ dirty: () => git(root, ['status', '--porcelain', '--untracked-files=no']).trim(),+ push(rel, content) { writeFileSync(join(upstream, rel), content); git(upstream, ['commit', '-q', '-am', `edit ${rel}`]); },+ async sync() {+ const { performSync } = await import('../../src/commands/sync.ts');+ const lines: string[] = [];+ const origError = console.error;+ const origWrite = process.stderr.write.bind(process.stderr);+ console.error = (...args: unknown[]) => { lines.push(args.map(String).join(' ')); };+ (process.stderr as unknown as { write: (chunk: unknown) => boolean }).write = (chunk: unknown) => { lines.push(String(chunk)); return true; };+ try {+ return { result: await performSync(engine, { sourceId: SOURCE, repoPath: root, noEmbed: true, noExtract: true }), stderr: lines.join('\n') };+ } finally {+ console.error = origError;+ process.stderr.write = origWrite;+ }+ },+ async legacyFence(slug, fact) {+ await setConfig({ remote_url: config.remote_url });+ try {+ return (await writeSingleFact(engine, SOURCE, { fact, provenance: 'test:c2', entity: slug, visibility: 'world', remote: false })).id;+ } finally { await setConfig(config); }+ },+ async facts(slug) {+ const rows = await engine.executeRaw<FactRow>(+ 'SELECT id, row_num, expired_at IS NOT NULL AS expired, fact FROM facts WHERE source_id = $1 AND entity_slug = $2 ORDER BY id', [SOURCE, slug]);+ return rows.map(r => ({ id: Number(r.id), row_num: r.row_num === null ? null : Number(r.row_num), expired: r.expired, fact: r.fact }));+ },+ };+ expect((await c.sync()).result.status).toBe('first_sync');+ await run(c);+ } finally { await close(); }+ });+ } finally { rmSync(dir, { recursive: true, force: true }); }+}++const repair = async (engine: BrainEngine, opts: { apply: boolean; expect?: string }): Promise<RepairResult> => {+ const scope = await resolveRepairScope(engine, SOURCE);+ return (await repairRunner(engine, { apply: opts.apply, logger: { info() {}, warn() {}, error() {} } as never }))+ .run(KIND, scope, { explicit: true, sourceFlag: SOURCE, ...(opts.expect ? { expect: opts.expect } : {}) });+};+const head = (c: Clone, rel: string) => git(c.root, ['show', `HEAD:${rel}`]);+const pageBody = async (engine: BrainEngine, slug: string) =>+ (await engine.executeRaw<{ compiled_truth: string }>('SELECT compiled_truth FROM pages WHERE source_id = $1 AND slug = $2', [SOURCE, slug]))[0]?.compiled_truth ?? '';++/** The engine whose `transaction` throws `error` once `armed()` is true. */+function failingTransactions(engine: BrainEngine, error: () => unknown, armed: () => boolean): BrainEngine {+ return new Proxy(engine, {+ get(target, prop) {+ if (prop === 'transaction') return (...args: unknown[]) => armed() ? Promise.reject(error()) : (target.transaction as (...a: unknown[]) => unknown)(...args);+ const value = Reflect.get(target, prop, target);+ return typeof value === 'function' ? value.bind(target) : value;+ },+ });+}++for (const { backend, databaseUrl } of pathologicalArms()) {+ describe(`C-2 gbrain-owned --url clones (${backend})`, () => {+ test('C-2 guard: a fact about a clone page stays database-only and recallable, write-through skips the clone, and the next upstream change pulls', async () => {+ await withClone(databaseUrl, async c => {+ const before = await snapshotItems(c.engine, SOURCE);+ const written = await expectUnitNotAborted(() => writeSingleFact(c.engine, SOURCE, { fact: ALICE_FACT, provenance: 'test:c2', entity: ALICE, visibility: 'world', remote: false }));+ expect({ dirty: c.dirty() }).toEqual({ dirty: '' });+ expect(await c.facts(ALICE)).toEqual([{ id: written.id, row_num: null, expired: false, fact: ALICE_FACT }]);+ const through = await writePageThrough(c.engine, NOTE, { sourceId: SOURCE });+ expect({ written: through.written, skipped: through.skipped }).toEqual({ written: false, skipped: 'url_clone' });+ expect({ dirty: c.dirty() }).toEqual({ dirty: '' });+ c.push(`${ALICE}.md`, personMd('Alice Example', 'Alice Example works at Acme Example. UPSTREAM-EDIT-1.'));+ const synced = await c.sync();+ expect({ status: synced.result.status, reason: synced.result.reason }).toEqual({ status: 'synced', reason: undefined });+ expect(await pageBody(c.engine, ALICE)).toContain('UPSTREAM-EDIT-1');+ expect((await c.facts(ALICE)).map(f => [f.id, f.row_num, f.expired])).toEqual([[written.id, null, false]]);+ expectOthersUnchanged(before, await snapshotItems(c.engine, SOURCE), { expectProgress: [ALICE] });+ const putPage = operations.find(o => o.name === 'put_page')!;+ const ctx = { engine: c.engine, config: {} as GBrainConfig, logger: { info() {}, warn() {}, error() {} }, dryRun: false, remote: false, sourceId: SOURCE } as unknown as OperationContext;+ const put = await putPage.handler(ctx, { slug: 'notes/agent-example', content: '---\ntype: note\ntitle: Agent Example\n---\n\n# Agent Example\n\nAGENT-EDIT.\n' })+ .then(() => 'database_only', (e: { code?: string }) => e.code);+ expect({ status: git(c.root, ['status', '--porcelain']).trim(), put })+ .toEqual({ status: '', put: backend === 'pglite' ? 'database_only' : 'owner_unavailable' });+ if (put === 'database_only') expect(await pageBody(c.engine, 'notes/agent-example')).toContain('AGENT-EDIT');+ });+ }, 180_000);++ test('C-2 refusal: a clone an older release dirtied makes sync name pull_blocked_local_changes and the preview-first repair', async () => {+ await withClone(databaseUrl, async c => {+ await c.legacyFence(ALICE, ALICE_FACT);+ expect(c.dirty()).toBe(`M ${ALICE}.md`);+ c.push(`${ALICE}.md`, personMd('Alice Example', 'Alice Example works at Acme Example. UPSTREAM-EDIT-2.'));+ const blocked = await c.sync();+ expect({ status: blocked.result.status, reason: blocked.result.reason }).toEqual({ status: 'partial', reason: 'pull_failed' });+ expect({ code: blocked.stderr.includes('pull_blocked_local_changes'), fix: blocked.stderr.includes(`gbrain repair url-clone-fences --source ${SOURCE}`) })+ .toEqual({ code: true, fix: true });+ const { urlClonePullBlock } = await import('../../src/core/url-clone.ts');+ const block = await urlClonePullBlock(c.engine, SOURCE);+ expect(block).toMatchObject({ code: 'pull_blocked_local_changes', source_id: SOURCE, paths: [`${ALICE}.md`] });+ expect({ ask_user: block!.fix.ask_user, preview: block!.fix.preview_argv }).toEqual({ ask_user: true, preview: ['gbrain', 'repair', 'url-clone-fences', '--source', SOURCE] });+ const again = await c.sync();+ expect({ status: again.result.status, reason: again.result.reason }).toEqual({ status: 'partial', reason: 'pull_failed' });+ });+ }, 180_000);++ test('C-2 repair: the preview proves fence-only diffs and refuses a file with a user edit; the apply moves rows database-only, restores from HEAD, and sync pulls again', async () => {+ await withClone(databaseUrl, async c => {+ const aliceFact = await c.legacyFence(ALICE, ALICE_FACT);+ const bobFact = await c.legacyFence(BOB, BOB_FACT);+ const bobFile = join(c.root, `${BOB}.md`);+ writeFileSync(bobFile, readFileSync(bobFile, 'utf8').replace('works at Acme Example.', 'works at Acme Example. A LOCAL USER EDIT.'));+ const bobBytes = readFileSync(bobFile, 'utf8');+ const [aliceRow] = await c.facts(ALICE);+ expect(aliceRow!.row_num).not.toBeNull();+ c.push(`${ALICE}.md`, personMd('Alice Example', 'Alice Example works at Acme Example. UPSTREAM-EDIT-3.'));+ expect((await c.sync()).result.reason).toBe('pull_failed');+ const before = await snapshotItems(c.engine, SOURCE);++ const preview = await expectUnitNotAborted(() => repair(c.engine, { apply: false }));+ expect(preview.listing).toEqual([+ { item: `${SOURCE}:${ALICE}.md`, class: 'fence_rows_only', detail: expect.stringContaining('1 fence row') },+ { item: `${SOURCE}:${BOB}.md`, class: 'non_fence_edit', detail: expect.stringContaining(`gbrain repair ${KIND} --source ${SOURCE}`) },+ ]);+ expectItemFailure({ key: preview.listing![1]!.item, code: preview.listing![1]!.class, fix: preview.listing![1]!.detail },+ { key: `${SOURCE}:${BOB}.md`, code: 'non_fence_edit', fix: /gbrain repair url-clone-fences --source acme-docs/ });+ expect(preview.apply_command).toContain(`--expect ${preview.preview_hash}`);+ expect(preview.apply_command).toContain('--yes');+ expect({ dirty: c.dirty(), alice: (await c.facts(ALICE))[0]!.row_num }).toEqual({ dirty: `M ${ALICE}.md\n M ${BOB}.md`, alice: aliceRow!.row_num });++ const applied = await expectUnitNotAborted(() => repair(c.engine, { apply: true, expect: preview.preview_hash }));+ expect({ applied: applied.applied, failed: applied.failed, outcomes: applied.outcomes }).toEqual({ applied: 1, failed: [], outcomes: { restored: 1 } });+ const backup = applied.outcome_items![0]!.detail!.backup as string;+ expect(readFileSync(backup, 'utf8')).toContain(FACTS_FENCE_BEGIN);+ expect(readFileSync(join(c.root, `${ALICE}.md`), 'utf8')).toBe(head(c, `${ALICE}.md`));+ expect(c.dirty()).toBe(`M ${BOB}.md`);+ expect(readFileSync(bobFile, 'utf8')).toBe(bobBytes);+ expect(await c.facts(ALICE)).toEqual([{ id: aliceFact, row_num: null, expired: false, fact: ALICE_FACT }]);+ expect((await c.facts(BOB)).map(f => [f.id, f.row_num !== null, f.expired])).toEqual([[bobFact, true, false]]);+ expect(await pageBody(c.engine, ALICE)).not.toContain(FACTS_FENCE_BEGIN);+ expectOthersUnchanged(before, await snapshotItems(c.engine, SOURCE), { changed: [ALICE] });++ const synced = await c.sync();+ expect({ status: synced.result.status, reason: synced.result.reason }).toEqual({ status: 'synced', reason: undefined });+ expect(await pageBody(c.engine, ALICE)).toContain('UPSTREAM-EDIT-3');+ expect((await c.facts(ALICE)).map(f => [f.id, f.row_num, f.expired])).toEqual([[aliceFact, null, false]]);+ });+ }, 240_000);++ test('C-2 recovery: once the user edit is gone the file previews fence-only and clears; a file that moved since the preview is not restored', async () => {+ await withClone(databaseUrl, async c => {+ await c.legacyFence(BOB, BOB_FACT);+ const bobFile = join(c.root, `${BOB}.md`);+ const fenced = readFileSync(bobFile, 'utf8');+ writeFileSync(bobFile, fenced.replace('works at Acme Example.', 'works at Acme Example. A LOCAL USER EDIT.'));+ expect((await repair(c.engine, { apply: false })).listing!.map(l => l.class)).toEqual(['non_fence_edit']);+ writeFileSync(bobFile, fenced);+ const preview = await repair(c.engine, { apply: false });+ expect(preview.listing!.map(l => l.class)).toEqual(['fence_rows_only']);+ writeFileSync(bobFile, `${fenced}\nMOVED AFTER THE PREVIEW\n`);+ const moved = await expectUnitNotAborted(() => repair(c.engine, { apply: true, expect: preview.preview_hash }));+ expect({ applied: moved.applied, outcomes: moved.outcomes }).toEqual({ applied: 0, outcomes: { changed_since_preview: 1 } });+ expect(readFileSync(bobFile, 'utf8')).toBe(`${fenced}\nMOVED AFTER THE PREVIEW\n`);+ expect((await c.facts(BOB)).every(f => f.row_num !== null)).toBe(true);+ writeFileSync(bobFile, fenced);+ const fresh = await repair(c.engine, { apply: false });+ const cleared = await expectUnitNotAborted(() => repair(c.engine, { apply: true, expect: fresh.preview_hash }));+ expect(cleared.outcomes).toEqual({ restored: 1 });+ expect({ dirty: c.dirty(), rows: (await c.facts(BOB)).map(f => [f.row_num, f.expired]) }).toEqual({ dirty: '', rows: [[null, false]] });+ });+ }, 240_000);++ for (const { name, error } of runScopedErrors()) {+ test(`C-2 run: a run-scoped failure (${name}) in the database step stops the repair and restores nothing`, async () => {+ await withClone(databaseUrl, async c => {+ await c.legacyFence(ALICE, ALICE_FACT);+ const aliceFile = join(c.root, `${ALICE}.md`);+ const dirtyBytes = readFileSync(aliceFile, 'utf8');+ const rows = await c.facts(ALICE);+ const preview = await repair(c.engine, { apply: false });+ const before = await snapshotItems(c.engine, SOURCE);+ const failing = failingTransactions(c.engine, error, () => existsSync(gbrainPath('backups', 'url-clone-fences')));+ const run = await repair(failing, { apply: true, expect: preview.preview_hash })+ .then(result => ({ stopped: result.stopped?.reason ?? null, applied: result.applied }), (e: unknown) => ({ stopped: e instanceof Error ? 'thrown' : String(e), applied: 0 }));+ expect({ stopped: run.stopped !== null, applied: run.applied }).toEqual({ stopped: true, applied: 0 });+ expect(readFileSync(aliceFile, 'utf8')).toBe(dirtyBytes);+ expect(await c.facts(ALICE)).toEqual(rows);+ expectOthersUnchanged(before, await snapshotItems(c.engine, SOURCE));+ });+ }, 180_000);+ }+ });+}diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txtindex 6b437b9f9d..f4e70f0491 100644--- a/test/postgres-unit-arms.txt+++ b/test/postgres-unit-arms.txt@@ -235,6 +235,7 @@ test/pathological/a49-unmanaged-purge-tombstones.test.tstest/pathological/a50-unmanaged-expired-sources.test.tstest/pathological/a9-repair-core.test.tstest/pathological/b6-triage-verdict-surrogate.test.ts+test/pathological/c2-url-clone-fences.test.tstest/persistence-background-pause.test.tstest/persistence-bounded-read-session.test.tstest/persistence-capacity-forecast.test.ts