Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(persistence): infer remote page type and subtype from the active schema pack (#5548)
garrytana52d0822ef1e
diff --git a/src/core/import-file.ts b/src/core/import-file.tsindex 1e990f18d0..a5a7e1ef34 100644--- a/src/core/import-file.ts+++ b/src/core/import-file.ts@@ -7,7 +7,7 @@ import { readFileSync, statSync, lstatSync } from 'fs';import { basename, extname, resolve } from 'path';import { createHash } from 'crypto';import type { BrainEngine, FileSpec } from './engine.ts';-import { parseMarkdown } from './markdown.ts';+import { parseMarkdown, resolveParsedSubtype, type ParseOpts } from './markdown.ts';import { classifyStoredType } from './schema-pack/type-usage.ts';import { prepareMarkdownChunks } from './markdown-chunks.ts';import { prepareCodeChunks, installCodeChunkEdges } from './code-chunks.ts';@@ -264,7 +264,7 @@ export async function importFromContent(* Callers thread this from `loadActivePack(ctx)` once per command —* NEVER per file inside sync (codex perf finding #7).*/- activePack?: { page_types: ReadonlyArray<{ name: string; path_prefixes: ReadonlyArray<string>; aliases?: ReadonlyArray<string> }> };+ activePack?: ParseOpts['activePack'];/*** v0.39.3.0 provenance write-through (WARN-8). When set, threaded to* `tx.putPage` so the page's `source_kind`, `source_uri`,@@ -631,7 +631,7 @@ export async function importFromContent(if (parsed.typeExplicit !== true && existing) {parsed.type = existing.type;}-+ resolveParsedSubtype(parsed, existing);// Alias-footgun visibility: an explicit frontmatter `type:` that is an// ALIAS of a canonical pack type (or entirely undeclared) is stored// literally and never re-normalized — different agents can silently filediff --git a/src/core/markdown.ts b/src/core/markdown.tsindex a1b6d66645..1c4e57cb1c 100644--- a/src/core/markdown.ts+++ b/src/core/markdown.ts@@ -35,7 +35,14 @@ export interface ParseOpts {* Callers thread this from `loadActivePack(ctx)` once per command —* NEVER per file inside sync, per codex perf finding #7.*/- activePack?: { page_types: ReadonlyArray<{ name: string; path_prefixes: ReadonlyArray<string> }> };+ activePack?: { page_types: ReadonlyArray<{+ name: string;+ path_prefixes: ReadonlyArray<string>;+ subtypes?: ReadonlyArray<{+ name: string;+ when: { path_pattern?: string; frontmatter_field?: string; frontmatter_value?: unknown };+ }>;+ }> };}export interface ParsedMarkdown {@@ -51,6 +58,8 @@ export interface ParsedMarkdown {* explicit frontmatter type is an override; absence means "don't change it".*/typeExplicit?: boolean;+ /** Pack rule matched for this path and type; not yet stored in frontmatter. */+ inferredSubtype?: { type: string; name: string };title: string;tags: string[];/** Present iff opts.validate. Empty array means no errors. */@@ -293,9 +302,8 @@ export function parseMarkdown(// `2024-06-01` is legitimate); the NON_STRING_FIELD lint finding below still// surfaces the un-quoted field so it can be cleaned up.const explicitType = coerceFrontmatterString(frontmatter.type);- const type = explicitType || (- opts?.activePack ? inferTypeFromPack(filePath, opts.activePack) : inferType(filePath)- );+ const inferred = opts?.activePack ? inferTypeAndSubtypeFromPack(filePath, opts.activePack, frontmatter) : undefined;+ const type = explicitType || inferred?.type || inferType(filePath);// #2446: title precedence is frontmatter `title:` > the body's first H1 >// the slug/filename-humanized fallback. Slug-based imports (contacts,// calendar) write a correct `# Heading` but no frontmatter title; without@@ -326,6 +334,7 @@ export function parseMarkdown(slug,type,typeExplicit: explicitType !== '',+ ...(inferred?.subtype && type === inferred.type ? { inferredSubtype: { type, name: inferred.subtype } } : {}),title,tags,};@@ -333,6 +342,21 @@ export function parseMarkdown(return result;}+/** Apply explicit, stored, then pack-inferred subtype precedence. */+export function resolveParsedSubtype(+ parsed: ParsedMarkdown,+ existing?: { type: string; frontmatter?: Record<string, unknown> | null } | null,+): void {+ if (Object.prototype.hasOwnProperty.call(parsed.frontmatter, 'subtype')) return;+ if (existing && parsed.type === existing.type) {+ if (existing.frontmatter && Object.prototype.hasOwnProperty.call(existing.frontmatter, 'subtype')) {+ parsed.frontmatter.subtype = existing.frontmatter.subtype;+ return;+ }+ }+ if (parsed.inferredSubtype?.type === parsed.type) parsed.frontmatter.subtype = parsed.inferredSubtype.name;+}+/*** Inspect raw content for the 7 frontmatter validation classes that gray-matter* silently accepts. Mutates `errors` in place. The order of checks is@@ -845,14 +869,14 @@ export function inferTypeAndSubtypeFromPack(const subtypes = matchedType.subtypes ?? [];if (subtypes.length === 0) return { type: typeName };for (const st of subtypes) {- // Frontmatter rule firstif (st.when.frontmatter_field !== undefined && frontmatter !== undefined) {const value = frontmatter[st.when.frontmatter_field];if (st.when.frontmatter_value !== undefined && value === st.when.frontmatter_value) {return { type: typeName, subtype: st.name };}}- // Path pattern rule+ }+ for (const st of subtypes) {if (st.when.path_pattern !== undefined) {try {const re = new RegExp(st.when.path_pattern);diff --git a/src/core/persistence/page-prepare.ts b/src/core/persistence/page-prepare.tsindex 3b4bd4c43f..49a619617d 100644--- a/src/core/persistence/page-prepare.ts+++ b/src/core/persistence/page-prepare.ts@@ -6,7 +6,7 @@ import type { BrainEngine } from '../engine.ts';import type { GBrainConfig } from '../config.ts';import type { Page, PageVersion } from '../types.ts';import { importFromContent, type ParsedPage } from '../import-file.ts';-import { parseMarkdown, serializePageToMarkdown, resolveSourceLocalFilePath } from '../markdown.ts';+import { parseMarkdown, resolveParsedSubtype, serializePageToMarkdown, resolveSourceLocalFilePath, type ParseOpts } from '../markdown.ts';import { OperationError } from '../ops/contract.ts';import { assertPageRevision, type PageSnapshot } from '../page-state/types.ts';import { isWriteTargetContained } from '../path-confine.ts';@@ -26,6 +26,7 @@ import { materializeTimeline, prepareCanonicalProjections } from './canonical-primport { preserveProtectedTakes } from './protected-takes.ts';import { isAutoLinkEnabled } from '../link-extraction.ts';import { prepareAutomaticLinks } from './links-preparation.ts';+import { loadActivePackForEngine } from '../schema-pack/engine-resolution.ts';import { preparePageAdvisories, remoteLinkHint, pageNoopAdvisories } from './page-advisories.ts';import { assertKnowledgePublicationAllowed } from '../shared-skills/knowledge-guard.ts';import { colonSlugWindowsRefusal, isWindowsColonTarget, nativeFileTarget } from './native-file-target.ts';@@ -81,7 +82,7 @@ export function publishesDatabaseOnly(root: string, slug: string, snapshot: Pagereturn isSourceDbOnlySlug(root, slug, 'refuse') || isNeverFiledDerivedPage(slug, snapshot.page);}export async function prepareFileTarget(engine: BrainEngine, row: Pick<WriteRequest, 'source_id' | 'worktree_id' | 'slug'>, snapshot: PageSnapshot | null,- content: string | null, hostId?: string, options: { allowMissing?: boolean; capture?: { path: string; hash: string } } = {}): Promise<PreparedMutation['file']> {+ content: string | null, hostId?: string, options: { allowMissing?: boolean; capture?: { path: string; hash: string }; activePack?: ParseOpts['activePack'] } = {}): Promise<PreparedMutation['file']> {if (!row.worktree_id) return undefined;// #5409: a read-only mirror's checkout belongs to its Git remote; nothing is written or removed there.if (await sourceMirrorReadOnly(engine, row.source_id)) return undefined;@@ -120,7 +121,8 @@ export async function prepareFileTarget(engine: BrainEngine, row: Pick<WriteRequ// A normal edit may replace only the bytes represented by its read snapshot.// Unknown local edits require explicit import/recovery, even for force writes.if (before && snapshot) {- const parsed = parseMarkdown(before.toString('utf8'), row.slug);+ const parsed = parseMarkdown(before.toString('utf8'), row.slug, { activePack: options.activePack });+ resolveParsedSubtype(parsed, snapshot.page);const expected = canonical(snapshot.page, snapshot.tags);// #1035 parity (#5521): a file without an explicit `type:` keeps the stored type on import.const type = parsed.typeExplicit ? parsed.type : snapshot.page.type;@@ -172,9 +174,10 @@ export async function preparePageMutation(engine: BrainEngine, row: WriteRequestassertPageRevision(snapshot, preparedIntent ? { expectedRevision: preparedIntent.expectedRevision } : engineMutationPrecondition(parseMutationPrecondition(p)));if ((snapshot?.page.id ?? null) !== row.page_id) throw new OperationError('page_identity_changed', 'The accepted page identity changed.');const observedRevision = snapshot?.revision ?? null;+ const activePack = (await loadActivePackForEngine(engine, { remote: row.authority.remote, sourceId: row.source_id }).catch(() => null))?.manifest;if (row.operation === 'put_page' && p.allow_empty !== true && snapshot && !snapshot.page.deleted_at&& typeof p.content === 'string' && `${snapshot.page.compiled_truth}\n${snapshot.page.timeline ?? ''}`.trim()) {- const incoming = parseMarkdown(p.content, row.slug);+ const incoming = parseMarkdown(p.content, row.slug, { activePack });if (!`${incoming.compiled_truth}\n${incoming.timeline ?? ''}`.trim()) {throw new OperationError('invalid_params', `Refusing to overwrite existing non-empty page '${row.slug}' with empty content. Use capture --file PATH --slug SLUG for file input; set allow_empty:true to intentionally clear it.`,'Use capture --file PATH --slug SLUG for file input, or pass allow_empty:true with the expected revision to intentionally clear it.');@@ -188,7 +191,7 @@ export async function preparePageMutation(engine: BrainEngine, row: WriteRequest// 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.- const file = await prepareFileTarget(engine, row, snapshot, null, undefined, { allowMissing: purge || options.allowMissingFile });+ const file = await prepareFileTarget(engine, row, snapshot, null, undefined, { allowMissing: purge || options.allowMissingFile, activePack });return { observedRevision, noop, file, ...await pageDatabaseOnlyPublication(engine, row, file), apply: async tx => {if (purge) {await tx.deletePage(row.slug, source);@@ -223,7 +226,7 @@ export async function preparePageMutation(engine: BrainEngine, row: WriteRequestcontent = serializePageToMarkdown(page, tags);}if (row.authority.remote && row.operation !== 'remember' && !row.operation.startsWith('takes_') && typeof content==='string') {- const parsed=parseMarkdown(content,row.slug);+ const parsed=parseMarkdown(content,row.slug,{ activePack });const compiled_truth=preserveProtectedTakes(parsed.compiled_truth,snapshot?.page.compiled_truth??'');const timeline=preserveProtectedTakes(parsed.timeline??'',snapshot?.page.timeline??'');if (compiled_truth!==parsed.compiled_truth || timeline!==(parsed.timeline??'')) content=serializePageToMarkdown({@@ -242,10 +245,11 @@ export async function preparePageMutation(engine: BrainEngine, row: WriteRequest// Detect an exact canonical no-op before ingestion can invoke any provider.// Revision/identity checks above still apply to stale identical replacements.if (snapshot && (snapshot.page.deleted_at != null) === targetDeleted && typeof content === 'string') {- const incoming = parseMarkdown(content,row.slug);+ const incoming = parseMarkdown(content,row.slug,{ activePack });+ resolveParsedSubtype(incoming, snapshot.page);const tags = versionTags ?? [...new Set([...snapshot.tags,...incoming.tags])].sort();if (digest(canonical(snapshot.page,snapshot.tags)) === digest(canonical(incoming,tags))) {- const file=await prepareFileTarget(engine,row,snapshot,targetDeleted ? null : serializePageToMarkdown(snapshot.page,snapshot.tags));+ const file=await prepareFileTarget(engine,row,snapshot,targetDeleted ? null : serializePageToMarkdown(snapshot.page,snapshot.tags),undefined,{ activePack });return {observedRevision,noop:true,file,...await pageDatabaseOnlyPublication(engine,row,file),apply:async()=>({...pageNoopAdvisories(row),status:'skipped',slug:row.slug,source_id:row.source_id,noop:true,chunks:0,chunk_skip_reason:'write_skipped',...(row.operation==='capture'?{channel:'capture',content_hash:p.capture_hash}:{})})};@@ -254,7 +258,7 @@ export async function preparePageMutation(engine: BrainEngine, row: WriteRequestlet prepared: PreparedContentImport | undefined;let provenance: CanonicalProvenance | undefined;const result = await importFromContent(engine, row.slug, content, {- ...source, noEmbed: true, remote: row.authority.remote,+ ...source, noEmbed: true, remote: row.authority.remote, activePack,forceRechunk: row.operation === 'restore_page' || row.operation === 'revert_version',allowEmptyOverwrite: p.allow_empty === true || row.operation === 'restore_page' || row.operation === 'revert_version',source_kind: typeof p.source_kind === 'string' ? p.source_kind : null,@@ -298,7 +302,7 @@ export async function preparePageMutation(engine: BrainEngine, row: WriteRequest? await prepareAutomaticLinks(engine,row.slug,ready.parsedPage,row.source_id) : undefined;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;- const file = await prepareFileTarget(engine, row, snapshot, targetDeleted ? null : rendered, undefined, { capture, allowMissing: options.allowMissingFile });+ const file = await prepareFileTarget(engine, row, snapshot, targetDeleted ? null : rendered, undefined, { capture, allowMissing: options.allowMissingFile, activePack });const mintMode = file && !snapshot?.page.source_path ? await scannerSlugRootMode(engine, row.source_id, file.root) : undefined;const sourcePath = file && mintMode ? scannerSourcePath(file.root, file.path, mintMode) : undefined;// An inferred mode is pinned with the first origin it mints, so later pages cannot flip the inference (#5610).diff --git a/src/core/persistence/sync-prepare.ts b/src/core/persistence/sync-prepare.tsindex 2fdebfee40..4c90c74983 100644--- a/src/core/persistence/sync-prepare.ts+++ b/src/core/persistence/sync-prepare.ts@@ -5,7 +5,7 @@ import type { GBrainConfig } from '../config.ts';import type { Page } from '../types.ts';import { OperationError } from '../ops/contract.ts';import { importFromContent, importCodeFile } from '../import-file.ts';-import { parseMarkdown, serializePageToMarkdown } from '../markdown.ts';+import { parseMarkdown, resolveParsedSubtype, serializePageToMarkdown } from '../markdown.ts';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';@@ -194,6 +194,7 @@ export async function prepareManagedSyncMutation(engine: BrainEngine, row: Writethrow new OperationError('revision_conflict', 'The renamed page changed after sync admission.');}const parsedInput = parseMarkdown(p.content, row.slug, { activePack });+ resolveParsedSubtype(parsedInput, base?.page);const expectedSlug = resolveSlugForPath(p.sourcePath);const retainedWindowsOrigin = process.platform === 'win32' && snapshot?.page.source_path != null &&syncOriginPath(snapshot.page.source_path) === syncOriginPath(p.sourcePath) && parsedInput.slug === snapshot.page.slug;@@ -237,6 +238,7 @@ export async function prepareManagedSyncMutation(engine: BrainEngine, row: Writethrow new OperationError('revision_conflict', 'A different page already owns this file identity; resolve the duplicate before syncing.');}const parsed = parseMarkdown(p.content, row.slug, { activePack });+ resolveParsedSubtype(parsed, base?.page);const tags = [...new Set([...(base?.tags ?? []), ...ready.parsedPage.tags])].sort();const renderedPage = { ...(base?.page ?? { id: 0, source_id: row.source_id, created_at: new Date(), updated_at: new Date() }), ...ready.parsedPage } as Page;if (renamed && parsedInput.typeExplicit !== true) renderedPage.type = parsedInput.type;diff --git a/test/fixtures/goldens/exports/runtime.json b/test/fixtures/goldens/exports/runtime.jsonindex b3dae42a69..886cd4c090 100644--- a/test/fixtures/goldens/exports/runtime.json+++ b/test/fixtures/goldens/exports/runtime.json@@ -660,6 +660,7 @@"isRelativeFileUri","parseMarkdown","resolvePageFilePath",+ "resolveParsedSubtype","resolveSourceLocalFilePath","serializeMarkdown","serializePageToMarkdown",diff --git a/test/fixtures/goldens/exports/types.json b/test/fixtures/goldens/exports/types.jsonindex cc5e33f9bd..9bbcf5a744 100644--- a/test/fixtures/goldens/exports/types.json+++ b/test/fixtures/goldens/exports/types.json@@ -4232,7 +4232,7 @@"kind": "function","name": "importFromContent","signature": [- "(engine: BrainEngine, slug: string, content: string, opts?: { prepare?: (prepared: PreparedContentImport) => Promise<ImportResult>; prepareFrontmatter?: (page: ParsedPage) => void; noEmbed?: boolean; sourceId?: string; filename?: string; sourcePath?: string; sourceRoot?: string; fileTimes?: { birthtime?: Date; mtime?: Date; firstCommit?: Date; }; forceRechunk?: boolean; activePack?: { page_types: ReadonlyArray<{ name: string; path_prefixes: ReadonlyArray<string>; aliases?: ReadonlyArray<string>; }>; }; source_kind?: string | null; source_uri?: string | null; ingested_via?: string | null; remote?: boolean; allowEmptyOverwrite?: boolean; beforeCommit?: (tx: BrainEngine, slug: string) => Promise<void>; onPostCommitEmbedding?: (complete: () => Promise<ImportEmbeddingResult>) => void; }) => Promise<ImportResult>"+ "(engine: BrainEngine, slug: string, content: string, opts?: { prepare?: (prepared: PreparedContentImport) => Promise<ImportResult>; prepareFrontmatter?: (page: ParsedPage) => void; noEmbed?: boolean; sourceId?: string; filename?: string; sourcePath?: string; sourceRoot?: string; fileTimes?: { birthtime?: Date; mtime?: Date; firstCommit?: Date; }; forceRechunk?: boolean; activePack?: ParseOpts[\"activePack\"]; source_kind?: string | null; source_uri?: string | null; ingested_via?: string | null; remote?: boolean; allowEmptyOverwrite?: boolean; beforeCommit?: (tx: BrainEngine, slug: string) => Promise<void>; onPostCommitEmbedding?: (complete: () => Promise<ImportEmbeddingResult>) => void; }) => Promise<ImportResult>"]},{@@ -4491,7 +4491,7 @@"kind": "variable","name": "LINK_EXTRACTOR_VERSION_TS","signature": [- "\"2026-10-01T00:00:00Z\""+ "\"2026-10-02T00:00:00Z\""]},{@@ -4765,7 +4765,7 @@{"kind": "interface","members": [- "activePack?: { page_types: ReadonlyArray<{ name: string; path_prefixes: ReadonlyArray<string>; }>; } | undefined",+ "activePack?: { page_types: ReadonlyArray<{ name: string; path_prefixes: ReadonlyArray<string>; subtypes?: ReadonlyArray<{ name: string; when: { path_pattern?: string; frontmatter_field?: string; frontmatter_value?: unknown; }; }>; }>; } | undefined","expectedSlug?: string | undefined","validate?: boolean | undefined"],@@ -4793,6 +4793,7 @@"compiled_truth: string","errors?: ParseValidationError[] | undefined","frontmatter: Record<string, unknown>",+ "inferredSubtype?: { type: string; name: string; } | undefined","slug: string","tags: string[]","timeline: string",@@ -4865,6 +4866,13 @@"(brainDir: string, slug: string, sourceId: string) => string"]},+ {+ "kind": "function",+ "name": "resolveParsedSubtype",+ "signature": [+ "(parsed: ParsedMarkdown, existing?: { type: string; frontmatter?: Record<string, unknown> | null; } | null) => void"+ ]+ },{"kind": "function","name": "resolveSourceLocalFilePath",diff --git a/test/ingestion/put-page-write-through.test.ts b/test/ingestion/put-page-write-through.test.tsindex 297e5acf88..1e17dabef0 100644--- a/test/ingestion/put-page-write-through.test.ts+++ b/test/ingestion/put-page-write-through.test.ts@@ -137,6 +137,125 @@ describe('put_page write-through — happy path', () => {expect(onDisk).toContain('WT body');});+ test("remote writes infer a custom type from the active pack through no-op and file checks", async () => {+ const packDir = path.join(+ tmpRoot,+ "home",+ ".gbrain",+ "schema-packs",+ "route-test",+ );+ fs.mkdirSync(packDir, { recursive: true });+ fs.writeFileSync(+ path.join(packDir, "pack.yaml"),+ `api_version: gbrain-schema-pack-v1+name: route-test+version: 1.0.0+extends: gbrain-base-v2+page_types:+ - name: goal+ primitive: concept+ path_prefixes: [goals/]+ aliases: []+ extractable: false+ expert_routing: false+`,+ );+ await withEnv({ GBRAIN_SCHEMA_PACK: "route-test" }, async () => {+ const ctx = makeCtx({ remote: true });+ const slug = "goals/learn-guitar";+ const content = "---\ntitle: Learn guitar\n---\n\nPractice regularly.";+ const first = (await putPage.handler(ctx, { slug, content })) as {+ revision: string;+ };+ const file = path.join(brainDir, `${slug}.md`);+ expect(+ (await engine.readPageSnapshot(slug, { sourceId: "default" }))?.page+ .type,+ ).toBe("goal");+ expect(fs.readFileSync(file, "utf8")).toContain("type: goal");++ const unchanged = await putPage.handler(ctx, {+ slug,+ content,+ expected_revision: first.revision,+ });+ expect(unchanged).toMatchObject({+ state: "committed",+ noop: true,+ revision: first.revision,+ });++ // A canonical file imported under the pack can omit type frontmatter.+ fs.writeFileSync(+ file,+ fs.readFileSync(file, "utf8").replace(/^type: goal\n/m, ""),+ );+ const edited = await putPage.handler(ctx, {+ slug,+ content: content.replace("regularly", "daily"),+ expected_revision: first.revision,+ });+ expect(edited).toMatchObject({ state: "committed" });+ expect(+ (await engine.readPageSnapshot(slug, { sourceId: "default" }))?.page+ .type,+ ).toBe("goal");+ });+ });++ test('remote writes infer path subtypes and preserve explicit or stored subtypes', async () => {+ const packDir = path.join(tmpRoot, 'home', '.gbrain', 'schema-packs', 'meeting-test');+ fs.mkdirSync(packDir, { recursive: true });+ fs.writeFileSync(path.join(packDir, 'pack.yaml'), `api_version: gbrain-schema-pack-v1+name: meeting-test+version: 1.0.0+extends: gbrain-base-v2+page_types:+ - name: meeting+ primitive: temporal+ path_prefixes: [therapy-meetings/, meetings/]+ aliases: []+ extractable: false+ expert_routing: false+ subtypes:+ - name: therapy+ when:+ path_pattern: '^therapy-meetings/'+ - name: relationship+ when:+ path_pattern: '^relationship-meetings/'+`);+ await withEnv({ GBRAIN_SCHEMA_PACK: 'meeting-test' }, async () => {+ const ctx = makeCtx({ remote: true });+ const slug = 'therapy-meetings/session';+ const content = '---\ntitle: Session\n---\n\nFirst discussion.';+ const first = await putPage.handler(ctx, { slug, content }) as { revision: string };+ const file = path.join(brainDir, `${slug}.md`);+ expect((await engine.readPageSnapshot(slug, { sourceId: 'default' }))?.page).toMatchObject({ type: 'meeting', frontmatter: { subtype: 'therapy' } });+ expect(fs.readFileSync(file, 'utf8')).toContain('subtype: therapy');++ const unchanged = await putPage.handler(ctx, { slug, content, expected_revision: first.revision });+ expect(unchanged).toMatchObject({ state: 'committed', noop: true, revision: first.revision });++ fs.writeFileSync(file, fs.readFileSync(file, 'utf8').replace(/^subtype: therapy\n/m, ''));+ const edited = await putPage.handler(ctx, { slug, content: content.replace('First', 'Second'), expected_revision: first.revision }) as { revision: string };+ expect(edited).toMatchObject({ state: 'committed' });+ expect((await engine.readPageSnapshot(slug, { sourceId: 'default' }))?.page.frontmatter.subtype).toBe('therapy');++ const explicit = await putPage.handler(ctx, { slug, content: '---\ntitle: Session\nsubtype: relationship\n---\n\nThird discussion.', expected_revision: edited.revision }) as { revision: string };+ expect((await engine.readPageSnapshot(slug, { sourceId: 'default' }))?.page.frontmatter.subtype).toBe('relationship');+ await putPage.handler(ctx, { slug, content: content.replace('First', 'Fourth'), expected_revision: explicit.revision });+ expect((await engine.readPageSnapshot(slug, { sourceId: 'default' }))?.page.frontmatter.subtype).toBe('relationship');++ const legacySlug = 'therapy-meetings/legacy';+ const legacy = await putPage.handler(ctx, { slug: legacySlug, content: '---\ntitle: Legacy\ntype: concept\n---\n\nExisting page.' }) as { revision: string };+ await putPage.handler(ctx, { slug: legacySlug, content: '---\ntitle: Legacy\n---\n\nUpdated page.', expected_revision: legacy.revision });+ expect((await engine.readPageSnapshot(legacySlug, { sourceId: 'default' }))?.page).toMatchObject({ type: 'concept' });+ expect((await engine.readPageSnapshot(legacySlug, { sourceId: 'default' }))?.page.frontmatter.subtype).toBeUndefined();+ });+ });+test('stamps provenance frontmatter (ingested_via=put_page for local CLI)', async () => {const ctx = makeCtx({ remote: false });const result = (await putPage.handler(ctx, {diff --git a/test/schema-pack-infer-type-and-subtype.test.ts b/test/schema-pack-infer-type-and-subtype.test.tsindex dc28efcd55..f23e882013 100644--- a/test/schema-pack-infer-type-and-subtype.test.ts+++ b/test/schema-pack-infer-type-and-subtype.test.ts@@ -47,6 +47,19 @@ describe('inferTypeAndSubtypeFromPack', () => {}, { bundle: true })).toEqual({ type: 'tweet', subtype: 'bundle' });});+ it('prefers a frontmatter rule over an earlier path rule', () => {+ expect(inferTypeAndSubtypeFromPack('tweets/a.md', {+ page_types: [{+ name: 'tweet',+ path_prefixes: ['/tweets/'],+ subtypes: [+ { name: 'bundle', when: { path_pattern: '^tweets/' } },+ { name: 'single', when: { frontmatter_field: 'thread_length', frontmatter_value: 1 } },+ ],+ }],+ }, { thread_length: 1 })).toEqual({ type: 'tweet', subtype: 'single' });+ });+it('returns canonical-only when no subtype rule matches', () => {expect(inferTypeAndSubtypeFromPack('tweets/a.md', {page_types: [{