An open source design system that's fully customizable and agent ready
TypeScript
docs(markdown): define extensible plugin protocol (#6338)
Cindy Zhang0faf070d8ba2
diff --git a/docs/specs/AST-036/spec.md b/docs/specs/AST-036/spec.mdindex 98dc3eadc3..7d9c9bbeb7 100644--- a/docs/specs/AST-036/spec.md+++ b/docs/specs/AST-036/spec.md@@ -7,7 +7,7 @@ authority: currentarchive_reason: nullsuperseded_by: nullapproved_by: cixzhang-approved_at: 2026-09-14+approved_at: 2026-09-15phase: acceptedowners: [cixzhang]affects_architecture:@@ -25,199 +25,374 @@ affects_consumer_docs: [Markdown, Outline]## Contract at a glance-| Area | Contract |-| --------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |-| Public contract | Proposes one additive `plugins` prop and `createMarkdownPlugin()`. Entries may contribute `text`, `syntax`, `fences`, `renderers`, or `decorations`. Every syntax entry also carries stable parse identity and a complete owning renderer set. Exact declarations belong to Markdown and its module API surfaces. |-| Behavior | Built-in syntax and protected contexts win. Plugins resolve in array and declaration order. Syntax and text use first claim; fence fallback or enhancement resolves a fence while decline continues; decorations compose in deterministic layers without changing the AST. |-| End-user impact | Readers may receive additional prose presentation, source syntax, semantic fence output, and source-range decoration. Ordinary Markdown, copyable failure fallbacks, heading and Outline identity, accessibility, generic CodeBlock highlighting, and built-in document, navigation, image, list, and table policy remain owned by their canonical surfaces. |-| Builder impact | Existing builders do nothing. Opt-in builders pass a stable plugin list. Astryx-authored modules may expose static, factory, or hook forms through Markdown and Core; third-party plugins remain explicit ordinary package imports. |-| Compatibility and readiness | This contract is current; implementation is pending. The zero-plugin path and released APIs stay unchanged. `inlinePlugins` is not soft-deprecated until modern text contributions have behavioral and type parity, an internal final adapter, migration docs, and a codemod. Runtime, browser, type, cache, allocation, bundle, performance, and remount evidence remains pending. |-| Review checks | Reject a registry or separate Astryx plugin package family; lifecycle-grouped public capabilities; unrestricted whole-document parse or render hooks; raw markup or arbitrary AST mutation; plugin-state-driven reparsing; work proportional to every plugin at every source character or rendered node; replacement of existing generic CodeBlock highlighting; unsafe or non-copyable fence failure; parsing-affecting decorations; or plugin override of Core-owned document, heading, navigation, image, list, or table policy. |-| Governing rules | [`architecture:public-component-api`](../../architecture/public-component-api.md); [`family:navigation-destinations`](../../families/navigation-destinations.md); [AST-002 FR4 — Existing composition and styling seams come first](../AST-002/spec.md); [AST-002 FR15 — Invalid states are prevented where practical](../AST-002/spec.md); [AST-002 FR17 — Public module and utility function names disclose one atomic role](../AST-002/spec.md); [AST-002 FR18 — Public primitives support composition intentionally](../AST-002/spec.md); [AST-002 FR20 — Callsite impact and decision burden are explicit](../AST-002/spec.md). |+| Area | Contract |+| -------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| Public contract | One additive `plugins` prop and `createMarkdownPlugin()`. A plugin exposes only `syntax`, immutable `transform`, and `renderers`. Text matching, semantic fences, and source decoration are helper-authored transforms, not separate protocol phases. |+| Behavior | Parsing, transformation, Markdown rendering, and Outline observe one stable, strictly typed, MDAST-aligned tree. Ordered transforms return validated replacement trees while Core retains built-in semantics and readable fallback. |+| Remark compatibility | A separate adapter may run synchronous transform-only Remark plugins over the documented supported MDAST subset. Parser extensions, async plugins, compiler plugins, arbitrary `VFile` state, and unsupported node kinds are rejected rather than approximated. |+| End-user impact | Readers may receive additional syntax and transformed document structure while ordinary Markdown, copyable fallback, heading and Outline identity, accessibility, navigation, images, lists, and tables retain canonical ownership. |+| Builder impact | Existing builders do nothing. Opt-in builders pass one stable plugin list. Simple text, fence, and decoration use cases use helpers that return transforms. |+| Compatibility | Omitted plugins and `plugins={[]}` are semantically the same empty pipeline. Core may skip empty preparation and allocation, but no separate behavior model exists. Existing `components`, `inlinePlugins`, math, citations, autolinks, and parser signatures retain their meaning. |+| Review checks | Reject a second plugin prop, public lifecycle-specific phases, mutable shared AST, raw-markup nodes, plugin override of Core semantics, unbounded parser hooks, silent Remark incompatibility, transform-driven reparsing, or work proportional to every plugin at every source character. |+| Governing rules | [`architecture:public-component-api`](../../architecture/public-component-api.md); [`family:navigation-destinations`](../../families/navigation-destinations.md); [AST-002 FR4](../AST-002/spec.md); [AST-002 FR15](../AST-002/spec.md); [AST-002 FR17](../AST-002/spec.md); [AST-002 FR18](../AST-002/spec.md); [AST-002 FR20](../AST-002/spec.md). |This section is a review projection; the body below is authoritative.## Intent-Application authors should be able to add reusable Markdown behavior without rewriting source text, forking the parser, or replacing the whole renderer. One model must cover prose replacement, inline or block extension syntax, language-scoped semantic fences, typed extension rendering, and source-range decoration while preserving an understandable processing order.+Application authors should be able to add reusable Markdown behavior without rewriting source text, forking the parser, or replacing the whole renderer. One understandable model must cover new source syntax, document-level semantic transformation, and typed rendering.-The system decision owns shared plugin admission, capability boundaries, composition, collision rules, compatibility, failure behavior, parse identity, and observable resource constraints. It does not own exact TypeScript declarations, consumer syntax, private dispatch or cache design, or the independent behavior of first-party plugin modules.--This specification changes no runtime by itself. The requirements below define the complete proposed behavior.+The public concepts should remain fewer than the use cases. Prose replacement, semantic code fences, source decoration, callouts, frontmatter, TOCs, footnotes, and compatible Remark transforms all use the same immutable transform boundary rather than becoming independent protocol phases.## Ownership boundary-AST-036 owns the shared plugin protocol and its cross-surface guarantees. The Markdown component contract owns aggregate public component and parser behavior. Outline owns its public outline behavior while using the shared projection required here. Any independently contractible first-party plugin will own its API, behavior, accessibility, fallback, and evidence in a module record created with that plugin. Consumer documentation owns signatures, prop and option references, examples, and migration recipes. Architecture owns private dispatch, indexing, cache, invalidation, allocation, and repository mechanisms.+AST-036 owns shared plugin admission, syntax and transform ordering, compatibility, validation, failure behavior, parse identity, Remark-adapter limits, and observable resource constraints. Markdown owns its concrete AST declarations, parser integration, aggregate rendering, and helpers. Outline owns its projection of Markdown heading identity. A first-party plugin owns its specific semantics and evidence in its own module record.## Non-goals-- Implement the runtime, first-party modules, consumer docs, codemod, or release artifacts in this specification change.-- Add a registry, discovery mechanism, separate Astryx plugin package family, unrestricted whole-document parser or renderer hook, raw-markup parser channel, or arbitrary AST mutation API.-- Replace generic CodeBlock highlighting or change built-in document, heading, navigation, image, list, table, Outline, or focused-syntax ownership.-- Define any concrete first-party plugin; its module record is added only when that plugin is proposed.-- Prescribe private dispatch, cache, index, invalidation, file, manifest, or repository mechanisms.+- Adopt Unified, mutable MDAST, `VFile`, or Remark as Core runtime dependencies.+- Break the released `parseMarkdown` result shape before a separately approved+ migration.+- Promise compatibility with arbitrary Remark parser, transform, compiler, async, or raw-HTML plugins.+- Expose mutable shared AST, unrestricted visitors, DOM access, package discovery, or a registry.+- Replace generic CodeBlock highlighting or Core-owned document, heading, navigation, image, list, or table semantics.+- Make a zero-plugin document a separate semantic mode.-## Current-state impact+## Platform support-| Current seam | Preserved behavior | Missing shared contract |-| ------------------------- | ----------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------- |-| `components` | Replaces supported built-in renderers, including the all-fence code renderer. | Cannot add typed syntax or compose independent language-scoped fence behavior. |-| `inlinePlugins` | Replaces matched text in rendered prose. | Has no named general-plugin identity, typed source node, block syntax, or source provenance. |-| Parser and streaming APIs | Produce the released closed AST and reuse settled incremental output. | Have no typed extension union, bounded plugin deferral, finalization rule, or syntax-only cache identity. |-| Markdown and Outline | Share built-in heading text and slug behavior. | Have no plain-text projection for inline extension nodes. |+- **Feature and engine floor:** unchanged from current Markdown/Core package support; the protocol adds no browser, React, Node, or TypeScript floor.+- **Unsupported behavior:** unsupported syntax/transform/Remark behavior fails closed to the last valid readable document and cannot silently approximate output.+- **Browser evidence:** interactive stories verify rendered output, keyboard/focus order, copyable fallback, navigation ownership, and unchanged no-plugin behavior in real Chromium; server-render fixtures cover non-browser use.++## Current-state impact-The proposal adds the missing shared protocol without replacing these seams.+| Current seam | Preserved behavior | New role |+| ------------------------- | -------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------- |+| `components` | Replaces supported built-in renderers, including the all-fence code renderer. | Continues to win before plugin rendering. |+| `inlinePlugins` | Replaces matched prose with released traversal, overlap, callback, and error behavior. | Remains compatible; a later migration may adapt it through a helper-backed transform only after exact parity. |+| Parser and streaming APIs | Produce the released AST and reuse settled incremental output. | Accept syntax plugins and apply live transforms without making transforms part of parse identity. |+| Markdown and Outline | Share built-in heading text and slug behavior. | Also share transformed heading projection and collision allocation. |## Semantic model-A plugin entry is an opaque capability-named value created by the public plugin factory. The closed capability names are `text`, `syntax`, `fences`, `renderers`, and `decorations`. A plain structural object cannot masquerade as a plugin entry. Heterogeneous lists preserve the union of their extension-node kinds under strict TypeScript.+A plugin entry is an opaque value created by Markdown's public `createMarkdownPlugin()` factory and accepted only through the ordered `plugins` array. Its public shape is `{name, apiVersion: 1, syntax?, transform?, renderers?}` subject to these rules: `syntax` contains ordered bounded inline/block tokenizer declarations and requires `parseKey`; `transform` is one synchronous immutable root-to-root function; `renderers` is a node-name-keyed map whose entries provide one pure render callback and one deterministic `toText` projection. A plugin exposes no other lifecycle phase. A plain object cannot masquerade as an entry, and heterogeneous lists preserve the union of their extension-node kinds under strict TypeScript.++The public construction surface is `createMarkdownPlugin()`, `createMarkdownTextTransform()`, `createMarkdownFenceTransform()`, and `createMarkdownSourceDecoration()`. Limited Remark compatibility is a separate tree-shakeable `createMarkdownRemarkTransform()` export from `@astryxdesign/core/Markdown/remark`. These helpers return or annotate the one `transform` capability; they never accept React render callbacks and are not additional lifecycle phases. In particular, `createMarkdownFenceTransform()` maps eligible built-in code nodes to an owning plugin's typed extension data, while that plugin's standard `renderers` map owns presentation and `toText`. Detailed TypeScript signatures and examples live in the Markdown consumer docs, while these names and responsibilities are part of this contract.++The canonical document is an immutable, discriminated, Unist-shaped tree aligned with the supported MDAST subset below. **MDAST is a public community specification maintained by the syntax-tree/unified ecosystem, not a browser or standards-body API.** Astryx's public contract is its own exported, versioned TypeScript node union: it uses the listed MDAST node names and field meanings where they align, documents every deviation, and does not promise nominal or structural interchangeability with arbitrary `mdast`, Unified, or third-party plugin versions. Parsing, transforms, Markdown rendering, and Outline projection observe the same node meanings. Released parser entrypoints retain their current result types and values through a compatibility boundary; adopting plugins requires no migration.++The Markdown owner exposes stable node unions and node-kind-narrowed traversal. Plugin-defined extension kinds augment the generic union without widening unrelated built-in callbacks. A transform receives readonly input and returns the original root or a replacement root. Equivalent validation and immutability implementations are permitted.++A syntax contribution declares non-empty literal prefixes, a finite pending bound, and a synchronous deterministic tokenizer. It may emit only its owning typed extension nodes. Syntax-bearing plugins declare stable parse identity; only ordered syntax identity participates in incremental parse identity.++A transform is synchronous and deterministic. It may replace, insert, remove, or annotate representable nodes within the permitted-edit matrix. It cannot mutate input, author source provenance, introduce raw markup or React values, or bypass Core-owned semantics. Transform changes refresh transformed output without changing syntax parse identity.++Renderers receive typed extension-node data only. Every extension node introduced through syntax or transform has a renderer and deterministic perceivable-text projection. A source-backed leaf falls back to exact authored source; a synthetic leaf falls back to its required text projection; a container keeps and renders its validated children. Sibling content continues after failure.++Each extension kind declares `content: 'none' | 'phrasing' | 'flow'` or a finite allowlist that narrows the category implied by `display`. Core validates children at every transform boundary. Syntax-created containers declare an inner source span that Core parses; plugins never turn raw source into child nodes. A plugin may read or remove another plugin's nodes, but it may create, edit, or duplicate only its own. Cross-plugin reads are declared through `dependsOn` and validated against list order.++Plugin admission and every failure phase use one source-free, rate-limited `onPluginDiagnostic` channel in development and production. Malformed entries and protocol-version mismatches fail locally rather than throwing into the caller. Plugin-authored reports use stable codes, never document-derived text.++Text matching, semantic fences, and source decoration are optional transform helpers, not additional public phases. Equivalent optimized execution is allowed when it preserves ordered transform semantics and observable results.++## Canonical MDAST compatibility matrix-An extension node identifies its owning plugin, node kind, inline or block display, finite data, exact consumed source, and optional source range. Core authors source provenance. Plugin data is limited recursively to null, booleans, numbers, strings, arrays, and string-keyed objects. It is finite and acyclic and contains no React values, DOM nodes, functions, or raw markup.+| Node or field | Supported contract | Rejected or constrained behavior |+| ------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------- |+| `root`, `children` | One root; ordered typed children. | Removing/retyping the root; cycles; shared mutable children. |+| `text`, `value` | Text replacement, splitting, insertion, and removal. | Functions, React values, or non-string `value`. |+| `paragraph`, `strong`, `emphasis`, `delete` | Ordered phrasing children. | Block children inside phrasing containers. |+| `heading`, `depth` | Phrasing children may transform; transformed text participates in shared Markdown/Outline identity. | Changing a source-backed heading's depth; renderer-defined IDs. |+| `inlineCode`, `break` | Standard MDAST meaning. | Transforming protected inline-code contents through text helpers. |+| `link`, `url`, `children` | Phrasing children; every Astryx-owned destination is revalidated by the navigation owner. | Nested links; bypassing destination policy; non-string URLs. |+| `image`, `url`, `alt` | Revalidated resource URL and text alternative. | Bypassing resource policy or removing required alternative text. |+| `blockquote` | Ordered block children. | Invalid child kinds. |+| `list`, `listItem` | `ordered`, optional `start`, `spread`, optional `checked`, and block children. Astryx also preserves the authored ordered-list `delimiter` for exact released projection. | Invalid task/list structure or non-finite starts. |+| `code`, `lang`, `meta`, `value` | MDAST semantics: `lang` is `null` when absent and `meta` is optional. Ordinary code remains copyable; fence helpers annotate the original node. | Replacing/removing source through the fence helper; bypassing `components.code`. |+| Astryx flow image | Preserves released standalone-image block behavior with `url` and `alt`; phrasing images retain normal MDAST placement. | Treating the flow extension as portable MDAST without adapter evidence. |+| `table`, `tableRow`, `tableCell`, `align` | Rectangular rows, phrasing cells, normalized alignment. | Replacing Core table semantics or producing ragged/invalid structure. |+| `thematicBreak` | Standard MDAST meaning. | Children or renderer slots. |+| `math`, `inlineMath` | Present only when the released math opt-in is enabled. | Enabling math through transformation alone. |+| `position` | Core-authored optional start/end UTF-16 offsets on source-backed nodes; line and column remain optional until available without changing released range behavior. Synthetic nodes omit position. | Authoring, shifting, or forging source positions. |+| `data` | Finite JSON-like plugin data under the owning plugin key; Core bookkeeping uses one reserved `astryx` namespace with no rendering effect by itself. | `hName`, `hProperties`, `hChildren`, functions, DOM/React values, raw-markup channels, or plugin-authored Core-reserved data. |+| Astryx extension node | Stable plugin/name/display/data discriminants; declared `none`, `phrasing`, `flow`, or narrowed allowlist content; renderer and text projection. | Foreign minting/editing/duplication, undeclared children, missing projection/renderer, or changing another plugin's discriminants. |+| Astryx citation node | Preserved as an owned typed extension to the MDAST subset. | Rewriting it as a link to bypass citation ownership. |+| Other MDAST nodes | Unsupported unless a later current contract adds them. | `html`, definitions/references, footnotes, frontmatter, directives, MDX, and other unknown nodes fail closed in the Remark adapter. |-A syntax-bearing entry declares stable parse identity through its ordered `name`, `apiVersion`, and `parseKey`, plus a complete renderer set for every extension-node kind it may emit. An entry without syntax cannot declare `parseKey` or renderers. Extension typing propagates through emphasis, links, headings, lists, blockquotes, tables, and every other recursive built-in container. The default no-extension type remains the released parser surface.+## Permitted transform edits-A text contribution supplies a global regular-expression pattern, may compute a later match end, and renders only the claimed text. Every match must advance. A computed end must be monotonic and within the available text. Public text contributions run only on eligible remaining built-in prose outside code, images, citations, and existing link children, and never process extension nodes. The internal legacy adapter alone retains the broader traversal required by FR20.+| Surface | Permitted | Rejected |+| ------------------------------- | ----------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------- |+| Document root | Return the same root or a structurally valid replacement root. | Removing/retyping the root or adding an independently rendered document shell. |+| Source-backed text and phrasing | Replace, split, insert, remove, or annotate while preserving protected contexts. | Text-helper matches inside protected code, links, images, citations, math, or accepted opaque syntax. |+| Headings | Transform phrasing children; remove or reorder headings; shared identity updates from transformed text. | Changing a source-backed depth, forging/duplicating provenance or identity, or supplying a renderer-only ID. |+| Links and images | Insert or update values that pass their current navigation/resource owners. | Bypassing destination, protocol, alternative-text, or trusted-resource policy. |+| Lists and tables | Insert, remove, or transform valid descendants while retaining Core-owned semantics. | Changing roles, ownership, or producing invalid structure. |+| Code fences | A semantic-fence helper may attach owned typed extension data to the original code node. | Replacing source through the helper, rendering inside the helper, or taking precedence over `components.code`. |+| Source decoration | Attach non-semantic, non-interactive presentation metadata to source-backed ranges. | Changing AST meaning, focus order, accessible name, navigation, selection, or copyable text. |+| Plugin extension nodes | Insert/edit the transform owner's node; read or remove foreign nodes/subtrees; preserve validated children. | Minting, editing, duplicating, or internally reordering another plugin's node; undeclared child content. |+| Inline entrypoints | Return exactly one paragraph-equivalent root containing phrasing nodes. | Block nodes, multiple top-level blocks, or a changed container shape. |-A syntax contribution declares one or more non-empty literal prefixes, a finite pending bound, and a synchronous tokenizer. The tokenizer receives the source, UTF-16 offset and exclusive end, finality, inline or block context, line start, and column. It may report no match, bounded defer, or a match that advances and supplies plugin data without source provenance. Inline syntax supplies one deterministic plain-text projection. Block-only syntax does not.+## Limited Remark compatibility profile-A fence contribution declares one or more languages and synchronously enhances, explicitly falls back, or declines. Rendering mode is exactly interactive, passive, or inert. Core supplies the exact source, normalized language, uninterpreted metadata, optional source range, finality, mode, and ordinary copyable fallback. Asynchronous loading may exist only inside returned render output under FR16.+A Remark adapter accepts a synchronous transform-only plugin confined to the matrix above. Each invocation receives a fresh mutable tree copy and an isolated constrained file object. The file exposes readonly source text, per-invocation finite JSON data, and diagnostic reporting; it exposes no processor registration, cross-run state, compiler, I/O, or async completion.-A decoration contribution has a stable identifier, source range, constrained visual description, and accessible label. Appearance is exactly highlight or underline. Tone is exactly neutral, accent, info, positive, warning, or critical. Decorations supply no authored children, renderer, DOM access, or parsing behavior.+The adapter's input type is structurally compatible with conventional Unified/Remark `Plugin` values, including their broad declared transformer return union, so a compatible package does not need a type wrapper. Runtime acceptance remains narrower: an invocation that actually returns a promise or uses an unsupported capability fails closed. Astryx exports its own supported-subset tree and file types rather than re-exporting or pinning the complete `mdast`/Unified type surface, so upstream type evolution cannot silently widen Astryx's contract.-Full and incremental parsing use the same plugin configuration. Incremental callers explicitly finalize input, and finalized incremental output equals full-parse output for the same source and options.+Remark compatibility is content-only, not presentation compatibility. Adapted plugins may return only the supported structural nodes and fields; Astryx still renders those nodes through its own components, tokens, navigation/resource policies, and accessibility semantics. `html`, `hName`, `hProperties`, `hChildren`, custom compiler output, CSS assumptions, and third-party renderer conventions are rejected rather than approximated. A plugin that needs new presentation must use an Astryx-owned typed extension node and renderer outside the Remark adapter.++The adapter validates the plugin's returned or mutated tree against the matrix before it becomes observable. Unsupported nodes, raw HTML, promises, shared processor state, invalid structure, forged positions, and unrepresentable metadata preserve the last valid tree and report a source-free diagnostic.++Compatibility is explicit per plugin and tested version. “Remark-compatible” means equivalent supported-subset fixtures pass the adapter matrix; package shape or ecosystem membership alone is not evidence. Plugins using processor data, micromark extensions, async work, unrestricted `VFile` behavior, unsupported nodes, renderer metadata, or compiler hooks are outside the profile.## Requirements-### Admission, compatibility, and publication+### Admission and compatibility-- **FR1 — One public plugin model.** `plugins` and `createMarkdownPlugin` are the canonical general extension model. A plugin declares only the capabilities it uses. No second plugin prop, lifecycle-grouped API, registry, discovery mechanism, or unrestricted document hook is introduced. Entries are opaque rather than accepted as arbitrary structural objects. A syntax-bearing entry must provide stable parse identity and a complete renderer set; an entry without syntax cannot declare either. Extension typing must remain discriminated through every recursive built-in container.-- **FR2 — Exact zero-plugin compatibility.** When `plugins` is omitted or empty and `inlinePlugins` is absent, Markdown takes the current code path without plugin normalization, indexing, allocation, cache-key changes, renderer wrappers, remounts, AST changes, DOM changes, styling changes, or measurable performance regression. Released no-plugin node unions and overloads retain their exact meaning.-- **FR3 — Released seams remain compatible.** Existing `components`, citations, opt-in GFM autolinking, sources, parser signatures, and any separately accepted focused-syntax contract retain their meaning. Existing consumers do not migrate to adopt plugins. Exact released field names, optionality, mutability, and no-plugin result types remain unchanged.-- **FR4 — `inlinePlugins` migrates only after parity.** Until modern text contributions have behavioral and type parity, migration docs, and a codemod, `inlinePlugins` is not deprecated. Core then adapts it internally as one final synthetic text contribution so current traversal, overlap, callback results, and error behavior are preserved—including `null` render output and thrown callbacks. The later soft deprecation adds guidance, not removal or a second runtime path. Removal or safer callback semantics require a separate breaking decision.-- **FR5 — Astryx-authored modules follow the Table precedent.** Each independently contractible first-party plugin is colocated under Markdown, has a canonical module record matching its public export, and is re-exported through Markdown and Core. Public authors may export a static plugin, a named factory, or a named hook according to whether the capability is fixed, configured, or live. Those exports construct or return durable plugin entries; they are not registries. Private dispatch, indexing, cache, and normalization helpers require neither module records nor public exports.-- **FR6 — External publishing is ordinary package composition.** A third party may publish a compatible plugin with a peer dependency covering the supported Core semver range, explicit module-system exports as needed, and tree-shakeable modules unless a documented side effect is required. Runtime protocol version validates compatibility. Astryx creates no separate plugin library or package family and performs no package discovery.+- **FR1 — One public plugin model.** `plugins` and `createMarkdownPlugin()` are the canonical extension seam. The only protocol capabilities are `syntax`, `transform`, and `renderers`; helper APIs may compile common use cases into transforms.+- **FR2 — One empty-pipeline behavior.** Omitted plugins and an empty list have identical AST, DOM, styling, targets, IDs, errors, and streaming behavior. Core may avoid empty normalization and allocation, but no behavior may depend on whether the empty list was explicit.+- **FR3 — Zero breaking changes.** Existing `components`, `inlinePlugins`, citations, opt-in GFM autolinking, math, sources, parser signatures, fields, optionality, mutability, no-plugin result types, DOM, accessibility, heading/Outline identity, streaming reuse, and renderer precedence retain their released meaning and behavior. Opting into plugins adds behavior only for that callsite.+- **FR4 — `inlinePlugins` migrates only after parity.** No deprecation occurs until a helper-backed transform preserves every released traversal context, overlap rule, callback result, `null`, throw, migration-doc, and codemod requirement.+- **FR5 — Entries are durable package values.** First-party plugins are colocated under Markdown and exported normally; third-party plugins are explicit package imports with a compatible Core peer range. No registry or discovery mechanism exists.-### Phase order and collisions+### Parsing and immutable transformation-- **FR7 — One fixed phase order.** Core recognizes built-in syntax and extension syntax; renders built-in and extension nodes and resolves semantic fences; applies text contributions only to remaining eligible built-in prose; then applies decorations to rendered source ranges. Decorations never change parsing. Text contributions never process extension nodes.-- **FR8 — Built-in lexical shields win for modern contributions.** Escapes, inline code, fence bodies, existing links and images, citations, and any accepted focused opaque syntax remain protected from public syntax and text contributions. Inline extension syntax runs only on remaining literal source and may run inside built-in emphasis or strikethrough after those containers are recognized. Block extension syntax runs only at a top-level line boundary after built-in blocks decline and before paragraph fallback; it does not run inside list items or blockquotes. The internal legacy `inlinePlugins` adapter is the sole compatibility exception: FR20 preserves its current recursive traversal into existing link children.-- **FR9 — Ordered first claim resolves exclusive conflicts.** Duplicate plugin names fail validation. Syntax plugins and their contributions are consulted in plugin-array and declaration order. The first match claims source; no-match continues; defer reserves the current offset until resolved. A proper prefix of an earlier matcher similarly reserves a non-final tail. Fence claimants use normalized case-insensitive language names: decline continues, while enhancement or explicit fallback resolves the fence. Text matches use the same ordered first-claim overlap rule, with the synthetic legacy contribution last.-- **FR10 — Decorations compose instead of claiming.** Every valid decoration contribution reaches the post-render phase in plugin order and its own representable contribution order. One contribution cannot suppress another. This shared protocol does not define capability-specific source anchoring, overlap presentation, selection, stale mapping, or host actions; those behaviors remain outside scope until a concrete module is proposed.+- **FR6 — Fixed order.** Built-in and extension syntax parse first; transforms then run in plugin-array order; rendering runs last. A transform observes the validated result of every earlier transform.+- **FR7 — Built-in lexical shields win during syntax.** Escapes, inline and fenced code, links, images, citations, math, and accepted opaque syntax remain protected according to their current owners. Block extension syntax remains top-level unless a current owner explicitly broadens it.+- **FR8 — Ordered syntax claims.** Duplicate plugin names fail validation. Syntax contributions resolve in plugin and declaration order; first match wins, defer reserves the bounded candidate, and terminal parsing resolves all pending source.+- **FR9 — Canonical AST is MDAST-aligned and strictly typed.** Parsing, transforms, rendering, and Outline projection use one stable Unist-shaped subset with complete available source positions. Public node-kind traversal narrows callbacks by discriminant, including generic plugin extensions. Released parser functions retain their existing result types and values until a separately approved migration.+- **FR10 — Transform input is immutable.** A transform returns the same root or a replacement root. Attempted mutation cannot change any observed input node, array, data object, source position, prior snapshot, or later plugin input.+- **FR11 — Transform output is representable and validated.** Output is finite, acyclic, typed data that satisfies both matrices above. Core rejects raw HTML, React values, DOM nodes, functions in node data, invalid built-in structure, foreign extension ownership, authored/shifted provenance, and block-shaped output from inline entrypoints.+- **FR12 — Transform failure is local to the plugin.** A throw, promise, rejected thenable, invalid result, or unsupported adapter output reports one source-free diagnostic and passes the last valid root to later plugins and rendering. Core attaches a rejection sink before refusing an asynchronous tokenizer or transform so a rejected promise cannot escape through the host's unhandled-rejection channel. Source-backed nodes preserve authored-source fallback; synthetic extension leaves use their required perceivable-text projection; extension containers preserve their validated children.+- **FR13 — Live transforms do not reparse or mutate retained output.** Adding, removing, reordering, or updating transforms refreshes transformed output without rerunning syntax tokenization. Only current parser options and ordered syntax identity invalidate syntax parse identity. Prior snapshots stay unchanged; unchanged settled legacy output retains its released reuse and remount behavior.-### Syntax validation and streaming+### Rendering and cross-surface identity-- **FR11 — Prefixes and matches advance.** Every declared prefix is a non-empty literal string. Offsets and ranges use JavaScript UTF-16 units. A match end is greater than the current offset and no greater than the available end. Emitted plugin, node name, and display kind must match the owning definition. Invalid configuration or output fails validation rather than looping, truncating content, or silently changing resolution order.-- **FR12 — Tokenization is synchronous and deterministic.** A tokenizer depends only on its supplied source window, position, finality, context, and immutable parse configuration. It performs no I/O, time-dependent work, random work, mutation, or asynchronous work. Core rejects promises but cannot sandbox trusted application code. Callback complexity remains the plugin author's documented responsibility.-- **FR13 — Pending syntax has one bounded decision span.** Every syntax contribution declares a positive finite UTF-16 span at least as large as its longest prefix. Core exposes at most that span from a candidate in both full and incremental parsing. The tokenizer must return match or no-match within it; defer is accepted only while non-final input has not yet filled the span. A match end remains inside the supplied span. A terminal incremental call resolves every remaining candidate under the same bound as full parsing, stores a final immutable snapshot, and produces the same AST for the same source and options. Omitting finality remains equivalent to false for released incremental-call compatibility.-- **FR14 — Core owns source provenance.** Core attaches the exact consumed source and optional absolute range. Plugin callbacks do not author or shift provenance. Extension nodes are immutable finite acyclic data. They cannot contain React values, DOM nodes, functions, or raw markup, and cannot insert, delete, reorder, or mutate unrelated nodes. Each extension node is atomic for streaming fade boundaries and advances by its consumed source length.+- **FR14 — Extension rendering is complete and local.** Every extension kind a plugin may introduce has an owning renderer and perceivable-text projection. Missing or failed rendering preserves exact authored source for source-backed leaves, the required projection for synthetic leaves, or validated Markdown children for containers; siblings continue running.+- **FR15 — Core semantics remain authoritative.** Plugins cannot replace the document root or override Core-owned heading level/ID, navigation, image policy, list semantics, table semantics, or built-in accessibility behavior. Trusted renderer-created links and resources remain renderer-owned.+- **FR16 — One heading projection.** Markdown and Markdown-derived Outline use the same syntax list, transform list, text projection, slugger, collision allocator, and released top-level heading traversal. Renderer output cannot change identity. A heading nested in an extension container behaves like one nested in a blockquote: it does not create an Outline entry or extend heading-ID traversal unless a later owner contract permits it.+- **FR17 — Existing code override remains compatible.** A semantic-fence helper may annotate an eligible original code node but cannot replace its source. Rendering resolves `components.code` first; only when absent may the helper proposal render. Ordinary copyable code is always the local fallback.-### Fence completion and fallback+### Remark compatibility-- **FR15 — Fence input states are explicit.** Every semantic fence renderer receives the literal source, normalized language, uninterpreted metadata, source range when enabled, finality, rendering mode, and Core's ordinary-code fallback for that exact source. A plugin may enhance, explicitly select fallback, or decline so a later claimant can run. It cannot suppress source because input is incomplete or unsupported.-- **FR16 — Core owns error isolation and copyable fallback.** Unsupported languages, exhausted declines, refusal, invalid results, thrown errors, rejected lazy subtrees, unavailable lazy dependencies, incomplete final fences, and unsupported modes render ordinary copyable code. Error isolation is local to the fence, and sibling Markdown continues rendering. Development diagnostics identify the plugin and fence once without exposing source contents. The protocol remains synchronous; asynchronous loading or rendering may occur only inside a returned lazy or Suspense subtree and Core's local fallback and error boundary, so no pending protocol state or stale-completion race exists.-- **FR17 — Mode bounds interactivity.** Interactive mode permits the plugin's documented controls. Passive mode renders perceivable output without requiring activation. Inert mode supplies noninteractive output suitable for restricted or server contexts. A plugin that cannot satisfy the requested mode returns fallback or decline.-- **FR18 — Existing code override remains compatible.** When the released custom code renderer is supplied, it keeps the application-owned all-fence override and wins before plugin fence resolution. Removing that override exposes the ordered plugin chain and Core fallback. No consumer is silently migrated. Generic CodeBlock syntax highlighting remains existing CodeBlock behavior, not a plugin responsibility.+- **FR18 — Adapter scope is explicit.** The adapter supports only synchronous transform-only plugins over the documented MDAST subset. It does not emulate Unified parser/compiler registration, async execution, processor state, or unrestricted `VFile` behavior.+- **FR19 — Translation is lossless or rejected.** Each adapted node and metadata field has a documented round trip. Unsupported input or output fails closed with readable source; the adapter never silently drops or approximates content.+- **FR20 — Compatibility is tested per plugin.** A package is called compatible only after fixtures prove equivalent supported-subset output, protected-context behavior, diagnostics, source preservation, and server rendering.-### Rendering, text, and Outline+### Resources-- **FR19 — Extension rendering stays local and complete.** Every syntax-bearing plugin statically supplies a complete renderer set for every node kind it can emit. Missing or incomplete ownership fails type checking or validation. Non-syntax plugins cannot provide a renderer-only branch. Renderers receive typed extension-node data only and cannot replace Core-owned document, heading or heading-ID, navigation, image, list, or table semantics.-- **FR20 — Text parity preserves legacy behavior.** Public text contributions cover the released regular-expression pattern, end-index, and render-callback capabilities but follow FR8's modern protected-context and failure defaults. The internal final synthetic `inlinePlugins` adapter preserves every released traversal context, overlap rule, callback result, and error behavior: it recurses through emphasis, existing link children, lists, and table cells; skips inline code, fenced code, images, and citations; preserves a valid `null` result; and does not add local recovery for a thrown legacy callback. Core validates progress and bounds without changing valid output. Exact fixtures, including linked-child text, `null`, and thrown callbacks, must remain equivalent before soft deprecation.-- **FR21 — One text projection governs plugin-enabled heading identity.** When inline extension nodes can contribute to headings, Markdown and Outline use the same plugin list, parse options, text projection, slugger, and collision allocator, producing unique matching IDs for that plugin-enabled document. Renderer output cannot change the generated ID. Block extension nodes do not create Outline entries in the first protocol version. The zero-plugin path retains its released heading-ID behavior under FR2.-- **FR22 — Missing or failed modern capability preserves readable source.** Unknown or unmatched syntax remains literal. Unknown, declined, refused, invalid, or failed fences render ordinary code. A tokenizer throw disables only that contribution for the current parse and continues ordered matching; if nothing claims the source, it remains literal. A plain-text projection failure uses the exact node source. Core isolates each modern text callback and extension renderer: a throw renders the exact matched text or node source locally and leaves sibling Markdown running. Modern plugins cannot make authored content disappear. Renderer-specific rich output has a perceivable text alternative when its visual representation is not equivalent to the source. Development diagnostics identify the failed plugin and capability once without logging source contents. The legacy adapter follows FR4 and FR20 instead.+- **FR21 — Unclaimed work is bounded.** A helper callback runs only for an actual claim; unmatched source cannot invoke it. Stable and recreated semantically equivalent plugin lists must both satisfy FR23, without requiring any particular preparation or dispatch implementation.+- **FR22 — Existing parser budgets remain the floor.** The canonical [parser performance fixture](../../../packages/core/src/Markdown/parser.perf.test.ts) remains green: full parse stays below 20/50/100/400/1000 ms at 10/50/200/500/2000 sections; full and incremental 50-character streaming stay below 5000 ms at 50 sections and 30000 ms at 500; incremental time stays at most 1.1× full reparse; and its exact settled-tail work, object-reuse, source-range, median/worst-block, and tracked whole-prefix assertions remain unchanged.+- **FR23 — Focused overhead budgets cover both transform paths.** Under the evidence protocol below, each budget names the path it measures. First-party helper transforms: five zero-work helpers add at most 15 percent and the representative three-helper set adds at most 25 percent, at both fixture sizes. Plugin-authored transforms, which pay full immutability and validation guards: five zero-work transforms add at most 30 percent and the representative three-transform set adds at most 50 percent, at both fixture sizes. Streaming the representative plugin-authored set stays within FR22's streaming budgets and at most 1.25× the same stream with an empty pipeline. Per-transform guard work is bounded by one traversal of that transform's output; whole-document invariant collection happens once per pipeline run, not once per transform. Core may skip a guard for a helper-authored transform only where the helper's own construction already guarantees the property, and the published budget must say which path a number describes.+- **FR24 — Optional work stays optional.** Remark adapters, the conformance kit, and heavy renderers are tree-shakeable and absent from parser-only/server bundles unless imported.-### Decorations+### Extension containers, ownership, and node data-- **FR23 — Decorations are constrained live post-render contributions.** Decorations run after text output, never mutate the AST, and do not participate in parse identity. Core owns source segmentation, noninteractive wrappers, Astryx-token visual painting, contribution ordering, and local failure isolation for the constrained decoration descriptors. Plugins receive no authored children, DOM node, React renderer slot, or AST mutation hook. A decoration change must not reparse content or remount unaffected syntax or fence output. Capability-specific anchoring, overlap presentation, selection, streaming, stale mapping, and host actions remain outside scope until a concrete module is proposed.+- **FR25 — Extension nodes declare their content.** Every extension kind declares `'none'`, `'phrasing'`, `'flow'`, or an explicit allowlist with optional finite cardinality bounds. An allowlist narrows the category its `display` already implies and never widens it, and an extension kind's name may not collide with a supported built-in node name. Core validates the declaration at admission and the actual children at every transform boundary. A container produced by syntax declares an inner source span that Core parses; no plugin supplies children built from raw source. Containers count toward the built-in container-depth bound, neither restart nor extend the heading traversal in FR16, and keep their children when their renderer fails.+- **FR26 — Ownership is minting and editing, not existence.** A transform may read another plugin's extension nodes and may remove them, including removing a subtree that contains them. It may not create, edit, reorder the internals of, or duplicate a node owned by another plugin. A source heading may be removed or inserted but its depth may not change and its identity may not be forged or duplicated. Every rejection under this rule reports a diagnostic that names the ownership rule and the owning plugin rather than a generic invalid-document code.+- **FR27 — Plugins declare the plugins they read.** `dependsOn` lists plugin names whose extension nodes a plugin reads. Preparation validates that each named plugin is present and ordered earlier. An unmet or misordered dependency is a failure local to the declaring plugin: its transform does not run, its syntax and renderers remain active, and one diagnostic distinguishes missing from misordered. Declaring no dependency keeps array-order-only behavior.+- **FR28 — Core-internal per-node state lives in one reserved data namespace.** Core's own per-node bookkeeping is a documented reserved key of node `data`, not a hidden, non-enumerable, or signature-matched channel. Plugin data lives under the owning plugin's key. Plugins may read reserved data; authoring, editing, forging, or removing it is rejected with a diagnostic.-### Security and accessibility+### Diagnostics and failure visibility-- **FR24 — Markdown source is untrusted; installed plugins are trusted code.** Source may select only capabilities already imported by the application. It cannot name packages, discover a registry, load code, or grant parser callbacks additional capabilities. Renderers and hooks are ordinary trusted application code and are not sandboxed by Markdown.-- **FR25 — Core exposes no raw-markup parser channel.** Parser callbacks and accepted extension-node or decoration data contain only finite acyclic data. The protocol exposes no raw-HTML node, DOM-valued AST field, arbitrary AST visitor, or `dangerouslySetInnerHTML` helper. Trusted renderers remain responsible for their own safe React or SVG output.-- **FR26 — Navigation and embedded-resource owners remain authoritative.** URL-like plugin data is not trusted. Astryx-owned navigation follows [`family:navigation-destinations`](../../families/navigation-destinations.md). Embedded resources retain their separate stricter policy. Core does not claim to sanitize links or resources manufactured entirely by trusted renderer code.-- **FR27 — Plugin output has a documented semantic contract.** Each public plugin documents role, accessible name and description, keyboard and focus behavior, reduced-motion behavior, forced-colors behavior, non-color meaning, and text fallback. Built-in document, heading, navigation, image, list, and table semantics cannot be overridden. An interactive plugin owns its complete established ARIA pattern and must not create invalid nested interaction.+- **FR29 — One diagnostic channel, including in production.** `onPluginDiagnostic` is available on the component and in parser options and receives one event per failure or advisory: the plugin name, phase (admission, syntax, transform, render, or adapter), stable enumerated code, and severity. Events are source-free by construction — no document text, node values, destinations, or positions — and are delivered in development and production. Delivery is rate-limited per document and plugin/phase/code, and a suppression code reports when the bound is reached. With no handler, development surfaces each unique code once and production stays silent. `context.report()` accepts a plugin-authored stable code rather than document-derived text and is delivered as an advisory, never as a failure. Any condition that silently degrades a document to reduced plugin behavior, including exceeding a validation size bound, emits a diagnostic.+- **FR30 — Admission and version failures are uniform and soft.** A malformed entry, duplicate name, unsupported protocol version, or otherwise unadmissible list behaves identically through the component and every public parser entrypoint: the call succeeds with the last valid configuration — an empty pipeline when nothing is admissible — reports one diagnostic, and never throws into the caller. A protocol-version mismatch is never an import-time or module-scope throw. Plugin identity created by a compatible duplicate Core copy remains valid through a stable cross-package brand whose frozen shape and version are verified.-### Identity, updates, and resources+### Authoring, canonical APIs, and packaging-- **FR28 — Parse identity includes syntax contributors only.** Incremental parse identity is the ordered tuple of plugin name, protocol version, and `parseKey` for syntax-bearing plugins in plugin order, plus existing parse-affecting Markdown options. Text, fences, renderers, decorations, plugin object identity, permissions, selection, and other live state are excluded. Adding, removing, reordering, or updating a non-syntax plugin refreshes only its post-parse behavior and retains settled AST cache. A syntax plugin changes its `parseKey` whenever its parser output can change. Changing the filtered syntax order or key invalidates once. No separate render key is required.-- **FR29 — Stable live updates avoid reparse and remount.** A stable logical plugin may update non-parse callbacks, lazy resources, or other live post-parse state without reparsing or remounting unaffected output. Development warns when renders repeatedly recreate an equivalent plugin or list with the same logical keys where stable identity would avoid preparation or allocation. Production behavior remains correct and warning-free.-- **FR30 — Stable plugin preparation is reused.** For a stable ordered plugin list, Core must prepare plugin dispatch once and reuse it across parsing and rendering. It must not repeat list-wide preparation unless the ordered list, protocol version, or syntax parse identity changes, and it must not inspect every plugin at every source character or rendered node. Live non-syntax updates refresh only their affected post-parse behavior and preserve the no-reparse and no-remount guarantees in FR28–FR29.-- **FR31 — Existing parser budgets remain the plugin-free floor.** Plugin-free full parsing remains below 20 milliseconds for 10 generated sections, 50 milliseconds for 50, 100 milliseconds for 200, 400 milliseconds for 500, and 1,000 milliseconds for 2,000 under the existing benchmark. Existing streaming budgets and settled-tail reuse gates also remain in force.-- **FR32 — Core overhead has focused budgets.** Evidence covers the exact plugin-free path, five zero-work plugins, realistic text, syntax, and fence plugins, streaming reuse, allocation counts, and remount counts. Zero-work dispatch adds at most 15 percent to 200- and 500-section parse medians. Realistic trivial callbacks add at most 25 percent while remaining within the absolute FR31 ceilings. These are Core preparation and dispatch budgets, not promises about arbitrary plugin work.-- **FR33 — Optional work stays optional.** Heavy optional renderers are lazy and tree-shakeable and remain absent from Core's parser path and bundle unless explicitly imported. Parser-only and server use requires no DOM. Each shipped plugin documents and tests its own callback and resource budget.+- **FR31 — Extension types are inferred.** `createMarkdownPlugin()` infers the plugin's extension-node union from its declaration. No callsite requires explicit type arguments or a hand-written node alias to obtain correct narrowing in `renderers`, `transform`, traversal, and the aggregated list union. A declaration that produces extension nodes without a matching renderer, or that resolves to an empty extension union while extension kinds are used, is a type error rather than a silently permissive `never`.+- **FR32 — The canonical AST has public parse entrypoints.** `parseMarkdownAst()` and `parseInlineAst()` return the canonical tree these types describe, accept the same options and ordered plugin list as the component, and sit beside the released `parseMarkdown` family, which keeps its projected result shape.+- **FR33 — A server-safe parser entry exists.** `@astryxdesign/core/Markdown/parser` exports parsing, canonical AST types, and plugin admission with no client-boundary directive, so a server importer does not pull a client reference. It is registered in the generated export map and covered by an import fixture, exactly as the adapter entry is.+- **FR34 — A conformance kit produces per-plugin evidence.** `@astryxdesign/core/Markdown/testing` exports fixtures a plugin author runs to produce the evidence FR20 requires: protected contexts, immutability, validation rejection, failure fallback and diagnostics, container content validation, streaming idempotence, and server rendering. It is tree-shakeable and absent from runtime bundles.+- **FR35 — Compatibility and limits are consumer-documented.** Consumer documentation publishes the supported and rejected categories with the Astryx answer for each: transform-only content rewriters are supported; anything that extends the grammar, emits markup or hast, depends on processor or file state, or only reports messages is not. It states plainly that no raw-markup stage exists, names the native capabilities that make specific plugin categories unnecessary, and documents that a renderer is arbitrary application code, so the trust boundary is the plugin package rather than the document.-## Public parser integration+### Streaming, theming, and stability-Markdown's block, inline, incremental, and Outline parsing entrypoints must accept the same plugin configuration and infer the same extension-node union. Every released no-plugin name, overload, return type, field, and mutability guarantee remains unchanged. Full and incremental parsing use the same plugin configuration; only incremental parsing exposes finality. Exact type names, overload declarations, and private mapping helpers belong to their owning API declarations and records.+- **FR36 — Transforms are idempotent under streaming.** A transform runs again for every streamed update. Given the same source prefix it must return the same result, and its output must converge rather than oscillate as the prefix grows. Transforms whose effect is valid only on complete input use the final-input signal. Evidence includes a no-oscillation fixture across chunk boundaries.+- **FR37 — Extension output has an opt-in theme target.** An extension renderer may opt into one Markdown-owned extension theme target so themes can reach plugin output. Opting out leaves output untargeted. The target carries no default styling or anatomy beyond block spacing and content width Core already applies, and it does not make plugin output part of Markdown's default anatomy.+- **FR38 — Prepared work is reused for equal lists.** Semantically equal plugin lists reuse prepared syntax and transform work across renders whether or not the array reference is stable, so preparation cost is not proportional to render count. Where reuse cannot be established, development reports one diagnostic identifying the recreated list, and consumer documentation states the hoisting guidance.+- **FR39 — Protocol stability is published.** The first public release publishes what `apiVersion` covers — entry shape, capability names, extension-node discriminants, declared content shapes, diagnostic codes and phases, and canonical node union — and what it does not — helper internals, unlisted AST fields, Core-reserved node data, and diagnostic text. A change that invalidates an existing conforming plugin bumps `apiVersion`; purely additive capability does not. The policy states which Core versions accept a given `apiVersion` and how skew fails, consistent with FR30.-## Compatibility, migration, and lifecycle+### Planned first-party scope-Existing consumers make no change.+- **FR40 — First-party plugins use the public protocol.** Astryx ships a small first-party set — a mention plugin, an entity-link plugin, and a callout container — built only on the public protocol, each owning its semantics and evidence in its own module record and serving as canonical documentation examples. No first-party plugin receives a capability, validation exemption, ordering privilege, or type affordance unavailable to a third party; an internal fast path is permitted only where it is observationally identical, per FR23.+- **FR41 — Footnotes, definitions, and references stay Core scope.** They are not a plugin surface: their identity is document-level ID allocation, collision handling, and back-reference navigation that Core owns under FR15 and FR16, and a plugin owning them would fork the identity system Markdown and Outline share. Until a separately approved contract adds them as Core syntax, they are unsupported, the adapter rejects them, and consumer documentation names the gap explicitly rather than implying a plugin workaround.-Modern text parity and the synthetic-last compatibility adapter must exist before adding a soft-deprecation annotation to `inlinePlugins`. The same release that soft-deprecates it supplies consumer migration documentation and a codemod to an equivalent plugin entry. The adapter remains for compatibility, and no removal timeline is implied.+## Performance evidence protocol-Protocol version changes only for incompatible protocol revisions. Package peer-semver ranges communicate which Core releases implement a protocol version. Mixed unsupported runtime versions fail validation before parsing or rendering.+- **Fixture:** a deterministic 200- and 500-section document; each section contains one heading, prose with an identifier and mention, a two-item list, a block quote, one table row, and an ordinary fenced code block.+- **Helper zero-work set:** five prepared first-party helper transforms with valid selectors that match no fixture node or source span.+- **Helper representative set:** three helpers that respectively match prose identifiers, annotate eligible code fences, and decorate a known source range.+- **Plugin-authored zero-work set:** five plugin-authored transforms that return their input root unchanged, taking the full immutability and validation path.+- **Plugin-authored representative set:** three plugin-authored transforms that respectively rewrite matched prose text, wrap a section in an extension container, and read a preceding plugin's nodes under a declared dependency.+- **Streaming set:** the plugin-authored representative set applied to the 200-section fixture streamed in 50-character chunks, compared against the same stream with an empty pipeline.+- **Comparison:** omitted/empty pipeline versus the same parse-and-transform call with the stable plugin list, in one isolated process and runner.+- **Sampling:** ten untimed warmups, then nine alternating paired rounds; each side averages 20 iterations per round. The reported ratio is the median of the nine paired ratios. Both 200- and 500-section ratios must satisfy FR23. An A/A control outside the measurement-validity bound invalidates that sample; the harness retries rather than certifying noisy output.+- **Cost-shape evidence:** guard traversal counts are asserted directly, so adding a transform may add at most one output traversal and may not repeat whole-document invariant collection.+- **Regression signal:** invoking a helper callback for unclaimed source, invoking a claimed helper more than once, regressing parse/result reuse, or publishing a number without naming its path must fail work-count or threshold evidence.-Astryx-authored plugin modules, their consumer docs, and their release notes land as separate atomic implementation changes only after AST-036 and the corresponding module contract are current. Each implementation owns public exports, generated API evidence, tests, docs, and a package Changeset. This specification-only change carries none.+## Public parser integration-## Future plugin ownership+Block, inline, incremental, canonical-AST, Markdown, and Outline entrypoints accept the same ordered plugin configuration and infer the same extension-node union while retaining their released signatures and projected result shapes. The canonical entrypoints return the canonical tree directly; released entrypoints keep their projection. The server-safe parser entry exposes the same behavior without a client boundary. Inline transforms must satisfy the one-paragraph phrasing constraint. Transform-only updates cannot increase syntax tokenizer calls, mutate prior snapshots, or remount unchanged settled output beyond current behavior.-No first-party plugin is proposed by this record. When a first-party plugin is designed, its public export and module record are added together; this shared protocol is linked rather than copied. Generic code syntax highlighting remains existing CodeBlock behavior.+### Public API admission evidence++| Caller-owned distinction | Before / unchanged default | Opt-in callsite | Why Core cannot derive it |+| ------------------------------ | ---------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ |+| No plugin behavior | `<Markdown>{source}</Markdown>` and `parseMarkdown(source)` retain released output. | `<Markdown plugins={plugins}>{source}</Markdown>` | Only the application knows which extension packages and ordering it trusts for this document. |+| Novel source grammar | Preprocess source or fork parsing; `components` and `inlinePlugins` cannot claim new block/inline grammar. | `createMarkdownPlugin({name, apiVersion: 1, parseKey, syntax, renderers})` | The application owns the literal grammar, bounded tokenizer, parse-version key, and extension semantics. |+| Semantic text/fence/range work | Existing `inlinePlugins` remains available; `components.code` remains the application-wide code override. | Put `createMarkdownTextTransform()`, `createMarkdownFenceTransform()`, or `createMarkdownSourceDecoration()` in the plugin's one `transform`; render typed output through `renderers`. | Only the plugin knows which prose, language, or source range has domain meaning; helpers cannot infer product semantics and never own rendering. |+| Rich extension container | No custom container syntax or renderer is active. | Declare `content: 'phrasing' | 'flow' | {allow, min?, max?}` and render the Core-parsed children through the owning renderer. | Core can validate and parse children but cannot infer whether a product concept is a callout, card, tab, or leaf. |+| Cross-plugin observation | Array order alone has no declared dependency. | Add `dependsOn: ['earlier-plugin']` before reading its nodes. | Only the later plugin knows that its transform requires another plugin's output; Core validates presence and order. |+| Diagnostics | With no handler, development reports unique failures and production stays silent. | Pass `onPluginDiagnostic={event => report(event)}` or the parser equivalent. | The host owns telemetry destination and retention; Astryx owns a source-free bounded event shape, not the logging system. |+| Canonical/server parsing | Released parser calls keep their projected unions. | Import `parseMarkdownAst` from `@astryxdesign/core/Markdown/parser` when a server or transform tool needs the canonical tree. | Core cannot infer whether a caller needs released compatibility data or canonical extension-aware structure. |+| Markdown-derived Outline | Existing calls omit options and retain released headings. | Pass the same `plugins` and finality to Markdown and `parseOutlineFromMarkdown`/`useOutlineFromMarkdown`. | The caller owns which document/plugin configuration both surfaces represent; Core then owns shared text/slug identity. |+| Theme reachability | Renderer output is untargeted by default. | Set the renderer's opt-in Markdown extension theme target. | Only the renderer author knows whether its application-owned output should participate in design-system theming. |++The new decisions are additive and opt-in. `components` swaps supported built-in rendering but cannot add source grammar or document transforms. `inlinePlugins` performs released prose matching but cannot add block syntax, canonical whole-tree transforms, or typed extension ownership. Existing parser options cannot express application-defined grammar, renderer ownership, declared cross-plugin dependencies, or host diagnostics. These surviving distinctions therefore belong to the caller and cannot be derived safely by Core.## Verification-- **FR1–FR6:** Public type, export, and compatibility evidence must cover direct exported inline-only, block-only, and mixed extension aliases; exact released built-in fields and mutability; nested emphasis, link, list, blockquote, and table typing; complete and incomplete renderer ownership; static, factory, and hook modules; first-party colocation and explicit third-party imports; and the zero-plugin path. Failure includes changing a released AST field or mutability, losing nested extension typing, accepting syntax without complete renderers, accepting a plain object as an entry, or preventing explicit tree-shakeable third-party import.-- **FR7–FR10:** Phase and collision evidence must cover built-ins; authored link children; competing syntax claims; fence decline chains; overlapping modern text; the synthetic legacy-last adapter; and overlapping decorations. Failure includes changing phase order, allowing modern text into protected links, changing legacy link-child output, making conflict resolution depend on chunking, or allowing one decoration to erase another.-- **FR11–FR14:** Parser validation and full-versus-incremental evidence must cover UTF-16 offsets; zero, backward, and overrun results; every-character prefix splits; omitted, false, and true finality; syntax reorder and `parseKey` changes; immutable snapshots; and exact source ranges. Failure includes callback loops or truncation, finalized incremental output differing from full parsing, mutation of settled nodes, or ranges no longer matching exact source.-- **FR15–FR18:** Fence evidence must cover unsupported, incomplete, and final input; enhancement, decline, explicit fallback, throws, lazy-subtree rejection, every mode, and the released all-fence custom-code override. Failure includes lost authored source, a fence error replacing sibling Markdown, asynchronous protocol state leaking into fence resolution, an unsupported mode remaining interactive, or the released override losing precedence.-- **FR19–FR23:** Rendering, text, Outline, and decoration evidence must cover every extension-node kind; legacy linked-child text, `null` output, and thrown callbacks; emphasis, list, and table traversal; code, image, and citation shields; modern callback failures; non-ASCII source; plugin-enabled duplicate headings; released no-plugin heading IDs; no decorations; two decoration contributions; stable live updates; and unaffected syntax and fence siblings. Failure includes removal of source, siblings, or valid layers; modern text entering protected links; changed legacy behavior; plugin-enabled heading and Outline identity diverging; no-plugin IDs changing; unmatched content disappearing; decoration changes reparsing or remounting unaffected output; AST mutation; decoration before text; or one valid decoration suppressing another.-- **FR24–FR27:** Security and accessibility evidence must cover script-like source; cyclic or non-data values; obfuscated URL-like data; interactive, passive, and inert output; keyboard operation; forced colors; reduced motion; light and dark themes; RTL; axe checks; and server rendering. Failure includes source loading code, raw markup entering parser output, an Astryx-owned unsafe sink activating, or essential meaning becoming color-only or pointer-only.-- **FR28–FR33:** Identity, cache, allocation, remount, performance, bundle, and server-import evidence must cover the exact zero-plugin path; five no-op plugins; adding, removing, reordering, and updating text, fence, renderer, and decoration entries; live callback and decoration updates; syntax add, remove, reorder, and `parseKey` changes; streaming; stable-list preparation reuse; and equivalent recreation. Failure includes a non-syntax change reparsing or dropping settled AST, a syntax-signature change failing to invalidate exactly once, repeated preparation for an unchanged list, zero-path allocation or indexing, work proportional to all plugins per character or node, budget overruns, or optional plugin code entering Core or the server parser.-- **Repository integrity:** Knowledge validation, type checks, public-content checks, formatting, and changed-file review must confirm that this proposal contains AST-036 and only required canonical backlinks. Failure includes invalid record shape, private context, unrelated component behavior, implementation, or a Changeset entering this proposal.+| Contract | Verification | Representative states | Mutation or failure expectation |+| -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------- |+| FR1–FR5 | Public type/export fixtures, DOM/AST snapshots, duplicated-Core-copy fixture, and the callsite matrix above | Omitted, explicit empty, stable/recreated lists, every released prop and parser overload, two Core copies in one graph | Removing empty parity, changing a released signature, or rejecting an entry created by a compatible second Core copy fails. |+| FR6–FR13 | Syntax claim matrix; typed narrowing; transform replacement/insertion/removal/annotation; inline-shape, mutation, cycle, raw, async, and provenance rejection | Full, inline, terminal, incremental partial/final, syntax-only update, transform-only update, prior snapshots | Reordering transforms changes ordered evidence; adding tokenizer calls, mutating a prior snapshot, or leaking a rejection fails. |+| FR14–FR17 | Renderer/fallback matrix, semantic-owner matrix, heading/Outline identity, code override precedence, server rendering | Source-backed and synthetic extensions, containers, duplicate headings, cross-base headings, custom code override present/absent | Failed render preserves exact source, required projection, or children; helper data never outranks `components.code`. |+| FR18–FR20 | One real compatible transform plus rejected async, parser-extension, raw-HTML, unsupported-node, forged-position, processor-state, and metadata fixtures | Every supported matrix row, constrained file messages/data, protected contexts, server rendering | Silent field loss, unsupported-node acceptance, source loss, or an escaping rejection fails closed fixtures. |+| FR21–FR24 | Canonical linked parser budgets, callback work counts, guard-traversal counts, bundle inspection, and the exact paired protocol above | 200/500 sections, stable/recreated lists, helper and plugin-authored zero-work and representative sets, streaming set | Any unmatched callback, duplicate claim callback, repeated whole-document guard, parser-budget regression, or breach fails. |+| FR25–FR28 | Content-declaration admission/tree validation, ownership matrix, dependency preparation, reserved-data rejection | Leaf, phrasing, flow, allowlist; nested containers at depth bound; foreign read/remove/mint/edit; unmet/misordered dependencies | Plugin-built raw-source children, invalid content, foreign mint/edit, or generic ownership diagnostics fail. |+| FR29–FR30 | Diagnostic fixtures in development/production and admission parity across entrypoints | Every phase/code, advisories, rate suppression, no-handler default, malformed list, duplicate Core, version skew | Silent production failure, document content in diagnostics, module-scope throw, or entrypoint divergence fails. |+| FR31–FR35 | Inference fixtures without explicit type arguments, canonical/server imports, conformance-kit self-test, documentation checks | Syntax-only, transform-only, renderer-only, heterogeneous lists, server import, third-party kit run | Explicit-type workarounds, client references in server entry, or undocumented rejected categories fail. |+| FR36–FR39 | Streaming no-oscillation, theme reachability, prepared-reuse counts, stability-policy docs | Chunk boundaries, final-only effects, themed/unthemed output, equal new-identity lists, version skew | Oscillation, unreachable opted-in output, per-render re-preparation, or unpublished policy fails. |+| FR40–FR41 | First-party module records/evidence and unsupported-node fixtures | Mention, entity link, callout; footnote/definition/reference source through parser and adapter | First-party privilege or plugin-owned footnote/definition support fails. |+| Repository integrity | Knowledge validation, public-content checks, typecheck, formatting, and changed-file review | Specification and every implementation PR | Internal content, stale owner records, unrelated paths, or formatting/type failures block merge. |## Related owner prerequisites-Before implementation acceptance, each prerequisite must exist in its canonical current owner and be linked by exact clause. This section records dependency status; it does not become a second owner.--1. Plugin-enabled Markdown and Outline must use one parse configuration and collision allocator for unique matching IDs, including citation-bearing headings and collisions across slug bases; the zero-plugin path retains released heading-ID behavior under FR2.-2. Incremental parsing must invalidate every current parse-affecting option before the ordered plugin parse identity extends that mechanism.-3. Parser and renderer navigation or embedded-resource behavior must conform to its current family owner before plugins rely on a shared result.-4. Modern text behavior must be proven against every released `inlinePlugins` fixture before soft deprecation or codemod publication; FR4 and FR20 remain the normative owner of that condition.+Before implementation acceptance, current owner clauses must cover:-If an exact current owner clause does not yet exist for prerequisites 1–3, the item remains an unresolved dependency. AST-036 does not silently create parallel Markdown, Outline, parser, navigation, or resource authority. Other parser cleanup remains report-only unless its canonical owner makes it an explicit dependency.+1. a stable canonical MDAST-aligned AST, typed node-map/visitor APIs, released-parser compatibility projection, public canonical parse entrypoints, and Core-owned semantic validation;+2. Markdown/Outline shared transformed heading identity and the unchanged top-level traversal both surfaces use;+3. observable invalidation identity that distinguishes syntax from live transforms;+4. navigation/resource conformance for transformed nodes;+5. exact `inlinePlugins` compatibility before any migration;+6. the diagnostic channel on the component and parser options;+7. the opt-in extension theme target in Markdown's theming anatomy;+8. server-safe parser and conformance-kit package entries;+9. first-party plugin module owners for mention, entity link, and callout.## Decision log-### DEC-1 — Keep one capability-named plugin model+### DEC-1 — Expose syntax, transform, and renderers only**Reference:** `spec:AST-036/DEC-1`-**Direction owner:** `cixzhang`, `2026-09-14`+**Direction owner:** `cixzhang`, `2026-09-15`-Adopts FR1. Capability names expose caller choices directly, remain shallow and searchable, and follow the existing Table composition precedent.+The public protocol has three concepts. Text matching, semantic fences, and decorations are transform helpers, not parallel lifecycle APIs, and they never render — presentation always comes from the owning plugin's `renderers`. This keeps one mental model while permitting specialized internal execution.-Rejected: immediately replacing released seams; adding parallel extension props; adding a registry or discovery mechanism; exposing unrestricted whole-document parse or render hooks; or organizing the public model around internal lifecycle stages.+Rejected: five independent public capability phases; a second transform prop; helpers that accept render callbacks; replacing simple local syntax with an unbounded document hook.-### DEC-2 — Colocate Astryx plugins; allow ordinary external packages+### DEC-2 — Make immutable AST transformation canonical**Reference:** `spec:AST-036/DEC-2`-**Direction owner:** `cixzhang`, `2026-09-14`+**Direction owner:** `cixzhang`, `2026-09-15`-Adopts FR5–FR6. First-party modules stay with Markdown and use ordinary public static, factory, or hook exports. Third parties use explicit package imports with protocol and package-version compatibility rather than an Astryx-controlled registry.+Transforms receive the canonical MDAST-aligned tree observed by parsing, rendering,+and Outline. Public node-kind traversal preserves strict discriminated narrowing,+including plugin extension nodes. Inputs are immutable and transforms return+validated roots. Core owners retain provenance, structural validity, fallback, and+semantic authority. Released parser results remain unchanged until a separately+approved migration.-Rejected: package discovery, central registration, a global plugin-marketplace contract, or separate first-party packages for the initial common plugins.+Rejected: a second transform tree, in-place mutation of canonical state,+transform-driven reparsing, raw markup, weakly typed string visitors, and+renderer-controlled heading identity.-### DEC-3 — Separate parse identity from live non-parse state+### DEC-3 — Support a limited Remark compatibility profile**Reference:** `spec:AST-036/DEC-3`-**Direction owner:** `cixzhang`, `2026-09-14`+**Direction owner:** `cixzhang`, `2026-09-15`++A tree-shakeable adapter may run synchronous transform-only Remark plugins over an explicit MDAST subset. Compatibility is per-plugin evidence, never inferred from package identity, and supported and rejected categories are published for consumers.++Rejected: adopting Unified/MDAST as Core's runtime, claiming arbitrary Remark compatibility, or silently approximating unsupported behavior.++### DEC-4 — Separate syntax identity from live transforms++**Reference:** `spec:AST-036/DEC-4`+**Direction owner:** `cixzhang`, `2026-09-15`++Only syntax and existing parser options determine parse identity. Transform and renderer updates reuse parsed output and rerun only their owning post-parse work.++Rejected: object identity as parse identity, transform-driven reparsing, a public render key, or repeated preparation for semantically equal inputs.++### DEC-5 — Extension nodes may contain validated Markdown++**Reference:** `spec:AST-036/DEC-5`+**Direction owner:** `cixzhang`, `2026-09-16`++Callouts, admonitions, details, tabs, cards, and columns require real Markdown children. An extension therefore declares leaf, phrasing, flow, or narrowed allowlist content, and Core validates children. Core parses syntax-container inner spans; plugins never build children from raw source, so provenance and protected contexts stay Core-owned. This deliberately does not widen heading identity: a heading inside a callout behaves like one inside a blockquote. A failed container renderer still exposes its validated children.++Rejected: leaf-only extension nodes; independent nested document shells; plugin-authored parsed children; unbounded nesting.++### DEC-6 — Ownership means minting and editing, not existence++**Reference:** `spec:AST-036/DEC-6`+**Direction owner:** `cixzhang`, `2026-09-16`++A transform may read or remove another plugin's nodes, including a removed subtree, but may not create, edit, internally reorder, or duplicate them. Source headings may be inserted, removed, or reordered but never re-levelled or given forged/duplicated identity. `dependsOn` makes cross-plugin reads explicit and validates presence and order.++Rejected: foreign-node immortality; immortal headings; silent missing/misordered dependencies; generic ownership diagnostics.++### DEC-7 — Failure is visible in production++**Reference:** `spec:AST-036/DEC-7`+**Direction owner:** `cixzhang`, `2026-09-16`++Astryx owns one source-free, rate-limited `onPluginDiagnostic` channel covering admission, syntax, transform, render, and adapter phases in development and production. Plugin advisories carry stable codes, not document-derived text. Admission failures are uniform across component and parser entrypoints; version skew never throws at import time. Rejected tokenizer and transform thenables are defused before refusal.++Rejected: development-only reporting; free-text document-derived messages; silent bounded-validation fallback; one entrypoint throwing where another recovers.++### DEC-8 — The canonical AST, server parser, and conformance kit are public++**Reference:** `spec:AST-036/DEC-8`+**Direction owner:** `cixzhang`, `2026-09-16`++Exported canonical node types have public parse producers. A server-safe parser entry avoids a client reference. Shared conformance fixtures let third parties produce required evidence. Plugin declarations infer extension types without hand-written aliases or multiple explicit type arguments.++Rejected: canonical types with no public producer; parser APIs reachable only through a client barrel; evidence requirements with no shared kit; inference deferred to examples.++### DEC-9 — Publish the cost of the path plugins actually take++**Reference:** `spec:AST-036/DEC-9`+**Direction owner:** `cixzhang`, `2026-09-16`++First-party helpers may skip guards their construction proves, but their numbers do not describe third-party cost. Budgets therefore name helper and plugin-authored paths separately, include streaming, and constrain guard work to one traversal of each transform output with whole-document invariants collected once per pipeline run.++Rejected: publishing helper-path numbers as protocol overhead; unmeasured streaming; repeated whole-document invariant collection per transform.++### DEC-10 — Footnotes, definitions, and references stay Core scope++**Reference:** `spec:AST-036/DEC-10`+**Direction owner:** `cixzhang`, `2026-09-16`++These concepts require document-level ID allocation, collision handling, and back-reference navigation shared with Markdown identity. They remain unsupported and adapter-rejected until a separate Core syntax contract adds them; documentation names the gap.++Rejected: first- or third-party footnote plugins; adapter translation into ordinary links; leaving the limitation undocumented.++### DEC-11 — First-party plugins are ordinary plugins++**Reference:** `spec:AST-036/DEC-11`+**Direction owner:** `cixzhang`, `2026-09-16`-Adopts FR28–FR30. Only ordered syntax contributors and existing parse-affecting Markdown options determine parse identity. Non-syntax capabilities, callbacks, lazy resources, and other live state update only their owning post-parse behavior. Equivalent internal implementations remain free to meet the observable cache, preparation, reparse, remount, and resource guarantees.+Mention, entity-link, and callout examples use only the public protocol, own their semantics and evidence in module records, and receive no capability, exemption, ordering privilege, or type affordance unavailable to third parties. An internal fast path is allowed only when observationally identical.-Rejected: object identity as parse identity; reparsing on live non-parse state changes; a separate public render key; repeated list-wide preparation for stable inputs; or work proportional to every plugin at every source character or rendered node.+Rejected: privileged first-party capabilities; demos that exercise private paths; a public protocol with no real first-party consumers.## Open questions-None. This contract is current; implementation and its required evidence remain pending.+None. The contract is current; implementation and compatibility evidence remain pending.## Content boundary-This record does not duplicate consumer signatures, prop or option references, examples, migration recipes, private parser or renderer mechanisms, repository file layouts, module-specific behavior, current audit results, or implementation steps. It links those facts to their canonical owners.+This record does not duplicate consumer signatures, examples, private dispatch/cache design, repository layout, first-party plugin behavior, or current audit results. Those belong to their canonical owners.diff --git a/packages/core/src/Markdown/Markdown.spec.md b/packages/core/src/Markdown/Markdown.spec.mdindex c47b870132..597d63ef7e 100644--- a/packages/core/src/Markdown/Markdown.spec.md+++ b/packages/core/src/Markdown/Markdown.spec.md@@ -7,7 +7,7 @@ authority: currentarchive_reason: nullsuperseded_by: nullapproved_by: cixzhang-approved_at: 2026-09-13+approved_at: 2026-09-15owners: [cixzhang]review_triggers: [api, theming]verified_by:@@ -16,6 +16,7 @@ verified_by:packages/core/src/Markdown/Markdown.public.test.ts,packages/core/src/Markdown/parser.test.ts,packages/core/src/Markdown/incremental.test.ts,+ packages/core/src/Outline/parseOutlineFromMarkdown.test.ts,packages/core/src/theme/themingTargets.test.ts,scripts/check-knowledge.mjs,]@@ -31,6 +32,10 @@ system_specs:spec:AST-002/DEC-5,spec:AST-005/DEC-1,spec:AST-005/DEC-2,+ spec:AST-036/DEC-1,+ spec:AST-036/DEC-2,+ spec:AST-036/DEC-3,+ spec:AST-036/DEC-4,]---@@ -39,18 +44,20 @@ system_specs:## IntentMarkdown renders parsed content in a Document with stable default block parts and-constrained renderer seams. In addition to the existing element overrides and-prose-only inline plugins, a caller may opt a document into dollar-delimited math-by supplying one typed renderer for both inline and display expressions. The-parser exposes the same syntax only through an explicit option. Existing parsing,-rendering, styling, and streaming behavior remain unchanged when math is absent.+constrained renderer seams. Callers may opt into the canonical plugin protocol for+bounded source syntax, immutable document transformation, and typed extension+rendering. They may separately opt into dollar-delimited math by supplying one typed+renderer for both inline and display expressions. The parser accepts matching+explicit options. Existing parsing, rendering, styling, and streaming behavior+remain unchanged when plugins and math are absent.## Compatibility and migration- Released default preserved: `yes`- Compatibility class: additive, opt-in public API; existing parser nodes, DOM,- styling, targets, and dollar-delimited text remain unchanged unless the caller- supplies `components.math` or passes `{math: true}` to a parser.+ styling, targets, dollar-delimited text, `components`, and `inlinePlugins` remain+ unchanged unless the caller supplies `plugins`, supplies `components.math`, or+ passes the matching explicit parser option.- Controlled/uncontrolled behavior: not applicable- Migration decision: none@@ -69,6 +76,13 @@ Consumer migration instructions belong in consumer docs and release notes.delimiter boundaries, escape behavior, parser nodes, and streaming parity.- Passing each recognized expression as inert text to the caller's one mathrenderer with an `inline` or `block` display value.+- Applying the canonical `plugins` protocol in the fixed syntax → immutable+ transform → render order while preserving built-in lexical shields, Core-owned+ semantics, and local readable fallback.+- Validating and freezing replacement document roots before later transforms or+ rendering observe them.+- Sharing plugin-enabled parse configuration, transformed heading projection, and+ collision-safe heading IDs with Markdown-derived Outline utilities.**Does not own / non-goals**@@ -78,11 +92,34 @@ Consumer migration instructions belong in consumer docs and release notes.additional default block anatomy.- Nested anatomy or targets owned by CodeBlock, Blockquote, List, CheckboxList,or Table.-- Executing or sanitizing a renderer's math library output, raw HTML parsing,- arbitrary AST plugins, or new list/table/inline-style override slots.+- Executing or sanitizing a renderer's math or plugin output, raw HTML parsing,+ mutable or unrestricted AST plugins, package discovery, or new+ list/table/inline-style override slots.## Public concepts+`plugins` is one optional ordered list of opaque entries created by+`createMarkdownPlugin()`. A plugin declares only the `syntax`, `transform`, and+`renderers` capabilities it uses. Syntax-bearing entries supply stable parse+identity. Parsing, transforms, rendering, and Outline use one stable, strictly typed,+MDAST-aligned canonical tree; `MarkdownAstNodeMap` and `visitMarkdownNodes` provide+node-kind narrowing. Released parser functions preserve their existing result shape+through a compatibility projection. Transforms return validated replacement roots+without entering parse identity. Every extension node introduced+by syntax or transformation has complete renderer ownership and a deterministic+text projection. Text matching, semantic fences, and source decoration are helpers+that compile to transforms rather than separate protocol phases. `spec:AST-036`+owns the shared protocol and limited Remark compatibility profile; this component+owns aggregate application and fallback.++### Acceptance and implementation state++The plugin clauses below are the accepted target contract for the AST-036 rollout,+not a claim that the APIs already ship. Until every clause's implementation and+verification land, the currently released no-plugin, parser, `components`, and+`inlinePlugins` behavior remains the only available contract. Each implementation PR+must identify the clauses it completes without weakening the zero-breaking baseline.+`MarkdownComponents.math` is one optional renderer with the signature`({value: string, display: 'inline' | 'block'}) => ReactNode`. Supplying it optsthe component into math parsing because the caller owns both whether dollar@@ -97,19 +134,30 @@ unions. Enabled calls return the explicit `InlineNodeWithMath` and## Behavioral and layout contract-| ID | Invariant |-| ---- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |-| FR1 | Block and inline displays render one Document root carrying the current `markdown` target. Inline display renders no block anatomy. |-| FR2 | On the default block render path, Heading, Paragraph, List, Code block, Blockquote, Table, Divider, and Image carry the eight current local block targets documented below. |-| FR3 | A supplied `heading`, `paragraph`, `code`, `blockquote`, `hr`, or safe-URL `image` renderer replaces the corresponding default part, so Markdown does not impose that part's local target on the replacement. |-| FR4 | The released Code block target remains `markdown-codeblock`; this compatibility anomaly is not renamed or aliased. |-| FR5 | Density and Heading level remain reflected capabilities on their owning targets. Display mode, streaming state, and renderer selection do not become separate anatomy entries. |-| FR6 | Without `components.math`, Markdown does not recognize math syntax. Default, legacy-set, `math: false`, and `ParseOptions`-annotated parser calls retain the released `InlineNode` / `BlockNode` result unions; only `MathParseOptions` returns the explicit math-enabled unions. |-| FR7 | With math enabled, `$…$` produces an inline `math` node and `$$…$$` produces a block `math` node. The renderer receives the delimiter-free source as `value` and its placement as `display`. |-| FR8 | Inline math stays on one line, cannot have whitespace touching either delimiter, and cannot open immediately after a digit or close immediately before one. `$$` is reserved for display math. These boundaries keep paired currency amounts literal. |-| FR9 | A backslash-escaped dollar is literal outside math and does not close math inside it. An unmatched inline or display delimiter remains literal in non-streaming output. |-| FR10 | Code spans and fenced code blocks are opaque to math parsing. Link destinations are opaque; link labels may contain inline math. Inline plugins run only on prose text and never inside math. |-| FR11 | Streaming converges to the same nodes as a full parse at every chunk boundary, including display math nested in ordinary lists, task lists, blockquotes, and their supported combinations, with LF or CRLF and with or without source ranges. Incomplete math is withheld only while its exact owning container remains open; a list/quote exit or quote-depth change restores literal parsing. Math-enabled incremental calls require `IncrementalParseState<true>`, so the cache and returned union share one contract. |+| ID | Invariant |+| ---- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| FR1 | Block and inline displays render one Document root carrying the current `markdown` target. Inline display renders no block anatomy. |+| FR2 | On the default block render path, Heading, Paragraph, List, Code block, Blockquote, Table, Divider, and Image carry the eight current local block targets documented below. |+| FR3 | A supplied `heading`, `paragraph`, `code`, `blockquote`, `hr`, or safe-URL `image` renderer replaces the corresponding default part, so Markdown does not impose that part's local target on the replacement. |+| FR4 | The released Code block target remains `markdown-codeblock`; this compatibility anomaly is not renamed or aliased. |+| FR5 | Density and Heading level remain reflected capabilities on their owning targets. Display mode, streaming state, and renderer selection do not become separate anatomy entries. |+| FR6 | Without `components.math`, Markdown does not recognize math syntax. Default, legacy-set, `math: false`, and `ParseOptions`-annotated parser calls retain the released `InlineNode` / `BlockNode` result unions; only `MathParseOptions` returns the explicit math-enabled unions. |+| FR7 | With math enabled, `$…$` produces an inline `math` node and `$$…$$` produces a block `math` node. The renderer receives the delimiter-free source as `value` and its placement as `display`. |+| FR8 | Inline math stays on one line, cannot have whitespace touching either delimiter, and cannot open immediately after a digit or close immediately before one. `$$` is reserved for display math. These boundaries keep paired currency amounts literal. |+| FR9 | A backslash-escaped dollar is literal outside math and does not close math inside it. An unmatched inline or display delimiter remains literal in non-streaming output. |+| FR10 | Code spans and fenced code blocks are opaque to math parsing. Link destinations are opaque; link labels may contain inline math. Inline plugins run only on prose text and never inside math. |+| FR11 | Streaming converges to the same nodes as a full parse at every chunk boundary, including display math nested in ordinary lists, task lists, blockquotes, and their supported combinations, with LF or CRLF and with or without source ranges. Incomplete math is withheld only while its exact owning container remains open; a list/quote exit or quote-depth change restores literal parsing. Math-enabled incremental calls require `IncrementalParseState<true>`, so the cache and returned union share one contract. |+| FR12 | Omitting `plugins` and passing an empty list are one semantic empty pipeline with identical parser unions, AST, DOM, styling, targets, IDs, and streaming behavior. Core may skip empty preparation and allocation without creating a separate behavior model. `components`, `inlinePlugins`, citations, autolinking, sources, and math retain their released meaning. |+| FR13 | Plugin-enabled parsing follows built-in lexical shields and ordered syntax claims, then uses one stable, strictly typed, MDAST-aligned canonical tree for transforms, rendering, and Outline. `MarkdownAstNodeMap` and `visitMarkdownNodes` narrow callbacks by node kind. Released parser functions preserve their existing result shape through a compatibility projection. Every returned root is finite, acyclic, representable, validated, and frozen before later plugins or rendering observe it. |+| FR14 | Plugin failures preserve the last valid document and readable authored source. Core retains heading, navigation, image, list, table, and document semantics and exposes no raw-markup parser channel, registry, package discovery, mutable shared AST, or unrestricted DOM hook. URL-like plugin data remains untrusted; Astryx-owned sinks follow `family:navigation-destinations`. |+| FR15 | Incremental parse identity contains every parse-affecting Markdown option and only ordered syntax-bearing plugin name, protocol version, and `parseKey`. Transform or renderer changes reuse settled parse output, rerun transformation, and do not remount unaffected extension output. |+| FR16 | Plugin-enabled Markdown and Markdown-derived Outline use the same parse options, ordered transforms, extension text projection, slugger, and collision allocator so every visible heading, Outline label, heading ID, and target agree. A limited Remark adapter may run only synchronous transform plugins whose input and output round-trip through the documented supported MDAST subset. |+| FR17 | An extension node declares `content` as `'none'`, `'phrasing'`, `'flow'`, or an explicit `{allow, min?, max?}` allowlist that narrows the category its `display` implies. Markdown parses every container's inner source span under the same grammar and shields, validates children at each transform boundary, renders children through the same built-in renderers and `components` seams, counts nesting toward the built-in depth bound, leaves FR16 heading traversal unchanged, and renders children in place when a container renderer fails. |+| FR18 | A transform may read and remove another plugin's extension nodes, including a subtree containing them, and may insert or remove headings; it may not create, edit, internally reorder, or duplicate another plugin's nodes, change a source heading's depth, or forge or duplicate heading identity. `dependsOn` is validated at preparation; an unmet or misordered dependency skips only that plugin's transform. Every rejection names the rule and owning plugin. |+| FR19 | `onPluginDiagnostic` is available on the component and parser options and receives one source-free event — plugin, phase, stable code, severity — per failure, advisory, or silent degradation, in development and production, rate-limited with a suppression code. Admission, duplicate-name, and protocol-version failures behave identically through the component and every parser entrypoint: the call succeeds with the last valid configuration and never throws into the caller. |+| FR20 | `parseMarkdownAst()` and `parseInlineAst()` return the canonical tree and accept the same options and plugin list as the component; `@astryxdesign/core/Markdown/parser` exposes parsing, canonical AST types, and plugin admission with no client boundary. `createMarkdownPlugin()` infers the extension-node union, so no callsite needs explicit type arguments, and a declaration that yields no usable extension type is a type error rather than a silent `never`. |+| FR21 | A transform runs again for every streamed update and must be idempotent and convergent; transforms whose effect requires complete input use the final-input signal. Semantically equal plugin lists reuse prepared work whether or not the array reference is stable, and development reports one diagnostic when a recreated list prevents reuse. |+| FR22 | An extension renderer may opt into the Markdown-owned extension theme target so themes reach plugin output. Opting out leaves output untargeted. The target adds no default styling or anatomy beyond the block spacing and content width Core already applies. |### Allowed variation@@ -125,21 +173,27 @@ unions. Enabled calls return the explicit `InlineNodeWithMath` and- **AV5 — Math renderer.** The caller may use any renderer that accepts the rawexpression and display value. Its DOM, styles, typesetting engine, error UI,and accessibility representation are outside Markdown's ownership.+- **AV6 — Installed plugins.** A host may supply any ordered set of compatible+ opaque plugin entries. Syntax, immutable transform behavior, renderer-owned+ output, and helper implementation may vary while validation, readable fallback,+ Core semantics, and heading identity stay fixed.### Representative states-| State | Required invariant | Allowed variation |-| ---------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------- |-| Default block content | Every parsed block uses its corresponding current Markdown target. | Block count, order, density, content width, and alignment. |-| Custom block renderers | The replaced Heading, Paragraph, Code block, Blockquote, Divider, or Image lacks the corresponding Markdown target. | Replacement structure and styling. |-| Ordered/unordered list | List carries `markdown-list`. | Marker kind, start value, item count, and nested content. |-| Task list | The outer List part carries `markdown-list`. | Checked values and item content. |-| Safe block image | Default Image carries `markdown-image`, or a custom image renderer replaces it. | Source and alternative text. |-| Unsafe block image URL | Markdown renders its fallback Image part with `markdown-image`; no custom image renderer receives the rejected URL. | Alternative text shown by the fallback. |-| Inline display | Document carries `markdown`; no block target renders. | Inline text, links, code, citations, plugins, and opt-in inline math. |-| Math renderer absent | Dollar-delimited source follows the released Markdown grammar and no `math` node or renderer output exists. | Currency, unmatched delimiters, and ordinary prose. |-| Math renderer present | Complete supported delimiters are opaque to Markdown formatting and are passed to the renderer as inert text. | Inline or block display and any renderer-owned output. |-| Streaming math | Incomplete math is withheld; once complete, the streamed nodes equal the full-parse nodes at top level and inside list/blockquote containers. | Delimiters and expression text may arrive in separate chunks; source ranges remain optional. |+| State | Required invariant | Allowed variation |+| ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- |+| Default block content | Every parsed block uses its corresponding current Markdown target. | Block count, order, density, content width, and alignment. |+| Custom block renderers | The replaced Heading, Paragraph, Code block, Blockquote, Divider, or Image lacks the corresponding Markdown target. | Replacement structure and styling. |+| Ordered/unordered list | List carries `markdown-list`. | Marker kind, start value, item count, and nested content. |+| Task list | The outer List part carries `markdown-list`. | Checked values and item content. |+| Safe block image | Default Image carries `markdown-image`, or a custom image renderer replaces it. | Source and alternative text. |+| Unsafe block image URL | Markdown renders its fallback Image part with `markdown-image`; no custom image renderer receives the rejected URL. | Alternative text shown by the fallback. |+| Inline display | Document carries `markdown`; no block target renders. | Inline text, links, code, citations, plugins, and opt-in inline math. |+| Math renderer absent | Dollar-delimited source follows the released Markdown grammar and no `math` node or renderer output exists. | Currency, unmatched delimiters, and ordinary prose. |+| Math renderer present | Complete supported delimiters are opaque to Markdown formatting and are passed to the renderer as inert text. | Inline or block display and any renderer-owned output. |+| Streaming math | Incomplete math is withheld; once complete, the streamed nodes equal the full-parse nodes at top level and inside list/blockquote containers. | Delimiters and expression text may arrive in separate chunks; source ranges remain optional. |+| Plugins omitted | Released parser unions, AST, DOM, targets, heading IDs, and performance remain unchanged. | Omitted or empty list; both are one empty transform pipeline. |+| Plugins enabled | Fixed syntax → immutable transform → render order, validated roots, readable fallback, and matching Markdown/Outline heading identity remain invariant. | Syntax, transforms, renderers, helper execution plans, plugin order, and live post-parse state. |### Transformation and precedence order@@ -151,6 +205,12 @@ unions. Enabled calls return the explicit `InlineNodeWithMath` anddisplay value. Markdown never turns it into HTML or executes it.- Existing URL sanitization remains in force for links and images; math adds nonavigation or raw-HTML sink.+- Built-in syntax and protected contexts claim first; extension syntax claims only+ eligible source; ordered transforms then receive deeply readonly document roots;+ Core validates each returned root before rendering.+- Text matching, semantic fences, and source decorations use transform helpers. Core+ may compile those helpers into indexed internal plans without exposing additional+ public phases.### Performance and resources@@ -162,6 +222,8 @@ unions. Enabled calls return the explicit `InlineNodeWithMath` andcontainer depth so an indented closer cannot become a new opener and a depthtransition cannot swallow literal content. The factory-created state carriesthe same legacy or math-enabled node contract as the parser call.+- Stable and semantically equal plugin lists reuse prepared syntax and transform plans. Only syntax enters parse identity; transform and renderer changes reuse parsed output. Zero-work and representative transforms remain within `spec:AST-036` FR21–FR23 budgets, including the plugin-authored and streaming paths.+- Remark compatibility adapters, the conformance kit, and optional renderers stay outside Core bundles unless explicitly imported.## Accessibility contract@@ -170,7 +232,10 @@ scrollable Table wrapper, and image alternative text remain unchanged. Math hasno Astryx-owned default output: the caller's renderer owns an accessiblerepresentation appropriate to its typesetting engine (for example MathML or alabelled `role="math"` element). Markdown adds no wrapper, ARIA attributes, or-HTML injection around renderer output.+HTML injection around renderer output. Plugin renderers likewise own their+complete documented semantic pattern, while Core preserves its own document,+heading, navigation, image, list, and table semantics. Transforms cannot erase+required accessible meaning or make meaning color-only.## Design relationships@@ -234,18 +299,27 @@ and this change preserves the existing spelling exactly.- `spec:AST-005/DEC-2` keeps embedded-resource policy separate. Markdown mayreject a broader set of image/resource URLs without narrowing the sharednavigation contract.+- `spec:AST-036` owns the opaque syntax/transform/renderer protocol, immutable AST+ validation, limited Remark compatibility, performance, and resource boundaries.+ This record owns aggregate Markdown behavior in FR12–FR22;+ `module:Outline/parseOutlineFromMarkdown` owns the corresponding Outline+ projection.- Nested Astryx primitives retain ownership of their own anatomy and targets;Markdown owns the outer block targets listed here.## Verification map-| Contract | Verification | Representative states | Failure signal |-| ---------------------- | -------------------------------------------------------------------------- | --------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------- |-| FR1–FR5 | `Markdown.test.tsx`, theme-target tests, and `scripts/check-knowledge.mjs` | Default block/inline output and all current targets | Existing DOM, target, spacing, or renderer behavior changes. |-| FR6–FR10 | `parser.test.ts` and `Markdown.test.tsx` | Opt-out, inline/display math, escapes, currency, code, links, plugins | A delimiter is claimed without opt-in, TeX is formatted as Markdown, or opaque contexts leak. |-| FR11 | `incremental.test.ts` and `Markdown.test.tsx` | Every-character top-level/list/task-list/blockquote splits, CRLF, source ranges | Streaming diverges from a full parse, shows partial syntax, mistakes a nested closer for an opener, or crosses a closed container. |-| Public syntax/types | `Markdown.public.test.ts`, core typecheck, and `Markdown.doc.mjs` | Legacy exhaustive switches, component renderer, full and incremental math opt-ins | A legacy union widens, math-enabled results omit math nodes, or docs drift from declarations. |-| Security/accessibility | `parser.test.ts`, `Markdown.test.tsx`, and renderer guidance | Inert expression strings and renderer-owned semantics | Astryx executes math as HTML or silently claims renderer-owned accessibility. |+| Contract | Verification | Representative states | Failure signal |+| ---------------------- | -------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- |+| FR1–FR5 | `Markdown.test.tsx`, theme-target tests, and `scripts/check-knowledge.mjs` | Default block/inline output and all current targets | Existing DOM, target, spacing, or renderer behavior changes. |+| FR6–FR10 | `parser.test.ts` and `Markdown.test.tsx` | Opt-out, inline/display math, escapes, currency, code, links, plugins | A delimiter is claimed without opt-in, TeX is formatted as Markdown, or opaque contexts leak. |+| FR11 | `incremental.test.ts` and `Markdown.test.tsx` | Every-character top-level/list/task-list/blockquote splits, CRLF, source ranges | Streaming diverges from a full parse, shows partial syntax, mistakes a nested closer for an opener, or crosses a closed container. |+| FR12–FR16 | plugin, transform, adapter, performance, and Outline parser tests | omitted/empty lists, immutable transforms, invalid outputs, live updates, one compatible Remark plugin, duplicate headings | Empty behavior forks, input mutates, invalid structure escapes, transforms reparse, adapter loses content, budgets fail, or heading targets diverge. |+| FR17–FR18 | container parse/validation, ownership, and dependency tests | leaf/container declarations, nested containers, foreign read/remove/mint/edit, unmet/misordered dependencies | Plugin-built parsed children, invalid content, lost fallback children, foreign mint/edit, or generic ownership codes. |+| FR19 | diagnostic-channel tests in development and production | every phase, advisory reports, rate suppression, no handler, malformed list, duplicate Core, version skew | A silent production failure, document content in a diagnostic, or one entrypoint throwing where another recovers. |+| FR20–FR22 | canonical/server imports, inference, streaming, preparation, theming tests | server imports, no explicit type args, chunk boundaries, recreated lists, themed/unthemed extensions | Client references, explicit-type workarounds, oscillation, per-render re-preparation, or unreachable opted-in output. |+| Public syntax/types | `Markdown.public.test.ts`, core typecheck, and `Markdown.doc.mjs` | Legacy exhaustive switches, math opt-ins, inferred extension-node unions | A released union widens, an enabled union loses nodes, or docs drift from declarations. |+| Security/accessibility | `parser.test.ts`, `Markdown.test.tsx`, and renderer guidance | Inert expression strings and renderer-owned semantics | Astryx executes math as HTML or silently claims renderer-owned accessibility. |Focused tests continue to pin all nine current target names and default blockplacement. Math intentionally adds no target and no default anatomy.@@ -274,6 +348,37 @@ Rejected: a generic AST/plugin escape hatch, raw HTML rendering, new list/tableslots without consumer evidence, or a separate boolean on the component thatcould enable math without a renderer.+### DEC-2 — Immutable transformation is the canonical Markdown extension seam++**Reference:** `component:Markdown/DEC-2`+**Decider:** `cixzhang`, `2026-09-15`++Markdown accepts one ordered `plugins` list whose opaque entries are created by+`createMarkdownPlugin()`. The public protocol exposes only bounded `syntax`,+immutable `transform`, and typed `renderers`. Core owns deep-readonly input,+validation and freezing of replacement roots, readable fallback, syntax-only parse+identity, preparation reuse, shared heading identity, containers, diagnostics, canonical/server parsing, and theming in FR12–FR22. Existing+`components`, `inlinePlugins`, math, citations, autolinking, and parser calls remain+compatible.++Text matching, semantic fences, and source decoration are transform helpers rather+than separate protocol phases. A tree-shakeable adapter may run only synchronous+transform-only Remark plugins over the documented MDAST subset; unsupported behavior+fails closed rather than being approximated.++This projects `spec:AST-036/DEC-1` through `DEC-4` into the component owner. It rejects a registry, package discovery, mutable shared AST, raw markup, a second plugin prop, or an unrestricted Unified runtime.++### DEC-3 — Containers, diagnostics, and canonical APIs are Markdown-owned++**Reference:** `component:Markdown/DEC-3`+**Decider:** `cixzhang`, `2026-09-16`++Markdown parses every extension container's inner span itself and validates children against the plugin's declared content shape, so a callout holds real Markdown while heading identity, protected contexts, navigation policy, and Outline scope stay Core-owned. Containers change what a document can express, not which headings have identity: the released top-level traversal shared by heading IDs and Outline is untouched. A failed container renderer shows its children rather than literal source. Ownership rejections name the rule and owner; removal of another plugin's nodes is permitted and only minting, editing, internal reordering, duplication, and identity forgery are not.++Markdown also owns the protocol's observability and entry surface: `onPluginDiagnostic` makes every failure visible in production without carrying document content, admission failures degrade instead of throwing at any entrypoint, canonical parse entrypoints and a server-safe parser entry exist beside the released projection, extension types are inferred, and extension output may opt into one theme target without becoming default anatomy.++This projects `spec:AST-036/DEC-5` through `DEC-11` into the component owner in FR17–FR22. It rejects leaf-only extensions, plugin-authored parsed children, independent document shells, development-only or free-text diagnostics, parsers reachable only through a client barrel, required hand-written extension aliases, and default anatomy for plugin output.+## Open questions- **OQ1 — Which focused tests should pin target absence for the five remainingdiff --git a/packages/core/src/Outline/Outline.spec.md b/packages/core/src/Outline/Outline.spec.mdindex 5c62542738..2626487ccd 100644--- a/packages/core/src/Outline/Outline.spec.md+++ b/packages/core/src/Outline/Outline.spec.md@@ -12,7 +12,7 @@ owners: [cixzhang]review_triggers: [theming]verified_by:[packages/core/src/Outline/Outline.test.tsx, scripts/check-knowledge.mjs]-modules: []+modules: [module:Outline/parseOutlineFromMarkdown]families: []design_specs: []architecture: [architecture:component-theming-surface]diff --git a/packages/core/src/Outline/modules/parseOutlineFromMarkdown.spec.md b/packages/core/src/Outline/modules/parseOutlineFromMarkdown.spec.mdnew file mode 100644index 0000000000..dd6ca4fd7a--- /dev/null+++ b/packages/core/src/Outline/modules/parseOutlineFromMarkdown.spec.md@@ -0,0 +1,142 @@+---+schema_version: 3+template_version: 1+kind: module+id: module:Outline/parseOutlineFromMarkdown+authority: current+archive_reason: null+superseded_by: null+approved_by: cixzhang+approved_at: 2026-09-15+owners: [cixzhang]+review_triggers: [public-api, behavior]+verified_by: [packages/core/src/Outline/parseOutlineFromMarkdown.test.ts]+parent_component: component:Outline+references:+ [architecture:public-component-api, component:Markdown, spec:AST-036]+---++# parseOutlineFromMarkdown module contract++## Intent++`parseOutlineFromMarkdown` and `useOutlineFromMarkdown` derive same-document+heading navigation from the same Markdown parse configuration, ordered immutable+transforms, text projection, and collision allocator used by the rendered document.+This focused module owns that utility behavior without deciding the draft Outline+component's anatomy or theming.++## Compatibility and migration++- Released default preserved: `yes`+- Compatibility class: additive parser options; calls without plugins preserve+ released labels, levels, IDs, and return types+- Migration decision: `spec:AST-036`++## Ownership boundary++**Owns**++- Deriving ordered `OutlineItem` values from Markdown headings.+- Accepting the same parser-affecting options and ordered plugin list as Markdown.+- Applying the same validated immutable transforms before selecting headings.+- Using the same extension text projection and collision-safe slug allocation as+ Markdown heading rendering.++**Does not own / non-goals**++- Outline component structure, active state, targets, layout, or theming.+- Plugin rendering, block-extension navigation entries, or renderer-derived text.+- A second parser, plugin registry, or independent heading-ID policy.++## Public API and concepts++`parseOutlineFromMarkdown(source, options?)` performs direct derivation.+`useOutlineFromMarkdown(source, options?)` memoizes the same derivation for React+callers. `options.plugins` uses the canonical opaque Markdown plugin entries. The+same ordered transforms run before heading selection; inline extension-node `toText`+projections then contribute to heading labels and IDs.++## Behavioral contract++| ID | Invariant | Basis | Acceptance and implementation state |+| --- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------- | ----------------------------------- |+| FR1 | Both utilities accept the same Markdown parser options and ordered plugin list as the rendered Markdown document. | `spec:AST-036` FR13, FR16 | pending implementation |+| FR2 | Both utilities apply the same validated immutable transforms before selecting headings, without allowing renderer output to affect identity. | `spec:AST-036` FR13, FR16 | pending implementation |+| FR3 | Plugin-enabled labels and IDs use the same extension `toText` projection, slugger, and cross-base collision allocator as Markdown, producing unique matching targets. | `spec:AST-036` FR16 | pending implementation |+| FR4 | An extension node never creates an Outline entry of its own, and extension containers do not change heading traversal: entries come from the same blocks Markdown assigns heading IDs to, so a heading nested in a container is omitted exactly as one nested in a blockquote or list item is. A container never restarts, extends, or re-scopes heading identity or slug allocation. | `spec:AST-036` FR16, FR25 | pending implementation |+| FR5 | Omitting plugins and passing an empty list preserve released heading selection, labels, levels, IDs, return type, and memoization behavior. | `spec:AST-036` FR2 | pending implementation |+| FR6 | The hook memoizes against source and every parse-affecting or transform-affecting option so changed configuration cannot return stale headings. | `component:Markdown` FR15–FR16 | pending implementation |+| FR7 | A transform that removes a heading removes its Outline entry, and a transform that inserts a synthetic heading adds one, in both surfaces identically. Source-backed heading depth cannot change, so an entry's level always matches the rendered heading. | `spec:AST-036` FR26 | pending implementation |+| FR8 | When a plugin fails, derivation uses the same last valid root the rendered document uses, so labels, levels, and IDs still agree. Failures are reported through the shared diagnostic channel; this module adds no failure mode, fallback, or throw of its own. | `spec:AST-036` FR12, FR29 | pending implementation |+| FR9 | Derivation runs on the canonical tree through the shared parse path and requires no DOM, renderer, client boundary, or second parser. Because transforms are idempotent under streaming, an outline derived from a growing source prefix converges rather than oscillates. | `spec:AST-036` FR32, FR33, FR36 | pending implementation |++### Transformation and precedence order++Markdown parse configuration → ordered immutable transforms → heading nodes →+shared perceivable-text projection → shared slug normalization → document-order+collision allocation → Outline items.++### Performance and resources++- The hook recomputes only when source or parser/transform configuration changes.+- Renderer output does not enter heading identity.+- No DOM, renderer mount, registry, Remark runtime, or optional plugin resource is+ required.++## Accessibility contract++Each derived label is the same perceivable heading text used for Markdown identity,+and each derived ID targets the matching rendered heading. This module adds no+interaction or ARIA behavior; the Outline component owns navigation presentation.++## Design relationships++No visual representation is owned by this parser utility.++## Parent and system relationships++- `component:Markdown` owns aggregate parsing, heading rendering, and the shared+ projection/collision rules.+- `spec:AST-036` owns the canonical plugin protocol and cross-surface parity.+- Draft `component:Outline` owns presentation only after its separate anatomy and+ theming decisions become current.++## Verification map++| Contract | Verification | Representative states | Mutation or failure expectation |+| -------- | ----------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------- |+| FR1–FR6 | Outline parser tests, plugin transform parity tests, and Core typecheck | transformed, formatted, and extension headings; headings nested in extension containers, blockquotes, and list items; duplicate and cross-base slugs; omitted/empty plugins | A transform is skipped, a label/ID diverges from Markdown, a container changes which headings have identity, or default output changes. |+| FR7–FR9 | Heading insert/remove parity, failure parity, and streaming derivation | headings removed with/without sections; inserted synthetic headings; failing transform; growing source prefix; server derivation | Outline/document disagreement, divergent fallback, a throw, stale IDs, or streamed oscillation. |++## Decision log++### DEC-1 — Markdown owns heading identity; Outline projects it++**Reference:** `module:Outline/parseOutlineFromMarkdown/DEC-1`+**Decider:** cixzhang, 2026-09-15++Outline utilities consume Markdown's parse configuration, ordered transforms, text+projection, and collision allocator rather than defining a second heading-identity+system. This keeps labels and link targets aligned without coupling plugin renderer+output to navigation identity.++### DEC-2 — One traversal survives containers and heading edits++**Reference:** `module:Outline/parseOutlineFromMarkdown/DEC-2`+**Decider:** cixzhang, 2026-09-16++Extension containers hold ordinary Markdown but do not change which headings have identity. Markdown assigns IDs by one traversal and this module reads the same one, so Outline never links to a heading Markdown did not identify. A heading inside a container remains omitted like one inside a blockquote or list item, and the extension node is never an Outline entry. Widening traversal is a separate decision.++Transforms may remove and insert headings, so Outline follows the rendered document rather than source: a dropped heading disappears, an inserted heading appears, and immutable source-backed depth keeps levels aligned. Both surfaces run the same pipeline rather than independent rules.++Rejected: a container-only traversal exception; extension nodes as Outline entries; source-only derivation; module-local plugin failure fallback.++## Open questions++None.++## Content boundary++This file does not duplicate plugin protocol details, Markdown parser mechanics,+consumer examples, or the draft Outline component's anatomy and theming contract.