Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(consolidate): #6023 hold a cluster whose typed claims tie at one effective instant; gbrain repair consolidate-ties reopens facts an earlier run closed
garrytan34782abe9b68
diff --git a/docs/architecture/canonical-writers.tsv b/docs/architecture/canonical-writers.tsvindex 9631217366..4c1fbab907 100644--- a/docs/architecture/canonical-writers.tsv+++ b/docs/architecture/canonical-writers.tsv@@ -222,6 +222,7 @@ src/core/repair/extractor-facts.ts 1 coordinator `gbrain repair extractor-facts`src/core/repair/captured-facts.ts 1 coordinator `gbrain repair captured-facts` expires preview-approved capture-lane facts that have no fence row. On a managed brain the UPDATE runs only inside the managed_maintenance_expire_captured_facts publication (owner-checked by maintenancePreflight, page key locked); an unmanaged brain runs it in one transaction. Fenced rows are never updated here: they are struck in the page and expired by the canonical projection of a revision-bound put_page.src/core/repair/ontology-facts.ts 1 coordinator `gbrain repair ontology-facts` (#6264) gives preview-approved ontology observations their own provenance back, clears their fence row number and expiry. On a managed brain the UPDATE runs only inside coordinatedDatabaseWrite (the ontology_propose path: write authority checked, source incarnation revalidated, entity and page keys locked); an unmanaged brain runs it in one maintenance transaction. It writes database-only ontology rows and never a page or file.src/core/repair/facts-rehome.ts 1 coordinator `gbrain repair facts-rehome` (B-7, #6925) moves preview-approved database-only facts off a page-less entity_slug onto the page the strict resolver reaches. On a managed brain the UPDATE runs only inside coordinatedDatabaseWrite (the relink_facts operation: write authority checked, source incarnation revalidated, both slugs locked); an unmanaged brain runs one maintenance transaction per slug. It rechecks the slug, target and fact ids against the preview and never writes a page or file.+src/core/repair/consolidate-ties.ts 1 coordinator `gbrain repair consolidate-ties` (#6023) sets preview-approved typed facts that consolidation closed at their own effective instant back to open validity. On a managed brain the UPDATE runs only inside coordinatedDatabaseWrite (the relink_facts operation: write authority checked, source incarnation revalidated, the entity key locked); an unmanaged brain runs one maintenance transaction per fact. It rechecks the fact, take and instant against the preview and never writes a page or file.src/core/repair/conversation-labels.ts 4 coordinator `gbrain repair conversation-labels` expires preview-approved label-misattributed conversation facts, expires the page completion marker and writes the not-extractable outcome, under the page key: one database-only managed_maintenance_conversation_label_retire request per batch of up to 25 pages on a managed brain (the preparer reclassifies each page under its lock), one maintenanceTransaction per batch on an unmanaged brain.src/core/persistence/atom-maintenance.ts 1 coordinator A managed atom retirement stamps retired_by/retired_at on the tombstone inside the coordinator publication of its managed_atom_delete request, after the page deletion path removed the canonical file, so the database row and file change commit or roll back together.src/core/repair/stale-atoms.ts 2 coordinator gbrain repair stale-atoms retires an atom on a managed brain through a managed_maintenance_retire_stale_atoms coordinated request (the marker stamp runs in its publication); only an unmanaged brain soft-deletes and stamps in a direct page-locked transaction, where no canonical writer enforcement applies.diff --git a/docs/architecture/system-of-record.md b/docs/architecture/system-of-record.mdindex 540754b0e6..a9866a58e8 100644--- a/docs/architecture/system-of-record.md+++ b/docs/architecture/system-of-record.md@@ -290,6 +290,7 @@ or a physical projection that leaves attribution untouched):- `src/core/persistence/takes-prepare.ts` (3): takes request preparer.- `src/core/repair/atoms-restore.ts` (3): the unmanaged `gbrain repair atoms-restore` apply archives the retired atom's version, restores it and drops its `retired_by`/`retired_at` stamp in one `maintenanceTransaction`; managed brains publish a `managed_maintenance_restore_reextract_atom` request instead.- `src/core/repair/captured-facts.ts` (1): a request on managed brains; the unmanaged captured-facts expiry runs in `maintenanceTransaction`.+- `src/core/repair/consolidate-ties.ts` (1): `gbrain repair consolidate-ties` reopens facts inside `coordinatedDatabaseWrite` on managed brains (the `relink_facts` operation) and in one `maintenanceTransaction` per fact on unmanaged brains.- `src/core/repair/conversation-labels.ts` (4): a request on managed brains; the unmanaged label retirement runs in `maintenanceTransaction`.- `src/core/repair/extractor-facts.ts` (1): a request on managed brains; the unmanaged extractor-facts restore runs in `maintenanceTransaction`.- `src/core/repair/facts-rehome.ts` (1): `gbrain repair facts-rehome` moves facts inside `coordinatedDatabaseWrite` on managed brains (the `relink_facts` operation) and in one `maintenanceTransaction` per slug on unmanaged brains.diff --git a/docs/guides/repair.md b/docs/guides/repair.mdindex df780aa5c4..33ef67064c 100644--- a/docs/guides/repair.md+++ b/docs/guides/repair.md@@ -1547,6 +1547,40 @@ gained a page, lost its target or whose facts changed since the preview reportsthe target is merged rather than copied. It writes the database only; no page isrewritten.+<a id="consolidate-ties"></a>+### Facts consolidation closed at their own effective time++Before this release, when two typed facts stated the same metric, unit and+period for the same effective time (an amount and its correction recorded on+one day, or one statement stored twice), the dream `consolidate` phase still+merged them: the take kept the higher-confidence statement and the other got+a `valid_until` equal to its own `valid_from`, a zero-length validity that+quietly marked a real fact superseded (#6023). The phase now leaves such a+cluster unchanged and reports it under `details.same_instant_clusters` with a+next step. `gbrain repair consolidate-ties` finds the facts an earlier run+closed this way and reopens them. It is explicit-only and preview-bound, and it+never runs on upgrade.++**Say to your agent:** *"Preview the facts consolidation closed at their own+effective time, then reopen them after I agree."* The agent runs+`gbrain repair consolidate-ties` and, after you agree, the printed apply command.++```bash+gbrain repair consolidate-ties # preview: one line per closed fact+gbrain repair consolidate-ties --apply --expect <hash>+```++A candidate is an active typed fact consolidated into a take whose+`valid_until` equals its `valid_from`, where another fact in the same take+states the same metric, unit and period at the same instant. The preview names+the fact, its tied partners and the take. The apply sets exactly the previewed+facts back to open validity (consolidation only touched facts that were+current) and keeps their consolidation mark; a fact that was expired, edited or+reopened since the preview reports `changed_since_preview` and is kept. The+take is not changed: if it holds the wrong statement, decide which one is+current and `gbrain forget` the other. It writes the database only; no page is+rewritten.+<a id="failed-writes"></a>### Failed writesdiff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 9347a38d1b..91956a8b2b 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -912,6 +912,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;{ since: '0.60.309.0', text: 'A brain without an embedding provider no longer queues embed-backfill jobs; one already queued ends once with the notice `embed_backfill_skipped`. A managed sync job submitted without pull options imports the checkout HEAD instead of failing permanently. A mention whose link target is not a valid slug is skipped instead of failing the links effect (#7008).' },{ since: '0.60.309.0', text: '`gbrain backup check` reads a dirty tree as dirty however long its status listing is (a listing over 1 MiB used to read `probe_failed`), the remote probe timeout is configurable with `backup.remote_timeout_ms` (or GBRAIN_BACKUP_REMOTE_TIMEOUT_MS, 0.5 to 30 s, default 2 s), and a timed-out probe is counted in `totals.remote_timeouts` and named as a timeout, not as a missing backup (#6907).' },{ since: '0.60.309.0', text: 'Managed dream synthesis counts a transcript a pre-managed run already synthesised as done while a dream-generated page naming that transcript still exists in the same source, so upgrading to managed mode no longer re-synthesises old transcripts (#6924).' },+ { since: '0.60.310.0', text: 'The dream `consolidate` phase no longer promotes a cluster in which two typed facts state the same metric, unit and period for the same effective time (an original amount and its correction recorded on one day, or the same statement twice). It used to keep the higher-confidence one as the take and close the other at its own instant, a zero-length validity that silently marked a real fact superseded. Such a cluster is now left unchanged: the phase reports `warn` with `details.clusters_held_same_instant` and `details.same_instant_clusters`, each with the fact ids and a next step (ask which statement is current, then `gbrain forget` the other). Facts an earlier run closed this way are listed by `gbrain repair consolidate-ties`, which reopens exactly the previewed ones on `--apply --expect <hash>`; nothing changes on upgrade.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/cycle/phases/consolidate.ts b/src/core/cycle/phases/consolidate.tsindex 2d20cabf8d..f452d4a4ae 100644--- a/src/core/cycle/phases/consolidate.ts+++ b/src/core/cycle/phases/consolidate.ts@@ -28,6 +28,7 @@ import type { BrainEngine, FactRow } from '../../engine.ts';import type { PhaseResult } from '../../cycle.ts';import { cosineSimilarity } from '../../facts/classify.ts';import { claimsDiverge, EXPLICIT_DUPLICATE_THRESHOLD } from '../../facts/capture-dedup.ts';+import { sameInstantTies, type SameInstantTie } from '../../facts/claim-ties.ts';import { createHash } from 'node:crypto';import { isAborted } from '../../abort-check.ts';import { classifyItemFailure, ItemRun } from '../../item-failure.ts';@@ -156,6 +157,8 @@ export async function runPhaseConsolidate(let clustersSkippedRetired = 0;let clustersGateHeld = 0;let clustersGateRejected = 0;+ let clustersHeldSameInstant = 0;+ const sameInstantClusters: SameInstantCluster[] = [];// #6023: a dry run lists the clusters it would write so an operator can// inspect them before `--yes`; capped so the envelope stays bounded.const preview: ConsolidateClusterPreview[] = [];@@ -263,6 +266,8 @@ export async function runPhaseConsolidate(for (const cluster of clusters) {if (cluster.length < 2) continue;+ const tie = clusterTie(cluster, claims);+ if (tie) { clustersHeldSameInstant += 1; if (sameInstantClusters.length < SAME_INSTANT_SAMPLES) sameInstantClusters.push(heldCluster(b, tie)); continue; }// Take selection: pick the highest-confidence fact's text as the// take claim (v0.31 deterministic). v0.32 will swap to a Sonnet// synthesis pass.@@ -297,6 +302,7 @@ export async function runPhaseConsolidate(factsConsolidated += Number(receipt.facts_consolidated ?? 0);takesWritten += Number(receipt.takes_written ?? 0);if (receipt.reason === 'retired_take') clustersSkippedRetired++;+ if (receipt.reason === 'same_instant_typed_claims') clustersHeldSameInstant++;continue;}@@ -400,15 +406,16 @@ export async function runPhaseConsolidate(return {phase: 'consolidate',- status: bucketsFailed > 0 ? 'warn' : factsConsolidated === 0 && clustersSkippedRetired > 0 ? 'skipped' : 'ok',+ status: bucketsFailed > 0 || clustersHeldSameInstant > 0 ? 'warn' : factsConsolidated === 0 && clustersSkippedRetired > 0 ? 'skipped' : 'ok',duration_ms: 0,- summary: dryRun+ summary: (dryRun? `(dry-run) would promote ${factsConsolidated} facts into ${takesWritten} takes across ${bucketsProcessed} buckets`: `promoted ${factsConsolidated} facts into ${takesWritten} takes across ${bucketsProcessed} buckets` +(clustersSkippedRetired ? `; skipped ${clustersSkippedRetired} clusters with retired takes` : '') +(clustersGateHeld ? `; held ${clustersGateHeld} takes for write-gate review` : '') +(clustersGateRejected ? `; write gate rejected ${clustersGateRejected} takes` : '') +- (bucketsFailed ? `; ${bucketsFailed} bucket(s) failed (details.bucket_failures)` : ''),+ (bucketsFailed ? `; ${bucketsFailed} bucket(s) failed (details.bucket_failures)` : '')) ++ (clustersHeldSameInstant ? `; held ${clustersHeldSameInstant} cluster(s) whose typed claims state one metric for the same effective time (details.same_instant_clusters)` : ''),details: {dryRun,cluster_threshold: threshold,@@ -422,6 +429,8 @@ export async function runPhaseConsolidate(clusters_skipped_retired: clustersSkippedRetired,clusters_gate_held: clustersGateHeld,clusters_gate_rejected: clustersGateRejected,+ clusters_held_same_instant: clustersHeldSameInstant,+ same_instant_clusters: sameInstantClusters,buckets_failed: bucketsFailed,bucket_failures: bucketFailures,...(factsConsolidated === 0 && clustersSkippedRetired > 0 ? { reason: 'retired_take' } : {}),@@ -443,6 +452,34 @@ async function gateNewTake(engine: BrainEngine, derivation: { trust: WriteTrust;return gate;}+/** One cluster held because two or more of its typed claims tie at one effective instant (`details.same_instant_clusters`). */+export interface SameInstantCluster {+ source_id: string;+ entity_slug: string;+ metric: string;+ unit: string | null;+ period: string | null;+ valid_from: string;+ fact_ids: number[];+ fix: Action;+}+const SAME_INSTANT_SAMPLES = 20;++function clusterTie(cluster: FactRow[], claims: Map<number, ClaimShape>): SameInstantTie | undefined {+ return sameInstantTies(cluster.map(f => ({ id: f.id, at: f.valid_from.getTime(), metric: claims.get(f.id)?.metric ?? null,+ unit: claims.get(f.id)?.unit ?? null, period: claims.get(f.id)?.period ?? null })))[0];+}++function heldCluster(bucket: { source_id: string; entity_slug: string }, tie: SameInstantTie): SameInstantCluster {+ const validFrom = new Date(tie.at).toISOString();+ const claim = [tie.metric, tie.unit, tie.period].filter(Boolean).join(', ');+ return { source_id: bucket.source_id, entity_slug: bucket.entity_slug, metric: tie.metric, unit: tie.unit, period: tie.period, valid_from: validFrom,+ fact_ids: tie.ids, fix: { ask_user: true, argv: ['gbrain', 'forget', '<FACT_ID>'], consent: [], actor: 'agent', requires_exclusive: false,+ inputs: [{ name: 'FACT_ID', how: `One of facts ${tie.ids.join(', ')}: the statement the user says is no longer current; for exact duplicates, any one of them.` }],+ why: 'Consolidation cannot order statements of one metric at one effective time, so it left the cluster unchanged; forgetting the stale one lets the next consolidate run promote the rest.',+ user_message: `Facts ${tie.ids.join(', ')} on ${bucket.entity_slug} state ${claim} for the same effective time (${validFrom}), and gbrain cannot tell which one is current, so it left them unconsolidated. Which one should stay? The other is forgotten, and the next consolidate run promotes the cluster.` } };+}+/** The typed-claim columns of a fact (FactRow does not carry them). */export interface ClaimShape {metric: string | null;diff --git a/src/core/facts/claim-ties.ts b/src/core/facts/claim-ties.tsnew file mode 100644index 0000000000..1a55eb6d22--- /dev/null+++ b/src/core/facts/claim-ties.ts@@ -0,0 +1,25 @@+/**+ * #6023: typed claims of one consolidation cluster that state the same metric,+ * unit and period for the same effective instant. Neither confidence nor row id+ * says which one corrects the other (or whether they are the same statement+ * twice), so the chronological writeback would pick a winner and close the+ * other at its own instant. Consolidation holds such a cluster unchanged; the+ * phase checks before submitting and the managed preparer checks an intent an+ * older release admitted.+ */+export interface ClaimInstant { id: number; at: number; metric: string | null; unit: string | null; period: string | null }++export interface SameInstantTie { ids: number[]; metric: string; unit: string | null; period: string | null; at: number }++/** Each group of two or more typed members sharing (metric, unit, period, instant), in first-member order; empty when there is none. */+export function sameInstantTies(members: readonly ClaimInstant[]): SameInstantTie[] {+ const groups = new Map<string, SameInstantTie>();+ for (const m of members) {+ if (m.metric === null) continue;+ const key = JSON.stringify([m.metric, m.unit, m.period, m.at]);+ const group = groups.get(key);+ if (group) group.ids.push(m.id);+ else groups.set(key, { ids: [m.id], metric: m.metric, unit: m.unit, period: m.period, at: m.at });+ }+ return [...groups.values()].filter(g => g.ids.length > 1);+}diff --git a/src/core/persistence/prepared-maintenance.ts b/src/core/persistence/prepared-maintenance.tsindex aa7be9ae59..d199746f8a 100644--- a/src/core/persistence/prepared-maintenance.ts+++ b/src/core/persistence/prepared-maintenance.ts@@ -31,6 +31,7 @@ import { isConnectorSourceKind } from './connector-identity.ts';import { MaintenanceWriteWait } from './maintenance-wait.ts';import { auditConflictsCommand, FILE_DRIFT_MESSAGE, liveFileDrift } from './drift-conflicts.ts';import { declaredWriteTrust, lowerToDerivedTier, readDerivationDeclaration, recordTaintEdges, type DerivationDeclaration } from '../trust/taint.ts';+import { sameInstantTies } from '../facts/claim-ties.ts';export interface MaintenanceAuthority {writer: WriteAuthority;@@ -542,6 +543,11 @@ async function prepareMaintenanceKind(engine: BrainEngine, row: WriteRequest, coconst p = row.intent;const facts = p.facts as FactSnapshot[];const pages = p.pages as EvidencePage[];+ if (sameInstantTies(facts.map(f => ({ id: f.id, at: Date.parse(String(f.value.valid_from)), metric: (f.value.claim_metric as string | null) ?? null,+ unit: (f.value.claim_unit as string | null) ?? null, period: (f.value.claim_period as string | null) ?? null }))).length) {+ return { observedRevision: p.expected_revision as string, noop: true, apply: async () => ({ status: 'skipped', reason: 'same_instant_typed_claims', noop: true,+ facts_consolidated: 0, takes_written: 0 }) };+ }const [existing] = await engine.executeRaw<{ id: number; row_num: number; active: boolean; resolved_at: unknown }>("SELECT id,row_num,active,resolved_at FROM takes WHERE page_id=$1 AND claim=$2 AND kind='fact' AND holder='self' ORDER BY id LIMIT 1", [row.page_id, p.claim]);if (existing && (!existing.active || existing.resolved_at)) {diff --git a/src/core/persistence/preview-approval.ts b/src/core/persistence/preview-approval.tsindex 6a1be58b00..150fbf7026 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' | 'conversation-labels' | 'captured-facts' | 'loop-facts' | 'ontology-facts' | 'facts-rehome' | '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' | 'missing-tables';+export type PreviewApprovalCommand = 'authorize-legacy' | 'jobs-cancel' | 'stale-atoms' | 'atoms-restore' | 'extractor-facts' | 'conversation-labels' | 'captured-facts' | 'loop-facts' | 'ontology-facts' | 'facts-rehome' | 'consolidate-ties' | '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' | 'missing-tables';export interface ApprovedSetKey {command: PreviewApprovalCommand;diff --git a/src/core/repair/consolidate-ties.ts b/src/core/repair/consolidate-ties.tsnew file mode 100644index 0000000000..b0c04e0584--- /dev/null+++ b/src/core/repair/consolidate-ties.ts@@ -0,0 +1,118 @@+/**+ * `gbrain repair consolidate-ties` (#6023): reopen facts that consolidation+ * closed at their own effective instant.+ *+ * Before this release, a cluster with two typed claims stating one metric,+ * unit and period for the same effective time was promoted anyway: the take+ * took the higher-confidence statement and the chronological writeback set+ * the other one's `valid_until` to its own `valid_from`, a zero-length+ * interval that quietly marked a real fact superseded. Consolidation now holds+ * such clusters; this repair finds the facts the old writeback closed.+ *+ * Candidates: an active typed fact consolidated into a take whose+ * `valid_until` equals its `valid_from`, where another fact consolidated+ * into the same take states the same metric, unit and period at the same+ * instant. A restore sets `valid_until` back to NULL (the writeback only+ * touched facts that were current) and keeps the consolidation mark, so the+ * fact is current again beside its partner; the preview names the take so the+ * operator can judge it.+ *+ * Explicit-only and preview-bound: the preview lists every candidate, prints a+ * hash and saves the set; `--apply --expect <hash>` restores exactly that set,+ * rechecking each fact in its own transaction and keeping it as+ * `changed_since_preview` when it no longer matches. On a managed brain each+ * restore commits as one coordinated database-only write on the entity's key.+ * Nothing runs on upgrade, and no page is rewritten.+ */+import type { BrainEngine } from '../engine.ts';+import { OperationError } from '../ops/contract.ts';+import { RELINK_OPERATION } from '../facts/relink-publish.ts';+import { maintenanceTransaction } from '../persistence/attribution.ts';+import { coordinatedDatabaseWrite } from '../persistence/database-write.ts';+import { clearApprovedSet, loadApprovedSet, previewChangedError, previewHash, saveApprovedSet } from '../persistence/preview-approval.ts';+import { afterCursor, type RepairHandler, type RepairItem, type RepairItemOutcome, type RepairPlan, type RepairScope } from './core.ts';++export interface ClosedTie {+ source_id: string;+ id: number;+ entity_slug: string;+ take_id: number;+ valid_from: string;+ /** The facts consolidated into the same take that state the same claim at the same instant. */+ partners: number[];+}++/** Every fact the pre-#6023 writeback closed at its own instant, in (source, id) order. Read-only. */+export async function findClosedTies(engine: BrainEngine, sourceIds: string[]): Promise<ClosedTie[]> {+ const rows = await engine.executeRaw<{ source_id: string; id: number | string; entity_slug: string; take_id: number | string; valid_from: string;+ partners: Array<number | string> | null }>(`+ SELECT f.source_id, f.id, f.entity_slug, f.consolidated_into AS take_id, f.valid_from::text AS valid_from,+ (SELECT array_agg(g.id ORDER BY g.id) FROM facts g+ WHERE g.source_id = f.source_id AND g.id <> f.id AND g.consolidated_into = f.consolidated_into+ AND g.claim_metric = f.claim_metric AND g.claim_unit IS NOT DISTINCT FROM f.claim_unit+ AND g.claim_period IS NOT DISTINCT FROM f.claim_period AND g.valid_from = f.valid_from) AS partners+ FROM facts f+ WHERE f.source_id = ANY($1::text[]) AND f.expired_at IS NULL AND f.claim_metric IS NOT NULL+ AND f.consolidated_into IS NOT NULL AND f.valid_until = f.valid_from AND f.entity_slug IS NOT NULL+ ORDER BY f.source_id, f.id`, [sourceIds]);+ return rows.filter(row => row.partners?.length).map(row => ({ source_id: row.source_id, id: Number(row.id), entity_slug: row.entity_slug,+ take_id: Number(row.take_id), valid_from: row.valid_from, partners: row.partners!.map(Number) }));+}++interface ApprovedTie extends ClosedTie { selection: string[] }+interface RestoreItem extends RepairItem { tie: ClosedTie; hash: string; last: boolean }++function previewCommand(scope: RepairScope): string {+ return `gbrain repair consolidate-ties${scope.source_ids.length === 1 ? ` --source ${scope.source_ids[0]}` : ''}`;+}++const sourcesOf = (engine: BrainEngine, scope: RepairScope) => 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]);++const hashOf = (scope: RepairScope, sources: unknown, ties: ClosedTie[]) =>+ previewHash({ kind: 'consolidate-ties-v1', brain_id: scope.brain_id, sources, selection: { source_ids: scope.source_ids }, ties });++function item(tie: ClosedTie, index: number, hash: string, last: boolean): RestoreItem {+ return { cursor: { phase: 1, id: index }, source_id: tie.source_id, slug: tie.entity_slug, chars: 0, action: 'restore', tie, hash, last };+}++export const consolidateTiesRepair: RepairHandler = {+ kind: 'consolidate-ties',+ publication: 'projection',+ embeds: false,+ async plan(engine, scope, after, opts): Promise<RepairPlan> {+ const command = previewCommand(scope);+ if (!opts?.apply) {+ const ties = await findClosedTies(engine, scope.source_ids);+ const hash = hashOf(scope, await sourcesOf(engine, scope), ties);+ if (ties.length) await saveApprovedSet<ApprovedTie>(engine, { command: 'consolidate-ties', hash }, ties.map(t => ({ ...t, selection: scope.source_ids })));+ return { items: ties.map((t, index) => item(t, index, hash, index === ties.length - 1)), preview_hash: hash, residuals: {},+ listing: ties.map(t => ({ item: `${t.source_id}:${t.id}`, class: 'restore',+ detail: `fact ${t.id} on ${t.entity_slug} was closed at its own effective time ${t.valid_from} when consolidation broke a tie with fact(s) `+ + `${t.partners.join(', ')} into take ${t.take_id}; restore reopens it` })) };+ }+ if (!opts.expect) {+ throw new OperationError('invalid_params', 'gbrain repair consolidate-ties --apply restores 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#explicit-only-repair-kinds');+ }+ const approved = await loadApprovedSet<ApprovedTie>(engine, { command: 'consolidate-ties', hash: opts.expect, previewCommand: command,+ emptyHash: async () => hashOf(scope, await sourcesOf(engine, scope), []) });+ if (approved.items.some(t => JSON.stringify(t.selection) !== JSON.stringify(scope.source_ids))) throw previewChangedError(opts.expect, command);+ const items = approved.items.map(({ selection: _selection, ...t }, index) => item(t, index, 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 { tie, hash, last } = entry as RestoreItem;+ const restore = async (tx: BrainEngine): Promise<boolean> => (await tx.executeRaw<{ id: number }>(+ `UPDATE facts SET valid_until = NULL+ WHERE source_id = $1 AND id = $2 AND entity_slug = $3 AND consolidated_into = $4 AND expired_at IS NULL+ AND valid_until = valid_from AND valid_from = $5::timestamptz+ RETURNING id`, [tie.source_id, tie.id, tie.entity_slug, tie.take_id, tie.valid_from])).length === 1;+ const managed = await coordinatedDatabaseWrite({ ...ctx, sourceId: tie.source_id }, RELINK_OPERATION, tie.entity_slug, [tie.entity_slug], tx => restore(tx));+ const restored = managed ? managed.value : await maintenanceTransaction(ctx.engine, restore);+ if (last) await clearApprovedSet(ctx.engine, { command: 'consolidate-ties', hash });+ if (!restored) return { applied: false, outcome: 'changed_since_preview', reason: 'the fact was expired, edited or reopened since the preview' };+ return { applied: true, outcome: 'restored', detail: { fact: tie.id, take: tie.take_id } };+ },+};diff --git a/src/core/repair/core.ts b/src/core/repair/core.tsindex 9a4b0d7b1f..eafbb2fc7b 100644--- a/src/core/repair/core.ts+++ b/src/core/repair/core.ts@@ -49,7 +49,7 @@ import { RECEIPT_RESERVATION_FLOOR } from '../persistence/receipt-bytes.ts';import { readFix } from '../ops/op-fix.ts';import { ItemRun, type ItemFailure } from '../item-failure.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', 'conversation-labels', 'captured-facts', 'loop-facts', 'ontology-facts', 'facts-rehome', 'orphan-children', 'failed-writes', 'split-facts', 'frontmatter', 'fences', 'slug-conflicts', 'timeline-comments', 'managed-sync-orphans', 'content-receipt-root', 'frontmatter-keys', 'file-drift', 'stuck-recovery', 'ghost-pages', 'origin-twins', 'receipt-compaction', 'aliases', 'rename-identity', 'overwritten-edits', 'missing-tables', 'url-clone-fences'] 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', 'extractor-facts', 'conversation-labels', 'captured-facts', 'loop-facts', 'ontology-facts', 'facts-rehome', 'consolidate-ties', 'orphan-children', 'failed-writes', 'split-facts', 'frontmatter', 'fences', 'slug-conflicts', 'timeline-comments', 'managed-sync-orphans', 'content-receipt-root', 'frontmatter-keys', 'file-drift', 'stuck-recovery', 'ghost-pages', 'origin-twins', 'receipt-compaction', 'aliases', 'rename-identity', 'overwritten-edits', 'missing-tables', 'url-clone-fences'] 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.tsindex a1e313a4a1..68a23ccf13 100644--- a/src/core/repair/registry.ts+++ b/src/core/repair/registry.ts@@ -57,6 +57,7 @@ import { capturedFactsRepair } from './captured-facts.ts';import { loopFactsRepair } from './loop-facts.ts';import { ontologyFactsRepair } from './ontology-facts.ts';import { factsRehomeRepair } from './facts-rehome.ts';+import { consolidateTiesRepair } from './consolidate-ties.ts';import { orphanChildrenRepair } from './orphan-children.ts';import { failedWritesRepair } from './failed-writes.ts';import { frontmatterRepair } from './frontmatter.ts';@@ -246,6 +247,14 @@ const SPECS: Record<RepairKind, Omit<RepairKindSpec, 'kind'>> = {+ '--expect <hash> moves exactly the previewed database-only facts; a slug that gained a page, lost its target or whose facts changed reports '+ 'changed_since_preview. Database-only; no page is rewritten.',},+ 'consolidate-ties': {+ handler: consolidateTiesRepair, embeds: 'none', checks: [], explicit_only: true, preview_bound: true,+ summary: 'Reopen typed facts that dream consolidation closed at their own effective time (#6023): before this release a cluster whose typed claims '+ + 'stated one metric, unit and period for the same instant was promoted anyway, and the fact that lost the confidence tie got a zero-length '+ + 'validity. The preview lists each such fact with its tied partners and take. Preview-bound: --apply --expect <hash> sets exactly the previewed '+ + 'facts back to open validity and keeps their consolidation mark; a fact that was expired, edited or reopened reports changed_since_preview. '+ + 'Database-only; no page is rewritten.',+ },'orphan-children': {handler: orphanChildrenRepair, embeds: 'none', checks: ['child_table_orphans'], explicit_only: true,summary: 'Delete rows of page child tables (chunks, versions, tags, takes, raw data, timeline, links) whose page no longer exists, and clear dangling 'diff --git a/test/consolidate-same-instant-6023.test.ts b/test/consolidate-same-instant-6023.test.tsindex c7bcd88745..86da88cd81 100644--- a/test/consolidate-same-instant-6023.test.ts+++ b/test/consolidate-same-instant-6023.test.ts@@ -186,7 +186,7 @@ for (const backend of testBackends()) {const before = await factRows(engine);const result = await runPhaseConsolidate(engine, { sourceId: 'default', minOldestAgeMs: 0 });expect(result.details.clusters_held_same_instant).toBe(1);- expect(await engine.executeRaw("SELECT request_id FROM write_requests WHERE intent->>'kind'='managed_maintenance_consolidate'")).toEqual([]);+ expect(await engine.executeRaw("SELECT request_id FROM persistence_requests WHERE intent->>'kind'='managed_maintenance_consolidate'")).toEqual([]);expect(await factRows(engine)).toEqual(before);expect(await takeCount(engine)).toBe(0);}, { databaseUrl });diff --git a/test/fix-wave-5-integration.test.ts b/test/fix-wave-5-integration.test.tsindex 686e84cbde..c3537b4dc6 100644--- a/test/fix-wave-5-integration.test.ts+++ b/test/fix-wave-5-integration.test.ts@@ -194,7 +194,7 @@ for (const backend of testBackends()) {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',- 'conversation-labels': 'gbrain repair conversation-labels', 'captured-facts': 'gbrain repair captured-facts', 'loop-facts': 'gbrain repair loop-facts', 'ontology-facts': 'gbrain repair ontology-facts', 'facts-rehome': 'gbrain repair facts-rehome', 'orphan-children': 'gbrain repair orphan-children', 'failed-writes': 'gbrain repair failed-writes', 'split-facts': 'gbrain repair split-facts',+ 'conversation-labels': 'gbrain repair conversation-labels', 'captured-facts': 'gbrain repair captured-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', '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', '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','overwritten-edits': 'gbrain repair overwritten-edits', 'missing-tables': 'gbrain repair missing-tables', 'url-clone-fences': 'gbrain repair url-clone-fences' };diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txtindex 303dc67023..0f82e31d0a 100644--- a/test/postgres-unit-arms.txt+++ b/test/postgres-unit-arms.txt@@ -40,6 +40,7 @@ test/claude-cli-output-cap.test.tstest/colon-slug-windows-5032.test.tstest/company-brain-policy.test.tstest/company-brain-runtime.test.ts+test/consolidate-same-instant-6023.test.tstest/conversation-facts-oversized-sidecar.test.tstest/cycle/synthesize-concepts-merge.test.tstest/decide/conflict-proposals-managed.test.tsdiff --git a/test/repair-explicit-only.test.ts b/test/repair-explicit-only.test.tsindex 09bf51035e..eb0c62c09f 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', 'conversation-labels', 'captured-facts', 'loop-facts', 'ontology-facts', 'facts-rehome', 'orphan-children', 'failed-writes', 'split-facts', 'frontmatter', 'timeline-comments', 'managed-sync-orphans', 'content-receipt-root', 'frontmatter-keys', 'file-drift', 'stuck-recovery', 'ghost-pages', 'origin-twins', 'receipt-compaction', 'aliases', 'rename-identity', 'overwritten-edits', 'missing-tables', 'url-clone-fences'];+const EXPLICIT: RepairKind[] = ['accepted-takes', 'google-file-modes', 'stale-atoms', 'atoms-restore', 'extractor-facts', 'conversation-labels', 'captured-facts', 'loop-facts', 'ontology-facts', 'facts-rehome', 'consolidate-ties', 'orphan-children', 'failed-writes', 'split-facts', 'frontmatter', 'timeline-comments', 'managed-sync-orphans', 'content-receipt-root', 'frontmatter-keys', 'file-drift', 'stuck-recovery', 'ghost-pages', 'origin-twins', 'receipt-compaction', 'aliases', 'rename-identity', 'overwritten-edits', 'missing-tables', 'url-clone-fences'];let engine: PGLiteEngine;const home = mkdtempSync(join(tmpdir(), 'gbrain-repair-explicit-'));diff --git a/test/trust-write-gate-drift.test.ts b/test/trust-write-gate-drift.test.tsindex a828b4a40a..4e2f5af112 100644--- a/test/trust-write-gate-drift.test.ts+++ b/test/trust-write-gate-drift.test.ts@@ -55,6 +55,7 @@ const EXEMPT: Record<string, string> = {'src/core/persistence/loop-fact-retirement.ts': 'expires a loop fact (lifecycle)','src/core/persistence/memory-mutations.ts': 'forget (lifecycle); remember is gated in memory-prepare.ts','src/core/repair/captured-facts.ts': 'owner repair of existing rows',+ 'src/core/repair/consolidate-ties.ts': 'owner repair reopening the validity of existing facts (lifecycle)','src/core/repair/extractor-facts.ts': 'owner repair of existing rows','src/core/repair/facts-rehome.ts': 'owner repair moving existing facts onto their entity page (placement)','src/core/repair/frontmatter.ts': 'owner repair of existing frontmatter',