From 53c005f776b7991bfc845cf71d203dc53e25d4b8 Mon Sep 17 00:00:00 2001 From: addyCooks Date: Thu, 20 Aug 2026 14:02:27 +0530 Subject: [PATCH] fix(web): recover a document title when auto-titling produces none Documents saved through the MCP connector have been landing with a null title, so every surface fell back to "Untitled Document". The titling step runs server-side, but the content itself almost always carries a usable title, and the ingest API has no title field for a caller to set. Resolve a display title from metadata.title, then the stored title, then the content itself (YAML frontmatter, a markdown heading, or a short opening line), and let add_memory pin a title through metadata. Fixes #1425 --- apps/mcp/src/server/client/index.test.ts | 28 +++ apps/mcp/src/server/client/index.ts | 7 +- apps/mcp/src/server/format.test.ts | 76 ++++++++ apps/mcp/src/server/format.ts | 16 +- apps/mcp/src/server/tools/add-memory.ts | 13 +- .../components/brain-home/brain-home-view.tsx | 5 +- apps/web/components/dashboard-view.tsx | 3 +- .../components/document-cards/mcp-preview.tsx | 7 +- .../document-cards/note-preview.tsx | 7 +- apps/web/components/document-modal/index.tsx | 11 +- .../components/documents-command-palette.tsx | 6 +- apps/web/components/memories-grid.tsx | 7 +- apps/web/lib/document-title.test.ts | 178 ++++++++++++++++++ apps/web/lib/document-title.ts | 106 +++++++++++ 14 files changed, 455 insertions(+), 15 deletions(-) create mode 100644 apps/mcp/src/server/format.test.ts create mode 100644 apps/web/lib/document-title.test.ts create mode 100644 apps/web/lib/document-title.ts diff --git a/apps/mcp/src/server/client/index.test.ts b/apps/mcp/src/server/client/index.test.ts index 464c2080..da54ecb2 100644 --- a/apps/mcp/src/server/client/index.test.ts +++ b/apps/mcp/src/server/client/index.test.ts @@ -95,6 +95,34 @@ describe("SupermemoryClient", () => { }) }) + it("pins an explicit title through metadata", async () => { + sdk.add.mockResolvedValue({ id: "doc_2" }) + + await client("work").createMemory("remember this", { + title: " Quarterly planning notes ", + }) + + expect(sdk.add).toHaveBeenCalledWith({ + content: "remember this", + containerTag: "work", + metadata: { + sm_source: "supermemory-mcp", + title: "Quarterly planning notes", + }, + }) + }) + + it("leaves the title out when it is blank or absent", async () => { + sdk.add.mockResolvedValue({ id: "doc_3" }) + + await client("work").createMemory("a", { title: " " }) + await client("work").createMemory("b", {}) + + for (const call of sdk.add.mock.calls) { + expect(call[0].metadata).toEqual({ sm_source: "supermemory-mcp" }) + } + }) + it("treats an empty space string as an unscoped connection", async () => { sdk.search.memories.mockResolvedValue({ results: [], diff --git a/apps/mcp/src/server/client/index.ts b/apps/mcp/src/server/client/index.ts index 9232cc3c..f9638826 100644 --- a/apps/mcp/src/server/client/index.ts +++ b/apps/mcp/src/server/client/index.ts @@ -189,12 +189,17 @@ export class SupermemoryClient { async createMemory( content: string, + options?: { title?: string }, ): Promise<{ id: string; status: string; containerTag: string }> { try { + const title = options?.title?.trim() const result = await this.client.add({ content, containerTag: this.containerTag, - metadata: { sm_source: MCP_SOURCE }, + metadata: { + sm_source: MCP_SOURCE, + ...(title ? { title } : {}), + }, }) return { id: result.id, diff --git a/apps/mcp/src/server/format.test.ts b/apps/mcp/src/server/format.test.ts new file mode 100644 index 00000000..4d923c5e --- /dev/null +++ b/apps/mcp/src/server/format.test.ts @@ -0,0 +1,76 @@ +import { describe, expect, it } from "vitest" +import type { DocumentDetails, DocumentsListResponse } from "./client" +import { formatDocument, formatDocumentsList } from "./format" + +function list(document: Record): DocumentsListResponse { + return { + documents: [ + { + id: "doc_1", + type: "text", + status: "done", + createdAt: "2026-08-07T12:53:00.000Z", + ...document, + }, + ], + pagination: { currentPage: 1, totalPages: 1, totalItems: 1, limit: 50 }, + } as unknown as DocumentsListResponse +} + +function details(document: Record): DocumentDetails { + return { + id: "doc_1", + type: "text", + status: "done", + createdAt: "2026-08-07T12:53:00.000Z", + updatedAt: "2026-08-07T12:53:00.000Z", + content: "body", + ...document, + } as unknown as DocumentDetails +} + +describe("document titles in MCP output", () => { + it("prefers a pinned metadata title over the stored one", () => { + expect( + formatDocumentsList( + list({ title: "Paraphrase", metadata: { title: "Pinned" } }), + ), + ).toContain('"Pinned"') + expect( + formatDocument( + details({ title: "Paraphrase", metadata: { title: "Pinned" } }), + ), + ).toContain("# Pinned") + }) + + it("uses the pinned title when titling produced nothing", () => { + expect( + formatDocumentsList(list({ title: null, metadata: { title: "Pinned" } })), + ).toContain('"Pinned"') + }) + + it("falls back to the stored title, then to a placeholder", () => { + expect(formatDocumentsList(list({ title: "Stored" }))).toContain('"Stored"') + expect(formatDocumentsList(list({ title: null }))).toContain("(untitled)") + expect(formatDocument(details({ title: null }))).toContain("# (untitled)") + }) + + it("ignores metadata that is blank or not a string", () => { + expect( + formatDocumentsList( + list({ title: "Stored", metadata: { title: " " } }), + ), + ).toContain('"Stored"') + expect( + formatDocumentsList(list({ title: "Stored", metadata: { title: 42 } })), + ).toContain('"Stored"') + }) + + it("survives non-object metadata", () => { + for (const metadata of [null, "raw", 7, true, ["a"]]) { + expect( + formatDocumentsList(list({ title: "Stored", metadata })), + ).toContain('"Stored"') + } + }) +}) diff --git a/apps/mcp/src/server/format.ts b/apps/mcp/src/server/format.ts index c9bb3f11..b35de6f5 100644 --- a/apps/mcp/src/server/format.ts +++ b/apps/mcp/src/server/format.ts @@ -18,6 +18,18 @@ function day(value: string | null | undefined): string { return value?.slice(0, 10) ?? "" } +function documentTitle(document: { + title?: string | null + metadata?: unknown +}): string { + const metadata = document.metadata + if (metadata && typeof metadata === "object") { + const pinned = (metadata as Record).title + if (typeof pinned === "string" && pinned.trim()) return pinned.trim() + } + return document.title?.trim() || "(untitled)" +} + function paginationSummary( currentPage: number, totalPages: number, @@ -39,7 +51,7 @@ export function formatDocumentsList(response: DocumentsListResponse): string { } const blocks = documents.map((document) => { - const title = document.title?.trim() || "(untitled)" + const title = documentTitle(document) const lines = [ `- [${document.id}] "${title}" (${document.type}, ${document.status}, ${day(document.createdAt)})`, ] @@ -150,7 +162,7 @@ export function getDocumentContent(document: DocumentDetails): { } export function formatDocument(document: DocumentDetails): string { - const title = document.title?.trim() || "(untitled)" + const title = documentTitle(document) const parts = [ `# ${title}`, `Document ID: ${document.id}`, diff --git a/apps/mcp/src/server/tools/add-memory.ts b/apps/mcp/src/server/tools/add-memory.ts index c708deb5..62a08390 100644 --- a/apps/mcp/src/server/tools/add-memory.ts +++ b/apps/mcp/src/server/tools/add-memory.ts @@ -11,6 +11,15 @@ export function register(deps: ToolDeps) { .max(200000, "Content exceeds maximum length") .describe("The memory content to save or forget"), action: z.enum(["save", "forget"]).optional().default("save"), + title: z + .string() + .trim() + .min(1) + .max(200) + .optional() + .describe( + "Optional title for the saved memory. Overrides the title generated during processing. Ignored when action is 'forget'.", + ), containerTag: optionalContainerTagSchema, }) @@ -42,7 +51,9 @@ export function register(deps: ToolDeps) { } } - const result = await client.createMemory(args.content) + const result = await client.createMemory(args.content, { + title: args.title, + }) const message = `Memory saved (ID: ${result.id}, space: ${result.containerTag})` const structuredContent: AddMemoryOutput = { action: "save", diff --git a/apps/web/components/brain-home/brain-home-view.tsx b/apps/web/components/brain-home/brain-home-view.tsx index 3501c5e8..2d68b758 100644 --- a/apps/web/components/brain-home/brain-home-view.tsx +++ b/apps/web/components/brain-home/brain-home-view.tsx @@ -12,6 +12,7 @@ import { TrialSetupBanner } from "@/components/trial-setup-banner" import { useTrialStatus } from "@/hooks/use-trial-status" import { dmSans125ClassName } from "@/lib/fonts" import { useViewMode } from "@/lib/view-mode-context" +import { resolveDocumentTitle } from "@/lib/document-title" import { AskInSlackCard, CONNECT_TOOLS_CARD_ID, @@ -31,6 +32,8 @@ const cardStyle = { type RecentDoc = { id?: string title?: string | null + content?: string | null + metadata?: Record | null createdAt?: string | Date | null updatedAt?: string | Date | null } @@ -390,7 +393,7 @@ function RecentMemories({

