Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

GBRA-161 PR 1b: stale-atoms retires through the generation primitive (approved, identity-bound); trust channel for managed_generation_

garrytane6931407920e
diff --git a/src/core/generations/plan.ts b/src/core/generations/plan.ts
index b5d2a08b25..7307512b83 100644
--- a/src/core/generations/plan.ts
+++ b/src/core/generations/plan.ts
@@ -34,6 +34,8 @@ export interface PlanInput {
release?: HeldReason;
/** An operator-approved retirement (a previewed repair): retire exactly these live owned keys, keep the rest; no floor or valve. */
approvedRetire?: readonly string[];
+ /** The identity each approved key had when the operator previewed it; a key edited since is not retired. */
+ approvedExpect?: Readonly<Record<string, string>>;
}
export type Plan =
@@ -43,7 +45,7 @@ export type Plan =
export function planGeneration(input: PlanInput): Plan {
const { live, rows, proposal, config } = input;
- if (input.approvedRetire) return planApprovedRetirement(input, input.approvedRetire);
+ if (input.approvedRetire) return planApprovedRetirement(input, input.approvedRetire, input.approvedExpect);
const proposed = new Map(proposal.map(item => [item.key, item]));
const recorded = new Set([...(live?.items.keys() ?? [])].filter(key => rows.get(key)?.live));
const unrecorded = [...rows.values()].filter(row => row.owned && row.live && !recorded.has(row.key));
@@ -85,9 +87,10 @@ export function planGeneration(input: PlanInput): Plan {
}
/** A previewed operator retirement: the approved keys still live and owned retire, every other live item is kept. */
-function planApprovedRetirement(input: PlanInput, approved: readonly string[]): Plan {
+function planApprovedRetirement(input: PlanInput, approved: readonly string[], expect?: Readonly<Record<string, string>>): Plan {
const recorded = [...(input.live?.items.keys() ?? [])].filter(key => input.rows.get(key)?.live);
- const retires = [...new Set(approved)].filter(key => input.rows.get(key)?.live && (input.rows.get(key)?.owned || recorded.includes(key))).sort();
+ const retires = [...new Set(approved)].filter(key => { const row = input.rows.get(key);
+ return row?.live && (row.owned || recorded.includes(key)) && (!expect || expect[key] === row.identityHash); }).sort();
const protectedKeys = [...input.rows.values()].filter(row => row.owned && row.live && !recorded.includes(row.key) && !retires.includes(row.key)).map(row => row.key).sort();
if (retires.some(key => input.rows.get(key)?.segmented)) return { kind: 'held', reason: 'segmented_unsupported', context: { retires: retires.length } };
if (!retires.length) return { kind: 'unchanged', protectedKeys };
diff --git a/src/core/generations/publish.ts b/src/core/generations/publish.ts
index 03a29c4a88..f569163724 100644
--- a/src/core/generations/publish.ts
+++ b/src/core/generations/publish.ts
@@ -39,7 +39,9 @@ export interface PublishRequest<C = unknown> {
/** An operator release of this held row (repair generations --mode release-held). */
release?: { holdId: string; reason: HeldReason };
/** A previewed operator retirement (`gbrain repair stale-atoms`): retire exactly these keys, stamped `retiredBy`; `items` is ignored. */
- approved?: { retire: readonly string[]; retiredBy: DerivedRetiredBy };
+ approved?: { retire: readonly string[]; retiredBy: DerivedRetiredBy; expect?: Readonly<Record<string, string>> };
+ /** Unmanaged only: runs in the activation transaction after the retirements (stale-atoms invalidates the origin's completions there). */
+ onRetired?: (tx: BrainEngine, retired: readonly string[]) => Promise<void>;
/** A transcript key's current file, recorded on the generation so a moved file keeps its key. */
locator?: string;
}
@@ -188,7 +190,7 @@ function logFailure(key: GenerationKey, operationId: string, mode: string, error
/** The set hash an operation binds: the proposal, or for an approved retirement the keys it retires. */
export function requestSetHash(request: Pick<PublishRequest<unknown>, 'items' | 'approved'>): string {
- return request.approved ? digest(['generation-approved-retire-v1', [...request.approved.retire].sort(), request.approved.retiredBy]) : itemSetHash(request.items);
+ return request.approved ? digest(['generation-approved-retire-v1', [...request.approved.retire].sort(), request.approved.retiredBy, request.approved.expect ?? null]) : itemSetHash(request.items);
}
/** The operation identity an identical replay matches (D2): kind, key, expected generation, input pin and result item-set hash. */
@@ -219,7 +221,7 @@ export async function planPublication<C>(db: BrainEngine, adapter: GenerationAda
const evidence = unrecorded.length ? await adapter.legacyEvidence(db, key, unrecorded) : new Set<string>();
const valve = await readValve(db, key, request.runId);
const plan = planGeneration({ live, rows, proposal: request.items, input, config, modelProduced: adapter.modelProduced, strictOrder: adapter.strictOrder, additive: request.partial === true,
- proofHolds: request.proof ? proofHolds(request.proof, input, live?.inputPin) : false, evidence, valve, release: request.release?.reason, approvedRetire: request.approved?.retire });
+ proofHolds: request.proof ? proofHolds(request.proof, input, live?.inputPin) : false, evidence, valve, release: request.release?.reason, approvedRetire: request.approved?.retire, approvedExpect: request.approved?.expect });
return { input, rows, plan };
}
@@ -269,6 +271,7 @@ export async function publishGeneration<C>(engine: BrainEngine, adapter: Generat
if (!request.partial) await adapter.completeItems?.(tx, key, current.map(([itemKey]) => itemKey), request.context);
await assertItemsLive(tx, adapter as GenerationAdapter<unknown>, key, new Map(current));
await adapter.retireItems(tx, key, plan.retires, request.approved?.retiredBy ?? adapter.retiredBy);
+ if (plan.retires.length) await request.onRetired?.(tx, plan.retires);
await faultPoint('generation:retired', { sourceId: key.sourceId, operation: key.kind });
const activated = await activateGeneration(tx, key, live, { operationId, runId: request.runId, input, setHash, locator: request.locator,
completeness: { complete: !request.partial, proof: request.proof?.kind ?? null, released: request.release?.reason ?? null,
diff --git a/src/core/persistence/atom-maintenance.ts b/src/core/persistence/atom-maintenance.ts
index 61ff1d7462..be80b9ee59 100644
--- a/src/core/persistence/atom-maintenance.ts
+++ b/src/core/persistence/atom-maintenance.ts
@@ -311,7 +311,7 @@ export interface ManagedAtomGeneration {
/** A transcript key's current file. */
locator?: string | null;
/** A previewed operator retirement (gbrain repair stale-atoms): retires exactly these atoms; no extraction is completed. */
- approved?: { retire: string[]; retiredBy: DerivedRetiredBy };
+ approved?: { retire: string[]; retiredBy: DerivedRetiredBy; expect?: Record<string, string> };
}
export type ManagedAtomPublication =
@@ -683,7 +683,7 @@ export async function prepareManagedAtomMutation(engine: BrainEngine, row: Write
WHERE id=$3 AND source_id=$4 AND deleted_at IS NOT NULL`, [p.retiredBy ?? ATOM_RETIRED_BY_REEXTRACT, new Date().toISOString(), row.page_id, row.source_id]);
if (p.activationId) await settleMember(tx, p.activationId, row.slug);
if (p.origin.kind === 'page' && p.origin.pageId !== null) {
- await bumpAtomGeneration(tx, row.source_id, row.source_incarnation, p.origin.pageId, p.origin.contentHash);
+ await bumpAtomGeneration(tx, row.source_id, row.source_incarnation, p.origin.pageId, p.origin.contentHash || null);
}
}
return { ...result, atom_run_key: p.runKey, atom_kind: p.kind };
diff --git a/src/core/repair/stale-atoms.ts b/src/core/repair/stale-atoms.ts
index d6e1b5ec6f..3938d94171 100644
--- a/src/core/repair/stale-atoms.ts
+++ b/src/core/repair/stale-atoms.ts
@@ -18,12 +18,16 @@
* with its class and saves the set under its hash; `--apply --expect <hash>`
* retires exactly that set. Each atom is rechecked when it is retired; one
* whose revision, class, origin or completion evidence changed reports
- * `changed_since_preview` and is kept. A managed brain retires one atom per
- * `managed_maintenance_retire_stale_atoms` request bound to the atom's
- * revision (no live origin is required); an unmanaged brain soft-deletes it
- * directly. Both stamp `retired_by: stale-atoms`, so a later extraction that
- * produces the atom again restores it, and both invalidate the origin page's
- * earlier completed extractions so a restored page is extracted again.
+ * `changed_since_preview` and is kept. GBRA-161 PR 1b: each atom retires as an
+ * approved generation of its origin key (generations/publish.ts, no floor or
+ * valve), bound to the atom's identity: unmanaged in one activation
+ * transaction, managed as a `managed_generation_activate` request and then a
+ * gated `managed_atom_delete` member (version first; no live origin is
+ * required). Both stamp `retired_by: stale-atoms`, record the retirement in
+ * the ledger (restorable through `gbrain repair generations`), and invalidate
+ * the origin page's earlier completed extractions so a restored page is
+ * extracted again. `managed_maintenance_retire_stale_atoms` requests journaled
+ * by an earlier version still publish through their preparer below.
*/
import type { BrainEngine } from '../engine.ts';
import type { GBrainConfig } from '../config.ts';
@@ -32,13 +36,12 @@ import type { WriteRequest } from '../persistence/model.ts';
import { opError, OperationError, type OperationContext } from '../ops/contract.ts';
import { readFix } from '../ops/op-fix.ts';
import { authorizeWrite } from '../persistence/authority.ts';
-import { managedPersistenceEnabled } from '../persistence/ownership.ts';
-import { maintenanceTransaction } from '../persistence/attribution.ts';
import { preparePageMutation } from '../persistence/page-prepare.ts';
-import { maintenancePreflight, submitMaintenanceIntent } from '../persistence/prepared-maintenance.ts';
-import { bumpAtomGeneration, managedAtomCompletedSql } from '../persistence/atom-maintenance.ts';
+import { bumpAtomGeneration, managedAtomCompletedSql, managedAtomSession, publishManagedAtomGeneration, type AtomOrigin } from '../persistence/atom-maintenance.ts';
+import { atomGenerationAdapter, atomOwnerKey, readAtomInput } from '../generations/adapters/atoms.ts';
+import { publishGeneration } from '../generations/publish.ts';
import { clearApprovedSet, loadApprovedSet, previewChangedError, previewHash, saveApprovedSet } from '../persistence/preview-approval.ts';
-import { afterCursor, repairRequestId, type RepairHandler, type RepairItem, type RepairItemOutcome, type RepairPlan, type RepairScope } from './core.ts';
+import { afterCursor, type RepairHandler, type RepairItem, type RepairItemOutcome, type RepairPlan, type RepairScope } from './core.ts';
export const STALE_ATOMS_RETIRED_BY = 'stale-atoms';
export const STALE_ATOMS_INTENT = 'managed_maintenance_retire_stale_atoms';
@@ -172,31 +175,37 @@ async function retireStaleAtom(ctx: OperationContext, atom: StaleAtom): Promise<
const engine = ctx.engine;
const changed = (reason: string): RepairItemOutcome => ({ applied: false, outcome: 'changed_since_preview', reason });
if (!sameAtom((await staleAtoms(engine, [atom.source_id], atom.id))[0], atom)) return changed('the atom or its source page changed');
- if (await managedPersistenceEnabled(engine)) {
- const authority = (await maintenancePreflight(engine, atom.source_id))!;
- try {
- await submitMaintenanceIntent(engine, authority, atom.slug, { kind: STALE_ATOMS_INTENT, expected_revision: atom.revision, atom },
- await repairRequestId(ctx, 'stale-atoms', atom, atom.revision));
- } catch (error) {
- if (error instanceof OperationError && ['revision_conflict', 'page_not_found', 'page_identity_changed'].includes(error.code)) return changed(error.message);
- if (error instanceof OperationError && error.code === 'source_changed') return { applied: false, outcome: 'file_conflict', reason: error.message };
- throw error;
+ // GBRA-161 PR 1b: the retirement is an approved generation of the atom's origin key (no floor or valve), bound to the
+ // atom's identity now; the primitive rechecks it live, owned and unedited under the origin and atom locks.
+ const key = { kind: atomGenerationAdapter.kind, sourceId: atom.source_id, ownerKey: atomOwnerKey({ kind: 'page', slug: atom.origin_slug }) };
+ const row = (await atomGenerationAdapter.readItems(engine, key, [atom.slug])).get(atom.slug);
+ if (!row?.live) return changed('the atom was removed');
+ const approved = { retire: [atom.slug], retiredBy: STALE_ATOMS_RETIRED_BY, expect: { [atom.slug]: row.identityHash } } as const;
+ try {
+ const session = await managedAtomSession(engine, atom.source_id);
+ if (session) {
+ const origin: AtomOrigin = { kind: 'page', locator: atom.origin_slug, contentHash: atom.class === 'origin_changed' ? atom.origin_hash! : '', textHash: '',
+ pageId: atom.origin_page_id, revision: null, visibility: 'world' };
+ const outcome = await publishManagedAtomGeneration(engine, session, origin, [], { key, content: null, approved: { ...approved, retire: [...approved.retire] } });
+ if (outcome.state !== 'admitted') return changed('the atom is no longer an owned, unedited atom of its origin');
+ const receipt = outcome.receipts.at(-1);
+ return receipt?.state === 'committed' ? { applied: true, outcome: 'retired' } : changed(`the retirement request ended ${receipt?.state ?? 'unrecorded'}`);
}
- return { applied: true, outcome: 'retired' };
+ const outcome = await publishGeneration(engine, atomGenerationAdapter, { key, items: [], input: await readAtomInput(engine, key), approved,
+ onRetired: tx => stampRetirement(tx, atom, false) });
+ return outcome.state === 'published' && outcome.retired.includes(atom.slug) ? { applied: true, outcome: 'retired' }
+ : changed('the atom is no longer an owned, unedited atom of its origin');
+ } catch (error) {
+ if (error instanceof OperationError && ['revision_conflict', 'page_not_found', 'page_identity_changed', 'generation_fenced', 'generation_live_conflict'].includes(error.code)) {
+ return changed(error.message);
+ }
+ if (error instanceof OperationError && error.code === 'source_changed') return { applied: false, outcome: 'file_conflict', reason: error.message };
+ throw error;
}
- const retired = await maintenanceTransaction(engine, async tx => {
- await tx.lockPageKeys([{ sourceId: atom.source_id, slug: atom.slug }, { sourceId: atom.source_id, slug: atom.origin_slug }]);
- if (!sameAtom((await staleAtoms(tx, [atom.source_id], atom.id))[0], atom)) return false;
- await tx.createVersion(atom.slug, { sourceId: atom.source_id });
- await tx.softDeletePage(atom.slug, { sourceId: atom.source_id });
- await stampRetirement(tx, atom);
- return true;
- });
- return retired ? { applied: true, outcome: 'retired' } : changed('the atom or its source page changed');
}
-async function stampRetirement(tx: BrainEngine, atom: StaleAtom): Promise<void> {
- await tx.executeRaw(`UPDATE pages SET frontmatter=frontmatter||jsonb_build_object('retired_by',$1::text,'retired_at',$2::text)
+async function stampRetirement(tx: BrainEngine, atom: StaleAtom, stamp = true): Promise<void> {
+ if (stamp) await tx.executeRaw(`UPDATE pages SET frontmatter=frontmatter||jsonb_build_object('retired_by',$1::text,'retired_at',$2::text)
WHERE id=$3 AND source_id=$4 AND deleted_at IS NOT NULL`, [STALE_ATOMS_RETIRED_BY, new Date().toISOString(), atom.id, atom.source_id]);
if (atom.origin_page_id === null) return;
const [{ incarnation }] = await tx.executeRaw<{ incarnation: string }>('SELECT incarnation::text AS incarnation FROM sources WHERE id=$1', [atom.source_id]);
diff --git a/src/core/trust/channel.ts b/src/core/trust/channel.ts
index 89484c27ea..5bce20913f 100644
--- a/src/core/trust/channel.ts
+++ b/src/core/trust/channel.ts
@@ -95,7 +95,7 @@ export function requestChannelTrust(row: Pick<WriteRequest, 'id' | 'operation' |
return effectiveWriteTrust({ channel: 'agent_written', lowerTo: lowered ? [lowered] : [], origin });
}
if (kind.startsWith('managed_sync_') || kind.startsWith('managed_maintenance_') || kind.startsWith('managed_facts_')
- || kind.startsWith('managed_atom_') || OWNER_SOURCE_KINDS.includes(kind)) return undefined;
+ || kind.startsWith('managed_atom_') || kind.startsWith('managed_generation_') || OWNER_SOURCE_KINDS.includes(kind)) return undefined;
if (AGENT_WRITE_OPERATIONS.includes(row.operation)) {
const lowered = intentContentOrigin(row.intent);
return effectiveWriteTrust({ channel: 'agent_written', lowerTo: lowered ? [lowered] : [], origin });