Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
chronicle: snapshot-pinned publication, judge failure classes, reconciliation (#5876 T3/T6/T8)
garrytanec2d1ac81dec
diff --git a/src/core/chronicle/extract-events.ts b/src/core/chronicle/extract-events.tsindex 9ed25daca1..1249dfe7cb 100644--- a/src/core/chronicle/extract-events.ts+++ b/src/core/chronicle/extract-events.ts@@ -6,12 +6,12 @@// → write event pages (content-addressed, idempotent) → project to timeline//// The judge is injectable so the deterministic write path is testable without a-// real gateway. The default judge calls the chat gateway; when no gateway is-// configured it returns zero events (auto-emit is a no-op, never an error).+// real gateway. The default judge calls the chat gateway and classifies every+// failure (no provider, provider error, refusal, truncation, unparseable+// output) so none is ever recorded as a genuine no_events answer.import type { BrainEngine } from '../engine.ts';-import { computeContentHash } from '../ingestion/types.ts';-import { maintenancePreflight, publishMaintenancePage } from '../persistence/prepared-maintenance.ts';-import { serializeMarkdown } from '../markdown.ts';+import { maintenancePreflight } from '../persistence/prepared-maintenance.ts';+import { buildChronicleEvent, pinDepth, publishChronicleGeneration, type BuiltChronicleEvent } from './publish.ts';export interface ChronicleEventProposal {when: string; // ISO datetime or YYYY-MM-DD@@ -36,8 +36,11 @@ export interface ChronicleJudgeResult {* - 'truncated': the model hit the output-token cap (stopReason 'length');* the JSON array was cut mid-stream and must not be parsed as complete.* - 'parse_failed': the model returned text but no valid JSON array.+ * - 'chat_error': the provider call failed (#5876 E2: never `no_events`).+ * - 'refused': refusal or content filter.+ * Only a parsed empty array is a genuine no-events answer.*/- failure?: 'truncated' | 'parse_failed' | 'llm_unavailable';+ failure?: 'truncated' | 'parse_failed' | 'llm_unavailable' | 'chat_error' | 'refused';}export type ChronicleJudge = (input: ChronicleJudgeInput) => Promise<ChronicleJudgeResult>;@@ -46,6 +49,8 @@ export interface ChronicleExtractResult {status: 'extracted' | 'no_events' | 'skipped';events_written: number;reason?: string;+ /** Owned events of an earlier generation this run retired. */+ events_retired?: number;}const KIND_VOCAB = new Set([@@ -58,12 +63,6 @@ function normalizeKind(k: string): string {return KIND_VOCAB.has(n) ? n : 'event';}-/** Parse a when string to a Date, or null when unparseable (for effective_date). */-function safeDate(s: string): Date | null {- const d = new Date(s);- return Number.isNaN(d.getTime()) ? null : d;-}-/** Resolve a when value to a stable YYYY-MM-DD at the pinned timezone. */export function isoDay(when: string, tz: string): string {if (/^\d{4}-\d{2}-\d{2}$/.test(when)) return when;@@ -103,10 +102,45 @@ function collectAttendees(fm: Record<string, unknown>): string[] {return [...out];}+export interface ChronicleJudgeContext {+ input: ChronicleJudgeInput;+ effectiveDate: string | null;+ attendees: string[];+}++/** The judge input for one immutable depth snapshot (E5: the judge never re-reads the page). */+export function chronicleJudgeContext(page: { slug: string; type: string; title: string; compiled_truth?: string | null;+ effective_date?: unknown; frontmatter?: Record<string, unknown> | null }): ChronicleJudgeContext {+ const fm = (page.frontmatter ?? {}) as Record<string, unknown>;+ const edRaw = page.effective_date as unknown;+ const effectiveDate: string | null =+ edRaw instanceof Date ? edRaw.toISOString()+ : typeof edRaw === 'string' && edRaw ? edRaw+ : typeof fm.date === 'string' ? fm.date+ : null;+ const attendees = collectAttendees(fm);+ return {+ effectiveDate, attendees,+ input: { slug: page.slug, type: page.type, title: page.title, body: page.compiled_truth ?? '', effectiveDate, attendees },+ };+}++/** Proposals → event pages for one depth snapshot. */+export function buildChronicleEvents(proposals: ChronicleEventProposal[], ctx: ChronicleJudgeContext,+ depth: { slug: string; visibility: 'private' | 'world'; contentHash: string }, tz: string): BuiltChronicleEvent[] {+ return proposals.map((ev) => buildChronicleEvent(ev, {+ depthSlug: depth.slug, attendees: ctx.attendees, effectiveDate: ctx.effectiveDate, tz,+ visibility: depth.visibility, depthHash: depth.contentHash, isoDay, normalizeKind,+ }));+}+/*** Run the chronicle extractor for one depth page. Idempotent: event slugs are* content-addressed (re-run upserts the same pages) and the projection upserts* on (event_page_id, date). A crash between writes re-runs to the same state.+ * The judge reads one snapshot; publication re-validates it and reconciles the+ * previous generation (publish.ts). Direct callers keep this result shape; the+ * `chronicle` phase classifies failures itself (cycle/chronicle.ts).*/export async function runChronicleExtract(engine: BrainEngine,@@ -114,17 +148,9 @@ export async function runChronicleExtract(): Promise<ChronicleExtractResult> {const sourceId = opts.sourceId ?? 'default';const tz = opts.tz ?? 'UTC';- const page = await engine.getPage(opts.slug, { sourceId });- if (!page) return { slug: opts.slug, status: 'skipped', events_written: 0, reason: 'page_not_found' };-- const fm = (page.frontmatter ?? {}) as Record<string, unknown>;- const edRaw = page.effective_date as unknown;- const effectiveDate: string | null =- edRaw instanceof Date ? edRaw.toISOString()- : typeof edRaw === 'string' && edRaw ? edRaw- : typeof fm.date === 'string' ? fm.date- : null;- const attendees = collectAttendees(fm);+ const snapshot = await engine.readPageSnapshot(opts.slug, { sourceId });+ if (!snapshot) return { slug: opts.slug, status: 'skipped', events_written: 0, reason: 'page_not_found' };+ const ctx = chronicleJudgeContext(snapshot.page);// #5523: a managed brain refuses the legacy putPage/projection writers.// Claim maintenance authority before judge spend; null when unmanaged.const maintenance = await maintenancePreflight(engine, sourceId);@@ -132,10 +158,7 @@ export async function runChronicleExtract(const judge = opts.judge ?? defaultJudge(engine);let result: ChronicleJudgeResult;try {- result = await judge({- slug: opts.slug, type: page.type, title: page.title,- body: page.compiled_truth ?? '', effectiveDate, attendees,- });+ result = await judge(ctx.input);} catch (e) {if ((e as Error)?.name === 'AbortError') throw e;return { slug: opts.slug, status: 'skipped', events_written: 0, reason: 'judge_error' };@@ -148,49 +171,21 @@ export async function runChronicleExtract(return { slug: opts.slug, status: 'skipped', events_written: 0, reason: `judge_${result.failure}` };}const proposals = Array.isArray(result?.events) ? result.events : [];- if (proposals.length === 0) return { slug: opts.slug, status: 'no_events', events_written: 0 };// PARSE BARRIER — reject the WHOLE batch on any malformed proposal; no partial writes.if (!proposals.every(isValidProposal)) {return { slug: opts.slug, status: 'skipped', events_written: 0, reason: 'malformed_proposal' };}-- let written = 0;- for (const ev of proposals) {- if (opts.signal?.aborted) { const e = new Error('aborted'); e.name = 'AbortError'; throw e; }- const who = ev.who.length ? ev.who : attendees;- const when = ev.when || effectiveDate || isoDay(new Date(0).toISOString(), tz);- const day = isoDay(when, tz);- const hash = computeContentHash(`${who.join(',')}|${ev.what}|${opts.slug}`).slice(0, 8);- const eventSlug = `life/events/${day}-${hash}`;- const title = ev.what.slice(0, 120);- const compiledTruth = `${ev.what} — see [[${opts.slug}]].`;- const event = { when, who, what: ev.what, where: ev.where ?? null, kind: normalizeKind(ev.kind), depth: opts.slug };- if (maintenance) {- // Database-only: life/events/ is derived machine output. event_date feeds- // the importer's effective_date, matching the legacy column.- const snapshot = await engine.readPageSnapshot(eventSlug, { sourceId, includeDeleted: true });- if (snapshot?.page.deleted_at) continue; // an operator deleted this event; never resurrect it- await publishMaintenancePage(engine, maintenance, eventSlug,- serializeMarkdown({ event, event_date: when, captured_via: 'life-chronicle:auto' }, compiledTruth, '',- { type: 'event', title, tags: [] }),- { expectedRevision: snapshot?.revision ?? null, file: false,- eventProjection: { depth_slug: opts.slug, date: day, summary: ev.what } });- written++;- continue;- }- await engine.putPage(eventSlug, {- type: 'event',- title,- compiled_truth: compiledTruth,- frontmatter: { type: 'event', event, captured_via: 'life-chronicle:auto' },- effective_date: safeDate(when),- }, { sourceId });- await engine.upsertEventProjection({- depthSlug: opts.slug, eventSlug, date: day, summary: ev.what, sourceId,- });- written++;+ const pin = pinDepth(snapshot);+ const generation = await publishChronicleGeneration(engine, {+ sourceId, pin, maintenance, decisionRequestId: null, signal: opts.signal,+ events: buildChronicleEvents(proposals, ctx, { slug: pin.slug, visibility: pin.visibility, contentHash: pin.contentHash }, tz),+ });+ if (generation.superseded) {+ return { slug: opts.slug, status: 'skipped', events_written: generation.written.length, reason: generation.superseded,+ events_retired: generation.retired.length };}- return { slug: opts.slug, status: 'extracted', events_written: written };+ return { slug: opts.slug, status: proposals.length === 0 ? 'no_events' : 'extracted',+ events_written: generation.written.length, events_retired: generation.retired.length };}const JUDGE_SYSTEM = `You segment a meeting/transcript page into discrete timeline EVENTS.@@ -204,7 +199,7 @@ Prefer the page's known date for "when" when the text gives no explicit time. Us*/const DEFAULT_JUDGE_MAX_TOKENS = 4000;-function defaultJudge(engine: BrainEngine): ChronicleJudge {+export function defaultJudge(engine: BrainEngine): ChronicleJudge {return async (input) => {const { isAvailable, chat } = await import('../ai/gateway.ts');// #2608: a missing chat provider used to return a bare `{events: []}` —@@ -233,14 +228,16 @@ function defaultJudge(engine: BrainEngine): ChronicleJudge {}],maxTokens,});- if (res.stopReason === 'refusal' || res.stopReason === 'content_filter') return { events: [] };+ if (res.stopReason === 'refusal' || res.stopReason === 'content_filter') return { events: [], failure: 'refused' };// #2606: output hit the token cap — the JSON array is cut mid-stream.// Do NOT feed it to the parser as if complete; surface the truncation.if (res.stopReason === 'length') return { events: [], failure: 'truncated' };text = res.text;} catch (err) {if ((err as Error)?.name === 'AbortError') throw err;- return { events: [] };+ // A budget refusal is the caller's to classify (no_pricing / cap), not a provider failure.+ if ((err as { tag?: string })?.tag === 'BUDGET_EXHAUSTED') throw err;+ return { events: [], failure: 'chat_error' };}const parsed = parseJudgeJson(text);// #2606: non-empty model text with no parseable JSON array is a parsediff --git a/src/core/chronicle/publish.ts b/src/core/chronicle/publish.tsnew file mode 100644index 0000000000..43a1558758--- /dev/null+++ b/src/core/chronicle/publish.ts@@ -0,0 +1,301 @@+/**+ * Life Chronicle event publication (#5876, E5/E8, C4b/C12).+ *+ * One extraction generation of a depth page (meeting, conversation, calendar+ * page) is published against the immutable snapshot the judge read:+ *+ * - 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.+ * - 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, 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 retires+ * nothing.+ *+ * Managed brains publish through two maintenance intents (database-only);+ * unmanaged brains write directly inside one transaction per event.+ */+import type { BrainEngine } from '../engine.ts';+import type { GBrainConfig } from '../config.ts';+import type { PageSnapshot } from '../page-state/types.ts';+import type { PreparedMutation } from '../persistence/coordinator.ts';+import type { WriteRequest } from '../persistence/model.ts';+import { OperationError } 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 { 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 { ChronicleEventProposal } from './extract-events.ts';++export const CHRONICLE_RETIRED_BY = 'life-chronicle';+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;+ compiledTruth: string;+ frontmatter: Record<string, unknown>;+ when: string;+ day: string;+ summary: string;+}++/** Event identity is content-addressed on (who, what, depth): a re-run upserts the same page. */+export function buildChronicleEvent(ev: ChronicleEventProposal, ctx: {+ depthSlug: string; attendees: string[]; effectiveDate: string | null; tz: string; visibility: Visibility; depthHash: string;+ isoDay: (when: string, tz: string) => string; normalizeKind: (kind: string) => string;+}): BuiltChronicleEvent {+ const who = ev.who.length ? ev.who : ctx.attendees;+ const when = ev.when || ctx.effectiveDate || ctx.isoDay(new Date(0).toISOString(), ctx.tz);+ const day = ctx.isoDay(when, ctx.tz);+ const hash = computeContentHash(`${who.join(',')}|${ev.what}|${ctx.depthSlug}`).slice(0, 8);+ const event = { when, who, what: ev.what, where: ev.where ?? null, kind: ctx.normalizeKind(ev.kind), depth: ctx.depthSlug };+ return {+ slug: `life/events/${day}-${hash}`,+ title: ev.what.slice(0, 120),+ compiledTruth: `${ev.what} — see [[${ctx.depthSlug}]].`,+ frontmatter: { event, event_date: when, captured_via: CHRONICLE_CAPTURED_VIA, visibility: ctx.visibility, chronicle_depth_hash: ctx.depthHash },+ when, day, summary: ev.what,+ };+}++/** 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 {+ if (!existing) return { write: true, restore: false, expectedRevision: null };+ if (existing.page.deleted_at) {+ return existing.page.frontmatter?.retired_by === CHRONICLE_RETIRED_BY+ ? { write: true, restore: true, expectedRevision: existing.revision }+ : { write: false, reason: 'operator_deleted' };+ }+ return owned.has(String(existing.page.content_hash ?? ''))+ ? { write: true, restore: false, expectedRevision: existing.revision }+ : { write: false, reason: 'operator_edited' };+}++function requestIdFor(value: unknown): string {+ const key = digest(value);+ return `${key.slice(0, 8)}-${key.slice(8, 12)}-4${key.slice(13, 16)}-a${key.slice(17, 20)}-${key.slice(20, 32)}`;+}++function supersededError(reason: string): OperationError {+ return new OperationError('revision_conflict', `chronicle_superseded: ${reason}. The depth page, its privacy or its writer grant changed after it was judged; nothing from this generation is published.`);+}++/** 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);+}++export interface ChronicleGenerationResult {+ written: Array<{ slug: string; hash: string }>;+ retired: string[];+ protected: Array<{ slug: string; reason: 'operator_deleted' | 'operator_edited' }>;+ superseded?: string;+}++/**+ * Publish one generation (possibly empty) for a pinned depth page and retire+ * the previous generation's owned events it did not reproduce.+ */+export async function publishChronicleGeneration(engine: BrainEngine, opts: {+ sourceId: string; pin: ChronicleDepthPin; events: BuiltChronicleEvent[]; decisionRequestId: string | null;+ maintenance?: MaintenanceAuthority | null; signal?: AbortSignal;+}): Promise<ChronicleGenerationResult> {+ const { sourceId, pin } = opts;+ 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 };++ for (const ev of opts.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: [] });+ const projection = { depth_slug: pin.slug, date: ev.day, summary: ev.summary };+ 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], event_projection: projection };+ await submitDatabaseMaintenanceIntent(engine, maintenance, ev.slug, intent,+ requestIdFor({ writer: maintenance.writer.principal, slug: ev.slug, intent }));+ } else {+ await engine.transaction(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);+ 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 });+ await tx.upsertEventProjection({ depthSlug: pin.slug, eventSlug: ev.slug, date: ev.day, summary: ev.summary, 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));+ }+ }++ const keep = new Set(opts.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 engine.transaction(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.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' };+ }+ }+ return result;+}++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]);+}++function safeDate(s: string): Date | null {+ const d = new Date(s);+ return Number.isNaN(d.getTime()) ? null : d;+}++interface ChronicleIntent extends Record<string, unknown> {+ kind: string;+ depth: ChronicleDepthPin;+ decision_request_id: string | null;+ owned_hashes: string[];+ restore_retired?: boolean;+ event_projection?: { depth_slug: string; date: string; summary: string };+}++/** Preparer for the two chronicle maintenance intents; validation re-runs under the publication's page locks. */+export async function prepareChronicleMutation(engine: BrainEngine, row: WriteRequest, config: GBrainConfig): Promise<PreparedMutation> {+ const p = row.intent as ChronicleIntent | null;+ if (!p || !p.depth || !Array.isArray(p.owned_hashes) || row.authority.remote) {+ throw new OperationError('invalid_params', 'Unsupported Life Chronicle maintenance intent.');+ }+ const owned = new Set(p.owned_hashes);+ const retire = p.kind === CHRONICLE_RETIRE_INTENT;+ const check = async (tx: BrainEngine) => {+ const reason = await depthPinBroken(tx, row.source_id, p.depth, p.decision_request_id);+ if (reason) throw supersededError(reason);+ const target = await tx.readPageSnapshot(row.slug, { sourceId: row.source_id, includeDeleted: true });+ if (retire) {+ if (!target || target.page.deleted_at || !owned.has(String(target.page.content_hash ?? ''))) throw supersededError('event_changed');+ return;+ }+ const verdict = judgeTarget(target, owned);+ if (!verdict.write) throw supersededError(verdict.reason);+ };+ await check(engine);+ const operation = retire ? 'delete_page' : 'put_page';+ const intent = row.intent!.expected_revision === null ? { ...row.intent, expected_revision: undefined } : row.intent;+ const prepared = await preparePageMutation(engine, { ...row, operation, intent }, config, undefined, undefined, { allowMissingFile: true });+ return { ...prepared, additionalPageKeys: [...prepared.additionalPageKeys ?? [], { sourceId: row.source_id, slug: p.depth.slug }],+ validate: async (tx) => { await prepared.validate?.(tx); await check(tx); },+ apply: async (tx) => {+ const outcome = await prepared.apply(tx);+ if (retire) {+ if (!prepared.noop) await stampRetired(tx, row.source_id, row.slug);+ return { ...outcome, retired_by: CHRONICLE_RETIRED_BY };+ }+ const projection = p.event_projection;+ if (!projection) return outcome;+ const { projected } = await tx.upsertEventProjection({ depthSlug: projection.depth_slug, eventSlug: row.slug,+ date: projection.date, summary: projection.summary, sourceId: row.source_id });+ return { ...outcome, event_projected: projected };+ } };+}diff --git a/src/core/persistence/prepared-maintenance.ts b/src/core/persistence/prepared-maintenance.tsindex 557bd29765..5213864182 100644--- a/src/core/persistence/prepared-maintenance.ts+++ b/src/core/persistence/prepared-maintenance.ts@@ -100,7 +100,10 @@ async function submitMaintenance(engine: BrainEngine, authority: MaintenanceAuthreturn writeResponse(wait.observe(await waitForWrite(engine, prior, loadConfig() ?? { engine: engine.kind }, wait.ms())));}const snapshot = await engine.readPageSnapshot(slug, { sourceId: authority.writer.sourceId, includeDeleted: true });- if (snapshot?.page.deleted_at) throw new OperationError('page_not_found', 'Maintenance cannot restore a deleted page.');+ // #5876: only a Life Chronicle event its extractor retired may be restored by a later generation.+ if (snapshot?.page.deleted_at && !(intent.restore_retired === true && snapshot.page.frontmatter?.retired_by === 'life-chronicle')) {+ throw new OperationError('page_not_found', 'Maintenance cannot restore a deleted page.');+ }if ((snapshot?.revision ?? null) !== intent.expected_revision) throw new OperationError('revision_conflict', 'The maintenance target changed before admission.');const row = await admitWrite(engine, { principal: authority.writer.principal, requestId, operation: 'submit_job',sourceId: authority.writer.sourceId, sourceIncarnation: authority.writer.sourceIncarnation, slug,@@ -311,6 +314,9 @@ export async function prepareMaintenanceMutation(engine: BrainEngine, row: Writeif (row.intent?.kind === 'managed_maintenance_adopt_fact_fence') return prepareFactFenceAdoption(engine, row, config);if (row.intent?.kind === 'managed_maintenance_phantom_merge') return (await import('../cycle/phantom-redirect-managed.ts')).preparePhantomMerge(engine, row, config);if (row.intent?.kind === 'managed_maintenance_phantom_delete') return (await import('../cycle/phantom-redirect-managed.ts')).preparePhantomDelete(engine, row, config);+ if (row.intent?.kind === 'managed_maintenance_chronicle_event' || row.intent?.kind === 'managed_maintenance_chronicle_retire') {+ return (await import('../chronicle/publish.ts')).prepareChronicleMutation(engine, row, config);+ }if (row.intent?.kind === 'managed_maintenance_retire_stale_atoms') return (await import('../repair/stale-atoms.ts')).prepareStaleAtomRetirement(engine, row, config);if (row.intent?.kind !== 'managed_maintenance_consolidate') throw new OperationError('invalid_params', 'Unsupported maintenance request.');const p = row.intent;