Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
fix(open-knowledge): honor backslash escapes in the markdown promoters (#2960)
Nick Gomez2a079313a408
diff --git a/.changeset/escaped-delimiters-stay-literal.md b/.changeset/escaped-delimiters-stay-literal.mdnew file mode 100644index 000000000..f411da018--- /dev/null+++ b/.changeset/escaped-delimiters-stay-literal.md@@ -0,0 +1,13 @@+---+'@inkeep/open-knowledge': patch+---++Backslash-escaped `==`, `$`, `%%` and `<!--` no longer turn into formatting.++Writing `\==not a highlight\==` now leaves the text exactly as typed, and the same holds for escaped inline math (`\$5\$`), escaped comments (`\%\%note\%\%`) and escaped HTML comments (`\<!-- note -->`). Escaping either delimiter is enough. Previously OK recognized these constructs after the markdown parser had already consumed the backslash, so an escaped pair still formatted, and saving the document deleted the backslashes from disk. Both the formatting and the byte loss are fixed: an escaped pair now round-trips unchanged in paragraphs, headings, table cells, the first line of a list item or blockquote, and for the `%%` and `<!-- -->` block fences themselves.++Three shapes are not covered yet and still lose their backslashes: an escaped pair written on a *continuation* line of a list item or blockquote (the line without the `-` or `>` marker), an escaped pair that follows an already-highlighted `==a **b** c==` span in the same paragraph, and an escaped autolink (`\<https://example.com>`, which still becomes a link). The autolink case is the same shape of problem in a different recognizer, and suppressing it needs a matching change to how the serializer escapes `:`, so it is handled separately.++Unescaped `==text==`, `$x$`, `%%note%%`, `<!-- note -->` and `~~text~~` behave exactly as before. An inline code span (`` `==x==` ``) is still the form to reach for when the text should read as code; backslash escapes are for keeping a literal pair in running prose.++The `palette` tool and the project skill now say which delimiters are live in ordinary prose and how to suppress them, so an agent authoring `Cost $5$ each` or a sentence containing `%%` is no longer surprised by silent math or silently hidden text.diff --git a/packages/core/src/markdown/comment-promoter.ts b/packages/core/src/markdown/comment-promoter.tsindex 193e286b0..7415c474a 100644--- a/packages/core/src/markdown/comment-promoter.ts+++ b/packages/core/src/markdown/comment-promoter.ts@@ -2,7 +2,11 @@ import type { Nodes, Paragraph, PhrasingContent, Root, RootContent, Text } fromimport { SKIP, visit } from 'unist-util-visit';import type { VFile } from 'vfile';import type { CommentBlockMdast, CommentMdast } from './mdast-augmentation.ts';-import { deriveFragmentPosition } from './promoter-position.ts';+import {+ deriveFragmentPosition,+ escapedValueOffsets,+ isEscapeDerivedRun,+} from './promoter-position.ts';const PERCENT_COMMENT_RE = /(?<!%)%%([^\n]*?[^\n%])%%(?!%)/g;@@ -11,7 +15,7 @@ const HTML_COMMENT_INLINE_RE = /<!--([\s\S]*?)-->/g;export function commentPromoterPlugin() {return (tree: Root, file: VFile) => {const source = typeof file.value === 'string' ? file.value : '';- handleBlockCommentsAtRoot(tree);+ handleBlockCommentsAtRoot(tree, source);visit(tree, 'text', (node: Text, index, parent) => {if (parent === undefined || index === undefined || index === null) return;@@ -19,7 +23,7 @@ export function commentPromoterPlugin() {const value = node.value;if (value.indexOf('%%') === -1 && value.indexOf('<!--') === -1) return;- const matches = collectInlineCommentMatches(value);+ const matches = collectInlineCommentMatches(value, escapedValueOffsets(source, node));if (matches.length === 0) return;const replacements: PhrasingContent[] = [];@@ -63,13 +67,23 @@ interface InlineCommentMatch {sourceForm: 'percent' | 'html';}-function collectInlineCommentMatches(value: string): InlineCommentMatch[] {+function collectInlineCommentMatches(+ value: string,+ escaped: ReadonlySet<number> | null,+): InlineCommentMatch[] {const out: InlineCommentMatch[] = [];PERCENT_COMMENT_RE.lastIndex = 0;let pm: RegExpExecArray | null;// biome-ignore lint/suspicious/noAssignInExpressions: idiomatic regex iterationwhile ((pm = PERCENT_COMMENT_RE.exec(value)) !== null) {+ if (+ isEscapeDerivedRun(escaped, pm.index, 2) ||+ isEscapeDerivedRun(escaped, pm.index + pm[0].length - 2, 2)+ ) {+ PERCENT_COMMENT_RE.lastIndex = pm.index + 1;+ continue;+ }if (pm[1].trim().length === 0) continue;out.push({start: pm.index,@@ -83,6 +97,13 @@ function collectInlineCommentMatches(value: string): InlineCommentMatch[] {let hm: RegExpExecArray | null;// biome-ignore lint/suspicious/noAssignInExpressions: idiomatic regex iterationwhile ((hm = HTML_COMMENT_INLINE_RE.exec(value)) !== null) {+ if (+ isEscapeDerivedRun(escaped, hm.index, 4) ||+ isEscapeDerivedRun(escaped, hm.index + hm[0].length - 3, 3)+ ) {+ HTML_COMMENT_INLINE_RE.lastIndex = hm.index + 1;+ continue;+ }const body = hm[1].trim();if (body === '') continue;out.push({@@ -104,7 +125,7 @@ function collectInlineCommentMatches(value: string): InlineCommentMatch[] {return deduped;}-function handleBlockCommentsAtRoot(tree: Root): void {+function handleBlockCommentsAtRoot(tree: Root, source: string): void {const children = tree.children;let i = 0;while (i < children.length) {@@ -113,8 +134,21 @@ function handleBlockCommentsAtRoot(tree: Root): void {if (child.type === 'paragraph') {const single = isSingleTextParagraph(child);if (single !== null) {+ const onlyText = child.children[0] as Text;+ let onlyEscapedCache: ReadonlySet<number> | null | undefined;+ const onlyEscapes = (): ReadonlySet<number> | null => {+ if (onlyEscapedCache === undefined) {+ onlyEscapedCache = escapedValueOffsets(source, onlyText);+ }+ return onlyEscapedCache;+ };+const fenced = matchSingleParagraphFence(single);- if (fenced !== null) {+ if (+ fenced !== null &&+ !isEscapeDerivedRun(onlyEscapes(), 0, 2) &&+ !isEscapeDerivedRun(onlyEscapes(), single.length - 2, 2)+ ) {const block: CommentBlockMdast = {type: 'commentBlock',children: [@@ -131,7 +165,11 @@ function handleBlockCommentsAtRoot(tree: Root): void {}const htmlBlockBody = matchHtmlCommentBlock(single);- if (htmlBlockBody !== null) {+ if (+ htmlBlockBody !== null &&+ !isEscapeDerivedRun(onlyEscapes(), single.length - single.trimStart().length, 4) &&+ !isEscapeDerivedRun(onlyEscapes(), single.trimEnd().length - 3, 3)+ ) {const block: CommentBlockMdast = {type: 'commentBlock',children: [@@ -149,7 +187,7 @@ function handleBlockCommentsAtRoot(tree: Root): void {}const strippedHtml = stripHtmlCommentDelimiters(child);- if (strippedHtml !== null) {+ if (strippedHtml !== null && !boundaryDelimitersEscaped(source, child, 4, 3)) {const block: CommentBlockMdast = {type: 'commentBlock',children: [strippedHtml],@@ -161,7 +199,7 @@ function handleBlockCommentsAtRoot(tree: Root): void {}const strippedPercent = stripPercentDelimiters(child);- if (strippedPercent !== null) {+ if (strippedPercent !== null && !boundaryDelimitersEscaped(source, child, 2, 2)) {const block: CommentBlockMdast = {type: 'commentBlock',children: [strippedPercent],@@ -173,11 +211,11 @@ function handleBlockCommentsAtRoot(tree: Root): void {}}- if (child.type === 'paragraph' && isFenceOnlyParagraph(child)) {+ if (child.type === 'paragraph' && isFenceOnlyParagraph(child, source)) {let j = i + 1;while (j < children.length) {const sibling = children[j];- if (sibling.type === 'paragraph' && isFenceOnlyParagraph(sibling)) break;+ if (sibling.type === 'paragraph' && isFenceOnlyParagraph(sibling, source)) break;j += 1;}if (j < children.length && j > i + 1) {@@ -197,6 +235,27 @@ function handleBlockCommentsAtRoot(tree: Root): void {}}+function runEscaped(source: string, node: Text, valueOffset: number, length: number): boolean {+ return isEscapeDerivedRun(escapedValueOffsets(source, node), valueOffset, length);+}++function boundaryDelimitersEscaped(+ source: string,+ p: Paragraph,+ openLength: number,+ closeLength: number,+): boolean {+ const first = p.children[0];+ const last = p.children[p.children.length - 1];+ if (first.type !== 'text' || last.type !== 'text') return false;+ const openAt = first.value.length - first.value.trimStart().length;+ const closeAt = last.value.trimEnd().length - closeLength;+ const firstEscaped = escapedValueOffsets(source, first);+ if (isEscapeDerivedRun(firstEscaped, openAt, openLength)) return true;+ const lastEscaped = last === first ? firstEscaped : escapedValueOffsets(source, last);+ return isEscapeDerivedRun(lastEscaped, closeAt, closeLength);+}+function isSingleTextParagraph(p: Paragraph): string | null {if (p.children.length !== 1) return null;const only = p.children[0];@@ -322,8 +381,9 @@ function countOccurrences(haystack: string, needle: string): number {return count;}-function isFenceOnlyParagraph(p: Paragraph): boolean {+function isFenceOnlyParagraph(p: Paragraph, source: string): boolean {const text = isSingleTextParagraph(p);if (text === null) return false;- return text.trim() === '%%';+ if (text.trim() !== '%%') return false;+ return !runEscaped(source, p.children[0] as Text, text.indexOf('%%'), 2);}diff --git a/packages/core/src/markdown/highlight-promoter.ts b/packages/core/src/markdown/highlight-promoter.tsindex f55912407..da0a81d23 100644--- a/packages/core/src/markdown/highlight-promoter.ts+++ b/packages/core/src/markdown/highlight-promoter.ts@@ -3,7 +3,11 @@ import type { MdxJsxTextElement } from 'mdast-util-mdx';import { SKIP, visit } from 'unist-util-visit';import type { VFile } from 'vfile';import type { MarkMdast } from './mdast-augmentation.ts';-import { deriveFragmentPosition } from './promoter-position.ts';+import {+ deriveFragmentPosition,+ escapedValueOffsets,+ isEscapeDerivedRun,+} from './promoter-position.ts';const HIGHLIGHT_RE = /(?<!=)==(?=\S)([^\n]*?[^\s=])==(?!=)/g;@@ -59,8 +63,16 @@ function sliceTextNode(source: Text, from: number, to: number): Text {return out;}-function promoteCrossChildren(parent: Parent): void {+function promoteCrossChildren(parent: Parent, source: string): void {const children = parent.children as PhrasingContent[];+ const escapeSets = new Map<Text, ReadonlySet<number> | null>();+ const escapesOf = (node: Text): ReadonlySet<number> | null => {+ const cached = escapeSets.get(node);+ if (cached !== undefined) return cached;+ const set = escapedValueOffsets(source, node);+ escapeSets.set(node, set);+ return set;+ };let outerI = 0;while (outerI < children.length) {const openChild = children[outerI];@@ -74,6 +86,7 @@ function promoteCrossChildren(parent: Parent): void {for (let n = 0; n <= openValue.length - 2; n++) {if (openValue.charCodeAt(n) !== 61 || openValue.charCodeAt(n + 1) !== 61) continue; // 61 = '='if (n > 0 && openValue.charCodeAt(n - 1) === 61) continue;+ if (isEscapeDerivedRun(escapesOf(openChild), n, 2)) continue;let charAfter: string | null;if (n + 2 < openValue.length) {charAfter = openValue.charAt(n + 2);@@ -97,6 +110,7 @@ function promoteCrossChildren(parent: Parent): void {for (let n2 = openPos + 3; n2 <= openValue.length - 2; n2++) {if (openValue.charCodeAt(n2) !== 61 || openValue.charCodeAt(n2 + 1) !== 61) continue;+ if (isEscapeDerivedRun(escapesOf(openChild), n2, 2)) continue;const before = openValue.charAt(n2 - 1);if (/[\s=]/.test(before)) continue;let after: string | null;@@ -120,6 +134,7 @@ function promoteCrossChildren(parent: Parent): void {if (sib.type === 'text') {for (let n2 = 0; n2 <= sib.value.length - 2; n2++) {if (sib.value.charCodeAt(n2) !== 61 || sib.value.charCodeAt(n2 + 1) !== 61) continue;+ if (isEscapeDerivedRun(escapesOf(sib), n2, 2)) continue;let before: string | null;if (n2 > 0) {before = sib.value.charAt(n2 - 1);@@ -192,11 +207,11 @@ function promoteCrossChildren(parent: Parent): void {}}-function walkPromote(node: Nodes): void {+function walkPromote(node: Nodes, source: string): void {if ('children' in node && Array.isArray(node.children)) {- promoteCrossChildren(node as Parent);+ promoteCrossChildren(node as Parent, source);for (const child of node.children) {- walkPromote(child as Nodes);+ walkPromote(child as Nodes, source);}}}@@ -210,11 +225,18 @@ export function highlightPromoterPlugin() {const value = node.value;if (value.indexOf('==') === -1) return;+ const escaped = escapedValueOffsets(source, node);HIGHLIGHT_RE.lastIndex = 0;const matches: RegExpExecArray[] = [];let m: RegExpExecArray | null;// biome-ignore lint/suspicious/noAssignInExpressions: idiomatic regex iterationwhile ((m = HIGHLIGHT_RE.exec(value)) !== null) {+ const start = m.index;+ const end = start + m[0].length;+ if (isEscapeDerivedRun(escaped, start, 2) || isEscapeDerivedRun(escaped, end - 2, 2)) {+ HIGHLIGHT_RE.lastIndex = start + 1;+ continue;+ }matches.push(m);}if (matches.length === 0) return;@@ -254,7 +276,7 @@ export function highlightPromoterPlugin() {return [SKIP, index + replacements.length];});- walkPromote(tree);+ walkPromote(tree, source);visit(tree, 'mdxJsxTextElement', (node: MdxJsxTextElement, index, parent) => {if (parent === undefined || index === undefined || index === null) return;diff --git a/packages/core/src/markdown/promoter-position.ts b/packages/core/src/markdown/promoter-position.tsindex ea7949ee1..f0a360385 100644--- a/packages/core/src/markdown/promoter-position.ts+++ b/packages/core/src/markdown/promoter-position.ts@@ -1,6 +1,10 @@import type { Text } from 'mdast';import type { Point, Position } from 'unist';+function consumesEscape(source: string, i: number, valueChar: string): boolean {+ return source[i] === '\\' && i + 1 < source.length && source[i + 1] === valueChar;+}+function valueOffsetToSourceOffset(source: string,parentSourceStart: number,@@ -10,19 +14,64 @@ function valueOffsetToSourceOffset(let srcCursor = parentSourceStart;let valCursor = 0;while (valCursor < targetValueOffset && srcCursor < source.length) {- if (- source[srcCursor] === '\\' &&- srcCursor + 1 < source.length &&- valueText[valCursor] === source[srcCursor + 1]- ) {+ srcCursor += consumesEscape(source, srcCursor, valueText[valCursor]) ? 2 : 1;+ valCursor += 1;+ }+ return srcCursor;+}++const NO_ESCAPES: ReadonlySet<number> = new Set();++export function escapedValueOffsets(source: string, node: Text): ReadonlySet<number> | null {+ if (!source || !node.position || typeof node.position.start?.offset !== 'number') {+ return null;+ }+ const start = node.position.start.offset;+ const value = node.value;+ const spanEnd = Math.min(+ node.position.end?.offset ?? source.length,+ start + 2 * value.length,+ source.length,+ );+ let hasBackslash = false;+ for (let i = start; i < spanEnd; i++) {+ if (source.charCodeAt(i) === 92 /* \ */) {+ hasBackslash = true;+ break;+ }+ }+ if (!hasBackslash) {+ return NO_ESCAPES;+ }++ let escaped: Set<number> | null = null;+ let srcCursor = start;+ let valCursor = 0;+ while (valCursor < value.length && srcCursor < source.length) {+ if (consumesEscape(source, srcCursor, value[valCursor])) {+ if (escaped === null) escaped = new Set();+ escaped.add(valCursor);srcCursor += 2;- valCursor += 1;- } else {+ } else if (source[srcCursor] === value[valCursor]) {srcCursor += 1;- valCursor += 1;+ } else {+ break;}+ valCursor += 1;}- return srcCursor;+ return escaped ?? NO_ESCAPES;+}++export function isEscapeDerivedRun(+ escaped: ReadonlySet<number> | null,+ valueOffset: number,+ length: number,+): boolean {+ if (escaped === null || escaped.size === 0) return false;+ for (let k = 0; k < length; k++) {+ if (escaped.has(valueOffset + k)) return true;+ }+ return false;}function offsetToPoint(source: string, offset: number): Point {diff --git a/packages/core/src/markdown/single-dollar-math-promoter.ts b/packages/core/src/markdown/single-dollar-math-promoter.tsindex be97d4d62..b012a5aff 100644--- a/packages/core/src/markdown/single-dollar-math-promoter.ts+++ b/packages/core/src/markdown/single-dollar-math-promoter.ts@@ -2,7 +2,11 @@ import type { PhrasingContent, Root, Text } from 'mdast';import type { InlineMath } from 'mdast-util-math';import { SKIP, visit } from 'unist-util-visit';import type { VFile } from 'vfile';-import { deriveFragmentPosition } from './promoter-position.ts';+import {+ deriveFragmentPosition,+ escapedValueOffsets,+ isEscapeDerivedRun,+} from './promoter-position.ts';const SINGLE_DOLLAR_MATH_RE = /(?<!\\)\$(?=\S)([^$\n]*?[^\s$])\$(?!\d)/g;@@ -15,11 +19,18 @@ export function singleDollarMathPromoterPlugin() {const value = node.value;if (value.indexOf('$') === -1) return;+ const escaped = escapedValueOffsets(source, node);SINGLE_DOLLAR_MATH_RE.lastIndex = 0;const matches: RegExpExecArray[] = [];let m: RegExpExecArray | null;// biome-ignore lint/suspicious/noAssignInExpressions: idiomatic regex iterationwhile ((m = SINGLE_DOLLAR_MATH_RE.exec(value)) !== null) {+ const start = m.index;+ const end = start + m[0].length;+ if (isEscapeDerivedRun(escaped, start, 1) || isEscapeDerivedRun(escaped, end - 1, 1)) {+ SINGLE_DOLLAR_MATH_RE.lastIndex = start + 1;+ continue;+ }matches.push(m);}if (matches.length === 0) return;diff --git a/packages/server/assets/skills/project/SKILL.md b/packages/server/assets/skills/project/SKILL.mdindex c8f621df3..fd0d5b8be 100644--- a/packages/server/assets/skills/project/SKILL.md+++ b/packages/server/assets/skills/project/SKILL.md@@ -67,7 +67,7 @@ Call `write` / `edit` as soon as you have content (route through MCP per the STO**Persist incrementally — the knowledge base IS your checkpoint (MUST).** On any multi-step or long-running task — a research sweep, a multi-source synthesis, a batch of docs — write completed work to the KB as you finish each unit: per section, per source, per doc. Never hold finished findings only in your context waiting for one final write at the end. A rate limit, crash, or context compaction mid-task discards everything still unwritten; work already persisted survives, and you resume by reading the doc back. Create the target doc early (skeleton + frontmatter), then `edit` each section in as it firms up.-**Pass a `summary` on every content write (SHOULD)** — a one-line (≤80 chars) user-facing change-note that becomes the timeline entry. **Reach for visual structure** (Callout, `mermaid`, table, `html preview`) where it carries the point better than prose; call `palette` as you draft. Advisory write-warnings, MDX authoring, delete/move mechanics, and visual authoring: `references/writing.md` + `references/components-and-visuals.md` + `references/media-and-assets.md`.+**Pass a `summary` on every content write (SHOULD)** — a one-line (≤80 chars) user-facing change-note that becomes the timeline entry. **Reach for visual structure** (Callout, `mermaid`, table, `html preview`) where it carries the point better than prose; call `palette` as you draft. Advisory write-warnings, MDX authoring, delete/move mechanics, keeping `==`/`$`/`%%`/`<!--` literal, and visual authoring: `references/writing.md` + `references/components-and-visuals.md` + `references/media-and-assets.md`.## Grounding — every factual claim needs a source (MUST)diff --git a/packages/server/assets/skills/project/references/components-and-visuals.md b/packages/server/assets/skills/project/references/components-and-visuals.mdindex cb6eb9da2..5780fe7b7 100644--- a/packages/server/assets/skills/project/references/components-and-visuals.md+++ b/packages/server/assets/skills/project/references/components-and-visuals.md@@ -10,8 +10,12 @@ OK auto-promotes markdown-native syntax into themed canonical components at pars| Collapsible section | `<details><summary>Title</summary>` … `</details>` | themed Accordion || Diagram | a ` ```mermaid ` fenced block (flowchart, sequence, class, state, ER, gantt, pie) — label-text pitfalls + escapes: `palette({ components: ["Mermaid"] })`; parse failures come back as `warnings` entries on write/edit | Mermaid diagram || Math | `$x$` inline, `$$…$$` block | KaTeX Math |+| Highlight | `==text==` | highlight mark |+| Author-only comment (hidden from readers) | `%%text%%` or `<!-- text -->` | comment mark || Inline a doc or asset | `![[file]]` | wiki embed |+**These delimiters are live in ordinary prose.** `==`, `$`, `$$`, `%%`, `<!--` … `-->` and `~~` format — or hide — whatever sits between them, wherever they appear, not only where you meant them as syntax. To show a literal pair, wrap it in an inline code span (`` `==x==` ``, `` `$5` ``), which always works and reads as code; or backslash-escape a delimiter to keep it as running prose. Escaping either side is enough for `==`, `$`, `%%` and `<!--`: `\==x\==`, `\$5`, `\%\%note\%\%`, `\<!-- note -->`. For `~~`, escape both tildes (`\~\~x\~\~`) — a one-sided `\~~x~~` renders right but gets rewritten to the two-sided form on save. Watch `%%` and `<!-- -->` in particular: an accidental pair doesn't restyle the text, it hides it.+`Tabs` is the lone canonical with **no** markdown-native form — write the JSX directly (`<Tabs><Tab label="…">…</Tab></Tabs>`). For any canonical's full JSX prop schema, call `palette({ components: [ids] })`. If no canonical fits, any `<TagName>…</TagName>` falls through as raw MDX — but prefer a canonical when one matches.**Discover the palette in one call.** `palette` returns every markdown-native form (copy-ready `example` + `guidance`), the themed `html preview` embed starters, and the injected theme-token list — the source of truth for component-forward, themed authoring. Canonical names/counts beyond the markdown-native set are project-specific; the inventory in the `write` / `edit` descriptions and `palette({ components })` are authoritative for those.diff --git a/packages/server/src/mcp/tools/palette.test.ts b/packages/server/src/mcp/tools/palette.test.tsindex 3587c4441..d0c0f41be 100644--- a/packages/server/src/mcp/tools/palette.test.ts+++ b/packages/server/src/mcp/tools/palette.test.ts@@ -40,11 +40,13 @@ interface ToolResult {type ToolHandler = (args: { cwd?: string }) => Promise<ToolResult>;-function captureRegistration(): ToolHandler {+function captureRegistrationFull(): { handler: ToolHandler; description: string } {let captured: ToolHandler | null = null;+ let capturedDescription: string | null = null;const server = {- registerTool(_name: string, _config: unknown, handler: ToolHandler) {+ registerTool(_name: string, config: { description: string }, handler: ToolHandler) {captured = handler;+ capturedDescription = config.description;},tool() {throw new Error('legacy tool() should not be called by palette');@@ -54,8 +56,12 @@ function captureRegistration(): ToolHandler {config: BASE_CONFIG,resolveCwd: async () => '/tmp/ok-get-authoring-palette-test',});- if (!captured) throw new Error('tool not registered');- return captured;+ if (!captured || capturedDescription === null) throw new Error('tool not registered');+ return { handler: captured, description: capturedDescription };+}++function captureRegistration(): ToolHandler {+ return captureRegistrationFull().handler;}describe('palette tool', () => {@@ -114,6 +120,56 @@ describe('palette tool', () => {expect(mermaid?.example).toContain('"Start (label with punctuation)"');});+ test('Highlight and Comment entries teach both suppression forms', async () => {+ const handler = captureRegistration();+ const { structuredContent } = await handler({});+ const byId = new Map((structuredContent?.components ?? []).map((c) => [c.id, c]));++ const highlight = byId.get('Highlight');+ expect(highlight?.authoring).toBe('markdown');+ expect(highlight?.example).toContain('==key phrase==');+ // Code span first (always works), backslash second (running prose).+ expect(highlight?.guidance).toContain('`==x==`');+ expect(highlight?.guidance).toContain('\\==x\\==');++ const comment = byId.get('Comment');+ expect(comment?.authoring).toBe('markdown');+ expect(comment?.example).toContain('%%');+ expect(comment?.example).toContain('<!--');+ // The comment forms HIDE text, which is why they need the loudest warning.+ expect(comment?.guidance).toContain('HIDES');+ expect(comment?.guidance).toContain('`%%x%%`');+ expect(comment?.guidance).toContain('\\%\\%x\\%\\%');++ // Currency is the highest-frequency accidental `$` pair.+ const math = byId.get('Math');+ expect(math?.guidance).toContain('Cost $5$ each');+ expect(math?.guidance).toContain('`$5`');+ expect(math?.guidance).toContain('\\$5');+ });++ test('the tool description discloses the delimiters that are live in prose', () => {+ const { description } = captureRegistrationFull();+ // The palette description is the surface every agent reads before+ // authoring, so the live-in-prose disclosure lives there and not only on+ // the per-construct entries.+ for (const token of [+ '==highlight==',+ '$inline math$',+ '%%comment%%',+ '<!-- comment -->',+ // `~~` is the one family whose escape is asymmetric: a one-sided+ // `\~~x~~` renders right but gets rewritten, so both tildes must be+ // escaped. If that guidance is ever refactored away, this catches it.+ '~~strikethrough~~',+ ]) {+ expect(description).toContain(token);+ }+ expect(description).toContain('HIDES');+ expect(description).toContain('inline code span');+ expect(description).toContain('backslash-escape');+ });+test('every registry-backed authoring form names a live canonical descriptor', async () => {const handler = captureRegistration();const { structuredContent } = await handler({});diff --git a/packages/server/src/mcp/tools/palette.ts b/packages/server/src/mcp/tools/palette.tsindex 599ce4e6a..845231059 100644--- a/packages/server/src/mcp/tools/palette.ts+++ b/packages/server/src/mcp/tools/palette.ts@@ -34,6 +34,8 @@ const DESCRIPTION = ['- `embedPatterns` — copy-ready ` ```html preview ` starters (chart, stat cards, custom SVG, interactive control) already wired to the theme tokens, so an embed tracks light/dark with no hand-picked colors.','- `tokens` — the CSS custom properties injected into every preview iframe; reference them as `var(--chart-1)`, `var(--foreground)`, … inside an `html preview` embed. **Inside SVG, route theme tokens through `style="..."` rather than presentation attributes** — `<circle style="fill: var(--chart-1)">` works; `<circle fill="var(--chart-1)">` silently falls back to black in Safari / older Chromium because CSS `var()` is not a valid SVG `<paint>` value per the W3C spec.','',+ '**These delimiters are live syntax in ordinary prose, not just inside the constructs above:** `==highlight==`, `$inline math$` / `$$block math$$`, `%%comment%%` and `<!-- comment -->` (both hidden from readers), `~~strikethrough~~`. An accidental pair silently formats — or, for the comment forms, HIDES — the text between it. To keep a pair literal, either wrap it in an inline code span (`` `==x==` ``, `` `$5` ``), which always works and reads as code, or backslash-escape either delimiter (`\\==x\\==`, `\\$5`, `\\%\\%note\\%\\%`, `\\<!-- note -->`) to keep it as running prose. `~~` is the exception: escape both tildes (`\\~\\~x\\~\\~`), because a one-sided `\\~~x~~` renders right but gets rewritten to the two-sided form on save.',+ '','External resources load directly: the preview iframe has open network access, so an embed can load external stylesheets, `fetch` live data, or pull map tiles / remote images / web fonts over `https:`. The iframe is a sandboxed null-origin frame — an embed can reach the network but never the knowledge base, cookies, or auth.','','Pass `components: [ids]` to ALSO get the full JSX-form prop schema for specific canonicals (e.g. `palette({ components: ["Callout", "Tabs"] })`) — merged from the former `get_components`.',@@ -161,7 +163,26 @@ const AUTHORING_FORMS: readonly AuthoringFormSeed[] = [description: 'LaTeX math, rendered with KaTeX.',authoring: 'markdown',example: 'Inline: $E = mc^2$\n\nBlock:\n\n$$\n\\int_0^1 x^2 \\, dx\n$$',- guidance: 'Write LaTeX in `$…$` (inline) or `$$…$$` (block) — OK auto-promotes it to Math.',+ guidance:+ 'Write LaTeX in `$…$` (inline) or `$$…$$` (block) — OK auto-promotes it to Math. `$` is live in ordinary prose too, so a currency pair like `Cost $5$ each` parses as math; write `` `$5` `` or `\\$5` to keep a literal dollar sign.',+ },+ {+ id: 'Highlight',+ fallbackDisplayName: 'Highlight',+ description: 'Marked / highlighted inline text.',+ authoring: 'markdown',+ example: 'The ==key phrase== stands out.',+ guidance:+ 'Write `==text==` — OK auto-promotes it to a highlight. `==` is live anywhere in prose, so to show a literal pair use an inline code span (`` `==x==` ``) or escape either side (`\\==x\\==`).',+ },+ {+ id: 'Comment',+ fallbackDisplayName: 'Comment',+ description: 'Author-only note, hidden from the rendered document.',+ authoring: 'markdown',+ example: '%%Not shown to readers.%%\n\n<!-- Also not shown to readers. -->',+ guidance:+ 'Write `%%text%%` or `<!-- text -->` — both render hidden and are dropped from the clipboard. Because they are live in prose, an accidental pair HIDES the text between it; to show a literal pair use an inline code span (`` `%%x%%` ``) or escape either side (`\\%\\%x\\%\\%`).',},{id: 'wiki-embed',