Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(put_page): warn on page types the active pack does not declare (#5880)
garrytan094d3e68041f
diff --git a/src/core/persistence/page-input.ts b/src/core/persistence/page-input.tsindex 020cb47c7f..c96e06bc13 100644--- a/src/core/persistence/page-input.ts+++ b/src/core/persistence/page-input.ts@@ -1,8 +1,8 @@import type { OperationContext } from '../ops/contract.ts';import { MAX_FILE_SIZE } from '../import-file.ts';import { parseMarkdown, serializeMarkdown } from '../markdown.ts';-import { loadActivePackForWriteVocabulary } from '../schema-pack/write-vocabulary.ts';-import { classifyStoredType, sanitizeTypeForDisplay } from '../schema-pack/type-usage.ts';+import { loadActivePackForWriteVocabulary, undeclaredPageTypeMessage, undeclaredPageTypeSuggestion } from '../schema-pack/write-vocabulary.ts';+import { classifyStoredType, safeCliToken, sanitizeTypeForDisplay } from '../schema-pack/type-usage.ts';/** Normalize model-authored types once at admission, after an existing UUID has replayed. */export async function normalizeSubagentPageInput(ctx: OperationContext, intent: Record<string, unknown>): Promise<void> {@@ -21,3 +21,38 @@ export async function normalizeSubagentPageInput(ctx: OperationContext, intent:ctx.logger.warn(`undeclared type '${sanitizeTypeForDisplay(parsed.type)}' normalized to 'note' `+ `(legacy_type kept; pack ${pack.manifest.name})`);}++export interface PageTypeWarning {+ code: 'page_type_undeclared';+ type: string;+ pack: string;+ cause: string;+ fix: string;+ docs: string;+}++/**+ * #5880: put_page stores an explicit type the write source's active pack+ * neither declares nor aliases as-is (warn, never reject); the caller gets+ * this warning in the committed result and on its logger.+ */+export async function undeclaredPageTypeWarning(ctx: OperationContext, intent: Record<string, unknown>, sourceId: string): Promise<PageTypeWarning | null> {+ if (typeof intent.content !== 'string' || typeof intent.slug !== 'string') return null;+ let parsed: ReturnType<typeof parseMarkdown>;+ try { parsed = parseMarkdown(intent.content, `${intent.slug}.md`); }+ catch { return null; }+ if (parsed.typeExplicit !== true) return null;+ const pack = await loadActivePackForWriteVocabulary({ engine: ctx.engine, remote: ctx.remote, sourceId });+ if (!pack || classifyStoredType(parsed.type, pack.manifest).kind !== 'undeclared') return null;+ const type = sanitizeTypeForDisplay(parsed.type);+ const warning: PageTypeWarning = {+ code: 'page_type_undeclared',+ type,+ pack: pack.manifest.name,+ cause: `${undeclaredPageTypeMessage(type, pack, 'put_page')} The page was stored with this type as-is.`,+ fix: `${undeclaredPageTypeSuggestion(pack)} To declare it: gbrain schema add-type ${safeCliToken(parsed.type) ?? '<type>'} (with its primitive and prefix)`,+ docs: 'docs/architecture/schema-packs.md#undeclared-page-types',+ };+ ctx.logger.warn(`[${warning.code}] ${warning.cause} ${warning.fix}`);+ return warning;+}diff --git a/src/core/persistence/page-mutations.ts b/src/core/persistence/page-mutations.tsindex 64e361505d..ad0b06c4d3 100644--- a/src/core/persistence/page-mutations.ts+++ b/src/core/persistence/page-mutations.ts@@ -17,7 +17,7 @@ import { claimWorktree, getWorktreeBinding } from './ownership.ts';import { parseMutationPrecondition } from './preconditions.ts';import { assertPurgeParams } from './purge-params.ts';import type { Principal } from './model.ts';-import { normalizeSubagentPageInput } from './page-input.ts';+import { normalizeSubagentPageInput, undeclaredPageTypeWarning } from './page-input.ts';import { assertKnowledgePublicationAllowed } from '../shared-skills/knowledge-guard.ts';import { isUnboundSourcePage, readUnboundWritePolicy, unboundSourceError } from './unbound-source.ts';import { colonSlugWindowsRefusal, isWindowsColonTarget } from './native-file-target.ts';@@ -110,6 +110,8 @@ export async function submitPageMutation(ctx: OperationContext,? await (await import('./takes-prepare.ts')).normalizeTakesIntent(ctx,p) : { ...p };delete intent.request_id;if (input.operation === 'put_page') await normalizeSubagentPageInput(ctx, intent);+ const typeWarning = input.operation === 'put_page' && input.managedFileImport !== true+ ? await undeclaredPageTypeWarning(ctx, { ...intent, slug }, sourceId) : null;if (input.operation === 'capture') {if (typeof p.content !== 'string' || !normalizeForHash(p.content) || detectBinaryNullByte(Buffer.from(p.content)) !== -1) {throw new OperationError('invalid_params', 'Capture requires nonempty text without binary NUL bytes.');@@ -196,5 +198,6 @@ export async function submitPageMutation(ctx: OperationContext,const row = await admitWrite(ctx.engine, { principal, operation: input.operation, sourceId, sourceIncarnation: source.incarnation,slug, pageId: snapshot?.page.id ?? null, requestId, callerIntent, intent, authority,worktreeId: writeThrough ? binding?.worktree_id : null, topologyGeneration: writeThrough ? binding?.topology_generation : null });- return writeResponse(await waitForWrite(ctx.engine, row, ctx.config, input.waitMs));+ const response = writeResponse(await waitForWrite(ctx.engine, row, ctx.config, input.waitMs));+ return typeWarning ? { ...response, type_warning: typeWarning } : response;}diff --git a/test/put-page-type-warning.test.ts b/test/put-page-type-warning.test.tsnew file mode 100644index 0000000000..c7c7f26bf0--- /dev/null+++ b/test/put-page-type-warning.test.ts@@ -0,0 +1,102 @@+/**+ * #5880 — put_page warns (never rejects) when its explicit page type is not+ * declared by the write source's active schema pack. Pre-fix an ordinary+ * put_page (MCP, `gbrain put`, `gbrain call put_page`) stored any type+ * silently, while capture rejected it and subagent writes normalized it.+ * The committed result now carries `type_warning` (stable code, cause, fix,+ * docs) and the caller's logger gets the same line; the page is still+ * stored as written.+ */+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+import { mkdtempSync, rmSync } from 'node:fs';+import { join } from 'node:path';+import { tmpdir } from 'node:os';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { operations, type OperationContext } from '../src/core/operations.ts';+import { withEnv } from './helpers/with-env.ts';+import { resetPgliteState } from './helpers/reset-pglite.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { _resetPackCacheForTests } from '../src/core/schema-pack/registry.ts';+import { configureGateway, resetGateway, __setEmbedTransportForTests } from '../src/core/ai/gateway.ts';++const home = mkdtempSync(join(tmpdir(), 'gbrain-5880-'));+const put = operations.find((o) => o.name === 'put_page')!;+let engine: PGLiteEngine;++beforeAll(async () => {+ configureGateway({+ embedding_model: 'openai:text-embedding-3-large',+ embedding_dimensions: 1536,+ env: { ...process.env, OPENAI_API_KEY: process.env.OPENAI_API_KEY || 'sk-test-stub' },+ });+ __setEmbedTransportForTests(async ({ values }: any) => ({+ embeddings: values.map(() => new Array(1536).fill(0)),+ usage: { tokens: 0 },+ }) as any);+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+});++afterAll(async () => {+ await disposePersistenceConsumer(engine);+ await engine.disconnect();+ rmSync(home, { recursive: true, force: true });+ __setEmbedTransportForTests(null);+ resetGateway();+});++beforeEach(async () => {+ await disposePersistenceConsumer(engine);+ await resetPgliteState(engine);+ _resetPackCacheForTests();+ await engine.setConfig('schema_pack', 'gbrain-base-v2');+});++function ctxWithLog(remote: boolean, warns: string[]): OperationContext {+ return {+ engine,+ config: { engine: 'pglite' as const, embedding_disabled: true },+ logger: { info: () => {}, warn: (m: string) => { warns.push(m); }, error: () => {} },+ dryRun: false,+ remote,+ sourceId: 'default',+ } as OperationContext;+}++const putPage = (ctx: OperationContext, slug: string, type: string) =>+ withEnv({ GBRAIN_HOME: home, GBRAIN_SCHEMA_PACK: undefined }, () => put.handler(ctx, {+ slug,+ content: `---\ntype: ${type}\ntitle: Example\n---\n\nBody text.`,+ })) as Promise<Record<string, any>>;++describe('#5880 put_page undeclared type warning', () => {+ test('trusted local write: stored as-is, result + logger carry page_type_undeclared', async () => {+ const warns: string[] = [];+ const result = await putPage(ctxWithLog(false, warns), 'notes/undeclared-local', 'meeting-transcript');+ expect(result.type_warning).toMatchObject({+ code: 'page_type_undeclared',+ type: 'meeting-transcript',+ pack: 'gbrain-base-v2',+ docs: 'docs/architecture/schema-packs.md#undeclared-page-types',+ });+ expect(result.type_warning.fix).toContain('gbrain schema add-type meeting-transcript');+ expect(warns.some((w) => w.includes('page_type_undeclared') && w.includes('meeting-transcript'))).toBe(true);+ const [row] = await engine.executeRaw<{ type: string }>(`SELECT type FROM pages WHERE slug = 'notes/undeclared-local'`);+ expect(row.type).toBe('meeting-transcript');+ });++ test('remote (MCP) write gets the same warning', async () => {+ const result = await putPage(ctxWithLog(true, []), 'notes/undeclared-remote', 'banana');+ expect(result.type_warning?.code).toBe('page_type_undeclared');+ });++ test('declared types and aliases do not warn', async () => {+ const warns: string[] = [];+ const declared = await putPage(ctxWithLog(false, warns), 'notes/declared', 'note');+ const alias = await putPage(ctxWithLog(false, warns), 'notes/alias', 'memo');+ expect(declared.type_warning).toBeUndefined();+ expect(alias.type_warning).toBeUndefined();+ expect(warns.filter((w) => w.includes('page_type_undeclared'))).toEqual([]);+ });+});