Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(facts): a quarantined page projects no facts or takes from its fences (#6259)
time-attackb71e667c8c53
diff --git a/docs/architecture/key-files/core-cycle.md b/docs/architecture/key-files/core-cycle.mdindex eb37d8b794..16cfbac9f7 100644--- a/docs/architecture/key-files/core-cycle.md+++ b/docs/architecture/key-files/core-cycle.md@@ -23,7 +23,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) are named as `FACTS_FENCE_FAILED: <slug> (<reason>)` and still skip the destructive reconcile (the empty-fence guard, `legacyRowsPending`), while 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`, `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. It is distinct from the coordinated `extract_facts` operation and durable page backstop. Tests: `test/managed-facts-writers.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) are named as `FACTS_FENCE_FAILED: <slug> (<reason>)` and still skip the destructive reconcile (the empty-fence guard, `legacyRowsPending`), while 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`, `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. It is distinct from the coordinated `extract_facts` operation and durable page backstop. Tests: `test/managed-facts-writers.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/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.md b/docs/architecture/key-files/core-persistence.mdindex df3e0608ef..1e5a8e6f65 100644--- a/docs/architecture/key-files/core-persistence.md+++ b/docs/architecture/key-files/core-persistence.md@@ -24,7 +24,7 @@ Connector ingestion, item holds and checkpoint validation continue in [Core PersAccepted output replays provider-free after restart; page/take preparers recheck original/current grants, source incarnation and revisions. Unresolved facts remain DB-only without phantom pages. Retired takes skip; semantic fact snapshots exclude derived vector/cache fields and journal quotas reject overlarge retained intent. Managed consolidation retains the explicit chronological `valid_until` writeback from the legacy consolidation phase, scoped to the accepted source/fact IDs and revalidated semantic snapshots; contradiction probes never gain supersession authority. `submitMaintenanceIntent` admits a maintenance request with its own intent kind keyed by the intent; `prepareMaintenanceMutation` also handles `managed_maintenance_phantom_merge` and `managed_maintenance_phantom_delete` (both delegated to `cycle/phantom-redirect-managed.ts`). `publishMaintenancePage` accepts an optional `eventProjection` (Life Chronicle): the event page and its depth-page timeline row commit in the same publication with the depth page key locked. Remote maintenance remains refused.- `src/core/persistence/derived-facts.ts` — database-only fact rows derived from page text (fence reconcile, conversation facts): `managedDerivedFactsPreflight` (managed check, accepting persistence, local writer, active source; before provider spend), `withDerivedFactsWrite` (one transaction holding the coordinator source capability and the page keys, like derived links), `writeDerivedFacts` (that on a managed brain, the caller's own engine call otherwise) and `replaceDerivedFactsForPage` (inside that transaction: the caller's current-page recheck, then the page's prior rows for one writer prefix are deleted and the replacement batch inserted, so a failed or raced extraction keeps the prior batch; `test/managed-facts-writers.test.ts`). No persistence request is admitted per row. Tests: `test/managed-extract-atoms.test.ts`, `test/managed-facts-backstop.test.ts`, `test/managed-maintenance.test.ts`.-- `src/core/persistence/canonical-projections.ts` — installs the facts, takes and timeline projections of a canonical page body inside its publication transaction. Rows written by the conversation fact extractor (`cli:extract-conversation-facts*`) share the page coordinate without a fence and are never expired as rows that left it (#1928 parity with the extract_facts reconcile), so republishing a conversation keeps its extracted facts until their own replay replaces them. Preparation takes the caller's prior snapshot and writer class and pins the stored timeline rows and take row numbers. Writer classes: `editing` (revision-bound `put_page`, reconcile with an approved body decision), `preserving` (`put_page` without a revision, reconcile, connectors), `file` (managed sync of file edits and managed import) and `immutable` (company-brain imports). One pure decision table (`timelineRowAction`) maps each row state (`in_body`, `drifted`, `removed`, `removed_marked`, `database_only`) to `refresh_detail`, `delete`, `keep` or `materialize`: database-only rows are materialized by `editing` and `preserving` writers and kept by the others; #6226 rows the older citation reading filed for either body are `superseded` (deleted by every writer) or, carrying their own detail, `superseded_annotated` (kept, never materialized); a materialized bullet the new body drops is deleted by `editing`/`file`, rendered again by `preserving` and kept DB-side by `immutable`. `materializeTimeline` runs during preparation, before the body is imported, digested and rendered, and appends each round-trippable row after existing bullets in date-then-id order as a marked bullet (`timeline-marker.ts`); `renderMaterializedBullet` requires render-then-extract to return exactly the tuple and normalized detail, so backlink receipts, empty or delimiter-bearing sources are kept and never rendered. `pendingTimelineRows` counts materializable and kept rows for the repair and doctor. Deletes and detail refreshes match the pinned id, tuple and detail, so rows changed after preparation are untouched. Fence refusals are typed `invalid_fence` (`fence-repair/refusal.ts`): `compileCanonicalProjections`, the validation-only entry, refuses the first defect `scanCanonicalFences` finds (repeated marker, any strict-parser warning, a row number used twice on the page) with wire `invalid_params`; a new fence row whose number belongs to a database-only take refuses as `stored_row_collision` with wire `take_row_collision`. When the prior takes fence does not parse, the page's stored `takes.row_num` count as prior canonical rows (TE1), so a row Tier 1 normalized updates its take instead of colliding. `unrecordedCanonicalTimeline` returns the body's canonical tuples with no stored row under the normalized key (managed `extract --stale` inserts only these), and `materializedHistoryRanges` locates marker lines whose hash matches the bullet after it, plus that bullet's indented detail (the dream verifier's history exemption). Tests: `test/canonical-projection-history.test.ts`, `test/timeline-materialize.test.ts` (PGLite and Postgres). A write that would drop rows held by a fence quoted in markdown code (readers project nothing from it) is refused as `invalid_fence` / `quoted_fence_rows` instead of deleting them. Pinned by `test/fence-marker-projection.test.ts`. #5969 (D3): an ordinary `put_page` / `put_pages` intent carries a `TimelineWritePolicy` (`timeline-omission.ts`) that changes only the rows the writer saw (`removed`, `removed_marked`): an explicitly empty section deletes them for every writer class; an omitted section keeps them for a local preserving writer (`materialize`) and deletes them with `drop_timeline`; maintenance, reconcile and file writers pass no policy. The pinned timeline `DELETE` returns what it removed, and the projection closure returns `{ timelineRowsRemoved: { count, earliest, latest } }` counting only `removed`/`removed_marked` rows it actually deleted (a row changed after preparation is neither deleted nor counted); `timelineRowsToRemove` judges the same set ahead of publication.+- `src/core/persistence/canonical-projections.ts` — installs the facts, takes and timeline projections of a canonical page body inside its publication transaction. Rows written by the conversation fact extractor (`cli:extract-conversation-facts*`) share the page coordinate without a fence and are never expired as rows that left it (#1928 parity with the extract_facts reconcile), so republishing a conversation keeps its extracted facts until their own replay replaces them. Preparation takes the caller's prior snapshot and writer class and pins the stored timeline rows and take row numbers. Writer classes: `editing` (revision-bound `put_page`, reconcile with an approved body decision), `preserving` (`put_page` without a revision, reconcile, connectors), `file` (managed sync of file edits and managed import) and `immutable` (company-brain imports). One pure decision table (`timelineRowAction`) maps each row state (`in_body`, `drifted`, `removed`, `removed_marked`, `database_only`) to `refresh_detail`, `delete`, `keep` or `materialize`: database-only rows are materialized by `editing` and `preserving` writers and kept by the others; #6226 rows the older citation reading filed for either body are `superseded` (deleted by every writer) or, carrying their own detail, `superseded_annotated` (kept, never materialized); a materialized bullet the new body drops is deleted by `editing`/`file`, rendered again by `preserving` and kept DB-side by `immutable`. `materializeTimeline` runs during preparation, before the body is imported, digested and rendered, and appends each round-trippable row after existing bullets in date-then-id order as a marked bullet (`timeline-marker.ts`); `renderMaterializedBullet` requires render-then-extract to return exactly the tuple and normalized detail, so backlink receipts, empty or delimiter-bearing sources are kept and never rendered. `pendingTimelineRows` counts materializable and kept rows for the repair and doctor. Deletes and detail refreshes match the pinned id, tuple and detail, so rows changed after preparation are untouched. Fence refusals are typed `invalid_fence` (`fence-repair/refusal.ts`): `compileCanonicalProjections`, the validation-only entry, refuses the first defect `scanCanonicalFences` finds (repeated marker, any strict-parser warning, a row number used twice on the page) with wire `invalid_params`; a new fence row whose number belongs to a database-only take refuses as `stored_row_collision` with wire `take_row_collision`. When the prior takes fence does not parse, the page's stored `takes.row_num` count as prior canonical rows (TE1), so a row Tier 1 normalized updates its take instead of colliding. `unrecordedCanonicalTimeline` returns the body's canonical tuples with no stored row under the normalized key (managed `extract --stale` inserts only these), and `materializedHistoryRanges` locates marker lines whose hash matches the bullet after it, plus that bullet's indented detail (the dream verifier's history exemption). Tests: `test/canonical-projection-history.test.ts`, `test/timeline-materialize.test.ts` (PGLite and Postgres). A write that would drop rows held by a fence quoted in markdown code (readers project nothing from it) is refused as `invalid_fence` / `quoted_fence_rows` instead of deleting them. Pinned by `test/fence-marker-projection.test.ts`. #5969 (D3): an ordinary `put_page` / `put_pages` intent carries a `TimelineWritePolicy` (`timeline-omission.ts`) that changes only the rows the writer saw (`removed`, `removed_marked`): an explicitly empty section deletes them for every writer class; an omitted section keeps them for a local preserving writer (`materialize`) and deletes them with `drop_timeline`; maintenance, reconcile and file writers pass no policy. The pinned timeline `DELETE` returns what it removed, and the projection closure returns `{ timelineRowsRemoved: { count, earliest, latest } }` counting only `removed`/`removed_marked` rows it actually deleted (a row changed after preparation is neither deleted nor counted); `timelineRowsToRemove` judges the same set ahead of publication. #6259: a quarantined page (gate `quarantine` marker) projects no facts or takes (timeline rows still project); rows projected before it was quarantined stay as they are.- `src/core/persistence/timeline-omission.ts` — #5969 (D3): `timelineSectionOf` reads a put_page body's Timeline section from the caller's raw content before normalization (`omitted`: no timeline sentinel and no `## Timeline`/`## History` heading outside code; `emptied`: a section with no entries; `present`). Admission (`page-mutations.ts`) records it on the intent as `timeline_section` (a caller-sent value is stripped; failed-writes replay passes the stored one through `submitPageMutation`'s `timelineSection`). `assertTimelineNotOmitted` refuses a remote omission that would delete rows with `timeline_rows_would_be_removed` (fix: `get_page include_content:true`, then the `drop_timeline: true` retry) before admission and again during preparation; `timelineWritePolicy` builds the projection policy. Successful deletes surface as the receipt's `timeline_rows_removed` advisory (`page-advisories.ts`, dates only), copied onto `put_pages` entries (`page-batch.ts`, which accepts `drop_timeline` per entry).- `src/core/persistence/admission-retry.ts` — bounded retries for database-confirmed admission transaction aborts. Each retry reuses the UUID and normalized intent, rechecks guarded authority and reserves quota only on commitment. Standalone journal admission uses 100ms lock waits within the five-second retry budget to retain queue position behind short counter transactions; backoff occurs after rollback releases the connection so counter contention leaves pool capacity for reads. Ambiguous connection/commit errors are never classified as confirmed rollback. Real counter-lock, sustained-queue progress, read-capacity and after-insert rollback tests live in `test/persistence-journal.test.ts`. Withdrawal retries wrap its whole source-exclusive transaction with its existing lock policy; `admitWriteInTransaction` never backs off inside an existing unit of work. `test/persistence-withdrawal-retry.test.ts` verifies guard release, complete rollback and bounded contention.diff --git a/src/core/cycle/extract-facts.ts b/src/core/cycle/extract-facts.tsindex 072f24036b..906d75cf6c 100644--- a/src/core/cycle/extract-facts.ts+++ b/src/core/cycle/extract-facts.ts@@ -42,6 +42,7 @@* slugs from the inline writer) are structurally unfenceable and never gate.*/+import { isQuarantined } from '../quarantine.ts';import { existsSync, readFileSync } from 'node:fs';import type { BrainEngine } from '../engine.ts';@@ -659,6 +660,8 @@ export async function runExtractFacts(return 'skipped';}revision = page.knowledge_revision ?? null;+ // #6259: a quarantined page projects no fence facts; its existing index is left as it is.+ if (isQuarantined(page.frontmatter as Record<string, unknown> | null)) return 'skipped';const body = page.compiled_truth ?? '';const parsed = parseFactsFence(body);diff --git a/src/core/cycle/extract-takes.ts b/src/core/cycle/extract-takes.tsindex c304c7c010..04726712f4 100644--- a/src/core/cycle/extract-takes.ts+++ b/src/core/cycle/extract-takes.ts@@ -24,6 +24,7 @@* v0.22.12 classifier path (extension follow-up — not blocking v0.28).*/+import { isQuarantined, QUARANTINE_KEY } from '../quarantine.ts';import { readFileSync } from 'node:fs';import { join, relative, sep } from 'node:path';import type { BrainEngine, TakeBatchInput } from '../engine.ts';@@ -196,6 +197,8 @@ export async function extractTakesFromFs(if (takes.length > 0) result.warnings.push(`TAKES_PAGE_NOT_IN_DB: slug=${slug} has takes fence but no page row; run 'gbrain sync' first`);continue;}+ // #6259: the stored page decides (the gate stamps quarantine on it); a quarantined page projects no takes.+ if ((await engine.executeRaw('SELECT 1 FROM pages WHERE id=$1 AND frontmatter ? $2', [pageId, QUARANTINE_KEY])).length) continue;await pruneRemovedTakes(engine, pageId, body, takes, warnings, dryRun);if (takes.length === 0) continue;@@ -242,6 +245,8 @@ export async function extractTakesFromDb(result.pagesScanned++;const page = await engine.getPage(slug, { sourceId: source_id });if (!page) continue;+ // #6259: a quarantined page projects no takes (its existing rows are left as they are).+ if (isQuarantined(page.frontmatter as Record<string, unknown> | null)) continue;if (coordinated) {// A page with no takes marker at all yields no prune, no upsert and no// warning; near-miss and unbalanced markers still reach the parser.diff --git a/src/core/persistence/canonical-projections.ts b/src/core/persistence/canonical-projections.tsindex 8160ded0bc..58b25020f0 100644--- a/src/core/persistence/canonical-projections.ts+++ b/src/core/persistence/canonical-projections.ts@@ -1,4 +1,5 @@import type { BrainEngine } from '../engine.ts';+import { isQuarantined } from '../quarantine.ts';import type { ParsedPage } from '../import-file.ts';import type { PageSnapshot } from '../page-state/types.ts';import { pipelined } from '../page-state/transactions.ts';@@ -338,6 +339,9 @@ function takeCollision(rows: number[], sections: Map<number, FenceSection>, slugexport async function prepareCanonicalProjections(engine: BrainEngine, page: ParsedPage, slug: string, sourceId: string,prior: PageSnapshot | null, writer: ProjectionWriter, policy?: TimelineWritePolicy): Promise<(tx: BrainEngine, pageId?: number) => Promise<CanonicalProjectionResult>> {const { factRows, takes, quoted, sections } = compileCanonicalProjections(page, slug, sourceId);+ // #6259: a page the content-quality gate hid as junk projects no facts or takes. Rows projected before it+ // was quarantined are left as they are (hiding them would need a new row state); only new projection stops.+ const projectFences = !isQuarantined(page.frontmatter);const { timeline, exactIncoming, pinned } = classifyTimeline(prior ? await storedTimeline(engine, prior.page.id) : [],page, prior?.page ?? null, slug, writer, policy);const deletions = JSON.stringify(pinned.filter(row => row.action === 'delete')@@ -360,7 +364,7 @@ export async function prepareCanonicalProjections(engine: BrainEngine, page: Parconst rows = await collisions(db, pageId);if (rows.length) throw takeCollision(rows, sections.takes, slug, sourceId);};- if (prior) await refuseCollisions(engine, prior.page.id);+ if (prior && projectFences) await refuseCollisions(engine, prior.page.id);// #5984: `pageId` is the caller's own read of the page in this transaction. The// statements are issued as pipelines; an engine call that sends more than one// statement (insertFacts, addTakesBatch) ends one, so order is kept.@@ -369,7 +373,7 @@ export async function prepareCanonicalProjections(engine: BrainEngine, page: Parif (id == null) return { timelineRowsRemoved: null };// #5969: only rows this statement actually deleted count; a row changed since preparation is left alone and uncounted.const removedDates: string[] = [];- if (quoted) await refuseQuotedFenceLoss(tx, id, quoted, takeRowsGone, factRows, slug, sourceId);+ if (quoted && projectFences) await refuseQuotedFenceLoss(tx, id, quoted, takeRowsGone, factRows, slug, sourceId);// Fact IDs in permanent receipts remain meaningful when a canonical row is// removed/replaced. Expire and detach its row position instead of deleting it.// Conversation-extractor rows share the page coordinate without a fence@@ -409,6 +413,10 @@ export async function prepareCanonicalProjections(engine: BrainEngine, page: Par() => tx.executeRaw(`UPDATE timeline_entries t SET detail=r.next FROM jsonb_to_recordset($2::text::jsonb) AS r(id integer,detail text,next text)WHERE t.page_id=$1 AND t.event_page_id IS NULL AND t.id=r.id AND t.detail=r.detail`, [id, refreshes]),];+ if (!projectFences) {+ await pipelined(tx, timelineRows);+ return { timelineRowsRemoved: removedSummary(removedDates) };+ }if (factRows.length) {await pipelined(tx, [expireFacts]);await tx.insertFacts(factRows, { source_id: sourceId }); // gbrain-allow-direct-insert: canonical fence projection shares the journal publication transactiondiff --git a/test/quarantine-fence-projection.test.ts b/test/quarantine-fence-projection.test.tsnew file mode 100644index 0000000000..a0b7275b01--- /dev/null+++ b/test/quarantine-fence-projection.test.ts@@ -0,0 +1,66 @@+/**+ * #6259 follow-up (quarantine leaks, item 3): a page the content-quality gate+ * hid as junk projects no facts or takes from its fences. The unmanaged+ * reconcilers (`runExtractFacts`, `extractTakesFromDb`, `extractTakesFromFs`)+ * skip it; rows projected before it was quarantined are left as they are.+ * The managed canonical projection is pinned in test/quarantine-override.serial.test.ts.+ */+import { afterAll, beforeAll, expect, test } from 'bun:test';+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { importFromContent } from '../src/core/import-file.ts';+import { runExtractFacts } from '../src/core/cycle/extract-facts.ts';+import { extractTakesFromDb, extractTakesFromFs } from '../src/core/cycle/extract-takes.ts';+import { isQuarantined } from '../src/core/quarantine.ts';+import { FACTS_FENCE_BEGIN as FB, FACTS_FENCE_END as FE } from '../src/core/facts-fence.ts';+import { TAKES_FENCE_BEGIN as TB, TAKES_FENCE_END as TE } from '../src/core/takes-fence.ts';+import { withEnv } from './helpers/with-env.ts';++const FH = '| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |\n|---|---|---|---|---|---|---|---|---|---|';+const TH = '| # | claim | kind | who | weight | since | source |\n|---|---|---|---|---|---|---|';+const fences = `${FB}\n${FH}\n| 1 | Example claim from the page | fact | 1.0 | world | medium | 2026-01-01 | | chat | |\n${FE}\n\n${TB}\n${TH}\n| 1 | Example take from the page | take | brain | 0.7 | 2026-01 | chat |\n${TE}`;+const JUNK = 'Scraped wall text: Cloudflare Ray ID: 8f2a. Please wait.';+const page = (title: string, lead: string) => `---\ntitle: ${title}\ntype: note\n---\n\n${lead}\n\n${fences}\n`;++let engine: PGLiteEngine;+const home = mkdtempSync(join(tmpdir(), 'gbrain-q-fences-'));+const env = { GBRAIN_HOME: home, GBRAIN_AUDIT_DIR: home, OPENAI_API_KEY: undefined, ANTHROPIC_API_KEY: undefined, VOYAGE_API_KEY: undefined };+beforeAll(async () => { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); });+afterAll(async () => { await engine.disconnect(); rmSync(home, { recursive: true, force: true }); });++const counts = async (slug: string) => {+ const [facts] = await engine.executeRaw<{ n: number }>("SELECT count(*)::int AS n FROM facts WHERE source_markdown_slug=$1 AND expired_at IS NULL", [slug]);+ const [takes] = await engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM takes k JOIN pages p ON p.id=k.page_id WHERE p.slug=$1', [slug]);+ return { facts: Number(facts!.n), takes: Number(takes!.n) };+};++test('the fence reconcilers project a clean page but skip a quarantined one', () => withEnv(env, async () => {+ await importFromContent(engine, 'notes/clean', page('Clean', 'Ordinary prose about the project.'), { noEmbed: true });+ await importFromContent(engine, 'notes/junk', page('Junk', JUNK), { noEmbed: true });+ expect(isQuarantined((await engine.getPage('notes/junk', { sourceId: 'default' }))!.frontmatter as Record<string, unknown>)).toBe(true);+ await runExtractFacts(engine, { slugs: ['notes/clean', 'notes/junk'] });+ await extractTakesFromDb(engine, { slugs: ['notes/clean', 'notes/junk'] });+ expect(await counts('notes/clean')).toEqual({ facts: 1, takes: 1 });+ expect(await counts('notes/junk')).toEqual({ facts: 0, takes: 0 });+}), 60_000);++test('a page quarantined after its fences projected keeps those rows (only new projection stops)', () => withEnv(env, async () => {+ await importFromContent(engine, 'notes/later-junk', page('Later', 'Ordinary prose first.'), { noEmbed: true });+ await runExtractFacts(engine, { slugs: ['notes/later-junk'] });+ await extractTakesFromDb(engine, { slugs: ['notes/later-junk'] });+ expect(await counts('notes/later-junk')).toEqual({ facts: 1, takes: 1 });+ await importFromContent(engine, 'notes/later-junk', page('Later', JUNK), { noEmbed: true });+ await runExtractFacts(engine, { slugs: ['notes/later-junk'] });+ await extractTakesFromDb(engine, { slugs: ['notes/later-junk'] });+ expect(await counts('notes/later-junk')).toEqual({ facts: 1, takes: 1 });+}), 60_000);++test('the file-walk takes reconciler skips a page the database holds as quarantined', () => withEnv(env, async () => {+ const repo = join(home, 'repo'); mkdirSync(join(repo, 'notes'), { recursive: true });+ writeFileSync(join(repo, 'notes', 'fs-junk.md'), page('Fs junk', JUNK));+ await importFromContent(engine, 'notes/fs-junk', page('Fs junk', JUNK), { noEmbed: true });+ await extractTakesFromFs(engine, { repoPath: repo, slugs: ['notes/fs-junk'] });+ expect((await counts('notes/fs-junk')).takes).toBe(0);+}), 60_000);diff --git a/test/quarantine-override.serial.test.ts b/test/quarantine-override.serial.test.tsindex ad55af1fab..79b7434f0d 100644--- a/test/quarantine-override.serial.test.ts+++ b/test/quarantine-override.serial.test.ts@@ -25,6 +25,8 @@ import { importFromContent } from '../src/core/import-file.ts';import { runQuarantine, QUARANTINE_HELP } from '../src/commands/quarantine.ts';import { getContentFlag, isQuarantined } from '../src/core/quarantine.ts';import { QUARANTINE_OVERRIDE_KEY } from '../src/core/quarantine-override.ts';+import { FACTS_FENCE_BEGIN, FACTS_FENCE_END } from '../src/core/facts-fence.ts';+import { TAKES_FENCE_BEGIN, TAKES_FENCE_END } from '../src/core/takes-fence.ts';import { claimWorktree } from '../src/core/persistence/ownership.ts';import { activateSharedSkillPersistence } from '../src/core/persistence/skill-activation.ts';import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';@@ -132,6 +134,17 @@ describe('quarantine clear on a managed brain (#6259)', () => {expect(response.facts_backstop).toEqual({ skipped: 'quarantined' });}), 120_000);+ test('a managed write the gate quarantines projects no facts or takes from its fences', () => run(async () => {+ const FH = '| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |\n|---|---|---|---|---|---|---|---|---|---|';+ const TH = '| # | claim | kind | who | weight | since | source |\n|---|---|---|---|---|---|---|';+ const fences = `${FACTS_FENCE_BEGIN}\n${FH}\n| 1 | Example claim from the page | fact | 1.0 | world | medium | 2026-01-01 | | chat | |\n${FACTS_FENCE_END}\n\n${TAKES_FENCE_BEGIN}\n${TH}\n| 1 | Example take from the page | take | brain | 0.7 | 2026-01 | chat |\n${TAKES_FENCE_END}`;+ const slug = 'notes/junk-fences';+ await submitPageMutation(ctx(), { operation: 'put_page', params: { slug, content: junkPage('Junk fences', `${JUNK_BODY}\n\n${fences}`), request_id: randomUUID() } });+ expect(isQuarantined((await engine.getPage(slug, { sourceId: 'default' }))!.frontmatter as Record<string, unknown>)).toBe(true);+ expect(await engine.executeRaw("SELECT id FROM facts WHERE source_markdown_slug=$1", [slug])).toEqual([]);+ expect(await engine.executeRaw('SELECT k.id FROM takes k JOIN pages p ON p.id=k.page_id WHERE p.slug=$1', [slug])).toEqual([]);+ }), 120_000);+test('a local managed put_page cannot plant gate-owned markers (only the clear\'s owner kind keeps its override)', () => run(async () => {const clean = '---\ntitle: Clean notes\ntype: note\nquarantine:\n reason: junk_pattern\n detail: planted\natoms_scan_hash: deadbeefdeadbeef\n---\n\nOrdinary prose with nothing junk-like in it.\n';const slug = 'notes/planted-managed';