@kabmo-labs/kabmo 0.17.0 → 0.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (269) hide show
  1. package/dist/client/index.html +1 -1
  2. package/dist/client/index.js +538 -457
  3. package/dist/client/static/js/index-hp75vsv9.css +1 -0
  4. package/dist/client/static/js/{index-rerjq5th.js → index-tc09dtca.js} +823 -814
  5. package/package.json +1 -1
  6. package/src/client/components/common/MarkdownRenderer.tsx +136 -89
  7. package/src/client/components/common/anchored-menu/index.test.tsx +141 -0
  8. package/src/client/components/common/anchored-menu/index.tsx +143 -0
  9. package/src/client/components/common/markdown-review/ReviewPopover.tsx +144 -0
  10. package/src/client/components/common/markdown-review/ReviewSummary.tsx +108 -0
  11. package/src/client/components/common/markdown-review/index.tsx +129 -0
  12. package/src/client/components/common/server-control/Panel.tsx +33 -23
  13. package/src/client/components/common/server-control/index.test.tsx +11 -5
  14. package/src/client/components/common/server-control/index.tsx +10 -8
  15. package/src/client/components/layout/session-sidebar/CategoryHeader.tsx +42 -21
  16. package/src/client/components/layout/session-sidebar/CategoryHeader.worktree.test.tsx +36 -17
  17. package/src/client/components/layout/session-sidebar/CategoryItem.tsx +8 -7
  18. package/src/client/components/layout/session-sidebar/about-modal/NotesDialog.tsx +94 -0
  19. package/src/client/components/layout/session-sidebar/about-modal/VersionLine.test.tsx +68 -0
  20. package/src/client/components/layout/session-sidebar/about-modal/VersionLine.tsx +36 -0
  21. package/src/client/components/layout/session-sidebar/about-modal/index.tsx +57 -34
  22. package/src/client/components/layout/session-sidebar/modern/WorkspaceHeader.tsx +28 -10
  23. package/src/client/components/layout/session-sidebar/modern/WorkspaceSection.tsx +7 -6
  24. package/src/client/components/layout/session-sidebar/modern/workspace-header.test.tsx +1 -1
  25. package/src/client/components/layout/update-popup/ReleaseNotes.tsx +8 -3
  26. package/src/client/components/layout/update-popup/index.tsx +5 -1
  27. package/src/client/components/mobile/mobile-right-sidebar/FullEditor.tsx +13 -15
  28. package/src/client/components/mobile/mobile-right-sidebar/Header.tsx +23 -1
  29. package/src/client/components/mobile/mobile-right-sidebar/MissingFileBanner.tsx +30 -0
  30. package/src/client/components/mobile/mobile-right-sidebar/PreviewScroller.tsx +18 -2
  31. package/src/client/components/mobile/mobile-session-sidebar/Item.tsx +22 -67
  32. package/src/client/components/mobile/mobile-session-sidebar/ItemMenu.tsx +110 -0
  33. package/src/client/components/settings/SettingsSidebarList.tsx +20 -0
  34. package/src/client/components/settings/categories/AgentSettings.tsx +23 -50
  35. package/src/client/components/settings/categories/CommandSettings.tsx +2 -2
  36. package/src/client/components/settings/categories/McpSettings.tsx +4 -21
  37. package/src/client/components/settings/categories/OmpSettings.tsx +147 -194
  38. package/src/client/components/settings/categories/SkillSettings.tsx +2 -2
  39. package/src/client/components/settings/categories/TokenUsageSettings.tsx +211 -229
  40. package/src/client/components/settings/categories/agent-settings/DetailPane.tsx +229 -237
  41. package/src/client/components/settings/categories/agent-settings/ModelPicker.tsx +71 -0
  42. package/src/client/components/settings/categories/agent-settings/SidebarList.tsx +9 -2
  43. package/src/client/components/settings/categories/agent-settings/levels.ts +38 -0
  44. package/src/client/components/settings/categories/behavior-settings/Editor.tsx +27 -7
  45. package/src/client/components/settings/categories/chat-settings/ToolRenderSection.tsx +23 -5
  46. package/src/client/components/settings/categories/command-settings/DetailPane.tsx +75 -33
  47. package/src/client/components/settings/categories/command-settings/SidebarList.tsx +7 -0
  48. package/src/client/components/settings/categories/mcp-settings/DetailPane.tsx +91 -76
  49. package/src/client/components/settings/categories/mcp-settings/EnvVarsSection.tsx +83 -0
  50. package/src/client/components/settings/categories/mcp-settings/ImportModal.tsx +26 -13
  51. package/src/client/components/settings/categories/mcp-settings/SidebarList.tsx +20 -0
  52. package/src/client/components/settings/categories/omp-settings/ConfigTabs.tsx +97 -36
  53. package/src/client/components/settings/categories/omp-settings/EngineHeader.tsx +151 -0
  54. package/src/client/components/settings/categories/omp-settings/ExtensionsPanel.tsx +68 -32
  55. package/src/client/components/settings/categories/omp-settings/OrderedChips.tsx +119 -0
  56. package/src/client/components/settings/categories/omp-settings/PresetBar.tsx +14 -7
  57. package/src/client/components/settings/categories/omp-settings/RoleEditor.tsx +15 -6
  58. package/src/client/components/settings/categories/omp-settings/RowEditor.tsx +165 -226
  59. package/src/client/components/settings/categories/omp-settings/types.ts +28 -0
  60. package/src/client/components/settings/categories/skill-settings/DetailHeader.tsx +35 -7
  61. package/src/client/components/settings/categories/skill-settings/DetailPane.tsx +34 -14
  62. package/src/client/components/settings/categories/skill-settings/SidebarList.tsx +21 -0
  63. package/src/client/components/settings/categories/skill-settings/pane.test.tsx +15 -6
  64. package/src/client/components/settings/categories/token-usage-settings/Breakdown.tsx +242 -102
  65. package/src/client/components/settings/categories/token-usage-settings/Chart.tsx +130 -56
  66. package/src/client/components/settings/categories/token-usage-settings/Controls.tsx +135 -0
  67. package/src/client/components/settings/categories/token-usage-settings/MetricsGrid.tsx +55 -33
  68. package/src/client/components/settings/categories/token-usage-settings/Provenance.tsx +59 -0
  69. package/src/client/components/settings/categories/token-usage-settings/panel.test.tsx +239 -0
  70. package/src/client/components/workspace/browser-panel/Screencast.test.ts +1 -0
  71. package/src/client/components/workspace/browser-panel/Screencast.tsx +17 -22
  72. package/src/client/components/workspace/browser-panel/TabStrip.test.tsx +158 -0
  73. package/src/client/components/workspace/browser-panel/TabStrip.tsx +90 -0
  74. package/src/client/components/workspace/browser-panel/index.tsx +50 -4
  75. package/src/client/components/workspace/browser-toolbar/index.tsx +41 -1
  76. package/src/client/components/workspace/chat-timeline/ThinkingSection.tsx +3 -1
  77. package/src/client/components/workspace/chat-timeline/ToolCallingSection.tsx +2 -0
  78. package/src/client/components/workspace/chat-timeline/block-chrome.test.tsx +13 -2
  79. package/src/client/components/workspace/chat-timeline/tool-renderers/panels/Bash.test.ts +88 -0
  80. package/src/client/components/workspace/chat-timeline/tool-renderers/panels/Bash.tsx +24 -1
  81. package/src/client/components/workspace/chat-timeline/tool-renderers/panels/Read.test.ts +34 -0
  82. package/src/client/components/workspace/chat-timeline/tool-renderers/panels/Read.tsx +5 -1
  83. package/src/client/components/workspace/chat-timeline/tool-renderers/shared/ArtifactChip.tsx +7 -6
  84. package/src/client/components/workspace/chat-timeline/tool-renderers/styles/Tui.test.tsx +237 -0
  85. package/src/client/components/workspace/chat-timeline/tool-renderers/styles/Tui.tsx +191 -0
  86. package/src/client/components/workspace/chat-timeline/tool-renderers/styles/styles.test.tsx +1 -1
  87. package/src/client/components/workspace/diff-panel/MergeDiffView.tsx +21 -7
  88. package/src/client/components/workspace/diff-panel/changes.test.ts +51 -0
  89. package/src/client/components/workspace/diff-panel/changes.ts +28 -12
  90. package/src/client/components/workspace/diff-panel/merge.test.ts +28 -0
  91. package/src/client/components/workspace/diff-panel/merge.ts +21 -1
  92. package/src/client/components/workspace/editor/Body.tsx +7 -0
  93. package/src/client/components/workspace/editor/FileDocument.tsx +15 -21
  94. package/src/client/components/workspace/editor/FilePane.tsx +12 -0
  95. package/src/client/components/workspace/editor/PreviewPane.tsx +70 -0
  96. package/src/client/components/workspace/editor/Toolbar.tsx +17 -1
  97. package/src/client/components/workspace/editor/index.tsx +25 -22
  98. package/src/client/components/workspace/editor/toolbar-clusters.test.ts +14 -0
  99. package/src/client/components/workspace/editor/toolbar-clusters.tsx +12 -86
  100. package/src/client/components/workspace/editor/toolbar-toggle.tsx +53 -0
  101. package/src/client/components/workspace/editor/toolbar-write-clusters.tsx +112 -0
  102. package/src/client/components/workspace/git-panel/commit-modal.test.ts +5 -3
  103. package/src/client/components/workspace/user-browser-panel/AddressBar.tsx +5 -0
  104. package/src/client/components/workspace/user-browser-panel/AnnotateBar.test.tsx +201 -0
  105. package/src/client/components/workspace/user-browser-panel/AnnotateBar.tsx +112 -0
  106. package/src/client/components/workspace/user-browser-panel/AnnotateLayer.test.tsx +225 -0
  107. package/src/client/components/workspace/user-browser-panel/AnnotateLayer.tsx +217 -0
  108. package/src/client/components/workspace/user-browser-panel/AnnotateTarget.tsx +99 -0
  109. package/src/client/components/workspace/user-browser-panel/Frame.tsx +30 -1
  110. package/src/client/components/workspace/user-browser-panel/index.tsx +81 -2
  111. package/src/client/data/agent-data/builtin.ts +0 -10
  112. package/src/client/data/agent-data/orchestrator.ts +0 -45
  113. package/src/client/data/agent-data/specialist.ts +0 -100
  114. package/src/client/data/mock/token-usage.ts +170 -120
  115. package/src/client/data/settings/omp-schema.json +33 -1
  116. package/src/client/hooks/browser/use-annotate.test.ts +143 -0
  117. package/src/client/hooks/browser/use-annotate.ts +98 -0
  118. package/src/client/hooks/browser/use-close-tab.test.ts +148 -0
  119. package/src/client/hooks/browser/use-close-tab.ts +67 -0
  120. package/src/client/hooks/browser/use-screencast.ts +13 -1
  121. package/src/client/hooks/chat/composer/browser-context.test.ts +117 -0
  122. package/src/client/hooks/chat/composer/browser-context.ts +40 -16
  123. package/src/client/hooks/chat/composer/items.test.ts +1 -1
  124. package/src/client/hooks/chat/composer/review-context.ts +38 -0
  125. package/src/client/hooks/chat/composer/use-draft.test.ts +132 -0
  126. package/src/client/hooks/chat/composer/use-draft.ts +31 -2
  127. package/src/client/hooks/chat/timeline/row-window.test.ts +15 -2
  128. package/src/client/hooks/editor/use-document-annotations.ts +124 -0
  129. package/src/client/hooks/editor/use-editor-panel-ui.ts +52 -0
  130. package/src/client/hooks/editor/use-file-review-mode.ts +35 -0
  131. package/src/client/hooks/editor/use-preview-review.ts +148 -0
  132. package/src/client/hooks/settings/agents.ts +149 -0
  133. package/src/client/hooks/settings/crud-list.test.ts +28 -6
  134. package/src/client/hooks/settings/crud-list.ts +96 -57
  135. package/src/client/hooks/settings/omp-config.ts +164 -0
  136. package/src/client/hooks/settings/useTokenUsage.ts +125 -0
  137. package/src/client/hooks/settings/write-feedback.test.ts +104 -0
  138. package/src/client/hooks/settings/write-feedback.ts +63 -0
  139. package/src/client/hooks/ui/markdown-hydration.ts +125 -0
  140. package/src/client/hooks/ui/updates/index.test.ts +100 -1
  141. package/src/client/hooks/ui/updates/index.ts +50 -0
  142. package/src/client/hooks/ui/updates/notes.test.ts +138 -0
  143. package/src/client/hooks/ui/updates/notes.ts +57 -0
  144. package/src/client/lib/browser/element-at.test.ts +229 -0
  145. package/src/client/lib/browser/element-at.ts +139 -0
  146. package/src/client/lib/review/client.ts +73 -0
  147. package/src/client/lib/router/search-params.ts +42 -20
  148. package/src/client/tailwind.css +65 -0
  149. package/src/server/lib/btw/lifecycle.server.ts +2 -2
  150. package/src/server/lib/db/schema.ts +7 -0
  151. package/src/server/lib/db/seed-terminal.test.ts +4 -0
  152. package/src/server/lib/omp/config/agent-definitions.test.ts +273 -0
  153. package/src/server/lib/omp/config/agents.ts +231 -61
  154. package/src/server/lib/omp/config/definitions.test.ts +9 -105
  155. package/src/server/lib/omp/config/extensions.ts +16 -7
  156. package/src/server/lib/omp/config/omp-config-files.test.ts +27 -0
  157. package/src/server/lib/omp/rpc/constants.test.ts +11 -0
  158. package/src/server/lib/omp/rpc/constants.ts +15 -0
  159. package/src/server/lib/omp/rpc/process.ts +11 -14
  160. package/src/server/lib/omp/rpc/session-commands.ts +6 -3
  161. package/src/server/lib/omp/rpc/utility-agent-dir.test.ts +134 -0
  162. package/src/server/lib/omp/rpc/utility-agent-dir.ts +138 -0
  163. package/src/server/lib/omp/rpc/utility.ts +12 -0
  164. package/src/server/lib/review/schema.server.ts +45 -0
  165. package/src/server/lib/review/store.server.ts +138 -0
  166. package/src/server/lib/terminal/attach-replay.test.ts +132 -0
  167. package/src/server/lib/terminal/output.test.ts +166 -0
  168. package/src/server/lib/terminal/output.ts +104 -0
  169. package/src/server/lib/terminal/runtime.server.ts +5 -0
  170. package/src/server/lib/terminal/send-result.test.ts +33 -0
  171. package/src/server/lib/terminal/send-result.ts +32 -0
  172. package/src/server/lib/terminal/session.server.ts +45 -11
  173. package/src/server/lib/terminal/store-liveness.test.ts +4 -0
  174. package/src/server/lib/updates/active-notes.test.ts +149 -0
  175. package/src/server/lib/updates/active-notes.ts +75 -0
  176. package/src/server/lib/updates/changelog-file.ts +42 -11
  177. package/src/server/lib/updates/changelog.test.ts +15 -1
  178. package/src/server/lib/updates/omp.ts +42 -15
  179. package/src/server/lib/updates/release-url.ts +27 -1
  180. package/src/server/lib/usage/index-parse.test.ts +200 -0
  181. package/src/server/lib/usage/index-parse.ts +178 -0
  182. package/src/server/lib/usage/index-query.server.ts +248 -0
  183. package/src/server/lib/usage/index-scan.server.ts +343 -0
  184. package/src/server/lib/usage/index-schema.server.ts +82 -0
  185. package/src/server/lib/usage/index.test.ts +234 -0
  186. package/src/server/lib/usage/providers.server.ts +4 -53
  187. package/src/server/routes/browser/index.ts +3 -0
  188. package/src/server/routes/browser/stream.ts +31 -2
  189. package/src/server/routes/browser/tabs.test.ts +94 -0
  190. package/src/server/routes/browser/tabs.ts +85 -0
  191. package/src/server/routes/index.ts +2 -0
  192. package/src/server/routes/review/bindings.ts +11 -0
  193. package/src/server/routes/review/index.ts +127 -0
  194. package/src/server/routes/review/routes.test.ts +191 -0
  195. package/src/server/routes/settings/agents.test.ts +180 -0
  196. package/src/server/routes/settings/agents.ts +95 -102
  197. package/src/server/routes/settings/mcp.test.ts +135 -0
  198. package/src/server/routes/settings/mcp.ts +14 -6
  199. package/src/server/routes/settings/settings-store-routes.test.ts +6 -113
  200. package/src/server/routes/telemetry/tokens.test.ts +145 -0
  201. package/src/server/routes/telemetry/tokens.ts +70 -149
  202. package/src/server/routes/terminal/ws.ts +6 -5
  203. package/src/server/routes/updates/index.ts +2 -0
  204. package/src/server/routes/updates/notes.ts +34 -0
  205. package/src/server/routes/updates/routes.test.ts +49 -0
  206. package/src/shared/lib/browser/annotate.test.ts +283 -0
  207. package/src/shared/lib/browser/annotate.ts +231 -0
  208. package/src/shared/lib/browser/browser-viewer.test.ts +26 -4
  209. package/src/shared/lib/browser/frame-gate.test.ts +91 -0
  210. package/src/shared/lib/browser/frame-gate.ts +69 -0
  211. package/src/shared/lib/browser/frame-params.test.ts +43 -0
  212. package/src/shared/lib/browser/frame-params.ts +60 -0
  213. package/src/shared/lib/browser/frame-pipeline.test.ts +132 -0
  214. package/src/shared/lib/browser/frame-pipeline.ts +80 -0
  215. package/src/shared/lib/browser/page-context.ts +60 -4
  216. package/src/shared/lib/browser/snapshot.test.ts +115 -0
  217. package/src/shared/lib/browser/snapshot.ts +112 -0
  218. package/src/shared/lib/browser/tab-close.test.ts +74 -0
  219. package/src/shared/lib/browser/tab-close.ts +77 -0
  220. package/src/shared/lib/browser/viewer.ts +45 -26
  221. package/src/shared/lib/chat/timeline/block-chrome.ts +19 -0
  222. package/src/shared/lib/chat/timeline/tool-render-mode.ts +17 -4
  223. package/src/shared/lib/chat/tool/artifact.ts +55 -20
  224. package/src/shared/lib/chat/tool/bash-facts.ts +96 -0
  225. package/src/shared/lib/chat/tool/minimized.test.ts +98 -0
  226. package/src/shared/lib/chat/tool/minimized.ts +64 -0
  227. package/src/shared/lib/chat/tool/summary.test.ts +28 -8
  228. package/src/shared/lib/chat/tool/summary.ts +3 -32
  229. package/src/shared/lib/markdown/blocks/anchor.ts +63 -0
  230. package/src/shared/lib/markdown/blocks/blocks.test.ts +141 -0
  231. package/src/shared/lib/markdown/blocks/renderer.ts +120 -0
  232. package/src/shared/lib/markdown/blocks/scan.ts +100 -0
  233. package/src/shared/lib/markdown/blocks/types.ts +62 -0
  234. package/src/shared/lib/markdown/marked.ts +58 -147
  235. package/src/shared/lib/markdown/math-extensions.ts +168 -0
  236. package/src/shared/lib/markdown/review/prompt.ts +77 -0
  237. package/src/shared/lib/markdown/review/reconcile.ts +55 -0
  238. package/src/shared/lib/markdown/review/review.test.ts +96 -0
  239. package/src/shared/lib/markdown/xml-sections.test.ts +140 -0
  240. package/src/shared/lib/markdown/xml-sections.ts +139 -0
  241. package/src/shared/lib/models/provider/label.ts +57 -0
  242. package/src/shared/lib/omp/config/agent-file.test.ts +54 -0
  243. package/src/shared/lib/omp/config/agent-file.ts +43 -0
  244. package/src/shared/lib/omp/config/row-value.test.ts +95 -0
  245. package/src/shared/lib/omp/config/row-value.ts +97 -0
  246. package/src/shared/lib/omp/config/schema.test.ts +31 -0
  247. package/src/shared/lib/omp/config/schema.ts +6 -0
  248. package/src/shared/lib/omp/rpc/frame.test.ts +48 -47
  249. package/src/shared/lib/omp/rpc/frame.ts +49 -40
  250. package/src/shared/lib/ui/menu-anchor.test.ts +69 -0
  251. package/src/shared/lib/ui/menu-anchor.ts +89 -0
  252. package/src/shared/lib/usage/breakdown.test.ts +197 -0
  253. package/src/shared/lib/usage/breakdown.ts +241 -0
  254. package/src/shared/lib/usage/range.test.ts +204 -0
  255. package/src/shared/lib/usage/range.ts +240 -0
  256. package/src/shared/lib/usage/view.test.ts +85 -0
  257. package/src/shared/lib/usage/view.ts +74 -0
  258. package/src/shared/types/browser.ts +78 -0
  259. package/src/shared/types/index.ts +1 -0
  260. package/src/shared/types/settings/agent.ts +28 -6
  261. package/src/shared/types/settings/state.ts +4 -3
  262. package/src/shared/types/settings/write.ts +6 -0
  263. package/src/shared/types/tokenUsage.ts +128 -21
  264. package/src/shared/types/updates.ts +20 -0
  265. package/dist/client/static/js/index-3ve31rzx.css +0 -1
  266. package/src/server/lib/omp/session/usage/aggregate-shaping.test.ts +0 -149
  267. package/src/server/lib/omp/session/usage/aggregate.test.ts +0 -243
  268. package/src/server/lib/omp/session/usage/aggregate.ts +0 -330
  269. package/src/server/lib/omp/session/usage/shaping.ts +0 -130
