Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
GBRA-161 PR 1a (wip): generation ledger, primitive and page/atom adapters
garrytanf0c6bdceb314
diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.mdindex 9a4120afda..4dd48ca70e 100644--- a/docs/guides/error-codes.md+++ b/docs/guides/error-codes.md@@ -1557,6 +1557,40 @@ More: [docs/guides/shared-brain-skills.md#approve-publication-following-and-edit|---|---|---|---|---|---|---|| The eval gate found retrieval regressions or correctness below its thresholds. | The request itself was wrong or no longer matches the brain; nothing was changed. | Correct the request using the message above, then retry. | agent | `repeat the read that failed` | 1 | no |+### generation_fenced++<a id="generation_fenced"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| A derived result was not published because the live generation or its input changed after the producer read them; nothing was written. | The generation primitive (GBRA-161) publishes a result only against the generation and input pin it was computed from. A concurrent run that published first (stale_generation), or an input edited since the read (pin_moved), would otherwise let an older result replace a newer one. | Run the producer again; it reads the current generation and input and recomputes. | agent | `repeat the read that failed` | 11 | yes |++Reasons: `stale_generation`, `pin_moved`.++More: [docs/architecture/generations.md](../../docs/architecture/generations.md)++### generation_held++<a id="generation_held"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| A derived result was recorded as held instead of published, so nothing it would have retired was retired. | A model-produced result at or below the input-relative shrink floor (shrunk), one over generations.max_items (oversize), one over the run window retirement budget (valve), an empty result without a proof the input is really empty (no_proof, fence_absent), repeated failed attempts on one input (attempts_exhausted) or a segmented page the ledger cannot keep a copy of (segmented_unsupported) would retire live items on evidence the primitive does not accept (GBRA-161 D4/D5). | Preview the held set with gbrain repair generations --kind <kind> --mode release-held --held --since <restore_days>d. shrunk, valve and attempts_exhausted publish once with --apply --expect <hash> --yes after the user agrees; oversize needs gbrain config set generations.max_items first; no_proof, fence_absent and segmented_unsupported clear only when the input changes. Run: gbrain doctor --only generation_held --json | agent | `repeat the read that failed` | 1 | no |++Reasons: `shrunk`, `oversize`, `valve`, `no_proof`, `fence_absent`, `attempts_exhausted`, `segmented_unsupported`.++More: [docs/guides/repair.md#generations](../../docs/guides/repair.md#generations)++### generation_live_conflict++<a id="generation_live_conflict"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| A derived generation was not activated because one of its items was not live at the content the publication wrote; nothing was committed. | Activation rechecks every item of the new generation under the key lock; an item another writer changed or deleted in between would make the ledger record a set that is not what the pages say. | Run the producer again; it reads the items as they are now. | agent | `repeat the read that failed` | 11 | yes |++More: [docs/architecture/generations.md](../../docs/architecture/generations.md)+### ghost_mass_delete_refused<a id="ghost_mass_delete_refused"></a>diff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex add785e961..9d1a2f7906 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -289,6 +289,9 @@ export const CODES = {follow_approval_required: { class: 'caller', summary: "Following a brain's shared skills needs the user's explicit follow approval.", docs: 'docs/guides/shared-brain-skills.md#approve-publication-following-and-editing-separately' },forget_requires_owner: { class: 'consent', exit: 3, actor: 'user', summary: "A caller asked to forget a fact (remote forget) or remove a take (takes_remove) more trusted than its own writes, so nothing was removed and the owner was asked instead.", why: "Lower-trust writers cannot overwrite, supersede or forget what the owner confirmed or curated (#5575 guarded supersession). The request became a trust proposal the owner can accept on the brain host; forget's frozen expired meaning is unchanged because nothing expired.", docs: 'docs/guides/error-codes.md#forget_requires_owner', suggestion: 'Do not retry. Tell the user the fact or take needs their decision and give them the command in fix (gbrain trust confirm <proposal_ref> on the brain host).' },reserved_frontmatter_key: { class: 'caller', summary: 'A remote page write tried to add or change a frontmatter key only a trusted derived writer sets (`retired_by`, `retired_at`, `retired_generation`); nothing was written.', why: 'Those keys mark a page a derived writer retired, which the purge holds for 30 days and the repairs treat as machine-owned. A remote caller that could set them could make a page look machine-retired. Carrying the stored value unchanged, or dropping the key, is allowed.', suggestion: 'Remove the key from the frontmatter (or keep the stored value) and write the page again.' },+ generation_fenced: { class: 'retryable', exit: 11, reasons: ['stale_generation', 'pin_moved'], summary: 'A derived result was not published because the live generation or its input changed after the producer read them; nothing was written.', why: 'The generation primitive (GBRA-161) publishes a result only against the generation and input pin it was computed from. A concurrent run that published first (stale_generation), or an input edited since the read (pin_moved), would otherwise let an older result replace a newer one.', docs: 'docs/architecture/generations.md', suggestion: 'Run the producer again; it reads the current generation and input and recomputes.' },+ generation_held: { class: 'caller', reasons: ['shrunk', 'oversize', 'valve', 'no_proof', 'fence_absent', 'attempts_exhausted', 'segmented_unsupported'], summary: 'A derived result was recorded as held instead of published, so nothing it would have retired was retired.', why: 'A model-produced result at or below the input-relative shrink floor (shrunk), one over generations.max_items (oversize), one over the run window retirement budget (valve), an empty result without a proof the input is really empty (no_proof, fence_absent), repeated failed attempts on one input (attempts_exhausted) or a segmented page the ledger cannot keep a copy of (segmented_unsupported) would retire live items on evidence the primitive does not accept (GBRA-161 D4/D5).', docs: 'docs/guides/repair.md#generations', suggestion: 'Preview the held set with gbrain repair generations --kind <kind> --mode release-held --held --since <restore_days>d. shrunk, valve and attempts_exhausted publish once with --apply --expect <hash> --yes after the user agrees; oversize needs gbrain config set generations.max_items first; no_proof, fence_absent and segmented_unsupported clear only when the input changes.', fix: { argv: ['gbrain', 'doctor', '--only', 'generation_held', '--json'], consent: [], actor: 'agent', why: 'Lists the held generations by kind and reason with their preview commands, read-only.', requires_exclusive: false } },+ generation_live_conflict: { class: 'retryable', exit: 11, summary: 'A derived generation was not activated because one of its items was not live at the content the publication wrote; nothing was committed.', why: 'Activation rechecks every item of the new generation under the key lock; an item another writer changed or deleted in between would make the ledger record a set that is not what the pages say.', docs: 'docs/architecture/generations.md', suggestion: 'Run the producer again; it reads the items as they are now.' },frontmatter_slug_conflict: { class: 'caller', summary: "The file's frontmatter `slug:` names a different page than its path does.", why: "The path decides a file's page; a conflicting declared slug would overwrite or fork another page, so the file is refused until one of them changes.", suggestion: 'Remove the `slug:` line or make it match the path, then commit and sync again.' },full_resync_required: { class: 'retryable', summary: "The catalog cursor is invalid or expired." },gate_failed: { class: 'caller', summary: "The eval gate found retrieval regressions or correctness below its thresholds." },diff --git a/src/core/generations/adapters/atoms.ts b/src/core/generations/adapters/atoms.tsnew file mode 100644index 0000000000..851ce4b374--- /dev/null+++ b/src/core/generations/adapters/atoms.ts@@ -0,0 +1,91 @@+/**+ * GBRA-161 PR 1a: the unmanaged atom adapter, the first real producer on the primitive. One owner key per origin+ * (`source_slug:<page>` or `source_path:<transcript>`); the items are the atom pages extract_atoms writes for it. A+ * completed extraction publishes its atoms, their provenance edges and the completion flip (`source_hash`) together with+ * the versioned retirement of the atoms it no longer produced, in one transaction. Managed brains keep the coordinator+ * path (persistence/atom-maintenance.ts) until PR 1b.+ *+ * An atom written before this release is the key's only when the extraction reproduces it or a retained page version+ * written by the extractor shows it unedited; any other atom naming the origin stays live and is reported as protected.+ */+import type { BrainEngine, LinkBatchInput } from '../../engine.ts';+import { ATOM_RETIRED_BY_EXTRACT, retireDerivedPagesInTransaction } from '../../persistence/derived-retirement-hold.ts';+import { deriveTrust, lowerDerivedPageIn } from '../../trust/taint.ts';+import { derivedGateInput } from '../../trust/derived-gate.ts';+import type { GenerationAdapter, GenerationKey, InputState } from '../contract.ts';+import { importPageItem, pageItemRow, pageVersionEvidence, preimageIdentity, preimageMarkdown, readPageRows } from './page.ts';++export const ATOM_KIND = 'atom';++/** What one extraction hands the adapter: the transcript's input (pages are read from the database) and the provenance edges. */+export interface AtomGenerationContext {+ /** A transcript's content hash and size; a page origin is read under the lock instead. */+ transcriptInput?: InputState;+ links?: LinkBatchInput[];+ /** Embedding calls the imports deferred until the activation commits. */+ postCommit?: Array<() => Promise<unknown>>;+ embed?: boolean;+}++type Origin = { field: 'source_slug' | 'source_path'; value: string };++export function atomOwnerKey(origin: { kind: 'page'; slug: string } | { kind: 'transcript'; filePath: string }): string {+ return origin.kind === 'page' ? `source_slug:${origin.slug}` : `source_path:${origin.filePath}`;+}++function originOf(key: GenerationKey): Origin {+ const at = key.ownerKey.indexOf(':');+ const field = key.ownerKey.slice(0, at);+ if (field !== 'source_slug' && field !== 'source_path') throw new Error(`not an atom owner key: ${key.ownerKey}`);+ return { field, value: key.ownerKey.slice(at + 1) };+}++export const atomGenerationAdapter: GenerationAdapter<AtomGenerationContext> = {+ kind: ATOM_KIND,+ retiredBy: ATOM_RETIRED_BY_EXTRACT,+ modelProduced: true,+ lockKeys(key, itemKeys) {+ const origin = originOf(key);+ return [...(origin.field === 'source_slug' ? [origin.value] : []), ...itemKeys].map(slug => ({ sourceId: key.sourceId, slug }));+ },+ async readInput(engine, key, context) {+ const origin = originOf(key);+ if (origin.field === 'source_path') return context?.transcriptInput ?? null;+ const [row] = await engine.executeRaw<{ content_hash: string | null; body_bytes: number | null }>(+ 'SELECT content_hash, body_bytes FROM pages WHERE source_id=$1 AND slug=$2 AND deleted_at IS NULL', [key.sourceId, origin.value]);+ return row?.content_hash ? { pin: row.content_hash, size: Number(row.body_bytes ?? 0) } : null;+ },+ async readItems(engine, key, itemKeys) {+ const origin = originOf(key);+ const rows = await readPageRows(engine, key.sourceId,+ `p.type='atom' AND (p.slug = ANY($2::text[]) OR (p.deleted_at IS NULL AND p.frontmatter->>'${origin.field}' = $3))`, [[...itemKeys], origin.value]);+ return new Map(rows.map(row => [row.slug, pageItemRow(row, row.frontmatter?.[origin.field] === origin.value+ && row.frontmatter?.imported_from == null && row.frontmatter?.managed_extraction !== true)]));+ },+ legacyEvidence: (engine, key, rows) => pageVersionEvidence(engine, key.sourceId, rows, "v.frontmatter->>'extracted_by' LIKE 'extract\\_atoms%'"),+ async publishItems(tx, key, items, context) {+ const origin = originOf(key);+ const taint = await deriveTrust(tx, origin.field === 'source_slug' ? [{ table: 'pages', sourceId: key.sourceId, slug: origin.value }] : [], { channel: 'derive:atoms' });+ for (const item of items) {+ await importPageItem(tx, key.sourceId, item.key, item.content, { writeGate: derivedGateInput(taint.trust),+ ...(context?.embed ? { noEmbed: false, onPostCommitEmbedding: complete => { context.postCommit?.push(complete); } } : {}) });+ await lowerDerivedPageIn(tx, taint, key.sourceId, item.key);+ }+ const written = new Set(items.map(item => item.key));+ const links = (context?.links ?? []).filter(link => written.has(link.to_slug));+ if (links.length) await tx.addLinksBatch(links, { auditSite: 'cycle.extract_atoms.provenance' }); // gbrain-allow-direct-insert: atom-provenance edges derived from the extraction itself (no markdown body to reconcile from)+ },+ async completeItems(tx, key, itemKeys, context) {+ const input = await atomGenerationAdapter.readInput(tx, key, context);+ if (!input || !itemKeys.length) return;+ await tx.executeRaw(`UPDATE pages SET frontmatter = frontmatter || jsonb_build_object('source_hash', $1::text)+ WHERE source_id = $2 AND type = 'atom' AND slug = ANY($3::text[]) AND deleted_at IS NULL`, [input.pin.slice(0, 16), key.sourceId, [...itemKeys]]);+ },+ retireItems: (tx, key, itemKeys, retiredBy) => retireDerivedPagesInTransaction(tx, key.sourceId, itemKeys, retiredBy),+ restoreItem: (tx, key, itemKey, preimage) => importPageItem(tx, key.sourceId, itemKey, preimageMarkdown(preimage)),+ preimageIdentity,+};++export async function readAtomInput(engine: BrainEngine, key: GenerationKey): Promise<InputState | null> {+ return atomGenerationAdapter.readInput(engine, key, undefined);+}diff --git a/src/core/generations/adapters/index.ts b/src/core/generations/adapters/index.tsnew file mode 100644index 0000000000..7b62612351--- /dev/null+++ b/src/core/generations/adapters/index.ts@@ -0,0 +1,13 @@+/**+ * GBRA-161: the generation adapters by ledger kind. The repair command and doctor resolve a kind here; tests register a+ * synthetic adapter (test/helpers/synthetic-generation.ts).+ */+import type { GenerationAdapter } from '../contract.ts';+import { atomGenerationAdapter } from './atoms.ts';++const adapters = new Map<string, GenerationAdapter<unknown>>([[atomGenerationAdapter.kind, atomGenerationAdapter as GenerationAdapter<unknown>]]);++export function generationAdapter(kind: string): GenerationAdapter<unknown> | undefined { return adapters.get(kind); }+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/adapters/page.ts b/src/core/generations/adapters/page.tsnew file mode 100644index 0000000000..8272b0d46c--- /dev/null+++ b/src/core/generations/adapters/page.ts@@ -0,0 +1,96 @@+/**+ * GBRA-161: the page building blocks every page-backed generation adapter shares (atoms and the synthetic test adapter+ * here; concepts, summaries and synthesis output in later PRs). The identity hash covers what a page says (type, title,+ * body, timeline, tags and frontmatter) and leaves out every stamp and provenance key, so a completion flip, an extraction+ * timestamp or a retirement stamp never reads as an edit, while a person's edit always does. Preimages are bounded copies+ * kept in `derived_generation_items`; a segmented page has none (the primitive holds it instead).+ */+import { createHash } from 'node:crypto';+import type { BrainEngine } from '../../engine.ts';+import { importFromContent } from '../../import-file.ts';+import { parseMarkdown, serializeMarkdown } from '../../markdown.ts';+import { PAGE_INLINE_MAX_BYTES } from '../../page-size-policy.ts';+import { stableJson } from '../../persistence/digest.ts';+import { RESERVED_RETIREMENT_KEYS } from '../../persistence/derived-retirement-hold.ts';+import type { PageType } from '../../types.ts';+import type { ItemRow, Preimage, ProposedItem } from '../contract.ts';++/** Frontmatter keys the identity hash ignores: completion, extraction and retirement stamps. */+export const IDENTITY_EXCLUDED_KEYS: ReadonlySet<string> = new Set(['source_hash', 'extracted_at', 'extracted_by', ...RESERVED_RETIREMENT_KEYS]);++/** The largest preimage a generation item keeps (UTF-8 bytes of its JSON); a larger page restores from no copy. */+export const PREIMAGE_MAX_BYTES = PAGE_INLINE_MAX_BYTES;++export interface PageIdentityInput {+ type: string; title: string; compiled_truth: string | null; timeline: string | null; frontmatter: Record<string, unknown> | null; tags: readonly string[];+}++export interface PageRowData extends PageIdentityInput { slug: string; page_id: number; deleted: boolean; segmented: boolean }++function normalizedFrontmatter(frontmatter: Record<string, unknown> | null): Record<string, unknown> {+ const plain = JSON.parse(JSON.stringify(frontmatter ?? {})) as Record<string, unknown>;+ return Object.fromEntries(Object.entries(plain).filter(([key]) => !IDENTITY_EXCLUDED_KEYS.has(key) && key !== 'type' && key !== 'title' && key !== 'tags'));+}++export function pageIdentityHash(page: PageIdentityInput): string {+ return createHash('sha256').update(stableJson({ type: page.type, title: page.title, body: (page.compiled_truth ?? '').trim(), timeline: (page.timeline ?? '').trim(),+ frontmatter: normalizedFrontmatter(page.frontmatter), tags: [...page.tags].sort() })).digest('hex');+}++/** A proposed page item from the markdown the producer would import. */+export function markdownItem(slug: string, content: string): ProposedItem {+ const parsed = parseMarkdown(content, slug);+ return { key: slug, content, identityHash: pageIdentityHash({ type: parsed.type, title: parsed.title, compiled_truth: parsed.compiled_truth,+ timeline: parsed.timeline, frontmatter: parsed.frontmatter, tags: parsed.tags }) };+}++/** Rows of `sourceId` matching `where` (a constant predicate over alias `p`; parameters start at $2), deleted rows included. */+export async function readPageRows(engine: BrainEngine, sourceId: string, where: string, params: readonly unknown[]): Promise<PageRowData[]> {+ const rows = await engine.executeRaw<PageRowData & { tags: string[] | null }>(+ `SELECT p.id AS page_id, p.slug, p.type, p.title, p.compiled_truth, p.timeline, p.frontmatter, p.deleted_at IS NOT NULL AS deleted,+ p.body_storage = 'segmented' AS segmented, COALESCE((SELECT jsonb_agg(t.tag ORDER BY t.tag) FROM tags t WHERE t.page_id = p.id), '[]'::jsonb) AS tags+ FROM pages p WHERE p.source_id = $1 AND (${where}) ORDER BY p.slug`, [sourceId, ...params]);+ return rows.map(row => ({ ...row, page_id: Number(row.page_id), tags: row.tags ?? [] }));+}++export function pagePreimage(row: PageRowData): Preimage {+ const json = { slug: row.slug, type: row.type, title: row.title, compiled_truth: row.compiled_truth, timeline: row.timeline ?? '',+ frontmatter: row.frontmatter ?? {}, tags: [...row.tags], deleted: row.deleted };+ const bytes = Buffer.byteLength(JSON.stringify(json));+ return row.segmented || row.compiled_truth === null || bytes > PREIMAGE_MAX_BYTES ? { json: null, bytes } : { json, bytes };+}++export function pageItemRow(row: PageRowData, owned: boolean): ItemRow {+ return { key: row.slug, identityHash: pageIdentityHash(row), live: !row.deleted, owned, segmented: row.segmented, preimage: () => pagePreimage(row) };+}++export function preimageIdentity(preimage: Record<string, unknown>): string {+ return pageIdentityHash({ type: String(preimage.type), title: String(preimage.title), compiled_truth: preimage.compiled_truth as string,+ timeline: (preimage.timeline as string) ?? '', frontmatter: (preimage.frontmatter as Record<string, unknown>) ?? {}, tags: (preimage.tags as string[]) ?? [] });+}++/** The markdown a preimage restores, without retirement stamps. */+export function preimageMarkdown(preimage: Record<string, unknown>): string {+ const frontmatter = { ...(preimage.frontmatter as Record<string, unknown>) };+ for (const key of RESERVED_RETIREMENT_KEYS) delete frontmatter[key];+ return serializeMarkdown(frontmatter, String(preimage.compiled_truth ?? ''), String(preimage.timeline ?? ''),+ { type: String(preimage.type) as PageType, title: String(preimage.title), tags: (preimage.tags as string[]) ?? [] });+}++/** Writes one page item inside the activation transaction; embeddings are left to the embedding backfill. */+export async function importPageItem(tx: BrainEngine, sourceId: string, slug: string, content: string,+ opts: Partial<Parameters<typeof importFromContent>[3]> = {}): Promise<void> {+ await importFromContent(tx, slug, content, { ...opts, sourceId, preserveGateMarkers: true, noEmbed: true });+}++/** Rows whose retained page version was written by the producer (`producer`: a predicate over version alias `v`) at the row's identity. */+export async function pageVersionEvidence(engine: BrainEngine, sourceId: string, rows: readonly ItemRow[], producer: string): Promise<Set<string>> {+ if (!rows.length) return new Set();+ const versions = await engine.executeRaw<PageIdentityInput & { slug: string; tags: string[] | null }>(+ `SELECT p.slug, v.type, v.title, v.compiled_truth, v.timeline, v.frontmatter, v.tags+ FROM page_versions v JOIN pages p ON p.id = v.page_id+ WHERE p.source_id = $1 AND p.slug = ANY($2::text[]) AND v.compiled_truth IS NOT NULL AND v.title IS NOT NULL AND (${producer})`,+ [sourceId, rows.map(row => row.key)]);+ const wanted = new Map(rows.map(row => [row.key, row.identityHash]));+ return new Set(versions.filter(v => pageIdentityHash({ ...v, tags: v.tags ?? [] }) === wanted.get(v.slug)).map(v => v.slug));+}diff --git a/src/core/generations/config.ts b/src/core/generations/config.tsnew file mode 100644index 0000000000..89d61faa14--- /dev/null+++ b/src/core/generations/config.ts@@ -0,0 +1,60 @@+/**+ * GBRA-161: the generation primitive's settings, their bounds and the one reader. `gbrain config set` refuses a value+ * out of range with the shared bound-refusal shape; a stored value that fails the bound (written before validation, or+ * by hand) reads as the default here, so a typo never widens a limit.+ */+import type { BrainEngine } from '../engine.ts';+import { digest } from '../persistence/digest.ts';++interface Bound { key: string; min: number; max: number; fallback: number; integer: boolean; example: string }++export const GENERATION_BOUNDS = {+ restoreDays: { key: 'generations.restore_days', min: 3, max: 365, fallback: 30, integer: true, example: '30' },+ shrinkFloor: { key: 'generations.shrink_floor', min: 0.05, max: 1, fallback: 0.5, integer: false, example: '0.5' },+ maxItems: { key: 'generations.max_items', min: 8, max: 1024, fallback: 64, integer: true, example: '64' },+ valveMaxPerRun: { key: 'generations.valve.max_per_run', min: 1, max: 100_000, fallback: 500, integer: true, example: '500' },+ valveMaxRatio: { key: 'generations.valve.max_ratio', min: 0.01, max: 1, fallback: 0.5, integer: false, example: '0.5' },+} as const satisfies Record<string, Bound>;++export interface GenerationsConfig { restoreDays: number; shrinkFloor: number; maxItems: number; valveMaxPerRun: number; valveMaxRatio: number }++/** The refusal for a value outside its bound, or null when `key` is not a generations key or the value fits. */+export function generationsConfigRefusal(key: string, value: string): { message: string; example: string } | null {+ const bound = Object.values(GENERATION_BOUNDS).find(entry => entry.key === key);+ if (!bound) return null;+ return parseBound(bound, value) === null+ ? { message: `${key} must be ${bound.integer ? 'an integer' : 'a number'} from ${bound.min} to ${bound.max} (got "${value}"); nothing was written.`, example: bound.example }+ : null;+}++function parseBound(bound: Bound, raw: string | null | undefined): number | null {+ const text = raw?.trim() ?? '';+ if (!(bound.integer ? /^\d+$/ : /^\d+(\.\d+)?$/).test(text)) return null;+ const value = Number(text);+ return value >= bound.min && value <= bound.max ? value : null;+}++/** Last value read, so synchronous listings (repair notices, the remediation plan) print the configured restore window. */+let restoreDaysSeen: number = GENERATION_BOUNDS.restoreDays.fallback;+export function restoreDaysHint(): number { return restoreDaysSeen; }++/** Reads the five settings; a failed read keeps the default for that setting, the same as an out-of-range value. */+export async function readGenerationsConfig(engine: Pick<BrainEngine, 'getConfig'>): Promise<GenerationsConfig> {+ const read = async (bound: Bound) => parseBound(bound, await engine.getConfig(bound.key).catch(() => null)) ?? bound.fallback;+ const config = { restoreDays: await read(GENERATION_BOUNDS.restoreDays), shrinkFloor: await read(GENERATION_BOUNDS.shrinkFloor),+ maxItems: await read(GENERATION_BOUNDS.maxItems), valveMaxPerRun: await read(GENERATION_BOUNDS.valveMaxPerRun), valveMaxRatio: await read(GENERATION_BOUNDS.valveMaxRatio) };+ restoreDaysSeen = config.restoreDays;+ return config;+}++/** The policy a held row binds: a changed floor, cap or valve setting lets an unchanged input be computed again. */+export function policyHash(config: GenerationsConfig): string {+ return digest(['generation-policy-v1', config.shrinkFloor, config.maxItems, config.valveMaxPerRun, config.valveMaxRatio]).slice(0, 16);+}++/**+ * SQL for the configured restore window in days, read inside the statement so the constant purge predicates+ * (derived-retirement-hold.ts) need no parameter: a missing or out-of-range stored value reads as the default.+ */+export const RESTORE_DAYS_SQL = `(SELECT COALESCE(MAX(CASE WHEN c.value ~ '^[0-9]{1,3}$' THEN CASE WHEN c.value::int BETWEEN ${GENERATION_BOUNDS.restoreDays.min} AND ${GENERATION_BOUNDS.restoreDays.max}+ THEN c.value::int END END), ${GENERATION_BOUNDS.restoreDays.fallback}) FROM config c WHERE c.key = '${GENERATION_BOUNDS.restoreDays.key}')`;diff --git a/src/core/generations/contract.ts b/src/core/generations/contract.tsnew file mode 100644index 0000000000..6ae9b3abb3--- /dev/null+++ b/src/core/generations/contract.ts@@ -0,0 +1,55 @@+/**+ * GBRA-161: the contract between the generation primitive (publish.ts) and the adapters that own one ledger kind each.+ * The primitive decides when a result may replace the live generation; the adapter knows how its items are read, written,+ * retired and restored. Items are identified by key (a page slug for page kinds) and compared by identity hash, a digest+ * of what the item says that leaves out completion, extraction and retirement stamps (adapters/page.ts).+ */+import type { BrainEngine } from '../engine.ts';+import type { DerivedRetiredBy } from '../persistence/derived-retirement-hold.ts';++/** One derived set: the items of one kind a single input owns in one source. */+export interface GenerationKey { kind: string; sourceId: string; ownerKey: string }++export const HELD_REASONS = ['shrunk', 'oversize', 'valve', 'no_proof', 'fence_absent', 'attempts_exhausted', 'segmented_unsupported'] as const;+export type HeldReason = typeof HELD_REASONS[number];++/** A held result the operator may publish once with `gbrain repair generations --mode release-held`. */+export const RELEASABLE_HELD_REASONS: ReadonlySet<HeldReason> = new Set(['shrunk', 'valve', 'attempts_exhausted', 'oversize']);++/** One item of a proposed generation: its key, the content the adapter writes, and its identity hash. */+export interface ProposedItem { key: string; content: string; identityHash: string }++/** A bounded copy of an item's stored state, kept on the ledger so a restore can bring it back (null: too large or segmented). */+export interface Preimage { json: Record<string, unknown> | null; bytes: number }++/** An item as stored now. `owned`: the row names this key's input as its origin (and is not imported or managed). */+export interface ItemRow { key: string; identityHash: string; live: boolean; owned: boolean; segmented: boolean; preimage(): Preimage }++/** The input a generation was derived from: a pin that changes whenever the input does, and its size in bytes. */+export interface InputState { pin: string; size: number }++export interface GenerationAdapter<C = unknown> {+ kind: string;+ /** The `retired_by` stamp the adapter's retirements carry. */+ retiredBy: DerivedRetiredBy;+ /** Model-produced kinds take the input-relative shrink floor; canonical projections do not. */+ modelProduced: 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). */+ readInput(engine: BrainEngine, key: GenerationKey, context: C | undefined): Promise<InputState | null>;+ /** Rows of the named keys (deleted rows included) and of every live row the key owns by its origin metadata. */+ readItems(engine: BrainEngine, key: GenerationKey, itemKeys: readonly string[]): Promise<Map<string, ItemRow>>;+ /** Of these unrecorded owned rows, the keys whose retained producer evidence shows them unedited at their identity. */+ legacyEvidence(engine: BrainEngine, key: GenerationKey, rows: readonly ItemRow[]): Promise<Set<string>>;+ /** Writes new and changed items inside the activation transaction. */+ publishItems(tx: BrainEngine, key: GenerationKey, items: readonly ProposedItem[], context: C | undefined): Promise<void>;+ /** Marks the generation's items complete (an atom's `source_hash` flip); skipped for a partial generation. */+ completeItems?(tx: BrainEngine, key: GenerationKey, itemKeys: readonly string[], context: C | undefined): Promise<void>;+ /** Versions, soft-deletes and stamps items the new generation no longer has. */+ retireItems(tx: BrainEngine, key: GenerationKey, itemKeys: readonly string[], retiredBy: DerivedRetiredBy): Promise<void>;+ /** Writes a preimage back (reviving a retired item, or returning an overwritten one to its earlier state). */+ 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;+}diff --git a/src/core/generations/plan.ts b/src/core/generations/plan.tsnew file mode 100644index 0000000000..ff9a208ee1--- /dev/null+++ b/src/core/generations/plan.ts@@ -0,0 +1,80 @@+/**+ * GBRA-161: the pure decision of one publication (no I/O). Given the live generation, the items as stored, the proposed+ * result and the settings, it returns what to write, retire and keep, or why the result is held (D4). publish.ts runs+ * it under the key lock and applies the answer in the activation transaction.+ *+ * Ownership: an item is the key's when the live generation recorded it, or when it carries the key's origin metadata and+ * either the result reproduces it or retained producer evidence shows it unedited (`evidence`, legacy adoption). Any other+ * live row with the key's origin metadata is protected: never retired, listed in the outcome.+ */+import type { GenerationsConfig } from './config.ts';+import type { HeldReason, InputState, ItemRow, ProposedItem } from './contract.ts';++/** The live generation as the ledger records it: owned item keys and their identity hashes at that generation. */+export interface LiveGeneration { id: number; generation: number; inputPin: string | null; inputSize: number | null; items: Map<string, string> }++/** Below this many retirements in one run window the ratio half of the valve does not apply (a small brain retiring a few items). */+export const VALVE_RATIO_MIN = 25;++export interface PlanInput {+ live: LiveGeneration | null;+ rows: ReadonlyMap<string, ItemRow>;+ proposal: readonly ProposedItem[];+ /** For an empty result: whether its empty-source proof held under the lock. */+ proofHolds: boolean;+ input: InputState | null;+ config: GenerationsConfig;+ modelProduced: boolean;+ /** A partial result (input cut short): writes its items, retires nothing. */+ additive: boolean;+ evidence: ReadonlySet<string>;+ valve: { windowRetired: number; ownedTotal: number };+ /** The held reason an operator release overrides (`shrunk`, `valve`, `attempts_exhausted`). */+ release?: HeldReason;+}++export type Plan =+ | { kind: 'publish'; puts: ProposedItem[]; kept: string[]; adopted: string[]; retires: string[]; carried: string[]; protectedKeys: string[] }+ | { kind: 'held'; reason: HeldReason; context: Record<string, unknown> }+ | { kind: 'unchanged'; protectedKeys: string[] };++export function planGeneration(input: PlanInput): Plan {+ const { live, rows, proposal, config } = input;+ const proposed = new Map(proposal.map(item => [item.key, item]));+ const recorded = new Set([...(live?.items.keys() ?? [])].filter(key => rows.get(key)?.live));+ const unrecorded = [...rows.values()].filter(row => row.owned && row.live && !recorded.has(row.key));+ const adoptable = new Set(unrecorded.filter(row => proposed.has(row.key) || input.evidence.has(row.key)).map(row => row.key));+ const protectedKeys = unrecorded.filter(row => !adoptable.has(row.key)).map(row => row.key).sort();+ const ownedBefore = new Set([...recorded, ...adoptable]);+ const retires = input.additive ? [] : [...ownedBefore].filter(key => !proposed.has(key)).sort();+ const puts = proposal.filter(item => { const row = rows.get(item.key); return !row || !row.live || row.identityHash !== item.identityHash; });+ const same = proposal.filter(item => !puts.includes(item)).map(item => item.key);+ const kept = same.filter(key => recorded.has(key));+ const adopted = same.filter(key => !recorded.has(key));+ const carried = input.additive ? [...recorded].filter(key => !proposed.has(key)).sort() : [];+ const ratio = live?.inputSize && input.input ? Math.min(1, input.input.size / live.inputSize) : 1;+ const context = { owned: ownedBefore.size, result: proposal.length, puts: puts.length, retires: retires.length, floor: config.shrinkFloor,+ input_ratio: Number(ratio.toFixed(4)), input_size: input.input?.size ?? null, live_input_size: live?.inputSize ?? null, protected: protectedKeys.length };+ const held = (reason: HeldReason, extra: Record<string, unknown> = {}): Plan => ({ kind: 'held', reason, context: { ...context, ...extra } });++ const touched = [...puts.map(item => item.key), ...retires];+ if (touched.some(key => rows.get(key)?.segmented)) return held('segmented_unsupported');+ if (!proposal.length && retires.length && !input.proofHolds) return held('no_proof');+ if (Math.max(puts.length, retires.length) > config.maxItems) return held('oversize', { max_items: config.maxItems });+ const shrinkReleased = input.release === 'shrunk' || input.release === 'attempts_exhausted';+ if (input.modelProduced && !input.additive && !shrinkReleased && proposal.length && retires.length && proposal.length < ownedBefore.size+ && proposal.length <= config.shrinkFloor * ownedBefore.size * ratio) return held('shrunk');+ if (retires.length) {+ const total = (input.release === 'valve' ? 0 : input.valve.windowRetired) + retires.length;+ const ratioLimit = config.valveMaxRatio * Math.max(input.valve.ownedTotal, ownedBefore.size);+ if (total > config.valveMaxPerRun || (input.release !== 'valve' && total > VALVE_RATIO_MIN && total > ratioLimit)) {+ return held('valve', { window_retired: input.valve.windowRetired, max_per_run: config.valveMaxPerRun, max_ratio: config.valveMaxRatio, owned_total: input.valve.ownedTotal });+ }+ }+ if (live && !puts.length && !retires.length && !adopted.length && !carried.length && sameKeys(recorded, proposed)) return { kind: 'unchanged', protectedKeys };+ return { kind: 'publish', puts, kept, adopted, retires, carried, protectedKeys };+}++function sameKeys(a: ReadonlySet<string>, b: ReadonlyMap<string, unknown>): boolean {+ return a.size === b.size && [...a].every(key => b.has(key));+}diff --git a/src/core/generations/proofs.ts b/src/core/generations/proofs.tsnew file mode 100644index 0000000000..6a4997d1fe--- /dev/null+++ b/src/core/generations/proofs.ts@@ -0,0 +1,30 @@+/**+ * GBRA-161 D4: the only ways an empty result may retire a live generation. A model returning nothing, or a parse that+ * produced no items, is never evidence that the input is empty; each proof below is rechecked under the key lock against+ * the input as stored and the live generation's pin, and a proof that does not hold publishes nothing (held `no_proof`).+ */+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). */+ | { kind: 'originIneligible'; reason: string }+ /** A canonical fence was read whole and holds no rows (fence kinds, PR 2). */+ | { kind: 'fenceParsedEmpty'; pin: string }+ /** The input changed since the live generation, and the change at `pin` committed the removal of every item. */+ | { kind: 'committedRemoval'; pin: string };++export const originGone = (): EmptySourceProof => ({ kind: 'originGone' });+export const fenceParsedEmpty = (pin: string): EmptySourceProof => ({ kind: 'fenceParsedEmpty', pin });+export const committedRemoval = (pin: string): EmptySourceProof => ({ kind: 'committedRemoval', pin });++/** Whether `proof` holds for the input as stored now (`input`) and the live generation's pin (`livePin`, null: no live generation). */+export function proofHolds(proof: EmptySourceProof, input: InputState | null, livePin: string | null | undefined, fenceKind = false): boolean {+ switch (proof.kind) {+ case 'originGone': return input === null && typeof livePin === 'string';+ case 'committedRemoval': return input !== null && input.pin === proof.pin && typeof livePin === 'string' && livePin !== proof.pin;+ case 'fenceParsedEmpty': return fenceKind && input !== null && input.pin === proof.pin;+ case 'originIneligible': return false;+ }+}diff --git a/src/core/generations/publish.ts b/src/core/generations/publish.tsnew file mode 100644index 0000000000..432a585850--- /dev/null+++ b/src/core/generations/publish.ts@@ -0,0 +1,218 @@+/**+ * GBRA-161 PR 1a: the generation primitive. `publishGeneration` is the one way a derived producer replaces the set of+ * items one input owns (docs/architecture/generations.md). Under the item page locks and the generation key lock it+ * replays an identical operation, fences a stale producer (`generation_fenced`), plans the result (plan.ts), and either+ * records it as held (`generation_held`, nothing retired) or, in one attributed transaction, writes the new and changed+ * items, marks them complete, rechecks each at its identity hash, versions and retires what the new generation no longer+ * has with bounded preimages on the ledger, supersedes the previous generation and activates the new one. Nothing is+ * retired except in the transaction that makes a complete successor live (D2, unmanaged path). Managed sources keep+ * their coordinator path until PR 1b.+ */+import type { BrainEngine } from '../engine.ts';+import { opError } from '../ops/contract.ts';+import { maintenanceTransaction } from '../persistence/attribution.ts';+import { digest, jsonBytes } from '../persistence/digest.ts';+import { faultPoint } from '../persistence/fault-points.ts';+import { LATEST_VERSION } from '../migrate.ts';+import { policyHash, readGenerationsConfig, type GenerationsConfig } from './config.ts';+import type { GenerationAdapter, GenerationKey, HeldReason, InputState, Preimage, ProposedItem } from './contract.ts';+import { planGeneration, type LiveGeneration } from './plan.ts';+import { proofHolds, type EmptySourceProof } from './proofs.ts';++/** The largest held proposal the ledger keeps (UTF-8 bytes of its JSON); a larger one is held without a releasable copy. */+export const HELD_PROPOSAL_MAX_BYTES = 4 * 1024 * 1024;++export interface PublishRequest<C = unknown> {+ key: GenerationKey;+ items: readonly ProposedItem[];+ /** For an empty result: the proof that the input really holds nothing (proofs.ts). */+ proof?: EmptySourceProof;+ /** The input the producer read; activation refuses when it moved (`pin_moved`). Omit for an `originGone` proof. */+ input?: InputState | null;+ /** The live generation number the producer planned against (0: none); a different live generation refuses (`stale_generation`). */+ expectedGeneration?: number;+ runId?: string;+ /** The input was cut short: write the items, retire nothing, leave them incomplete. */+ partial?: boolean;+ context?: C;+ /** An operator release of this held row (repair generations --mode release-held). */+ release?: { holdId: string; reason: HeldReason };+}++export type PublishOutcome =+ | { state: 'published'; generationId: number; generation: number; puts: string[]; kept: string[]; adopted: string[]; retired: string[]; protected: string[] }+ | { state: 'unchanged'; generation: number | null; retired: string[]; protected: string[] }+ | { state: 'held'; reason: HeldReason; holdId: string; context: Record<string, unknown> };++/** Item-set hash of a result: what an identical replay and a held row bind. */+export function itemSetHash(items: readonly Pick<ProposedItem, 'key' | 'identityHash'>[]): string {+ return digest(['generation-items-v1', [...items].map(item => [item.key, item.identityHash]).sort((a, b) => a[0]!.localeCompare(b[0]!))]);+}++const keyLock = (key: GenerationKey) => `gbrain:generation:${key.kind}:${key.sourceId}:${key.ownerKey}`;++/** Takes the item page locks (slug order) and then the generation key lock (D7). */+export async function lockGeneration(tx: BrainEngine, adapter: GenerationAdapter<unknown>, key: GenerationKey, itemKeys: readonly string[]): Promise<void> {+ const pages = adapter.lockKeys(key, itemKeys).sort((a, b) => a.slug.localeCompare(b.slug));+ if (pages.length) await tx.lockPageKeys(pages);+ await tx.executeRaw('SELECT pg_advisory_xact_lock(hashtext($1)::bigint)', [keyLock(key)]);+}++/** The live generation of `key` with its owned items, or null. */+export async function readLiveGeneration(db: BrainEngine, key: GenerationKey): Promise<LiveGeneration | null> {+ const [row] = await db.executeRaw<{ id: number; generation: number; input_pin: string | null; input_size: number | null }>(+ `SELECT id, generation, input_pin, input_size FROM derived_generations WHERE source_id=$1 AND kind=$2 AND owner_key=$3 AND state='live'`,+ [key.sourceId, key.kind, key.ownerKey]);+ if (!row) return null;+ const items = await db.executeRaw<{ item_key: string; identity_hash: string }>(+ `SELECT item_key, identity_hash FROM derived_generation_items WHERE generation_id=$1 AND action IN ('published','kept','adopted','revived')`, [row.id]);+ return { id: Number(row.id), generation: Number(row.generation), inputPin: row.input_pin, inputSize: row.input_size === null ? null : Number(row.input_size),+ items: new Map(items.map(item => [item.item_key, item.identity_hash])) };+}++function fenced(reason: 'stale_generation' | 'pin_moved', key: GenerationKey, detail: string) {+ return opError('generation_fenced', `The ${key.kind} generation of ${key.ownerKey} was not published: ${detail}; nothing was written.`,+ 'Run the producer again; it reads the current generation and input and recomputes.', { reason, docs: 'docs/architecture/generations.md' });+}++export interface LedgerItem { key: string; identityHash: string; action: 'published' | 'retired' | 'revived' | 'kept' | 'adopted'; preimage?: Preimage }++/** Supersedes the live row (if any) and activates a new generation with its items, in the caller's transaction. */+export async function activateGeneration(tx: BrainEngine, key: GenerationKey, live: LiveGeneration | null, row: {+ operationId: string; runId?: string; input: InputState | null; setHash: string; completeness: Record<string, unknown>; restoreOf?: number;+}, items: readonly LedgerItem[]): Promise<{ id: number; generation: number }> {+ const generation = (live?.generation ?? 0) + 1;+ if (live) await tx.executeRaw(`UPDATE derived_generations SET state='superseded', updated_at=now() WHERE id=$1 AND state='live'`, [live.id]);+ const [created] = await tx.executeRaw<{ id: number }>(+ `INSERT INTO derived_generations (source_id, kind, owner_key, generation, state, run_id, operation_id, input_pin, input_size, completeness, item_set_hash, restore_of)+ VALUES ($1,$2,$3,$4,'live',$5,$6,$7,$8,$9::jsonb,$10,$11) RETURNING id`,+ [key.sourceId, key.kind, key.ownerKey, generation, row.runId ?? null, row.operationId, row.input?.pin ?? null, row.input?.size ?? null,+ JSON.stringify(row.completeness), row.setHash, row.restoreOf ?? null]);+ const id = Number(created!.id);+ if (live) await tx.executeRaw('UPDATE derived_generations SET superseded_by=$1 WHERE id=$2', [id, live.id]);+ for (const item of items) {+ await tx.executeRaw(`INSERT INTO derived_generation_items (generation_id, item_key, identity_hash, action, preimage, preimage_bytes) VALUES ($1,$2,$3,$4,$5::jsonb,$6)`,+ [id, item.key, item.identityHash, item.action, item.preimage?.json ? JSON.stringify(item.preimage.json) : null, item.preimage?.bytes ?? null]);+ }+ await tx.executeRaw(`DELETE FROM derived_generations WHERE source_id=$1 AND kind=$2 AND owner_key=$3 AND state='held'`, [key.sourceId, key.kind, key.ownerKey]);+ return { id, generation };+}++/** 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> {+ if (!expected.size) return;+ const rows = await adapter.readItems(tx, key, [...expected.keys()]);+ const wrong = [...expected].filter(([itemKey, identity]) => { const row = rows.get(itemKey); return !row?.live || row.identityHash !== identity; }).map(([itemKey]) => itemKey);+ if (wrong.length) {+ throw opError('generation_live_conflict', `The ${key.kind} generation of ${key.ownerKey} was not activated: ${wrong.slice(0, 5).join(', ')} is not live at the content just written; nothing was committed.`,+ 'Run the producer again; it reads the items as they are now.', { docs: 'docs/architecture/generations.md' });+ }+}++async function recordHeld(tx: BrainEngine, key: GenerationKey, config: GenerationsConfig, request: PublishRequest<unknown>, setHash: string,+ reason: HeldReason, context: Record<string, unknown>): Promise<PublishOutcome> {+ const holdId = digest(['generation-hold-v1', key, request.input?.pin ?? null, policyHash(config), setHash, reason]).slice(0, 32);+ const [existing] = await tx.executeRaw<{ id: number; hold_id: string }>(+ `SELECT id, hold_id FROM derived_generations WHERE source_id=$1 AND kind=$2 AND owner_key=$3 AND state='held'`, [key.sourceId, key.kind, key.ownerKey]);+ if (existing?.hold_id === holdId) {+ await tx.executeRaw('UPDATE derived_generations SET attempts=attempts+1, updated_at=now() WHERE id=$1', [existing.id]);+ return { state: 'held', reason, holdId, context };+ }+ if (existing) await tx.executeRaw('DELETE FROM derived_generations WHERE id=$1', [existing.id]);+ const proposal = request.items.map(item => ({ key: item.key, content: item.content, identityHash: item.identityHash }));+ const bytes = jsonBytes(proposal);+ await tx.executeRaw(+ `INSERT INTO derived_generations (source_id, kind, owner_key, generation, state, run_id, operation_id, hold_id, input_pin, input_size, item_set_hash,+ held_reason, held_context, proposal, proposal_bytes, attempts)+ VALUES ($1,$2,$3,0,'held',$4,$5,$6,$7,$8,$9,$10,$11::jsonb,$12::jsonb,$13,1)`,+ [key.sourceId, key.kind, key.ownerKey, request.runId ?? null, `held:${holdId}`, holdId, request.input?.pin ?? null, request.input?.size ?? null, setHash,+ reason, JSON.stringify({ ...context, partial: request.partial === true }), bytes <= HELD_PROPOSAL_MAX_BYTES ? JSON.stringify(proposal) : null, bytes]);+ return { state: 'held', reason, holdId, context };+}++/** Whether `key` holds a result for this same input and policy, so the producer can skip recomputing it (CEO-outside r3 F5). */+export async function heldForInput(engine: BrainEngine, key: GenerationKey, pin: string): Promise<boolean> {+ const config = await readGenerationsConfig(engine);+ const rows = await engine.executeRaw<{ hold_id: string; item_set_hash: string; held_reason: string }>(+ `SELECT hold_id, item_set_hash, held_reason FROM derived_generations WHERE source_id=$1 AND kind=$2 AND owner_key=$3 AND state='held' AND input_pin=$4`,+ [key.sourceId, key.kind, key.ownerKey, pin]);+ return rows.some(row => row.hold_id === digest(['generation-hold-v1', key, pin, policyHash(config), row.item_set_hash, row.held_reason]).slice(0, 32));+}++function logFailure(key: GenerationKey, operationId: string, mode: string, error: unknown): void {+ const message = error instanceof Error ? error.message : String(error);+ console.error(`[generations] ${mode} failed: kind=${key.kind} source=${key.sourceId} schema=v${LATEST_VERSION} mode=unmanaged operation=${operationId}: ${message.slice(0, 300)}`);+}++export async function publishGeneration<C>(engine: BrainEngine, adapter: GenerationAdapter<C>, request: PublishRequest<C>): Promise<PublishOutcome> {+ const { key } = request;+ const config = await readGenerationsConfig(engine);+ const setHash = itemSetHash(request.items);+ const operationId = digest(['generation-publish-v1', key, request.expectedGeneration ?? null, request.input?.pin ?? null, setHash,+ request.partial === true, request.release?.holdId ?? null]);+ const itemKeys = request.items.map(item => item.key);+ try {+ const outcome = await maintenanceTransaction(engine, async tx => {+ await lockGeneration(tx, adapter as GenerationAdapter<unknown>, key, itemKeys);+ const [replay] = await tx.executeRaw<{ generation: number }>(`SELECT generation FROM derived_generations WHERE operation_id=$1 AND state <> 'held'`, [operationId]);+ if (replay) return { state: 'unchanged', generation: Number(replay.generation), retired: [], protected: [] } satisfies PublishOutcome;+ const live = await readLiveGeneration(tx, key);+ if (request.expectedGeneration !== undefined && (live?.generation ?? 0) !== request.expectedGeneration) {+ throw fenced('stale_generation', key, `the live generation is ${live?.generation ?? 0}, the producer planned against ${request.expectedGeneration}`);+ }+ const input = await adapter.readInput(tx, key, request.context);+ if (request.input && input?.pin !== request.input.pin) throw fenced('pin_moved', key, 'its input changed after the producer read it');+ const rows = await adapter.readItems(tx, key, itemKeys);+ const unrecorded = [...rows.values()].filter(row => row.owned && row.live && !live?.items.has(row.key) && !itemKeys.includes(row.key));+ const evidence = unrecorded.length ? await adapter.legacyEvidence(tx, key, unrecorded) : new Set<string>();+ const valve = await readValve(tx, key, request.runId);+ const plan = planGeneration({ live, rows, proposal: request.items, input, config, modelProduced: adapter.modelProduced, additive: request.partial === true,+ proofHolds: request.proof ? proofHolds(request.proof, input, live?.inputPin) : false, evidence, valve, release: request.release?.reason });+ if (plan.kind === 'held') return recordHeld(tx, key, config, request, setHash, plan.reason, plan.context);+ if (plan.kind === 'unchanged') return { state: 'unchanged', generation: live?.generation ?? null, retired: [], protected: plan.protectedKeys } satisfies PublishOutcome;+ const preimage = (itemKey: string) => rows.get(itemKey)?.preimage();+ if (plan.puts.length) await adapter.publishItems(tx, key, plan.puts, request.context);+ await faultPoint('generation:published', { sourceId: key.sourceId, operation: key.kind });+ 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 adapter.retireItems(tx, key, plan.retires, adapter.retiredBy);+ await faultPoint('generation:retired', { sourceId: key.sourceId, operation: key.kind });+ const items: LedgerItem[] = [+ ...plan.puts.map(item => ({ key: item.key, identityHash: item.identityHash, action: 'published' as const, ...(rows.get(item.key)?.live ? { preimage: preimage(item.key) } : {}) })),+ ...plan.kept.map(itemKey => ({ key: itemKey, identityHash: rows.get(itemKey)!.identityHash, action: 'kept' as const })),+ ...plan.adopted.map(itemKey => ({ key: itemKey, identityHash: rows.get(itemKey)!.identityHash, action: 'adopted' as const })),+ ...plan.carried.map(itemKey => ({ key: itemKey, identityHash: live!.items.get(itemKey)!, action: 'kept' as const })),+ ...plan.retires.map(itemKey => ({ key: itemKey, identityHash: rows.get(itemKey)!.identityHash, action: 'retired' as const, preimage: preimage(itemKey) })),+ ];+ const activated = await activateGeneration(tx, key, live, { operationId, runId: request.runId, input, setHash,+ completeness: { complete: !request.partial, proof: request.proof?.kind ?? null, released: request.release?.reason ?? null } }, items);+ if (plan.retires.length) await bumpValve(tx, key, request.runId, plan.retires.length);+ return { state: 'published', generationId: activated.id, generation: activated.generation, puts: plan.puts.map(item => item.key), kept: plan.kept,+ adopted: plan.adopted, retired: plan.retires, protected: plan.protectedKeys } satisfies PublishOutcome;+ });+ if (outcome.state === 'published') await faultPoint('generation:activated', { sourceId: key.sourceId, operation: key.kind });+ return outcome;+ } catch (error) {+ logFailure(key, operationId, 'publish', error);+ throw error;+ }+}++const windowKey = (runId: string | undefined) => runId ? `run:${runId}` : `day:${new Date().toISOString().slice(0, 10)}`;++async function readValve(tx: BrainEngine, key: GenerationKey, runId: string | undefined): Promise<{ windowRetired: number; ownedTotal: number }> {+ const [row] = await tx.executeRaw<{ retired: number | null; owned: number }>(+ `SELECT (SELECT retired FROM derived_generation_valve WHERE source_id=$1 AND kind=$2 AND window_key=$3) AS retired,+ (SELECT count(*)::int 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.state='live' AND i.action IN ('published','kept','adopted','revived')) AS owned`,+ [key.sourceId, key.kind, windowKey(runId)]);+ return { windowRetired: Number(row?.retired ?? 0), ownedTotal: Number(row?.owned ?? 0) };+}++async function bumpValve(tx: BrainEngine, key: GenerationKey, runId: string | undefined, retired: number): Promise<void> {+ await tx.executeRaw(`INSERT INTO derived_generation_valve (source_id, kind, window_key, retired) VALUES ($1,$2,$3,$4)+ ON CONFLICT (source_id, kind, window_key) DO UPDATE SET retired=derived_generation_valve.retired+EXCLUDED.retired, updated_at=now()`,+ [key.sourceId, key.kind, windowKey(runId), retired]);+}+diff --git a/src/core/persistence/derived-retirement-hold.ts b/src/core/persistence/derived-retirement-hold.tsindex 43e7f6485b..e33ce6e50b 100644--- a/src/core/persistence/derived-retirement-hold.ts+++ b/src/core/persistence/derived-retirement-hold.ts@@ -12,26 +12,31 @@import type { BrainEngine } from '../engine.ts';import { OperationError } from '../ops/contract.ts';import { maintenanceTransaction } from './attribution.ts';+import { GENERATION_BOUNDS, RESTORE_DAYS_SQL } from '../generations/config.ts';/** The `retired_by` stamps derived writers put on the pages they retire. */-export const DERIVED_RETIRED_BY = ['extract-atoms', 'managed-reextract', 'stale-atoms', 'life-chronicle'] as const;+export const DERIVED_RETIRED_BY = ['extract-atoms', 'managed-reextract', 'stale-atoms', 'life-chronicle', 'generation-restore'] as const;export type DerivedRetiredBy = typeof DERIVED_RETIRED_BY[number];/** The unmanaged extract_atoms retirement of atoms a completed re-extraction did not reproduce. */export const ATOM_RETIRED_BY_EXTRACT: DerivedRetiredBy = 'extract-atoms';-/** Days after `deleted_at` that the purge keeps a derived retirement. */-export const DERIVED_RETIREMENT_HOLD_DAYS = 30;+/** Days after `deleted_at` that the purge keeps a derived retirement by default; `generations.restore_days` (3 to 365) overrides it. */+export const DERIVED_RETIREMENT_HOLD_DAYS = GENERATION_BOUNDS.restoreDays.fallback;/** Frontmatter keys only a trusted derived writer sets; a remote page write never carries them. */export const RESERVED_RETIREMENT_KEYS = ['retired_by', 'retired_at', 'retired_generation'] as const;const stamps = DERIVED_RETIRED_BY.map(stamp => `'${stamp}'`).join(',');-/** SQL predicate for a purge scan over `pages` aliased `alias`: the page is not a derived retirement inside its hold. */+/**+ * SQL predicate for a purge scan over `pages` aliased `alias`: the page is not a derived retirement inside its hold. The+ * window is the configured `generations.restore_days` read in the statement (GBRA-161 PR 1a), so a longer window is+ * never purged early.+ */export function derivedRetirementPurgeHold(alias: string): string {return `NOT (COALESCE(${alias}.frontmatter->>'retired_by','') IN (${stamps})- AND ${alias}.deleted_at > now() - interval '${DERIVED_RETIREMENT_HOLD_DAYS} days')`;+ AND ${alias}.deleted_at > now() - interval '1 day' * ${RESTORE_DAYS_SQL})`;}/** Stamps pages the caller soft-deleted in this transaction as retired by `retiredBy`. */@@ -41,15 +46,19 @@ async function stampDerivedRetirement(tx: BrainEngine, sourceId: string, slugs:WHERE source_id=$3 AND slug=ANY($4::text[]) AND deleted_at IS NOT NULL`, [retiredBy, new Date().toISOString(), sourceId, [...slugs]]);}+/** Versions, soft-deletes and stamps `slugs` as retired by `retiredBy` inside the caller's attributed transaction. */+export async function retireDerivedPagesInTransaction(tx: BrainEngine, sourceId: string, slugs: readonly string[], retiredBy: DerivedRetiredBy): Promise<void> {+ if (!slugs.length) return;+ for (const slug of slugs) await tx.createVersion(slug, { sourceId });+ await tx.softDeletePages([...slugs], { sourceId });+ await stampDerivedRetirement(tx, sourceId, slugs, retiredBy);+}+/** Versions, soft-deletes and stamps `slugs` as retired by `retiredBy`, one attributed transaction per 500 pages. */export async function retireDerivedPages(engine: BrainEngine, sourceId: string, slugs: readonly string[], retiredBy: DerivedRetiredBy): Promise<void> {for (let i = 0; i < slugs.length; i += 500) {const batch = slugs.slice(i, i + 500);- await maintenanceTransaction(engine, async tx => {- for (const slug of batch) await tx.createVersion(slug, { sourceId });- await tx.softDeletePages(batch, { sourceId });- await stampDerivedRetirement(tx, sourceId, batch, retiredBy);- });+ await maintenanceTransaction(engine, tx => retireDerivedPagesInTransaction(tx, sourceId, batch, retiredBy));}}diff --git a/src/core/persistence/fault-points.ts b/src/core/persistence/fault-points.tsindex 0a35653c5b..c62d7ab9f4 100644--- a/src/core/persistence/fault-points.ts+++ b/src/core/persistence/fault-points.ts@@ -87,7 +87,10 @@ export type FaultPoint = `publication:${PublicationBoundary}` | `effect:${Effect| 'large_file:stage_copying' | 'large_file:stage_flushed'// A streamed file (large-file.ts `stageStreamedContent`: restore_page, a segmented withdrawal mirror) after each piece is// written to its in-progress name, before the stream is verified, flushed and renamed to the reserved stage name.- | 'large_file:stage_streaming';+ | 'large_file:stage_streaming'+ // GBRA-161: inside a generation activation, after its items are written and after its retirements, both before the commit;+ // and after the activation committed, before the producer acknowledges it.+ | 'generation:published' | 'generation:retired' | 'generation:activated';/*** `signal` (#6278, `consumer:preparing` only): the preparation's abort signal, so* a stalling hook can model both the reporter's cases: a preparer that honoursdiff --git a/src/core/pglite-schema.generated.ts b/src/core/pglite-schema.generated.tsindex 34ac28d9ea..709ccec6c4 100644--- a/src/core/pglite-schema.generated.ts+++ b/src/core/pglite-schema.generated.ts@@ -1217,6 +1217,53 @@ CREATE TABLE IF NOT EXISTS extract_atoms_page_state (CREATE INDEX IF NOT EXISTS extract_atoms_page_state_tombstoned_idxON extract_atoms_page_state (source_incarnation, content_hash, page_id) WHERE tombstoned;CREATE INDEX IF NOT EXISTS extract_atoms_page_state_page_idx ON extract_atoms_page_state (page_id);++CREATE TABLE IF NOT EXISTS derived_generations (+ id BIGSERIAL PRIMARY KEY,+ source_id TEXT NOT NULL REFERENCES sources(id) ON DELETE CASCADE,+ kind TEXT NOT NULL,+ owner_key TEXT NOT NULL,+ generation INTEGER NOT NULL DEFAULT 0,+ state TEXT NOT NULL CHECK (state IN ('live','held','superseded')),+ run_id TEXT,+ operation_id TEXT NOT NULL,+ hold_id TEXT,+ input_pin TEXT,+ input_size BIGINT,+ completeness JSONB NOT NULL DEFAULT '{}',+ item_set_hash TEXT NOT NULL,+ held_reason TEXT CHECK (held_reason IS NULL OR held_reason IN ('shrunk','oversize','valve','no_proof','fence_absent','attempts_exhausted','segmented_unsupported')),+ held_context JSONB,+ proposal JSONB,+ proposal_bytes INTEGER,+ attempts INTEGER NOT NULL DEFAULT 0,+ superseded_by BIGINT,+ restore_of BIGINT,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now()+);+CREATE UNIQUE INDEX IF NOT EXISTS derived_generations_one_live ON derived_generations (source_id, kind, owner_key) WHERE state = 'live';+CREATE UNIQUE INDEX IF NOT EXISTS derived_generations_one_hold ON derived_generations (source_id, kind, owner_key) WHERE state = 'held';+CREATE UNIQUE INDEX IF NOT EXISTS derived_generations_operation ON derived_generations (operation_id);+CREATE INDEX IF NOT EXISTS derived_generations_state_created ON derived_generations (state, created_at);+CREATE TABLE IF NOT EXISTS derived_generation_items (+ generation_id BIGINT NOT NULL REFERENCES derived_generations(id) ON DELETE CASCADE,+ item_key TEXT NOT NULL,+ identity_hash TEXT NOT NULL,+ action TEXT NOT NULL CHECK (action IN ('published','retired','revived','kept','adopted')),+ preimage JSONB,+ preimage_bytes INTEGER,+ PRIMARY KEY (generation_id, item_key)+);+CREATE INDEX IF NOT EXISTS derived_generation_items_key ON derived_generation_items (item_key);+CREATE TABLE IF NOT EXISTS derived_generation_valve (+ source_id TEXT NOT NULL REFERENCES sources(id) ON DELETE CASCADE,+ kind TEXT NOT NULL,+ window_key TEXT NOT NULL,+ retired INTEGER NOT NULL DEFAULT 0,+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ PRIMARY KEY (source_id, kind, window_key)+);CREATE TABLE IF NOT EXISTS page_embedding_budget (page_id INTEGER PRIMARY KEY REFERENCES pages(id) ON DELETE CASCADE,state TEXT NOT NULL DEFAULT 'open' CHECK (state IN ('open', 'held', 'capped')),diff --git a/src/core/schema-embedded.generated.ts b/src/core/schema-embedded.generated.tsindex defc56577d..eaee2f2f8d 100644--- a/src/core/schema-embedded.generated.ts+++ b/src/core/schema-embedded.generated.ts@@ -1947,6 +1947,54 @@ CREATE TABLE IF NOT EXISTS extract_atoms_page_state (CREATE INDEX IF NOT EXISTS extract_atoms_page_state_tombstoned_idxON extract_atoms_page_state (source_incarnation, content_hash, page_id) WHERE tombstoned;CREATE INDEX IF NOT EXISTS extract_atoms_page_state_page_idx ON extract_atoms_page_state (page_id);++-- GBRA-161: the generation ledger (src/core/generations/, docs/architecture/generations.md).+CREATE TABLE IF NOT EXISTS derived_generations (+ id BIGSERIAL PRIMARY KEY,+ source_id TEXT NOT NULL REFERENCES sources(id) ON DELETE CASCADE,+ kind TEXT NOT NULL,+ owner_key TEXT NOT NULL,+ generation INTEGER NOT NULL DEFAULT 0,+ state TEXT NOT NULL CHECK (state IN ('live','held','superseded')),+ run_id TEXT,+ operation_id TEXT NOT NULL,+ hold_id TEXT,+ input_pin TEXT,+ input_size BIGINT,+ completeness JSONB NOT NULL DEFAULT '{}',+ item_set_hash TEXT NOT NULL,+ held_reason TEXT CHECK (held_reason IS NULL OR held_reason IN ('shrunk','oversize','valve','no_proof','fence_absent','attempts_exhausted','segmented_unsupported')),+ held_context JSONB,+ proposal JSONB,+ proposal_bytes INTEGER,+ attempts INTEGER NOT NULL DEFAULT 0,+ superseded_by BIGINT,+ restore_of BIGINT,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now()+);+CREATE UNIQUE INDEX IF NOT EXISTS derived_generations_one_live ON derived_generations (source_id, kind, owner_key) WHERE state = 'live';+CREATE UNIQUE INDEX IF NOT EXISTS derived_generations_one_hold ON derived_generations (source_id, kind, owner_key) WHERE state = 'held';+CREATE UNIQUE INDEX IF NOT EXISTS derived_generations_operation ON derived_generations (operation_id);+CREATE INDEX IF NOT EXISTS derived_generations_state_created ON derived_generations (state, created_at);+CREATE TABLE IF NOT EXISTS derived_generation_items (+ generation_id BIGINT NOT NULL REFERENCES derived_generations(id) ON DELETE CASCADE,+ item_key TEXT NOT NULL,+ identity_hash TEXT NOT NULL,+ action TEXT NOT NULL CHECK (action IN ('published','retired','revived','kept','adopted')),+ preimage JSONB,+ preimage_bytes INTEGER,+ PRIMARY KEY (generation_id, item_key)+);+CREATE INDEX IF NOT EXISTS derived_generation_items_key ON derived_generation_items (item_key);+CREATE TABLE IF NOT EXISTS derived_generation_valve (+ source_id TEXT NOT NULL REFERENCES sources(id) ON DELETE CASCADE,+ kind TEXT NOT NULL,+ window_key TEXT NOT NULL,+ retired INTEGER NOT NULL DEFAULT 0,+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ PRIMARY KEY (source_id, kind, window_key)+);-- (migration v246) Per-page embedding spend ledger for large pages-- (page-embedding-budget.ts): held pages wait for approval, capped pages are-- partially embedded up to embed.max_usd_per_page.diff --git a/src/core/schema-migrations/latest.generated.ts b/src/core/schema-migrations/latest.generated.tsindex 1f7aa9e1ba..d776960602 100644--- a/src/core/schema-migrations/latest.generated.ts+++ b/src/core/schema-migrations/latest.generated.ts@@ -4,4 +4,4 @@// The highest schema migration version (migrate.ts LATEST_VERSION), importable without// loading the migrations themselves.-export const LATEST_SCHEMA_VERSION = 264;+export const LATEST_SCHEMA_VERSION = 265;diff --git a/src/core/schema-migrations/registry.generated.ts b/src/core/schema-migrations/registry.generated.tsindex 87001c9313..afd04991d4 100644--- a/src/core/schema-migrations/registry.generated.ts+++ b/src/core/schema-migrations/registry.generated.ts@@ -265,6 +265,7 @@ import { v261 } from './v261-persistence-request-transient-retries.ts';import { v262 } from './v262-commit-notifier.ts';import { v263 } from './v263-try-jsonb-function.ts';import { v264 } from './v264-set-based-fact-insert-guards.ts';+import { v265 } from './v265-derived-generations.ts';// Array order is historical (see HISTORICAL_ARRAY_ORDER in the generator); the// runner sorts by version before applying.@@ -528,4 +529,5 @@ export const MIGRATIONS: Migration[] = [v262,v263,v264,+ v265,];diff --git a/src/core/schema-migrations/v265-derived-generations.ts b/src/core/schema-migrations/v265-derived-generations.tsnew file mode 100644index 0000000000..edf3125868--- /dev/null+++ b/src/core/schema-migrations/v265-derived-generations.ts@@ -0,0 +1,63 @@+import type { Migration } from './types.ts';++// Applied by src/core/migrate.ts on the next initSchema(); see docs/ENGINES.md+// ("Canonical schema sources") for when schema.sql or a TS fragment also changes.+//+// GBRA-161 PR 1a: the generation ledger (docs/architecture/generations.md). One live row per+// (source, kind, owner key) records which derived items the current generation owns; superseded+// rows keep the item sets and bounded preimages a restore republishes; a held row records a result+// the primitive would not publish and why. The valve table counts retirements per run window.+// New tables only: no existing row changes. The number is a placeholder restamped at the merge slot.+export const v265: Migration = {+ version: 265,+ name: 'derived_generations',+ idempotent: true,+ sql: `+ CREATE TABLE IF NOT EXISTS derived_generations (+ id BIGSERIAL PRIMARY KEY,+ source_id TEXT NOT NULL REFERENCES sources(id) ON DELETE CASCADE,+ kind TEXT NOT NULL,+ owner_key TEXT NOT NULL,+ generation INTEGER NOT NULL DEFAULT 0,+ state TEXT NOT NULL CHECK (state IN ('live','held','superseded')),+ run_id TEXT,+ operation_id TEXT NOT NULL,+ hold_id TEXT,+ input_pin TEXT,+ input_size BIGINT,+ completeness JSONB NOT NULL DEFAULT '{}',+ item_set_hash TEXT NOT NULL,+ held_reason TEXT CHECK (held_reason IS NULL OR held_reason IN ('shrunk','oversize','valve','no_proof','fence_absent','attempts_exhausted','segmented_unsupported')),+ held_context JSONB,+ proposal JSONB,+ proposal_bytes INTEGER,+ attempts INTEGER NOT NULL DEFAULT 0,+ superseded_by BIGINT,+ restore_of BIGINT,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now()+ );+ CREATE UNIQUE INDEX IF NOT EXISTS derived_generations_one_live ON derived_generations (source_id, kind, owner_key) WHERE state = 'live';+ CREATE UNIQUE INDEX IF NOT EXISTS derived_generations_one_hold ON derived_generations (source_id, kind, owner_key) WHERE state = 'held';+ CREATE UNIQUE INDEX IF NOT EXISTS derived_generations_operation ON derived_generations (operation_id);+ CREATE INDEX IF NOT EXISTS derived_generations_state_created ON derived_generations (state, created_at);+ CREATE TABLE IF NOT EXISTS derived_generation_items (+ generation_id BIGINT NOT NULL REFERENCES derived_generations(id) ON DELETE CASCADE,+ item_key TEXT NOT NULL,+ identity_hash TEXT NOT NULL,+ action TEXT NOT NULL CHECK (action IN ('published','retired','revived','kept','adopted')),+ preimage JSONB,+ preimage_bytes INTEGER,+ PRIMARY KEY (generation_id, item_key)+ );+ CREATE INDEX IF NOT EXISTS derived_generation_items_key ON derived_generation_items (item_key);+ CREATE TABLE IF NOT EXISTS derived_generation_valve (+ source_id TEXT NOT NULL REFERENCES sources(id) ON DELETE CASCADE,+ kind TEXT NOT NULL,+ window_key TEXT NOT NULL,+ retired INTEGER NOT NULL DEFAULT 0,+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ PRIMARY KEY (source_id, kind, window_key)+ );+ `,+};diff --git a/src/schema.sql b/src/schema.sqlindex b5cb777853..5bbce01a85 100644--- a/src/schema.sql+++ b/src/schema.sql@@ -1943,6 +1943,54 @@ CREATE TABLE IF NOT EXISTS extract_atoms_page_state (CREATE INDEX IF NOT EXISTS extract_atoms_page_state_tombstoned_idxON extract_atoms_page_state (source_incarnation, content_hash, page_id) WHERE tombstoned;CREATE INDEX IF NOT EXISTS extract_atoms_page_state_page_idx ON extract_atoms_page_state (page_id);++-- GBRA-161: the generation ledger (src/core/generations/, docs/architecture/generations.md).+CREATE TABLE IF NOT EXISTS derived_generations (+ id BIGSERIAL PRIMARY KEY,+ source_id TEXT NOT NULL REFERENCES sources(id) ON DELETE CASCADE,+ kind TEXT NOT NULL,+ owner_key TEXT NOT NULL,+ generation INTEGER NOT NULL DEFAULT 0,+ state TEXT NOT NULL CHECK (state IN ('live','held','superseded')),+ run_id TEXT,+ operation_id TEXT NOT NULL,+ hold_id TEXT,+ input_pin TEXT,+ input_size BIGINT,+ completeness JSONB NOT NULL DEFAULT '{}',+ item_set_hash TEXT NOT NULL,+ held_reason TEXT CHECK (held_reason IS NULL OR held_reason IN ('shrunk','oversize','valve','no_proof','fence_absent','attempts_exhausted','segmented_unsupported')),+ held_context JSONB,+ proposal JSONB,+ proposal_bytes INTEGER,+ attempts INTEGER NOT NULL DEFAULT 0,+ superseded_by BIGINT,+ restore_of BIGINT,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now()+);+CREATE UNIQUE INDEX IF NOT EXISTS derived_generations_one_live ON derived_generations (source_id, kind, owner_key) WHERE state = 'live';+CREATE UNIQUE INDEX IF NOT EXISTS derived_generations_one_hold ON derived_generations (source_id, kind, owner_key) WHERE state = 'held';+CREATE UNIQUE INDEX IF NOT EXISTS derived_generations_operation ON derived_generations (operation_id);+CREATE INDEX IF NOT EXISTS derived_generations_state_created ON derived_generations (state, created_at);+CREATE TABLE IF NOT EXISTS derived_generation_items (+ generation_id BIGINT NOT NULL REFERENCES derived_generations(id) ON DELETE CASCADE,+ item_key TEXT NOT NULL,+ identity_hash TEXT NOT NULL,+ action TEXT NOT NULL CHECK (action IN ('published','retired','revived','kept','adopted')),+ preimage JSONB,+ preimage_bytes INTEGER,+ PRIMARY KEY (generation_id, item_key)+);+CREATE INDEX IF NOT EXISTS derived_generation_items_key ON derived_generation_items (item_key);+CREATE TABLE IF NOT EXISTS derived_generation_valve (+ source_id TEXT NOT NULL REFERENCES sources(id) ON DELETE CASCADE,+ kind TEXT NOT NULL,+ window_key TEXT NOT NULL,+ retired INTEGER NOT NULL DEFAULT 0,+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ PRIMARY KEY (source_id, kind, window_key)+);-- (migration v246) Per-page embedding spend ledger for large pages-- (page-embedding-budget.ts): held pages wait for approval, capped pages are-- partially embedded up to embed.max_usd_per_page.