Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(persistence): the file check and reconcile keep the stored type and subtype of a file without a type line (#5521)

time-attackb6814d805fd4
diff --git a/src/core/markdown.ts b/src/core/markdown.ts
index 9c3b78eb80..e71bc0eca3 100644
--- a/src/core/markdown.ts
+++ b/src/core/markdown.ts
@@ -500,6 +500,17 @@ export function resolveParsedSubtype(
if (parsed.inferredSubtype?.type === parsed.type) parsed.frontmatter.subtype = parsed.inferredSubtype.name;
}
+/**
+ * Aligns a canonical file's parse with what its import over `stored` keeps (#1035, #5521): a file without an explicit
+ * `type:` (or whose type was only inferred from its path, #6605) keeps the stored type, and the subtype is resolved
+ * against that type, so the stored subtype is kept too. Import does the same, in this order. The write guard
+ * (page-prepare.ts) and reconcile (reconcile-state.ts, reconcile-prepare.ts) share it.
+ */
+export function alignWithStored(parsed: ParsedMarkdown, stored: { type: string; frontmatter?: Record<string, unknown> | null }, inferred: boolean): void {
+ if (inferred || !parsed.typeExplicit) parsed.type = stored.type as ParsedMarkdown['type'];
+ resolveParsedSubtype(parsed, stored);
+}
+
/**
* #5988 hold codes: deterministic content refusals. Ingestion holds the one
* file and keeps going instead of failing the whole sync. Defined once here;
diff --git a/src/core/persistence/page-prepare.ts b/src/core/persistence/page-prepare.ts
index eaed61749e..6bc9379362 100644
--- a/src/core/persistence/page-prepare.ts
+++ b/src/core/persistence/page-prepare.ts
@@ -12,7 +12,7 @@ import type { BrainEngine } from '../engine.ts';
import type { GBrainConfig } from '../config.ts';
import type { Page, PageVersion } from '../types.ts';
import { importFromContent, verifyPageReadable, type ParsedPage } from '../import-file.ts';
-import { comparableFrontmatter, frontmatterHoldMessageWithoutKeys, parseMarkdown, resolveParsedSubtype, serializePageToMarkdown, resolveSourceLocalFilePath, type ParsedMarkdown, type ParseOpts } from '../markdown.ts';
+import { alignWithStored, comparableFrontmatter, frontmatterHoldMessageWithoutKeys, parseMarkdown, resolveParsedSubtype, serializePageToMarkdown, resolveSourceLocalFilePath, type ParsedMarkdown, type ParseOpts } from '../markdown.ts';
import { assertLargePageReplacement } from './large-page-guard.ts';
import { applyInference } from '../frontmatter-inference.ts';
import { OperationError, opError } from '../ops/contract.ts';
@@ -199,14 +199,12 @@ function importedFileType(parsed: ParsedMarkdown, page: Pick<Page, 'type' | 'fro
// #5521 parity for subtype (#5928): a pack rule is not part of the file's bytes, so a file
// without an explicit `subtype:` keeps the stored subtype (or none); the import still stamps it.
delete parsed.inferredSubtype;
- resolveParsedSubtype(parsed, page);
+ alignWithStored(parsed, page, inferred);
// #6429: the v0.13.1 grandfather stamped `validate: false` into the database; on an unmanaged brain that path
// never wrote the file, so the file lacks a key the database carries. The mechanical stamp authors nothing
// (grandfather.ts): a file without a `validate:` key keeps the stored stamp, and the next coordinated write publishes it.
if (!Object.hasOwn(parsed.frontmatter, 'validate') && page.frontmatter?.validate === false) parsed.frontmatter.validate = false;
- // #1035 parity (#5521): a file without an explicit `type:` keeps the stored type on import. An inferred
- // type is not one the file declared (#6605): inference only applies to a file with no frontmatter.
- return parsed.typeExplicit && !inferred ? parsed.type : page.type;
+ return parsed.type;
}
/** The withdrawal ledger readPageSnapshot overlaid the snapshot's body with, for a segmented body read under it. */
function snapshotLedger(snapshot: PageSnapshot): BodyLedger {
diff --git a/src/core/persistence/reconcile-prepare.ts b/src/core/persistence/reconcile-prepare.ts
index e94807af30..1d09452e5b 100644
--- a/src/core/persistence/reconcile-prepare.ts
+++ b/src/core/persistence/reconcile-prepare.ts
@@ -4,7 +4,7 @@ import { readFileSync } from 'node:fs';
import type { BrainEngine } from '../engine.ts';
import type { GBrainConfig } from '../config.ts';
import { importFromContent, type ParsedPage } from '../import-file.ts';
-import { parseMarkdown, serializePageToMarkdown } from '../markdown.ts';
+import { alignWithStored, parseMarkdown, serializePageToMarkdown } from '../markdown.ts';
import { parseFactsFence, renderFactsTable, replaceOrInsertFactsFence, restoreHiddenFactRows, type ParsedFact } from '../facts-fence.ts';
import { opError } from '../ops/contract.ts';
import { readFix, trustedCliRequired } from '../ops/op-fix.ts';
@@ -169,7 +169,7 @@ export async function prepareReconcileMutation(engine: BrainEngine, row: WriteRe
const scanStateTransferred = final ? await transferLegacyAtomPageState(tx, state.snapshot, final) : false;
const reading = reconcileFileReading(readFileSync(state.path, 'utf8'), state.importPath, final?.page ?? state.snapshot.page);
const file = parseMarkdown(reading.content, row.slug);
- if (reading.inferred && final) file.type = final.page.type;
+ if (final) alignWithStored(file, final.page, reading.inferred);
if (!sameCanonicalImport(final, prepared.result) || digest(reconcileCanonical(file, file.tags)) !== artifact.result_digest) {
throw opError('storage_error', 'Reconciliation canonical readback did not match the reviewed result.',
`After publishing, ${row.slug} in source ${row.source_id} read back differently from the reviewed result, so the database change rolled back and the owner's recovery restores the file. Inspect request ${row.request_id}'s receipt before anything else and do not apply the preview again until it is terminal.`,
diff --git a/src/core/persistence/reconcile-state.ts b/src/core/persistence/reconcile-state.ts
index 290ba6cdb1..8432bf85f9 100644
--- a/src/core/persistence/reconcile-state.ts
+++ b/src/core/persistence/reconcile-state.ts
@@ -3,7 +3,7 @@ import { dirname, join, relative, sep } from 'node:path';
import type { BrainEngine } from '../engine.ts';
import { loadConfig, loadConfigWithEngine } from '../config.ts';
import { loadOperatorLiterals } from '../content-sanity-literals.ts';
-import { parseMarkdown } from '../markdown.ts';
+import { alignWithStored, parseMarkdown } from '../markdown.ts';
import { parseDataFrontmatter } from '../data-frontmatter.ts';
import { OperationError, opError } from '../ops/contract.ts';
import { readFix } from '../ops/op-fix.ts';
@@ -214,7 +214,7 @@ export async function readReconcileState(engine: BrainEngine, sourceId: string,
const importPath = scannerSourcePath(root, path, mode);
const reading = reconcileFileReading(text, importPath, snapshot.page);
const parsed = parseMarkdown(reading.content, `${slug}.md`, { validate: true, expectedSlug: slug });
- if (reading.inferred) parsed.type = snapshot.page.type;
+ alignWithStored(parsed, snapshot.page, reading.inferred);
const errors = parsed.errors?.filter(e => !['MISSING_OPEN', 'MISSING_CLOSE', 'EMPTY_FRONTMATTER'].includes(e.code)) ?? [];
if (!errors.length && !parsed.errors?.some(e => e.code === 'MISSING_CLOSE') && parsed.slug !== slug) {
// #5966 (W14 P1.7): a well-formed file whose path derives another slug is a legacy render of a slug the
diff --git a/test/ingestion/put-page-write-through.test.ts b/test/ingestion/put-page-write-through.test.ts
index 6c81e379b5..d14ca00dd4 100644
--- a/test/ingestion/put-page-write-through.test.ts
+++ b/test/ingestion/put-page-write-through.test.ts
@@ -296,6 +296,40 @@ ${subtypes}`);
expect(fs.readFileSync(file, 'utf8')).toContain('subtype: therapy');
});
+ test('a type-less file whose stored type is not its pack path type keeps the stored subtype in the file check (#5521)', async () => {
+ const packDir = path.join(tmpRoot, 'home', '.gbrain', 'schema-packs', 'typed-meetings');
+ fs.mkdirSync(packDir, { recursive: true });
+ fs.writeFileSync(path.join(packDir, 'pack.yaml'), `api_version: gbrain-schema-pack-v1
+name: typed-meetings
+version: 1.0.0
+extends: gbrain-base-v2
+page_types:
+ - name: meeting
+ primitive: temporal
+ path_prefixes: [therapy-meetings/]
+ aliases: []
+ extractable: false
+ expert_routing: false
+ subtypes:
+ - name: therapy
+ when:
+ path_pattern: '^therapy-meetings/'
+`);
+ const ctx = makeCtx({ remote: true });
+ const slug = 'therapy-meetings/review';
+ const file = path.join(brainDir, `${slug}.md`);
+ const write = (params: Record<string, unknown>) => withEnv({ GBRAIN_SCHEMA_PACK: 'typed-meetings' }, () => putPage.handler(ctx, { slug, ...params }));
+ const first = await write({ content: '---\ntitle: Review\ntype: note\nsubtype: weekly\n---\n\nFirst discussion.' }) as { revision: string };
+ expect((await engine.readPageSnapshot(slug, { sourceId: 'default' }))?.page).toMatchObject({ type: 'note', frontmatter: { subtype: 'weekly' } });
+
+ // A mirror rewrites the file without its type and subtype lines; import reads it as the same page (#1035).
+ fs.writeFileSync(file, fs.readFileSync(file, 'utf8').replace(/^(type|subtype): .*\n/gm, ''));
+ const edited = await write({ content: '---\ntitle: Review\n---\n\nSecond discussion.', expected_revision: first.revision });
+ expect(edited).toMatchObject({ state: 'committed' });
+ expect((await engine.readPageSnapshot(slug, { sourceId: 'default' }))?.page).toMatchObject({
+ type: 'note', compiled_truth: 'Second discussion.', frontmatter: { subtype: 'weekly' } });
+ });
+
test('a grandfather validate:false stamp held only by the database is not an uncoordinated file edit (#6429)', async () => {
const ctx = makeCtx({ remote: true });
const slug = 'companies/acme-example';
diff --git a/test/reconcile-audit.test.ts b/test/reconcile-audit.test.ts
index f8b44dfa7d..fd0a23c2df 100644
--- a/test/reconcile-audit.test.ts
+++ b/test/reconcile-audit.test.ts
@@ -10,6 +10,9 @@ import { activatePersistence } from '../src/core/persistence/activation.ts';
import { registerLocalWriter, revokeLocalWriter } from '../src/core/persistence/identity.ts';
import { claimWorktree } from '../src/core/persistence/ownership.ts';
import { auditCanonicalSource, runReconcileAudit } from '../src/core/persistence/reconcile-audit.ts';
+import { liveFileDrift } from '../src/core/persistence/drift-conflicts.ts';
+import { importFromContent } from '../src/core/import-file.ts';
+import { loadActivePackForEngine } from '../src/core/schema-pack/engine-resolution.ts';
import { withEnv } from './helpers/with-env.ts';
import { resetPgliteState } from './helpers/reset-pglite.ts';
@@ -81,6 +84,39 @@ test('audit reports database-only pages separately; a legacy row without source_
expect(collided.findings.find(row => row.slug === 'd-db-only')?.reason).not.toBe('database_only');
}), 60_000);
+test('a page typed by a schema pack path rule, whose file has no type line, is not drift', () => fixture(async (root, source) => {
+ const packDir = join(process.env.GBRAIN_HOME!, '.gbrain', 'schema-packs', 'path-typed');
+ mkdirSync(packDir, { recursive: true });
+ writeFileSync(join(packDir, 'pack.yaml'), `api_version: gbrain-schema-pack-v1
+name: path-typed
+version: 1.0.0
+extends: gbrain-base-v2
+page_types:
+ - name: standup
+ primitive: temporal
+ path_prefixes: [standups/]
+ aliases: []
+ extractable: false
+ expert_routing: false
+ subtypes:
+ - name: daily
+ when:
+ path_pattern: '^standups/'
+`);
+ await withEnv({ GBRAIN_SCHEMA_PACK: 'path-typed' }, async () => {
+ const slug = 'standups/monday';
+ const content = '---\ntitle: Monday\n---\nA synthetic standup.\n';
+ const pack = await loadActivePackForEngine(engine, { remote: false, sourceId: source });
+ await importFromContent(engine, slug, content, { sourceId: source, sourcePath: `${slug}.md`, activePack: pack.manifest, noEmbed: true });
+ expect((await engine.readPageSnapshot(slug, { sourceId: source }))?.page).toMatchObject({ type: 'standup', frontmatter: { subtype: 'daily' } });
+ mkdirSync(join(root, 'standups'));
+ writeFileSync(join(root, `${slug}.md`), content);
+ const report = await runReconcileAudit(engine, { source_id: source });
+ expect(report.findings.map(row => row.slug)).toEqual(['b', 'c']);
+ expect(await liveFileDrift(engine, source, slug)).toMatchObject({ still_present: false, reason: 'agrees' });
+ });
+}), 60_000);
+
test('audit cursor is bounded, explicit and not a source checkpoint', () => fixture(async (_root, source) => {
const first = await runReconcileAudit(engine, { source_id: source, limit: 1 });
expect(first).toMatchObject({ inspected: 1, drifted: 0, next_after: 'a', complete: false });
diff --git a/test/reconcile-stored-type-5521.test.ts b/test/reconcile-stored-type-5521.test.ts
new file mode 100644
index 0000000000..549b4cafb5
--- /dev/null
+++ b/test/reconcile-stored-type-5521.test.ts
@@ -0,0 +1,102 @@
+/**
+ * #5521 (preview half): a canonical file with frontmatter but no `type:` line keeps the stored type on import
+ * (#1035), and with it the stored subtype. Reconcile read such a file with the type its path infers, so an
+ * untouched file previewed a `/type` conflict, taking the file would have retyped the page, and an apply that
+ * kept the file's bytes failed its readback.
+ */
+import { afterAll, beforeAll, 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 type { Page } from '../src/core/types.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { importFromFile } from '../src/core/import-file.ts';
+import { claimWorktree } from '../src/core/persistence/ownership.ts';
+import { registerLocalWriter, withVerifiedLocalRegistration } from '../src/core/persistence/identity.ts';
+import { runReconcileApply, runReconcilePreview } from '../src/core/persistence/reconcile.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { loadActivePackForEngine } from '../src/core/schema-pack/engine-resolution.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const home = mkdtempSync(join(tmpdir(), 'gbrain-reconcile-stored-type-'));
+let engine: PGLiteEngine;
+beforeAll(async () => {
+ engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema();
+ const packDir = join(home, '.gbrain', 'schema-packs', 'path-typed');
+ mkdirSync(packDir, { recursive: true });
+ writeFileSync(join(packDir, 'pack.yaml'), `api_version: gbrain-schema-pack-v1
+name: path-typed
+version: 1.0.0
+extends: gbrain-base-v2
+page_types:
+ - name: standup
+ primitive: temporal
+ path_prefixes: [standups/]
+ aliases: []
+ extractable: false
+ expert_routing: false
+ subtypes:
+ - name: daily
+ when:
+ path_pattern: '^standups/'
+`);
+}, 60_000);
+afterAll(async () => {
+ await withEnv({ GBRAIN_HOME: home }, async () => { await disposePersistenceConsumer(engine); await engine.disconnect(); });
+ rmSync(home, { recursive: true, force: true });
+});
+
+
+/** Imports `rel` from `content`, rewrites the file to `onDisk` and runs `check` as the source's canonical owner. */
+async function imported<T>(rel: string, content: string, onDisk: string, pack: string | undefined,
+ check: (page: { id: string; root: string; slug: string; stored: Page }) => Promise<T>): Promise<T> {
+ return withEnv({ GBRAIN_HOME: home, GBRAIN_SCHEMA_PACK: pack, OPENAI_API_KEY: undefined, ANTHROPIC_API_KEY: undefined }, async () => {
+ const id = `stored-type-${randomUUID().slice(0, 8)}`, root = join(home, id), slug = rel.replace(/\.md$/, '');
+ mkdirSync(join(root, 'standups'), { recursive: true });
+ writeFileSync(join(root, rel), content);
+ await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', [id, root]);
+ const activePack = pack ? (await loadActivePackForEngine(engine, { remote: false, sourceId: id })).manifest : undefined;
+ expect((await importFromFile(engine, join(root, rel), rel, { sourceId: id, noEmbed: true, ...(activePack ? { activePack } : {}) })).status).toBe('imported');
+ writeFileSync(join(root, rel), onDisk);
+ const stored = (await engine.readPageSnapshot(slug, { sourceId: id }))!.page;
+ await claimWorktree(engine, id, root);
+ const registration = await registerLocalWriter(engine, 'cli');
+ return withVerifiedLocalRegistration(engine, registration, () => check({ id, root, slug, stored }));
+ });
+}
+
+const NOTE = '---\ntitle: Item\ntype: note\n---\nA synthetic note.\n';
+const TYPELESS_NOTE = '---\ntitle: Item\n---\nA synthetic note.\n';
+
+test('a file without a type line previews no type conflict against the stored type', () => imported('notes-item.md', NOTE, TYPELESS_NOTE, undefined,
+ async ({ id, root, slug, stored }) => {
+ expect(stored.type).toBe('note');
+ expect((await runReconcilePreview(engine, { source_id: id, slug })).conflict_paths).toEqual([]);
+ writeFileSync(join(root, 'notes-item.md'), TYPELESS_NOTE.replace('---\n', '---\ntype: concept\n'));
+ expect((await runReconcilePreview(engine, { source_id: id, slug })).conflict_paths).toEqual(['/type']);
+ }), 120_000);
+
+test('a body edit to a file without a type line applies with its bytes kept, as repair --prefer file does', () => imported('notes-item.md', NOTE, TYPELESS_NOTE, undefined,
+ async ({ id, root, slug }) => {
+ const edited = TYPELESS_NOTE.replace('note.', 'note, edited.');
+ writeFileSync(join(root, 'notes-item.md'), edited);
+ const preview = await runReconcilePreview(engine, { source_id: id, slug });
+ expect(preview.conflict_paths).toEqual(['/compiled_truth']);
+ const resolved = await runReconcilePreview(engine, { source_id: id, slug, from: preview.preview, decisions: [{ path: '/compiled_truth', action: 'take_file' }] });
+ const receipt = await runReconcileApply(engine, { source_id: id, slug, preview: resolved.preview, request_id: randomUUID(), keep_file_bytes: true });
+ expect(receipt.state).toBe('committed');
+ expect((await engine.readPageSnapshot(slug, { sourceId: id }))!.page).toMatchObject({ type: 'note', compiled_truth: 'A synthetic note, edited.' });
+ expect(readFileSync(join(root, 'notes-item.md'), 'utf8')).toBe(edited);
+ }), 120_000);
+
+test('a pack-typed page whose file has no type line previews neither a type nor a subtype conflict', () => {
+ const content = '---\ntitle: Monday\n---\nA synthetic standup.\n';
+ return imported('standups/monday.md', content, content, 'path-typed', async ({ id, root, slug, stored }) => {
+ expect(stored).toMatchObject({ type: 'standup', frontmatter: { subtype: 'daily' } });
+ expect((await runReconcilePreview(engine, { source_id: id, slug })).conflict_paths).toEqual([]);
+ expect((await runReconcilePreview(engine, { source_id: id, slug, auto_additive: true })).classification).toBe('no_drift');
+ writeFileSync(join(root, 'standups/monday.md'), content.replace('---\n', '---\ntype: concept\n'));
+ expect((await runReconcilePreview(engine, { source_id: id, slug })).conflict_paths).toContain('/type');
+ });
+}, 120_000);