Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
fix(ok): comments travel within OK, never in external clipboard (#2791)
Nick Gomez0c81a9de0499
diff --git a/.changeset/comment-clipboard-contract.md b/.changeset/comment-clipboard-contract.mdnew file mode 100644index 000000000..915383348--- /dev/null+++ b/.changeset/comment-clipboard-contract.md@@ -0,0 +1,5 @@+---+'@inkeep/open-knowledge': patch+---++Comment annotations (`%%…%%` and `<!-- … -->`) now stay with copied content inside OpenKnowledge and never appear in content pasted into other apps. Copying or cutting in the WYSIWYG editor scrubs comments from every public clipboard flavor (plain text, rich HTML in all serializer tiers, table cells) and carries them on a private OpenKnowledge clipboard flavor, so pasting back into OpenKnowledge restores the annotation instead of silently dropping it or leaking it as visible text.diff --git a/knip.config.ts b/knip.config.tsindex 6f8bbbc63..d8a79af2f 100644--- a/knip.config.ts+++ b/knip.config.ts@@ -122,7 +122,9 @@ export default {'packages/server': {entry: ['src/**/*.test.ts'],project: 'src/**',- ignoreDependencies: ['@types/shell-quote'],+ ignoreDependencies: [+ '@types/shell-quote',+ ],},'packages/cli': {entry: ['src/**/*.test.ts', 'scripts/*.ts', 'tests/**/*.ts'],diff --git a/packages/app/src/editor/TiptapEditor.tsx b/packages/app/src/editor/TiptapEditor.tsxindex b099962c0..bdf658ca0 100644--- a/packages/app/src/editor/TiptapEditor.tsx+++ b/packages/app/src/editor/TiptapEditor.tsx@@ -44,6 +44,7 @@ import { BubbleMenuBar } from './bubble-menu/BubbleMenuBar';import {createClipboardHtmlSerializer,createClipboardTextSerializer,+ createCopyCutHandler,createHandleDrop,createHandlePaste,} from './clipboard/index.ts';@@ -233,6 +234,11 @@ function buildClipboardState() {text: createClipboardTextSerializer({ mdManager }),html: createClipboardHtmlSerializer({ mdManager }),paste: createHandlePaste({ mdManager }),+ // Copy/cut intercept: engages only when the copied slice contains+ // clipboard-omitted content (comment annotations) — it then ships the+ // scrubbed public flavors plus the private OK flavor that lets OK→OK+ // paste restore the annotation. All other copies decline to PM native.+ copy: createCopyCutHandler({ mdManager }),// Drop-side dispatcher mirrors paste so dragged text/HTML payloads// flow through the same branch tree (markdown-first tiebreak,// vscode-data, gfm, html, plaintext) instead of PM's default@@ -491,6 +497,10 @@ function buildEditorOptions(args: BuildEditorOptionsArgs): Partial<EditorOptionsclipboardSerializer: clipboard.html.serializer,handlePaste: (view, event) => clipboard.paste(view, event),handleDrop: createSidebarAwareHandleDrop(clipboard.drop, args.onSidebarDrop),+ handleDOMEvents: {+ copy: (view, event) => clipboard.copy(view, event as ClipboardEvent, false),+ cut: (view, event) => clipboard.copy(view, event as ClipboardEvent, true),+ },},// Wrap every extension's lifecycle hooks so each emits an// `ok/cold/ext-{name}-{hook}` span. PROD short-circuits todiff --git a/packages/app/src/editor/clipboard/comment-clipboard-contract.test.ts b/packages/app/src/editor/clipboard/comment-clipboard-contract.test.tsnew file mode 100644index 000000000..8eb9250ea--- /dev/null+++ b/packages/app/src/editor/clipboard/comment-clipboard-contract.test.ts@@ -0,0 +1,681 @@+/**+ * Comment clipboard contract — `%%…%%` / `<!-- … -->` annotations.+ *+ * The contract: comments travel with copied content WITHIN OK (every+ * paste branch), and NEVER reach external targets in any clipboard+ * flavor. Concretely:+ *+ * - text/plain and text/html (walker tier, markdown tier, cell tier)+ * carry ZERO comment bytes — no visible `%%…%%`, no entity-escaped+ * `<!-- -->` text, no hidden spans or HTML comments.+ * - An OK-origin copy of a comment-bearing selection carries the full+ * slice markdown (comments included) on a private clipboard flavor+ * (`application/x-openknowledge-markdown`); the paste router prefers+ * that flavor, so OK→OK paste restores the comment on every branch+ * shape (pm-slice, markdown-first, generic-html).+ * - Cut and copy behave identically with respect to comment carriage.+ * - Copies with no comment content don't engage the private flavor at+ * all (native behavior, byte-identical payloads).+ */++import { MarkdownManager, sharedExtensions } from '@inkeep/open-knowledge-core';+import { getSchema } from '@tiptap/core';+import { EditorState, TextSelection } from '@tiptap/pm/state';+import { describe, expect, test, vi } from 'vitest';++import { createHandlePaste } from './handle-paste.ts';+import { isMarkdown } from './is-markdown.ts';+import { createClipboardHtmlSerializer, createClipboardTextSerializer } from './serialize.ts';++/** The private OK→OK clipboard flavor. Pinned here as a contract constant. */+const INTERNAL_MIME = 'application/x-openknowledge-markdown';++const COMMENT_BYTE_PATTERNS = ['%%', '<!--', '<!--', '<!--', 'hidden note'];++function expectNoCommentBytes(payload: string): void {+ for (const pattern of COMMENT_BYTE_PATTERNS) {+ expect(payload).not.toContain(pattern);+ }+}++const md = new MarkdownManager({ extensions: sharedExtensions });+const schema = getSchema(sharedExtensions);+const textSerializer = createClipboardTextSerializer({ mdManager: md });++/** Build a real EditorState from markdown, select-all, and run the real text/plain serializer. */+function copyAllAsPlainText(markdown: string): string {+ const json = md.parse(markdown);+ const doc = schema.nodeFromJSON(json);+ const state = EditorState.create({ schema, doc });+ const sel = TextSelection.create(doc, 0, doc.content.size);+ const st = state.apply(state.tr.setSelection(sel));+ const view = { state: st } as unknown as Parameters<typeof textSerializer>[1];+ return textSerializer(st.selection.content(), view);+}++function findMarkNames(json: unknown, out = new Set<string>()): Set<string> {+ if (Array.isArray(json)) {+ for (const c of json) findMarkNames(c, out);+ return out;+ }+ if (json && typeof json === 'object') {+ const o = json as { type?: string; marks?: { type: string }[]; content?: unknown };+ for (const m of o.marks ?? []) out.add(m.type);+ findMarkNames(o.content, out);+ }+ return out;+}++function findNodeTypes(json: unknown, out = new Set<string>()): Set<string> {+ if (Array.isArray(json)) {+ for (const c of json) findNodeTypes(c, out);+ return out;+ }+ if (json && typeof json === 'object') {+ const o = json as { type?: string; content?: unknown };+ if (o.type) out.add(o.type);+ findNodeTypes(o.content, out);+ }+ return out;+}++// ─── text/plain: zero comment bytes ────────────────────────────────────++describe('text/plain (copy) omits comment constructs', () => {+ test('inline %%…%% comment is scrubbed from text/plain', () => {+ const out = copyAllAsPlainText('Plain prose before %%hidden note%% and after.');+ expectNoCommentBytes(out);+ expect(out).toContain('Plain prose before');+ expect(out).toContain('and after.');+ });++ test('inline <!-- … --> comment is scrubbed from text/plain', () => {+ const out = copyAllAsPlainText('Plain prose before <!-- hidden note --> and after.');+ expectNoCommentBytes(out);+ expect(out).toContain('Plain prose before');+ });++ test('block %% fence is scrubbed from text/plain', () => {+ const out = copyAllAsPlainText('Visible paragraph.\n\n%%\n\nsecret block body\n\n%%');+ expect(out).not.toContain('secret block body');+ expect(out).not.toContain('%%');+ expect(out).toContain('Visible paragraph.');+ });++ test('comment-only copy yields empty text/plain', () => {+ const out = copyAllAsPlainText('%%only a comment%%');+ expect(out.trim()).toBe('');+ });+});++// ─── isMarkdown gate: comment forms carry zero markdown signals ────────+// (Unchanged behavior, pinned: this is WHY text/plain cannot rescue an+// OK→OK paste and a private flavor is required.)++describe('isMarkdown gate — comment forms carry zero markdown signals', () => {+ test('plain prose + inline %% comment fails the gate', () => {+ expect(isMarkdown('Plain prose before %%hidden note%% and after.')).toBe(false);+ });++ test('plain prose + inline HTML comment fails the gate', () => {+ expect(isMarkdown('Plain prose before <!-- hidden note --> and after.')).toBe(false);+ });++ test('block %% fence alone fails the gate', () => {+ expect(isMarkdown('Visible paragraph.\n\n%%\n\nsecret block body\n\n%%')).toBe(false);+ });++ test('control: the same payload with one markdown signal passes the gate', () => {+ expect(isMarkdown('# Title\n\nProse with %%hidden note%% inside.')).toBe(true);+ });+});++// ─── markdown-tier text/html: zero comment bytes ───────────────────────++describe('markdown-tier text/html omits comment constructs', () => {+ let domInstalled = false;++ async function markdownTierHtmlFor(markdown: string): Promise<string> {+ const { installDomGlobals } = await import('../walk-currency-test-harness.ts');+ if (!domInstalled) {+ installDomGlobals();+ domInstalled = true;+ }+ const mgr = new MarkdownManager({ extensions: sharedExtensions });+ // No view attached → serializeFragment falls to the markdown tier.+ const handle = createClipboardHtmlSerializer({ mdManager: mgr });+ const doc = schema.nodeFromJSON(mgr.parse(markdown));+ const frag = handle.serializer.serializeFragment(doc.content, { document });+ const div = document.createElement('div');+ div.appendChild(frag);+ return div.innerHTML;+ }++ test('inline %% form is scrubbed from the markdown-tier payload', async () => {+ const html = await markdownTierHtmlFor('Plain prose before %%hidden note%% and after.');+ expectNoCommentBytes(html);+ expect(html).toContain('Plain prose before');+ });++ test('inline HTML form is scrubbed from the markdown-tier payload', async () => {+ const html = await markdownTierHtmlFor('Plain prose before <!-- hidden note --> and after.');+ expectNoCommentBytes(html);+ expect(html).toContain('Plain prose before');+ });++ test('block %% fence is scrubbed from the markdown-tier payload', async () => {+ const html = await markdownTierHtmlFor('Visible paragraph.\n\n%%\n\nsecret block body\n\n%%');+ expect(html).not.toContain('secret block body');+ expect(html).not.toContain('%%');+ expect(html).toContain('Visible paragraph.');+ });++ test('drag-style TextSelection (walker bails → markdown tier) is scrubbed', async () => {+ const { installDomGlobals } = await import('../walk-currency-test-harness.ts');+ const { Editor } = await import('@tiptap/core');+ const { TextSelection: TS } = await import('@tiptap/pm/state');+ if (!domInstalled) {+ installDomGlobals();+ domInstalled = true;+ }+ const mgr = new MarkdownManager({ extensions: sharedExtensions });+ const editor = new Editor({+ element: document.createElement('div'),+ extensions: sharedExtensions,+ content: mgr.parse('Prose before %%hidden note%% and after.\n\nSecond paragraph.'),+ });+ try {+ const view = editor.view;+ const handle = createClipboardHtmlSerializer({ mdManager: mgr });+ handle.setView(view);+ const doc = view.state.doc;+ view.dispatch(view.state.tr.setSelection(TS.create(doc, 1, doc.content.size - 1)));+ const slice = view.state.selection.content();+ const frag = handle.serializer.serializeFragment(slice.content, { document });+ const div = document.createElement('div');+ div.appendChild(frag);+ expectNoCommentBytes(div.innerHTML);+ expect(div.innerHTML).toContain('Prose before');+ } finally {+ editor.destroy();+ }+ });+});++// ─── walker tier: comment omission (already-enforced cells, pinned) ────++describe('walker tier (real EditorView, AllSelection) omits comment content', () => {+ let domInstalled = false;++ async function walkerHtmlFor(markdown: string): Promise<string> {+ const { installDomGlobals } = await import('../walk-currency-test-harness.ts');+ const { Editor } = await import('@tiptap/core');+ const { AllSelection } = await import('@tiptap/pm/state');+ if (!domInstalled) {+ installDomGlobals();+ domInstalled = true;+ }+ const mgr = new MarkdownManager({ extensions: sharedExtensions });+ const editor = new Editor({+ element: document.createElement('div'),+ extensions: sharedExtensions,+ content: mgr.parse(markdown),+ });+ try {+ const view = editor.view;+ const handle = createClipboardHtmlSerializer({ mdManager: mgr });+ handle.setView(view);+ view.dispatch(view.state.tr.setSelection(new AllSelection(view.state.doc)));+ const slice = view.state.selection.content();+ const frag = handle.serializer.serializeFragment(slice.content, { document });+ const div = document.createElement('div');+ div.appendChild(frag);+ return div.innerHTML;+ } finally {+ editor.destroy();+ }+ }++ test('inline comment span is dropped from the walker payload', async () => {+ const html = await walkerHtmlFor(+ 'Prose before %%hidden note%% and after.\n\nSecond paragraph.',+ );+ expect(html).toContain('Prose before');+ expect(html).toContain('Second paragraph.');+ expect(html).not.toContain('hidden note');+ expect(html).not.toContain('data-comment-mark');+ });++ test('top-level commentBlock is skipped by the walker payload', async () => {+ const html = await walkerHtmlFor('Visible paragraph.\n\n%%\n\nsecret block body\n\n%%');+ expect(html).toContain('Visible paragraph.');+ expect(html).not.toContain('secret block body');+ });++ test('comment-only selection yields an empty paragraph, zero comment bytes', async () => {+ // Documented external artifact for a comment-only copy: the walker keeps+ // the (now empty) paragraph so PM has an element to stamp data-pm-slice+ // on; external rich targets receive an empty paragraph, never bytes.+ const html = await walkerHtmlFor('%%only a comment%%');+ expect(html).toMatch(/<p[^>]*><\/p>/);+ expect(html).not.toContain('only a comment');+ });+});++// ─── copy/cut interception: the private OK flavor ──────────────────────++type CopyModule = typeof import('./handle-copy.ts');++async function loadCopyModule(): Promise<CopyModule | null> {+ try {+ return await import('./handle-copy.ts');+ } catch {+ return null;+ }+}++interface FakeClipboardData {+ data: Map<string, string>;+ types: string[];+ getData: (k: string) => string;+ setData: (k: string, v: string) => void;+ clearData: () => void;+}++function fakeClipboardEvent(): ClipboardEvent & { clipboardData: FakeClipboardData } {+ const data = new Map<string, string>();+ const clipboardData: FakeClipboardData = {+ data,+ get types() {+ return Array.from(data.keys());+ },+ getData: (k: string) => data.get(k) ?? '',+ setData: (k: string, v: string) => {+ data.set(k, v);+ },+ clearData: () => data.clear(),+ };+ return {+ clipboardData,+ preventDefault: vi.fn(),+ } as unknown as ClipboardEvent & { clipboardData: FakeClipboardData };+}++describe('copy/cut interception — private flavor carries the comment, public flavors do not', () => {+ let domInstalled = false;++ async function withEditor<T>(+ markdown: string,+ fn: (view: import('@tiptap/pm/view').EditorView) => Promise<T> | T,+ ): Promise<T> {+ const { installDomGlobals } = await import('../walk-currency-test-harness.ts');+ const { Editor } = await import('@tiptap/core');+ const { AllSelection } = await import('@tiptap/pm/state');+ if (!domInstalled) {+ installDomGlobals();+ domInstalled = true;+ }+ const mgr = new MarkdownManager({ extensions: sharedExtensions });+ // Mirror the production editorProps wiring (TiptapEditor.tsx): the+ // copy intercept delegates public flavors to these serializers via+ // view.serializeForClipboard.+ const htmlHandle = createClipboardHtmlSerializer({ mdManager: mgr });+ const editor = new Editor({+ element: document.createElement('div'),+ extensions: sharedExtensions,+ content: mgr.parse(markdown),+ editorProps: {+ clipboardTextSerializer: createClipboardTextSerializer({ mdManager: mgr }),+ clipboardSerializer: htmlHandle.serializer,+ },+ });+ try {+ const view = editor.view;+ htmlHandle.setView(view);+ view.dispatch(view.state.tr.setSelection(new AllSelection(view.state.doc)));+ return await fn(view);+ } finally {+ editor.destroy();+ }+ }++ test('copy sets the private flavor with comment bytes; public flavors are scrubbed', async () => {+ const mod = await loadCopyModule();+ if (!mod) expect.fail('handle-copy.ts missing — internal clipboard channel not implemented');+ await withEditor('Prose before %%hidden note%% and after.', (view) => {+ const handler = mod.createCopyCutHandler({ mdManager: md });+ const event = fakeClipboardEvent();+ expect(handler(view, event, false)).toBe(true);+ const internal = event.clipboardData.getData(INTERNAL_MIME);+ expect(internal).toContain('%%hidden note%%');+ expectNoCommentBytes(event.clipboardData.getData('text/html'));+ expectNoCommentBytes(event.clipboardData.getData('text/plain'));+ expect(event.clipboardData.getData('text/plain')).toContain('Prose before');+ });+ });++ test('cut behaves identically to copy for comment carriage and deletes the selection', async () => {+ const mod = await loadCopyModule();+ if (!mod) expect.fail('handle-copy.ts missing — internal clipboard channel not implemented');+ await withEditor('Prose before %%hidden note%% and after.', (view) => {+ const handler = mod.createCopyCutHandler({ mdManager: md });+ const event = fakeClipboardEvent();+ expect(handler(view, event, true)).toBe(true);+ expect(event.clipboardData.getData(INTERNAL_MIME)).toContain('%%hidden note%%');+ expectNoCommentBytes(event.clipboardData.getData('text/html'));+ expectNoCommentBytes(event.clipboardData.getData('text/plain'));+ expect(view.state.doc.textContent).toBe('');+ });+ });++ test('comment-only copy: private flavor carries the comment, public flavors are empty', async () => {+ const mod = await loadCopyModule();+ if (!mod) expect.fail('handle-copy.ts missing — internal clipboard channel not implemented');+ await withEditor('%%only a comment%%', (view) => {+ const handler = mod.createCopyCutHandler({ mdManager: md });+ const event = fakeClipboardEvent();+ expect(handler(view, event, false)).toBe(true);+ expect(event.clipboardData.getData(INTERNAL_MIME)).toContain('%%only a comment%%');+ expect(event.clipboardData.getData('text/plain').trim()).toBe('');+ expect(event.clipboardData.getData('text/html')).not.toContain('only a comment');+ });+ });++ test('a selection with no comment content declines the intercept (native path)', async () => {+ const mod = await loadCopyModule();+ if (!mod) expect.fail('handle-copy.ts missing — internal clipboard channel not implemented');+ await withEditor('Plain prose, no annotations.\n\nSecond paragraph.', (view) => {+ const handler = mod.createCopyCutHandler({ mdManager: md });+ const event = fakeClipboardEvent();+ expect(handler(view, event, false)).toBe(false);+ expect(event.clipboardData.types).toHaveLength(0);+ });+ });++ test('cell selection: public flavors scrubbed, NO private flavor (table convention)', async () => {+ const mod = await loadCopyModule();+ if (!mod) expect.fail('handle-copy.ts missing — internal clipboard channel not implemented');+ const { installDomGlobals } = await import('../walk-currency-test-harness.ts');+ const { Editor } = await import('@tiptap/core');+ const { CellSelection } = await import('@tiptap/pm/tables');+ if (!domInstalled) {+ installDomGlobals();+ domInstalled = true;+ }+ const mgr = new MarkdownManager({ extensions: sharedExtensions });+ const htmlHandle = createClipboardHtmlSerializer({ mdManager: mgr });+ const editor = new Editor({+ element: document.createElement('div'),+ extensions: sharedExtensions,+ content: mgr.parse('| a | b |\n| --- | --- |\n| %%hidden note%% x | d |'),+ editorProps: {+ clipboardTextSerializer: createClipboardTextSerializer({ mdManager: mgr }),+ clipboardSerializer: htmlHandle.serializer,+ },+ });+ try {+ const view = editor.view;+ htmlHandle.setView(view);+ const cellPositions: number[] = [];+ view.state.doc.descendants((node, pos) => {+ if (node.type.name === 'tableCell' || node.type.name === 'tableHeader') {+ cellPositions.push(pos);+ }+ });+ expect(cellPositions.length).toBeGreaterThanOrEqual(3);+ // Select the comment-bearing body cell (third cell: row 2, col 1).+ view.dispatch(+ view.state.tr.setSelection(CellSelection.create(view.state.doc, cellPositions[2])),+ );+ const handler = mod.createCopyCutHandler({ mdManager: mgr });+ const event = fakeClipboardEvent();+ expect(handler(view, event, false)).toBe(true);+ expectNoCommentBytes(event.clipboardData.getData('text/plain'));+ expectNoCommentBytes(event.clipboardData.getData('text/html'));+ expect(event.clipboardData.getData('text/plain')).toContain('x');+ expect(event.clipboardData.getData(INTERNAL_MIME)).toBe('');+ } finally {+ editor.destroy();+ }+ });++ test('interior selection: private flavor peels partial wrappers but keeps the comment', async () => {+ const mod = await loadCopyModule();+ if (!mod) expect.fail('handle-copy.ts missing — internal clipboard channel not implemented');+ const { installDomGlobals } = await import('../walk-currency-test-harness.ts');+ const { Editor } = await import('@tiptap/core');+ const { TextSelection: TS } = await import('@tiptap/pm/state');+ if (!domInstalled) {+ installDomGlobals();+ domInstalled = true;+ }+ const mgr = new MarkdownManager({ extensions: sharedExtensions });+ const htmlHandle = createClipboardHtmlSerializer({ mdManager: mgr });+ const editor = new Editor({+ element: document.createElement('div'),+ extensions: sharedExtensions,+ content: mgr.parse('> Quoted %%hidden note%% text tail'),+ editorProps: {+ clipboardTextSerializer: createClipboardTextSerializer({ mdManager: mgr }),+ clipboardSerializer: htmlHandle.serializer,+ },+ });+ try {+ const view = editor.view;+ htmlHandle.setView(view);+ const doc = view.state.doc;+ // Strict interior subset of the blockquote's text → the text/plain+ // carrier historically peeled the `> ` wrapper; the private flavor+ // must match that shape while keeping the comment bytes.+ view.dispatch(view.state.tr.setSelection(TS.create(doc, 3, doc.content.size - 3)));+ const handler = mod.createCopyCutHandler({ mdManager: mgr });+ const event = fakeClipboardEvent();+ expect(handler(view, event, false)).toBe(true);+ const internal = event.clipboardData.getData(INTERNAL_MIME);+ expect(internal).toContain('%%hidden note%%');+ expect(internal).not.toContain('>');+ expectNoCommentBytes(event.clipboardData.getData('text/plain'));+ } finally {+ editor.destroy();+ }+ });+});++// ─── paste router: the private flavor wins for OK-origin payloads ──────++function fakeDT(data: Record<string, string>): ClipboardEvent {+ return {+ clipboardData: {+ types: Object.keys(data),+ getData: (k: string) => data[k] ?? '',+ },+ } as unknown as ClipboardEvent;+}++// Narrow fake PM view (mirrors handle-paste.test.ts): the router only reads+// selection/codeBlock lookups before deciding a branch.+// biome-ignore lint/suspicious/noExplicitAny: narrow fake for router-only test+function fakeView(parentNodeName = 'paragraph'): any {+ const $from = {+ depth: 1,+ parent: { isTextblock: true },+ node: (_d: number) => ({ type: { name: parentNodeName } }),+ };+ return {+ state: {+ selection: { empty: true, from: 1, to: 1, $from, $to: $from },+ schema: {+ nodes: {},+ marks: {},+ text: (t: string) => ({ text: t }),+ nodeFromJSON: () => ({+ content: { size: 0, childCount: 0, forEach: () => {} },+ slice: () => ({}),+ }),+ },+ tr: {+ replaceSelectionWith: () => ({ setMeta: () => ({ scrollIntoView: () => ({}) }) }),+ replaceSelection: () => ({ setMeta: () => ({ scrollIntoView: () => ({}) }) }),+ },+ },+ dispatch: vi.fn(),+ };+}++describe('paste router — private flavor restores comments on every OK→OK branch shape', () => {+ const internalPayload = 'Plain prose before %%hidden note%% and after.';++ test('pm-slice shape (Branch C cell): private flavor wins, comment carried', () => {+ const mdManager = {+ parse: vi.fn(() => ({+ type: 'doc',+ content: [{ type: 'paragraph', content: [{ type: 'text', text: 'x' }] }],+ })),+ };+ // biome-ignore lint/suspicious/noExplicitAny: fake manager+ const handle = createHandlePaste({ mdManager: mdManager as any });+ const result = handle(+ fakeView(),+ fakeDT({+ [INTERNAL_MIME]: internalPayload,+ 'text/html': '<p data-pm-slice="1 1 []">Plain prose before and after.</p>',+ 'text/plain': 'Plain prose before and after.',+ }),+ );+ expect(result).toBe(true);+ expect(mdManager.parse).toHaveBeenCalledWith(internalPayload);+ });++ test('markdown-first shape (Branch B cell): private flavor wins, comment carried', () => {+ const mdManager = {+ parse: vi.fn(() => ({+ type: 'doc',+ content: [{ type: 'paragraph', content: [{ type: 'text', text: 'x' }] }],+ })),+ };+ // biome-ignore lint/suspicious/noExplicitAny: fake manager+ const handle = createHandlePaste({ mdManager: mdManager as any });+ const internalMd = '# Title\n\nProse with %%hidden note%% inside.';+ const result = handle(+ fakeView(),+ fakeDT({+ [INTERNAL_MIME]: internalMd,+ 'text/html': '<h1 data-pm-slice="1 1 []">Title</h1><p>Prose with inside.</p>',+ 'text/plain': '# Title\n\nProse with inside.',+ }),+ );+ expect(result).toBe(true);+ expect(mdManager.parse).toHaveBeenCalledWith(internalMd);+ });++ test('generic-html shape (Branch D cell): private flavor wins, comment carried', () => {+ const mdManager = {+ parse: vi.fn(() => ({+ type: 'doc',+ content: [{ type: 'paragraph', content: [{ type: 'text', text: 'x' }] }],+ })),+ };+ // biome-ignore lint/suspicious/noExplicitAny: fake manager+ const handle = createHandlePaste({ mdManager: mdManager as any });+ const result = handle(+ fakeView(),+ fakeDT({+ [INTERNAL_MIME]: internalPayload,+ 'text/html': '<p>Plain prose before and after.</p>',+ 'text/plain': 'Plain prose before and after.',+ }),+ );+ expect(result).toBe(true);+ expect(mdManager.parse).toHaveBeenCalledWith(internalPayload);+ });++ test('no private flavor + pm-slice + non-markdown plain → Branch C unchanged', () => {+ const mdManager = { parse: vi.fn() };+ // biome-ignore lint/suspicious/noExplicitAny: fake manager+ const handle = createHandlePaste({ mdManager: mdManager as any });+ const result = handle(+ fakeView(),+ fakeDT({+ 'text/html': '<p data-pm-slice="1 1 []">Plain prose before and after.</p>',+ 'text/plain': 'Plain prose before and after.',+ }),+ );+ expect(result).toBe(false);+ expect(mdManager.parse).not.toHaveBeenCalled();+ });++ test('codeBlock cursor gate precedes the private flavor (verbatim plain insert)', () => {+ const mdManager = { parse: vi.fn() };+ // biome-ignore lint/suspicious/noExplicitAny: fake manager+ const handle = createHandlePaste({ mdManager: mdManager as any });+ const view = fakeView('codeBlock');+ const result = handle(+ view,+ fakeDT({+ [INTERNAL_MIME]: internalPayload,+ 'text/plain': 'Plain prose before and after.',+ }),+ );+ expect(result).toBe(true);+ expect(mdManager.parse).not.toHaveBeenCalled();+ expect(view.dispatch).toHaveBeenCalled();+ });+});++// ─── carrier proof: mdManager.parse restores comment constructs ────────++describe('carrier proof — mdManager.parse restores comment constructs from the private flavor', () => {+ test('inline %% form re-parses to a comment mark', () => {+ const json = md.parse('Prose with %%hidden note%% inside.');+ expect(findMarkNames(json).has('comment')).toBe(true);+ });++ test('inline HTML form re-parses to a comment construct', () => {+ const json = md.parse('Prose with <!-- hidden note --> inside.');+ const kinds = new Set([...findMarkNames(json), ...findNodeTypes(json)]);+ expect(kinds.has('comment') || kinds.has('commentBlock')).toBe(true);+ });++ test('block %% fence re-parses to a commentBlock node', () => {+ const json = md.parse('Visible.\n\n%%\n\nsecret block body\n\n%%');+ expect(findNodeTypes(json).has('commentBlock')).toBe(true);+ });+});++// ─── renderHTML omission contract (attribute level, pinned) ────────────++describe('renderHTML stamps the clipboard opt-out attr', () => {+ test('comment mark renders with data-clipboard-omit="true" + display:none', () => {+ const json = md.parse('Prose with %%hidden note%% inside.');+ const doc = schema.nodeFromJSON(json);+ let found = false;+ doc.descendants((node) => {+ for (const mark of node.marks) {+ if (mark.type.name === 'comment') {+ const spec = mark.type.spec.toDOM?.(mark, true);+ const attrs = (spec as [string, Record<string, string>])?.[1] ?? {};+ expect(attrs['data-clipboard-omit']).toBe('true');+ expect(attrs.style).toContain('display: none');+ found = true;+ }+ }+ });+ expect(found).toBe(true);+ });++ test('commentBlock renders with data-clipboard-omit="true" + display:none', () => {+ const json = md.parse('Visible.\n\n%%\n\nsecret block body\n\n%%');+ const doc = schema.nodeFromJSON(json);+ let found = false;+ doc.descendants((node) => {+ if (node.type.name === 'commentBlock') {+ const spec = node.type.spec.toDOM?.(node);+ const attrs = (spec as [string, Record<string, string>])?.[1] ?? {};+ expect(attrs['data-clipboard-omit']).toBe('true');+ expect(attrs.style).toContain('display: none');+ found = true;+ }+ });+ expect(found).toBe(true);+ });+});diff --git a/packages/app/src/editor/clipboard/comment-scrub.ts b/packages/app/src/editor/clipboard/comment-scrub.tsnew file mode 100644index 000000000..4aa081ff1--- /dev/null+++ b/packages/app/src/editor/clipboard/comment-scrub.ts@@ -0,0 +1,170 @@+/**+ * Clipboard-omitted content scrub — the non-DOM half of the+ * `data-clipboard-omit` contract.+ *+ * The live-DOM walker (`clipboard-walker.ts`) drops subtrees whose+ * rendered element carries `data-clipboard-omit="true"` (comment mark+ * spans, commentBlock asides). Every other outbound flavor — text/plain,+ * the markdown-tier text/html fallback, the CellSelection table tier —+ * serializes from the PM tree and never sees that DOM attribute, so+ * omitted content leaked through them verbatim. This module gives those+ * PM-tree serializers the same omission semantics, keyed off the SAME+ * declaration: a mark/node type is "clipboard-omitted" when its+ * `spec.toDOM` output stamps `data-clipboard-omit="true"`. Deriving+ * membership from the rendered spec (instead of a hardcoded name list)+ * keeps future opt-in descriptors covered without touching this file.+ *+ * OK→OK travel: scrubbing every standard flavor means no public payload+ * can carry an annotation back into OK. Copy/cut therefore rides the+ * unscrubbed slice markdown on {@link OK_INTERNAL_CLIPBOARD_MIME} (see+ * `handle-copy.ts`), which the paste dispatcher prefers — the+ * BlockNote/Lexical pattern of a private internal flavor with public+ * flavors stripped.+ */++import type { Mark, MarkType, Node, NodeType, Schema, Slice } from '@tiptap/pm/model';+import { Fragment, Slice as SliceCtor } from '@tiptap/pm/model';++/**+ * Private clipboard flavor carrying the copied slice's canonical markdown+ * WITH clipboard-omitted content intact. Written only by the copy/cut+ * intercept when the slice contains omitted content; read first by the+ * paste dispatcher.+ */+export const OK_INTERNAL_CLIPBOARD_MIME = 'application/x-openknowledge-markdown';++const OMIT_ATTR = 'data-clipboard-omit';++interface OmittedTypes {+ marks: Set<MarkType>;+ nodes: Set<NodeType>;+}++const omittedTypesCache = new WeakMap<Schema, OmittedTypes>();++function toDomStampsOmit(spec: unknown): boolean {+ if (!Array.isArray(spec)) return false;+ const attrs = spec[1];+ return (+ typeof attrs === 'object' &&+ attrs !== null &&+ !Array.isArray(attrs) &&+ (attrs as Record<string, unknown>)[OMIT_ATTR] === 'true'+ );+}++/**+ * The schema's clipboard-omitted mark/node types, derived once per schema+ * by probing each type's `spec.toDOM` output for the omit attribute. A+ * `toDOM` probe throw (a type whose renderer needs richer context than a+ * bare instance) counts as not-omitted — fail open to "keep the content",+ * never to "drop user content".+ */+function getClipboardOmittedTypes(schema: Schema): OmittedTypes {+ const cached = omittedTypesCache.get(schema);+ if (cached) return cached;+ const result: OmittedTypes = { marks: new Set(), nodes: new Set() };+ for (const markType of Object.values(schema.marks)) {+ try {+ const mark = markType.create();+ if (toDomStampsOmit(markType.spec.toDOM?.(mark, true))) result.marks.add(markType);+ } catch {+ // not omitted+ }+ }+ for (const nodeType of Object.values(schema.nodes)) {+ try {+ const node = nodeType.createAndFill();+ if (node && toDomStampsOmit(nodeType.spec.toDOM?.(node))) result.nodes.add(nodeType);+ } catch {+ // not omitted+ }+ }+ omittedTypesCache.set(schema, result);+ return result;+}++function isOmittedNode(node: Node, omitted: OmittedTypes): boolean {+ if (omitted.nodes.has(node.type)) return true;+ return node.marks.some((mark: Mark) => omitted.marks.has(mark.type));+}++function scrubFragment(fragment: Fragment, omitted: OmittedTypes): Fragment {+ const out: Node[] = [];+ let changed = false;+ fragment.forEach((child) => {+ if (isOmittedNode(child, omitted)) {+ changed = true;+ return;+ }+ const scrubbedContent = scrubFragment(child.content, omitted);+ if (scrubbedContent !== child.content) {+ changed = true;+ out.push(child.copy(scrubbedContent));+ } else {+ out.push(child);+ }+ });+ return changed ? Fragment.fromArray(out) : fragment;+}++/** True when any node in the fragment is clipboard-omitted (or carries an omitted mark). */+function fragmentContainsOmitted(fragment: Fragment, omitted: OmittedTypes): boolean {+ let found = false;+ fragment.forEach((child) => {+ if (found) return;+ if (isOmittedNode(child, omitted) || fragmentContainsOmitted(child.content, omitted)) {+ found = true;+ }+ });+ return found;+}++export function sliceContainsClipboardOmitted(slice: Slice, schema: Schema): boolean {+ const omitted = getClipboardOmittedTypes(schema);+ if (omitted.marks.size === 0 && omitted.nodes.size === 0) return false;+ return fragmentContainsOmitted(slice.content, omitted);+}++/** Depth of the open-node chain reachable from the fragment's edge. */+function maxOpenDepth(fragment: Fragment, side: 'first' | 'last'): number {+ let depth = 0;+ let node = side === 'first' ? fragment.firstChild : fragment.lastChild;+ while (node && !node.isLeaf) {+ depth += 1;+ node = side === 'first' ? node.firstChild : node.lastChild;+ }+ return depth;+}++/**+ * A copy of `slice` with clipboard-omitted content removed. Emptied+ * wrapper blocks are kept (an inline-comment-only paragraph scrubs to an+ * empty paragraph — matching the walker's rendering of the same+ * selection). Open depths are clamped in the corner where a dropped edge+ * node shortened the open chain.+ */+export function stripClipboardOmitted(slice: Slice, schema: Schema): Slice {+ const omitted = getClipboardOmittedTypes(schema);+ if (omitted.marks.size === 0 && omitted.nodes.size === 0) return slice;+ const scrubbed = scrubFragment(slice.content, omitted);+ if (scrubbed === slice.content) return slice;+ const openStart = Math.min(slice.openStart, maxOpenDepth(scrubbed, 'first'));+ const openEnd = Math.min(slice.openEnd, maxOpenDepth(scrubbed, 'last'));+ return new SliceCtor(scrubbed, openStart, openEnd);+}++/** Node-level scrub for the TSV cell path (returns the node unchanged when clean). */+export function stripClipboardOmittedFromNode(node: Node, schema: Schema): Node {+ const omitted = getClipboardOmittedTypes(schema);+ if (omitted.marks.size === 0 && omitted.nodes.size === 0) return node;+ const scrubbed = scrubFragment(node.content, omitted);+ return scrubbed === node.content ? node : node.copy(scrubbed);+}++/** Fragment-level scrub for the CellSelection table tier. */+export function stripClipboardOmittedFromFragment(fragment: Fragment, schema: Schema): Fragment {+ const omitted = getClipboardOmittedTypes(schema);+ if (omitted.marks.size === 0 && omitted.nodes.size === 0) return fragment;+ return scrubFragment(fragment, omitted);+}diff --git a/packages/app/src/editor/clipboard/handle-copy.ts b/packages/app/src/editor/clipboard/handle-copy.tsnew file mode 100644index 000000000..0a862516e--- /dev/null+++ b/packages/app/src/editor/clipboard/handle-copy.ts@@ -0,0 +1,104 @@+/**+ * WYSIWYG copy/cut intercept — the OK→OK travel half of the+ * `data-clipboard-omit` contract.+ *+ * Every standard clipboard flavor is scrubbed of clipboard-omitted+ * content (comment annotations) at the serializers, so no public payload+ * can carry an annotation back into OK. When — and only when — the copied+ * slice contains omitted content, this handler owns the copy/cut event:+ *+ * - `text/html` + `text/plain` via `view.serializeForClipboard(slice)`,+ * which runs the editor's own `clipboardSerializer` /+ * `clipboardTextSerializer` props (scrubbed output, `data-pm-slice`+ * stamped by PM) — byte-identical to what PM's native handler would+ * have written;+ * - the UNSCRUBBED slice markdown on the private+ * `application/x-openknowledge-markdown` flavor, which the paste+ * dispatcher prefers, restoring the annotation on OK→OK paste.+ *+ * Selections with no omitted content decline the intercept (return+ * false) so PM's native copy path runs and behavior stays byte-identical+ * to before this handler existed. Comment-bearing CellSelection copies+ * are intercepted for the scrubbed public flavors only (a scrubbed-empty+ * TSV would otherwise be resurrected as raw bytes by the truthiness+ * fallbacks) but get NO private flavor: their payload belongs to the+ * table clipboard convention and prosemirror-tables' own cell-merge+ * paste handling — a private flavor there would reroute+ * table-into-table paste.+ *+ * Error-path discipline (matches serialize.ts): any throw declines the+ * intercept — PM's native handler still ships the scrubbed flavors, so a+ * failure here can lose OK→OK comment carriage but can never leak.+ */++import type { MarkdownManager } from '@inkeep/open-knowledge-core';+import { TextSelection } from '@tiptap/pm/state';+import { CellSelection } from '@tiptap/pm/tables';+import type { EditorView } from '@tiptap/pm/view';+import { OK_INTERNAL_CLIPBOARD_MIME, sliceContainsClipboardOmitted } from './comment-scrub.ts';+import { logSerializeFail } from './instrument.ts';+import {+ createClipboardTextSerializer,+ sliceToDocJson,+ stripEnclosingMarkerWrappers,+} from './serialize.ts';++interface CopyCutHandlerDeps {+ mdManager: MarkdownManager;+}++export function createCopyCutHandler(deps: CopyCutHandlerDeps) {+ const serializeText = createClipboardTextSerializer(deps);+ return (view: EditorView, event: ClipboardEvent, isCut: boolean): boolean => {+ try {+ const { selection, schema } = view.state;+ if (selection.empty) return false;+ const data = event.clipboardData;+ if (!data) return false;+ const slice = selection.content();+ if (!sliceContainsClipboardOmitted(slice, schema)) return false;++ const { dom } = view.serializeForClipboard(slice);+ // Serialize text through our own scrubbed serializer, NOT via+ // serializeForClipboard's text or someProp: both treat an empty+ // string as "serializer declined" (truthiness fallback) and+ // substitute raw unscrubbed bytes — and empty IS the correct+ // payload for a comment-only copy.+ const text = serializeText(slice, view);++ event.preventDefault();+ data.clearData();+ data.setData('text/html', dom.innerHTML);+ data.setData('text/plain', text);++ if (!(selection instanceof CellSelection)) {+ // Match the pre-scrub text/plain carrier byte-for-byte (the payload+ // the paste dispatcher's markdown branch historically consumed):+ // peel partially-covered marker wrappers for interior text+ // selections, but keep the omitted content. CellSelections get NO+ // private flavor — their payload belongs to the table clipboard+ // convention and prosemirror-tables' cell-merge paste handling;+ // owning the event above still guarantees the scrubbed flavors+ // land instead of a truthiness-fallback resurrect.+ let internalSlice = slice;+ if (selection instanceof TextSelection) {+ internalSlice = stripEnclosingMarkerWrappers(slice, view.state);+ }+ const internalMarkdown = deps.mdManager.serialize(sliceToDocJson(internalSlice, schema));+ data.setData(OK_INTERNAL_CLIPBOARD_MIME, internalMarkdown);+ }++ if (isCut && view.editable) {+ view.dispatch(view.state.tr.deleteSelection().scrollIntoView());+ }+ return true;+ } catch (err) {+ logSerializeFail({+ view: 'wysiwyg',+ kind: 'html',+ reason: `copy-intercept:${(err as Error)?.message ?? 'unknown'}`,+ });+ return false;+ }+ };+}diff --git a/packages/app/src/editor/clipboard/handle-paste.ts b/packages/app/src/editor/clipboard/handle-paste.tsindex 8485ab9d9..3cc970c43 100644--- a/packages/app/src/editor/clipboard/handle-paste.ts+++ b/packages/app/src/editor/clipboard/handle-paste.ts@@ -72,6 +72,7 @@ import { Fragment, type Node as ProseMirrorNode } from '@tiptap/pm/model';import { type EditorState, TextSelection, type Transaction } from '@tiptap/pm/state';import type { EditorView } from '@tiptap/pm/view';import { PREVENT_AUTOLINK_META } from '../gfm-autolink-plugin.ts';+import { OK_INTERNAL_CLIPBOARD_MIME } from './comment-scrub.ts';import { type ClipboardSource, detectSource } from './detect-source.ts';import {type ClipboardBranch,@@ -180,6 +181,20 @@ function handleDropOrPaste(}}+ // Private OK flavor: an OK-origin copy whose slice contained+ // clipboard-omitted content (comment annotations) carries the full+ // slice markdown here, because every public flavor ships scrubbed (see+ // comment-scrub.ts). Prefer it over the public flavors so OK→OK paste+ // restores the annotation regardless of which branch shape the public+ // payload would have taken. Runs after the shift/codeblock/lone-URL+ // gates so those explicit gestures keep their meaning.+ const internal = dt.getData(OK_INTERNAL_CLIPBOARD_MIME);+ if (internal && tryBranchMarkdown(view, internal, deps, 'internal', source)) {+ logSourceDetected({ view: 'wysiwyg', branch: 'internal', source });+ logIfSlow(start, { op: surface, view: 'wysiwyg', branch: 'internal', source });+ return true;+ }+// Branch A: VS Code with language metadata.const vscodeData = dt.getData('vscode-editor-data');if (vscodeData && plain && tryBranchA(view, vscodeData, plain, source)) {@@ -372,7 +387,7 @@ function tryBranchMarkdown(view: EditorView,markdown: string,deps: PasteDispatcherDeps,- branchLabel: 'B' | 'E' | 'url',+ branchLabel: 'B' | 'E' | 'url' | 'internal',source: ClipboardSource,): boolean {let json: JSONContent;diff --git a/packages/app/src/editor/clipboard/index.ts b/packages/app/src/editor/clipboard/index.tsindex 9eccca09d..120355e30 100644--- a/packages/app/src/editor/clipboard/index.ts+++ b/packages/app/src/editor/clipboard/index.ts@@ -15,6 +15,7 @@*/export { OPT_OUT_ATTR } from './clipboard-sanitize.ts';+export { createCopyCutHandler } from './handle-copy.ts';export { createHandleDrop, createHandlePaste } from './handle-paste.ts';export {createClipboardHtmlSerializer,diff --git a/packages/app/src/editor/clipboard/instrument.ts b/packages/app/src/editor/clipboard/instrument.tsindex 48c14c254..39d225101 100644--- a/packages/app/src/editor/clipboard/instrument.ts+++ b/packages/app/src/editor/clipboard/instrument.ts@@ -154,6 +154,7 @@ export type ClipboardBranch =| 'D'| 'E'| 'url'+ | 'internal'| 'shift'| 'codeblock'| 'serialize';diff --git a/packages/app/src/editor/clipboard/serialize.ts b/packages/app/src/editor/clipboard/serialize.tsindex aa96fe6c9..5abdfeb45 100644--- a/packages/app/src/editor/clipboard/serialize.ts+++ b/packages/app/src/editor/clipboard/serialize.ts@@ -43,6 +43,11 @@ import {type WalkerEnv,walkLiveDomToInlineStyledFragment,} from './clipboard-walker.ts';+import {+ stripClipboardOmitted,+ stripClipboardOmittedFromFragment,+ stripClipboardOmittedFromNode,+} from './comment-scrub.ts';import { classifyError, logSerializeFail } from './instrument.ts';interface WysiwygSerializerDeps {@@ -67,7 +72,11 @@ export interface ClipboardHtmlSerializerHandle {* to construct before the editor mounts.*/export function createClipboardTextSerializer(deps: WysiwygSerializerDeps) {- return (slice: Slice, view: EditorView): string => {+ return (rawSlice: Slice, view: EditorView): string => {+ // Clipboard-omitted content (comment annotations) must not reach the+ // text/plain payload; scrub once at entry so every path below —+ // including the textBetween fallback — serializes the clean slice.+ const slice = stripClipboardOmitted(rawSlice, view.state.schema);// CellSelection copies belong to the table clipboard convention, not// to the markdown pipeline. `\t`-separated cells / `\n`-separated// rows is what browsers and spreadsheets (Excel, Sheets, Numbers)@@ -158,7 +167,8 @@ export function serializeCellSelectionAsText(selection: CellSelection): string {* in-cell break as a real newline.*/function cellText(cell: Node): string {- return cell.textBetween(0, cell.content.size, '\n', (leaf) =>+ const scrubbed = stripClipboardOmittedFromNode(cell, cell.type.schema);+ return scrubbed.textBetween(0, scrubbed.content.size, '\n', (leaf) =>leaf.type.name === 'hardBreak' ? '\n' : '',);}@@ -218,7 +228,7 @@ function selectionCoversAllTextOf($from: ResolvedPos, $to: ResolvedPos, depth: n* loop (fail-safe: under-peel falls back to the pre-existing full-structure* output).*/-function stripEnclosingMarkerWrappers(slice: Slice, state: EditorState): Slice {+export function stripEnclosingMarkerWrappers(slice: Slice, state: EditorState): Slice {const selection = state.selection;if (!(selection instanceof TextSelection) || selection.empty) return slice;const { $from, $to } = selection;@@ -340,7 +350,12 @@ class MdastClipboardSerializer extends DOMSerializer {try {const schema = fragment.firstChild?.type.schema ?? view.state.schema;const defaultSerializer = DOMSerializer.fromSchema(schema);- const wrapped = wrapAsTableFragment(fragment, schema);+ // The default DOMSerializer would render comment spans (hidden but+ // byte-carrying) into the cell payload — scrub before serializing.+ const wrapped = wrapAsTableFragment(+ stripClipboardOmittedFromFragment(fragment, schema),+ schema,+ );return defaultSerializer.serializeFragment(wrapped, { document }, target);} catch (err) {logSerializeFail({@@ -405,7 +420,12 @@ class MdastClipboardSerializer extends DOMSerializer {slice = new SliceCtor(fragment, 0, 0);}}- const html = markdownToHtml(sliceToMarkdown(slice, schema, this.mdManager));+ // Same omission semantics as the walker tier: the markdown tier is an+ // external-facing text/html payload, so clipboard-omitted content is+ // scrubbed before serialization.+ const html = markdownToHtml(+ sliceToMarkdown(stripClipboardOmitted(slice, schema), schema, this.mdManager),+ );const frag = parseHtmlToDocumentFragment(html);if (target) {for (const child of Array.from(frag.childNodes)) target.appendChild(child);@@ -588,8 +608,9 @@ function buildWalkerEnv(view: EditorView, mdManager: MarkdownManager): WalkerEnv* and whole-node doc slices (the walker's source-fallback) are unaffected by* the discard.*- * Exported only for unit-test reach; the production caller is- * `sliceToMarkdown` above.+ * Production callers: `sliceToMarkdown` above and the copy/cut intercept+ * (`handle-copy.ts`), which serializes the unscrubbed slice for the+ * private OK clipboard flavor.*/export function sliceToDocJson(slice: Slice, schema: Schema): JSONContent {let content = slice.content;diff --git a/packages/app/src/editor/clipboard/wysiwyg-stop-rule.test.ts b/packages/app/src/editor/clipboard/wysiwyg-stop-rule.test.tsindex 98d9887c2..922afe3af 100644--- a/packages/app/src/editor/clipboard/wysiwyg-stop-rule.test.ts+++ b/packages/app/src/editor/clipboard/wysiwyg-stop-rule.test.ts@@ -1,4 +1,4 @@-import { describe, expect, test } from 'bun:test';+import { describe, expect, test } from 'vitest';import { buildPatternDConstructorOptions } from '../TiptapEditor';import { buildSeededPatternDProvider, fakeClipboard } from '../walk-currency-test-harness';@@ -29,12 +29,21 @@ describe('WYSIWYG STOP rule — ProseMirror clipboard hooks', () => {expect(props.clipboardSerializer).toBe(fakeClipboard.html.serializer);});- test('does not wire DOM-level copy/cut/dragstart handlers on editorProps', () => {+ test('wires copy/cut ONLY to the comment-carriage intercept; dragstart stays PM-native', () => {+ // Narrowed STOP rule (precedent #19(b)): PM's clipboard hooks remain the+ // payload producers, and dragstart must stay PM-native so `view.dragging`+ // keeps the internal DnD fast path. The single sanctioned DOM-level+ // exception is the copy/cut comment-carriage intercept (handle-copy.ts):+ // PM's hook API exposes no clipboardData, so the private OK flavor that+ // lets comments travel OK→OK cannot exist via hooks alone. The intercept+ // DELEGATES payload production to view.serializeForClipboard (PM hooks+ // included) and declines every slice without clipboard-omitted content.const props = buildWysiwygEditorProps();const handleDOMEvents = props.handleDOMEvents ?? {};- expect(handleDOMEvents).not.toHaveProperty('copy');- expect(handleDOMEvents).not.toHaveProperty('cut');+ expect(typeof handleDOMEvents.copy).toBe('function');+ expect(typeof handleDOMEvents.cut).toBe('function');expect(handleDOMEvents).not.toHaveProperty('dragstart');+ expect(handleDOMEvents).not.toHaveProperty('paste');});});diff --git a/packages/app/src/editor/walk-currency-test-harness.ts b/packages/app/src/editor/walk-currency-test-harness.tsindex 257336024..8715ceaf2 100644--- a/packages/app/src/editor/walk-currency-test-harness.ts+++ b/packages/app/src/editor/walk-currency-test-harness.ts@@ -86,6 +86,7 @@ export const fakeClipboard = {html: { serializer: {}, setView: () => {} },paste: () => false,drop: () => false,+ copy: () => false,} as unknown as ClipboardArg;export function seedFragmentParagraph(ydoc: Y.Doc, text: string): void {diff --git a/packages/core/src/bridge/bind-frontmatter-doc.ts b/packages/core/src/bridge/bind-frontmatter-doc.tsindex c014b1413..8f9d95287 100644--- a/packages/core/src/bridge/bind-frontmatter-doc.ts+++ b/packages/core/src/bridge/bind-frontmatter-doc.ts@@ -1,3 +1,4 @@+import type * as Y from 'yjs';import type { Err, Ok, Result } from '../config/result.ts';import { type FrontmatterValidationError, toFrontmatterIssue } from '../frontmatter/errors.ts';diff --git a/packages/core/src/bridge/bridge-invariant.ts b/packages/core/src/bridge/bridge-invariant.tsindex 005627195..8bfdb40cd 100644--- a/packages/core/src/bridge/bridge-invariant.ts+++ b/packages/core/src/bridge/bridge-invariant.ts@@ -1,3 +1,4 @@+import { fnv1aDigest } from './hash-util.ts';export type BridgeInvariantSite = 'observer-b' | 'persistence' | 'test-harness';diff --git a/packages/core/src/bridge/doc-boundary-space.ts b/packages/core/src/bridge/doc-boundary-space.tsindex 8890f6739..c18c086d5 100644--- a/packages/core/src/bridge/doc-boundary-space.ts+++ b/packages/core/src/bridge/doc-boundary-space.ts@@ -1,3 +1,4 @@+import { FRONTMATTER_RE, stripFrontmatter } from '../extensions/frontmatter.ts';const LEADING_BOUNDARY_RE = /^(?:\r?\n)+/;diff --git a/packages/core/src/bridge/growth-detect.ts b/packages/core/src/bridge/growth-detect.tsindex 9d9c244b0..463e89595 100644--- a/packages/core/src/bridge/growth-detect.ts+++ b/packages/core/src/bridge/growth-detect.ts@@ -1,3 +1,4 @@+const DEFAULT_MIN_SUBSTANTIVE_LINE_LENGTH = 16;export const DUPLICATION_GATE_MIN_LINE_LENGTH = 8;diff --git a/packages/core/src/bridge/merge-three-way.ts b/packages/core/src/bridge/merge-three-way.tsindex 3ab9cc6ef..3c927eb47 100644--- a/packages/core/src/bridge/merge-three-way.ts+++ b/packages/core/src/bridge/merge-three-way.ts@@ -38,6 +38,7 @@ function mergeThreeWayImpl(baseline: string, userText: string, agentText: stringreturn parts.join('\n');}+export type BridgeMergeContentLossSide = 'user' | 'agent';export type BridgeMergeContentLossWhich = 'substring' | 'order' | 'growth';diff --git a/packages/core/src/bridge/normalize.ts b/packages/core/src/bridge/normalize.tsindex 4b8890476..3f0880aa5 100644--- a/packages/core/src/bridge/normalize.ts+++ b/packages/core/src/bridge/normalize.ts@@ -1,3 +1,4 @@+const COMMONMARK_ESCAPE_RE = /\\([!"#$%&'()*+,\-./:;<=>?@[\]^_`{|}~])/g;const TABLE_ALIGN_ROW_RE = /^\s*\|?\s*:?-+:?\s*(\|\s*:?-+:?\s*)+\|?\s*$/;diff --git a/packages/core/src/bridge/pm-structural-equivalence.ts b/packages/core/src/bridge/pm-structural-equivalence.tsindex 754dc5cc2..0be5203e4 100644--- a/packages/core/src/bridge/pm-structural-equivalence.ts+++ b/packages/core/src/bridge/pm-structural-equivalence.ts@@ -32,6 +32,7 @@ const BR_SENTINEL: PmStructuralNode = { type: '__br__' };const BR_LITERAL_RE = /^<br\s*\/?>$/i;+interface DegradeEntry {readonly label: string;readonly severity: ToleranceClassSeverity;@@ -127,6 +128,7 @@ export interface ComparePmStructuralOptions {ignoreAttrs?: (attrKey: string) => boolean;}+/** Rebuild a node with `fn` applied to each child; identity when childless.* Shared by the degrade canonicalizers so none re-implements the walk. */function mapChildren(@@ -248,6 +250,7 @@ function applyDegrades(tree: PmStructuralNode): {return { normalized: current, fired };}+export function comparePmStructural(expected: PmStructuralNode,actual: PmStructuralNode,diff --git a/packages/core/src/bridge/subsequence.ts b/packages/core/src/bridge/subsequence.tsindex af20de1e2..dca644141 100644--- a/packages/core/src/bridge/subsequence.ts+++ b/packages/core/src/bridge/subsequence.ts@@ -1,3 +1,4 @@+/** True when `needle` is a subsequence of `haystack` (two-pointer, O(n+m)):* insertions in `haystack` are free; any dropped or substituted `needle` byte* fails. */diff --git a/packages/core/src/markdown/callout-transformer.ts b/packages/core/src/markdown/callout-transformer.tsindex 83d47404a..a363dfd54 100644--- a/packages/core/src/markdown/callout-transformer.ts+++ b/packages/core/src/markdown/callout-transformer.ts@@ -1,3 +1,4 @@+import type { Blockquote, Paragraph, Root } from 'mdast';import type { MdxJsxAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';import { visit } from 'unist-util-visit';diff --git a/packages/core/src/markdown/comment-promoter.ts b/packages/core/src/markdown/comment-promoter.tsindex 193e286b0..47f0d07e4 100644--- a/packages/core/src/markdown/comment-promoter.ts+++ b/packages/core/src/markdown/comment-promoter.ts@@ -1,3 +1,4 @@+import type { Nodes, Paragraph, PhrasingContent, Root, RootContent, Text } from 'mdast';import { SKIP, visit } from 'unist-util-visit';import type { VFile } from 'vfile';diff --git a/packages/core/src/markdown/dedent-block-jsx-close.ts b/packages/core/src/markdown/dedent-block-jsx-close.tsindex ece5c02a1..b6299a948 100644--- a/packages/core/src/markdown/dedent-block-jsx-close.ts+++ b/packages/core/src/markdown/dedent-block-jsx-close.ts@@ -1,3 +1,4 @@+import { findFencedRegions, isInsideFence } from './fence-regions.ts';const INDENTED_BLOCK_JSX_CLOSE_RE = /^([ ]{1,3})(<\/[A-Z][A-Za-z0-9_]*\s*>)([ \t]*)$/gm;diff --git a/packages/core/src/markdown/details-accordion-promoter.ts b/packages/core/src/markdown/details-accordion-promoter.tsindex 54774764a..acd398aa6 100644--- a/packages/core/src/markdown/details-accordion-promoter.ts+++ b/packages/core/src/markdown/details-accordion-promoter.ts@@ -1,3 +1,4 @@+import type { Nodes, Paragraph, Parent, Root, Text } from 'mdast';import type { MdxJsxAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';import { visit } from 'unist-util-visit';diff --git a/packages/core/src/markdown/fence-regions.ts b/packages/core/src/markdown/fence-regions.tsindex c7518d614..fb5ac8e8a 100644--- a/packages/core/src/markdown/fence-regions.ts+++ b/packages/core/src/markdown/fence-regions.ts@@ -1,3 +1,4 @@+const FENCE_RE = /^(`{3,}|~{3,})/gm;export function findFencedRegions(src: string): Array<[number, number]> {diff --git a/packages/core/src/markdown/fixtures/index.ts b/packages/core/src/markdown/fixtures/index.tsindex 00f5771ee..6931623c7 100644--- a/packages/core/src/markdown/fixtures/index.ts+++ b/packages/core/src/markdown/fixtures/index.ts@@ -1,3 +1,4 @@+import { readFileSync } from 'node:fs';import { dirname, resolve } from 'node:path';import { fileURLToPath } from 'node:url';@@ -8,6 +9,7 @@ function fixturePath(...segments: string[]): string {return resolve(FIXTURES_DIR, ...segments);}+interface GfmExample {section: string;markdown: string;@@ -17,6 +19,7 @@ export function loadGfmExamples(): GfmExample[] {return JSON.parse(readFileSync(fixturePath('gfm', 'examples.json'), 'utf8')) as GfmExample[];}+interface MdxCrashEntry {id: string;input: string;@@ -68,6 +71,7 @@ export function loadLargeEmbedFixtures(): LargeEmbedFixture[] {) as LargeEmbedFixture[];}+export function loadPrd6955Before(): string {return readFileSync(fixturePath('regression', 'prd-6955-before.md'), 'utf8');}@@ -76,6 +80,7 @@ export function loadPrd6955CorruptedTriplicated(): string {return readFileSync(fixturePath('regression', 'prd-6955-corrupted-triplicated.md'), 'utf8');}+export interface NgPinnedCase {id: string;name: string;@@ -92,6 +97,7 @@ export function loadNgPinnedCases(): NgPinnedCase[] {) as NgPinnedCase[];}+export function loadLargeRealistic(): string {return readFileSync(fixturePath('perf', 'large-realistic.md'), 'utf8');}diff --git a/packages/core/src/markdown/fixtures/perf/generate.ts b/packages/core/src/markdown/fixtures/perf/generate.tsindex 8b1eb8519..daa3ef82b 100644--- a/packages/core/src/markdown/fixtures/perf/generate.ts+++ b/packages/core/src/markdown/fixtures/perf/generate.ts@@ -1,3 +1,4 @@+import { writeFileSync } from 'node:fs';import { dirname, resolve } from 'node:path';import { fileURLToPath } from 'node:url';@@ -10,6 +11,7 @@ const BASELINE_ONLY_COUNTS = [500, 2500] as const;const SEED = 0xf1de1117;+function mulberry32(seed: number): () => number {let a = seed >>> 0;return () => {@@ -36,6 +38,7 @@ function pickWeighted<T>(rand: () => number, items: readonly [T, number][]): T {return items[items.length - 1][0];}+const WORDS = ['lorem','ipsum',@@ -153,6 +156,7 @@ function mdxBlock(rand: () => number): string {return `<${name}>\n\n${sentence(rand)}\n\n</${name}>`;}+type BlockKind = 'paragraph' | 'heading' | 'list' | 'code' | 'table' | 'mdx';const MIX: readonly [BlockKind, number][] = [@@ -191,6 +195,7 @@ function generateDocument(blockCount: number, seed: number): string {return `${blocks.join('\n\n')}\n`;}+function main(): void {for (const count of [...BLOCK_COUNTS, ...BASELINE_ONLY_COUNTS]) {const doc = generateDocument(count, SEED);diff --git a/packages/core/src/markdown/guard-flanking-matrix.ts b/packages/core/src/markdown/guard-flanking-matrix.tsindex 420dc0fe5..32c055c5b 100644--- a/packages/core/src/markdown/guard-flanking-matrix.ts+++ b/packages/core/src/markdown/guard-flanking-matrix.ts@@ -7,6 +7,7 @@ import {import { BACKSLASH_GUARD_SUBSTITUTIONS, encodeBackslashEscapes } from './backslash-escape-guard.ts';import { ENTITY_REF_GUARD_SUBSTITUTIONS, encodeEntityRefs } from './entity-ref-guard.ts';+export const ATTENTION_DELIMITERS = ['*', '_', '**', '~~', '=='] as const;export type FlankClass = 'whitespace' | 'punctuation' | 'other';diff --git a/packages/core/src/markdown/handler-shadow-audit.ts b/packages/core/src/markdown/handler-shadow-audit.tsindex 2653473da..283913255 100644--- a/packages/core/src/markdown/handler-shadow-audit.ts+++ b/packages/core/src/markdown/handler-shadow-audit.ts@@ -1,3 +1,4 @@+export interface HandlerShadowWitness {input: string;expect: 'byte' | 'byte-and-reparse-type';diff --git a/packages/core/src/markdown/highlight-promoter.ts b/packages/core/src/markdown/highlight-promoter.tsindex f55912407..6319f264f 100644--- a/packages/core/src/markdown/highlight-promoter.ts+++ b/packages/core/src/markdown/highlight-promoter.ts@@ -1,3 +1,4 @@+import type { Nodes, Parent, PhrasingContent, Root, Text } from 'mdast';import type { MdxJsxTextElement } from 'mdast-util-mdx';import { SKIP, visit } from 'unist-util-visit';diff --git a/packages/core/src/markdown/html-to-mdast.ts b/packages/core/src/markdown/html-to-mdast.tsindex b1f252c31..8dc3a81b5 100644--- a/packages/core/src/markdown/html-to-mdast.ts+++ b/packages/core/src/markdown/html-to-mdast.ts@@ -1,3 +1,4 @@+import type { Root as HastRoot } from 'hast';import type { List, Root as MdastRoot } from 'mdast';import rehypeParse from 'rehype-parse';@@ -85,7 +86,8 @@ export function htmlToMdast(html: string, options?: HtmlToMdastOptions): MdastRothrow new HtmlPayloadTooLargeError(html.length, maxBytes);}- const processor = unified().use(rehypeParse, { fragment: true });+ const processor = unified()+ .use(rehypeParse, { fragment: true });for (const plugin of cleanupPlugins) {processor.use(plugin);diff --git a/packages/core/src/markdown/image-promoter.ts b/packages/core/src/markdown/image-promoter.tsindex 706fa9afb..994eb6917 100644--- a/packages/core/src/markdown/image-promoter.ts+++ b/packages/core/src/markdown/image-promoter.ts@@ -1,3 +1,4 @@+import type { Image, Paragraph, Root } from 'mdast';import type { MdxJsxAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';import { visit } from 'unist-util-visit';diff --git a/packages/core/src/markdown/index.ts b/packages/core/src/markdown/index.tsindex 8b36807fd..fc30bda02 100644--- a/packages/core/src/markdown/index.ts+++ b/packages/core/src/markdown/index.ts@@ -1,3 +1,4 @@+import {type FromProseMirrorOptions,fromPmMark,@@ -196,6 +197,7 @@ export class MarkdownManager {}}+const registry = createRegistry();function destructureAttrs(@@ -244,6 +246,7 @@ function destructureAttrs(return result;}+function hasDirtyDescendant(node: PmNode): boolean {let found = false;node.descendants((child) => {@@ -263,6 +266,7 @@ function effectiveDirty(node: PmNode, freshnessChecker?: StructuralFreshnessChecreturn freshnessChecker ? freshnessChecker.isDiverged(node.toJSON()) : false;}+function isEmptyMdastParagraph(node: MdastNodes): boolean {if (node.type !== 'paragraph') return false;const children = node.children ?? [];@@ -331,6 +335,7 @@ function extractTextFromMdastNodes(nodes: MdastNodes[]): string {return out;}+import {AUDIO_EXTENSIONS,FILE_ATTACHMENT_EXTENSIONS,@@ -577,6 +582,7 @@ function buildMdastToPmHandlers(}));}+if (m.emphasis) {handlers.emphasis = toPmMark(m.emphasis, (node: Emphasis) => ({sourceDelimiter: node.data?.sourceDelimiter ?? '*',@@ -657,6 +663,7 @@ function buildMdastToPmHandlers(}));}+if (m.link) {const sourceLiteralMark = m.sourceLiteral;handlers.link = (node: Link, _parent: MdastParent, state: MdastToPmState) => {@@ -935,6 +942,7 @@ function buildMdastToPmHandlers(};}+const blockUnknownHandler = (node: {type: string;position?: { start: { offset: number }; end: { offset: number } };@@ -1060,6 +1068,7 @@ function buildMdastToPmHandlers(return handlers as RemarkProseMirrorOptions['handlers'];}+function buildPmToMdastHandlers(schema: Schema,freshness: FreshnessCheckerHolder,diff --git a/packages/core/src/markdown/lint/config-files.ts b/packages/core/src/markdown/lint/config-files.tsindex 312c9c74b..94b34dee1 100644--- a/packages/core/src/markdown/lint/config-files.ts+++ b/packages/core/src/markdown/lint/config-files.ts@@ -1,3 +1,4 @@+const MARKDOWNLINT_JSON_CONFIG_FILES: ReadonlySet<string> = new Set(['.markdownlint.json','.markdownlint.jsonc',diff --git a/packages/core/src/markdown/lint/config-schemas.ts b/packages/core/src/markdown/lint/config-schemas.tsindex e78a1381d..207cd95c2 100644--- a/packages/core/src/markdown/lint/config-schemas.ts+++ b/packages/core/src/markdown/lint/config-schemas.ts@@ -29,6 +29,7 @@ const fullPluginShape = Object.fromEntries(LINT_PLUGINS.map((plugin) => [plugin.id, plugin.sliceSchema]),) as z.ZodRawShape;+export const LinterConfigSchema = z.object({enabled: z.boolean(),plugins: z.object(fullPluginShape),diff --git a/packages/core/src/markdown/lint/default-config.ts b/packages/core/src/markdown/lint/default-config.tsindex d48eea5e4..a51f2ffb0 100644--- a/packages/core/src/markdown/lint/default-config.ts+++ b/packages/core/src/markdown/lint/default-config.ts@@ -6,6 +6,7 @@ export const DEFAULT_MARKDOWNLINT_CONFIG: Record<string, MarkdownlintRuleSettingMD013: false,};+export function resolveMarkdownlintConfig(rules: Record<string, MarkdownlintRuleSetting> | undefined,): Configuration {diff --git a/packages/core/src/markdown/lint/index.ts b/packages/core/src/markdown/lint/index.tsindex 8a154ce30..d763d8d28 100644--- a/packages/core/src/markdown/lint/index.ts+++ b/packages/core/src/markdown/lint/index.ts@@ -1,3 +1,4 @@+import { LINT_PLUGINS, type LinterConfig } from './plugins.ts';import type { LintDiagnostic } from './types.ts';diff --git a/packages/core/src/markdown/lint/plugins.ts b/packages/core/src/markdown/lint/plugins.tsindex 1cd40ef3a..65a1b564c 100644--- a/packages/core/src/markdown/lint/plugins.ts+++ b/packages/core/src/markdown/lint/plugins.ts@@ -1,3 +1,4 @@+import { z } from 'zod';import { DEFAULT_MARKDOWNLINT_CONFIG, resolveMarkdownlintConfig } from './default-config.ts';import { fixMarkdownText, runMarkdownlint } from './markdownlint-runner.ts';@@ -8,6 +9,7 @@ import {type MarkdownlintSlice,} from './types.ts';+const MarkdownlintRuleSettingSchema = z.union([z.boolean(),z.enum(MARKDOWNLINT_RULE_SEVERITIES),diff --git a/packages/core/src/markdown/lint/types.ts b/packages/core/src/markdown/lint/types.tsindex 617f6e5b9..3651bd7eb 100644--- a/packages/core/src/markdown/lint/types.ts+++ b/packages/core/src/markdown/lint/types.ts@@ -1,3 +1,4 @@+export const LINT_PLUGIN_IDS = ['markdownlint'] as const;export type LintPluginId = (typeof LINT_PLUGIN_IDS)[number];@@ -41,6 +42,7 @@ export interface MarkdownlintSlice {rules: Record<string, MarkdownlintRuleSetting>;}+interface RuleOptionSpecBase {key: string;description: string;diff --git a/packages/core/src/markdown/math-promoter.ts b/packages/core/src/markdown/math-promoter.tsindex a5b511f25..bd79424c7 100644--- a/packages/core/src/markdown/math-promoter.ts+++ b/packages/core/src/markdown/math-promoter.ts@@ -1,3 +1,4 @@+import type { Code, Root } from 'mdast';import type { Math as MdastMath } from 'mdast-util-math';import type { MdxJsxAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';diff --git a/packages/core/src/markdown/mdast-to-hast-handlers.ts b/packages/core/src/markdown/mdast-to-hast-handlers.tsindex 679c72ef7..f84967798 100644--- a/packages/core/src/markdown/mdast-to-hast-handlers.ts+++ b/packages/core/src/markdown/mdast-to-hast-handlers.ts@@ -1,3 +1,4 @@+import type { Comment, Element, ElementContent, Properties } from 'hast';import type { FootnoteDefinition, FootnoteReference } from 'mdast';import type { MdxJsxFlowElement, MdxJsxTextElement } from 'mdast-util-mdx';diff --git a/packages/core/src/markdown/mdast-to-html.ts b/packages/core/src/markdown/mdast-to-html.tsindex 8ce2b2492..df788a80d 100644--- a/packages/core/src/markdown/mdast-to-html.ts+++ b/packages/core/src/markdown/mdast-to-html.ts@@ -1,3 +1,4 @@+import type { Element, Root as HastRoot, Text as HastText } from 'hast';import type { Root as MdastRoot, Text as MdastText } from 'mdast';import type { Handler } from 'mdast-util-to-hast';diff --git a/packages/core/src/markdown/merged-walker.ts b/packages/core/src/markdown/merged-walker.tsindex bfd7e3109..fa3cfcd86 100644--- a/packages/core/src/markdown/merged-walker.ts+++ b/packages/core/src/markdown/merged-walker.ts@@ -1,3 +1,4 @@+import type { Nodes, Parent, Root } from 'mdast';import { SKIP, visit } from 'unist-util-visit';import type { VFile } from 'vfile';diff --git a/packages/core/src/markdown/mermaid-promoter.ts b/packages/core/src/markdown/mermaid-promoter.tsindex 1a897fca8..17ed2b829 100644--- a/packages/core/src/markdown/mermaid-promoter.ts+++ b/packages/core/src/markdown/mermaid-promoter.ts@@ -1,3 +1,4 @@+import type { Code, Root } from 'mdast';import type { MdxJsxAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';import { visit } from 'unist-util-visit';diff --git a/packages/core/src/markdown/parse-with-fallback.ts b/packages/core/src/markdown/parse-with-fallback.tsindex 9864b3b60..7e4a9a48b 100644--- a/packages/core/src/markdown/parse-with-fallback.ts+++ b/packages/core/src/markdown/parse-with-fallback.ts@@ -168,6 +168,7 @@ export function parseRecursive(}}+interface VFilePlace {offset?: number;start?: { offset?: number };@@ -186,6 +187,7 @@ function extractErrorOffset(err: unknown): number | undefined {return undefined;}+interface Region {start: number;end: number;@@ -209,6 +211,7 @@ function nearestBlankLineAfter(src: string, offset: number): number | null {return null;}+export interface TagEvent {kind: 'open' | 'close' | 'self-close';name: string;@@ -355,6 +358,7 @@ function findFallbackRegion(src: string, errorOffset: number): Region {return { start: blockStart, end: blockEnd };}+interface SourceBlock {src: string;start: number;@@ -452,6 +456,7 @@ function tryPerBlockFallback(};}+function wholeDocRawText(source: string): JSONContent {return {type: 'doc',diff --git a/packages/core/src/markdown/parser-drop-closure.ts b/packages/core/src/markdown/parser-drop-closure.tsindex e6ab4fd57..43d420187 100644--- a/packages/core/src/markdown/parser-drop-closure.ts+++ b/packages/core/src/markdown/parser-drop-closure.ts@@ -1,3 +1,4 @@+export type DroppedTokenAdjudication =| {kind: 'format-dof-axis';diff --git a/packages/core/src/markdown/pipeline.ts b/packages/core/src/markdown/pipeline.tsindex 7f2d5adca..e9e507469 100644--- a/packages/core/src/markdown/pipeline.ts+++ b/packages/core/src/markdown/pipeline.ts@@ -1,3 +1,4 @@+import {type FromProseMirrorOptions,fromProseMirror,diff --git a/packages/core/src/markdown/position-aware-join.ts b/packages/core/src/markdown/position-aware-join.tsindex 5a5e4c42a..f8f5e8530 100644--- a/packages/core/src/markdown/position-aware-join.ts+++ b/packages/core/src/markdown/position-aware-join.ts@@ -1,3 +1,4 @@+import type { Join } from 'mdast-util-to-markdown';import type { Position } from 'unist';diff --git a/packages/core/src/markdown/position-slice.ts b/packages/core/src/markdown/position-slice.tsindex 0f399d34c..e5b4c9eba 100644--- a/packages/core/src/markdown/position-slice.ts+++ b/packages/core/src/markdown/position-slice.ts@@ -1,3 +1,4 @@+import type { Nodes, Root } from 'mdast';import { visit } from 'unist-util-visit';import type { VFile } from 'vfile';@@ -476,7 +477,8 @@ export function applyPositionSliceToNode(const first = source[startOff];if (first !== '[' && first !== '<' && !node.title) {node.data.sourceStyle = 'gfm-autolink';- } else if (first === '[') {+ }+ else if (first === '[') {const slice = source.slice(startOff, endOff);const closeBracketIdx = slice.lastIndexOf('](');if (closeBracketIdx !== -1) {diff --git a/packages/core/src/markdown/rehype-plugins/skip-notion-whitespace.ts b/packages/core/src/markdown/rehype-plugins/skip-notion-whitespace.tsindex db10fa54b..ca225ce9b 100644--- a/packages/core/src/markdown/rehype-plugins/skip-notion-whitespace.ts+++ b/packages/core/src/markdown/rehype-plugins/skip-notion-whitespace.ts@@ -1,3 +1,4 @@+import type { Comment, Element, Root, Text } from 'hast';import type { Plugin } from 'unified';diff --git a/packages/core/src/markdown/rehype-plugins/strip-cocoa-meta.ts b/packages/core/src/markdown/rehype-plugins/strip-cocoa-meta.tsindex 34068d103..3a2524a9a 100644--- a/packages/core/src/markdown/rehype-plugins/strip-cocoa-meta.ts+++ b/packages/core/src/markdown/rehype-plugins/strip-cocoa-meta.ts@@ -1,3 +1,4 @@+import type { Element, ElementContent, Root } from 'hast';import type { Plugin } from 'unified';diff --git a/packages/core/src/markdown/rehype-plugins/strip-gdocs-wrapper.ts b/packages/core/src/markdown/rehype-plugins/strip-gdocs-wrapper.tsindex 93151d43b..2279a0189 100644--- a/packages/core/src/markdown/rehype-plugins/strip-gdocs-wrapper.ts+++ b/packages/core/src/markdown/rehype-plugins/strip-gdocs-wrapper.ts@@ -1,3 +1,4 @@+import type { Element, Root } from 'hast';import type { Plugin } from 'unified';diff --git a/packages/core/src/markdown/rehype-plugins/strip-github-hovercard.ts b/packages/core/src/markdown/rehype-plugins/strip-github-hovercard.tsindex 188f02d83..a0f467c42 100644--- a/packages/core/src/markdown/rehype-plugins/strip-github-hovercard.ts+++ b/packages/core/src/markdown/rehype-plugins/strip-github-hovercard.ts@@ -1,3 +1,4 @@+import type { Element, Root } from 'hast';import type { Plugin } from 'unified';diff --git a/packages/core/src/markdown/rehype-plugins/strip-gmail-classes.ts b/packages/core/src/markdown/rehype-plugins/strip-gmail-classes.tsindex 4ba2c3418..4e8542a21 100644--- a/packages/core/src/markdown/rehype-plugins/strip-gmail-classes.ts+++ b/packages/core/src/markdown/rehype-plugins/strip-gmail-classes.ts@@ -1,3 +1,4 @@+import type { Element, Root } from 'hast';import type { Plugin } from 'unified';diff --git a/packages/core/src/markdown/rehype-plugins/strip-gsheets-wrapper.ts b/packages/core/src/markdown/rehype-plugins/strip-gsheets-wrapper.tsindex 1a74b1272..a3c96b24a 100644--- a/packages/core/src/markdown/rehype-plugins/strip-gsheets-wrapper.ts+++ b/packages/core/src/markdown/rehype-plugins/strip-gsheets-wrapper.ts@@ -1,3 +1,4 @@+import type { Element, ElementContent, Root } from 'hast';import type { Plugin } from 'unified';diff --git a/packages/core/src/markdown/rehype-plugins/strip-mso-styles.ts b/packages/core/src/markdown/rehype-plugins/strip-mso-styles.tsindex de35e7b79..e95cf43d6 100644--- a/packages/core/src/markdown/rehype-plugins/strip-mso-styles.ts+++ b/packages/core/src/markdown/rehype-plugins/strip-mso-styles.ts@@ -1,3 +1,4 @@+import type { Comment, Element, ElementContent, Root } from 'hast';import type { Plugin } from 'unified';diff --git a/packages/core/src/markdown/rehype-plugins/strip-slack-classes.ts b/packages/core/src/markdown/rehype-plugins/strip-slack-classes.tsindex b4be1b2ea..ffdb4d5b5 100644--- a/packages/core/src/markdown/rehype-plugins/strip-slack-classes.ts+++ b/packages/core/src/markdown/rehype-plugins/strip-slack-classes.ts@@ -1,3 +1,4 @@+import type { Element, ElementContent, Root } from 'hast';import type { Plugin } from 'unified';diff --git a/packages/core/src/markdown/rehype-plugins/strip-vscode-spans.ts b/packages/core/src/markdown/rehype-plugins/strip-vscode-spans.tsindex 3c8d88b7c..e2a96d1a7 100644--- a/packages/core/src/markdown/rehype-plugins/strip-vscode-spans.ts+++ b/packages/core/src/markdown/rehype-plugins/strip-vscode-spans.ts@@ -1,3 +1,4 @@+import type { Element, Root } from 'hast';import type { Plugin } from 'unified';diff --git a/packages/core/src/markdown/resolve-image-url.ts b/packages/core/src/markdown/resolve-image-url.tsindex cf2c9da8e..0389575ac 100644--- a/packages/core/src/markdown/resolve-image-url.ts+++ b/packages/core/src/markdown/resolve-image-url.ts@@ -1,3 +1,4 @@+import { isRelativeUrl } from './safe-url.ts';function isDevDiagnosticContext(): boolean {diff --git a/packages/core/src/markdown/safe-url.ts b/packages/core/src/markdown/safe-url.tsindex 4d3250d3a..8be632ba4 100644--- a/packages/core/src/markdown/safe-url.ts+++ b/packages/core/src/markdown/safe-url.ts@@ -1,3 +1,4 @@+export const SAFE_URL_SCHEMES = ['https', 'http', 'mailto', 'tel', 'ftp', 'sms'] as const;const SCHEME_ALT = SAFE_URL_SCHEMES.map((s) => `${s}:`).join('|');diff --git a/packages/core/src/markdown/serialize-helpers.ts b/packages/core/src/markdown/serialize-helpers.tsindex 46cc6a074..542204403 100644--- a/packages/core/src/markdown/serialize-helpers.ts+++ b/packages/core/src/markdown/serialize-helpers.ts@@ -1,3 +1,4 @@+import type { Node as PmNode } from '@tiptap/pm/model';import type { MdxJsxAttribute, MdxJsxExpressionAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';import type { PropDef, SerializeContext } from '../registry/types.ts';diff --git a/packages/core/src/markdown/single-dollar-math-promoter.ts b/packages/core/src/markdown/single-dollar-math-promoter.tsindex be97d4d62..fe73659e6 100644--- a/packages/core/src/markdown/single-dollar-math-promoter.ts+++ b/packages/core/src/markdown/single-dollar-math-promoter.ts@@ -1,3 +1,4 @@+import type { PhrasingContent, Root, Text } from 'mdast';import type { InlineMath } from 'mdast-util-math';import { SKIP, visit } from 'unist-util-visit';diff --git a/packages/core/src/markdown/to-markdown-handlers.ts b/packages/core/src/markdown/to-markdown-handlers.tsindex 8f4e9a41c..7bce04302 100644--- a/packages/core/src/markdown/to-markdown-handlers.ts+++ b/packages/core/src/markdown/to-markdown-handlers.ts@@ -1,3 +1,4 @@+import type { Nodes, Parents } from 'mdast';import type { MdxJsxAttribute, MdxJsxExpressionAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';import type { Handle, Info, State } from 'mdast-util-to-markdown';diff --git a/packages/core/src/markdown/unknown-mdast-guard.ts b/packages/core/src/markdown/unknown-mdast-guard.tsindex cd245c38c..c5bfd2386 100644--- a/packages/core/src/markdown/unknown-mdast-guard.ts+++ b/packages/core/src/markdown/unknown-mdast-guard.ts@@ -1,3 +1,4 @@+import type { Root as MdastRoot } from 'mdast';import type { VFile } from 'vfile';diff --git a/packages/core/src/markdown/whitespace-char-ref.ts b/packages/core/src/markdown/whitespace-char-ref.tsindex d578476a7..ac9f5239b 100644--- a/packages/core/src/markdown/whitespace-char-ref.ts+++ b/packages/core/src/markdown/whitespace-char-ref.ts@@ -1,3 +1,4 @@+const INLINE_WHITESPACE_BY_CODE: ReadonlyMap<number, string> = new Map([[0x20, ' '],[0x09, '\t'],diff --git a/packages/core/src/markdown/wiki-link-micromark.ts b/packages/core/src/markdown/wiki-link-micromark.tsindex 6dad26200..afd9936fe 100644--- a/packages/core/src/markdown/wiki-link-micromark.ts+++ b/packages/core/src/markdown/wiki-link-micromark.ts@@ -17,6 +17,7 @@ declare module 'micromark-util-types' {}}+const CODE_BANG = 33; // !const CODE_LBRACKET = 91; // [const CODE_RBRACKET = 93; // ]@@ -260,6 +261,7 @@ export function wikiLinkSyntax(): Extension {};}+function enterWikiLink(this: CompileContext, token: Token) {this.enter({@@ -385,6 +387,7 @@ export const wikiLinkToMarkdown: {unsafe: [{ character: '[', inConstruct: ['phrasing'] }],};+const MICROMARK_EXT = wikiLinkSyntax();export function remarkWikiLink(this: Processor) {