Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
GBRA-161 PR 1a (wip): unmanaged atoms publish as one generation; doctor checks; config keys
garrytan1b7684f6375e
diff --git a/src/commands/config.ts b/src/commands/config.tsindex 1ee7b3bf9e..3d3b7f71a9 100644--- a/src/commands/config.ts+++ b/src/commands/config.ts@@ -392,6 +392,12 @@ async function setConfigWithDecideHooks(engine: BrainEngine, key: string, value:if (err) { console.error(`[config] ${err}`); process.exit(1); }}(await import('./config/enumerated-keys.ts')).refuseUnregisteredEnumeratedKey(key, force);+ const generationsRefusal = key.startsWith('generations.') ? (await import('../core/generations/config.ts')).generationsConfigRefusal(key, value) : null;+ if (generationsRefusal) {+ const { exitCliError, usageError } = await import('../cli/cli-error.ts');+ exitCliError(usageError(generationsRefusal.message, `Re-run with a value in range, e.g. gbrain config set ${key} ${generationsRefusal.example}.`,+ { fix: { argv: ['gbrain', 'config', 'get', key], consent: [], actor: 'agent', why: 'Shows the value in effect; nothing was written.', requires_exclusive: false } }), 'config');+ }const searchRefusal = key.startsWith('search.') ? (await import('../core/search/config-values.ts')).searchConfigValueRefusal(key, value) : null;if (searchRefusal) {const { exitCliError, usageError } = await import('../cli/cli-error.ts');diff --git a/src/commands/doctor/checks/generations.ts b/src/commands/doctor/checks/generations.tsnew file mode 100644index 0000000000..06f0351c22--- /dev/null+++ b/src/commands/doctor/checks/generations.ts@@ -0,0 +1,74 @@+/**+ * GBRA-161 doctor checks over the generation ledger (docs/architecture/generations.md). Both are `WAVE_CHECKS` entries+ * and read-only.+ *+ * - `generation_retirements`: items live generations retired inside the restore window (`generations.restore_days`),+ * which `gbrain repair generations --mode restore` can bring back. Retiring what a complete successor no longer has is+ * the normal path, so this is `ok` with the counts and the read-only preview; it never warns by itself.+ * - `generation_held`: results the primitive held instead of publishing (shrunk, oversize, valve, no_proof, ...). The+ * previous generation stays live and nothing was retired; `warn` names each reason and the preview that lists them.+ * Releasable reasons take `--mode release-held` after the user agrees; the others clear when the producer's input+ * gives the proof it lacked.+ */+import type { BrainEngine } from '../../../core/engine.ts';+import type { Check } from '../../doctor.ts';+import { agentFix } from '../check-fix.ts';+import { readGenerationsConfig } from '../../../core/generations/config.ts';+import { RELEASABLE_HELD_REASONS, type HeldReason } from '../../../core/generations/contract.ts';+import { generationsPreviewArgv } from '../../../core/generations/repair.ts';++const DOCS = 'docs/guides/repair.md#generations';++async function activeSources(engine: BrainEngine, sourceIds?: string[]): Promise<string[]> {+ return sourceIds ?? (await engine.executeRaw<{ id: string }>('SELECT id FROM sources WHERE archived IS NOT TRUE ORDER BY id')).map(row => row.id);+}++export async function generationRetirementsCheck(engine: BrainEngine, sourceIds?: string[]): Promise<Check> {+ try {+ const sources = await activeSources(engine, sourceIds);+ const { restoreDays } = await readGenerationsConfig(engine);+ const rows = await engine.executeRaw<{ source_id: string; kind: string; keys: number; items: number; oldest: string | null }>(`+ SELECT g.source_id, g.kind, count(DISTINCT g.id)::int AS keys, count(*)::int AS items, min(g.created_at)::text AS oldest+ FROM derived_generations g JOIN derived_generation_items i ON i.generation_id=g.id AND i.action='retired'+ WHERE g.source_id=ANY($1::text[]) AND g.state='live' AND g.created_at >= now() - interval '1 day' * $2+ GROUP BY g.source_id, g.kind ORDER BY g.source_id, g.kind`, [sources, restoreDays]);+ const bySource = rows.map(row => ({ ...row, keys: Number(row.keys), items: Number(row.items) }));+ const items = bySource.reduce((sum, row) => sum + row.items, 0);+ const details = { items, keys: bySource.reduce((sum, row) => sum + row.keys, 0), restore_days: restoreDays, by_source: bySource, repair: 'generations', docs: DOCS };+ if (!items) return { name: 'generation_retirements', status: 'ok', details, message: `No live generation retired items in the last ${restoreDays} day(s).` };+ const first = bySource[0]!;+ const preview = generationsPreviewArgv({ kind: first.kind, sourceId: first.source_id });+ return { name: 'generation_retirements', status: 'ok', details,+ message: `${items} derived item(s) were retired by ${details.keys} live generation(s) in the last ${restoreDays} day(s) `+ + `(${bySource.map(row => `${row.source_id}/${row.kind}: ${row.items}`).join('; ')}); each is restorable until the purge hold ends. `+ + `Preview a restore with ${preview.join(' ')} (read-only).` };+ } catch (error) {+ return { name: 'generation_retirements', status: 'warn', details: { items: 'unknown' },+ message: `Generation retirements could not be inspected: ${error instanceof Error ? error.message : String(error)}. Health is unknown.` };+ }+}++export async function generationHeldCheck(engine: BrainEngine, sourceIds?: string[]): Promise<Check> {+ try {+ const sources = await activeSources(engine, sourceIds);+ const rows = await engine.executeRaw<{ source_id: string; kind: string; held_reason: HeldReason; count: number; oldest: string | null }>(`+ SELECT source_id, kind, held_reason, count(*)::int AS count, min(created_at)::text AS oldest+ FROM derived_generations WHERE source_id=ANY($1::text[]) AND state='held'+ GROUP BY source_id, kind, held_reason ORDER BY source_id, kind, held_reason`, [sources]);+ const byReason = rows.map(row => ({ ...row, count: Number(row.count), releasable: RELEASABLE_HELD_REASONS.has(row.held_reason) }));+ const count = byReason.reduce((sum, row) => sum + row.count, 0);+ const details = { count, releasable: byReason.filter(row => row.releasable).reduce((sum, row) => sum + row.count, 0), by_reason: byReason, repair: 'generations', docs: DOCS };+ if (!count) return { name: 'generation_held', status: 'ok', details, message: 'No derived generation is held.' };+ const first = byReason.find(row => row.releasable) ?? byReason[0]!;+ const preview = generationsPreviewArgv({ kind: first.kind, sourceId: first.source_id }, 'release-held');+ return { name: 'generation_held', status: 'warn', details,+ message: `${count} derived result(s) were held instead of published (${byReason.map(row => `${row.source_id}/${row.kind} ${row.held_reason}: ${row.count}`).join('; ')}); `+ + 'the previous generation of each key stays live and nothing was retired. '+ + `Preview them with ${preview.join(' ')} (read-only); release a releasable one only after the user agrees.`,+ fix: agentFix(preview, 'Lists each held result with its reason, attempts and item count and prints the apply command bound to that set; it writes nothing. '+ + 'Releasing is the user\'s call: show them the preview before running the apply.', 'generation_held', { docs: DOCS }) };+ } catch (error) {+ return { name: 'generation_held', status: 'warn', details: { count: 'unknown' },+ message: `Held generations could not be inspected: ${error instanceof Error ? error.message : String(error)}. Health is unknown.` };+ }+}diff --git a/src/commands/doctor/checks/graph-health.ts b/src/commands/doctor/checks/graph-health.tsindex fd1e55d209..64a6d5a9d7 100644--- a/src/commands/doctor/checks/graph-health.ts+++ b/src/commands/doctor/checks/graph-health.ts@@ -353,6 +353,8 @@ export const timelineHistoryEntry: DoctorEntry = {'google_calendar_readable','google_api_access','atom_retirements_restorable',+ 'generation_retirements',+ 'generation_held','extractor_facts_expired','conversation_label_facts','conversation_outcomes_stale',diff --git a/src/commands/doctor/wave-checks.ts b/src/commands/doctor/wave-checks.tsindex c38dccc236..5eafcadead 100644--- a/src/commands/doctor/wave-checks.ts+++ b/src/commands/doctor/wave-checks.ts@@ -322,6 +322,20 @@ export const WAVE_CHECKS: readonly WaveCheckSpec[] = [impact: 'Some atoms were retired when a re-extraction returned no atoms, and the purge removes them once their hold ends',run: async (engine, scope) => (await import('./checks/atom-retirements.ts')).atomRetirementsRestorableCheck(engine, scope.sourceIds),},+ {+ id: 'generation_retirements', resolution: 'repair', registration: 'wave',+ hostOnly: 'Restoring a derived generation is a host-side, explicit-only repair.',+ count: d => Number(d.items ?? 0),+ impact: 'Live generations retired derived items inside the restore window; they stay restorable until the purge hold ends',+ run: async (engine, scope) => (await import('./checks/generations.ts')).generationRetirementsCheck(engine, scope.sourceIds),+ },+ {+ id: 'generation_held', resolution: 'repair', registration: 'wave',+ hostOnly: 'Releasing a held derived generation is a host-side, explicit-only repair.',+ count: d => Number(d.count ?? 0),+ impact: 'Some derived results were held instead of published, so their keys keep the previous generation',+ run: async (engine, scope) => (await import('./checks/generations.ts')).generationHeldCheck(engine, scope.sourceIds),+ },{id: 'extractor_facts_expired', resolution: 'repair', registration: 'wave',hostOnly: 'Restoring expired extractor facts is a host-side, explicit-only repair.',diff --git a/src/core/config.ts b/src/core/config.tsindex 2af511bea4..c72ed9e886 100644--- a/src/core/config.ts+++ b/src/core/config.ts@@ -1766,6 +1766,8 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = ['fences.normalize', // #6188: inline Tier 1 fence normalization (fence-repair/config.ts); default on'fences.repair.enabled', 'fences.repair.llm', // #6188: the fence_repair cycle phase and its Tier 3 model step (fence-repair/config.ts); default on'fences.repair.max_usd_per_page', 'fences.repair.max_usd_per_day', // #6188: Tier 3 fence repair caps; 0 = no model spend+ // GBRA-161: the generation primitive's restore window, shrink floor, item cap and retirement valve (generations/config.ts)+ 'generations.restore_days', 'generations.shrink_floor', 'generations.max_items', 'generations.valve.max_per_run', 'generations.valve.max_ratio',// #2179: clamp window for DCR-requested per-client token TTLs. Read by// `gbrain serve --http` at startup; unset min defaults to 300s, unset max// defaults fail-closed to max(--token-ttl, min).diff --git a/src/core/cycle/extract-atoms-page-state.ts b/src/core/cycle/extract-atoms-page-state.tsindex f6bbf52149..1f1e701f0d 100644--- a/src/core/cycle/extract-atoms-page-state.ts+++ b/src/core/cycle/extract-atoms-page-state.ts@@ -2,7 +2,6 @@ import type { SqlEngine } from '../persistence/model.ts';import type { PageSnapshot } from '../page-state/types.ts';import { stableJson } from '../persistence/digest.ts';import type { BrainEngine } from '../engine.ts';-import { maintenanceTransaction } from '../persistence/attribution.ts';/*** gbrain#4148: consecutive same-content failures of a content-deterministic@@ -71,32 +70,6 @@ export async function writeAtomPageState(return Number(row.fail_count);}-export async function completeAtomReceipts(- engine: BrainEngine, sourceId: string, importedSlugs: string[], hash16: string, page?: AtomPageInput,-): Promise<void> {- await maintenanceTransaction(engine, async tx => {- const completed = await tx.executeRaw(- `UPDATE pages- SET frontmatter = frontmatter || jsonb_build_object('source_hash', $1::text)- WHERE source_id = $2 AND type = 'atom' AND slug = ANY($3::text[]) AND deleted_at IS NULL- ${page ? `AND EXISTS (- SELECT 1 FROM pages origin JOIN sources s ON s.id=origin.source_id- WHERE origin.id=$4 AND s.incarnation=$5::uuid AND origin.source_id=$2- AND origin.content_hash=$6 AND origin.knowledge_revision=$7::uuid AND origin.deleted_at IS NULL- FOR SHARE OF origin, s- )` : ''}- RETURNING slug`,- page- ? [hash16, sourceId, importedSlugs, page.identity?.pageId ?? null,- page.identity?.sourceIncarnation ?? null, page.contentHash, page.identity?.revision ?? null]- : [hash16, sourceId, importedSlugs],- );- if (completed.length !== new Set(importedSlugs).size) {- throw new Error('atom completion could not be saved because the source or atom pages changed; pending atoms remain retryable');- }- });-}-const LEGACY_KEYS = ['atoms_scan_hash', 'atoms_fail_hash', 'atoms_fail_count'];export function matchingLegacyAtomPageState(frontmatter: Record<string, unknown>, contentHash: string): { fail_count: number; tombstoned: boolean } | null {diff --git a/src/core/cycle/extract-atoms.ts b/src/core/cycle/extract-atoms.tsindex ebfa604659..fa25b7ac08 100644--- a/src/core/cycle/extract-atoms.ts+++ b/src/core/cycle/extract-atoms.ts@@ -66,7 +66,6 @@ import type { GBrainConfig } from '../config.ts';import type { ProgressReporter } from '../progress.ts';import { chat as gatewayChat, withBudgetTracker, isAvailable } from '../ai/gateway.ts';import { createGlobalLlmHaltTracker, haltedClassOf, providerContentBlockReason, type GlobalLlmErrorClass } from '../ai/errors.ts';-import { importFromContent } from '../import-file.ts';import { derivedWriteThrough, reportFileHolds } from './derived-write-through.ts';import { serializeMarkdown } from '../markdown.ts';import { DEFAULT_EXTRACT_MAX_INPUT_CHARS, extractAtomsInput, inputTruncatedLine, recordPartialDisposition, releasePartialDispositions, resolveExtractAtomsInputCap, stampTranscriptTombstone, type ExtractAtomsInput, type ExtractAtomsItem } from './extract-atoms-input.ts';@@ -94,10 +93,11 @@ import { OperationError } from '../ops/contract.ts';import { isOpPageSlug } from '../ops/context.ts';import type { WriteReceipt } from '../persistence/types.ts';import { acceptedPendingReceipt } from '../persistence/accepted-pending.ts';-import { AtomPageStateError, completeAtomReceipts, MAX_DETERMINISTIC_FAILURES, readAtomPageIdentity, writeAtomPageState, type AtomPageInput } from './extract-atoms-page-state.ts';-import { ATOM_RETIRED_BY_EXTRACT, retireDerivedPages } from '../persistence/derived-retirement-hold.ts';-import { deriveTrust, lowerDerivedPage } from '../trust/taint.ts';-import { derivedGateInput } from '../trust/derived-gate.ts';+import { AtomPageStateError, MAX_DETERMINISTIC_FAILURES, readAtomPageIdentity, writeAtomPageState, type AtomPageInput } from './extract-atoms-page-state.ts';+import { ATOM_KIND, atomGenerationAdapter, atomOwnerKey, atomPagePin, type AtomGenerationContext } from '../generations/adapters/atoms.ts';+import { markdownItem } from '../generations/adapters/page.ts';+import type { GenerationKey } from '../generations/contract.ts';+import { heldForInput, publishGeneration } from '../generations/publish.ts';import { ATOM_TYPES, ATOMS_RESPONSE_SCHEMA } from './extract-atoms-schema.ts';import { parseAtomsOutcome } from './extract-atoms-parse.ts';export { parseAtomsOutcome, parseAtomsResponse, type AtomsParseOutcome } from './extract-atoms-parse.ts';@@ -992,6 +992,8 @@ export async function runPhaseExtractAtoms(let hardFailureCount = 0;let writesPending = 0; // #5601: accepted atom batches still publishing (progress, not failures)let heldFailed = 0;+ // GBRA-161: one run id for the receipt and every generation this run publishes (`gbrain repair generations --run`).+ const runId = `atoms-${Date.now().toString(36)}-${sourceId.slice(0, 4)}`;let inputTruncated = 0; // #6503: items cut at the input cap this run (partial disposition, see extract-atoms-input.ts)async function stampAtomsScanHash(item: AtomPageInput): Promise<void> {@@ -1096,6 +1098,8 @@ export async function runPhaseExtractAtoms(const resumed = !opts.dryRun && managed && origin ? await resumeManagedAtoms(engine, managed, origin) : 'run';if (resumed === 'done') { duplicatesSkipped++; continue; }if (resumed === 'held') { heldFailed++; continue; } // #6325: settled after repeated failures; doctor lists it+ // GBRA-161: a complete read whose result for this same input and policy is already held is not computed again.+ if (!opts.dryRun && !managed && !truncated && await heldForInput(engine, atomGenerationOrigin(sourceId, item).key, atomInputPin(item))) { duplicatesSkipped++; continue; }const cutLine = truncated ? inputTruncatedLine(originLabel, input, maxInputChars) : null; // A7: a complete appended-tail read prints nothingif (cutLine) { inputTruncated++; console.error(cutLine); } // counted only for a model call@@ -1172,6 +1176,7 @@ export async function runPhaseExtractAtoms(const hash16 = item.contentHash.slice(0, 16);const importedSlugs: string[] = [];const managedAtoms: Array<{ slug: string; content: string; links: LinkBatchInput[] }> = [];+ const unmanagedAtoms: Array<{ slug: string; content: string }> = [];// #3961: provenance edges source-page → atom, accumulated during the// atom loop and flushed BEFORE the completion-receipt flip (see the// write below). Page-kind items only — transcripts are files, not@@ -1246,8 +1251,7 @@ export async function runPhaseExtractAtoms({ type: 'atom', title: atom.title, tags: [] },);if (managed) managedAtoms.push({ slug, content: md, links: [] });- else { const taint = await deriveTrust(engine, item.kind === 'page' ? [{ table: 'pages', sourceId, slug: item.slug }] : [], { channel: 'derive:atoms' }); // #5575 I2/B3: gated and stamped at the origin's taint- await importFromContent(engine, slug, md, { sourceId, preserveGateMarkers: true, noEmbed: !isAvailable('embedding'), writeGate: derivedGateInput(taint.trust) }).then(() => lowerDerivedPage(engine, taint, sourceId, slug)); }+ else unmanagedAtoms.push({ slug, content: md });importedSlugs.push(slug);if (item.kind === 'page') {provenanceLinks.push({@@ -1291,18 +1295,23 @@ export async function runPhaseExtractAtoms(totalAtomsExtracted += managedAtoms.length;await commitAtomsWatermark(item, input, published);} else {- if (provenanceLinks.length > 0) {- await engine.addLinksBatch(provenanceLinks, { auditSite: 'cycle.extract_atoms.provenance' }); // gbrain-allow-direct-insert: atom-provenance edges derived from the extraction itself (no markdown body to reconcile from)- }- // Completion receipt: flip provisional → real in one statement (only- // after every atom AND provenance edge persisted), then stamp the- // source page. A crash between flip and stamp degrades to the legacy- // atom-rows-mean-done semantics — safe, not lossy.+ // GBRA-161: the atoms, their provenance edges (#3961, #4733), the completion flip (source_hash, #4148) and the+ // versioned retirement of the atoms this extraction no longer produced (C-14) publish as one generation in one+ // transaction (#5575 I2/B3: gated and stamped at the origin's taint inside the adapter). #6503: a cut item publishes+ // additively, stays provisional (`pending:<hash>`), retires nothing and records its partial disposition.throwIfAborted(opts.signal, 'extract_atoms');- // #6503: a cut item keeps its atoms provisional (`pending:<hash>`, the upsert path when it runs- // again), retires nothing and records its partial disposition instead of a completion stamp.- const retired = truncated ? [] : await completeUnmanagedItem(engine, sourceId, item, hash16, importedSlugs);- await atomFiles?.write(importedSlugs, retired);+ const { key, context } = atomGenerationOrigin(sourceId, item);+ context.links = provenanceLinks;+ context.embed = isAvailable('embedding');+ const outcome = await publishGeneration(engine, atomGenerationAdapter, { key, items: unmanagedAtoms.map(atom => markdownItem(atom.slug, atom.content)),+ input: { pin: atomInputPin(item), size: Buffer.byteLength(item.kind === 'transcript' ? item.content : sourcePage?.compiled_truth ?? '') },+ partial: truncated, context, runId });+ for (const complete of context.postCommit ?? []) await complete().catch(error => console.error(`[extract_atoms] ${originLabel}: post-commit embedding failed (the embedding backfill retries it): ${error instanceof Error ? error.message : String(error)}`));+ if (outcome.state === 'held') {+ console.error(`[extract_atoms] ${originLabel}: result held (${outcome.reason}); the previous atoms stay live. Preview: gbrain repair generations --kind ${ATOM_KIND} --mode release-held --key ${key.ownerKey} --source ${sourceId}`);+ continue;+ }+ await atomFiles?.write(unmanagedAtoms.map(atom => atom.slug), outcome.retired);if (truncated) await recordPartialDisposition(engine, sourceId, item, maxInputChars);else if (item.kind === 'page') await stampAtomsScanHash(item);await commitAtomsWatermark(item, input, []);@@ -1375,7 +1384,6 @@ export async function runPhaseExtractAtoms(// audit-trail / search-visibility surfaces don't block the phase result.const hardStopped = opts.signal?.aborted === true;if (!opts.dryRun && !managed && totalAtomsExtracted > 0 && !hardStopped) {- const runId = `atoms-${Date.now().toString(36)}-${sourceId.slice(0, 4)}`;try {await writeReceipt(engine, {kind: 'atoms',@@ -1458,51 +1466,16 @@ export async function runPhaseExtractAtoms(}, atomFiles?.held, 'atom');}-/**- * Completion receipt: flip provisional → real in one statement (only after- * every atom AND provenance edge persisted). C-14: atoms are keyed by- * LLM-chosen titles, which drift between extractions, so once this extraction- * is complete, retire the atoms an earlier extraction of the same source- * produced that this one did not. Returns the retired slugs.- */-async function completeUnmanagedItem(engine: BrainEngine, sourceId: string,- item: { kind: 'transcript'; filePath: string } | ({ kind: 'page' } & AtomPageInput), hash16: string, importedSlugs: string[]): Promise<string[]> {- await completeAtomReceipts(engine, sourceId, importedSlugs, hash16, item.kind === 'page' ? item : undefined);- return retireStaleAtoms(engine, sourceId, item.kind === 'page'- ? { key: 'source_slug', value: item.slug } : { key: 'source_path', value: item.filePath }, hash16, importedSlugs);+/** GBRA-161: the input pin an unmanaged item was read at (a page's is bound to its row and revision, see atomPagePin). */+function atomInputPin(item: ExtractAtomsItem): string {+ return item.kind === 'page' ? atomPagePin(item.contentHash, item.identity) : item.contentHash;}-/**- * Soft-delete a source's atoms from earlier extractions (a different or- * provisional source_hash) that the current, completed extraction did not- * re-produce. Imported atoms (`imported_from`) and managed atoms are left- * alone; retired atoms are held 30 days. Best-effort: a failure leaves duplicates, never loses current atoms.- */-async function retireStaleAtoms(- engine: BrainEngine,- sourceId: string,- origin: { key: 'source_slug' | 'source_path'; value: string },- hash16: string,- currentSlugs: string[],-): Promise<string[]> {- try {- const rows = await engine.executeRaw<{ slug: string }>(- `SELECT slug FROM pages- WHERE source_id = $1 AND type = 'atom' AND deleted_at IS NULL- AND frontmatter->>'${origin.key}' = $2- AND COALESCE(frontmatter->>'source_hash', '') <> $3- AND (frontmatter->>'imported_from') IS NULL- AND COALESCE(frontmatter->>'managed_extraction', '') <> 'true'- AND NOT (slug = ANY($4::text[]))`,- [sourceId, origin.value, hash16, currentSlugs],- );- const stale = rows.map(r => r.slug);- await retireDerivedPages(engine, sourceId, stale, ATOM_RETIRED_BY_EXTRACT);- return stale;- } catch (err) {- console.error(`[extract_atoms] stale atom cleanup failed for ${origin.value} (non-fatal): ${err instanceof Error ? err.message : String(err)}`);- return [];- }+/** GBRA-161: the generation key of one unmanaged item and the context its adapter reads (a transcript's input is not in the database). */+function atomGenerationOrigin(sourceId: string, item: ExtractAtomsItem): { key: GenerationKey; context: AtomGenerationContext } {+ const ownerKey = atomOwnerKey(item.kind === 'page' ? { kind: 'page', slug: item.slug } : { kind: 'transcript', filePath: item.filePath });+ return { key: { kind: ATOM_KIND, sourceId, ownerKey },+ context: { postCommit: [], ...(item.kind === 'transcript' ? { transcriptInput: { pin: item.contentHash, size: Buffer.byteLength(item.content) } } : {}) } };}/**diff --git a/src/core/doctor-categories.ts b/src/core/doctor-categories.tsindex 6f1c7ff277..8bb72f326b 100644--- a/src/core/doctor-categories.ts+++ b/src/core/doctor-categories.ts@@ -68,6 +68,9 @@ export const BRAIN_CHECK_NAMES: ReadonlySet<string> = new Set(['connector_held_items','git_held_files','fence_integrity',+ // GBRA-161: derived items live generations retired in the restore window, and results held instead of published (doctor/checks/generations.ts).+ 'generation_held',+ 'generation_retirements',// #5575: stored trust tier counts, the legacy-row backfill, scan and source claims.'trust_tiers','trust_scan',diff --git a/src/core/generations/adapters/atoms.ts b/src/core/generations/adapters/atoms.tsindex 851ce4b374..d428c92651 100644--- a/src/core/generations/adapters/atoms.ts+++ b/src/core/generations/adapters/atoms.ts@@ -33,6 +33,15 @@ export function atomOwnerKey(origin: { kind: 'page'; slug: string } | { kind: 'treturn origin.kind === 'page' ? `source_slug:${origin.slug}` : `source_path:${origin.filePath}`;}+/**+ * A page origin's input pin: its content hash bound to the page row and its knowledge revision, so an extraction of a+ * page deleted and recreated (or edited back to the same text) during the provider call cannot complete (#4148). The+ * first 16 characters stay the completion stamp (`source_hash`).+ */+export function atomPagePin(contentHash: string, identity: { pageId: number; revision: string } | undefined): string {+ return identity ? `${contentHash}:${identity.pageId}:${identity.revision}` : contentHash;+}+function originOf(key: GenerationKey): Origin {const at = key.ownerKey.indexOf(':');const field = key.ownerKey.slice(0, at);@@ -51,9 +60,9 @@ export const atomGenerationAdapter: GenerationAdapter<AtomGenerationContext> = {async readInput(engine, key, context) {const origin = originOf(key);if (origin.field === 'source_path') return context?.transcriptInput ?? null;- const [row] = await engine.executeRaw<{ content_hash: string | null; body_bytes: number | null }>(- 'SELECT content_hash, body_bytes FROM pages WHERE source_id=$1 AND slug=$2 AND deleted_at IS NULL', [key.sourceId, origin.value]);- return row?.content_hash ? { pin: row.content_hash, size: Number(row.body_bytes ?? 0) } : null;+ const [row] = await engine.executeRaw<{ id: number; content_hash: string | null; revision: string | null; body_bytes: number | null }>(+ 'SELECT id, content_hash, knowledge_revision::text AS revision, body_bytes FROM pages WHERE source_id=$1 AND slug=$2 AND deleted_at IS NULL', [key.sourceId, origin.value]);+ return row?.content_hash ? { pin: atomPagePin(row.content_hash, row.revision ? { pageId: Number(row.id), revision: row.revision } : undefined), size: Number(row.body_bytes ?? 0) } : null;},async readItems(engine, key, itemKeys) {const origin = originOf(key);diff --git a/src/core/generations/adapters/page.ts b/src/core/generations/adapters/page.tsindex 8272b0d46c..33e53ca25f 100644--- a/src/core/generations/adapters/page.ts+++ b/src/core/generations/adapters/page.ts@@ -77,10 +77,10 @@ export function preimageMarkdown(preimage: Record<string, unknown>): string {{ type: String(preimage.type) as PageType, title: String(preimage.title), tags: (preimage.tags as string[]) ?? [] });}-/** Writes one page item inside the activation transaction; embeddings are left to the embedding backfill. */+/** Writes one page item inside the activation transaction; without a post-commit embedding hook it leaves embeddings to the backfill. */export async function importPageItem(tx: BrainEngine, sourceId: string, slug: string, content: string,opts: Partial<Parameters<typeof importFromContent>[3]> = {}): Promise<void> {- await importFromContent(tx, slug, content, { ...opts, sourceId, preserveGateMarkers: true, noEmbed: true });+ await importFromContent(tx, slug, content, { noEmbed: true, ...opts, sourceId, preserveGateMarkers: true });}/** Rows whose retained page version was written by the producer (`producer`: a predicate over version alias `v`) at the row's identity. */diff --git a/src/core/generations/config.ts b/src/core/generations/config.tsindex 89d61faa14..1b70f44a82 100644--- a/src/core/generations/config.ts+++ b/src/core/generations/config.ts@@ -40,7 +40,7 @@ export function restoreDaysHint(): number { return restoreDaysSeen; }/** Reads the five settings; a failed read keeps the default for that setting, the same as an out-of-range value. */export async function readGenerationsConfig(engine: Pick<BrainEngine, 'getConfig'>): Promise<GenerationsConfig> {- const read = async (bound: Bound) => parseBound(bound, await engine.getConfig(bound.key).catch(() => null)) ?? bound.fallback;+ const read = async (bound: Bound) => parseBound(bound, await Promise.resolve().then(() => engine.getConfig(bound.key)).catch(() => null)) ?? bound.fallback;const config = { restoreDays: await read(GENERATION_BOUNDS.restoreDays), shrinkFloor: await read(GENERATION_BOUNDS.shrinkFloor),maxItems: await read(GENERATION_BOUNDS.maxItems), valveMaxPerRun: await read(GENERATION_BOUNDS.valveMaxPerRun), valveMaxRatio: await read(GENERATION_BOUNDS.valveMaxRatio) };restoreDaysSeen = config.restoreDays;diff --git a/src/core/generations/publish.ts b/src/core/generations/publish.tsindex 432a585850..aae0bda9b4 100644--- a/src/core/generations/publish.ts+++ b/src/core/generations/publish.ts@@ -154,7 +154,7 @@ export async function publishGeneration<C>(engine: BrainEngine, adapter: Generattry {const outcome = await maintenanceTransaction(engine, async tx => {await lockGeneration(tx, adapter as GenerationAdapter<unknown>, key, itemKeys);- const [replay] = await tx.executeRaw<{ generation: number }>(`SELECT generation FROM derived_generations WHERE operation_id=$1 AND state <> 'held'`, [operationId]);+ const [replay] = await tx.executeRaw<{ generation: number }>(`SELECT generation FROM derived_generations WHERE operation_id=$1 AND state = 'live'`, [operationId]);if (replay) return { state: 'unchanged', generation: Number(replay.generation), retired: [], protected: [] } satisfies PublishOutcome;const live = await readLiveGeneration(tx, key);if (request.expectedGeneration !== undefined && (live?.generation ?? 0) !== request.expectedGeneration) {@@ -169,7 +169,10 @@ export async function publishGeneration<C>(engine: BrainEngine, adapter: Generatconst plan = planGeneration({ live, rows, proposal: request.items, input, config, modelProduced: adapter.modelProduced, additive: request.partial === true,proofHolds: request.proof ? proofHolds(request.proof, input, live?.inputPin) : false, evidence, valve, release: request.release?.reason });if (plan.kind === 'held') return recordHeld(tx, key, config, request, setHash, plan.reason, plan.context);- if (plan.kind === 'unchanged') return { state: 'unchanged', generation: live?.generation ?? null, retired: [], protected: plan.protectedKeys } satisfies PublishOutcome;+ if (plan.kind === 'unchanged') {+ if (!request.partial) await adapter.completeItems?.(tx, key, itemKeys, request.context);+ return { state: 'unchanged', generation: live?.generation ?? null, retired: [], protected: plan.protectedKeys } satisfies PublishOutcome;+ }const preimage = (itemKey: string) => rows.get(itemKey)?.preimage();if (plan.puts.length) await adapter.publishItems(tx, key, plan.puts, request.context);await faultPoint('generation:published', { sourceId: key.sourceId, operation: key.kind });diff --git a/src/core/pglite-schema.generated.ts b/src/core/pglite-schema.generated.tsindex 709ccec6c4..aafa21bb83 100644--- a/src/core/pglite-schema.generated.ts+++ b/src/core/pglite-schema.generated.ts@@ -1244,7 +1244,7 @@ CREATE TABLE IF NOT EXISTS derived_generations ();CREATE UNIQUE INDEX IF NOT EXISTS derived_generations_one_live ON derived_generations (source_id, kind, owner_key) WHERE state = 'live';CREATE UNIQUE INDEX IF NOT EXISTS derived_generations_one_hold ON derived_generations (source_id, kind, owner_key) WHERE state = 'held';-CREATE UNIQUE INDEX IF NOT EXISTS derived_generations_operation ON derived_generations (operation_id);+CREATE INDEX IF NOT EXISTS derived_generations_operation ON derived_generations (operation_id);CREATE INDEX IF NOT EXISTS derived_generations_state_created ON derived_generations (state, created_at);CREATE TABLE IF NOT EXISTS derived_generation_items (generation_id BIGINT NOT NULL REFERENCES derived_generations(id) ON DELETE CASCADE,diff --git a/src/core/schema-embedded.generated.ts b/src/core/schema-embedded.generated.tsindex eaee2f2f8d..c59a36eaa5 100644--- a/src/core/schema-embedded.generated.ts+++ b/src/core/schema-embedded.generated.ts@@ -1975,7 +1975,7 @@ CREATE TABLE IF NOT EXISTS derived_generations ();CREATE UNIQUE INDEX IF NOT EXISTS derived_generations_one_live ON derived_generations (source_id, kind, owner_key) WHERE state = 'live';CREATE UNIQUE INDEX IF NOT EXISTS derived_generations_one_hold ON derived_generations (source_id, kind, owner_key) WHERE state = 'held';-CREATE UNIQUE INDEX IF NOT EXISTS derived_generations_operation ON derived_generations (operation_id);+CREATE INDEX IF NOT EXISTS derived_generations_operation ON derived_generations (operation_id);CREATE INDEX IF NOT EXISTS derived_generations_state_created ON derived_generations (state, created_at);CREATE TABLE IF NOT EXISTS derived_generation_items (generation_id BIGINT NOT NULL REFERENCES derived_generations(id) ON DELETE CASCADE,diff --git a/src/core/schema-migrations/v265-derived-generations.ts b/src/core/schema-migrations/v265-derived-generations.tsindex edf3125868..d7e0a80098 100644--- a/src/core/schema-migrations/v265-derived-generations.ts+++ b/src/core/schema-migrations/v265-derived-generations.ts@@ -39,7 +39,7 @@ export const v265: Migration = {);CREATE UNIQUE INDEX IF NOT EXISTS derived_generations_one_live ON derived_generations (source_id, kind, owner_key) WHERE state = 'live';CREATE UNIQUE INDEX IF NOT EXISTS derived_generations_one_hold ON derived_generations (source_id, kind, owner_key) WHERE state = 'held';- CREATE UNIQUE INDEX IF NOT EXISTS derived_generations_operation ON derived_generations (operation_id);+ CREATE INDEX IF NOT EXISTS derived_generations_operation ON derived_generations (operation_id);CREATE INDEX IF NOT EXISTS derived_generations_state_created ON derived_generations (state, created_at);CREATE TABLE IF NOT EXISTS derived_generation_items (generation_id BIGINT NOT NULL REFERENCES derived_generations(id) ON DELETE CASCADE,diff --git a/src/schema.sql b/src/schema.sqlindex 5bbce01a85..a900c6e424 100644--- a/src/schema.sql+++ b/src/schema.sql@@ -1971,7 +1971,7 @@ CREATE TABLE IF NOT EXISTS derived_generations ();CREATE UNIQUE INDEX IF NOT EXISTS derived_generations_one_live ON derived_generations (source_id, kind, owner_key) WHERE state = 'live';CREATE UNIQUE INDEX IF NOT EXISTS derived_generations_one_hold ON derived_generations (source_id, kind, owner_key) WHERE state = 'held';-CREATE UNIQUE INDEX IF NOT EXISTS derived_generations_operation ON derived_generations (operation_id);+CREATE INDEX IF NOT EXISTS derived_generations_operation ON derived_generations (operation_id);CREATE INDEX IF NOT EXISTS derived_generations_state_created ON derived_generations (state, created_at);CREATE TABLE IF NOT EXISTS derived_generation_items (generation_id BIGINT NOT NULL REFERENCES derived_generations(id) ON DELETE CASCADE,diff --git a/test/cycle/extract-atoms-reconcile.test.ts b/test/cycle/extract-atoms-reconcile.test.tsindex 597eec1bdf..014e35ca3d 100644--- a/test/cycle/extract-atoms-reconcile.test.ts+++ b/test/cycle/extract-atoms-reconcile.test.ts@@ -67,6 +67,9 @@ describe('extract_atoms reconciles atoms with their source (C-14)', () => {test('a re-extracted transcript retires atoms its new extraction dropped', async () => {const filePath = '/corpus/2026-05-01-standup.txt';+ // GBRA-161: one atom replacing two is a shrink the default floor (0.5) holds for review; this test is about the+ // retirement of the dropped atom, so it lowers the floor to its minimum.+ await engine.setConfig('generations.shrink_floor', '0.05');await runPhaseExtractAtoms(engine, {_transcripts: [{ filePath, content: 'v1', contentHash: 'a'.repeat(64) }], _pages: [],_chat: chatWithTitles(['Ship smaller', 'Measure first']),diff --git a/test/extract-atoms-input-truncated-6503.test.ts b/test/extract-atoms-input-truncated-6503.test.tsindex 3bc684bea3..5eac90bd57 100644--- a/test/extract-atoms-input-truncated-6503.test.ts+++ b/test/extract-atoms-input-truncated-6503.test.ts@@ -78,7 +78,11 @@ const transcriptState = (engine: BrainEngine, sourceId: string, filePath: string/** An atom an earlier, larger-cap extraction derived from the item's tail: another source_hash, same origin. */async function seedTailAtom(engine: BrainEngine, sourceId: string, originKey: 'source_slug' | 'source_path', origin: string, slug: string, managed: boolean) {await engine.putPage(slug, { type: 'atom', title: 'Hidden decision from the tail', compiled_truth: 'The tail decision was recorded by an earlier extraction.',- frontmatter: { atom_type: 'insight', [originKey]: origin, source_hash: 'earlier0000cap00', dream_generated: true, ...(managed ? { managed_extraction: true } : {}) } }, { sourceId });+ frontmatter: { atom_type: 'insight', [originKey]: origin, source_hash: 'earlier0000cap00', dream_generated: true, extracted_by: 'extract_atoms-v0.41.2.1',+ ...(managed ? { managed_extraction: true } : {}) } }, { sourceId });+ // GBRA-161: an atom from before the generation ledger is retired only on retained extractor evidence (a page version+ // the extractor wrote, unedited since), which a real earlier extraction leaves behind.+ await engine.createVersion(slug, { sourceId });}describe('extract_atoms partial disposition for items cut at max_input_chars (#6503)', () => {@@ -145,6 +149,8 @@ describe('extract_atoms partial disposition for items cut at max_input_chars (#6test('unmanaged page: head atoms publish, the tail atom survives, no completion stamp, skipped until the cap rises', async () => {for (const { backend, engine } of engines) {await engine.setConfig(KNOB, String(CAP));+ // GBRA-161: the released run replaces the head atom and the tail atom with one atom, a shrink the default floor holds.+ await engine.setConfig('generations.shrink_floor', '0.05');const sourceId = `cut-page-${backend}`;await engine.executeRaw('INSERT INTO sources(id,name) VALUES($1,$1)', [sourceId]);const slug = 'notes/long-decision';@@ -183,6 +189,8 @@ describe('extract_atoms partial disposition for items cut at max_input_chars (#6test('unmanaged transcript: the same disposition through the transcript seam', async () => {for (const { backend, engine } of engines) {await engine.setConfig(KNOB, String(CAP));+ // GBRA-161: as above, one atom replaces two when the cap rises.+ await engine.setConfig('generations.shrink_floor', '0.05');const sourceId = `cut-transcript-${backend}`;await engine.executeRaw('INSERT INTO sources(id,name) VALUES($1,$1)', [sourceId]);const filePath = `/corpus/${sourceId}/session.txt`;diff --git a/test/extract-atoms-page-state.test.ts b/test/extract-atoms-page-state.test.tsindex 50752fc2e3..847e67b8db 100644--- a/test/extract-atoms-page-state.test.ts+++ b/test/extract-atoms-page-state.test.ts@@ -175,11 +175,13 @@ describe('derived atom page state', () => {if (failure === 'atom' && args[1].type === 'atom' && ++writes === 2) throw new Error('synthetic second atom failure');return put.apply(this, args);}) as typeof put;- engine.addLinksBatch = async (...args) => {+ // GBRA-161: the atoms, their edges and the completion flip are written in one generation transaction, so the stubs+ // keep their receiver (the transaction) instead of writing around it.+ engine.addLinksBatch = async function (this: PGLiteEngine, ...args: Parameters<typeof links>) {if (failure === 'links') throw new Error('synthetic provenance failure');- const result = await links.apply(engine, args);+ const result = await links.apply(this, args);if (failure === 'deleted-before-completion') {- await engine.executeRaw("DELETE FROM pages WHERE source_id='default' AND slug=$1", [args[0][0].to_slug]);+ await this.executeRaw("DELETE FROM pages WHERE source_id='default' AND slug=$1", [args[0][0].to_slug]);}return result;};@@ -187,19 +189,19 @@ describe('derived atom page state', () => {const result = await scan(atoms);expect(result.status).toBe('warn');if (failure === 'deleted-before-completion') {- expect(JSON.stringify(result.details.failures)).toContain('pending atoms remain retryable');+ expect(JSON.stringify(result.details.failures)).toContain('is not live at the content just written; nothing was committed');}}finally { engine.putPage = put; engine.addLinksBatch = links; }- const pending = await engine.executeRaw<{ hash: string }>("SELECT frontmatter->>'source_hash' AS hash FROM pages WHERE type='atom'");- expect(pending).toHaveLength(failure === 'links' ? 2 : 1);- expect(pending.every(row => row.hash.startsWith('pending:'))).toBe(true);+ // GBRA-161: a failed publication rolls back whole: no atom row, provisional or final, and no scan state.+ expect(await engine.executeRaw("SELECT slug FROM pages WHERE type='atom'")).toEqual([]);expect((await rows()).every(row => !row.tombstoned)).toBe(true);expect(await countExtractAtomsBacklog(engine, 'default')).toBe(1);expect((await scan(atoms)).status).toBe('ok');+ const [origin] = await engine.executeRaw<{ content_hash: string }>("SELECT content_hash FROM pages WHERE source_id='default' AND slug=$1", [slug]);const complete = await engine.executeRaw<{ hash: string }>("SELECT frontmatter->>'source_hash' AS hash FROM pages WHERE type='atom'");expect(complete).toHaveLength(2);- expect(complete.every(row => row.hash === (pending[0].hash.slice('pending:'.length)))).toBe(true);+ expect(complete.every(row => row.hash === origin!.content_hash.slice(0, 16))).toBe(true);expect((await engine.getLinks(slug)).filter(link => link.link_source === 'atom-provenance')).toHaveLength(2);expect(await countExtractAtomsBacklog(engine, 'default')).toBe(0);});diff --git a/test/extract-atoms-provenance-links.test.ts b/test/extract-atoms-provenance-links.test.tsindex 02639665d8..f390ea1309 100644--- a/test/extract-atoms-provenance-links.test.ts+++ b/test/extract-atoms-provenance-links.test.ts@@ -596,10 +596,11 @@ describe('provenance edges are banked BEFORE the completion flip (#4733)', () =>const originalAddLinksBatch = engine.addLinksBatch;let provenanceWrites = 0;- engine.addLinksBatch = async (links, opts) => {+ // GBRA-161: the edges are written inside the generation's activation transaction, so the stub keeps its receiver.+ engine.addLinksBatch = async function (this: typeof engine, links, opts) {provenanceWrites++;if (provenanceWrites === 1) throw new Error('forced provenance write failure');- return originalAddLinksBatch.call(engine, links, opts);+ return originalAddLinksBatch.call(this, links, opts);};try {const first = await runPhaseExtractAtoms(engine, {@@ -616,15 +617,15 @@ describe('provenance edges are banked BEFORE the completion flip (#4733)', () =>error: expect.stringContaining('forced provenance write failure'),}),]);- // No edge banked, and the atom's receipt NEVER flipped: the pending- // hash keeps the item discoverable for the next run.+ // No edge banked, and the atom's receipt NEVER flipped. GBRA-161: the atoms, edges and flip are one generation+ // transaction, so the failed publication left no atom row at all; the item stays discoverable for the next run.expect((await engine.getLinks(sourceSlug)).filter(l => l.link_source === 'atom-provenance')).toHaveLength(0);const pending = await engine.executeRaw<{ source_hash: string }>(`SELECT frontmatter->>'source_hash' AS source_hashFROM pages WHERE type = 'atom' AND frontmatter->>'source_slug' = $1`,[sourceSlug],);- expect(pending).toEqual([{ source_hash: `pending:${contentHash.slice(0, 16)}` }]);+ expect(pending).toEqual([]);const retry = await runPhaseExtractAtoms(engine, {_transcripts: [],@@ -760,21 +761,28 @@ describe('case-insensitive same-page atom adoption (#5030)', () => {await engine.putPage(slugA, {type: 'atom', title: titleA, compiled_truth: 'Duplicate atom A.', timeline: '',- frontmatter: { source_slug: sourceSlug, source_hash: 'eeee111122223333', atom_type: 'insight' },+ frontmatter: { source_slug: sourceSlug, source_hash: 'eeee111122223333', atom_type: 'insight', extracted_by: 'extract_atoms-v0.41.2.1' },});await engine.putPage(slugB, {type: 'atom', title: titleB, compiled_truth: 'Duplicate atom B.', timeline: '',- frontmatter: { source_slug: sourceSlug, source_hash: 'ffff444455556666', atom_type: 'insight' },+ frontmatter: { source_slug: sourceSlug, source_hash: 'ffff444455556666', atom_type: 'insight', extracted_by: 'extract_atoms-v0.41.2.1' },});+ // GBRA-161: an atom from before the generation ledger is retired only on retained extractor evidence (a page+ // version the extractor wrote, unedited since), so the seed keeps one like a real extraction would.+ await engine.createVersion(slugA, { sourceId: 'default' });+ await engine.createVersion(slugB, { sourceId: 'default' });// Re-extraction returns yet a THIRD case variant of the same title. Must// not throw, and must not silently adopt either pre-existing duplicate.const thirdCaseTitle = 'ambiguous Duplicate title';+ // GBRA-161: one atom replacing two is a shrink the default floor (0.5) holds for review; this test is about slug+ // choice, so it lowers the floor to its minimum for this one run.+ await engine.setConfig('generations.shrink_floor', '0.05');const result = await runPhaseExtractAtoms(engine, {_transcripts: [],_pages: [{ slug: sourceSlug, content: 'A claim with an ambiguous title history.', contentHash: 'gggg777788889999' }],_chat: stubChat(thirdCaseTitle),- });+ }).finally(() => engine.setConfig('generations.shrink_floor', '0.5'));expect(result.status).toBe('ok');expect(result.details?.failures).toEqual([]);expect(result.details?.atoms_extracted).toBe(1);diff --git a/test/helpers/config-reader-registry.ts b/test/helpers/config-reader-registry.tsindex 0023b4b023..54eab4555f 100644--- a/test/helpers/config-reader-registry.ts+++ b/test/helpers/config-reader-registry.ts@@ -116,6 +116,7 @@ export const UNRESOLVED_CONFIG_READS: readonly UnresolvedConfigRead[] = [{ file: 'src/core/feedback/settings.ts', expr: 'key', why: P },{ file: 'src/core/fence-repair/config.ts', expr: 'key', why: P },{ file: 'src/core/fence-repair/config.ts', expr: 'key', why: P },+ { file: 'src/core/generations/config.ts', expr: 'bound.key', why: 'readGenerationsConfig walk over GENERATION_BOUNDS (the five generations.* keys, each registered in KNOWN_CONFIG_KEYS)' },{ file: 'src/core/import-file.ts', expr: 'key', why: P },{ file: 'src/core/import-screen.ts', expr: 'key', why: P },{ file: 'src/core/line-grammar.ts', expr: 'key', why: P },diff --git a/test/repair-explicit-only.test.ts b/test/repair-explicit-only.test.tsindex 1bdcc370f6..450c1752d3 100644--- a/test/repair-explicit-only.test.ts+++ b/test/repair-explicit-only.test.ts@@ -24,7 +24,9 @@ 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', 'redacted-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', 'legacy-twins', 'missing-tables', 'url-clone-fences', 'segmented-mirror', 'uncommitted-deletions'];+const EXPLICIT: RepairKind[] = ['accepted-takes', 'google-file-modes', 'stale-atoms', 'atoms-restore', 'extractor-facts', 'conversation-labels', 'captured-facts', 'redacted-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', 'legacy-twins', 'missing-tables', 'url-clone-fences', 'segmented-mirror', 'uncommitted-deletions', 'generations'];+// GBRA-161: the generations preview carries its ledger kind and the restore window, so the printed command runs as is.+const PREVIEW = (kind: RepairKind): string => kind === 'generations' ? 'gbrain repair generations --kind atom --since 30d' : `gbrain repair ${kind}`;let engine: PGLiteEngine;const home = mkdtempSync(join(tmpdir(), 'gbrain-repair-explicit-'));@@ -106,7 +108,7 @@ describe('surfaces that list instead of run', () => {for (const args of [['--all', '--json'], ['--json']]) {const out = JSON.parse(await captured(args)) as { results: Array<{ kind: string }>; explicit_kinds: Array<{ kind: string; code: string; preview_command: string }> };expect(out.results.map(r => r.kind)).toEqual(AUTO_REPAIR_REGISTRY.map(spec => spec.kind));- expect(out.explicit_kinds).toEqual(EXPLICIT.map(kind => ({ kind, code: 'explicit_kind_required', preview_command: `gbrain repair ${kind}`,+ expect(out.explicit_kinds).toEqual(EXPLICIT.map(kind => ({ kind, code: 'explicit_kind_required', preview_command: PREVIEW(kind),docs: 'docs/guides/repair.md#explicit-only-repair-kinds' })));}expect(await captured(['--all'])).toContain('Explicit-only kinds (not run without their name; preview each): gbrain repair accepted-takes; gbrain repair google-file-modes; gbrain repair stale-atoms; gbrain repair atoms-restore; gbrain repair extractor-facts; gbrain repair conversation-labels; gbrain repair captured-facts; gbrain repair redacted-facts; gbrain repair loop-facts');@@ -146,7 +148,7 @@ describe('surfaces that list instead of run', () => {expect((await planRepairSteps(engine)).some(step => EXPLICIT.includes(step.kind))).toBe(false);const plan = await withEnv({ GBRAIN_HOME: home }, () => computeRemediationPlan(engine, { repairs: {} }));expect(plan.repair_steps!.some(step => EXPLICIT.includes(step.kind))).toBe(false);- expect(plan.explicit_repairs!.map(n => [n.kind, n.code, n.preview_command])).toEqual(EXPLICIT.map(kind => [kind, 'explicit_kind_required', `gbrain repair ${kind}`]));+ expect(plan.explicit_repairs!.map(n => [n.kind, n.code, n.preview_command])).toEqual(EXPLICIT.map(kind => [kind, 'explicit_kind_required', PREVIEW(kind)]));const text = renderRemediationPlanLines(plan, 90).join('\n');expect(text).toContain('Explicit-only repairs');expect(text).toContain(' stale-atoms: gbrain repair stale-atoms');