Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(repair): gbrain repair take-supersession rebuilds broken supersession chains (#5886)

garrytan6536666fb89c
diff --git a/TODOS.md b/TODOS.md
index 0a7eb3bf17..20131ec15c 100644
--- a/TODOS.md
+++ b/TODOS.md
@@ -122,7 +122,7 @@ Spec: `docs/designs/AGENT_OPERATOR_WAVE.md` (Deferred list). Contract: `docs/pro
**What:** `auto_chronicle=true` still has no effect; doctor and the advisor say so. #5329's backfill idempotency landed in v0.60.32.0, so re-enabling the trigger no longer means duplicate event pages from repeat runs. **Fix:** call `runChronicleBackstop` from the import path behind the flag, with a cost note. **Effort:** M. **Priority:** P2 (Foundations 2).
- [x] **P2 — Cycle-side fence for `row_num IS NULL` facts (#5299).** **Completed** — the `extract_facts` phase fences them itself every cycle through the shared core pass (`src/core/facts/unfenced-facts.ts`) and reconciles those pages in the same run.
**What:** facts without a fence row number are invisible to the fence reconciler. **Fix:** the cycle fences them after GBRA-35's facts writeback (now on master). **Effort:** M. **Priority:** P2 (Foundations 2).
-- [ ] **P2 — One-shot repair for supersession chains broken on managed brains (#5886).**
+- [x] **P2 — One-shot repair for supersession chains broken on managed brains (#5886).** **Completed** — `gbrain repair take-supersession` (preview, then `--apply`) relinks each struck take from journal, stored-pointer or forced fence-structure evidence and reports ambiguous pages with the manual edit.
**What:** v0.60.36.0 writes the supersession pointer on the old take row; chains written before it keep `superseded_by` NULL on managed brains. **Fix:** a `gbrain repair` kind that rebuilds the pointers from the fence. **Effort:** S. **Priority:** P2.
- [ ] **P2 — Doctor check for pages still waiting on their revision backfill (#5216).**
**What:** the backfill is resumable and reports progress on upgrade, but a brain whose backfill keeps stopping on a failing row has no standing doctor signal. **Effort:** S. **Priority:** P2.
diff --git a/docs/architecture/key-files/commands-5.md b/docs/architecture/key-files/commands-5.md
index 2fd1ac6745..fe319cff86 100644
--- a/docs/architecture/key-files/commands-5.md
+++ b/docs/architecture/key-files/commands-5.md
@@ -3,7 +3,7 @@
[Subsystem index](../KEY_FILES.md). Read only the entries relevant to your change.
Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.
-- `src/commands/repair.ts` — `gbrain repair [<kind>] [--apply] [--source <id>] [--limit <n>] [--no-embed] [--json]` and `gbrain repair --all`. Kinds `timeline` (#5567 materialize), `visibility` (#5525 tighten-only backfill) `safe-chunks` (#5050/#5247 projection-only re-seal of pages of every kind below the safe-chunk fence; `--no-embed` defers embedding to `embed --stale`), `contextual-mode` (#5621 projection-only stamp of the import-time contextual retrieval mode on pages that have none; honors `--no-embed`) `connector-checkpoints` (#5686 brain-wide cleanup of connector checkpoint rows no source can load), `orphan-bindings` (#5732 brain-wide cleanup of persistence source bindings whose source or incarnation is gone) and `embedding-effects` (#5629/#5734 settlement of stale queued and failed embedding effects: reconciled, superseded, retry_queued or blocked, reported per item in `outcomes` / `outcome_items`) and `google-file-modes` (clears group/other bits on gbrain's own files under Google source dirs outside `~/.gbrain`; filesystem only); no kind previews every kind. Dry run unless `--apply` (no prompt; `--yes` refused). `parseRepairArgs` is strict: any unknown option or a second positional refuses `invalid_params` before anything runs, and `--max-usd`/`--max-cost` name the capped route `gbrain doctor --remediate --yes --include-repairs --max-usd <n> --expect <plan_hash>` (hash from `doctor --remediation-plan --json`). Help lines come from `REPAIR_REGISTRY`; `--json` adds `paid` per kind and `paid_kinds`. Output carries the resolved scope, affected count, a capped `source:slug` sample, residual counts, request-ID / receipt-byte / re-embedding cost and capacity, and the apply command; `--json` has the same fields. Host-only: thin clients refuse via `THIN_CLIENT_REFUSED_COMMANDS`. Logic lives in `src/core/repair/`.
+- `src/commands/repair.ts` — `gbrain repair [<kind>] [--apply] [--source <id>] [--limit <n>] [--no-embed] [--json]` and `gbrain repair --all`. Kinds `timeline` (#5567 materialize), `visibility` (#5525 tighten-only backfill) `safe-chunks` (#5050/#5247 projection-only re-seal of pages of every kind below the safe-chunk fence; `--no-embed` defers embedding to `embed --stale`), `contextual-mode` (#5621 projection-only stamp of the import-time contextual retrieval mode on pages that have none; honors `--no-embed`) `connector-checkpoints` (#5686 brain-wide cleanup of connector checkpoint rows no source can load), `take-supersession` (#5886 relinks takes supersession chains from journal, stored-pointer or forced fence-structure evidence; ambiguous pages are reported with the manual edit, never rewritten; `src/core/repair/take-supersession.ts`), `orphan-bindings` (#5732 brain-wide cleanup of persistence source bindings whose source or incarnation is gone) and `embedding-effects` (#5629/#5734 settlement of stale queued and failed embedding effects: reconciled, superseded, retry_queued or blocked, reported per item in `outcomes` / `outcome_items`) and `google-file-modes` (clears group/other bits on gbrain's own files under Google source dirs outside `~/.gbrain`; filesystem only); no kind previews every kind. Dry run unless `--apply` (no prompt; `--yes` refused). `parseRepairArgs` is strict: any unknown option or a second positional refuses `invalid_params` before anything runs, and `--max-usd`/`--max-cost` name the capped route `gbrain doctor --remediate --yes --include-repairs --max-usd <n> --expect <plan_hash>` (hash from `doctor --remediation-plan --json`). Help lines come from `REPAIR_REGISTRY`; `--json` adds `paid` per kind and `paid_kinds`. Output carries the resolved scope, affected count, a capped `source:slug` sample, residual counts, request-ID / receipt-byte / re-embedding cost and capacity, and the apply command; `--json` has the same fields. Host-only: thin clients refuse via `THIN_CLIENT_REFUSED_COMMANDS`. Logic lives in `src/core/repair/`.
- `src/commands/reindex.ts` — `gbrain reindex --markdown [--type PAGE_TYPE] [--limit N] [--workers N] [--dry-run] [--json] [--no-embed] [--repo PATH]`. The writer pool is sized once from the run's page target (pending, capped by `--limit`) through `resolveWorkersWithClamp`, so Postgres runs over 100 pages default to `DEFAULT_PARALLEL_WORKERS` while PGLite stays at one; `--workers` overrides and the used count is reported as `workers` in the result and JSON (pinned by `test/e2e/reindex-auto-workers-5181.test.ts`). Walks markdown pages with stale `chunker_version` (plus unstamped contextual-retrieval mode when embedding is enabled; `--no-embed` still stamps the mode of every page it re-chunks) in 100-row id-keyset batches; a failed row cannot starve later batches in the same invocation. `--type` adds a bound-parameter `pages.type = $N` scope for focused backfills such as atom pages and is rejected by reindex modes that do not consume it. Current-version chunkless healing deliberately remains owned by the native, bounded `embed --stale` path. Rows with non-null `source_path` re-import via `importFromFile`; rows without fall back to `importFromContent`. Both paths pass `forceRechunk: true` to bypass `importFromContent`'s `content_hash` short-circuit — without it the chunker version bump never reaches pages whose source content hasn't changed, AND the stripFactsFence privacy strip never applies to chunks stored without it. Wired into `src/commands/upgrade.ts:runPostUpgrade` after `apply-migrations`. The DB-only fallback (no source file on disk) does NOT pass body-only `compiled_truth` to `importFromContent` (that path re-parses with EMPTY frontmatter and OVERWRITES the page's real frontmatter/title/timeline); it `getPage`+`getTags`, reconstructs FULL markdown via `serializeMarkdown(frontmatter, compiled_truth, timeline, {type, title, tags})`, and re-imports THAT so re-chunking a DB-only page preserves everything while bumping `chunker_version`. Pinned by `test/reindex-preserve-tags.test.ts` and `test/reindex.test.ts`.
- `src/commands/repair-jsonb.ts` — `gbrain repair-jsonb [--dry-run] [--json]`: rewrites `jsonb_typeof='string'` rows in place across 8 affected columns (pages.frontmatter, raw_data.data, ingest_log.pages_updated, files.metadata, page_versions.frontmatter, subagent_messages.content_blocks, subagent_tool_executions.input, subagent_tool_executions.output). The subagent targets are `jsonPayloadOnly`: those columns can legitimately hold jsonb string scalars (persistToolExec binds a tool's pre-serialized string payload as-is), so their damage predicate additionally requires container-shaped content (`^\s*[\[{]`) that `pg_input_is_valid(..., 'jsonb')` (PG16+ floor, same as the IS JSON predicate `updateSourceConfig` relies on) actually parses — a plain-text value that merely starts with `[` or `{` is never flagged or corrupted. Targets whose table doesn't exist on the brain are skipped via `to_regclass` (brains without the subagent tables), and one target's failure is recorded on stderr while the run continues — earlier repairs are already committed and the v0_12_2 migration orchestrator JSON-parses stdout. `runDoctor`'s `jsonb_integrity` check counts damage with the same predicate over the same target list. Repairs double-encoded rows on Postgres; PGLite no-ops. Idempotent. Pinned by `test/repair-jsonb.test.ts` + `test/doctor.test.ts`.
diff --git a/docs/guides/repair.md b/docs/guides/repair.md
index af5743953a..fa4de464d9 100644
--- a/docs/guides/repair.md
+++ b/docs/guides/repair.md
@@ -74,7 +74,7 @@ any other option the table below does not list, including `--max-usd`: a
refused run changes nothing. To cap paid embedding work, run the repairs
through `gbrain doctor --remediate --yes --include-repairs --expect <plan_hash> --max-usd <n>`
(`<plan_hash>` comes from `gbrain doctor --remediation-plan --json`). `--all`
-runs `timeline`, then `visibility`, then `safe-chunks`, then `contextual-mode`, then `connector-checkpoints`, then `request-indexes`, then `connector-fences`, then `orphan-bindings`, then `embedding-effects`, and stops at the
+runs `timeline`, then `visibility`, then `safe-chunks`, then `contextual-mode`, then `connector-checkpoints`, then `request-indexes`, then `connector-fences`, then `take-supersession`, then `orphan-bindings`, then `embedding-effects`, and stops at the
first kind that stops.
The explicit-only kinds (`google-file-modes`, `stale-atoms`, `extractor-facts`) never run under
`--all`; it lists each with its preview command and still exits 0 when they
@@ -119,6 +119,7 @@ should also check `results[].complete`.
| `visibility` | `derived_visibility` | Stamps an explicit `visibility` on extracted atoms and synthesized concepts. An atom takes its origin page's visibility; transcript atoms and atoms whose origin is gone become `private`; a concept takes the strictest visibility of its input atoms. A concept input found only through an atom's `concepts:` list counts as private. Atoms are repaired before concepts. It never loosens an explicit value: `private` stays `private`, and `world` can only become `private`. A missing value is stamped with the origin's value, which is `world` when the origin page is public. | `concepts_without_lineage`: concepts whose inputs cannot be found. They stay as they are, and remote readers already treat a missing visibility as private. `atoms_origin_gone_to_private` counts atoms made private because their origin page no longer exists. |
| `request-indexes` | `persistence_request_indexes` | Creates a missing managed sync request index, or drops an INVALID one (left by an interrupted concurrent build) and rebuilds it, on a brain whose schema version is already current. Postgres builds each index `CONCURRENTLY`, one at a time, so writes continue; PGLite builds inline. It changes no user data, takes no journal admission and runs brain-wide (`--source` does not narrow it). See [managed sync request indexes](#request-indexes). | `building`: an index another session is still building; it is never dropped. |
| `connector-fences` | none (a `connector_fence_below_timeline` refusal names it) | Moves a facts or takes fence that sits below the timeline sentinel of a Google or GitHub page into the page body through a revision-bound `put_page`, so the connector's next re-render carries the fence instead of refusing. Then re-attempt the held item with `gbrain sources retry-held <source>`. | `kept_ambiguous_pages`: pages whose fences are duplicated, unbalanced or unparseable. Move the fence by hand: read the page, place the fence above the `<!-- timeline -->` line, and save it with the current `expected_revision`. |
+| `take-supersession` | none | Rebuilds `takes.superseded_by` for supersession chains written before the pointer moved onto the old fence row (#5886). Each struck take is linked to the row that replaced it only from evidence: a committed `takes_supersede` receipt, a stored `superseded_by`, or a row carrying the old `superseded by #<own row>` pointer with exactly one possible predecessor. The pointer is written onto the old row (`<source>; superseded by #N`) and stale self-pointers are dropped through a revision-bound `put_page`; a page whose fence is already right but whose stored pointers differ is reprojected without a page write. See [take supersession](#take-supersession). | `ambiguous_pages` / `ambiguous_rows`: pages where a new row has two or more possible predecessors, or where evidence conflicts. The preview lists each with its candidates and the manual edit; nothing on them changes. `unparsed_pages`: pages whose takes fence does not parse cleanly. |
| `connector-checkpoints` | `connector_checkpoints` | Deletes managed connector checkpoint rows and retry pointers that no registered connector source can load and that are older than 7 days. They accumulate after a content setting such as `g_history_days` changes, or when a connector host older than v0.60.11.0 runs during an upgrade. Cleanup only: it never copies or re-keys a checkpoint, takes no journal admission and runs brain-wide (`--source` does not narrow it). | Rows a queued or running connector write, or a connector's recorded pending set, still references. |
| `orphan-bindings` | `orphan_persistence_bindings` | Deletes persistence source bindings whose source was removed, or that belong to an earlier incarnation of a source re-added under the same id. Releases before this one left the binding behind on `gbrain sources remove` and `gbrain sources purge`, so the re-added source read as claimed and every `gbrain sync --source <id>` failed with `writer_coordinator_required`. Bookkeeping only: no journal admission, no page or file changes, and it runs brain-wide (`--source` does not narrow it). See [orphan bindings](#orphan-bindings). | A binding that a queued, running or recovering write request of the same source incarnation still references. |
| `embedding-effects` | `stale_embedding_effects` | Settles stale queued and failed embedding effects of committed writes, which block receipt compaction and activation: `reconciled` when current vectors pass the effect verifier, `superseded` when the page was deleted or a newer revision owns its own effect, `retry_queued` for the owner (paid; a used-up retry allowance gets one new bounded cycle per explicit apply). See [stale queued embedding effects](#stale-queued-embedding-effects). | `blocked` effects, counted by reason (`owner_unavailable`, `embedding_disabled`, `embedding_unconfigured`, `projection_pending`, `no_replacement_obligation`). |
@@ -303,6 +304,34 @@ the item's error code names, then re-attempt. See
| A sync fails with `connector_holds_exhausted` | `gbrain sources status <source> --json` | Fix the cause, then `gbrain sources retry-held <source>` and `gbrain sync --source <source>` | `gbrain doctor` | agent, after the user agrees | `egress` |
| A sync refuses with `connector_fence_below_timeline` | `gbrain repair connector-fences --source <source>` | `gbrain repair connector-fences --source <source> --apply`, then `gbrain sources retry-held <source>` | `gbrain sync --source <source>` succeeds | brain host, after the user agrees | `egress` |
+<a id="take-supersession"></a>
+### Take supersession
+
+**Say to your agent:** *"My superseded takes don't point at the take that
+replaced them. Repair the supersession chains."*
+
+Takes superseded before the pointer moved onto the old fence row have
+`superseded_by` empty: the old row was struck without a pointer, and the new
+row often cites itself (`superseded by #<its own row>`). Preview, then apply
+after you agree:
+
+```bash
+gbrain repair take-supersession # per page: each link, its evidence, ambiguous pages
+gbrain repair take-supersession --json # details.pages[] and details.ambiguous[]
+gbrain repair take-supersession --apply # writes the pointers; a second apply changes nothing
+```
+
+The repair links a struck row to its replacement only from evidence, in this
+order: a committed `takes_supersede` receipt for the page, a stored
+`superseded_by`, then a self-pointer row that has exactly one struck, unlinked
+row above it (resolved hop by hop, so a chain of supersessions resolves). It
+never guesses. When a new row has two or more possible predecessors, the page
+is listed under `ambiguous` with the candidates and left unchanged. Fix it by
+hand: read the page (`gbrain get --source <source> -- <slug>`), append
+`; superseded by #<new row>` to the source cell of the row each new row
+replaced, save it with the current `expected_revision`, then run the repair
+again; it drops the leftover self-pointers and stores the pointers.
+
<a id="orphan-bindings"></a>
### Orphan persistence bindings
diff --git a/scripts/e2e-test-map.ts b/scripts/e2e-test-map.ts
index ae0cc2c252..8147e5015b 100644
--- a/scripts/e2e-test-map.ts
+++ b/scripts/e2e-test-map.ts
@@ -684,6 +684,8 @@ export const E2E_TEST_MAP: Record<string, string[]> = {
"src/core/connectors/connector-text.ts": ["test/e2e/connector-holds.test.ts"],
"src/commands/sources-retry-held.ts": ["test/e2e/connector-holds.test.ts"],
"src/core/repair/connector-fences.ts": ["test/e2e/connector-holds.test.ts"],
+ // #5886 follow-up: gbrain repair take-supersession.
+ "src/core/repair/take-supersession.ts": ["test/e2e/repair-take-supersession-postgres.test.ts"],
// Fix wave 5 (#5770): stale-atoms repair and its #5777 cross-lane journey.
"src/core/repair/stale-atoms.ts": ["test/e2e/repair-stale-atoms-postgres.test.ts", "test/e2e/journey-atoms-sync-race-postgres.test.ts", "test/e2e/managed-extract-atoms.test.ts", "test/e2e/fix-wave-5-integration.test.ts", "test/e2e/write-attribution-postgres.test.ts"],
// Fix wave 3 lane A: connector identity, account pin, no-op kernel, pending set and migration 176.
diff --git a/src/core/repair/core.ts b/src/core/repair/core.ts
index 55c2a1bade..3fc6c02bc5 100644
--- a/src/core/repair/core.ts
+++ b/src/core/repair/core.ts
@@ -24,7 +24,7 @@ import { initializeLocalPersistence, requestPrincipalForContext } from '../persi
import { lookupEmbeddingPrice, estimateCostFromChars } from '../embedding-pricing.ts';
import { shellQuote } from '../agent-output.ts';
-export const REPAIR_KINDS = ['timeline', 'visibility', 'safe-chunks', 'contextual-mode', 'connector-checkpoints', 'request-indexes', 'connector-fences', 'orphan-bindings', 'embedding-effects', 'attribution-backfill', 'planner-stats', 'google-file-modes', 'stale-atoms', 'extractor-facts', 'captured-facts', 'loop-facts', 'orphan-children', 'failed-writes', 'frontmatter'] as const;
+export const REPAIR_KINDS = ['timeline', 'visibility', 'safe-chunks', 'contextual-mode', 'connector-checkpoints', 'request-indexes', 'connector-fences', 'take-supersession', 'orphan-bindings', 'embedding-effects', 'attribution-backfill', 'planner-stats', 'google-file-modes', 'stale-atoms', 'extractor-facts', 'captured-facts', 'loop-facts', 'orphan-children', 'failed-writes', 'frontmatter'] 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 5a67806c6c..b026a20b0c 100644
--- a/src/core/repair/registry.ts
+++ b/src/core/repair/registry.ts
@@ -29,6 +29,7 @@ import { contextualModeRepair } from './contextual-mode.ts';
import { connectorCheckpointsRepair } from './connector-checkpoints.ts';
import { requestIndexesRepair } from './request-indexes.ts';
import { connectorFencesRepair } from './connector-fences.ts';
+import { takeSupersessionRepair } from './take-supersession.ts';
import { orphanBindingsRepair } from './orphan-bindings.ts';
import { embeddingEffectsRepair } from './embedding-effects.ts';
import { googleFileModesRepair } from './google-file-modes.ts';
@@ -94,6 +95,14 @@ const SPECS: Record<RepairKind, Omit<RepairKindSpec, 'kind'>> = {
+ 'carry them instead of refusing with connector_fence_below_timeline (fix wave 4). Ambiguous fences are kept and counted for a manual edit. '
+ 'Each repaired page is re-embedded by its publication.',
},
+ 'take-supersession': {
+ handler: takeSupersessionRepair, embeds: 'effect', checks: [],
+ summary: 'Rebuild takes.superseded_by for supersession chains written before the pointer moved onto the old fence row (#5886). Each struck row is linked '
+ + 'to the row that replaced it only from evidence: a committed takes_supersede receipt, a stored superseded_by, or a row carrying the old '
+ + '`superseded by #<own row>` pointer with exactly one possible predecessor. The pointer is written onto the old row and stale self-pointers are '
+ + 'dropped through a revision-bound put_page; a page whose fence is right but whose stored pointers differ is reprojected. Ambiguous pages are '
+ + 'listed with the manual edit and never changed.',
+ },
'orphan-bindings': {
handler: orphanBindingsRepair, embeds: 'none', checks: ['orphan_persistence_bindings'],
summary: 'Delete persistence source bindings whose source or source incarnation no longer exists (#5732), so a source re-added under the same id can be claimed again. '
diff --git a/src/core/repair/take-supersession.ts b/src/core/repair/take-supersession.ts
new file mode 100644
index 0000000000..46f2ee0db2
--- /dev/null
+++ b/src/core/repair/take-supersession.ts
@@ -0,0 +1,287 @@
+/**
+ * `gbrain repair take-supersession` (#5886): rebuild `takes.superseded_by`
+ * for supersession chains written before the pointer moved onto the old
+ * fence row.
+ *
+ * The canonical projection derives `superseded_by` from an inactive fence
+ * row whose source cell cites `superseded by #N`. Older `supersedeRow`
+ * struck the old row without a pointer and, when the caller gave no source,
+ * wrote `superseded by #<own row>` onto the NEW row, so managed brains store
+ * `superseded_by = NULL` (and a later strike of that new row projects a
+ * self-reference).
+ *
+ * Per page the repair links each struck row to the row that replaced it,
+ * using only evidence, in this order:
+ * 1. `journal`: a committed `takes_supersede` receipt for the page names
+ * `old_row` and `new_row`;
+ * 2. `database`: the `takes` row of a struck row still holds a
+ * `superseded_by` (the unmanaged mirror wrote it);
+ * 3. `fence_structure`: a row that carries the old self-pointer was created
+ * by a supersession, and exactly one struck, unlinked row above it
+ * remains as its predecessor (resolved repeatedly, so a chain resolves
+ * hop by hop).
+ * A page where a self-pointer row has two or more candidate predecessors, or
+ * where two pieces of evidence disagree, is ambiguous: it is reported with
+ * the candidates and the manual edit, and nothing on it changes.
+ *
+ * A page that needs a link or carries a stale self-pointer is republished
+ * through a revision-bound `put_page`, whose canonical projection then
+ * writes `superseded_by`: the old row's source cell gains
+ * `superseded by #N` after its own provenance, and self-pointers are
+ * dropped, exactly as `supersedeRow` writes a new supersession. A page whose
+ * fence is already right but whose database pointers differ is reprojected
+ * under the page key (coordinator capability on a managed brain, a
+ * maintenance transaction otherwise). A second apply finds nothing to do.
+ */
+import type { BrainEngine } from '../engine.ts';
+import { serializePageToMarkdown } from '../markdown.ts';
+import type { OperationContext } from '../ops/contract.ts';
+import { opError } from '../ops/contract.ts';
+import { readFix } from '../ops/op-fix.ts';
+import { maintenanceAttribution, maintenanceTransaction } from '../persistence/attribution.ts';
+import { withCoordinatedWrite } from '../persistence/context.ts';
+import { managedPersistenceEnabled } from '../persistence/ownership.ts';
+import { submitPageMutation } from '../persistence/page-mutations.ts';
+import { TAKES_FENCE_BEGIN, parseTakesFence, type ParsedTake } from '../takes-fence.ts';
+import { takesPreparation } from '../takes-write.ts';
+import { afterCursor, repairRequestId, type RepairCursor, type RepairHandler, type RepairItem, type RepairItemOutcome, type RepairScope } from './core.ts';
+
+export type SupersessionEvidence = 'journal' | 'database' | 'fence_structure';
+
+export interface SupersessionLink { old_row: number; new_row: number; evidence: SupersessionEvidence }
+
+export interface SupersessionAnalysis {
+ /** Pointers to write onto struck rows. */
+ links: SupersessionLink[];
+ /** Rows whose stale `superseded by #<own row>` source cell is dropped. */
+ self_pointers: number[];
+ /** Self-pointer rows with two or more candidate predecessors, or rows whose evidence conflicts. */
+ ambiguous: Array<{ new_row: number; candidates: number[] }>;
+ /** The fence after the repair (unchanged rows when nothing moves). */
+ takes: ParsedTake[];
+ /** Whether the fence text changes. */
+ fence_changed: boolean;
+}
+
+const POINTER = /superseded by #(\d+)/i;
+const SELF_POINTER = /^superseded by #(\d+)$/i;
+
+/** The `superseded_by` the canonical projection derives from a fence row. */
+function projectedPointer(t: ParsedTake): number | null {
+ return takesPreparation.toCanonicalBatchInput(0, t).superseded_by ?? null;
+}
+
+function isSelfPointer(t: ParsedTake): boolean {
+ const m = (t.source ?? '').trim().match(SELF_POINTER);
+ return m !== null && Number(m[1]) === t.rowNum;
+}
+
+/**
+ * Infer each struck row's replacement from the evidence, in evidence order.
+ * Pure: `journal` and `database` are `[old_row, new_row]` pairs.
+ */
+export function analyzeSupersession(takes: ParsedTake[], evidence: { journal: Array<[number, number]>; database: Array<[number, number]> }): SupersessionAnalysis {
+ const byRow = new Map(takes.map(t => [t.rowNum, t]));
+ const linkedTo = new Map<number, number>();
+ const linkedFrom = new Map<number, number>();
+ for (const t of takes) {
+ const p = projectedPointer(t);
+ if (p !== null && p !== t.rowNum && byRow.has(p)) { linkedTo.set(t.rowNum, p); linkedFrom.set(p, t.rowNum); }
+ }
+ // Struck rows that cite nothing, or only their own row number: the rows a link may be written onto.
+ const open = new Set(takes.filter(t => !t.active && !linkedTo.has(t.rowNum) && (!POINTER.test(t.source ?? '') || isSelfPointer(t))).map(t => t.rowNum));
+ const links: SupersessionLink[] = [];
+ const ambiguous = new Map<number, number[]>();
+ const link = (oldRow: number, newRow: number, kind: SupersessionEvidence) => {
+ links.push({ old_row: oldRow, new_row: newRow, evidence: kind });
+ linkedTo.set(oldRow, newRow); linkedFrom.set(newRow, oldRow); open.delete(oldRow);
+ };
+
+ for (const kind of ['journal', 'database'] as const) {
+ const pairs = evidence[kind].filter(([o, n]) => n > o && byRow.has(n) && byRow.has(o) && !byRow.get(o)!.active);
+ for (const [o, n] of pairs) {
+ if (!open.has(o) || linkedFrom.get(n) === o) continue;
+ // Evidence that gives this row a second successor, or this successor a second predecessor, is a conflict.
+ const rivals = pairs.filter(([o2, n2]) => (o2 === o) !== (n2 === n)).map(([o2]) => o2);
+ const taken = linkedFrom.get(n);
+ if (rivals.length || taken !== undefined) {
+ ambiguous.set(n, [...new Set([...(ambiguous.get(n) ?? []), o, ...rivals, ...(taken !== undefined ? [taken] : [])])].sort((a, b) => a - b));
+ continue;
+ }
+ link(o, n, kind);
+ }
+ }
+
+ // A self-pointer row was created by a supersession; resolve the ones with exactly one candidate, repeatedly.
+ let pending = takes.filter(t => isSelfPointer(t) && !linkedFrom.has(t.rowNum) && !ambiguous.has(t.rowNum)).map(t => t.rowNum);
+ for (let progress = true; progress;) {
+ progress = false;
+ for (const n of pending) {
+ const candidates = [...open].filter(o => o < n);
+ if (candidates.length !== 1) continue;
+ link(candidates[0], n, 'fence_structure');
+ pending = pending.filter(row => row !== n);
+ progress = true;
+ }
+ }
+ for (const n of pending) {
+ const candidates = [...open].filter(o => o < n).sort((a, b) => a - b);
+ if (candidates.length > 1) ambiguous.set(n, candidates);
+ }
+
+ const result = { ambiguous: [...ambiguous].map(([new_row, candidates]) => ({ new_row, candidates })).sort((a, b) => a.new_row - b.new_row) };
+ if (result.ambiguous.length) return { links: [], self_pointers: [], ...result, takes, fence_changed: false };
+ const self_pointers = takes.filter(isSelfPointer).map(t => t.rowNum);
+ const next = takes.map(t => {
+ const own = isSelfPointer(t) ? '' : (t.source ?? '').trim();
+ const target = links.find(l => l.old_row === t.rowNum)?.new_row;
+ if (target !== undefined) return { ...t, source: own ? `${own}; superseded by #${target}` : `superseded by #${target}` };
+ if (isSelfPointer(t)) return { ...t, source: undefined };
+ return t;
+ });
+ return { links, self_pointers, ...result, takes: next, fence_changed: links.length > 0 || self_pointers.length > 0 };
+}
+
+interface TakePage { id: number; source_id: string; slug: string }
+
+interface PagePlan {
+ page: TakePage;
+ revision: string;
+ content: string;
+ analysis: SupersessionAnalysis;
+ /** Rows whose stored `superseded_by` differs from the (repaired) fence. */
+ reproject: Array<{ row_num: number; from: number | null; to: number | null }>;
+}
+
+type PageState = PagePlan | { skipped: 'unparsed' } | null;
+
+async function readPage(engine: BrainEngine, page: TakePage): Promise<PageState> {
+ const snapshot = await engine.readPageSnapshot(page.slug, { sourceId: page.source_id });
+ if (!snapshot) return null;
+ const content = serializePageToMarkdown(snapshot.page, snapshot.tags);
+ if (content.split(TAKES_FENCE_BEGIN).length !== 2) return { skipped: 'unparsed' };
+ const parsed = parseTakesFence(content);
+ if (parsed.warnings.length || !parsed.takes.length) return { skipped: 'unparsed' };
+ const stored = await engine.executeRaw<{ row_num: number; superseded_by: number | null }>(
+ 'SELECT row_num, superseded_by FROM takes WHERE page_id = $1', [snapshot.page.id]);
+ const journal = await engine.executeRaw<{ old_row: string | null; new_row: string | null }>(
+ `SELECT outcome->>'old_row' AS old_row, outcome->>'new_row' AS new_row FROM persistence_requests
+ WHERE operation = 'takes_supersede' AND state = 'committed' AND source_id = $1
+ AND (page_id = $2 OR (page_id IS NULL AND slug = $3))`, [page.source_id, snapshot.page.id, page.slug]);
+ const pairs = (rows: Array<[unknown, unknown]>): Array<[number, number]> => rows
+ .map(([o, n]) => [Number(o), Number(n)] as [number, number])
+ .filter(([o, n]) => Number.isSafeInteger(o) && Number.isSafeInteger(n) && o > 0 && n > 0);
+ const analysis = analyzeSupersession(parsed.takes, {
+ journal: pairs(journal.map(r => [r.old_row, r.new_row])),
+ database: pairs(stored.filter(r => r.superseded_by !== null).map(r => [r.row_num, r.superseded_by])),
+ });
+ const storedBy = new Map(stored.map(r => [Number(r.row_num), r.superseded_by === null ? null : Number(r.superseded_by)]));
+ const reproject = analysis.ambiguous.length ? [] : analysis.takes
+ .filter(t => storedBy.has(t.rowNum) && storedBy.get(t.rowNum) !== projectedPointer(t))
+ .map(t => ({ row_num: t.rowNum, from: storedBy.get(t.rowNum)!, to: projectedPointer(t) }));
+ return { page: { ...page, id: snapshot.page.id }, revision: snapshot.revision, content, analysis, reproject };
+}
+
+function actionText(plan: PagePlan): string {
+ const parts = [
+ ...plan.analysis.links.map(l => `link #${l.old_row}->#${l.new_row} (${l.evidence})`),
+ ...(plan.analysis.self_pointers.length ? [`drop self-pointer on #${plan.analysis.self_pointers.join(', #')}`] : []),
+ ...(!plan.analysis.fence_changed && plan.reproject.length ? [`reproject superseded_by on #${plan.reproject.map(r => r.row_num).join(', #')}`] : []),
+ ];
+ return parts.join('; ');
+}
+
+function ambiguityFix(page: TakePage, ambiguous: SupersessionAnalysis['ambiguous']): string {
+ return ambiguous.map(a => `row #${a.new_row} replaced one of #${a.candidates.join(', #')}`).join('; ')
+ + `. Read the page (gbrain get --source ${page.source_id} -- ${page.slug}), append "; superseded by #<new row>" to the source cell of the row each new row replaced, `
+ + 'save it with the current expected_revision, then run gbrain repair take-supersession again.';
+}
+
+async function candidatePages(engine: BrainEngine, sourceIds: string[], after: RepairCursor | null): Promise<TakePage[]> {
+ const pages = await engine.executeRaw<TakePage>(
+ `SELECT p.id, p.source_id, p.slug FROM pages p
+ WHERE p.source_id = ANY($1::text[]) AND p.deleted_at IS NULL
+ AND EXISTS (SELECT 1 FROM takes t WHERE t.page_id = p.id AND (t.active = false OR t.source ILIKE '%superseded by #%'))
+ ORDER BY p.id`, [sourceIds]);
+ return pages.filter(page => afterCursor({ phase: 0, id: page.id }, after));
+}
+
+/** Reproject a page whose fence is already right: under the page key, against the planned revision. */
+async function reprojectPage(engine: BrainEngine, plan: PagePlan): Promise<void> {
+ const { page } = plan;
+ const write = async (tx: BrainEngine) => {
+ await tx.lockPageKeys([{ sourceId: page.source_id, slug: page.slug }]);
+ const current = await tx.readPageSnapshot(page.slug, { sourceId: page.source_id });
+ if (!current || current.revision !== plan.revision) {
+ throw opError('revision_conflict', 'The page changed after the supersession repair read it; nothing was written.',
+ `Page ${page.slug} in source ${page.source_id} changed during the repair, so its take pointers were left as they are. Preview again with the command in fix; it plans against the current page.`,
+ { fix: readFix('Previews the take supersession repair against the current pages without changing anything.', { argv: ['gbrain', 'repair', 'take-supersession', '--source', page.source_id] }) });
+ }
+ for (const row of plan.reproject) {
+ await tx.executeRaw('UPDATE takes SET superseded_by = $3 WHERE page_id = $1 AND row_num = $2', [page.id, row.row_num, row.to]);
+ }
+ };
+ if (await managedPersistenceEnabled(engine)) {
+ const attribution = await maintenanceAttribution(engine);
+ await engine.transaction(tx => withCoordinatedWrite(tx, [page.source_id], () => write(tx), attribution));
+ } else {
+ await maintenanceTransaction(engine, write);
+ }
+}
+
+interface SupersessionItem extends RepairItem { page: TakePage }
+
+export const takeSupersessionRepair: RepairHandler = {
+ kind: 'take-supersession',
+ async plan(engine, scope: RepairScope, after) {
+ const items: SupersessionItem[] = [];
+ const pages: Array<Record<string, unknown>> = [];
+ const ambiguous: Array<Record<string, unknown>> = [];
+ let unparsed = 0;
+ for (const page of await candidatePages(engine, scope.source_ids, after)) {
+ const state = await readPage(engine, page);
+ if (!state) continue;
+ if ('skipped' in state) { unparsed++; continue; }
+ if (state.analysis.ambiguous.length) {
+ ambiguous.push({ source_id: page.source_id, slug: page.slug, rows: state.analysis.ambiguous, fix: ambiguityFix(page, state.analysis.ambiguous) });
+ continue;
+ }
+ if (!state.analysis.fence_changed && !state.reproject.length) continue;
+ const action = actionText(state);
+ items.push({ cursor: { phase: 0, id: page.id }, source_id: page.source_id, slug: page.slug, chars: state.content.length, action, page });
+ pages.push({ source_id: page.source_id, slug: page.slug, links: state.analysis.links, self_pointers: state.analysis.self_pointers,
+ reproject: state.analysis.fence_changed ? [] : state.reproject, action });
+ }
+ return {
+ items,
+ residuals: {
+ links: pages.reduce((n, p) => n + (p.links as unknown[]).length, 0),
+ ambiguous_pages: ambiguous.length,
+ ambiguous_rows: ambiguous.reduce((n, p) => n + (p.rows as unknown[]).length, 0),
+ unparsed_pages: unparsed,
+ },
+ ...(pages.length || ambiguous.length ? { details: { pages, ambiguous } } : {}),
+ };
+ },
+ async apply(ctx: OperationContext, entry): Promise<RepairItemOutcome> {
+ const { page } = entry as SupersessionItem;
+ const state = await readPage(ctx.engine, page);
+ if (!state || 'skipped' in state) return { applied: false, outcome: 'unchanged', reason: 'the page or its takes fence is no longer readable' };
+ if (state.analysis.ambiguous.length) return { applied: false, outcome: 'ambiguous', reason: ambiguityFix(page, state.analysis.ambiguous) };
+ if (state.analysis.fence_changed) {
+ await submitPageMutation(ctx, { operation: 'put_page', params: { slug: page.slug, source_id: page.source_id,
+ content: takesPreparation.replaceFence(state.content, state.analysis.takes), expected_revision: state.revision,
+ request_id: await repairRequestId(ctx, 'take-supersession', entry, state.revision) } });
+ return { applied: true, outcome: 'repaired', detail: { links: state.analysis.links, self_pointers: state.analysis.self_pointers } };
+ }
+ if (!state.reproject.length) return { applied: false, outcome: 'unchanged' };
+ await reprojectPage(ctx.engine, state);
+ return { applied: true, outcome: 'reprojected', detail: { rows: state.reproject } };
+ },
+ render(details) {
+ const lines: string[] = [];
+ for (const p of (details.pages ?? []) as Array<{ source_id: string; slug: string; action: string }>) lines.push(` ${p.source_id}:${p.slug}: ${p.action}`);
+ for (const p of (details.ambiguous ?? []) as Array<{ source_id: string; slug: string; fix: string }>) lines.push(` ambiguous ${p.source_id}:${p.slug}: ${p.fix}`);
+ return lines;
+ },
+};
diff --git a/test/e2e/repair-take-supersession-postgres.test.ts b/test/e2e/repair-take-supersession-postgres.test.ts
new file mode 100644
index 0000000000..dd89999c29
--- /dev/null
+++ b/test/e2e/repair-take-supersession-postgres.test.ts
@@ -0,0 +1,3 @@
+import { registerPostgresTests } from '../helpers/test-backends.ts';
+
+await registerPostgresTests(() => import('../repair-take-supersession.test.ts'));
diff --git a/test/fix-wave-3-integration.test.ts b/test/fix-wave-3-integration.test.ts
index 2d251fac54..a02888b608 100644
--- a/test/fix-wave-3-integration.test.ts
+++ b/test/fix-wave-3-integration.test.ts
@@ -432,7 +432,7 @@ test('check 9: every registered repair kind reaches the remediation plan with it
await engine.executeRaw("UPDATE pages SET contextual_retrieval_mode=NULL,chunker_version=1,text_projection_revision=gen_random_uuid() WHERE source_id=$1 AND slug='people/second-example'", [f.id]);
await engine.executeRaw("INSERT INTO op_checkpoints(op,fingerprint,completed_keys,updated_at) VALUES('managed-connector',$1,'[]'::jsonb,now()-interval '9 days')", [`orphan-${randomUUID()}`]);
const kinds = AUTO_REPAIR_REGISTRY.map(spec => spec.kind);
- expect(kinds).toEqual(['timeline', 'visibility', 'safe-chunks', 'contextual-mode', 'connector-checkpoints', 'request-indexes', 'connector-fences', 'orphan-bindings', 'embedding-effects', 'attribution-backfill', 'planner-stats']);
+ expect(kinds).toEqual(['timeline', 'visibility', 'safe-chunks', 'contextual-mode', 'connector-checkpoints', 'request-indexes', 'connector-fences', 'take-supersession', 'orphan-bindings', 'embedding-effects', 'attribution-backfill', 'planner-stats']);
const planned = Object.fromEntries((await planRepairSteps(engine, { noEmbed: true })).map(step => [step.kind, step]));
expect(planned['contextual-mode']).toMatchObject({ paid: false, embeds: 'inline', command: 'gbrain repair contextual-mode --no-embed --apply' });
expect(planned['connector-checkpoints']).toMatchObject({ paid: false, embeds: 'none' });
diff --git a/test/fix-wave-4-integration.test.ts b/test/fix-wave-4-integration.test.ts
index 35027ab125..9bcb721ba7 100644
--- a/test/fix-wave-4-integration.test.ts
+++ b/test/fix-wave-4-integration.test.ts
@@ -211,7 +211,7 @@ test('X6: deactivate carries a held connector item into classic state (wave 5):
test('X11: the remediation run reaches every new repair kind, runs the free ones under --max-usd 0 and clears their doctor findings', async () => withEnv(env, async () => {
for (const engine of engines) {
expect(AUTO_REPAIR_REGISTRY.map(spec => spec.kind)).toEqual(['timeline', 'visibility', 'safe-chunks', 'contextual-mode', 'connector-checkpoints',
- 'request-indexes', 'connector-fences', 'orphan-bindings', 'embedding-effects', 'attribution-backfill', 'planner-stats']);
+ 'request-indexes', 'connector-fences', 'take-supersession', 'orphan-bindings', 'embedding-effects', 'attribution-backfill', 'planner-stats']);
// Pending work for Lane A (a dropped index) and Lane D (an orphan binding of a removed source).
await engine.executeRaw('DROP INDEX IF EXISTS persistence_requests_sync_run_open');
await withPersistenceOff(engine, async () => {
diff --git a/test/repair-command.test.ts b/test/repair-command.test.ts
index 2e36098281..25460f6186 100644
--- a/test/repair-command.test.ts
+++ b/test/repair-command.test.ts
@@ -175,7 +175,7 @@ describe('gbrain repair timeline', () => {
} finally { console.log = log; }
const json = JSON.parse(out[0]);
expect(json.scope.source_ids).toEqual([source]);
- expect(json.results.map((r: { kind: string }) => r.kind)).toEqual(['timeline', 'visibility', 'safe-chunks', 'contextual-mode', 'connector-checkpoints', 'request-indexes', 'connector-fences', 'orphan-bindings', 'embedding-effects', 'attribution-backfill', 'planner-stats']);
+ expect(json.results.map((r: { kind: string }) => r.kind)).toEqual(['timeline', 'visibility', 'safe-chunks', 'contextual-mode', 'connector-checkpoints', 'request-indexes', 'connector-fences', 'take-supersession', 'orphan-bindings', 'embedding-effects', 'attribution-backfill', 'planner-stats']);
expect(json.results[0]).toMatchObject({ mode: 'dry_run', affected: 1 });
expect(out[1]).toContain(`Scope: brain `);
expect(out[1]).toContain(`sources ${source}`);
diff --git a/test/repair-flags.test.ts b/test/repair-flags.test.ts
index 96039e3504..6c38c685ec 100644
--- a/test/repair-flags.test.ts
+++ b/test/repair-flags.test.ts
@@ -87,6 +87,6 @@ describe('gbrain repair flags', () => {
const human = await captured(['--all']);
expect(human).toContain("may queue paid embeddings: timeline, visibility, safe-chunks");
const free = JSON.parse(await captured(["--all", "--json", "--no-embed"])) as { paid_kinds: string[] };
- expect(free.paid_kinds).toEqual(["timeline", "visibility", "connector-fences", "embedding-effects"]);
+ expect(free.paid_kinds).toEqual(["timeline", "visibility", "connector-fences", "take-supersession", "embedding-effects"]);
});
});
diff --git a/test/repair-take-supersession.test.ts b/test/repair-take-supersession.test.ts
new file mode 100644
index 0000000000..7b77d731b5
--- /dev/null
+++ b/test/repair-take-supersession.test.ts
@@ -0,0 +1,218 @@
+/**
+ * #5886 follow-up: `gbrain repair take-supersession` rebuilds
+ * `takes.superseded_by` for chains written before the pointer moved onto the
+ * old fence row.
+ *
+ * Protects: a broken chain (struck rows without a pointer, new rows citing
+ * themselves) is relinked only from evidence — a committed takes_supersede
+ * receipt, a stored superseded_by, or a self-pointer row with exactly one
+ * possible predecessor — through a revision-bound put_page whose projection
+ * stores superseded_by; a page with two possible predecessors is reported
+ * with the manual edit and never changed; the preview writes nothing; a
+ * second apply changes nothing; a page whose fence is already right but whose
+ * stored pointers were cleared is reprojected.
+ * Fails when: the kind is missing, when it guesses a link the evidence does
+ * not force, when it rewrites an ambiguous page, or when a rerun rewrites
+ * a repaired page again.
+ * Why existing coverage misses it: test/takes-supersede-pointer.test.ts covers
+ * new supersessions only; nothing repairs chains already stored.
+ * Seams: none; real PGLite (and Postgres through the e2e registration), the
+ * shared `managedBrain`, and the same repair runner `gbrain repair` uses.
+ */
+import { describe, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { mkdirSync, mkdtempSync, readFileSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import type { BrainEngine } from '../src/core/engine.ts';
+import type { OperationContext } from '../src/core/ops/contract.ts';
+import { maintenanceTransaction } from '../src/core/persistence/attribution.ts';
+import { withCoordinatedWrite } from '../src/core/persistence/context.ts';
+import { claimWorktree, managedPersistenceEnabled } from '../src/core/persistence/ownership.ts';
+import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { resolveRepairScope } from '../src/core/repair/core.ts';
+import { repairRunner } from '../src/core/repair/registry.ts';
+import { analyzeSupersession } from '../src/core/repair/take-supersession.ts';
+import { parseTakesFence, renderTakesFence, type ParsedTake } from '../src/core/takes-fence.ts';
+import { managedBrain } from './helpers/managed-brain.ts';
+import { isolatedSharedSkillsEngine } from './helpers/shared-skills-engine.ts';
+import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';
+import { TEST_WRITE_ATTRIBUTION } from './helpers/write-attribution.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const take = (rowNum: number, claim: string, active: boolean, source?: string): ParsedTake =>
+ ({ rowNum, claim, kind: 'bet', holder: 'world', weight: 0.6, active, ...(source !== undefined ? { source } : {}) });
+
+const page = (title: string, takes: ParsedTake[]) =>
+ `---\ntype: note\ntitle: ${title}\n---\n# ${title}\n\nProse.\n\n## Takes\n\n${renderTakesFence(takes)}\n`;
+
+/** 1 -> 2 -> 3 written by the old supersedeRow: struck rows cite nothing, each new row cites itself. */
+const CHAIN = [
+ take(1, 'Widget co ships in Q3', false, 'call notes'),
+ take(2, 'Widget co ships in Q4', false, 'superseded by #2'),
+ take(3, 'Widget co ships in Q1', true, 'superseded by #3'),
+ take(4, 'Acme example hires a CFO', true, 'board memo'),
+];
+/** Two struck rows and two self-pointer rows: either pairing is possible. */
+const AMBIGUOUS = [
+ take(1, 'Acme example raises a seed round', false, 'press'),
+ take(2, 'Acme example hires a COO', false),
+ take(3, 'Acme example raises a Series A', true, 'superseded by #3'),
+ take(4, 'Acme example hires a CTO', true, 'superseded by #4'),
+];
+
+const submit = (ctx: OperationContext, operation: string, params: Record<string, unknown>) =>
+ submitPageMutation(ctx, { operation, params: { request_id: randomUUID(), ...params } }) as Promise<Record<string, unknown>>;
+
+async function takeRows(engine: BrainEngine, sourceId: string, slug: string) {
+ return engine.executeRaw<{ row_num: number; active: boolean; source: string | null; superseded_by: number | null }>(
+ `SELECT t.row_num, t.active, t.source, t.superseded_by FROM takes t JOIN pages p ON p.id = t.page_id
+ WHERE p.source_id = $1 AND p.slug = $2 ORDER BY t.row_num`, [sourceId, slug]);
+}
+
+async function fenceOf(engine: BrainEngine, sourceId: string, slug: string) {
+ const snapshot = (await engine.readPageSnapshot(slug, { sourceId }))!;
+ return parseTakesFence(snapshot.page.compiled_truth).takes.map(t => [t.rowNum, t.active, t.source ?? '']);
+}
+
+async function repair(engine: BrainEngine, apply: boolean) {
+ const runner = await repairRunner(engine, { apply, logger: { info() {}, warn() {}, error() {} } });
+ return runner.run('take-supersession', await resolveRepairScope(engine));
+}
+
+describe('analyzeSupersession', () => {
+ test('a chain of self-pointer rows resolves hop by hop; the pointer lands after the old row\'s own provenance', () => {
+ const result = analyzeSupersession(CHAIN, { journal: [], database: [] });
+ expect(result.ambiguous).toEqual([]);
+ expect(result.links).toEqual([
+ { old_row: 1, new_row: 2, evidence: 'fence_structure' },
+ { old_row: 2, new_row: 3, evidence: 'fence_structure' },
+ ]);
+ expect(result.takes.map(t => [t.rowNum, t.source ?? ''])).toEqual([
+ [1, 'call notes; superseded by #2'], [2, 'superseded by #3'], [3, ''], [4, 'board memo']]);
+ });
+
+ test('two possible predecessors are ambiguous and change nothing; one piece of evidence resolves the rest', () => {
+ const open = analyzeSupersession(AMBIGUOUS, { journal: [], database: [] });
+ expect(open).toMatchObject({ links: [], self_pointers: [], fence_changed: false,
+ ambiguous: [{ new_row: 3, candidates: [1, 2] }, { new_row: 4, candidates: [1, 2] }] });
+ expect(open.takes).toBe(AMBIGUOUS);
+
+ const stored = analyzeSupersession(AMBIGUOUS, { journal: [], database: [[1, 3]] });
+ expect(stored.ambiguous).toEqual([]);
+ expect(stored.links).toEqual([{ old_row: 1, new_row: 3, evidence: 'database' }, { old_row: 2, new_row: 4, evidence: 'fence_structure' }]);
+ });
+
+ test('conflicting evidence is ambiguous; a pointer already in the fence wins over stale evidence', () => {
+ expect(analyzeSupersession(AMBIGUOUS, { journal: [[1, 3], [1, 4]], database: [] }).ambiguous)
+ .toEqual([{ new_row: 3, candidates: [1] }, { new_row: 4, candidates: [1] }]);
+ const fenced = [take(1, 'A', false, 'superseded by #2'), take(2, 'B', true)];
+ expect(analyzeSupersession(fenced, { journal: [[1, 2]], database: [[1, 2]] })).toMatchObject({ links: [], ambiguous: [], fence_changed: false });
+ });
+
+ test('a struck row citing another row, or a dangling pointer, is never rewritten', () => {
+ const takes = [take(1, 'A', false, 'superseded by #9'), take(2, 'B', true, 'superseded by #2')];
+ const result = analyzeSupersession(takes, { journal: [], database: [] });
+ expect(result.links).toEqual([]);
+ expect(result.takes.map(t => t.source ?? '')).toEqual(['superseded by #9', '']);
+ });
+});
+
+for (const backend of testBackends()) {
+ const databaseUrl = backend === 'postgres' ? requirePostgresTestDatabase() : undefined;
+
+ test(`${backend}: managed: a broken chain is relinked, an ambiguous page is reported untouched, preview writes nothing and a second apply is a no-op`, async () => {
+ await managedBrain(async ({ engine, ctx, root }) => {
+ expect(await managedPersistenceEnabled(engine)).toBe(true);
+ await submit(ctx, 'put_page', { slug: 'notes/chain', content: page('Chain', CHAIN) });
+ await submit(ctx, 'put_page', { slug: 'notes/ambiguous', content: page('Ambiguous', AMBIGUOUS) });
+ // A real supersession whose fence an old binary then rewrote into the old shape: only the journal knows the link.
+ await submit(ctx, 'put_page', { slug: 'notes/journal', content: page('Journal', [take(1, 'Widget co hires', true, 'memo'), take(2, 'Widget co raises', true, 'deck')]) });
+ expect(await submit(ctx, 'takes_supersede', { slug: 'notes/journal', row_num: 2, claim: 'Widget co raises more' })).toMatchObject({ state: 'committed', old_row: 2, new_row: 3 });
+ await submit(ctx, 'put_page', { slug: 'notes/journal', content: page('Journal', [take(1, 'Widget co hires', false, 'memo'),
+ take(2, 'Widget co raises', false, 'deck'), take(3, 'Widget co raises more', true, 'superseded by #3')]),
+ expected_revision: (await engine.readPageSnapshot('notes/journal', { sourceId: 'default' }))!.revision });
+
+ expect((await takeRows(engine, 'default', 'notes/chain')).map(r => r.superseded_by)).toEqual([null, 2, null, null]);
+ expect((await takeRows(engine, 'default', 'notes/journal')).map(r => r.superseded_by)).toEqual([null, null, null]);
+
+ const revisions = async () => Promise.all(['notes/chain', 'notes/ambiguous', 'notes/journal'].map(async slug =>
+ (await engine.readPageSnapshot(slug, { sourceId: 'default' }))!.revision));
+ const requests = async () => (await engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM persistence_requests'))[0].n;
+ const before = { revisions: await revisions(), requests: await requests(), chain: await takeRows(engine, 'default', 'notes/chain') };
+
+ const preview = await repair(engine, false);
+ expect(preview).toMatchObject({ mode: 'dry_run', affected: 2, residuals: { links: 3, ambiguous_pages: 1, ambiguous_rows: 2, unparsed_pages: 0 } });
+ expect(preview.sample).toEqual(['default:notes/chain', 'default:notes/journal']);
+ const details = preview.details as { pages: Array<{ slug: string; action: string }>; ambiguous: Array<{ source_id: string; slug: string; rows: unknown; fix: string }> };
+ expect(details.pages.map(p => [p.slug, p.action])).toEqual([
+ ['notes/chain', 'link #1->#2 (fence_structure); link #2->#3 (fence_structure); drop self-pointer on #2, #3'],
+ ['notes/journal', 'link #2->#3 (journal); drop self-pointer on #3'],
+ ]);
+ expect(details.ambiguous).toEqual([{ source_id: 'default', slug: 'notes/ambiguous',
+ rows: [{ new_row: 3, candidates: [1, 2] }, { new_row: 4, candidates: [1, 2] }], fix: expect.stringContaining('gbrain get --source default -- notes/ambiguous') }]);
+ expect(await revisions()).toEqual(before.revisions);
+ expect(await requests()).toBe(before.requests);
+ expect(await takeRows(engine, 'default', 'notes/chain')).toEqual(before.chain);
+
+ const applied = await repair(engine, true);
+ expect(applied).toMatchObject({ mode: 'apply', applied: 2, skipped: 0, complete: true, outcomes: { repaired: 2 } });
+ expect((await takeRows(engine, 'default', 'notes/chain')).map(r => [r.row_num, r.active, r.source ?? '', r.superseded_by])).toEqual([
+ [1, false, 'call notes; superseded by #2', 2],
+ [2, false, 'superseded by #3', 3],
+ [3, true, '', null],
+ [4, true, 'board memo', null],
+ ]);
+ expect((await takeRows(engine, 'default', 'notes/journal')).map(r => [r.row_num, r.superseded_by])).toEqual([[1, null], [2, 3], [3, null]]);
+ expect(await fenceOf(engine, 'default', 'notes/ambiguous')).toEqual(AMBIGUOUS.map(t => [t.rowNum, t.active, t.source ?? '']));
+ const file = readFileSync(join(root, 'notes/chain.md'), 'utf8');
+ expect(parseTakesFence(file).takes.map(t => t.source ?? '')).toEqual(['call notes; superseded by #2', 'superseded by #3', '', 'board memo']);
+
+ const afterApply = { revisions: await revisions(), requests: await requests() };
+ const second = await repair(engine, true);
+ expect(second).toMatchObject({ affected: 0, applied: 0, residuals: { links: 0, ambiguous_pages: 1 } });
+ expect(await revisions()).toEqual(afterApply.revisions);
+ expect(await requests()).toBe(afterApply.requests);
+ }, { databaseUrl });
+ }, 120_000);
+
+ test(`${backend}: a page whose fence is right but whose stored pointers were cleared is reprojected, managed and unmanaged`, async () => {
+ const fence = [take(1, 'Widget co ships in Q3', false, 'call notes; superseded by #2'), take(2, 'Widget co ships in Q4', true, 'call notes')];
+ const clearPointers = (write: (fn: (tx: BrainEngine) => Promise<unknown>) => Promise<unknown>) =>
+ write(tx => tx.executeRaw(`UPDATE takes SET superseded_by = NULL WHERE page_id = (SELECT id FROM pages WHERE source_id = 'default' AND slug = 'notes/reproject')`));
+ const check = async (engine: BrainEngine) => {
+ const revision = (await engine.readPageSnapshot('notes/reproject', { sourceId: 'default' }))!.revision;
+ expect((await takeRows(engine, 'default', 'notes/reproject')).map(r => r.superseded_by)).toEqual([null, null]);
+ const applied = await repair(engine, true);
+ expect(applied).toMatchObject({ applied: 1, outcomes: { reprojected: 1 } });
+ expect((await takeRows(engine, 'default', 'notes/reproject')).map(r => r.superseded_by)).toEqual([2, null]);
+ expect((await engine.readPageSnapshot('notes/reproject', { sourceId: 'default' }))!.revision).toBe(revision);
+ expect(await repair(engine, true)).toMatchObject({ affected: 0, applied: 0 });
+ };
+
+ await managedBrain(async ({ engine, ctx }) => {
+ await submit(ctx, 'put_page', { slug: 'notes/reproject', content: page('Reproject', fence) });
+ await clearPointers(fn => engine.transaction(tx => withCoordinatedWrite(tx, ['default'], () => fn(tx), TEST_WRITE_ATTRIBUTION)));
+ await check(engine);
+ }, { databaseUrl });
+
+ const home = mkdtempSync(join(tmpdir(), 'gbrain-take-supersession-'));
+ try {
+ await withEnv({ GBRAIN_HOME: home, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined }, async () => {
+ const { engine, close } = await isolatedSharedSkillsEngine(databaseUrl);
+ try {
+ const root = join(home, 'brain'); mkdirSync(root);
+ await engine.executeRaw("UPDATE sources SET local_path = $1 WHERE id = 'default'", [root]);
+ await claimWorktree(engine, 'default', root);
+ const ctx = { engine, config: { engine: engine.kind, embedding_disabled: true }, sourceId: 'default', remote: false,
+ dryRun: false, logger: { info() {}, warn() {}, error() {} } } as OperationContext;
+ await submit(ctx, 'put_page', { slug: 'notes/reproject', content: page('Reproject', fence) });
+ expect(await managedPersistenceEnabled(engine)).toBe(false);
+ await clearPointers(fn => maintenanceTransaction(engine, fn));
+ await check(engine);
+ } finally { await disposePersistenceConsumer(engine); await close(); }
+ });
+ } finally { rmSync(home, { recursive: true, force: true }); }
+ }, 120_000);
+}