Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

repair visibility: plan by class (facts first, links only for lineage), windowed --expect, progress, statement bound; doctor facts first

garrytanf4f5b41e36d1
diff --git a/docs/guides/repair.md b/docs/guides/repair.md
index e5ce5e24b2..57a8e7f0f3 100644
--- a/docs/guides/repair.md
+++ b/docs/guides/repair.md
@@ -59,7 +59,7 @@ timeline: 12 item(s) to repair
```bash
gbrain repair timeline --apply
-gbrain repair visibility --apply
+gbrain repair visibility --apply # every class; or preview one window and apply it (below)
gbrain repair safe-chunks --apply
gbrain repair safe-chunks --apply --no-embed # re-seal text now, embed later
gbrain repair contextual-mode --apply
@@ -68,6 +68,23 @@ gbrain repair google-file-modes --apply # explicit-only: runs only w
gbrain repair --all --apply # every automatic kind in order
```
+On a large brain, apply `visibility` one previewed window at a time. The preview
+plans one class at a time in the order remote callers are exposed (world facts
+from a private page, remotely readable ones first; Life Chronicle events;
+alias-only pages; then atoms and concepts, the only class that reads
+concept-provenance links), reports progress on stderr, lists one window
+(1,000 items; `--limit` up to 10,000) and prints the apply command for it:
+
+```bash
+gbrain repair visibility --class facts # one class: facts, events, aliases or lineage
+gbrain repair visibility --class facts --apply --expect <hash> # exactly that window
+```
+
+The apply touches only the listed items and resumes after its last applied
+item if it stops. Apply the window (or decide not to), then preview again for
+the next one. Each plan statement is bounded at 120 s; a class that overruns is
+reported and skipped while the other classes are listed.
+
`--apply` writes without a prompt, so review the preview first. With
`--apply` you must name a kind or pass `--all`; `--yes` is refused, and so is
any other option the table below does not list, including `--max-usd`: a
diff --git a/scripts/page-body-readers-baseline.tsv b/scripts/page-body-readers-baseline.tsv
index 488c5c068d..1db5db157d 100644
--- a/scripts/page-body-readers-baseline.tsv
+++ b/scripts/page-body-readers-baseline.tsv
@@ -505,7 +505,9 @@ src/core/repair/timeline.ts removedRowIds field STREAM
src/core/repair/timeline.ts scanTimelineHistory sql STREAM
src/core/repair/timeline.ts timelineRepair call:serializePageToMarkdown SEGW
src/core/repair/timeline.ts timelineRepair field STREAM
-src/core/repair/visibility.ts planVisibilityRepair sql META
+src/core/repair/visibility.ts planAliases sql META
+src/core/repair/visibility.ts planEvents sql META
+src/core/repair/visibility.ts planLineage sql META
src/core/repair/visibility.ts visibilityRepair call:serializePageToMarkdown SEGW
src/core/schema-migrations/v091-pages-generation-trigger-and-bookmark.ts v091 sql NONE not the page body: historical generation trigger
src/core/schema-migrations/v123-configurable-fts-language.ts v123 sql NONE not the page body: historical
diff --git a/src/commands/doctor/budget.ts b/src/commands/doctor/budget.ts
index 354fd334f2..2597ad86e3 100644
--- a/src/commands/doctor/budget.ts
+++ b/src/commands/doctor/budget.ts
@@ -158,7 +158,8 @@ const AGENT_RERUN_HEADROOM_MS = 10_000;
/**
* One check an entry could not finish within its budget, in the shared unknown convention. The fix reruns the
* check alone with `--budget-ms N` (which `--only` makes its entry budget), N ten times the budget it ran out of:
- * the agent's while N fits an agent tool call (AGENT_TOOL_LIMIT_MS), else the user's to run in a terminal.
+ * the agent's while N fits an agent tool call (AGENT_TOOL_LIMIT_MS), else the user's to run in a terminal. When the agent's
+ * N is capped below ten times, the message also names the uncapped budget to use in a terminal if the capped rerun stops too.
*/
export function budgetUnknownCheck(name: string, elapsedMs: number, budgetMs: number, limit: BudgetLimit = 'entry'): Check {
const agentCap = AGENT_TOOL_LIMIT_MS - AGENT_RERUN_HEADROOM_MS;
@@ -169,8 +170,9 @@ export function budgetUnknownCheck(name: string, elapsedMs: number, budgetMs: nu
const why = `Runs only this check with a ${n} ms budget, above the ${elapsedMs} ms it already took; read-only.`;
return {
name, status: 'warn', elapsed_ms: elapsedMs,
- message: `Not finished within ${which}. Health is unknown, not clear; rerun this check alone: ${argv.join(' ')}`,
- details: { health: 'unknown', reason: 'budget', limit, exact: false, elapsed_ms: elapsedMs, budget_ms: budgetMs, rerun_budget_ms: n },
+ message: `Not finished within ${which}. Health is unknown, not clear; rerun this check alone: ${argv.join(' ')}`
+ + (n < wanted ? ` (capped to fit an agent tool call; if it stops again, run it in a terminal with --budget-ms ${wanted})` : ''),
+ details: { health: 'unknown', reason: 'budget', limit, exact: false, elapsed_ms: elapsedMs, budget_ms: budgetMs, rerun_budget_ms: n, ...(n < wanted ? { terminal_budget_ms: wanted } : {}) },
fix: n <= agentCap ? agentFix(argv, why, name)
: { argv, consent: [], actor: 'user', requires_exclusive: false, why: `${why} It can run longer than an agent tool call, so run it in a terminal.` },
};
diff --git a/src/commands/doctor/checks/derived-visibility.ts b/src/commands/doctor/checks/derived-visibility.ts
index be994f114b..e4dead7c13 100644
--- a/src/commands/doctor/checks/derived-visibility.ts
+++ b/src/commands/doctor/checks/derived-visibility.ts
@@ -11,11 +11,15 @@
* in or extracted from a private page. Facts a remote caller can recall today
* are listed by id (first 50); slugs stay out of the check, which remote
* callers may run. `gbrain repair visibility` previews every row.
+ *
+ * The fact count, the only class remote callers can read today, runs first; each
+ * statement is bounded by PLAN_STATEMENT_MS, and derived-page counts that overrun
+ * it are reported as unknown while the fact count still stands.
*/
import type { BrainEngine } from '../../../core/engine.ts';
import type { Check } from '../../doctor.ts';
import { derivationPrivateSql, privateSnapshotFilterFragment, readHonorAliases } from '../../../core/search/private-visibility.ts';
-import { aliasOnlyPagesSql, worldFactsFromPrivateSources } from '../../../core/repair/visibility.ts';
+import { aliasOnlyPagesSql, PLAN_STATEMENT_MS, worldFactsFromPrivateSources } from '../../../core/repair/visibility.ts';
const FACT_SAMPLE = 50;
@@ -23,7 +27,16 @@ export async function derivedVisibilityCheck(engine: BrainEngine, sourceId?: str
const name = 'derived_visibility';
try {
const aliasesHonored = await readHonorAliases(engine);
- const [row] = await engine.executeRaw<{ unstamped_atoms: number; unstamped_concepts: number; looser_atoms: number; looser_concepts: number; looser_events: number; alias_pages_without_visibility: number }>(
+ const sources = sourceId ? [sourceId] : (await engine.executeRaw<{ id: string }>('SELECT id FROM sources')).map(s => s.id);
+ const facts = await worldFactsFromPrivateSources(engine, sources);
+ const readable = facts.filter(f => f.readable);
+ const factDetails = { world_facts_from_private_sources: facts.length, world_facts_remotely_readable: readable.length,
+ remotely_readable_fact_ids: readable.slice(0, FACT_SAMPLE).map(f => String(f.id)), fact_ids_truncated: readable.length > FACT_SAMPLE };
+ const factPart = `${facts.length} active world fact(s) are held in or were extracted from a private page; ${readable.length} of them are readable by remote callers (ids in details.remotely_readable_fact_ids).`;
+ const preview = 'Preview: gbrain repair visibility (it lists one window, remotely readable facts first, and prints the --apply --expect command for it; run that after the user agrees).';
+ let counts;
+ try {
+ counts = await engine.executeRaw<{ unstamped_atoms: number; unstamped_concepts: number; looser_atoms: number; looser_concepts: number; looser_events: number; alias_pages_without_visibility: number }>(
`WITH derived AS (
SELECT p.* FROM pages p WHERE p.deleted_at IS NULL ${sourceId ? 'AND p.source_id=$1' : ''}
AND (p.type='atom' OR (p.type='concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)
@@ -42,13 +55,14 @@ export async function derivedVisibilityCheck(engine: BrainEngine, sourceId?: str
WHERE o.source_id=d.source_id AND o.slug=d.frontmatter->'event'->>'depth' AND o.deleted_at IS NULL
AND ${derivationPrivateSql('o')}))::int AS looser_events,
(SELECT COUNT(*)::int FROM pages ap WHERE ${aliasOnlyPagesSql('ap')} ${sourceId ? 'AND ap.source_id=$1' : ''}) AS alias_pages_without_visibility
- FROM derived d`, sourceId ? [sourceId] : []);
- const sources = sourceId ? [sourceId] : (await engine.executeRaw<{ id: string }>('SELECT id FROM sources')).map(s => s.id);
- const facts = await worldFactsFromPrivateSources(engine, sources);
- const readable = facts.filter(f => f.readable);
- const details = { ...row, world_facts_from_private_sources: facts.length, world_facts_remotely_readable: readable.length,
- remotely_readable_fact_ids: readable.slice(0, FACT_SAMPLE).map(f => String(f.id)), fact_ids_truncated: readable.length > FACT_SAMPLE,
- count: 'exact', truncated: false, repair: 'visibility' };
+ FROM derived d`, sourceId ? [sourceId] : [], { timeoutMs: PLAN_STATEMENT_MS });
+ } catch (e) {
+ if ((e as { code?: string } | null)?.code !== '57014') throw e;
+ return { name, status: 'warn', details: { ...factDetails, derived_counts: 'unknown', count: 'lower_bound', truncated: true, repair: 'visibility' },
+ message: [...(facts.length ? [factPart] : []), `Derived page counts did not finish within ${PLAN_STATEMENT_MS} ms; preview them with gbrain repair visibility --class lineage.`, preview].join(' ') };
+ }
+ const row = counts[0]!;
+ const details = { ...row, ...factDetails, count: 'exact', truncated: false, repair: 'visibility' };
const unstamped = row.unstamped_atoms + row.unstamped_concepts;
const looser = row.looser_atoms + row.looser_concepts + row.looser_events;
if (unstamped + looser + row.alias_pages_without_visibility + facts.length === 0) {
@@ -59,8 +73,8 @@ export async function derivedVisibilityCheck(engine: BrainEngine, sourceId?: str
+ `and ${looser} are stored looser than their origin (${row.looser_events} chronicle events); remote reads treat the unstamped ones as private.`);
if (row.alias_pages_without_visibility) parts.push(`${row.alias_pages_without_visibility} page(s) mark themselves private with a privacy alias (access, confidentiality) but carry no visibility. `
+ (aliasesHonored ? 'Remote page reads hide them (to show them: gbrain config set visibility.honor_aliases false).' : 'visibility.honor_aliases is false, so remote page reads show them.'));
- if (facts.length) parts.push(`${facts.length} active world fact(s) are held in or were extracted from a private page; ${readable.length} of them are readable by remote callers (ids in details.remotely_readable_fact_ids).`);
- parts.push('Preview: gbrain repair visibility — apply after the user agrees: gbrain repair visibility --apply');
+ if (facts.length) parts.unshift(factPart);
+ parts.push(preview);
return { name, status: 'warn', details, message: parts.join(' ') };
} catch (e) {
return { name, status: 'warn', message: `derived visibility check skipped: ${e instanceof Error ? e.message : String(e)}`,
diff --git a/src/commands/repair.ts b/src/commands/repair.ts
index 30fb3de4fe..862c7a3212 100644
--- a/src/commands/repair.ts
+++ b/src/commands/repair.ts
@@ -158,7 +158,7 @@ const VALUE_FLAGS = new Set(['--source', '--limit', '--expect', '--only', '--ski
/** Flags only some kinds accept, with the kinds that do. */
const KIND_FLAGS: Record<string, readonly string[]> = {
'--only': ['frontmatter', 'fences', 'slug-conflicts', 'file-drift', CONTENT_LANE], '--skip': ['frontmatter', 'fences', 'slug-conflicts', 'file-drift', CONTENT_LANE], '--diff': ['frontmatter', 'fences', 'slug-conflicts', CONTENT_LANE], '--yes': ['frontmatter', 'conversation-labels', 'stuck-recovery', 'ghost-pages', 'legacy-twins', 'rename-identity', 'url-clone-fences'],
- '--slug': ['fences', 'file-drift', 'rename-identity', 'overwritten-edits', 'origin-twins'], '--from': ['rename-identity'], '--close': ['rename-identity'], '--prefer': ['file-drift'], '--request': ['file-drift'], '--all-drifted': ['file-drift'], '--class': ['file-drift'], '--since': ['file-drift'],
+ '--slug': ['fences', 'file-drift', 'rename-identity', 'overwritten-edits', 'origin-twins'], '--from': ['rename-identity'], '--close': ['rename-identity'], '--prefer': ['file-drift'], '--request': ['file-drift'], '--all-drifted': ['file-drift'], '--class': ['file-drift', 'visibility'], '--since': ['file-drift'],
'--held': ['file-drift'], '--side': ['file-drift'], '--state': ['file-drift'],
'--keep': ['stuck-recovery'], '--request-id': ['stuck-recovery'],
'--older-than': ['receipt-compaction'], '--include-failures': ['receipt-compaction'], '--force': ['receipt-compaction'],
@@ -408,6 +408,7 @@ export async function runRepairCommand(engine: BrainEngine, args: string[]): Pro
const results = await runRepairKinds(kinds, scope, { apply, source, noEmbed, named: kind !== undefined }, k => runner.run(k, scope, { limit, sourceFlag: source, explicit: k === kind, expect, includeAmbiguous,
...(k === kind && KIND_FLAGS['--only']!.includes(k) ? { only, skip } : {}), ...(k === kind && slugs.length ? { slugs } : {}),
...(k === kind && noLlm ? { noLlm } : {}), ...(k === kind && maxUsd !== undefined ? { maxLlmUsd: maxUsd } : {}),
+ ...(k === kind && k === 'visibility' && driftClass ? { driftClass } : {}),
...(k === kind && k === 'file-drift' ? { prefer, requests, allDrifted, driftClass, since, ...(held ? { held } : {}), ...(side ? { side } : {}), ...(state ? { state } : {}) } : {}),
...(k === kind && keep ? { keep } : {}), ...(k === kind && requestId ? { requestId } : {}),
...(k === kind && k === 'receipt-compaction' ? { olderThan, includeFailures, force } : {}),
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index c1e0393f16..9760241961 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -1078,6 +1078,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;
// #7263 (a background doctor refresh held a one-job worker for up to 2 h).
{ since: '0.60.348.0', text: 'The background `doctor-refresh` job now queues behind sync, the autopilot cycles, global maintenance, embed backfill and loops extract (priority 10), and measures for at most 10 minutes: past that it starts no further check, records what it finished and completes, and the rest stays unknown until the next hourly refresh. Its timeout drops from 2 hours to 15 minutes. `gbrain config set doctor.background_refresh false` stops doctor from queueing it.' },
{ since: 'TBD', text: 'Remote (MCP and HTTP) page reads now hide a page marked private only by a privacy alias (`access: private|restricted|confidential` or `confidentiality: confidential|secret|private|restricted`, with no `visibility`), as they hide `visibility: private` pages; local CLI reads are unchanged. To keep showing such pages to remote callers: `gbrain config set visibility.honor_aliases false`.' },
+ { since: 'TBD', text: '`gbrain repair visibility` previews one class at a time, in the order remote callers are exposed: world facts from a private page (remotely readable ones first), Life Chronicle events, alias-only pages, then atoms and concepts; only that last class (`--class lineage`) reads concept-provenance links, and `--class facts|events|aliases|lineage` previews one. A preview lists one window (1,000 items, `--limit` up to 10,000), reports progress on stderr and prints `--apply --expect <hash>`, which applies exactly that window and resumes after its last applied item; apply it, then preview again for the next window. A bare `--apply` (`--all`, the remediation plan) still applies every class. Each plan statement is bounded at 120 s; a class that overruns is reported and skipped while the others are listed. The fact and concept-lineage plans are set-based now (a large brain timed out on them), and doctor `derived_visibility` counts facts first and reports derived-page counts as unknown when they overrun the same bound. A doctor rerun hint capped to fit an agent tool call also names the uncapped `--budget-ms` to use in a terminal.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/persistence/preview-approval.ts b/src/core/persistence/preview-approval.ts
index f39f2a71c7..105c797451 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' | 'redacted-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' | 'legacy-twins' | 'missing-tables' | 'segmented-mirror' | 'uncommitted-deletions';
+export type PreviewApprovalCommand = 'authorize-legacy' | 'jobs-cancel' | 'stale-atoms' | 'atoms-restore' | 'extractor-facts' | 'conversation-labels' | 'captured-facts' | 'redacted-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' | 'legacy-twins' | 'missing-tables' | 'segmented-mirror' | 'uncommitted-deletions' | 'visibility';
export interface ApprovedSetKey {
command: PreviewApprovalCommand;
diff --git a/src/core/repair/core.ts b/src/core/repair/core.ts
index a8c3beec79..724c91bc53 100644
--- a/src/core/repair/core.ts
+++ b/src/core/repair/core.ts
@@ -114,7 +114,9 @@ export interface RepairPlanOptions { apply: boolean; expect?: string; includeAmb
/** `rename-identity` (#6729): the old slug that disambiguates a pair (`--from`), and the close disposition (`--close`). */
from?: string; close?: boolean;
/** `uncommitted-deletions` (#7130): the preview window starts below this page id (`--after`). */
- afterPage?: number }
+ afterPage?: number;
+ /** `visibility`: the preview window's size (`--limit`); an apply still stops after `--limit` items. */
+ limit?: number }
export interface RepairHandler {
kind: RepairKind;
@@ -334,7 +336,8 @@ async function runRepairScoped(ctx: OperationContext, handler: RepairHandler, sc
...(opts.held ? { held: true } : {}), ...(opts.side ? { side: opts.side } : {}), ...(opts.state ? { state: opts.state } : {}),
...(opts.keep ? { keep: opts.keep } : {}), ...(opts.requestId ? { requestId: opts.requestId } : {}),
...(opts.olderThan ? { olderThan: opts.olderThan } : {}), ...(opts.includeFailures ? { includeFailures: true } : {}), ...(opts.force ? { force: true } : {}),
- ...(opts.from ? { from: opts.from } : {}), ...(opts.close ? { close: true } : {}), ...(opts.afterPage !== undefined ? { afterPage: opts.afterPage } : {}) };
+ ...(opts.from ? { from: opts.from } : {}), ...(opts.close ? { close: true } : {}), ...(opts.afterPage !== undefined ? { afterPage: opts.afterPage } : {}),
+ ...(opts.limit !== undefined ? { limit: opts.limit } : {}) };
const plan = await handler.plan(ctx.engine, scope, resumed, planOpts);
const pending = opts.limit !== undefined ? plan.items.slice(0, opts.limit) : plan.items;
const counters = await capacity(ctx);
diff --git a/src/core/repair/registry.ts b/src/core/repair/registry.ts
index e73a2a3a1f..fa78a55326 100644
--- a/src/core/repair/registry.ts
+++ b/src/core/repair/registry.ts
@@ -117,10 +117,11 @@ const SPECS: Record<RepairKind, Omit<RepairKindSpec, 'kind'>> = {
summary: 'Write database-only timeline rows back into their pages as marked bullets (#5567). Rows that cannot round-trip are kept and counted. Each repaired page is re-embedded by its publication.',
},
visibility: {
- handler: visibilityRepair, embeds: 'effect', checks: ['derived_visibility'],
+ handler: visibilityRepair, embeds: 'effect', checks: ['derived_visibility'], preview_bound: true,
summary: 'Stamp explicit visibility on extracted atoms and synthesized concepts, tighten-only (#5525). Transcript and missing origins become private; nothing is ever loosened. '
+ 'Also makes private the chronicle events of a private origin, the pages that carry a privacy alias (access: private, ...) but no visibility, and the world facts held in or extracted from a private page. '
- + 'Each repaired page is re-embedded by its publication.',
+ + 'The preview plans by class (--class facts|events|aliases|lineage; facts first, only lineage reads links), lists one window (--limit, default 1000) '
+ + 'and prints --apply --expect <hash>, which applies exactly that window (resumable); preview again for the next window. Each repaired page is re-embedded by its publication.',
},
'safe-chunks': {
handler: safeChunksRepair, embeds: 'inline', checks: ['safe_index_pending'],
diff --git a/src/core/repair/visibility.ts b/src/core/repair/visibility.ts
index d4c89a38dc..e3e03eb769 100644
--- a/src/core/repair/visibility.ts
+++ b/src/core/repair/visibility.ts
@@ -19,6 +19,15 @@
* field (read as private) is stamped with the origin's value. A concept with no
* recoverable lineage is left unchanged and counted. Atoms are applied before
* concepts so a concept is judged against its repaired inputs.
+ *
+ * The preview plans one class at a time (`--class facts|events|aliases|lineage`, default all), in the
+ * order remote callers are exposed: facts (remotely readable ones first), chronicle events, alias-only
+ * pages, then atoms and concepts. Only the lineage class reads concept-provenance links. It lists one
+ * bounded window (`--limit`, default VISIBILITY_WINDOW items) and prints `--apply --expect <hash>`,
+ * which applies exactly that window (resumable: a stopped apply continues after its last item). A
+ * class past a full window is not read; apply the window and preview again for the next one. Each
+ * plan statement runs under PLAN_STATEMENT_MS; a class that overruns it is reported and skipped.
+ * Progress goes to stderr. A bare `--apply` (`--all`, the remediation plan) applies every class.
*/
import type { BrainEngine } from '../engine.ts';
import { serializePageToMarkdown } from '../markdown.ts';
@@ -34,7 +43,10 @@ import type { WriteRequest } from '../persistence/model.ts';
import { managedPersistenceEnabled } from '../persistence/ownership.ts';
import { maintenancePreflight, submitDatabaseMaintenanceIntent } from '../persistence/prepared-maintenance.ts';
import { isSegmentedPage } from '../page-body/page-shape.ts';
-import { afterCursor, repairRequestId, type RepairHandler, type RepairItem, type RepairScope, type RepairCursor } from './core.ts';
+import { afterCursor, repairRequestId, type RepairHandler, type RepairItem, type RepairPlan, type RepairPlanOptions, type RepairScope, type RepairCursor } from './core.ts';
+import { clearApprovedSet, loadApprovedSet, previewChangedError, previewHash, saveApprovedSet } from '../persistence/preview-approval.ts';
+import { createProgress, startHeartbeat } from '../progress.ts';
+import { cliOptsToProgressOptions, getCliOptions } from '../cli-options.ts';
interface DerivedRow { id: number; source_id: string; slug: string; type: string; visibility: string | null; chars: number }
interface AtomRow extends DerivedRow { source_slug: string | null; origin_id: number | null; origin_type: string | null; origin_frontmatter: Record<string, unknown> | null }
@@ -51,46 +63,45 @@ function tightened(current: string | null, target: Visibility): Visibility | nul
return target;
}
-/**
- * Every atom / synthesized concept in scope whose stored visibility should
- * change. `only` narrows the plan to one page (and, for a concept, its inputs)
- * so an item is re-decided against current state just before it is applied.
- */
-export async function planVisibilityRepair(engine: BrainEngine, sourceIds: string[], only?: number) {
- const [kind] = only === undefined ? [] : await engine.executeRaw<{ type: string }>('SELECT type FROM pages WHERE id=$1', [only]);
- const conceptIds = only === undefined ? null : kind?.type === 'concept' ? [only] : [];
- const eventIds = only === undefined ? null : kind?.type === 'event' ? [only] : [];
- const concepts = await engine.executeRaw<DerivedRow>(`SELECT c.id,c.source_id,c.slug,c.type,c.frontmatter->>'visibility' AS visibility,
+/** Each plan statement's bound (Postgres; PGLite has no other session to wait on). */
+export const PLAN_STATEMENT_MS = 120_000;
+const bounded = { timeoutMs: PLAN_STATEMENT_MS };
+
+/** Extracted atoms and synthesized concepts: the only class that reads concept-provenance links. */
+async function planLineage(engine: BrainEngine, sourceIds: string[], only?: { id: number; type: string }) {
+ const conceptIds = only === undefined ? null : only.type === 'concept' ? [only.id] : [];
+ const concepts = conceptIds?.length === 0 ? [] : await engine.executeRaw<DerivedRow>(`SELECT c.id,c.source_id,c.slug,c.type,c.frontmatter->>'visibility' AS visibility,
length(c.compiled_truth) AS chars
FROM pages c WHERE c.type='concept' AND c.frontmatter->>'synthesized_by' IS NOT NULL AND c.deleted_at IS NULL
- AND c.source_id=ANY($1::text[]) AND ($2::integer[] IS NULL OR c.id=ANY($2::integer[])) ORDER BY c.id`, [sourceIds, conceptIds]);
+ AND c.source_id=ANY($1::text[]) AND ($2::integer[] IS NULL OR c.id=ANY($2::integer[])) ORDER BY c.id`, [sourceIds, conceptIds], bounded);
// A member recovered only from an atom's `concepts:` list has no provenance
// edge, so a later private flip could not reach the concept: it stays private.
// Set-based: provenance edges by page id, `concepts:` references by a hash join on the concept name.
- const inputs = concepts.length ? await engine.executeRaw<InputRow>(`WITH c AS (
+ const inputs = concepts.length ? await engine.executeRaw<InputRow>(`WITH c AS MATERIALIZED (
SELECT id,source_id,regexp_replace(slug,'^concepts/','') AS name FROM pages WHERE id=ANY($1::integer[])),
+ refs AS MATERIALIZED (
+ SELECT a.id AS atom_id,a.source_id,regexp_replace(ref,'^.*/','') AS name FROM pages a
+ CROSS JOIN LATERAL jsonb_array_elements_text(CASE WHEN jsonb_typeof(a.frontmatter->'concepts')='array' THEN a.frontmatter->'concepts' ELSE '[]'::jsonb END) ref
+ WHERE a.type='atom' AND a.deleted_at IS NULL AND a.source_id IN (SELECT source_id FROM c)),
members AS (
SELECT l.from_page_id AS concept_id,l.to_page_id AS atom_id,true AS linked FROM links l
JOIN c ON c.id=l.from_page_id JOIN pages a ON a.id=l.to_page_id AND a.source_id=c.source_id AND a.type='atom' AND a.deleted_at IS NULL
WHERE l.link_source='concept-provenance' AND l.link_type='synthesized_from'
UNION ALL
- SELECT c.id,a.id,false FROM pages a
- CROSS JOIN LATERAL jsonb_array_elements_text(CASE WHEN jsonb_typeof(a.frontmatter->'concepts')='array' THEN a.frontmatter->'concepts' ELSE '[]'::jsonb END) ref
- JOIN c ON c.source_id=a.source_id AND c.name=regexp_replace(ref,'^.*/','')
- WHERE a.type='atom' AND a.deleted_at IS NULL AND a.source_id IN (SELECT source_id FROM c))
- SELECT concept_id,atom_id,bool_or(linked) AS linked FROM members GROUP BY concept_id,atom_id`, [concepts.map(c => Number(c.id))]) : [];
+ SELECT c.id,r.atom_id,false FROM refs r JOIN c ON c.source_id=r.source_id AND c.name=r.name)
+ SELECT concept_id,atom_id,bool_or(linked) AS linked FROM members GROUP BY concept_id,atom_id`, [concepts.map(c => Number(c.id))], bounded) : [];
const inputsByConcept = new Map<number, InputRow[]>();
for (const row of inputs) {
const list = inputsByConcept.get(Number(row.concept_id));
if (list) list.push(row); else inputsByConcept.set(Number(row.concept_id), [row]);
}
- const atomIds = only === undefined ? null : kind?.type === 'atom' ? [only] : inputs.map(row => Number(row.atom_id));
- const atoms = await engine.executeRaw<AtomRow>(`SELECT a.id,a.source_id,a.slug,a.type,a.frontmatter->>'visibility' AS visibility,
+ const atomIds = only === undefined ? null : only.type === 'atom' ? [only.id] : inputs.map(row => Number(row.atom_id));
+ const atoms = atomIds?.length === 0 ? [] : await engine.executeRaw<AtomRow>(`SELECT a.id,a.source_id,a.slug,a.type,a.frontmatter->>'visibility' AS visibility,
length(a.compiled_truth) AS chars, a.frontmatter->>'source_slug' AS source_slug,
o.id AS origin_id,o.type AS origin_type,o.frontmatter AS origin_frontmatter
FROM pages a LEFT JOIN pages o ON o.source_id=a.source_id AND o.slug=a.frontmatter->>'source_slug' AND o.deleted_at IS NULL
WHERE a.type='atom' AND a.deleted_at IS NULL AND a.source_id=ANY($1::text[])
- AND ($2::integer[] IS NULL OR a.id=ANY($2::integer[])) ORDER BY a.id`, [sourceIds, atomIds]);
+ AND ($2::integer[] IS NULL OR a.id=ANY($2::integer[])) ORDER BY a.id`, [sourceIds, atomIds], bounded);
const changes: VisibilityChange[] = [];
const atomVisibility = new Map<number, Visibility>();
@@ -113,25 +124,51 @@ export async function planVisibilityRepair(engine: BrainEngine, sourceIds: strin
const next = tightened(concept.visibility, strictestVisibility(members));
if (next) changes.push({ id: Number(concept.id), source_id: concept.source_id, slug: concept.slug, phase: 1, from: concept.visibility, to: next });
}
+ return { changes, rows: [...atoms, ...concepts], residuals: { atoms_origin_gone_to_private: originGone, concepts_without_lineage: noLineage } };
+}
+
+/** Life Chronicle events whose origin is private now. */
+async function planEvents(engine: BrainEngine, sourceIds: string[], only?: number) {
const events = await engine.executeRaw<EventRow>(`SELECT e.id,e.source_id,e.slug,e.type,e.frontmatter->>'visibility' AS visibility,
length(e.compiled_truth) AS chars,o.id AS origin_id,o.type AS origin_type,o.frontmatter AS origin_frontmatter
FROM pages e LEFT JOIN pages o ON o.source_id=e.source_id AND o.slug=e.frontmatter->'event'->>'depth' AND o.deleted_at IS NULL
WHERE e.type='event' AND e.frontmatter->>'captured_via' LIKE 'life-chronicle:%' AND e.deleted_at IS NULL
AND COALESCE(e.frontmatter->>'visibility','world')<>'private'
- AND e.source_id=ANY($1::text[]) AND ($2::integer[] IS NULL OR e.id=ANY($2::integer[])) ORDER BY e.id`, [sourceIds, eventIds]);
- let eventsOriginGone = 0;
+ AND e.source_id=ANY($1::text[]) AND ($2::integer[] IS NULL OR e.id=ANY($2::integer[])) ORDER BY e.id`, [sourceIds, only === undefined ? null : [only]], bounded);
+ const changes: VisibilityChange[] = [];
+ let originGone = 0;
for (const event of events) {
- if (event.origin_id == null) { eventsOriginGone++; continue; }
+ if (event.origin_id == null) { originGone++; continue; }
if (effectiveVisibility({ kind: 'page', page: { type: event.origin_type, frontmatter: event.origin_frontmatter } }) !== 'private') continue;
changes.push({ id: Number(event.id), source_id: event.source_id, slug: event.slug, phase: 2, from: event.visibility, to: 'private' });
}
- const aliased = await engine.executeRaw<DerivedRow>(`SELECT p.id,p.source_id,p.slug,p.type,NULL::text AS visibility,length(p.compiled_truth) AS chars
+ return { changes, rows: events, residuals: { events_origin_gone: originGone } };
+}
+
+/** Pages marked private by a privacy alias alone. */
+async function planAliases(engine: BrainEngine, sourceIds: string[], only?: number) {
+ const rows = await engine.executeRaw<DerivedRow>(`SELECT p.id,p.source_id,p.slug,p.type,NULL::text AS visibility,length(p.compiled_truth) AS chars
FROM pages p WHERE ${aliasOnlyPagesSql('p')} AND p.source_id=ANY($1::text[]) AND ($2::integer[] IS NULL OR p.id=ANY($2::integer[])) ORDER BY p.id`,
- [sourceIds, only === undefined ? null : [only]]);
- for (const page of aliased) changes.push({ id: Number(page.id), source_id: page.source_id, slug: page.slug, phase: 3, from: null, to: 'private' });
- const chars = new Map([...atoms, ...concepts, ...events, ...aliased].map(row => [Number(row.id), Number(row.chars)]));
- return { changes, chars, residuals: { atoms_origin_gone_to_private: originGone, concepts_without_lineage: noLineage,
- events_origin_gone: eventsOriginGone } };
+ [sourceIds, only === undefined ? null : [only]], bounded);
+ return { changes: rows.map(page => ({ id: Number(page.id), source_id: page.source_id, slug: page.slug, phase: 3 as const, from: null, to: 'private' as const })), rows, residuals: {} };
+}
+
+/**
+ * Every atom / synthesized concept / chronicle event / alias-only page in scope
+ * whose stored visibility should change. `only` narrows the plan to one page
+ * (and, for a concept, its inputs) so an item is re-decided against current
+ * state just before it is applied; only an atom or concept reads links.
+ */
+export async function planVisibilityRepair(engine: BrainEngine, sourceIds: string[], only?: number) {
+ const [kind] = only === undefined ? [] : await engine.executeRaw<{ type: string }>('SELECT type FROM pages WHERE id=$1', [only]);
+ if (only !== undefined && !kind) return { changes: [], chars: new Map<number, number>(), residuals: {} };
+ const lineage = only === undefined || kind!.type === 'atom' || kind!.type === 'concept'
+ ? await planLineage(engine, sourceIds, only === undefined ? undefined : { id: only, type: kind!.type }) : null;
+ const events = await planEvents(engine, sourceIds, only);
+ const aliased = await planAliases(engine, sourceIds, only);
+ const parts = [...(lineage ? [lineage] : []), events, aliased];
+ return { changes: parts.flatMap(part => part.changes), chars: new Map(parts.flatMap(part => part.rows).map(row => [Number(row.id), Number(row.chars)])),
+ residuals: Object.assign({}, ...parts.map(part => part.residuals)) as Record<string, number> };
}
/**
@@ -198,8 +235,7 @@ export async function prepareFactVisibilityTighten(engine: BrainEngine, row: Wri
* database-only row is updated in place (a database-only maintenance request
* on a managed brain). A page stored in segments is left for the owner.
*/
-async function applyFactItem(ctx: Parameters<RepairHandler['apply']>[0], item: RepairItem): Promise<boolean> {
- const factId = item.cursor.id;
+async function applyFactItem(ctx: Parameters<RepairHandler['apply']>[0], item: RepairItem, factId: number): Promise<boolean> {
const [fact] = await worldFactsFromPrivateSources(ctx.engine, [item.source_id], [factId]);
if (!fact) return false;
if (fact.row_num === null) {
@@ -225,31 +261,138 @@ async function applyFactItem(ctx: Parameters<RepairHandler['apply']>[0], item: R
return stored?.visibility === 'private';
}
+export type VisibilityClass = 'facts' | 'events' | 'aliases' | 'lineage';
+/** Plan order: what a remote caller can read first; only `lineage` reads concept-provenance links. */
+export const VISIBILITY_CLASSES: readonly VisibilityClass[] = ['facts', 'events', 'aliases', 'lineage'];
+/** Items one preview lists and one `--apply --expect` applies (`--limit` sets it, up to VISIBILITY_WINDOW_MAX). */
+export const VISIBILITY_WINDOW = 1000;
+export const VISIBILITY_WINDOW_MAX = 10_000;
+const CLASS_OF_PHASE: Record<number, VisibilityClass> = { 0: 'lineage', 1: 'lineage', 2: 'events', 3: 'aliases', 4: 'facts' };
+
+/** One planned change; `target` is the page (phases 0-3) or fact (phase 4) it changes. */
+interface VisibilityItem extends RepairItem { target: RepairCursor; hash?: string; last?: boolean }
+interface ApprovedVisibility { target: RepairCursor; source_id: string; slug: string; chars: number; action: string; change: { from: string | null; to: string }; selection: Selection }
+interface Selection { source_ids: string[]; class: VisibilityClass | null }
+
+const visibilityPreviewCommand = (scope: RepairScope, selection: Selection, sourceFlag?: boolean) =>
+ `gbrain repair visibility${sourceFlag && scope.source_ids.length === 1 ? ` --source ${scope.source_ids[0]}` : ''}${selection.class ? ` --class ${selection.class}` : ''}`;
+
+function selectedClass(opts?: RepairPlanOptions): VisibilityClass | null {
+ const value = opts?.driftClass;
+ if (value === undefined) return null;
+ if ((VISIBILITY_CLASSES as readonly string[]).includes(value)) return value as VisibilityClass;
+ throw opError('invalid_params', `--class for gbrain repair visibility takes ${VISIBILITY_CLASSES.join(', ')} (got "${value}").`,
+ 'Preview every class with gbrain repair visibility, or one with e.g. gbrain repair visibility --class facts.');
+}
+
+const isStatementTimeout = (error: unknown) => (error as { code?: string } | null)?.code === '57014';
+
+/** Every planned change of one class, as items in their stable (phase, id) cursor order. */
+async function planClass(engine: BrainEngine, sourceIds: string[], cls: VisibilityClass): Promise<{ items: VisibilityItem[]; residuals: Record<string, number> }> {
+ const toItems = (part: { changes: VisibilityChange[]; rows: DerivedRow[] }) => {
+ const chars = new Map(part.rows.map(row => [Number(row.id), Number(row.chars)]));
+ return part.changes.map(change => ({ cursor: { phase: change.phase, id: change.id }, target: { phase: change.phase, id: change.id }, source_id: change.source_id,
+ slug: change.slug, chars: chars.get(change.id) ?? 0, action: `visibility ${change.from ?? '(none)'} -> ${change.to}`, change: { from: change.from, to: change.to } }))
+ .sort((a, b) => a.cursor.phase - b.cursor.phase || a.cursor.id - b.cursor.id);
+ };
+ if (cls === 'facts') {
+ const facts = await worldFactsFromPrivateSources(engine, sourceIds);
+ const items = facts.map(fact => ({ cursor: { phase: 4, id: Number(fact.id) }, target: { phase: 4, id: Number(fact.id) }, source_id: fact.source_id,
+ slug: fact.source_markdown_slug ?? fact.entity_slug ?? 'memory/unattributed', chars: 0, readable: fact.readable,
+ action: `fact ${fact.id} visibility world -> private${fact.readable ? ' (remotely readable now)' : ''}`, change: { from: 'world', to: 'private' } }));
+ return { items, residuals: { world_facts_remotely_readable: facts.filter(fact => fact.readable).length } };
+ }
+ const part = cls === 'events' ? await planEvents(engine, sourceIds) : cls === 'aliases' ? await planAliases(engine, sourceIds) : await planLineage(engine, sourceIds);
+ return { items: toItems(part), residuals: part.residuals };
+}
+
export const visibilityRepair: RepairHandler = {
kind: 'visibility',
- async plan(engine: BrainEngine, scope: RepairScope, after: RepairCursor | null) {
- const { changes, chars, residuals } = await planVisibilityRepair(engine, scope.source_ids);
- const facts = await worldFactsFromPrivateSources(engine, scope.source_ids);
- const items: RepairItem[] = [...changes.map(change => ({ cursor: { phase: change.phase, id: change.id }, source_id: change.source_id,
- slug: change.slug, chars: chars.get(change.id) ?? 0, action: `visibility ${change.from ?? '(none)'} -> ${change.to}`,
- change: { from: change.from, to: change.to } })),
- ...facts.map(fact => ({ cursor: { phase: 4, id: Number(fact.id) }, source_id: fact.source_id,
- slug: fact.source_markdown_slug ?? fact.entity_slug ?? 'memory/unattributed', chars: 0,
- action: `fact ${fact.id} visibility world -> private${fact.readable ? ' (remotely readable now)' : ''}`, change: { from: 'world', to: 'private' } }))]
- .filter(item => afterCursor(item.cursor, after));
- return { items, residuals: { ...residuals, world_facts_remotely_readable: facts.filter(fact => fact.readable).length } };
+ async plan(engine: BrainEngine, scope: RepairScope, after: RepairCursor | null, opts?: RepairPlanOptions): Promise<RepairPlan> {
+ const selection: Selection = { source_ids: scope.source_ids, class: selectedClass(opts) };
+ const classes = selection.class ? [selection.class] : VISIBILITY_CLASSES;
+ const command = visibilityPreviewCommand(scope, selection, true);
+ if (opts?.apply && opts.expect) {
+ const approved = await loadApprovedSet<ApprovedVisibility>(engine, { command: 'visibility', hash: opts.expect, previewCommand: command,
+ emptyHash: async () => previewHash(hashParts(scope, selection, [])) });
+ if (approved.items.some(entry => (entry.selection.class ?? null) !== selection.class || JSON.stringify(entry.selection.source_ids) !== JSON.stringify(selection.source_ids))) {
+ throw previewChangedError(opts.expect, command);
+ }
+ const items: VisibilityItem[] = approved.items.map(({ selection: _selection, ...entry }, index) => ({ ...entry, cursor: { phase: 0, id: index },
+ hash: opts.expect, last: index === approved.items.length - 1 }));
+ return { items: items.filter(entry => afterCursor(entry.cursor, after)), preview_hash: opts.expect, residuals: {} };
+ }
+ if (opts?.apply) {
+ // A bare --apply (--all, the remediation plan) applies every planned change in (phase, id) order, resumable by that cursor.
+ const planned = await Promise.all(classes.map(cls => planClass(engine, scope.source_ids, cls)));
+ return { items: planned.flatMap(part => part.items).sort((a, b) => a.cursor.phase - b.cursor.phase || a.cursor.id - b.cursor.id)
+ .filter(item => afterCursor(item.cursor, after)), residuals: Object.assign({}, ...planned.map(part => part.residuals)) };
+ }
+ const size = Math.min(Math.max(1, opts?.limit ?? VISIBILITY_WINDOW), VISIBILITY_WINDOW_MAX);
+ const progress = opts?.remote === false ? createProgress(cliOptsToProgressOptions(getCliOptions())) : null;
+ progress?.start('repair.visibility.plan', classes.length);
+ const window: VisibilityItem[] = [];
+ const residuals: Record<string, number> = {};
+ const pending: Partial<Record<VisibilityClass, number>> = {};
+ const notRead: VisibilityClass[] = [];
+ const timedOut: VisibilityClass[] = [];
+ let pendingPastWindow = 0;
+ for (const cls of classes) {
+ if (window.length >= size) { notRead.push(cls); progress?.heartbeat(`${cls}: not read (window full)`); progress?.tick(1); continue; }
+ const started = Date.now();
+ progress?.heartbeat(`reading ${cls}`);
+ const stopHeartbeat = progress ? startHeartbeat(progress, `still reading ${cls}`, 10_000) : () => {};
+ let planned: Awaited<ReturnType<typeof planClass>>;
+ try { planned = await planClass(engine, scope.source_ids, cls); } catch (error) {
+ if (!isStatementTimeout(error)) throw error;
+ timedOut.push(cls); progress?.heartbeat(`${cls}: over the ${PLAN_STATEMENT_MS} ms statement bound, skipped`); progress?.tick(1); continue;
+ } finally { stopHeartbeat(); }
+ const ordered = cls === 'facts' ? [...planned.items.filter(item => (item as { readable?: boolean }).readable), ...planned.items.filter(item => !(item as { readable?: boolean }).readable)] : planned.items;
+ const taken = ordered.slice(0, size - window.length);
+ window.push(...taken);
+ pendingPastWindow += ordered.length - taken.length;
+ pending[cls] = ordered.length;
+ Object.assign(residuals, planned.residuals);
+ progress?.heartbeat(`${cls}: ${ordered.length} to repair${cls === 'facts' ? ` (${planned.residuals.world_facts_remotely_readable} remotely readable)` : ''} in ${Date.now() - started} ms`);
+ progress?.tick(1);
+ }
+ progress?.finish();
+ const items = window.map(({ readable: _readable, ...item }: VisibilityItem & { readable?: boolean }) => item as VisibilityItem);
+ const hash = previewHash(hashParts(scope, selection, items));
+ if (items.length) await saveApprovedSet<ApprovedVisibility>(engine, { command: 'visibility', hash },
+ items.map(item => ({ target: item.target, source_id: item.source_id, slug: item.slug, chars: item.chars, action: item.action, change: item.change!, selection })));
+ const next = visibilityPreviewCommand(scope, selection, true);
+ const warnings = [
+ ...(pendingPastWindow || notRead.length ? [`This preview lists one window of ${items.length} item(s)${pendingPastWindow ? `; ${pendingPastWindow} more found past it` : ''}${notRead.length ? `; not read: ${notRead.join(', ')}` : ''}. `
+ + `Apply this window (or decide not to), then preview again for the next one: ${next}`] : []),
+ ...timedOut.map(cls => `Class ${cls} did not finish within the ${PLAN_STATEMENT_MS} ms statement bound and is not listed; the other classes are. `
+ + `Preview the others with --class, or run gbrain doctor --only derived_visibility for the counts.`),
+ ];
+ return { warnings, items: items.map((item, index) => ({ ...item, cursor: { phase: 0, id: index } })), preview_hash: hash,
+ residuals,
+ listing: items.map(item => ({ item: `${item.source_id}:${item.slug}`, class: CLASS_OF_PHASE[item.target.phase]!, detail: item.action })),
+ details: { window: { size, listed: items.length, pending, pending_past_window: pendingPastWindow, not_read: notRead, timed_out: timedOut, next_preview: next } } };
},
- async apply(ctx, item) {
- if (item.cursor.phase === 4) return applyFactItem(ctx, item);
- const snapshot = await ctx.engine.readPageSnapshot(item.slug, { sourceId: item.source_id });
- if (!snapshot || !item.change) return false;
- // Re-decide against current origins and inputs; a changed decision waits for the next run.
- const fresh = (await planVisibilityRepair(ctx.engine, [item.source_id], snapshot.page.id)).changes.find(c => c.id === snapshot.page.id);
- if (!fresh || fresh.from !== item.change.from || fresh.to !== item.change.to) return false;
- const page = { ...snapshot.page, frontmatter: { ...snapshot.page.frontmatter, visibility: item.change.to } };
- await submitPageMutation(ctx, { operation: 'put_page', params: { slug: item.slug, source_id: item.source_id,
- content: serializePageToMarkdown(page, snapshot.tags), expected_revision: snapshot.revision,
- request_id: await repairRequestId(ctx, 'visibility', item, snapshot.revision) } });
- return true;
+ async apply(ctx, entry) {
+ const item = entry as VisibilityItem;
+ const target = item.target ?? item.cursor;
+ try {
+ if (target.phase === 4) return await applyFactItem(ctx, item, target.id);
+ const snapshot = await ctx.engine.readPageSnapshot(item.slug, { sourceId: item.source_id });
+ if (!snapshot || !item.change || Number(snapshot.page.id) !== target.id) return false;
+ // Re-decide against current origins and inputs; a changed decision waits for the next run.
+ const fresh = (await planVisibilityRepair(ctx.engine, [item.source_id], target.id)).changes.find(c => c.id === target.id);
+ if (!fresh || fresh.from !== item.change.from || fresh.to !== item.change.to) return false;
+ const page = { ...snapshot.page, frontmatter: { ...snapshot.page.frontmatter, visibility: item.change.to } };
+ await submitPageMutation(ctx, { operation: 'put_page', params: { slug: item.slug, source_id: item.source_id,
+ content: serializePageToMarkdown(page, snapshot.tags), expected_revision: snapshot.revision,
+ request_id: await repairRequestId(ctx, 'visibility', item, snapshot.revision) } });
+ return true;
+ } finally {
+ if (item.last && item.hash) await clearApprovedSet(ctx.engine, { command: 'visibility', hash: item.hash });
+ }
},
};
+
+const hashParts = (scope: RepairScope, selection: Selection, items: VisibilityItem[]) => ({ kind: 'visibility-v2', brain_id: scope.brain_id, selection,
+ items: items.map(item => ({ target: item.target, source_id: item.source_id, slug: item.slug, change: item.change })) });
diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txt
index 6c7db283bf..c6e807451b 100644
--- a/test/postgres-unit-arms.txt
+++ b/test/postgres-unit-arms.txt
@@ -453,6 +453,7 @@ test/unbound-source-6536.test.ts
test/unindexed-files.test.ts
test/vector-manifest-probe-bound.test.ts
test/visibility-fail-closed-derived-writes.test.ts
+test/visibility-repair-scale.test.ts
test/withdrawal-overlay-concurrency.test.ts
test/withdrawal-publication-file.test.ts
test/worktree-refresh-recovery-row-gbra130.test.ts
diff --git a/test/visibility-repair-scale.test.ts b/test/visibility-repair-scale.test.ts
new file mode 100644
index 0000000000..6f03cc6f9c
--- /dev/null
+++ b/test/visibility-repair-scale.test.ts
@@ -0,0 +1,194 @@
+/**
+ * GBRA-159: gbrain repair visibility on a large brain. The preview plans one
+ * class at a time, remotely readable facts first; facts, chronicle events and
+ * alias-only pages never read concept-provenance links; it lists one bounded
+ * window whose --apply --expect <hash> applies exactly that window (resumable);
+ * a class over the statement bound is skipped and reported; doctor's fact count
+ * comes first. Synthetic data only. PGLite + Postgres.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { resolveRepairScope, runRepair, type RepairResult } from '../src/core/repair/core.ts';
+import { visibilityRepair } from '../src/core/repair/visibility.ts';
+import { derivedVisibilityCheck } from '../src/commands/doctor/checks/derived-visibility.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { withEnv } from './helpers/with-env.ts';
+import { testBackends } from './helpers/test-backends.ts';
+
+const backends = testBackends();
+const engines: BrainEngine[] = [];
+let closePostgres: (() => Promise<void>) | undefined;
+const home = mkdtempSync(join(tmpdir(), 'gbrain-visibility-scale-'));
+
+beforeAll(async () => {
+ if (backends.includes('pglite')) {
+ const engine = new PGLiteEngine();
+ await engine.connect({}); await engine.initSchema(); engines.push(engine);
+ }
+ if (backends.includes('postgres')) {
+ const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!);
+ engines.push(pg.engine); closePostgres = pg.close;
+ }
+}, 120_000);
+
+afterAll(async () => {
+ for (const engine of engines) { await disposePersistenceConsumer(engine); if (engine.kind === 'pglite') await engine.disconnect(); }
+ await closePostgres?.();
+ rmSync(home, { recursive: true, force: true });
+});
+
+const ctx = (engine: BrainEngine) => ({ engine, config: { engine: engine.kind, embedding_disabled: true },
+ logger: { info() {}, warn() {}, error() {} }, dryRun: false, remote: true, sourceId: 'default' }) as never;
+
+async function reset(engine: BrainEngine) {
+ for (const sql of ['DELETE FROM links', 'DELETE FROM facts', 'DELETE FROM content_chunks', 'DELETE FROM pages', "DELETE FROM op_checkpoints WHERE op IN ('repair','repair-approval')"]) await engine.executeRaw(sql);
+}
+
+/**
+ * The shape of a large brain: `origins` meeting pages (every 5th explicitly private, every 7th private by an alias),
+ * atoms extracted from them, synthesized concepts with provenance links to three of every four members, chronicle
+ * events, alias-only notes, world facts extracted from the meetings (half held on a world entity page, so remotely
+ * readable when the meeting is private) and plain filler pages. Inserted set-based in chunks, page triggers off.
+ */
+async function seedShape(engine: BrainEngine, n: { origins: number; atoms: number; concepts: number; events: number; aliased: number; facts: number; filler: number }) {
+ const chunked = async (count: number, sql: (lo: number, hi: number) => string) => {
+ for (let lo = 1; lo <= count; lo += 5000) await engine.executeRaw(sql(lo, Math.min(count, lo + 4999)));
+ };
+ await engine.executeRaw('ALTER TABLE pages DISABLE TRIGGER USER');
+ try {
+ await chunked(n.filler, (lo, hi) => "INSERT INTO pages (source_id,slug,type,title,compiled_truth,frontmatter) SELECT 'default','notes/filler-'||g,'note','f'||g,'filler','{}'::jsonb FROM generate_series(" + lo + ',' + hi + ') g');
+ await chunked(n.origins, (lo, hi) => "INSERT INTO pages (source_id,slug,type,title,compiled_truth,frontmatter) SELECT 'default','meetings/m-'||g,'meeting','m'||g,'meeting body',"
+ + "CASE WHEN g%5=0 THEN '{\"visibility\":\"private\"}'::jsonb WHEN g%7=0 THEN '{\"access\":\"private\"}'::jsonb ELSE '{}'::jsonb END FROM generate_series(" + lo + ',' + hi + ') g');
+ await engine.executeRaw("INSERT INTO pages (source_id,slug,type,title,compiled_truth,frontmatter) VALUES ('default','people/alice-example','person','Alice','entity','{}'::jsonb)");
+ await chunked(n.atoms, (lo, hi) => "INSERT INTO pages (source_id,slug,type,title,compiled_truth,frontmatter) SELECT 'default','atoms/a-'||g,'atom','a'||g,'atom body',"
+ + "jsonb_build_object('source_slug','meetings/m-'||(1+g%" + n.origins + "),'concepts',jsonb_build_array('concepts/c-'||(1+g%" + n.concepts + ")))"
+ + " || CASE WHEN g%3=0 THEN '{\"visibility\":\"world\"}'::jsonb ELSE '{}'::jsonb END FROM generate_series(" + lo + ',' + hi + ') g');
+ await chunked(n.concepts, (lo, hi) => "INSERT INTO pages (source_id,slug,type,title,compiled_truth,frontmatter) SELECT 'default','concepts/c-'||g,'concept','c'||g,'concept body',"
+ + "jsonb_build_object('synthesized_by','synthesize_concepts-v1') || CASE WHEN g%2=0 THEN '{\"visibility\":\"world\"}'::jsonb ELSE '{}'::jsonb END FROM generate_series(" + lo + ',' + hi + ') g');
+ await chunked(n.events, (lo, hi) => "INSERT INTO pages (source_id,slug,type,title,compiled_truth,frontmatter) SELECT 'default','events/e-'||g,'event','e'||g,'event body',"
+ + "jsonb_build_object('captured_via','life-chronicle:auto','event',jsonb_build_object('depth','meetings/m-'||(1+g%" + n.origins + "))) FROM generate_series(" + lo + ',' + hi + ') g');
+ await chunked(n.aliased, (lo, hi) => "INSERT INTO pages (source_id,slug,type,title,compiled_truth,frontmatter) SELECT 'default','notes/n-'||g,'note','n'||g,'note body',"
+ + "CASE WHEN g%2=0 THEN '{\"access\":\"private\"}'::jsonb ELSE '{\"confidentiality\":\"internal\"}'::jsonb END FROM generate_series(" + lo + ',' + hi + ') g');
+ } finally { await engine.executeRaw('ALTER TABLE pages ENABLE TRIGGER USER'); }
+ await engine.executeRaw("INSERT INTO links (from_page_id,to_page_id,link_type,link_source) SELECT c.id,a.id,'synthesized_from','concept-provenance' FROM pages c "
+ + "JOIN pages a ON a.type='atom' AND a.frontmatter->'concepts'->>0 = c.slug WHERE c.type='concept' AND a.id%4<>0");
+ await chunked(n.facts, (lo, hi) => "INSERT INTO facts (source_id,fact,visibility,source,source_markdown_slug,source_session) SELECT 'default','fact '||g,'world','mcp:put_page',"
+ + "CASE WHEN g%2=0 THEN 'people/alice-example' ELSE 'meetings/m-'||(1+g%" + n.origins + ") END,'put_page:meetings/m-'||(1+g%" + n.origins + ") FROM generate_series(" + lo + ',' + hi + ') g');
+ await engine.executeRaw('ANALYZE');
+}
+
+/** The engine with every statement recorded, and `fail` choosing statements to end with a statement timeout. */
+function recording(engine: BrainEngine, fail?: (sql: string) => boolean) {
+ const statements: string[] = [];
+ const proxy = new Proxy(engine, { get(target, key) {
+ if (key === 'executeRaw') return async (sql: string, params?: unknown[], opts?: never) => {
+ statements.push(sql);
+ if (fail?.(sql)) throw Object.assign(new Error('canceling statement due to statement timeout'), { code: '57014' });
+ return target.executeRaw(sql, params, opts);
+ };
+ const value = Reflect.get(target, key);
+ return typeof value === 'function' ? value.bind(target) : value;
+ } });
+ return { engine: proxy as BrainEngine, statements, readsLinks: () => statements.some(sql => /\blinks\b/.test(sql)) };
+}
+
+const SMALL = { origins: 50, atoms: 120, concepts: 6, events: 30, aliased: 10, facts: 40, filler: 0 };
+const privateFacts = (engine: BrainEngine) => engine.executeRaw<{ id: number }>("SELECT id FROM facts WHERE visibility='private' ORDER BY id");
+const preview = (engine: BrainEngine, opts: { driftClass?: string; limit?: number } = {}) =>
+ withEnv({ GBRAIN_HOME: home }, async () => runRepair(ctx(engine), visibilityRepair, await resolveRepairScope(engine), { apply: false, ...opts }));
+const apply = (engine: BrainEngine, expect: string, opts: { driftClass?: string; limit?: number } = {}) =>
+ withEnv({ GBRAIN_HOME: home }, async () => runRepair(ctx(engine), visibilityRepair, await resolveRepairScope(engine), { apply: true, expect, ...opts }));
+
+describe('GBRA-159 visibility repair plans by class, facts first, without links for facts and events', () => {
+ test('facts, events and aliases never read links; the default window fills from remotely readable facts first', async () => {
+ for (const engine of engines) {
+ await reset(engine);
+ await seedShape(engine, SMALL);
+ for (const cls of ['facts', 'events', 'aliases']) {
+ const rec = recording(engine);
+ const result = await preview(rec.engine, { driftClass: cls });
+ expect(result.affected).toBeGreaterThan(0);
+ expect(rec.readsLinks()).toBe(false);
+ expect(result.apply_command).toContain(` --class ${cls} --apply --expect ${result.preview_hash}`);
+ }
+ const rec = recording(engine);
+ const window = await preview(rec.engine, { limit: 5 });
+ expect(rec.readsLinks()).toBe(false);
+ expect(window.affected).toBe(5);
+ expect(window.listing!.every(entry => entry.class === 'facts' && entry.detail!.endsWith('(remotely readable now)'))).toBe(true);
+ expect(window.details).toMatchObject({ window: { size: 5, listed: 5, not_read: ['events', 'aliases', 'lineage'] } });
+ expect(window.warnings!.join(' ')).toContain('Apply this window (or decide not to), then preview again for the next one: gbrain repair visibility');
+ const lineage = await preview(engine, { driftClass: 'lineage' });
+ expect(lineage.listing!.every(entry => entry.class === 'lineage')).toBe(true);
+ expect(lineage.affected).toBeGreaterThan(0);
+ }
+ }, 120_000);
+
+ test('--apply --expect applies exactly the previewed window, resumes after a stop, and refuses a spent or other-class hash', async () => {
+ for (const engine of engines) {
+ await reset(engine);
+ await seedShape(engine, SMALL);
+ const before = await engine.executeRaw<{ n: number }>("SELECT count(*)::int AS n FROM facts WHERE visibility='world'");
+ const window = await preview(engine, { driftClass: 'facts', limit: 3 });
+ const listed = window.listing!.map(entry => Number(/^fact (\d+) /.exec(entry.detail!)![1]));
+ expect(listed).toHaveLength(3);
+ const first: RepairResult = await apply(engine, window.preview_hash!, { driftClass: 'facts', limit: 1 });
+ expect(first).toMatchObject({ applied: 1, complete: false });
+ expect((await privateFacts(engine)).map(row => Number(row.id))).toEqual(listed.slice(0, 1));
+ const rest = await apply(engine, window.preview_hash!, { driftClass: 'facts' });
+ expect(rest).toMatchObject({ applied: 2, complete: true, resumed_from: { phase: 0, id: 0 } });
+ expect((await privateFacts(engine)).map(row => Number(row.id))).toEqual(listed);
+ const after = await engine.executeRaw<{ n: number }>("SELECT count(*)::int AS n FROM facts WHERE visibility='world'");
+ expect(after[0]!.n).toBe(before[0]!.n - 3);
+ await expect(apply(engine, window.preview_hash!, { driftClass: 'facts' })).rejects.toThrow(/preview changed/i);
+ const events = await preview(engine, { driftClass: 'events', limit: 2 });
+ await expect(apply(engine, events.preview_hash!, { driftClass: 'facts' })).rejects.toThrow(/preview changed/i);
+ const next = await preview(engine, { driftClass: 'facts', limit: 3 });
+ expect(next.listing!.map(entry => Number(/^fact (\d+) /.exec(entry.detail!)![1])).some(id => listed.includes(id))).toBe(false);
+ }
+ }, 120_000);
+
+ test('a class over the statement bound is skipped and reported; doctor still reports the fact count first', async () => {
+ for (const engine of engines) {
+ await reset(engine);
+ await seedShape(engine, SMALL);
+ const rec = recording(engine, sql => sql.includes('concept-provenance'));
+ const result = await preview(rec.engine, { limit: 10_000 });
+ expect(result.details).toMatchObject({ window: { timed_out: ['lineage'], not_read: [] } });
+ expect(new Set(result.listing!.map(entry => entry.class))).toEqual(new Set(['facts', 'events', 'aliases']));
+ expect(result.warnings!.join(' ')).toContain('Class lineage did not finish within');
+ const doctor = await derivedVisibilityCheck(recording(engine, sql => sql.trimStart().startsWith('WITH derived')).engine);
+ expect(doctor.status).toBe('warn');
+ expect(doctor.details).toMatchObject({ derived_counts: 'unknown', count: 'lower_bound' });
+ expect(Number(doctor.details!.world_facts_remotely_readable)).toBeGreaterThan(0);
+ expect(doctor.message).toContain('readable by remote callers');
+ }
+ }, 120_000);
+});
+
+describe('GBRA-159 scale: tens of thousands of derived rows', () => {
+ // GBRAIN_VISIBILITY_SCALE_FILLER adds plain pages for the full large-brain shape (e.g. 540000 for about 600k pages).
+ const filler = Number(process.env.GBRAIN_VISIBILITY_SCALE_FILLER ?? 0);
+ test('the default preview, a lineage preview and doctor each finish in under 10 s', async () => {
+ for (const engine of engines) {
+ await reset(engine);
+ await seedShape(engine, { origins: 20_000, atoms: 40_000, concepts: 1_000, events: 2_000, aliased: 4_000, facts: 20_000, filler });
+ const timed = async <T>(run: () => Promise<T>) => { const started = performance.now(); const value = await run(); return { value, ms: performance.now() - started }; };
+ const window = await timed(() => preview(engine));
+ expect(window.value.affected).toBe(1000);
+ expect(window.ms).toBeLessThan(10_000);
+ const lineage = await timed(() => preview(engine, { driftClass: 'lineage' }));
+ expect((lineage.value.details as { window: { pending: { lineage: number } } }).window.pending.lineage).toBeGreaterThan(30_000);
+ expect(lineage.ms).toBeLessThan(10_000);
+ const doctor = await timed(() => derivedVisibilityCheck(engine));
+ expect(doctor.value.details).toMatchObject({ count: 'exact' });
+ expect(doctor.ms).toBeLessThan(10_000);
+ console.error(`[${engine.kind}] preview ${Math.round(window.ms)} ms, lineage ${Math.round(lineage.ms)} ms, doctor ${Math.round(doctor.ms)} ms (filler ${filler})`);
+ }
+ }, 600_000);
+});