@@ -0,0 +1,168 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+
6
+ /**
7
+ * The four math extensions, split out of `marked.ts` for the per-file ceiling —
8
+ * and because they are the one part of the pipeline with rules that do not fit
9
+ * in a renderer override: each is a tokenizer plus a renderer, registered
10
+ * through `marked.use({ extensions })`.
11
+ *
12
+ * ## The placeholder is never the formula
13
+ *
14
+ * KaTeX is ~522 kB of JS worth fetching only when a message contains math, so
15
+ * this module emits a span carrying the source and the display flag; `katex.ts`
16
+ * swaps it for real markup once the library lands.
17
+ *
18
+ * ## The prose-escape flag is shared state, and that is deliberate
19
+ *
20
+ * `renderMarkdown` escapes HTML in prose before marked sees it, so a tokenizer
21
+ * captures `x &lt; y` rather than `x < y` — and KaTeX would report a syntax
22
+ * error for a perfectly good formula. The flag is set for the duration of one
23
+ * synchronous `parse`, which is why `setProseEscaped` exists instead of a
24
+ * parameter threaded through four renderers. `marked.parse` never awaits, so no
25
+ * nested render can observe it mid-parse.
26
+ */
27
+
28
+ import type { TokenizerAndRendererExtension } from 'marked';
29
+
30
+ import { MATH_PENDING_CLASS } from '@/shared/lib/markdown/katex';
31
+
32
+ /**
33
+ * True while `renderMarkdown` parses prose it escaped itself, read by the math
34
+ * renderers below.
35
+ */
36
+ let proseEscaped = false;
37
+
38
+ /** Set for the duration of one parse; always paired with `false`. */
39
+ export function setProseEscaped(value: boolean): void {
40
+ proseEscaped = value;
41
+ }
42
+
43
+ interface TokenLike {
44
+ type: string;
45
+ text?: string;
46
+ raw?: string;
47
+ }
48
+
49
+ /**
50
+ * Emit a math placeholder instead of rendering KaTeX inline.
51
+ *
52
+ * Two things happen to the captured source, and both exist because this is the
53
+ * one place all four math extensions funnel through:
54
+ *
55
+ * 1. **Entities are reversed** when the prose was escaped. Only the three
56
+ * entities that escaper emits are reversed, and only when it ran — a document
57
+ * (`allowHtml`) whose own text legitimately holds `&amp;` is left alone.
58
+ * 2. **The result is percent-encoded**, the way a mermaid block carries its
59
+ * source. HTML-escaping the payload instead re-escapes what step 1 just
60
+ * restored, and the attribute round-trip hides the extra layer from both
61
+ * ends. An encoded payload holds no HTML-special character, so nothing
62
+ * between here and injection can alter it.
63
+ */
64
+ export function renderMathPlaceholder(tex: string, displayMode: boolean): string {
65
+ const restored = proseEscaped
66
+ ? tex.replace(/&(amp|lt|gt);/g, (_, name: string) => (name === 'amp' ? '&' : name === 'lt' ? '<' : '>'))
67
+ : tex;
68
+ const display = displayMode ? ' data-math-display="1"' : '';
69
+ const span = `<span class="${MATH_PENDING_CLASS}" data-math="${encodeURIComponent(restored)}"${display}></span>`;
70
+ // Block math must stay inside a block element: DOMPurify drops a bare
71
+ // `<span>` that sits at the top level of the fragment, which silently deleted
72
+ // every `$$…$$` formula. KaTeX's own output is inline-level too, so the old
73
+ // synchronous renderer relied on the same wrapper being present.
74
+ return displayMode ? `<p>${span}</p>` : span;
75
+ }
76
+
77
+ /** The four extensions, in the order `marked.ts` registers them. */
78
+ export function mathExtensions(): TokenizerAndRendererExtension[] {
79
+ return [
80
+ // \( ... \) inline math
81
+ {
82
+ name: 'inlineMath',
83
+ level: 'inline',
84
+ start(src: string) {
85
+ return src.match(/\\\(/)?.index;
86
+ },
87
+ tokenizer(src: string) {
88
+ const match = /^\\\(([\s\S]+?)\\\)/.exec(src);
89
+ return match
90
+ ? { type: 'inlineMath', raw: match[0], text: match[1] }
91
+ : undefined;
92
+ },
93
+ renderer(token: TokenLike) {
94
+ return renderMathPlaceholder(token.text ?? '', false);
95
+ },
96
+ },
97
+ // \[ ... \] block math
98
+ {
99
+ name: 'blockMath',
100
+ level: 'block',
101
+ start(src: string) {
102
+ return src.match(/^\\\[/)?.index;
103
+ },
104
+ tokenizer(src: string) {
105
+ const match = /^\\\[([\s\S]+?)\\\]/.exec(src);
106
+ return match
107
+ ? { type: 'blockMath', raw: match[0], text: match[1] }
108
+ : undefined;
109
+ },
110
+ renderer(token: TokenLike) {
111
+ return renderMathPlaceholder(token.text ?? '', true);
112
+ },
113
+ },
114
+ // $$ ... $$ display math (block-level, must be its own line)
115
+ {
116
+ name: 'blockMathDisplay',
117
+ level: 'block',
118
+ start(src: string) {
119
+ return src.match(/^\$\$/)?.index;
120
+ },
121
+ tokenizer(src: string) {
122
+ const match = /^\$\$([\s\S]+?)\$\$(?:\n|$)/.exec(src);
123
+ return match
124
+ ? { type: 'blockMathDisplay', raw: match[0], text: match[1] }
125
+ : undefined;
126
+ },
127
+ renderer(token: TokenLike) {
128
+ return renderMathPlaceholder(token.text ?? '', true);
129
+ },
130
+ },
131
+ // $ ... $ inline math. The flanking rules are the whole defence: a single
132
+ // `$` is the one delimiter that collides with ordinary text, and this
133
+ // pipeline renders shell output, currency, SQL and awk programs all day.
134
+ //
135
+ // opening $ — not preceded by a word char (checked in `start`, the only
136
+ // place the preceding character is visible), and not
137
+ // followed by a digit, `$` or `{`. The digit guard is what
138
+ // makes `$5`, `$1` and `$10` text; `{` keeps `${HOME}` out.
139
+ // closing $ — not preceded by whitespace, and not followed by a WORD
140
+ // char or `$`. That trailing guard is load-bearing twice
141
+ // over: it rejects `PATH=$PATH:$HOME` (closer followed by
142
+ // `H`) and `a$b$c` (followed by `c`), and it is the reason
143
+ // the rule no longer depends on where `start` happened to
144
+ // land — the tokenizer is anchored at `^` and cannot see
145
+ // the preceding character, so `a$b$c` was math while
146
+ // `ax$b$c` was text on the identical rule.
147
+ //
148
+ // `$n$ = 3` and `$x^2$ benar` still parse: a space after the closer is not
149
+ // a word char.
150
+ {
151
+ name: 'inlineMathDollar',
152
+ level: 'inline',
153
+ start(src: string) {
154
+ const match = /(^|[^\w$])\$(?!\$)(?!\s)/.exec(src);
155
+ return match ? match.index + (match[1]?.length ?? 0) : undefined;
156
+ },
157
+ tokenizer(src: string) {
158
+ const match = /^\$(?![\d${])((?:\\\$|[^$])*?)(?<!\s)\$(?![\w$])/.exec(src);
159
+ return match
160
+ ? { type: 'inlineMathDollar', raw: match[0], text: match[1] }
161
+ : undefined;
162
+ },
163
+ renderer(token: TokenLike) {
164
+ return renderMathPlaceholder(token.text ?? '', false);
165
+ },
166
+ },
167
+ ];
168
+ }
@@ -0,0 +1,77 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+
6
+ /**
7
+ * A document review as the text the agent receives.
8
+ *
9
+ * The same shape the browser panel's page context uses: the judgements become
10
+ * PROMPT TEXT in the composer draft, never a second store the agent has to be
11
+ * taught to read. Each line names the block by its line range and quotes it, so
12
+ * the agent can find the paragraph without counting, and each mark says which
13
+ * answer was chosen in words (`good`, `needs work`) rather than a glyph alone.
14
+ *
15
+ * The closing instruction is load-bearing: without it, a list of verdicts reads
16
+ * as a description of the document instead of a decision about it — and a
17
+ * `good` block is exactly the instruction "leave this alone".
18
+ */
19
+
20
+ import type { BlockVerdict, DocumentAnnotation } from '@/shared/lib/markdown/blocks/types';
21
+
22
+ /** One `scope\0repo` pair as the prompt spells it: a path a reader can act on. */
23
+ export interface ReviewPromptDocument {
24
+ /** The document's path, relative to the workspace (or nested repo). */
25
+ path: string;
26
+ annotations: readonly Pick<DocumentAnnotation, 'lineStart' | 'lineEnd' | 'verdict' | 'note' | 'quote'>[];
27
+ }
28
+
29
+ const VERDICT_LABEL: Record<BlockVerdict, string> = {
30
+ good: 'good — leave it as it is',
31
+ 'needs-work': 'needs work',
32
+ };
33
+
34
+ function rangeOf(annotation: ReviewPromptDocument['annotations'][number]): string {
35
+ return annotation.lineStart === annotation.lineEnd
36
+ ? `L${annotation.lineStart}`
37
+ : `L${annotation.lineStart}-${annotation.lineEnd}`;
38
+ }
39
+
40
+ /**
41
+ * The block this review adds to the draft; empty when nothing was judged.
42
+ *
43
+ * An empty review produces NO text rather than a header claiming zero marks: the
44
+ * button that sends it is disabled in that state, and a stray header would be
45
+ * something the user has to delete before typing.
46
+ */
47
+ export function formatReviewBlock(document: ReviewPromptDocument): string {
48
+ const marks = document.annotations.filter((annotation) => annotation.verdict === 'good' || annotation.verdict === 'needs-work');
49
+ if (marks.length === 0) return '';
50
+ const lines = marks.map((annotation) => {
51
+ const quote = annotation.quote ? ` «${annotation.quote}»` : '';
52
+ const note = annotation.note.trim();
53
+ return `- ${rangeOf(annotation)}${quote} — ${VERDICT_LABEL[annotation.verdict]}${note ? `: ${note}` : ''}`;
54
+ });
55
+ return [
56
+ `[Review dokumen] ${document.path}`,
57
+ ...lines,
58
+ 'Ini keputusan user atas blok-blok di atas: blok bertanda "needs work" perlu diperbaiki sesuai catatannya, blok bertanda "good" jangan diubah.',
59
+ ].join('\n');
60
+ }
61
+
62
+ /** A blank draft gets the block alone; otherwise one blank line separates them. */
63
+ export function appendReviewBlock(previous: string, block: string): string {
64
+ if (!block) return previous;
65
+ if (!previous) return block;
66
+ const separator = previous.endsWith('\n\n') ? '' : previous.endsWith('\n') ? '\n' : '\n\n';
67
+ return `${previous}${separator}${block}`;
68
+ }
69
+
70
+ /** DOM event a document review dispatches to append its block to the draft. */
71
+ export const REVIEW_INCLUDE_EVENT = 'omp:review-include';
72
+
73
+ /** Hand a finished review to the composer, whichever tree is listening. */
74
+ export function emitReviewBlock(block: string): void {
75
+ if (typeof window === 'undefined' || !block) return;
76
+ window.dispatchEvent(new CustomEvent<string>(REVIEW_INCLUDE_EVENT, { detail: block }));
77
+ }
@@ -0,0 +1,55 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+
6
+ /**
7
+ * Which stored marks still describe a block on screen, and which do not.
8
+ *
9
+ * A mark names its block by content (`type:hash#n`), so editing a block detaches
10
+ * its mark: the stored quote no longer matches anything rendered. That is a
11
+ * real state the reader must SEE — the note is still what they wrote, and the
12
+ * only copy of it — so it is reported as `outdated` with its quote intact and a
13
+ * way to remove it, never deleted behind their back.
14
+ *
15
+ * A mark that matches nothing because the DOCUMENT was not rendered at all (a
16
+ * refused read, an unsupported kind) is a different fact and is not this
17
+ * module's business: the caller only reconciles against a real block list.
18
+ */
19
+
20
+ import type { DocumentAnnotation, MdBlock } from '@/shared/lib/markdown/blocks/types';
21
+
22
+ export interface ReconcileResult<T extends DocumentAnnotation> {
23
+ /** Marks whose block is on screen, keyed by block key. */
24
+ attached: Map<string, T>;
25
+ /** Marks whose block is no longer rendered, newest first. */
26
+ outdated: T[];
27
+ }
28
+
29
+ /** Attach stored marks to the blocks the render produced. */
30
+ export function reconcileAnnotations<T extends DocumentAnnotation>(
31
+ blocks: readonly MdBlock[],
32
+ annotations: readonly T[],
33
+ ): ReconcileResult<T> {
34
+ const byKey = new Map(blocks.map((block) => [block.key, block]));
35
+ const attached = new Map<string, T>();
36
+ const outdated: T[] = [];
37
+
38
+ for (const annotation of annotations) {
39
+ if (byKey.has(annotation.blockKey)) attached.set(annotation.blockKey, annotation);
40
+ else outdated.push(annotation);
41
+ }
42
+ outdated.sort((left, right) => right.updatedAt - left.updatedAt);
43
+ return { attached, outdated };
44
+ }
45
+
46
+ /** The verdict counts the summary chip prints. */
47
+ export function tallyAnnotations<T extends DocumentAnnotation>(attached: ReadonlyMap<string, T>): { good: number; needsWork: number } {
48
+ let good = 0;
49
+ let needsWork = 0;
50
+ for (const annotation of attached.values()) {
51
+ if (annotation.verdict === 'good') good += 1;
52
+ else needsWork += 1;
53
+ }
54
+ return { good, needsWork };
55
+ }
@@ -0,0 +1,96 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+
6
+ /**
7
+ * Reconciliation and the prompt: what a stored judgement becomes once the
8
+ * document has moved.
9
+ *
10
+ * The behaviours pinned here are the ones a user notices when they are wrong:
11
+ * a mark that follows its block, a mark that says it is outdated instead of
12
+ * disappearing, and composer text that names a block precisely enough for the
13
+ * agent to find it.
14
+ */
15
+
16
+ import { describe, expect, test } from 'bun:test';
17
+
18
+ import { reconcileAnnotations, tallyAnnotations } from '@/shared/lib/markdown/review/reconcile';
19
+ import { appendReviewBlock, formatReviewBlock } from '@/shared/lib/markdown/review/prompt';
20
+ import type { DocumentAnnotation, MdBlock } from '@/shared/lib/markdown/blocks/types';
21
+
22
+ const block = (key: string, quote = key): MdBlock => ({ key, type: 'paragraph', lineStart: 1, lineEnd: 1, quote });
23
+
24
+ const annotation = (overrides: Partial<DocumentAnnotation> & { id: string; blockKey: string }): DocumentAnnotation => ({
25
+ scope: 'root\u0000.',
26
+ path: 'NOTES.md',
27
+ lineStart: 1,
28
+ lineEnd: 1,
29
+ verdict: 'good',
30
+ note: '',
31
+ quote: 'x',
32
+ createdAt: 1,
33
+ updatedAt: 1,
34
+ ...overrides,
35
+ });
36
+
37
+ describe('reconcileAnnotations', () => {
38
+ test('a mark follows its block, and a mark whose block is gone is OUTDATED', () => {
39
+ const blocks = [block('a'), block('b')];
40
+ const result = reconcileAnnotations(blocks, [
41
+ annotation({ id: '1', blockKey: 'b' }),
42
+ annotation({ id: '2', blockKey: 'gone', updatedAt: 5 }),
43
+ ]);
44
+ expect([...result.attached.keys()]).toEqual(['b']);
45
+ expect(result.outdated.map((row) => row.id)).toEqual(['2']);
46
+ // The note is still there: it is the user's only copy.
47
+ expect(result.outdated[0].quote).toBe('x');
48
+ });
49
+
50
+ test('outdated marks are newest first, so the last edit is at the top', () => {
51
+ const result = reconcileAnnotations([], [
52
+ annotation({ id: 'old', blockKey: 'x', updatedAt: 1 }),
53
+ annotation({ id: 'new', blockKey: 'y', updatedAt: 9 }),
54
+ ]);
55
+ expect(result.outdated.map((row) => row.id)).toEqual(['new', 'old']);
56
+ });
57
+
58
+ test('the tally counts what is attached, not what is stored', () => {
59
+ const result = reconcileAnnotations([block('a'), block('b')], [
60
+ annotation({ id: '1', blockKey: 'a', verdict: 'good' }),
61
+ annotation({ id: '2', blockKey: 'b', verdict: 'needs-work' }),
62
+ annotation({ id: '3', blockKey: 'outdated', verdict: 'needs-work' }),
63
+ ]);
64
+ expect(tallyAnnotations(result.attached)).toEqual({ good: 1, needsWork: 1 });
65
+ });
66
+ });
67
+
68
+ describe('formatReviewBlock', () => {
69
+ test('names each block by range and quote, and says what the verdict means', () => {
70
+ const text = formatReviewBlock({
71
+ path: 'docs/NOTES.md',
72
+ annotations: [
73
+ annotation({ id: '1', blockKey: 'a', lineStart: 3, lineEnd: 5, verdict: 'needs-work', note: 'basi', quote: '## Notes' }),
74
+ annotation({ id: '2', blockKey: 'b', lineStart: 9, lineEnd: 9, verdict: 'good', quote: 'Run gates' }),
75
+ ],
76
+ });
77
+ expect(text).toContain('[Review dokumen] docs/NOTES.md');
78
+ expect(text).toContain('- L3-5 «## Notes» — needs work: basi');
79
+ expect(text).toContain('- L9 «Run gates» — good');
80
+ // The instruction is what turns a list of verdicts into a decision.
81
+ expect(text).toContain('jangan diubah');
82
+ });
83
+
84
+ test('an empty review produces no text at all', () => {
85
+ expect(formatReviewBlock({ path: 'a.md', annotations: [] })).toBe('');
86
+ });
87
+
88
+ test('a blank draft takes the block; an existing one is separated by a blank line', () => {
89
+ expect(appendReviewBlock('', 'BLOCK')).toBe('BLOCK');
90
+ expect(appendReviewBlock('draft', 'BLOCK')).toBe('draft\n\nBLOCK');
91
+ // One blank line either way: a single trailing newline still needs a separator.
92
+ expect(appendReviewBlock('draft\n', 'BLOCK')).toBe('draft\n\nBLOCK');
93
+ expect(appendReviewBlock('draft\n\n', 'BLOCK')).toBe('draft\n\nBLOCK');
94
+ expect(appendReviewBlock('draft', '')).toBe('draft');
95
+ });
96
+ });
@@ -0,0 +1,140 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+
6
+ /**
7
+ * XML section wrappers in omp's `xd://` docs (`<instruction>`, `<examples>`,
8
+ * `<critical>`) became headings before the markdown parse. Without that, the
9
+ * prose path escaped the tags — the reader saw `<instruction>` as a literal
10
+ * line and every section ran together as one block.
11
+ *
12
+ * The gates are what the tests pin: a paired, whole-line wrapper is rewritten,
13
+ * and nothing else is (a code fence showing the tags as an example, an
14
+ * attribute-carrying wrapper, an unpaired tag, a tag inside a sentence).
15
+ */
16
+
17
+ import { describe, expect, test } from 'bun:test';
18
+ import { xmlSectionsToHeadings } from '@/shared/lib/markdown/xml-sections';
19
+
20
+ describe('xmlSectionsToHeadings', () => {
21
+ test('paired wrappers become headings and their closing lines disappear', () => {
22
+ const source = [
23
+ 'Intro line.',
24
+ '',
25
+ '<instruction>',
26
+ '- Static content? Use `read`.',
27
+ '</instruction>',
28
+ '',
29
+ '<critical>',
30
+ '- MUST open a tab before direct use.',
31
+ '</critical>',
32
+ ].join('\n');
33
+
34
+ expect(xmlSectionsToHeadings(source)).toBe([
35
+ 'Intro line.',
36
+ '',
37
+ '## Instruction',
38
+ '- Static content? Use `read`.',
39
+ '',
40
+ '',
41
+ '## Critical',
42
+ '- MUST open a tab before direct use.',
43
+ '',
44
+ ].join('\n'));
45
+ });
46
+
47
+ test('nesting steps the heading level down, capped at h6', () => {
48
+ const source = [
49
+ '<outer>',
50
+ '<inner>',
51
+ 'text',
52
+ '</inner>',
53
+ '</outer>',
54
+ '<a>',
55
+ '<b>',
56
+ '<c>',
57
+ '<d>',
58
+ '<e>',
59
+ 'deep',
60
+ '</e>',
61
+ '</d>',
62
+ '</c>',
63
+ '</b>',
64
+ '</a>',
65
+ ].join('\n');
66
+
67
+ expect(xmlSectionsToHeadings(source)).toBe([
68
+ '## Outer',
69
+ '### Inner',
70
+ 'text',
71
+ '',
72
+ '',
73
+ '## A',
74
+ '### B',
75
+ '#### C',
76
+ '##### D',
77
+ '###### E',
78
+ 'deep',
79
+ '',
80
+ '',
81
+ '',
82
+ '',
83
+ '',
84
+ ].join('\n'));
85
+ });
86
+
87
+ test('a crossed pair leaves the unmatched lines literal', () => {
88
+ // Valid = open + matching close, properly nested. `<a>` never gets its own
89
+ // close where the stack expects it, so only the well-formed `<b>` pair is
90
+ // a section.
91
+ const source = ['<a>', 'text', '<b>', 'inner', '</a>', '</b>'].join('\n');
92
+
93
+ expect(xmlSectionsToHeadings(source)).toBe(
94
+ ['<a>', 'text', '## B', 'inner', '</a>', ''].join('\n'),
95
+ );
96
+ });
97
+
98
+ test('a fenced block that shows the wrappers keeps them verbatim', () => {
99
+ const source = [
100
+ '<instruction>',
101
+ 'Outer section.',
102
+ '```xml',
103
+ '<instruction>',
104
+ 'literal',
105
+ '</instruction>',
106
+ '```',
107
+ '</instruction>',
108
+ ].join('\n');
109
+
110
+ expect(xmlSectionsToHeadings(source)).toBe([
111
+ '## Instruction',
112
+ 'Outer section.',
113
+ '```xml',
114
+ '<instruction>',
115
+ 'literal',
116
+ '</instruction>',
117
+ '```',
118
+ '',
119
+ ].join('\n'));
120
+ });
121
+
122
+ test('an unpaired or inline tag is left exactly as written', () => {
123
+ const source = [
124
+ '<summary>',
125
+ 'no closing partner',
126
+ 'use <slug> here',
127
+ '<system-reminder reason="a rule fired">',
128
+ 'wrapped with attributes',
129
+ '</system-reminder>',
130
+ 'closing without an opener: </notes>',
131
+ ].join('\n');
132
+
133
+ expect(xmlSectionsToHeadings(source)).toBe(source);
134
+ });
135
+
136
+ test('a source with no tags is returned untouched', () => {
137
+ const source = '# Title\n\n- a < b';
138
+ expect(xmlSectionsToHeadings(source)).toBe(source);
139
+ });
140
+ });
@@ -0,0 +1,139 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+
6
+ /**
7
+ * XML section wrappers → markdown headings.
8
+ *
9
+ * omp's `xd://` device docs are markdown, but several sections are marked with
10
+ * an XML-ish wrapper instead of a heading: `<instruction>…</instruction>`,
11
+ * `<examples>…</examples>`, `<critical>…</critical>`. The markdown pipeline
12
+ * escapes source HTML (agent output renders markup as data), so the read panel
13
+ * showed `<instruction>` and `</instruction>` as literal lines and the sections
14
+ * ran together as ordinary prose — the wrap did no visual work at all.
15
+ *
16
+ * Converting them before the markdown parse is the only place both halves can
17
+ * be dropped: marked would otherwise treat a bare tag line as an HTML block,
18
+ * and DOMPurify's profile strips it only after the paragraph boundaries are
19
+ * already decided.
20
+ *
21
+ * Deliberately narrow, because the same text path renders real markdown files:
22
+ *
23
+ * - A wrapper must occupy a WHOLE line AND be valid: an opening line closed by
24
+ * the same name, properly nested. `<slug>` inside a sentence, a lone
25
+ * `<summary>`, a stray `</tag>`, and a tag carrying attributes
26
+ * (`<system-reminder reason="…">`, which the output envelope already reads)
27
+ * are left byte-for-byte as they were.
28
+ * - Nothing inside a fenced code block is touched: a doc that shows the tags
29
+ * as an example must keep showing them as text.
30
+ * - Nesting moves the heading level down one, capped at `h6`; the first level
31
+ * is `h2`, since the document's own `#` title is `h1`.
32
+ */
33
+
34
+ /** A wrapper line: `<name>` / `</name>`, nothing else on the line. */
35
+ const OPEN_RE = /^<([A-Za-z][\w-]*)>$/;
36
+ const CLOSE_RE = /^<\/([A-Za-z][\w-]*)>$/;
37
+
38
+ /** One wrapper line, and the pair it forms when a matching close arrives. */
39
+ interface Section {
40
+ name: string;
41
+ openIndex: number;
42
+ /** The wrapper this one sits inside — matched or not; the level check sorts
43
+ * that out once the whole source has been scanned. */
44
+ parent?: Section;
45
+ /** Line index of the closing wrapper, once the pair was matched. */
46
+ closeIndex?: number;
47
+ }
48
+
49
+ /** A fence opener or closer, indented no more than markdown allows. */
50
+ function fenceAt(line: string): { char: string; length: number } | undefined {
51
+ const body = line.trimStart();
52
+ if (line.length - body.length > 3) return undefined;
53
+ const match = /^(`{3,}|~{3,})/.exec(body);
54
+ return match ? { char: match[1][0], length: match[1].length } : undefined;
55
+ }
56
+
57
+ /** `security-scan` → `Security Scan`; an already-capitalized name is kept. */
58
+ function sectionLabel(name: string): string {
59
+ return name
60
+ .split(/[-_]+/)
61
+ .filter(Boolean)
62
+ .map((part) => part.charAt(0).toUpperCase() + part.slice(1))
63
+ .join(' ');
64
+ }
65
+
66
+ /**
67
+ * Rewrite standalone XML wrapper pairs into `##`-level headings, and drop the
68
+ * closing wrapper lines.
69
+ *
70
+ * A wrapper only counts when it is VALID: an opening line and a closing line
71
+ * with the same name, properly nested against every other wrapper around it. A
72
+ * stray `<tag>`, a stray `</tag>`, and a crossed pair (`<a><b></a></b>`) stay
73
+ * literal — they are text about markup, not a section of the document.
74
+ */
75
+ export function xmlSectionsToHeadings(source: string): string {
76
+ if (!source.includes('<')) return source;
77
+
78
+ const lines = source.split('\n');
79
+
80
+ // Which lines sit inside a fenced code block, so the scan below can skip
81
+ // them. A fence is closed by a run of the same character that is at least as
82
+ // long as the one that opened it.
83
+ const inFence: boolean[] = [];
84
+ let fence: { char: string; length: number } | undefined;
85
+ for (const line of lines) {
86
+ const candidate = fenceAt(line);
87
+ if (fence) {
88
+ inFence.push(true);
89
+ if (candidate && candidate.char === fence.char && candidate.length >= fence.length) fence = undefined;
90
+ continue;
91
+ }
92
+ if (candidate) fence = candidate;
93
+ inFence.push(candidate !== undefined);
94
+ }
95
+
96
+ const stack: Section[] = [];
97
+ /** The opening line index of every valid pair, and where its close sits. */
98
+ const headings = new Map<number, Section>();
99
+ const closes = new Set<number>();
100
+
101
+ for (let index = 0; index < lines.length; index += 1) {
102
+ if (inFence[index]) continue;
103
+ const text = lines[index].trim();
104
+
105
+ const closed = CLOSE_RE.exec(text);
106
+ if (closed) {
107
+ // Strict nesting: only the wrapper that is actually open can be closed.
108
+ const opener = stack[stack.length - 1];
109
+ if (!opener || opener.name !== closed[1]) continue;
110
+ stack.pop();
111
+ opener.closeIndex = index;
112
+ headings.set(opener.openIndex, opener);
113
+ closes.add(index);
114
+ continue;
115
+ }
116
+
117
+ const opened = OPEN_RE.exec(text);
118
+ if (opened) stack.push({ name: opened[1], openIndex: index, parent: stack[stack.length - 1] });
119
+ }
120
+
121
+ if (headings.size === 0) return source;
122
+
123
+ /** Heading level from the nesting of VALID ancestors only: an unmatched
124
+ * wrapper stays literal text and therefore contributes no level. */
125
+ const level = (section: Section): number => {
126
+ const parent = section.parent;
127
+ if (!parent || parent.closeIndex === undefined) return 2;
128
+ return Math.min(6, level(parent) + 1);
129
+ };
130
+
131
+ return lines
132
+ .map((line, index) => {
133
+ const section = headings.get(index);
134
+ if (section) return `${'#'.repeat(level(section))} ${sectionLabel(section.name)}`;
135
+ if (closes.has(index)) return '';
136
+ return line;
137
+ })
138
+ .join('\n');
139
+ }