🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
🐛 fix(documents): strip leading body H1 and pasted skill frontmatter on save (#20543)
Arvin Xu1752cc486499
diff --git a/apps/server/src/services/agentDocuments/index.test.ts b/apps/server/src/services/agentDocuments/index.test.tsindex 15ba663799c..b5619a2e38d 100644--- a/apps/server/src/services/agentDocuments/index.test.ts+++ b/apps/server/src/services/agentDocuments/index.test.ts@@ -6,11 +6,8 @@ import { createHeadlessEditor } from '@lobehub/editor/headless';import { beforeEach, describe, expect, it, vi } from 'vitest';import { AgentModel } from '@/database/models/agent';-import {- AgentDocumentModel,- buildDocumentFilename,- extractMarkdownH1Title,-} from '@/database/models/agentDocuments';+import type * as AgentDocumentsModels from '@/database/models/agentDocuments';+import { AgentDocumentModel, buildDocumentFilename } from '@/database/models/agentDocuments';import { AgentSkillModel } from '@/database/models/agentSkill';import { FileModel } from '@/database/models/file';import { TopicDocumentModel } from '@/database/models/topicDocument';@@ -26,14 +23,16 @@ const headlessEditorMocks = vi.hoisted(() => ({applyLiteXMLBatch: vi.fn(),}));-vi.mock('@/database/models/agentDocuments', () => ({+vi.mock('@/database/models/agentDocuments', async (importOriginal) => ({+ // Spread the real module so pure helpers (e.g. extractMarkdownH1Title) keep+ // their production behavior while the model classes stay mocked.+ ...(await importOriginal<typeof AgentDocumentsModels>()),AgentDocumentModel: vi.fn(),DocumentLoadPosition: {BEFORE_FIRST_USER: 'before_first_user',},buildDocumentFilename: vi.fn(),deriveAgentDocumentFields: vi.fn(() => ({})),- extractMarkdownH1Title: vi.fn((content: string) => ({ content })),}));vi.mock('@/database/models/agent', () => ({@@ -178,7 +177,6 @@ describe('AgentDocumentsService', () => {return mockTopicDocumentModel;});vi.mocked(buildDocumentFilename).mockImplementation((title: string) => title);- vi.mocked(extractMarkdownH1Title).mockImplementation((content: string) => ({ content }));});describe('createDocument', () => {@@ -281,23 +279,22 @@ describe('AgentDocumentsService', () => {expect(mockModel.create).not.toHaveBeenCalled();});- it('keeps the explicit title and the H1 body line when they differ', async () => {- vi.mocked(extractMarkdownH1Title).mockReturnValueOnce({- content: 'body',- title: 'FASE G-2D — INFORME DE CIERRE',- });+ it('removes a leading H1 even when it differs from the explicit title', async () => {mockModel.findByParentAndFilename.mockResolvedValue(undefined);mockModel.create.mockResolvedValue({ id: 'new-doc', filename: 'G-2D-CIERRE-20260922-1101' });const service = new AgentDocumentsService(db, userId);- const content = '# FASE G-2D — INFORME DE CIERRE\n\nbody';- await service.createDocument('agent-1', 'G-2D-CIERRE-20260922-1101', content);+ await service.createDocument(+ 'agent-1',+ 'G-2D-CIERRE-20260922-1101',+ '# FASE G-2D — INFORME DE CIERRE\n\nbody',+ );expect(vi.mocked(buildDocumentFilename)).toHaveBeenCalledWith('G-2D-CIERRE-20260922-1101');expect(mockModel.create).toHaveBeenCalledWith('agent-1','G-2D-CIERRE-20260922-1101',- content,+ 'body',{editorData: { root: { children: [] } },title: 'G-2D-CIERRE-20260922-1101',@@ -308,10 +305,6 @@ describe('AgentDocumentsService', () => {it('names the document from its H1 when the tool call omits the title', async () => {// Seen in production after #19969: a model sent only `content`, and// `title.trim()` threw "Cannot read properties of undefined (reading 'trim')".- vi.mocked(extractMarkdownH1Title).mockReturnValueOnce({- content: 'body',- title: 'Research Notes V2',- });mockModel.findByParentAndFilename.mockResolvedValue(undefined);mockModel.create.mockResolvedValue({ id: 'new-doc', filename: 'Research Notes V2' });@@ -329,10 +322,6 @@ describe('AgentDocumentsService', () => {});it('strips an H1 that duplicates the explicit title', async () => {- vi.mocked(extractMarkdownH1Title).mockReturnValueOnce({- content: 'body',- title: 'My Title',- });mockModel.findByParentAndFilename.mockResolvedValue(undefined);mockModel.create.mockResolvedValue({ id: 'new-doc', filename: 'My Title' });@@ -345,11 +334,56 @@ describe('AgentDocumentsService', () => {});});- it('falls back to the H1 as the title when no title is given', async () => {- vi.mocked(extractMarkdownH1Title).mockReturnValueOnce({- content: 'body',- title: 'My Title',+ it('strips a near-duplicate H1 when the title carries a suffix', async () => {+ mockModel.findByParentAndFilename.mockResolvedValue(undefined);+ mockModel.create.mockResolvedValue({ id: 'new-doc', filename: '任务验证未通过汇总' });++ const service = new AgentDocumentsService(db, userId);+ await service.createDocument(+ 'agent-1',+ '任务验证未通过汇总(T-77-T-312)',+ '# 任务验证未通过汇总\n\nbody',+ );++ expect(mockModel.create).toHaveBeenCalledWith(+ 'agent-1',+ '任务验证未通过汇总(T-77-T-312)',+ 'body',+ {+ editorData: { root: { children: [] } },+ title: '任务验证未通过汇总(T-77-T-312)',+ },+ );+ });++ it('removes a leading H1 that differs from the explicit title', async () => {+ mockModel.findByParentAndFilename.mockResolvedValue(undefined);+ mockModel.create.mockResolvedValue({ id: 'new-doc', filename: 'Doc' });++ const service = new AgentDocumentsService(db, userId);+ await service.createDocument('agent-1', 'Doc', '# 一、总体结论\n\nbody');++ expect(mockModel.create).toHaveBeenCalledWith('agent-1', 'Doc', 'body', {+ editorData: { root: { children: [] } },+ title: 'Doc',});+ });++ it('keeps H1 headings that appear after other body content', async () => {+ mockModel.findByParentAndFilename.mockResolvedValue(undefined);+ mockModel.create.mockResolvedValue({ id: 'new-doc', filename: 'Doc' });++ const service = new AgentDocumentsService(db, userId);+ const content = 'intro\n\n# Echoes the title\n\n## Keep me\n\nbody';+ await service.createDocument('agent-1', 'Doc', content);++ expect(mockModel.create).toHaveBeenCalledWith('agent-1', 'Doc', content, {+ editorData: { root: { children: [] } },+ title: 'Doc',+ });+ });++ it('falls back to the H1 as the title when no title is given', async () => {mockModel.findByParentAndFilename.mockResolvedValue(undefined);mockModel.create.mockResolvedValue({ id: 'new-doc', filename: 'My Title' });@@ -1073,6 +1107,88 @@ lossless tool result});});+ it('strips a leading H1 that duplicates the document title', async () => {+ mockModel.findById+ .mockResolvedValueOnce({+ agentId: 'agent-1',+ content: 'old',+ documentId: 'documents-1',+ id: 'agent-doc-1',+ title: 'My Title',+ })+ .mockResolvedValueOnce({+ agentId: 'agent-1',+ content: 'body',+ documentId: 'documents-1',+ id: 'agent-doc-1',+ title: 'My Title',+ });++ const service = new AgentDocumentsService(db, userId);+ await service.replaceDocumentContentById('agent-doc-1', '# My Title\n\nbody', 'agent-1');++ expect(mockModel.update).toHaveBeenCalledWith('agent-doc-1', {+ content: 'body',+ editorData: { root: { children: [] } },+ });+ });++ it('strips a leading H1 that differs from the document title', async () => {+ mockModel.findById+ .mockResolvedValueOnce({+ agentId: 'agent-1',+ content: 'old',+ documentId: 'documents-1',+ id: 'agent-doc-1',+ title: 'Doc',+ })+ .mockResolvedValueOnce({+ agentId: 'agent-1',+ content: 'body',+ documentId: 'documents-1',+ id: 'agent-doc-1',+ title: 'Doc',+ });++ const service = new AgentDocumentsService(db, userId);+ await service.replaceDocumentContentById('agent-doc-1', '# 一、总体结论\n\nbody', 'agent-1');++ expect(mockModel.update).toHaveBeenCalledWith('agent-doc-1', {+ content: 'body',+ editorData: { root: { children: [] } },+ });+ });++ it('keeps H1 headings that appear after other body content', async () => {+ mockModel.findById+ .mockResolvedValueOnce({+ agentId: 'agent-1',+ content: 'old',+ documentId: 'documents-1',+ id: 'agent-doc-1',+ title: 'Doc',+ })+ .mockResolvedValueOnce({+ agentId: 'agent-1',+ content: 'intro\n\n# Echoes the title\n\n## Keep me\n\nbody',+ documentId: 'documents-1',+ id: 'agent-doc-1',+ title: 'Doc',+ });++ const service = new AgentDocumentsService(db, userId);+ await service.replaceDocumentContentById(+ 'agent-doc-1',+ 'intro\n\n# Echoes the title\n\n## Keep me\n\nbody',+ 'agent-1',+ );++ expect(mockModel.update).toHaveBeenCalledWith('agent-doc-1', {+ content: 'intro\n\n# Echoes the title\n\n## Keep me\n\nbody',+ editorData: { root: { children: [] } },+ });+ });+it('should apply LiteXML operations against editor data', async () => {mockModel.findById.mockResolvedValueOnce({diff --git a/apps/server/src/services/agentDocuments/index.ts b/apps/server/src/services/agentDocuments/index.tsindex e127bc4ff00..567b98da1ac 100644--- a/apps/server/src/services/agentDocuments/index.ts+++ b/apps/server/src/services/agentDocuments/index.ts@@ -647,12 +647,13 @@ export class AgentDocumentsService {}// The caller's explicit title wins; a leading H1 only names untitled documents.- // The H1 is stripped from the body only when it duplicates the chosen title.- const { title: extractedTitle, content: strippedContent } = extractMarkdownH1Title(content);+ // The leading H1 is always dropped from the body: the document title renders+ // as the page header on share/editor surfaces, so that first heading would+ // read as a second page title. Deeper body headings are left alone.+ const { title: extractedTitle, content: finalContent } = extractMarkdownH1Title(content);// Tool callers do not always send `title` even though the schema asks for it.const requestedTitle = typeof title === 'string' ? title.trim() : '';const finalTitle = requestedTitle || extractedTitle || '';- const finalContent = extractedTitle === finalTitle ? strippedContent : content;const metadata = options.hintIsSkill? {agentSignal: {@@ -882,7 +883,11 @@ export class AgentDocumentsService {async replaceDocumentContentById(documentId: string, content: string, expectedAgentId?: string) {const doc = await this.getDocumentByIdInAgent(documentId, expectedAgentId);if (!doc) return undefined;- const snapshot = await createAgentMarkdownSnapshot(content);++ // Mirror createDocument: the document title renders as the page header, so+ // a leading H1 would show it a second time; deeper headings are kept.+ const { content: finalContent } = extractMarkdownH1Title(content);+ const snapshot = await createAgentMarkdownSnapshot(finalContent);if (doc.content !== snapshot.content) {await this.documentService.trySaveCurrentDocumentHistory(doc.documentId, 'llm_call');diff --git a/apps/server/src/services/skillManagement/SkillManagementDocumentService.test.ts b/apps/server/src/services/skillManagement/SkillManagementDocumentService.test.tsindex cb92075fccc..19572a92a2a 100644--- a/apps/server/src/services/skillManagement/SkillManagementDocumentService.test.ts+++ b/apps/server/src/services/skillManagement/SkillManagementDocumentService.test.ts@@ -26,12 +26,10 @@ import type { SkillAgentDocument } from './types';const now = new Date('2026-05-02T00:00:00.000Z');const backingDocumentUpdatedAt = new Date('2026-05-03T00:00:00.000Z');-const createSnapshot = vi.fn(- async (content: string): Promise<AgentDocumentEditorSnapshot> => ({- content,- editorData: { markdown: content, root: { children: [{ type: 'paragraph' }], type: 'root' } },- }),-);+const createSnapshot = vi.fn(async (content: string): Promise<AgentDocumentEditorSnapshot> => ({+ content,+ editorData: { markdown: content, root: { children: [{ type: 'paragraph' }], type: 'root' } },+}));const expectedEditorData = (content: string) => ({markdown: content,@@ -368,6 +366,27 @@ describe('SkillManagementDocumentService', () => {expect(detail?.index.documentId).toBe('document-2');});+ it('strips frontmatter pasted into bodyMarkdown instead of failing the save', async () => {+ const { service } = createService();++ const detail = await service.createSkill({+ agentId: 'agent-1',+ bodyMarkdown:+ '---\nname: stale-name\ndescription: Stale description\n---\n\n# Skill\n\n- Step one.',+ description: 'Canonical description',+ name: 'release-writer',+ title: 'Release Writer',+ });++ expect(detail.content).toBe(+ skillContent('release-writer', 'Canonical description', '# Skill\n\n- Step one.'),+ );+ expect(detail.frontmatter).toEqual({+ description: 'Canonical description',+ name: 'release-writer',+ });+ });+it('converts a hinted source document into the index while preserving ids', async () => {const { agentDocumentModel, service } = createService();const source = await agentDocumentModel.create('agent-1', 'draft-skill', '# Draft', {@@ -520,6 +539,29 @@ describe('SkillManagementDocumentService', () => {);});+ it('strips pasted frontmatter when replacing the skill index', async () => {+ const { service } = createService();+ const created = await service.createSkill({+ agentId: 'agent-1',+ bodyMarkdown: skillBody(),+ description: 'Researches APIs',+ name: 'researcher',+ title: 'Researcher',+ });++ const detail = await service.replaceSkillIndex({+ agentId: 'agent-1',+ bodyMarkdown: '---\nname: other\ndescription: Stale\n---\n\n# Better\n\nBody.',+ name: 'researcher',+ });++ expect(detail?.content).toBe(+ skillContent('researcher', 'Researches APIs', '# Better\n\nBody.'),+ );+ expect(detail?.frontmatter).toEqual({ description: 'Researches APIs', name: 'researcher' });+ expect(created.index.agentDocumentId).toBe(detail?.index.agentDocumentId);+ });+it('resolves a target skill from either the bundle or index agent document id', async () => {const { service } = createService();const created = await service.createSkill({diff --git a/apps/server/src/services/skillManagement/SkillManagementDocumentService.ts b/apps/server/src/services/skillManagement/SkillManagementDocumentService.tsindex d563787943d..9495e165af0 100644--- a/apps/server/src/services/skillManagement/SkillManagementDocumentService.ts+++ b/apps/server/src/services/skillManagement/SkillManagementDocumentService.ts@@ -121,7 +121,8 @@ export class SkillManagementDocumentService {** Expects:* - `name` is a stable lowercase skill name.- * - `bodyMarkdown` is Markdown body content without YAML frontmatter.+ * - `bodyMarkdown` is Markdown body content; a pasted YAML frontmatter block+ * is stripped because frontmatter renders from structured fields.** Returns:* - The created skill detail with normalized frontmatter content.@@ -336,7 +337,8 @@ export class SkillManagementDocumentService {** Expects:* - The target resolves to a live managed skill bundle.- * - Incoming bodyMarkdown has no YAML frontmatter.+ * - Incoming bodyMarkdown may carry a pasted YAML frontmatter block; it is+ * stripped before rendering because frontmatter renders from structured fields.** Returns:* - Updated skill detail with index content included.diff --git a/apps/server/src/services/skillManagement/frontmatter.test.ts b/apps/server/src/services/skillManagement/frontmatter.test.tsindex 840bcfade48..a7b6b7319fa 100644--- a/apps/server/src/services/skillManagement/frontmatter.test.ts+++ b/apps/server/src/services/skillManagement/frontmatter.test.ts@@ -1,8 +1,10 @@+import matter from 'gray-matter';import { describe, expect, it } from 'vitest';import {normalizeSkillIndexContent,parseSkillFrontmatter,+ renderSkillIndexContent,validateSkillName,} from './frontmatter';@@ -112,3 +114,94 @@ describe('normalizeSkillIndexContent', () => {).toThrow('Skill frontmatter description is required');});});++describe('renderSkillIndexContent', () => {+ it('renders frontmatter from structured fields and keeps the body', () => {+ expect(+ renderSkillIndexContent({+ bodyMarkdown: '# Review\n\n## Workflow\n- Check tests.',+ description: 'Review PRs',+ name: 'review',+ }),+ ).toBe(+ '---\ndescription: Review PRs\nname: review\n---\n# Review\n\n## Workflow\n- Check tests.',+ );+ });++ it('strips a pasted frontmatter block from the body instead of failing', () => {+ expect(+ renderSkillIndexContent({+ bodyMarkdown:+ '---\nname: stale-name\ndescription: Stale description\n---\n\n# Review\n\nBody.',+ description: 'Review PRs',+ name: 'review',+ }),+ ).toBe('---\ndescription: Review PRs\nname: review\n---\n# Review\n\nBody.');+ });++ it('ignores frontmatter fields in the pasted block; structured fields win', () => {+ const rendered = renderSkillIndexContent({+ bodyMarkdown: '---\nname: other-name\ninjected: yes\n---\nBody',+ description: 'Canonical',+ name: 'review',+ });++ expect(parseSkillFrontmatter(rendered)).toEqual({ description: 'Canonical', name: 'review' });+ });++ it('rejects an unclosed frontmatter block', () => {+ expect(() =>+ renderSkillIndexContent({+ bodyMarkdown: '---\nname: review\n# No closing delimiter',+ description: 'Review PRs',+ name: 'review',+ }),+ ).toThrow('Skill bodyMarkdown must close YAML frontmatter');+ });++ it('rejects a body that is empty after stripping frontmatter', () => {+ expect(() =>+ renderSkillIndexContent({+ bodyMarkdown: '---\nname: review\ndescription: Stale\n---\n',+ description: 'Review PRs',+ name: 'review',+ }),+ ).toThrow('Skill bodyMarkdown is required');+ });++ it('keeps a thematic break around prose (scalar block) verbatim', () => {+ const rendered = renderSkillIndexContent({+ bodyMarkdown: '---\n\nIntroduction\n\n---\n\n# Steps',+ description: 'Review PRs',+ name: 'review',+ });++ expect(parseSkillFrontmatter(rendered)).toEqual({ description: 'Review PRs', name: 'review' });+ // The prose between the delimiters must survive in the body.+ expect(matter(rendered).content).toContain('Introduction');+ expect(matter(rendered).content).toContain('# Steps');+ });++ it('keeps a block that parses to a YAML list verbatim', () => {+ const rendered = renderSkillIndexContent({+ bodyMarkdown: '---\n- a\n- b\n---\n\nBody',+ description: 'Review PRs',+ name: 'review',+ });++ expect(parseSkillFrontmatter(rendered)).toEqual({ description: 'Review PRs', name: 'review' });+ expect(matter(rendered).content).toContain('- a');+ expect(matter(rendered).content).toContain('Body');+ });++ it('keeps malformed YAML inside a closed block verbatim', () => {+ const rendered = renderSkillIndexContent({+ bodyMarkdown: '---\nfoo: [bar\n---\n\nBody',+ description: 'Review PRs',+ name: 'review',+ });++ expect(parseSkillFrontmatter(rendered)).toEqual({ description: 'Review PRs', name: 'review' });+ expect(matter(rendered).content).toContain('foo: [bar');+ });+});diff --git a/apps/server/src/services/skillManagement/frontmatter.ts b/apps/server/src/services/skillManagement/frontmatter.tsindex 41d76509641..9112af1cdf8 100644--- a/apps/server/src/services/skillManagement/frontmatter.ts+++ b/apps/server/src/services/skillManagement/frontmatter.ts@@ -91,6 +91,29 @@ const parseMatter = (content: string): ParsedMatterResult => {return { body: parsed.content, data: parsed.data };};+/**+ * Remove a leading frontmatter-looking block from a pasted body and return the+ * remaining body, or `undefined` when the block is not actually frontmatter.+ *+ * A thematic break followed by prose (`---\n\nIntroduction\n\n---`) parses to+ * a YAML scalar, a list parses to an array, and malformed YAML throws — none+ * of them is a metadata mapping, so the body must be kept verbatim rather than+ * silently losing content through the second delimiter.+ */+const stripPastedFrontmatter = (body: string): string | undefined => {+ let parsed: { content: string; data: unknown };+ try {+ parsed = matter(body);+ } catch {+ return undefined;+ }++ const { content, data } = parsed;+ if (typeof data !== 'object' || data === null || Array.isArray(data)) return undefined;++ return content.trimStart();+};+/*** Renders skill index content from structured metadata and body Markdown.*@@ -99,18 +122,40 @@ const parseMatter = (content: string): ParsedMatterResult => {** After:* - "---\nname: review\ndescription: Review PRs\n---\n# Review\n\n## Workflow\n- Check tests."+ *+ * Models often paste a full SKILL.md-shaped body that already carries a+ * frontmatter block. Frontmatter is always rendered from the structured+ * fields (`name` / `description`), so a well-formed leading metadata block is+ * stripped from the body instead of failing the save; a block that only looks+ * like frontmatter (a thematic break around prose) is kept verbatim, and an+ * unclosed block is rejected.*/export const renderSkillIndexContent = (input: RenderSkillIndexContentInput): string => {const name = validateSkillName(input.name);const description = normalizeFrontmatterScalar(input.description, 'description');- const body = input.bodyMarkdown.trimStart();+ let body = input.bodyMarkdown.trimStart();if (!body) {throw new Error('Skill bodyMarkdown is required');}if (body.startsWith('---')) {- throw new Error('Skill bodyMarkdown must not include YAML frontmatter');+ if (!FRONTMATTER_BLOCK_PATTERN.test(body)) {+ throw new Error('Skill bodyMarkdown must close YAML frontmatter');+ }+ body = stripPastedFrontmatter(body) ?? body;+ if (!body) {+ throw new Error('Skill bodyMarkdown is required');+ }++ if (body.startsWith('---')) {+ // The block parsed to prose (a thematic break around text, a list, or+ // malformed YAML) and is kept verbatim. matter.stringify() would+ // re-parse the leading delimiter and corrupt the output, so compose the+ // structured frontmatter block manually.+ const block = matter.stringify('', { description, name }).replace(/\n+$/, '\n');+ return block + body;+ }}return matterdiff --git a/apps/server/src/services/skillManagement/types.ts b/apps/server/src/services/skillManagement/types.tsindex 3263e9083a1..48e997a7808 100644--- a/apps/server/src/services/skillManagement/types.ts+++ b/apps/server/src/services/skillManagement/types.ts@@ -96,7 +96,7 @@ export interface GetSkillInput extends SkillTargetInput {export interface CreateSkillInput {/** Agent id that owns the skill documents. */agentId: string;- /** Markdown body authored by the skill-management agent; must not include YAML frontmatter. */+ /** Markdown body authored by the skill-management agent; a pasted YAML frontmatter block is stripped before rendering. */bodyMarkdown: string;/** Frontmatter description to persist for the skill. */description: string;@@ -114,7 +114,7 @@ export interface CreateSkillInput {export interface ReplaceSkillIndexInput extends SkillTargetInput {/** Agent id that owns the skill documents. */agentId: string;- /** Replacement Markdown body authored by the skill-management agent; must not include YAML frontmatter. */+ /** Replacement Markdown body authored by the skill-management agent; a pasted YAML frontmatter block is stripped before rendering. */bodyMarkdown: string;/** Optional frontmatter description override. */description?: string;diff --git a/apps/share/package.json b/apps/share/package.jsonindex 951147420bf..735ad282559 100644--- a/apps/share/package.json+++ b/apps/share/package.json@@ -16,6 +16,7 @@"devDependencies": {"@ant-design/cssinjs": "^2.1.2","@cloudflare/vite-plugin": "^1.52.1",+ "@codemirror/streamparser": "^6.0.0","@react-router/dev": "^8.3.0","isbot": "^5.1.32","vite-tsconfig-paths": "^6.1.1",diff --git a/packages/builtin-tool-agent-documents/src/agentShareSystemRole.ts b/packages/builtin-tool-agent-documents/src/agentShareSystemRole.tsindex b0cb16d4bef..37ebe54b6a4 100644--- a/packages/builtin-tool-agent-documents/src/agentShareSystemRole.ts+++ b/packages/builtin-tool-agent-documents/src/agentShareSystemRole.ts@@ -23,6 +23,10 @@ export const agentShareSystemPrompt = `You have access to a restricted Agent Doc5. Confirm the completed action and present any returned document URL as a clickable markdown link.</workflow>+<content_guidelines>+- Start content directly with the body. Do NOT open with an H1 (\`#\`) heading — the title field already renders as the document header, so the leading H1 is removed automatically; use \`##\` or deeper for in-document sections.+</content_guidelines>+<response_boundaries>- Never expose an internal document ID to the user.- Do not claim access to documents outside this shared topic.diff --git a/packages/builtin-tool-agent-documents/src/manifest.ts b/packages/builtin-tool-agent-documents/src/manifest.tsindex e27006c55e9..a279ea84fac 100644--- a/packages/builtin-tool-agent-documents/src/manifest.ts+++ b/packages/builtin-tool-agent-documents/src/manifest.ts@@ -21,7 +21,7 @@ export const AgentDocumentsManifest: BuiltinToolManifest = {properties: {content: {description:- 'Document content in Markdown. Put JSON, code or any text that must stay byte-exact inside a fenced code block (```json … ```); outside code, Markdown syntax such as `\\`, `__` or `*` is interpreted.',+ 'Document content in Markdown. Put JSON, code or any text that must stay byte-exact inside a fenced code block (```json … ```); outside code, Markdown syntax such as `\\`, `__` or `*` is interpreted. Do not open with an H1 (`#`) heading — the title renders as the document header and the leading H1 is removed automatically; start directly with the body and use `##` or deeper for sections.',type: 'string',},hintIsSkill: {@@ -95,7 +95,7 @@ export const AgentDocumentsManifest: BuiltinToolManifest = {properties: {content: {description:- 'New full document content in Markdown. Put JSON, code or any text that must stay byte-exact inside a fenced code block (```json … ```).',+ 'New full document content in Markdown. Put JSON, code or any text that must stay byte-exact inside a fenced code block (```json … ```). Do not open with an H1 (`#`) heading — the title renders as the document header and the leading H1 is removed automatically; use `##` or deeper for sections.',type: 'string',},id: {diff --git a/packages/builtin-tool-agent-documents/src/systemRole.ts b/packages/builtin-tool-agent-documents/src/systemRole.tsindex fdd24deb76e..ede58c0b1a2 100644--- a/packages/builtin-tool-agent-documents/src/systemRole.ts+++ b/packages/builtin-tool-agent-documents/src/systemRole.ts@@ -47,6 +47,7 @@ Only use listDocuments/readDocument when the user is asking about agent document- Use renameDocument for title-only changes; avoid rewriting content unnecessarily.- Use copyDocument before major edits when user may want a backup version.- Keep load-rule changes explicit and summarize their effect, especially when they change permissions, sharing scope, load location, or load strategy.+- Start content directly with the body. Do NOT open with an H1 (\`#\`) heading — the title field already renders as the document header, so the leading H1 is removed automatically; use \`##\` or deeper for in-document sections.</best_practices><response_format>diff --git a/packages/builtin-tool-skill-maintainer/src/manifest.ts b/packages/builtin-tool-skill-maintainer/src/manifest.tsindex 160bd067cd4..aab3cdbb200 100644--- a/packages/builtin-tool-skill-maintainer/src/manifest.ts+++ b/packages/builtin-tool-skill-maintainer/src/manifest.ts@@ -14,7 +14,8 @@ const skillTargetProperties = {} as const;const skillBodyMarkdownProperty = {- description: 'Markdown body for SKILL.md. Do not include YAML frontmatter.',+ description:+ 'Markdown body for SKILL.md. Do not include YAML frontmatter — a pasted frontmatter block is stripped automatically, and frontmatter is rendered from name/description.',type: 'string',} as const;diff --git a/packages/database/src/models/agentDocuments/__tests__/filename.test.ts b/packages/database/src/models/agentDocuments/__tests__/filename.test.tsindex bc2f1194ee8..7ebad8975fe 100644--- a/packages/database/src/models/agentDocuments/__tests__/filename.test.ts+++ b/packages/database/src/models/agentDocuments/__tests__/filename.test.ts@@ -66,4 +66,18 @@ describe('extractMarkdownH1Title', () => {const result = extractMarkdownH1Title('# Spaced Title \nbody');expect(result.title).toBe('Spaced Title');});++ it('accepts up to 3 leading spaces per CommonMark', () => {+ const result = extractMarkdownH1Title(' # Spaced Title\nbody');+ expect(result.title).toBe('Spaced Title');+ expect(result.content).toBe('body');+ });++ it('does not treat deeper indentation (code blocks) as a heading', () => {+ const content = ' # install dependencies\n npm install';+ expect(extractMarkdownH1Title(content)).toEqual({ content });++ const tabIndented = '\t# install dependencies\n\tnpm install';+ expect(extractMarkdownH1Title(tabIndented)).toEqual({ content: tabIndented });+ });});diff --git a/packages/database/src/models/agentDocuments/filename.ts b/packages/database/src/models/agentDocuments/filename.tsindex 9c440bc0e37..e79a5b79407 100644--- a/packages/database/src/models/agentDocuments/filename.ts+++ b/packages/database/src/models/agentDocuments/filename.ts@@ -28,8 +28,10 @@ export const buildDocumentFilename = (title: string): string => {* the remaining content with that heading stripped.** Only matches a `# ` heading that appears at the top of the document- * (optionally preceded by blank lines). Setext-style (`===`) and indented- * headings are not recognised.+ * (optionally preceded by blank lines), with up to 3 leading spaces per+ * CommonMark. Deeper indentation (a tab or 4 spaces) is an indented code+ * block and is not recognised, so a code line such as ` # install` stays+ * untouched. Setext-style (`===`) headings are not recognised either.*/export const extractMarkdownH1Title = (content: string): { content: string; title?: string } => {const lines = content.split(/\r?\n/);@@ -38,7 +40,7 @@ export const extractMarkdownH1Title = (content: string): { content: string; titlwhile (i < lines.length && lines[i].trim() === '') i += 1;if (i >= lines.length) return { content };- const headingMatch = lines[i].match(/^[ \t]*#[ \t]+(\S.*)$/);+ const headingMatch = lines[i].match(/^ {0,3}#[ \t]+(\S.*)$/);if (!headingMatch) return { content };const title = headingMatch[1].trim();