@senad-d/drawme 0.1.10 → 0.2.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.
package/src/workflow.ts CHANGED
@@ -1,4 +1,5 @@
1
- import type { DrawioInfo } from "./drawio";
1
+ import { FEATURE_MIN, INDEX_MIN, rendererUnavailable, supportsPageIndex, type DrawioInfo } from "./renderer";
2
+ import { MAX_STORYBOARD_FRAMES } from "./storyboard";
2
3
 
3
4
  /**
4
5
  * Maximum number of automatic source-correction retries across the visual
@@ -18,24 +19,22 @@ export interface WorkflowReferences {
18
19
  diagramTypes: string | null;
19
20
  xmlAuthoring: string | null;
20
21
  stylePresets: string | null;
21
- /** Only provided when the CLI supports Mermaid conversion (v30+). */
22
+ /** Only provided when the CLI supports Mermaid conversion. */
22
23
  mermaidAuthoring: string | null;
23
24
  }
24
25
 
26
+ export function rendererFeatures(cli: DrawioInfo): string {
27
+ const status = (supported: boolean | undefined) => supported ? "supported" : `unsupported (requires ${FEATURE_MIN} or later)`;
28
+ return `Mermaid import: ${status(cli.supportsMermaid)}; --layout: ${status(cli.supportsLayout)}.`;
29
+ }
30
+
25
31
  function cliStatus(cli: DrawioInfo): string {
32
+ const label = "1. **CLI status (already checked — do not call `drawio_check`)** — ";
26
33
  if (!cli.available) {
27
- return (
28
- "1. **CLI status (already checked — do not call `drawio_check`)** — the draw.io CLI is NOT available. " +
29
- "Still author and validate the `.drawio` XML, tell the user how to install draw.io (macOS: `brew install --cask drawio`; other platforms: https://github.com/jgraph/drawio-desktop/releases) or open the source, and skip conversion, layout, previews, visual review, and exports."
30
- );
34
+ return label + rendererUnavailable(cli) +
35
+ " Still author and validate the `.drawio` XML, share the recovery guidance and the source path, and skip conversion, layout, previews, visual review, and exports.";
31
36
  }
32
- const features = cli.supportsMermaid
33
- ? "Mermaid conversion and the ELK auto-layout pass are available (v30+)."
34
- : "This is below v30: hand-author XML; Mermaid conversion and ELK auto-layout are NOT available.";
35
- return (
36
- `1. **CLI status (already checked — do not call \`drawio_check\`)** — draw.io ${cli.version ?? "?"} at \`${cli.binary ?? "?"}\`. ` +
37
- features
38
- );
37
+ return `${label}draw.io ${cli.version ?? "?"} at \`${cli.binary ?? "?"}\`. ${rendererFeatures(cli)}`;
39
38
  }
40
39
 
41
40
  function referenceSection(title: string, path: string, content: string | null): string[] {
@@ -54,9 +53,9 @@ function referenceSection(title: string, path: string, content: string | null):
54
53
  * semantics, and regression), each answering explicit questions on its own
55
54
  * preview and each required to be clean before the next starts. Findings go
56
55
  * into a numbered ledger naming the affected cells, and every fix must be
57
- * verified by comparing the replacement preview against the previous image
58
- * (verdict: fixed / not fixed / regressed) rather than by trusting the XML
59
- * edit. The CLI check result and the topic references are embedded, so no
56
+ * verified on a fresh preview rather than by trusting the XML edit. Compare
57
+ * it with a previous image only when the tool reports one is comparable.
58
+ * The CLI check result and the topic references are embedded, so no
60
59
  * upfront tool calls or file reads are needed; only the rarely needed
61
60
  * troubleshooting reference stays on-demand. The preview tool result states
62
61
  * whether the review image is attached, so the review instructions branch on
@@ -64,7 +63,15 @@ function referenceSection(title: string, path: string, content: string | null):
64
63
  */
