Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

GBRA-161 PR 1b: managed atoms on the generation primitive (activation request, gated members, transcript keys)

garrytan41ece5767907
diff --git a/src/core/cycle/extract-atoms-input.ts b/src/core/cycle/extract-atoms-input.ts
index 83d9583d41..d10e1a7b34 100644
--- a/src/core/cycle/extract-atoms-input.ts
+++ b/src/core/cycle/extract-atoms-input.ts
@@ -44,7 +44,7 @@ export async function resolveExtractAtomsInputCap(engine: BrainEngine): Promise<
}
export type ExtractAtomsItem =
- | { kind: 'transcript'; filePath: string; content: string; contentHash: string }
+ | { kind: 'transcript'; filePath: string; content: string; contentHash: string; transcriptKey?: string }
| ({ kind: 'page' } & AtomPageInput);
export interface ExtractAtomsInput {
diff --git a/src/core/cycle/extract-atoms.ts b/src/core/cycle/extract-atoms.ts
index 75219783a5..249275fea1 100644
--- a/src/core/cycle/extract-atoms.ts
+++ b/src/core/cycle/extract-atoms.ts
@@ -80,6 +80,8 @@ import { classifyRunStop, providerHaltReason, upsertExtractRollup } from '../ext
import { abortableSleep } from '../retry.ts';
import { throwIfAborted } from '../abort-check.ts';
import { createHash } from 'crypto';
+import { existsSync } from 'node:fs';
+import { isAbsolute, relative, resolve, sep } from 'node:path';
import { slugifySegment } from '../sync.ts';
import { resolveAlias, resolveTierDefault } from '../model-config.ts';
import { isMissingSchemaObject, warnOncePerProcess } from '../utils.ts';
@@ -87,14 +89,15 @@ import { utcDate } from './cycle-date.ts';
import { atomSourceDate } from './atom-source-date.ts';
import { normalizeForGrounding } from './synthesize-verify.ts';
import type { TranscriptPageIndex } from '../transcripts/discover.ts';
-import { managedAtomSession, readAtomOrigin, resumeManagedAtoms, publishManagedAtoms, MANAGED_ATOM_DISCOVERY_SQL, type AtomOrigin } from '../persistence/atom-maintenance.ts';
+import { atomOriginPin, managedAtomSession, readAtomOrigin, resumeManagedAtoms, publishManagedAtoms, publishManagedAtomGeneration, resumeManagedGenerationMembers,
+ MANAGED_ATOM_DISCOVERY_SQL, type AtomOrigin } from '../persistence/atom-maintenance.ts';
import { effectiveVisibility } from '../search/private-visibility.ts';
import { OperationError } from '../ops/contract.ts';
import { isOpPageSlug } from '../ops/context.ts';
import type { WriteReceipt } from '../persistence/types.ts';
import { acceptedPendingReceipt } from '../persistence/accepted-pending.ts';
import { AtomPageStateError, MAX_DETERMINISTIC_FAILURES, readAtomPageIdentity, writeAtomPageState, type AtomPageInput } from './extract-atoms-page-state.ts';
-import { ATOM_KIND, atomGenerationAdapter, atomOwnerKey, atomPagePin, type AtomGenerationContext } from '../generations/adapters/atoms.ts';
+import { ATOM_KIND, atomGenerationAdapter, atomOwnerKey, atomPagePin, TRANSCRIPT_KEY_PREFIX, type AtomGenerationContext } from '../generations/adapters/atoms.ts';
import { markdownItem } from '../generations/adapters/page.ts';
import type { GenerationKey } from '../generations/contract.ts';
import { heldForInput, publishGeneration } from '../generations/publish.ts';
@@ -207,7 +210,7 @@ export interface ExtractAtomsOpts {
*/
_loadConfig?: () => GBrainConfig | Promise<GBrainConfig | null> | null;
/** Test seam: skip transcript discovery; use these transcripts directly. */
- _transcripts?: Array<{ filePath: string; content: string; contentHash: string }>;
+ _transcripts?: Array<{ filePath: string; content: string; contentHash: string; root?: { path: string; label: string } }>;
/**
* Test seam (v0.41.2.1): skip page discovery; use these pages directly.
* Mirrors _transcripts shape. `undefined` triggers discovery; `[]`
@@ -697,6 +700,7 @@ export async function runPhaseExtractAtoms(
const sourceId = opts.sourceId ?? 'default';
const chat = opts._chat ?? gatewayChat;
const managed = await managedAtomSession(engine, sourceId, opts._managedRetry, opts.attempt?.writeWait);
+ if (managed && !opts.dryRun) await resumeManagedGenerationMembers(engine, managed); // GBRA-161 PR 1b: finish what a crash after an activation left
const atomFiles = await derivedWriteThrough(engine, 'extract_atoms', sourceId, { managed: managed !== null, dryRun: opts.dryRun ?? false });
const writeRequests: WriteReceipt[] = [];
const pageAtomTitles = new Map<string, Map<string, string[]>>();
@@ -704,7 +708,7 @@ export async function runPhaseExtractAtoms(
// 1a. Get transcripts (test seam OR production discovery).
// v0.41.2.1: config loader switched to loadConfigWithEngine() so the
// dream.* DB-plane merge from Phase 1 reaches this phase.
- let transcripts: Array<{ filePath: string; content: string; contentHash: string }> = opts._transcripts ?? [];
+ let transcripts: Array<{ filePath: string; content: string; contentHash: string; root?: { path: string; label: string } }> = opts._transcripts ?? [];
// Configured transcript corpus paths are brain-global, so only default discovers them.
if (
sourceId === 'default'
@@ -732,7 +736,7 @@ export async function runPhaseExtractAtoms(
transcripts = discovered.map((d) => ({
filePath: d.filePath,
content: d.content,
- contentHash: d.contentHash,
+ contentHash: d.contentHash, root: transcriptRoot(d.filePath, corpusDir, meetingDir),
}));
}
} catch {
@@ -765,6 +769,7 @@ export async function runPhaseExtractAtoms(
// 2. Apply transcript-side source-hash idempotency in ONE batch query
// instead of N per-hash round trips. Page-side idempotency lives in
// the discovery SQL's NOT EXISTS subquery (already batched).
+ const transcriptKeys = await resolveTranscriptKeys(engine, sourceId, transcripts, opts.dryRun === true);
const transcriptsLive: typeof transcripts = [];
let duplicatesSkipped = 0;
const allHashes16 = transcripts.map(t => t.contentHash.slice(0, 16));
@@ -816,7 +821,7 @@ export async function runPhaseExtractAtoms(
// the cap — `--drain` can no longer report the same backlog number
// forever while atoms keep getting extracted from transcripts.
type WorkItem =
- | { kind: 'transcript'; filePath: string; content: string; contentHash: string }
+ | { kind: 'transcript'; filePath: string; content: string; contentHash: string; transcriptKey?: string }
| ({ kind: 'page' } & AtomPageInput);
const seenHashes = new Set<string>();
@@ -824,7 +829,7 @@ export async function runPhaseExtractAtoms(
for (const t of transcriptsLive) {
if (seenHashes.has(t.contentHash)) { duplicatesSkipped++; continue; }
seenHashes.add(t.contentHash);
- transcriptItems.push({ kind: 'transcript', ...t });
+ transcriptItems.push({ kind: 'transcript', filePath: t.filePath, content: t.content, contentHash: t.contentHash, transcriptKey: transcriptKeys.get(t.filePath) });
}
const pageItems: WorkItem[] = [];
for (const p of pages) {
@@ -1099,7 +1104,7 @@ export async function runPhaseExtractAtoms(
if (resumed === 'done') { duplicatesSkipped++; continue; }
if (resumed === 'held') { heldFailed++; continue; } // #6325: settled after repeated failures; doctor lists it
// GBRA-161: a complete read whose result for this same input and policy is already held is not computed again.
- if (!opts.dryRun && !managed && !truncated && await heldForInput(engine, atomGenerationOrigin(sourceId, item).key, atomInputPin(item))) { duplicatesSkipped++; continue; }
+ if (!opts.dryRun && !truncated && await heldForInput(engine, atomGenerationOrigin(sourceId, item).key, origin ? atomOriginPin(origin) : atomInputPin(item))) { duplicatesSkipped++; continue; }
const cutLine = truncated ? inputTruncatedLine(originLabel, input, maxInputChars) : null; // A7: a complete appended-tail read prints nothing
if (cutLine) { inputTruncated++; console.error(cutLine); } // counted only for a model call
@@ -1188,7 +1193,7 @@ export async function runPhaseExtractAtoms(
const slug =
item.kind === 'page'
? await resolvePageAtomSlug(engine, atom.title, item.slug, sourceId, undatedDate, pageAtomTitles)
- : atomSlug(atom.title, srcRef, undefined, undatedDate);
+ : await resolveTranscriptAtomSlug(engine, sourceId, atom.title, item, undatedDate);
const originFrontmatter =
item.kind === 'transcript'
? { source_path: item.filePath }
@@ -1289,7 +1294,9 @@ export async function runPhaseExtractAtoms(
if (managed && origin) {
for (const atom of managedAtoms) atom.links = provenanceLinks.filter(link => link.to_slug === atom.slug);
throwIfAborted(opts.signal, 'extract_atoms');
- const published = await publishManagedAtoms(engine, managed, origin, managedAtoms);
+ const generation = await publishManagedAtomGeneration(engine, managed, origin, managedAtoms, { ...atomGenerationOrigin(sourceId, item), content: item.content, runId });
+ if (generation.state === 'held') { console.error(heldLine(originLabel, atomGenerationOrigin(sourceId, item).key, generation.reason)); continue; }
+ const published = generation.receipts;
writeRequests.push(...published);
if (published.some(receipt => receipt.state !== 'committed')) writesPending++;
totalAtomsExtracted += managedAtoms.length;
@@ -1461,17 +1468,15 @@ export async function runPhaseExtractAtoms(
*/
async function publishUnmanagedAtoms(engine: BrainEngine, sourceId: string, item: ExtractAtomsItem, atoms: ReadonlyArray<{ slug: string; content: string }>,
links: LinkBatchInput[], opts: { partial: boolean; runId: string; originLabel: string }) {
- const { key, context } = atomGenerationOrigin(sourceId, item);
+ const { key, context, locator } = atomGenerationOrigin(sourceId, item);
context.links = links;
context.embed = isAvailable('embedding');
const outcome = await publishGeneration(engine, atomGenerationAdapter, { key, items: atoms.map(atom => markdownItem(atom.slug, atom.content)),
- input: { pin: atomInputPin(item), size: Buffer.byteLength(item.content) }, partial: opts.partial, context, runId: opts.runId });
+ input: { pin: atomInputPin(item), size: Buffer.byteLength(item.content) }, partial: opts.partial, context, runId: opts.runId, locator });
for (const complete of context.postCommit ?? []) {
await complete().catch(error => console.error(`[extract_atoms] ${opts.originLabel}: post-commit embedding failed (the embedding backfill retries it): ${error instanceof Error ? error.message : String(error)}`));
}
- if (outcome.state === 'held') {
- console.error(`[extract_atoms] ${opts.originLabel}: result held (${outcome.reason}); the previous atoms stay live. Preview: gbrain repair generations --kind ${ATOM_KIND} --mode release-held --key ${key.ownerKey} --source ${sourceId}`);
- }
+ if (outcome.state === 'held') console.error(heldLine(opts.originLabel, key, outcome.reason));
return outcome;
}
@@ -1480,11 +1485,66 @@ function atomInputPin(item: ExtractAtomsItem): string {
return item.kind === 'page' ? atomPagePin(item.contentHash, item.identity) : item.contentHash;
}
-/** GBRA-161: the generation key of one unmanaged item and the context its adapter reads (a transcript's input is not in the database). */
-function atomGenerationOrigin(sourceId: string, item: ExtractAtomsItem): { key: GenerationKey; context: AtomGenerationContext } {
- const ownerKey = atomOwnerKey(item.kind === 'page' ? { kind: 'page', slug: item.slug } : { kind: 'transcript', filePath: item.filePath });
- return { key: { kind: ATOM_KIND, sourceId, ownerKey },
- context: { postCommit: [], ...(item.kind === 'transcript' ? { transcriptInput: { pin: item.contentHash, size: Buffer.byteLength(item.content) } } : {}) } };
+/**
+ * GBRA-161: the generation key of one item and the context its adapter reads (a transcript's input is not in the
+ * database). A transcript's key is its root label and root-relative path (resolveTranscriptKeys), or its path when the
+ * caller named no root.
+ */
+function atomGenerationOrigin(sourceId: string, item: ExtractAtomsItem): { key: GenerationKey; context: AtomGenerationContext; locator?: string } {
+ if (item.kind === 'page') return { key: { kind: ATOM_KIND, sourceId, ownerKey: atomOwnerKey({ kind: 'page', slug: item.slug }) }, context: { postCommit: [] } };
+ return { key: { kind: ATOM_KIND, sourceId, ownerKey: atomOwnerKey({ kind: 'transcript', transcriptKey: item.transcriptKey ?? item.filePath }) }, locator: item.filePath,
+ context: { postCommit: [], locator: item.filePath, transcriptInput: { pin: item.contentHash, size: Buffer.byteLength(item.content) } } };
+}
+
+const heldLine = (originLabel: string, key: GenerationKey, reason: string) =>
+ `[extract_atoms] ${originLabel}: result held (${reason}); the previous atoms stay live. Preview: gbrain repair generations --kind ${ATOM_KIND} --mode release-held --key ${key.ownerKey} --source ${key.sourceId}`;
+
+/** GBRA-161 PR 1b: the corpus root a discovered transcript lies under, with the label its key carries. */
+function transcriptRoot(filePath: string, corpusDir: string, meetingDir: string | undefined): { path: string; label: string } {
+ const inside = (dir: string) => { const rel = relative(resolve(dir), resolve(filePath)); return rel !== '' && !rel.startsWith('..') && !isAbsolute(rel); };
+ return meetingDir && inside(meetingDir) && !(inside(corpusDir) && resolve(corpusDir).length > resolve(meetingDir).length)
+ ? { path: meetingDir, label: 'meetings' } : { path: corpusDir, label: 'corpus' };
+}
+
+/**
+ * GBRA-161 PR 1b (Eng r3 F1): each transcript's generation key: its root label and path relative to that root, never its
+ * basename or content hash, so two files of one name in two folders never share a key. A file whose key has no live
+ * generation but whose content equals the input of a live transcript generation whose file is gone was moved: it keeps
+ * that key, and the generation's locator follows it (recorded even when the unchanged file is not extracted again).
+ */
+async function resolveTranscriptKeys(engine: BrainEngine, sourceId: string, transcripts: ReadonlyArray<{ filePath: string; contentHash: string; root?: { path: string; label: string } }>,
+ dryRun: boolean): Promise<Map<string, string>> {
+ const own = new Map(transcripts.map(t => [t.filePath, t.root ? `${t.root.label}/${relative(resolve(t.root.path), resolve(t.filePath)).split(sep).join('/')}` : t.filePath]));
+ if (!transcripts.length) return own;
+ const live = await engine.executeRaw<{ id: number; owner_key: string; locator: string | null; input_pin: string | null }>(
+ `SELECT id, owner_key, locator, input_pin FROM derived_generations WHERE source_id=$1 AND kind=$2 AND state='live' AND owner_key LIKE $3`,
+ [sourceId, ATOM_KIND, `${TRANSCRIPT_KEY_PREFIX}%`]);
+ const claimed = new Set([...own.values()].map(key => `${TRANSCRIPT_KEY_PREFIX}${key}`).filter(key => live.some(row => row.owner_key === key)));
+ for (const t of transcripts) {
+ if (claimed.has(`${TRANSCRIPT_KEY_PREFIX}${own.get(t.filePath)}`)) continue;
+ const moved = live.find(row => !claimed.has(row.owner_key) && row.input_pin === t.contentHash && row.locator && row.locator !== t.filePath && !existsSync(row.locator));
+ if (!moved) continue;
+ claimed.add(moved.owner_key);
+ own.set(t.filePath, moved.owner_key.slice(TRANSCRIPT_KEY_PREFIX.length));
+ if (!dryRun) await engine.executeRaw('UPDATE derived_generations SET locator=$2, updated_at=now() WHERE id=$1', [moved.id, t.filePath]);
+ }
+ return own;
+}
+
+/**
+ * GBRA-161 PR 1b: a transcript atom's slug. The title-and-date slug, unless a live atom of another transcript already
+ * holds it (two files of one name in two folders extract the same title): then the slug folds in the transcript's key.
+ */
+async function resolveTranscriptAtomSlug(engine: BrainEngine, sourceId: string, title: string, item: { filePath: string; transcriptKey?: string },
+ undatedDate: string): Promise<string> {
+ const legacy = atomSlug(title, item.filePath, undefined, undatedDate);
+ const [held] = await engine.executeRaw<{ source_path: string | null }>(
+ `SELECT frontmatter->>'source_path' AS source_path FROM pages WHERE source_id=$1 AND slug=$2 AND deleted_at IS NULL`, [sourceId, legacy]);
+ if (!held || held.source_path === item.filePath || !held.source_path) return legacy;
+ const [mine] = await engine.executeRaw<{ locator: string | null }>(
+ `SELECT locator FROM derived_generations WHERE source_id=$1 AND kind=$2 AND owner_key=$3 AND state='live'`,
+ [sourceId, ATOM_KIND, atomOwnerKey({ kind: 'transcript', transcriptKey: item.transcriptKey ?? item.filePath })]);
+ return mine?.locator === held.source_path ? legacy : atomSlug(title, item.filePath, item.transcriptKey ?? item.filePath, undatedDate);
}
/**
diff --git a/src/core/generations/adapters/atoms.ts b/src/core/generations/adapters/atoms.ts
index fdce66b518..17e0648efa 100644
--- a/src/core/generations/adapters/atoms.ts
+++ b/src/core/generations/adapters/atoms.ts
@@ -1,36 +1,49 @@
/**
- * 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.
+ * GBRA-161: the atom adapter. One owner key per origin: `source_slug:<page>`, or `transcript:<root>/<path>` for a
+ * transcript (its path relative to the corpus root it was found under, never its basename or content hash; a moved
+ * file whose content pin matches keeps its key, extract-atoms.ts `resolveTranscriptKeys`). The items are the atom pages
+ * extract_atoms writes for it. Unmanaged: 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 (PR 1b): the same plan runs through a `managed_generation_activate` request and per-page member
+ * requests (generations/managed.ts, persistence/atom-maintenance.ts); only `readInput`, `readItems` and
+ * `legacyEvidence` are used there.
*
- * 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.
+ * An atom written before the ledger is the key's only when the extraction reproduces it, or retained producer evidence
+ * shows it unedited: a page version written by the extractor, or a committed managed atom write receipt whose content
+ * has the row's identity (not one an activation that never happened admitted). Any other atom naming the origin stays
+ * live and is reported as protected.
*/
+import { existsSync, readFileSync } from 'node:fs';
import type { BrainEngine, LinkBatchInput } from '../../engine.ts';
+import { sha256 } from '../../persistence/digest.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';
+import { importPageItem, markdownItem, 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. */
+ /** A transcript's content hash and size as the extractor read it; a page origin is read under the lock instead. */
transcriptInput?: InputState;
+ /** A transcript's current file (its atoms' `source_path`). With `verifyFile` the input is read from the file itself. */
+ locator?: string;
+ verifyFile?: boolean;
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 };
+type Origin = { field: 'source_slug' | 'source_path'; value: string | null };
-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}`;
+export const TRANSCRIPT_KEY_PREFIX = 'transcript:';
+
+/** A page origin's key, or a transcript's (`transcriptKey`: its root label and root-relative path, extract-atoms.ts). */
+export function atomOwnerKey(origin: { kind: 'page'; slug: string } | { kind: 'transcript'; transcriptKey: string }): string {
+ return origin.kind === 'page' ? `source_slug:${origin.slug}` : `${TRANSCRIPT_KEY_PREFIX}${origin.transcriptKey}`;
}
/**
@@ -42,11 +55,17 @@ export function atomPagePin(contentHash: string, identity: { pageId: number; rev
return identity ? `${contentHash}:${identity.pageId}:${identity.revision}` : contentHash;
}
-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) };
+/** The origin metadata a key's atoms carry: a page key's slug; a transcript key's current file (null when unknown). */
+function originOf(key: GenerationKey, context?: AtomGenerationContext): Origin {
+ if (key.ownerKey.startsWith(TRANSCRIPT_KEY_PREFIX)) return { field: 'source_path', value: context?.locator ?? null };
+ if (!key.ownerKey.startsWith('source_slug:')) throw new Error(`not an atom owner key: ${key.ownerKey}`);
+ return { field: 'source_slug', value: key.ownerKey.slice('source_slug:'.length) };
+}
+
+function readTranscriptFile(path: string): InputState | null {
+ if (!existsSync(path)) return null;
+ const bytes = readFileSync(path);
+ return { pin: sha256(bytes), size: bytes.length };
}
export const atomGenerationAdapter: GenerationAdapter<AtomGenerationContext> = {
@@ -55,28 +74,31 @@ export const atomGenerationAdapter: GenerationAdapter<AtomGenerationContext> = {
modelProduced: true,
lockKeys(key, itemKeys) {
const origin = originOf(key);
- return [...(origin.field === 'source_slug' ? [origin.value] : []), ...itemKeys].map(slug => ({ sourceId: key.sourceId, slug }));
+ 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 origin = originOf(key, context);
+ if (origin.field === 'source_path') return context?.verifyFile && context.locator ? readTranscriptFile(context.locator) : context?.transcriptInput ?? null;
const [row] = await engine.executeRaw<{ id: number; content_hash: string | null; revision: string | null; body_bytes: number | null }>(
`SELECT id, content_hash, knowledge_revision::text AS revision,
CASE WHEN body_storage = 'segmented' THEN body_bytes ELSE octet_length(COALESCE(compiled_truth, '')) + octet_length(COALESCE(timeline, '')) END AS 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: atomPagePin(row.content_hash, row.revision ? { pageId: Number(row.id), revision: row.revision } : undefined), size: Number(row.body_bytes ?? 0) } : null;
},
- async readItems(engine, key, itemKeys) {
- const origin = originOf(key);
+ async readItems(engine, key, itemKeys, context) {
+ const origin = originOf(key, context);
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)]));
+ `p.type='atom' AND (p.slug = ANY($2::text[]) OR (p.deleted_at IS NULL AND $3::text IS NOT NULL AND p.frontmatter->>'${origin.field}' = $3))`, [[...itemKeys], origin.value]);
+ return new Map(rows.map(row => [row.slug, pageItemRow(row, origin.value !== null && row.frontmatter?.[origin.field] === origin.value
+ && row.frontmatter?.imported_from == null)]));
+ },
+ async legacyEvidence(engine, key, rows) {
+ const versions = await pageVersionEvidence(engine, key.sourceId, rows, "v.frontmatter->>'extracted_by' LIKE 'extract\\_atoms%'");
+ return new Set([...versions, ...await receiptEvidence(engine, key.sourceId, rows.filter(row => !versions.has(row.key)))]);
},
- 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' });
+ 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); } } : {}) });
@@ -97,6 +119,21 @@ export const atomGenerationAdapter: GenerationAdapter<AtomGenerationContext> = {
preimageIdentity,
};
+/**
+ * Rows whose committed managed atom write receipt holds content at the row's identity: the extractor wrote it and it is
+ * unedited since. A receipt an activation admitted that never happened is no evidence (its atom is an orphan candidate).
+ */
+async function receiptEvidence(engine: BrainEngine, sourceId: string, rows: readonly { key: string; identityHash: string }[]): Promise<Set<string>> {
+ if (!rows.length) return new Set();
+ const receipts = await engine.executeRaw<{ slug: string; content: string }>(
+ `SELECT r.slug, r.intent->>'content' AS content FROM persistence_requests r
+ WHERE r.source_id=$1 AND r.slug=ANY($2::text[]) AND r.state='committed' AND r.intent->>'kind'='managed_atom_page' AND r.intent ? 'content'
+ AND (r.intent->>'activationId' IS NULL OR EXISTS (SELECT 1 FROM derived_generation_activations a WHERE a.id=r.intent->>'activationId' AND a.state='activated'))`,
+ [sourceId, rows.map(row => row.key)]);
+ const wanted = new Map(rows.map(row => [row.key, row.identityHash]));
+ return new Set(receipts.filter(receipt => markdownItem(receipt.slug, receipt.content).identityHash === wanted.get(receipt.slug)).map(receipt => receipt.slug));
+}
+
export async function readAtomInput(engine: BrainEngine, key: GenerationKey): Promise<InputState | null> {
return atomGenerationAdapter.readInput(engine, key, undefined);
}
diff --git a/src/core/generations/adapters/page.ts b/src/core/generations/adapters/page.ts
index 33e53ca25f..6114e39a3b 100644
--- a/src/core/generations/adapters/page.ts
+++ b/src/core/generations/adapters/page.ts
@@ -13,10 +13,15 @@ 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 { HASH_EPHEMERAL_FRONTMATTER_KEYS } from '../../utils.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]);
+/**
+ * Frontmatter keys the identity hash ignores: completion, extraction and retirement stamps, the keys the content hash
+ * already treats as ephemeral, and the first-write provenance a managed writer stamps (source_kind, ingested_via).
+ */
+export const IDENTITY_EXCLUDED_KEYS: ReadonlySet<string> = new Set(['source_hash', 'extracted_at', 'extracted_by', 'source_kind', 'ingested_via',
+ ...HASH_EPHEMERAL_FRONTMATTER_KEYS, ...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;
diff --git a/src/core/generations/contract.ts b/src/core/generations/contract.ts
index 6174952dd8..b592b0e63b 100644
--- a/src/core/generations/contract.ts
+++ b/src/core/generations/contract.ts
@@ -42,7 +42,7 @@ export interface GenerationAdapter<C = unknown> {
/** 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>>;
+ readItems(engine: BrainEngine, key: GenerationKey, itemKeys: readonly string[], context?: C): 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. */
diff --git a/src/core/generations/managed.ts b/src/core/generations/managed.ts
new file mode 100644
index 0000000000..26bd552d18
--- /dev/null
+++ b/src/core/generations/managed.ts
@@ -0,0 +1,226 @@
+/**
+ * GBRA-161 PR 1b: managed generations (D2 on the existing page target; docs/architecture/generations.md#managed-sources).
+ *
+ * A managed source never composes a generation inside one transaction: every page write is its own coordinated request
+ * with its own file. So a managed publication is admitted as one batch, in this order:
+ * 1. `create` members: page writes of new identities only (a key no live row holds), so a crash leaves old and new
+ * both live, never neither;
+ * 2. one `managed_generation_activate` request: under the member page locks and then the generation key lock it
+ * rechecks the expected generation, the input pin and every member at its planned identity (`generation_fenced`,
+ * `generation_live_conflict` otherwise), flips the ledger and marks every item a member still overwrites or retires
+ * `pending` (retire_pending: still live);
+ * 3. `overwrite` and `retire` members: the existing per-page managed put and delete requests (version first, stamp),
+ * each refusing unless its item is pending on the activation's live generation and clearing the mark when it commits.
+ * Every request id is deterministic: the activation's is digest(operation id, the producer's run scope), a member's
+ * digest(activation id, member slug, action). The activation row (`derived_generation_activations`) is written with the batch, before any member runs:
+ * a crash after activation resumes the pending members on the next run (`listPendingMembers`); members created by an
+ * activation that never happened are orphan candidates (`listOrphanCandidates`), listed and never retired automatically.
+ * Doctor counts both (`generation_retirements`); `gbrain repair generations --mode pending` lists and resumes them.
+ */
+import type { BrainEngine } from '../engine.ts';
+import type { PreparedMutation } from '../persistence/coordinator.ts';
+import type { WriteRequest } from '../persistence/model.ts';
+import type { DerivedRetiredBy } from '../persistence/derived-retirement-hold.ts';
+import { opError } from '../ops/contract.ts';
+import { readFix } from '../ops/op-fix.ts';
+import { digest } from '../persistence/digest.ts';
+import { faultPoint } from '../persistence/fault-points.ts';
+import { generationAdapter } from './adapters/index.ts';
+import { readGenerationsConfig } from './config.ts';
+import type { GenerationAdapter, GenerationKey, InputState, ProposedItem } from './contract.ts';
+import { proofHolds, type EmptySourceProof } from './proofs.ts';
+import { activateGeneration, bumpValve, exhaustedHold, generationKeyLock, generationFenced, liveConflict, planPublication, publishOperationId,
+ readLiveGeneration, recordHeld, requestSetHash, type LedgerItem, type PublishOutcome, type PublishRequest } from './publish.ts';
+
+export const GENERATION_ACTIVATE_INTENT = 'managed_generation_activate';
+/** The pseudo slug the activation request is journaled under (it writes no page). */
+export const GENERATION_ACTIVATE_SLUG = '__generation_activate__';
+
+export type MemberAction = 'create' | 'overwrite' | 'retire';
+/** One member of an activation: `identity` is what it leaves (the retired identity for a retirement), `before` what the target held when planned. */
+export interface ActivationMember { slug: string; action: MemberAction; identity: string; before: string | null }
+
+export interface ActivationPlanIntent {
+ kind: typeof GENERATION_ACTIVATE_INTENT;
+ activationId: string;
+ key: GenerationKey;
+ expectedGeneration: number;
+ input: InputState | null;
+ operationId: string;
+ setHash: string;
+ runId: string | null;
+ partial: boolean;
+ proof: EmptySourceProof | null;
+ retiredBy: DerivedRetiredBy;
+ approved: boolean;
+ members: ActivationMember[];
+ /** Items the generation keeps without a member (an approved retirement keeps the rest; a partial result carries them). */
+ kept: string[];
+ carried: string[];
+ /** The adapter context the activation reads the input and items with (atoms: the transcript file). */
+ context: unknown;
+ locator: string | null;
+}
+/** The journaled activation intent: the plan plus the run key its batch shares. */
+export type ActivationIntent = ActivationPlanIntent & { runKey: string } & Record<string, unknown>;
+
+/** A request id in UUID form from a hex digest (the journal keys requests by UUID). */
+export function requestUuid(hex: string): string {
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-8${hex.slice(13, 16)}-a${hex.slice(17, 20)}-${hex.slice(20, 32)}`;
+}
+export const activationRequestId = (operationId: string, scope: string | null = null): string =>
+ requestUuid(digest(['generation-activate-v1', operationId, ...(scope ? [scope] : [])]));
+export const memberRequestId = (activationId: string, slug: string, action: string): string => requestUuid(digest([activationId, slug, action]));
+
+export type ManagedPlan =
+ | { kind: 'held'; outcome: Extract<PublishOutcome, { state: 'held' }> }
+ | { kind: 'unchanged' }
+ | { kind: 'publish'; intent: ActivationPlanIntent; members: Array<ActivationMember & { item?: ProposedItem }> };
+
+/**
+ * Plans a managed publication without locks (the activation rechecks everything under them): a held result is recorded
+ * as held and admits nothing; otherwise every proposed item is a member (`create` when no live row holds its key, else
+ * `overwrite`, so stamps such as the completion hash stay current), and every retirement a `retire` member.
+ */
+export async function planManagedGeneration<C>(engine: BrainEngine, adapter: GenerationAdapter<C>, request: PublishRequest<C>,
+ opts: { retiredBy?: DerivedRetiredBy; locator?: string | null; scope?: string | null } = {}): Promise<ManagedPlan> {
+ const config = await readGenerationsConfig(engine);
+ const live = await readLiveGeneration(engine, request.key);
+ const planned: PublishRequest<C> = { ...request, expectedGeneration: request.expectedGeneration ?? live?.generation ?? 0 };
+ const setHash = requestSetHash(planned);
+ const stopped = await exhaustedHold(engine, planned as PublishRequest<unknown>, config, setHash);
+ if (stopped?.state === 'held') return { kind: 'held', outcome: stopped };
+ const { input, rows, plan } = await planPublication(engine, adapter, planned, config, live);
+ if (request.input && input?.pin !== request.input.pin) throw generationFenced('pin_moved', request.key, 'its input changed after the producer read it');
+ if (plan.kind === 'held') {
+ const outcome = await engine.transaction(tx => recordHeld(tx, request.key, config, planned as PublishRequest<unknown>, setHash, plan.reason, plan.context));
+ return { kind: 'held', outcome: outcome as Extract<PublishOutcome, { state: 'held' }> };
+ }
+ if (plan.kind === 'unchanged' && !request.items.length) return { kind: 'unchanged' };
+ const retires = plan.kind === 'publish' ? plan.retires : [];
+ const members: Array<ActivationMember & { item?: ProposedItem }> = [
+ ...request.items.map(item => { const row = rows.get(item.key);
+ return row?.live ? { slug: item.key, action: 'overwrite' as const, identity: item.identityHash, before: row.identityHash, item }
+ : { slug: item.key, action: 'create' as const, identity: item.identityHash, before: null, item }; }),
+ ...retires.map(slug => ({ slug, action: 'retire' as const, identity: rows.get(slug)!.identityHash, before: rows.get(slug)!.identityHash })),
+ ];
+ const operationId = publishOperationId(planned as PublishRequest<unknown>, setHash);
+ const kept = request.approved && plan.kind === 'publish' ? plan.kept : [];
+ return { kind: 'publish', members, intent: { kind: GENERATION_ACTIVATE_INTENT, activationId: activationRequestId(operationId, opts.scope ?? null), key: request.key,
+ expectedGeneration: planned.expectedGeneration!, input: request.input ?? input, operationId, setHash, runId: request.runId ?? null, partial: request.partial === true,
+ proof: request.proof ?? null, retiredBy: request.approved?.retiredBy ?? opts.retiredBy ?? adapter.retiredBy, approved: request.approved !== undefined,
+ members: members.map(({ item: _item, ...member }) => member), kept, carried: plan.kind === 'publish' ? plan.carried : [],
+ context: request.context ?? null, locator: opts.locator ?? null } };
+}
+
+/** Records an admitted activation and its members, in the admission transaction (before any member runs). */
+export async function recordActivation(tx: BrainEngine, intent: ActivationPlanIntent): Promise<void> {
+ await tx.executeRaw(`INSERT INTO derived_generation_activations (id, source_id, kind, owner_key, expected_generation, input_pin, item_set_hash, state, members)
+ VALUES ($1,$2,$3,$4,$5,$6,$7,'pending',$8::text::jsonb) ON CONFLICT (id) DO NOTHING`,
+ [intent.activationId, intent.key.sourceId, intent.key.kind, intent.key.ownerKey, intent.expectedGeneration, intent.input?.pin ?? null, intent.setHash,
+ JSON.stringify(intent.members.map(member => ({ slug: member.slug, action: member.action, identity: member.identity })))]);
+}
+
+const memberFix = (sourceId: string, kind: string) => readFix('Lists pending generation members and orphan candidates, read-only.',
+ { argv: ['gbrain', 'repair', 'generations', '--kind', kind, '--mode', 'pending', '--source', sourceId, '--json'] });
+
+/** Preparer of `managed_generation_activate` (trusted local only): the ledger flip and the retire_pending marks; it writes no page or file. */
+export async function prepareGenerationActivation(engine: BrainEngine, row: WriteRequest): Promise<PreparedMutation> {
+ const p = row.intent as ActivationIntent | null;
+ const adapter = p?.key ? generationAdapter(p.key.kind) : undefined;
+ if (!p || p.kind !== GENERATION_ACTIVATE_INTENT || row.authority.remote || !adapter || p.key.sourceId !== row.source_id || p.activationId !== row.request_id) {
+ throw opError('permission_denied', 'Unsupported generation activation request.',
+ `Request ${row.request_id} in source ${row.source_id} is not a generation activation the trusted local writer admitted, so the coordinator refused it before any change. Activations run only from the gbrain CLI on the brain host.`,
+ { fix: readFix('Shows the source owner and any write in flight, read-only.', { argv: ['gbrain', 'sources', 'writer', 'status', '--source', row.source_id, '--json'] }) });
+ }
+ const memberKeys = [...new Set([...p.members.map(member => member.slug), ...p.kept])];
+ return { observedRevision: null, noop: true, additionalPageKeys: adapter.lockKeys(p.key, memberKeys),
+ validate: async tx => { await tx.executeRaw('SELECT pg_advisory_xact_lock(hashtext($1)::bigint)', [generationKeyLock(p.key)]); },
+ apply: async tx => {
+ const live = await readLiveGeneration(tx, p.key);
+ if ((live?.generation ?? 0) !== p.expectedGeneration) {
+ throw generationFenced('stale_generation', p.key, `the live generation is ${live?.generation ?? 0}, the producer planned against ${p.expectedGeneration} (activation ${p.activationId})`);
+ }
+ const input = await adapter.readInput(tx, p.key, p.context);
+ if (p.proof ? !proofHolds(p.proof, input, live?.inputPin) : (p.input && input?.pin !== p.input.pin)) {
+ throw generationFenced('pin_moved', p.key, `its input changed after the producer read it (activation ${p.activationId})`);
+ }
+ const rows = await adapter.readItems(tx, p.key, memberKeys, p.context);
+ const wrong = p.members.filter(member => { const current = rows.get(member.slug);
+ return !current?.live || current.identityHash !== (member.action === 'create' ? member.identity : member.before); }).map(member => member.slug);
+ if (wrong.length) throw liveConflict(p.key, wrong);
+ const items: LedgerItem[] = [
+ ...p.members.map(member => { const current = rows.get(member.slug)!;
+ if (member.action === 'create') return { key: member.slug, identityHash: member.identity, action: 'published' as const };
+ if (member.action === 'retire') return { key: member.slug, identityHash: member.identity, action: 'retired' as const, preimage: current.preimage(), pending: true };
+ return member.identity === member.before ? { key: member.slug, identityHash: member.identity, action: 'kept' as const, pending: true }
+ : { key: member.slug, identityHash: member.identity, action: 'published' as const, preimage: current.preimage(), pending: true }; }),
+ ...p.kept.filter(slug => rows.get(slug)?.live).map(slug => ({ key: slug, identityHash: rows.get(slug)!.identityHash, action: 'kept' as const })),
+ ...p.carried.filter(slug => live?.items.has(slug)).map(slug => ({ key: slug, identityHash: live!.items.get(slug)!, action: 'kept' as const })),
+ ];
+ const activated = await activateGeneration(tx, p.key, live, { operationId: p.operationId, runId: p.runId ?? undefined, input, setHash: p.setHash,
+ completeness: { complete: !p.partial, proof: p.proof?.kind ?? null, managed: true, ...(p.approved ? { approved: p.retiredBy } : {}) },
+ activationId: p.activationId, locator: p.locator }, items);
+ await tx.executeRaw(`UPDATE derived_generation_activations SET state='activated', generation_id=$2, updated_at=now() WHERE id=$1`, [p.activationId, activated.id]);
+ const retires = p.members.filter(member => member.action === 'retire').length;
+ if (retires) await bumpValve(tx, p.key, p.runId ?? undefined, retires);
+ return { activation_id: p.activationId, generation: activated.generation, members: p.members.length, pending: items.filter(item => item.pending).length };
+ } };
+}
+
+/**
+ * Refuses a member overwrite or retirement unless its item is pending on the live generation its activation made:
+ * an activation that never happened, a generation superseded since, or an item already settled changes nothing.
+ */
+export async function assertMemberPending(db: BrainEngine, row: Pick<WriteRequest, 'request_id' | 'source_id' | 'slug'>, activationId: string, kind: string): Promise<void> {
+ await faultPoint('generation:member', { sourceId: row.source_id, operation: kind });
+ const [state] = await db.executeRaw<{ state: string; generation_state: string | null; pending: boolean | null }>(
+ `SELECT a.state, g.state AS generation_state, i.pending FROM derived_generation_activations a
+ LEFT JOIN derived_generations g ON g.id=a.generation_id
+ LEFT JOIN derived_generation_items i ON i.generation_id=a.generation_id AND i.item_key=$2
+ WHERE a.id=$1 AND a.source_id=$3`, [activationId, row.slug, row.source_id]);
+ const why = !state || state.state !== 'activated' ? 'its generation was never activated'
+ : state.generation_state !== 'live' ? 'a later generation superseded it' : state.pending !== true ? 'the item is already settled' : null;
+ if (!why) return;
+ throw opError('revision_conflict', `The generation member was not applied: ${why}.`,
+ `Request ${row.request_id} would overwrite or retire ${row.slug} in source ${row.source_id} for activation ${activationId}, but ${why}, so the page keeps its content. Read the pending list; nothing needs undoing.`,
+ { fix: memberFix(row.source_id, kind) });
+}
+
+/** Clears an item's pending mark once its member request committed (in the member's publication transaction). */
+export async function settleMember(tx: BrainEngine, activationId: string, slug: string): Promise<void> {
+ await tx.executeRaw(`UPDATE derived_generation_items SET pending=false
+ WHERE generation_id=(SELECT generation_id FROM derived_generation_activations WHERE id=$1) AND item_key=$2`, [activationId, slug]);
+}
+
+export interface PendingMember { source_id: string; kind: string; owner_key: string; generation_id: number; activation_id: string; slug: string; action: 'overwrite' | 'retire'; identity: string }
+
+/** Items live generations still wait on a member request for (retire_pending and pending overwrites). */
+export async function listPendingMembers(db: BrainEngine, sourceIds: readonly string[], kind?: string): Promise<PendingMember[]> {
+ const rows = await db.executeRaw<PendingMember & { item_action: string }>(
+ `SELECT g.source_id, g.kind, g.owner_key, g.id AS generation_id, g.activation_id, i.item_key AS slug, i.action AS item_action, i.identity_hash AS identity
+ FROM derived_generation_items i JOIN derived_generations g ON g.id=i.generation_id
+ WHERE i.pending AND g.state='live' AND g.source_id=ANY($1::text[]) AND ($2::text IS NULL OR g.kind=$2) ORDER BY g.source_id, g.kind, g.owner_key, i.item_key`,
+ [[...sourceIds], kind ?? null]);
+ return rows.map(row => ({ source_id: row.source_id, kind: row.kind, owner_key: row.owner_key, generation_id: Number(row.generation_id), activation_id: row.activation_id,
+ slug: row.slug, action: row.item_action === 'retired' ? 'retire' as const : 'overwrite' as const, identity: row.identity }));
+}
+
+export interface OrphanCandidate { source_id: string; kind: string; owner_key: string; activation_id: string; slug: string; created_at: string }
+
+/**
+ * Pages a `create` member wrote for an activation that never happened (its request ended without committing, or was
+ * never journaled) that no live generation owns. Listed for the operator; never retired automatically.
+ */
+export async function listOrphanCandidates(db: BrainEngine, sourceIds: readonly string[], kind?: string): Promise<OrphanCandidate[]> {
+ const rows = await db.executeRaw<OrphanCandidate>(
+ `SELECT a.source_id, a.kind, a.owner_key, a.id AS activation_id, m->>'slug' AS slug, a.created_at::text AS created_at
+ FROM derived_generation_activations a CROSS JOIN LATERAL jsonb_array_elements(a.members) m
+ WHERE a.state='pending' AND a.source_id=ANY($1::text[]) AND ($2::text IS NULL OR a.kind=$2) AND m->>'action'='create'
+ AND NOT EXISTS (SELECT 1 FROM persistence_requests r WHERE r.request_id=a.id::uuid AND r.state IN ('queued','running','recovering'))
+ AND EXISTS (SELECT 1 FROM pages p WHERE p.source_id=a.source_id AND p.slug=m->>'slug' AND p.deleted_at IS NULL)
+ AND NOT EXISTS (SELECT 1 FROM derived_generation_items i JOIN derived_generations g ON g.id=i.generation_id
+ WHERE g.source_id=a.source_id AND g.kind=a.kind AND g.state='live' AND i.item_key=m->>'slug' AND i.action<>'retired')
+ ORDER BY a.source_id, a.kind, a.owner_key, slug`, [[...sourceIds], kind ?? null]);
+ return rows;
+}
diff --git a/src/core/generations/plan.ts b/src/core/generations/plan.ts
index 6dac3c213f..b5d2a08b25 100644
--- a/src/core/generations/plan.ts
+++ b/src/core/generations/plan.ts
@@ -11,7 +11,7 @@ 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> }
+export interface LiveGeneration { id: number; generation: number; inputPin: string | null; inputSize: number | null; items: Map<string, string>; locator?: string | null }
/** 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;
@@ -32,6 +32,8 @@ export interface PlanInput {
valve: { windowRetired: number; ownedTotal: number };
/** The held reason an operator release overrides (`shrunk`, `valve`, `attempts_exhausted`). */
release?: HeldReason;
+ /** An operator-approved retirement (a previewed repair): retire exactly these live owned keys, keep the rest; no floor or valve. */
+ approvedRetire?: readonly string[];
}
export type Plan =
@@ -41,6 +43,7 @@ export type Plan =
export function planGeneration(input: PlanInput): Plan {
const { live, rows, proposal, config } = input;
+ if (input.approvedRetire) return planApprovedRetirement(input, input.approvedRetire);
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));
@@ -69,7 +72,7 @@ export function planGeneration(input: PlanInput): Plan {
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');
+ && 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);
@@ -81,6 +84,16 @@ export function planGeneration(input: PlanInput): Plan {
return { kind: 'publish', puts, kept, adopted, retires, carried, protectedKeys };
}
+/** A previewed operator retirement: the approved keys still live and owned retire, every other live item is kept. */
+function planApprovedRetirement(input: PlanInput, approved: readonly string[]): Plan {
+ const recorded = [...(input.live?.items.keys() ?? [])].filter(key => input.rows.get(key)?.live);
+ const retires = [...new Set(approved)].filter(key => input.rows.get(key)?.live && (input.rows.get(key)?.owned || recorded.includes(key))).sort();
+ const protectedKeys = [...input.rows.values()].filter(row => row.owned && row.live && !recorded.includes(row.key) && !retires.includes(row.key)).map(row => row.key).sort();
+ if (retires.some(key => input.rows.get(key)?.segmented)) return { kind: 'held', reason: 'segmented_unsupported', context: { retires: retires.length } };
+ if (!retires.length) return { kind: 'unchanged', protectedKeys };
+ return { kind: 'publish', puts: [], kept: recorded.filter(key => !retires.includes(key)).sort(), 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/publish.ts b/src/core/generations/publish.ts
index c959b4c315..03a29c4a88 100644
--- a/src/core/generations/publish.ts
+++ b/src/core/generations/publish.ts
@@ -15,8 +15,9 @@ 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 type { DerivedRetiredBy } from '../persistence/derived-retirement-hold.ts';
+import type { GenerationAdapter, GenerationKey, HeldReason, InputState, ItemRow, Preimage, ProposedItem } from './contract.ts';
+import { planGeneration, type LiveGeneration, type Plan } 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. */
@@ -37,6 +38,10 @@ export interface PublishRequest<C = unknown> {
context?: C;
/** An operator release of this held row (repair generations --mode release-held). */
release?: { holdId: string; reason: HeldReason };
+ /** A previewed operator retirement (`gbrain repair stale-atoms`): retire exactly these keys, stamped `retiredBy`; `items` is ignored. */
+ approved?: { retire: readonly string[]; retiredBy: DerivedRetiredBy };
+ /** A transcript key's current file, recorded on the generation so a moved file keeps its key. */
+ locator?: string;
}
export type PublishOutcome =
@@ -49,50 +54,55 @@ export function itemSetHash(items: readonly Pick<ProposedItem, 'key' | 'identity
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}`;
+/** The advisory lock name of a generation key (taken after its page locks, D7). */
+export const generationKeyLock = (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)]);
+ await tx.executeRaw('SELECT pg_advisory_xact_lock(hashtext($1)::bigint)', [generationKeyLock(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'`,
+ const [row] = await db.executeRaw<{ id: number; generation: number; input_pin: string | null; input_size: number | null; locator: string | null }>(
+ `SELECT id, generation, input_pin, input_size, locator 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])) };
+ items: new Map(items.map(item => [item.item_key, item.identity_hash])), locator: row.locator };
}
-function fenced(reason: 'stale_generation' | 'pin_moved', key: GenerationKey, detail: string) {
+export function generationFenced(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#publishing' });
}
-export interface LedgerItem { key: string; identityHash: string; action: 'published' | 'retired' | 'revived' | 'kept' | 'adopted'; preimage?: Preimage }
+/** `pending`: a managed member request still has to overwrite or retire the item (it stays live until then). */
+export interface LedgerItem { key: string; identityHash: string; action: 'published' | 'retired' | 'revived' | 'kept' | 'adopted'; preimage?: Preimage; pending?: boolean }
/** 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;
+ activationId?: string; locator?: string | null;
}, 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::text::jsonb,$10,$11) RETURNING id`,
+ `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,
+ activation_id, locator)
+ VALUES ($1,$2,$3,$4,'live',$5,$6,$7,$8,$9::text::jsonb,$10,$11,$12,$13) 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]);
+ JSON.stringify(row.completeness), row.setHash, row.restoreOf ?? null, row.activationId ?? null, row.locator ?? live?.locator ?? 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::text::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(`INSERT INTO derived_generation_items (generation_id, item_key, identity_hash, action, preimage, preimage_bytes, pending)
+ VALUES ($1,$2,$3,$4,$5::text::jsonb,$6,$7)`,
+ [id, item.key, item.identityHash, item.action, item.preimage?.json ? JSON.stringify(item.preimage.json) : null, item.preimage?.bytes ?? null, item.pending === true]);
}
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]);
await tx.executeRaw('DELETE FROM derived_generation_attempts WHERE source_id=$1 AND kind=$2 AND owner_key=$3', [key.sourceId, key.kind, key.ownerKey]);
@@ -104,10 +114,13 @@ export async function assertItemsLive(tx: BrainEngine, adapter: GenerationAdapte
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#publishing' });
- }
+ if (wrong.length) throw liveConflict(key, wrong);
+}
+
+/** `generation_live_conflict`: these items are not live at the identity the generation records. */
+export function liveConflict(key: GenerationKey, wrong: readonly string[]) {
+ return 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#publishing' });
}
/** A held result's identity: key, input pin, policy, item set and reason. The attempts counter and `heldForInput` share it. */
@@ -118,7 +131,7 @@ function holdIdFor(key: GenerationKey, pin: string | null, config: GenerationsCo
/** Terminal failures of one hold identity before its result is held `attempts_exhausted` (plan D2, CEO r3 F4). */
export const MAX_GENERATION_ATTEMPTS = 3;
-async function recordHeld(tx: BrainEngine, key: GenerationKey, config: GenerationsConfig, request: PublishRequest<unknown>, setHash: string,
+export async function recordHeld(tx: BrainEngine, key: GenerationKey, config: GenerationsConfig, request: PublishRequest<unknown>, setHash: string,
reason: HeldReason, context: Record<string, unknown>): Promise<PublishOutcome> {
const holdId = holdIdFor(key, request.input?.pin ?? null, config, setHash, reason);
const [existing] = await tx.executeRaw<{ id: number; hold_id: string }>(
@@ -173,19 +186,67 @@ function logFailure(key: GenerationKey, operationId: string, mode: 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)}`);
}
+/** The set hash an operation binds: the proposal, or for an approved retirement the keys it retires. */
+export function requestSetHash(request: Pick<PublishRequest<unknown>, 'items' | 'approved'>): string {
+ return request.approved ? digest(['generation-approved-retire-v1', [...request.approved.retire].sort(), request.approved.retiredBy]) : itemSetHash(request.items);
+}
+
+/** The operation identity an identical replay matches (D2): kind, key, expected generation, input pin and result item-set hash. */
+export function publishOperationId(request: PublishRequest<unknown>, setHash: string): string {
+ return digest(['generation-publish-v1', request.key, request.expectedGeneration ?? null, request.input?.pin ?? null, setHash,
+ request.partial === true, request.release?.holdId ?? null]);
+}
+
+/** The held `attempts_exhausted` outcome this result already stopped at, or null (an operator release never stops here). */
+export async function exhaustedHold(db: BrainEngine, request: PublishRequest<unknown>, config: GenerationsConfig, setHash: string): Promise<PublishOutcome | null> {
+ if (request.release) return null;
+ const { key } = request;
+ const exhausted = holdIdFor(key, request.input?.pin ?? null, config, setHash, 'attempts_exhausted');
+ const [stopped] = await db.executeRaw<{ held_context: Record<string, unknown> | null }>(
+ `SELECT held_context FROM derived_generations WHERE source_id=$1 AND kind=$2 AND owner_key=$3 AND state='held' AND hold_id=$4`, [key.sourceId, key.kind, key.ownerKey, exhausted]);
+ return stopped ? { state: 'held', reason: 'attempts_exhausted', holdId: exhausted, context: stopped.held_context ?? {} } : null;
+}
+
+/** Reads the input, the items and the valve and plans the result (plan.ts); under the key lock for a publication, unlocked for a managed preview. */
+export async function planPublication<C>(db: BrainEngine, adapter: GenerationAdapter<C>, request: PublishRequest<C>, config: GenerationsConfig,
+ live: LiveGeneration | null, extraKeys: readonly string[] = []): Promise<{ input: InputState | null; rows: Map<string, ItemRow>; plan: Plan }> {
+ const { key } = request;
+ const itemKeys = [...new Set([...request.items.map(item => item.key), ...(request.approved?.retire ?? []), ...(live?.items.keys() ?? []), ...extraKeys])];
+ const named = new Set([...request.items.map(item => item.key), ...(request.approved?.retire ?? [])]);
+ const input = await adapter.readInput(db, key, request.context);
+ const rows = await adapter.readItems(db, key, itemKeys, request.context);
+ const unrecorded = [...rows.values()].filter(row => row.owned && row.live && !live?.items.has(row.key) && !named.has(row.key));
+ const evidence = unrecorded.length ? await adapter.legacyEvidence(db, key, unrecorded) : new Set<string>();
+ const valve = await readValve(db, key, request.runId);
+ const plan = planGeneration({ live, rows, proposal: request.items, input, config, modelProduced: adapter.modelProduced, strictOrder: adapter.strictOrder, additive: request.partial === true,
+ proofHolds: request.proof ? proofHolds(request.proof, input, live?.inputPin) : false, evidence, valve, release: request.release?.reason, approvedRetire: request.approved?.retire });
+ return { input, rows, plan };
+}
+
+/** The ledger rows of a publish plan; `pending` marks the items a managed member request still overwrites or retires. */
+export function ledgerItems(plan: Extract<Plan, { kind: 'publish' }>, rows: ReadonlyMap<string, ItemRow>, live: LiveGeneration | null,
+ pending: { overwrites?: ReadonlySet<string>; retires?: boolean } = {}): LedgerItem[] {
+ const preimage = (itemKey: string) => rows.get(itemKey)?.preimage();
+ const rewritten = (itemKey: string) => pending.overwrites?.has(itemKey) === true;
+ return [
+ ...plan.puts.map(item => ({ key: item.key, identityHash: item.identityHash, action: 'published' as const,
+ ...(rows.get(item.key)?.live ? { preimage: preimage(item.key) } : {}), ...(rewritten(item.key) ? { pending: true } : {}) })),
+ ...plan.kept.map(itemKey => ({ key: itemKey, identityHash: rows.get(itemKey)!.identityHash, action: 'kept' as const, ...(rewritten(itemKey) ? { pending: true } : {}) })),
+ ...plan.adopted.map(itemKey => ({ key: itemKey, identityHash: rows.get(itemKey)!.identityHash, action: 'adopted' as const, ...(rewritten(itemKey) ? { pending: true } : {}) })),
+ ...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),
+ ...(pending.retires ? { pending: true } : {}) })),
+ ];
+}
+
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);
- if (!request.release) {
- const exhausted = holdIdFor(key, request.input?.pin ?? null, config, setHash, 'attempts_exhausted');
- const [stopped] = await engine.executeRaw<{ held_context: Record<string, unknown> | null }>(
- `SELECT held_context FROM derived_generations WHERE source_id=$1 AND kind=$2 AND owner_key=$3 AND state='held' AND hold_id=$4`, [key.sourceId, key.kind, key.ownerKey, exhausted]);
- if (stopped) return { state: 'held', reason: 'attempts_exhausted', holdId: exhausted, context: stopped.held_context ?? {} };
- }
+ const setHash = requestSetHash(request);
+ const operationId = publishOperationId(request as PublishRequest<unknown>, setHash);
+ const itemKeys = [...request.items.map(item => item.key), ...(request.approved?.retire ?? [])];
+ const stopped = await exhaustedHold(engine, request as PublishRequest<unknown>, config, setHash);
+ if (stopped) return stopped;
try {
const outcome = await maintenanceTransaction(engine, async tx => {
await lockGeneration(tx, adapter as GenerationAdapter<unknown>, key, itemKeys);
@@ -193,38 +254,25 @@ export async function publishGeneration<C>(engine: BrainEngine, adapter: Generat
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}`);
+ throw generationFenced('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, strictOrder: adapter.strictOrder, additive: request.partial === true,
- proofHolds: request.proof ? proofHolds(request.proof, input, live?.inputPin) : false, evidence, valve, release: request.release?.reason });
+ const { input, rows, plan } = await planPublication(tx, adapter, request, config, live);
+ if (request.input && input?.pin !== request.input.pin) throw generationFenced('pin_moved', key, 'its input changed after the producer read it');
if (plan.kind === 'held') return recordHeld(tx, key, config, request, setHash, plan.reason, plan.context);
if (plan.kind === 'unchanged') {
if (!request.partial) await adapter.completeItems?.(tx, key, itemKeys, request.context);
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 adapter.retireItems(tx, key, plan.retires, request.approved?.retiredBy ?? 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);
+ const activated = await activateGeneration(tx, key, live, { operationId, runId: request.runId, input, setHash, locator: request.locator,
+ completeness: { complete: !request.partial, proof: request.proof?.kind ?? null, released: request.release?.reason ?? null,
+ ...(request.approved ? { approved: request.approved.retiredBy } : {}) } }, ledgerItems(plan, rows, live));
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;
@@ -244,7 +292,7 @@ export async function publishGeneration<C>(engine: BrainEngine, adapter: Generat
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 }> {
+export 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
@@ -253,7 +301,7 @@ async function readValve(tx: BrainEngine, key: GenerationKey, runId: string | un
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> {
+export 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/atom-maintenance.ts b/src/core/persistence/atom-maintenance.ts
index d0e34397b1..61ff1d7462 100644
--- a/src/core/persistence/atom-maintenance.ts
+++ b/src/core/persistence/atom-maintenance.ts
@@ -22,6 +22,12 @@ import type { WriteReceipt } from './types.ts';
import { MAX_DETERMINISTIC_FAILURES, writeAtomPageState } from '../cycle/extract-atoms-page-state.ts';
import { effectiveVisibility } from '../search/private-visibility.ts';
import { declareDerivation, deriveTrust, lowerToDerivedTier, recordTaintEdges } from '../trust/taint.ts';
+import type { DerivedRetiredBy } from './derived-retirement-hold.ts';
+import type { GenerationKey } from '../generations/contract.ts';
+import { atomGenerationAdapter, atomPagePin, type AtomGenerationContext } from '../generations/adapters/atoms.ts';
+import { markdownItem } from '../generations/adapters/page.ts';
+import { assertMemberPending, GENERATION_ACTIVATE_SLUG, listPendingMembers, memberRequestId, planManagedGeneration,
+ recordActivation, settleMember, type ActivationIntent } from '../generations/managed.ts';
export interface AtomOrigin {
kind: 'page' | 'transcript';
@@ -63,6 +69,14 @@ export interface AtomIntent extends Record<string, unknown> {
failure?: string;
checkpointKey?: string;
expectedCheckpoint?: unknown;
+ /** GBRA-161 PR 1b: the generation activation this member belongs to (absent on a batch admitted before the ledger). */
+ activationId?: string;
+ /** A page member: create (a new identity, admitted before the activation) or overwrite (after it, pending on it). */
+ phase?: 'create' | 'overwrite';
+ /** A retirement member's stamp (the extractor's, or stale-atoms for an approved repair). */
+ retiredBy?: DerivedRetiredBy;
+ /** The generation key the batch publishes, so a retry republishes under the same key. */
+ generationKey?: GenerationKey;
}
const ownerStatusFix = (sourceId: string): Action => readFix(
@@ -280,6 +294,165 @@ function atomRequestId(key: string, slug: string): string {
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-8${hex.slice(13, 16)}-a${hex.slice(17, 20)}-${hex.slice(20, 32)}`;
}
+/** The input pin an origin was read at, as the atom adapter reads it under the activation's locks. */
+export function atomOriginPin(origin: AtomOrigin): string {
+ return origin.kind === 'page'
+ ? atomPagePin(origin.contentHash, origin.pageId !== null && origin.revision ? { pageId: origin.pageId, revision: origin.revision } : undefined)
+ : origin.textHash;
+}
+const originInput = (origin: AtomOrigin, content: string | null) => ({ pin: atomOriginPin(origin), size: Buffer.byteLength(content ?? '') });
+
+export interface ManagedAtomGeneration {
+ key: GenerationKey;
+ /** The origin text the model read (its size is the input size the floor scales by). */
+ content: string | null;
+ context?: AtomGenerationContext;
+ runId?: string;
+ /** A transcript key's current file. */
+ locator?: string | null;
+ /** A previewed operator retirement (gbrain repair stale-atoms): retires exactly these atoms; no extraction is completed. */
+ approved?: { retire: string[]; retiredBy: DerivedRetiredBy };
+}
+
+export type ManagedAtomPublication =
+ | { state: 'held'; reason: string; holdId: string; receipts: WriteReceipt[] }
+ | { state: 'admitted' | 'unchanged'; receipts: WriteReceipt[]; activationId?: string };
+
+/**
+ * GBRA-161 PR 1b: publishes one origin's atoms as a managed generation (generations/managed.ts). A held result admits
+ * nothing (no completion either, so the input is not marked done; the extractor skips it while the hold stands). An
+ * unchanged empty result completes the extraction only. Otherwise one admission transaction records the activation and
+ * admits, in order: create page members (new identities), the managed_generation_activate request, overwrite page
+ * members, retire delete members and the completion; every member id is digest(activation id, slug, action).
+ */
+export async function publishManagedAtomGeneration(engine: BrainEngine, session: ManagedAtomSession, origin: AtomOrigin,
+ atoms: Array<{ slug: string; content: string; links: LinkBatchInput[] }>, generation: ManagedAtomGeneration): Promise<ManagedAtomPublication> {
+ const context: AtomGenerationContext = { ...generation.context, ...(origin.kind === 'transcript' ? { locator: origin.locator, verifyFile: true } : {}) };
+ const claim = atomClaim(session, origin);
+ const plan = await planManagedGeneration(engine, atomGenerationAdapter, { key: generation.key, items: atoms.map(atom => markdownItem(atom.slug, atom.content)),
+ input: generation.approved ? undefined : originInput(origin, generation.content), partial: Boolean(origin.partialInputChars), context, runId: generation.runId,
+ approved: generation.approved }, { retiredBy: ATOM_RETIRED_BY_REEXTRACT, scope: generation.approved ? null : claim.runKey, locator: generation.locator ?? (origin.kind === 'transcript' ? origin.locator : null) });
+ if (plan.kind === 'held') return { state: 'held', reason: plan.outcome.reason, holdId: plan.outcome.holdId, receipts: [] };
+ if (plan.kind === 'unchanged') return { state: 'unchanged', receipts: generation.approved ? [] : await publishManagedAtoms(engine, session, origin, []) };
+ const runKey = generation.approved ? digest(['managed-atoms-approved', plan.intent.activationId]) : claim.runKey;
+ const advance = !generation.approved && claim.checkpointKey ? { checkpointKey: claim.checkpointKey, expectedCheckpoint: claim.expectedCheckpoint ?? null } : {};
+ const { activationId } = plan.intent;
+ const bySlug = new Map(atoms.map(atom => [atom.slug, atom]));
+ type Admission = { slug: string; pageId: number | null; requestId: string; intent: Record<string, unknown>; child: boolean };
+ const inputs: Admission[] = [];
+ const later: Admission[] = [];
+ for (const member of plan.members) {
+ await authorizeWrite(engine, session.authority, member.action === 'retire' ? 'delete_page' : 'put_page', member.slug);
+ const snapshot = await engine.readPageSnapshot(member.slug, { sourceId: session.sourceId, includeDeleted: true });
+ const requestId = memberRequestId(activationId, member.slug, member.action);
+ const shared = { runKey, origin, activationId, generationKey: generation.key, ...advance };
+ if (member.action === 'retire') {
+ if (!snapshot || snapshot.page.deleted_at) throw opError('page_identity_changed', 'An atom the generation retires changed before admission.',
+ `Atom ${member.slug} in source ${session.sourceId} was removed after the generation was planned; nothing was admitted. Run the producer again.`, { fix: pageFix(session.sourceId, member.slug) });
+ later.push({ slug: member.slug, pageId: snapshot.page.id, requestId, child: true, intent: { kind: 'managed_atom_delete', ...shared,
+ expected_revision: snapshot.revision, retiredBy: plan.intent.retiredBy } });
+ continue;
+ }
+ const atom = bySlug.get(member.slug)!;
+ if (snapshot && ((snapshot.page.deleted_at && !snapshot.page.frontmatter.retired_by) || snapshot.page.type !== 'atom' ||
+ (origin.kind === 'page' ? snapshot.page.frontmatter.source_slug !== origin.locator : snapshot.page.frontmatter.source_path !== origin.locator))) {
+ throw opError('page_identity_changed', 'The atom target belongs to another origin or was removed.',
+ `Atom slug ${member.slug} in source ${session.sourceId} is held by a page this extraction does not own (another origin, a non-atom page or a deleted page); nothing was admitted. Read that page; whether to move or remove it is the user's decision.`,
+ { fix: pageFix(session.sourceId, member.slug) });
+ }
+ const entry: Admission = { slug: member.slug, pageId: snapshot?.page.id ?? null, requestId, child: true, intent: { kind: 'managed_atom_page', ...shared, phase: member.action,
+ ...(snapshot ? { expected_revision: snapshot.revision } : {}), content: atom.content, links: atom.links } };
+ (member.action === 'create' ? inputs : later).push(entry);
+ }
+ const activation: ActivationIntent = { ...plan.intent, runKey };
+ inputs.push({ slug: GENERATION_ACTIVATE_SLUG, pageId: null, requestId: activationId, child: false, intent: activation });
+ inputs.push(...later);
+ const rows = await engine.transaction(async tx => {
+ await recordActivation(tx, plan.intent);
+ const children: string[] = [];
+ const accepted: WriteRequest[] = [];
+ const complete: Admission[] = generation.approved ? [] : [{ slug: '__managed_atom_complete__', pageId: null, requestId: atomRequestId(runKey, '__managed_atom_complete__'), child: false,
+ intent: { kind: 'managed_atom_complete', runKey, origin, children, activationId, generationKey: generation.key, ...advance } }];
+ for (const input of [...inputs, ...complete]) {
+ const row = await admitWriteInTransaction(tx, { principal: session.authority.principal, authority: session.authority,
+ operation: 'submit_job', sourceId: session.sourceId, sourceIncarnation: session.incarnation,
+ worktreeId: session.binding?.worktree_id, topologyGeneration: session.binding?.topology_generation,
+ slug: input.slug, pageId: input.pageId, requestId: input.requestId, callerIntent: input.intent, intent: input.intent });
+ accepted.push(row);
+ if (input.child) children.push(row.id);
+ }
+ return accepted;
+ });
+ return { state: 'admitted', activationId, receipts: await waitAtomReceipts(engine, session, rows) };
+}
+
+async function waitAtomReceipts(engine: BrainEngine, session: ManagedAtomSession, rows: WriteRequest[]): Promise<WriteReceipt[]> {
+ const receipts: WriteReceipt[] = [];
+ for (const row of rows) {
+ const finished = session.wait.observe(await waitForWrite(engine, row, session.config, session.wait.ms()));
+ try { writeResponse(finished); }
+ catch (error) {
+ // #5601: an accepted batch still publishing is progress; its deterministic request ids resume it next run.
+ const pending = acceptedPendingReceipt(error);
+ if (!pending) throw error;
+ receipts.push(pending);
+ continue;
+ }
+ receipts.push(receiptFor(finished));
+ }
+ return receipts;
+}
+
+export interface ResumedMember { slug: string; activation_id: string; action: 'overwrite' | 'retire'; outcome: 'waited' | 'resubmitted' | 'kept_edited' | 'unrecoverable' }
+
+/**
+ * GBRA-161 PR 1b: finishes what a crash after an activation left pending in this source. A member request still queued
+ * is waited on; one that ended without committing (or was never journaled) is submitted again under a fresh id bound to
+ * the failed one, unless its page changed since the activation planned it (then the page keeps its content and the mark
+ * clears: a person's edit wins). Returns one entry per pending member.
+ */
+export async function resumeManagedGenerationMembers(engine: BrainEngine, session: ManagedAtomSession): Promise<ResumedMember[]> {
+ const pending = await listPendingMembers(engine, [session.sourceId], atomGenerationAdapter.kind);
+ const resumed: ResumedMember[] = [];
+ for (const member of pending) {
+ let row = await getWriteRequest(engine, session.authority.principal, memberRequestId(member.activation_id, member.slug, member.action));
+ if (row && ['queued', 'running', 'recovering'].includes(row.state)) {
+ row = session.wait.observe(await waitForWrite(engine, row, session.config, session.wait.ms()));
+ if (row.state === 'committed') { resumed.push({ slug: member.slug, activation_id: member.activation_id, action: member.action, outcome: 'waited' }); continue; }
+ }
+ if (row?.state === 'committed') continue;
+ resumed.push({ slug: member.slug, activation_id: member.activation_id, action: member.action, outcome: await resubmitMember(engine, session, member, row) });
+ }
+ return resumed;
+}
+
+async function resubmitMember(engine: BrainEngine, session: ManagedAtomSession, member: Awaited<ReturnType<typeof listPendingMembers>>[number],
+ failed: WriteRequest | null): Promise<ResumedMember['outcome']> {
+ const [planned] = await engine.executeRaw<{ before: string | null }>(
+ `SELECT m->>'before' AS before FROM derived_generation_activations a CROSS JOIN LATERAL jsonb_array_elements(a.members) m WHERE a.id=$1 AND m->>'slug'=$2`,
+ [member.activation_id, member.slug]);
+ const snapshot = await engine.readPageSnapshot(member.slug, { sourceId: session.sourceId });
+ const rows = snapshot ? await atomGenerationAdapter.readItems(engine, { kind: member.kind, sourceId: member.source_id, ownerKey: member.owner_key }, [member.slug]) : new Map();
+ const current = rows.get(member.slug);
+ const before = member.action === 'retire' ? member.identity : planned?.before ?? null;
+ if (!snapshot || !current?.live || (current.identityHash !== before && current.identityHash !== member.identity)) {
+ await engine.transaction(tx => settleMember(tx, member.activation_id, member.slug));
+ return 'kept_edited';
+ }
+ const prior = failed?.intent as AtomIntent | null | undefined;
+ if (!prior?.origin || (member.action === 'overwrite' && typeof prior.content !== 'string')) return 'unrecoverable';
+ const intent: Record<string, unknown> = { ...prior, expected_revision: snapshot.revision };
+ delete intent.checkpointKey;
+ delete intent.expectedCheckpoint;
+ const requestId = memberRequestId(member.activation_id, member.slug, `${member.action}:after:${failed?.id ?? 'missing'}`);
+ const row = await engine.transaction(tx => admitWriteInTransaction(tx, { principal: session.authority.principal, authority: session.authority,
+ operation: 'submit_job', sourceId: session.sourceId, sourceIncarnation: session.incarnation,
+ worktreeId: session.binding?.worktree_id, topologyGeneration: session.binding?.topology_generation,
+ slug: member.slug, pageId: snapshot.page.id, requestId, callerIntent: intent, intent }));
+ await waitAtomReceipts(engine, session, [row]);
+ return 'resubmitted';
+}
+
async function atomBatchRows(engine: BrainEngine, session: ManagedAtomSession, key: string): Promise<WriteRequest[]> {
const completionId = atomRequestId(key, '__managed_atom_complete__');
const completion = await getWriteRequest(engine, session.authority.principal, completionId);
@@ -467,6 +640,9 @@ export async function prepareManagedAtomMutation(engine: BrainEngine, row: Write
`Request ${row.request_id} in source ${row.source_id} is not an atom maintenance intent the trusted local writer can publish, so the coordinator refused it before any change. Atom extraction runs only from the gbrain CLI on the brain host; inspect the owner before resubmitting anything.`,
{ fix: ownerStatusFix(row.source_id) });
}
+ // GBRA-161 PR 1b: an overwrite or retirement member runs only after its activation: the activation rechecked the input
+ // and the planned identities under the locks, so the member checks its item is pending on that live generation instead.
+ const gated = Boolean(p.activationId) && (p.kind === 'managed_atom_delete' || p.phase === 'overwrite');
const validate = async (tx: BrainEngine) => {
// A connector preflighted as unbound publishes database-only; one claimed since then must use its owner.
if (row.authority.databaseOnlyReason === 'connector_database' && await getWorktreeBinding(tx, row.source_id)) {
@@ -474,6 +650,7 @@ export async function prepareManagedAtomMutation(engine: BrainEngine, row: Write
`Connector source ${row.source_id} was claimed by a canonical owner after this database-only atom run started; request ${row.request_id} changed nothing. Run the atom drain on the owning host.`,
{ fix: ownerStatusFix(row.source_id) });
}
+ if (gated) { await assertMemberPending(tx, row, p.activationId!, 'atom'); return; }
if (p.origin.kind === 'transcript') {
if (sha256(readFileSync(p.origin.locator)) !== p.origin.textHash) throw opError('source_changed', 'The accepted atom transcript changed.',
`The transcript behind atom request ${row.request_id} in source ${row.source_id} was edited after acceptance, so the request published nothing. Run the atom drain again to extract the current file.`,
@@ -491,19 +668,20 @@ export async function prepareManagedAtomMutation(engine: BrainEngine, row: Write
await validate(engine);
const additionalPageKeys = p.origin.kind === 'page' ? [{ sourceId: row.source_id, slug: p.origin.locator }] : [];
if (p.kind === 'managed_atom_delete') {
- await replacementPublished(engine, row, p);
+ if (!p.activationId) await replacementPublished(engine, row, p);
await authorizeWrite(engine, row.authority, 'delete_page', row.slug);
const prepared = await preparePageMutation(engine, { ...row, operation: 'delete_page' }, config, undefined, undefined, { allowMissingFile: true });
return { ...prepared, additionalPageKeys, validate: async tx => {
await validate(tx);
- await replacementPublished(tx, row, p);
+ if (!p.activationId) await replacementPublished(tx, row, p);
await authorizeWrite(tx, row.authority, 'delete_page', row.slug);
await prepared.validate?.(tx);
}, apply: async tx => {
const result = await prepared.apply(tx);
if (!prepared.noop) {
await tx.executeRaw(`UPDATE pages SET frontmatter=frontmatter||jsonb_build_object('retired_by',$1::text,'retired_at',$2::text)
- WHERE id=$3 AND source_id=$4 AND deleted_at IS NOT NULL`, [ATOM_RETIRED_BY_REEXTRACT, new Date().toISOString(), row.page_id, row.source_id]);
+ WHERE id=$3 AND source_id=$4 AND deleted_at IS NOT NULL`, [p.retiredBy ?? ATOM_RETIRED_BY_REEXTRACT, new Date().toISOString(), row.page_id, row.source_id]);
+ if (p.activationId) await settleMember(tx, p.activationId, row.slug);
if (p.origin.kind === 'page' && p.origin.pageId !== null) {
await bumpAtomGeneration(tx, row.source_id, row.source_incarnation, p.origin.pageId, p.origin.contentHash);
}
@@ -526,6 +704,12 @@ export async function prepareManagedAtomMutation(engine: BrainEngine, row: Write
AND atom.knowledge_revision::text=r.outcome->>'revision' AND atom.deleted_at IS NULL)
OR (COALESCE(r.intent->>'kind',r.outcome->>'atom_kind')='managed_atom_delete'
AND atom.id=r.page_id AND atom.deleted_at IS NOT NULL))`, [children, row.source_incarnation, p.runKey]);
+ if (p.activationId) {
+ const [activation] = await tx.executeRaw<{ state: string }>('SELECT state FROM derived_generation_activations WHERE id=$1', [p.activationId]);
+ if (activation?.state !== 'activated') throw opError('revision_conflict', 'The atom batch\'s generation was not activated.',
+ `Activation ${p.activationId} of atom batch ${row.request_id} in source ${row.source_id} did not commit (another generation of its origin landed first, or an atom changed), so the batch was not marked complete; atoms it created are listed as orphan candidates and kept. The next atom drain extracts the source again.`,
+ { fix: receiptFix(p.activationId) });
+ }
if (committed.length !== children.length) throw opError('revision_conflict', 'The atom batch is not fully committed.',
`Some atom pages in batch ${row.request_id} for source ${row.source_id} did not commit or changed afterwards, so the batch was not marked complete. Read the batch receipt; the next atom drain extracts the source again.`,
{ fix: receiptFix(row.request_id) });
@@ -572,6 +756,7 @@ export async function prepareManagedAtomMutation(engine: BrainEngine, row: Write
config, undefined, undefined, { allowMissingFile: true });
return { ...prepared, trust: derivation.trust, additionalPageKeys, validate: async tx => { await validate(tx); await authorizeWrite(tx, row.authority, 'put_page', row.slug); await prepared.validate?.(tx); }, apply: async tx => {
const result = await prepared.apply(tx);
+ if (gated) await settleMember(tx, p.activationId!, row.slug);
if (p.links?.length) await tx.addLinksBatch(p.links, { auditSite: 'cycle.extract_atoms.provenance' });
const [atom] = await tx.executeRaw<{ id: number }>('SELECT id FROM pages WHERE source_id=$1 AND slug=$2 AND deleted_at IS NULL', [row.source_id, row.slug]);
if (atom) {
diff --git a/src/core/persistence/fault-points.ts b/src/core/persistence/fault-points.ts
index c62d7ab9f4..e1008a866c 100644
--- a/src/core/persistence/fault-points.ts
+++ b/src/core/persistence/fault-points.ts
@@ -90,7 +90,9 @@ export type FaultPoint = `publication:${PublicationBoundary}` | `effect:${Effect
| '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';
+ | 'generation:published' | 'generation:retired' | 'generation:activated'
+ // GBRA-161 PR 1b: as a managed generation member (an overwrite or retirement after its activation committed) is prepared.
+ | 'generation:member';
/**
* `signal` (#6278, `consumer:preparing` only): the preparation's abort signal, so
* a stalling hook can model both the reporter's cases: a preparer that honours
diff --git a/src/core/persistence/service.ts b/src/core/persistence/service.ts
index 63cd328226..2d2baf25b7 100644
--- a/src/core/persistence/service.ts
+++ b/src/core/persistence/service.ts
@@ -86,6 +86,7 @@ export async function preparePersistedMutation(e: BrainEngine, row: WriteRequest
throw new OperationError('unsupported_mutation_protocol', 'No compatible skill mutation preparer is registered.', `Request ${row.request_id} (${row.operation}) was accepted by a gbrain version whose preparer this one lacks, so it has not run. Run gbrain upgrade on every host that serves this brain; the request stays journaled and resumes after the upgrade.`);
}
if (row.operation === 'submit_job' && String(row.intent?.kind).startsWith('managed_atom_')) return (await import('./atom-maintenance.ts')).prepareManagedAtomMutation(e, row, cfg);
+ if (row.operation === 'submit_job' && row.intent?.kind === 'managed_generation_activate') return (await import('../generations/managed.ts')).prepareGenerationActivation(e, row);
if (row.operation === 'extract_facts' && String(row.intent?.kind).startsWith('managed_facts_')) return (await import('./facts-prepare.ts')).prepareManagedFactsMutation(e, row, cfg);
if (row.operation === 'submit_job' && String(row.intent?.kind).startsWith('connector_v2_')) return (await import('./connector-sync.ts')).prepareConnectorMutation(e, row);
if (row.operation === 'submit_job' && String(row.intent?.kind).startsWith('managed_connector_')) return (await import('./connector-sync.ts')).prepareOutdatedConnectorMutation(e, row);
diff --git a/src/core/pglite-schema.generated.ts b/src/core/pglite-schema.generated.ts
index 7cc096eb7e..3097330709 100644
--- a/src/core/pglite-schema.generated.ts
+++ b/src/core/pglite-schema.generated.ts
@@ -1240,7 +1240,9 @@ CREATE TABLE IF NOT EXISTS derived_generations (
superseded_by BIGINT,
restore_of BIGINT,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
- updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ locator TEXT,
+ activation_id TEXT
);
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';
@@ -1253,9 +1255,11 @@ CREATE TABLE IF NOT EXISTS derived_generation_items (
action TEXT NOT NULL CHECK (action IN ('published','retired','revived','kept','adopted')),
preimage JSONB,
preimage_bytes INTEGER,
+ pending BOOLEAN NOT NULL DEFAULT false,
PRIMARY KEY (generation_id, item_key)
);
CREATE INDEX IF NOT EXISTS derived_generation_items_key ON derived_generation_items (item_key);
+CREATE INDEX IF NOT EXISTS derived_generation_items_pending ON derived_generation_items (generation_id) WHERE pending;
CREATE TABLE IF NOT EXISTS derived_generation_valve (
source_id TEXT NOT NULL REFERENCES sources(id) ON DELETE CASCADE,
kind TEXT NOT NULL,
@@ -1274,6 +1278,21 @@ CREATE TABLE IF NOT EXISTS derived_generation_attempts (
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE INDEX IF NOT EXISTS derived_generation_attempts_key ON derived_generation_attempts (source_id, kind, owner_key);
+CREATE TABLE IF NOT EXISTS derived_generation_activations (
+ id TEXT PRIMARY KEY,
+ source_id TEXT NOT NULL REFERENCES sources(id) ON DELETE CASCADE,
+ kind TEXT NOT NULL,
+ owner_key TEXT NOT NULL,
+ expected_generation INTEGER NOT NULL,
+ input_pin TEXT,
+ item_set_hash TEXT NOT NULL,
+ state TEXT NOT NULL CHECK (state IN ('pending','activated')),
+ generation_id BIGINT REFERENCES derived_generations(id) ON DELETE SET NULL,
+ members JSONB NOT NULL DEFAULT '[]',
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
+);
+CREATE INDEX IF NOT EXISTS derived_generation_activations_key ON derived_generation_activations (source_id, kind, owner_key, state);
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.ts
index 98c249a9f5..5392093c71 100644
--- a/src/core/schema-embedded.generated.ts
+++ b/src/core/schema-embedded.generated.ts
@@ -1971,7 +1971,9 @@ CREATE TABLE IF NOT EXISTS derived_generations (
superseded_by BIGINT,
restore_of BIGINT,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
- updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ locator TEXT,
+ activation_id TEXT
);
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';
@@ -1984,9 +1986,11 @@ CREATE TABLE IF NOT EXISTS derived_generation_items (
action TEXT NOT NULL CHECK (action IN ('published','retired','revived','kept','adopted')),
preimage JSONB,
preimage_bytes INTEGER,
+ pending BOOLEAN NOT NULL DEFAULT false,
PRIMARY KEY (generation_id, item_key)
);
CREATE INDEX IF NOT EXISTS derived_generation_items_key ON derived_generation_items (item_key);
+CREATE INDEX IF NOT EXISTS derived_generation_items_pending ON derived_generation_items (generation_id) WHERE pending;
CREATE TABLE IF NOT EXISTS derived_generation_valve (
source_id TEXT NOT NULL REFERENCES sources(id) ON DELETE CASCADE,
kind TEXT NOT NULL,
@@ -2005,6 +2009,21 @@ CREATE TABLE IF NOT EXISTS derived_generation_attempts (
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE INDEX IF NOT EXISTS derived_generation_attempts_key ON derived_generation_attempts (source_id, kind, owner_key);
+CREATE TABLE IF NOT EXISTS derived_generation_activations (
+ id TEXT PRIMARY KEY,
+ source_id TEXT NOT NULL REFERENCES sources(id) ON DELETE CASCADE,
+ kind TEXT NOT NULL,
+ owner_key TEXT NOT NULL,
+ expected_generation INTEGER NOT NULL,
+ input_pin TEXT,
+ item_set_hash TEXT NOT NULL,
+ state TEXT NOT NULL CHECK (state IN ('pending','activated')),
+ generation_id BIGINT REFERENCES derived_generations(id) ON DELETE SET NULL,
+ members JSONB NOT NULL DEFAULT '[]',
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
+);
+CREATE INDEX IF NOT EXISTS derived_generation_activations_key ON derived_generation_activations (source_id, kind, owner_key, state);
-- (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.ts
index d776960602..713bc06f24 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 = 265;
+export const LATEST_SCHEMA_VERSION = 266;
diff --git a/src/core/schema-migrations/registry.generated.ts b/src/core/schema-migrations/registry.generated.ts
index afd04991d4..0026ae9b18 100644
--- a/src/core/schema-migrations/registry.generated.ts
+++ b/src/core/schema-migrations/registry.generated.ts
@@ -266,6 +266,7 @@ 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';
+import { v266 } from './v266-derived-generation-activations.ts';
// Array order is historical (see HISTORICAL_ARRAY_ORDER in the generator); the
// runner sorts by version before applying.
@@ -530,4 +531,5 @@ export const MIGRATIONS: Migration[] = [
v263,
v264,
v265,
+ v266,
];
diff --git a/src/core/schema-migrations/v266-derived-generation-activations.ts b/src/core/schema-migrations/v266-derived-generation-activations.ts
new file mode 100644
index 0000000000..0db86905a7
--- /dev/null
+++ b/src/core/schema-migrations/v266-derived-generation-activations.ts
@@ -0,0 +1,38 @@
+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 1b: managed generations (docs/architecture/generations.md#managed-sources). A managed activation flips the
+// ledger in one coordinated request and marks the items its member requests still have to overwrite or retire
+// `pending` (still live); each member request clears its mark, so a crash resumes the rest. The activations table
+// records every admitted activation with its members before any of them runs, so members created by an activation
+// that never happened are listed (orphan candidates) and never retired automatically. `locator` is a transcript key's
+// current file (a moved file keeps its key). New columns default to the old behaviour; no existing row changes. The
+// number is a placeholder restamped at the merge slot.
+export const v266: Migration = {
+ version: 266,
+ name: 'derived_generation_activations',
+ idempotent: true,
+ sql: `
+ ALTER TABLE derived_generations ADD COLUMN IF NOT EXISTS locator TEXT;
+ ALTER TABLE derived_generations ADD COLUMN IF NOT EXISTS activation_id TEXT;
+ ALTER TABLE derived_generation_items ADD COLUMN IF NOT EXISTS pending BOOLEAN NOT NULL DEFAULT false;
+ CREATE INDEX IF NOT EXISTS derived_generation_items_pending ON derived_generation_items (generation_id) WHERE pending;
+ CREATE TABLE IF NOT EXISTS derived_generation_activations (
+ id TEXT PRIMARY KEY,
+ source_id TEXT NOT NULL REFERENCES sources(id) ON DELETE CASCADE,
+ kind TEXT NOT NULL,
+ owner_key TEXT NOT NULL,
+ expected_generation INTEGER NOT NULL,
+ input_pin TEXT,
+ item_set_hash TEXT NOT NULL,
+ state TEXT NOT NULL CHECK (state IN ('pending','activated')),
+ generation_id BIGINT REFERENCES derived_generations(id) ON DELETE SET NULL,
+ members JSONB NOT NULL DEFAULT '[]',
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
+ );
+ CREATE INDEX IF NOT EXISTS derived_generation_activations_key ON derived_generation_activations (source_id, kind, owner_key, state);
+ `,
+};
diff --git a/src/schema.sql b/src/schema.sql
index df730a47a4..a3a4921517 100644
--- a/src/schema.sql
+++ b/src/schema.sql
@@ -1967,7 +1967,9 @@ CREATE TABLE IF NOT EXISTS derived_generations (
superseded_by BIGINT,
restore_of BIGINT,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
- updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ locator TEXT,
+ activation_id TEXT
);
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';
@@ -1980,9 +1982,11 @@ CREATE TABLE IF NOT EXISTS derived_generation_items (
action TEXT NOT NULL CHECK (action IN ('published','retired','revived','kept','adopted')),
preimage JSONB,
preimage_bytes INTEGER,
+ pending BOOLEAN NOT NULL DEFAULT false,
PRIMARY KEY (generation_id, item_key)
);
CREATE INDEX IF NOT EXISTS derived_generation_items_key ON derived_generation_items (item_key);
+CREATE INDEX IF NOT EXISTS derived_generation_items_pending ON derived_generation_items (generation_id) WHERE pending;
CREATE TABLE IF NOT EXISTS derived_generation_valve (
source_id TEXT NOT NULL REFERENCES sources(id) ON DELETE CASCADE,
kind TEXT NOT NULL,
@@ -2001,6 +2005,21 @@ CREATE TABLE IF NOT EXISTS derived_generation_attempts (
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE INDEX IF NOT EXISTS derived_generation_attempts_key ON derived_generation_attempts (source_id, kind, owner_key);
+CREATE TABLE IF NOT EXISTS derived_generation_activations (
+ id TEXT PRIMARY KEY,
+ source_id TEXT NOT NULL REFERENCES sources(id) ON DELETE CASCADE,
+ kind TEXT NOT NULL,
+ owner_key TEXT NOT NULL,
+ expected_generation INTEGER NOT NULL,
+ input_pin TEXT,
+ item_set_hash TEXT NOT NULL,
+ state TEXT NOT NULL CHECK (state IN ('pending','activated')),
+ generation_id BIGINT REFERENCES derived_generations(id) ON DELETE SET NULL,
+ members JSONB NOT NULL DEFAULT '[]',
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
+);
+CREATE INDEX IF NOT EXISTS derived_generation_activations_key ON derived_generation_activations (source_id, kind, owner_key, state);
-- (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/test/helpers/managed-atom-regressions.ts b/test/helpers/managed-atom-regressions.ts
index 21e9bbe8a4..f86213c785 100644
--- a/test/helpers/managed-atom-regressions.ts
+++ b/test/helpers/managed-atom-regressions.ts
@@ -130,12 +130,13 @@ export async function exerciseAtomRetryFence(engine: BrainEngine, state: typeof
expect(first.status).toBe('warn');
expect(failureInjected).toBe(true);
expect(calls).toBe(1);
- const accepted = await engine.executeRaw<WriteRequest>('SELECT * FROM persistence_requests WHERE source_id=$1 ORDER BY sequence', [sourceId]);
+ const accepted = await engine.executeRaw<WriteRequest>("SELECT * FROM persistence_requests WHERE source_id=$1 AND intent->>'kind' IS DISTINCT FROM 'managed_generation_activate' ORDER BY sequence", [sourceId]);
expect(accepted).toHaveLength(slugs.length + 1);
+ expect(await engine.executeRaw("SELECT state FROM persistence_requests WHERE source_id=$1 AND intent->>'kind'='managed_generation_activate'", [sourceId])).toHaveLength(1);
const completion = await waitForWrite(observedEngine, accepted.at(-1)!, { engine: engine.kind });
expect(completion.state).toBe('conflict');
await disposePersistenceConsumer(observedEngine);
- const originals = await engine.executeRaw<WriteRequest>('SELECT * FROM persistence_requests WHERE source_id=$1 ORDER BY sequence', [sourceId]);
+ const originals = await engine.executeRaw<WriteRequest>("SELECT * FROM persistence_requests WHERE source_id=$1 AND intent->>'kind' IS DISTINCT FROM 'managed_generation_activate' ORDER BY sequence", [sourceId]);
expect(originals[0].state).toBe(state);
expect(originals[0].page_id).toBe(originalTarget?.page.id ?? null);
expect(originals[0].intent?.expected_revision).toBe(originalTarget?.revision);
@@ -229,8 +230,9 @@ export async function exerciseAtomWriteThroughPolicy(engine: BrainEngine, value:
expect((await run()).status).toBe('ok');
await disposePersistenceConsumer(engine);
expect(calls).toBe(1);
- const rows = await engine.executeRaw<WriteRequest>('SELECT * FROM persistence_requests WHERE source_id=$1 ORDER BY sequence', [sourceId]);
+ const rows = await engine.executeRaw<WriteRequest>("SELECT * FROM persistence_requests WHERE source_id=$1 AND intent->>'kind' IS DISTINCT FROM 'managed_generation_activate' ORDER BY sequence", [sourceId]);
expect(rows).toHaveLength(2);
+ expect(await engine.executeRaw("SELECT state FROM persistence_requests WHERE source_id=$1 AND intent->>'kind'='managed_generation_activate'", [sourceId])).toEqual([{ state: 'committed' }]);
expect(rows.every(row => row.state === 'committed')).toBe(true);
const atom = (await engine.getPage(rows[0].slug, { sourceId }))!;
expect(atom.frontmatter.visibility).toBe('private');
diff --git a/test/helpers/managed-atoms-contract.ts b/test/helpers/managed-atoms-contract.ts
index 2033a912e8..19a8fdcc5e 100644
--- a/test/helpers/managed-atoms-contract.ts
+++ b/test/helpers/managed-atoms-contract.ts
@@ -470,7 +470,10 @@ export async function exerciseManagedAtomRetirement(engine: BrainEngine, scenari
const written = await writeSource(bodies[1]);
for (const [name, hash] of [['legacy-prefix', written.content_hash!.slice(0, 16)], ['legacy-full', written.content_hash!]] as const) {
await engine.putPage(`atoms/2026-01-01/${name}`, { type: 'atom', title: name, compiled_truth: `Legacy atom ${name}.`,
- frontmatter: { source_slug: slug, source_hash: hash } }, { sourceId });
+ frontmatter: { source_slug: slug, source_hash: hash, extracted_by: 'extract_atoms-v0.41.2.1' } }, { sourceId });
+ // GBRA-161: an atom from before the generation ledger retires only on retained extractor evidence (a page
+ // version the extractor wrote, unedited since), which a real earlier extraction of the older content leaves.
+ if (name === 'legacy-full') await engine.createVersion(`atoms/2026-01-01/${name}`, { sourceId });
}
return written;
});
@@ -623,11 +626,12 @@ export async function exerciseManagedAtomBatch(engine: BrainEngine, scenario: ty
expect(first.status).toBe('warn');
expect(first.details?.atoms_extracted).toBe(0);
expect(calls).toBe(1);
- const accepted = await engine.executeRaw<WriteRequest>('SELECT * FROM persistence_requests WHERE source_id=$1 ORDER BY sequence', [sourceId]);
+ const accepted = await engine.executeRaw<WriteRequest>("SELECT * FROM persistence_requests WHERE source_id=$1 AND intent->>'kind' IS DISTINCT FROM 'managed_generation_activate' ORDER BY sequence", [sourceId]);
expect(accepted).toHaveLength(3);
+ expect(await engine.executeRaw("SELECT state FROM persistence_requests WHERE source_id=$1 AND intent->>'kind'='managed_generation_activate'", [sourceId])).toHaveLength(1);
const completion = await waitForWrite(observedEngine, accepted[2], { engine: engine.kind });
expect(completion.state).toBe(scenario === 'completion_rollback' ? 'failed' : 'conflict');
- const originals = await engine.executeRaw('SELECT request_id,state,outcome,error_code,error_message FROM persistence_requests WHERE source_id=$1 ORDER BY sequence', [sourceId]);
+ const originals = await engine.executeRaw("SELECT request_id,state,outcome,error_code,error_message FROM persistence_requests WHERE source_id=$1 AND intent->>'kind' IS DISTINCT FROM 'managed_generation_activate' ORDER BY sequence", [sourceId]);
expect(originals[0].state).toBe('committed');
expect(originals[1].state).toBe(scenario === 'partial_publication' ? 'conflict' : 'committed');
if (scenario !== 'partial_publication') expect(injected).toBe(true);
@@ -645,7 +649,7 @@ export async function exerciseManagedAtomBatch(engine: BrainEngine, scenario: ty
const replay = await runPhaseExtractAtoms(observedEngine, { ...opts, _chat: providerFree });
expect(replay.status).toBe('warn');
expect(calls).toBe(1);
- expect(await engine.executeRaw('SELECT request_id,state,outcome,error_code,error_message FROM persistence_requests WHERE source_id=$1 ORDER BY sequence', [sourceId])).toEqual(originals);
+ expect(await engine.executeRaw("SELECT request_id,state,outcome,error_code,error_message FROM persistence_requests WHERE source_id=$1 AND intent->>'kind' IS DISTINCT FROM 'managed_generation_activate' ORDER BY sequence", [sourceId])).toEqual(originals);
if (scenario.endsWith('_after_provenance')) {
await expect(retryManagedAtomBatch(observedEngine, sourceId, completion.request_id, 'reviewed-retry')).rejects.toMatchObject({ code: 'page_identity_changed' });
expect(await countExtractAtomsBacklog(engine, sourceId)).toBe(1);
diff --git a/test/pathological/h1-zero-yield-atom-reextract.test.ts b/test/pathological/h1-zero-yield-atom-reextract.test.ts
index 21068d208e..50bbb05281 100644
--- a/test/pathological/h1-zero-yield-atom-reextract.test.ts
+++ b/test/pathological/h1-zero-yield-atom-reextract.test.ts
@@ -107,7 +107,6 @@ for (const { backend, databaseUrl } of pathologicalArms()) {
await extract(engine, ['Launch exit criteria', 'Weekly review owner']);
const first = await atoms(engine);
expect(first.map(row => row.live)).toEqual([true, true]);
- const kept = first.find(row => row.slug.includes('exit-criteria'))!.slug;
const retiring = first.find(row => row.slug.includes('review-owner'))!.slug;
await edit(ctx, 'second');
let fired = false;
@@ -115,9 +114,11 @@ for (const { backend, databaseUrl } of pathologicalArms()) {
if (fired || point !== 'consumer:preparing' || !detail.writeId) return;
const [row] = await engine.executeRaw<{ slug: string; kind: string | null }>(
"SELECT slug, intent->>'kind' AS kind FROM persistence_requests WHERE id=$1::uuid", [detail.writeId]);
- if (row?.kind !== 'managed_atom_page' || row.slug !== kept) return;
+ // GBRA-161 PR 1b: the replacement is the new identity (a create member, admitted before the activation); a
+ // same-identity sibling is rewritten only after the activation accepted the complete result.
+ if (row?.kind !== 'managed_atom_page' || !row.slug.includes('review-cadence')) return;
fired = true;
- throw new OperationError('revision_conflict', `Page ${kept} changed after the atom batch was accepted.`, 'Run the atom drain again.');
+ throw new OperationError('revision_conflict', `Page ${row.slug} changed after the atom batch was accepted.`, 'Run the atom drain again.');
});
try { await extract(engine, ['Launch exit criteria', 'Launch review cadence']).catch(() => undefined); }
finally { installFaultHook(undefined); }