agentic-mermaid 0.1.1 → 0.1.2

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 (336) hide show
  1. package/CHANGELOG.md +144 -4
  2. package/LICENSES/Apache-2.0.txt +202 -0
  3. package/README.md +25 -32
  4. package/THIRD_PARTY_NOTICES.md +29 -0
  5. package/dist/agent-core.d.ts +463 -0
  6. package/dist/agent-core.js +397 -0
  7. package/dist/agent.d.ts +73 -1868
  8. package/dist/agent.js +336 -37325
  9. package/dist/agentic-mermaid-mcp.js +7 -38399
  10. package/dist/am.js +33632 -40445
  11. package/dist/chunk-4QECACIA.js +4702 -0
  12. package/dist/chunk-CDPKJ2BQ.js +37 -0
  13. package/dist/chunk-QKDLMOJJ.js +3487 -0
  14. package/dist/chunk-WI35L7IR.js +615 -0
  15. package/dist/chunk-WN3YDOBG.js +149 -0
  16. package/dist/chunk-ZYMMKQ3I.js +62637 -0
  17. package/dist/index-D54dqSdC.d.ts +6777 -0
  18. package/dist/index.d.ts +1 -1
  19. package/dist/index.js +310 -33014
  20. package/dist/mcp-cli-SBQSTJFC.js +17 -0
  21. package/docs/README.md +14 -6
  22. package/docs/schemas/style-spec.schema.json +1221 -30
  23. package/examples/styles/catalog.json +54 -0
  24. package/examples/styles/cloudflare-workers-inspired-prototype.mmd +9 -0
  25. package/examples/styles/cloudflare-workers-inspired-prototype.style.json +110 -0
  26. package/examples/styles/cupertino-prototype.mmd +10 -0
  27. package/examples/styles/cupertino-prototype.style.json +63 -0
  28. package/examples/styles/mid-century-report.style.json +2 -2
  29. package/examples/styles/star-chart-atlas.style.json +2 -1
  30. package/examples/styles/transit-route-map.style.json +2 -2
  31. package/examples/styles/vercel-inspired-prototype.mmd +6 -0
  32. package/examples/styles/vercel-inspired-prototype.style.json +87 -0
  33. package/package.json +68 -43
  34. package/server.json +2 -2
  35. package/skills/agentic-mermaid-diagram-workflow/SKILL.md +17 -36
  36. package/skills/agentic-mermaid-diagram-workflow/references/cli.md +4 -5
  37. package/skills/agentic-mermaid-diagram-workflow/references/code-mode.md +15 -31
  38. package/skills/agentic-mermaid-diagram-workflow/references/sequence.md +10 -14
  39. package/skills/agentic-mermaid-live-editor/SKILL.md +100 -206
  40. package/AGENT_NATIVE.md +0 -607
  41. package/Instructions_for_agents.md +0 -89
  42. package/TODO.md +0 -684
  43. package/assets/hero.png +0 -0
  44. package/dist/index-wjRjbsP-.d.ts +0 -1102
  45. package/docs/agent-api-cookbook.md +0 -308
  46. package/docs/agent-mutation-policy.md +0 -104
  47. package/docs/agent-workflow-examples.md +0 -46
  48. package/docs/api.md +0 -211
  49. package/docs/ascii.md +0 -103
  50. package/docs/assets/improvements/box-start-connector.png +0 -0
  51. package/docs/assets/improvements/comment-dropped-lint.png +0 -0
  52. package/docs/assets/improvements/er-content-loss.png +0 -0
  53. package/docs/assets/improvements/fan-in-trunks.png +0 -0
  54. package/docs/assets/improvements/gantt-family.png +0 -0
  55. package/docs/assets/improvements/gantt-milestone-clamp.png +0 -0
  56. package/docs/assets/improvements/gantt-verify-seam.png +0 -0
  57. package/docs/assets/improvements/subgraph-container-edges.png +0 -0
  58. package/docs/assets/improvements/wrapper-frontmatter.png +0 -0
  59. package/docs/assets/improvements/wrapper-init-directive.png +0 -0
  60. package/docs/assets/improvements/wrapper-leading-comment.png +0 -0
  61. package/docs/assets/style-cookbook/mid-century-report.png +0 -0
  62. package/docs/assets/style-cookbook/star-chart-atlas.png +0 -0
  63. package/docs/assets/style-cookbook/transit-route-map.png +0 -0
  64. package/docs/comparison.md +0 -94
  65. package/docs/config.md +0 -105
  66. package/docs/contributing/adding-diagram-types.md +0 -144
  67. package/docs/contributing/diagram-family-citizenship.matrix.json +0 -2127
  68. package/docs/contributing/diagram-family-citizenship.md +0 -82
  69. package/docs/contributing/harvesting-upstream-tests.md +0 -126
  70. package/docs/contributing/lessons-learned.md +0 -276
  71. package/docs/contributing/releasing.md +0 -82
  72. package/docs/contributing/visual-review-evidence.md +0 -53
  73. package/docs/custom-style-cookbook.md +0 -154
  74. package/docs/design/families/README.md +0 -26
  75. package/docs/design/families/architecture-beta.md +0 -48
  76. package/docs/design/families/flowchart-parser-conformance.md +0 -22
  77. package/docs/design/families/gantt-research.md +0 -137
  78. package/docs/design/families/gantt.md +0 -329
  79. package/docs/design/families/journey-agentic-cards-before.png +0 -0
  80. package/docs/design/families/journey-experience-curve-implementation.png +0 -0
  81. package/docs/design/families/journey-mermaid-classic-implementation.png +0 -0
  82. package/docs/design/families/journey-mermaid-classic-prototype.png +0 -0
  83. package/docs/design/families/journey-mermaid-classic-prototype.svg +0 -163
  84. package/docs/design/families/journey-mermaid-classic-prototype.svg.png +0 -0
  85. package/docs/design/families/journey-migration-parity.md +0 -439
  86. package/docs/design/families/journey-section-overlap-after.png +0 -0
  87. package/docs/design/families/journey-section-overlap-before.png +0 -0
  88. package/docs/design/families/journey-usage-research.md +0 -423
  89. package/docs/design/families/journey.md +0 -153
  90. package/docs/design/families/xychart.md +0 -85
  91. package/docs/design/system/README.md +0 -45
  92. package/docs/design/system/abstraction-audit.md +0 -224
  93. package/docs/design/system/abstraction-recommendations.md +0 -655
  94. package/docs/design/system/architecture.mmd +0 -29
  95. package/docs/design/system/architecture.svg +0 -137
  96. package/docs/design/system/layout-guarantees-and-robustness.md +0 -351
  97. package/docs/design/system/layout-rubric.md +0 -138
  98. package/docs/design/system/route-contracts.md +0 -848
  99. package/docs/design/system/source-preservation-ladder.md +0 -52
  100. package/docs/design/system/styles-rollout.md +0 -216
  101. package/docs/design/system/ugly-layouts.md +0 -119
  102. package/docs/diagram-families.md +0 -193
  103. package/docs/features.md +0 -147
  104. package/docs/fork-differences.md +0 -130
  105. package/docs/getting-started.md +0 -175
  106. package/docs/issue-derived-test-cases.md +0 -156
  107. package/docs/layout-characterization/README.md +0 -245
  108. package/docs/layout-characterization/contact-sheet-families.md +0 -498
  109. package/docs/layout-characterization/contact-sheet.md +0 -638
  110. package/docs/layout-characterization/properties.md +0 -281
  111. package/docs/layout-characterization/visual-quality.md +0 -160
  112. package/docs/layout-characterization/visual-snapshots/architecture.svg +0 -79
  113. package/docs/layout-characterization/visual-snapshots/class.svg +0 -60
  114. package/docs/layout-characterization/visual-snapshots/er.svg +0 -61
  115. package/docs/layout-characterization/visual-snapshots/flowchart.svg +0 -58
  116. package/docs/layout-characterization/visual-snapshots/gantt.svg +0 -52
  117. package/docs/layout-characterization/visual-snapshots/journey.svg +0 -98
  118. package/docs/layout-characterization/visual-snapshots/pie.svg +0 -36
  119. package/docs/layout-characterization/visual-snapshots/quadrant.svg +0 -47
  120. package/docs/layout-characterization/visual-snapshots/sequence.svg +0 -59
  121. package/docs/layout-characterization/visual-snapshots/state.svg +0 -52
  122. package/docs/layout-characterization/visual-snapshots/timeline.svg +0 -64
  123. package/docs/layout-characterization/visual-snapshots/xychart.svg +0 -97
  124. package/docs/mcp-code-mode-rationale.md +0 -101
  125. package/docs/mcp-http-transport.md +0 -223
  126. package/docs/mermaid-layout-complaints.md +0 -837
  127. package/docs/mutation-testing.md +0 -206
  128. package/docs/project/divergences.md +0 -98
  129. package/docs/project/dogfooding-docs-strategy.md +0 -66
  130. package/docs/project/hosted-mcp-cloudflare-plan.md +0 -338
  131. package/docs/project/lessons-learned.md +0 -1019
  132. package/docs/project/remove-role-styling-plan.md +0 -176
  133. package/docs/quality.md +0 -215
  134. package/docs/react.md +0 -97
  135. package/docs/style-authoring.md +0 -133
  136. package/docs/testing-strategy.md +0 -335
  137. package/docs/theming.md +0 -162
  138. package/examples/agent-improve-auth-flow.ts +0 -206
  139. package/examples/agent-loop.ts +0 -53
  140. package/examples/mcp-vs-cli-complex-diagrams.ts +0 -133
  141. package/llms.txt +0 -104
  142. package/skill-evals/README.md +0 -77
  143. package/skill-evals/fixtures/architecture-cache/input.mmd +0 -5
  144. package/skill-evals/fixtures/class-payment/input.mmd +0 -4
  145. package/skill-evals/fixtures/er-orders/input.mmd +0 -10
  146. package/skill-evals/fixtures/flowchart-cache/input.mmd +0 -3
  147. package/skill-evals/fixtures/gantt-release/input.mmd +0 -7
  148. package/skill-evals/fixtures/journey-checkout/input.mmd +0 -6
  149. package/skill-evals/fixtures/pie-exports/input.mmd +0 -5
  150. package/skill-evals/fixtures/quadrant-priorities/input.mmd +0 -11
  151. package/skill-evals/fixtures/sequence-retry/input.mmd +0 -8
  152. package/skill-evals/fixtures/state-lifecycle/input.mmd +0 -5
  153. package/skill-evals/fixtures/timeline-release/input.mmd +0 -6
  154. package/skill-evals/fixtures/xychart-growth/input.mmd +0 -5
  155. package/skill-evals/shared-benchmark.json +0 -510
  156. package/src/agent/analyze.ts +0 -157
  157. package/src/agent/apply.ts +0 -146
  158. package/src/agent/architecture-body.ts +0 -458
  159. package/src/agent/certificates.ts +0 -110
  160. package/src/agent/class-body.ts +0 -319
  161. package/src/agent/core.ts +0 -207
  162. package/src/agent/create.ts +0 -106
  163. package/src/agent/describe.ts +0 -368
  164. package/src/agent/er-body.ts +0 -224
  165. package/src/agent/facts.ts +0 -360
  166. package/src/agent/families-builtin.ts +0 -920
  167. package/src/agent/families.ts +0 -232
  168. package/src/agent/family-layouts.ts +0 -832
  169. package/src/agent/flowchart-body.ts +0 -372
  170. package/src/agent/flowchart-unsupported.ts +0 -243
  171. package/src/agent/font-coverage.ts +0 -288
  172. package/src/agent/gantt-body.ts +0 -495
  173. package/src/agent/index.ts +0 -10
  174. package/src/agent/journey-body.ts +0 -374
  175. package/src/agent/label-metrics.ts +0 -28
  176. package/src/agent/layout-to-rendered.ts +0 -63
  177. package/src/agent/mutate.ts +0 -97
  178. package/src/agent/mutation-ops.ts +0 -51
  179. package/src/agent/op-schema.ts +0 -443
  180. package/src/agent/parse.ts +0 -223
  181. package/src/agent/pie-body.ts +0 -270
  182. package/src/agent/png.ts +0 -171
  183. package/src/agent/quadrant-body.ts +0 -336
  184. package/src/agent/quality.ts +0 -363
  185. package/src/agent/readability-audit.ts +0 -92
  186. package/src/agent/rendered-route-audit.ts +0 -61
  187. package/src/agent/sequence-body.ts +0 -345
  188. package/src/agent/serialize.ts +0 -214
  189. package/src/agent/state-body.ts +0 -589
  190. package/src/agent/structural-count.ts +0 -150
  191. package/src/agent/timeline-body.ts +0 -280
  192. package/src/agent/trace-log.ts +0 -43
  193. package/src/agent/types.ts +0 -995
  194. package/src/agent/verify.ts +0 -603
  195. package/src/agent/xychart-body.ts +0 -472
  196. package/src/architecture/config.ts +0 -282
  197. package/src/architecture/layout.ts +0 -496
  198. package/src/architecture/parser.ts +0 -375
  199. package/src/architecture/renderer.ts +0 -611
  200. package/src/architecture/types.ts +0 -113
  201. package/src/ascii/ansi.ts +0 -423
  202. package/src/ascii/architecture.ts +0 -210
  203. package/src/ascii/canvas.ts +0 -443
  204. package/src/ascii/class-diagram.ts +0 -697
  205. package/src/ascii/converter.ts +0 -475
  206. package/src/ascii/draw.ts +0 -1693
  207. package/src/ascii/edge-bundling.ts +0 -328
  208. package/src/ascii/edge-routing.ts +0 -330
  209. package/src/ascii/er-diagram.ts +0 -439
  210. package/src/ascii/gantt.ts +0 -276
  211. package/src/ascii/grid.ts +0 -747
  212. package/src/ascii/index.ts +0 -196
  213. package/src/ascii/journey.ts +0 -169
  214. package/src/ascii/meta.ts +0 -244
  215. package/src/ascii/multiline-utils.ts +0 -80
  216. package/src/ascii/pathfinder.ts +0 -301
  217. package/src/ascii/pie.ts +0 -67
  218. package/src/ascii/quadrant.ts +0 -158
  219. package/src/ascii/reverse.ts +0 -216
  220. package/src/ascii/sequence.ts +0 -499
  221. package/src/ascii/shapes/circle.ts +0 -27
  222. package/src/ascii/shapes/corners.ts +0 -143
  223. package/src/ascii/shapes/diamond.ts +0 -27
  224. package/src/ascii/shapes/hexagon.ts +0 -27
  225. package/src/ascii/shapes/index.ts +0 -106
  226. package/src/ascii/shapes/rectangle.ts +0 -168
  227. package/src/ascii/shapes/rounded.ts +0 -27
  228. package/src/ascii/shapes/special.ts +0 -332
  229. package/src/ascii/shapes/stadium.ts +0 -110
  230. package/src/ascii/shapes/state.ts +0 -192
  231. package/src/ascii/shapes/types.ts +0 -73
  232. package/src/ascii/timeline.ts +0 -141
  233. package/src/ascii/types.ts +0 -312
  234. package/src/ascii/validate.ts +0 -120
  235. package/src/ascii/width.ts +0 -81
  236. package/src/ascii/wrap.ts +0 -131
  237. package/src/ascii/xychart.ts +0 -919
  238. package/src/browser.ts +0 -29
  239. package/src/class/layout.ts +0 -240
  240. package/src/class/parser.ts +0 -332
  241. package/src/class/renderer.ts +0 -638
  242. package/src/class/types.ts +0 -129
  243. package/src/cli/agent-instructions.ts +0 -1
  244. package/src/cli/am-bin.ts +0 -6
  245. package/src/cli/exit-codes.ts +0 -18
  246. package/src/cli/index.ts +0 -1132
  247. package/src/cli/init-agent.ts +0 -147
  248. package/src/cli/run-entrypoint.ts +0 -10
  249. package/src/color-resolver.ts +0 -152
  250. package/src/elk-instance.ts +0 -114
  251. package/src/er/layout.ts +0 -187
  252. package/src/er/parser.ts +0 -226
  253. package/src/er/renderer.ts +0 -792
  254. package/src/er/types.ts +0 -99
  255. package/src/family-rubric.ts +0 -425
  256. package/src/font-manifest.ts +0 -31
  257. package/src/gantt/layout.ts +0 -365
  258. package/src/gantt/parser.ts +0 -282
  259. package/src/gantt/pipeline.ts +0 -27
  260. package/src/gantt/renderer.ts +0 -414
  261. package/src/gantt/schedule.ts +0 -513
  262. package/src/gantt/types.ts +0 -255
  263. package/src/index.ts +0 -368
  264. package/src/journey/layout.ts +0 -554
  265. package/src/journey/parse-core.ts +0 -251
  266. package/src/journey/parser.ts +0 -101
  267. package/src/journey/renderer.ts +0 -917
  268. package/src/journey/types.ts +0 -144
  269. package/src/layout/geometry.ts +0 -182
  270. package/src/layout/pass.ts +0 -142
  271. package/src/layout/passes/index.ts +0 -3916
  272. package/src/layout-engine.ts +0 -1565
  273. package/src/layout-rubric.ts +0 -659
  274. package/src/mcp/artifacts.ts +0 -137
  275. package/src/mcp/dynamic-harness.ts +0 -31
  276. package/src/mcp/dynamic-modules.d.ts +0 -7
  277. package/src/mcp/facade.ts +0 -608
  278. package/src/mcp/harness-runtime.ts +0 -203
  279. package/src/mcp/hosted-server.ts +0 -468
  280. package/src/mcp/mcp-bin.ts +0 -3
  281. package/src/mcp/mcp-cli.ts +0 -82
  282. package/src/mcp/protocol.ts +0 -13
  283. package/src/mcp/sandbox.ts +0 -195
  284. package/src/mcp/sdk-decl.ts +0 -391
  285. package/src/mcp/server.ts +0 -362
  286. package/src/mcp/tool-surface.ts +0 -146
  287. package/src/mermaid-source.ts +0 -655
  288. package/src/multiline-utils.ts +0 -228
  289. package/src/parser.ts +0 -1031
  290. package/src/pie/layout.ts +0 -168
  291. package/src/pie/parser.ts +0 -136
  292. package/src/pie/renderer.ts +0 -234
  293. package/src/pie/types.ts +0 -82
  294. package/src/quadrant/layout.ts +0 -191
  295. package/src/quadrant/parser.ts +0 -183
  296. package/src/quadrant/renderer.ts +0 -322
  297. package/src/quadrant/types.ts +0 -113
  298. package/src/render-family-hooks.ts +0 -244
  299. package/src/renderer.ts +0 -1099
  300. package/src/route-contracts.ts +0 -2723
  301. package/src/scene/backend.ts +0 -76
  302. package/src/scene/fidelity.ts +0 -183
  303. package/src/scene/hybrid-backend.ts +0 -174
  304. package/src/scene/ir.ts +0 -181
  305. package/src/scene/marks.ts +0 -127
  306. package/src/scene/rough-backend.ts +0 -378
  307. package/src/scene/seed.ts +0 -46
  308. package/src/scene/style-registry.ts +0 -556
  309. package/src/sequence/layout.ts +0 -456
  310. package/src/sequence/parser.ts +0 -255
  311. package/src/sequence/renderer.ts +0 -604
  312. package/src/sequence/types.ts +0 -154
  313. package/src/shape-clipping.ts +0 -351
  314. package/src/shared/accessibility-directives.ts +0 -22
  315. package/src/shared/batched.ts +0 -61
  316. package/src/shared/color-math.ts +0 -93
  317. package/src/shared/svg-a11y.ts +0 -29
  318. package/src/shared/syntax-error.ts +0 -17
  319. package/src/shared/unicode-ranges.ts +0 -135
  320. package/src/styles.ts +0 -318
  321. package/src/svg-paths.ts +0 -28
  322. package/src/text-metrics.ts +0 -248
  323. package/src/theme.ts +0 -710
  324. package/src/timeline/layout.ts +0 -381
  325. package/src/timeline/parser.ts +0 -215
  326. package/src/timeline/renderer.ts +0 -538
  327. package/src/timeline/types.ts +0 -105
  328. package/src/types.ts +0 -462
  329. package/src/website-worker-modules.d.ts +0 -18
  330. package/src/xychart/axis-utils.ts +0 -109
  331. package/src/xychart/colors.ts +0 -124
  332. package/src/xychart/config.ts +0 -88
  333. package/src/xychart/layout.ts +0 -656
  334. package/src/xychart/parser.ts +0 -504
  335. package/src/xychart/renderer.ts +0 -640
  336. package/src/xychart/types.ts +0 -282
