Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Read world pages without owner-only fence rows in atom extraction and dream phases

garrytan5ba4764b7911
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 821c6f24a1..0c8d2a60fd 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -10,6 +10,20 @@ credits are retained; no result has been reassigned to another provider. Origina
identifiers and attribution are available in the pre-removal Git revision
`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).
+## [Unreleased]
+
+**Atoms extracted from a world page never carry a fence row the page shows only to its owner, and `gbrain repair atom-fence-rows` finds and narrows atoms stored before.** A world page's facts table can hold rows marked `visibility: private`, and its takes table is never part of what a remote caller reads. Atom extraction, take proposals and the patterns phase read a page as a world reader sees it, so what they produce holds only world rows. Atoms an earlier version stored may still hold such a row: doctor `atom_fence_rows` counts them and names the read-only preview, and only `gbrain repair atom-fence-rows --apply --expect <hash>` makes the previewed atoms private. Nothing runs on upgrade.
+
+### Itemized changes
+
+- `src/core/cycle/extract-atoms-input.ts`: a page's extraction input is its `publicBody` (facts rows other than world and the takes fence removed); the cap, the watermark and quote verification apply to that text, on the cycle phase and the managed path alike.
+- `src/core/cycle/propose-takes.ts`: the extractor receives the page's `publicBody`; the content hash, fence skip and dedup rows still read the stored body.
+- `src/core/cycle/patterns.ts`: reflection excerpts in the subagent prompt and the quote-grounding sources are the reflection's `publicBody`.
+- `src/core/repair/atom-fence-rows.ts` (new, registered in `repair/core.ts`, `repair/registry.ts`, `persistence/preview-approval.ts`): explicit-only, preview-bound kind; the preview lists each world atom with its source page and the row kinds and numbers it carries (never the row text) and changes nothing; the apply sets `visibility: private` on exactly the previewed set through a revision-bound put_page.
+- `src/commands/doctor/checks/atom-fence-rows.ts` (new, a host-only `WAVE_CHECKS` entry, BRAIN category): `atom_fence_rows` warns with the count per source and the preview command.
+- Docs: `docs/guides/repair.md#atom-fence-rows` (what is listed, the apply, cost), `skills/RESOLVER.md`, key-files rows in `core-cycle.md`, `hindsight.md`, `core-cycle-patterns.md` and `memory-purge.md`.
+- Tests (PGLite and Postgres): `test/extract-atoms-world-fence-rows.test.ts` (cycle phase and managed brain: prompt, atoms and a remote read of each atom hold only world rows), `test/cycle-world-fence-rows.test.ts` (propose_takes input and proposals, patterns prompt and quote grounding), `test/repair-atom-fence-rows.test.ts` (doctor finding, preview changes nothing, apply without `--expect` refuses, apply narrows exactly the previewed atoms, unmanaged and managed).
+
## [0.60.626.0] - 2026-11-09
**`gbrain sources record-origin --remote` now locks down the existing checkout too, and on a managed brain it can no longer report success while a reclone still clones with git-lfs on.** On a managed brain the record took only the source row lock, so a reclone that had already read the source, or held its worktree locks, could clone with git-lfs downloads and hooks on after the command said the source was recorded. The record now takes the worktree locks and rows a reclone takes (refusing the id `source_busy` while one runs), and the reclone reads the record under its own locks. `--remote --apply` now also turns git-lfs downloads and hooks off in the existing checkout's `.git/config`, because a reclone only happens when a checkout is lost or replaced, and until then doctor read green while the checkout still fetched git-lfs objects and ran hooks. The git-lfs check now reads a committed `.gitattributes` under a directory whose name holds a tab (it was cut at the tab and skipped), ignores commented-out `filter=lfs` lines, says "declares a git-lfs filter" when a rule only declares one, and records a clone of an empty repository instead of telling the operator to restore an intact checkout. A failed write is reported for its own id instead of ending the run without saying which ids were recorded.
diff --git a/docs/architecture/key-files/core-cycle-patterns.md b/docs/architecture/key-files/core-cycle-patterns.md
index eca0f28339..2c4742f32c 100644
--- a/docs/architecture/key-files/core-cycle-patterns.md
+++ b/docs/architecture/key-files/core-cycle-patterns.md
@@ -4,7 +4,7 @@
Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.
Patterns, drift reports and the cycle modules listed after them.
-- `src/core/cycle/patterns.ts` — Patterns phase: cross-session theme detection over reflections within `dream.patterns.lookback_days` (default 30). Names a pattern only when ≥`dream.patterns.min_evidence` (default 3) reflections support it. Reflection excerpts use the shared UTF-16-safe truncator; a raw `.slice(0, 600)` can split an emoji pair and make Postgres reject the subagent job's JSONB payload. Single Sonnet subagent; same allow-list path as synthesize (imports `loadAllowedSlugPrefixes` + `loadOutputRoot` from synthesize.ts — the reflections lookup, prompt slug templates, and allow-list all honor `dream.synthesize.output_root`, default 'wiki'). Subagent job/wait timeouts are config keys `dream.patterns.subagent_timeout_ms` / `dream.patterns.subagent_wait_timeout_ms` (defaults 30/35 min, mirroring the `dream.synthesize.*` pair). The phase status reflects the child outcome: non-`completed` outcome with zero writes → `fail` (error code `PATTERNS_CHILD_<OUTCOME>`); non-`completed` with partial writes → `warn`. Runs AFTER `extract` so the graph is fresh. The fan-out sets `require_writes: true` so an all-writes-failed child dead-letters instead of reporting completed. Budget clamping: clamped to the remaining parent-job budget via `clampSubagentBudgets` when the cycle threads `deadlineAtMs` — the clamp template synthesize.ts reuses; `MIN_PATTERNS_SUBAGENT_BUDGET_MS` gates an honest skip, and `CYCLE_DEADLINE_RESERVE_MS` is re-exported here from its base-phase.ts home. Evidence watermark: a `completed` child stamps the newest consumed reflection `updated_at` into the state row `dream.patterns.last_evidence_ts` (never `now()`; fail/warn/timeout paths don't stamp, so a dead child retries next tick), and a later run skips `no_new_evidence` while no reflection in the window is newer — autopilot's hourly global tick becomes a free skip until a reflection actually changes; an absent/unparseable stamp fails open; `--once` bypasses the gate but a completed forced run still s... (line truncated to 2000 chars)
+- `src/core/cycle/patterns.ts` — Patterns phase: cross-session theme detection over reflections within `dream.patterns.lookback_days` (default 30). Names a pattern only when ≥`dream.patterns.min_evidence` (default 3) reflections support it. Reflection excerpts use the shared UTF-16-safe truncator; a raw `.slice(0, 600)` can split an emoji pair and make Postgres reject the subagent job's JSONB payload. Single Sonnet subagent; same allow-list path as synthesize (imports `loadAllowedSlugPrefixes` + `loadOutputRoot` from synthesize.ts — the reflections lookup, prompt slug templates, and allow-list all honor `dream.synthesize.output_root`, default 'wiki'). Subagent job/wait timeouts are config keys `dream.patterns.subagent_timeout_ms` / `dream.patterns.subagent_wait_timeout_ms` (defaults 30/35 min, mirroring the `dream.synthesize.*` pair). The phase status reflects the child outcome: non-`completed` outcome with zero writes → `fail` (error code `PATTERNS_CHILD_<OUTCOME>`); non-`completed` with partial writes → `warn`. Runs AFTER `extract` so the graph is fresh. The fan-out sets `require_writes: true` so an all-writes-failed child dead-letters instead of reporting completed. Budget clamping: clamped to the remaining parent-job budget via `clampSubagentBudgets` when the cycle threads `deadlineAtMs` — the clamp template synthesize.ts reuses; `MIN_PATTERNS_SUBAGENT_BUDGET_MS` gates an honest skip, and `CYCLE_DEADLINE_RESERVE_MS` is re-exported here from its base-phase.ts home. Evidence watermark: a `completed` child stamps the newest consumed reflection `updated_at` into the state row `dream.patterns.last_evidence_ts` (never `now()`; fail/warn/timeout paths don't stamp, so a dead child retries next tick), and a later run skips `no_new_evidence` while no reflection in the window is newer — autopilot's hourly global tick becomes a free skip until a reflection actually changes; an absent/unparseable stamp fails open; `--once` bypasses the gate but a completed forced run still s... (line truncated to 2000 chars) Reflection excerpts in the subagent prompt and the quote-grounding sources are the reflection's `publicBody`, so neither carries a facts row other than world or a takes row (test: `test/cycle-world-fence-rows.test.ts`).
- `src/core/cycle/drift.ts` report publication (#6052): a managed drift report whose publish is held (`publishOrHold`) is not linked in the detail, `reports_written` is 0 and `publish_deferred` 1, the detail names the hold (accepted and still publishing, or not admitted under database contention), and the phase is `partial`; every other publish error still throws.
- `src/core/cycle/phases/consolidate.ts` — the consolidate phase: clusters facts per page and promotes the best claim into a take. `cycle.consolidate.enabled` (default on; an explicit falsy value returns `skipped`, #6667) is read inside the phase; `dream --phase consolidate --once` bypasses it. Take identity for the upsert lookup is `(page_id, claim)` restricted to rows this phase authors (`kind='fact' AND holder='self'`) — `since_date` is NOT identity (it derives from MIN(valid_from) of the cluster and moves whenever extract_facts re-inserts, which degraded the lookup into duplicate INSERTs); deliberately NOT filtered on `active` (a superseded take still owns its claim — skipping it would resurrect a retired claim via the INSERT path); `ORDER BY id` keeps the pick deterministic across pre-existing duplicate rows. A resolved take is immutable — its id is reused for consolidation but the row is left untouched. Managed local consolidation passes the cycle source ID, publishes take, contributing facts and validity changes atomically: a fenced member on the entity page is closed in its `## Facts` fence row in the same page publication and its `valid_until` derives from that cell, an unfenced member is closed in the database, and a member fenced on another page stays open (test `test/consolidate-fenced-close-reimport.test.ts`). Retired/resolved matching takes produce a durable skipped receipt; semantic intent excludes vectors/timestamps/cache metadata, while a genuine newer fact/page snapshot changes request identity. Only live world-visible evidence is promoted; private facts remain private. #5575 ENG-3: fact tiers are read per bucket and external_untrusted facts cluster in a separate pass, so an external claim never shares a take with owner facts. Each cluster's take is written at `derive:consolidate` = min(cluster fact tiers, agent_written): unmanaged, the take insert or re-promotion, consolidation marks and valid_until writeback are one `derivedMaintenanceTransaction` (a re-promotion lowers the existing take to min(existing, cluster), even a resolved one); managed, the request carries `declareDerivation`. Edges: take -> every cluster fact. The unmanaged path runs the write gate (`decideTakeWrite`, config read once per run via `loadImportSanityConfig`) on each... (line truncated to 2000 chars)
diff --git a/docs/architecture/key-files/core-cycle.md b/docs/architecture/key-files/core-cycle.md
index 1891a1231f..dce05b1392 100644
--- a/docs/architecture/key-files/core-cycle.md
+++ b/docs/architecture/key-files/core-cycle.md
@@ -22,7 +22,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/cycle/extract-atoms-drain-outcome.ts` — #6817: `drainOutcome(result)`, the one mapping from a drain stop to exit code, JSON `status` (never `ok` for an incomplete stop), `retryable`, `code` and `reason`, read from the error registry (`atom_drain_incomplete` exit 11, `atom_drain_provider_failure` exit 1 with `rate_limit`/`transient` overridden to retryable exit 11, `atom_drain_no_progress` exit 1; a null count is always `atom_drain_incomplete`/`count_unavailable`). Used by `dream --drain` and the `extract-atoms-drain` Minion handler; type-only import of the drain module. Tests: `test/extract-atoms-drain-outcome.test.ts`, `test/dream-drain-failure-summary.serial.test.ts`, `test/extract-atoms-drain-handler.test.ts`.
- `src/core/cycle/extract-atoms-budget-notice.ts` — #6425: `drainBudgetNotice(result)` renders the `atom_drain_budget` notice a `budget`-stopped drain carries in `gbrain dream --drain --json` (spend, per-run cap, pages left; paid fix `gbrain config set cycle.extract_atoms.budget_usd <USD>`, verify `gbrain config get`), and `usd` formats the amounts for the stderr stop line. Dynamically imported by `dream.ts` so its notice-rendering imports stay out of the CLI flag scan. Tests: `test/dream-drain-failure-summary.serial.test.ts`.
-- `src/core/cycle/extract-atoms-input.ts` — #6503 the input cap and the partial disposition. `resolveExtractAtomsInputCap` reads `cycle.extract_atoms.max_input_chars` (floor 1000; the older `max_source_chars`, floor 500, loses when both are set; default 50 000) before discovery. `extractAtomsInput(item, cap)` binds the cut once: paste-stripped for a transcript (#5812), UTF-8-safe, with `truncated` measured on the text the cap applied to. A page item also takes its stored `extract_atoms` watermark (`src/core/extraction-watermark.ts`, large pages A7): when the body still starts with the watermarked prefix the model reads only the appended text (its newest `cap` characters when longer), which is still partial input, so the same disposition below applies; `inputTruncatedLine` is null for a complete tail read (not counted, no stderr) and names the window otherwise, and the phase commits the plan once the item's writes committed (a pending managed batch keeps the old watermark). A cut item is extracted once from its head and gets a partial disposition instead of a completion: `input_truncated` counts it on the phase result (and the drain sums it into `input_truncated`, with one `[drain]` line), `inputTruncatedLine` is written to stderr naming the knob, the head atoms publish, no completion stamp is written and nothing is retired. `recordPartialDisposition` stores the cap under (content hash, cap) in `extract_atoms_page_state` / `extract_atoms_transcript_state.partial_input_chars` (migration v240; the page row is pinned to the identity discovery read), and on a managed brain the origin carries `partialInputChars`, which enters the run key, keeps the completion's checkpoint `partial`, skips the page-state stamp and the retirement, and marks the completion outcome `status: 'partial'`. Discovery and the backlog count skip a partial row like a tombstone (`PAGE_SCAN_STATE_EXCLUSION_SQL`, `tombstonedTranscriptsForHashes`, the partial checkpoint); `releasePartialDispositions` runs before discovery with the current cap and clears the rows and checkpoints a raised cap supersedes, so the item is eligible again with zero model calls in between; `countExtractAtomsBacklog` reads the same cap and counts a page whose partial row or checkpoint sits below it (`pageScanStateExclusionSql` / `managedAtomDiscoverySql` with the cap; #7391), so a drain, doctor and autopilot see it before any phase has released it, while counting itself writes nothing (`test/extract-atoms-raised-cap-drain-7391.test.ts`); a content change is a new row. Resumed and budget-skipped items are not counted. `stampTranscriptTombstone` (v146) lives here too. Tests: `test/extract-atoms-input-truncated-6503.test.ts` (PGLite and Postgres, page and transcript, managed and unmanaged).
+- `src/core/cycle/extract-atoms-input.ts` — #6503 the input cap and the partial disposition. `resolveExtractAtomsInputCap` reads `cycle.extract_atoms.max_input_chars` (floor 1000; the older `max_source_chars`, floor 500, loses when both are set; default 50 000) before discovery. `extractAtomsInput(item, cap)` binds the cut once: paste-stripped for a transcript (#5812), UTF-8-safe, with `truncated` measured on the text the cap applied to. A page item also takes its stored `extract_atoms` watermark (`src/core/extraction-watermark.ts`, large pages A7): when the body still starts with the watermarked prefix the model reads only the appended text (its newest `cap` characters when longer), which is still partial input, so the same disposition below applies; `inputTruncatedLine` is null for a complete tail read (not counted, no stderr) and names the window otherwise, and the phase commits the plan once the item's writes committed (a pending managed batch keeps the old watermark). A cut item is extracted once from its head and gets a partial disposition instead of a completion: `input_truncated` counts it on the phase result (and the drain sums it into `input_truncated`, with one `[drain]` line), `inputTruncatedLine` is written to stderr naming the knob, the head atoms publish, no completion stamp is written and nothing is retired. `recordPartialDisposition` stores the cap under (content hash, cap) in `extract_atoms_page_state` / `extract_atoms_transcript_state.partial_input_chars` (migration v240; the page row is pinned to the identity discovery read), and on a managed brain the origin carries `partialInputChars`, which enters the run key, keeps the completion's checkpoint `partial`, skips the page-state stamp and the retirement, and marks the completion outcome `status: 'partial'`. Discovery and the backlog count skip a partial row like a tombstone (`PAGE_SCAN_STATE_EXCLUSION_SQL`, `tombstonedTranscriptsForHashes`, the partial checkpoint); `releasePartialDispositions` runs before discovery with the current cap and clears the rows and checkpoints a raised cap supersedes, so the item is eligible again with zero model calls in between; `countExtractAtomsBacklog` reads the same cap and counts a page whose partial row or checkpoint sits below it (`pageScanStateExclusionSql` / `managedAtomDiscoverySql` with the cap; #7391), so a drain, doctor and autopilot see it before any phase has released it, while counting itself writes nothing (`test/extract-atoms-raised-cap-drain-7391.test.ts`); a content change is a new row. Resumed and budget-skipped items are not counted. `stampTranscriptTombstone` (v146) lives here too. Tests: `test/extract-atoms-input-truncated-6503.test.ts` (PGLite and Postgres, page and transcript, managed and unmanaged). A page is read as a world reader sees it (`publicBody` from `mentions/aliases.ts`: facts rows other than world and the takes fence removed) before the cap and the watermark apply, so the prompt, the atoms and a verified `source_quote` never hold a row a remote read of the page hides; test: `test/extract-atoms-world-fence-rows.test.ts` (unmanaged and managed, PGLite and Postgres).
- `src/core/cycle/extract-atoms.ts` — the extract_atoms lens phase: mines eligible pages into `atoms/<date>/<stem>-<hash>` pages. The input cap, the cut and the partial disposition of a cut item are in `extract-atoms-input.ts` (#6503). Transcript input is paste-stripped before the cut (#5812); discovery skips self-captures (#5820) and keeps only the session-corpus files `keepSessionSourceTranscripts` (`synthesize-source-routing.ts`, shared with synthesize; a file is a corpus file by its spelled or real path, an unreadable real path is held `corpus_path_unresolvable`, #7871) resolves to the run's source, read-only in a dry run, reporting the rest in `details.source_routing` (#7846); a resumed generation member whose transcript no longer resolves to the run's source (`transcriptSourceHold`) is held, not resubmitted, and counted in `details.source_routing.generation_members_held` (#7870); the meeting transcripts dir is read only for `default`. Discovery and the backlog count append `connectorAtomExclusionSql` (`connector-atoms.ts`), so connector `email`/`meeting` pages stay out only when `cycle.extract_atoms.connector_pages` is false. The type allowlist is `unionExtractableTypes(packExtractable, packExcluded)`: the legacy floor (meeting, source, article, video, book, original) minus the floor types the active pack declares not extractable (`nonExtractableTypesFromPack`, #5756; a declared type without `extractable: true` is a pack decision, an undeclared type keeps the floor), plus the pack's `extractable: true` types, minus synthesis outputs; gbrain-base is unchanged, gbrain-recommended's `source: false` now holds for atoms as it did for facts. Pinned by `test/pack-extractable-floor-5756.test.ts`. A drain attempt passes `opts.attempt` (`budgetTracker`, `writeWait`) so its batches share one budget and one maintenance publish wait. Eligibility reads source-incarnation/page/full-hash-keyed derived scan state; scan and failure markers do not mutate canonical frontmatter. Managed extraction checks source-wide local authority and owner readiness before provider work, admits outputs plus a completion request together, and replays retained output without another model call. A failed managed batch is retried by the next run instead (#6325, `resumeManagedAtoms` in `persistence/atom-maintenance.ts`); an origin held after `MAX_DETERMINISTIC_FAILURES` (now defined in `extract-atoms-page-state.ts`, re-exported here) is skipped with no model call and counted in `details.held_failed`, never in `failures`. Managed atom files keep provisional source hashes; only the source-incarnation/page/full-hash durable completion receipt excludes an item from discovery and backlog counts. Unmanaged atom completion flips and their cardinality check share a transaction after provenance links persist, so a partial match rolls back and stays retryable. A page-derived atom upserts at its locator-folded slug, else a compatible legacy title-only slug; when both miss, the source page's live bound atoms are loaded once per page per run and exactly one JS-lowercased title match is adopted (a case-only title change never mints a duplicate; zero or several matches mint the new slug). Response parsing lives in `extract-atoms-parse.ts`. Atoms of one item that resolve to one slug (a repeated title) publish once, the first kept (#7514: two items at one key failed the generation, managed `generation_live_conflict`, unmanaged a primary-key violation). A managed item whose atom write did not commit is a write failure (`atomWriteFailure`, `persistence/atom-maintenance.ts`): its `failures` entry carries `request_id`, `code`, and its strike, never a provider classification. An undated source dates its atoms by the source page's creation date (`undated` for transcripts), never the run date. A page-derived atom's frontmatter `date` is the source page's content date (`atom-source-date.ts`: the stored `effective_date`, else `computeEffectiveDate`), read with the input before the model call, so classic import and managed publication store that `effective_date` (source `date`) and `extracted_at` stays the processing stamp; transcript-derived atoms carry no `date`. After an unmanaged item completes (`completeUnmanagedItem`), `retireStaleAtoms` soft-deletes that source's atoms from earlier extractions (other or provisional `source_hash`) that this extraction did not re-produce; a cut item neither completes nor retires. Hard `opts.signal` (chat call, pacing, checks before each item and commit) leaves no strike, receipt or rollup; soft `opts.stopSignal` stops before the next item.
Managed completion admits revision-pinned `managed_atom_delete` children alongside replacement pages, removes canonical files through the page deletion path, and commits its checkpoint only after every publication and retirement commits.
Both paths prevent LLM-chosen titles that drift between extractions from piling up.
diff --git a/docs/architecture/key-files/hindsight.md b/docs/architecture/key-files/hindsight.md
index d9079de021..41c8c9fafe 100644
--- a/docs/architecture/key-files/hindsight.md
+++ b/docs/architecture/key-files/hindsight.md
@@ -22,7 +22,7 @@ round-trip suite (CHECK admits unresolvable+NULL, still rejects partial+true and
unresolvable+true|false, pre-v80 NULL/NULL rows survive).
- `src/core/cycle/base-phase.ts` — abstract `BaseCyclePhase` class. Enforces `sourceScopeOpts(ctx)` threading at the type level; rules out the source-isolation leak class structurally for every new phase. Inherits source-scope, budget meter, error envelope, progress reporter. propose_takes / grade_takes / calibration_profile all extend it. `run()` honors dry-run for every subclass at once: when `opts.dryRun` or `ctx.dryRun === true`, it returns `status: 'skipped'` / `reason: 'no_dry_run_support'` before `process()` (no LLM calls, no take_proposals / take_grade_cache / calibration_profiles writes) — the same skip shape extract and resolve_symbol_edges use; runCycle threads `dryRun` into all three call sites. The ONE home of `CYCLE_DEADLINE_RESERVE_MS` (60s carved out of the enclosing job's remaining wall-clock — wait-poll + worker force-evict grace + cleanup headroom; patterns.ts re-exports it) and of `BasePhaseOpts.deadlineAtMs` (the enclosing minion job's absolute deadline, threaded via runCycle; null/unset for direct `gbrain dream` callers — phases then fall back to their derived defaults).
-- `src/core/cycle/propose-takes.ts` — LLM scans markdown prose, proposes gradeable claims to the `take_proposals` queue. Candidate discovery excludes `extract_receipt` pages before the LLM call so the phase never re-ingests its own operational receipts; nullable legacy page types remain eligible. `cycle.propose_takes.types` (#5213; `proposeTakesTypes`, a JSON array of page types in the `cycle.enrich_thin.types` shape) narrows the candidate query to those types with `type = ANY(...)` on top of the source scope; unset keeps every type eligible and a malformed value is ignored with one stderr line. Idempotency cache on `(source_id, page_slug, content_hash, prompt_version)` composite unique index. `extractorOutcome` (#6782) is the one reading of a reply, used for both the takes and the tombstone decision: it locates the first JSON value (after `<think>` and whole-reply fence stripping, the whole remainder or up to its own closing bracket) and returns `valid_empty` only for a complete empty array not followed by a JSON object or an array of take-shaped objects (a `[1]` citation does not count), `valid_nonempty` for at least one take, else `invalid`, which `defaultExtractor` throws as transient (no tombstone). A zero-claim tombstone is keyed by the page's content hash, so any edit to the page extracts it again on the next cycle. Fence-dedup: existing canonical takes passed to the extractor as context. Opt-in `dream.propose_takes.attribution_rules=true` adds `EXTRACT_TAKES_ATTRIBUTION_RULES` (withdrawn claims, assistant-authored judgments not attributed to the user) under prompt version suffix `+attribution5425`; off by default because it measured lower cat15 recall. Ships a stub prompt; tuned prompt arrives via the synthetic corpus build. Per-page extractor failures log a warning and continue, but a whole-run condition (per `classifyGlobalLlmError` in `src/core/ai/errors.ts`) breaks the page loop with a single combined warning line, sets `aborted_global_error`, and records a halt in the rollup — auth/billing on the first hit, bare rate_limit only after `RATE_LIMIT_HALT_STREAK` (3) consecutive hits (a successful call resets the streak). Status: `fail` when the halt happened with ZERO successful extractor calls (the whole LLM lane is down), otherwise any warnings fold into `warn` + ` (N warning(s))` summary suffix, so swallowed failures can't read as a clean `ok`. `llm_calls_succeeded`/`llm_calls_failed`/`halted` land in details. The phase wall-clock deadline is DERIVED, never a literal (a literal equal to the autopilot-cycle handler anchor, with non-co-started clocks, would make the clean `deadline_hit` partial-completion path structurally unreachable): explicit `opts.deadlineMs` wins (test seam), else `resolveProposeTakesDeadlineMs(deadlineAtMs, now)` = `PHASE_DEADLINE_FRACTION_OF_JOB` (0.8, headroom for grade_takes + calibration_profile which run after it with no deadline of their own) × (remaining job budget − `CYCLE_DEADLINE_RESERVE_MS`), clamped to the fallback (0.8 × the `autopilot-cycle` entry in `HANDLER_DEFAULT_TIMEOUT_MS` — a missing anchor throws at module LOAD, failing the whole cycle visibly). A fractioned value under `MIN_PROPOSE_TAKES_BUDGET_MS` (2 min) resolves to null and the phase returns an honest `skipped` with `reason: 'insufficient_cycle_budget'` (after the cheap provider probe, before any rollup/DB write — records neither a halt nor a completed round; next cycle retries with a fresh budget). Pinned by `test/propose-takes.test.ts` + `test/propose-takes-per-claim.test.ts` + `test/cycle-phase-deadline-drift.test.ts`. The kind vocabulary is `TAKE_KIND_VALUES` imported from `src/core/takes-fence.ts` (the fence enum — no hand-copied set); an unknown kind maps through the legacy-kind table, else `take`. `dream.propose_takes.call_timeout_ms` (whole ms 1000..300000; `config set` refuses others, a stored out-of-range value is clamped and a non-number ignored, each with a named-key phase warning) replaces the output-cap scaling for every extractor call, held to the phase time left (never below 90 s); a call its own bound stops fails per page with an error naming the key. Pinned by `test/propose-takes-config-max-tokens.test.ts` + `test/propose-takes-truncation.test.ts`. #5212: `listCandidatePages` also skips the dream cycle's own output by its writer stamps (`dream_generated = true`, `extracted_by LIKE 'extract_atoms%'`, `synthesized_by LIKE 'synthesize_concepts%'`), pinned on PGLite (`test/propose-takes-per-claim.test.ts`) and Postgres (`test/e2e/propose-takes-jsonb-postgres.test.ts`). The mechanical holder check of #5425 [UC4] (`cycle/propose-takes-attribution.ts`, one call after the extractor returns, behind `dream.attribution_checks`, default off) is separate from the prompt rule and documented with that module. GBRA-130 A-25: extractor failures go through `ProposeTakesFailures` (`cycle/propose-takes-failures.ts`, op_checkpoints op `propose-takes-failures` per source): a page that failed before at the same content hash and prompt version is retried after the fresh pages, only fresh failures feed the #3763 halt and the `propose_takes.pages` ItemRun breaker, and a run-scoped error rethrows. A content-class failure (`request_too_large`, `content_rejected`) repeated in `PROPOSE_TAKES_HOLD_RUNS` (3) counted runs, each with extractor success evidence, writes a failure tombstone: a `rejected` take_proposals row whose claim is `(extraction failed: <code>)`, distinct from an empty extraction; transient failures never hold, and a systemic run or global halt counts nothing. The result adds `failed_pages`, `failure_tombstones_written` and `systemic`; the summary names `gbrain takes propose --failed`. A content or prompt-version change, or `gbrain takes propose --retry-failed`, retries a held page. Pinned by `test/pathological/a25-propose-takes-poison-pages.test.ts` (both engines).
+- `src/core/cycle/propose-takes.ts` — LLM scans markdown prose, proposes gradeable claims to the `take_proposals` queue. Candidate discovery excludes `extract_receipt` pages before the LLM call so the phase never re-ingests its own operational receipts; nullable legacy page types remain eligible. `cycle.propose_takes.types` (#5213; `proposeTakesTypes`, a JSON array of page types in the `cycle.enrich_thin.types` shape) narrows the candidate query to those types with `type = ANY(...)` on top of the source scope; unset keeps every type eligible and a malformed value is ignored with one stderr line. Idempotency cache on `(source_id, page_slug, content_hash, prompt_version)` composite unique index. `extractorOutcome` (#6782) is the one reading of a reply, used for both the takes and the tombstone decision: it locates the first JSON value (after `<think>` and whole-reply fence stripping, the whole remainder or up to its own closing bracket) and returns `valid_empty` only for a complete empty array not followed by a JSON object or an array of take-shaped objects (a `[1]` citation does not count), `valid_nonempty` for at least one take, else `invalid`, which `defaultExtractor` throws as transient (no tombstone). A zero-claim tombstone is keyed by the page's content hash, so any edit to the page extracts it again on the next cycle. Fence-dedup: existing canonical takes passed to the extractor as context. Opt-in `dream.propose_takes.attribution_rules=true` adds `EXTRACT_TAKES_ATTRIBUTION_RULES` (withdrawn claims, assistant-authored judgments not attributed to the user) under prompt version suffix `+attribution5425`; off by default because it measured lower cat15 recall. Ships a stub prompt; tuned prompt arrives via the synthetic corpus build. Per-page extractor failures log a warning and continue, but a whole-run condition (per `classifyGlobalLlmError` in `src/core/ai/errors.ts`) breaks the page loop with a single combined warning line, sets `aborted_global_error`, and records a halt in the rollup — auth/billing on the first hit, bare rate_limit only after `RATE_LIMIT_HALT_STREAK` (3) consecutive hits (a successful call resets the streak). Status: `fail` when the halt happened with ZERO successful extractor calls (the whole LLM lane is down), otherwise any warnings fold into `warn` + ` (N warning(s))` summary suffix, so swallowed failures can't read as a clean `ok`. `llm_calls_succeeded`/`llm_calls_failed`/`halted` land in details. The phase wall-clock deadline is DERIVED, never a literal (a literal equal to the autopilot-cycle handler anchor, with non-co-started clocks, would make the clean `deadline_hit` partial-completion path structurally unreachable): explicit `opts.deadlineMs` wins (test seam), else `resolveProposeTakesDeadlineMs(deadlineAtMs, now)` = `PHASE_DEADLINE_FRACTION_OF_JOB` (0.8, headroom for grade_takes + calibration_profile which run after it with no deadline of their own) × (remaining job budget − `CYCLE_DEADLINE_RESERVE_MS`), clamped to the fallback (0.8 × the `autopilot-cycle` entry in `HANDLER_DEFAULT_TIMEOUT_MS` — a missing anchor throws at module LOAD, failing the whole cycle visibly). A fractioned value under `MIN_PROPOSE_TAKES_BUDGET_MS` (2 min) resolves to null and the phase returns an honest `skipped` with `reason: 'insufficient_cycle_budget'` (after the cheap provider probe, before any rollup/DB write — records neither a halt nor a completed round; next cycle retries with a fresh budget). Pinned by `test/propose-takes.test.ts` + `test/propose-takes-per-claim.test.ts` + `test/cycle-phase-deadline-drift.test.ts`. The kind vocabulary is `TAKE_KIND_VALUES` imported from `src/core/takes-fence.ts` (the fence enum — no hand-copied set); an unknown kind maps through the legacy-kind table, else `take`. `dream.propose_takes.call_timeout_ms` (whole ms 1000..300000; `config set` refuses others, a stored out-of-range value is clamped and a non-number ignored, each with a named-key phase warning) replaces the output-cap scaling for every extractor call, held to the phase time left (never below 90 s); a call its own bound stops fails per page with an error naming the key. Pinned by `test/propose-takes-config-max-tokens.test.ts` + `test/propose-takes-truncation.test.ts`. #5212: `listCandidatePages` also skips the dream cycle's own output by its writer stamps (`dream_generated = true`, `extracted_by LIKE 'extract_atoms%'`, `synthesized_by LIKE 'synthesize_concepts%'`), pinned on PGLite (`test/propose-takes-per-claim.test.ts`) and Postgres (`test/e2e/propose-takes-jsonb-postgres.test.ts`). The mechanical holder check of #5425 [UC4] (`cycle/propose-takes-attribution.ts`, one call after the extractor returns, behind `dream.attribution_checks`, default off) is separate from the prompt rule and documented with that module. GBRA-130 A-25: extractor failures go through `ProposeTakesFailures` (`cycle/propose-takes-failures.ts`, op_checkpoints op `propose-takes-failures` per source): a page that failed before at the same content hash and prompt version is retried after the fresh pages, only fresh failures feed the #3763 halt and the `propose_takes.pages` ItemRun breaker, and a run-scoped error rethrows. A content-class failure (`request_too_large`, `content_rejected`) repeated in `PROPOSE_TAKES_HOLD_RUNS` (3) counted runs, each with extractor success evidence, writes a failure tombstone: a `rejected` take_proposals row whose claim is `(extraction failed: <code>)`, distinct from an empty extraction; transient failures never hold, and a systemic run or global halt counts nothing. The result adds `failed_pages`, `failure_tombstones_written` and `systemic`; the summary names `gbrain takes propose --failed`. A content or prompt-version change, or `gbrain takes propose --retry-failed`, retries a held page. Pinned by `test/pathological/a25-propose-takes-poison-pages.test.ts` (both engines). The extractor receives the page's `publicBody` (facts rows other than world and the takes fence removed); the content hash, the fence skip and the dedup rows still read the stored body (test: `test/cycle-world-fence-rows.test.ts`).
- `src/core/cycle/grade-takes.ts` — walks unresolved takes older than 6 months, retrieves evidence, asks judge model, caches verdict. Auto-resolve DISABLED by default. Conservative thresholds: >=0.95 single OR >=0.85 ensemble 3/3 unanimous. `aggregateEnsemble` reuses the cross-modal substrate; fires on the borderline 0.6-0.95 band. Writes to `take_grade_cache`. Same global-error posture as propose-takes: a judge failure that classifies as a whole-run condition breaks the take loop with `aborted_global_error` (auth/billing first hit; rate_limit after 3 consecutive takes; `fail` status when zero judge calls succeeded, else `warn` + warning count; `judge_calls_succeeded`/`judge_calls_failed`/`halted` in details). Rejected ensemble judges are classified the same way — `Promise.allSettled` never flattens a revoked key or exhausted spend limit into a silent null verdict. Per-take auto-apply failures stay per-take.
- `src/core/cycle/grade-takes-measured.ts` — `GRADE_TAKES_MEASURED_MODELS` (the judges that met the W6 take-grading eval's preregistered rule, `evals/take-grading/PREREGISTRATION.md`; `openai:gpt-6.1-sol` since the 2026-10-16 counted run) and `gradeJudgeMeasured()`, which `gbrain takes grades` (`cmdGrades` in `src/commands/takes.ts`, trusted local, no MCP op) uses to mark cached verdicts no measurement backs. Auto-resolve stays unwired.
- `src/core/cycle/calibration-profile.ts` — aggregates resolved takes into 2-4 narrative pattern statements + active bias tags. Voice-gated via `gateVoice()`. Cold-brain skip when <5 resolved. Writes to `calibration_profiles` with audit columns (`voice_gate_passed`, `voice_gate_attempts`, `grade_completion`).
diff --git a/docs/architecture/key-files/memory-purge.md b/docs/architecture/key-files/memory-purge.md
index e751a343f0..5eec6163c2 100644
--- a/docs/architecture/key-files/memory-purge.md
+++ b/docs/architecture/key-files/memory-purge.md
@@ -27,6 +27,8 @@ User-facing contract: [expire versus purge](../../guides/memory-boundaries.md#pu
- `src/core/generations/ledger-scrub.ts` — GBRA-161: purge reaches the generation ledger. A page purge (`page-purge.ts`) nulls the purged item's preimages in `derived_generation_items` and every held proposal in `derived_generations` naming it; a fact purge (`facts/purge.ts`) nulls every preimage, proposal and held context carrying the claim. Both are `swept` (`generation_ledger`) in the deletion inventory, so the verification probes them; `gbrain repair generations` then refuses a scrubbed item with `no_preimage`.
- `src/core/persistence/atom-retirement-hold.ts` — #7013: the one SQL rule for atoms `gbrain repair atoms-restore` restores. `atomRetirementsSql(scope)` is set-based (CTEs over `pages` joined on source and origin key, linear in the atoms in scope) and returns every non-imported atom soft-deleted with `retired_by: managed-reextract` with `origin_live` (a live page origin in its source, or a transcript), `replaced` (a live atom of the same origin carries another stripped source hash), `latest` (its hash is the hash of the origin's latest `managed-reextract` retirement) and `restorable` (all three right); `atomOriginScopeSql` narrows it to one atom's source and origin through the frontmatter GIN index for the apply recheck; `atomRetirementPurgeHold`, which keeps such an atom out of every batch purge selection (engine `purgeDeletedPages` preview and delete, the belief-ledger expiry, `selectPurgeCandidates`) for `ATOM_RESTORE_HOLD_DAYS` (30) after `deleted_at`, next to the #6729 `identityDowngradePurgeHold`. An explicit `delete --purge` is not held. Static strings only, so `engine-sql/pages.ts` imports it.
- `src/core/repair/atoms-restore.ts` — `gbrain repair atoms-restore` (#7013), explicit-only and preview-bound: lists atoms an empty managed re-extraction retired (`retired_by: managed-reextract`) that `atomRetirementsSql` (`persistence/atom-retirement-hold.ts`) marks `restorable`, each with origin, stripped source hash and `retired_at`, and residuals `restorable`, `origins`, `origin_gone`, `replaced`, `older_generation`; `--apply --expect <hash>` restores the approved set, rechecking each atom (id, incarnation, revision, origin, hash, `retired_at`, rule match) and reporting `changed_since_preview` otherwise. Managed: one `managed_maintenance_restore_reextract_atom` request per atom (`deleted_page: true`, bound to the deleted revision, request id in the outcome detail); `prepareAtomRestore` (dispatched from `prepared-maintenance.ts`) rechecks the rule under the atom and origin page locks and publishes a revision-bound `revert_version` to `version_id`, the newest live version of the atom at its source hash without `retired_by` (the one the coordinated delete archived; file written back, `allowMissingFile`); none is `no_version`, lowered to the `derive:atoms` tier of its origin with taint edges. Unmanaged: `createVersion`, `restorePage` and the two keys dropped in one `maintenanceTransaction`. Extraction state is not touched. Test: `test/pathological/h5-atoms-restore.test.ts`.
+- `src/core/repair/atom-fence-rows.ts` — `gbrain repair atom-fence-rows`, explicit-only and preview-bound: `findAtomFenceRows` lists live page-bound `visibility: world` atoms whose title, body or `source_quote` contains (case and whitespace folded, claims of at least `MIN_CLAIM_CHARS`) the claim of a facts row of their live source page whose visibility is not world or a takes row whose holder is not world, absent from the page's `publicBody`; keyset pages of 500 atoms whose source page names a facts or takes fence, each source page read once, segmented source pages counted `origin_unread`. The preview lists atom, source page and row kinds and numbers (never row text) under a saved hash; `--apply --expect <hash>` rechecks each atom and sets `visibility: private` through a revision-bound put_page (`narrowed`), else `changed_since_preview`. Doctor `atom_fence_rows` shares the scan. Test: `test/repair-atom-fence-rows.test.ts` (unmanaged and managed, PGLite and Postgres).
+- `src/commands/doctor/checks/atom-fence-rows.ts` — doctor `atom_fence_rows` (BRAIN, a host-only `WAVE_CHECKS` repair entry cleared by the explicit-only `atom-fence-rows`, so remediation classifies it `explicit_kind_required`): runs `findAtomFenceRows` per source, each statement bounded by `PLAN_STATEMENT_MS`; `warn` names the count per source and the read-only preview `gbrain repair atom-fence-rows --source <id> --json` as an agent `fix`, never a slug or row text; an overrun reports the count as unknown.
- `src/core/persistence/purge-parks.ts` — #6741 C: per-tombstone purge parks in op_checkpoints (op `purge-deleted-park`, key source+slug+deleted_at, so a re-deleted page starts fresh); park at `PURGE_PARK_LIMIT` (5) non-deferral failures, a success clears it, and parks of a source seen inactive rearm the first run its writer is active again (`notePurgeSourceWriter`). `purgeStaleCheckpoints` exempts the op; `prunePurgeParks` drops parks whose tombstone is gone. A park records the gbrain `version` of its last failure; `isParked` (the managed and unmanaged selection, doctor `purge_parked_pages`) counts only the running version's, so a park another version wrote (or one with no version) gets one automatic attempt and a failure re-parks it under the running version. Tests: `test/purge-deleted-parks.test.ts`, `test/purge-parks-version.test.ts` (Postgres: `test/e2e/purge-parks-version-postgres.test.ts`).
diff --git a/docs/guides/repair.md b/docs/guides/repair.md
index 869474b574..df24feef58 100644
--- a/docs/guides/repair.md
+++ b/docs/guides/repair.md
@@ -8,7 +8,7 @@ can load, and Google source files other local users can read. `gbrain repair`
fixes those and the other kinds listed in
[What each kind fixes](#what-each-kind-fixes). Every run is a preview unless
you pass `--apply`.
-The explicit-only kinds, among them `google-file-modes`, `stale-atoms`, `atoms-restore`, `extractor-facts`, `unwithdrawn-facts`,
+The explicit-only kinds, among them `google-file-modes`, `stale-atoms`, `atoms-restore`, `atom-fence-rows`, `extractor-facts`, `unwithdrawn-facts`,
`captured-facts`, `agent-session-facts`, `redacted-facts`, `loop-facts`, `ontology-facts`, `orphan-children`, `failed-writes`, `frontmatter`, `managed-sync-orphans`, `content-receipt-root`, `stuck-recovery`, `aliases`, `rename-identity` and `segmented-mirror`, run only when you name them (see [Explicit-only repair kinds](#explicit-only-repair-kinds)).
`gbrain doctor --remediation-plan` lists the same kinds as repair steps, and
`gbrain doctor --remediate --yes --include-repairs --expect <plan_hash>` runs them under a budget
@@ -1976,6 +1976,46 @@ their count, origins, oldest and newest retirement and the date the first hold
ends; its fix is the read-only preview. Show the user the preview before
running the apply.
+### Atom fence rows
+
+A world atom carries the claim of a fence row its source page shows only to
+the owner when an older extraction read the whole page: a facts row whose
+`visibility` is not `world`, or a takes row whose holder is not `world`.
+Extraction now reads a page as a world reader sees it, so new atoms never
+carry such a row, but atoms already stored keep what they copied and a remote
+read returns it. `gbrain repair atom-fence-rows` finds them and, only when you
+apply it, makes them private. It is explicit-only and preview-bound, and
+nothing runs on upgrade.
+
+```bash
+gbrain doctor --only atom_fence_rows --json # count per source; ok when none
+gbrain repair atom-fence-rows --source <id> --json # preview: each atom, its source page, the row kinds and numbers, and a hash
+gbrain repair atom-fence-rows --source <id> --apply --expect <hash>
+```
+
+An atom is listed when it is live, page-bound (`source_slug`), stamped
+`visibility: world`, and its title, body or `source_quote` contains (case and
+whitespace folded) the claim of such a row of its live source page, unless the
+page's world text holds the same claim too. Claims shorter than 12 characters
+are not matched. The preview names each atom with its source page and the
+rows (`facts row 2`, `takes row 1`), never the row text, and changes nothing.
+A source page stored in segments is not read: its world atoms are counted as
+`origin_unread`.
+
+The apply sets `visibility: private` on exactly the previewed set through a
+revision-bound put_page, which re-chunks and re-embeds each atom; remote reads
+and search stop returning it, local reads keep it. An atom whose revision,
+source page or matched rows changed since the preview reports
+`changed_since_preview` and is kept. `--apply` without `--expect` refuses
+with the preview and apply commands; a stale hash or another `--source`
+refuses with [`preview_changed`](#preview-changed).
+
+Cost: doctor and the preview read every world atom whose source page names a
+facts or takes fence, in pages of 500 by id, and each such source page once;
+no model is called. Doctor bounds each statement at 120 seconds and reports
+the count as unknown when one overruns. Show the user the preview before
+running the apply.
+
### Generations
Unmanaged atom extraction publishes each page's or transcript's atoms as one
diff --git a/scripts/page-body-readers-baseline.tsv b/scripts/page-body-readers-baseline.tsv
index d8efd29ede..0a0b5abefa 100644
--- a/scripts/page-body-readers-baseline.tsv
+++ b/scripts/page-body-readers-baseline.tsv
@@ -547,6 +547,8 @@ src/core/repair/accepted-takes.ts livePage call:serializePageToMarkdown SEGW mat
src/core/repair/agent-session-facts.ts retireTakes call:serializePageToMarkdown INLINE inline pages only: a segmented page returns before the read and its takes are kept (changed_since_preview)
src/core/repair/agent-session-facts.ts rewriteFencedFacts call:serializePageToMarkdown INLINE inline pages only: a segmented page returns before the read and its fenced facts are kept (changed_since_preview)
src/core/repair/agent-session-facts.ts rewriteFencedFacts field INLINE inline pages only: a segmented page returns before the read and its fenced facts are kept (changed_since_preview)
+src/core/repair/atom-fence-rows.ts atomFenceRowsRepair call:serializePageToMarkdown SEGW
+src/core/repair/atom-fence-rows.ts findAtomFenceRows sql INLINE inline source pages only: a segmented source page (compiled_truth NULL) is counted origin_unread and never read
src/core/repair/captured-facts.ts strikeFencedRows call:serializePageToMarkdown SEGW
src/core/repair/captured-facts.ts strikeFencedRows field SEGW
src/core/repair/connector-fences.ts candidates sql STREAM
diff --git a/skills/RESOLVER.md b/skills/RESOLVER.md
index ec8127c6d1..fb03fce881 100644
--- a/skills/RESOLVER.md
+++ b/skills/RESOLVER.md
@@ -146,7 +146,7 @@ off until the user opts in, and paid enrichment is a separate choice.
| "harvest this skill into gbrain", "publish this skill to gbrain", "lift this skill upstream", "share this skill with other gbrain clients", "promote my skill to gbrain" | `skills/skillpack-harvest/SKILL.md` |
| Post-restart health + auto-fix, "did the container restart break anything", smoke test | `skills/smoke-test/SKILL.md` |
| `GBRAIN_DB_ACCESS`, "gbrain database error", "gbrain connection refused", "brain database is down", "cannot reach the brain database", "fix gbrain database access", "repair gbrain postgres" | `skills/db-repair/SKILL.md` |
-| Doctor `timeline_history` / `derived_visibility` / unsealed pages, "repair timeline history", "fix atom visibility", "re-seal withheld pages" | Preview with `gbrain repair`, apply one kind with `gbrain repair <kind> --apply` on the brain host after the user agrees. See `docs/guides/repair.md` |
+| Doctor `timeline_history` / `derived_visibility` / `atom_fence_rows` / unsealed pages, "repair timeline history", "fix atom visibility", "re-seal withheld pages" | Preview with `gbrain repair` (or `gbrain repair <kind>` for an explicit-only kind), apply one kind with the `--apply` command its preview prints, on the brain host after the user agrees. See `docs/guides/repair.md` |
| A page write refused `owner_unavailable` with `detail: unbound_source` (classic Postgres) | Write the file, commit, `gbrain sync --source <id>` (remote: relay to the user); never claim or activate to get one write through. See `skills/conventions/agent-operator-protocol.md` |
| A write or sync refused with `file_database_drift`, `ambiguous_source_path`, `physical_root_device_changed`, `cursor_processing_options_conflict`, `take_row_collision`, `invalid_source_uri`, `queue_capacity`, or doctor `parked_effects` | Relay the error's `suggestion` command; see `docs/guides/write-refusals.md` before running it |
| A gbrain command or MCP tool returned an error, exited 3 (`confirmation_required`), 10 or 11, or printed `[AGENT]` / a notice block; "what does this error code mean" | Follow the agent operator protocol, `docs/protocol/AGENT_OPERATOR_v1.md` (read `code`, follow `fix.next`); look a code up offline with `gbrain errors <code>` |
diff --git a/skills/skills.lock.json b/skills/skills.lock.json
index f72f8f0ad1..34ec4c5149 100644
--- a/skills/skills.lock.json
+++ b/skills/skills.lock.json
@@ -1,5 +1,5 @@
{
- "RESOLVER.md": "587768c702e0badf5e7d6201cd5902b7313b218e5663ab527e3a8365f5c438ee",
+ "RESOLVER.md": "17a9a2ae1f98a8ae4663d9eb6d5f83092981ee8623dd58320bdda6ef8b77c0ed",
"_AGENT_README.md": "d66098abeb735975ffed54cb9c89d51255996500a9554ae1d1e996db4171631f",
"_brain-filing-rules.json": "4e6ecee2d94867d146583d60bf98dccdd9205bb70793af56fe1397a2b258ae0d",
"_brain-filing-rules.md": "ff42b331bce542d708f97ff0a73ff0fb5664b46ee9b1862a5478b15dc637487e",
diff --git a/src/commands/doctor/checks/atom-fence-rows.ts b/src/commands/doctor/checks/atom-fence-rows.ts
new file mode 100644
index 0000000000..c61a2e42ae
--- /dev/null
+++ b/src/commands/doctor/checks/atom-fence-rows.ts
@@ -0,0 +1,45 @@
+/**
+ * `atom_fence_rows`: world atoms whose title, body or source_quote carries the claim of a fence row their source page
+ * shows only to the owner (repair/atom-fence-rows.ts holds the rule and the scan). A `WAVE_CHECKS` entry, host-only:
+ * `ok` when none; `warn` with the count per source and the read-only preview as fix, never a slug or row text. The
+ * apply narrows the previewed atoms to private and needs the user's agreement on that set. Each statement is bounded
+ * by PLAN_STATEMENT_MS; an overrun reports the count as unknown.
+ */
+import type { BrainEngine } from '../../../core/engine.ts';
+import type { Check } from '../../doctor.ts';
+import { agentFix } from '../check-fix.ts';
+import { findAtomFenceRows } from '../../../core/repair/atom-fence-rows.ts';
+import { PLAN_STATEMENT_MS } from '../../../core/repair/visibility.ts';
+
+const DOCS = 'docs/guides/repair.md#atom-fence-rows';
+
+export async function atomFenceRowsCheck(engine: BrainEngine, sourceIds?: string[]): Promise<Check> {
+ const name = 'atom_fence_rows';
+ try {
+ const sources = sourceIds ?? (await engine.executeRaw<{ id: string }>('SELECT id FROM sources WHERE archived IS NOT TRUE ORDER BY id')).map(row => row.id);
+ const bySource: Array<{ source_id: string; count: number }> = [];
+ let originUnread = 0;
+ for (const source of sources) {
+ const scan = await findAtomFenceRows(engine, [source], { timeoutMs: PLAN_STATEMENT_MS });
+ originUnread += scan.origin_unread;
+ if (scan.atoms.length) bySource.push({ source_id: source, count: scan.atoms.length });
+ }
+ const count = bySource.reduce((sum, row) => sum + row.count, 0);
+ const details = { count, by_source: bySource, origin_unread: originUnread, repair: 'atom-fence-rows', docs: DOCS };
+ if (!count) {
+ return { name, status: 'ok', details, message: 'No world atom carries a fence row its source page shows only to the owner.' };
+ }
+ const preview = ['gbrain', 'repair', 'atom-fence-rows', '--source', bySource[0]!.source_id, '--json'];
+ return { name, status: 'warn', details,
+ message: `${count} world atom(s) carry the claim of a fence row their source page shows only to the owner, so remote callers can read it `
+ + `(${bySource.map(row => `${row.source_id}: ${row.count}`).join('; ')}). Preview them with ${preview.join(' ')} (read-only); `
+ + 'narrow the previewed set to private only after the user agrees.',
+ fix: agentFix(preview, 'Lists each atom with its source page and the fence row kinds and numbers it carries, and prints the apply command bound to that set; '
+ + 'it writes nothing. Narrowing the atoms is the user\'s call: show them the preview before running the apply.', name, { docs: DOCS }) };
+ } catch (error) {
+ const timedOut = (error as { code?: string } | null)?.code === '57014';
+ return { name, status: 'warn', details: { count: 'unknown' },
+ message: timedOut ? `The world atom scan did not finish within ${PLAN_STATEMENT_MS} ms; preview it with gbrain repair atom-fence-rows --source <id>. Health is unknown.`
+ : `World atoms could not be checked for owner-only fence rows: ${error instanceof Error ? error.message : String(error)}. Health is unknown.` };
+ }
+}
diff --git a/src/commands/doctor/checks/graph-health.ts b/src/commands/doctor/checks/graph-health.ts
index 2793146f8d..4dd2795553 100644
--- a/src/commands/doctor/checks/graph-health.ts
+++ b/src/commands/doctor/checks/graph-health.ts
@@ -388,6 +388,7 @@ export const timelineHistoryEntry: DoctorEntry = {
'google_calendar_readable',
'google_api_access',
'atom_retirements_restorable',
+ 'atom_fence_rows',
'generation_retirements',
'generation_held',
'generation_pending',
diff --git a/src/commands/doctor/wave-checks.ts b/src/commands/doctor/wave-checks.ts
index 4300748be7..fdc38b02d0 100644
--- a/src/commands/doctor/wave-checks.ts
+++ b/src/commands/doctor/wave-checks.ts
@@ -338,6 +338,13 @@ export const WAVE_CHECKS: readonly WaveCheckSpec[] = [
impact: 'Some atoms were retired when a re-extraction returned no atoms, and the purge removes them once their hold ends',
run: async (engine, scope) => (await import('./checks/atom-retirements.ts')).atomRetirementsRestorableCheck(engine, scope.sourceIds),
},
+ {
+ id: 'atom_fence_rows', resolution: 'repair', registration: 'wave',
+ hostOnly: 'Narrowing atoms to private is a host-side, explicit-only repair.',
+ count: d => Number(d.count ?? 0),
+ impact: 'Some world atoms carry text of a fence row their source page shows only to the owner',
+ run: async (engine, scope) => (await import('./checks/atom-fence-rows.ts')).atomFenceRowsCheck(engine, scope.sourceIds),
+ },
{
id: 'generation_retirements', resolution: 'repair', registration: 'wave',
hostOnly: 'Restoring a derived generation is a host-side, explicit-only repair.',
diff --git a/src/core/cycle/extract-atoms-input.ts b/src/core/cycle/extract-atoms-input.ts
index d10e1a7b34..f29081f3fb 100644
--- a/src/core/cycle/extract-atoms-input.ts
+++ b/src/core/cycle/extract-atoms-input.ts
@@ -22,6 +22,7 @@ import { truncateUtf8 } from '../text-safe.ts';
import { corpusTextForExtraction } from '../context/corpus-segments.ts';
import { AtomPageStateError, type AtomPageInput } from './extract-atoms-page-state.ts';
import { planExtraction, type ExtractionPlan, type StoredWatermark } from '../extraction-watermark.ts';
+import { publicBody } from '../mentions/aliases.ts';
export const DEFAULT_EXTRACT_MAX_INPUT_CHARS = 50_000;
export const EXTRACT_MAX_INPUT_CHARS_KEY = 'cycle.extract_atoms.max_input_chars';
@@ -65,11 +66,16 @@ export interface ExtractAtomsInput {
* Large pages A7: a page whose stored watermark still matches its body reads
* the text appended since (`watermark`); a tail read is partial input too, so
* the #6503 disposition holds (no completion stamp, nothing retired).
+ * A page is read as a world reader sees it (`publicBody`: facts fence rows
+ * other than world and the takes fence removed), so neither the prompt, the
+ * atoms nor a verified quote can carry a row a remote read of the page hides;
+ * the cap and the watermark apply to that text.
*/
export function extractAtomsInput(item: ExtractAtomsItem, maxInputChars: number, watermark: StoredWatermark | null = null): ExtractAtomsInput {
if (item.kind === 'page') {
- const plan = planExtraction(item.content, watermark, { cap: maxInputChars, pipeline: 'extract_atoms', emptyTail: 'head' });
- return { promptContent: plan.text, truncated: plan.mode !== 'full', inputChars: item.content.length, plan };
+ const body = publicBody(item.content);
+ const plan = planExtraction(body, watermark, { cap: maxInputChars, pipeline: 'extract_atoms', emptyTail: 'head' });
+ return { promptContent: plan.text, truncated: plan.mode !== 'full', inputChars: body.length, plan };
}
const text = corpusTextForExtraction(item.filePath, item.content);
const promptContent = truncateUtf8(text, maxInputChars);
diff --git a/src/core/cycle/extract-atoms.ts b/src/core/cycle/extract-atoms.ts
index f5fc349b6e..1b5362a2f0 100644
--- a/src/core/cycle/extract-atoms.ts
+++ b/src/core/cycle/extract-atoms.ts
@@ -1219,8 +1219,8 @@ export async function runPhaseExtractAtoms(
// #4706: pin the quote to its origin, or don't claim one. Located:
// store the ORIGINAL characters (not the model's rendering, so
// typographic drift can't accumulate) + [start, end) offsets into
- // promptContent — valid against the full item too, because the cut
- // is a prefix. Not located: the model paraphrased; drop the quote
+ // promptContent, the item's extraction input (extract-atoms-input.ts:
+ // a page as a world reader sees it). Not located: the model paraphrased; drop the quote
// rather than persist an unverifiable one (an atom without a
// quotation is honest; one with a fabricated quote is not, and
// body/lesson/concepts stay useful either way). Verified against
diff --git a/src/core/cycle/patterns.ts b/src/core/cycle/patterns.ts
index 842826a20d..b5368ec02f 100644
--- a/src/core/cycle/patterns.ts
+++ b/src/core/cycle/patterns.ts
@@ -33,6 +33,7 @@ import { waitForCompletionRenewing, TimeoutError } from '../minions/wait-for-com
import type { MinionJobInput, MinionJobStatus, SubagentHandlerData } from '../minions/types.ts';
import { parseMarkdown, serializeMarkdown, serializePageToMarkdown } from '../markdown.ts';
import { truncateUtf8 } from '../text-safe.ts';
+import { publicBody } from '../mentions/aliases.ts';
import { PAGE_MAX_BYTES } from '../page-size-policy.ts';
import type { Page, PageType } from '../types.ts';
// #2415: allow-list + output-root resolution shared with the synthesize
@@ -645,7 +646,7 @@ async function gatherReflections(
// leave a lone surrogate. Postgres rejects that when the prompt is bound
// into the minion job's JSONB payload. Use the shared safe truncator so a
// reflection containing emoji cannot abort the entire patterns phase.
- excerpt: truncateUtf8(r.compiled_truth ?? '', 600),
+ excerpt: truncateUtf8(publicBody(r.compiled_truth ?? ''), 600),
seat: r.seat ?? null,
taint: { table: 'pages', id: Number(r.id), tier: storedTrustTier(r.trust_tier) },
}));
@@ -939,7 +940,7 @@ async function loadGroundingSources<T>(engine: BrainEngine, sourceId: string, re
}
body = await (await import('../page-body/ingest.ts')).materializeSegmentedBody(engine, Number(p.id), sourceId);
}
- sources.push(groundSource(p.slug, `${body.compiled_truth}\n\n${body.timeline}`, { tolerant: true }));
+ sources.push(groundSource(p.slug, publicBody(`${body.compiled_truth}\n\n${body.timeline}`), { tolerant: true }));
}
return sources;
}
diff --git a/src/core/cycle/propose-takes.ts b/src/core/cycle/propose-takes.ts
index c8e4e82858..fe0dc4aa90 100644
--- a/src/core/cycle/propose-takes.ts
+++ b/src/core/cycle/propose-takes.ts
@@ -56,6 +56,7 @@ import { GBrainError } from '../types.ts';
import { isConfigTruthy } from '../config.ts';
import { matchingCloseBracket } from '../llm-json.ts';
import { TAKE_KIND_VALUES } from '../takes-fence.ts';
+import { publicBody } from '../mentions/aliases.ts';
import { attributionChecksEnabled } from './attribution-checks.ts';
import { downgradeAssistantOnlyHolders } from './propose-takes-attribution.ts';
import { ProposeTakesFailures, PROPOSE_TAKES_HOLD_RUNS, type FailedPage } from './propose-takes-failures.ts';
@@ -1015,7 +1016,7 @@ class ProposeTakesPhase extends BaseCyclePhase {
try {
proposals = await extractor({
pagePath: page.slug,
- pageBody: body,
+ pageBody: publicBody(body),
existingTakes,
modelHint: opts.model,
// #4494: configurable output caps (see resolution above).
diff --git a/src/core/doctor-categories.ts b/src/core/doctor-categories.ts
index 7f676f4c6a..a08478eaf5 100644
--- a/src/core/doctor-categories.ts
+++ b/src/core/doctor-categories.ts
@@ -59,6 +59,8 @@ export const BRAIN_CHECK_NAMES: ReadonlySet<string> = new Set([
'atom_provenance_drift',
// #7013: atoms an empty managed re-extraction retired that atoms-restore can bring back (doctor/checks/atom-retirements.ts).
'atom_retirements_restorable',
+ // World atoms that carry an owner-only fence row of their source page (doctor/checks/atom-fence-rows.ts).
+ 'atom_fence_rows',
'captured_facts_active',
// #8064: owner-attributed capture facts from agent-launched sessions (doctor/checks/agent-session-facts.ts).
'agent_session_facts',
diff --git a/src/core/persistence/preview-approval.ts b/src/core/persistence/preview-approval.ts
index 517d1114fb..8491bb43e5 100644
--- a/src/core/persistence/preview-approval.ts
+++ b/src/core/persistence/preview-approval.ts
@@ -40,7 +40,7 @@ export const PREVIEW_APPROVAL_OP = 'repair-approval';
/** The default `purgeStaleCheckpoints` TTL; an older approved set may already be gone. */
export const APPROVAL_MAX_AGE_DAYS = 7;
-export type PreviewApprovalCommand = 'authorize-legacy' | 'jobs-cancel' | 'stale-atoms' | 'atoms-restore' | 'extractor-facts' | 'unwithdrawn-facts' | 'conversation-labels' | 'captured-facts' | 'agent-session-facts' | 'redacted-facts' | 'loop-facts' | 'ontology-facts' | 'facts-rehome' | 'consolidate-ties' | 'duplicate-facts' | 'failed-writes' | 'split-facts' | 'frontmatter' | 'fences' | 'slug-conflicts' | 'managed-sync-orphans' | 'frontmatter-keys' | 'file-drift' | 'stuck-recovery' | 'ghost-pages' | 'origin-twins' | 'receipt-compaction' | 'accepted-takes' | 'rename-identity' | 'overwritten-edits' | 'legacy-twins' | 'missing-tables' | 'segmented-mirror' | 'segmented-tiling' | 'uncommitted-deletions' | 'visibility' | 'generations' | 'fact-claim-dates' | 'timeline-order' | 'contact-rows' | 'provenance' | 'secret-spans' | 'rows-behind' | 'private-labels';
+export type PreviewApprovalCommand = 'authorize-legacy' | 'jobs-cancel' | 'stale-atoms' | 'atoms-restore' | 'atom-fence-rows' | 'extractor-facts' | 'unwithdrawn-facts' | 'conversation-labels' | 'captured-facts' | 'agent-session-facts' | 'redacted-facts' | 'loop-facts' | 'ontology-facts' | 'facts-rehome' | 'consolidate-ties' | 'duplicate-facts' | 'failed-writes' | 'split-facts' | 'frontmatter' | 'fences' | 'slug-conflicts' | 'managed-sync-orphans' | 'frontmatter-keys' | 'file-drift' | 'stuck-recovery' | 'ghost-pages' | 'origin-twins' | 'receipt-compaction' | 'accepted-takes' | 'rename-identity' | 'overwritten-edits' | 'legacy-twins' | 'missing-tables' | 'segmented-mirror' | 'segmented-tiling' | 'uncommitted-deletions' | 'visibility' | 'generations' | 'fact-claim-dates' | 'timeline-order' | 'contact-rows' | 'provenance' | 'secret-spans' | 'rows-behind' | 'private-labels';
export interface ApprovedSetKey {
command: PreviewApprovalCommand;
diff --git a/src/core/repair/atom-fence-rows.ts b/src/core/repair/atom-fence-rows.ts
new file mode 100644
index 0000000000..2fd74f04cf
--- /dev/null
+++ b/src/core/repair/atom-fence-rows.ts
@@ -0,0 +1,176 @@
+/**
+ * `gbrain repair atom-fence-rows`: world atoms that carry text of a fence row
+ * their source page shows only to the owner.
+ *
+ * Atoms extracted before the extraction input was the page as a world reader
+ * sees it (extract-atoms-input.ts) could copy such a row into their title, body
+ * or verified `source_quote`, and a world atom serves it to remote callers. A
+ * live page-bound atom stamped `visibility: world` is listed when its title,
+ * body or source_quote contains (case and whitespace folded) the claim of a
+ * facts row of its live source page whose visibility is not world, or of a
+ * takes row whose holder is not world, unless the page's world text
+ * (`publicBody`) holds the same claim too. Claims under MIN_CLAIM_CHARS are
+ * not matched. A source page stored in segments is not read; its atoms are
+ * counted as `origin_unread`.
+ *
+ * Explicit-only and preview-bound: the preview lists each atom with its source
+ * page and the row kinds and numbers it carries, never the row text, and
+ * changes nothing; `--apply --expect <hash>` narrows exactly that set to
+ * `visibility: private` through a revision-bound put_page (re-chunked and
+ * re-embedded by its publication). An atom whose revision, source page or
+ * matched rows changed since reports `changed_since_preview` and is kept.
+ * The same scan backs doctor's `atom_fence_rows` check.
+ */
+import type { BrainEngine } from '../engine.ts';
+import { parseFactsFence } from '../facts-fence.ts';
+import { parseTakesFence } from '../takes-fence.ts';
+import { publicBody } from '../mentions/aliases.ts';
+import { serializePageToMarkdown } from '../markdown.ts';
+import { OperationError } from '../ops/contract.ts';
+import { submitPageMutation } from '../persistence/page-mutations.ts';
+import { clearApprovedSet, loadApprovedSet, previewChangedError, previewHash, saveApprovedSet } from '../persistence/preview-approval.ts';
+import { afterCursor, repairRequestId, type RepairHandler, type RepairItem, type RepairItemOutcome, type RepairPlan, type RepairScope } from './core.ts';
+
+export const MIN_CLAIM_CHARS = 12;
+const BATCH = 500;
+
+export interface HiddenRowMatch { kind: 'facts' | 'takes'; row: number }
+
+export interface AtomFenceRow {
+ id: number;
+ source_id: string;
+ slug: string;
+ revision: string;
+ origin_slug: string;
+ origin_id: number;
+ origin_hash: string | null;
+ rows: HiddenRowMatch[];
+}
+
+interface ScanOptions { atomId?: number; timeoutMs?: number }
+
+const fold = (text: string) => text.replace(/~~/g, '').replace(/\s+/g, ' ').trim().toLowerCase();
+
+/** Claims of the page's facts rows other than world and takes rows held by someone other than world, absent from its world text. */
+function hiddenRows(body: string): Array<HiddenRowMatch & { claim: string }> {
+ const world = fold(publicBody(body));
+ const rows = [
+ ...parseFactsFence(body).facts.filter(f => f.visibility !== 'world').map(f => ({ kind: 'facts' as const, row: f.rowNum, claim: fold(f.claim) })),
+ ...parseTakesFence(body).takes.filter(t => t.holder !== 'world').map(t => ({ kind: 'takes' as const, row: t.rowNum, claim: fold(t.claim) })),
+ ];
+ return rows.filter(r => r.claim.length >= MIN_CLAIM_CHARS && !world.includes(r.claim));
+}
+
+/**
+ * World atoms of these sources that carry a hidden row of their source page, in id order, and the number of world
+ * atoms whose source page is stored in segments (not read). One keyset-paged pass over the sources' world atoms whose
+ * source page names a facts or takes fence, plus one read of each such page.
+ */
+export async function findAtomFenceRows(engine: BrainEngine, sourceIds: string[], opts: ScanOptions = {}): Promise<{ atoms: AtomFenceRow[]; origin_unread: number }> {
+ const atoms: AtomFenceRow[] = [];
+ const origins = new Map<number, Array<HiddenRowMatch & { claim: string }>>();
+ let originUnread = 0;
+ let after = 0;
+ for (;;) {
+ const rows = await engine.executeRaw<{ id: number; source_id: string; slug: string; revision: string; text: string; origin_id: number; origin_slug: string;
+ origin_hash: string | null; origin_unread: boolean }>(
+ `SELECT a.id, a.source_id, a.slug, a.knowledge_revision::text AS revision,
+ concat_ws(E'\\n', a.title, a.compiled_truth, a.frontmatter->>'source_quote') AS text,
+ o.id AS origin_id, o.slug AS origin_slug, o.content_hash AS origin_hash, o.compiled_truth IS NULL AS origin_unread
+ FROM pages a
+ JOIN pages o ON o.source_id=a.source_id AND o.slug=a.frontmatter->>'source_slug' AND o.deleted_at IS NULL
+ WHERE a.source_id=ANY($1::text[]) AND a.type='atom' AND a.deleted_at IS NULL AND a.frontmatter->>'visibility'='world'
+ AND ($2::int IS NULL OR a.id=$2::int) AND a.id>$3
+ AND (o.compiled_truth IS NULL OR strpos(o.compiled_truth, 'gbrain:facts:begin')>0 OR strpos(o.compiled_truth, 'gbrain:takes:begin')>0)
+ ORDER BY a.id LIMIT $4`, [sourceIds, opts.atomId ?? null, after, BATCH], opts.timeoutMs ? { timeoutMs: opts.timeoutMs } : undefined);
+ if (!rows.length) break;
+ const unseen = [...new Set(rows.filter(r => !r.origin_unread).map(r => Number(r.origin_id)))].filter(id => !origins.has(id));
+ if (unseen.length) {
+ const bodies = await engine.executeRaw<{ id: number; body: string | null }>('SELECT id, compiled_truth AS body FROM pages WHERE id=ANY($1::int[])',
+ [unseen], opts.timeoutMs ? { timeoutMs: opts.timeoutMs } : undefined);
+ for (const page of bodies) origins.set(Number(page.id), hiddenRows(page.body ?? ''));
+ }
+ for (const row of rows) {
+ if (row.origin_unread) { originUnread++; continue; }
+ const text = fold(row.text ?? '');
+ const matched = (origins.get(Number(row.origin_id)) ?? []).filter(hidden => text.includes(hidden.claim)).map(({ kind, row: n }) => ({ kind, row: n }));
+ if (matched.length) atoms.push({ id: Number(row.id), source_id: row.source_id, slug: row.slug, revision: row.revision, origin_slug: row.origin_slug,
+ origin_id: Number(row.origin_id), origin_hash: row.origin_hash, rows: matched });
+ }
+ after = Number(rows.at(-1)!.id);
+ if (rows.length < BATCH) break;
+ }
+ return { atoms, origin_unread: originUnread };
+}
+
+export function atomFenceRowsPreviewCommand(sourceIds: string[]): string {
+ return `gbrain repair atom-fence-rows${sourceIds.length === 1 ? ` --source ${sourceIds[0]}` : ''}`;
+}
+
+interface AtomFenceRowItem extends RepairItem { atom: AtomFenceRow; hash: string; last: boolean }
+
+interface ApprovedAtom extends AtomFenceRow { selection: string[] }
+
+const rowLabel = (atom: AtomFenceRow) => atom.rows.map(r => `${r.kind} row ${r.row}`).join(', ');
+
+const sameAtom = (live: AtomFenceRow | undefined, approved: AtomFenceRow) => !!live
+ && (['id', 'source_id', 'slug', 'revision', 'origin_slug', 'origin_id', 'origin_hash'] as const).every(field => live[field] === approved[field])
+ && rowLabel(live) === rowLabel(approved);
+
+function item(atom: AtomFenceRow, hash: string, last: boolean): AtomFenceRowItem {
+ return { cursor: { phase: 1, id: atom.id }, source_id: atom.source_id, slug: atom.slug, chars: 0,
+ action: 'narrow:private', change: { from: 'world', to: 'private' }, atom, hash, last };
+}
+
+async function hashParts(engine: BrainEngine, scope: RepairScope, atoms: AtomFenceRow[]) {
+ const sources = await engine.executeRaw<{ id: string; incarnation: string }>(
+ 'SELECT id, incarnation::text AS incarnation FROM sources WHERE id=ANY($1::text[]) ORDER BY id', [scope.source_ids]);
+ return { kind: 'atom-fence-rows-v1', brain_id: scope.brain_id, sources, selection: { source_ids: scope.source_ids }, atoms };
+}
+
+export const atomFenceRowsRepair: RepairHandler = {
+ kind: 'atom-fence-rows',
+ async plan(engine, scope, after, opts): Promise<RepairPlan> {
+ const command = atomFenceRowsPreviewCommand(scope.source_ids);
+ if (!opts?.apply) {
+ const { atoms, origin_unread } = await findAtomFenceRows(engine, scope.source_ids);
+ const hash = previewHash(await hashParts(engine, scope, atoms));
+ if (atoms.length) await saveApprovedSet<ApprovedAtom>(engine, { command: 'atom-fence-rows', hash }, atoms.map(atom => ({ ...atom, selection: scope.source_ids })));
+ return { items: atoms.map((atom, index) => item(atom, hash, index === atoms.length - 1)), preview_hash: hash,
+ residuals: { origin_unread },
+ listing: atoms.map(atom => ({ item: `${atom.source_id}:${atom.slug}`, class: [...new Set(atom.rows.map(r => r.kind))].join('+'),
+ detail: `source page ${atom.origin_slug}: ${rowLabel(atom)}` })) };
+ }
+ if (!opts.expect) {
+ throw new OperationError('invalid_params', 'gbrain repair atom-fence-rows --apply narrows only the set a preview printed.',
+ `Preview first: ${command} — then run the apply command it prints: ${command} --apply --expect <preview-hash>`,
+ 'docs/guides/repair.md#atom-fence-rows');
+ }
+ const approved = await loadApprovedSet<ApprovedAtom>(engine, { command: 'atom-fence-rows', hash: opts.expect, previewCommand: command,
+ emptyHash: async () => previewHash(await hashParts(engine, scope, [])) });
+ if (approved.items.some(atom => JSON.stringify(atom.selection) !== JSON.stringify(scope.source_ids))) throw previewChangedError(opts.expect, command);
+ const items = approved.items.map(({ selection: _selection, ...atom }, index) => item(atom, opts.expect!, index === approved.items.length - 1));
+ return { items: items.filter(entry => afterCursor(entry.cursor, after)), preview_hash: opts.expect, residuals: {} };
+ },
+ async apply(ctx, entry): Promise<RepairItemOutcome> {
+ const { atom, hash, last } = entry as AtomFenceRowItem;
+ try {
+ const changed = (reason: string): RepairItemOutcome => ({ applied: false, outcome: 'changed_since_preview', reason });
+ if (!sameAtom((await findAtomFenceRows(ctx.engine, [atom.source_id], { atomId: atom.id })).atoms[0], atom)) return changed('the atom, its source page or the rows it carries changed');
+ const snapshot = await ctx.engine.readPageSnapshot(atom.slug, { sourceId: atom.source_id });
+ if (!snapshot || Number(snapshot.page.id) !== atom.id || snapshot.revision !== atom.revision) return changed('the atom changed');
+ const page = { ...snapshot.page, frontmatter: { ...snapshot.page.frontmatter, visibility: 'private' } };
+ await submitPageMutation(ctx, { operation: 'put_page', params: { slug: atom.slug, source_id: atom.source_id,
+ content: serializePageToMarkdown(page, snapshot.tags), expected_revision: snapshot.revision,
+ request_id: await repairRequestId(ctx, 'atom-fence-rows', entry, snapshot.revision) } });
+ return { applied: true, outcome: 'narrowed' };
+ } catch (error) {
+ if (error instanceof OperationError && ['revision_conflict', 'page_not_found', 'page_identity_changed'].includes(error.code)) {
+ return { applied: false, outcome: 'changed_since_preview', reason: error.message };
+ }
+ throw error;
+ } finally {
+ if (last) await clearApprovedSet(ctx.engine, { command: 'atom-fence-rows', hash });
+ }
+ },
+};
diff --git a/src/core/repair/core.ts b/src/core/repair/core.ts
index 346ed9c9d5..e264dbe0f3 100644
--- a/src/core/repair/core.ts
+++ b/src/core/repair/core.ts
@@ -52,7 +52,7 @@ import type { ProgressReporter } from '../progress.ts';
import type { GenerationsSelection } from '../generations/repair.ts';
import type { PrivateLabelsLedger } from './private-labels.ts';
-export const REPAIR_KINDS = ['timeline', 'visibility', 'safe-chunks', 'contextual-mode', 'connector-checkpoints', 'request-indexes', 'connector-fences', 'take-supersession', 'accepted-takes', 'orphan-bindings', 'embedding-effects', 'attribution-backfill', 'planner-stats', 'google-file-modes', 'stale-atoms', 'atoms-restore', 'extractor-facts', 'unwithdrawn-facts', 'conversation-labels', 'captured-facts', 'agent-session-facts', 'redacted-facts', 'loop-facts', 'ontology-facts', 'facts-rehome', 'consolidate-ties', 'duplicate-facts', 'orphan-children', 'failed-writes', 'split-facts', 'frontmatter', 'fences', 'slug-conflicts', 'timeline-comments', 'timeline-order', 'contact-rows', 'managed-sync-orphans', 'content-receipt-root', 'frontmatter-keys', 'file-drift', 'stuck-recovery', 'ghost-pages', 'origin-twins', 'receipt-compaction', 'aliases', 'rename-identity', 'overwritten-edits', 'legacy-twins', 'missing-tables', 'url-clone-fences', 'segmented-mirror', 'segmented-tiling', 'uncommitted-deletions', 'generations', 'fact-claim-dates', 'provenance', 'secret-spans', 'rows-behind', 'access', 'private-labels'] as const;
+export const REPAIR_KINDS = ['timeline', 'visibility', 'safe-chunks', 'contextual-mode', 'connector-checkpoints', 'request-indexes', 'connector-fences', 'take-supersession', 'accepted-takes', 'orphan-bindings', 'embedding-effects', 'attribution-backfill', 'planner-stats', 'google-file-modes', 'stale-atoms', 'atoms-restore', 'atom-fence-rows', 'extractor-facts', 'unwithdrawn-facts', 'conversation-labels', 'captured-facts', 'agent-session-facts', 'redacted-facts', 'loop-facts', 'ontology-facts', 'facts-rehome', 'consolidate-ties', 'duplicate-facts', 'orphan-children', 'failed-writes', 'split-facts', 'frontmatter', 'fences', 'slug-conflicts', 'timeline-comments', 'timeline-order', 'contact-rows', 'managed-sync-orphans', 'content-receipt-root', 'frontmatter-keys', 'file-drift', 'stuck-recovery', 'ghost-pages', 'origin-twins', 'receipt-compaction', 'aliases', 'rename-identity', 'overwritten-edits', 'legacy-twins', 'missing-tables', 'url-clone-fences', 'segmented-mirror', 'segmented-tiling', 'uncommitted-deletions', 'generations', 'fact-claim-dates', 'provenance', 'secret-spans', 'rows-behind', 'access', 'private-labels'] as const;
export type RepairKind = typeof REPAIR_KINDS[number];
export interface RepairScope { brain_id: string; source_ids: string[] }
diff --git a/src/core/repair/registry.ts b/src/core/repair/registry.ts
index 5df44750c1..3208fa4621 100644
--- a/src/core/repair/registry.ts
+++ b/src/core/repair/registry.ts
@@ -54,6 +54,7 @@ import { embeddingEffectsRepair } from './embedding-effects.ts';
import { googleFileModesRepair } from './google-file-modes.ts';
import { staleAtomsRepair } from './stale-atoms.ts';
import { atomsRestoreRepair } from './atoms-restore.ts';
+import { atomFenceRowsRepair } from './atom-fence-rows.ts';
import { extractorFactsRepair } from './extractor-facts.ts';
import { unwithdrawnFactsRepair } from './unwithdrawn-facts.ts';
import { conversationLabelsRepair } from './conversation-labels.ts';
@@ -224,6 +225,14 @@ const SPECS: Record<RepairKind, Omit<RepairKindSpec, 'kind'>> = {
+ 'that writes the canonical file back, its request id in the outcome); an atom that changed since reports changed_since_preview and stays deleted. '
+ 'The purge holds these atoms for 30 days after deletion. Runs only when named; never on upgrade.',
},
+ 'atom-fence-rows': {
+ handler: atomFenceRowsRepair, embeds: 'effect', checks: ['atom_fence_rows'], explicit_only: true, preview_bound: true,
+ summary: 'Narrow to private the world atoms whose title, body or source_quote carries the claim of a fence row their source page shows only to the owner '
+ + '(a facts row whose visibility is not world, a takes row whose holder is not world), copied by an extraction that read the whole page. The preview lists '
+ + 'each atom with its source page and the row kinds and numbers, never the row text, and changes nothing. Preview-bound: --apply --expect <hash> sets '
+ + 'visibility: private on exactly the previewed set through a revision-bound put_page; an atom that changed since reports changed_since_preview. '
+ + 'Source pages stored in segments are not read (origin_unread). Runs only when named; never on upgrade.',
+ },
'extractor-facts': {
handler: extractorFactsRepair, embeds: 'none', checks: ['extractor_facts_expired'], explicit_only: true,
summary: 'Restore conversation-extractor facts that the pre-v0.60.11.0 canonical projection expired (#5731). Restores only facts with receipt evidence '
diff --git a/test/cycle-world-fence-rows.test.ts b/test/cycle-world-fence-rows.test.ts
new file mode 100644
index 0000000000..ebe28dcd6e
--- /dev/null
+++ b/test/cycle-world-fence-rows.test.ts
@@ -0,0 +1,84 @@
+/**
+ * Dream phases that read page bodies never carry a non-world fence row into
+ * what they produce.
+ *
+ * propose_takes sends a page's prose to the extractor model and files what it
+ * returns as take proposals; patterns sends each reflection's excerpt to its
+ * subagent, which writes world pattern pages, and grounds those pages' quotes
+ * against the reflections. Each reads the page as a world reader sees it
+ * (facts rows other than world and the takes fence removed), so a hidden row
+ * never reaches the extractor, a proposal, the subagent prompt, or a quote
+ * certified as verified. PGLite and Postgres.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import type { BrainEngine } from '../src/core/engine.ts';
+import type { OperationContext } from '../src/core/ops/contract.ts';
+import { importFromContent } from '../src/core/import-file.ts';
+import { runPhaseProposeTakes, type ProposeTakesExtractor } from '../src/core/cycle/propose-takes.ts';
+import { __testing, groundPatternPages } from '../src/core/cycle/patterns.ts';
+import { isolatedSharedSkillsEngine } from './helpers/shared-skills-engine.ts';
+import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';
+import { FENCES, HIDDEN_TAKE_ROW, PRIVATE_ROW, WORLD_PAGE_BODY, WORLD_ROW } from './helpers/world-fence-page.ts';
+
+const REFLECTION = 'wiki/personal/reflections/launch-week';
+const PATTERN = 'wiki/personal/patterns/launch-checklists';
+
+for (const backend of testBackends()) {
+ describe(`dream phases read a world page without its non-world fence rows (${backend})`, () => {
+ let engine: BrainEngine;
+ let close: () => Promise<void>;
+
+ beforeAll(async () => {
+ ({ engine, close } = await isolatedSharedSkillsEngine(backend === 'postgres' ? requirePostgresTestDatabase() : undefined));
+ await engine.putPage('notes/launch-review', { type: 'note', title: 'Launch review', compiled_truth: WORLD_PAGE_BODY, timeline: '' }, { sourceId: 'default' });
+ await importFromContent(engine, REFLECTION,
+ `---\ntype: note\ntitle: Launch week\n---\nI keep writing "ship the checklist first" when a launch slips.\n\n${FENCES}`,
+ { noEmbed: true, sourceId: 'default' });
+ }, 120_000);
+ afterAll(async () => { await close?.(); });
+
+ test('propose_takes: the extractor input and the proposals hold only world rows', async () => {
+ const bodies: string[] = [];
+ const extractor: ProposeTakesExtractor = async ({ pageBody }) => {
+ bodies.push(pageBody);
+ return [WORLD_ROW, PRIVATE_ROW, HIDDEN_TAKE_ROW].filter(row => pageBody.includes(row))
+ .map(row => ({ claim_text: row, kind: 'take' as const, holder: 'world', weight: 0.6 }));
+ };
+ const ctx: OperationContext = { engine, config: {} as never, logger: { info() {}, warn() {}, error() {} } as never, dryRun: false, remote: false, sourceId: 'default' };
+ await runPhaseProposeTakes(ctx, { extractor, deadlineMs: 600_000 });
+ const proposals = (await engine.executeRaw<{ claim_text: string }>(
+ "SELECT claim_text FROM take_proposals WHERE page_slug='notes/launch-review'")).map(row => row.claim_text);
+ expect(proposals).not.toContain(PRIVATE_ROW);
+ expect(proposals).not.toContain(HIDDEN_TAKE_ROW);
+ expect(proposals).toContain(WORLD_ROW);
+ expect(bodies.length).toBeGreaterThan(0);
+ for (const body of bodies) {
+ expect(body).not.toContain(PRIVATE_ROW);
+ expect(body).not.toContain(HIDDEN_TAKE_ROW);
+ }
+ }, 120_000);
+
+ test('patterns: the subagent prompt holds only world rows of a reflection', async () => {
+ const reflections = await __testing.gatherReflections(engine, 30, 'wiki/personal/reflections', 'default');
+ const reflection = reflections.find(r => r.slug === REFLECTION)!;
+ expect(reflection.excerpt).toContain(WORLD_ROW);
+ const prompt = __testing.buildPatternsPrompt(reflections, 1, 'wiki/personal/reflections', 'wiki/personal/patterns', '2026-11-09');
+ expect(prompt).not.toContain(PRIVATE_ROW);
+ expect(prompt).not.toContain(HIDDEN_TAKE_ROW);
+ });
+
+ test('patterns: quote grounding never certifies a quote only a hidden row holds', async () => {
+ await engine.setConfig('dream.quote_verify', 'true');
+ await importFromContent(engine, PATTERN,
+ `---\ntype: note\ntitle: Launch checklists\ndream_generated: true\n---\nYou wrote "ship the checklist first" and "${WORLD_ROW}".\n\nYou also noted "${PRIVATE_ROW}".\n`,
+ { noEmbed: true, sourceId: 'default' });
+ const reflections = [{ slug: REFLECTION, title: 'Launch week', excerpt: '', updatedAt: new Date(), seat: null }];
+ const stats = await groundPatternPages(engine, null, [{ slug: PATTERN, source_id: 'default' }], reflections, 'wiki/personal/patterns', 'default', '2026-11-09');
+ const page = (await engine.getPage(PATTERN, { sourceId: 'default' }))!;
+ expect(page.compiled_truth).not.toContain(PRIVATE_ROW);
+ expect(page.compiled_truth).toContain('ship the checklist first');
+ expect(page.compiled_truth).toContain(WORLD_ROW);
+ expect(stats).toMatchObject({ pages: 1, quarantined: 1 });
+ });
+ });
+}
diff --git a/test/extract-atoms-world-fence-rows.test.ts b/test/extract-atoms-world-fence-rows.test.ts
new file mode 100644
index 0000000000..421295041d
--- /dev/null
+++ b/test/extract-atoms-world-fence-rows.test.ts
@@ -0,0 +1,137 @@
+/**
+ * Atoms extracted from a world page never carry a non-world fence row.
+ *
+ * A world page's facts fence may hold rows marked `visibility: private`, and its
+ * takes fence is never part of the page text a remote caller reads. The
+ * extraction input is the page as a world reader sees it (the facts fence keeps
+ * only world rows, the takes fence is dropped), so neither the model prompt nor
+ * the atom it returns (title, body, verified source_quote) can hold a hidden
+ * row, and a remote get_page of the atom returns none of it.
+ *
+ * The stub model copies every fence row it is shown into an atom, so a hidden
+ * row that reached the prompt would reach the atom. PGLite and Postgres, the
+ * unmanaged cycle phase (page discovery) and a managed brain (origin
+ * publication through the coordinator).
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import type { ChatOpts, ChatResult } from '../src/core/ai/gateway.ts';
+import { runPhaseExtractAtoms } from '../src/core/cycle/extract-atoms.ts';
+import { dispatchToolCall } from '../src/mcp/dispatch.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { managedBrain } from './helpers/managed-brain.ts';
+import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';
+import { HIDDEN_TAKE_ROW, PRIVATE_ROW, WORLD_ROW, WORLD_PAGE_BODY as BODY } from './helpers/world-fence-page.ts';
+
+const SLUG = 'notes/launch-review';
+
+/** A model that turns every fence row it is shown into an atom quoting that row verbatim. */
+function copyingChat() {
+ const prompts: string[] = [];
+ const chat = async (opts: ChatOpts): Promise<ChatResult> => {
+ const last = opts.messages[opts.messages.length - 1];
+ const prompt = typeof last.content === 'string' ? last.content : JSON.stringify(last.content);
+ prompts.push(prompt);
+ const rows = [WORLD_ROW, PRIVATE_ROW, HIDDEN_TAKE_ROW].filter(row => prompt.includes(row));
+ const atoms = [
+ { title: 'Measure every launch', body: 'Measure every launch against clear exit criteria.', atom_type: 'insight',
+ source_quote: 'the team measures every launch against clear exit criteria' },
+ ...rows.map((row, i) => ({ title: `Row ${i + 1}: ${row}`, body: `Recorded on the page: ${row}.`, atom_type: 'insight', source_quote: row })),
+ ];
+ const text = JSON.stringify(atoms);
+ return { text, blocks: [{ type: 'text', text }], stopReason: 'end',
+ usage: { input_tokens: 10, output_tokens: 10, cache_read_tokens: 0, cache_creation_tokens: 0 }, model: 'anthropic:claude-haiku-4-5', providerId: 'anthropic' };
+ };
+ return { prompts, chat };
+}
+
+const atomsOf = (engine: BrainEngine, sourceId: string) =>
+ engine.executeRaw<{ slug: string; title: string; compiled_truth: string; visibility: string | null; source_quote: string | null }>(
+ `SELECT slug, title, compiled_truth, frontmatter->>'visibility' AS visibility, frontmatter->>'source_quote' AS source_quote
+ FROM pages WHERE source_id=$1 AND type='atom' AND deleted_at IS NULL AND frontmatter->>'source_slug'=$2 ORDER BY slug`, [sourceId, SLUG]);
+
+async function remoteGet(engine: BrainEngine, sourceId: string, slug: string): Promise<string> {
+ const out = await dispatchToolCall(engine, 'get_page', { slug }, { remote: true, transport: 'stdio', sourceId, takesHoldersAllowList: ['world'] });
+ return out.content.map(c => c.text).join('\n');
+}
+
+async function expectOnlyWorldRows(engine: BrainEngine, sourceId: string, prompts: string[], backend: string) {
+ const atoms = await atomsOf(engine, sourceId);
+ expect(atoms.length, backend).toBeGreaterThan(0);
+ for (const atom of atoms) {
+ expect(atom.visibility, backend).toBe('world');
+ const remote = await remoteGet(engine, sourceId, atom.slug);
+ expect(remote, backend).not.toContain(PRIVATE_ROW);
+ expect(remote, backend).not.toContain(HIDDEN_TAKE_ROW);
+ for (const text of [atom.title, atom.compiled_truth, atom.source_quote ?? '']) {
+ expect(text, backend).not.toContain(PRIVATE_ROW);
+ expect(text, backend).not.toContain(HIDDEN_TAKE_ROW);
+ }
+ }
+ expect(atoms.some(atom => atom.source_quote === WORLD_ROW), backend).toBe(true);
+ expect(prompts.length, backend).toBeGreaterThan(0);
+ for (const prompt of prompts) {
+ expect(prompt, backend).not.toContain(PRIVATE_ROW);
+ expect(prompt, backend).not.toContain(HIDDEN_TAKE_ROW);
+ expect(prompt, backend).toContain(WORLD_ROW);
+ }
+ // Control: the source page itself reads back remotely with its world row and without the hidden ones.
+ const source = await remoteGet(engine, sourceId, SLUG);
+ expect(source, backend).toContain(WORLD_ROW);
+ expect(source, backend).not.toContain(PRIVATE_ROW);
+}
+
+describe('atoms extracted from a world page never carry a non-world fence row', () => {
+ const engines: Array<{ backend: string; engine: BrainEngine }> = [];
+ let closePostgres: (() => Promise<void>) | undefined;
+
+ beforeAll(async () => {
+ for (const backend of testBackends()) {
+ if (backend === 'pglite') {
+ const engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ engines.push({ backend, engine });
+ } else {
+ const isolated = await isolatedPersistencePostgres(requirePostgresTestDatabase());
+ engines.push({ backend, engine: isolated.engine });
+ closePostgres = isolated.close;
+ }
+ }
+ }, 120_000);
+ afterAll(async () => {
+ for (const { engine } of engines) { await disposePersistenceConsumer(engine); await engine.disconnect(); }
+ await closePostgres?.();
+ });
+
+ test('cycle phase: the prompt, the atoms and a remote read of each atom hold only world rows', async () => {
+ for (const { backend, engine } of engines) {
+ const sourceId = `world-rows-${backend}`;
+ await engine.executeRaw('INSERT INTO sources(id,name) VALUES($1,$1)', [sourceId]);
+ await engine.putPage(SLUG, { type: 'note', title: 'Launch review', compiled_truth: BODY, timeline: '' }, { sourceId });
+ const { prompts, chat } = copyingChat();
+ const result = await runPhaseExtractAtoms(engine, { sourceId, _chat: chat, _transcripts: [] });
+ expect(result.status, backend).toBe('ok');
+ await expectOnlyWorldRows(engine, sourceId, prompts, backend);
+ }
+ }, 120_000);
+
+ test('managed brain: the published atoms hold only world rows', async () => {
+ for (const backend of testBackends()) {
+ const databaseUrl = backend === 'postgres' ? requirePostgresTestDatabase() : undefined;
+ await managedBrain(async ({ engine }) => {
+ const page = (await engine.getPage(SLUG, { sourceId: 'default' }))!;
+ const { prompts, chat } = copyingChat();
+ const result = await runPhaseExtractAtoms(engine, { sourceId: 'default', _chat: chat, _transcripts: [],
+ _pages: [{ slug: SLUG, content: page.compiled_truth, contentHash: page.content_hash! }] });
+ await disposePersistenceConsumer(engine);
+ expect(result.status, backend).toBe('ok');
+ await expectOnlyWorldRows(engine, 'default', prompts, backend);
+ }, { databaseUrl, setup: async ({ engine }) => {
+ await engine.putPage(SLUG, { type: 'note', title: 'Launch review', compiled_truth: BODY, timeline: '' }, { sourceId: 'default' });
+ } });
+ }
+ }, 180_000);
+});
diff --git a/test/fix-wave-5-integration.test.ts b/test/fix-wave-5-integration.test.ts
index eead4303dc..54d64b45ff 100644
--- a/test/fix-wave-5-integration.test.ts
+++ b/test/fix-wave-5-integration.test.ts
@@ -193,7 +193,7 @@ for (const backend of testBackends()) {
const liveAtoms = async () => (await engine.executeRaw<{ n: number }>("SELECT count(*)::int AS n FROM pages WHERE type='atom' AND deleted_at IS NULL"))[0].n;
const activeFacts = async () => (await engine.executeRaw<{ n: number }>("SELECT count(*)::int AS n FROM facts WHERE source_markdown_slug='conversations/expired' AND expired_at IS NULL"))[0].n;
const untouched = async () => { expect(await liveAtoms()).toBe(30); expect(await activeFacts()).toBe(0); };
- const previews = { 'accepted-takes': 'gbrain repair accepted-takes', 'google-file-modes': 'gbrain repair google-file-modes', 'stale-atoms': 'gbrain repair stale-atoms', 'atoms-restore': 'gbrain repair atoms-restore', 'extractor-facts': 'gbrain repair extractor-facts', 'unwithdrawn-facts': 'gbrain repair unwithdrawn-facts',
+ const previews = { 'accepted-takes': 'gbrain repair accepted-takes', 'google-file-modes': 'gbrain repair google-file-modes', 'stale-atoms': 'gbrain repair stale-atoms', 'atoms-restore': 'gbrain repair atoms-restore', 'atom-fence-rows': 'gbrain repair atom-fence-rows', 'extractor-facts': 'gbrain repair extractor-facts', 'unwithdrawn-facts': 'gbrain repair unwithdrawn-facts',
'conversation-labels': 'gbrain repair conversation-labels', 'captured-facts': 'gbrain repair captured-facts', 'agent-session-facts': 'gbrain repair agent-session-facts', 'redacted-facts': 'gbrain repair redacted-facts', 'loop-facts': 'gbrain repair loop-facts', 'ontology-facts': 'gbrain repair ontology-facts', 'facts-rehome': 'gbrain repair facts-rehome', 'consolidate-ties': 'gbrain repair consolidate-ties', 'duplicate-facts': 'gbrain repair duplicate-facts', 'orphan-children': 'gbrain repair orphan-children', 'failed-writes': 'gbrain repair failed-writes', 'split-facts': 'gbrain repair split-facts',
frontmatter: 'gbrain repair frontmatter', 'timeline-comments': 'gbrain repair timeline-comments', 'timeline-order': 'gbrain repair timeline-order', 'contact-rows': 'gbrain repair contact-rows', 'managed-sync-orphans': 'gbrain repair managed-sync-orphans', 'content-receipt-root': 'gbrain repair content-receipt-root', 'frontmatter-keys': 'gbrain repair frontmatter-keys', 'file-drift': 'gbrain repair file-drift',
'stuck-recovery': 'gbrain repair stuck-recovery', 'ghost-pages': 'gbrain repair ghost-pages', 'origin-twins': 'gbrain repair origin-twins', 'receipt-compaction': 'gbrain repair receipt-compaction', aliases: 'gbrain repair aliases', 'rename-identity': 'gbrain repair rename-identity',
diff --git a/test/fixtures/goldens/doctor/content-pglite-human.json b/test/fixtures/goldens/doctor/content-pglite-human.json
index 4e25de0931..62ba0260df 100644
--- a/test/fixtures/goldens/doctor/content-pglite-human.json
+++ b/test/fixtures/goldens/doctor/content-pglite-human.json
@@ -138,6 +138,7 @@
" [OK] google_calendar_readable: No Google source recorded an unreadable calendar at its last sync.",
" [OK] google_api_access: No Google source recorded a disabled API or missing scope at its last sync.",
" [OK] atom_retirements_restorable: No atom retired by an empty re-extraction is waiting to be restored.",
+ " [OK] atom_fence_rows: No world atom carries a fence row its source page shows only to the owner.",
" [OK] generation_retirements: No live generation retired items in the last 30 day(s).",
" [OK] generation_held: No derived generation is held.",
" [OK] generation_pending: No activated generation waits on a member request, and no orphan candidate exists.",
diff --git a/test/fixtures/goldens/doctor/content-pglite-json.json b/test/fixtures/goldens/doctor/content-pglite-json.json
index 63bb1b5937..ad26231f39 100644
--- a/test/fixtures/goldens/doctor/content-pglite-json.json
+++ b/test/fixtures/goldens/doctor/content-pglite-json.json
@@ -1845,6 +1845,20 @@
"name": "atom_retirements_restorable",
"status": "ok"
},
+ {
+ "category": "brain",
+ "details": {
+ "by_source": [],
+ "count": 0,
+ "docs": "docs/guides/repair.md#atom-fence-rows",
+ "origin_unread": 0,
+ "repair": "atom-fence-rows"
+ },
+ "elapsed_ms": "<volatile>",
+ "message": "No world atom carries a fence row its source page shows only to the owner.",
+ "name": "atom_fence_rows",
+ "status": "ok"
+ },
{
"category": "brain",
"details": {
diff --git a/test/fixtures/goldens/doctor/hot-checks-pglite-json.json b/test/fixtures/goldens/doctor/hot-checks-pglite-json.json
index 0bf4f033b0..ba2da3b7a0 100644
--- a/test/fixtures/goldens/doctor/hot-checks-pglite-json.json
+++ b/test/fixtures/goldens/doctor/hot-checks-pglite-json.json
@@ -2024,6 +2024,20 @@
"name": "atom_retirements_restorable",
"status": "ok"
},
+ {
+ "category": "brain",
+ "details": {
+ "by_source": [],
+ "count": 0,
+ "docs": "docs/guides/repair.md#atom-fence-rows",
+ "origin_unread": 0,
+ "repair": "atom-fence-rows"
+ },
+ "elapsed_ms": "<volatile>",
+ "message": "No world atom carries a fence row its source page shows only to the owner.",
+ "name": "atom_fence_rows",
+ "status": "ok"
+ },
{
"category": "brain",
"details": {
@@ -7121,6 +7135,20 @@
"name": "atom_retirements_restorable",
"status": "ok"
},
+ {
+ "category": "brain",
+ "details": {
+ "by_source": [],
+ "count": 0,
+ "docs": "docs/guides/repair.md#atom-fence-rows",
+ "origin_unread": 0,
+ "repair": "atom-fence-rows"
+ },
+ "elapsed_ms": "<volatile>",
+ "message": "No world atom carries a fence row its source page shows only to the owner.",
+ "name": "atom_fence_rows",
+ "status": "ok"
+ },
{
"category": "brain",
"details": {
diff --git a/test/fixtures/goldens/doctor/hot-checks-postgres-json.json b/test/fixtures/goldens/doctor/hot-checks-postgres-json.json
index 8efd132b9c..736fe7416e 100644
--- a/test/fixtures/goldens/doctor/hot-checks-postgres-json.json
+++ b/test/fixtures/goldens/doctor/hot-checks-postgres-json.json
@@ -2029,6 +2029,20 @@
"name": "atom_retirements_restorable",
"status": "ok"
},
+ {
+ "category": "brain",
+ "details": {
+ "by_source": [],
+ "count": 0,
+ "docs": "docs/guides/repair.md#atom-fence-rows",
+ "origin_unread": 0,
+ "repair": "atom-fence-rows"
+ },
+ "elapsed_ms": "<volatile>",
+ "message": "No world atom carries a fence row its source page shows only to the owner.",
+ "name": "atom_fence_rows",
+ "status": "ok"
+ },
{
"category": "brain",
"details": {
@@ -7127,6 +7141,20 @@
"name": "atom_retirements_restorable",
"status": "ok"
},
+ {
+ "category": "brain",
+ "details": {
+ "by_source": [],
+ "count": 0,
+ "docs": "docs/guides/repair.md#atom-fence-rows",
+ "origin_unread": 0,
+ "repair": "atom-fence-rows"
+ },
+ "elapsed_ms": "<volatile>",
+ "message": "No world atom carries a fence row its source page shows only to the owner.",
+ "name": "atom_fence_rows",
+ "status": "ok"
+ },
{
"category": "brain",
"details": {
diff --git a/test/fixtures/goldens/doctor/json-pglite-degraded.json b/test/fixtures/goldens/doctor/json-pglite-degraded.json
index 5dc7b9d4bb..1f6eca27be 100644
--- a/test/fixtures/goldens/doctor/json-pglite-degraded.json
+++ b/test/fixtures/goldens/doctor/json-pglite-degraded.json
@@ -1722,6 +1722,20 @@
"name": "atom_retirements_restorable",
"status": "ok"
},
+ {
+ "category": "brain",
+ "details": {
+ "by_source": [],
+ "count": 0,
+ "docs": "docs/guides/repair.md#atom-fence-rows",
+ "origin_unread": 0,
+ "repair": "atom-fence-rows"
+ },
+ "elapsed_ms": "<volatile>",
+ "message": "No world atom carries a fence row its source page shows only to the owner.",
+ "name": "atom_fence_rows",
+ "status": "ok"
+ },
{
"category": "brain",
"details": {
diff --git a/test/fixtures/goldens/doctor/json-pglite-fresh.json b/test/fixtures/goldens/doctor/json-pglite-fresh.json
index fe956f3135..f2c7555b21 100644
--- a/test/fixtures/goldens/doctor/json-pglite-fresh.json
+++ b/test/fixtures/goldens/doctor/json-pglite-fresh.json
@@ -1778,6 +1778,20 @@
"name": "atom_retirements_restorable",
"status": "ok"
},
+ {
+ "category": "brain",
+ "details": {
+ "by_source": [],
+ "count": 0,
+ "docs": "docs/guides/repair.md#atom-fence-rows",
+ "origin_unread": 0,
+ "repair": "atom-fence-rows"
+ },
+ "elapsed_ms": "<volatile>",
+ "message": "No world atom carries a fence row its source page shows only to the owner.",
+ "name": "atom_fence_rows",
+ "status": "ok"
+ },
{
"category": "brain",
"details": {
diff --git a/test/fixtures/goldens/doctor/json-postgres-fresh.json b/test/fixtures/goldens/doctor/json-postgres-fresh.json
index 4c4b47af54..158f9958c1 100644
--- a/test/fixtures/goldens/doctor/json-postgres-fresh.json
+++ b/test/fixtures/goldens/doctor/json-postgres-fresh.json
@@ -1783,6 +1783,20 @@
"name": "atom_retirements_restorable",
"status": "ok"
},
+ {
+ "category": "brain",
+ "details": {
+ "by_source": [],
+ "count": 0,
+ "docs": "docs/guides/repair.md#atom-fence-rows",
+ "origin_unread": 0,
+ "repair": "atom-fence-rows"
+ },
+ "elapsed_ms": "<volatile>",
+ "message": "No world atom carries a fence row its source page shows only to the owner.",
+ "name": "atom_fence_rows",
+ "status": "ok"
+ },
{
"category": "brain",
"details": {
diff --git a/test/fixtures/goldens/doctor/registry-build-checks.json b/test/fixtures/goldens/doctor/registry-build-checks.json
index 51e19e3824..5b0101c95b 100644
--- a/test/fixtures/goldens/doctor/registry-build-checks.json
+++ b/test/fixtures/goldens/doctor/registry-build-checks.json
@@ -597,6 +597,10 @@
"category": "brain",
"name": "atom_retirements_restorable"
},
+ {
+ "category": "brain",
+ "name": "atom_fence_rows"
+ },
{
"category": "brain",
"name": "generation_retirements"
diff --git a/test/helpers/world-fence-page.ts b/test/helpers/world-fence-page.ts
new file mode 100644
index 0000000000..5090c6f9f3
--- /dev/null
+++ b/test/helpers/world-fence-page.ts
@@ -0,0 +1,25 @@
+/** A world page whose facts fence holds one world and one private row and whose takes fence holds one row (synthetic names only). */
+export const PRIVATE_ROW = 'Alice-example keeps the source-a renewal terms at canaryprivaterow7781';
+export const HIDDEN_TAKE_ROW = 'Acme-example will move the launch to canarytakerow4410';
+export const WORLD_ROW = 'Acme-example ships the launch checklist every quarter';
+const PROSE = 'The launch review found that the team measures every launch against clear exit criteria. '.repeat(10);
+
+export const FENCES = `## Facts
+
+<!--- gbrain:facts:begin -->
+| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |
+|---|-------|------|------------|------------|------------|------------|-------------|--------|---------|
+| 1 | ${WORLD_ROW} | fact | 1.0 | world | medium | 2026-01-01 | | test | |
+| 2 | ${PRIVATE_ROW} | fact | 1.0 | private | medium | 2026-01-01 | | test | |
+<!--- gbrain:facts:end -->
+
+## Takes
+
+<!--- gbrain:takes:begin -->
+| # | claim | kind | who | weight | since | source |
+|---|-------|------|-----|--------|-------|--------|
+| 1 | ${HIDDEN_TAKE_ROW} | take | brain | 0.6 | 2026-01 | test |
+<!--- gbrain:takes:end -->
+`;
+
+export const WORLD_PAGE_BODY = `# Launch review\n\n${PROSE}\n\n${FENCES}`;
diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txt
index 5204d12ad7..d81d3b57cd 100644
--- a/test/postgres-unit-arms.txt
+++ b/test/postgres-unit-arms.txt
@@ -65,6 +65,7 @@ test/contact-rows-drift-8109.test.ts
test/conversation-facts-outcome-marker-purge-7778.test.ts
test/conversation-facts-oversized-sidecar.test.ts
test/conversation-facts-purged-claim-7438.test.ts
+test/cycle-world-fence-rows.test.ts
test/cycle/derived-write-through-commit.test.ts
test/cycle/dream-reverse-write-commit.test.ts
test/cycle/synthesize-concepts-merge.test.ts
@@ -85,6 +86,7 @@ test/engine-sql-facts-keyset.test.ts
test/extract-all-stamp-intersection.serial.test.ts
test/extract-atoms-input-truncated-6503.test.ts
test/extract-atoms-raised-cap-drain-7391.test.ts
+test/extract-atoms-world-fence-rows.test.ts
test/extract-endpoint-revision.serial.test.ts
test/extract-entities-managed.test.ts
test/extract-timeline-from-meetings-managed.test.ts
@@ -473,6 +475,7 @@ test/refresh-write-barrier.test.ts
test/remediation-manual-only.test.ts
test/remember-batch-entity-7432.test.ts
test/repair-apply-pending-6543.test.ts
+test/repair-atom-fence-rows.test.ts
test/repair-database-stop-gbra133.test.ts
test/repair-embedding-effects.test.ts
test/repair-failed-writes-conflict-6429.test.ts
diff --git a/test/repair-atom-fence-rows.test.ts b/test/repair-atom-fence-rows.test.ts
new file mode 100644
index 0000000000..03743427d3
--- /dev/null
+++ b/test/repair-atom-fence-rows.test.ts
@@ -0,0 +1,159 @@
+/**
+ * `gbrain repair atom-fence-rows` and doctor's `atom_fence_rows`, on PGLite and Postgres.
+ *
+ * World atoms an earlier extraction produced from the whole page can carry the claim of a facts row whose visibility
+ * is not world, or of a takes row held by someone other than world, and a remote read of the atom returns it. Doctor
+ * counts them per source and names the read-only preview; the preview lists them (slug, source page, row kind and
+ * number, never the row text) and changes nothing; only --apply --expect <hash> narrows exactly that set to private.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { configureGateway, resetGateway } from '../src/core/ai/gateway.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { OperationError } from '../src/core/ops/contract.ts';
+import { runRepairCommand } from '../src/commands/repair.ts';
+import { atomFenceRowsCheck } from '../src/commands/doctor/checks/atom-fence-rows.ts';
+import { WAVE_CHECKS } from '../src/commands/doctor/wave-checks.ts';
+import { dispatchToolCall } from '../src/mcp/dispatch.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';
+import { withEnv } from './helpers/with-env.ts';
+import { managedBrain } from './helpers/managed-brain.ts';
+import { HIDDEN_TAKE_ROW, PRIVATE_ROW, WORLD_PAGE_BODY, WORLD_ROW } from './helpers/world-fence-page.ts';
+
+interface RepairJson { results: Array<{ affected: number; residuals: Record<string, number>; apply_command: string; applied: number; skipped: number;
+ listing?: Array<{ item: string; class: string; detail?: string }>; outcomes?: Record<string, number> }> }
+
+const ORIGIN = 'notes/launch-review';
+const CARRIES_FACT = 'atoms/2026-01-01/renewal-terms';
+const CARRIES_TAKE = 'atoms/2026-01-01/launch-move';
+const CLEAN = 'atoms/2026-01-01/launch-checklist';
+const ALREADY_PRIVATE = 'atoms/2026-01-01/renewal-terms-private';
+
+test('atom_fence_rows is a host-only wave check that names the atom-fence-rows repair', () => {
+ const spec = WAVE_CHECKS.find(check => check.id === 'atom_fence_rows');
+ expect(spec).toMatchObject({ resolution: 'repair', registration: 'wave' });
+ expect(spec!.hostOnly).toBeTruthy();
+});
+
+for (const kind of testBackends()) {
+ describe(`gbrain repair atom-fence-rows (${kind})`, () => {
+ let engine: BrainEngine;
+ let close: (() => Promise<void>) | undefined;
+ let sourceId: string;
+ const home = mkdtempSync(join(tmpdir(), 'gbrain-repair-atom-fence-rows-'));
+
+ const putAtom = (slug: string, body: string, frontmatter: Record<string, unknown>) =>
+ engine.putPage(slug, { type: 'atom', title: slug.split('/').at(-1)!, compiled_truth: body,
+ frontmatter: { type: 'atom', atom_type: 'insight', source_slug: ORIGIN, source_hash: 'aaaaaaaaaaaaaaaa', visibility: 'world', dream_generated: true,
+ extracted_by: 'extract_atoms-v0.41.2.1', ...frontmatter } }, { sourceId });
+
+ beforeAll(async () => {
+ configureGateway({ embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: 1536, env: {} });
+ if (kind === 'postgres') ({ engine, close } = await isolatedPersistencePostgres(requirePostgresTestDatabase()));
+ else { const pglite = new PGLiteEngine(); await pglite.connect({}); await pglite.initSchema(); engine = pglite; }
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ sourceId = `fence-rows-${randomUUID().slice(0, 8)}`;
+ await engine.executeRaw('INSERT INTO sources(id,name) VALUES($1,$1)', [sourceId]);
+ await engine.putPage(ORIGIN, { type: 'note', title: 'Launch review', compiled_truth: WORLD_PAGE_BODY, timeline: '' }, { sourceId });
+ await putAtom(CARRIES_FACT, `Recorded on the page: ${PRIVATE_ROW}.`, {});
+ await putAtom(CARRIES_TAKE, 'A launch decision was recorded.', { source_quote: HIDDEN_TAKE_ROW });
+ await putAtom(CLEAN, `Recorded on the page: ${WORLD_ROW}.`, { source_quote: WORLD_ROW });
+ await putAtom(ALREADY_PRIVATE, `Recorded on the page: ${PRIVATE_ROW}.`, { visibility: 'private' });
+ }, 120_000);
+ afterAll(async () => {
+ await disposePersistenceConsumer(engine);
+ if (close) await close(); else await engine.disconnect();
+ resetGateway();
+ rmSync(home, { recursive: true, force: true });
+ });
+
+ const repair = async (args: string[]): Promise<RepairJson> => {
+ const lines: string[] = [];
+ const original = console.log;
+ console.log = (...parts: unknown[]) => { lines.push(parts.map(String).join(' ')); };
+ try { await withEnv({ GBRAIN_HOME: home }, () => runRepairCommand(engine, ['atom-fence-rows', '--source', sourceId, ...args, '--json'])); } finally { console.log = original; }
+ return JSON.parse(lines.join('\n')) as RepairJson;
+ };
+ const atoms = () => engine.executeRaw<{ slug: string; visibility: string; revision: string }>(
+ `SELECT slug, frontmatter->>'visibility' AS visibility, knowledge_revision::text AS revision FROM pages WHERE source_id=$1 AND type='atom' ORDER BY slug`, [sourceId]);
+ const remoteGet = async (slug: string) => {
+ try {
+ const out = await dispatchToolCall(engine, 'get_page', { slug }, { remote: true, transport: 'stdio', sourceId, takesHoldersAllowList: ['world'] });
+ return out.content.map(c => c.text).join('\n');
+ } catch (error) { return String(error); }
+ };
+
+ test('doctor warns with the count and the preview command, the preview lists exactly the carrying atoms and changes nothing, the apply narrows them', async () => {
+ expect(await remoteGet(CARRIES_FACT)).toContain(PRIVATE_ROW);
+
+ const finding = await atomFenceRowsCheck(engine, [sourceId]);
+ expect(finding.status).toBe('warn');
+ expect(finding.details).toMatchObject({ count: 2, repair: 'atom-fence-rows' });
+ expect(finding.message).toContain(`gbrain repair atom-fence-rows --source ${sourceId} --json`);
+ expect(JSON.stringify(finding)).not.toContain(PRIVATE_ROW);
+ expect(JSON.stringify(finding)).not.toContain(CARRIES_FACT);
+
+ const before = await atoms();
+ const preview = await repair([]);
+ const result = preview.results[0]!;
+ expect(result.listing!.map(row => ({ item: row.item, class: row.class, detail: row.detail })).sort((a, b) => a.item.localeCompare(b.item))).toEqual([
+ { item: `${sourceId}:${CARRIES_TAKE}`, class: 'takes', detail: `source page ${ORIGIN}: takes row 1` },
+ { item: `${sourceId}:${CARRIES_FACT}`, class: 'facts', detail: `source page ${ORIGIN}: facts row 2` },
+ ].sort((a, b) => a.item.localeCompare(b.item)));
+ expect(JSON.stringify(preview)).not.toContain(PRIVATE_ROW);
+ expect(JSON.stringify(preview)).not.toContain(HIDDEN_TAKE_ROW);
+ expect(await atoms()).toEqual(before);
+
+ const unbound = await withEnv({ GBRAIN_HOME: home }, () => runRepairCommand(engine, ['atom-fence-rows', '--source', sourceId, '--apply', '--json']))
+ .then(() => null, (error: unknown) => error);
+ expect(unbound).toBeInstanceOf(OperationError);
+ expect(await atoms()).toEqual(before);
+
+ const hash = result.apply_command.match(/--expect ([0-9a-f]+)/)![1]!;
+ const applied = (await repair(['--apply', '--expect', hash])).results[0]!;
+ expect(applied.applied).toBe(2);
+ expect(applied.outcomes).toMatchObject({ narrowed: 2 });
+ const after = Object.fromEntries((await atoms()).map(row => [row.slug, row.visibility]));
+ expect(after).toEqual({ [CARRIES_FACT]: 'private', [CARRIES_TAKE]: 'private', [CLEAN]: 'world', [ALREADY_PRIVATE]: 'private' });
+ expect(await remoteGet(CARRIES_FACT)).not.toContain(PRIVATE_ROW);
+ expect(await remoteGet(CARRIES_TAKE)).not.toContain(HIDDEN_TAKE_ROW);
+ expect(await remoteGet(CLEAN)).toContain(WORLD_ROW);
+
+ expect((await atomFenceRowsCheck(engine, [sourceId])).status).toBe('ok');
+ expect((await repair([])).results[0]!.listing ?? []).toEqual([]);
+ }, 120_000);
+ test('managed brain: the apply narrows the previewed atom through the coordinator', async () => {
+ await managedBrain(async ({ engine: brain }) => {
+ const run = async (args: string[]): Promise<RepairJson> => {
+ const lines: string[] = [];
+ const original = console.log;
+ console.log = (...parts: unknown[]) => { lines.push(parts.map(String).join(' ')); };
+ try { await runRepairCommand(brain, ['atom-fence-rows', '--source', 'default', ...args, '--json']); } finally { console.log = original; }
+ return JSON.parse(lines.join('\n')) as RepairJson;
+ };
+ expect((await atomFenceRowsCheck(brain, ['default'])).details).toMatchObject({ count: 1 });
+ const preview = (await run([])).results[0]!;
+ expect(preview.listing!.map(row => row.item)).toEqual([`default:${CARRIES_FACT}`]);
+ const hash = preview.apply_command.match(/--expect ([0-9a-f]+)/)![1]!;
+ const applied = (await run(['--apply', '--expect', hash])).results[0]!;
+ await disposePersistenceConsumer(brain);
+ expect(applied.outcomes).toMatchObject({ narrowed: 1 });
+ const [row] = await brain.executeRaw<{ visibility: string }>(
+ `SELECT frontmatter->>'visibility' AS visibility FROM pages WHERE source_id='default' AND slug=$1`, [CARRIES_FACT]);
+ expect(row!.visibility).toBe('private');
+ expect((await atomFenceRowsCheck(brain, ['default'])).status).toBe('ok');
+ }, { databaseUrl: kind === 'postgres' ? requirePostgresTestDatabase() : undefined, setup: async ({ engine: brain }) => {
+ await brain.putPage(ORIGIN, { type: 'note', title: 'Launch review', compiled_truth: WORLD_PAGE_BODY, timeline: '' }, { sourceId: 'default' });
+ await brain.putPage(CARRIES_FACT, { type: 'atom', title: 'renewal-terms', compiled_truth: `Recorded on the page: ${PRIVATE_ROW}.`,
+ frontmatter: { type: 'atom', atom_type: 'insight', source_slug: ORIGIN, source_hash: 'aaaaaaaaaaaaaaaa', visibility: 'world', dream_generated: true,
+ managed_extraction: true, extracted_by: 'extract_atoms-v0.41.2.1' } }, { sourceId: 'default' });
+ } });
+ }, 180_000);
+ });
+}
diff --git a/test/repair-explicit-only.test.ts b/test/repair-explicit-only.test.ts
index 1f7d773808..5bd02d489f 100644
--- a/test/repair-explicit-only.test.ts
+++ b/test/repair-explicit-only.test.ts
@@ -24,7 +24,7 @@ import { REPAIR_HELP, parseRepairArgs, runRepairCommand } from '../src/commands/
import { _resetCliExitVerdictForTests, currentExitCode } from '../src/core/cli-force-exit.ts';
import { withEnv } from './helpers/with-env.ts';
-const EXPLICIT: RepairKind[] = ['accepted-takes', 'google-file-modes', 'stale-atoms', 'atoms-restore', 'extractor-facts', 'unwithdrawn-facts', 'conversation-labels', 'captured-facts', 'agent-session-facts', 'redacted-facts', 'loop-facts', 'ontology-facts', 'facts-rehome', 'consolidate-ties', 'duplicate-facts', 'orphan-children', 'failed-writes', 'split-facts', 'frontmatter', 'timeline-comments', 'timeline-order', 'contact-rows', 'managed-sync-orphans', 'content-receipt-root', 'frontmatter-keys', 'file-drift', 'stuck-recovery', 'ghost-pages', 'origin-twins', 'receipt-compaction', 'aliases', 'rename-identity', 'overwritten-edits', 'legacy-twins', 'missing-tables', 'url-clone-fences', 'segmented-mirror', 'segmented-tiling', 'uncommitted-deletions', 'generations', 'fact-claim-dates', 'provenance', 'secret-spans', 'rows-behind', 'private-labels'];
+const EXPLICIT: RepairKind[] = ['accepted-takes', 'google-file-modes', 'stale-atoms', 'atoms-restore', 'atom-fence-rows', 'extractor-facts', 'unwithdrawn-facts', 'conversation-labels', 'captured-facts', 'agent-session-facts', 'redacted-facts', 'loop-facts', 'ontology-facts', 'facts-rehome', 'consolidate-ties', 'duplicate-facts', 'orphan-children', 'failed-writes', 'split-facts', 'frontmatter', 'timeline-comments', 'timeline-order', 'contact-rows', 'managed-sync-orphans', 'content-receipt-root', 'frontmatter-keys', 'file-drift', 'stuck-recovery', 'ghost-pages', 'origin-twins', 'receipt-compaction', 'aliases', 'rename-identity', 'overwritten-edits', 'legacy-twins', 'missing-tables', 'url-clone-fences', 'segmented-mirror', 'segmented-tiling', 'uncommitted-deletions', 'generations', 'fact-claim-dates', 'provenance', 'secret-spans', 'rows-behind', 'private-labels'];
// GBRA-161: the generations preview carries its ledger kind and the restore window, so the printed command runs as is.
const PREVIEW = (kind: RepairKind): string => kind === 'generations' ? 'gbrain repair generations --kind atom --since 30d' : `gbrain repair ${kind}`;
let engine: PGLiteEngine;
@@ -111,7 +111,7 @@ describe('surfaces that list instead of run', () => {
expect(out.explicit_kinds).toEqual(EXPLICIT.map(kind => ({ kind, code: 'explicit_kind_required', preview_command: PREVIEW(kind),
docs: 'docs/guides/repair.md#explicit-only-repair-kinds' })));
}
- expect(await captured(['--all'])).toContain('Explicit-only kinds (not run without their name; preview each): gbrain repair accepted-takes; gbrain repair google-file-modes; gbrain repair stale-atoms; gbrain repair atoms-restore; gbrain repair extractor-facts; gbrain repair unwithdrawn-facts; gbrain repair conversation-labels; gbrain repair captured-facts; gbrain repair agent-session-facts; gbrain repair redacted-facts; gbrain repair loop-facts');
+ expect(await captured(['--all'])).toContain('Explicit-only kinds (not run without their name; preview each): gbrain repair accepted-takes; gbrain repair google-file-modes; gbrain repair stale-atoms; gbrain repair atoms-restore; gbrain repair atom-fence-rows; gbrain repair extractor-facts; gbrain repair unwithdrawn-facts; gbrain repair conversation-labels; gbrain repair captured-facts; gbrain repair agent-session-facts; gbrain repair redacted-facts; gbrain repair loop-facts');
});
test('gbrain repair --all --apply exits 0 when explicit kinds are the only ones left', async () => {