Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

GBRA-161 PR 1b: doctor generation_pending, repair generations --mode cleanup listing, managed release-held

garrytanf3142d2180e8
diff --git a/src/commands/doctor/checks/generations.ts b/src/commands/doctor/checks/generations.ts
index 06f0351c22..ccfbdb51ef 100644
--- a/src/commands/doctor/checks/generations.ts
+++ b/src/commands/doctor/checks/generations.ts
@@ -9,6 +9,10 @@
* 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.
+ * - `generation_pending` (GBRA-161 PR 1b, managed sources): items an activated generation still waits on a member
+ * request for (`retire_pending` retirements and pending overwrites, still live), which the next extraction run of the
+ * source resumes, and orphan candidates: pages a `create` member wrote for an activation that never happened, listed
+ * with their activation id and never retired automatically. Either warns; nothing here writes.
*/
import type { BrainEngine } from '../../../core/engine.ts';
import type { Check } from '../../doctor.ts';
@@ -16,6 +20,7 @@ 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';
+import { listOrphanCandidates, listPendingMembers } from '../../../core/generations/managed.ts';
const DOCS = 'docs/guides/repair.md#generations';
@@ -72,3 +77,31 @@ export async function generationHeldCheck(engine: BrainEngine, sourceIds?: strin
message: `Held generations could not be inspected: ${error instanceof Error ? error.message : String(error)}. Health is unknown.` };
}
}
+
+export async function generationPendingCheck(engine: BrainEngine, sourceIds?: string[]): Promise<Check> {
+ try {
+ const sources = await activeSources(engine, sourceIds);
+ const pending = await listPendingMembers(engine, sources);
+ const orphans = await listOrphanCandidates(engine, sources);
+ const count = (rows: Array<{ source_id: string; kind: string }>) => [...rows.reduce((acc, row) => acc.set(`${row.source_id}/${row.kind}`, (acc.get(`${row.source_id}/${row.kind}`) ?? 0) + 1), new Map<string, number>())]
+ .map(([group, n]) => `${group}: ${n}`).join('; ');
+ const details = { pending: pending.length, retire_pending: pending.filter(row => row.action === 'retire').length, orphans: orphans.length,
+ pending_items: pending.slice(0, 20).map(row => ({ source_id: row.source_id, kind: row.kind, slug: row.slug, action: row.action, activation_id: row.activation_id })),
+ orphan_candidates: orphans.slice(0, 20).map(row => ({ source_id: row.source_id, kind: row.kind, slug: row.slug, activation_id: row.activation_id })), docs: DOCS };
+ if (!pending.length && !orphans.length) return { name: 'generation_pending', status: 'ok', details, message: 'No activated generation waits on a member request, and no orphan candidate exists.' };
+ const parts = [
+ ...(pending.length ? [`${pending.length} item(s) of activated generations wait on their member request (${count(pending)}; ${details.retire_pending} retire_pending, still live). `
+ + 'The next extraction run of each source resumes them; a page edited since keeps its content.'] : []),
+ ...(orphans.length ? [`${orphans.length} orphan candidate(s): pages written for an activation that never happened (${orphans.slice(0, 5).map(row => `${row.source_id}:${row.slug} activation ${row.activation_id}`).join('; ')}). `
+ + 'They are never retired automatically; whether to keep or delete each is the user\'s decision.'] : []),
+ ];
+ const first = orphans[0] ?? pending[0]!;
+ const preview = generationsPreviewArgv({ kind: first.kind, sourceId: first.source_id }, 'cleanup');
+ return { name: 'generation_pending', status: 'warn', details, message: `${parts.join(' ')} List them with ${preview.join(' ')} (read-only).`,
+ fix: agentFix(preview, 'Lists each pending member and orphan candidate with its activation id; it writes nothing. Pending members resume on the next extraction run; orphan candidates stay until the user decides.',
+ 'generation_pending', { docs: DOCS }) };
+ } catch (error) {
+ return { name: 'generation_pending', status: 'warn', details: { pending: 'unknown' },
+ message: `Pending generation members 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.ts
index 64a6d5a9d7..2e7a651636 100644
--- a/src/commands/doctor/checks/graph-health.ts
+++ b/src/commands/doctor/checks/graph-health.ts
@@ -355,6 +355,7 @@ export const timelineHistoryEntry: DoctorEntry = {
'atom_retirements_restorable',
'generation_retirements',
'generation_held',
+ 'generation_pending',
'extractor_facts_expired',
'conversation_label_facts',
'conversation_outcomes_stale',
diff --git a/src/commands/doctor/wave-checks.ts b/src/commands/doctor/wave-checks.ts
index 5eafcadead..b1731b5dec 100644
--- a/src/commands/doctor/wave-checks.ts
+++ b/src/commands/doctor/wave-checks.ts
@@ -336,6 +336,13 @@ export const WAVE_CHECKS: readonly WaveCheckSpec[] = [
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: 'generation_pending', resolution: 'repair', registration: 'wave',
+ hostOnly: 'Pending generation members and orphan candidates are host-side state of managed derived writers.',
+ count: d => Number(d.pending ?? 0) + Number(d.orphans ?? 0),
+ impact: 'Some activated generations still wait on member requests, or pages were written for an activation that never happened',
+ run: async (engine, scope) => (await import('./checks/generations.ts')).generationPendingCheck(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/doctor-categories.ts b/src/core/doctor-categories.ts
index 8bb72f326b..d5d4a3bac2 100644
--- a/src/core/doctor-categories.ts
+++ b/src/core/doctor-categories.ts
@@ -70,6 +70,7 @@ export const BRAIN_CHECK_NAMES: ReadonlySet<string> = new Set([
'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_pending',
'generation_retirements',
// #5575: stored trust tier counts, the legacy-row backfill, scan and source claims.
'trust_tiers',
diff --git a/src/core/generations/managed.ts b/src/core/generations/managed.ts
index 26bd552d18..b87be37552 100644
--- a/src/core/generations/managed.ts
+++ b/src/core/generations/managed.ts
@@ -15,7 +15,7 @@
* digest(activation id, member slug, action). The activation row (`derived_generation_activations`) is written with the batch, before any member runs:
* a crash after activation resumes the pending members on the next run (`listPendingMembers`); members created by an
* activation that never happened are orphan candidates (`listOrphanCandidates`), listed and never retired automatically.
- * Doctor counts both (`generation_retirements`); `gbrain repair generations --mode pending` lists and resumes them.
+ * Doctor counts both (`generation_pending`) and `gbrain repair generations --mode cleanup` lists them, read-only.
*/
import type { BrainEngine } from '../engine.ts';
import type { PreparedMutation } from '../persistence/coordinator.ts';
@@ -26,7 +26,7 @@ import { readFix } from '../ops/op-fix.ts';
import { digest } from '../persistence/digest.ts';
import { faultPoint } from '../persistence/fault-points.ts';
import { generationAdapter } from './adapters/index.ts';
-import { readGenerationsConfig } from './config.ts';
+import { readGenerationsConfig, restoreDaysHint } from './config.ts';
import type { GenerationAdapter, GenerationKey, InputState, ProposedItem } from './contract.ts';
import { proofHolds, type EmptySourceProof } from './proofs.ts';
import { activateGeneration, bumpValve, exhaustedHold, generationKeyLock, generationFenced, liveConflict, planPublication, publishOperationId,
@@ -122,7 +122,7 @@ export async function recordActivation(tx: BrainEngine, intent: ActivationPlanIn
}
const memberFix = (sourceId: string, kind: string) => readFix('Lists pending generation members and orphan candidates, read-only.',
- { argv: ['gbrain', 'repair', 'generations', '--kind', kind, '--mode', 'pending', '--source', sourceId, '--json'] });
+ { argv: ['gbrain', 'repair', 'generations', '--kind', kind, '--mode', 'cleanup', '--source', sourceId, '--since', `${restoreDaysHint()}d`, '--json'] });
/** Preparer of `managed_generation_activate` (trusted local only): the ledger flip and the retire_pending marks; it writes no page or file. */
export async function prepareGenerationActivation(engine: BrainEngine, row: WriteRequest): Promise<PreparedMutation> {
diff --git a/src/core/generations/repair.ts b/src/core/generations/repair.ts
index 8991a5ae93..a89ed5e22c 100644
--- a/src/core/generations/repair.ts
+++ b/src/core/generations/repair.ts
@@ -10,7 +10,10 @@
* - release-held: publishes a held result once (shrunk, valve, attempts_exhausted; oversize after the operator raised
* `generations.max_items`). no_proof, fence_absent, tie and segmented_unsupported are refused: releasing them would
* manufacture the proof they lack.
- * - cleanup: the synthesis unmatched-predecessor retire (PR 4); no kind in this release has it.
+ * - cleanup: lists what a managed source's activations left behind (GBRA-161 PR 1b): items an activated generation still
+ * waits on a member request for (resumed by the next extraction run) and orphan candidates (pages a `create` member
+ * wrote for an activation that never happened), each with its activation id. It is preview-only: an orphan is never
+ * retired automatically. The synthesis unmatched-predecessor retire joins this mode in PR 4.
*
* Explicit-only, preview-bound, destructive consent: the preview saves the set under its hash and `--apply --expect <hash>
* --yes` applies exactly that set, rechecking each key under its locks (`changed_since_preview` otherwise).
@@ -19,12 +22,14 @@ import type { BrainEngine } from '../engine.ts';
import { opError, OperationError, type OperationContext } from '../ops/contract.ts';
import { readFix } from '../ops/op-fix.ts';
import { maintenanceTransaction } from '../persistence/attribution.ts';
+import { managedPersistenceEnabled } from '../persistence/ownership.ts';
import { stableJson } from '../persistence/digest.ts';
import { clearApprovedSet, loadApprovedSet, previewChangedError, previewHash, saveApprovedSet } from '../persistence/preview-approval.ts';
import { afterCursor, type RepairHandler, type RepairItem, type RepairItemOutcome, type RepairPlan, type RepairScope } from '../repair/core.ts';
import { generationAdapter, generationKinds } from './adapters/index.ts';
import { readGenerationsConfig, restoreDaysHint } from './config.ts';
import { RELEASABLE_HELD_REASONS, type GenerationAdapter, type GenerationKey, type HeldReason, type ProposedItem } from './contract.ts';
+import { listOrphanCandidates, listPendingMembers } from './managed.ts';
import { activateGeneration, assertItemsLive, itemSetHash, lockGeneration, publishGeneration, readLiveGeneration, type LedgerItem } from './publish.ts';
export const GENERATION_MODES = ['restore', 'release-held', 'cleanup'] as const;
@@ -41,7 +46,7 @@ export function generationsSelectionArgv(selection: GenerationsSelection): strin
}
/** The read-only preview a notice prints for a kind (and optionally one key): the restore window, or the held set. */
-export function generationsPreviewArgv(target: { kind: string; ownerKey?: string; sourceId?: string }, mode: 'restore' | 'release-held' = 'restore'): string[] {
+export function generationsPreviewArgv(target: { kind: string; ownerKey?: string; sourceId?: string }, mode: GenerationMode = 'restore'): string[] {
return ['gbrain', 'repair', 'generations', '--kind', target.kind, '--mode', mode, ...(target.sourceId ? ['--source', target.sourceId] : []),
...(target.ownerKey ? ['--key', target.ownerKey] : mode === 'release-held' ? ['--held'] : ['--since', `${restoreDaysHint()}d`]), '--json'];
}
@@ -58,9 +63,8 @@ export function generationsSelectionRefusal(selection: Partial<GenerationsSelect
if (!generationAdapter(selection.kind)) return usage(`--kind ${selection.kind} is not a generation kind this brain publishes (${kinds}).`, `Pass --kind ${generationKinds()[0] ?? 'atom'}.`, selection);
if (!selection.mode || !GENERATION_MODES.includes(selection.mode)) {
return usage(`--mode must be restore, release-held or cleanup (got "${selection.mode ?? ''}").`,
- 'restore republishes the generation a key replaced; release-held publishes a held result once.', selection);
+ 'restore republishes the generation a key replaced; release-held publishes a held result once; cleanup lists pending members and orphan candidates.', selection);
}
- if (selection.mode === 'cleanup') return usage(`--mode cleanup retires unmatched synthesis predecessors; --kind ${selection.kind} has none.`, 'Use --mode restore or --mode release-held for this kind.', selection);
if (!selection.run && !selection.since && !selection.key && selection.generation === undefined && !selection.held) {
return usage('gbrain repair generations needs a selector: --run, --since, --key, --generation or --held.', `Bound the set, e.g. ${example(selection.mode === 'release-held' ? 'release-held' : 'restore')}.`, selection);
}
@@ -76,7 +80,10 @@ interface ReleaseEntry {
mode: 'release-held'; id: number; source_id: string; owner_key: string; reason: HeldReason; hold_id: string; input_pin: string | null;
attempts: number; proposal_bytes: number | null; items: number; refused: string[];
}
-type Entry = RestoreEntry | ReleaseEntry;
+interface CleanupEntry {
+ mode: 'cleanup'; id: number; source_id: string; owner_key: string; slug: string; activation_id: string; state: 'pending_overwrite' | 'retire_pending' | 'orphan_candidate'; refused: string[];
+}
+type Entry = RestoreEntry | ReleaseEntry | CleanupEntry;
interface EntryItem extends RepairItem { entry: Entry; hash: string; last: boolean; selection: GenerationsSelection }
function selectorSql(selection: GenerationsSelection, params: unknown[], alias: string): string {
@@ -123,6 +130,19 @@ async function planRestore(db: BrainEngine, adapter: GenerationAdapter<unknown>,
async function selectEntries(db: BrainEngine, adapter: GenerationAdapter<unknown>, sources: string[], selection: GenerationsSelection, id?: number): Promise<Entry[]> {
const params: unknown[] = [sources, adapter.kind];
+ if (selection.mode === 'cleanup') {
+ const since = selection.since ? Date.parse(selection.since) : null;
+ const keyed = (row: { owner_key: string }) => !selection.key || row.owner_key === selection.key;
+ const pending = (await listPendingMembers(db, sources, adapter.kind)).filter(keyed)
+ .filter(row => selection.generation === undefined || row.generation_id === selection.generation);
+ const orphans = selection.generation !== undefined ? [] : (await listOrphanCandidates(db, sources, adapter.kind)).filter(keyed)
+ .filter(row => since === null || Date.parse(row.created_at) >= since);
+ return [
+ ...pending.map(row => ({ source_id: row.source_id, owner_key: row.owner_key, slug: row.slug, activation_id: row.activation_id,
+ state: row.action === 'retire' ? 'retire_pending' as const : 'pending_overwrite' as const })),
+ ...orphans.map(row => ({ source_id: row.source_id, owner_key: row.owner_key, slug: row.slug, activation_id: row.activation_id, state: 'orphan_candidate' as const })),
+ ].map((row, index) => ({ mode: 'cleanup' as const, id: index + 1, ...row, refused: [] }));
+ }
if (selection.mode === 'restore') {
const where = id === undefined ? selectorSql(selection, params, 'g') : (params.push(id), ` AND g.id = $${params.length}`);
const rows = await db.executeRaw<{ id: number; source_id: string; owner_key: string; generation: number; prev_id: number; prev_generation: number }>(
@@ -155,6 +175,7 @@ async function selectEntries(db: BrainEngine, adapter: GenerationAdapter<unknown
function describeEntry(entry: Entry): string {
const refused = entry.refused.length ? `; refused: ${entry.refused.join(', ')}` : '';
+ if (entry.mode === 'cleanup') return `${entry.state.replace('_', ' ')} ${entry.slug} (activation ${entry.activation_id})${entry.state === 'orphan_candidate' ? ', never retired automatically' : ', resumed by the next extraction run'}`;
if (entry.mode === 'release-held') return `held ${entry.reason}, ${entry.items} item(s), ${entry.attempts} attempt(s)${refused}`;
return `generation ${entry.generation} back to ${entry.restore_to}: revive ${entry.revive.length}, retire ${entry.retire.length}${refused}`;
}
@@ -184,15 +205,22 @@ export const generationsRepair: RepairHandler = {
async plan(engine, scope, after, opts): Promise<RepairPlan> {
const { adapter, selection } = requireAdapter(opts?.generations);
const command = previewCommand(scope, selection);
- const item = (entry: Entry, hash: string, last: boolean): EntryItem => ({ cursor: { phase: entry.mode === 'restore' ? 1 : 2, id: entry.id }, source_id: entry.source_id,
- slug: entry.owner_key, chars: 0, action: entry.mode === 'restore' ? 'restore' : 'release', entry, hash, last, selection });
+ const item = (entry: Entry, hash: string, last: boolean): EntryItem => ({ cursor: { phase: entry.mode === 'restore' ? 1 : entry.mode === 'release-held' ? 2 : 3, id: entry.id },
+ source_id: entry.source_id, slug: entry.mode === 'cleanup' ? entry.slug : entry.owner_key, chars: 0, action: entry.mode === 'restore' ? 'restore' : entry.mode === 'release-held' ? 'release' : 'list',
+ entry, hash, last, selection });
if (!opts?.apply) {
const entries = await selectEntries(engine, adapter, scope.source_ids, selection);
const hash = previewHash(await hashParts(engine, scope, selection, entries));
if (entries.length) await saveApprovedSet<Approved>(engine, { command: 'generations', hash }, entries.map(entry => ({ ...entry, selection, sources: scope.source_ids })));
return { items: entries.map((entry, index) => item(entry, hash, index === entries.length - 1)), preview_hash: hash,
residuals: { keys: entries.length, refused: entries.filter(entry => entry.refused.length).length },
- listing: entries.map(entry => ({ item: `${entry.source_id}:${entry.owner_key}`, class: entry.refused.length ? 'refused' : entry.mode, detail: describeEntry(entry) })) };
+ listing: entries.map(entry => ({ item: `${entry.source_id}:${entry.mode === 'cleanup' ? entry.slug : entry.owner_key}`,
+ class: entry.mode === 'cleanup' ? entry.state : entry.refused.length ? 'refused' : entry.mode, detail: describeEntry(entry) })) };
+ }
+ if (selection.mode === 'cleanup') {
+ throw new OperationError('invalid_params', `gbrain repair generations --mode cleanup only lists pending members and orphan candidates for --kind ${selection.kind}; there is nothing to apply.`,
+ `Pending members resume on the next extraction run of their source. An orphan candidate is never retired automatically: show the user ${command} and delete one only if they decide to.`,
+ 'docs/guides/repair.md#generations');
}
if (!opts.expect) {
throw new OperationError('invalid_params', 'gbrain repair generations --apply applies only the set a preview printed.',
@@ -223,16 +251,21 @@ export const generationsRepair: RepairHandler = {
async function applyEntry(ctx: OperationContext, adapter: GenerationAdapter<unknown>, approved: Entry, selection: GenerationsSelection): Promise<RepairItemOutcome> {
const changed = (reason: string): RepairItemOutcome => ({ applied: false, outcome: 'changed_since_preview', reason });
+ if (approved.mode === 'cleanup') return { applied: false, outcome: 'refused', reason: `${approved.slug}: cleanup entries are listed, never applied` };
if (approved.refused.length) return { applied: false, outcome: 'refused', reason: approved.refused.join(', ') };
const key = keyOf(adapter.kind, approved.source_id, approved.owner_key);
if (approved.mode === 'release-held') {
const [row] = await ctx.engine.executeRaw<{ proposal: ProposedItem[] | null; hold_id: string }>(
`SELECT proposal, hold_id FROM derived_generations WHERE id=$1 AND state='held'`, [approved.id]);
if (!row || row.hold_id !== approved.hold_id || !row.proposal) return changed('the held result changed or was released since the preview');
+ if (await managedPersistenceEnabled(ctx.engine)) return releaseManaged(ctx.engine, adapter, key, approved, row.proposal);
const outcome = await publishGeneration(ctx.engine, adapter, { key, items: row.proposal, runId: `release:${approved.hold_id}`, release: { holdId: approved.hold_id, reason: approved.reason } });
if (outcome.state === 'held') return { applied: false, outcome: 'refused', reason: `${approved.owner_key}: still held (${outcome.reason})` };
return { applied: true, outcome: 'released', detail: { generation: outcome.generation, ...(outcome.state === 'published' ? { retired: outcome.retired.length } : {}) } };
}
+ if (await managedPersistenceEnabled(ctx.engine)) {
+ return { applied: false, outcome: 'refused', reason: `${approved.owner_key}: a managed source restores retired atoms with gbrain repair atoms-restore; a generation restore here runs on unmanaged brains only` };
+ }
const restored = await maintenanceTransaction(ctx.engine, async tx => {
const live = await readLiveGeneration(tx, key);
const plan0 = live?.id === approved.id ? await planRestore(tx, adapter, key, approved.id, approved.restore_to_id) : null;
@@ -258,3 +291,26 @@ async function applyEntry(ctx: OperationContext, adapter: GenerationAdapter<unkn
if (Array.isArray(restored)) return { applied: false, outcome: 'refused', reason: restored.join(', ') };
return { applied: true, outcome: 'restored', detail: { generation: restored.generation, restore_of: approved.restore_to, revived: approved.revive.length, retired: approved.retire.length } };
}
+
+/**
+ * GBRA-161 PR 1b: a managed source publishes a released held result through its writer (generations/managed.ts): the
+ * retained proposal is admitted as one activation batch against the origin's current input. Atom page keys only; a
+ * transcript key's held result clears when its next extraction lands on a different result.
+ */
+async function releaseManaged(engine: BrainEngine, adapter: GenerationAdapter<unknown>, key: GenerationKey, approved: ReleaseEntry, proposal: ProposedItem[]): Promise<RepairItemOutcome> {
+ const refused = (reason: string): RepairItemOutcome => ({ applied: false, outcome: 'refused', reason: `${approved.owner_key}: ${reason}` });
+ if (adapter.kind !== 'atom' || !key.ownerKey.startsWith('source_slug:')) return refused('a managed release publishes atom page keys only');
+ const atoms = await import('../persistence/atom-maintenance.ts');
+ const session = await atoms.managedAtomSession(engine, key.sourceId);
+ if (!session) return refused('the source is no longer managed; preview again');
+ const slug = key.ownerKey.slice('source_slug:'.length);
+ const page = await engine.getPage(slug, { sourceId: key.sourceId });
+ if (!page?.content_hash) return refused(`origin page ${slug} is gone; the held result cannot publish`);
+ const origin = await atoms.readAtomOrigin(engine, session, { kind: 'page', slug, content: page.compiled_truth, contentHash: page.content_hash });
+ const outcome = await atoms.publishManagedAtomGeneration(engine, session, origin, proposal.map(item => ({ slug: item.key, content: item.content, links: [] })),
+ { key, content: page.compiled_truth, runId: `release:${approved.hold_id}`, release: { holdId: approved.hold_id, reason: approved.reason } });
+ if (outcome.state === 'held') return refused(`still held (${outcome.reason})`);
+ const failed = outcome.receipts.filter(receipt => receipt.state !== 'committed');
+ if (failed.length) return refused(`${failed.length} request(s) of the release did not commit (${failed.map(receipt => receipt.request_id).join(', ')})`);
+ return { applied: true, outcome: 'released', detail: { requests: outcome.receipts.length } };
+}
diff --git a/src/core/persistence/atom-maintenance.ts b/src/core/persistence/atom-maintenance.ts
index be80b9ee59..07e0c5b9a8 100644
--- a/src/core/persistence/atom-maintenance.ts
+++ b/src/core/persistence/atom-maintenance.ts
@@ -23,7 +23,7 @@ import { MAX_DETERMINISTIC_FAILURES, writeAtomPageState } from '../cycle/extract
import { effectiveVisibility } from '../search/private-visibility.ts';
import { declareDerivation, deriveTrust, lowerToDerivedTier, recordTaintEdges } from '../trust/taint.ts';
import type { DerivedRetiredBy } from './derived-retirement-hold.ts';
-import type { GenerationKey } from '../generations/contract.ts';
+import type { GenerationKey, HeldReason } from '../generations/contract.ts';
import { atomGenerationAdapter, atomPagePin, type AtomGenerationContext } from '../generations/adapters/atoms.ts';
import { markdownItem } from '../generations/adapters/page.ts';
import { assertMemberPending, GENERATION_ACTIVATE_SLUG, listPendingMembers, memberRequestId, planManagedGeneration,
@@ -312,6 +312,8 @@ export interface ManagedAtomGeneration {
locator?: string | null;
/** A previewed operator retirement (gbrain repair stale-atoms): retires exactly these atoms; no extraction is completed. */
approved?: { retire: string[]; retiredBy: DerivedRetiredBy; expect?: Record<string, string> };
+ /** An operator release of the held row this result matches (gbrain repair generations --mode release-held). */
+ release?: { holdId: string; reason: HeldReason };
}
export type ManagedAtomPublication =
@@ -331,7 +333,7 @@ export async function publishManagedAtomGeneration(engine: BrainEngine, session:
const claim = atomClaim(session, origin);
const plan = await planManagedGeneration(engine, atomGenerationAdapter, { key: generation.key, items: atoms.map(atom => markdownItem(atom.slug, atom.content)),
input: generation.approved ? undefined : originInput(origin, generation.content), partial: Boolean(origin.partialInputChars), context, runId: generation.runId,
- approved: generation.approved }, { retiredBy: ATOM_RETIRED_BY_REEXTRACT, scope: generation.approved ? null : claim.runKey, locator: generation.locator ?? (origin.kind === 'transcript' ? origin.locator : null) });
+ approved: generation.approved, release: generation.release }, { retiredBy: ATOM_RETIRED_BY_REEXTRACT, scope: generation.approved ? null : claim.runKey, locator: generation.locator ?? (origin.kind === 'transcript' ? origin.locator : null) });
if (plan.kind === 'held') return { state: 'held', reason: plan.outcome.reason, holdId: plan.outcome.holdId, receipts: [] };
if (plan.kind === 'unchanged') return { state: 'unchanged', receipts: generation.approved ? [] : await publishManagedAtoms(engine, session, origin, []) };
const runKey = generation.approved ? digest(['managed-atoms-approved', plan.intent.activationId]) : claim.runKey;
diff --git a/src/core/repair/registry.ts b/src/core/repair/registry.ts
index 3f9aa10594..5ddb4aa784 100644
--- a/src/core/repair/registry.ts
+++ b/src/core/repair/registry.ts
@@ -504,7 +504,7 @@ const SPECS: Record<RepairKind, Omit<RepairKindSpec, 'kind'>> = {
+ 'Runs only when named; never on upgrade.',
},
'generations': {
- handler: generationsRepair, embeds: 'effect', checks: ['generation_retirements', 'generation_held'], explicit_only: true, preview_bound: true, consent: 'destructive',
+ handler: generationsRepair, embeds: 'effect', checks: ['generation_retirements', 'generation_held', 'generation_pending'], explicit_only: true, preview_bound: true, consent: 'destructive',
consentText: {
what: 'Apply the previewed generations repair: restore each listed key to the generation it replaced, or publish each listed held result once',
why: 'The preview listed each key with what it revives, retires or publishes; the apply changes exactly that set and refuses a key that changed since.',
@@ -513,7 +513,9 @@ const SPECS: Record<RepairKind, Omit<RepairKindSpec, 'kind'>> = {
},
summary: 'Undo or release a derived generation (GBRA-161): --kind <kind> names the ledger kind, --mode restore (default) republishes the item set the '
+ 'selected live generation replaced from its ledger preimages and retires what it added, --mode release-held publishes a held result once '
- + '(shrunk, valve, attempts_exhausted; oversize after raising generations.max_items; no_proof, fence_absent, tie and segmented_unsupported are refused). '
+ + '(shrunk, valve, attempts_exhausted; oversize after raising generations.max_items; no_proof, fence_absent, tie and segmented_unsupported are refused; '
+ + 'a managed source releases atom page keys through its writer and restores retired atoms with atoms-restore), --mode cleanup lists, read-only, the members '
+ + 'an activated managed generation still waits on and the orphan candidates an activation that never happened left, each with its activation id. '
+ 'One selector bounds the set: --run <id>, --since <ISO-8601|7d>, --key <owner>, --generation <id>, or --held (release-held). The preview lists each key '
+ 'and saves the set under its hash; --apply --expect <hash> --yes applies exactly that set, refusing a key edited since or with no stored preimage. '
+ 'Runs only when named; never on upgrade.',