Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(put_page): refuse new .md/.mdx-suffixed slugs instead of writing foo.md.md (#4807)
time-attack720b33ed01e3
diff --git a/src/core/import-file.ts b/src/core/import-file.tsindex a56473a683..5968cfd44a 100644--- a/src/core/import-file.ts+++ b/src/core/import-file.ts@@ -1,4 +1,5 @@import { assertUnmanagedCanonicalWriter } from './persistence/maintenance.ts';+import { suffixedFrontmatterSlugHold } from './persistence/suffixed-slug.ts';import { maintenanceTransaction } from './persistence/attribution.ts';import { assertImportBase, sameCanonicalImport, sameContentAnyKeyOrder } from './page-state/import-guard.ts';import { stabilizeSafetyAssessments } from './persistence/reconcile-safety.ts';@@ -1252,6 +1253,8 @@ export async function importFromFile(}}+ const suffixHold = usedFrontmatterFallback ? await suffixedFrontmatterSlugHold(engine, opts.sourceId, relativePath, resolvedSlug) : null;+ if (suffixHold) return { slug: expectedSlug, status: 'skipped', chunks: 0, error: suffixHold.message, refusal: suffixHold, skip_reason: suffixHold.code };// Emit the dual-channel audit entry AFTER we know we're not going to// short-circuit, so we don't log noise for failed imports.if (usedFrontmatterFallback) {diff --git a/src/core/ops/pages.ts b/src/core/ops/pages.tsindex 10f9918e56..1b00f663b0 100644--- a/src/core/ops/pages.ts+++ b/src/core/ops/pages.ts@@ -1,4 +1,5 @@import { pageMutationSource, submitPageMutation } from '../persistence/page-mutations.ts';+import { suffixedSlugDryRun } from '../persistence/suffixed-slug.ts';import { PAGE_MUTATION_PARAMS, CAPTURE_EVENT_PARAMS, WRITE_WAIT_PARAM } from '../persistence/params.ts';import { assertPurgeParams } from '../persistence/purge-params.ts';/**@@ -315,6 +316,7 @@ const put_page: Operation = {validatePageSlug(p.slug);enforceClientSlugFence(ctx, p.slug, 'put_page');enforceSubagentSlugFence(ctx, p.slug, 'put_page');+ await suffixedSlugDryRun(ctx, sourceId, p.slug);}return { dry_run: true, action: 'put_page', slug: p.slug };}diff --git a/src/core/persistence/page-mutations.ts b/src/core/persistence/page-mutations.tsindex 2c0884154f..7cafb9e477 100644--- a/src/core/persistence/page-mutations.ts+++ b/src/core/persistence/page-mutations.ts@@ -4,6 +4,7 @@ import { isAbsolute, join, relative, resolve, sep } from 'node:path';import type { OperationContext } from '../ops/contract.ts';import { OperationError } from '../ops/contract.ts';import { enforceClientSlugFence, enforceSubagentSlugFence, normalizeSlugPrefix, parseSourceIdParam, requireWritablePage, validatePageSlug } from '../ops/context.ts';+import { suffixedSlugAdmission } from './suffixed-slug.ts';import { defaultSlug, detectBinaryNullByte, explicitCaptureType, mergeCaptureFrontmatter, normalizeForHash } from '../capture-content.ts';import { computeContentHash } from '../ingestion/types.ts';import { resolveSlugForPath } from '../sync.ts';@@ -151,7 +152,7 @@ export async function submitPageMutation(ctx: OperationContext,if (prepared.prior) return pendingAwareResponse(ctx, await waitForWrite(ctx.engine, prepared.prior, ctx.config, waitMs()));const row = await admitWrite(ctx.engine, prepared.admission);const response = pendingAwareResponse(ctx, await waitForWrite(ctx.engine, row, ctx.config, waitMs()));- return prepared.typeWarning ? { ...response, type_warning: prepared.typeWarning } : response;+ return { ...response, ...(prepared.typeWarning ? { type_warning: prepared.typeWarning } : {}), ...(prepared.slugAdvisory ? { slug_advisory: prepared.slugAdvisory } : {}) };}/**@@ -161,7 +162,7 @@ export async function submitPageMutation(ctx: OperationContext,*/export async function preparePageAdmission(ctx: OperationContext,input: { operation: string; params: Record<string, unknown>; managedFileImport?: true; batch?: PageBatchMember }-): Promise<{ prior: WriteRequest; admission?: undefined; typeWarning?: undefined } | { prior?: undefined; admission: WriteAdmission; typeWarning: PageTypeWarning | null }> {+): Promise<{ prior: WriteRequest; admission?: undefined; typeWarning?: undefined; slugAdvisory?: undefined } | { prior?: undefined; admission: WriteAdmission; typeWarning: PageTypeWarning | null; slugAdvisory: string | null }> {if (input.operation === 'put_page' && ['kind', 'preview', 'backup_reference'].some(key => Object.hasOwn(input.params, key))) {if (ctx.remote !== false || input.managedFileImport !== true || !OWNER_FILE_INTENTS.has(String(input.params.kind)) ||['preview', 'backup_reference'].some(key => Object.hasOwn(input.params, key))) {@@ -238,6 +239,8 @@ export async function preparePageAdmission(ctx: OperationContext,const authority = await submissionAuthority(ctx, input.operation, sourceId, source.incarnation, slug);await assertKnowledgePublicationAllowed(ctx.engine, { source_id: sourceId, source_incarnation: source.incarnation, slug });const snapshot = await ctx.engine.readPageSnapshot(slug, { sourceId, includeDeleted: true });+ const slugAdvisory = input.operation === 'put_page' && input.managedFileImport !== true+ ? suffixedSlugAdmission(ctx, slug, !!snapshot && !snapshot.page.deleted_at) : null;// #5616: typed edit refusals before admission; publication repeats them on the locked snapshot.if (input.operation === 'edit_page') {const { applyPageEdits, assertEditRevision, parsePageEdits } = await import('./page-edit.ts');@@ -292,7 +295,7 @@ export async function preparePageAdmission(ctx: OperationContext,&& !publishesDatabaseOnly(join(binding.local_path, binding.relative_path), slug, snapshot)) {throw colonSlugWindowsRefusal(slug, sourceId);}- return { typeWarning, admission: { principal, operation: input.operation, sourceId, sourceIncarnation: source.incarnation,+ return { typeWarning, slugAdvisory, admission: { principal, operation: input.operation, sourceId, sourceIncarnation: source.incarnation,slug, pageId: snapshot?.page.id ?? null, requestId, callerIntent, intent, authority,...(input.operation === 'edit_page' ? { terminalReservation: Math.max(16_384, Buffer.byteLength(JSON.stringify(authority)) + 8192)+ (await import('./page-edit.ts')).EDIT_PAGE_RECEIPT_RESERVE } : {}),diff --git a/src/core/persistence/suffixed-slug.ts b/src/core/persistence/suffixed-slug.tsnew file mode 100644index 0000000000..2a9776742c--- /dev/null+++ b/src/core/persistence/suffixed-slug.ts@@ -0,0 +1,73 @@+/**+ * put_page admission for slugs that end in `.md`/`.mdx` (#4807, E-D17).+ *+ * A page is stored at `<slug>.md`, so a new `notes/foo.md` page would land on+ * disk as `notes/foo.md.md`: reported as written, invisible to the file the+ * caller meant, and re-imported by sync under the same suffixed slug. A new+ * suffixed slug is refused with the bare slug as the recovery. A live page+ * that already has the exact suffixed `(source_id, slug)` identity (written+ * before this check) stays updatable, so its chunks and deep-research id keep+ * working; the response carries an advisory naming the bare slug and the+ * manual move, since master has no rename operation. A file import that takes+ * its identity from a frontmatter `slug:` follows the same rule through the+ * held-file path; path-derived import slugs, `validateSlug` and every internal+ * stored-identity reader are unchanged.+ */+import type { BrainEngine } from '../engine.ts';+import type { ContentRefusal } from '../import-screen.ts';+import { opError, type OperationContext, type OperationError } from '../ops/contract.ts';+import { opTransport, readFix } from '../ops/op-fix.ts';++const MARKDOWN_SUFFIX = /(\.mdx?)+$/i;++/** The slug without its trailing markdown extensions, or null when it has none. */+export function bareSlugOf(slug: string): string | null {+ return MARKDOWN_SUFFIX.test(slug) ? slug.replace(MARKDOWN_SUFFIX, '') : null;+}++function refusal(ctx: OperationContext, bare: string): OperationError {+ const cli = opTransport(ctx) === 'cli';+ return opError('invalid_params', 'put_page slugs must not end in .md or .mdx.',+ cli ? `Write the page as ${bare}: gbrain put ${bare} (the .md file name is added for you).`+ : `Call put_page again with slug "${bare}" and the same content (the .md file name is added for you).`, {+ why: 'A page is stored at <slug>.md, so a slug ending in .md would create a second extension on disk (<slug>.md.md) that the intended file never sees.',+ fix: {+ ...readFix('Checks whether the bare slug already holds a page before writing it there.',+ { argv: ['gbrain', 'get', bare], mcp: { tool: 'get_page', arguments: { slug: bare } } }),+ verify: { argv: ['gbrain', 'get', bare], mcp: { tool: 'get_page', arguments: { slug: bare } } },+ },+ });+}++/**+ * Refuses a new suffixed slug; for a live exact-identity page returns the+ * advisory to attach to the response. Null for every other slug.+ */+export function suffixedSlugAdmission(ctx: OperationContext, slug: string, liveExactRow: boolean): string | null {+ const bare = bareSlugOf(slug);+ if (bare === null) return null;+ if (!liveExactRow) throw refusal(ctx, bare);+ return `This page's slug ends in .md, which new pages cannot use. To move it, put_page its content under "${bare}", then delete_page "${slug}".`;+}+++async function liveExactRow(engine: BrainEngine, sourceId: string, slug: string): Promise<boolean> {+ const snapshot = await engine.readPageSnapshot(slug, { sourceId, includeDeleted: true });+ return !!snapshot && !snapshot.page.deleted_at;+}++/** Dry-run form: reads the exact `(source_id, slug)` row itself. */+export async function suffixedSlugDryRun(ctx: OperationContext, sourceId: string, slug: string): Promise<void> {+ if (bareSlugOf(slug) === null) return;+ suffixedSlugAdmission(ctx, slug, await liveExactRow(ctx.engine, sourceId, slug.toLowerCase()));+}++/**+ * The hold for a file import whose frontmatter `slug:` ends in `.md`/`.mdx`+ * and names no live page. The message names the file, never the declared value.+ */+export async function suffixedFrontmatterSlugHold(engine: BrainEngine, sourceId: string | undefined, relativePath: string, slug: string): Promise<ContentRefusal | null> {+ if (bareSlugOf(slug) === null || await liveExactRow(engine, sourceId ?? 'default', slug)) return null;+ return { code: 'frontmatter_slug_conflict', key: 'slug',+ message: `The frontmatter slug of ${relativePath} must not end in .md or .mdx: a page is stored at <slug>.md, so it would create a second extension on disk. Remove the extension from the "slug:" line, or remove the line.` };+}diff --git a/test/ingestion/put-page-write-through.test.ts b/test/ingestion/put-page-write-through.test.tsindex 29cdb0d18a..103348492d 100644--- a/test/ingestion/put-page-write-through.test.ts+++ b/test/ingestion/put-page-write-through.test.ts@@ -587,3 +587,108 @@ describe('put_page write-through — failure isolation', () => {expect(page).toBeNull();});});++// ── #4807 (E-D17): put_page refuses a new .md/.mdx-suffixed slug ─────────────++describe('put_page suffixed slugs (#4807)', () => {+ const content = '---\ntitle: Report\n---\n\nreport body';+ async function writeRequests(): Promise<number> {+ const [row] = await engine.executeRaw<{ n: number }>('SELECT COUNT(*)::int AS n FROM persistence_requests');+ return Number(row!.n);+ }+ async function refusalOf(promise: Promise<unknown>): Promise<OperationError> {+ try { await promise; } catch (error) { return error as OperationError; }+ throw new Error('expected a refusal');+ }++ test('a new suffixed slug is refused before admission: no row, no receipt, no file (x.md.md or x.md)', async () => {+ const before = await writeRequests();+ for (const slug of ['inbox/report.md', 'Inbox/Report.MD', 'inbox/report.md.mdx']) {+ const error = await refusalOf(putPage.handler(makeCtx(), { slug, content }));+ expect(error).toBeInstanceOf(OperationError);+ expect(error.code).toBe('invalid_params');+ expect(error.message).toBe('put_page slugs must not end in .md or .mdx.');+ expect(error.suggestion).toBe('Write the page as inbox/report: gbrain put inbox/report (the .md file name is added for you).');+ }+ expect(await writeRequests()).toBe(before);+ expect(await engine.getPage('inbox/report.md', { sourceId: 'default' })).toBeNull();+ expect(fs.existsSync(path.join(brainDir, 'inbox/report.md.md'))).toBe(false);+ expect(fs.existsSync(path.join(brainDir, 'inbox/report.md'))).toBe(false);+ });++ test('dry-run refuses the same way, and the corrected bare slug then writes inbox/report.md', async () => {+ const error = await refusalOf(putPage.handler(makeCtx({ dryRun: true }), { slug: 'inbox/report.md', content }));+ expect(error.code).toBe('invalid_params');+ const result = (await putPage.handler(makeCtx(), { slug: 'inbox/report', content })) as { slug_advisory?: string; write_through?: { written: boolean } };+ expect(result.write_through?.written).toBe(true);+ expect(result.slug_advisory).toBeUndefined();+ expect(fs.readFileSync(path.join(brainDir, 'inbox/report.md'), 'utf8')).toContain('report body');+ });++ test('rendered contract: CLI and MCP envelopes carry why, a read-only get_page fix and verify on the bare slug', async () => {+ const { toAgentError, cliRenderContext } = await import('../../src/core/agent-output.ts');+ const cli = toAgentError(await refusalOf(putPage.handler(makeCtx(), { slug: 'inbox/report.md', content })),+ { transport: 'cli', command: 'put', render: cliRenderContext() });+ expect(cli).toMatchObject({ code: 'invalid_params', class: 'caller', contract_version: 1 });+ expect(cli.why).toContain('<slug>.md.md');+ expect(cli.fix).toMatchObject({ argv: ['gbrain', 'get', 'inbox/report'], next: 'run', verify: { argv: ['gbrain', 'get', 'inbox/report'] } });+ const remote = await refusalOf(putPage.handler(makeCtx({ remote: true }), { slug: 'inbox/report.md', content }));+ expect(remote.suggestion).toBe('Call put_page again with slug "inbox/report" and the same content (the .md file name is added for you).');+ expect(remote.fix?.mcp).toEqual({ tool: 'get_page', arguments: { slug: 'inbox/report' } });+ });++ test('a live exact foo.md row (chunks, deep-research id) still updates, keeps its id and gets the move advisory; its bare twin is untouched', async () => {+ const { encodeDeepResearchId, decodeDeepResearchId } = await import('../../src/core/deep-research-id.ts');+ const legacy = 'notes/legacy.md';+ await engine.putPage(legacy, { type: 'note', title: 'Legacy', compiled_truth: 'old legacy body', timeline: '' }, { sourceId: 'default' });+ await engine.putPage('notes/legacy', { type: 'note', title: 'Twin', compiled_truth: 'bare twin body', timeline: '' }, { sourceId: 'default' });+ await engine.upsertChunks(legacy, [{ chunk_index: 0, chunk_text: 'old legacy body', chunk_source: 'compiled_truth' }], { sourceId: 'default' });+ const before = (await engine.getPage(legacy, { sourceId: 'default' }))!;+ const chunkText = async () => (await engine.executeRaw<{ t: string }>(+ "SELECT c.chunk_text AS t FROM content_chunks c JOIN pages p ON p.id = c.page_id WHERE p.slug = 'notes/legacy.md' AND p.source_id = 'default'")).map(r => r.t).join(' ');+ expect(await chunkText()).toContain('old legacy body');++ const snapshot = (await engine.readPageSnapshot(legacy, { sourceId: 'default' }))!;+ fs.mkdirSync(path.join(brainDir, 'notes'), { recursive: true });+ fs.writeFileSync(path.join(brainDir, `${legacy}.md`), serializePageToMarkdown(snapshot.page, snapshot.tags));+ const revision = snapshot.revision;+ const result = (await putPage.handler(makeCtx(), { slug: legacy, content: '---\ntitle: Legacy\n---\n\nnew legacy body', expected_revision: revision })) as { slug_advisory?: string };+ expect(result.slug_advisory).toBe('This page\'s slug ends in .md, which new pages cannot use. To move it, put_page its content under "notes/legacy", then delete_page "notes/legacy.md".');+ const after = (await engine.getPage(legacy, { sourceId: 'default' }))!;+ expect(after.id).toBe(before.id);+ expect(after.compiled_truth).toContain('new legacy body');+ expect(await chunkText()).toContain('new legacy body');+ const id = encodeDeepResearchId('default', legacy);+ expect(decodeDeepResearchId(id)).toEqual({ sourceId: 'default', slug: legacy });+ const fetchOp = operations.find(o => o.name === 'fetch')!;+ const fetched = (await fetchOp.handler(makeCtx(), { id })) as { id: string; text: string };+ expect(fetched.text).toContain('new legacy body');+ expect((await engine.getPage('notes/legacy', { sourceId: 'default' }))!.compiled_truth).toContain('bare twin body');+ });++ test('a soft-deleted foo.md row does not count as live: re-creating it is refused', async () => {+ await engine.putPage('notes/gone.md', { type: 'note', title: 'Gone', compiled_truth: 'gone', timeline: '' }, { sourceId: 'default' });+ await engine.executeRaw("UPDATE pages SET deleted_at = now() WHERE slug = 'notes/gone.md'");+ const error = await refusalOf(putPage.handler(makeCtx(), { slug: 'notes/gone.md', content }));+ expect(error.code).toBe('invalid_params');+ });+});++describe('file import with a .md-suffixed frontmatter slug (#4807)', () => {+ test('a frontmatter slug ending in .md that names no live page is held with the same rule; an existing exact row imports', async () => {+ const { importFile } = await import('../../src/core/import-file.ts');+ const file = path.join(brainDir, 'notes', 'held.md');+ fs.mkdirSync(path.dirname(file), { recursive: true });+ fs.writeFileSync(file, '---\ntitle: Held\nslug: notes/held.md\n---\n\nheld body');+ const held = await importFile(engine, file, 'notes/held.md', { noEmbed: true, sourceId: 'default' });+ expect(held).toMatchObject({ status: 'skipped', skip_reason: 'frontmatter_slug_conflict', refusal: { code: 'frontmatter_slug_conflict', key: 'slug' } });+ expect(held.error).toContain('must not end in .md or .mdx');+ expect(held.error).not.toContain('slug: notes/held.md');+ expect(await engine.getPage('notes/held.md', { sourceId: 'default' })).toBeNull();++ await engine.putPage('notes/held.md', { type: 'note', title: 'Held', compiled_truth: 'legacy', timeline: '' }, { sourceId: 'default' });+ const imported = await importFile(engine, file, 'notes/held.md', { noEmbed: true, sourceId: 'default' });+ expect(imported.status).toBe('imported');+ expect(imported.slug).toBe('notes/held.md');+ });+});diff --git a/test/loops-extract-run.serial.test.ts b/test/loops-extract-run.serial.test.tsindex 2679be4ecb..e7550e3655 100644--- a/test/loops-extract-run.serial.test.ts+++ b/test/loops-extract-run.serial.test.ts@@ -57,8 +57,8 @@ const { normalizeAlias } = await import('../src/core/search/alias-normalize.ts')const { MinionQueue } = await import('../src/core/minions/queue.ts');const SRC = 'g1';-const EMAIL_SLUG = 'emails/2026/08/2026-08-20-test-thread-abcd1234.md';-const SUPPRESSED_SLUG = 'emails/2026/08/2026-08-20-suppressed-thread-efab5678.md';+const EMAIL_SLUG = 'emails/2026/08/2026-08-20-test-thread-abcd1234';+const SUPPRESSED_SLUG = 'emails/2026/08/2026-08-20-suppressed-thread-efab5678';const THREAD_ID = 'thread-abcd1234';const SUPPRESSED_THREAD_ID = 'thread-efab5678';const PERSON_SLUG = 'people/alice-example';@@ -225,7 +225,7 @@ describe('runLoopsExtract', () => {// the extraction sail through to the model. The rendered thread page// carries every SENDER (`senders`, the message authors); all of them// gate the lane.- const slug = 'emails/2026/08/2026-08-24-earlier-muted-77665544.md';+ const slug = 'emails/2026/08/2026-08-24-earlier-muted-77665544';await engine.putPage(slug,{@@ -277,7 +277,7 @@ describe('runLoopsExtract', () => {// thread she was CC'd on, and an outside sender could dodge extraction by// CC'ing a known-muted address. Only addresses that AUTHORED a message// count.- const slug = 'emails/2026/08/2026-08-25-muted-cc-only-88776655.md';+ const slug = 'emails/2026/08/2026-08-25-muted-cc-only-88776655';await engine.putPage(slug,{@@ -479,7 +479,7 @@ describe('runLoopsExtract', () => {});test('prompt hardening: newest 12k is retained and sanitized; stale head is dropped', async () => {- const slug = 'emails/2026/08/2026-08-22-injection-thread-99887766.md';+ const slug = 'emails/2026/08/2026-08-22-injection-thread-99887766';// 'ignore previous instructions' matches sanitize.ts's 'ignore-prior'// pattern (replacement '[redacted]'). The old head marker is pushed out// while the newest evidence remains inside the 12k payload.@@ -519,7 +519,7 @@ describe('runLoopsExtract', () => {});test('counterparty without a person page: loop still lands, no edge is written', async () => {- const slug = 'emails/2026/08/2026-08-21-bob-thread-ef567890.md';+ const slug = 'emails/2026/08/2026-08-21-bob-thread-ef567890';await engine.putPage(slug,{@@ -578,7 +578,7 @@ describe('runLoopsExtract', () => {});test('verbatim evidence: a fabricated quote is BLANKED (loop lands, edge label falls back to text); a genuine quote survives whitespace-normalized', async () => {- const slug = 'emails/2026/08/2026-08-23-verbatim-thread-11223344.md';+ const slug = 'emails/2026/08/2026-08-23-verbatim-thread-11223344';await engine.putPage(slug,{diff --git a/test/ops-loops.test.ts b/test/ops-loops.test.tsindex d1e7989704..fe01e42059 100644--- a/test/ops-loops.test.ts+++ b/test/ops-loops.test.ts@@ -271,7 +271,7 @@ describe('open_loops grouped', () => {});describe('open_loops deep links + context (trusted local)', () => {- const EMAIL_SLUG = 'emails/2026/08/2026-08-20-plan-review-abcd1234.md';+ const EMAIL_SLUG = 'emails/2026/08/2026-08-20-plan-review-abcd1234';test('deep_link regenerates from the page account + hex message-id evidence', async () => {// The thread page carries the account in frontmatter; the loop points atdiff --git a/test/utils.test.ts b/test/utils.test.tsindex 568e9a2070..e77ca3a426 100644--- a/test/utils.test.ts+++ b/test/utils.test.ts@@ -25,6 +25,11 @@ describe('validateSlug', () => {test('rejects leading slash', () => {expect(() => validateSlug('/absolute/path')).toThrow('start with /');});++ test('keeps a stored .md suffix: legacy identities are refused for new pages at put_page, never renamed here (#4807)', () => {+ expect(validateSlug('notes/foo.md')).toBe('notes/foo.md');+ expect(validateSlug('Notes/Foo.MDX')).toBe('notes/foo.mdx');+ });});describe('contentHash', () => {