- {doc.title?.trim() || "Untitled memory"} + {resolveDocumentTitle(doc) || "Untitled memory"}

{formatWhen(doc.createdAt)} diff --git a/apps/web/components/dashboard-view.tsx b/apps/web/components/dashboard-view.tsx index 12c76a86..90fa98bd 100644 --- a/apps/web/components/dashboard-view.tsx +++ b/apps/web/components/dashboard-view.tsx @@ -45,6 +45,7 @@ import { normalizePluginClientId } from "@/lib/plugin-catalog" import { detectPluginSpace } from "@/lib/plugin-space" import { useDigests } from "@/hooks/use-digests" import { ReviewMemoriesCard } from "@/components/review-memories-card" +import { resolveDocumentTitle } from "@/lib/document-title" type DocumentsResponse = z.infer type DocumentWithMemories = DocumentsResponse["documents"][0] @@ -1599,7 +1600,7 @@ export function DashboardView({ )} - {doc.title?.trim() || "Untitled"} + {resolveDocumentTitle(doc) || "Untitled"} diff --git a/apps/web/components/document-cards/mcp-preview.tsx b/apps/web/components/document-cards/mcp-preview.tsx index 19cdeec4..0e33a345 100644 --- a/apps/web/components/document-cards/mcp-preview.tsx +++ b/apps/web/components/document-cards/mcp-preview.tsx @@ -6,6 +6,7 @@ import { dmSansClassName } from "@/lib/fonts" import { cn } from "@lib/utils" import { ClaudeDesktopIcon, MCPIcon } from "@ui/assets/icons" import type { ParsedPluginDocument } from "@/lib/plugin-document" +import { resolveDocumentTitle } from "@/lib/document-title" import { PluginPreview } from "./plugin-preview" type DocumentsResponse = z.infer @@ -28,6 +29,8 @@ export function McpPreview({ .replace(/\b\w/g, (match) => match.toUpperCase()) : "MCP Client" + const title = resolveDocumentTitle(document) + return (
@@ -43,9 +46,9 @@ export function McpPreview({
- {document.title && ( + {title && (

- {document.title} + {title}

)} {document.content && ( diff --git a/apps/web/components/document-cards/note-preview.tsx b/apps/web/components/document-cards/note-preview.tsx index e9623497..8de965ca 100644 --- a/apps/web/components/document-cards/note-preview.tsx +++ b/apps/web/components/document-cards/note-preview.tsx @@ -6,6 +6,7 @@ import { dmSansClassName } from "@/lib/fonts" import { cn } from "@lib/utils" import { DocumentIcon } from "@/components/document-icon" import type { ParsedPluginDocument } from "@/lib/plugin-document" +import { resolveDocumentTitle } from "@/lib/document-title" import { PluginPreview } from "./plugin-preview" type DocumentsResponse = z.infer @@ -22,6 +23,8 @@ export function NotePreview({ return } + const title = resolveDocumentTitle(document) + return (
@@ -31,14 +34,14 @@ export function NotePreview({

- {document.title && ( + {title && (

- {document.title} + {title}

)} {document.summary && ( diff --git a/apps/web/components/document-modal/index.tsx b/apps/web/components/document-modal/index.tsx index 77d80826..e74d6f97 100644 --- a/apps/web/components/document-modal/index.tsx +++ b/apps/web/components/document-modal/index.tsx @@ -27,6 +27,7 @@ import type { UseMutationResult } from "@tanstack/react-query" import { toast } from "sonner" import { useIsMobile } from "@hooks/use-mobile" import { parsePluginDocument } from "@/lib/plugin-document" +import { resolveDocumentTitle } from "@/lib/document-title" import { useFullDocumentContent } from "@/hooks/use-full-document" type DocumentsResponse = z.infer @@ -219,6 +220,10 @@ export function DocumentModal({ () => parsePluginDocument(effectiveDocument), [effectiveDocument], ) + const resolvedTitle = useMemo( + () => resolveDocumentTitle(effectiveDocument), + [effectiveDocument], + ) const [draftContentString, setDraftContentString] = useState(initialEditorString) @@ -330,17 +335,17 @@ export function DocumentModal({ <> {isMobile ? ( - {_document?.title} - Document + {resolvedTitle} - Document ) : ( - {_document?.title} - Document + {resolvedTitle} - Document )}
type DocumentWithMemories = DocumentsResponse["documents"][0] @@ -282,7 +283,10 @@ export function DocumentsCommandPalette({ ) } - const title = item.kind === "document" ? item.doc.title : item.result.title + const title = + item.kind === "document" + ? resolveDocumentTitle(item.doc) + : item.result.title const type = item.kind === "document" ? item.doc.type : item.result.type const url = item.kind === "document" diff --git a/apps/web/components/memories-grid.tsx b/apps/web/components/memories-grid.tsx index beaee36c..11a87197 100644 --- a/apps/web/components/memories-grid.tsx +++ b/apps/web/components/memories-grid.tsx @@ -29,6 +29,7 @@ import { YoutubePreview } from "./document-cards/youtube-preview" import { getAbsoluteUrl, isYouTubeUrl, useYouTubeChannelName } from "./utils" import { SyncLogoIcon } from "@ui/assets/icons" import { McpPreview } from "./document-cards/mcp-preview" +import { resolveDocumentTitle } from "@/lib/document-title" import { NotionPreview } from "./document-cards/notion-preview" import { getFaviconUrl, isSupermemoryFileUrl } from "@/lib/url-helpers" import { QuickNoteCard } from "./quick-note-card" @@ -1143,6 +1144,10 @@ const DocumentCard = memo( () => parsePluginDocument(document), [document], ) + const resolvedTitle = useMemo( + () => resolveDocumentTitle(document), + [document], + ) const [rotation, setRotation] = useState({ rotateX: 0, rotateY: 0 }) const cardRef = useRef<HTMLButtonElement>(null) const [ogData, setOgData] = useState<OgData | null>(null) @@ -1298,7 +1303,7 @@ const DocumentCard = memo( "text-[13px] text-[#E5E5E5] line-clamp-1 font-semibold", )} > - {document.title || ogData?.title || "Untitled Document"} + {resolvedTitle || ogData?.title || "Untitled Document"} </p> {getFaviconUrl(document.url) && needsOgData && ( <img diff --git a/apps/web/lib/document-title.test.ts b/apps/web/lib/document-title.test.ts new file mode 100644 index 00000000..47c43151 --- /dev/null +++ b/apps/web/lib/document-title.test.ts @@ -0,0 +1,178 @@ +import { describe, expect, it } from "bun:test" +import { resolveDocumentTitle } from "./document-title" + +const fromContent = (content: string | null | undefined) => + resolveDocumentTitle({ content }) + +describe("resolveDocumentTitle precedence", () => { + it("prefers metadata.title over everything", () => { + expect( + resolveDocumentTitle({ + title: "LLM paraphrase", + metadata: { title: "Pinned" }, + content: "# Derived", + }), + ).toBe("Pinned") + }) + + it("falls back to the stored title", () => { + expect( + resolveDocumentTitle({ title: "Stored", content: "# Derived" }), + ).toBe("Stored") + }) + + it("derives from content when titling produced nothing", () => { + expect(resolveDocumentTitle({ title: null, content: "# Derived" })).toBe( + "Derived", + ) + }) + + it("skips blank and non-string candidates", () => { + expect(resolveDocumentTitle({ title: " ", content: "# Derived" })).toBe( + "Derived", + ) + expect( + resolveDocumentTitle({ metadata: { title: " " }, content: "# Derived" }), + ).toBe("Derived") + expect( + resolveDocumentTitle({ metadata: { title: 42 }, content: "# Derived" }), + ).toBe("Derived") + expect( + resolveDocumentTitle({ metadata: { title: null }, title: "Stored" }), + ).toBe("Stored") + }) + + it("survives odd metadata shapes", () => { + expect(resolveDocumentTitle({ metadata: null, title: "Stored" })).toBe( + "Stored", + ) + expect( + resolveDocumentTitle({ + metadata: [] as unknown as Record<string, unknown>, + title: "Stored", + }), + ).toBe("Stored") + }) + + it("returns null when there is nothing to show", () => { + expect(resolveDocumentTitle(null)).toBeNull() + expect(resolveDocumentTitle(undefined)).toBeNull() + expect(resolveDocumentTitle({})).toBeNull() + expect(resolveDocumentTitle({ title: null, content: null })).toBeNull() + }) +}) + +describe("deriving a title from content", () => { + it("reads markdown headings at every level", () => { + expect(fromContent("# Quarterly planning\n\nProse.")).toBe( + "Quarterly planning", + ) + expect(fromContent("###### Deep heading\n\nProse.")).toBe("Deep heading") + }) + + it("drops closing hashes and surrounding markup", () => { + expect(fromContent("### Deploy runbook ###\n\nSteps.")).toBe( + "Deploy runbook", + ) + expect(fromContent("# **Bold heading**\n\nProse.")).toBe("Bold heading") + expect(fromContent("**Bold line**\n\nProse.")).toBe("Bold line") + expect(fromContent("`code line`\n\nProse.")).toBe("code line") + expect(fromContent('"Quoted line"\n\nProse.')).toBe("Quoted line") + }) + + it("requires a space after the hashes", () => { + expect(fromContent("#NotAHeading\n\nProse.")).toBe("#NotAHeading") + }) + + it("reads a YAML frontmatter title", () => { + expect( + fromContent( + '---\ntitle: "Kubernetes upgrade"\ntags: [infra]\n---\n\nBody.', + ), + ).toBe("Kubernetes upgrade") + expect(fromContent("---\ntitle: 'Single quoted'\n---\nBody.")).toBe( + "Single quoted", + ) + }) + + it("prefers frontmatter over a following heading", () => { + expect(fromContent("---\ntitle: Real\n---\n\n# Other")).toBe("Real") + }) + + it("falls through when frontmatter has no usable title", () => { + expect(fromContent("---\ntags: [infra]\n---\n\n# Heading wins")).toBe( + "Heading wins", + ) + expect(fromContent("---\ntitle:\n---\n\n# Heading wins")).toBe( + "Heading wins", + ) + }) + + it("ignores an indented title key inside frontmatter", () => { + expect(fromContent("---\nauthor:\n title: Nested\n---\n\n# Heading")).toBe( + "Heading", + ) + }) + + it("takes a short opening line followed by prose", () => { + expect( + fromContent("Postgres connection pooling\n\nWe moved to pgbouncer."), + ).toBe("Postgres connection pooling") + }) + + it("takes a setext heading regardless of length", () => { + const long = `${"Long ".repeat(40)}heading` + expect(fromContent(`${long}\n===\n\nBody.`)).toStartWith("Long") + expect(fromContent("Underlined\n---\n\nBody.")).toBe("Underlined") + }) + + it("rejects an opening paragraph too long to be a title", () => { + expect( + fromContent("This is ordinary prose that keeps going. ".repeat(6)), + ).toBeNull() + }) + + it("rejects list, quote, table, rule, fence and URL openers", () => { + expect(fromContent("- first\n- second")).toBeNull() + expect(fromContent("* first\n* second")).toBeNull() + expect(fromContent("1. first\n2. second")).toBeNull() + expect(fromContent("> quoted\n\nmore")).toBeNull() + expect(fromContent("| a | b |\n| - | - |")).toBeNull() + expect(fromContent("---\n\nnot frontmatter")).toBeNull() + expect(fromContent("```ts\nconst a = 1\n```")).toBeNull() + expect(fromContent("~~~\ncode\n~~~")).toBeNull() + expect(fromContent("https://example.com/article")).toBeNull() + expect(fromContent("www.example.com/article")).toBeNull() + }) + + it("skips leading blank lines", () => { + expect(fromContent("\n\n\n# After blanks\n\nProse.")).toBe("After blanks") + }) + + it("handles CRLF, a BOM and collapsed whitespace", () => { + expect(fromContent("# Spaced out\r\n\r\nBody.")).toBe("Spaced out") + expect(fromContent("\ufeff---\r\ntitle: From BOM\r\n---\r\nBody.")).toBe( + "From BOM", + ) + expect(fromContent("Tabbed\ttitle\n\nBody.")).toBe("Tabbed title") + }) + + it("truncates an overlong heading to a bounded length", () => { + const title = fromContent(`# ${"word ".repeat(60)}`) + expect(title).not.toBeNull() + expect((title as string).length).toBeLessThanOrEqual(120) + expect(title).toEndWith("…") + }) + + it("returns null for empty, blank or missing content", () => { + expect(fromContent("")).toBeNull() + expect(fromContent(" \n\n ")).toBeNull() + expect(fromContent("#\n\nBody.")).toBeNull() + expect(fromContent(null)).toBeNull() + expect(fromContent(undefined)).toBeNull() + }) + + it("handles a single-line document with no trailing newline", () => { + expect(fromContent("Just one line")).toBe("Just one line") + }) +}) diff --git a/apps/web/lib/document-title.ts b/apps/web/lib/document-title.ts new file mode 100644 index 00000000..2328b1e0 --- /dev/null +++ b/apps/web/lib/document-title.ts @@ -0,0 +1,106 @@ +type TitleSource = { + title?: string | null + content?: string | null + metadata?: Record<string, unknown> | null +} + +const MAX_TITLE_CHARS = 120 +const FRONTMATTER = /^\ufeff?---[ \t]*\r?\n([\s\S]*?)\r?\n---[ \t]*(?:\r?\n|$)/ +const FRONTMATTER_TITLE = /^title[ \t]*:[ \t]*(.+)$/m +const ATX_HEADING = /^#{1,6}\s+(.*?)\s*#*$/ +const SETEXT_UNDERLINE = /^(?:=+|-{2,})$/ +const HORIZONTAL_RULE = /^(?:-{3,}|\*{3,}|_{3,})$/ +const BLOCK_MARKER = /^(?:[-*+]\s|>\s?|\d+[.)]\s|\|)/ +const BARE_URL = /^(?:https?:\/\/|www\.)\S+$/i +const WORD = /[\p{L}\p{N}]/u +const WRAPPERS = ["***", "**", "__", "*", "_", "`"] + +function collapse(value: string): string { + return value.replace(/\s+/g, " ").trim() +} + +function clamp(value: string): string | null { + if (!value) return null + return value.length <= MAX_TITLE_CHARS + ? value + : `${value.slice(0, MAX_TITLE_CHARS - 1).trimEnd()}…` +} + +function unwrap(value: string): string { + let text = value.trim() + for (const marker of WRAPPERS) { + while ( + text.length > marker.length * 2 && + text.startsWith(marker) && + text.endsWith(marker) + ) { + text = text.slice(marker.length, -marker.length).trim() + } + } + const quote = text[0] + if ( + text.length >= 2 && + (quote === '"' || quote === "'") && + text.endsWith(quote) + ) { + text = text.slice(1, -1).trim() + } + return text +} + +function fromContent(content: string): string | null { + const frontmatter = FRONTMATTER.exec(content) + const declared = frontmatter?.[1] + ? FRONTMATTER_TITLE.exec(frontmatter[1])?.[1] + : undefined + if (declared) { + const title = clamp(collapse(unwrap(declared))) + if (title) return title + } + + const body = frontmatter ? content.slice(frontmatter[0].length) : content + const lines = body.split(/\r?\n/) + const start = lines.findIndex((line) => line.trim().length > 0) + if (start === -1) return null + + const first = (lines[start] ?? "").trim() + if ( + first.startsWith("```") || + first.startsWith("~~~") || + BARE_URL.test(first) || + HORIZONTAL_RULE.test(first) + ) { + return null + } + + const heading = ATX_HEADING.exec(first) + if (heading) return clamp(collapse(unwrap(heading[1] ?? ""))) + if (BLOCK_MARKER.test(first)) return null + + const candidate = collapse(unwrap(first)) + if (!WORD.test(candidate)) return null + const underlined = SETEXT_UNDERLINE.test(lines[start + 1]?.trim() ?? "") + if (!underlined && candidate.length > MAX_TITLE_CHARS) return null + return clamp(candidate) +} + +export function resolveDocumentTitle( + document: TitleSource | null | undefined, +): string | null { + if (!document) return null + + const metadata = document.metadata + const pinned = + metadata && typeof metadata === "object" ? metadata.title : undefined + + for (const candidate of [pinned, document.title]) { + if (typeof candidate === "string") { + const title = clamp(collapse(candidate)) + if (title) return title + } + } + + return typeof document.content === "string" + ? fromContent(document.content) + : null +}