Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
perf(import): one closing page write per coordinated import, indexed claim root probe, content-free import checkpoints (GBRA-69)
time-attackf0b015b91e5a
diff --git a/src/core/engine-sql/chunks.ts b/src/core/engine-sql/chunks.tsindex 1e4406476c..01d96262e0 100644--- a/src/core/engine-sql/chunks.ts+++ b/src/core/engine-sql/chunks.ts@@ -65,7 +65,7 @@ export async function upsertChunksOnce(guards: ChunkPageGuards,slug: string,chunks: ChunkInput[],- opts?: { sourceId?: string; embeddingColumn?: ResolvedColumn; expectedRevision?: string; sealChunkerVersion?: number; pageId?: number },+ opts?: { sourceId?: string; embeddingColumn?: ResolvedColumn; expectedRevision?: string; sealChunkerVersion?: number; pageId?: number; deferSeal?: true },): Promise<void> {const memo = guards.memo ?? (<T>(_key: string, read: () => Promise<T>) => read());// Normalize the same way putPage does — pages.slug is stored lowercased,@@ -317,7 +317,7 @@ export async function upsertChunksOnce(WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN now()ELSE content_chunks.embedding_pending_sinceEND`);- if (sealed === undefined) { await exec.query(text, params); return; }+ if (sealed === undefined || opts?.deferSeal) { await exec.query(text, params); return; }const [{ rows }] = await pipelined({ kind: exec.dialect }, [sealPage, () => exec.query(text, params)]) as [{ rows: Array<{ id: number }> }];if (rows.length === 0) throw new Error(`Page not found: ${slug} (source=${sourceId})`);if (Number(rows[0]!.id) !== Number(sealed)) throw new Error(`Page ${slug} (source=${sourceId}) is not the page this transaction wrote`);diff --git a/src/core/engine.ts b/src/core/engine.tsindex 96a9b21d66..55292ab628 100644--- a/src/core/engine.ts+++ b/src/core/engine.ts@@ -1178,8 +1178,10 @@ export interface BrainEngine {* sealed at that chunker version after the insert. With `pageId` (the* caller's own write of that page in this transaction) the seal and the* insert are sent together and the seal's page is checked against it.+ * With `deferSeal` as well, the caller stamps the chunker version and checks+ * the page itself later in the same transaction (`sealImportedPage`).*/- upsertChunks(slug: string, chunks: ChunkInput[], opts?: { sourceId?: string; embeddingColumn?: ResolvedColumn; expectedRevision?: string; sealChunkerVersion?: number; pageId?: number } & BatchOpts): Promise<void>;+ upsertChunks(slug: string, chunks: ChunkInput[], opts?: { sourceId?: string; embeddingColumn?: ResolvedColumn; expectedRevision?: string; sealChunkerVersion?: number; pageId?: number; deferSeal?: true } & BatchOpts): Promise<void>;/*** Read every chunk for a page. Scope precedence mirrors getPage (#2555):* a federated grant (`sourceIds[]`) wins over scalar `sourceId`; withdiff --git a/src/core/import-file.ts b/src/core/import-file.tsindex 0659fb51f1..d5f6a59b0c 100644--- a/src/core/import-file.ts+++ b/src/core/import-file.ts@@ -758,6 +758,8 @@ export async function importFromContent(() => writePageAliases(tx, slug, sourceId ?? 'default', parsed, opts.activePack, mentionPolicy),]);const pageId = written && written.deleted_at == null ? written.id : undefined;+ // A coordinated caller stamps the chunker version with its text seal, after its read-back (sealImportedPage).+ const deferSeal = opts.coordinated === true && pageId !== undefined;await pipelined(tx, [async () => {// Tag reconciliation (A14): frontmatter tags carry tag_source='frontmatter'.@@ -776,7 +778,7 @@ export async function importFromContent(const embeddingColumn = await stampEmbeddingInputs(tx, fresh, null,{ title: parsed.title, tier: effectiveCRMode === 'title' ? 'title' : 'none', corpusGeneration });await tx.upsertChunks(slug, kept.size ? fresh.filter((_, i) => !kept.has(i)) : fresh, { ...txOpts, ...(embeddingColumn ? { embeddingColumn } : {}), sealChunkerVersion: MARKDOWN_CHUNKER_VERSION,- ...(pageId !== undefined ? { pageId: Number(pageId) } : {}) });+ ...(pageId !== undefined ? { pageId: Number(pageId) } : {}), ...(deferSeal ? { deferSeal: true as const } : {}) });// v0.41.31: stamp embedding provenance when this import actually// embedded (not --no-embed), so a later model/dims swap is detectable// as stale via embed --stale. The deferred/backfill + per-slug embed@@ -790,7 +792,7 @@ export async function importFromContent(} else {// Seal only the completed, full-body sanitized replacement (the upsert above seals its own); a// body-only write or a failed transaction must never certify old stored fragments.- await tx.executeRaw('UPDATE pages SET chunker_version = $1 WHERE source_id = $2 AND slug = $3', [MARKDOWN_CHUNKER_VERSION, txOpts.sourceId, slug]);+ if (!deferSeal) await tx.executeRaw('UPDATE pages SET chunker_version = $1 WHERE source_id = $2 AND slug = $3', [MARKDOWN_CHUNKER_VERSION, txOpts.sourceId, slug]);}},]);@@ -840,7 +842,8 @@ export async function importFromContent(// guard. Deferred provider results cannot replace newer text or chunks.persistedProjection = await readProjectionSnapshot(tx, slug, txOpts.sourceId);}- return { pageId: written && written.deleted_at == null ? written.id : undefined, sealed: !opts.coordinated && !opts.beforeCommit };+ return { pageId: written && written.deleted_at == null ? written.id : undefined, sealed: !opts.coordinated && !opts.beforeCommit,+ ...(deferSeal ? { chunkerSeal: MARKDOWN_CHUNKER_VERSION } : {}) };};if (opts.prepare) return opts.prepare({slug, parsedPage, observedRevision: (existing as (typeof existing & { knowledge_revision?: string }) | null)?.knowledge_revision ?? null,diff --git a/src/core/page-state/projections.ts b/src/core/page-state/projections.tsindex 09d82109c7..2434b84852 100644--- a/src/core/page-state/projections.ts+++ b/src/core/page-state/projections.ts@@ -32,6 +32,24 @@ export async function sealPageTextProjection(engine: BrainEngine, slug: string,[sourceId, slug, sanitizeRemoteBody(current.page.timeline), current.revision]);}+/**+ * A coordinated import's one closing page write: the chunker version its apply+ * deferred (`PreparedImportApplied.chunkerSeal`) and, when `live` is the page at+ * its current revision, the text seal `sealPageTextProjection` would write. The+ * chunker version is stamped whatever the revision, as the deferred seal was.+ */+export async function sealImportedPage(engine: BrainEngine, slug: string, sourceId: string, live: PageSnapshot | null,+ chunkerSeal: number, pageId?: number): Promise<void> {+ const rows = await engine.executeRaw<{ id: number }>(`UPDATE pages SET chunker_version=$5,+ text_projection_revision=CASE WHEN knowledge_revision=$4::uuid THEN knowledge_revision ELSE text_projection_revision END,+ search_vector=CASE WHEN knowledge_revision=$4::uuid THEN setweight(to_tsvector('${getFtsLanguage()}',COALESCE(title,'')),'A') ||+ setweight(to_tsvector('${getFtsLanguage()}',$3::text),'C') ELSE search_vector END+ WHERE source_id=$1 AND slug=$2 RETURNING id`,+ [sourceId, slug, live ? sanitizeRemoteBody(live.page.timeline) : '', live?.revision ?? null, chunkerSeal]);+ if (rows.length === 0) throw new Error(`Page not found: ${slug} (source=${sourceId})`);+ if (pageId !== undefined && Number(rows[0]!.id) !== Number(pageId)) throw new Error(`Page ${slug} (source=${sourceId}) is not the page this transaction wrote`);+}+export interface ProjectionSnapshot {snapshot: PageSnapshot;chunks: Chunk[];diff --git a/src/core/persistence/import-mutations.ts b/src/core/persistence/import-mutations.tsindex dd0c6b322f..f89ab6effd 100644--- a/src/core/persistence/import-mutations.ts+++ b/src/core/persistence/import-mutations.ts@@ -62,6 +62,13 @@ const IMPORT_OP = 'managed-file-import';/** How long an import waits for one file's publication, as a single import always has. */const IMPORT_WAIT_MS = 30_000;type PendingImport = ManagedImportIntent & { request_id: string; source_id: string };+/**+ * GBRA-69: the durable pre-admission checkpoint holds the admission's expectations and request id,+ * not the file's content: its key binds the input hash, so a retry restores the content from the+ * bytes it just read (and refuses when they no longer hash to the stored input). Checkpoints older+ * binaries wrote still carry the content; their row is matched as stored.+ */+type StoredImport = Omit<PendingImport, 'content'> & { content?: string };export async function importManagedFile(engine: BrainEngine, filePath: string, sourcePath: string,opts: { sourceId?: string; noEmbed?: boolean; activePack?: ImportPack; signal?: AbortSignal; slugRoot?: string } = {}): Promise<ImportResult> {@@ -138,9 +145,17 @@ async function importPlanned(ctx: OperationContext, binding: WorktreeBinding,principal = await requestPrincipalForContext(ctx);} catch (error) { for (const entry of planned) fail(entry.i, error); return; }const members = planned.map(entry => ({ ...entry, key: digest({ principal, incarnation: binding.source_incarnation, inputPath: entry.inputPath, sourcePath: entry.sourcePath,- path: entry.path, inputHash: entry.inputHash, noEmbed: !!opts.noEmbed, activePack: opts.activePack ?? null }), params: undefined as PendingImport | undefined }));- const readPending = async (keys: string[]) => new Map((await engine.executeRaw<{ fingerprint: string; completed_keys: [PendingImport] }>(+ path: entry.path, inputHash: entry.inputHash, noEmbed: !!opts.noEmbed, activePack: opts.activePack ?? null }),+ params: undefined as PendingImport | undefined, stored: undefined as StoredImport | undefined }));+ const readPending = async (keys: string[]) => new Map((await engine.executeRaw<{ fingerprint: string; completed_keys: [StoredImport] }>('SELECT fingerprint,completed_keys FROM op_checkpoints WHERE op=$1 AND fingerprint=ANY($2::text[])', [IMPORT_OP, keys])).map(row => [row.fingerprint, row.completed_keys[0]]));+ const resume = (member: (typeof members)[number], stored: StoredImport) => {+ // The key binds the input hash and slug, so a mismatch is a checkpoint this binary cannot pair with the bytes.+ if (stored.inputHash !== member.inputHash || stored.slug !== member.slug) throw opError('internal_error', 'A pending import checkpoint does not match the file it is keyed by.',+ `The checkpointed import of ${member.sourcePath} (request ${stored.request_id}) in source ${sourceId} records a different input than the bytes just read under the same key, so nothing was resubmitted. Report it with gbrain doctor --json.`);+ member.stored = stored;+ member.params = { ...stored, content: member.content } as PendingImport;+ };const open = new Set(members);const settle = (member: (typeof members)[number], value: ImportResult) => { open.delete(member); done(member.i, value); };const refuse = (member: (typeof members)[number], reason: unknown) => { open.delete(member); fail(member.i, reason); };@@ -152,9 +167,9 @@ async function importPlanned(ctx: OperationContext, binding: WorktreeBinding,const pending = await readPending(members.map(member => member.key));const fresh: typeof members = [];await withScreeningPaths(async () => { for (const member of members) {- member.params = pending.get(member.key);- if (member.params) continue;try {+ const stored = pending.get(member.key);+ if (stored) { resume(member, stored); continue; }const snapshot = await engine.readPageSnapshot(member.slug, { sourceId, includeDeleted: true });// The input is the canonical file itself (the common case): its hash was taken from the bytes just read.const targetHash = member.target === member.inputPath ? member.inputHash : existsSync(member.target) ? sha256(readImportBytes(member.target)) : null;@@ -171,9 +186,9 @@ async function importPlanned(ctx: OperationContext, binding: WorktreeBinding,if (fresh.length) {await engine.executeRaw(`INSERT INTO op_checkpoints(op,fingerprint,completed_keys)SELECT $1,k,c::jsonb FROM unnest($2::text[],$3::text[]) AS u(k,c) ON CONFLICT DO NOTHING`,- [IMPORT_OP, fresh.map(member => member.key), fresh.map(member => JSON.stringify([member.params]))]);+ [IMPORT_OP, fresh.map(member => member.key), fresh.map(member => { const { content: _content, ...stored } = member.params!; return JSON.stringify([stored]); })]);const stored = await readPending(fresh.map(member => member.key));- for (const member of fresh) member.params = stored.get(member.key)!;+ for (const member of fresh) { try { resume(member, stored.get(member.key)!); } catch (error) { refuse(member, error); } }}} catch (error) { for (const member of [...open]) refuse(member, error); return; }const submitted = members.filter(member => open.has(member));@@ -198,7 +213,7 @@ async function importPlanned(ctx: OperationContext, binding: WorktreeBinding,try {await engine.executeRaw(`DELETE FROM op_checkpoints o USING unnest($2::text[],$3::text[]) AS d(k,c)WHERE o.op=$1 AND o.fingerprint=d.k AND o.completed_keys=d.c::jsonb`,- [IMPORT_OP, cleared.map(member => member.key), cleared.map(member => JSON.stringify([member.params]))]);+ [IMPORT_OP, cleared.map(member => member.key), cleared.map(member => JSON.stringify([member.stored]))]);} catch (error) { for (const member of cleared) fail(member.i, error); }}diff --git a/src/core/persistence/import-prepare.ts b/src/core/persistence/import-prepare.tsindex c782a2912e..97f31fec75 100644--- a/src/core/persistence/import-prepare.ts+++ b/src/core/persistence/import-prepare.ts@@ -15,7 +15,7 @@ import { fenceWhere } from '../fence-repair/refusal.ts';import { pageFencesNormalized } from '../fence-repair/report.ts';import { isWriteTargetContained } from '../path-confine.ts';import { assertPageRevision } from '../page-state/types.ts';-import { sealPageTextProjection } from '../page-state/projections.ts';+import { sealImportedPage, sealPageTextProjection } from '../page-state/projections.ts';import { assertKnowledgePublicationAllowed } from '../shared-skills/knowledge-guard.ts';import { getWorktreeBinding } from './ownership.ts';import { localHostId } from './identity.ts';@@ -215,7 +215,7 @@ export async function prepareManagedImportMutation(engine: BrainEngine, row: Writrust: await ownerImportTrust(engine, row, ready.parsedPage?.frontmatter, p.sourcePath), deferEmbedding: image || p.noEmbed, validate: async tx => { await checkPaths(tx); await ready.validate(tx); },file: { root, path, content: rendered, expectedBeforeHash: p.targetHash },apply: async tx => {- await ready.apply(tx);+ const applied = await ready.apply(tx);await tx.executeRaw('UPDATE pages SET source_path=$3 WHERE source_id=$1 AND slug=$2 AND source_path IS DISTINCT FROM $3', [row.source_id, row.slug, p.sourcePath]);if (project) {// The coordinator proved the base revision under its page guard (importFromContent `coordinated`); this is the@@ -226,7 +226,8 @@ export async function prepareManagedImportMutation(engine: BrainEngine, row: Wriif (!ready.noop) {await verifyPageReadable(tx, row.slug, ready.contentHash!, row.source_id, 'importFromContent', live?.page ?? null);await project(tx, final?.page.id);- if (live) await sealPageTextProjection(tx, row.slug, row.source_id, live);+ if (applied?.chunkerSeal !== undefined) await sealImportedPage(tx, row.slug, row.source_id, live, applied.chunkerSeal, applied.pageId);+ else if (live) await sealPageTextProjection(tx, row.slug, row.source_id, live);}mutation.postimage = final;} else if (!ready.noop && !image) await sealPageTextProjection(tx, row.slug, row.source_id);diff --git a/src/core/persistence/journal.ts b/src/core/persistence/journal.tsindex c8d7e290c4..ec0ca3066f 100644--- a/src/core/persistence/journal.ts+++ b/src/core/persistence/journal.ts@@ -466,6 +466,13 @@ async function assertWorktreeNotRefreshing(tx: BrainEngine, input: WriteAdmissiothrow error;}+/**+ * An unfinished row ahead of `r` on its root that `r` may not pass. The root (a worktree, or a+ * database-only incarnation) is matched by the caller with columns the pending indexes cover,+ * so each probe is an index range scan rather than a walk of every pending row.+ */+const EARLIER_HEAD = (earlier: string, r: string, priority: string, laneRoots: string) => `${earlier}.sequence<${r}.sequence+ AND ${earlier}.state IN ('queued','running','recovering') AND NOT ${PASSES_QUEUED_SYNC(earlier, r, priority, laneRoots)}`;/*** The rows `claimNextWrite` may claim, over `persistence_requests r LEFT JOIN* persistence_worktrees w`, with $1 = host id and $2 = excluded root keys. An@@ -504,14 +511,14 @@ export const claimableWriteSql = (priority: string, laneRoots = "'{}'::text[]")AND (NOT (mirror.data ? 'targets') OR mirror.data->'targets' @> jsonb_build_array(jsonb_build_object('slug',r.slug))))AND NOT EXISTS (SELECT 1 FROM persistence_requests blocked WHERE blocked.worktree_id=r.worktree_id AND blocked.recovery IS NOT NULL)AND NOT EXISTS (SELECT 1 FROM persistence_requests earlier- WHERE COALESCE(earlier.worktree_id::text,'db:'||earlier.source_incarnation::text)- =COALESCE(r.worktree_id::text,'db:'||r.source_incarnation::text)- AND earlier.sequence<r.sequence AND earlier.state IN ('queued','running','recovering')- AND NOT ${PASSES_QUEUED_SYNC('earlier', 'r', priority, laneRoots)})+ WHERE r.worktree_id IS NOT NULL AND earlier.worktree_id=r.worktree_id AND ${EARLIER_HEAD('earlier', 'r', priority, laneRoots)})+ AND NOT EXISTS (SELECT 1 FROM persistence_requests earlier+ WHERE r.worktree_id IS NULL AND earlier.worktree_id IS NULL AND earlier.source_incarnation=r.source_incarnation+ AND ${EARLIER_HEAD('earlier', 'r', priority, laneRoots)})AND NOT ((${priority}) AND ${SYNC_KIND('r')} AND EXISTS (SELECT 1 FROM persistence_requests aheadWHERE ahead.worktree_id=r.worktree_id AND ahead.sequence>r.sequence AND ahead.state IN ('running','recovering') AND NOT ${SYNC_KIND('ahead')}))`;/** With the switch on, a claimable foreground request is claimed before the sync rows it passes. */-const CLAIM_ORDER = (priority: string) => `(${priority} AND NOT ${SYNC_KIND('r')}) DESC, r.sequence`;+export const CLAIM_ORDER = (priority: string) => `(${priority} AND NOT ${SYNC_KIND('r')}) DESC, r.sequence`;/*** The `foreground_priority` switch as SQL, so a claim reads it in its own statement: the environment* override (a process constant) or, without one, the brain config row (on unless `0`/`false`).diff --git a/src/core/persistence/page-prepare.ts b/src/core/persistence/page-prepare.tsindex 53bf7a892f..b28df78fb2 100644--- a/src/core/persistence/page-prepare.ts+++ b/src/core/persistence/page-prepare.ts@@ -32,7 +32,7 @@ import type { PreparedContentImport } from './prepared-import.ts';import type { PreparedMutation } from './coordinator.ts';import type { SqlEngine, WriteRequest } from './model.ts';import { isUnboundSourcePage } from './unbound-source.ts';-import { sealPageTextProjection } from '../page-state/projections.ts';+import { sealImportedPage, sealPageTextProjection } from '../page-state/projections.ts';import { pipelined } from '../page-state/transactions.ts';import { overlayCanonicalBodies } from '../page-state/snapshot.ts';import { materializeTimeline, prepareCanonicalProjections, type TimelineRowsRemoved } from './canonical-projections.ts';@@ -532,7 +532,8 @@ export async function preparePageMutation(unbounded: BrainEngine, row: WriteRequconst final = await tx.readPageSnapshot(row.slug, { ...source, includeDeleted: true });const live = final && final.page.deleted_at == null ? final : null;await verifyPageReadable(tx, row.slug, ready.contentHash!, row.source_id, 'importFromContent', live?.page ?? null);- if (live) await sealPageTextProjection(tx, row.slug, row.source_id, live);+ if (applied?.chunkerSeal !== undefined) await sealImportedPage(tx, row.slug, row.source_id, live, applied.chunkerSeal, applied.pageId);+ else if (live) await sealPageTextProjection(tx, row.slug, row.source_id, live);if (core) await core.record(tx, final?.revision ?? null);publication.postimage = final;} else {diff --git a/src/core/persistence/prepared-import.ts b/src/core/persistence/prepared-import.tsindex 3d4ec6e84d..473808ef5b 100644--- a/src/core/persistence/prepared-import.ts+++ b/src/core/persistence/prepared-import.ts@@ -6,9 +6,10 @@ import type { ImportResult, ParsedPage } from '../import-file.ts';* #6007: what an apply reports to its caller. `pageId` is the page it* wrote, when the write left it live; `sealed` means sealing its text* projection was its last step that can change the page's revision, title or- * timeline.+ * timeline. `chunkerSeal`: a coordinated apply left the page's chunker version+ * to the caller, which stamps it with its text seal (`sealImportedPage`).*/-export interface PreparedImportApplied { pageId?: number; sealed: boolean }+export interface PreparedImportApplied { pageId?: number; sealed: boolean; chunkerSeal?: number }/** Parsing/provider work is complete. apply must run under the coordinator's transaction. */export interface PreparedContentImport {diff --git a/src/core/persistence/sync-prepare.ts b/src/core/persistence/sync-prepare.tsindex e1fb882f05..29a80ebd30 100644--- a/src/core/persistence/sync-prepare.ts+++ b/src/core/persistence/sync-prepare.ts@@ -17,7 +17,7 @@ import { resolveSlugForPath, slugifyPath, isCodeFilePath } from '../sync.ts';import { SOURCE_CONFIG_OBJECT_SQL } from '../source-config-sql.ts';import { sameCanonicalImport } from '../page-state/import-guard.ts';import { assertPageRevision } from '../page-state/types.ts';-import { sealPageTextProjection } from '../page-state/projections.ts';+import { sealImportedPage, sealPageTextProjection } from '../page-state/projections.ts';import { pipelined, transactionMemo } from '../page-state/transactions.ts';import { prepareCanonicalProjections } from './canonical-projections.ts';import { digest, sha256 } from './digest.ts';@@ -566,7 +566,7 @@ export async function prepareManagedSyncMutation(unbounded: BrainEngine, row: Wrapplied = movedImport;}// A moved page is versioned from its own (rename source) read.- await applied.apply(tx, renamed ? undefined : preimage);+ const installed = await applied.apply(tx, renamed ? undefined : preimage);// Hash no-ops still repair a missing physical origin under the same guard (a page write records it itself).if (applied.noop) await tx.executeRaw('UPDATE pages SET source_path=$3 WHERE source_id=$1 AND slug=$2 AND source_path IS DISTINCT FROM $3', [row.source_id, row.slug, p.sourcePath]);// #5984: the one read of the page after its last page write (the projections@@ -578,7 +578,11 @@ export async function prepareManagedSyncMutation(unbounded: BrainEngine, row: Wr// The projections, the text seal, the hold and the provenance touch separate rows; their pipelines run together.await pipelined(tx, [async () => { if (!applied.noop || p.companyApproval) await project(tx, final?.page.id); },- async () => { if (!applied.noop && live) await sealPageTextProjection(tx, row.slug, row.source_id, live); },+ async () => {+ if (applied.noop) return;+ if (installed?.chunkerSeal !== undefined) await sealImportedPage(tx, row.slug, row.source_id, live, installed.chunkerSeal, installed.pageId);+ else if (live) await sealPageTextProjection(tx, row.slug, row.source_id, live);+ },() => releaseHold(tx),async () => { if (final) await recordSyncImportProvenance(tx, { source_id: row.source_id, incarnation: row.source_incarnation, page_id: Number(final.page.id), origin: p.sourcePath!,raw_sha256: sha256(p.content!), ...(p.blobOid ? { blob_oid: p.blobOid } : {}), gbrain_version: VERSION, ...(recovery?.length ? { recovery } : {}) }); },diff --git a/src/core/pglite-engine.ts b/src/core/pglite-engine.tsindex c66351c7af..1ea17107c7 100644--- a/src/core/pglite-engine.ts+++ b/src/core/pglite-engine.ts@@ -1760,13 +1760,13 @@ export class PGLiteEngine implements BrainEngine {// Chunks SQL lives once in ./engine-sql/chunks.ts (refactor wave 1, W1-extended).// The engine keeps the retry + transaction wrapper, the RLS scope// transaction and the source-scope / active-column resolution.- async upsertChunks(slug: string, chunks: ChunkInput[], opts?: { sourceId?: string; embeddingColumn?: ResolvedColumn; expectedRevision?: string; sealChunkerVersion?: number; pageId?: number } & BatchOpts): Promise<void> {+ async upsertChunks(slug: string, chunks: ChunkInput[], opts?: { sourceId?: string; embeddingColumn?: ResolvedColumn; expectedRevision?: string; sealChunkerVersion?: number; pageId?: number; deferSeal?: true } & BatchOpts): Promise<void> {if (this._chunkWritesInTransaction) return this._upsertChunksOnce(slug, chunks, opts);return this.batchRetry(opts?.auditSite ?? 'upsertChunks', opts?.signal,() => this.transaction(tx => (tx as PGLiteEngine)._upsertChunksOnce(slug, chunks, opts)), chunks.length);}- private async _upsertChunksOnce(slug: string, chunks: ChunkInput[], opts?: { sourceId?: string; embeddingColumn?: ResolvedColumn; expectedRevision?: string; sealChunkerVersion?: number; pageId?: number }): Promise<void> {+ private async _upsertChunksOnce(slug: string, chunks: ChunkInput[], opts?: { sourceId?: string; embeddingColumn?: ResolvedColumn; expectedRevision?: string; sealChunkerVersion?: number; pageId?: number; deferSeal?: true }): Promise<void> {return chunksImpl.upsertChunksOnce(this.engineSql, {lockPageKeys: (keys) => this.lockPageKeys(keys),readPageSnapshot: (pageSlug, snapshotOpts) => this.readPageSnapshot(pageSlug, snapshotOpts),diff --git a/src/core/postgres-engine.ts b/src/core/postgres-engine.tsindex 58d8e40a22..d42e531409 100644--- a/src/core/postgres-engine.ts+++ b/src/core/postgres-engine.ts@@ -1485,13 +1485,13 @@ export class PostgresEngine implements BrainEngine {// Chunks SQL lives once in ./engine-sql/chunks.ts (refactor wave 1, W1-extended).// The engine keeps the retry + transaction wrapper, the RLS scope// transaction and the source-scope / active-column resolution.- async upsertChunks(slug: string, chunks: ChunkInput[], opts?: { sourceId?: string; embeddingColumn?: ResolvedColumn; expectedRevision?: string; sealChunkerVersion?: number; pageId?: number } & BatchOpts): Promise<void> {+ async upsertChunks(slug: string, chunks: ChunkInput[], opts?: { sourceId?: string; embeddingColumn?: ResolvedColumn; expectedRevision?: string; sealChunkerVersion?: number; pageId?: number; deferSeal?: true } & BatchOpts): Promise<void> {if (this._chunkWritesInTransaction) return this._upsertChunksOnce(slug, chunks, opts);return this.batchRetry(opts?.auditSite ?? 'upsertChunks', opts?.signal,() => this.transaction(tx => (tx as PostgresEngine)._upsertChunksOnce(slug, chunks, opts)), chunks.length);}- private async _upsertChunksOnce(slug: string, chunks: ChunkInput[], opts?: { sourceId?: string; embeddingColumn?: ResolvedColumn; expectedRevision?: string; sealChunkerVersion?: number; pageId?: number }): Promise<void> {+ private async _upsertChunksOnce(slug: string, chunks: ChunkInput[], opts?: { sourceId?: string; embeddingColumn?: ResolvedColumn; expectedRevision?: string; sealChunkerVersion?: number; pageId?: number; deferSeal?: true }): Promise<void> {return chunksImpl.upsertChunksOnce(this.engineSql, {lockPageKeys: (keys) => this.lockPageKeys(keys),readPageSnapshot: (pageSlug, snapshotOpts) => this.readPageSnapshot(pageSlug, snapshotOpts),diff --git a/test/claim-earlier-equivalence.test.ts b/test/claim-earlier-equivalence.test.tsnew file mode 100644index 0000000000..f7dd22d426--- /dev/null+++ b/test/claim-earlier-equivalence.test.ts@@ -0,0 +1,18 @@+/**+ * GBRA-69: the write claim's root probe (journal.ts `claimableWriteSql`) claims+ * the same rows in the same order as the former COALESCE-keyed predicate.+ * Postgres arm, with the index-scan probe: test/e2e/claim-earlier-equivalence.test.ts.+ */+import { expect, test } from 'bun:test';+import { compareClaimOrders } from './helpers/claim-earlier-fixture.ts';+import { isolatedSharedSkillsEngine } from './helpers/shared-skills-engine.ts';++test('PGLite: the indexed root probe claims what the COALESCE key claimed, in the same order', async () => {+ const { engine, close } = await isolatedSharedSkillsEngine();+ try {+ const cases = await compareClaimOrders(engine);+ expect(cases.filter(c => c.former.length > 0).length).toBeGreaterThan(cases.length / 2);+ expect(cases.filter(c => c.former.length > 1).length).toBeGreaterThan(cases.length / 8);+ for (const c of cases) expect({ seed: c.seed, priority: c.priority, lanes: c.lanes, order: c.current }).toEqual({ seed: c.seed, priority: c.priority, lanes: c.lanes, order: c.former });+ } finally { await close(); }+}, 120_000);diff --git a/test/e2e/claim-earlier-equivalence.test.ts b/test/e2e/claim-earlier-equivalence.test.tsnew file mode 100644index 0000000000..9f73abe30c--- /dev/null+++ b/test/e2e/claim-earlier-equivalence.test.ts@@ -0,0 +1,32 @@+/**+ * Postgres arm of test/claim-earlier-equivalence.test.ts (GBRA-69): the claim's+ * root probe claims what the former COALESCE key claimed, and with queued rows+ * on 8 worktrees it is an index range scan of its own root (the former key+ * walked every root's pending rows once per queued candidate).+ */+import { describe, expect, test } from 'bun:test';+import { compareClaimOrders, explainEarlierProbe } from '../helpers/claim-earlier-fixture.ts';+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';++const url = process.env.DATABASE_URL;+describe.skipIf(!url)('Postgres write claim root probe', () => {+ test('claims the same rows in the same order as the COALESCE key', async () => {+ const { engine, close } = await isolatedPersistencePostgres(url!);+ try {+ const cases = await compareClaimOrders(engine);+ expect(cases.filter(c => c.former.length > 1).length).toBeGreaterThan(cases.length / 8);+ for (const c of cases) expect({ seed: c.seed, priority: c.priority, lanes: c.lanes, order: c.current }).toEqual({ seed: c.seed, priority: c.priority, lanes: c.lanes, order: c.former });+ } finally { await close(); }+ }, 180_000);++ test('the probe is an index scan of the pending rows, and reads fewer buffers than the COALESCE key', async () => {+ const { engine, close } = await isolatedPersistencePostgres(url!);+ try {+ const { current, former } = await explainEarlierProbe(engine);+ expect(current.earlier.length).toBeGreaterThan(0);+ for (const scan of current.earlier) expect(scan.type).toMatch(/Index|Bitmap/);+ expect(current.earlier.some(scan => /worktree_id/.test(String(scan.index)))).toBe(true);+ expect(current.buffers).toBeLessThan(former.buffers * 0.85);+ } finally { await close(); }+ }, 180_000);+});diff --git a/test/e2e/managed-import-crash.test.ts b/test/e2e/managed-import-crash.test.tsnew file mode 100644index 0000000000..a966a58638--- /dev/null+++ b/test/e2e/managed-import-crash.test.ts@@ -0,0 +1,96 @@+/**+ * GBRA-69 forced probes: a managed import SIGKILLed after admission, or at its+ * one closing page write inside publication, is recovered from the durable+ * request intent alone. The pre-admission checkpoint no longer carries the+ * content, so the retry resumes the same request id and the content it+ * publishes is the content the request stored; the page ends sealed (chunker+ * version and text projection) as an uninterrupted import leaves it.+ * PGLite always runs; Postgres runs when DATABASE_URL is set.+ */+import { afterAll, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';+import type { BrainEngine } from '../../src/core/engine.ts';+import { MARKDOWN_CHUNKER_VERSION } from '../../src/core/chunkers/recursive.ts';+import { importManagedFile } from '../../src/core/persistence/import-mutations.ts';+import { managedImportContent } from '../../src/core/persistence/import-prepare.ts';+import { claimWorktree } from '../../src/core/persistence/ownership.ts';+import { registerLocalWriter } from '../../src/core/persistence/identity.ts';+import { disposePersistenceConsumer } from '../../src/core/persistence/service.ts';+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';+import { editRequest } from '../helpers/persistence-request-fixture.ts';+import { withEnv } from '../helpers/with-env.ts';++const home = mkdtempSync(join(tmpdir(), 'gbrain-import-crash-'));+const env = { GBRAIN_HOME: home, OPENAI_API_KEY: undefined, VOYAGE_API_KEY: undefined, ANTHROPIC_API_KEY: undefined };+afterAll(() => rmSync(home, { recursive: true, force: true }));++const kinds = ['pglite', ...(process.env.DATABASE_URL ? ['postgres'] as const : [])] as const;++async function open(kind: 'pglite' | 'postgres', dataDir: string) {+ if (kind === 'pglite') {+ const engine = new PGLiteEngine();+ await engine.connect({ database_path: dataDir });+ return { engine: engine as BrainEngine, target: dataDir, close: () => engine.disconnect() };+ }+ const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!);+ const [{ name }] = await pg.engine.executeRaw<{ name: string }>('SELECT current_database() AS name');+ const url = new URL(process.env.DATABASE_URL!); url.pathname = `/${name}`;+ return { engine: pg.engine as BrainEngine, target: url.toString(), close: pg.close };+}++for (const kind of kinds) for (const boundary of ['admitted', 'closing_write'] as const) {+ test(`${kind}: an import killed at ${boundary} publishes its stored request on retry`, () => withEnv(env, async () => {+ const dataDir = join(home, `${kind}-${boundary}.pglite`);+ let brain = await open(kind, dataDir);+ if (kind === 'pglite') await brain.engine.initSchema();+ const sourceId = `crash-${randomUUID().slice(0, 8)}`;+ const root = join(home, sourceId), input = join(home, `${sourceId}-input`);+ mkdirSync(root); mkdirSync(input);+ await brain.engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ await brain.engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', [sourceId, root]);+ await registerLocalWriter(brain.engine, 'cli');+ await claimWorktree(brain.engine, sourceId, root);+ await brain.engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ const file = join(input, 'crash.md');+ writeFileSync(file, '---\ntitle: Crash\ntags: [example]\n---\n# Crash\n\nPublished from the stored request after the writer was killed.\n');+ const expected = managedImportContent('crash.md', readFileSync(file)).content;+ if (kind === 'pglite') { await disposePersistenceConsumer(brain.engine); await brain.close(); }++ const child = Bun.spawn([process.execPath, '--no-env-file', join(import.meta.dir, '../fixtures/managed-import-crash-worker.ts'),+ kind, brain.target, file, 'crash.md', sourceId, boundary], { env: { ...process.env, GBRAIN_HOME: home }, stdout: 'pipe', stderr: 'inherit' });+ const [stdout, code] = await Promise.all([new Response(child.stdout).text(), child.exited]);+ expect(stdout).toContain(`"boundary":"${boundary}"`);+ expect(child.signalCode ?? code).toBe('SIGKILL');++ if (kind === 'pglite') { brain = await open(kind, dataDir); }+ const engine = brain.engine;+ try {+ const [checkpoint] = await engine.executeRaw<{ params: Record<string, unknown> }>(+ "SELECT completed_keys->0 AS params FROM op_checkpoints WHERE op='managed-file-import' AND completed_keys->0->>'source_id'=$1", [sourceId]);+ expect(checkpoint!.params).not.toHaveProperty('content');+ const requestId = String(checkpoint!.params.request_id);+ const [killed] = await engine.executeRaw<{ id: string; state: string; content: string }>(+ "SELECT id::text, state, intent->>'content' AS content FROM persistence_requests WHERE source_id=$1 AND request_id=$2::uuid", [sourceId, requestId]);+ expect(killed).toMatchObject({ state: boundary === 'admitted' ? 'queued' : 'running', content: expected });+ expect(await engine.getPage('crash', { sourceId })).toBeNull();+ // The dead writer's claim lease is spent rather than waited out.+ if (boundary === 'closing_write') await editRequest(engine, killed!.id, "claim_expires_at=now()-interval '1 minute'");++ expect(await importManagedFile(engine, file, 'crash.md', { sourceId, noEmbed: true })).toMatchObject({ status: 'imported' });+ const requests = await engine.executeRaw<{ request_id: string; state: string; content: string }>(+ "SELECT request_id::text, state, intent->>'content' AS content FROM persistence_requests WHERE source_id=$1 AND operation='put_page'", [sourceId]);+ expect(requests).toEqual([{ request_id: requestId, state: 'committed', content: expected }]);+ const [page] = await engine.executeRaw<{ body: string; chunker_version: number; sealed: boolean; searchable: boolean; tags: string[] }>(+ `SELECT compiled_truth AS body, chunker_version, text_projection_revision=knowledge_revision AS sealed, search_vector IS NOT NULL AS searchable,+ ARRAY(SELECT tag FROM tags t WHERE t.page_id=p.id ORDER BY tag) AS tags FROM pages p WHERE source_id=$1 AND slug='crash'`, [sourceId]);+ expect(page).toMatchObject({ chunker_version: MARKDOWN_CHUNKER_VERSION, sealed: true, searchable: true, tags: ['example'] });+ expect(page!.body).toContain('Published from the stored request');+ expect(readFileSync(join(root, 'crash.md'), 'utf8')).toContain('Published from the stored request');+ expect(await engine.executeRaw("SELECT 1 FROM op_checkpoints WHERE op='managed-file-import' AND completed_keys->0->>'source_id'=$1", [sourceId])).toHaveLength(0);+ } finally { await disposePersistenceConsumer(engine); await brain.close(); }+ }), 180_000);+}diff --git a/test/fixtures/managed-import-crash-worker.ts b/test/fixtures/managed-import-crash-worker.tsnew file mode 100644index 0000000000..d80e366214--- /dev/null+++ b/test/fixtures/managed-import-crash-worker.ts@@ -0,0 +1,26 @@+// Executed only in an owned subprocess by test/e2e/managed-import-crash.test.ts (GBRA-69).+// Imports one file into a managed source and SIGKILLs itself at a boundary:+// `admitted` (the request is durable and nothing has claimed it) or+// `closing_write` (inside the publication transaction, at the import's one closing page write).+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';+import { PostgresEngine } from '../../src/core/postgres-engine.ts';+import type { BrainEngine } from '../../src/core/engine.ts';+import { importManagedFile } from '../../src/core/persistence/import-mutations.ts';++const [kind, target, file, sourcePath, sourceId, boundary] = process.argv.slice(2) as [string, string, string, string, string, 'admitted' | 'closing_write'];+const Engine = kind === 'pglite' ? PGLiteEngine : PostgresEngine;+const marker = boundary === 'admitted' ? 'FOR UPDATE OF r SKIP LOCKED' : 'UPDATE pages SET chunker_version=$5';+const original = Engine.prototype.executeRaw;+Engine.prototype.executeRaw = async function (this: BrainEngine, sql: string, params?: unknown[]) {+ if (sql.includes(marker)) {+ process.stdout.write(`${JSON.stringify({ event: 'boundary', boundary })}\n`);+ process.kill(process.pid, 'SIGKILL');+ await new Promise(() => {});+ }+ return original.call(this, sql, params);+} as typeof original;+const engine = new Engine();+await engine.connect(kind === 'pglite' ? { database_path: target } : { database_url: target, poolSize: 4 });+await importManagedFile(engine, file, sourcePath, { sourceId, noEmbed: true });+process.stdout.write(`${JSON.stringify({ event: 'completed' })}\n`);+process.exit(0);diff --git a/test/helpers/claim-earlier-fixture.ts b/test/helpers/claim-earlier-fixture.tsnew file mode 100644index 0000000000..edee0034c2--- /dev/null+++ b/test/helpers/claim-earlier-fixture.ts@@ -0,0 +1,119 @@+/**+ * GBRA-69: the claim's "unfinished row ahead on the same root" probe matches+ * the root by indexed columns instead of a COALESCE text key. The fixture+ * compares the claimable rows, in claim order, of the current predicate and+ * the former one over randomized request tables: worktree and database-only+ * roots (two incarnations), every request state, sync rows that may be passed,+ * lane groups and recovery records. Both engines run it; the tables are+ * session-local shadows, so the brain's own request journal is never touched.+ */+import { randomUUID } from 'node:crypto';+import type { BrainEngine } from '../../src/core/engine.ts';+import { CLAIM_ORDER, claimableWriteSql } from '../../src/core/persistence/journal.ts';++const NEW_EARLIER = 'AND NOT EXISTS (SELECT 1 FROM persistence_requests earlier\n WHERE r.worktree_id IS NOT NULL AND earlier.worktree_id=r.worktree_id AND ';++/** The predicate as it was before GBRA-69, rebuilt from the current one around the shared head condition. */+export function formerClaimableWriteSql(priority: string, laneRoots?: string): string {+ const current = claimableWriteSql(priority, laneRoots);+ const start = current.indexOf(NEW_EARLIER);+ const end = current.lastIndexOf('AND NOT ((');+ if (start < 0 || end < 0) throw new Error('claimableWriteSql no longer has the two root probes this fixture rebuilds');+ const first = current.slice(start + NEW_EARLIER.length, current.indexOf('\n AND NOT EXISTS', start + NEW_EARLIER.length));+ const head = first.slice(0, first.lastIndexOf(')'));+ return `${current.slice(0, start)}AND NOT EXISTS (SELECT 1 FROM persistence_requests earlier+ WHERE COALESCE(earlier.worktree_id::text,'db:'||earlier.source_incarnation::text)+ =COALESCE(r.worktree_id::text,'db:'||r.source_incarnation::text)+ AND ${head})+ ${current.slice(end)}`;+}++function rng(seed: number) {+ let s = seed >>> 0;+ return () => { s = (s * 1664525 + 1013904223) >>> 0; return s / 2 ** 32; };+}++async function shadowTables(tx: BrainEngine) {+ for (const table of ['persistence_requests', 'persistence_worktrees', 'persistence_effects', 'persistence_worktree_refreshes']) {+ await tx.executeRaw(`CREATE TEMP TABLE ${table} (LIKE public.${table} INCLUDING DEFAULTS INCLUDING INDEXES) ON COMMIT DROP`);+ }+}++const planNodes = (plan: Record<string, unknown>): Array<Record<string, unknown>> =>+ [plan, ...((plan.Plans as Array<Record<string, unknown>> | undefined) ?? []).flatMap(planNodes)];++/**+ * Postgres: the scans of the `earlier` probe under the current and the former predicate, with their+ * buffer hits, over `roots` worktrees that each hold `queued` queued rows (the former key walked every+ * root's pending rows once per candidate) plus `committed` committed rows on the first.+ */+export async function explainEarlierProbe(engine: BrainEngine, roots = 8, queued = 32, committed = 20_000) {+ const host = randomUUID(), incarnation = randomUUID();+ const worktrees = Array.from({ length: roots }, () => randomUUID());+ return engine.transaction(async tx => {+ await shadowTables(tx);+ const insert = (worktree: string, count: number, state: string) => tx.executeRaw(`INSERT INTO persistence_requests(principal_kind,principal_id,request_id,operation,+ source_id,source_incarnation,slug,worktree_id,digest,intent,authority,intent_bytes,terminal_reservation,state)+ SELECT 'local_cli','fixture',gen_random_uuid(),'put_page','fixture-source',$1::uuid,'page-'||g,$2::uuid,'d','{"kind":"managed_file_import"}'::jsonb,'{}'::jsonb,0,0,$4+ FROM generate_series(1,$3::int) g`, [incarnation, worktree, count, state]);+ for (const worktree of worktrees) {+ await tx.executeRaw(`INSERT INTO persistence_worktrees(id,owner_host_id,state) VALUES ($1::uuid,$2::uuid,'active')`, [worktree, host]);+ await insert(worktree, queued, 'queued');+ }+ await insert(worktrees[0]!, committed, 'committed');+ await tx.executeRaw('ANALYZE persistence_requests');+ const explain = async (where: string) => {+ const [row] = await tx.executeRaw<{ 'QUERY PLAN': unknown }>(`EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON) SELECT r.* FROM persistence_requests r+ LEFT JOIN persistence_worktrees w ON w.id=r.worktree_id WHERE ${where} ORDER BY ${CLAIM_ORDER('true')} LIMIT 1 FOR UPDATE OF r SKIP LOCKED`, [host, []]);+ const raw = row!['QUERY PLAN'];+ const plan = ((typeof raw === 'string' ? JSON.parse(raw) : raw) as Array<{ Plan: Record<string, unknown> }>)[0]!.Plan;+ return { earlier: planNodes(plan).filter(node => node.Alias === 'earlier').map(node => ({ type: String(node['Node Type']), index: node['Index Name'] })),+ buffers: ['Shared Hit Blocks', 'Shared Read Blocks', 'Local Hit Blocks', 'Local Read Blocks'].reduce((sum, key) => sum + Number(plan[key] ?? 0), 0) };+ };+ return { current: await explain(claimableWriteSql('true')), former: await explain(formerClaimableWriteSql('true')) };+ });+}++export interface ClaimCase { seed: number; priority: boolean; lanes: boolean; current: string[]; former: string[] }++/** Runs `cases` randomized tables and returns both predicates' claim order for each. */+export async function compareClaimOrders(engine: BrainEngine, cases = 120): Promise<ClaimCase[]> {+ const host = randomUUID(), otherHost = randomUUID();+ const worktrees = [randomUUID(), randomUUID(), randomUUID()];+ const incarnations = [randomUUID(), randomUUID()];+ const out: ClaimCase[] = [];+ await engine.transaction(async tx => {+ await shadowTables(tx);+ await tx.executeRaw(`INSERT INTO persistence_worktrees(id,owner_host_id,state) VALUES ($1::uuid,$4::uuid,'active'),($2::uuid,$4::uuid,'active'),($3::uuid,$5::uuid,'active')`,+ [...worktrees, host, otherHost]);+ for (let seed = 1; seed <= cases; seed++) {+ const random = rng(seed);+ const pick = <T>(values: readonly T[]) => values[Math.floor(random() * values.length)]!;+ await tx.executeRaw('DELETE FROM persistence_requests');+ const rows = 4 + Math.floor(random() * 14);+ for (let i = 0; i < rows; i++) {+ const database = random() < 0.35;+ const worktree = database ? null : pick(worktrees);+ const sync = random() < 0.4;+ const lane = sync && random() < 0.3;+ const slug = pick(['alpha', 'beta', 'gamma', 'delta']);+ const intent = sync ? { kind: pick(['managed_sync_import', 'managed_sync_delete']), ...(lane ? { lane: 'group-1' } : {}),+ ...(random() < 0.2 ? { renameFrom: { slug: pick(['alpha', 'beta']) } } : {}) } : { kind: 'put_page' };+ await tx.executeRaw(`INSERT INTO persistence_requests(principal_kind,principal_id,request_id,operation,source_id,source_incarnation,page_id,slug,+ worktree_id,digest,intent,authority,intent_bytes,terminal_reservation,state,recovery)+ VALUES ('local_cli','fixture',$1::uuid,'put_page','fixture-source',$2::uuid,$3,$4,$5::uuid,'d',$6::text::jsonb,'{}'::jsonb,0,0,$7,$8::text::jsonb)`,+ [randomUUID(), database ? pick(incarnations) : incarnations[0], random() < 0.5 ? Math.floor(random() * 4) : null, slug, worktree, JSON.stringify(intent),+ pick(['queued', 'queued', 'queued', 'running', 'recovering', 'committed', 'failed']), random() < 0.08 ? JSON.stringify({ version: 1 }) : null]);+ }+ for (const priority of [true, false]) for (const lanes of [false, true]) {+ const laneRoots = lanes ? `ARRAY['${worktrees[0]}']::text[]` : undefined;+ const query = (where: string) => tx.executeRaw<{ id: string }>(`SELECT r.id::text AS id FROM persistence_requests r+ LEFT JOIN persistence_worktrees w ON w.id=r.worktree_id WHERE ${where} ORDER BY ${CLAIM_ORDER(String(priority))}`, [host, []]);+ const current = (await query(claimableWriteSql(String(priority), laneRoots))).map(row => row.id);+ const former = (await query(formerClaimableWriteSql(String(priority), laneRoots))).map(row => row.id);+ out.push({ seed, priority, lanes, current, former });+ }+ }+ });+ return out;+}diff --git a/test/persistence-file-import.test.ts b/test/persistence-file-import.test.tsindex bf2f8b0fea..49ac09164d 100644--- a/test/persistence-file-import.test.ts+++ b/test/persistence-file-import.test.ts@@ -142,6 +142,44 @@ test('a committed import replays the durable cursor when checkpoint cleanup was}}), 120_000);+test('GBRA-69: the import checkpoint holds no content; an import stopped after it resumes its request with the bytes it read', async () => withEnv(env, async () => {+ for (const engine of engines) {+ const f = await fixture(engine), file = join(f.input, 'checkpoint.md');+ writeFileSync(file, '# Checkpoint\n\nThe content travels with the request, not the checkpoint.\n');+ const expected = () => managedImportContent('checkpoint.md', readFileSync(file)).content;+ const stored = () => engine.executeRaw<{ params: Record<string, unknown> }>(+ "SELECT completed_keys->0 AS params FROM op_checkpoints WHERE op='managed-file-import' AND completed_keys->0->>'source_id'=$1", [f.sourceId]);+ const original = engine.executeRaw;+ const stop = async (legacy: boolean) => {+ let reads = 0;+ engine.executeRaw = async function(this: BrainEngine, sql, params) {+ // The second checkpoint read is the one after the insert: the process stops before it submits.+ if (sql.startsWith('SELECT fingerprint,completed_keys FROM op_checkpoints') && ++reads === 2) throw new Error('simulated stop after the checkpoint');+ return original.call(this, sql, params);+ } as BrainEngine['executeRaw'];+ try { await expect(importManagedFile(engine, file, 'checkpoint.md', { sourceId: f.sourceId, noEmbed: true })).rejects.toThrow('simulated stop'); }+ finally { engine.executeRaw = original; }+ const [row] = await stored();+ expect(row!.params).not.toHaveProperty('content');+ expect(row!.params).toMatchObject({ kind: 'managed_file_import', slug: 'checkpoint', inputHash: sha256(readFileSync(file)) });+ // A checkpoint an older binary wrote carried the content; it resumes and clears the same way.+ if (legacy) await engine.executeRaw(`UPDATE op_checkpoints SET completed_keys=jsonb_set(completed_keys,'{0,content}',to_jsonb($2::text))+ WHERE op='managed-file-import' AND completed_keys->0->>'source_id'=$1`, [f.sourceId, expected()]);+ return String(row!.params.request_id);+ };+ for (const legacy of [false, true]) {+ const requestId = await stop(legacy);+ expect(await importManagedFile(engine, file, 'checkpoint.md', { sourceId: f.sourceId, noEmbed: true })).toMatchObject({ status: 'imported' });+ const requests = await engine.executeRaw<{ request_id: string; content: string; state: string }>(+ "SELECT request_id::text, intent->>'content' AS content, state FROM persistence_requests WHERE source_id=$1 AND request_id=$2::uuid", [f.sourceId, requestId]);+ expect(requests).toEqual([{ request_id: requestId, content: expected(), state: 'committed' }]);+ expect(await stored()).toHaveLength(0);+ writeFileSync(file, `# Checkpoint\n\nSecond pass ${legacy}.\n`);+ }+ expect((await engine.getPage('checkpoint', { sourceId: f.sourceId }))?.compiled_truth).toContain('Second pass false');+ }+}), 120_000);+test('managed import refuses cross-source input, symlink targets, skills, malformed YAML and disabled image modality', async () => withEnv(env, async () => {for (const engine of engines) {const f = await fixture(engine), other = await fixture(engine);