Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
#6712 PR 1: code, image, file-repair and published no-op publishes record full import provenance
garrytan18efa097525a
diff --git a/src/core/persistence/file-repair.ts b/src/core/persistence/file-repair.tsindex 4422faeed6..bba8598a41 100644--- a/src/core/persistence/file-repair.ts+++ b/src/core/persistence/file-repair.ts@@ -69,7 +69,7 @@ import { getWorktreeBinding } from './ownership.ts';import { checkOwner, ownerUnavailableError } from './owner-refusal.ts';import { loadRepairBusySet, repairBusy, repairBusyError } from './repair-busy.ts';import { submitPageMutation } from './page-mutations.ts';-import { clearGitHold, recordSyncImportProvenance } from './sync-holds.ts';+import { clearGitHold, recordSyncImportProvenance, syncDiskProvenance, syncImportParserFor } from './sync-holds.ts';import { screenSyncImport } from './sync-prepare.ts';import type { SyncRename } from './sync-discovery.ts';import type { PreparedContentImport } from './prepared-import.ts';@@ -237,9 +237,9 @@ export async function prepareRepairPublication(engine: BrainEngine, input: Repai}/** The schema pack and content-sanity settings a repair preview and its publication both read, so their results agree. */-export async function repairScreenConfig(engine: BrainEngine, sourceId: string): Promise<Pick<RepairPublicationInput, 'activePack' | 'sanity'>> {- const activePack = (await loadActivePackForEngine(engine, { remote: false, sourceId }).catch(() => null))?.manifest;- return { ...(activePack ? { activePack } : {}), sanity: await loadImportSanityConfig(engine) };+export async function repairScreenConfig(engine: BrainEngine, sourceId: string): Promise<Pick<RepairPublicationInput, 'activePack' | 'sanity'> & { packIdentity: string | null }> {+ const pack = await loadActivePackForEngine(engine, { remote: false, sourceId }).catch(() => null);+ return { ...(pack?.manifest ? { activePack: pack.manifest } : {}), sanity: await loadImportSanityConfig(engine), packIdentity: pack?.identity ?? null };}function assertTrustedRepairCaller(ctx: Pick<OperationContext, 'remote'>): void {@@ -381,9 +381,10 @@ export async function prepareManagedFileRepairMutation(engine: BrainEngine, row: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 (!applied.noop) { await project(tx); await sealPageTextProjection(tx, row.slug, row.source_id); }const holdCleared = await clearGitHold(tx, { sourceId: row.source_id, incarnation: row.source_incarnation, path: p.path, observedAt: p.holdObservedAt ?? new Date().toISOString() });- const [page] = await tx.executeRaw<{ id: number }>('SELECT id FROM pages WHERE source_id=$1 AND slug=$2', [row.source_id, row.slug]);- if (page) await recordSyncImportProvenance(tx, { source_id: row.source_id, incarnation: row.source_incarnation, page_id: Number(page.id), origin: p.sourcePath,- raw_sha256: sha256(importContent), gbrain_version: VERSION });+ // #6712 PR 1: the record names what is on disk now (the approved bytes), the page revision they produced and the parser, so the next discovery prescreens the file.+ const page = await tx.readPageSnapshot(row.slug, { ...source, includeDeleted: true });+ if (page && page.page.deleted_at == null) await recordSyncImportProvenance(tx, { source_id: row.source_id, incarnation: row.source_incarnation, page_id: Number(page.page.id), origin: p.sourcePath,+ raw_sha256: sha256(importContent), gbrain_version: VERSION, revision: page.revision, parser: syncImportParserFor(p.sourcePath, screenConfig.packIdentity), ...syncDiskProvenance(bytes, null) });return { status: moved ? 'renamed' : applied.noop ? 'skipped' : snapshot ? 'updated' : 'created', slug: row.slug, source_id: row.source_id,chunks: applied.result.chunks, imported_file: true, file_repaired: fileChanges, hold_cleared: holdCleared, ...(moved ? { renamed_from: moved.slug } : {}),...(fenceRepair ? { fence_repair: fenceRepair } : {}), ...(contentRepair ? { content_repair: contentRepair } : {}) };diff --git a/src/core/persistence/sync-holds.ts b/src/core/persistence/sync-holds.tsindex 0ddeb1f9e8..cb51814891 100644--- a/src/core/persistence/sync-holds.ts+++ b/src/core/persistence/sync-holds.ts@@ -43,9 +43,10 @@ import { fenceHoldFix, fenceHoldLocation, fencePreviewArgv, readFenceAutoRepair,import { contentHoldDocs, contentHoldFix } from '../content-repair/hold-fix.ts';import { STRUCTURED_WRITE_ADVICE, type FencesNormalized } from '../fence-repair/report.ts';import type { SyncRename } from './sync-discovery.ts';-import { isMultimodalEnabled } from '../sync.ts';+import { isCodeFilePath, isImageFilePath, isMultimodalEnabled } from '../sync.ts';import { VERSION } from '../../version.ts';import { MARKDOWN_CHUNKER_VERSION } from '../chunkers/recursive.ts';+import { chunkerStamp } from '../chunkers/code.ts';import { gitBlobOid, sha256 } from './digest.ts';export const GIT_HOLD_OP = 'sync-hold';@@ -684,7 +685,7 @@ export interface SyncImportProvenance {/*** #6712 PR 0 (write-only until a reader lands): the bytes the publish left on disk, the canonical writeback when it* wrote one, else the file as admitted; null when no file was on disk. `disk_blob_oid` is their Git blob id, comparable- * with `git ls-tree` without reading the file. Absent on records written before the stamp, and on records a repair wrote.+ * with `git ls-tree` without reading the file. Absent on records written before the stamp (PR 1 adds them to code, image and repair records).*/disk_sha256?: string | null;disk_blob_oid?: string | null;@@ -716,6 +717,16 @@ export function syncImportParser(schemaPack: string | null): SyncImportParser {return { parser_version: SYNC_IMPORT_PARSER_VERSION, markdown_chunker: MARKDOWN_CHUNKER_VERSION, schema_pack: schemaPack };}+/**+ * #6712 PR 1: the parser fingerprint an import of `path` records and the discovery prescreen expects: a code page names+ * the code chunker and its grammars (`chunkerStamp`), an image the image importer, a Markdown page `syncImportParser`.+ */+export function syncImportParserFor(path: string, schemaPack: string | null): SyncImportParser {+ if (isImageFilePath(path)) return { parser_version: 'image=1', markdown_chunker: MARKDOWN_CHUNKER_VERSION, schema_pack: null };+ if (isCodeFilePath(path)) return { parser_version: `code=1;chunker=${chunkerStamp()}`, markdown_chunker: MARKDOWN_CHUNKER_VERSION, schema_pack: null };+ return syncImportParser(schemaPack);+}+const provenanceFingerprint = (sourceId: string, incarnation: string, pageId: number) => `${sourceId}:${incarnation}:${pageId}`;export async function recordSyncImportProvenance(tx: Exec, value: Omit<SyncImportProvenance, 'recorded_at' | 'validated'>): Promise<void> {diff --git a/src/core/persistence/sync-image.ts b/src/core/persistence/sync-image.tsindex 7181e30caa..6759a2ae3e 100644--- a/src/core/persistence/sync-image.ts+++ b/src/core/persistence/sync-image.ts@@ -46,6 +46,8 @@ export interface ManagedSyncImageContext {validate: (tx: BrainEngine) => Promise<void>;/** Clears the path's hold (if any) when the import commits. */releaseHold: (tx: BrainEngine) => Promise<void>;+ /** #6712 PR 1: records the page's import provenance (revision, disk bytes, parser) in the publishing transaction. */+ recordProvenance: (tx: BrainEngine) => Promise<void>;/** The caller's publication refusal, so the image branch names requests, retries and codes the way the text branch does. */refuse: (code: RegistryCode, message: string, cause: string) => OperationError;clock?: ClaimPhaseClock;@@ -94,6 +96,7 @@ export async function prepareManagedSyncImage(engine: BrainEngine, row: WriteReqawait ready.apply(tx);await tx.executeRaw('UPDATE pages SET source_path=$3 WHERE source_id=$1 AND slug=$2 AND deleted_at IS NULL AND source_path IS DISTINCT FROM $3', [row.source_id, row.slug, p.sourcePath]);await ctx.releaseHold(tx);+ await ctx.recordProvenance(tx);mutation.postimage = await tx.readPageSnapshot(row.slug, { sourceId: row.source_id, includeDeleted: true });return { status: ctx.renamedFrom ? 'renamed' : ready.noop ? 'skipped' : snapshot ? 'updated' : 'created', slug: row.slug, source_id: row.source_id,chunks: ready.result.chunks, noop: ready.noop && !ctx.renamedFrom, imported_file: true, ...(ctx.renamedFrom ? { renamed_from: ctx.renamedFrom.slug } : {}) };diff --git a/src/core/persistence/sync-prepare.ts b/src/core/persistence/sync-prepare.tsindex b6c0b1077e..23b38ddb85 100644--- a/src/core/persistence/sync-prepare.ts+++ b/src/core/persistence/sync-prepare.ts@@ -44,7 +44,7 @@ import { CURSOR_CHANGED_REFUSAL_MESSAGE, EARLIER_PAGE_REFUSAL_MESSAGE, knockOnDeimport { checkpointCursorReplaced } from './sync-checkpoint-replaced.ts';import { frontmatterSlugConflictMessage } from './verb-errors.ts';import { chunkerStamp } from '../chunkers/code.ts';-import { clearGitHold, countGitHolds, recordSyncImportProvenance, syncDiskProvenance, syncImportParser, type SyncImportProvenanceBase } from './sync-holds.ts';+import { clearGitHold, countGitHolds, recordSyncImportProvenance, syncDiskProvenance, syncImportParser, syncImportParserFor, type SyncImportProvenanceBase } from './sync-holds.ts';import { clearSyncSlice, writeSyncSlice, type SyncSliceState } from './sync-slices.ts';import { CHECKPOINT_MOVED_MESSAGE, emptySyncScope, pinnedSlugModeMismatch, slugModeMismatchCause } from './sync-slug-mode.ts';import { readPagePurgeTombstones } from './page-purge.ts';@@ -375,7 +375,7 @@ async function recordSliceCursor(tx: BrainEngine, row: WriteRequest, p: { syncOp/** The code-file branch of `prepareManagedSyncMutation`: `importCodeFile` with `prepare`, text embedding deferred to `embed --stale` (the image branch is `sync-image.ts`). */async function prepareManagedSyncCode(engine: BrainEngine, row: WriteRequest, p: { content: string; sourcePath: string; rawHash: string | null; lineEndingOnly?: boolean; companyApproval: boolean },- ctx: { snapshot: Snapshot | null; validate: (tx: BrainEngine) => Promise<void>; releaseHold: (tx: BrainEngine) => Promise<void>; clock?: ClaimPhaseClock;+ ctx: { snapshot: Snapshot | null; validate: (tx: BrainEngine) => Promise<void>; releaseHold: (tx: BrainEngine) => Promise<void>; recordProvenance: (tx: BrainEngine) => Promise<void>; clock?: ClaimPhaseClock;refuse: (code: RegistryCode, message: string, cause: string) => OperationError; contentRefusal: (refusal: ContentRefusal) => OperationError }): Promise<PreparedMutation> {const { snapshot, validate, releaseHold, clock, refuse } = ctx;if (p.companyApproval) throw refuse('profile_incompatible', 'Company source approval permits only committed Markdown content.',@@ -400,11 +400,46 @@ async function prepareManagedSyncCode(engine: BrainEngine, row: WriteRequest, p:noop: ready.noop, deferEmbedding: true, apply: async tx => {await ready.apply(tx);await releaseHold(tx);+ await ctx.recordProvenance(tx);return { status: ready.noop ? 'skipped' : snapshot ? 'updated' : 'created', slug: row.slug, source_id: row.source_id,chunks: result.chunks, noop: ready.noop, imported_file: true };} };}+/**+ * #6712 PR 1: the import provenance a code or image publication records in its transaction, as a Markdown import records+ * its own: the page's revision after the write, the bytes on disk (the file: neither writes one back) and the parser.+ */+function syncFileProvenance(row: WriteRequest, p: SyncIntent, root: string, rawSha256: string): (tx: BrainEngine) => Promise<void> {+ return async tx => {+ const final = await tx.readPageSnapshot(row.slug, { sourceId: row.source_id, includeDeleted: true });+ if (!final || final.page.deleted_at != null) return;+ await recordSyncImportProvenance(tx, { source_id: row.source_id, incarnation: row.source_incarnation, page_id: Number(final.page.id), origin: p.sourcePath!,+ raw_sha256: rawSha256, ...(p.blobOid ? { blob_oid: p.blobOid } : {}), working: p.working === true, gbrain_version: VERSION, revision: final.revision,+ parser: syncImportParserFor(p.sourcePath!, null), ...syncDiskProvenance(syncDiskBytes(root, p.path!, p.content!, p.rawHash), p.target) });+ };+}++/**+ * The no-op of an entry whose newer working-tree bytes are the current page (`published`): it records, as its import+ * provenance, those working-tree bytes at the page's current revision (#6712 PR 1), so the commit that later carries+ * them is prescreened; the pinned bytes it did not import are not recorded.+ */+function publishedSyncNoop(row: WriteRequest, p: SyncIntent, root: string, snapshot: Snapshot | null, schemaPack: string | null,+ validate: (tx: BrainEngine) => Promise<void>, releaseHold: (tx: BrainEngine) => Promise<void>): SyncPreparedMutation {+ const importProvenance: SyncImportProvenanceBase = { source_id: row.source_id, incarnation: row.source_incarnation, origin: p.sourcePath!, raw_sha256: p.rawHash!,+ working: true, gbrain_version: VERSION, parser: syncImportParser(schemaPack) };+ return { observedRevision: snapshot?.revision ?? null, noop: true, contentUnchanged: true, validate, importProvenance,+ apply: async tx => {+ await releaseHold(tx);+ const current = await tx.readPageSnapshot(row.slug, { sourceId: row.source_id, includeDeleted: true });+ if (current && current.page.deleted_at == null && current.revision === snapshot?.revision) {+ await recordSyncImportProvenance(tx, { ...importProvenance, page_id: Number(current.page.id), revision: current.revision, ...syncDiskProvenance(readSyncFile(root, p.path!), p.target) });+ }+ return { status: 'skipped', slug: row.slug, source_id: row.source_id, chunks: 0, noop: true, imported_file: true };+ } };+}+/** The bytes on disk of an import that writes no file back: its frozen content when that is the file (raw hash), else the file read now (null: absent). */export function syncDiskBytes(root: string, path: string, content: string, rawHash: string | null): Uint8Array | null {return rawHash !== null && rawHash === sha256(content) ? Buffer.from(content) : readSyncFile(root, path);@@ -590,10 +625,11 @@ export async function prepareManagedSyncMutation(unbounded: BrainEngine, row: Wrif (isImageFilePath(p.sourcePath)) {return prepareManagedSyncImage(engine, row, { content: p.content, sourcePath: p.sourcePath, path: p.path, rawHash: p.rawHash, lineEndingOnly: p.lineEndingOnly },{ root, snapshot, ...(moved && moved.slug !== row.slug ? { renamedFrom: { slug: moved.slug } } : {}), noEmbed: p.processingOptions?.noEmbed === true || p.embedDeferred === true, companyApproval: !!p.companyApproval, validate, releaseHold, clock, screening: !!screening,+ recordProvenance: syncFileProvenance(row, p, root, sha256(Buffer.from(p.content, 'base64'))),refuse: (code, message, cause) => syncPublicationRefusal(code, message, row, p, cause) });}if (isCodeFilePath(p.sourcePath)) return prepareManagedSyncCode(engine, row, { content: p.content, sourcePath: p.sourcePath, rawHash: p.rawHash, lineEndingOnly: p.lineEndingOnly, companyApproval: !!p.companyApproval },- { snapshot, validate, releaseHold, clock, refuse: (code, message, cause) => syncPublicationRefusal(code, message, row, p, cause), contentRefusal: refusal => syncContentRefusal(refusal, row, p) });+ { snapshot, validate, releaseHold, recordProvenance: syncFileProvenance(row, p, root, sha256(p.content)), clock, refuse: (code, message, cause) => syncPublicationRefusal(code, message, row, p, cause), contentRefusal: refusal => syncContentRefusal(refusal, row, p) });const schema = p.companyApproval?.schema;if (schema && p.processingOptions?.noSchemaPack) throw syncPublicationRefusal('profile_incompatible', 'Company source approval requires its pinned schema pack.', row,{ ...p, processingOptions: { ...p.processingOptions!, noSchemaPack: false } },@@ -614,8 +650,7 @@ export async function prepareManagedSyncMutation(unbounded: BrainEngine, row: Wrconst { 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,purgedPages: await readPagePurgeTombstones(engine, row.source_id) });- if (screen.status === 'published') return { observedRevision: snapshot?.revision ?? null, noop: true, contentUnchanged: true, validate,- apply: async tx => { await releaseHold(tx); return { status: 'skipped', slug: row.slug, source_id: row.source_id, chunks: 0, noop: true, imported_file: true }; } };+ if (screen.status === 'published') return publishedSyncNoop(row, p, root, snapshot, pack?.identity ?? null, validate, releaseHold);if (screen.status === 'refused') throw syncContentRefusal(screen.refusal, row, p);const recovery = screen.parsed?.errors?.find(error => error.code === 'YAML_PARSE' && error.recoverable)?.recovery;const commentValue = screen.parsed?.warnings?.some(warning => warning.code === 'FRONTMATTER_COMMENT_VALUE') === true;diff --git a/test/sync-import-provenance-disk.test.ts b/test/sync-import-provenance-disk.test.tsindex db827ec5e9..ff962068c4 100644--- a/test/sync-import-provenance-disk.test.ts+++ b/test/sync-import-provenance-disk.test.ts@@ -8,7 +8,8 @@* (the written-back file, not the input) and a file whose disk bytes differ from the pinned blob only by line endings;* a record without them (older releases, repairs) is read and replaced by the next publish of the page.* Regression it catches: a record that hashes the pinned input instead of the bytes on disk, or omits the revision.- * Code and image pages write no import provenance, so they have no case here. Synthetic content only.+ * #6712 PR 1: code and image pages record the same fields (their parser names the code chunker or the image importer),+ * so the discovery prescreen can match them. Synthetic content only.*/import { afterAll, beforeAll, describe, expect, test } from 'bun:test';import { execFileSync } from 'node:child_process';@@ -21,7 +22,8 @@ import { PGLiteEngine } from '../src/core/pglite-engine.ts';import { claimWorktree } from '../src/core/persistence/ownership.ts';import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';import { performManagedSync } from '../src/core/persistence/sync-run.ts';-import { readSyncImportProvenance, SYNC_IMPORT_PARSER_VERSION, SYNC_IMPORT_PROVENANCE_OP } from '../src/core/persistence/sync-holds.ts';+import { readSyncImportProvenance, SYNC_IMPORT_PARSER_VERSION, SYNC_IMPORT_PROVENANCE_OP, syncImportParserFor } from '../src/core/persistence/sync-holds.ts';+import { chunkerStamp } from '../src/core/chunkers/code.ts';import { loadActivePackForEngine } from '../src/core/schema-pack/engine-resolution.ts';import { MARKDOWN_CHUNKER_VERSION } from '../src/core/chunkers/recursive.ts';import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';@@ -52,14 +54,14 @@ describe('managed-sync import provenance records the bytes on disk, the revisionconst each = (fn: (engine: BrainEngine) => Promise<void>) => withEnv({ GBRAIN_HOME: home, OPENAI_API_KEY: undefined, ANTHROPIC_API_KEY: undefined },async () => { for (const engine of engines) await fn(engine); });- async function fixture(engine: BrainEngine, files: Record<string, string>) {+ async function fixture(engine: BrainEngine, files: Record<string, string | Buffer>, config: Record<string, string> = {}) {await disposePersistenceConsumer(engine);await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');const id = `prov-${randomUUID().slice(0, 12)}`, root = join(home, id);mkdirSync(root, { recursive: true }); git(root, 'init', '-q');for (const [path, body] of Object.entries(files)) { mkdirSync(dirname(join(root, path)), { recursive: true }); writeFileSync(join(root, path), body); }const head = commit(root, 'seed');- await engine.executeRaw("INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,'{}')", [id, root]);+ await engine.executeRaw('INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,$3::jsonb)', [id, root, JSON.stringify(config)]);await claimWorktree(engine, id, root);await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');const [{ incarnation }] = await engine.executeRaw<{ incarnation: string }>('SELECT incarnation::text AS incarnation FROM sources WHERE id=$1', [id]);@@ -134,6 +136,20 @@ describe('managed-sync import provenance records the bytes on disk, the revision}})), 120_000);+ test('#6712 PR 1: a code page and an image page record the file bytes, the revision and their own parser', async () => withEnv({ GBRAIN_EMBEDDING_MULTIMODAL: 'true', GBRAIN_EMBEDDING_IMAGE_OCR: 'false' }, () => each(async engine => {+ const png = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==', 'base64');+ const f = await fixture(engine, { 'src/example.ts': 'export const example = 1;\n', 'notes/photo.png': png, 'notes/plain.md': note('A synthetic note beside code.') }, { strategy: 'auto' });+ expect((await performManagedSync(engine, f.opts)).status).toBe('first_sync');+ for (const [path, parser] of [['src/example.ts', `code=1;chunker=${chunkerStamp()}`], ['notes/photo.png', 'image=1']] as const) {+ const [{ slug }] = await engine.executeRaw<{ slug: string }>('SELECT slug FROM pages WHERE source_id=$1 AND source_path=$2', [f.id, path]);+ const { snapshot, record } = await provenanceOf(engine, f, slug);+ const disk = readFileSync(join(f.root, path));+ expect(record).toMatchObject({ origin: path, disk_sha256: sha256(disk), disk_blob_oid: git(f.root, 'rev-parse', `HEAD:${path}`), revision: snapshot.revision,+ parser: { parser_version: parser, markdown_chunker: MARKDOWN_CHUNKER_VERSION, schema_pack: null } });+ expect(record.parser).toEqual(syncImportParserFor(path, null));+ }+ })), 120_000);+test('a record without the fields is read as it is, and the next publish of the page stamps them', async () => each(async engine => {const f = await fixture(engine, { 'notes/legacy.md': note('A synthetic observation an older release imported.') });expect((await performManagedSync(engine, f.opts)).status).toBe('first_sync');