65
64
  export function drawmeWorkflow(description: string, refDir: string, cli: DrawioInfo, refs: WorkflowReferences): string {
66
65
  const quoted = description.replaceAll("\n", "\n> ");
67
- const mermaidPlanning = refs.mermaidAuthoring !== null || cli.supportsMermaid
66
+ const canSelectPage = supportsPageIndex(cli.version);
67
+ const previewPages = !cli.available ? "" : canSelectPage
68
+ ? " Every preview renders a single page, so for a multi-page file, export one preview per page with `pageIndex` and review every page (page-suffixed names, e.g. `<name>.review-p2-fit.png`)."
69
+ : ` Omit \`pageIndex\` to preview the first page when it is in scope. Visually reviewing later pages requires draw.io ${INDEX_MIN} or later; report those pages as not visually reviewed.`;
70
+ const finalPages = !cli.available ? "" : canSelectPage
71
+ ? " A final export renders a single page: for a multi-page file, export each page with `pageIndex` and a distinct `output` per page and format."
72
+ : ` Without \`pageIndex\`, export only the first page if it is in scope. Do not substitute the first page for a requested later page; report what could not be exported and advise upgrading to draw.io ${INDEX_MIN} or later.`;
73
+ const canConvert = cli.available && cli.supportsMermaid;
74
+ const mermaidPlanning = canConvert
68
75
  ? " If it is a standard type with no custom styling, prefer concise Mermaid converted with `drawio_from_mermaid`; see the Mermaid authoring reference below."
69
76
  : "";
70
77
  return [
@@ -75,28 +82,34 @@ export function drawmeWorkflow(description: string, refDir: string, cli: DrawioI
75
82
  `> ${quoted}`,
76
83
  "",
77
84
  "Produce a `.drawio` file and export it, following the workflow below. For anything that touches the draw.io CLI, use the DrawMe tools — do NOT shell out to `drawio` yourself. The references at the end of this message are already loaded: do not re-read those files.",
85
+ "Rendering is local, but the request and any attached preview or storyboard enter Pi’s model context and may be sent to a configured hosted provider. An exported file path alone does not mean an image was attached.",
78
86
  "",
79
87
  cliStatus(cli),
80
88
  "2. **Plan** — choose the diagram type, shapes, relationships, and layout direction (LR or TB). Plan generous spacing (200–350px between shapes) and do NOT fix page dimensions up front: the canvas is fitted to the finished content later with `drawio_fit_canvas`. For a specific type (ERD, UML class, sequence, C4, architecture, ML/DL, flowchart, SysML, BPMN, network, swimlane), follow the diagram-types reference below. Pick one style preset from the style presets reference below: Light unless the user explicitly asks for a dark theme or for multiple colors (Dark, Multi-color, or both). Never choose Dark or Multi-color on your own. Set the theme's page background and use its colors, edge styles, and typography for every cell; take only structural style keys from the diagram-types reference, not its colors. If the request asks for movement, plan an animated SVG: a `drawio_animate` motion story (entrances, connector draw-ins, travelling dots, highlights, dimming) following the preset reference's motion design section, persistent connector flow for continuous direction, or both; use a portable page sequence only when draw.io's own viewer must play the animation. Also plan a static PNG fallback unless the user explicitly asks for SVG only." +
81
89
  mermaidPlanning,
82
- "3. **Author** — for hand-written XML, follow the XML authoring reference below. Keep XML uncompressed; never reuse ids `0`/`1`; give every edge `<mxGeometry relative=\"1\" as=\"geometry\"/>`; use `drawio_shapesearch` rather than guessing exact vendor/UML/BPMN/cloud styles. For animation, author the complete static diagram first and add motion afterwards with `drawio_animate`; do not hand-write page animation JSON for effects it covers. Connector flow stays in edge styles. Never hide a cell with `visible=0` when the animation needs to reveal it. For large graphs (>~15 nodes) on v30+, hand-write nodes and use `drawio_layout`. Space elements generously rather than packing them, then run `drawio_fit_canvas` after authoring — and again after any Mermaid conversion or layout — so the page wraps the content with a comfortable margin. Treat every write, edit, Mermaid conversion, layout, and canvas-fit result as a source edit.",
83
- "4. **Validate after every source edit** — call `drawio_validate` immediately after authoring and after every later XML edit, Mermaid conversion, or layout operation. Fix all errors before previewing. Every warning must be either fixed or recorded explicitly as reviewed and acceptable with a reason; unresolved or unreviewed warnings block final export. For animated SVG, unsupported page effects are blocking rather than acceptable because final animation verification will reject them.",
84
- "5. **Visual review — three focused passes, then a holistic confirmation** — run this once authoring and validation are clean. Export previews with `drawio_export` mode `\"preview\"`; every preview renders a single page, so for a multi-page file, export one preview per page with `pageIndex` and review every page (page-suffixed names, e.g. `<name>.review-p2-fit.png`). The result text states whether the preview image is attached; follow the matching path:",
90
+ "3. **Author** — for hand-written XML, follow the XML authoring reference below. Keep XML uncompressed; never reuse ids `0`/`1`; give every edge `<mxGeometry relative=\"1\" as=\"geometry\"/>`; use `drawio_shapesearch` rather than guessing exact vendor/UML/BPMN/cloud styles. For animation, author the complete static diagram first and add motion afterwards with `drawio_animate`; do not hand-write page animation JSON for effects it covers. Connector flow stays in edge styles. Never hide a cell with `visible=0` when the animation needs to reveal it. For large graphs (>~15 nodes), hand-write nodes and use `drawio_layout` only if the CLI supports it. Space elements generously rather than packing them, then run `drawio_fit_canvas` after authoring — and again after any Mermaid conversion or layout — so the page wraps the content with a comfortable margin. Treat every write, edit, Mermaid conversion, layout, and canvas-fit result as a source edit.",
91
+ "4. **Validate after every source edit** — call `drawio_validate` immediately after authoring and after every later XML edit, Mermaid conversion, or layout operation. Fix all errors before previewing. An incomplete report is not clean: address the reported limit or read/parse problem and validate again before proceeding. Every warning must be either fixed or recorded explicitly as reviewed and acceptable with a reason; unresolved or unreviewed warnings block final export. For animated SVG, unsupported page effects are blocking rather than acceptable because final animation verification will reject them.",
92
+ "5. **Visual review — three focused passes, then a holistic confirmation** — run this once authoring and validation are clean. Export previews with `drawio_export` mode `\"preview\"`." +
93
+ previewPages + " The result text states whether the preview image is attached; follow the matching path:",
85
94
  " - **Image attached** — run the four passes below in order. Do not start the next pass until every finding of the current one is verified **fixed** in a fresh render or explicitly accepted with a reason. For each pass: export its preview, write a structured critique that hunts for defects — do not summarize or admire the diagram — answer the pass's questions explicitly (a bare \"yes\" is not an answer; point at the evidence in the image), and record findings in one numbered ledger kept for the rest of the run: `F1, F2, …: pass / severity / affected cell ids / what is visibly wrong and where in the image / planned fix` (pick fixes from the defect→fix recipes in the XML authoring reference). The critique's job is to narrow every problem down to specific cells so the fix step can be surgical.",
86
95
  " 1. **Pass 1 — fit and sizing** (`<name>.review-fit.png`) answers: does the diagram fit its page, and does the canvas or any element need resizing? Hunt: content touching or crossing a page edge; one outer margin visibly thinner than the others; large empty regions or a page far larger than its content; elements too small for their labels — text touching or crossing its own shape border, clipped or mid-word truncated; a smallest label you cannot comfortably read at full-diagram scale (tighten the canvas with `drawio_fit_canvas`, split content across pages, or simplify the layout — never judge what you cannot read, and never treat \"too small to tell\" as a pass).",
87
96
  " 2. **Pass 2 — element placement** (`<name>.review-layout.png`) answers: is every element positioned correctly, and is there a visibly better arrangement? Hunt: shapes whose borders touch or overlap; two labels touching or overlapping each other; label text lying on top of any line or unrelated shape; rows/columns that drift out of alignment; uneven gaps between peers; children poking out of their container or crowding its title; related elements far apart while unrelated ones sit adjacent. Improve, not only repair: if moving an element would shorten edges, remove crossings, or make the arrangement symmetric, record that as a finding too.",
88
97
  " 3. **Pass 3 — connections** (`<name>.review-connectors.png`) answers: is every connection correct, cleanly routed, symmetric where the layout is symmetric, and anchored to the middle of the element side it faces wherever possible? Trace every edge from source to target and check it against the plan — right source, right target, right direction, right label. Hunt: an endpoint floating off its shape or plunging deep into it; an edge entering at an odd corner when a side-center anchor is available (pin `exitX`/`exitY`/`entryX`/`entryY` to the facing side's center, spreading evenly only when several edges share one side); mirrored branches routed asymmetrically; an arrowhead hidden by a shape or crushed into a bend; an edge passing through a shape it does not connect; parallel edges stacked on top of each other; an edge label sitting on its line so the text is struck through, or closer than about half a text-height to any line; crossings a reroute through a free corridor would remove.",
89
- " Heed `drawio_validate` anchor warnings literally: re-pin an exit or entry to the suggested facing side before adding waypoints. Treat predicted route-through observations as focused preview-review hints, not proof of draw.io's rendered route; add waypoints or move a shape only when the preview confirms the obstruction.",
90
- " 4. **Pass 4 — typography, semantics, and regression** (`<name>.review.png`) is the holistic confirmation. Read every label word for word — a label you cannot fully read is itself a finding; check text contrast against fills; confirm every requested component and relationship is present, pointing the right way, with the right label; check hierarchy, grouping, and that legend entries match the colors actually used; apply the type's `Review:` checklist from the diagram-types reference; and re-check passes 1–3 for regressions. For animation, cross-check the sequence order, cell ids, durations, direction, loop setting, and reduced-motion/static fallback structurally; the PNG preview is intentionally static and must not be presented as temporal playback proof. Review the motion itself on the `drawio_animate` storyboard after this pass. Retain this image (every page, for a multi-page file) for the final report.",
91
- " - **Image NOT attached** — the current model cannot view images. Skip the visual passes: do not describe or judge renders; review structurally instead by cross-checking `drawio_validate` findings and a `drawio_explain` read-back against the user's request. Keep the latest `<name>.review.png` on disk so the user can view it, and state plainly in the summary that rendered inspection was skipped.",
92
- "6. **Fix and verify before the next pass** — resolve a pass's findings with targeted source edits: after each edit, validate, then re-export the same pass preview (for a multi-page file, the page the finding is on). The superseded preview file is deleted from disk, but its image is still visible earlier in this conversation: compare the new image against it at each addressed finding's location and record a verdict — **fixed** (the defect is gone in the new render), **not fixed** (still visible), or **regressed** (the edit introduced a new defect; log it as a new numbered finding). Never mark a finding fixed because the XML changed — only because the new image shows it fixed. When elements overlap, are cramped, clipped, or short on margin, never shrink or squeeze elements to fit the page — move them apart, then run `drawio_fit_canvas` to enlarge the canvas around them. A pass is complete only when all of its findings are fixed or explicitly accepted, and every pass must be complete before final export. If the correction limit is reached mid-pass, finish the remaining passes as inspection-only and report their findings as unresolved. Each successful preview export automatically removes the previous preview file for the same source, so only the latest review image remains.",
98
+ " Heed `drawio_validate` anchor warnings literally: re-pin an exit or entry to the suggested facing side before adding waypoints. An unchecked auto-route warning means validation cannot inspect the rendered route, not that it found a crossing. Treat predicted route-through observations as focused preview-review hints, not proof of draw.io's rendered route; add waypoints or move a shape when the preview confirms the obstruction.",
99
+ " 4. **Pass 4 — typography, semantics, and regression** (`<name>.review.png`) is the holistic confirmation. Read every label word for word — a label you cannot fully read is itself a finding; check text contrast against fills; confirm every requested component and relationship is present, pointing the right way, with the right label; check hierarchy, grouping, and that legend entries match the colors actually used; apply the type's `Review:` checklist from the diagram-types reference; and re-check passes 1–3 for regressions. For animation, cross-check the sequence order, cell ids, durations, direction, loop setting, and reduced-motion/static fallback structurally; the PNG preview is intentionally static and must not be presented as temporal playback proof. Use the `drawio_animate` storyboard, if attached, to check motion order and visibility after this pass. Record the findings for each page in the final report; a transcript attachment is not a retained file.",
100
+ " - **Image NOT attached** — if the current model cannot view images or its support is unknown, skip the visual passes. Do not describe or judge renders; review structurally by cross-checking `drawio_validate` findings and a `drawio_explain` read-back against the user's request. State plainly that rendered inspection was skipped and share the final export path for the user to view.",
101
+ "6. **Fix and verify before the next pass** — resolve a pass's findings with targeted source edits: after each edit, validate, then re-export the same pass preview on the page the finding is on, if the renderer can select it. Compare at each addressed location only if the result reports a comparable prior attachment still in context; otherwise inspect the fresh image against the written findings without claiming a before/after comparison. Record a verdict — **fixed** (the defect is gone in the new render), **not fixed** (still visible), or **regressed** (the edit introduced a new defect; log it as a new numbered finding). Never mark a finding fixed because the XML changed — only because the new image shows it fixed. When elements overlap, are cramped, clipped, or short on margin, never shrink or squeeze elements to fit the page — move them apart, then run `drawio_fit_canvas` to enlarge the canvas around them. A pass is complete only when all of its findings are fixed or explicitly accepted, and every pass must be complete before final export. If the correction limit is reached mid-pass, finish the remaining passes as inspection-only and report their findings as unresolved.",
102
+ " Preview cleanup is process-local: a successful preview or final export may retire tracked preview files for this source, including other pages. It does not reconstruct tracking after restart. A file being removed or replaced tells you nothing about whether an earlier attachment is still in context. Report cleanup warnings; do not delete previews yourself or promise that their paths remain.",
93
103
  `7. **Correction limit** — pass inspection previews (the first preview of each pass) do not count against the limit. Across the whole review, allow at most ${AUTOMATIC_CORRECTION_LIMIT} correction retries; one retry is one targeted source-edit → \`drawio_validate\` → replacement-preview cycle, whatever its verdict. Count retries explicitly. If the limit is reached with a finding unresolved, stop automatic editing, keep the best validated state, and continue to final export — name the unresolved finding, its pass, and its last verdict plainly in the final report instead of looping or waiting for input.`,
94
104
  "8. **No human gate** — the run is fully autonomous: once started, never pause to ask for approval, confirmation, or feedback. When pass 4 is clean (or the correction limit was reached), proceed directly to final export. If the user interrupts with feedback mid-run, append it to the ledger as new numbered findings: targeted edit, validate, before/after confirmation on the relevant pass preview, a fresh pass-4 holistic preview, then continue to export.",
95
- "9. **Final export** — immediately after pass 4 is clean (or the correction limit was reached), call `drawio_export` with `mode: \"final\"` for each requested format (default PNG; SVG/PDF/JPG on request). When motion was requested, the primary deliverable is a `drawio_animate` call with the planned steps. Check its storyboard frame by frame against the planned story; when a frame shows the wrong order or visibility, fix the steps and call it again (each call counts as one correction retry). For a page whose only motion is connector flow or a native page sequence, call `drawio_export` with `animated: true` and `format: \"svg\"` instead. Read the result and report animation as successful only when it says `Animation verified`. Also export the planned static PNG fallback unless the user requested SVG only. Animated mode never supports preview, PNG, PDF, or JPG. A final export renders a single page: for a multi-page file, export each page with `pageIndex` and a distinct `output` per page and format. The first successful final export removes the one remaining latest preview for the same source; do not delete previews yourself or report it as a retained output. Report the `.drawio` source and every final path, whether animation verification passed, retained reviewed warnings, any unresolved finding from the correction limit, and cleanup warnings. Offer `drawio_open` for fine-tuning afterwards.",
105
+ "9. **Final export** — immediately after pass 4 is clean (or the correction limit was reached), call `drawio_export` with `mode: \"final\"` for each requested format (default PNG; SVG/PDF/JPG on request). When motion was requested, use `drawio_animate` with the planned steps; to reuse stored DrawMe motion, give it `input` and omit `steps`. Use at most 200 steps; hold, stagger, and wait duration are 0–60000 ms, visual duration is greater than 0 and at most 60000 ms, and the timeline before hold is at most 300000 ms. A dimmed visible cell can fade back in; a fully visible cell cannot enter again. " +
106
+ `The storyboard samples up to ${MAX_STORYBOARD_FRAMES} visual batch ends, keeping first and last; parallel steps share a frame and waits alone add no frame. If attached, check the storyboard frame by frame against the planned story; if not, check the step order structurally and report its file path without claiming inspection. When a frame shows the wrong order or visibility, fix the steps and call again (each retry counts against the correction limit). ` +
107
+ "For a page whose only motion is connector flow or a native page sequence, call `drawio_export` with `animated: true` and `format: \"svg\"` instead. Read the result and report animation as successful only when it says `Animation verified`. Also export the planned static PNG fallback unless the user requested SVG only. Animated mode never supports preview, PNG, PDF, or JPG." +
108
+ finalPages + " Report the `.drawio` source and every final path, whether animation verification passed, retained reviewed warnings, any unresolved finding from the correction limit, and cleanup warnings. Offer `drawio_open` for fine-tuning afterwards.",
96
109
  "",
97
- "Failure handling: several DrawMe tools report failures as a text result beginning with `Export failed`, `Layout failed`, `Mermaid conversion failed`, `Fit canvas failed`, `Explain failed`, or `Open failed` rather than a tool error — always read the result text and treat those as failures. If export fails, read `" +
110
+ "Failure handling: several DrawMe tools report failures as a text result beginning with `Export failed:`, `Animate failed:`, `Fit canvas failed:`, `Mermaid conversion failed:`, `Layout failed:`, `Explain failed:`, or `Open failed:` rather than a tool error — always read the result text and treat those as failures. If export fails, read `" +
98
111
  refDir +
99
- "/troubleshooting.md` (the one reference kept on-demand). On draw.io below v30, use hand-authored XML instead of Mermaid conversion or ELK layout, but keep validation, the pass-based review, requested-format handling, and final cleanup unchanged.",
112
+ "/troubleshooting.md` (the one reference kept on-demand). If the CLI lacks Mermaid or layout support, hand-author and place the XML instead; keep validation, pass-based review, and final exports when the renderer is available.",
100
113
  "",
101
114
  "---",
102
115
  "",
@@ -105,8 +118,6 @@ export function drawmeWorkflow(description: string, refDir: string, cli: DrawioI
105
118
  ...referenceSection("diagram types", `${refDir}/diagram-types.md`, refs.diagramTypes),
106
119
  ...referenceSection("XML authoring", `${refDir}/xml-authoring.md`, refs.xmlAuthoring),
107
120
  ...referenceSection("style presets", `${refDir}/style-presets.md`, refs.stylePresets),
108
- ...(refs.mermaidAuthoring !== null || cli.supportsMermaid
109
- ? referenceSection("Mermaid authoring", `${refDir}/mermaid-authoring.md`, refs.mermaidAuthoring)
110
- : []),
121
+ ...(canConvert ? referenceSection("Mermaid authoring", `${refDir}/mermaid-authoring.md`, refs.mermaidAuthoring) : []),
111
122
  ].join("\n");
112
123
  }