Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(persistence): preparers name their step at each await boundary; memo rule; fault point consumer:preparing (#6278)
garrytanbc0a7baeb494
diff --git a/src/core/persistence/group-publish.ts b/src/core/persistence/group-publish.tsindex 1e32618088..17ef15fa08 100644--- a/src/core/persistence/group-publish.ts+++ b/src/core/persistence/group-publish.ts@@ -145,7 +145,7 @@ const STABLE_IN_PREPARATION = new Set([* publication re-checks what it relies on under its locks. It lives only for* one group's preparation; a failed read is not kept.*/-function preparationReads(engine: BrainEngine): BrainEngine {+export function preparationReads(engine: BrainEngine): BrainEngine {const reads = new Map<string, Promise<unknown>>();const once = <T>(id: string, read: () => Promise<T>): Promise<T> => {let value = reads.get(id) as Promise<T> | undefined;diff --git a/src/core/persistence/page-prepare.ts b/src/core/persistence/page-prepare.tsindex 8abbdeea28..1214dec574 100644--- a/src/core/persistence/page-prepare.ts+++ b/src/core/persistence/page-prepare.ts@@ -1,4 +1,5 @@import { isEmbedSkipped } from '../embed-skip.ts';+import { enterClaimStep, type ClaimPhaseClock } from './claim-phase.ts';import { isQuarantined, quarantineOutcome } from '../quarantine.ts';import { existsSync, readFileSync } from 'node:fs';import { join, relative, sep } from 'node:path';@@ -253,10 +254,13 @@ async function pageDatabaseOnlyPublication(engine: SqlEngine, row: WriteRequest,* `coordinated`: the caller publishes this mutation itself through the coordinator, whose* page guard and revision check on `row.slug` cover this import (the put_page apply diet).*/+/** `options.clock` (#6278): the claim's phase clock; each await boundary names its step through `enterClaimStep`. */export async function preparePageMutation(engine: BrainEngine, row: WriteRequest, _config: GBrainConfig,preparedIntent?: { content: string; expectedRevision: string; tags?: string[] }, signal?: AbortSignal,- options: { allowMissingFile?: boolean; coordinated?: boolean } = {}): Promise<PreparedMutation> {+ options: { allowMissingFile?: boolean; coordinated?: boolean; clock?: ClaimPhaseClock } = {}): Promise<PreparedMutation> {signal?.throwIfAborted();+ const clock = options.clock;+ enterClaimStep(clock, 'page_snapshot', undefined, 'db');if (!row.intent) throw pageRefusal('storage_error', 'A pending write lost its normalized intent.', row,`The request has no stored intent for ${row.slug} (its payload was compacted or never recorded), so it cannot be published and wrote nothing.`);const p = row.intent;@@ -269,6 +273,7 @@ export async function preparePageMutation(engine: BrainEngine, row: WriteRequest() => loadActivePackForEngine(engine, { remote: row.authority.remote, sourceId: row.source_id }).catch(() => null),]) as [unknown, PageSnapshot | null, Awaited<ReturnType<typeof loadActivePackForEngine>> | null];signal?.throwIfAborted();+ enterClaimStep(clock, 'revision_check');assertPageRevision(snapshot, preparedIntent ? { expectedRevision: preparedIntent.expectedRevision } : engineMutationPrecondition(parseMutationPrecondition(p)));if ((snapshot?.page.id ?? null) !== row.page_id) throw pageIdentityError(snapshot != null || row.page_id === null, 'The accepted page identity changed.');const observedRevision = snapshot?.revision ?? null;@@ -288,7 +293,8 @@ export async function preparePageMutation(engine: BrainEngine, row: WriteRequestconst purge = p.purge === true;const noop = !purge && snapshot.page.deleted_at != null;// Always-loaded core pages: a remote caller cannot delete one (owner-only).- if (!noop) await prepareCoreGuard(engine, { row, snapshot, incoming: null });+ if (!noop) { enterClaimStep(clock, 'core_guard', undefined, 'db'); await prepareCoreGuard(engine, { row, snapshot, incoming: null }); }+ enterClaimStep(clock, 'file_target', undefined, 'fs');// Tombstones still own their recorded artifact. Purge always attempts its// removal before the guarded hard-delete and receipt commit; failure rolls// back to the prior row, and replay survives the eventual absence of that row.@@ -356,12 +362,14 @@ export async function preparePageMutation(engine: BrainEngine, row: WriteRequest&& (preparedIntent !== undefined || typeof p.expected_revision === 'string') ? 'editing' : 'preserving';// #5969 (D3): only an ordinary put_page intent carries a timeline section; every other writer keeps the shared policy.const timelinePolicy = row.operation === 'put_page' ? timelineWritePolicy(p, row.authority.remote, writer) : undefined;+ enterClaimStep(clock, 'timeline_policy', undefined, 'db');if (timelinePolicy && typeof content === 'string') await assertTimelineNotOmitted(engine, { intent: p, remote: row.authority.remote, writer,slug: row.slug, sourceId: row.source_id, content, prior: snapshot });// #5567: database-only timeline rows are written back into the page before// the no-op check, digest, rendering and chunking see the body.if (projected && snapshot && typeof content === 'string') {const parsed = parseMarkdown(content,row.slug);+ enterClaimStep(clock, 'materialize_timeline', undefined, 'db');const { timeline, materialized } = await materializeTimeline(engine,parsed,row.slug,snapshot,writer,timelinePolicy);if (materialized) content = serializePageToMarkdown({...snapshot.page,...parsed,timeline,type:parsed.typeExplicit ? parsed.type : snapshot.page.type},parsed.tags);}@@ -383,6 +391,7 @@ export async function preparePageMutation(engine: BrainEngine, row: WriteRequest// The apply diet: the publisher's locked read of row.slug is the import base, and one read after the// last page write serves the read-back check, the seal, the core notice and the receipt (as sync does).const lean = options.coordinated === true && !targetDeleted && row.operation !== 'restore_page' && !versionTags;+ enterClaimStep(clock, 'import_content', undefined, 'db');const result = await importFromContent(engine, row.slug, content, {...source, noEmbed: true, remote: row.authority.remote, activePack, fences: projected ? 'coordinated' : 'lenient', coordinated: lean,...(lean ? { existingSnapshot: snapshot } : {}),@@ -441,6 +450,8 @@ export async function preparePageMutation(engine: BrainEngine, row: WriteRequestconst autoLinkedPage = ordinaryPage || p.kind === 'managed_maintenance_page';const capture = row.operation === 'capture' && typeof p.capture_path === 'string' && typeof p.capture_file_hash === 'string'? { path: p.capture_path, hash: p.capture_file_hash } : undefined;+ // Projections, advisories, link resolution (links-preparation.ts), the file target and the core guard go out together.+ enterClaimStep(clock, 'link_resolution', undefined, 'db');const [project, advisories, links, target, core] = await pipelined(together, [async () => projected ? prepareCanonicalProjections(engine,ready.parsedPage,row.slug,row.source_id,snapshot,writer,timelinePolicy) : undefined,async () => noop || targetDeleted ? pageNoopAdvisories(row) : !ordinaryPage ? remoteLinkHint(row) : preparePageAdvisories(engine,row,ready.parsedPage,snapshot),@@ -456,6 +467,7 @@ export async function preparePageMutation(engine: BrainEngine, row: WriteRequestconst fencesNormalized = shownFixes.length ? { fences_normalized: pageFencesNormalized({ sourceId: row.source_id, slug: row.slug, fixes: shownFixes,writer: row.principal_kind, path: snapshot?.page.source_path ?? null, remote: row.authority.remote }) } : {};const file = target && fenceRepair ? { ...target, commit: fenceRepairCommit(relative(target.root, target.path).split(sep).join('/'), fenceRepair.classes) } : target;+ enterClaimStep(clock, 'publication_mode', undefined, 'db');const [mintMode, databaseOnly] = await pipelined(together, [async () => file && !snapshot?.page.source_path ? scannerSlugRootMode(engine, row.source_id, file.root) : undefined,() => pageDatabaseOnlyPublication(engine, row, file),diff --git a/src/core/persistence/prepared-maintenance.ts b/src/core/persistence/prepared-maintenance.tsindex d27d48fc07..5ce0270967 100644--- a/src/core/persistence/prepared-maintenance.ts+++ b/src/core/persistence/prepared-maintenance.ts@@ -1,4 +1,5 @@import { realpathSync } from 'node:fs';+import { enterClaimStep, type ClaimPhaseClock } from './claim-phase.ts';import { join } from 'node:path';import type { BrainEngine, FactRow } from '../engine.ts';import { loadConfig, type GBrainConfig } from '../config.ts';@@ -266,7 +267,8 @@ export async function submitFactFenceAdoption(engine: BrainEngine, authority: Ma}}-async function prepareFactFenceAdoption(engine: BrainEngine, row: WriteRequest, config: GBrainConfig): Promise<PreparedMutation> {+/** `clock` (#6278): the claim's phase clock; the adoption's await boundaries (read facts, parse, occupied rows, the page) name their step. */+async function prepareFactFenceAdoption(engine: BrainEngine, row: WriteRequest, config: GBrainConfig, clock?: ClaimPhaseClock): Promise<PreparedMutation> {const p = row.intent!;const facts = p.facts as FactFenceAssignment[];if (p.source_incarnation !== row.source_incarnation) throw opError('source_changed', 'The fact adoption source changed.',@@ -277,8 +279,11 @@ async function prepareFactFenceAdoption(engine: BrainEngine, row: WriteRequest,`Fact-fence adoption request ${row.request_id} for ${row.slug} in ${row.source_id} was refused before publication; nothing changed. The plan itself is malformed, so report the request ID to the user rather than running the same backfill again.`,{ fix: receiptFix(row) });}+ enterClaimStep(clock, 'adoption_parse_fence');const fence = new Map(parseFactsFence(p.content as string).facts.map(f => [f.rowNum, f]));+ // `lock` is the publication transaction's re-check: the claim's clock stamps only the preparation's reads.const check = async (db: BrainEngine, lock: boolean) => {+ if (!lock) enterClaimStep(clock, 'adoption_read_facts', undefined, 'db');const current = await readFacts(db, row.source_id, facts.map(f => f.id), lock);for (const assignment of facts) {const fact = current.find(f => f.id === assignment.id);@@ -295,6 +300,7 @@ async function prepareFactFenceAdoption(engine: BrainEngine, row: WriteRequest,{ fix: receiptFix(row) });}}+ if (!lock) enterClaimStep(clock, 'adoption_occupied_rows', undefined, 'db');const occupied = await db.executeRaw(`SELECT id FROM facts WHERE source_id=$1 AND source_markdown_slug=$2AND row_num=ANY($3::integer[])${lock ? ' FOR UPDATE' : ''}`, [row.source_id, row.slug, facts.map(f => f.row_num)]);if (occupied.length) throw opError('revision_conflict', 'An adopted fence position is already owned by another fact.',@@ -303,7 +309,7 @@ async function prepareFactFenceAdoption(engine: BrainEngine, row: WriteRequest,};await check(engine, false);const prepared = await preparePageMutation(engine, { ...row, intent: { kind: 'managed_maintenance_page', content: p.content,- expected_revision: p.expected_revision } }, config);+ expected_revision: p.expected_revision } }, config, undefined, undefined, { clock });return { ...prepared, validate: async tx => { await prepared.validate?.(tx); await check(tx, true); }, apply: async tx => {// Runs ahead of the page import and its canonical projection, so the// projection's expiry pass and insertFacts see the adopted positions.@@ -335,14 +341,16 @@ export async function applyPreservingTakeResolutions(tx: BrainEngine, pageId: nureturn outcome;}-export async function prepareMaintenanceMutation(engine: BrainEngine, row: WriteRequest, config: GBrainConfig): Promise<PreparedMutation> {+/** `clock` (#6278): the claim's phase clock, threaded to the page and adoption preparers' step boundaries. */+export async function prepareMaintenanceMutation(engine: BrainEngine, row: WriteRequest, config: GBrainConfig, clock?: ClaimPhaseClock): Promise<PreparedMutation> {if (row.authority.remote) throw trustedCliRequired('Remote maintenance publication is not supported.');+ enterClaimStep(clock, 'maintenance_dispatch');if (row.intent?.kind === 'managed_maintenance_restore_extractor_facts') return (await import('../repair/extractor-facts.ts')).prepareExtractorFactsRestore(engine, row);if (row.intent?.kind === 'managed_maintenance_expire_captured_facts') return (await import('../repair/captured-facts.ts')).prepareCapturedFactsExpiry(engine, row);if (row.intent?.kind === 'managed_maintenance_timeline_extract') return (await import('../../commands/extract-timeline-db.ts')).prepareTimelineExtract(engine, row);if (row.intent?.kind === 'managed_maintenance_page') {const prepared = await preparePageMutation(engine, row.intent.expected_revision === null- ? { ...row, intent: { ...row.intent, expected_revision: undefined } } : row, config);+ ? { ...row, intent: { ...row.intent, expected_revision: undefined } } : row, config, undefined, undefined, { clock });const projection = row.intent.event_projection as MaintenanceEventProjection | undefined;if (!projection) return prepared;// #5523: the event page and its depth-page timeline row commit together in@@ -356,7 +364,7 @@ export async function prepareMaintenanceMutation(engine: BrainEngine, row: Writereturn { ...outcome, event_projected: projected };} };}- if (row.intent?.kind === 'managed_maintenance_adopt_fact_fence') return prepareFactFenceAdoption(engine, row, config);+ if (row.intent?.kind === 'managed_maintenance_adopt_fact_fence') return prepareFactFenceAdoption(engine, row, config, clock);if (row.intent?.kind === 'managed_maintenance_phantom_merge') return (await import('../cycle/phantom-redirect-managed.ts')).preparePhantomMerge(engine, row, config);if (row.intent?.kind === 'managed_maintenance_phantom_delete') return (await import('../cycle/phantom-redirect-managed.ts')).preparePhantomDelete(engine, row, config);if (row.intent?.kind === 'managed_maintenance_chronicle_event' || row.intent?.kind === 'managed_maintenance_chronicle_retire') {diff --git a/src/core/persistence/service.ts b/src/core/persistence/service.tsindex 25398555e5..332f9ddce1 100644--- a/src/core/persistence/service.ts+++ b/src/core/persistence/service.ts@@ -11,6 +11,7 @@ import { registerPgliteReopen } from '../pglite-lifecycle.ts';import { assertMutationProtocol } from './protocol.ts';import { writeSwitchOn } from './switches.ts';import { pendingWriteHint } from './health.ts';+import { enterClaimStep, type ClaimPhaseClock } from './claim-phase.ts';import { receiptDeliveredHint } from './connector-errors.ts';import type { PgAccessReason } from '../pg-access-classify.ts';import { contentRefusalFromReceipt } from '../import-screen.ts';@@ -47,12 +48,17 @@ const preparers = new Map<string, { prepare: PrepareMutation; target: 'page' | 'export function registerMutationPreparer(operation: string, prepare: PrepareMutation, target: 'page' | 'skill_bundle' = 'page'): void {preparers.set(operation, { prepare, target });}-export async function preparePersistedMutation(e: BrainEngine, row: WriteRequest, cfg: GBrainConfig, signal?: AbortSignal) {+/**+ * `signal` is the foreground (remember/put_page/edit_page) statement signal, as before; `clock` (#6278) is the claim's+ * phase clock, which carries the preparation's cancellation to every preparer's `enterClaimStep` boundaries.+ */+export async function preparePersistedMutation(e: BrainEngine, row: WriteRequest, cfg: GBrainConfig, signal?: AbortSignal, clock?: ClaimPhaseClock) {assertMutationProtocol(row);+ enterClaimStep(clock, 'dispatch');const registered = preparers.get(row.operation);if (registered) {if (registered.target !== (row.target_kind ?? 'page')) throw new OperationError('unsupported_mutation_protocol', 'The registered preparer does not support this mutation target.', `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.`);- return registered.prepare(e, row, cfg, signal);+ return registered.prepare(e, row, cfg, signal, clock);}if (row.target_kind === 'skill_bundle') {if (['put_skill', 'delete_skill'].includes(row.operation)) return (await import('../shared-skills/publication.ts')).prepareSharedSkillMutation(e, row, cfg);@@ -65,8 +71,8 @@ export async function preparePersistedMutation(e: BrainEngine, row: WriteRequestif (row.operation === 'put_page' && row.intent?.kind === 'canonical_reconcile') return (await import('./reconcile-prepare.ts')).prepareReconcileMutation(e, row, cfg);if (row.operation === 'put_page' && row.intent?.kind === 'managed_grandfather') return (await import('./grandfather.ts')).prepareGrandfatherMutation(e, row);if (row.operation === 'submit_job' && row.intent?.kind === 'code_projection_reindex') return (await import('./projection-reindex.ts')).prepareCodeReindex(e, row);- if (row.operation === 'submit_job' && String(row.intent?.kind).startsWith('managed_sync_')) return (await import('./sync-prepare.ts')).prepareManagedSyncMutation(e, row, cfg);- if (row.operation === 'submit_job' && String(row.intent?.kind).startsWith('managed_maintenance_')) return (await import('./prepared-maintenance.ts')).prepareMaintenanceMutation(e, row, cfg);+ if (row.operation === 'submit_job' && String(row.intent?.kind).startsWith('managed_sync_')) return (await import('./sync-prepare.ts')).prepareManagedSyncMutation(e, row, cfg, clock);+ if (row.operation === 'submit_job' && String(row.intent?.kind).startsWith('managed_maintenance_')) return (await import('./prepared-maintenance.ts')).prepareMaintenanceMutation(e, row, cfg, clock);if (row.operation === 'put_page' && row.intent?.kind === 'managed_file_import') return (await import('./import-prepare.ts')).prepareManagedImportMutation(e, row, cfg);if (row.operation === 'put_page' && row.intent?.kind === 'managed_file_repair') return (await import('./file-repair.ts')).prepareManagedFileRepairMutation(e, row, cfg);if (row.operation === 'remember') return (await import('./memory-mutations.ts')).prepareMemoryMutation(e, row, cfg, signal);@@ -76,7 +82,7 @@ export async function preparePersistedMutation(e: BrainEngine, row: WriteRequestif (['takes_add','takes_update','takes_supersede','takes_resolve','takes_remove'].includes(row.operation)) return (await import('./takes-prepare.ts')).prepareTakesMutation(e,row,cfg);if (['add_tag','remove_tag','add_timeline_entry'].includes(row.operation)) return prepareSemanticPageMutation(e, row, cfg);if (['put_page','capture','delete_page','restore_page','revert_version','edit_page'].includes(row.operation)) return preparePageMutation(e, row, cfg, undefined, signal,- { coordinated: await writeSwitchOn(e, 'single_write_group').catch(() => true) });+ { coordinated: await writeSwitchOn(e, 'single_write_group').catch(() => true), clock });throw new OperationError('unsupported_mutation_protocol', 'No compatible mutation preparer is registered for this operation.', `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.`);}export function startPersistenceConsumer(engine: BrainEngine, config: GBrainConfig): PersistenceConsumer {diff --git a/src/core/persistence/sync-prepare.ts b/src/core/persistence/sync-prepare.tsindex f4daf9a832..5bd568bbd3 100644--- a/src/core/persistence/sync-prepare.ts+++ b/src/core/persistence/sync-prepare.ts@@ -1,4 +1,5 @@import { realpathSync } from 'node:fs';+import { enterClaimStep, type ClaimPhaseClock } from './claim-phase.ts';import { basename, join } from 'node:path';import type { BrainEngine } from '../engine.ts';import type { GBrainConfig } from '../config.ts';@@ -228,7 +229,13 @@ function companyWritebackRefusal(row: WriteRequest, p: SyncIntent, fenceFixes: r: `The file of ${row.slug} needs a canonical correction, and a company-brain source never rewrites repository files; correct it in the repository and commit.`);}-export async function prepareManagedSyncMutation(engine: BrainEngine, row: WriteRequest, _config: GBrainConfig): Promise<PreparedMutation> {+/**+ * `clock` (#6278): the claim's phase clock. Each await boundary below names its step and what it waits on+ * (`enterClaimStep`), which also throws the preparation's abort reason once its budget cut it off. No+ * statement here takes the member's signal: the reads a group memoizes (preparationReads) must stay shared,+ * and the step boundaries are where cancellation lands.+ */+export async function prepareManagedSyncMutation(engine: BrainEngine, row: WriteRequest, _config: GBrainConfig, clock?: ClaimPhaseClock): Promise<PreparedMutation> {const p = row.intent as SyncIntent | null;if (!p || !['managed_sync_import', 'managed_sync_delete', 'managed_sync_checkpoint'].includes(p.kind)) throw syncPublicationRefusal('invalid_params', 'Unsupported internal sync intent.', row, p,'The request does not carry a managed sync intent this release can publish.');@@ -241,21 +248,27 @@ export async function prepareManagedSyncMutation(engine: BrainEngine, row: Writeif (await transactionMemo(tx, `git-holds:${row.source_id}:${row.source_incarnation}`, () => countGitHolds(tx, row.source_id, row.source_incarnation)) === 0) return;await clearGitHold(tx, { sourceId: row.source_id, incarnation: row.source_incarnation, path, observedAt: p.holdObservedAt });};+ enterClaimStep(clock, 'managed_sync_active', undefined, 'db');await assertManagedSyncActive(engine);if (p.kind !== 'managed_sync_delete' && (!p.processingOptions ||['noEmbed', 'noExtract', 'noSchemaPack'].some(key => typeof p.processingOptions?.[key as keyof SyncProcessingOptions] !== 'boolean'))) {throw new OperationError('invalid_params', 'The legacy sync request has no durable processing options.','Inspect this unchanged request, then use --retry-failed with explicit sync options to rediscover. Unknown embedding and schema consent cannot be inferred from a retry.');}+ enterClaimStep(clock, 'authority', undefined, 'db');await validateSyncAuthority(engine, p.syncAuthority, row.slug);+ enterClaimStep(clock, 'worktree_binding', undefined, 'db');const binding = await getWorktreeBinding(engine, row.source_id);if (!binding?.local_path || String(binding.owner_epoch) !== p.ownerEpoch) throw syncPublicationRefusal('owner_unavailable', 'The accepted sync owner changed.', row, p,`The canonical owner of ${row.source_id} changed, or lost its local path, after this sync was admitted. Do not claim or transfer the source to repair content.`, true);const root = join(binding.local_path, binding.relative_path);+ enterClaimStep(clock, 'configured_root', undefined, 'db');const [configuredSource] = await engine.executeRaw<{ local_path: string | null }>('SELECT local_path FROM sources WHERE id=$1', [row.source_id]);assertConfiguredSyncRoot(root, configuredSource?.local_path ?? null);- if (p.kind !== 'managed_sync_checkpoint') await assertKnowledgePublicationAllowed(engine, row,- p.path === null ? undefined : { root, path: join(root, p.path) });+ if (p.kind !== 'managed_sync_checkpoint') {+ enterClaimStep(clock, 'knowledge_publication', undefined, 'db');+ await assertKnowledgePublicationAllowed(engine, row, p.path === null ? undefined : { root, path: join(root, p.path) });+ }let origin: Parameters<typeof assertSyncEntryOrigin>[1] | undefined;let originContext: Parameters<typeof assertSyncEntryOrigin>[0] | undefined;let originScope: SyncOriginScope | undefined;@@ -264,6 +277,7 @@ export async function prepareManagedSyncMutation(engine: BrainEngine, row: Write'The stored intent has no recorded file path for this page.');let working = p.working;if (p.kind === 'managed_sync_delete' && working === undefined) {+ enterClaimStep(clock, 'manifest_entry', undefined, 'db');const [manifest] = await engine.executeRaw<{ entry: { path: string; sourcePath: string; action: string; working: boolean; pageId?: number | null } }>("SELECT completed_keys->$2::integer AS entry FROM op_checkpoints WHERE op='managed-sync-manifest' AND fingerprint=$1", [p.runId, p.index]);const entry = manifest?.entry;@@ -275,9 +289,11 @@ export async function prepareManagedSyncMutation(engine: BrainEngine, row: Writeworking = entry.working;}origin = { path: p.path, sourcePath: p.sourcePath, action: p.kind === 'managed_sync_delete' ? 'delete' : 'import', working };+ enterClaimStep(clock, 'git_rev_parse', undefined, 'git');originContext = { root, gitRoot: realpathSync(syncGit(root, ['rev-parse', '--show-toplevel']).trim()), target: p.target, slugMode: p.slugMode };assertSyncEntryOrigin(originContext, origin);originScope = syncOriginScope({ ...originContext, sourceId: row.source_id });+ enterClaimStep(clock, 'origin_check', undefined, 'db');await assertSyncPageOrigin(engine, row.source_id, p.sourcePath, originPageId, p.kind === 'managed_sync_delete', originScope);if (p.renameFrom) await assertSyncPageOrigin(engine, row.source_id, p.renameFrom.sourcePath, p.renameFrom.pageId, true, originScope);}@@ -357,6 +373,7 @@ export async function prepareManagedSyncMutation(engine: BrainEngine, row: Writereturn { status: 'synced', source_id: row.source_id, committed_pages: p.total };} };const source = { sourceId: row.source_id };+ enterClaimStep(clock, 'page_snapshot', undefined, 'db');const snapshot = await engine.readPageSnapshot(row.slug, { ...source, includeDeleted: true });assertPageRevision(snapshot, p.expected_revision === null ? {} : { expectedRevision: p.expected_revision });const recordedOrigin = moved?.slug === row.slug ? moved.sourcePath : p.sourcePath!;@@ -367,6 +384,7 @@ export async function prepareManagedSyncMutation(engine: BrainEngine, row: Write}if (p.unownedDeletion) return { observedRevision: snapshot!.revision, noop: true, validate,apply: async tx => { await releaseHold(tx); return { status: 'skipped', slug: row.slug, source_id: row.source_id, noop: true, reason: 'unowned_deleted_path' }; } };+ enterClaimStep(clock, 'unbound_source_check', undefined, 'db');if (snapshot && snapshot.page.source_path == null && await isUnboundSourcePage(engine, row.source_id, row.slug)) {throw syncPublicationRefusal('source_changed', UNBOUND_COLLISION_MESSAGE, row, p,`A canonical file now occupies the path of page ${row.slug}, written while ${row.source_id} was unbound; neither copy was overwritten. Rename or remove the file and commit, or copy what you need into the page first.`);@@ -389,6 +407,7 @@ export async function prepareManagedSyncMutation(engine: BrainEngine, row: Writeconst codeScreen = screenImportContent({ content: p.content, path: p.sourcePath });if (codeScreen.status === 'refused') throw syncContentRefusal(codeScreen.refusal, row, p);let prepared: PreparedContentImport | undefined;+ enterClaimStep(clock, 'code_import', undefined, 'db');const result = await importCodeFile(engine, p.sourcePath, p.content, { ...source, noEmbed: true,prepare: async value => { prepared = value; return value.result; } });if (!prepared || prepared.slug !== row.slug) throw syncPublicationRefusal('invalid_params', result.error ?? 'The code file identity could not be prepared.', row, p,@@ -409,15 +428,19 @@ export async function prepareManagedSyncMutation(engine: BrainEngine, row: Writeif (schema && p.processingOptions?.noSchemaPack) throw syncPublicationRefusal('profile_incompatible', 'Company source approval requires its pinned schema pack.', row,{ ...p, processingOptions: { ...p.processingOptions!, noSchemaPack: false } },`A company-brain source imports with its pinned schema pack, so ${row.source_id} cannot sync with --no-schema-pack.`);+ enterClaimStep(clock, 'schema_pack', undefined, 'db');const activePack = p.processingOptions?.noSchemaPack ? undefined : schema ? (await checkApprovedSchemaForEngine(engine, { name: schema.name, identity: schema.identity, resolvedManifestHash: schema.resolved_digest },{ remote: false, sourceId: row.source_id })).pack.manifest : (await loadActivePackForEngine(engine, { remote: row.authority.remote, sourceId: row.source_id }).catch(() => null))?.manifest;// A renamed page is prepared where it stands; publication moves it, then re-prepares at the new slug.const renamed = moved && moved.slug !== row.slug ? moved : undefined;+ if (renamed) enterClaimStep(clock, 'rename_source', undefined, 'db');const base = renamed ? await engine.readPageSnapshot(renamed.slug, { ...source, includeDeleted: true }) : snapshot;if (renamed && (base?.page.id !== renamed.pageId || base.revision !== renamed.revision || base.page.deleted_at != null)) {throw syncPublicationRefusal('revision_conflict', 'The renamed page changed after sync admission.', row, p,`Page ${renamed.slug}, which this file was renamed from, changed or was deleted after the sync was admitted.`);}+ // The screen hashes the frozen bytes and, for a newer working tree, reads the file (raw hash).+ enterClaimStep(clock, 'import_screen', undefined, 'fs');const { screen, parsedInput, newerWorkingTree } = await settledSyncScreen(engine, { content: p.content, rawHash: p.rawHash, lineEndingOnly: p.lineEndingOnly === true,slug: row.slug, sourcePath: p.sourcePath, path: p.path, root, snapshot, base, renamed: !!renamed, activePack, companyApproval: !!p.companyApproval });if (screen.status === 'published') return { observedRevision: snapshot?.revision ?? null, noop: true, contentUnchanged: true, validate,@@ -439,6 +462,7 @@ export async function prepareManagedSyncMutation(engine: BrainEngine, row: Write}}let prepared: PreparedContentImport | undefined;+ enterClaimStep(clock, 'import_content', undefined, 'db');// #6188: the import reuses this screen's fence verdict for the same bytes (one fence scan per file at prepare).const importOptions = { ...source, noEmbed: true, remote: row.authority.remote, preserveGateMarkers: true, activePack, coordinated: true, fences: 'coordinated' as const,...(importContent === p.content && screen.status === 'importable' ? { fenceScreen: screen.fences ?? null } : {}),@@ -472,11 +496,13 @@ export async function prepareManagedSyncMutation(engine: BrainEngine, row: Writeconst fenceFixes = ready.result.fences_normalized ?? [];if (overlay && p.companyApproval) throw companyWritebackRefusal(row, p, fenceFixes);// #5409: a read-only mirror keeps its canonical metadata in the database only; its checkout stays the remote's bytes.+ enterClaimStep(clock, 'mirror_check', undefined, 'db');const mirrorReadOnly = overlay && await sourceMirrorReadOnly(engine, row.source_id);const writeback = overlay && !mirrorReadOnly;if (writeback && !p.lineEndingOnly && p.rawHash !== sha256(p.content)) throw syncPublicationRefusal('source_changed', 'Canonical sanitization cannot overwrite newer working-tree bytes.', row, p,`The canonical correction for ${row.slug} would overwrite newer working-tree bytes; preserve the local edit and commit it.`);// A rename projects against the moved page (same id), so its pinned timeline rows carry over.+ enterClaimStep(clock, 'canonical_projections', undefined, 'db');const project = await prepareCanonicalProjections(engine, ready.parsedPage, row.slug, row.source_id, base, p.companyApproval ? 'immutable' : 'file');const preparedImport: PreparedMutation = { observedRevision: snapshot?.revision ?? null,// Tells the #5470 screen the content is unchanged; publication still queues its effects.diff --git a/test/persistence-preparation-kill-accounting.test.ts b/test/persistence-preparation-kill-accounting.test.tsnew file mode 100644index 0000000000..b775f298b5--- /dev/null+++ b/test/persistence-preparation-kill-accounting.test.ts@@ -0,0 +1,62 @@+/**+ * #6278: the kill case on PGLite. Protects: when a process reopens the datastore+ * and `releaseAbandonedClaims` reclaims the dead owner's claims, a request whose+ * claim was stamped `preparing` under the reclaimed token is charged one+ * preparation attempt, while a publishing claim, a stamp from an earlier claim+ * and a switched-off brain are never charged (the same rule as the Postgres+ * expired-claim sweep). Fails when the reclaim charges nothing (a kill loop+ * never reaches the attempt limit) or charges every running row.+ */+import { afterAll, beforeAll, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { admitWrite, claimNextWrite, getWriteRequestById } from '../src/core/persistence/journal.ts';+import { releaseAbandonedClaims } from '../src/core/persistence/effect-journal.ts';+import { claimPhaseStamp, startClaimPhase } from '../src/core/persistence/claim-phase.ts';+import { admission, fixtures, initializeFixtures, selectFixtureHost, type HarnessConfig } from '../scripts/persistence/harness.ts';+import { withEnv } from './helpers/with-env.ts';++const home = mkdtempSync(join(tmpdir(), 'gbrain-kill-accounting-'));+const config: HarnessConfig = { kind: 'pglite', root: home, dataDir: join(home, 'data'), hostId: randomUUID(),+ seed: 6278, schedules: 0, operations: 0, sourceIds: ['kill-accounting', 'kill-accounting-b', 'kill-accounting-c'], principalIds: [randomUUID()] };+const env = { GBRAIN_HOME: home, GBRAIN_PERSISTENCE_FIXTURE_HOME: home };+let engine: PGLiteEngine;++beforeAll(async () => withEnv(env, async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ selectFixtureHost(config.hostId);+ await initializeFixtures(engine, config);+}), 120_000);+afterAll(async () => { await engine.disconnect(); rmSync(home, { recursive: true, force: true }); });++test('the PGLite reclaim charges a preparing claim of the reclaimed token only, and only with the switch on', async () => withEnv(env, async () => {+ const sources = await fixtures(engine, config);+ // Three roots, one claimed request each: claimed (stamped preparing at claim), publishing, and an earlier claim's stamp.+ const rows = await Promise.all(sources.map((source, i) => admitWrite(engine, admission(config, source, `kill/${i}`, `body ${i}`))));+ const claimed = [];+ for (let i = 0; i < 3; i++) claimed.push((await claimNextWrite(engine, config.hostId, 30_000, claimed.map(row => row.worktree_id!)))!);+ expect(claimed.map(row => row.slug).sort()).toEqual(rows.map(row => row.slug).sort());+ const byIndex = (i: number) => claimed.find(row => row.slug === `kill/${i}`)!;+ const publishing = startClaimPhase(); publishing.phase = 'publishing';+ await engine.executeRaw('UPDATE persistence_requests SET claim_phase=$2::text::jsonb WHERE id=$1::uuid', [byIndex(1).id, claimPhaseStamp(publishing, byIndex(1).execution_token)]);+ await engine.executeRaw('UPDATE persistence_requests SET claim_phase=$2::text::jsonb WHERE id=$1::uuid', [byIndex(2).id, claimPhaseStamp(startClaimPhase(), randomUUID())]);+ // The switch off: the dead owner's claims are released and nothing is charged.+ const future = new Date(Date.now() + 60_000);+ expect(await releaseAbandonedClaims(engine, future, false)).toBe(3);+ for (let i = 0; i < 3; i++) expect(await getWriteRequestById(engine, byIndex(i).id)).toMatchObject({ state: 'queued', preparation_attempts: 0 });+ // Claim again (fresh stamps), restore the two control stamps, then reclaim with the switch on.+ const again = [];+ for (let i = 0; i < 3; i++) again.push((await claimNextWrite(engine, config.hostId, 30_000, again.map(row => row.worktree_id!)))!);+ const second = (i: number) => again.find(row => row.slug === `kill/${i}`)!;+ await engine.executeRaw('UPDATE persistence_requests SET claim_phase=$2::text::jsonb WHERE id=$1::uuid', [second(1).id, claimPhaseStamp(publishing, second(1).execution_token)]);+ await engine.executeRaw('UPDATE persistence_requests SET claim_phase=$2::text::jsonb WHERE id=$1::uuid', [second(2).id, claimPhaseStamp(startClaimPhase(), randomUUID())]);+ expect(await releaseAbandonedClaims(engine, future, true)).toBe(3);+ expect((await getWriteRequestById(engine, second(0).id))).toMatchObject({ state: 'queued', preparation_attempts: 1 });+ expect((await getWriteRequestById(engine, second(1).id))).toMatchObject({ state: 'queued', preparation_attempts: 0 });+ expect((await getWriteRequestById(engine, second(2).id))).toMatchObject({ state: 'queued', preparation_attempts: 0 });+}), 30_000);diff --git a/test/persistence-preparation-memo-rule.test.ts b/test/persistence-preparation-memo-rule.test.tsnew file mode 100644index 0000000000..83cddc8f46--- /dev/null+++ b/test/persistence-preparation-memo-rule.test.ts@@ -0,0 +1,43 @@+/**+ * #6278: the memo rule (group-publish.ts). Protects: a claimed group's shared+ * preparation reads (`preparationReads`) stay shared when one member is cut+ * off: the member's cancellation lands at its own `enterClaimStep` boundary+ * and a signalled statement bypasses the memo, so an aborted member can never+ * reject a sibling's read. Fails when a member's signal is threaded into a+ * memoized statement (the memo would skip itself, costing GBRA-45's shared+ * read, or the abort would reject the shared promise).+ */+import { expect, test } from 'bun:test';+import type { BrainEngine } from '../src/core/engine.ts';+import { preparationReads } from '../src/core/persistence/group-publish.ts';+import { enterClaimStep, startClaimPhase } from '../src/core/persistence/claim-phase.ts';++const STABLE = 'SELECT local_path FROM sources WHERE id=$1';++test('an aborted member never rejects a sibling\'s shared read, and the shared read goes out once', async () => {+ const gate = Promise.withResolvers<Array<{ local_path: string }>>();+ const calls: Array<{ sql: string; signal: boolean }> = [];+ const engine = { executeRaw: (sql: string, _params?: unknown[], opts?: { signal?: AbortSignal }) => {+ calls.push({ sql, signal: !!opts?.signal });+ return gate.promise;+ } } as unknown as BrainEngine;+ const reads = preparationReads(engine);+ const a = new AbortController(), b = new AbortController();+ const clockA = startClaimPhase(Date.now(), a.signal), clockB = startClaimPhase(Date.now(), b.signal);+ // Both members start the same read; member A's statement takes no signal (the clock carries it), so the memo answers both.+ const readA = reads.executeRaw(STABLE, ['default']);+ const readB = reads.executeRaw(STABLE, ['default']);+ expect(calls).toEqual([{ sql: STABLE, signal: false }]);+ // A's budget passes: its next boundary throws, B is untouched.+ a.abort({ code: 'preparation_deadline' });+ expect(() => enterClaimStep(clockA, 'configured_root', undefined, 'db')).toThrow();+ expect(() => enterClaimStep(clockB, 'configured_root', undefined, 'db')).not.toThrow();+ gate.resolve([{ local_path: '/brain' }]);+ expect(await readB).toEqual([{ local_path: '/brain' }]);+ expect(await readA).toEqual([{ local_path: '/brain' }]);+ // A statement that does take a signal bypasses the memo and reaches the engine on its own.+ const own = reads.executeRaw(STABLE, ['default'], { signal: b.signal });+ expect(calls).toHaveLength(2);+ expect(calls[1]).toEqual({ sql: STABLE, signal: true });+ await own;+});