package/src/cli/index.ts DELETED
@@ -1,1132 +0,0 @@
1
- // ============================================================================
2
- // am — agentic-mermaid CLI (v4).
3
- // ============================================================================
4
-
5
- import { readFileSync, existsSync, writeFileSync, mkdtempSync, watch } from 'node:fs'
6
- import { spawnSync } from 'node:child_process'
7
- import { join, resolve } from 'node:path'
8
- import { tmpdir } from 'node:os'
9
- import { parseMermaid } from '../agent/parse.ts'
10
- import { logToolInvocation } from '../agent/trace-log.ts'
11
- import { serializeMermaid, synthesizeFromGraph } from '../agent/serialize.ts'
12
- import { mutateChecked } from '../agent/mutate.ts'
13
- import { verifyMermaid } from '../agent/verify.ts'
14
- import { renderMermaidSVG, renderMermaidASCII, renderMermaidPNG, layoutMermaid } from '../agent/index.ts'
15
- import type { PngFontWarning } from '../agent/png.ts'
16
- import { describeMermaid } from '../agent/describe.ts'
17
- import { collectBatched } from '../shared/batched.ts'
18
- import type {
19
- ValidDiagram, WarningCode, AnyMutationOp,
20
- MutationError, Result, MutableValidDiagram,
21
- } from '../agent/types.ts'
22
- import { WARNING_SEVERITY, WARNING_TIER } from '../agent/types.ts'
23
- import { BUILTIN_FAMILY_METADATA, builtinFamilyMetadata, knownFamilies, getFamily } from '../agent/families.ts'
24
- import { knownStyles, getStyle, validateStyleSpec, inferBackend, resolveStyleStack, styleKind } from '../scene/style-registry.ts'
25
- import type { StyleInput, StyleSpec } from '../scene/style-registry.ts'
26
- import type { BuiltinFamilyId } from '../agent/families.ts'
27
- import '../agent/families-builtin.ts'
28
- import { AGENT_INSTRUCTIONS } from './agent-instructions.ts'
29
- import { initAgentFiles } from './init-agent.ts'
30
- import { EXIT_OK, EXIT_ARG_ERROR, EXIT_VERIFY_FAILED, EXIT_INTERNAL } from './exit-codes.ts'
31
- import type { ParseError } from '../agent/types.ts'
32
-
33
- /**
34
- * Loop 12 M1: build a structured CLI error envelope. Keeps `message` a short
35
- * human string (the first error's message) and carries the full structured
36
- * ParseError[] in `details` — so an agent reads `error.details` instead of
37
- * re-parsing a JSON string buried in `error.message`.
38
- */
39
- function parseErrorEnvelope(errors: ParseError[]): { ok: false; error: { code: string; message: string; details: ParseError[] } } {
40
- const first = errors[0]
41
- const message = first ? `${first.code}: ${first.message}` : 'parse error'
42
- return { ok: false, error: { code: 'PARSE_FAILED', message, details: errors } }
43
- }
44
-
45
- export interface ParsedArgs { command?: string; positional: string[]; flags: Record<string, string | boolean> }
46
-
47
- // Single source of truth for CLI flags. A flag with no `arg` is a boolean;
48
- // `arg` is the usage placeholder shown in `[--flag <arg>]`. BOOLEAN_FLAGS is
49
- // DERIVED from this, so the parser's boolean classification cannot drift from
50
- // the documented usage.
51
- export const FLAG_SPECS: Record<string, { arg?: string }> = {
52
- // booleans
53
- 'agent-instructions': {}, 'ascii': {}, 'certificates': {}, 'help': {}, 'json': {},
54
- 'watch': {}, 'open': {}, 'force': {}, 'canonical-wrapper': {}, 'system-fonts': {},
55
- // value flags (placeholder = what the usage shows after the flag)
56
- 'suppress': { arg: 'CODES' }, 'label-cap': { arg: 'N' }, 'op': { arg: 'JSON' },
57
- 'style': { arg: 'NAMES|file' }, 'seed': { arg: 'N' },
58
- 'ops': { arg: 'JSON|file' }, 'output': { arg: 'FILE' }, 'format': { arg: 'fmt' },
59
- 'security': { arg: 'mode' }, 'dir': { arg: 'DIR' }, 'font-dirs': { arg: 'DIRS' },
60
- }
61
-
62
- export const BOOLEAN_FLAGS = new Set(Object.keys(FLAG_SPECS).filter(name => !FLAG_SPECS[name]!.arg))
63
-
64
- export function parseArgs(argv: string[]): ParsedArgs {
65
- const out: ParsedArgs = { positional: [], flags: {} }
66
- let i = 0
67
- while (i < argv.length) {
68
- const arg = argv[i]!
69
- if (arg.startsWith('--')) {
70
- const eq = arg.indexOf('=')
71
- if (eq !== -1) out.flags[arg.slice(2, eq)] = arg.slice(eq + 1)
72
- else {
73
- const name = arg.slice(2)
74
- const next = argv[i + 1]
75
- if (BOOLEAN_FLAGS.has(name) || next === undefined || next.startsWith('--')) out.flags[name] = true
76
- else { out.flags[name] = next; i++ }
77
- }
78
- } else if (!out.command) out.command = arg
79
- else out.positional.push(arg)
80
- i++
81
- }
82
- return out
83
- }
84
-
85
- function readSourceArg(arg: string | undefined): string {
86
- if (!arg || arg === '-') {
87
- // Loop 9 M5: TTY-stdin guard. When stdin is an interactive TTY (no
88
- // pipe), the read blocks forever waiting for the user to paste + Ctrl-D
89
- // — confusing UX. Fail fast with a clear hint.
90
- if (process.stdin.isTTY) throw new Error('needs a file argument or piped stdin')
91
- try { return readFileSync(0).toString('utf8') } catch { return '' }
92
- }
93
- if (!existsSync(arg)) throw new Error(`File not found: ${arg}`)
94
- return readFileSync(arg, 'utf8')
95
- }
96
-
97
- function replacer(_k: string, v: unknown): unknown { return v instanceof Map ? Object.fromEntries(v) : v }
98
-
99
- export const GLOBAL_USAGE = `Usage: am <command> [options] [file|-]
100
-
101
- Commands:
102
- render <file|-> Render to SVG/ASCII/Unicode/layout JSON/PNG
103
- verify <file|-> Verify; emits structured JSON warnings
104
- parse <file|-> Parse; emits ValidDiagram JSON
105
- serialize Read ValidDiagram JSON from stdin; emit canonical source
106
- mutate <file|-> --op '<JSON>' Apply MutationOp(s); verify + emit source
107
- preview <file|-> Write standalone HTML preview; optionally --open
108
- format <file|-> Idempotent reformat
109
- describe <file|-> Prose summary or AX-tree JSON
110
- capabilities Emit JSON describing families + warning codes + mutation ops
111
- batch Read JSONL ops from stdin; emit one JSON envelope per line
112
- render-markdown <file> Render fenced mermaid blocks in Markdown (SVG or --ascii)
113
- styles List registered styles (looks + themes); see also render --style
114
- llms-txt Emit the agent discovery digest
115
- init-agent Write a repo-local agent drop-in (AGENTS section, skill, MCP config)
116
-
117
- Flags:
118
- --json Structured JSON output
119
- --ascii For render/render-markdown: ASCII instead of SVG
120
- --op <JSON> For mutate: one MutationOp
121
- --ops <JSON|file> For mutate: JSON array of MutationOps
122
- --output <FILE> For render png / preview output path
123
- --open For preview: open generated HTML in browser
124
- --force For init-agent: refresh generated skill/MCP files
125
- --style <NAMES|file> For render svg/png: style stack — comma-separated names and/or .json spec files
126
- --seed <N> For render svg/png: re-roll ink wobble of styled looks (never layout)
127
- --font-dirs <DIRS> For render png: extra font directories, comma-separated (CJK/emoji coverage)
128
- --system-fonts For render png: also load OS fonts (coverage warnings then skipped)
129
- --suppress <CODES> For verify: comma-separated WarningCodes to suppress
130
- --label-cap <N> For verify: LABEL_OVERFLOW char cap (default 40)
131
- --certificates For render --format json: include route/family certificates
132
- --agent-instructions Print the canonical agent-use guide
133
- --help Show this message (or per-command help: am <cmd> --help)
134
-
135
- Exit codes:
136
- 0 ok
137
- 2 arg / parse error (bad flag, missing file, malformed JSON)
138
- 3 verify reported errors (severity 'error')
139
- 4 uncaught internal failure
140
- `
141
-
142
- export const COMMAND_HELP: Record<string, string> = {
143
- render: `am render <file|-> [--format svg|ascii|unicode|json|png] [--ascii] [--json]
144
- Render a diagram. Default is SVG.
145
- --format svg SVG markup (default)
146
- --format ascii 7-bit ASCII art (also via --ascii)
147
- --format unicode Unicode box-drawing ASCII art
148
- --format json Layout JSON (nodes, edges, groups, bounds)
149
- --certificates With --format json, include route/family certificates
150
- --format png PNG bytes; requires --output <file.png>; no watch/multi-input
151
- --style <S> Style stack: comma-separated names and/or .json spec files,
152
- merged left → right (e.g. --style hand-drawn,dracula or
153
- --style ./brand.json). Applies to svg/png. See: am styles
154
- --seed <N> Re-roll ink wobble of styled looks; never moves layout
155
- --font-dirs <DIRS> PNG only: extra font directories (comma-separated) for
156
- scripts the bundled Inter/DejaVu fonts don't cover (CJK,
157
- emoji); uncovered characters warn on stderr
158
- --system-fonts PNG only: also load OS-installed fonts (trades cross-machine
159
- determinism for coverage; skips coverage warnings)
160
- --security strict Remove external-fetch refs from SVG output
161
- --watch Re-render one input file on change (non-PNG only)
162
- Multiple inputs emit a JSON results array for non-PNG formats.
163
- With --json, the svg/ascii/unicode forms wrap output as {"<format>": "..."}.`,
164
- styles: `am styles [--json]
165
- List every registered style. A style is a partial description of how diagrams
166
- look; a colors-only style is a theme, a full look sets stroke/fill/typography
167
- too. Stack them with render --style (e.g. --style hand-drawn,dracula) and
168
- re-roll ink with --seed. Custom styles are JSON records (docs/style-authoring.md);
169
- pass a .json file path anywhere a name is accepted.
170
- With --json: [{ name, kind: default|look|theme, backend, intent?, blurb }].`,
171
- verify: `am verify <file|-> [--suppress A,B] [--label-cap N]
172
- Always emits JSON: {ok, warnings[], layout}.
173
- Tier-1 error codes flip ok=false:
174
- EMPTY_DIAGRAM, EDGE_MISANCHORED, OFF_CANVAS, GROUP_BREACH, UNRESOLVABLE_SCHEDULE,
175
- RENDER_FAILED (source verifies structurally but the render parser rejects it). Warning codes:
176
- UNKNOWN_SHAPE, LABEL_OVERFLOW (char-cap),
177
- NODE_OVERLAP, ROUTE_SELF_CROSS, ROUTE_HITCH, ROUTE_UNEXPLAINED_BEND, ROUTE_LABEL_ON_SHARED_TRUNK,
178
- ROUTE_CONTAINER_MISANCHOR, ROUTE_SHAPE_MISANCHOR, ROUTE_STALE_AFTER_NODE_MOVE,
179
- DUPLICATE_EDGE, UNREACHABLE_NODE, DECISION_BRANCH_UNLABELED, COMMENT_DROPPED, UNSUPPORTED_SYNTAX,
180
- CONTENT_DROPPED_ON_ROUNDTRIP, INEFFECTIVE_CONFIG. Tier-3 lint is advisory.
181
- Exit 0 if ok, 3 if verify reports severity='error'.`,
182
- parse: `am parse <file|->
183
- Emits ValidDiagram JSON (Maps serialized to objects). Exit 2 on parse error.
184
- Pipe to 'am serialize' to round-trip.`,
185
- serialize: `am serialize (reads ValidDiagram JSON on stdin)
186
- Emits canonical Mermaid source. Accepts the JSON shape that 'am parse' emits;
187
- rebuilds the diagram via synthesizeFromGraph without re-parsing source.`,
188
- mutate: `am mutate <file|-> (--op '<JSON>' | --ops '<JSON array|file.json>') [--json]
189
- Applies one or more MutationOps, verifies the final diagram, then emits source.
190
- Flowchart/state, sequence, timeline, class, ER, journey, architecture, xychart,
191
- pie, quadrant, and gantt have typed mutation ops; opaque-fallback diagrams (unmodeled
192
- syntax) return a structured UNSUPPORTED_FAMILY error (exit 2). Verify failures
193
- exit 3 and omit source.`,
194
- preview: `am preview <file|-> [--output preview.html] [--open] [--json] [--security strict]
195
- Writes a standalone HTML preview containing strict-mode rendered SVG. Without
196
- --output, emits HTML to stdout unless --open is set, in which case a temp HTML
197
- file is written and opened. With --json, emits {ok,path,opened,bytes} for file output.`,
198
- format: `am format <file|-> [--canonical-wrapper]
199
- Parse then re-serialize. Idempotent. The leading source wrapper (frontmatter,
200
- %%{init}%% directives, comments before the header) is preserved byte-verbatim
201
- by default; --canonical-wrapper instead synthesizes Mermaid's documented shape
202
- (title/displayMode top-level, everything else under config:, directives folded).`,
203
- describe: `am describe <file|-> [--format text|json|facts] [--json]
204
- Summarize a Mermaid diagram. Text format emits prose by default; --json wraps
205
- it as {ok,text}. --format json emits the structured AX tree
206
- {kind,nodes,edges,entryPoints,sinks}; with --json it wraps as {ok,tree}.
207
- --format facts emits deterministic semantic fact lines; with --json it wraps as {ok,facts}.`,
208
- capabilities: `am capabilities [--json]
209
- Emits a single JSON object describing the SDK's capability surface:
210
- { sdkVersion, families: [{ id, hasMutate, hasExtractLabels, mutationOps, editPolicy, example }],
211
- warningCodes: [{ code, tier, severity }],
212
- outputFormats: ["svg", "ascii", "unicode", "png", "json"] }
213
- editPolicy is "structured-when-narrowed" or "source-level-only". Use this to
214
- introspect what the CLI can do without running every command.`,
215
- batch: `am batch (reads JSONL from stdin)
216
- Each line: { op: "render"|"verify"|"parse"|"serialize"|"mutate", source: string,
217
- options?: {}, mutation?: MutationOp, mutations?: MutationOp[] }. Emits one JSON
218
- envelope per line: { ok, op, data?, error? }. Malformed JSON or unknown ops
219
- surface as ok:false; the batch continues and exits 0 even if lines errored.`,
220
- 'render-markdown': `am render-markdown <file.md> [--ascii]
221
- Render fenced \`\`\`mermaid blocks. Bad diagrams yield ok:false entries and do
222
- not abort the rest of the Markdown file.`,
223
- 'llms-txt': `am llms-txt
224
- Emit the committed agent-discovery digest generated from current capabilities.`,
225
- 'init-agent': `am init-agent [--dir <path>] [--force] [--json]
226
- Write a repo-local, agent-agnostic drop-in so coding agents discover the
227
- parse → narrow → mutate → verify → serialize contract automatically. Creates
228
- without clobbering by default:
229
- - AGENTS.md marked section pointing agents at the workflow + hosted docs
230
- - skills/agentic-mermaid-diagram-workflow/SKILL.md generic skill bundle
231
- - .mcp.json sample agentic-mermaid MCP server config
232
- --dir defaults to the current directory. --force overwrites skill/MCP files;
233
- the AGENTS.md section is always appended only once, guarded by a marker.`,
234
- }
235
-
236
- export function runCli(argv: string[]): number {
237
- const args = parseArgs(argv)
238
- if (args.flags['agent-instructions']) { process.stdout.write(AGENT_INSTRUCTIONS); return EXIT_OK }
239
- if (args.flags.help && !args.command) { process.stdout.write(GLOBAL_USAGE); return EXIT_OK }
240
- if (!args.command) { process.stdout.write(GLOBAL_USAGE); return EXIT_ARG_ERROR }
241
- if (args.flags.help) {
242
- process.stdout.write((COMMAND_HELP[args.command] ?? GLOBAL_USAGE) + '\n')
243
- return EXIT_OK
244
- }
245
- const json = Boolean(args.flags.json)
246
- // Opt-in invocation logging: when AM_TRACE_LOG names a file, append one JSON
247
- // line per real command run. Shares the sink with the library and hosted MCP
248
- // (src/agent/trace-log.ts) so the agent-usage eval can grade traceOk from
249
- // observed calls on ANY channel. The library verify/mutate/create the CLI
250
- // commands call also log, so `am verify`/`am mutate` are covered even here.
251
- logToolInvocation(args.command)
252
- try {
253
- switch (args.command) {
254
- case 'render': return cmdRender(args, json)
255
- case 'verify': return cmdVerify(args)
256
- case 'parse': return cmdParse(args)
257
- case 'serialize': return cmdSerialize()
258
- case 'mutate': return cmdMutate(args, json)
259
- case 'preview': return cmdPreview(args, json)
260
- case 'format': return cmdFormat(args)
261
- case 'describe': return cmdDescribe(args, json)
262
- case 'capabilities': return cmdCapabilities()
263
- case 'styles': return cmdStyles(json)
264
- case 'llms-txt': return cmdLlmsTxt()
265
- case 'init-agent': return cmdInitAgent(args, json)
266
- case 'batch': return cmdBatch()
267
- case 'render-markdown': return cmdRenderMarkdown(args)
268
- default:
269
- process.stderr.write(`Unknown command: ${args.command}\n${GLOBAL_USAGE}`)
270
- return EXIT_ARG_ERROR
271
- }
272
- } catch (e) {
273
- const msg = e instanceof Error ? e.message : String(e)
274
- // Loop 9 M5: argument-shape errors (missing file, TTY stdin, etc.) get
275
- // exit 2 per the documented contract. Heuristic: messages thrown from
276
- // readSourceArg / arg parsing are advisory rather than internal bugs.
277
- const isArgError = /^needs a file argument|^File not found:/.test(msg)
278
- if (json) process.stdout.write(JSON.stringify({ ok: false, error: { code: isArgError ? 'ARG' : 'INTERNAL', message: msg } }) + '\n')
279
- else process.stderr.write(`Error: ${msg}\n`)
280
- return isArgError ? EXIT_ARG_ERROR : EXIT_INTERNAL
281
- }
282
- }
283
-
284
- function cmdRender(args: ParsedArgs, json: boolean): number {
285
- const format = typeof args.flags.format === 'string' ? args.flags.format : (args.flags.ascii ? 'ascii' : 'svg')
286
- const security = args.flags.security === 'strict' ? 'strict' as const : 'default' as const
287
- if (!['svg', 'ascii', 'unicode', 'json', 'png'].includes(format)) {
288
- process.stderr.write(`am render: unsupported --format ${format}; expected svg, ascii, unicode, json, or png\n`)
289
- return EXIT_ARG_ERROR
290
- }
291
- if (args.flags.security !== undefined && args.flags.security !== 'strict') {
292
- process.stderr.write('am render --security accepts only strict\n')
293
- return EXIT_ARG_ERROR
294
- }
295
- if (args.flags.watch && args.positional.length > 1) {
296
- process.stderr.write('am render --watch accepts exactly one input file\n')
297
- return EXIT_ARG_ERROR
298
- }
299
-
300
- // --style: a stack of names and/or .json spec files; fail fast (exit 2) on
301
- // unknown names or invalid specs instead of surfacing an internal error.
302
- let style: StyleInput[] | undefined
303
- if (typeof args.flags.style === 'string') {
304
- try {
305
- style = parseStyleFlag(args.flags.style)
306
- resolveStyleStack(style)
307
- } catch (e) {
308
- process.stderr.write(`am render --style: ${e instanceof Error ? e.message : String(e)}\n`)
309
- return EXIT_ARG_ERROR
310
- }
311
- if (format === 'ascii' || format === 'unicode' || format === 'json') {
312
- process.stderr.write(`am render: --style applies to svg/png output; ignored for --format ${format}\n`)
313
- }
314
- }
315
- const seed = typeof args.flags.seed === 'string' ? Number(args.flags.seed) : undefined
316
- if (seed !== undefined && !Number.isFinite(seed)) {
317
- process.stderr.write('am render --seed expects a finite number\n')
318
- return EXIT_ARG_ERROR
319
- }
320
-
321
- if (args.positional.length > 1 && format === 'png') {
322
- process.stderr.write('am render --format png accepts exactly one input; run once per file with a distinct --output path\n')
323
- return EXIT_ARG_ERROR
324
- }
325
-
326
- // #959: multi-input — when more than one positional file is given, render
327
- // each and emit a JSON array of results, skipping bad files (like #543).
328
- // Single-input keeps the existing single-output behavior. PNG is excluded
329
- // because it writes bytes to a single --output path.
330
- if (args.positional.length > 1) {
331
- const results = args.positional.map((file, index) => {
332
- try {
333
- const src = readSourceArg(file)
334
- const output = renderSourceToFormat(src, format, { security, certificates: args.flags.certificates === true, style, seed })
335
- return { index, file, ok: true, output }
336
- } catch (e) {
337
- const parseEnvelope = e as { ok?: false; error?: { code?: string; message?: string; details?: unknown } }
338
- if (parseEnvelope?.ok === false && parseEnvelope.error?.code === 'PARSE_FAILED') {
339
- return { index, file, ok: false, error: parseEnvelope.error }
340
- }
341
- return { index, file, ok: false, error: { code: 'RENDER_FAILED', message: e instanceof Error ? e.message : String(e) } }
342
- }
343
- })
344
- process.stdout.write(JSON.stringify({ ok: true, files: results }) + '\n')
345
- return EXIT_OK
346
- }
347
-
348
- // #930: watch mode — re-render on file change.
349
- if (args.flags.watch && format === 'png') {
350
- process.stderr.write('am render --format png does not support --watch; run non-watch PNG renders with --output <file.png>\n')
351
- return EXIT_ARG_ERROR
352
- }
353
- if (args.flags.watch && typeof args.positional[0] === 'string' && args.positional[0] !== '-') {
354
- return cmdRenderWatch(args.positional[0], format, args, json, { security, certificates: args.flags.certificates === true, style, seed })
355
- }
356
-
357
- const source = readSourceArg(args.positional[0])
358
- const parsed = parseMermaid(source)
359
- if (!parsed.ok) {
360
- process.stdout.write(JSON.stringify(parseErrorEnvelope(parsed.error)) + '\n')
361
- return EXIT_ARG_ERROR
362
- }
363
-
364
- if (format === 'png') {
365
- const outFile = typeof args.flags.o === 'string' ? args.flags.o : (typeof args.flags.output === 'string' ? args.flags.output : '')
366
- if (!outFile) {
367
- process.stderr.write('am render --format png requires --output <file.png> (PNG bytes corrupt terminals if piped to stdout)\n')
368
- return EXIT_ARG_ERROR
369
- }
370
- const scale = typeof args.flags.scale === 'string' ? Number(args.flags.scale) : 2
371
- const background = typeof args.flags.bg === 'string' ? args.flags.bg : 'white'
372
- const fontDirs = typeof args.flags['font-dirs'] === 'string'
373
- ? args.flags['font-dirs'].split(',').map(s => s.trim()).filter(Boolean)
374
- : undefined
375
- const loadSystemFonts = args.flags['system-fonts'] === true
376
- // PNG render is native-sync via resvg; keep bytes off stdout and write the
377
- // raster artifact explicitly to the requested output path.
378
- return renderPngSync(source, { scale, background, style, seed, fontDirs, loadSystemFonts }, outFile, json)
379
- }
380
- // Loop 9 M3/M4, #7645: json = layout shape; unicode is the default text
381
- // renderer; `--security strict` strips external-fetch refs from SVG.
382
- const out = renderSourceToFormat(source, format, { security, certificates: args.flags.certificates === true, style, seed })
383
- if (typeof out !== 'string') {
384
- process.stdout.write(JSON.stringify(out) + '\n')
385
- return EXIT_OK
386
- }
387
- process.stdout.write(json ? JSON.stringify({ [format]: out }) + '\n' : (out.endsWith('\n') ? out : out + '\n'))
388
- return EXIT_OK
389
- }
390
-
391
- interface RenderFormatOptions { security?: 'default' | 'strict'; certificates?: boolean; style?: StyleInput[]; seed?: number }
392
-
393
- /** The ONE format dispatch behind every render path — single-input,
394
- * multi-input, and watch differ only in I/O and error envelopes, so they
395
- * share this core instead of re-enumerating formats (the style/seed
396
- * threading previously had to touch three copies). JSON parse failures
397
- * throw the structured envelope; callers decide how to surface it. */
398
- function renderSourceToFormat(source: string, format: string, opts: RenderFormatOptions = {}): string | object {
399
- if (format === 'ascii' || format === 'unicode') return renderMermaidASCII(source, { useAscii: format === 'ascii' })
400
- if (format === 'json') {
401
- const parsed = parseMermaid(source)
402
- if (!parsed.ok) throw parseErrorEnvelope(parsed.error)
403
- return layoutMermaid(parsed.value, { debug: opts.certificates === true })
404
- }
405
- return renderMermaidSVG(source, { security: opts.security, style: opts.style, seed: opts.seed })
406
- }
407
-
408
- /**
409
- * #930: pure re-render step for watch mode — reads the file, renders to the
410
- * requested format, returns the output string. Extracted so it's unit-testable
411
- * without fs.watch timing.
412
- */
413
- export function renderFileOnce(file: string, format: string, opts: RenderFormatOptions = {}): string {
414
- const src = readFileSync(file, 'utf8')
415
- try {
416
- const out = renderSourceToFormat(src, format, opts)
417
- return typeof out === 'string' ? out : JSON.stringify(out)
418
- } catch (e) {
419
- // Watch mode wants a printable line, not a throw: the structured JSON
420
- // parse envelope serializes; real render errors keep propagating.
421
- if ((e as { ok?: boolean; error?: unknown })?.ok === false) return JSON.stringify(e)
422
- throw e
423
- }
424
- }
425
-
426
- function cmdRenderWatch(file: string, format: string, args: ParsedArgs, _json: boolean, opts: { security?: 'default' | 'strict'; certificates?: boolean; style?: StyleInput[]; seed?: number } = {}): number {
427
- const outFile = typeof args.flags.output === 'string' ? args.flags.output : ''
428
- const emit = () => {
429
- try {
430
- const out = renderFileOnce(file, format, opts)
431
- if (outFile) { writeFileSync(outFile, out) ; process.stderr.write(`rendered → ${outFile}\n`) }
432
- else process.stdout.write(out + (out.endsWith('\n') ? '' : '\n'))
433
- } catch (e) { process.stderr.write(`render error: ${(e as Error).message}\n`) }
434
- }
435
- emit() // initial render
436
- process.stderr.write(`watching ${file} (Ctrl-C to stop)…\n`)
437
- watch(file, { persistent: true }, (event) => { if (event === 'change') emit() })
438
- // Block forever — the watcher keeps the event loop alive.
439
- return EXIT_OK
440
- }
441
-
442
- function renderPngSync(source: string, opts: { scale: number; background: string; style?: StyleInput[]; seed?: number; fontDirs?: string[]; loadSystemFonts?: boolean }, outFile: string, json: boolean): number {
443
- try {
444
- // Glyph-coverage warnings (CJK/emoji without a covering font) go to
445
- // stderr — the PNG itself can't show what silently became tofu — and
446
- // ride along in the --json envelope for programmatic callers.
447
- const warnings: PngFontWarning[] = []
448
- const png = renderMermaidPNG(source, { ...opts, onWarning: w => warnings.push(w) })
449
- writeFileSync(outFile, png)
450
- for (const w of warnings) process.stderr.write(`am render --format png: warning ${w.code}: ${w.message}\n`)
451
- if (json) process.stdout.write(JSON.stringify({ ok: true, path: outFile, bytes: png.length, warnings }) + '\n')
452
- return EXIT_OK
453
- } catch (e) {
454
- const msg = e instanceof Error ? e.message : String(e)
455
- process.stderr.write(`am render --format png: ${msg}\n`)
456
- return EXIT_INTERNAL
457
- }
458
- }
459
-
460
- function cmdVerify(args: ParsedArgs): number {
461
- const source = readSourceArg(args.positional[0])
462
- const suppressRaw = typeof args.flags.suppress === 'string' ? args.flags.suppress : ''
463
- const suppress = suppressRaw ? (suppressRaw.split(',').map(s => s.trim()).filter(Boolean) as WarningCode[]) : undefined
464
- const labelCharCap = typeof args.flags['label-cap'] === 'string' ? parseInt(args.flags['label-cap'], 10) : undefined
465
- const r = verifyMermaid(source, { suppress, labelCharCap })
466
- process.stdout.write(JSON.stringify(r, replacer) + '\n')
467
- return r.ok ? EXIT_OK : EXIT_VERIFY_FAILED
468
- }
469
-
470
- function cmdParse(args: ParsedArgs): number {
471
- const r = parseMermaid(readSourceArg(args.positional[0]))
472
- if (!r.ok) {
473
- // Error envelope matches the documented batch shape (cli/index.ts:107).
474
- // Success emits the bare ValidDiagram payload — pipeable into `am serialize`
475
- // without unwrapping, which preserves existing consumer contracts.
476
- process.stdout.write(JSON.stringify(parseErrorEnvelope(r.error)) + '\n')
477
- return EXIT_ARG_ERROR
478
- }
479
- process.stdout.write(JSON.stringify(toJsonSafe(r.value), replacer) + '\n')
480
- return EXIT_OK
481
- }
482
-
483
- function cmdSerialize(): number {
484
- const stdin = readSourceArg('-')
485
- let payload: unknown
486
- try { payload = JSON.parse(stdin) } catch (e) { process.stderr.write(`serialize: invalid JSON: ${(e as Error).message}\n`); return EXIT_ARG_ERROR }
487
- const r = synthesizeFromGraph(payload as Parameters<typeof synthesizeFromGraph>[0])
488
- if (!r.ok) { process.stderr.write(`serialize: ${JSON.stringify(r.error)}\n`); return EXIT_ARG_ERROR }
489
- process.stdout.write(serializeMermaid(r.value))
490
- return EXIT_OK
491
- }
492
-
493
- type CliMutationError = MutationError | { code: 'UNSUPPORTED_FAMILY' | 'VERIFY_FAILED' | 'PARSE_FAILED' | 'INVALID_OP'; message: string; details?: unknown }
494
-
495
- type MutationRunResult =
496
- | { ok: true; source: string; verify: ReturnType<typeof verifyMermaid> }
497
- | { ok: false; error: CliMutationError; verify?: ReturnType<typeof verifyMermaid> }
498
-
499
- function parseMutationOpsFlag(args: ParsedArgs): Result<AnyMutationOp[], CliMutationError> {
500
- const opStr = typeof args.flags.op === 'string' ? args.flags.op : ''
501
- const opsStr = typeof args.flags.ops === 'string' ? args.flags.ops : ''
502
- if (opStr && opsStr) return { ok: false, error: { code: 'INVALID_OP', message: 'mutate accepts either --op or --ops, not both' } }
503
- if (!opStr && !opsStr) return { ok: false, error: { code: 'INVALID_OP', message: 'mutate requires --op <JSON> or --ops <JSON array|file.json>' } }
504
- try {
505
- if (opStr) return { ok: true, value: [JSON.parse(opStr) as AnyMutationOp] }
506
- const raw = existsSync(opsStr) ? readFileSync(opsStr, 'utf8') : opsStr
507
- const parsed = JSON.parse(raw) as unknown
508
- if (!Array.isArray(parsed)) return { ok: false, error: { code: 'INVALID_OP', message: '--ops must be a JSON array of MutationOps' } }
509
- if (parsed.length === 0) return { ok: false, error: { code: 'INVALID_OP', message: '--ops must contain at least one MutationOp' } }
510
- return { ok: true, value: parsed as AnyMutationOp[] }
511
- } catch (e) {
512
- return { ok: false, error: { code: 'INVALID_OP', message: `invalid mutation JSON: ${(e as Error).message}` } }
513
- }
514
- }
515
-
516
- function mutateAny(d: ValidDiagram, op: AnyMutationOp): Result<MutableValidDiagram, CliMutationError> {
517
- // mutate() dispatches to the family's registered mutator by diagram kind,
518
- // so the CLI only rules out what the registry cannot handle: opaque bodies
519
- // (source-preserved syntax has no structured ops) and families without a
520
- // mutate hook. The per-family narrowing cascade this replaces re-encoded
521
- // the family list a 13th time.
522
- const plugin = getFamily(d.kind)
523
- if (d.body.kind !== 'opaque' && plugin?.mutate && plugin.serialize) {
524
- // `--op`/`--ops` arrive as untyped JSON, so the CLI funnels through the same
525
- // mutateChecked choke point the MCP paths use: shape is validated (a wrong/
526
- // missing/mistyped field is a prescriptive INVALID_OP) before the mutator.
527
- return mutateChecked(d as MutableValidDiagram, op)
528
- }
529
- return {
530
- ok: false,
531
- error: { code: 'UNSUPPORTED_FAMILY', message: `mutate supports ${knownFamilies().join(', ')} diagrams; got ${d.kind}${d.body.kind === 'opaque' ? ' (source-level/opaque body — structured mutation is not exposed for this family or syntax)' : ''}` },
532
- }
533
- }
534
-
535
- export function mutateSource(source: string, ops: AnyMutationOp[]): MutationRunResult {
536
- const r0 = parseMermaid(source)
537
- if (!r0.ok) {
538
- const env = parseErrorEnvelope(r0.error)
539
- return { ok: false, error: { code: 'PARSE_FAILED', message: env.error.message, details: env.error.details } }
540
- }
541
- let current: ValidDiagram = r0.value
542
- for (let index = 0; index < ops.length; index++) {
543
- const op = ops[index]!
544
- const next = mutateAny(current, op)
545
- if (!next.ok) {
546
- const details = (next.error as { details?: unknown }).details
547
- return { ok: false, error: { ...next.error, details: { index, op, ...(typeof details === 'object' && details ? details as Record<string, unknown> : {}) } } }
548
- }
549
- current = next.value
550
- }
551
- const verify = verifyMermaid(current)
552
- if (!verify.ok) {
553
- return {
554
- ok: false,
555
- error: { code: 'VERIFY_FAILED', message: 'mutated diagram failed verify; source was not emitted', details: verify.warnings },
556
- verify,
557
- }
558
- }
559
- return { ok: true, source: serializeMermaid(current), verify }
560
- }
561
-
562
- function cmdMutate(args: ParsedArgs, json: boolean): number {
563
- const source = readSourceArg(args.positional[0])
564
- const ops = parseMutationOpsFlag(args)
565
- if (!ops.ok) { process.stderr.write(`mutate: ${ops.error.message}\n`); return EXIT_ARG_ERROR }
566
- return emitMutationRun(mutateSource(source, ops.value), json)
567
- }
568
-
569
- function emitMutationRun(r: MutationRunResult, json: boolean): number {
570
- if (!r.ok) {
571
- process.stdout.write(JSON.stringify({ ok: false, error: r.error, verify: r.verify }, replacer) + '\n')
572
- return r.error.code === 'VERIFY_FAILED' ? EXIT_VERIFY_FAILED : EXIT_ARG_ERROR
573
- }
574
- process.stdout.write(json ? JSON.stringify({ ok: true, source: r.source, verify: r.verify }, replacer) + '\n' : r.source)
575
- return EXIT_OK
576
- }
577
-
578
- export function buildPreviewHtml(source: string, opts: { security?: 'default' | 'strict' } = {}): Result<string, { code: string; message: string; details?: unknown }> {
579
- const parsed = parseMermaid(source)
580
- if (!parsed.ok) {
581
- const env = parseErrorEnvelope(parsed.error)
582
- return { ok: false, error: env.error }
583
- }
584
- const svg = renderMermaidSVG(source, { security: opts.security ?? 'strict' })
585
- const title = parsed.value.meta.frontmatter?.title ?? 'Mermaid preview'
586
- const escapedTitle = escapeHtml(String(title))
587
- const escapedSource = escapeHtml(source)
588
- return { ok: true, value: `<!doctype html>
589
- <html lang="en">
590
- <head>
591
- <meta charset="utf-8" />
592
- <meta name="viewport" content="width=device-width, initial-scale=1" />
593
- <title>${escapedTitle}</title>
594
- <style>
595
- body { margin: 0; min-height: 100vh; display: grid; grid-template-rows: auto 1fr; background: #f8fafc; color: #0f172a; font-family: system-ui, sans-serif; }
596
- header { padding: 12px 16px; border-bottom: 1px solid #e2e8f0; background: white; }
597
- main { padding: 24px; overflow: auto; }
598
- .canvas { width: max-content; max-width: 100%; margin: 0 auto; background: white; box-shadow: 0 18px 70px rgba(15,23,42,.12); }
599
- svg { display: block; max-width: 100%; height: auto; }
600
- details { margin-top: 16px; }
601
- pre { white-space: pre-wrap; background: #0f172a; color: #e2e8f0; padding: 12px; border-radius: 8px; }
602
- </style>
603
- </head>
604
- <body>
605
- <header><strong>${escapedTitle}</strong></header>
606
- <main>
607
- <div class="canvas">${svg}</div>
608
- <details><summary>Mermaid source</summary><pre>${escapedSource}</pre></details>
609
- </main>
610
- </body>
611
- </html>` }
612
- }
613
-
614
- function escapeHtml(s: string): string {
615
- return s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;')
616
- }
617
-
618
- export function openPreviewFile(path: string): { ok: true } | { ok: false; error: string } {
619
- const override = process.env.AM_OPEN_COMMAND
620
- const command = override || (process.platform === 'darwin' ? 'open' : process.platform === 'win32' ? 'cmd' : 'xdg-open')
621
- const args = override ? [path] : process.platform === 'win32' ? ['/c', 'start', '', path] : [path]
622
- const r = spawnSync(command, args, { stdio: 'ignore' })
623
- if (r.error || r.status !== 0) return { ok: false, error: `open command failed: ${command}` }
624
- return { ok: true }
625
- }
626
-
627
- function cmdPreview(args: ParsedArgs, json: boolean): number {
628
- const source = readSourceArg(args.positional[0])
629
- const security = 'strict' as const
630
- if (args.flags.security !== undefined && args.flags.security !== 'strict') {
631
- process.stderr.write('am preview --security accepts only strict\n')
632
- return EXIT_ARG_ERROR
633
- }
634
- const html = buildPreviewHtml(source, { security })
635
- if (!html.ok) { process.stdout.write(JSON.stringify({ ok: false, error: html.error }) + '\n'); return EXIT_ARG_ERROR }
636
- let outFile = typeof args.flags.output === 'string' ? args.flags.output : ''
637
- if (!outFile && args.flags.open) outFile = join(mkdtempSync(join(tmpdir(), 'am-preview-')), 'preview.html')
638
- if (outFile) {
639
- const path = resolve(outFile)
640
- writeFileSync(path, html.value)
641
- let opened = false
642
- if (args.flags.open) {
643
- const openedResult = openPreviewFile(path)
644
- if (!openedResult.ok) { process.stderr.write(`am preview --open: ${openedResult.error}\n`); return EXIT_INTERNAL }
645
- opened = true
646
- }
647
- if (json) process.stdout.write(JSON.stringify({ ok: true, path, opened, bytes: html.value.length }) + '\n')
648
- else process.stdout.write(`${path}\n`)
649
- return EXIT_OK
650
- }
651
- process.stdout.write(json ? JSON.stringify({ ok: true, html: html.value }) + '\n' : html.value)
652
- return EXIT_OK
653
- }
654
-
655
- function cmdFormat(args: ParsedArgs): number {
656
- const r = parseMermaid(readSourceArg(args.positional[0]))
657
- if (!r.ok) { process.stderr.write(`format: parse failed: ${JSON.stringify(r.error)}\n`); return EXIT_ARG_ERROR }
658
- const wrapper = args.flags['canonical-wrapper'] ? 'canonical' as const : 'verbatim' as const
659
- process.stdout.write(serializeMermaid(r.value, { wrapper }))
660
- return EXIT_OK
661
- }
662
-
663
- function cmdDescribe(args: ParsedArgs, json: boolean): number {
664
- const source = readSourceArg(args.positional[0])
665
- const rawFormat = args.flags.format
666
- const format = rawFormat === 'json' || rawFormat === 'facts' || rawFormat === 'text' || rawFormat === undefined
667
- ? (rawFormat ?? 'text') as 'text' | 'json' | 'facts'
668
- : undefined
669
- if (!format) {
670
- process.stderr.write('am describe --format must be one of: text, json, facts\n')
671
- return EXIT_ARG_ERROR
672
- }
673
- const parsed = parseMermaid(source)
674
- if (!parsed.ok) {
675
- const env = parseErrorEnvelope(parsed.error)
676
- if (json || format === 'json') process.stdout.write(JSON.stringify(env) + '\n')
677
- else process.stderr.write(`describe: parse failed: ${env.error.message}\n`)
678
- return EXIT_ARG_ERROR
679
- }
680
- const described = describeMermaid(parsed.value, { format })
681
- if (format === 'json') {
682
- const tree = JSON.parse(described)
683
- process.stdout.write(JSON.stringify(json ? { ok: true, tree } : tree) + '\n')
684
- return EXIT_OK
685
- }
686
- if (format === 'facts') {
687
- const facts = described.split('\n').filter(Boolean)
688
- process.stdout.write(json ? JSON.stringify({ ok: true, facts }) + '\n' : facts.join('\n') + '\n')
689
- return EXIT_OK
690
- }
691
- process.stdout.write(json ? JSON.stringify({ ok: true, text: described }) + '\n' : described + '\n')
692
- return EXIT_OK
693
- }
694
-
695
- // ---- Loop 7 / A3.1: capabilities ------------------------------------------
696
-
697
- type FamilyEditPolicy = 'structured-when-narrowed' | 'source-level-only'
698
-
699
- interface FamilyCapability {
700
- id: string
701
- hasMutate: boolean
702
- hasExtractLabels: boolean
703
- mutationOps: string[]
704
- /** Full field shapes for each op — { opKind: [{name, required, type}] }, with
705
- * enum vocabularies spelled out inline in `type`. Lets a model fill an op
706
- * correctly on the first try instead of guessing field names/values and
707
- * learning them only from the INVALID_OP error. Absent for source-level-only
708
- * families (no structured ops). */
709
- opFields?: Record<string, OpFieldDoc[]>
710
- editPolicy: FamilyEditPolicy
711
- /** The `as*` narrower to call before structured mutation (e.g. `asState`). */
712
- narrower?: string
713
- /** Mermaid header keyword(s) that open this family (e.g. `stateDiagram-v2`,
714
- * `architecture-beta`) — so a model authoring from blank opens with the right
715
- * header instead of inferring it from `example` or defaulting to flowchart. */
716
- headers?: readonly string[]
717
- /** Minimal canonical source (header + core syntax); absent for
718
- * registered non-builtin families that don't declare one. */
719
- example?: string
720
- }
721
-
722
- interface WarningCodeCapability {
723
- code: WarningCode
724
- tier: string
725
- severity: string
726
- }
727
-
728
- interface CapabilitiesEnvelope {
729
- sdkVersion: string
730
- families: FamilyCapability[]
731
- warningCodes: WarningCodeCapability[]
732
- outputFormats: string[]
733
- }
734
-
735
- // Source of truth now lives in the agent layer (src/agent/mutation-ops.ts) so
736
- // the mutators can name their valid ops in errors; imported and re-exported here
737
- // to keep the capabilities envelope and existing `from '../cli/index.ts'`
738
- // importers working.
739
- import { MUTATION_OPS_BY_FAMILY } from '../agent/mutation-ops.ts'
740
- export { MUTATION_OPS_BY_FAMILY }
741
- import { describeOps, hasOpSchema, type OpFieldDoc } from '../agent/op-schema.ts'
742
-
743
- type MutableFamilyId = keyof typeof MUTATION_OPS_BY_FAMILY
744
-
745
- export function buildCapabilities(): CapabilitiesEnvelope {
746
- const sdkVersion = (() => {
747
- try {
748
- const pkg = require('../../package.json') as { version: string }
749
- return pkg.version
750
- } catch {
751
- return 'unknown'
752
- }
753
- })()
754
- const mutableFamilies = new Set(Object.keys(MUTATION_OPS_BY_FAMILY))
755
- const families: FamilyCapability[] = knownFamilies().map((id) => {
756
- const p = getFamily(id)!
757
- const mutationOps = id in MUTATION_OPS_BY_FAMILY ? [...MUTATION_OPS_BY_FAMILY[id as MutableFamilyId]] : []
758
- const editPolicy: FamilyEditPolicy = mutationOps.length > 0 ? 'structured-when-narrowed' : 'source-level-only'
759
- return {
760
- id,
761
- // Capabilities describe the public agent surface, not whether the
762
- // implementation currently lives in a FamilyPlugin hook or central
763
- // dispatch. Every registered family parses, serializes, verifies, and
764
- // renders — so those constant booleans are omitted (they read as a
765
- // "probe-me" menu with nothing to branch on). Only what actually varies
766
- // is emitted: whether structured mutation and label extraction apply.
767
- hasMutate: mutableFamilies.has(id),
768
- hasExtractLabels: Boolean(p.extractLabels),
769
- mutationOps,
770
- opFields: hasOpSchema(id) ? describeOps(id) : undefined,
771
- editPolicy,
772
- narrower: builtinFamilyMetadata(id)?.narrower,
773
- headers: builtinFamilyMetadata(id)?.headers,
774
- example: builtinFamilyMetadata(id)?.example,
775
- }
776
- })
777
- const warningCodes: WarningCodeCapability[] = (Object.keys(WARNING_SEVERITY) as WarningCode[]).map(code => ({
778
- code,
779
- tier: WARNING_TIER[code],
780
- severity: WARNING_SEVERITY[code],
781
- }))
782
- return { sdkVersion, families, warningCodes, outputFormats: ['svg', 'ascii', 'unicode', 'png', 'json'] }
783
- }
784
-
785
- /** Resolve the --style flag: comma-separated style names and/or .json spec
786
- * files forming a stack (merged left → right by resolveStyleStack). JSON
787
- * specs are validated before use so bad files are arg errors, not throws. */
788
- function parseStyleFlag(value: string): StyleInput[] {
789
- return value.split(',').map(entry => entry.trim()).filter(Boolean).map(entry => {
790
- if (entry.endsWith('.json') || existsSync(entry)) {
791
- if (!existsSync(entry)) throw new Error(`style spec file not found: ${entry}`)
792
- const spec = JSON.parse(readFileSync(entry, 'utf8')) as unknown
793
- const problems = validateStyleSpec(spec)
794
- if (problems.length > 0) throw new Error(`invalid style spec ${entry}: ${problems.join('; ')}`)
795
- return spec as StyleSpec
796
- }
797
- return entry
798
- })
799
- }
800
-
801
- function cmdStyles(json: boolean): number {
802
- const rows = knownStyles().map(name => {
803
- if (name === 'crisp') {
804
- return { name, kind: 'default' as const, backend: 'default' as const, blurb: 'The byte-identical default renderer (style unset).' }
805
- }
806
- const spec = getStyle(name)!
807
- return {
808
- name,
809
- kind: styleKind(spec),
810
- backend: inferBackend(spec),
811
- ...(spec.intent ? { intent: spec.intent } : {}),
812
- blurb: spec.blurb ?? '',
813
- }
814
- })
815
- if (json) {
816
- process.stdout.write(JSON.stringify(rows) + '\n')
817
- return EXIT_OK
818
- }
819
- const nameWidth = Math.max(...rows.map(r => r.name.length))
820
- for (const r of rows) {
821
- process.stdout.write(`${r.name.padEnd(nameWidth)} ${r.kind.padEnd(7)} ${r.blurb}\n`)
822
- }
823
- process.stdout.write(`\nStack styles with: am render <file> --style <name[,name|file.json...]> [--seed N]\nAuthor your own: docs/style-authoring.md (JSON records; validate with validateStyleSpec).\n`)
824
- return EXIT_OK
825
- }
826
-
827
- function cmdCapabilities(): number {
828
- process.stdout.write(JSON.stringify(buildCapabilities()) + '\n')
829
- return EXIT_OK
830
- }
831
-
832
- // ---- Loop 11 / M4 (#6430): llms.txt agent-discovery digest ----------------
833
-
834
- /**
835
- * Build an llms.txt digest (https://llmstxt.org) for agent discovery.
836
- * Derived from buildCapabilities() so the family list, warning codes, and
837
- * output formats stay in sync with the actual SDK surface.
838
- */
839
- export function buildLlmsTxt(): string {
840
- const cap = buildCapabilities()
841
- const families = cap.families.map(f => f.id).join(', ')
842
- const structured = cap.families.filter(f => f.hasMutate).map(f => f.id)
843
- const narrowers = BUILTIN_FAMILY_METADATA.map(f => f.narrower).join(', ')
844
- const formats = cap.outputFormats.join(', ')
845
- const codes = cap.warningCodes.map(w => `${w.code} (${w.tier}/${w.severity})`).join(', ')
846
- return `# Agentic Mermaid
847
-
848
- > Agent-native Mermaid runtime: parse, verify, mutate, and round-trip
849
- > Mermaid diagrams with a typed IR. Deterministic ASCII / PNG / SVG. No
850
- > browser required. CLI + MCP + library.
851
-
852
- Version: ${cap.sdkVersion}
853
-
854
- ## What it does
855
-
856
- A typed editing surface over Mermaid for AI agents. Parse a diagram to a
857
- ValidDiagram, mutate it with typed ops, verify structurally (no pixels),
858
- serialize back to canonical source. Layout is deterministic (verified
859
- cross-process and same-machine cross-runtime on x86_64/ARM64).
860
-
861
- ## The agent loop
862
-
863
- New diagrams: author Mermaid source → parse → verify → render/return.
864
- Existing structured diagrams: parse → narrow → mutate → verify → serialize.
865
- Run verify at every commit point. Never serialize a diagram whose verify result
866
- you haven't inspected.
867
-
868
- ## CLI verbs (\`am <verb>\`)
869
-
870
- - render --format svg, ascii, unicode, json [--security strict] — render a diagram
871
- - render --format png --output file.png — render one input to PNG (no PNG bytes on stdout, no multi-input/watch)
872
- - render --style <names|file.json> --seed N — styled svg/png; comma-separate to stack (--style hand-drawn,dracula)
873
- - styles [--json] — list registered styles (default + full looks + palette-only themes)
874
- - parse — diagram → ValidDiagram JSON
875
- - verify — structural validation (exit 3 if invalid)
876
- - mutate --op '<json>' / --ops '<json array|file>' — apply typed mutation(s), verify, then emit source
877
- - preview [--output file.html] [--open] — standalone strict-mode HTML preview for user inspection
878
- - format — normalize / canonicalize source
879
- - describe [--format text|json|facts] — natural-language, AX-tree, or semantic facts summary
880
- - capabilities --json — machine-readable capability envelope incl. editPolicy + mutationOps
881
- - batch --jsonl — bulk render/verify/parse/serialize/mutate ops, one JSON envelope per line
882
- - render-markdown <file.md> [--ascii] — render fenced mermaid blocks, skip invalid ones
883
- - llms-txt — this document
884
- - init-agent [--dir .] [--force] — write AGENTS.md section, root skills/ bundle, and .mcp.json sample
885
-
886
- Exit codes: 0 ok, 2 arg error, 3 verify-failed, 4 internal.
887
-
888
- ## MCP tools
889
-
890
- Code Mode \`execute(code)\` (JavaScript in a node:vm sandbox with a typed
891
- mermaid.* SDK declaration) plus narrow helper tools: render_png and describe.
892
- render_png is offline.
893
-
894
- ## Output formats
895
-
896
- Agentic Mermaid outputs SVG, PNG, ASCII, Unicode, and JSON layout. Full capability list: ${formats}. SVG strict mode (security: 'strict') emits zero external-fetch
897
- references — safe for untrusted/agent-generated diagrams. See SECURITY.md.
898
-
899
- ## Diagram families
900
-
901
- All families parse, verify, render, round-trip: ${families}.
902
- Structured mutation (${cap.families.find(f => f.hasMutate)?.editPolicy}): ${structured.join(', ')}.
903
- Narrowers: ${narrowers}.
904
- State diagrams own a dedicated body (BUILD-19): narrow with asState; state-shaped ops apply (asFlowchart returns null on them).
905
- Source-level-only: ${cap.families.filter(f => !f.hasMutate).map(f => f.id).join(', ') || 'none — every renderable family ships structured mutation'}.
906
- Opaque-fallback bodies (unmodeled syntax) round-trip losslessly via preserved source (never silently dropped) and stay source-level only.
907
-
908
- ## Warning codes
909
-
910
- ${codes}
911
-
912
- ## Library
913
-
914
- \`import { parseMermaid, mutate, verifyMermaid, analyzeMermaid,
915
- analyzeMermaidSource, serializeMermaid, renderMermaidASCII,
916
- renderMermaidPNG, renderMermaidSVG, renderMermaidASCIIWithMeta,
917
- describeMermaid, asciiToMermaid, verifyNoExternalRefs,
918
- registerStyle, knownStyles, validateStyleSpec } from 'agentic-mermaid/agent'\`
919
-
920
- ## Styles
921
-
922
- Every render call accepts style: a name ('hand-drawn', 'excalidraw',
923
- 'pen-and-ink', 'freehand', 'watercolor', 'blueprint', 'tufte', or any theme
924
- name — a theme is a palette-only style), an inline JSON spec, or a stack
925
- merged left → right ({ style: ['hand-drawn', 'dracula'] }). seed re-rolls
926
- ink wobble, never layout — (source, style, seed) reproduces an image
927
- exactly. Custom styles are data: validateStyleSpec(json) checks untrusted
928
- records, registerStyle({ name, … }) makes them addressable by name.
929
- Authoring guide + quality rubric: docs/style-authoring.md.
930
-
931
- ## Docs
932
-
933
- - docs/README.md — documentation index and structure
934
- - Instructions_for_agents.md — canonical agent-use guide
935
- - AGENT_NATIVE.md — architecture/spec rationale
936
- - docs/features.md — current capability inventory
937
- - docs/api.md — library/CLI/MCP API reference, including SVG/PNG/ASCII output
938
- - docs/diagram-families.md — family examples and edit policy
939
- - docs/theming.md — themes, CSS variables, and Shiki compatibility
940
- - docs/style-authoring.md — styles: the composable look system (a theme is a palette-only style; stack names/specs; author custom styles as data records with the quality rubric)
941
- - docs/quality.md — determinism + "good looking" rubric
942
- - TODO.md — only active backlog
943
- - SECURITY.md — threat model + strict-mode guarantee
944
- - docs/agent-mutation-policy.md — structured-vs-source-level policy
945
- - docs/agent-api-cookbook.md — copy-pasteable library/CLI/MCP recipes
946
- - docs/mcp-code-mode-rationale.md — MCP surface rationale
947
- - docs/agent-workflow-examples.md — runnable MCP/CLI + agent-improvement examples
948
- - skills/ — agent-agnostic SKILL.md bundles for diagram workflow and live-editor development
949
- - skill-evals/ — skill-eval-harness manifest, fixtures, and benchmark instructions
950
- `
951
- }
952
-
953
- function cmdLlmsTxt(): number {
954
- process.stdout.write(buildLlmsTxt())
955
- return EXIT_OK
956
- }
957
-
958
- function cmdInitAgent(args: ParsedArgs, json: boolean): number {
959
- const dir = typeof args.flags.dir === 'string' ? resolve(args.flags.dir) : process.cwd()
960
- const force = Boolean(args.flags.force)
961
- const result = initAgentFiles({ dir, force })
962
- if (json) {
963
- process.stdout.write(JSON.stringify({ ok: true, ...result }) + '\n')
964
- return EXIT_OK
965
- }
966
- const rel = (p: string) => p.startsWith(dir) ? '.' + p.slice(dir.length) : p
967
- for (const p of result.written) process.stdout.write(` created ${rel(p)}\n`)
968
- for (const p of result.appended) process.stdout.write(` updated ${rel(p)}\n`)
969
- for (const p of result.skipped) process.stdout.write(` skipped ${rel(p)} (exists; use --force if applicable)\n`)
970
- process.stdout.write('\nNext: read AGENTS.md, connect the MCP server in .mcp.json, or run `am --agent-instructions`.\n')
971
- return EXIT_OK
972
- }
973
-
974
- // ---- Loop 12 M5 (#543): render-markdown — convert fenced blocks ------------
975
-
976
- export interface MarkdownBlockResult {
977
- index: number
978
- ok: boolean
979
- format?: string
980
- output?: string
981
- error?: { code: string; message: string }
982
- }
983
-
984
- /**
985
- * Extract ```mermaid fenced blocks from markdown and render each. A bad
986
- * diagram yields an { ok:false } entry and does NOT abort the rest (#543:
987
- * "skip invalid diagrams instead of failing the whole conversion").
988
- */
989
- export function renderMarkdownBlocks(md: string, format: 'svg' | 'ascii' = 'svg'): MarkdownBlockResult[] {
990
- const FENCE = /```mermaid[ \t]*\r?\n([\s\S]*?)\r?\n```/g
991
- const blocks: string[] = []
992
- for (const m of md.matchAll(FENCE)) blocks.push(m[1]!)
993
- return collectBatched(blocks, (src, i): MarkdownBlockResult => {
994
- try {
995
- const output = format === 'ascii' ? renderMermaidASCII(src, { useAscii: true }) : renderMermaidSVG(src)
996
- return { index: i, ok: true, format, output }
997
- } catch (e) {
998
- return { index: i, ok: false, error: { code: 'RENDER_FAILED', message: (e as Error).message } }
999
- }
1000
- }, 'MARKDOWN_BLOCK_ERROR').map((r, i) => r.ok ? r.value : { index: i, ok: false, error: r.error })
1001
- }
1002
-
1003
- function cmdRenderMarkdown(args: ParsedArgs): number {
1004
- const md = readSourceArg(args.positional[0])
1005
- const format = args.flags.ascii ? 'ascii' as const : 'svg' as const
1006
- const results = renderMarkdownBlocks(md, format)
1007
- process.stdout.write(JSON.stringify({ ok: true, blocks: results }) + '\n')
1008
- // Per-block failures don't fail the command (#543) — exit OK.
1009
- return EXIT_OK
1010
- }
1011
-
1012
- // ---- Loop 7 / A3.2: batch -------------------------------------------------
1013
-
1014
- interface BatchLine {
1015
- op: 'render' | 'verify' | 'parse' | 'serialize' | 'mutate'
1016
- source: string
1017
- options?: Record<string, unknown>
1018
- mutation?: AnyMutationOp
1019
- mutations?: AnyMutationOp[]
1020
- }
1021
-
1022
- interface BatchOutput {
1023
- ok: boolean
1024
- op?: string
1025
- data?: unknown
1026
- error?: { code: string; message: string }
1027
- }
1028
-
1029
- /**
1030
- * Execute a single batch line. Exported for tests; the CLI just shuttles
1031
- * lines into and out of this function.
1032
- */
1033
- export function runBatchLine(rawLine: string, lineIndex = 0): BatchOutput {
1034
- let parsed: BatchLine
1035
- try {
1036
- parsed = JSON.parse(rawLine) as BatchLine
1037
- } catch (e) {
1038
- return { ok: false, error: { code: 'INVALID_JSON', message: (e as Error).message } }
1039
- }
1040
- if (!parsed || typeof parsed !== 'object' || typeof parsed.op !== 'string') {
1041
- return { ok: false, error: { code: 'INVALID_PAYLOAD', message: 'missing op string' } }
1042
- }
1043
- const op = parsed.op
1044
- try {
1045
- switch (op) {
1046
- case 'render': {
1047
- const options = parsed.options ?? {}
1048
- const asAscii = Boolean((options as { ascii?: boolean }).ascii)
1049
- // #7540: auto-namespace SVG ids per batch line so the rendered
1050
- // diagrams can coexist on one HTML page without def-id collisions.
1051
- const out = asAscii
1052
- ? renderMermaidASCII(parsed.source)
1053
- : renderMermaidSVG(parsed.source, { idPrefix: `d${lineIndex}-` })
1054
- return { ok: true, op, data: asAscii ? { ascii: out } : { svg: out } }
1055
- }
1056
- case 'verify': {
1057
- const options = parsed.options as { suppress?: WarningCode[]; labelCharCap?: number } | undefined
1058
- const r = verifyMermaid(parsed.source, options ?? {})
1059
- return { ok: true, op, data: JSON.parse(JSON.stringify(r, replacer)) }
1060
- }
1061
- case 'parse': {
1062
- const r = parseMermaid(parsed.source)
1063
- if (!r.ok) { const env = parseErrorEnvelope(r.error); return { ok: false, op, error: env.error } }
1064
- return { ok: true, op, data: JSON.parse(JSON.stringify(toJsonSafe(r.value), replacer)) }
1065
- }
1066
- case 'serialize': {
1067
- // For batch, the line's `source` field is a JSON-stringified ValidDiagram
1068
- // (same shape as `am parse` emits). We re-hydrate it via synthesizeFromGraph.
1069
- let payload: unknown
1070
- try {
1071
- payload = JSON.parse(parsed.source)
1072
- } catch (e) {
1073
- return { ok: false, op, error: { code: 'INVALID_JSON', message: (e as Error).message } }
1074
- }
1075
- const r = synthesizeFromGraph(payload as Parameters<typeof synthesizeFromGraph>[0])
1076
- if (!r.ok) return { ok: false, op, error: { code: 'SYNTHESIZE_FAILED', message: JSON.stringify(r.error) } }
1077
- return { ok: true, op, data: { source: serializeMermaid(r.value) } }
1078
- }
1079
- case 'mutate': {
1080
- const ops = Array.isArray(parsed.mutations)
1081
- ? parsed.mutations
1082
- : parsed.mutation
1083
- ? [parsed.mutation]
1084
- : []
1085
- if (ops.length === 0) return { ok: false, op, error: { code: 'INVALID_OP', message: 'mutate batch line requires mutation or mutations[]' } }
1086
- const r = mutateSource(parsed.source, ops)
1087
- if (!r.ok) return { ok: false, op, error: { code: r.error.code, message: r.error.message } }
1088
- return { ok: true, op, data: { source: r.source, verify: JSON.parse(JSON.stringify(r.verify, replacer)) } }
1089
- }
1090
- default:
1091
- return { ok: false, op, error: { code: 'UNKNOWN_OP', message: `unknown op: ${op}` } }
1092
- }
1093
- } catch (e) {
1094
- return { ok: false, op, error: { code: 'INTERNAL', message: (e as Error).message } }
1095
- }
1096
- }
1097
-
1098
- function cmdBatch(): number {
1099
- const stdin = readSourceArg('-')
1100
- const lines = stdin.split('\n').filter(l => l.trim() !== '')
1101
- // Loop 9 M8: shared per-item iteration via collectBatched. Same scaffold
1102
- // as runWithJudge — see src/shared/batched.ts.
1103
- const results = collectBatched(lines, (line, i) => runBatchLine(line, i), 'BATCH_HANDLER_ERROR')
1104
- for (const r of results) {
1105
- if (r.ok) process.stdout.write(JSON.stringify(r.value) + '\n')
1106
- else process.stdout.write(JSON.stringify({ ok: false, error: r.error }) + '\n')
1107
- }
1108
- // Per-line errors don't abort the batch; the process always exits OK.
1109
- return EXIT_OK
1110
- }
1111
-
1112
- function toJsonSafe(d: ValidDiagram): unknown {
1113
- if (d.body.kind === 'flowchart') {
1114
- const g = d.body.graph
1115
- return {
1116
- kind: d.kind, meta: d.meta,
1117
- body: { kind: 'flowchart', graph: {
1118
- direction: g.direction,
1119
- nodes: Object.fromEntries(g.nodes),
1120
- edges: g.edges,
1121
- subgraphs: g.subgraphs,
1122
- // Preserve styling so `am parse | am serialize` is lossless.
1123
- classDefs: Object.fromEntries(g.classDefs),
1124
- classAssignments: Object.fromEntries(g.classAssignments),
1125
- nodeStyles: Object.fromEntries(g.nodeStyles),
1126
- linkStyles: Object.fromEntries([...g.linkStyles].map(([k, v]) => [String(k), v])),
1127
- } },
1128
- canonicalSource: d.canonicalSource,
1129
- }
1130
- }
1131
- return { kind: d.kind, meta: d.meta, body: d.body, canonicalSource: d.canonicalSource }
1132
- }