Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

GBRA-161 PR 1a: publish kill-point probe, strict-order tie hold, attempts counter, generation probes

garrytand08241b9540f
diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.md
index 8630a15e48..4c71df50b6 100644
--- a/docs/guides/error-codes.md
+++ b/docs/guides/error-codes.md
@@ -1575,9 +1575,9 @@ More: [docs/architecture/generations.md#publishing](../../docs/architecture/gene
| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
|---|---|---|---|---|---|---|
-| A derived result was recorded as held instead of published, so nothing it would have retired was retired. | A model-produced result at or below the input-relative shrink floor (shrunk), one over generations.max_items (oversize), one over the run window retirement budget (valve), an empty result without a proof the input is really empty (no_proof, fence_absent), repeated failed attempts on one input (attempts_exhausted) or a segmented page the ledger cannot keep a copy of (segmented_unsupported) would retire live items on evidence the primitive does not accept (GBRA-161 D4/D5). | Preview the held set with gbrain repair generations --kind <kind> --mode release-held --held --since <restore_days>d. shrunk, valve and attempts_exhausted publish once with --apply --expect <hash> --yes after the user agrees; oversize needs gbrain config set generations.max_items first; no_proof, fence_absent and segmented_unsupported clear only when the input changes. Run: gbrain doctor --only generation_held --json | agent | `repeat the read that failed` | 1 | no |
+| A derived result was recorded as held instead of published, so nothing it would have retired was retired. | A model-produced result at or below the input-relative shrink floor (shrunk), one over generations.max_items (oversize), one over the run window retirement budget (valve), an empty result without a proof the input is really empty (no_proof, fence_absent), repeated failed attempts on one input (attempts_exhausted) a segmented page the ledger cannot keep a copy of (segmented_unsupported) or a ranked result whose cut is ambiguous (tie) would retire live items on evidence the primitive does not accept (GBRA-161 D4/D5). | Preview the held set with gbrain repair generations --kind <kind> --mode release-held --held --since <restore_days>d. shrunk, valve and attempts_exhausted publish once with --apply --expect <hash> --yes after the user agrees; oversize needs gbrain config set generations.max_items first; no_proof, fence_absent, segmented_unsupported and tie clear only when the input or the producer result changes. Run: gbrain doctor --only generation_held --json | agent | `repeat the read that failed` | 1 | no |
-Reasons: `shrunk`, `oversize`, `valve`, `no_proof`, `fence_absent`, `attempts_exhausted`, `segmented_unsupported`.
+Reasons: `shrunk`, `oversize`, `valve`, `no_proof`, `fence_absent`, `attempts_exhausted`, `segmented_unsupported`, `tie`.
More: [docs/guides/repair.md#generations](../../docs/guides/repair.md#generations)
diff --git a/src/core/deletion-inventory.ts b/src/core/deletion-inventory.ts
index 1d362965c2..a12d82e442 100644
--- a/src/core/deletion-inventory.ts
+++ b/src/core/deletion-inventory.ts
@@ -63,6 +63,7 @@ const ROWS: readonly Row[] = [
['decide_sweep_deferred', 'out_of_scope', 'no_memory_text', 'source_id slot reason'],
['decision_receipts', 'out_of_scope', 'probed_reported', 'decision_id source_id slot mode provider model_alias model_resolved question_kind state_hash question_hash answer_choice outcome subject_ref call_site lane policy_fingerprint calibration_ref error_reason run_meta', 'run_meta'],
['derivation_inputs', 'out_of_scope', 'text_free_ledger', 'derived_table derived_id input_table input_id source_id'],
+ ['derived_generation_attempts', 'out_of_scope', 'no_memory_text', 'hold_id source_id kind owner_key codes'],
['derived_generation_items', 'swept', 'generation_ledger', 'item_key identity_hash action preimage', 'preimage'],
['derived_generation_valve', 'out_of_scope', 'no_memory_text', 'source_id kind window_key'],
['derived_generations', 'swept', 'generation_ledger', 'source_id kind owner_key state run_id operation_id hold_id input_pin completeness item_set_hash held_reason held_context proposal', 'held_context proposal'],
diff --git a/src/core/error-registry.ts b/src/core/error-registry.ts
index f4db43354e..c2940e5ff0 100644
--- a/src/core/error-registry.ts
+++ b/src/core/error-registry.ts
@@ -290,7 +290,7 @@ export const CODES = {
forget_requires_owner: { class: 'consent', exit: 3, actor: 'user', summary: "A caller asked to forget a fact (remote forget) or remove a take (takes_remove) more trusted than its own writes, so nothing was removed and the owner was asked instead.", why: "Lower-trust writers cannot overwrite, supersede or forget what the owner confirmed or curated (#5575 guarded supersession). The request became a trust proposal the owner can accept on the brain host; forget's frozen expired meaning is unchanged because nothing expired.", docs: 'docs/guides/error-codes.md#forget_requires_owner', suggestion: 'Do not retry. Tell the user the fact or take needs their decision and give them the command in fix (gbrain trust confirm <proposal_ref> on the brain host).' },
reserved_frontmatter_key: { class: 'caller', summary: 'A remote page write tried to add or change a frontmatter key only a trusted derived writer sets (`retired_by`, `retired_at`, `retired_generation`); nothing was written.', why: 'Those keys mark a page a derived writer retired, which the purge holds for 30 days and the repairs treat as machine-owned. A remote caller that could set them could make a page look machine-retired. Carrying the stored value unchanged, or dropping the key, is allowed.', suggestion: 'Remove the key from the frontmatter (or keep the stored value) and write the page again.' },
generation_fenced: { class: 'retryable', exit: 11, reasons: ['stale_generation', 'pin_moved'], summary: 'A derived result was not published because the live generation or its input changed after the producer read them; nothing was written.', why: 'The generation primitive (GBRA-161) publishes a result only against the generation and input pin it was computed from. A concurrent run that published first (stale_generation), or an input edited since the read (pin_moved), would otherwise let an older result replace a newer one.', docs: 'docs/architecture/generations.md#publishing', suggestion: 'Run the producer again; it reads the current generation and input and recomputes.' },
- generation_held: { class: 'caller', reasons: ['shrunk', 'oversize', 'valve', 'no_proof', 'fence_absent', 'attempts_exhausted', 'segmented_unsupported'], summary: 'A derived result was recorded as held instead of published, so nothing it would have retired was retired.', why: 'A model-produced result at or below the input-relative shrink floor (shrunk), one over generations.max_items (oversize), one over the run window retirement budget (valve), an empty result without a proof the input is really empty (no_proof, fence_absent), repeated failed attempts on one input (attempts_exhausted) or a segmented page the ledger cannot keep a copy of (segmented_unsupported) would retire live items on evidence the primitive does not accept (GBRA-161 D4/D5).', docs: 'docs/guides/repair.md#generations', suggestion: 'Preview the held set with gbrain repair generations --kind <kind> --mode release-held --held --since <restore_days>d. shrunk, valve and attempts_exhausted publish once with --apply --expect <hash> --yes after the user agrees; oversize needs gbrain config set generations.max_items first; no_proof, fence_absent and segmented_unsupported clear only when the input changes.', fix: { argv: ['gbrain', 'doctor', '--only', 'generation_held', '--json'], consent: [], actor: 'agent', why: 'Lists the held generations by kind and reason with their preview commands, read-only.', requires_exclusive: false } },
+ generation_held: { class: 'caller', reasons: ['shrunk', 'oversize', 'valve', 'no_proof', 'fence_absent', 'attempts_exhausted', 'segmented_unsupported', 'tie'], summary: 'A derived result was recorded as held instead of published, so nothing it would have retired was retired.', why: 'A model-produced result at or below the input-relative shrink floor (shrunk), one over generations.max_items (oversize), one over the run window retirement budget (valve), an empty result without a proof the input is really empty (no_proof, fence_absent), repeated failed attempts on one input (attempts_exhausted) a segmented page the ledger cannot keep a copy of (segmented_unsupported) or a ranked result whose cut is ambiguous (tie) would retire live items on evidence the primitive does not accept (GBRA-161 D4/D5).', docs: 'docs/guides/repair.md#generations', suggestion: 'Preview the held set with gbrain repair generations --kind <kind> --mode release-held --held --since <restore_days>d. shrunk, valve and attempts_exhausted publish once with --apply --expect <hash> --yes after the user agrees; oversize needs gbrain config set generations.max_items first; no_proof, fence_absent, segmented_unsupported and tie clear only when the input or the producer result changes.', fix: { argv: ['gbrain', 'doctor', '--only', 'generation_held', '--json'], consent: [], actor: 'agent', why: 'Lists the held generations by kind and reason with their preview commands, read-only.', requires_exclusive: false } },
generation_live_conflict: { class: 'retryable', exit: 11, summary: 'A derived generation was not activated because one of its items was not live at the content the publication wrote; nothing was committed.', why: 'Activation rechecks every item of the new generation under the key lock; an item another writer changed or deleted in between would make the ledger record a set that is not what the pages say.', docs: 'docs/architecture/generations.md#publishing', suggestion: 'Run the producer again; it reads the items as they are now.' },
frontmatter_slug_conflict: { class: 'caller', summary: "The file's frontmatter `slug:` names a different page than its path does.", why: "The path decides a file's page; a conflicting declared slug would overwrite or fork another page, so the file is refused until one of them changes.", suggestion: 'Remove the `slug:` line or make it match the path, then commit and sync again.' },
full_resync_required: { class: 'retryable', summary: "The catalog cursor is invalid or expired." },
diff --git a/src/core/generations/contract.ts b/src/core/generations/contract.ts
index 6ae9b3abb3..6174952dd8 100644
--- a/src/core/generations/contract.ts
+++ b/src/core/generations/contract.ts
@@ -10,14 +10,15 @@ import type { DerivedRetiredBy } from '../persistence/derived-retirement-hold.ts
/** One derived set: the items of one kind a single input owns in one source. */
export interface GenerationKey { kind: string; sourceId: string; ownerKey: string }
-export const HELD_REASONS = ['shrunk', 'oversize', 'valve', 'no_proof', 'fence_absent', 'attempts_exhausted', 'segmented_unsupported'] as const;
+export const HELD_REASONS = ['shrunk', 'oversize', 'valve', 'no_proof', 'fence_absent', 'attempts_exhausted', 'segmented_unsupported', 'tie'] as const;
export type HeldReason = typeof HELD_REASONS[number];
/** A held result the operator may publish once with `gbrain repair generations --mode release-held`. */
export const RELEASABLE_HELD_REASONS: ReadonlySet<HeldReason> = new Set(['shrunk', 'valve', 'attempts_exhausted', 'oversize']);
/** One item of a proposed generation: its key, the content the adapter writes, and its identity hash. */
-export interface ProposedItem { key: string; content: string; identityHash: string }
+/** `order`: the item's rank in a strict-order result (adapters with `strictOrder`); two items sharing one is a tie. */
+export interface ProposedItem { key: string; content: string; identityHash: string; order?: number }
/** A bounded copy of an item's stored state, kept on the ledger so a restore can bring it back (null: too large or segmented). */
export interface Preimage { json: Record<string, unknown> | null; bytes: number }
@@ -34,6 +35,8 @@ export interface GenerationAdapter<C = unknown> {
retiredBy: DerivedRetiredBy;
/** Model-produced kinds take the input-relative shrink floor; canonical projections do not. */
modelProduced: boolean;
+ /** The result is a ranked cut: every item carries a distinct `order`, and a tie (or a missing rank) holds the result (`tie`). */
+ strictOrder?: boolean;
/** Page keys locked before the ledger row, in slug order with the input guard (D7). */
lockKeys(key: GenerationKey, itemKeys: readonly string[]): Array<{ sourceId: string; slug: string }>;
/** The input as stored now, or null when it is gone. `context` carries an input the database does not hold (a transcript). */
diff --git a/src/core/generations/plan.ts b/src/core/generations/plan.ts
index ff9a208ee1..6dac3c213f 100644
--- a/src/core/generations/plan.ts
+++ b/src/core/generations/plan.ts
@@ -25,6 +25,7 @@ export interface PlanInput {
input: InputState | null;
config: GenerationsConfig;
modelProduced: boolean;
+ strictOrder?: boolean;
/** A partial result (input cut short): writes its items, retires nothing. */
additive: boolean;
evidence: ReadonlySet<string>;
@@ -59,6 +60,11 @@ export function planGeneration(input: PlanInput): Plan {
const touched = [...puts.map(item => item.key), ...retires];
if (touched.some(key => rows.get(key)?.segmented)) return held('segmented_unsupported');
+ if (input.strictOrder) {
+ const orders = proposal.map(item => item.order);
+ const tied = orders.filter((order, index) => order === undefined || orders.indexOf(order) !== index);
+ if (tied.length) return held('tie', { tied: tied.length });
+ }
if (!proposal.length && retires.length && !input.proofHolds) return held('no_proof');
if (Math.max(puts.length, retires.length) > config.maxItems) return held('oversize', { max_items: config.maxItems });
const shrinkReleased = input.release === 'shrunk' || input.release === 'attempts_exhausted';
diff --git a/src/core/generations/publish.ts b/src/core/generations/publish.ts
index 20981e9ad2..c959b4c315 100644
--- a/src/core/generations/publish.ts
+++ b/src/core/generations/publish.ts
@@ -9,7 +9,7 @@
* their coordinator path until PR 1b.
*/
import type { BrainEngine } from '../engine.ts';
-import { opError } from '../ops/contract.ts';
+import { opError, OperationError } from '../ops/contract.ts';
import { maintenanceTransaction } from '../persistence/attribution.ts';
import { digest, jsonBytes } from '../persistence/digest.ts';
import { faultPoint } from '../persistence/fault-points.ts';
@@ -95,6 +95,7 @@ export async function activateGeneration(tx: BrainEngine, key: GenerationKey, li
[id, item.key, item.identityHash, item.action, item.preimage?.json ? JSON.stringify(item.preimage.json) : null, item.preimage?.bytes ?? null]);
}
await tx.executeRaw(`DELETE FROM derived_generations WHERE source_id=$1 AND kind=$2 AND owner_key=$3 AND state='held'`, [key.sourceId, key.kind, key.ownerKey]);
+ 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]);
return { id, generation };
}
@@ -109,9 +110,17 @@ export async function assertItemsLive(tx: BrainEngine, adapter: GenerationAdapte
}
}
+/** A held result's identity: key, input pin, policy, item set and reason. The attempts counter and `heldForInput` share it. */
+function holdIdFor(key: GenerationKey, pin: string | null, config: GenerationsConfig, setHash: string, reason: HeldReason): string {
+ return digest(['generation-hold-v1', key, pin, policyHash(config), setHash, reason]).slice(0, 32);
+}
+
+/** 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,
reason: HeldReason, context: Record<string, unknown>): Promise<PublishOutcome> {
- const holdId = digest(['generation-hold-v1', key, request.input?.pin ?? null, policyHash(config), setHash, reason]).slice(0, 32);
+ const holdId = holdIdFor(key, request.input?.pin ?? null, config, setHash, reason);
const [existing] = await tx.executeRaw<{ id: number; hold_id: string }>(
`SELECT id, hold_id FROM derived_generations WHERE source_id=$1 AND kind=$2 AND owner_key=$3 AND state='held'`, [key.sourceId, key.kind, key.ownerKey]);
if (existing?.hold_id === holdId) {
@@ -136,9 +145,29 @@ export async function heldForInput(engine: BrainEngine, key: GenerationKey, pin:
const rows = await engine.executeRaw<{ hold_id: string; item_set_hash: string; held_reason: string }>(
`SELECT hold_id, item_set_hash, held_reason FROM derived_generations WHERE source_id=$1 AND kind=$2 AND owner_key=$3 AND state='held' AND input_pin=$4`,
[key.sourceId, key.kind, key.ownerKey, pin]);
- return rows.some(row => row.hold_id === digest(['generation-hold-v1', key, pin, policyHash(config), row.item_set_hash, row.held_reason]).slice(0, 32));
+ return rows.some(row => row.hold_id === holdIdFor(key, pin, config, row.item_set_hash, row.held_reason as HeldReason));
}
+/**
+ * Counts one terminal failure of this hold identity (a fenced producer is not a failure of the result, so it is not
+ * counted); the third holds the result `attempts_exhausted` with the last three error codes. Only codes are stored.
+ */
+async function recordAttempt(engine: BrainEngine, key: GenerationKey, config: GenerationsConfig, request: PublishRequest<unknown>, setHash: string, code: string): Promise<void> {
+ const holdId = holdIdFor(key, request.input?.pin ?? null, config, setHash, 'attempts_exhausted');
+ await maintenanceTransaction(engine, async tx => {
+ const [row] = await tx.executeRaw<{ attempts: number; codes: string[] }>(
+ `INSERT INTO derived_generation_attempts (hold_id, source_id, kind, owner_key, attempts, codes) VALUES ($1,$2,$3,$4,1,jsonb_build_array($5::text))
+ ON CONFLICT (hold_id) DO UPDATE SET attempts=derived_generation_attempts.attempts+1, codes=derived_generation_attempts.codes || jsonb_build_array($5::text), updated_at=now()
+ RETURNING attempts, codes`, [holdId, key.sourceId, key.kind, key.ownerKey, code]);
+ if (Number(row!.attempts) < MAX_GENERATION_ATTEMPTS) return;
+ await tx.executeRaw('DELETE FROM derived_generation_attempts WHERE hold_id=$1', [holdId]);
+ await recordHeld(tx, key, config, request, setHash, 'attempts_exhausted', { attempts: Number(row!.attempts), codes: row!.codes.slice(-MAX_GENERATION_ATTEMPTS) });
+ });
+}
+
+const failureCode = (error: unknown): string => error instanceof OperationError ? error.code
+ : typeof (error as { code?: unknown })?.code === 'string' ? String((error as { code: string }).code) : 'error';
+
function logFailure(key: GenerationKey, operationId: string, mode: string, error: unknown): void {
const message = error instanceof Error ? error.message : String(error);
console.error(`[generations] ${mode} failed: kind=${key.kind} source=${key.sourceId} schema=v${LATEST_VERSION} mode=unmanaged operation=${operationId}: ${message.slice(0, 300)}`);
@@ -151,6 +180,12 @@ export async function publishGeneration<C>(engine: BrainEngine, adapter: Generat
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 ?? {} };
+ }
try {
const outcome = await maintenanceTransaction(engine, async tx => {
await lockGeneration(tx, adapter as GenerationAdapter<unknown>, key, itemKeys);
@@ -166,7 +201,7 @@ export async function publishGeneration<C>(engine: BrainEngine, adapter: Generat
const unrecorded = [...rows.values()].filter(row => row.owned && row.live && !live?.items.has(row.key) && !itemKeys.includes(row.key));
const evidence = unrecorded.length ? await adapter.legacyEvidence(tx, key, unrecorded) : new Set<string>();
const valve = await readValve(tx, key, request.runId);
- const plan = planGeneration({ live, rows, proposal: request.items, input, config, modelProduced: adapter.modelProduced, additive: request.partial === true,
+ 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 });
if (plan.kind === 'held') return recordHeld(tx, key, config, request, setHash, plan.reason, plan.context);
if (plan.kind === 'unchanged') {
@@ -198,6 +233,11 @@ export async function publishGeneration<C>(engine: BrainEngine, adapter: Generat
return outcome;
} catch (error) {
logFailure(key, operationId, 'publish', error);
+ const code = failureCode(error);
+ if (code !== 'generation_fenced') {
+ await recordAttempt(engine, key, config, request as PublishRequest<unknown>, setHash, code)
+ .catch(counted => logFailure(key, operationId, 'attempt count', counted));
+ }
throw error;
}
}
diff --git a/src/core/generations/repair.ts b/src/core/generations/repair.ts
index c554f62ee0..8991a5ae93 100644
--- a/src/core/generations/repair.ts
+++ b/src/core/generations/repair.ts
@@ -8,7 +8,7 @@
* are versioned and retired (`retired_by: generation-restore`). A key with an item edited since the generation, or one
* with no stored preimage, is refused whole and the apply exits incomplete; nothing of that key changes.
* - release-held: publishes a held result once (shrunk, valve, attempts_exhausted; oversize after the operator raised
- * `generations.max_items`). no_proof, fence_absent and segmented_unsupported are refused: releasing them would
+ * `generations.max_items`). no_proof, fence_absent, tie and segmented_unsupported are refused: releasing them would
* manufacture the proof they lack.
* - cleanup: the synthesis unmatched-predecessor retire (PR 4); no kind in this release has it.
*
diff --git a/src/core/persistence/graduation-inventory.ts b/src/core/persistence/graduation-inventory.ts
index 478af4f449..98229c2d05 100644
--- a/src/core/persistence/graduation-inventory.ts
+++ b/src/core/persistence/graduation-inventory.ts
@@ -57,6 +57,7 @@ export const GRADUATION_INVENTORY: Inventory = {
carry('decide_sweep_deferred', 'operational', 'Deferred System One sweep work with its schedule.'),
carry('decision_receipts', 'user_data', 'Durable System One decision receipts.'),
carry('derivation_inputs', 'user_data', 'Derivation dependency edges (#5575); purge needs them to find artifacts derived from purged content.'),
+ carry('derived_generation_attempts', 'operational', 'Generation attempt counters per hold identity (GBRA-161): three terminal failures hold the result attempts_exhausted.'),
carry('derived_generation_items', 'user_data', 'Generation ledger items (GBRA-161): which derived items each generation owns, with the bounded preimages a restore republishes.'),
carry('derived_generation_valve', 'operational', 'Generation retirement valve counters per run window (GBRA-161).'),
carry('derived_generations', 'user_data', 'Generation ledger (GBRA-161): the live, superseded and held generations of each derived key; restore and release-held read it.'),
diff --git a/src/core/pglite-schema.generated.ts b/src/core/pglite-schema.generated.ts
index aafa21bb83..7cc096eb7e 100644
--- a/src/core/pglite-schema.generated.ts
+++ b/src/core/pglite-schema.generated.ts
@@ -1232,7 +1232,7 @@ CREATE TABLE IF NOT EXISTS derived_generations (
input_size BIGINT,
completeness JSONB NOT NULL DEFAULT '{}',
item_set_hash TEXT NOT NULL,
- held_reason TEXT CHECK (held_reason IS NULL OR held_reason IN ('shrunk','oversize','valve','no_proof','fence_absent','attempts_exhausted','segmented_unsupported')),
+ held_reason TEXT CHECK (held_reason IS NULL OR held_reason IN ('shrunk','oversize','valve','no_proof','fence_absent','attempts_exhausted','segmented_unsupported','tie')),
held_context JSONB,
proposal JSONB,
proposal_bytes INTEGER,
@@ -1264,6 +1264,16 @@ CREATE TABLE IF NOT EXISTS derived_generation_valve (
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
PRIMARY KEY (source_id, kind, window_key)
);
+CREATE TABLE IF NOT EXISTS derived_generation_attempts (
+ hold_id TEXT PRIMARY KEY,
+ source_id TEXT NOT NULL REFERENCES sources(id) ON DELETE CASCADE,
+ kind TEXT NOT NULL,
+ owner_key TEXT NOT NULL,
+ attempts INTEGER NOT NULL DEFAULT 0,
+ codes JSONB NOT NULL DEFAULT '[]',
+ 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 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/repair/registry.ts b/src/core/repair/registry.ts
index 19d97a304c..3f9aa10594 100644
--- a/src/core/repair/registry.ts
+++ b/src/core/repair/registry.ts
@@ -513,7 +513,7 @@ const SPECS: Record<RepairKind, Omit<RepairKindSpec, 'kind'>> = {
},
summary: 'Undo or release a derived generation (GBRA-161): --kind <kind> names the ledger kind, --mode restore (default) republishes the item set the '
+ 'selected live generation replaced from its ledger preimages and retires what it added, --mode release-held publishes a held result once '
- + '(shrunk, valve, attempts_exhausted; oversize after raising generations.max_items; no_proof, fence_absent and segmented_unsupported are refused). '
+ + '(shrunk, valve, attempts_exhausted; oversize after raising generations.max_items; no_proof, fence_absent, tie and segmented_unsupported are refused). '
+ 'One selector bounds the set: --run <id>, --since <ISO-8601|7d>, --key <owner>, --generation <id>, or --held (release-held). The preview lists each key '
+ 'and saves the set under its hash; --apply --expect <hash> --yes applies exactly that set, refusing a key edited since or with no stored preimage. '
+ 'Runs only when named; never on upgrade.',
diff --git a/src/core/schema-embedded.generated.ts b/src/core/schema-embedded.generated.ts
index c59a36eaa5..98c249a9f5 100644
--- a/src/core/schema-embedded.generated.ts
+++ b/src/core/schema-embedded.generated.ts
@@ -1963,7 +1963,7 @@ CREATE TABLE IF NOT EXISTS derived_generations (
input_size BIGINT,
completeness JSONB NOT NULL DEFAULT '{}',
item_set_hash TEXT NOT NULL,
- held_reason TEXT CHECK (held_reason IS NULL OR held_reason IN ('shrunk','oversize','valve','no_proof','fence_absent','attempts_exhausted','segmented_unsupported')),
+ held_reason TEXT CHECK (held_reason IS NULL OR held_reason IN ('shrunk','oversize','valve','no_proof','fence_absent','attempts_exhausted','segmented_unsupported','tie')),
held_context JSONB,
proposal JSONB,
proposal_bytes INTEGER,
@@ -1995,6 +1995,16 @@ CREATE TABLE IF NOT EXISTS derived_generation_valve (
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
PRIMARY KEY (source_id, kind, window_key)
);
+CREATE TABLE IF NOT EXISTS derived_generation_attempts (
+ hold_id TEXT PRIMARY KEY,
+ source_id TEXT NOT NULL REFERENCES sources(id) ON DELETE CASCADE,
+ kind TEXT NOT NULL,
+ owner_key TEXT NOT NULL,
+ attempts INTEGER NOT NULL DEFAULT 0,
+ codes JSONB NOT NULL DEFAULT '[]',
+ 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);
-- (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/v265-derived-generations.ts b/src/core/schema-migrations/v265-derived-generations.ts
index d7e0a80098..410d73e217 100644
--- a/src/core/schema-migrations/v265-derived-generations.ts
+++ b/src/core/schema-migrations/v265-derived-generations.ts
@@ -6,7 +6,8 @@ import type { Migration } from './types.ts';
// GBRA-161 PR 1a: the generation ledger (docs/architecture/generations.md). One live row per
// (source, kind, owner key) records which derived items the current generation owns; superseded
// rows keep the item sets and bounded preimages a restore republishes; a held row records a result
-// the primitive would not publish and why. The valve table counts retirements per run window.
+// the primitive would not publish and why. The valve table counts retirements per run window, and the attempts
+// table counts terminal failures of one hold identity (three land a held attempts_exhausted row).
// New tables only: no existing row changes. The number is a placeholder restamped at the merge slot.
export const v265: Migration = {
version: 265,
@@ -27,7 +28,7 @@ export const v265: Migration = {
input_size BIGINT,
completeness JSONB NOT NULL DEFAULT '{}',
item_set_hash TEXT NOT NULL,
- held_reason TEXT CHECK (held_reason IS NULL OR held_reason IN ('shrunk','oversize','valve','no_proof','fence_absent','attempts_exhausted','segmented_unsupported')),
+ held_reason TEXT CHECK (held_reason IS NULL OR held_reason IN ('shrunk','oversize','valve','no_proof','fence_absent','attempts_exhausted','segmented_unsupported','tie')),
held_context JSONB,
proposal JSONB,
proposal_bytes INTEGER,
@@ -59,5 +60,15 @@ export const v265: Migration = {
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
PRIMARY KEY (source_id, kind, window_key)
);
+ CREATE TABLE IF NOT EXISTS derived_generation_attempts (
+ hold_id TEXT PRIMARY KEY,
+ source_id TEXT NOT NULL REFERENCES sources(id) ON DELETE CASCADE,
+ kind TEXT NOT NULL,
+ owner_key TEXT NOT NULL,
+ attempts INTEGER NOT NULL DEFAULT 0,
+ codes JSONB NOT NULL DEFAULT '[]',
+ 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);
`,
};
diff --git a/src/schema.sql b/src/schema.sql
index a900c6e424..df730a47a4 100644
--- a/src/schema.sql
+++ b/src/schema.sql
@@ -1959,7 +1959,7 @@ CREATE TABLE IF NOT EXISTS derived_generations (
input_size BIGINT,
completeness JSONB NOT NULL DEFAULT '{}',
item_set_hash TEXT NOT NULL,
- held_reason TEXT CHECK (held_reason IS NULL OR held_reason IN ('shrunk','oversize','valve','no_proof','fence_absent','attempts_exhausted','segmented_unsupported')),
+ held_reason TEXT CHECK (held_reason IS NULL OR held_reason IN ('shrunk','oversize','valve','no_proof','fence_absent','attempts_exhausted','segmented_unsupported','tie')),
held_context JSONB,
proposal JSONB,
proposal_bytes INTEGER,
@@ -1991,6 +1991,16 @@ CREATE TABLE IF NOT EXISTS derived_generation_valve (
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
PRIMARY KEY (source_id, kind, window_key)
);
+CREATE TABLE IF NOT EXISTS derived_generation_attempts (
+ hold_id TEXT PRIMARY KEY,
+ source_id TEXT NOT NULL REFERENCES sources(id) ON DELETE CASCADE,
+ kind TEXT NOT NULL,
+ owner_key TEXT NOT NULL,
+ attempts INTEGER NOT NULL DEFAULT 0,
+ codes JSONB NOT NULL DEFAULT '[]',
+ 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);
-- (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/fixtures/generation-crash-worker.ts b/test/fixtures/generation-crash-worker.ts
new file mode 100644
index 0000000000..2955710d57
--- /dev/null
+++ b/test/fixtures/generation-crash-worker.ts
@@ -0,0 +1,162 @@
+/**
+ * GBRA-161: SIGKILL a real child process at each generation publish fault point and check what a reopened brain holds.
+ * The child publishes generation 1 of a synthetic key, installs a fault hook that blocks at the chosen point, and starts
+ * publishing generation 2 (which retires one item); the parent kills it there. A recovery child then reads the ledger
+ * and pages, reruns the identical publication twice and reports. Disk PGLite, or a fresh Postgres database per case.
+ */
+import assert from 'node:assert/strict';
+import { randomUUID } from 'node:crypto';
+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync, writeSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join, resolve } from 'node:path';
+import postgres from '#postgres'
+import { childEnvironment } from '../../scripts/persistence/validate.ts';
+import type { BrainEngine } from '../../src/core/engine.ts';
+import { publishGeneration } from '../../src/core/generations/publish.ts';
+import { installFaultHook, type FaultPoint } from '../../src/core/persistence/fault-points.ts';
+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';
+import { PostgresEngine } from '../../src/core/postgres-engine.ts';
+import { assertSafeE2eDatabaseUrl } from '../helpers/db-guard.ts';
+import { liveSlugs, setSyntheticInput, syntheticAdapter, syntheticItem, syntheticKey } from '../helpers/synthetic-generation.ts';
+
+export const GENERATION_CRASH_POINTS = ['generation:published', 'generation:retired', 'generation:activated'] as const satisfies readonly FaultPoint[];
+type Point = typeof GENERATION_CRASH_POINTS[number];
+interface WorkerConfig { kind: 'pglite' | 'postgres'; point: Point; root: string; dataDir: string; databaseUrl?: string }
+interface WorkerEvent { event: string; point?: string; result?: Record<string, unknown>; message?: string }
+
+const OWNER = 'owner:notes/crash-source';
+const key = syntheticKey('default', OWNER);
+const items = (names: string[]) => names.map(name => syntheticItem(OWNER, `derived/${name}`, `${name} claim.`));
+const emit = (event: WorkerEvent) => process.stdout.write(`${JSON.stringify(event)}\n`);
+
+function stopSynchronously(event: WorkerEvent): never {
+ const bytes = Buffer.from(`${JSON.stringify(event)}\n`);
+ for (let offset = 0; offset < bytes.length;) offset += writeSync(1, bytes, offset, bytes.length - offset);
+ const blocked = new Int32Array(new SharedArrayBuffer(4));
+ for (;;) Atomics.wait(blocked, 0, 0);
+}
+
+async function openEngine(config: WorkerConfig): Promise<BrainEngine> {
+ const engine = config.kind === 'pglite' ? new PGLiteEngine() : new PostgresEngine();
+ if (config.kind === 'postgres') assertSafeE2eDatabaseUrl(config.databaseUrl!);
+ await engine.connect(config.kind === 'pglite' ? { database_path: config.dataDir } : { database_url: config.databaseUrl!, poolSize: 4 });
+ await engine.initSchema();
+ return engine;
+}
+
+const second = (engine: BrainEngine) => { setSyntheticInput(key, { pin: 'pin-2', size: 100 });
+ return publishGeneration(engine, syntheticAdapter, { key, items: items(['a', 'b', 'c']), input: { pin: 'pin-2', size: 100 } }); };
+
+async function crash(config: WorkerConfig): Promise<void> {
+ const engine = await openEngine(config);
+ setSyntheticInput(key, { pin: 'pin-1', size: 100 });
+ const first = await publishGeneration(engine, syntheticAdapter, { key, items: items(['a', 'b', 'c', 'd']), input: { pin: 'pin-1', size: 100 } });
+ assert.equal(first.state, 'published');
+ installFaultHook(point => { if (point === config.point) stopSynchronously({ event: 'boundary', point }); });
+ await second(engine);
+ emit({ event: 'failure', message: `publication finished without reaching ${config.point}` });
+ process.exit(1);
+}
+
+async function recover(config: WorkerConfig): Promise<Record<string, unknown>> {
+ const engine = await openEngine(config);
+ try {
+ const ledger = async () => (await engine.executeRaw<{ generation: number; state: string }>(
+ 'SELECT generation, state FROM derived_generations ORDER BY id')).map(row => `${row.state}:${Number(row.generation)}`);
+ const before = { ledger: await ledger(), live: await liveSlugs(engine, OWNER) };
+ const rerun = await second(engine);
+ const again = await second(engine);
+ const [items] = await engine.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM derived_generation_items i JOIN derived_generations g ON g.id=i.generation_id WHERE g.state='live'`);
+ return { before, rerun: rerun.state, rerun_generation: 'generation' in rerun ? rerun.generation : null, again: again.state,
+ after: { ledger: await ledger(), live: await liveSlugs(engine, OWNER), live_items: Number(items!.n) } };
+ } finally { await engine.disconnect(); }
+}
+
+function spawnWorker(configPath: string, home: string, mode: 'crash' | 'recover') {
+ const child = Bun.spawn([process.execPath, '--no-env-file', resolve(import.meta.path), mode, configPath],
+ { cwd: home, env: childEnvironment(home), stdin: 'ignore', stdout: 'pipe', stderr: 'inherit' });
+ const events: WorkerEvent[] = [];
+ const reading = (async () => {
+ const decoder = new TextDecoder();
+ let pending = '';
+ for await (const chunk of child.stdout) {
+ pending += decoder.decode(chunk, { stream: true });
+ for (let newline = pending.indexOf('\n'); newline >= 0; newline = pending.indexOf('\n')) {
+ const line = pending.slice(0, newline);
+ pending = pending.slice(newline + 1);
+ try { const event = JSON.parse(line); if (typeof event.event === 'string') events.push(event); } catch {}
+ }
+ }
+ })();
+ return {
+ child,
+ async event(name: string): Promise<WorkerEvent> {
+ const deadline = Date.now() + 120_000;
+ for (;;) {
+ const found = events.find(event => event.event === name);
+ if (found) return found;
+ const failure = events.find(event => event.event === 'failure');
+ assert(!failure, `${mode}: ${failure?.message}`);
+ assert(child.exitCode === null || events.length, `${mode} exited before ${name}`);
+ assert(Date.now() < deadline, `${mode} timed out before ${name}`);
+ await Bun.sleep(100);
+ }
+ },
+ async kill() { if (child.exitCode === null) child.kill('SIGKILL'); await child.exited; await reading; },
+ };
+}
+
+export async function runGenerationCrashCase(options: { kind: 'pglite' | 'postgres'; point: Point; databaseUrl?: string }): Promise<Record<string, unknown>> {
+ const root = mkdtempSync(join(tmpdir(), 'gbrain-generation-crash-'));
+ const home = join(root, 'home');
+ mkdirSync(home, { mode: 0o700 });
+ const children: ReturnType<typeof spawnWorker>[] = [];
+ let admin: ReturnType<typeof postgres> | undefined;
+ let database: string | undefined;
+ try {
+ let databaseUrl: string | undefined;
+ if (options.kind === 'postgres') {
+ assert(options.databaseUrl, 'Postgres crash coverage requires an explicit test DATABASE_URL');
+ assertSafeE2eDatabaseUrl(options.databaseUrl);
+ admin = postgres(options.databaseUrl, { max: 1, prepare: false, onnotice() {} });
+ database = `gbrain_test_generation_crash_${randomUUID().replaceAll('-', '')}`;
+ await admin.unsafe(`CREATE DATABASE ${database}`);
+ const url = new URL(options.databaseUrl);
+ url.pathname = `/${database}`;
+ databaseUrl = url.toString();
+ }
+ const config: WorkerConfig = { ...options, databaseUrl, root, dataDir: join(root, 'data') };
+ const configPath = join(root, 'config.json');
+ writeFileSync(configPath, JSON.stringify(config), { mode: 0o600 });
+ const killed = spawnWorker(configPath, home, 'crash');
+ children.push(killed);
+ const reached = await killed.event('boundary');
+ assert.equal(reached.point, options.point);
+ assert.equal(killed.child.exitCode, null, 'the fault point must be a live blocked process');
+ await killed.kill();
+ const restarted = spawnWorker(configPath, home, 'recover');
+ children.push(restarted);
+ const done = await restarted.event('done');
+ assert.equal(await restarted.child.exited, 0);
+ return { killed_signal: killed.child.signalCode, ...done.result };
+ } finally {
+ try { await Promise.all(children.map(child => child.kill())); }
+ finally {
+ try { if (database && admin) await admin.unsafe(`DROP DATABASE ${database} WITH (FORCE)`); }
+ finally { await admin?.end({ timeout: 1 }); rmSync(root, { recursive: true, force: true }); }
+ }
+ }
+}
+
+if (import.meta.main) {
+ const [mode, configPath] = process.argv.slice(2);
+ const config: WorkerConfig = JSON.parse(readFileSync(configPath!, 'utf8'));
+ try {
+ if (mode === 'crash') await crash(config);
+ else { emit({ event: 'done', result: await recover(config) }); process.exit(0); }
+ } catch (error) {
+ const message = error instanceof Error ? error.message : 'Unknown worker failure';
+ emit({ event: 'failure', message: config.databaseUrl ? message.replaceAll(config.databaseUrl, '[test database]') : message });
+ process.exit(1);
+ }
+}
diff --git a/test/graduation-inventory.test.ts b/test/graduation-inventory.test.ts
index 9ca39bbb35..3f07ec2f79 100644
--- a/test/graduation-inventory.test.ts
+++ b/test/graduation-inventory.test.ts
@@ -60,7 +60,7 @@ describe('graduation inventory', () => {
expect(new Set(names).size).toBe(names.length);
const counts: Record<string, number> = {};
for (const e of GRADUATION_INVENTORY.entries) counts[e.class] = (counts[e.class] ?? 0) + 1;
- expect(counts).toEqual({ carry: 139, rebind: 2, rebuild: 3, discard: 9, schema_owned: 4 });
+ expect(counts).toEqual({ carry: 140, rebind: 2, rebuild: 3, discard: 9, schema_owned: 4 });
for (const e of GRADUATION_INVENTORY.entries) {
expect({ relation: e.relation, reason: e.reason.length > 5, present: e.engines.pglite || e.engines.postgres })
.toEqual({ relation: e.relation, reason: true, present: true });
diff --git a/test/helpers/synthetic-generation.ts b/test/helpers/synthetic-generation.ts
index 55d68ea7dc..dabfe2d329 100644
--- a/test/helpers/synthetic-generation.ts
+++ b/test/helpers/synthetic-generation.ts
@@ -35,8 +35,12 @@ export const syntheticAdapter: GenerationAdapter<undefined> = {
};
registerGenerationAdapter(syntheticAdapter as GenerationAdapter<unknown>);
+/** The same kind as a ranked cut (`strictOrder`): a tie in the result holds it (#6023 shape). */
+export const strictSyntheticAdapter: GenerationAdapter<undefined> = { ...syntheticAdapter, strictOrder: true };
+
/** One proposed synthetic item: a note page owned by `ownerKey` with this body. */
-export function syntheticItem(ownerKey: string, slug: string, body: string): ProposedItem {
+export function syntheticItem(ownerKey: string, slug: string, body: string, order?: number): ProposedItem {
+ if (order !== undefined) return { ...syntheticItem(ownerKey, slug, body), order };
return markdownItem(slug, serializeMarkdown({ synthetic_owner: ownerKey, synthetic_producer: 'synthetic' }, body, '', { type: 'note', title: slug.split('/').pop()!, tags: [] }));
}
diff --git a/test/pathological/g1-generation-crash.test.ts b/test/pathological/g1-generation-crash.test.ts
new file mode 100644
index 0000000000..60ad684a69
--- /dev/null
+++ b/test/pathological/g1-generation-crash.test.ts
@@ -0,0 +1,36 @@
+/**
+ * GBRA-161 PR 1a: a publication killed at any of its fault points leaves exactly one coherent generation.
+ *
+ * Protects: SIGKILL at `generation:published` or `generation:retired` (inside the activation transaction) leaves the old
+ * generation live with every item, and the rerun activates the new one once; SIGKILL at `generation:activated` (after
+ * commit) leaves the new generation live, and the rerun republishes nothing. No case leaves a held row, a second live
+ * row or a retired item without its generation.
+ * Fails when: any write of the publication commits outside the activation transaction, or a replay after commit writes again.
+ * Seams: a real child process (test/fixtures/generation-crash-worker.ts) on disk PGLite, or a fresh Postgres database
+ * when DATABASE_URL is set.
+ */
+import { describe, expect, test } from 'bun:test';
+import { GENERATION_CRASH_POINTS, runGenerationCrashCase } from '../fixtures/generation-crash-worker.ts';
+import { pathologicalArms } from './harness.ts';
+
+const OLD = ['derived/a', 'derived/b', 'derived/c', 'derived/d'];
+const NEW = ['derived/a', 'derived/b', 'derived/c'];
+
+for (const { backend, databaseUrl } of pathologicalArms()) {
+ describe(`GBRA-161 generation publish survives SIGKILL (${backend})`, () => {
+ for (const point of GENERATION_CRASH_POINTS) {
+ test(`killed at ${point}`, async () => {
+ const result = await runGenerationCrashCase({ kind: backend, point, databaseUrl });
+ expect(result.killed_signal).toBe('SIGKILL');
+ if (point === 'generation:activated') {
+ expect(result.before).toEqual({ ledger: ['superseded:1', 'live:2'], live: NEW });
+ expect({ rerun: result.rerun, generation: result.rerun_generation, again: result.again }).toEqual({ rerun: 'unchanged', generation: 2, again: 'unchanged' });
+ } else {
+ expect(result.before).toEqual({ ledger: ['live:1'], live: OLD });
+ expect({ rerun: result.rerun, generation: result.rerun_generation, again: result.again }).toEqual({ rerun: 'published', generation: 2, again: 'unchanged' });
+ }
+ expect(result.after).toEqual({ ledger: ['superseded:1', 'live:2'], live: NEW, live_items: 4 });
+ }, 240_000);
+ }
+ });
+}
diff --git a/test/pathological/g1-generation-probes.test.ts b/test/pathological/g1-generation-probes.test.ts
new file mode 100644
index 0000000000..e0851a5cf5
--- /dev/null
+++ b/test/pathological/g1-generation-probes.test.ts
@@ -0,0 +1,194 @@
+/**
+ * GBRA-161 PR 1a: the primitive's remaining edges, each on the synthetic adapter unless named.
+ *
+ * Protects: (a) concurrent first publications of one key leave one live row (identical results replay, a different
+ * result is fenced) and no duplicate items; (b) a successor item deleted between publish and activation fails activation
+ * with `generation_live_conflict` and nothing commits or retires; (c) a different result on the same pin gets a fresh
+ * operation identity, is fenced by the expected generation and is never a replay; (d) a strict-order result with a tie
+ * holds and retires nothing, while a strictly ordered one closes with restorable retirements (#6023 shape); (e) a missing
+ * or uncommitted input cannot mint `committedRemoval` (#7130/#7141 shape); (f) a CLI restore with a refused key exits
+ * non-zero and lists the key; (g) three terminal failures on one hold identity hold the result `attempts_exhausted` with
+ * the last three codes, later runs stop there, and `--mode release-held` publishes it once.
+ * Seams: test/helpers/synthetic-generation.ts. PGLite always, Postgres when DATABASE_URL is set.
+ */
+import { describe, expect, test } from 'bun:test';
+import { mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import type { BrainEngine } from '../../src/core/engine.ts';
+import type { GenerationAdapter } from '../../src/core/generations/contract.ts';
+import { OperationError } from '../../src/core/ops/contract.ts';
+import { committedRemoval } from '../../src/core/generations/proofs.ts';
+import { publishGeneration, type PublishRequest } from '../../src/core/generations/publish.ts';
+import { resolveRepairScope } from '../../src/core/repair/core.ts';
+import { repairRunner } from '../../src/core/repair/registry.ts';
+import { runRepairCommand } from '../../src/commands/repair.ts';
+import { _resetCliExitVerdictForTests, currentExitCode } from '../../src/core/cli-force-exit.ts';
+import { managedPersistenceEnabled } from '../../src/core/persistence/ownership.ts';
+import { _resetWriteThroughCacheForTest } from '../../src/core/write-through.ts';
+import { isolatedSharedSkillsEngine } from '../helpers/shared-skills-engine.ts';
+import { withEnv } from '../helpers/with-env.ts';
+import { liveSlugs, setSyntheticInput, strictSyntheticAdapter, syntheticAdapter, syntheticItem, syntheticKey } from '../helpers/synthetic-generation.ts';
+import { pathologicalArms } from './harness.ts';
+
+const OWNER = 'owner:notes/probe-source';
+const key = syntheticKey('default', OWNER);
+const slug = (name: string) => `derived/${name}`;
+const items = (spec: Record<string, string>, ranked = false) => Object.entries(spec).map(([name, body], index) => syntheticItem(OWNER, slug(name), body, ranked ? index + 1 : undefined));
+const FOUR = { a: 'Alpha claim.', b: 'Beta claim.', c: 'Gamma claim.', d: 'Delta claim.' };
+
+async function withBrain(databaseUrl: string | undefined, run: (engine: BrainEngine) => Promise<void>): Promise<void> {
+ const home = mkdtempSync(join(tmpdir(), 'gbrain-g1p-'));
+ try {
+ await withEnv({ GBRAIN_HOME: home, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined }, async () => {
+ _resetWriteThroughCacheForTest();
+ const { engine, close } = await isolatedSharedSkillsEngine(databaseUrl);
+ try {
+ expect(await managedPersistenceEnabled(engine)).toBe(false);
+ await run(engine);
+ } finally { await close(); setSyntheticInput(key, null); }
+ });
+ } finally { rmSync(home, { recursive: true, force: true }); }
+}
+
+function publish(engine: BrainEngine, spec: Record<string, string>, pin: string, extra: Partial<PublishRequest<undefined>> = {}, adapter: GenerationAdapter<undefined> = syntheticAdapter) {
+ setSyntheticInput(key, { pin, size: 100 });
+ return publishGeneration(engine, adapter, { key, items: items(spec, adapter.strictOrder), input: { pin, size: 100 }, ...extra });
+}
+const codeOf = (error: unknown) => error instanceof OperationError ? error.code : String(error);
+const ledger = async (engine: BrainEngine) => (await engine.executeRaw<{ generation: number; state: string }>('SELECT generation, state FROM derived_generations ORDER BY id'))
+ .map(row => `${row.state}:${Number(row.generation)}`);
+
+for (const { backend, databaseUrl } of pathologicalArms()) {
+ describe(`GBRA-161 generation probes (${backend})`, () => {
+ test('concurrent first publications leave one live row: identical results replay, a different result is fenced', async () => {
+ await withBrain(databaseUrl, async engine => {
+ setSyntheticInput(key, { pin: 'pin-1', size: 100 });
+ const same = await Promise.allSettled(Array.from({ length: 4 }, () => publishGeneration(engine, syntheticAdapter, { key, items: items(FOUR), input: { pin: 'pin-1', size: 100 } })));
+ expect(same.map(result => result.status === 'fulfilled' ? result.value.state : codeOf(result.reason)).sort()).toEqual(['published', 'unchanged', 'unchanged', 'unchanged']);
+ expect(await ledger(engine)).toEqual(['live:1']);
+ const [count] = await engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM derived_generation_items');
+ expect(Number(count!.n)).toBe(4);
+ });
+ await withBrain(databaseUrl, async engine => {
+ setSyntheticInput(key, { pin: 'pin-1', size: 100 });
+ const racing = await Promise.allSettled([FOUR, { e: 'Epsilon claim.' }].map(spec =>
+ publishGeneration(engine, syntheticAdapter, { key, items: items(spec), input: { pin: 'pin-1', size: 100 }, expectedGeneration: 0 })));
+ expect(racing.map(result => result.status === 'fulfilled' ? result.value.state : codeOf(result.reason)).sort()).toEqual(['generation_fenced', 'published']);
+ expect(await ledger(engine)).toEqual(['live:1']);
+ const live = await liveSlugs(engine, OWNER);
+ expect([[slug('a'), slug('b'), slug('c'), slug('d')], [slug('e')]]).toContainEqual(live);
+ });
+ }, 120_000);
+
+ test('a successor item deleted between publish and activation fails activation; nothing commits or retires', async () => {
+ await withBrain(databaseUrl, async engine => {
+ await publish(engine, FOUR, 'pin-1');
+ const hiding: GenerationAdapter<undefined> = { ...syntheticAdapter, async publishItems(tx, k, written, context) {
+ await syntheticAdapter.publishItems(tx, k, written, context);
+ await tx.softDeletePages([slug('e')], { sourceId: k.sourceId });
+ } };
+ const failed = await publish(engine, { a: 'Alpha claim.', b: 'Beta claim.', c: 'Gamma claim.', e: 'Epsilon claim.' }, 'pin-2', {}, hiding).catch(error => error);
+ expect(codeOf(failed)).toBe('generation_live_conflict');
+ expect(await ledger(engine)).toEqual(['live:1']);
+ expect(await liveSlugs(engine, OWNER)).toEqual([slug('a'), slug('b'), slug('c'), slug('d')]);
+ expect(await engine.executeRaw('SELECT 1 FROM pages WHERE slug=$1', [slug('e')])).toEqual([]);
+ });
+ }, 120_000);
+
+ test('a different result on the same pin gets a fresh identity: fenced by the expected generation, never a replay', async () => {
+ await withBrain(databaseUrl, async engine => {
+ expect(await publish(engine, FOUR, 'pin-1', { expectedGeneration: 0 })).toMatchObject({ state: 'published', generation: 1 });
+ const stale = await publish(engine, { a: 'Alpha claim.', b: 'Beta claim.', c: 'Gamma claim.', e: 'Epsilon claim.' }, 'pin-1', { expectedGeneration: 0 }).catch(error => error);
+ expect(codeOf(stale)).toBe('generation_fenced');
+ expect((stale as OperationError).details?.reason ?? (stale as { reason?: string }).reason).toBe('stale_generation');
+ expect(await publish(engine, FOUR, 'pin-1', { expectedGeneration: 0 })).toMatchObject({ state: 'unchanged', generation: 1 });
+ const next = await publish(engine, { a: 'Alpha claim.', b: 'Beta claim.', c: 'Gamma claim.', e: 'Epsilon claim.' }, 'pin-1', { expectedGeneration: 1 });
+ expect(next).toMatchObject({ state: 'published', generation: 2, retired: [slug('d')] });
+ const ops = await engine.executeRaw<{ operation_id: string }>('SELECT operation_id FROM derived_generations ORDER BY id');
+ expect(new Set(ops.map(row => row.operation_id)).size).toBe(2);
+ });
+ }, 120_000);
+
+ test('a strict-order result with a tie holds and retires nothing; a strictly ordered one closes with restorable retirements', async () => {
+ await withBrain(databaseUrl, async engine => {
+ await publish(engine, FOUR, 'pin-1', {}, strictSyntheticAdapter);
+ setSyntheticInput(key, { pin: 'pin-2', size: 100 });
+ const tied = [syntheticItem(OWNER, slug('a'), 'Alpha claim.', 1), syntheticItem(OWNER, slug('b'), 'Beta claim.', 2), syntheticItem(OWNER, slug('c'), 'Gamma claim.', 2)];
+ expect(await publishGeneration(engine, strictSyntheticAdapter, { key, items: tied, input: { pin: 'pin-2', size: 100 } })).toMatchObject({ state: 'held', reason: 'tie' });
+ expect(await liveSlugs(engine, OWNER)).toEqual([slug('a'), slug('b'), slug('c'), slug('d')]);
+ const ordered = await publish(engine, { a: 'Alpha claim.', b: 'Beta claim.', c: 'Gamma claim.' }, 'pin-2', {}, strictSyntheticAdapter);
+ expect(ordered).toMatchObject({ state: 'published', retired: [slug('d')] });
+ const [retired] = await engine.executeRaw<{ has_preimage: boolean }>(`SELECT i.preimage IS NOT NULL AS has_preimage FROM derived_generation_items i
+ JOIN derived_generations g ON g.id=i.generation_id WHERE g.state='live' AND i.action='retired'`);
+ expect(retired).toEqual({ has_preimage: true });
+ });
+ }, 120_000);
+
+ test('a missing or uncommitted input cannot mint committedRemoval; the committed removal retires', async () => {
+ await withBrain(databaseUrl, async engine => {
+ await publish(engine, { a: 'Alpha claim.' }, 'pin-1');
+ setSyntheticInput(key, null);
+ expect(await publishGeneration(engine, syntheticAdapter, { key, items: [], proof: committedRemoval('pin-2') })).toMatchObject({ state: 'held', reason: 'no_proof' });
+ setSyntheticInput(key, { pin: 'pin-3', size: 0 });
+ expect(await publishGeneration(engine, syntheticAdapter, { key, items: [], proof: committedRemoval('pin-2') })).toMatchObject({ state: 'held', reason: 'no_proof' });
+ expect(await liveSlugs(engine, OWNER)).toEqual([slug('a')]);
+ setSyntheticInput(key, { pin: 'pin-2', size: 0 });
+ expect(await publishGeneration(engine, syntheticAdapter, { key, items: [], proof: committedRemoval('pin-2'), input: { pin: 'pin-2', size: 0 } }))
+ .toMatchObject({ state: 'published', retired: [slug('a')] });
+ });
+ }, 120_000);
+
+ test('a CLI restore with a refused key exits non-zero and lists the key', async () => {
+ await withBrain(databaseUrl, async engine => {
+ await publish(engine, FOUR, 'pin-1');
+ await publish(engine, { a: 'Alpha claim.', b: 'Beta claim.', c: 'Gamma claim.', e: 'Epsilon claim.' }, 'pin-2');
+ await engine.putPage(slug('e'), { type: 'note', title: 'e', compiled_truth: 'Epsilon, edited by hand.', frontmatter: { synthetic_owner: OWNER, synthetic_producer: 'synthetic' } });
+ const scope = await resolveRepairScope(engine, 'default');
+ const quiet = { info: () => {}, warn: () => {}, error: () => {} };
+ const preview = await (await repairRunner(engine, { apply: false, logger: quiet })).run('generations', scope,
+ { explicit: true, sourceFlag: 'default', generations: { kind: 'synthetic', mode: 'restore', key: OWNER } });
+ const lines: string[] = [];
+ const log = console.log, err = console.error;
+ console.log = (...args: unknown[]) => { lines.push(args.map(String).join(' ')); };
+ console.error = () => {};
+ try {
+ await runRepairCommand(engine, ['generations', '--kind', 'synthetic', '--key', OWNER, '--source', 'default', '--apply', '--expect', preview.preview_hash!, '--yes', '--json']);
+ expect(currentExitCode()).toBe(1);
+ } finally { console.log = log; console.error = err; _resetCliExitVerdictForTests(); process.exitCode = 0; }
+ const out = JSON.parse(lines.join('\n')) as { results: Array<{ stopped?: { reason: string; message: string }; outcome_items?: Array<{ item: string; outcome: string }> }> };
+ expect(out.results[0]!.stopped?.reason).toBe('incomplete');
+ expect(out.results[0]!.stopped?.message).toContain(`${slug('e')}: edited_since`);
+ expect(out.results[0]!.outcome_items).toEqual([expect.objectContaining({ item: `default:${OWNER}`, outcome: 'refused' })]);
+ expect(await liveSlugs(engine, OWNER)).toEqual([slug('a'), slug('b'), slug('c'), slug('e')]);
+ });
+ }, 120_000);
+
+ test('three terminal failures on one hold identity hold attempts_exhausted with the last three codes; release-held publishes it once', async () => {
+ await withBrain(databaseUrl, async engine => {
+ await publish(engine, FOUR, 'pin-1');
+ let calls = 0;
+ const failing: GenerationAdapter<undefined> = { ...syntheticAdapter, async publishItems() { calls++; throw Object.assign(new Error('synthetic write failure'), { code: `E_SYNTH_${calls}` }); } };
+ const next = { a: 'Alpha claim, revised.', b: 'Beta claim.', c: 'Gamma claim.', d: 'Delta claim.' };
+ for (let i = 1; i <= 3; i++) expect(String(await publish(engine, next, 'pin-2', {}, failing).catch(error => error.code))).toBe(`E_SYNTH_${i}`);
+ const stopped = await publish(engine, next, 'pin-2', {}, failing);
+ expect(stopped).toMatchObject({ state: 'held', reason: 'attempts_exhausted' });
+ expect(calls).toBe(3);
+ const [held] = await engine.executeRaw<{ held_reason: string; held_context: { codes: string[] } }>("SELECT held_reason, held_context FROM derived_generations WHERE state='held'");
+ expect(held?.held_reason).toBe('attempts_exhausted');
+ expect(held?.held_context.codes).toEqual(['E_SYNTH_1', 'E_SYNTH_2', 'E_SYNTH_3']);
+ expect(await engine.executeRaw('SELECT 1 FROM derived_generation_attempts')).toEqual([]);
+ const scope = await resolveRepairScope(engine, 'default');
+ const quiet = { info: () => {}, warn: () => {}, error: () => {} };
+ const selection = { kind: 'synthetic', mode: 'release-held' as const, held: true };
+ const preview = await (await repairRunner(engine, { apply: false, logger: quiet })).run('generations', scope, { explicit: true, sourceFlag: 'default', generations: selection });
+ expect(preview.listing).toEqual([expect.objectContaining({ class: 'release-held', detail: expect.stringContaining('held attempts_exhausted') })]);
+ const applied = await (await repairRunner(engine, { apply: true, noEmbed: true, logger: quiet })).run('generations', scope,
+ { explicit: true, sourceFlag: 'default', generations: selection, expect: preview.preview_hash });
+ expect(applied.outcomes).toEqual({ released: 1 });
+ expect(await ledger(engine)).toEqual(['superseded:1', 'live:2']);
+ expect((await engine.executeRaw<{ compiled_truth: string }>('SELECT compiled_truth FROM pages WHERE slug=$1', [slug('a')]))[0]!.compiled_truth).toContain('revised');
+ });
+ }, 120_000);
+ });
+}