Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
GBRA-161 PR 3: Life Chronicle events on the generation primitive (C-2, C-3, C-6)
garrytan5680c2fa5313
diff --git a/docs/architecture/derived-census.tsv b/docs/architecture/derived-census.tsvindex aee37f6820..79db46b13a 100644--- a/docs/architecture/derived-census.tsv+++ b/docs/architecture/derived-census.tsv@@ -2,13 +2,13 @@# Rows: path<TAB>ceiling<TAB>class<TAB>note. Ceilings only shrink (--prune lowers them); a new soft-delete site needs a reviewed row.# class: primitive | engine | canonical | pending:inventory (a derived or mixed writer each later GBRA-161 PR reviews onto the generation primitive).src/commands/sync/deletes.ts 1 canonical sync deletes a page whose canonical file was removed-src/core/chronicle/publish.ts 1 pending:inventory derived or mixed writer not yet on the generation primitive; reviewed in a later GBRA-161 PRsrc/core/company-brain/profile.ts 1 pending:inventory derived or mixed writer not yet on the generation primitive; reviewed in a later GBRA-161 PRsrc/core/cycle/phantom-redirect.ts 1 pending:inventory derived or mixed writer not yet on the generation primitive; reviewed in a later GBRA-161 PRsrc/core/engine-sql/pages.ts 5 engine the shared soft-delete SQL both engines delegate tosrc/core/engine.ts 3 engine BrainEngine interface declarations of softDeletePage/softDeletePagessrc/core/facts/derivation-inputs.ts 1 pending:inventory derived or mixed writer not yet on the generation primitive; reviewed in a later GBRA-161 PRsrc/core/generations/adapters/atoms.ts 1 primitive the unmanaged atom adapter retires through retireDerivedPagesInTransaction inside the generation activation (publish.ts)+src/core/generations/adapters/chronicle-events.ts 1 primitive the Life Chronicle event adapter retires dropped events (with their timeline projection rows) through retireDerivedPagesInTransaction inside the generation activation (publish.ts, managed.ts; GBRA-161 PR 3)src/core/minions/handlers/ingest-capture.ts 1 pending:inventory derived or mixed writer not yet on the generation primitive; reviewed in a later GBRA-161 PRsrc/core/ops/extraction.ts 1 pending:inventory derived or mixed writer not yet on the generation primitive; reviewed in a later GBRA-161 PRsrc/core/page-body/segment-rewrite.ts 1 pending:inventory derived or mixed writer not yet on the generation primitive; reviewed in a later GBRA-161 PRdiff --git a/docs/architecture/generations.md b/docs/architecture/generations.mdindex 40ae6bb0f9..2605d95fe4 100644--- a/docs/architecture/generations.md+++ b/docs/architecture/generations.md@@ -54,6 +54,19 @@ Adapters (`contract.ts`) own one kind each: `adapters/atoms.ts` (atoms, one keyrelease. An atom's identity leaves out the provenance a managed writer stamps (`source_kind`, `ingested_via`,`ingested_at`, `trust_tier` and the other content-hash ephemeral keys), so a managed write never reads as an edit.+Life Chronicle events publish through `publishChronicleGeneration` (`adapters/chronicle-events.ts`, kind+`chronicle_event`, key `depth:<slug>`, GBRA-161 PR 3). Each judged revision of a depth page (meeting, conversation,+calendar page) is a generation of event pages; each event's timeline projection row on the depth page belongs to its+item. A complete re-judgment retires the events it dropped together with their projection rows in the activation+(versioned, `retired_by: life-chronicle`); a result below the model floor is held `shrunk`, and an empty or partial one+(#7013) retires nothing. An empty generation retires only with a proof: `originIneligible` (the revision became+ineligible: `not_chronicle_shaped`, `dream_generated` or `too_short`, rechecked against the chronicle ledger by the+adapter's `proofHolds`) or `originGone` (the chronicle phase retires the events of a deleted depth page). Ownership+stays content-addressed: an event is the extractor's while its content hash is on the chronicle ledger, its identity is+the one the live generation recorded, or it is exactly what this publication proposed; an operator-edited or+operator-deleted event is never an item, so nothing overwrites, retires or revives it.+`gbrain repair generations --kind chronicle-event --mode restore` brings retired events and their rows back.+### Managed sourcesA managed source (`generations/managed.ts`) never composes a generation in one transaction: every page write is its own@@ -66,6 +79,11 @@ coordinated request with its own file. A publication is planned without locks an3. `overwrite` and `retire` members: the existing per-page managed put and delete requests (version first, stamp), eachrefusing unless its item is pending on the live generation its activation made, and clearing the mark on commit.+A database-only kind (`databaseOnly`: chronicle events, which have no canonical file) writes its new and changed items+as their own requests before the activation, which it journals on the input page bound to its revision; the activation+checks those members at the identity they now hold, records their before-states from the plan and retires the dropped+items itself, so nothing is left pending. Its restore runs as one coordinated `managed_generation_restore` request.+The activation id is digest(operation id, run scope) and each member's digest(activation id, slug, action), so a rerunreplays them. Between steps 1 and 3 old and new items are both live, never neither. The next extraction run of thesource resumes pending members (`resumeManagedGenerationMembers`): a request still queued is waited on, one that endeddiff --git a/docs/guides/repair.md b/docs/guides/repair.mdindex 733f24e2d4..2ebdc0d073 100644--- a/docs/guides/repair.md+++ b/docs/guides/repair.md@@ -1572,6 +1572,11 @@ held result waits, with the read-only release preview as its fix;`generation_retirements` reports what is restorable. Show the user the previewbefore running the apply. Managed brains keep their coordinator path for now.+Life Chronicle events publish the same way (`--kind chronicle-event`, key+`depth:<slug>`): a restore brings back the events a re-judgment or a deleted+depth page retired, with their timeline rows on the depth page, and it runs on+managed brains as one coordinated request.+### Extractor factsA managed write by a gbrain older than v0.60.11.0 to a conversation pagediff --git a/scripts/check-core-guard-coverage.mjs b/scripts/check-core-guard-coverage.mjsindex 0c8c371014..9ffaa632c3 100644--- a/scripts/check-core-guard-coverage.mjs+++ b/scripts/check-core-guard-coverage.mjs@@ -35,6 +35,7 @@ const EXEMPT = {'src/core/persistence/connector-google-receipts.ts': 'connector receipt rows, not page text','src/core/persistence/projection-reindex.ts': 'rebuilds derived projections; page text is unchanged','src/core/persistence/noop-kernel.ts': 'decides that nothing would change; publishes nothing',+ 'src/core/generations/repair.ts': 'the managed restore of a database-only generation (chronicle event pages, never core pages) revives and retires derived items through the adapter inside the coordinated request','src/core/generations/managed.ts': 'the generation activation flips the derived ledger; it writes no page text (its member page writes go through preparePageMutation)','src/core/persistence/consumer.ts': 'dispatches to preparers; no page content of its own','src/core/persistence/coordinator.ts': 'takes the ordered source lock from exclusiveSources; prepares nothing itself',diff --git a/scripts/page-body-readers-baseline.tsv b/scripts/page-body-readers-baseline.tsvindex fe88c2df0b..ad60342332 100644--- a/scripts/page-body-readers-baseline.tsv+++ b/scripts/page-body-readers-baseline.tsv@@ -85,7 +85,6 @@ src/core/chronicle/backfill.ts runChronicleBackfill sql STREAMsrc/core/chronicle/execute.ts executeChronicleRow field LEADsrc/core/chronicle/extract-events.ts chronicleJudgeContext field LEADsrc/core/chronicle/ledger.ts decideChronicle field LEAD-src/core/chronicle/publish.ts publishChronicleGeneration call:putPage INLINEsrc/core/chronicle/publish.ts publishChronicleGeneration call:serializeMarkdown INLINEsrc/core/code-chunks.ts prepareCodeChunks field INLINEsrc/core/company-brain/inspection.ts readPage field STREAM@@ -606,6 +605,8 @@ src/core/persistence/page-edit.ts applyPageEdits call:serializePageToMarkdown SEsrc/core/persistence/page-edit.ts applyPageEdits field SEGW within's stored-offset mapping on the materialized snapshot, as pageSegments; a segmented page takes prepareSegmentedEditMutation firstsrc/core/persistence/page-edit.ts prepareSegmentedEditMutation call:serializePageToMarkdown NONE serializes the frontmatter head with an empty body; the body streams from the segmentssrc/core/persistence/page-edit.ts assertSegmentedFencesCompile field NONE the fields hold only the stored fence text laid out at its lines (scanCanonicalFences input); no page body is read+src/core/generations/adapters/chronicle-events.ts chronicleEventAdapter field NONE restoreItem reads the body field of a ledger preimage JSON copy; segmented and oversize pages have no preimage+src/core/generations/adapters/chronicle-events.ts writeEventPage call:putPage INLINE writes a Life Chronicle event page from the extractor's short proposal or a ledger preimage JSON copy; no stored page body is readsrc/core/generations/adapters/page.ts pageIdentityHash field INLINE identity hash of a derived page item: a segmented row hashes its empty inline body and is held segmented_unsupported before any write, so no segmented page is rewritten or retiredsrc/core/generations/adapters/page.ts markdownItem field NONE reads the compiled_truth parseMarkdown returns for the producer's proposed markdown; no stored page body is readsrc/core/generations/adapters/page.ts readPageRows sql INLINE reads derived page items (atoms) with body_storage; a segmented row is marked segmented and held segmented_unsupported, with no preimagediff --git a/src/core/chronicle/execute.ts b/src/core/chronicle/execute.tsindex d7797e1d73..48c20c5c94 100644--- a/src/core/chronicle/execute.ts+++ b/src/core/chronicle/execute.ts@@ -175,7 +175,7 @@ export async function executeChronicleRow(ctx: ChronicleExecContext, row: Chroni// An ineligible revision of a page that once produced events retires them (E8). No model call.if (row.state === 'skipped') {const generation = await publishChronicleGeneration(engine, { sourceId: row.source_id, pin, events: [],- decisionRequestId: null, replaces: true, maintenance: ctx.maintenance, signal: ctx.signal });+ decisionRequestId: null, replaces: true, proof: { kind: 'originIneligible', reason: String(row.reason) }, maintenance: ctx.maintenance, signal: ctx.signal });await setNextAttempt(engine, row, null);return done('skipped', row.reason, { retired: generation.retired.length });}diff --git a/src/core/chronicle/publish.ts b/src/core/chronicle/publish.tsindex 61891026ee..0083a80d07 100644--- a/src/core/chronicle/publish.ts+++ b/src/core/chronicle/publish.ts@@ -1,30 +1,32 @@/**- * Life Chronicle event publication (#5876, E5/E8, C4b/C12).+ * Life Chronicle event publication (#5876, E5/E8, C4b/C12; GBRA-161 PR 3).** One extraction generation of a depth page (meeting, conversation, calendar- * page) is published against the immutable snapshot the judge read:+ * page) is published against the immutable snapshot the judge read, through the+ * generation primitive (generations/adapters/chronicle-events.ts):*- * - Every event write re-validates, in its own publication step, that the- * depth page still has the judged revision, content hash, source- * incarnation and privacy, and that the writer whose revision was decided- * still holds the extraction grant. Any change → `superseded`; no model- * call or transaction spans the judge.+ * - The activation re-validates that the depth page still has the judged+ * revision, content hash, source incarnation and privacy, and that the+ * writer whose revision was decided still holds the extraction grant. Any+ * change → `superseded`; no model call or transaction spans the judge.* - Events carry the depth page's effective visibility.* - Ownership is content-addressed: an event is the extractor's while its* live content_hash is one the ledger recorded for this depth page. An* operator-edited event (hash changed) is never overwritten or retired;- * an operator-deleted event (deleted without `retired_by`) is never- * resurrected.- * - Only after the whole generation published, and only when the caller- * declares it a complete replacement (`replaces`), the previous- * generation's owned events it did not reproduce are retired (soft-deleted- * with `retired_by: life-chronicle`, reversible); a later generation that- * produces one again restores it. A failed or superseded run, and an empty- * or partial one (#7013), retires nothing.+ * an operator-deleted event (deleted without a verified retirement) is+ * never resurrected.+ * - A complete generation (`replaces`) retires the previous generation's+ * owned events it did not reproduce, with their timeline projection rows, in+ * the activation: versioned, soft-deleted, `retired_by: life-chronicle`, and+ * restorable with `gbrain repair generations --kind chronicle-event`. A result+ * below the shrink floor is held and retires nothing; so does an empty or+ * partial one (#7013). An empty generation retires only with a proof: the+ * revision became ineligible (`originIneligible`) or the depth page is gone+ * (`originGone`).*- * Managed brains publish through two maintenance intents (database-only);- * unmanaged brains write directly inside one attributed maintenance- * transaction per event.+ * Managed brains publish each new or changed event through the chronicle event+ * intent (database-only), then one `managed_generation_activate` request that+ * retires and flips the ledger; unmanaged brains do it all in one transaction.*/import type { BrainEngine } from '../engine.ts';import type { GBrainConfig } from '../config.ts';@@ -35,61 +37,27 @@ import { OperationError, opError } from '../ops/contract.ts';import { computeContentHash } from '../ingestion/types.ts';import { serializeMarkdown } from '../markdown.ts';import { digest } from '../persistence/digest.ts';-import { authorizeFactsBackstop } from '../persistence/effect-facts.ts';-import { maintenanceTransaction } from '../persistence/attribution.ts';import { maintenancePreflight, submitDatabaseMaintenanceIntent, type MaintenanceAuthority } from '../persistence/prepared-maintenance.ts';import { preparePageMutation } from '../persistence/page-prepare.ts';-import { effectiveVisibility, type Visibility } from '../search/private-visibility.ts';+import type { Visibility } from '../search/private-visibility.ts';import type { ChronicleEventProposal } from './extract-events.ts';import { resolveChronicleEventSlugs } from './event-identity.ts';-import { declareDerivation, declaredWriteTrust, deriveTrust, derivedMaintenanceTransaction, readDerivationDeclaration } from '../trust/taint.ts';+import { declareDerivation, declaredWriteTrust, deriveTrust, readDerivationDeclaration } from '../trust/taint.ts';import { derivedGateConfig, derivedGateInput, timelineRowAllowed } from '../trust/derived-gate.ts';import { assessTimelineForGate, type WriteGateAssessment } from '../write-gate.ts';import { recordWriteGateReceipt } from '../write-gate-store.ts';+import type { InputState, ProposedItem } from '../generations/contract.ts';+import { originGone, type EmptySourceProof } from '../generations/proofs.ts';+import { publishGeneration, type PublishOutcome, type PublishRequest } from '../generations/publish.ts';+import { planManagedGeneration, recordActivation, type ActivationIntent } from '../generations/managed.ts';+import { CHRONICLE_EVENT_KIND, CHRONICLE_RETIRED_BY, chronicleEventAdapter, chronicleEventItem, chronicleOwnerKey, depthInputPin, depthPinBroken,+ orphanedDepthKeys, ownedEventHashes, pinDepth, verifiedChronicleRetirement, type ChronicleDepthPin, type ChronicleGenerationContext } from '../generations/adapters/chronicle-events.ts';-export const CHRONICLE_RETIRED_BY = 'life-chronicle';+export { CHRONICLE_RETIRED_BY, depthPinBroken, ownedEventHashes, pinDepth, type ChronicleDepthPin };export const CHRONICLE_EVENT_INTENT = 'managed_maintenance_chronicle_event';export const CHRONICLE_RETIRE_INTENT = 'managed_maintenance_chronicle_retire';export const CHRONICLE_CAPTURED_VIA = 'life-chronicle:auto';-/** The judged depth page; publication re-checks every field. */-export interface ChronicleDepthPin {- slug: string;- pageId: number;- revision: string;- contentHash: string;- incarnation: string;- visibility: Visibility;-}--export function pinDepth(snapshot: PageSnapshot): ChronicleDepthPin {- return {- slug: snapshot.page.slug, pageId: Number(snapshot.page.id), revision: snapshot.revision,- contentHash: String(snapshot.page.content_hash ?? ''), incarnation: snapshot.sourceIncarnation,- visibility: effectiveVisibility({ kind: 'page', page: snapshot.page }),- };-}--/** null while the pin holds; otherwise why the generation is superseded. */-export async function depthPinBroken(tx: BrainEngine, sourceId: string, pin: ChronicleDepthPin,- decisionRequestId: string | null): Promise<string | null> {- const current = await tx.readPageSnapshot(pin.slug, { sourceId });- if (!current) return 'page_missing';- if (Number(current.page.id) !== pin.pageId || current.revision !== pin.revision- || String(current.page.content_hash ?? '') !== pin.contentHash || current.sourceIncarnation !== pin.incarnation- || effectiveVisibility({ kind: 'page', page: current.page }) !== pin.visibility) return 'superseded';- if (decisionRequestId) {- const [request] = await tx.executeRaw<WriteRequest>('SELECT * FROM persistence_requests WHERE id=$1::uuid', [decisionRequestId]);- if (!request) return 'superseded';- try { await authorizeFactsBackstop(tx, request); }- catch (error) {- if (error instanceof OperationError) return 'superseded';- throw error;- }- }- return null;-}-export interface BuiltChronicleEvent {slug: string;title: string;@@ -119,20 +87,13 @@ export function buildChronicleEvent(ev: ChronicleEventProposal, ctx: {};}-/** Every event content hash the extractor ever wrote for this depth page. */-export async function ownedEventHashes(engine: BrainEngine, sourceId: string, pageId: number): Promise<Set<string>> {- const rows = await engine.executeRaw<{ hash: string }>(- 'SELECT DISTINCT unnest(event_hashes) AS hash FROM chronicle_page_state WHERE source_id=$1 AND page_id=$2',- [sourceId, pageId]);- return new Set(rows.map((r) => r.hash));-}-type TargetVerdict = { write: true; restore: boolean; expectedRevision: string | null } | { write: false; reason: 'operator_deleted' | 'operator_edited' };-function judgeTarget(existing: PageSnapshot | null, owned: Set<string>): TargetVerdict {+/** Whether an event slug may be written: absent, owned and live, or retired by a verified chronicle retirement (restored). */+async function judgeTarget(db: BrainEngine, sourceId: string, existing: PageSnapshot | null, owned: Set<string>): Promise<TargetVerdict> {if (!existing) return { write: true, restore: false, expectedRevision: null };if (existing.page.deleted_at) {- return existing.page.frontmatter?.retired_by === CHRONICLE_RETIRED_BY+ return await verifiedChronicleRetirement(db, sourceId, existing.page)? { write: true, restore: true, expectedRevision: existing.revision }: { write: false, reason: 'operator_deleted' };}@@ -154,7 +115,7 @@ function supersededError(reason: string): OperationError {/** A publication failure that means the judged generation no longer applies. */export function isSupersession(error: unknown): boolean {return error instanceof OperationError- && ['revision_conflict', 'page_identity_changed', 'source_changed', 'permission_denied', 'page_not_found'].includes(error.code);+ && ['revision_conflict', 'page_identity_changed', 'source_changed', 'permission_denied', 'page_not_found', 'generation_fenced', 'generation_live_conflict'].includes(error.code);}export interface ChronicleGenerationResult {@@ -162,116 +123,117 @@ export interface ChronicleGenerationResult {retired: string[];protected: Array<{ slug: string; reason: 'operator_deleted' | 'operator_edited' }>;superseded?: string;+ /** The result was held (`generation_held`): nothing was published or retired. */+ held?: string;}/**- * Publish one generation (possibly empty) for a pinned depth page. With `replaces` (a complete judged generation, or- * an ineligible revision's empty one) it then retires the previous generation's owned events it did not reproduce;- * without it (an empty or partial judged generation, #7013) it retires nothing.+ * Publish one generation (possibly empty) for a pinned depth page. `replaces`: a complete judged generation, which may+ * retire the previous generation's owned events it did not reproduce (within the shrink floor and valve); without it+ * (an empty or partial judged generation, #7013) it adds and retires nothing. `proof` makes an empty `replaces`+ * generation retire every owned event: `originIneligible` (the revision no longer qualifies) or `originGone` (the+ * depth page is gone; `pin` is then null).*/export async function publishChronicleGeneration(engine: BrainEngine, opts: {- sourceId: string; pin: ChronicleDepthPin; events: BuiltChronicleEvent[]; decisionRequestId: string | null;- replaces: boolean; maintenance?: MaintenanceAuthority | null; signal?: AbortSignal;+ sourceId: string; pin: ChronicleDepthPin | null; depthSlug?: string; events: BuiltChronicleEvent[]; decisionRequestId: string | null;+ replaces: boolean; proof?: EmptySourceProof; maintenance?: MaintenanceAuthority | null; signal?: AbortSignal;}): Promise<ChronicleGenerationResult> {const { sourceId, pin } = opts;+ const depthSlug = pin?.slug ?? opts.depthSlug!;const maintenance = opts.maintenance === undefined ? await maintenancePreflight(engine, sourceId) : opts.maintenance;- const owned = await ownedEventHashes(engine, sourceId, pin.pageId);const result: ChronicleGenerationResult = { written: [], retired: [], protected: [] };- const abort = () => { if (opts.signal?.aborted) { const e = new Error('aborted'); e.name = 'AbortError'; throw e; } };- const broken = await depthPinBroken(engine, sourceId, pin, opts.decisionRequestId);- if (broken) return { ...result, superseded: broken };- const events = await resolveChronicleEventSlugs(engine, sourceId, opts.events);- // #5575 I2: the judge read only the depth page, so its events carry that page's tier (capped at agent_written).- const derivation = await deriveTrust(engine, [{ table: 'pages', id: pin.pageId }], { channel: 'derive:chronicle' });- const gateCfg = await derivedGateConfig(engine);-- for (const ev of events) {- abort();- const existing = await engine.readPageSnapshot(ev.slug, { sourceId, includeDeleted: true });- const verdict = judgeTarget(existing, owned);- if (!verdict.write) { result.protected.push({ slug: ev.slug, reason: verdict.reason }); continue; }- const content = serializeMarkdown(ev.frontmatter, ev.compiledTruth, '', { type: 'event', title: ev.title, tags: [] });- // #5575 B3: the event's summary lands on the depth page's timeline; a quarantined or rejected one projects nothing.- const projectionGate = assessTimelineForGate({ summary: ev.summary, source: `life-chronicle:event:${ev.slug}` }, derivedGateInput(derivation.trust), gateCfg);- const projection = timelineRowAllowed(projectionGate) ? { depth_slug: pin.slug, date: ev.day, summary: ev.summary } : undefined;- try {- if (maintenance) {- const intent = { kind: CHRONICLE_EVENT_INTENT, content, expected_revision: verdict.expectedRevision,- restore_retired: verdict.restore, depth: pin, decision_request_id: opts.decisionRequestId,- owned_hashes: [...owned], ...(projection ? { event_projection: projection } : {}), derivation: declareDerivation(derivation.trust, derivation.inputs) };- await submitDatabaseMaintenanceIntent(engine, maintenance, ev.slug, intent,- requestIdFor({ writer: maintenance.writer.principal, slug: ev.slug, intent }));- } else {- await derivedMaintenanceTransaction(engine, derivation, async (tx) => {- const reason = await depthPinBroken(tx, sourceId, pin, null);- if (reason) throw supersededError(reason);- const again = judgeTarget(await tx.readPageSnapshot(ev.slug, { sourceId, includeDeleted: true }), owned);- if (!again.write) throw supersededError(again.reason);- const page = await tx.putPage(ev.slug, { type: 'event', title: ev.title, compiled_truth: ev.compiledTruth,- frontmatter: { type: 'event', ...ev.frontmatter }, effective_date: safeDate(ev.when) }, { sourceId });- if (projection) {- await tx.upsertEventProjection({ depthSlug: pin.slug, eventSlug: ev.slug, date: ev.day, summary: ev.summary, sourceId });- await recordProjectionFlag(tx, projectionGate, page.id, ev.day, sourceId);- }- return { result: undefined, rows: [{ table: 'pages', id: page.id, sourceId }] };- });- }- } catch (error) {- if (!isSupersession(error)) throw error;- return { ...result, superseded: 'superseded' };- }- const written = await engine.readPageSnapshot(ev.slug, { sourceId });- if (written?.page.content_hash) {- result.written.push({ slug: ev.slug, hash: String(written.page.content_hash) });- owned.add(String(written.page.content_hash));+ if (opts.signal?.aborted) { const e = new Error('aborted'); e.name = 'AbortError'; throw e; }+ const key = { kind: CHRONICLE_EVENT_KIND, sourceId, ownerKey: chronicleOwnerKey(depthSlug) };+ const context: ChronicleGenerationContext = { decisionRequestId: opts.decisionRequestId };+ let input: InputState | null = null;+ const items: ProposedItem[] = [];+ const members = new Map<string, { event: BuiltChronicleEvent; verdict: Extract<TargetVerdict, { write: true }>; markdown: string }>();+ if (pin) {+ const broken = await depthPinBroken(engine, sourceId, pin, opts.decisionRequestId);+ if (broken) return { ...result, superseded: broken };+ input = await chronicleEventAdapter.readInput(engine, key, context);+ if (input?.pin !== depthInputPin(pin)) return { ...result, superseded: 'superseded' };+ const owned = await ownedEventHashes(engine, sourceId, pin.pageId);+ for (const event of await resolveChronicleEventSlugs(engine, sourceId, opts.events)) {+ const verdict = await judgeTarget(engine, sourceId, await engine.readPageSnapshot(event.slug, { sourceId, includeDeleted: true }), owned);+ if (!verdict.write) { result.protected.push({ slug: event.slug, reason: verdict.reason }); continue; }+ const markdown = serializeMarkdown(event.frontmatter, event.compiledTruth, '', { type: 'event', title: event.title, tags: [] });+ items.push(chronicleEventItem(event.slug, { markdown, title: event.title, compiledTruth: event.compiledTruth, frontmatter: event.frontmatter,+ when: event.when, day: event.day, summary: event.summary }));+ members.set(event.slug, { event, verdict, markdown });}}-- if (!opts.replaces) return result;- const keep = new Set(events.map((e) => e.slug));- const stale = await engine.executeRaw<{ slug: string; revision: string; content_hash: string }>(- `SELECT slug, knowledge_revision::text AS revision, content_hash FROM pages- WHERE source_id=$1 AND type='event' AND deleted_at IS NULL AND frontmatter->'event'->>'depth'=$2- AND frontmatter->>'captured_via' LIKE 'life-chronicle:%' AND content_hash = ANY($3::text[])- ORDER BY slug`,- [sourceId, pin.slug, [...owned]]);- for (const event of stale) {- if (keep.has(event.slug)) continue;- abort();- try {- if (maintenance) {- const intent = { kind: CHRONICLE_RETIRE_INTENT, expected_revision: event.revision, depth: pin,- decision_request_id: opts.decisionRequestId, owned_hashes: [...owned] };- await submitDatabaseMaintenanceIntent(engine, maintenance, event.slug, intent,- requestIdFor({ writer: maintenance.writer.principal, slug: event.slug, intent }));- } else {- await maintenanceTransaction(engine, async (tx) => {- const reason = await depthPinBroken(tx, sourceId, pin, null);- if (reason) throw supersededError(reason);- const live = await tx.readPageSnapshot(event.slug, { sourceId });- if (!live || !owned.has(String(live.page.content_hash ?? ''))) return;- await tx.createVersion(event.slug, { sourceId, preimage: live });- await tx.softDeletePage(event.slug, { sourceId });- await stampRetired(tx, sourceId, event.slug);- });- }- result.retired.push(event.slug);- } catch (error) {- if (!isSupersession(error)) throw error;- return { ...result, superseded: 'superseded' };- }+ if (!opts.replaces && !items.length) return result;+ context.planned = Object.fromEntries(items.map(item => [item.key, item.identityHash]));+ const request = { key, items, input, partial: !opts.replaces, ...(opts.proof ? { proof: opts.proof } : {}), context };+ let outcome: PublishOutcome | null;+ try {+ outcome = maintenance ? await publishManagedChronicle(engine, maintenance, request, pin, members, opts.decisionRequestId)+ : await publishGeneration(engine, chronicleEventAdapter, request);+ } catch (error) {+ if (!isSupersession(error)) throw error;+ return { ...result, written: await writtenEvents(engine, sourceId, items), superseded: 'superseded' };}- return result;+ if (outcome?.state === 'held') return { ...result, held: outcome.reason };+ return { ...result, written: await writtenEvents(engine, sourceId, items), retired: outcome?.state === 'published' ? outcome.retired : [] };}-async function stampRetired(tx: BrainEngine, sourceId: string, slug: string): Promise<void> {- await tx.executeRaw(`UPDATE pages SET frontmatter=frontmatter||jsonb_build_object('retired_by',$1::text,'retired_at',$2::text)- WHERE source_id=$3 AND slug=$4 AND deleted_at IS NOT NULL`, [CHRONICLE_RETIRED_BY, new Date().toISOString(), sourceId, slug]);+/** The live content hash of each proposed event (what the chronicle ledger records as the extractor's). */+async function writtenEvents(engine: BrainEngine, sourceId: string, items: readonly ProposedItem[]): Promise<Array<{ slug: string; hash: string }>> {+ if (!items.length) return [];+ const rows = await engine.executeRaw<{ slug: string; content_hash: string | null }>(+ 'SELECT slug, content_hash FROM pages WHERE source_id=$1 AND slug=ANY($2::text[]) AND deleted_at IS NULL', [sourceId, items.map(item => item.key)]);+ const hashes = new Map(rows.map(row => [row.slug, row.content_hash]));+ return items.flatMap(item => hashes.get(item.key) ? [{ slug: item.key, hash: String(hashes.get(item.key)) }] : []);}-function safeDate(s: string): Date | null {- const d = new Date(s);- return Number.isNaN(d.getTime()) ? null : d;+/**+ * The managed publication (database-only): the plan's new and changed events go through the chronicle event intent,+ * one request each, then one `managed_generation_activate` request, journaled on the depth page and bound to its+ * revision, rechecks the pin and every member, retires the dropped events with their projection rows and flips the+ * ledger in one transaction. null: nothing to publish.+ */+async function publishManagedChronicle(engine: BrainEngine, maintenance: MaintenanceAuthority, request: PublishRequest<ChronicleGenerationContext>,+ pin: ChronicleDepthPin | null, members: Map<string, { event: BuiltChronicleEvent; verdict: Extract<TargetVerdict, { write: true }>; markdown: string }>,+ decisionRequestId: string | null): Promise<PublishOutcome | null> {+ const plan = await planManagedGeneration(engine, chronicleEventAdapter, request, { scope: decisionRequestId });+ if (plan.kind === 'held') return plan.outcome;+ if (plan.kind === 'unchanged') return { state: 'unchanged', generation: null, retired: [], protected: [] };+ await engine.transaction(tx => recordActivation(tx, plan.intent));+ const owned = pin ? await ownedEventHashes(engine, request.key.sourceId, pin.pageId) : new Set<string>();+ const derivation = pin ? await deriveTrust(engine, [{ table: 'pages', id: pin.pageId }], { channel: 'derive:chronicle' }) : null;+ const gateCfg = pin ? await derivedGateConfig(engine) : null;+ for (const member of plan.members) {+ if (member.action === 'retire' || !pin || !derivation || !gateCfg) continue;+ const { event, verdict, markdown } = members.get(member.slug)!;+ if (member.action === 'overwrite' && member.identity === member.before) continue;+ // #5575 B3: the event's summary lands on the depth page's timeline; a quarantined or rejected one projects nothing.+ const gate = assessTimelineForGate({ summary: event.summary, source: `life-chronicle:event:${event.slug}` }, derivedGateInput(derivation.trust), gateCfg);+ const projection = timelineRowAllowed(gate) ? { depth_slug: pin.slug, date: event.day, summary: event.summary } : undefined;+ const intent = { kind: CHRONICLE_EVENT_INTENT, content: markdown, expected_revision: verdict.expectedRevision,+ restore_retired: verdict.restore, depth: pin, decision_request_id: decisionRequestId, activation_id: plan.intent.activationId,+ owned_hashes: [...owned], ...(projection ? { event_projection: projection } : {}), derivation: declareDerivation(derivation.trust, derivation.inputs) };+ await submitDatabaseMaintenanceIntent(engine, maintenance, event.slug, intent, requestIdFor({ writer: maintenance.writer.principal, slug: event.slug, intent }));+ }+ const depth = await engine.readPageSnapshot(request.key.ownerKey.slice('depth:'.length), { sourceId: request.key.sourceId, includeDeleted: true });+ const activation: ActivationIntent & { expected_revision: string | null } = { ...plan.intent, runKey: plan.intent.activationId,+ expected_revision: depth?.revision ?? null, ...(depth?.page.deleted_at ? { deleted_page: true } : {}) };+ await submitDatabaseMaintenanceIntent(engine, maintenance, request.key.ownerKey.slice('depth:'.length), activation, plan.intent.activationId);+ const retired = plan.members.filter(member => member.action === 'retire').map(member => member.slug);+ return { state: 'published', generationId: 0, generation: plan.intent.expectedGeneration + 1, puts: [], kept: [], adopted: [], retired, protected: [] };+}++/** C-6: retires the events of up to `limit` depth pages of `sourceId` that are gone, each through `originGone`; returns the count. */+export async function retireOrphanedChronicleEvents(engine: BrainEngine, sourceId: string, maintenance?: MaintenanceAuthority | null, limit = 50): Promise<number> {+ let retired = 0;+ const keys = await orphanedDepthKeys(engine, sourceId, limit);+ if (keys.length && maintenance === undefined) maintenance = await maintenancePreflight(engine, sourceId);+ for (const ownerKey of keys) {+ const generation = await publishChronicleGeneration(engine, { sourceId, pin: null, depthSlug: ownerKey.slice('depth:'.length), events: [],+ decisionRequestId: null, replaces: true, proof: originGone(), maintenance });+ retired += generation.retired.length;+ }+ return retired;}interface ChronicleIntent extends Record<string, unknown> {@@ -300,7 +262,7 @@ export async function prepareChronicleMutation(engine: BrainEngine, row: WriteReif (!target || target.page.deleted_at || !owned.has(String(target.page.content_hash ?? ''))) throw supersededError('event_changed');return;}- const verdict = judgeTarget(target, owned);+ const verdict = await judgeTarget(tx, row.source_id, target, owned);if (!verdict.write) throw supersededError(verdict.reason);};await check(engine);@@ -330,6 +292,13 @@ export async function prepareChronicleMutation(engine: BrainEngine, row: WriteRe} };}+/** A retirement journaled by an earlier release (`managed_maintenance_chronicle_retire`): the stamp, and its projection row goes with it (C-3). */+async function stampRetired(tx: BrainEngine, sourceId: string, slug: string): Promise<void> {+ await tx.executeRaw(`UPDATE pages SET frontmatter=frontmatter||jsonb_build_object('retired_by',$1::text,'retired_at',$2::text)+ WHERE source_id=$3 AND slug=$4 AND deleted_at IS NOT NULL`, [CHRONICLE_RETIRED_BY, new Date().toISOString(), sourceId, slug]);+ await tx.executeRaw('DELETE FROM timeline_entries t USING pages p WHERE p.id=t.event_page_id AND p.source_id=$1 AND p.slug=$2', [sourceId, slug]);+}+/** A flagged event projection's receipt on its timeline row (found by its event page and date). */async function recordProjectionFlag(tx: BrainEngine, assessment: WriteGateAssessment, eventPageId: number, date: string, sourceId: string, requestId?: string): Promise<void> {if (assessment.verdict !== 'flag') return;diff --git a/src/core/cycle/chronicle.ts b/src/core/cycle/chronicle.tsindex 356cd1d68a..00d3167b86 100644--- a/src/core/cycle/chronicle.ts+++ b/src/core/cycle/chronicle.ts@@ -35,6 +35,7 @@ import {} from '../chronicle/contract.ts';import { CHRONICLE_TYPES, RESCUE_SLUG_PREFIXES } from '../chronicle/eligibility.ts';import { claimChronicleRow, executeChronicleRow } from '../chronicle/execute.ts';+import { retireOrphanedChronicleEvents } from '../chronicle/publish.ts';import { failExhaustedCampaignRows } from '../chronicle/campaign.ts';import { defaultJudge, type ChronicleDropReason, type ChronicleJudge } from '../chronicle/extract-events.ts';import {@@ -157,6 +158,13 @@ export async function runPhaseChronicle(engine: BrainEngine, opts: ChroniclePhasfor (const sourceId of sources) {await discover(engine, sourceId, { managed, enabled, activatedAt, settings, now: now(), dryRun });}+ if (!dryRun) {+ // C-6: a deleted depth page's events retire through `originGone` (no model call, so no chat provider needed).+ for (const sourceId of sources) {+ try { details.events_retired += await retireOrphanedChronicleEvents(engine, sourceId); }+ catch (error) { console.warn(`[chronicle] ${sourceId}: retiring the events of deleted pages failed (${error instanceof Error ? error.message : String(error)}); the next run retries.`); }+ }+ }const queues = new Map<string, ChronicleLedgerRow[]>();for (const sourceId of sources) {const rows = await candidates(engine, sourceId, enabled, maxItems);diff --git a/src/core/generations/adapters/chronicle-events.ts b/src/core/generations/adapters/chronicle-events.tsnew file mode 100644index 0000000000..10e1f5f4b4--- /dev/null+++ b/src/core/generations/adapters/chronicle-events.ts@@ -0,0 +1,299 @@+/**+ * GBRA-161 PR 3: the Life Chronicle event adapter (kind `chronicle_event`, one owner key per depth page:+ * `depth:<slug>`). The items are the event pages a judged revision of the depth page yields, each with the timeline+ * projection row it puts on the depth page. A re-judged revision publishes a new generation: changed events are+ * versioned and overwritten, and the events it dropped retire (versioned, soft-deleted, `retired_by: life-chronicle`)+ * together with their projection rows, in the activation. Chronicle pages are database-only, so a managed source runs the+ * same activation in one coordinated request (`databaseOnly`).+ *+ * Ownership stays content-addressed (#5876): an event is the depth page's while it names that page as its depth and its+ * content hash is one the chronicle ledger recorded for it, or its identity is the one the live generation recorded. An+ * operator-edited event (any other content) and an operator-deleted one (deleted without a verified retirement) are not+ * items at all: the adapter never overwrites, retires or revives them.+ */+import type { BrainEngine } from '../../engine.ts';+import type { PageSnapshot } from '../../page-state/types.ts';+import { pageBodyBytes } from '../../page-body/page-shape.ts';+import { digest } from '../../persistence/digest.ts';+import { RESERVED_RETIREMENT_KEYS, retireDerivedPagesInTransaction } from '../../persistence/derived-retirement-hold.ts';+import { withWriteTrust } from '../../persistence/context.ts';+import { effectiveVisibility, type Visibility } from '../../search/private-visibility.ts';+import { deriveTrust, lowerDerivedPageIn } from '../../trust/taint.ts';+import { derivedGateConfig, derivedGateInput, timelineRowAllowed } from '../../trust/derived-gate.ts';+import { assessTimelineForGate, type WriteGateAssessment } from '../../write-gate.ts';+import { recordWriteGateReceipt } from '../../write-gate-store.ts';+import type { EmptySourceProof } from '../proofs.ts';+import type { GenerationAdapter, GenerationKey, InputState, ItemRow, ProposedItem } from '../contract.ts';+import { markdownItem, pageIdentityHash, pagePreimage, preimageIdentity, readPageRows, type PageRowData } from './page.ts';++export const CHRONICLE_EVENT_KIND = 'chronicle_event';+export const CHRONICLE_RETIRED_BY = 'life-chronicle';+/** Ineligibility reasons that retire a depth page's events with no model call (chronicle/ledger.ts RETIRE_REASONS). */+export const CHRONICLE_INELIGIBLE_REASONS = ['not_chronicle_shaped', 'dream_generated', 'too_short'] as const;++/** The judged depth page; publication re-checks every field. */+export interface ChronicleDepthPin {+ slug: string;+ pageId: number;+ revision: string;+ contentHash: string;+ incarnation: string;+ visibility: Visibility;+}++export function pinDepth(snapshot: PageSnapshot): ChronicleDepthPin {+ return {+ slug: snapshot.page.slug, pageId: Number(snapshot.page.id), revision: snapshot.revision,+ contentHash: String(snapshot.page.content_hash ?? ''), incarnation: snapshot.sourceIncarnation,+ visibility: effectiveVisibility({ kind: 'page', page: snapshot.page }),+ };+}++/** null while the pin holds; otherwise why the generation is superseded. `decisionRequestId`: the writer grant is rechecked too. */+export async function depthPinBroken(tx: BrainEngine, sourceId: string, pin: ChronicleDepthPin, decisionRequestId: string | null): Promise<string | null> {+ const current = await tx.readPageSnapshot(pin.slug, { sourceId });+ if (!current) return 'page_missing';+ if (Number(current.page.id) !== pin.pageId || current.revision !== pin.revision+ || String(current.page.content_hash ?? '') !== pin.contentHash || current.sourceIncarnation !== pin.incarnation+ || effectiveVisibility({ kind: 'page', page: current.page }) !== pin.visibility) return 'superseded';+ return decisionRequestId && !await grantHolds(tx, decisionRequestId) ? 'superseded' : null;+}++async function grantHolds(tx: BrainEngine, decisionRequestId: string): Promise<boolean> {+ const [request] = await tx.executeRaw<import('../../persistence/model.ts').WriteRequest>('SELECT * FROM persistence_requests WHERE id=$1::uuid', [decisionRequestId]);+ if (!request) return false;+ const { authorizeFactsBackstop } = await import('../../persistence/effect-facts.ts');+ const { OperationError } = await import('../../ops/contract.ts');+ try { await authorizeFactsBackstop(tx, request); return true; }+ catch (error) { if (error instanceof OperationError) return false; throw error; }+}++export const chronicleOwnerKey = (depthSlug: string) => `depth:${depthSlug}`;+const depthOf = (key: GenerationKey) => {+ if (!key.ownerKey.startsWith('depth:')) throw new Error(`not a chronicle owner key: ${key.ownerKey}`);+ return key.ownerKey.slice('depth:'.length);+};++/** The input pin of a judged depth page: every field the pin rechecks, so any change refuses activation (`pin_moved`). */+export const depthInputPin = (pin: ChronicleDepthPin) => digest(['chronicle-depth-v1', pin.pageId, pin.revision, pin.contentHash, pin.incarnation, pin.visibility]);++/**+ * What one publication hands the adapter: the writer grant the activation rechecks (null: none, e.g. a retire-only run),+ * and the identity of each event it proposes. An event live at exactly its proposed identity is the extractor's output,+ * so the activation recognises what this publication wrote before the chronicle ledger records its hash.+ */+export interface ChronicleGenerationContext { decisionRequestId: string | null; planned?: Record<string, string> }++/** One proposed event: the markdown its page is written from and the projection row it puts on the depth page. */+export interface ChronicleEventContent {+ markdown: string;+ title: string;+ compiledTruth: string;+ frontmatter: Record<string, unknown>;+ when: string;+ day: string;+ summary: string;+}++export function chronicleEventItem(slug: string, event: ChronicleEventContent): ProposedItem {+ return { key: slug, content: JSON.stringify(event), identityHash: markdownItem(slug, event.markdown).identityHash };+}++function safeDate(value: unknown): Date | null {+ const date = new Date(String(value ?? ''));+ return Number.isNaN(date.getTime()) ? null : date;+}++type EventRow = PageRowData & { content_hash: string | null };+type Projection = { date: string; summary: string; detail: string };++/** The depth page row (a live one first), for its id; null when it was purged. */+async function depthRow(db: BrainEngine, sourceId: string, slug: string): Promise<{ id: number; live: boolean } | null> {+ const [row] = await db.executeRaw<{ id: number; live: boolean }>(+ 'SELECT id, deleted_at IS NULL AS live FROM pages WHERE source_id=$1 AND slug=$2 ORDER BY deleted_at NULLS FIRST, id DESC LIMIT 1', [sourceId, slug]);+ return row ? { id: Number(row.id), live: row.live } : null;+}++/** Every event content hash the chronicle ledger recorded for the depth page `pageId`. */+export async function ownedEventHashes(db: BrainEngine, sourceId: string, pageId: number): Promise<Set<string>> {+ const rows = await db.executeRaw<{ hash: string }>('SELECT DISTINCT unnest(event_hashes) AS hash FROM chronicle_page_state WHERE source_id=$1 AND page_id=$2', [sourceId, pageId]);+ return new Set(rows.map(row => row.hash));+}++/** Slugs of `sourceId` the chronicle ledger records as retired by a generation (the verified half of a retirement stamp). */+async function ledgerRetired(db: BrainEngine, sourceId: string, slugs: readonly string[]): Promise<Set<string>> {+ if (!slugs.length) return new Set();+ const rows = await db.executeRaw<{ item_key: string }>(+ `SELECT DISTINCT i.item_key FROM derived_generation_items i JOIN derived_generations g ON g.id=i.generation_id+ WHERE g.source_id=$1 AND g.kind=$2 AND i.action='retired' AND i.item_key=ANY($3::text[])`, [sourceId, CHRONICLE_EVENT_KIND, [...slugs]]);+ return new Set(rows.map(row => row.item_key));+}++/**+ * Whether a deleted event page is one the extractor retired, verified rather than read off its stamp alone: the stamp+ * names a derived retirement and either the generation ledger recorded it, or (a retirement from before the ledger) its+ * content hash is one the chronicle ledger recorded for its depth page.+ */+export async function verifiedChronicleRetirement(db: BrainEngine, sourceId: string, page: { slug: string; content_hash?: string | null; frontmatter?: Record<string, unknown> | null }): Promise<boolean> {+ const stamp = page.frontmatter?.retired_by;+ if (stamp !== CHRONICLE_RETIRED_BY && stamp !== 'generation-restore') return false;+ if ((await ledgerRetired(db, sourceId, [page.slug])).has(page.slug)) return true;+ const depth = (page.frontmatter?.event as { depth?: unknown } | undefined)?.depth;+ if (stamp !== CHRONICLE_RETIRED_BY || typeof depth !== 'string' || !page.content_hash) return false;+ const row = await depthRow(db, sourceId, depth);+ return row !== null && (await ownedEventHashes(db, sourceId, row.id)).has(String(page.content_hash));+}++async function projectionRows(db: BrainEngine, pageIds: readonly number[]): Promise<Map<number, Projection[]>> {+ const out = new Map<number, Projection[]>();+ if (!pageIds.length) return out;+ const rows = await db.executeRaw<{ event_page_id: number; date: string; summary: string; detail: string | null }>(+ 'SELECT event_page_id, date::text AS date, summary, detail FROM timeline_entries WHERE event_page_id = ANY($1::bigint[]) ORDER BY date', [[...pageIds]]);+ for (const row of rows) out.set(Number(row.event_page_id), [...out.get(Number(row.event_page_id)) ?? [], { date: row.date, summary: row.summary, detail: row.detail ?? '' }]);+ return out;+}++/**+ * The event rows of `itemKeys` and every live event naming the depth page, classified: owned live events and verified+ * retirements are items; an operator-edited or operator-deleted event (or any other page at a proposed slug) is left out.+ */+async function readEventItems(db: BrainEngine, key: GenerationKey, itemKeys: readonly string[], context?: ChronicleGenerationContext): Promise<Map<string, ItemRow>> {+ const depth = depthOf(key);+ const rows = await readPageRows(db, key.sourceId, `p.slug = ANY($2::text[]) OR (p.deleted_at IS NULL AND p.type='event' AND p.frontmatter->'event'->>'depth' = $3+ AND p.frontmatter->>'captured_via' LIKE 'life-chronicle:%')`, [[...itemKeys], depth]);+ if (!rows.length) return new Map();+ const hashes = await db.executeRaw<{ slug: string; content_hash: string | null }>('SELECT slug, content_hash FROM pages WHERE source_id=$1 AND id = ANY($2::bigint[])',+ [key.sourceId, rows.map(row => row.page_id)]);+ const hashOf = new Map(hashes.map(row => [row.slug, row.content_hash]));+ const events: EventRow[] = rows.filter(row => row.type === 'event').map(row => ({ ...row, content_hash: hashOf.get(row.slug) ?? null }));+ const depthPage = await depthRow(db, key.sourceId, depth);+ const owned = depthPage ? await ownedEventHashes(db, key.sourceId, depthPage.id) : new Set<string>();+ const recorded = new Map((await db.executeRaw<{ item_key: string; identity_hash: string }>(+ `SELECT i.item_key, i.identity_hash FROM derived_generation_items i JOIN derived_generations g ON g.id=i.generation_id+ WHERE g.source_id=$1 AND g.kind=$2 AND g.owner_key=$3 AND g.state='live' AND i.action <> 'retired'`, [key.sourceId, CHRONICLE_EVENT_KIND, key.ownerKey]))+ .map(row => [row.item_key, row.identity_hash]));+ const retired = await ledgerRetired(db, key.sourceId, events.filter(row => row.deleted).map(row => row.slug));+ const projections = await projectionRows(db, events.map(row => row.page_id));+ const out = new Map<string, ItemRow>();+ for (const row of events) {+ const fm = row.frontmatter ?? {};+ const origin = String(fm.captured_via ?? '').startsWith('life-chronicle:') && (fm.event as { depth?: unknown } | undefined)?.depth === depth;+ if (!origin) continue;+ if (row.deleted) {+ const stamp = fm.retired_by;+ const verified = retired.has(row.slug) || (stamp === CHRONICLE_RETIRED_BY && owned.has(String(row.content_hash ?? '')));+ if (!verified || (stamp !== CHRONICLE_RETIRED_BY && stamp !== 'generation-restore')) continue;+ } else if (!owned.has(String(row.content_hash ?? '')) && recorded.get(row.slug) !== pageIdentityHash(row) && context?.planned?.[row.slug] !== pageIdentityHash(row)) continue;+ const rowProjections = projections.get(row.page_id) ?? [];+ out.set(row.slug, { key: row.slug, identityHash: pageIdentityHash(row), live: !row.deleted, owned: true, segmented: row.segmented, preimage: () => {+ const page = pagePreimage(row);+ return page.json ? { json: { ...page.json, projection: rowProjections, content_hash: row.content_hash }, bytes: page.bytes } : page;+ } });+ }+ return out;+}++async function recordProjectionFlag(tx: BrainEngine, assessment: WriteGateAssessment, eventPageId: number, date: string, sourceId: string): Promise<void> {+ if (assessment.verdict !== 'flag') return;+ const [entry] = await tx.executeRaw<{ id: number }>('SELECT id FROM timeline_entries WHERE event_page_id=$1 AND date=$2::date', [eventPageId, date]);+ if (entry) await recordWriteGateReceipt(tx, { targetTable: 'timeline_entries', targetId: Number(entry.id), sourceId, assessment });+}++/**+ * Writes one event page (versioned first when it replaces a live one) inside the caller's transaction; returns its id.+ * `contentHash`: a restore keeps the hash the page had, which the chronicle ledger owns (jsonb reorders frontmatter keys,+ * and the content hash is order-sensitive).+ */+async function writeEventPage(tx: BrainEngine, sourceId: string, slug: string, page: { title: string; compiledTruth: string; frontmatter: Record<string, unknown>; when: unknown; contentHash?: string | null }): Promise<number> {+ const live = await tx.readPageSnapshot(slug, { sourceId });+ if (live) await tx.createVersion(slug, { sourceId, preimage: live });+ const written = await tx.putPage(slug, { type: 'event', title: page.title, compiled_truth: page.compiledTruth,+ frontmatter: { type: 'event', ...page.frontmatter }, effective_date: safeDate(page.when), ...(page.contentHash ? { content_hash: page.contentHash } : {}) }, { sourceId });+ return Number(written.id);+}++export const chronicleEventAdapter: GenerationAdapter<ChronicleGenerationContext> = {+ kind: CHRONICLE_EVENT_KIND,+ retiredBy: CHRONICLE_RETIRED_BY,+ modelProduced: true,+ databaseOnly: true,+ lockKeys: (key, itemKeys) => [depthOf(key), ...itemKeys].map(slug => ({ sourceId: key.sourceId, slug })),+ async readInput(engine, key, context) {+ const snapshot = await engine.readPageSnapshot(depthOf(key), { sourceId: key.sourceId });+ if (!snapshot) return null;+ const pin = pinDepth(snapshot);+ const size = pageBodyBytes(snapshot.page);+ const revoked = context?.decisionRequestId ? !await grantHolds(engine, context.decisionRequestId) : false;+ return { pin: revoked ? `${depthInputPin(pin)}:grant_revoked` : depthInputPin(pin), size };+ },+ readItems: (engine, key, itemKeys, context) => readEventItems(engine, key, itemKeys, context),+ // An owned event already carries producer evidence (its content hash is on the chronicle ledger).+ legacyEvidence: async (_engine, _key, rows) => new Set(rows.map(row => row.key)),+ async publishItems(tx, key, items, context) {+ const depth = depthOf(key);+ const derivation = await deriveTrust(tx, [{ table: 'pages', sourceId: key.sourceId, slug: depth }], { channel: 'derive:chronicle' });+ const gateCfg = await derivedGateConfig(tx);+ const items0 = await readEventItems(tx, key, items.map(item => item.key), context);+ await withWriteTrust(tx, derivation.trust, async () => {+ for (const item of items) {+ const event = JSON.parse(item.content) as ChronicleEventContent;+ const existing = await tx.executeRaw('SELECT 1 FROM pages WHERE source_id=$1 AND slug=$2', [key.sourceId, item.key]);+ if (existing.length && !items0.has(item.key)) {+ const { opError } = await import('../../ops/contract.ts');+ throw opError('revision_conflict', `chronicle_superseded: ${item.key} was edited or deleted by an operator; nothing from this generation is published.`,+ 'Nothing to do: the next chronicle cycle judges the depth page again and leaves that event as the operator left it.');+ }+ const pageId = await writeEventPage(tx, key.sourceId, item.key, { title: event.title, compiledTruth: event.compiledTruth, frontmatter: event.frontmatter, when: event.when });+ await lowerDerivedPageIn(tx, derivation, key.sourceId, item.key);+ // #5575 B3: the event's summary lands on the depth page's timeline; a quarantined or rejected one projects nothing.+ const gate = assessTimelineForGate({ summary: event.summary, source: `life-chronicle:event:${item.key}` }, derivedGateInput(derivation.trust), gateCfg);+ if (!timelineRowAllowed(gate)) continue;+ await tx.upsertEventProjection({ depthSlug: depth, eventSlug: item.key, date: event.day, summary: event.summary, sourceId: key.sourceId });+ await recordProjectionFlag(tx, gate, pageId, event.day, key.sourceId);+ }+ });+ },+ async retireItems(tx, key, itemKeys, retiredBy) {+ if (!itemKeys.length) return;+ await tx.executeRaw(`DELETE FROM timeline_entries t USING pages p WHERE p.id=t.event_page_id AND p.source_id=$1 AND p.slug=ANY($2::text[])`, [key.sourceId, [...itemKeys]]);+ await retireDerivedPagesInTransaction(tx, key.sourceId, itemKeys, retiredBy);+ },+ async restoreItem(tx, key, itemKey, preimage) {+ const frontmatter = { ...(preimage.frontmatter as Record<string, unknown>) };+ for (const stamp of RESERVED_RETIREMENT_KEYS) delete frontmatter[stamp];+ delete frontmatter.type;+ const pageId = await writeEventPage(tx, key.sourceId, itemKey, { title: String(preimage.title), compiledTruth: String(preimage.compiled_truth ?? ''), frontmatter,+ when: frontmatter.event_date, contentHash: typeof preimage.content_hash === 'string' ? preimage.content_hash : null });+ const depth = await depthRow(tx, key.sourceId, depthOf(key));+ if (!depth?.live) return;+ for (const projection of (preimage.projection as Projection[] | undefined) ?? []) {+ await tx.executeRaw(`INSERT INTO timeline_entries (page_id, date, source, summary, detail, event_page_id) VALUES ($1, $2::date, $3, $4, $5, $6)+ ON CONFLICT (event_page_id, date) WHERE event_page_id IS NOT NULL DO UPDATE SET summary=EXCLUDED.summary, detail=EXCLUDED.detail, page_id=EXCLUDED.page_id, source=EXCLUDED.source`,+ [depth.id, projection.date, `life-chronicle:event:${itemKey}`, projection.summary, projection.detail, pageId]);+ }+ },+ preimageIdentity,+ async proofHolds(engine, key, proof: EmptySourceProof) {+ if (proof.kind !== 'originIneligible' || !(CHRONICLE_INELIGIBLE_REASONS as readonly string[]).includes(proof.reason)) return false;+ const snapshot = await engine.readPageSnapshot(depthOf(key), { sourceId: key.sourceId });+ if (!snapshot?.page.content_hash) return false;+ const { CHRONICLE_EXTRACTOR_VERSION } = await import('../../chronicle/contract.ts');+ const rows = await engine.executeRaw('SELECT 1 FROM chronicle_page_state WHERE source_id=$1 AND page_id=$2 AND content_hash=$3 AND extractor_version=$4 AND state=$5 AND reason=$6',+ [key.sourceId, Number(snapshot.page.id), snapshot.page.content_hash, CHRONICLE_EXTRACTOR_VERSION, 'skipped', proof.reason]);+ return rows.length > 0;+ },+};++/** The live chronicle generations of `sourceId` whose depth page is gone and that still hold a live event (C-6): their owner keys, oldest first. */+export async function orphanedDepthKeys(db: BrainEngine, sourceId: string, limit: number): Promise<string[]> {+ const rows = await db.executeRaw<{ owner_key: string }>(+ `SELECT g.owner_key FROM derived_generations g+ WHERE g.source_id=$1 AND g.kind=$2 AND g.state='live'+ AND EXISTS (SELECT 1 FROM derived_generation_items i JOIN pages e ON e.source_id=g.source_id AND e.slug=i.item_key AND e.deleted_at IS NULL+ WHERE i.generation_id=g.id AND i.action <> 'retired')+ AND NOT EXISTS (SELECT 1 FROM pages p WHERE p.source_id=g.source_id AND p.slug=substr(g.owner_key, 7) AND p.deleted_at IS NULL)+ ORDER BY g.updated_at, g.id LIMIT $3`, [sourceId, CHRONICLE_EVENT_KIND, limit]);+ return rows.map(row => row.owner_key);+}++export type { InputState };diff --git a/src/core/generations/adapters/index.ts b/src/core/generations/adapters/index.tsindex 7b62612351..75b382aff5 100644--- a/src/core/generations/adapters/index.ts+++ b/src/core/generations/adapters/index.ts@@ -4,10 +4,12 @@*/import type { GenerationAdapter } from '../contract.ts';import { atomGenerationAdapter } from './atoms.ts';+import { chronicleEventAdapter } from './chronicle-events.ts';-const adapters = new Map<string, GenerationAdapter<unknown>>([[atomGenerationAdapter.kind, atomGenerationAdapter as GenerationAdapter<unknown>]]);+const adapters = new Map<string, GenerationAdapter<unknown>>([atomGenerationAdapter, chronicleEventAdapter].map(adapter => [adapter.kind, adapter as GenerationAdapter<unknown>]));-export function generationAdapter(kind: string): GenerationAdapter<unknown> | undefined { return adapters.get(kind); }+/** The adapter of `kind`; a hyphenated spelling (`chronicle-event`) names the same kind. */+export function generationAdapter(kind: string): GenerationAdapter<unknown> | undefined { return adapters.get(kind) ?? adapters.get(kind.replaceAll('-', '_')); }export function generationKinds(): string[] { return [...adapters.keys()]; }/** Registers an adapter for a kind (tests and later PRs). */export function registerGenerationAdapter(adapter: GenerationAdapter<unknown>): void { adapters.set(adapter.kind, adapter); }diff --git a/src/core/generations/contract.ts b/src/core/generations/contract.tsindex b592b0e63b..9a6ccc75f7 100644--- a/src/core/generations/contract.ts+++ b/src/core/generations/contract.ts@@ -37,6 +37,12 @@ export interface GenerationAdapter<C = unknown> {modelProduced: boolean;/** The result is a ranked cut: every item carries a distinct `order`, and a tie (or a missing rank) holds the result (`tie`). */strictOrder?: boolean;+ /**+ * Its items are database-only pages (no canonical file). A managed source then writes the new and changed items as+ * ordinary requests before the activation, and the activation itself retires what the generation dropped (no retire+ * members, nothing left pending); a restore runs as one coordinated request (managed.ts).+ */+ databaseOnly?: boolean;/** Page keys locked before the ledger row, in slug order with the input guard (D7). */lockKeys(key: GenerationKey, itemKeys: readonly string[]): Array<{ sourceId: string; slug: string }>;/** The input as stored now, or null when it is gone. `context` carries an input the database does not hold (a transcript). */@@ -55,4 +61,6 @@ export interface GenerationAdapter<C = unknown> {restoreItem(tx: BrainEngine, key: GenerationKey, itemKey: string, preimage: Record<string, unknown>): Promise<void>;/** The identity hash of a preimage, so a restore can tell whether the item changed since. */preimageIdentity(preimage: Record<string, unknown>): string;+ /** Rechecks an `originIneligible` proof against the input as stored now (proofs.ts); an adapter without it never accepts one. */+ proofHolds?(engine: BrainEngine, key: GenerationKey, proof: import('./proofs.ts').EmptySourceProof): Promise<boolean>;}diff --git a/src/core/generations/managed.ts b/src/core/generations/managed.tsindex b87be37552..026206fdbc 100644--- a/src/core/generations/managed.ts+++ b/src/core/generations/managed.ts@@ -37,8 +37,12 @@ export const GENERATION_ACTIVATE_INTENT = 'managed_generation_activate';export const GENERATION_ACTIVATE_SLUG = '__generation_activate__';export type MemberAction = 'create' | 'overwrite' | 'retire';-/** One member of an activation: `identity` is what it leaves (the retired identity for a retirement), `before` what the target held when planned. */-export interface ActivationMember { slug: string; action: MemberAction; identity: string; before: string | null }+/**+ * One member of an activation: `identity` is what it leaves (the retired identity for a retirement), `before` what the+ * target held when planned. A database-only kind's overwrite carries `preimage`, the before-state its request replaces+ * ahead of the activation.+ */+export interface ActivationMember { slug: string; action: MemberAction; identity: string; before: string | null; preimage?: Record<string, unknown> | null }export interface ActivationPlanIntent {kind: typeof GENERATION_ACTIVATE_INTENT;@@ -100,7 +104,8 @@ export async function planManagedGeneration<C>(engine: BrainEngine, adapter: Genconst retires = plan.kind === 'publish' ? plan.retires : [];const members: Array<ActivationMember & { item?: ProposedItem }> = [...request.items.map(item => { const row = rows.get(item.key);- return row?.live ? { slug: item.key, action: 'overwrite' as const, identity: item.identityHash, before: row.identityHash, item }+ return row?.live ? { slug: item.key, action: 'overwrite' as const, identity: item.identityHash, before: row.identityHash, item,+ ...(adapter.databaseOnly && item.identityHash !== row.identityHash ? { preimage: row.preimage().json } : {}) }: { slug: item.key, action: 'create' as const, identity: item.identityHash, before: null, item }; }),...retires.map(slug => ({ slug, action: 'retire' as const, identity: rows.get(slug)!.identityHash, before: rows.get(slug)!.identityHash })),];@@ -134,7 +139,8 @@ export async function prepareGenerationActivation(engine: BrainEngine, row: Writ{ fix: readFix('Shows the source owner and any write in flight, read-only.', { argv: ['gbrain', 'sources', 'writer', 'status', '--source', row.source_id, '--json'] }) });}const memberKeys = [...new Set([...p.members.map(member => member.slug), ...p.kept])];- return { observedRevision: null, noop: true, additionalPageKeys: adapter.lockKeys(p.key, memberKeys),+ // A database-only kind journals its activation on the input page, bound to the revision it planned against.+ return { observedRevision: typeof p.expected_revision === 'string' ? p.expected_revision : null, noop: true, additionalPageKeys: adapter.lockKeys(p.key, memberKeys),validate: async tx => { await tx.executeRaw('SELECT pg_advisory_xact_lock(hashtext($1)::bigint)', [generationKeyLock(p.key)]); },apply: async tx => {const live = await readLiveGeneration(tx, p.key);@@ -142,22 +148,30 @@ export async function prepareGenerationActivation(engine: BrainEngine, row: Writthrow generationFenced('stale_generation', p.key, `the live generation is ${live?.generation ?? 0}, the producer planned against ${p.expectedGeneration} (activation ${p.activationId})`);}const input = await adapter.readInput(tx, p.key, p.context);- if (p.proof ? !proofHolds(p.proof, input, live?.inputPin) : (p.input && input?.pin !== p.input.pin)) {+ const proven = p.proof?.kind === 'originIneligible' ? await adapter.proofHolds?.(tx, p.key, p.proof) === true && (!p.input || input?.pin === p.input.pin)+ : p.proof ? proofHolds(p.proof, input, live?.inputPin) : !p.input || input?.pin === p.input.pin;+ if (!proven) {throw generationFenced('pin_moved', p.key, `its input changed after the producer read it (activation ${p.activationId})`);}const rows = await adapter.readItems(tx, p.key, memberKeys, p.context);+ // A database-only kind wrote its new and changed items before the activation; it retires inside it.+ const databaseOnly = adapter.databaseOnly === true;const wrong = p.members.filter(member => { const current = rows.get(member.slug);- return !current?.live || current.identityHash !== (member.action === 'create' ? member.identity : member.before); }).map(member => member.slug);+ return !current?.live || current.identityHash !== (member.action === 'create' || (databaseOnly && member.action === 'overwrite') ? member.identity : member.before); })+ .map(member => member.slug);if (wrong.length) throw liveConflict(p.key, wrong);const items: LedgerItem[] = [...p.members.map(member => { const current = rows.get(member.slug)!;+ const pending = databaseOnly ? {} : { pending: true };if (member.action === 'create') return { key: member.slug, identityHash: member.identity, action: 'published' as const };- if (member.action === 'retire') return { key: member.slug, identityHash: member.identity, action: 'retired' as const, preimage: current.preimage(), pending: true };- return member.identity === member.before ? { key: member.slug, identityHash: member.identity, action: 'kept' as const, pending: true }- : { key: member.slug, identityHash: member.identity, action: 'published' as const, preimage: current.preimage(), pending: true }; }),+ if (member.action === 'retire') return { key: member.slug, identityHash: member.identity, action: 'retired' as const, preimage: current.preimage(), ...pending };+ if (member.identity === member.before) return { key: member.slug, identityHash: member.identity, action: 'kept' as const, ...pending };+ const preimage = !databaseOnly ? current.preimage() : member.preimage ? { json: member.preimage, bytes: Buffer.byteLength(JSON.stringify(member.preimage)) } : undefined;+ return { key: member.slug, identityHash: member.identity, action: 'published' as const, ...(preimage ? { preimage } : {}), ...pending }; }),...p.kept.filter(slug => rows.get(slug)?.live).map(slug => ({ key: slug, identityHash: rows.get(slug)!.identityHash, action: 'kept' as const })),...p.carried.filter(slug => live?.items.has(slug)).map(slug => ({ key: slug, identityHash: live!.items.get(slug)!, action: 'kept' as const })),];+ if (databaseOnly) await adapter.retireItems(tx, p.key, p.members.filter(member => member.action === 'retire').map(member => member.slug), p.retiredBy);const activated = await activateGeneration(tx, p.key, live, { operationId: p.operationId, runId: p.runId ?? undefined, input, setHash: p.setHash,completeness: { complete: !p.partial, proof: p.proof?.kind ?? null, managed: true, ...(p.approved ? { approved: p.retiredBy } : {}) },activationId: p.activationId, locator: p.locator }, items);diff --git a/src/core/generations/proofs.ts b/src/core/generations/proofs.tsindex 6a4997d1fe..42a33d9b4f 100644--- a/src/core/generations/proofs.ts+++ b/src/core/generations/proofs.ts@@ -8,7 +8,7 @@ import type { InputState } from './contract.ts';export type EmptySourceProof =/** The input is gone (deleted page, removed transcript) and a live generation was derived from it. */| { kind: 'originGone' }- /** The input no longer qualifies for this kind; only an adapter that can recheck the rule accepts it (none in this release). */+ /** The input no longer qualifies for this kind; only an adapter that rechecks the rule accepts it (`proofHolds`: chronicle events). */| { kind: 'originIneligible'; reason: string }/** A canonical fence was read whole and holds no rows (fence kinds, PR 2). */| { kind: 'fenceParsedEmpty'; pin: string }diff --git a/src/core/generations/publish.ts b/src/core/generations/publish.tsindex f569163724..330e490d27 100644--- a/src/core/generations/publish.ts+++ b/src/core/generations/publish.ts@@ -112,9 +112,9 @@ export async function activateGeneration(tx: BrainEngine, key: GenerationKey, li}/** Rechecks that each item is live at the identity the generation records (Eng-outside r3). */-export async function assertItemsLive(tx: BrainEngine, adapter: GenerationAdapter<unknown>, key: GenerationKey, expected: ReadonlyMap<string, string>): Promise<void> {+export async function assertItemsLive(tx: BrainEngine, adapter: GenerationAdapter<unknown>, key: GenerationKey, expected: ReadonlyMap<string, string>, context?: unknown): Promise<void> {if (!expected.size) return;- const rows = await adapter.readItems(tx, key, [...expected.keys()]);+ const rows = await adapter.readItems(tx, key, [...expected.keys()], context);const wrong = [...expected].filter(([itemKey, identity]) => { const row = rows.get(itemKey); return !row?.live || row.identityHash !== identity; }).map(([itemKey]) => itemKey);if (wrong.length) throw liveConflict(key, wrong);}@@ -220,8 +220,10 @@ export async function planPublication<C>(db: BrainEngine, adapter: GenerationAdaconst unrecorded = [...rows.values()].filter(row => row.owned && row.live && !live?.items.has(row.key) && !named.has(row.key));const evidence = unrecorded.length ? await adapter.legacyEvidence(db, key, unrecorded) : new Set<string>();const valve = await readValve(db, key, request.runId);+ const proven = request.proof?.kind === 'originIneligible' ? await adapter.proofHolds?.(db, key, request.proof) === true+ : request.proof ? proofHolds(request.proof, input, live?.inputPin) : false;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, approvedExpect: request.approved?.expect });+ proofHolds: proven, evidence, valve, release: request.release?.reason, approvedRetire: request.approved?.retire, approvedExpect: request.approved?.expect });return { input, rows, plan };}@@ -269,7 +271,7 @@ export async function publishGeneration<C>(engine: BrainEngine, adapter: Generatawait faultPoint('generation:published', { sourceId: key.sourceId, operation: key.kind });const current = [...plan.puts.map(item => [item.key, item.identityHash] as const), ...[...plan.kept, ...plan.adopted].map(itemKey => [itemKey, rows.get(itemKey)!.identityHash] as const)];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 assertItemsLive(tx, adapter as GenerationAdapter<unknown>, key, new Map(current), request.context);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 });diff --git a/src/core/generations/repair.ts b/src/core/generations/repair.tsindex 259c32d851..aab218d3fa 100644--- a/src/core/generations/repair.ts+++ b/src/core/generations/repair.ts@@ -24,13 +24,15 @@ import { readFix } from '../ops/op-fix.ts';import { maintenanceTransaction } from '../persistence/attribution.ts';import { managedPersistenceEnabled } from '../persistence/ownership.ts';import { assertInlineBody } from '../page-body/page-shape.ts';-import { stableJson } from '../persistence/digest.ts';+import { digest, stableJson } from '../persistence/digest.ts';+import type { PreparedMutation } from '../persistence/coordinator.ts';+import type { WriteRequest } from '../persistence/model.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 { listOrphanCandidates, listPendingMembers, requestUuid } 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;@@ -264,35 +266,75 @@ async function applyEntry(ctx: OperationContext, adapter: GenerationAdapter<unknif (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 } : {}) } };}+ let restored: Awaited<ReturnType<typeof restoreGeneration>>;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` };+ if (!adapter.databaseOnly) {+ 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` };+ }+ restored = await submitManagedRestore(ctx.engine, adapter, key, approved);+ } else {+ restored = await maintenanceTransaction(ctx.engine, tx => restoreGeneration(tx, adapter, key, approved));}- 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;- await lockGeneration(tx, adapter, key, plan0 ? [...plan0.target.keys(), ...plan0.retire] : []);- if (!plan0 || (await readLiveGeneration(tx, key))?.id !== approved.id) return 'changed' as const;- const plan = await planRestore(tx, adapter, key, approved.id, approved.restore_to_id);- if (stableJson([plan.revive, plan.retire, plan.refused]) !== stableJson([approved.revive, approved.retire, approved.refused])) return 'changed' as const;- if (plan.refused.length) return plan.refused;- for (const itemKey of plan.revive) await adapter.restoreItem(tx, key, itemKey, plan.preimages.get(itemKey)!);- await adapter.retireItems(tx, key, plan.retire, 'generation-restore');- await assertItemsLive(tx, adapter, key, plan.target);- const items: LedgerItem[] = [- ...[...plan.target].map(([itemKey, identity]) => ({ key: itemKey, identityHash: identity, action: plan.revive.includes(itemKey) ? 'revived' as const : 'kept' as const,- ...(plan.revive.includes(itemKey) && plan.rows.get(itemKey)?.live ? { preimage: plan.rows.get(itemKey)!.preimage() } : {}) })),- ...plan.retire.map(itemKey => ({ key: itemKey, identityHash: plan.rows.get(itemKey)!.identityHash, action: 'retired' as const, preimage: plan.rows.get(itemKey)!.preimage() })),- ];- const setHash = itemSetHash([...plan.target].map(([itemKey, identityHash]) => ({ key: itemKey, identityHash })));- const activated = await activateGeneration(tx, key, live, { operationId: `restore:${approved.id}:${approved.restore_to_id}`, input: await adapter.readInput(tx, key, undefined),- setHash, completeness: { complete: true, restore: approved.restore_to }, restoreOf: approved.restore_to_id }, items);- return activated;- });if (restored === 'changed') return changed('the live generation or its items changed since the preview');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 } };}+/** The approved restore of one key, under its locks in the caller's transaction: 'changed', the refused keys, or the new generation. */+async function restoreGeneration(tx: BrainEngine, adapter: GenerationAdapter<unknown>, key: GenerationKey, approved: RestoreEntry): Promise<'changed' | string[] | { generation: number }> {+ const live = await readLiveGeneration(tx, key);+ const plan0 = live?.id === approved.id ? await planRestore(tx, adapter, key, approved.id, approved.restore_to_id) : null;+ await lockGeneration(tx, adapter, key, plan0 ? [...plan0.target.keys(), ...plan0.retire] : []);+ if (!plan0 || (await readLiveGeneration(tx, key))?.id !== approved.id) return 'changed' as const;+ const plan = await planRestore(tx, adapter, key, approved.id, approved.restore_to_id);+ if (stableJson([plan.revive, plan.retire, plan.refused]) !== stableJson([approved.revive, approved.retire, approved.refused])) return 'changed' as const;+ if (plan.refused.length) return plan.refused;+ for (const itemKey of plan.revive) await adapter.restoreItem(tx, key, itemKey, plan.preimages.get(itemKey)!);+ await adapter.retireItems(tx, key, plan.retire, 'generation-restore');+ await assertItemsLive(tx, adapter, key, plan.target);+ const items: LedgerItem[] = [+ ...[...plan.target].map(([itemKey, identity]) => ({ key: itemKey, identityHash: identity, action: plan.revive.includes(itemKey) ? 'revived' as const : 'kept' as const,+ ...(plan.revive.includes(itemKey) && plan.rows.get(itemKey)?.live ? { preimage: plan.rows.get(itemKey)!.preimage() } : {}) })),+ ...plan.retire.map(itemKey => ({ key: itemKey, identityHash: plan.rows.get(itemKey)!.identityHash, action: 'retired' as const, preimage: plan.rows.get(itemKey)!.preimage() })),+ ];+ const setHash = itemSetHash([...plan.target].map(([itemKey, identityHash]) => ({ key: itemKey, identityHash })));+ const activated = await activateGeneration(tx, key, live, { operationId: `restore:${approved.id}:${approved.restore_to_id}`, input: await adapter.readInput(tx, key, undefined),+ setHash, completeness: { complete: true, restore: approved.restore_to }, restoreOf: approved.restore_to_id }, items);+ return { generation: activated.generation };+}++export const GENERATION_RESTORE_INTENT = 'managed_generation_restore';++/**+ * GBRA-161 PR 3: a managed source restores a database-only kind (chronicle events) in one coordinated request, journaled+ * on the key's input page and bound to its current revision: the request runs `restoreGeneration` under the item locks.+ */+async function submitManagedRestore(engine: BrainEngine, adapter: GenerationAdapter<unknown>, key: GenerationKey, approved: RestoreEntry): Promise<'changed' | string[] | { generation: number }> {+ const { maintenancePreflight, submitDatabaseMaintenanceIntent } = await import('../persistence/prepared-maintenance.ts');+ const authority = await maintenancePreflight(engine, key.sourceId);+ if (!authority) return [`${approved.owner_key}: the source is no longer managed; preview again`];+ const slug = adapter.lockKeys(key, [])[0]!.slug;+ const input = await engine.readPageSnapshot(slug, { sourceId: key.sourceId, includeDeleted: true });+ const intent = { kind: GENERATION_RESTORE_INTENT, key, approved, expected_revision: input?.revision ?? null, ...(input?.page.deleted_at ? { deleted_page: true } : {}) };+ const receipt = await submitDatabaseMaintenanceIntent(engine, authority, slug, intent, requestUuid(digest(['generation-restore-v1', key, approved.id, approved.restore_to_id, input?.revision ?? null])));+ const result = receipt.restore as 'changed' | string[] | { generation: number } | undefined;+ return result ?? 'changed';+}++/** Preparer of `managed_generation_restore` (trusted local only): the restore of a database-only kind, writing no file. */+export async function prepareGenerationRestore(engine: BrainEngine, row: WriteRequest): Promise<PreparedMutation> {+ const p = row.intent as { kind?: string; key?: GenerationKey; approved?: RestoreEntry; expected_revision?: string | null } | null;+ const adapter = p?.key ? generationAdapter(p.key.kind) : undefined;+ if (!p || p.kind !== GENERATION_RESTORE_INTENT || row.authority.remote || !adapter?.databaseOnly || !p.approved || p.key!.sourceId !== row.source_id) {+ throw opError('permission_denied', 'Unsupported generation restore request.',+ `Request ${row.request_id} in source ${row.source_id} is not a generation restore the trusted local writer admitted, so the coordinator refused it before any change. Restores run only from gbrain repair generations on the brain host.`);+ }+ const key = p.key!;+ const approved = p.approved;+ return { observedRevision: p.expected_revision ?? null, noop: true, additionalPageKeys: adapter.lockKeys(key, [...approved.revive, ...approved.retire]),+ apply: async tx => ({ restore: await restoreGeneration(tx, adapter, key, approved) }) };+}+/*** 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; adiff --git a/src/core/persistence/prepared-maintenance.ts b/src/core/persistence/prepared-maintenance.tsindex 20634a79ab..7af634c479 100644--- a/src/core/persistence/prepared-maintenance.ts+++ b/src/core/persistence/prepared-maintenance.ts@@ -154,8 +154,10 @@ async function submitMaintenance(engine: BrainEngine, authority: MaintenanceAuththrow opError('page_identity_changed', 'The deleted page was restored or purged before maintenance admitted its request.',`Page ${slug} in '${authority.writer.sourceId}' is no longer soft-deleted, so nothing was submitted for it. Run maintenance again to plan from the current pages.`);}- // #5876: only a Life Chronicle event its extractor retired may be restored by a later generation.- if (snapshot?.page.deleted_at && intent.deleted_page !== true && !(intent.restore_retired === true && snapshot.page.frontmatter?.retired_by === 'life-chronicle')) {+ // #5876: only a Life Chronicle event its extractor retired may be restored by a later generation; the stamp counts only+ // when the generation ledger (or the chronicle ledger's owned hashes) verifies it (GBRA-161 PR 3).+ if (snapshot?.page.deleted_at && intent.deleted_page !== true && !(intent.restore_retired === true+ && await (await import('../generations/adapters/chronicle-events.ts')).verifiedChronicleRetirement(engine, authority.writer.sourceId, snapshot.page))) {throw opError('page_not_found', 'Maintenance cannot restore a deleted page.',`Page ${slug} in '${authority.writer.sourceId}' was deleted after maintenance read it, and maintenance never recreates deleted pages; nothing was submitted. Run maintenance again to plan from the current pages.`);}diff --git a/src/core/persistence/service.ts b/src/core/persistence/service.tsindex bb45a0633c..4619103d9a 100644--- a/src/core/persistence/service.ts+++ b/src/core/persistence/service.ts@@ -88,6 +88,7 @@ export async function preparePersistedMutation(e: BrainEngine, row: WriteRequest}if (row.operation === 'submit_job' && String(row.intent?.kind).startsWith('managed_atom_')) return (await import('./atom-maintenance.ts')).prepareManagedAtomMutation(e, row, cfg);if (row.operation === 'submit_job' && row.intent?.kind === 'managed_generation_activate') return (await import('../generations/managed.ts')).prepareGenerationActivation(e, row);+ if (row.operation === 'submit_job' && row.intent?.kind === 'managed_generation_restore') return (await import('../generations/repair.ts')).prepareGenerationRestore(e, row);if (row.operation === 'extract_facts' && String(row.intent?.kind).startsWith('managed_facts_')) return (await import('./facts-prepare.ts')).prepareManagedFactsMutation(e, row, cfg);if (row.operation === 'submit_job' && String(row.intent?.kind).startsWith('connector_v2_')) return (await import('./connector-sync.ts')).prepareConnectorMutation(e, row);if (row.operation === 'submit_job' && String(row.intent?.kind).startsWith('managed_connector_')) return (await import('./connector-sync.ts')).prepareOutdatedConnectorMutation(e, row);diff --git a/test/pathological/g3-chronicle-generations.test.ts b/test/pathological/g3-chronicle-generations.test.tsnew file mode 100644index 0000000000..415e65ee84--- /dev/null+++ b/test/pathological/g3-chronicle-generations.test.ts@@ -0,0 +1,183 @@+/**+ * GBRA-161 PR 3 (C-2, C-3, C-6): Life Chronicle events publish through the generation primitive. A re-judged depth page+ * publishes a new event generation: the events it dropped retire (versioned, `retired_by: life-chronicle`) together+ * with their timeline projection rows, in the activation, and `gbrain repair generations --kind chronicle-event` brings+ * both back. A model `[]` or a shrink below the floor retires nothing; a deleted depth page retires its events only+ * through `originGone`. Managed (database-only, coordinated) and unmanaged brains end in the same state. PGLite;+ * Postgres when DATABASE_URL is set.+ */+import { describe, expect, test } from 'bun:test';+import { mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import type { BrainEngine } from '../../src/core/engine.ts';+import type { OperationContext } from '../../src/core/ops/contract.ts';+import { operationsByName } from '../../src/core/operations.ts';+import { runPhaseChronicle } from '../../src/core/cycle/chronicle.ts';+import type { ChronicleJudgeResult } from '../../src/core/chronicle/extract-events.ts';+import { maintenanceTransaction } from '../../src/core/persistence/attribution.ts';+import { managedPersistenceEnabled } from '../../src/core/persistence/ownership.ts';+import type { GenerationsSelection } from '../../src/core/generations/repair.ts';+import { resolveRepairScope, type RepairResult } from '../../src/core/repair/core.ts';+import { repairRunner } from '../../src/core/repair/registry.ts';+import { _resetWriteThroughCacheForTest } from '../../src/core/write-through.ts';+import { isolatedSharedSkillsEngine } from '../helpers/shared-skills-engine.ts';+import { withEnv } from '../helpers/with-env.ts';+import { managedBrain, pathologicalArms } from './harness.ts';++const today = new Date().toISOString().slice(0, 10);+const BODY = 'Alice and Bob reviewed the launch plan and agreed on the next steps for the beta. '.repeat(3);+const DEPTH = 'meetings/sync';+const ev = (what: string) => ({ when: today, who: ['people/alice-example'], what, kind: 'commitment' });++/** One brain in one mode, driven the way its writers drive it. */+interface World {+ engine: BrainEngine;+ managed: boolean;+ put(slug: string, body: string): Promise<void>;+ remove(slug: string): Promise<void>;+ /** One chronicle phase run whose judge answers `events`. */+ judge(events: string[] | null): Promise<Record<string, unknown>>;+}++async function managedWorld(databaseUrl: string | undefined, run: (world: World) => Promise<void>): Promise<void> {+ await managedBrain(async ({ engine, ctx }) => {+ expect(await managedPersistenceEnabled(engine)).toBe(true);+ const put = async (slug: string, body: string) => {+ const current = await engine.readPageSnapshot(slug, { sourceId: 'default' });+ await operationsByName.put_page.handler(ctx, { slug, content: `---\ntype: meeting\ntitle: Sync\ndate: ${today}\n---\n\n${body}`,+ ...(current ? { expected_revision: current.revision } : {}) });+ };+ const remove = async (slug: string) => {+ const current = (await engine.readPageSnapshot(slug, { sourceId: 'default' }))!;+ await operationsByName.delete_page.handler(ctx as OperationContext, { slug, expected_revision: current.revision });+ };+ await run({ engine, managed: true, put, remove, judge: events => phase(engine, events) });+ }, { databaseUrl });+}++async function unmanagedWorld(databaseUrl: string | undefined, run: (world: World) => Promise<void>): Promise<void> {+ const home = mkdtempSync(join(tmpdir(), 'gbrain-g3-'));+ try {+ await withEnv({ GBRAIN_HOME: home, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined }, async () => {+ _resetWriteThroughCacheForTest();+ const { engine, close } = await isolatedSharedSkillsEngine(databaseUrl);+ try {+ expect(await managedPersistenceEnabled(engine)).toBe(false);+ await engine.setConfig('chronicle.auto_settle_seconds', '0');+ await engine.setConfig('chronicle.activated_at', new Date(Date.now() - 60_000).toISOString());+ const put = async (slug: string, body: string) => {+ await maintenanceTransaction(engine, tx => tx.putPage(slug, { type: 'meeting', title: 'Sync', compiled_truth: body, frontmatter: { date: today } }, { sourceId: 'default' }));+ };+ const remove = async (slug: string) => { await maintenanceTransaction(engine, async tx => { await tx.createVersion(slug, { sourceId: 'default' }); await tx.softDeletePage(slug, { sourceId: 'default' }); }); };+ await run({ engine, managed: false, put, remove, judge: events => phase(engine, events) });+ } finally { await close(); }+ });+ } finally { rmSync(home, { recursive: true, force: true }); }+}++async function phase(engine: BrainEngine, events: string[] | null): Promise<Record<string, unknown>> {+ await engine.executeRaw("UPDATE chronicle_page_state SET next_attempt_at=now()-interval '1 second', decided_at=now()-interval '1 hour' WHERE state='pending'");+ const answer: ChronicleJudgeResult = events === null ? { events: [], failure: 'parse_failed' } : { events: events.map(ev) };+ return (await runPhaseChronicle(engine, { judge: async () => answer })).details as Record<string, unknown>;+}++/** Every event page with its liveness, stamp and the projection rows that point at it. */+async function eventState(engine: BrainEngine) {+ return engine.executeRaw<{ what: string; deleted: boolean; retired_by: string | null; projections: number }>(+ `SELECT p.frontmatter->'event'->>'what' AS what, p.deleted_at IS NOT NULL AS deleted, p.frontmatter->>'retired_by' AS retired_by,+ (SELECT count(*)::int FROM timeline_entries t WHERE t.event_page_id = p.id) AS projections+ FROM pages p WHERE p.type='event' ORDER BY what`);+}++async function repair(engine: BrainEngine, selection: GenerationsSelection, expectHash?: string): Promise<RepairResult> {+ const scope = await resolveRepairScope(engine, 'default');+ const quiet = { info: () => {}, warn: () => {}, error: () => {} };+ return (await repairRunner(engine, { apply: expectHash !== undefined, noEmbed: true, logger: quiet })).run('generations', scope,+ { explicit: true, sourceFlag: 'default', generations: selection, ...(expectHash ? { expect: expectHash } : {}) });+}++const MODES = [['managed', managedWorld], ['unmanaged', unmanagedWorld]] as const;++for (const { backend, databaseUrl } of pathologicalArms()) {+ for (const [mode, world] of MODES) {+ describe(`GBRA-161 PR 3 chronicle generations (${backend}, ${mode})`, () => {+ test('C-2/C-3: a re-judgment that drops an event retires it with its timeline row, and restore brings both back', async () => {+ await world(databaseUrl, async w => {+ await w.put(DEPTH, BODY);+ await w.judge(['Alice agreed to ship the beta', 'Bob owns the launch email']);+ expect(await eventState(w.engine)).toEqual([+ { what: 'Alice agreed to ship the beta', deleted: false, retired_by: null, projections: 1 },+ { what: 'Bob owns the launch email', deleted: false, retired_by: null, projections: 1 }]);+ await w.put(DEPTH, `${BODY} Wording changed.`);+ await w.judge(['Alice agreed to ship the beta']);+ expect(await eventState(w.engine)).toEqual([+ { what: 'Alice agreed to ship the beta', deleted: false, retired_by: null, projections: 1 },+ { what: 'Bob owns the launch email', deleted: true, retired_by: 'life-chronicle', projections: 0 }]);+ const selection: GenerationsSelection = { kind: 'chronicle-event', mode: 'restore', key: `depth:${DEPTH}` };+ const preview = await repair(w.engine, selection);+ expect(preview.listing?.map(row => row.class)).toEqual(['restore']);+ const applied = await repair(w.engine, selection, preview.preview_hash!);+ expect(applied.outcome_items?.map(item => item.outcome)).toEqual(['restored']);+ expect((await eventState(w.engine)).map(e => [e.what, e.deleted, e.projections])).toEqual([+ ['Alice agreed to ship the beta', false, 1], ['Bob owns the launch email', false, 1]]);+ });+ }, 240_000);++ test('a model [] or a shrink below the floor retires nothing', async () => {+ await world(databaseUrl, async w => {+ await w.put(DEPTH, BODY);+ await w.judge(['Alice agreed to ship the beta', 'Bob owns the launch email', 'Carol books the venue', 'Dan drafts the agenda']);+ await w.put(DEPTH, `${BODY} v2.`);+ await w.judge([]);+ expect((await eventState(w.engine)).map(e => e.deleted)).toEqual([false, false, false, false]);+ await w.put(DEPTH, `${BODY} v3.`);+ await w.judge(['Alice agreed to ship the beta']);+ expect((await eventState(w.engine)).map(e => [e.deleted, e.projections])).toEqual([[false, 1], [false, 1], [false, 1], [false, 1]]);+ expect(await w.engine.executeRaw("SELECT held_reason FROM derived_generations WHERE kind='chronicle_event' AND state='held'")).toEqual([{ held_reason: 'shrunk' }]);+ });+ }, 240_000);++ test('C-6: a deleted depth page retires its events through originGone', async () => {+ await world(databaseUrl, async w => {+ await w.put(DEPTH, BODY);+ await w.judge(['Alice agreed to ship the beta']);+ await w.remove(DEPTH);+ await w.judge([]);+ expect(await eventState(w.engine)).toEqual([{ what: 'Alice agreed to ship the beta', deleted: true, retired_by: 'life-chronicle', projections: 0 }]);+ expect(await w.engine.executeRaw(+ "SELECT completeness->>'proof' AS proof FROM derived_generations WHERE kind='chronicle_event' AND state='live'")).toEqual([{ proof: 'originGone' }]);+ });+ }, 240_000);+ });+ }++ test(`managed and unmanaged brains end in the same chronicle state (${backend})`, async () => {+ const script = async (w: World) => {+ await w.put(DEPTH, BODY);+ await w.judge(['Alice agreed to ship the beta', 'Bob owns the launch email', 'Carol books the venue']);+ await w.put(DEPTH, `${BODY} v2.`);+ await w.judge(['Alice agreed to ship the beta', 'Carol books the venue']);+ await w.put(DEPTH, `${BODY} v3.`);+ await w.judge(null);+ await w.put('meetings/other', BODY);+ await w.judge(['Erin signs the lease']);+ await w.remove('meetings/other');+ await w.judge([]);+ return {+ events: await eventState(w.engine),+ ledger: await w.engine.executeRaw(`SELECT owner_key, state, generation, completeness->>'proof' AS proof,+ (SELECT count(*)::int FROM derived_generation_items i WHERE i.generation_id = g.id AND i.action = 'retired') AS retired+ FROM derived_generations g WHERE kind='chronicle_event' ORDER BY owner_key, generation`),+ };+ };+ const states: unknown[] = [];+ for (const [, world] of MODES) await world(databaseUrl, async w => { states.push(await script(w)); });+ expect(states[0]).toEqual(states[1]);+ expect((states[0] as { events: unknown[] }).events).toEqual([+ { what: 'Alice agreed to ship the beta', deleted: false, retired_by: null, projections: 1 },+ { what: 'Bob owns the launch email', deleted: true, retired_by: 'life-chronicle', projections: 0 },+ { what: 'Carol books the venue', deleted: false, retired_by: null, projections: 1 },+ { what: 'Erin signs the lease', deleted: true, retired_by: 'life-chronicle', projections: 0 }]);+ }, 480_000);+}diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txtindex 160be93ff6..707fb63164 100644--- a/test/postgres-unit-arms.txt+++ b/test/postgres-unit-arms.txt@@ -325,6 +325,7 @@ test/pathological/g1-atom-generations.test.tstest/pathological/g1-generation-crash.test.tstest/pathological/g1-generation-probes.test.tstest/pathological/g1-generations.test.ts+test/pathological/g3-chronicle-generations.test.tstest/pathological/h1-zero-yield-atom-reextract.test.tstest/pathological/h2-git-effect-moved-remote.test.tstest/pathological/h3-chronicle-partial-generation.test.ts