flowfig 0.4.0 → 0.5.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/README.md CHANGED
@@ -16,18 +16,6 @@
16
16
 
17
17
  </div>
18
18
 
19
- An agent with the flowfig instructions made faithful, checked diagrams more often than the same agent without them:
20
-
21
- | Criterion | Agent without flowfig instructions | Agent with flowfig instructions |
22
- | --------------------------------------------------- | ---------------------------------- | ---------------------------------------------- |
23
- | Diagram faithful to the code (no invented part) | 7 of 8 | 8 of 8 |
24
- | Right diagram form for the task | 5 of 7 | 7 of 7 |
25
- | Passes `flowfig check --strict` | 5 of 7 | 6 of 6 |
26
- | Right action (draws, declines or splits) | 6 of 8 | 7 of 8 |
27
- | Held-out tasks (not used to write the instructions) | – | 2 of 4 pass all 6 criteria; 2 of 4 pass 4 of 6 |
28
-
29
- [How we measured](#how-we-measured).
30
-
31
19
  ## Use it
32
20
 
33
21
  Set up your repo:
@@ -117,7 +105,6 @@ and the cost of the run. `draw` needs Claude Code on the machine and a login. `d
117
105
  - [Use from Node](#use-from-node)
118
106
  - [Use with your coding agent](#use-with-your-coding-agent)
119
107
  - [What flowfig does not draw](#what-flowfig-does-not-draw)
120
- - [How we measured](#how-we-measured)
121
108
  - [License](#license)
122
109
  - [Development](#development)
123
110
 
@@ -314,6 +301,7 @@ The last line gives the counts of the parts of the figure. Compare the counts wi
314
301
  | `low-contrast` | error | A text and background pair below 4.5:1, in the light, dark or custom theme. |
315
302
  | `empty-step` | warning | A step with no beats. |
316
303
  | `small-text` | warning | At the page width, the smallest text is below the minimum size. |
304
+ | `lane-end-block` | warning | In wrapped lanes, an edge ends at a lane that no block on its side shows. |
317
305
  | `font-estimated` | warning | `theme.font` is set. The SVG check estimates text width for the system font. |
318
306
  | `color-not-checked` | warning | A color that the check cannot read, so its contrast is not checked. |
319
307
 
@@ -321,7 +309,7 @@ The last line gives the counts of the parts of the figure. Compare the counts wi
321
309
  | ----------------- | ---------------------------------------------------------------------------------------------------------- |
322
310
  | `--strict` | Every warning becomes an error. |
323
311
  | `--json` | Print the findings as a JSON array, for scripts. Each finding has `rule`, `severity`, `ids` and `message`. |
324
- | `--width <px>` | The page width for `small-text`. Default: 830. |
312
+ | `--width <px>` | The page width for `small-text` and for the lanes wrap. Default: 830. |
325
313
  | `--min-text <px>` | The smallest text size the reader must get. Default: 10. |
326
314
 
327
315
  The exit code is 0 with no errors, 1 with one or more errors, and 2 for bad use, such as a missing input, an unknown flag, or a `--width` value that is not a number.
@@ -515,22 +503,6 @@ flowfig draws parts, the messages between the parts, and their order. flowfig dr
515
503
  and converts a Mermaid `gantt` to it. flowfig does not draw class diagrams, ER diagrams, charts of numbers or mind maps. Use Mermaid
516
504
  or a chart library for those.
517
505
 
518
- ## How we measured
519
-
520
- We ran an evaluation before this release: 47 coding-agent runs, with Claude Sonnet as the agent. The runs covered 12 tasks in 5
521
- test repos: a TypeScript login API, a Python ETL pipeline, an order state machine, a 20-service platform and a mixed CLI repo.
522
- The agent ran without the flowfig instructions and with them. An Opus grader scored each run against an answer key.
523
-
524
- 4 tasks were held out: they shaped no instruction. On the held-out tasks, 2 of 4 runs passed all 6 criteria. The other 2 passed
525
- 4 of 6: one drew an edge from the wrong box, and one reply stated a runtime effect wrongly.
526
-
527
- A first draft of the instructions scored worse than no instructions: 5 of 8 faithful. We rewrote the instructions from the
528
- failures and tested them again. The "with" column comes from the version that we tested on all 8 tasks. The shipped instructions
529
- add two refinements: the scope of a repo with many flows, and each edge taken from the caller in the code. 9 more runs tested
530
- the two refinements on the tasks that still failed.
531
-
532
- The evaluation also found 3 faults in flowfig itself. We fixed all 3 before this release.
533
-
534
506
  ## License
535
507
 
536
508
  MIT. See [LICENSE](LICENSE).
package/dist/check.js CHANGED
@@ -1,6 +1,7 @@
1
1
  // The rules behind `flowfig check`. They never draw and never measure: a renderer gives a Scene, and these read it. So one rule set
2
2
  // covers the SVG (estimated text) and the React player (measured text), and any later view that gives a scene.
3
3
  import { DARK, LIGHT, ON_ACCENT, TONES, edgeId, isGroup, dayOf, isLanesLayout, validAt, laneColumns, nodes, str, toBeat, } from './model.js';
4
+ import { crosses } from './geometry.js';
4
5
  import { textWidth } from './text.js';
5
6
  import { owners, parseSource } from './source.js';
6
7
  const err = (rule, ids, message) => ({ rule, severity: 'error', ids, message });
@@ -111,6 +112,7 @@ const at = ([p0, p1, p2, p3], t) => {
111
112
  const [a, b, c, d] = [u * u * u, 3 * u * u * t, 3 * u * t * t, t * t * t];
112
113
  return { x: a * p0.x + b * p1.x + c * p2.x + d * p3.x, y: a * p0.y + b * p1.y + c * p2.y + d * p3.y };
113
114
  };
115
+ const lerp = (p, q, t) => ({ x: p.x + (q.x - p.x) * t, y: p.y + (q.y - p.y) * t });
114
116
  // The margins keep a touch from counting: an edge leaves along a border, and pills sit edge to edge.
115
117
  const inside = (p, r, pad) => p.x > r.x + pad && p.x < r.x + r.w - pad && p.y > r.y + pad && p.y < r.y + r.h - pad;
116
118
  const overlap = (a, b, pad) => a.x + pad < b.x + b.w - pad && b.x + pad < a.x + a.w - pad && a.y + pad < b.y + b.h - pad && b.y + pad < a.y + a.h - pad;
@@ -127,11 +129,52 @@ export function checkScene(scene, { width = 830, minText = 10 } = {}) {
127
129
  for (const e of scene.edges) {
128
130
  if (e.behind)
129
131
  continue;
130
- const pts = Array.from({ length: 33 }, (_, i) => at(e.curve, i / 32));
132
+ const pts = e.pts
133
+ ? e.pts.slice(1).flatMap((q, k) => Array.from({ length: 17 }, (_, i) => lerp(e.pts[k], q, i / 16)))
134
+ : Array.from({ length: 33 }, (_, i) => at(e.curve, i / 32));
131
135
  for (const b of scene.boxes)
132
136
  if (b.id !== e.from && b.id !== e.to && pts.some((p) => inside(p, b.rect, 2)))
133
137
  out.push(err('edge-crosses-box', [e.id, b.id], `edge "${e.id}" passes through box "${b.id}"`));
134
138
  }
139
+ // A stub pill (the label of an edge with `pts`) must not sit on another edge's path.
140
+ const pills = scene.edges.filter((e) => e.pts && e.label);
141
+ const under = new Set();
142
+ for (const e of scene.edges) {
143
+ if (e.behind)
144
+ continue;
145
+ const pts = e.pts
146
+ ? e.pts.slice(1).flatMap((q, k) => Array.from({ length: 17 }, (_, i) => lerp(e.pts[k], q, i / 16)))
147
+ : Array.from({ length: 33 }, (_, i) => at(e.curve, i / 32));
148
+ for (const f of pills)
149
+ if (f.id !== e.id && !under.has(e.id + ' ' + f.id) && pts.some((p) => inside(p, f.label, 2))) {
150
+ under.add(e.id + ' ' + f.id);
151
+ out.push(err('label-overlap', [e.id, f.id], `edge "${e.id}" passes under the pill of edge "${f.id}"`));
152
+ }
153
+ }
154
+ // A stub line (a segment of an edge with `pts`) must not cross the path of another edge.
155
+ const path = (e) => e.pts
156
+ ? e.pts.slice(1).flatMap((q, k) => Array.from({ length: 17 }, (_, i) => lerp(e.pts[k], q, i / 16)))
157
+ : Array.from({ length: 33 }, (_, i) => at(e.curve, i / 32));
158
+ const stubs = scene.edges.filter((e) => e.pts && e.pts.length > 1);
159
+ const hit = new Set();
160
+ for (const f of stubs)
161
+ for (const e of scene.edges) {
162
+ if (e.behind || e === f || (e.id === f.id && e.pts) || hit.has(f.id + ' ' + e.id))
163
+ continue;
164
+ const p = path(e);
165
+ if (f.pts.slice(1).some((a, k) => p.slice(1).some((b, i) => crosses(f.pts[k], a, p[i], b)))) {
166
+ hit.add(f.id + ' ' + e.id);
167
+ out.push(warn('stub-crosses-edge', [f.id, e.id], `the stub of edge "${f.id}" crosses edge "${e.id}"`));
168
+ }
169
+ }
170
+ // A stub pill sits inside the band of its box: a pill across a band border reads as part of two lanes.
171
+ for (const f of pills)
172
+ for (const l of scene.lanes ?? []) {
173
+ const [p, r] = [f.label, l.rect];
174
+ const inside = p.x >= r.x && p.x + p.w <= r.x + r.w && p.y >= r.y && p.y + p.h <= r.y + r.h;
175
+ if (!inside && overlap(p, r, 0))
176
+ out.push(err('label-overlap', [f.id], `the pill of edge "${f.id}" crosses the border of lane "${l.id}"`));
177
+ }
135
178
  const labeled = scene.edges.filter((e) => e.label);
136
179
  labeled.forEach((e, i) => {
137
180
  for (const f of labeled.slice(i + 1))
package/dist/cli.js CHANGED
@@ -352,7 +352,7 @@ if (errors)
352
352
  process.exit(1);
353
353
  const dest = out ?? (input === '-' ? 'figure.svg' : input.replace(/\.[^./\\]+$/, '') + '.svg');
354
354
  // The spec rides along in <metadata>: an SVG is then its own source, and no JSON has to be kept.
355
- const withSpec = svgWithSpec(props);
355
+ const withSpec = svgWithSpec(props, opts);
356
356
  writeFileSync(dest, withSpec);
357
357
  console.log(`${dest} — ${(withSpec.length / 1024).toFixed(1)} kB`);
358
358
  if (open) {
@@ -9,11 +9,21 @@ export type Pt = {
9
9
  x: number;
10
10
  y: number;
11
11
  };
12
+ /** A cross-block edge of wrapped lanes: the two drawn stubs, their pills, and their points for `check`. `d` then holds both stubs,
13
+ * so a packet runs the source stub and jumps to the target stub. */
14
+ export type Stub = {
15
+ parts: [string, string];
16
+ pills: [Rect, Rect];
17
+ pts: [Pt[], Pt[]];
18
+ short?: true;
19
+ tight: [boolean, boolean];
20
+ };
12
21
  export type Routed = {
13
22
  id: string;
14
23
  d: string;
15
24
  mid: Pt;
16
25
  curve: [Pt, Pt, Pt, Pt];
26
+ stub?: Stub;
17
27
  };
18
28
  type Around = 'above' | 'below';
19
29
  export declare function route(edges: {
@@ -23,5 +33,11 @@ export declare function route(edges: {
23
33
  around?: Around;
24
34
  sides?: [Side, Side];
25
35
  elbow?: boolean;
26
- }[], rects: Record<string, Rect>, tips?: Set<string>, avoid?: Rect[]): Routed[];
36
+ stub?: number[];
37
+ bands?: [Rect | undefined, Rect | undefined];
38
+ labelW?: number;
39
+ }[], rects: Record<string, Rect>, tips?: Set<string>, avoid?: Rect[], // what an elbow's vertical run and a stub pill must not cross (the timeline's outside labels; the boxes and gutters of lanes)
40
+ area?: Rect): Routed[];
41
+ /** True if the segment a-b crosses the segment c-d. The ends of a-b are trimmed by 1.5 px, so a touch at a box side does not count. */
42
+ export declare function crosses(a: Pt, b: Pt, c: Pt, d: Pt): boolean;
27
43
  export {};
package/dist/geometry.js CHANGED
@@ -1,5 +1,12 @@
1
+ import { STUB } from './model.js';
1
2
  const cx = (r) => r.x + r.w / 2;
2
3
  const cy = (r) => r.y + r.h / 2;
4
+ /** A point on the cubic Bézier at `t`, as `check` samples an edge. */
5
+ const bezier = ([p0, p1, p2, p3], t) => {
6
+ const u = 1 - t;
7
+ const [a, b, c, d] = [u * u * u, 3 * u * u * t, 3 * u * t * t, t * t * t];
8
+ return { x: a * p0.x + b * p1.x + c * p2.x + d * p3.x, y: a * p0.y + b * p1.y + c * p2.y + d * p3.y };
9
+ };
3
10
  // Turns edges between measured boxes into curved SVG paths.
4
11
  // Boxes stacked on top of each other connect bottom->top, otherwise side->side.
5
12
  // Several edges leaving the same side of a box are spread out so they don't overlap,
@@ -7,7 +14,11 @@ const cy = (r) => r.y + r.h / 2;
7
14
  // `elbow` draws a right-angle path, from a right end to a left end: its four curve points are the corners.
8
15
  // `sides` fixes the two sides an edge uses (a timeline uses right to left).
9
16
  // `around` makes an edge leave and enter from the top or bottom, arcing over whatever sits between.
10
- export function route(edges, rects, tips = new Set(), avoid = []) {
17
+ // `bands` (with `stub`) are the lane bands of the source and of the target: each pill stays inside its band, 4 px clear of the border.
18
+ // `labelW` is the width of an edge's label pill: a stub pill keeps clear of it.
19
+ // `stub` (wrapped lanes: the source pill width, the target pill width, and the width of a shorter source pill) draws a short stub from the source to a pill, and from a second pill into the target.
20
+ export function route(edges, rects, tips = new Set(), avoid = [], // what an elbow's vertical run and a stub pill must not cross (the timeline's outside labels; the boxes and gutters of lanes)
21
+ area) {
11
22
  const picks = [];
12
23
  for (const e of edges) {
13
24
  const a = rects[e.from], b = rects[e.to];
@@ -16,17 +27,19 @@ export function route(edges, rects, tips = new Set(), avoid = []) {
16
27
  const stacked = a.x < b.x + b.w && b.x < a.x + a.w;
17
28
  const [sa, sb] = e.sides
18
29
  ? e.sides
19
- : e.around
20
- ? e.around === 'above'
21
- ? ['t', 't']
22
- : ['b', 'b']
23
- : stacked
24
- ? a.y < b.y
25
- ? ['b', 't']
26
- : ['t', 'b']
27
- : a.x < b.x
28
- ? ['r', 'l']
29
- : ['l', 'r'];
30
+ : e.stub
31
+ ? ['r', 'l']
32
+ : e.around
33
+ ? e.around === 'above'
34
+ ? ['t', 't']
35
+ : ['b', 'b']
36
+ : stacked
37
+ ? a.y < b.y
38
+ ? ['b', 't']
39
+ : ['t', 'b']
40
+ : a.x < b.x
41
+ ? ['r', 'l']
42
+ : ['l', 'r'];
30
43
  picks.push({ ...e, a, b, sa, sb });
31
44
  }
32
45
  // For every (box, side), list the edge ends that sit there, sorted by where the other end is.
@@ -67,8 +80,131 @@ export function route(edges, rects, tips = new Set(), avoid = []) {
67
80
  const [s, c1, c2, e] = curve;
68
81
  return { id, d: `M ${s.x} ${s.y} C ${c1.x} ${c1.y}, ${c2.x} ${c2.y}, ${e.x} ${e.y}`, mid, curve };
69
82
  };
70
- return picks.map((p) => {
83
+ // Stub pills are placed after the other edges. Each pill keeps clear of `avoid`, of the edge labels, of the pills and stubs
84
+ // before it, and of every edge path (sampled as `check` samples it).
85
+ const pills = [];
86
+ const paths = [];
87
+ // The same samples as segments: a stub line must not cross one.
88
+ const runs = [];
89
+ const track = (pts) => {
90
+ paths.push(...pts);
91
+ pts.slice(1).forEach((q, i) => runs.push([pts[i], q]));
92
+ };
93
+ const inBand = (r, b) => !b || (r.x >= b.x + 4 && r.x + r.w <= b.x + b.w - 4 && r.y >= b.y + 4 && r.y + r.h <= b.y + b.h - 4);
94
+ const clear = (r, band) => inBand(r, band) &&
95
+ (!area || (r.x >= area.x && r.x + r.w <= area.x + area.w && r.y >= area.y && r.y + r.h <= area.y + area.h)) &&
96
+ ![...avoid, ...pills].some((q) => r.x < q.x + q.w + 2 && q.x < r.x + r.w + 2 && r.y < q.y + q.h + 2 && q.y < r.y + r.h + 2) &&
97
+ !paths.some((q) => q.x > r.x - 2 && q.x < r.x + r.w + 2 && q.y > r.y - 2 && q.y < r.y + r.h + 2);
98
+ const one = (p) => {
71
99
  const s = anchor.get(p.id + ':s'), e = anchor.get(p.id + ':e');
100
+ if (p.stub) {
101
+ // The source pill goes right of the source and the target pill left of the target, at the nearest clear place: it slides
102
+ // away from the box in 8 px steps, and up or down inside the band in 4 px steps. The stub then runs on a slant. The last
103
+ // places are below and above the box. A place is clear if the pill and its stub keep clear of everything, and the pill stays
104
+ // inside its band. If no place is clear, the source pill tries its shorter text. If no place is clear then, the first place
105
+ // stays and `check` reports it.
106
+ const [ow, iw, sw] = p.stub;
107
+ const [sb, tb] = p.bands ?? [];
108
+ const rows = (box, y0, band) => {
109
+ const ys = band
110
+ ? Array.from({ length: Math.max(0, Math.floor((band.h - 26) / 4)) + 1 }, (_, i) => band.y + 4 + i * 4)
111
+ : [box.y + box.h + 2, box.y - 20];
112
+ return [y0, ...ys.filter((y) => y !== y0)];
113
+ };
114
+ // A place and its stub. Beside the box, the stub runs from the box side to the near end of the pill. Under or over the box,
115
+ // it runs straight down or up between the box and the pill. `dir` is 1 for the source (box to pill), -1 for the target.
116
+ const place = (box, from, dir, r, side, tip) => {
117
+ let a, b;
118
+ if (side)
119
+ [a, b] = [from, { x: dir > 0 ? r.x : r.x + r.w, y: r.y + 9 }];
120
+ else {
121
+ // A diamond has its point at the middle: the stub meets the point.
122
+ const x = tip ? cx(box) : Math.min(Math.max(r.x + r.w / 2, box.x + 8, r.x + 8), box.x + box.w - 8, r.x + r.w - 8);
123
+ const under = r.y >= box.y + box.h;
124
+ [a, b] = [
125
+ { x, y: under ? box.y + box.h : box.y },
126
+ { x, y: under ? r.y : r.y + r.h },
127
+ ];
128
+ }
129
+ return dir > 0 ? [r, a, b] : [r, b, a];
130
+ };
131
+ const beside = (w, box, from, dir, band) => {
132
+ const tip = tips.has(dir > 0 ? p.from : p.to);
133
+ const out = [];
134
+ for (let dx = STUB - 8 * Math.ceil((box.w + w) / 8); dx <= STUB + 240; dx += 8)
135
+ for (const y of rows(box, from.y - 9, band)) {
136
+ // Closer than STUB to the box side, a pill sits under or over the box, with room for the stub.
137
+ const x = dir > 0 ? from.x + dx : from.x - dx - w;
138
+ if (dx < STUB && !(y >= box.y + box.h + STUB / 2 || y + 18 <= box.y - STUB / 2))
139
+ continue;
140
+ if (dx < STUB && tip && !(x + 8 <= cx(box) && cx(box) <= x + w - 8))
141
+ continue;
142
+ out.push([...place(box, from, dir, { x, y, w, h: 18 }, dx >= STUB, tip), Math.abs(dx - STUB) + Math.abs(y + 9 - from.y)]);
143
+ }
144
+ return out.sort((m, q) => m[3] - q[3]).map(([r, a, b]) => [r, a, b]);
145
+ };
146
+ const outs = (w) => [
147
+ ...beside(w, p.a, s, 1, sb),
148
+ [
149
+ { x: cx(p.a) - w / 2, y: p.a.y + p.a.h + STUB, w, h: 18 },
150
+ { x: cx(p.a), y: p.a.y + p.a.h },
151
+ { x: cx(p.a), y: p.a.y + p.a.h + STUB },
152
+ ],
153
+ [
154
+ { x: cx(p.a) - w / 2, y: p.a.y - STUB - 18, w, h: 18 },
155
+ { x: cx(p.a), y: p.a.y },
156
+ { x: cx(p.a), y: p.a.y - STUB },
157
+ ],
158
+ ];
159
+ const ins = [
160
+ ...beside(iw, p.b, e, -1, tb),
161
+ [
162
+ { x: cx(p.b) - iw / 2, y: p.b.y - STUB - 18, w: iw, h: 18 },
163
+ { x: cx(p.b), y: p.b.y - STUB },
164
+ { x: cx(p.b), y: p.b.y },
165
+ ],
166
+ [
167
+ { x: cx(p.b) - iw / 2, y: p.b.y + p.b.h + STUB, w: iw, h: 18 },
168
+ { x: cx(p.b), y: p.b.y + p.b.h + STUB },
169
+ { x: cx(p.b), y: p.b.y + p.b.h },
170
+ ],
171
+ ];
172
+ const seg = (a, b) => Array.from({ length: 9 }, (_, i) => ({ x: a.x + ((b.x - a.x) * i) / 8, y: a.y + ((b.y - a.y) * i) / 8 }));
173
+ // A stub must not run through a box other than its own, nor through a pill or a label, nor cross an edge path.
174
+ const free = (a, b, own) => seg(a, b).every((q) => ![...avoid, ...pills].some((r) => r !== own && q.x > r.x + 2 && q.x < r.x + r.w - 2 && q.y > r.y + 2 && q.y < r.y + r.h - 2));
175
+ const whole = (a, b) => !runs.some(([c, d]) => crosses(a, b, c, d));
176
+ const fits = (own, band, strict) => ([r, a, b]) => clear(r, band) && free(a, b, own) && (!strict || whole(a, b));
177
+ // The first place whose stub crosses no edge path. If none, the first place that clears everything else: in a dense
178
+ // figure no place may avoid every edge, and `check` then warns about the crossing.
179
+ const first = (own, band, lists) => [true, false].flatMap((strict) => lists.map((l, i) => [l.find(fits(own, band, strict)), i, !strict])).find(([x]) => x);
180
+ const hit = first(p.a, sb, [outs(ow), ...(sw == null ? [] : [outs(sw)])]);
181
+ const cut = hit?.[1] === 1;
182
+ const [po, o1, o2] = hit?.[0] ?? outs(ow)[0];
183
+ pills.push(po);
184
+ track(seg(o1, o2));
185
+ const hit2 = first(p.b, tb, [ins]);
186
+ const [pi, i1, i2] = hit2?.[0] ?? ins[0];
187
+ pills.push(pi);
188
+ track(seg(i1, i2));
189
+ const line = (a, b) => `M ${a.x} ${a.y} L ${b.x} ${b.y}`;
190
+ const parts = [line(o1, o2), line(i1, i2)];
191
+ return {
192
+ id: p.id,
193
+ d: parts.join(' '),
194
+ mid: { x: po.x + po.w / 2, y: po.y + 9 },
195
+ curve: [o1, o1, i2, i2],
196
+ stub: {
197
+ parts,
198
+ pills: [po, pi],
199
+ pts: [
200
+ [o1, o2],
201
+ [i1, i2],
202
+ ],
203
+ tight: [hit?.[2] !== false, hit2?.[2] !== false],
204
+ ...(cut && { short: true }),
205
+ },
206
+ };
207
+ }
72
208
  if (p.elbow) {
73
209
  // The vertical run sits at the midpoint x. Under 16 px of gap, it detours: out 8 px past the start, back to 8 px
74
210
  // before the end, then forward into the target. A gap of 0 px or less takes the same detour.
@@ -103,5 +239,32 @@ export function route(edges, rects, tips = new Set(), avoid = []) {
103
239
  const c1 = horiz ? { x: s.x + sign * k, y: s.y } : { x: s.x, y: s.y + sign * k };
104
240
  const c2 = horiz ? { x: e.x - sign * k, y: e.y } : { x: e.x, y: e.y - sign * k };
105
241
  return drawn(p.id, [s, c1, c2, e], { x: (s.x + e.x) / 2, y: (s.y + e.y) / 2 });
106
- });
242
+ };
243
+ const done = new Map();
244
+ for (const p of picks) {
245
+ if (p.stub)
246
+ continue;
247
+ const r = one(p);
248
+ done.set(p, r);
249
+ if (p.labelW)
250
+ pills.push({ x: r.mid.x - p.labelW / 2, y: r.mid.y - 9, w: p.labelW, h: 18 });
251
+ track(Array.from({ length: 33 }, (_, i) => bezier(r.curve, i / 32)));
252
+ }
253
+ for (const p of picks)
254
+ if (p.stub)
255
+ done.set(p, one(p));
256
+ return picks.map((p) => done.get(p));
257
+ }
258
+ /** True if the segment a-b crosses the segment c-d. The ends of a-b are trimmed by 1.5 px, so a touch at a box side does not count. */
259
+ export function crosses(a, b, c, d) {
260
+ const len = Math.hypot(b.x - a.x, b.y - a.y);
261
+ if (len < 4)
262
+ return false;
263
+ const t = 1.5 / len;
264
+ const [p, q] = [
265
+ { x: a.x + (b.x - a.x) * t, y: a.y + (b.y - a.y) * t },
266
+ { x: b.x - (b.x - a.x) * t, y: b.y - (b.y - a.y) * t },
267
+ ];
268
+ const side = (o, u, v) => Math.sign((u.x - o.x) * (v.y - o.y) - (u.y - o.y) * (v.x - o.x));
269
+ return side(p, q, c) * side(p, q, d) < 0 && side(c, d, p) * side(c, d, q) < 0;
107
270
  }
package/dist/guide.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  /** The full guide, as Markdown. `flowfig docs` prints it. */
2
- export declare const GUIDE = "# flowfig guide\n\nflowfig draws animated flow figures. A figure has boxes, the edges between the boxes, and steps. In each step, a packet moves along\nthe edges. The output is one animated SVG with no script. The SVG plays in a GitHub README, in PR and issue comments, and in blog\nposts. A figure is about 5 to 50 kB.\n\nYou write a JSON spec. You never write SVG by hand. The command `npx flowfig` checks the spec and renders it.\n\n## What flowfig draws\n\nA spec has three forms.\n\n- The map (the default). The map shows the boxes and the edges. A packet moves along an edge in each beat.\n- The map with a rail (`\"rail\": true`). The rail is a lifeline diagram under the map. It has one row for each message.\n- The rail alone (`\"rail\": \"only\"`). Use it when the reader needs only the order of the messages, for example when the map is already in the same document.\n\nUse the rail for a sequence of messages: a request lifecycle, an API call chain, or a Mermaid `sequenceDiagram`. Put each message on\nan edge. Put each phase in a step. Put messages that run at the same time in one beat. Mark a message that does not wait for an\nanswer with `\"async\": true`: every send to a queue or a topic, every emitted event, and every call the caller does not await.\n\n## Scope: what flowfig draws and what it does not\n\nflowfig draws how something works: parts, the messages between them, and the order of the messages.\n\n| The user asks for | Draw |\n| ------------------------------------------ | ------------------------------------------------------------------------------------------ |\n| An architecture, a data flow, a pipeline | The map. Group parts by service, network or trust boundary. `store` for data at rest. |\n| A request lifecycle, a call chain | The map with `\"rail\": true`. One message per hop, with its real payload in `data`. |\n| A sequence diagram only | `\"rail\": \"only\"`. |\n| A state lifecycle, a state machine | One box per state, one edge per transition, labeled with its event. One step per path. Mark the first state with `mark: \"start\"` and each final state with `mark: \"end\"`. |\n| A flowchart with branches | `shape: \"decision\"` for each branch. One step per path. |\n| A roadmap or a timeline | `timeline: true`. One labeled group per track, in a `column` group. Items with `from` and `to` (dates), a milestone with `from` only, an edge for a dependency, `today` for the line. A dependent item starts after its source ends. |\n| A process across roles (a ticket, an order, a refund) | `lanes: true`. One labeled group per role, in a `column` group. Put each step in the lane of the role that does it. Link each step with `source` to the SOP heading. About four time columns fit at 830 px: merge steps, give the outcomes of one decision the same `at`, or split the figure. |\n\nflowfig draws a roadmap or a timeline with dates (`timeline: true`), and converts a Mermaid `gantt` to it. flowfig does not\ndraw class or ER diagrams (fields, types, cardinality), charts of numbers or mind maps. If the user asks for one of these, say that\nflowfig does not draw it, suggest Mermaid (`classDiagram`, `erDiagram`), and draw nothing with flowfig.\n\n## Workflow\n\n### 1. Pick the scope\n\nIf the code has more than one flow, name each flow in the reply. Then draw one flow, or draw one structure view and call it a\nstructure view. If the user asks for the whole system, draw one top view with groups, or a set of figures that together cover\nevery part. Keep each figure to 12 boxes or fewer.\n\n### 2. Write the fact list\n\nBefore the spec, write a list of the facts that the figure must show. Take each fact from the code and from its wiring: config\nfiles, compose files, route tables and queue bindings (or from the pasted Mermaid). Give each fact its `file:line`:\n\n- every part (service, function, store, queue, external system);\n- every call, in order, written as `caller \u2192 callee: payload (file:line of the call)`. The edge in the spec goes from that caller\n to that callee;\n- every call that does not wait for an answer (fire and forget, a queue, a webhook, a callback), and every consumer of each queue\n or topic;\n- every branch and every error path (a rejected input, a retry, a dead-letter path);\n- every end state.\n\nIf the code does not show a fact, leave the fact out. Do not guess a part, a name or an order.\n\n### 3. Write the spec\n\nEach fact becomes a box, an edge, a beat, a `data` card or a `show` row. Use the real names from the code as labels, and\nreal example data from the code or its tests. Keep each fact that you leave out, with the reason, for the reply.\nGive each box and edge that draws code a `source`, from the fact list: `\"src/auth/login.ts#verifyPassword\"`. A store or an outside part may have none.\nA box that draws a step from a document links to that document: `\"docs/sop/refunds.md#step-3-approve-the-refund\"`, the heading as a GitHub anchor. `verify` checks it the same way.\n\nMermaid mapping:\n\n| Mermaid | flowfig |\n| ---------------------------------------- | ------------------------------------------------------------------ |\n| `participant` | a box |\n| `A->>B: text` | an edge from A to B, and a hop with `data: \"text\"` |\n| `B-->>A: text` (a reply) | a hop on the same edge with `back: true` |\n| `A-)B: text` (async) | a hop with `async: true` |\n| `par ... and ... end` | the hops of all branches in one beat |\n| `alt` / `opt` | one step per path |\n| `stateDiagram` states and transitions | boxes, and edges labeled with the event |\n\n### 4. Render, then fix\n\n```bash\nnpx flowfig - out.svg <<'SPEC'\n{ \"props\": { \"layout\": ..., \"edges\": [...], \"steps\": [...] } }\nSPEC\n```\n\nThe quoted `<<'SPEC'` heredoc passes the JSON with no change. The command checks the spec first. If the check finds an error, the\ncommand writes no SVG and lists the faults. Fix each fault and render again.\n\n- Fix a layout fault by changing the layout first: put parts in rows or columns, route an edge `around`, or change a gap.\n Never remove a fact from the fact list to pass the check. If you must remove one, name it in the reply.\n- If `small-text` appears, the figure is too wide. Put the parts in two rows, move a detail from `label` to `sub`, or split\n the figure. Use more steps in one figure before you make a second figure. Keep the real name from the code in the label:\n `ReportsController` stays `ReportsController`, not `Controller`. Do not change `--width` to pass the check: the\n reader sees the figure at the real page width.\n- Fix every other warning, or tell the user why it stays.\n- Do not use `--no-check` to hide a fault.\n\n### 5. Read the figure back\n\nRun `npx flowfig --spec out.svg`. Compare the spec with the fact list. Check that each edge goes from the caller to the callee\nthat its fact names. Add each fact that is missing, fix each wrong edge, and render again.\n\nRun `npx flowfig verify out.svg` from the repo root. Fix each `missing-file` or `missing-symbol`.\n\n### 6. Look at the SVG\n\nThe check estimates the text width, so it cannot see everything. If you can open a browser, open the SVG and take a\nscreenshot. Wait a few seconds and take a second screenshot to see a later beat. If you cannot open a browser, write \"not\nlooked at\" in the reply. Never report a look that you did not do. A browser tool can block `file://` URLs. If it does, serve the folder\nwith `python3 -m http.server`.\n\n### 7. Write the reply\n\nThe reply has these parts, in this order:\n\n1. the path of each SVG;\n2. what each figure shows: the parts and the steps. Copy the counts from the `figure:` line of the check output. Copy every name\n from the read-back spec. Never count from memory;\n3. the scope: the flow you drew, why, and the other flows that exist;\n4. what the figure leaves out, and why;\n5. the two check lines that the render printed, `0 errors, 0 warnings` and `figure: ...`, copied as printed, and whether\n you looked at the SVG;\n6. one line `npx flowfig open <path>` for each SVG, at the end of the reply. Do not run that command yourself.\n\nTo change an SVG later, print its spec with `--spec`, change the spec, and render again.\n\n## Spec reference\n\n`props` has these fields.\n\n| Field | Type | Meaning |\n| ---------- | ----------------------- | ---------------------------------------------------------------------------------------------- |\n| `layout` | group | The boxes and how they line up. Required. |\n| `edges` | edge[] | The arrows between the boxes. Required. |\n| `steps` | step[] | The stories the figure tells. With no steps, the figure is a still map. |\n| `lanes` | `true` | Draw the layout as swimlanes: a `column` group of labeled groups, one per role. The boxes run left to right in step order. |\n| `timeline` | `true` | Draw the layout as a timeline: one labeled group per track, with the boxes placed by their `from` and `to` dates. |\n| `today` | `YYYY-MM-DD` | In a `timeline` figure: the date where the today line stops. Default: the last date of the items. |\n| `rail` | `true` or `\"only\"` | Draw the steps as a lifeline rail under the map. `\"only\"` draws the rail without the map. |\n| `speed` | number | Milliseconds a packet takes to cross one edge. Default: 900. |\n| `theme` | object | Colors: `accent`, `fg`, `muted`, `bg`, `surface`, `border`, `font`. Each color you omit keeps its built-in value. |\n\n### layout\n\nThe layout is a tree. A group has `children` and these optional fields.\n\n- `id`: a name that an edge can use to reach the group as a whole.\n- `label`: the title on the frame. Only a group with a `label` gets a frame.\n- `direction`: `\"row\"` (the default) or `\"column\"`.\n- `gap`: the space between children in px. Default: 28 for a column. For a row, the gap fits the widest edge label between two children (at least 56).\n- `align`: `\"start\"`, `\"center\"` or `\"end\"`. This sets where the children line up across the direction.\n\nEvery other item is a box.\n\n| Box field | Meaning |\n| --------- | --------------------------------------------------------------------------------------------------------- |\n| `id` | Required. The name that edges and steps use. It must be unique in the figure. |\n| `label` | Required. The title in the box. |\n| `sub` | A smaller line under the label. |\n| `shape` | `\"box\"` (default), `\"decision\"` (a diamond) or `\"store\"` (a database cylinder for data at rest). |\n| `at` | In a `lanes` figure: the time column of the box, 0 first. Default: the order in which the steps first reach the box. |\n| `from` | In a `timeline` figure: the start of the item, or the date of a milestone, as YYYY-MM-DD. |\n| `to` | In a `timeline` figure: the last day of the item, as YYYY-MM-DD. Without it the box is a milestone. |\n| `width` | Width in px. This overrides the width that the layout picks. |\n| `source` | The code this draws: `path` or `path#symbol`, relative to the repo root. `flowfig verify` checks it. |\n| `lines` | The least number of text lines that a content card keeps. The card still grows to fit its content. |\n| `tone` | The state color of the box: a 1 px border and a light tint. Use `blue`, `purple`, `green`, `orange`, `red` or `gray`. |\n| `mark` | `\"start\"` or `\"end\"` | A lifecycle mark: a filled dot before a start state, a ringed dot after an end state. |\n\n### edges\n\nAn edge has these fields.\n\n- `id`: the name that steps use. Default: `from->to`.\n- `from` and `to`: the `id` of a box or a group.\n- `label`: text on the edge, drawn as a small pill.\n- `around`: `\"above\"` or `\"below\"`. This routes the edge over or under the boxes in between (loops, skip-ahead edges).\n- `quiet`: if `true`, the SVG draws the edge only while a step uses it.\n- `source`: the code this edge draws, as `path` or `path#symbol`. `flowfig verify` checks it.\n\n### steps\n\nA step has `label` and `flow`. It can also have `caption` (the line under the figure while no beat has a `say`) and `nodes` (ids of\nboxes to highlight for the whole step).\n\n`flow` is a list of beats. A beat is one of these:\n\n- an edge id (a string);\n- an array of edge ids, which run at the same time;\n- an object `{ edges?, say?, show?, light?, ms? }`. A beat with no `edges` is a pause.\n\nThe beat fields:\n\n- `edges`: an edge id, a hop object, or an array of these. A hop object is `{ edge, back?, data?, tone?, async?, source? }`.\n - `back: true` runs the packet from the `to` box to the `from` box.\n - `data` is a small card that moves with the packet.\n - `async: true` marks a message that does not wait for an answer. The rail draws it dashed, with an `async` tag.\n - `tone`: the color of this hop for its beat. The packet, the data card, the edge, the label pill and the arrival box take the color. The trail after the beat stays the accent.\n - `green`: a success or a cache hit. `orange`: a warning, a miss or a retry. `red`: an error or a rejected input.\n - `gray`: idle or skipped. `purple`: async or background. `blue`: the default row color.\n - If the hop has no `tone`, the arrival box uses its box `tone`, then the accent. A hop `tone` wins over a box `tone`.\n- `say`: the caption for the beat.\n- `show`: `{ boxId: [row, ...] }`. This fills the content card of each named box. The card keeps the rows until the step ends.\n- `light`: ids of boxes to highlight for this beat.\n- `ms`: how long the beat lasts. Default: the time one packet needs to cross an edge.\n\nA row of a content card is `{ tag?, tone?, text, meta?, mark?, mono? }`.\n\n- `tag`: a short colored label at the start of the line.\n- `tone`: the color of the tag: `blue` (default), `purple`, `green`, `orange`, `red` or `gray`.\n- `text`: the main text.\n- `meta`: muted text after the main text.\n- `mark`: a mark at the right end of the line, such as a check or \"new\".\n- `mono`: if `true`, the text uses a monospace font.\n\n## Content rules\n\n- Give every box a stable `id`.\n- Use `shape: \"store\"` for data at rest (a database, a cache, a file, a queue). Use a plain box for a part that does work. Use `shape: \"decision\"` for a branch.\n- Keep one clear main path, left to right. Put side parts in a `column` group.\n- Use `quiet: true` on a long edge that crosses the picture. A quiet edge needs a beat that uses it, or the check reports\n `hidden-edge`.\n- In a rail, draw an error reply as a hop back on the same edge, with the error in `data` (`{ \"edge\": \"login\", \"back\": true,\n \"data\": \"401 CREDENTIALS_INVALID\" }`). A call that stays inside one part (a hash check, a guard) is not a message: put it in\n `say` or in a `show` row of that part.\n- Keep an SVG to one or two steps. The SVG plays every step in a loop, with no controls.\n- Use the React player, `<Flow {...props} />` from `flowfig`, for a page that needs tabs, pause or hover.\n\n## Example\n\n```json\n{\n \"props\": {\n \"layout\": {\n \"children\": [\n { \"id\": \"client\", \"label\": \"Browser\" },\n { \"id\": \"api\", \"label\": \"API Server\" },\n { \"id\": \"db\", \"label\": \"Database\", \"shape\": \"store\" }\n ]\n },\n \"edges\": [\n { \"id\": \"req\", \"from\": \"client\", \"to\": \"api\", \"label\": \"GET /users/42\" },\n { \"id\": \"q\", \"from\": \"api\", \"to\": \"db\", \"label\": \"SELECT\" }\n ],\n \"steps\": [\n {\n \"label\": \"read\",\n \"flow\": [\n { \"edges\": { \"edge\": \"req\", \"data\": \"GET /users/42\" }, \"say\": \"The browser asks for user 42.\" },\n { \"edges\": \"q\", \"show\": { \"db\": [{ \"tag\": \"row\", \"tone\": \"gray\", \"text\": \"Ada Lovelace\" }] }, \"say\": \"The API server reads the row.\" },\n { \"edges\": { \"edge\": \"req\", \"back\": true, \"data\": \"200 OK\" }, \"say\": \"The API server sends the user.\" }\n ]\n }\n ]\n }\n}\n```\n\n## Commands\n\n```bash\nnpx flowfig - out.svg < spec.json # render a spec from stdin\nnpx flowfig spec.json out.svg # render a spec file\nnpx flowfig figure.ts out.svg # render a module whose default export is a spec\nnpx flowfig check <input> [--json] # list the faults. The input can also be an SVG that flowfig wrote.\nnpx flowfig verify <input>... # check that the code each source names still exists\nnpx flowfig diff <old> <new> # list what changed in the spec between two figures\nnpx flowfig --spec out.svg # print the spec that an SVG carries\nnpx flowfig open out.svg # show the figure in the default browser\nnpx flowfig gif out.svg [out.gif] # write an animated GIF (needs Chrome, Edge, Chromium or Brave)\nnpx flowfig docs # print this guide\nnpx flowfig init # write these instructions for the coding agents of a repo\n```\n\nA render checks first and writes nothing on an error. `--strict` makes warnings errors. `--width` sets the page width.\n`--min-text` sets the smallest text that the reader should get. `--no-check` skips the check.\n";
2
+ export declare const GUIDE = "# flowfig guide\n\nflowfig draws animated flow figures. A figure has boxes, the edges between the boxes, and steps. In each step, a packet moves along\nthe edges. The output is one animated SVG with no script. The SVG plays in a GitHub README, in PR and issue comments, and in blog\nposts. A figure is about 5 to 50 kB.\n\nYou write a JSON spec. You never write SVG by hand. The command `npx flowfig` checks the spec and renders it.\n\n## What flowfig draws\n\nA spec has three forms.\n\n- The map (the default). The map shows the boxes and the edges. A packet moves along an edge in each beat.\n- The map with a rail (`\"rail\": true`). The rail is a lifeline diagram under the map. It has one row for each message.\n- The rail alone (`\"rail\": \"only\"`). Use it when the reader needs only the order of the messages, for example when the map is already in the same document.\n\nUse the rail for a sequence of messages: a request lifecycle, an API call chain, or a Mermaid `sequenceDiagram`. Put each message on\nan edge. Put each phase in a step. Put messages that run at the same time in one beat. Mark a message that does not wait for an\nanswer with `\"async\": true`: every send to a queue or a topic, every emitted event, and every call the caller does not await.\n\n## Scope: what flowfig draws and what it does not\n\nflowfig draws how something works: parts, the messages between them, and the order of the messages.\n\n| The user asks for | Draw |\n| ------------------------------------------ | ------------------------------------------------------------------------------------------ |\n| An architecture, a data flow, a pipeline | The map. Group parts by service, network or trust boundary. `store` for data at rest. |\n| A request lifecycle, a call chain | The map with `\"rail\": true`. One message per hop, with its real payload in `data`. |\n| A sequence diagram only | `\"rail\": \"only\"`. |\n| A state lifecycle, a state machine | One box per state, one edge per transition, labeled with its event. One step per path. Mark the first state with `mark: \"start\"` and each final state with `mark: \"end\"`. |\n| A flowchart with branches | `shape: \"decision\"` for each branch. One step per path. |\n| A roadmap or a timeline | `timeline: true`. One labeled group per track, in a `column` group. Items with `from` and `to` (dates), a milestone with `from` only, an edge for a dependency, `today` for the line. A dependent item starts after its source ends. |\n| A process across roles (a ticket, an order, a refund) | `lanes: true`. One labeled group per role, in a `column` group. Put each step in the lane of the role that does it. Link each step with `source` to the SOP heading. If the steps do not fit the width, flowfig wraps the time columns into blocks and links the blocks with labeled stubs, so keep the whole process in one figure. Give the outcomes of one decision the same `at`. |\n\nflowfig draws a roadmap or a timeline with dates (`timeline: true`), and converts a Mermaid `gantt` to it. flowfig does not\ndraw class or ER diagrams (fields, types, cardinality), charts of numbers or mind maps. If the user asks for one of these, say that\nflowfig does not draw it, suggest Mermaid (`classDiagram`, `erDiagram`), and draw nothing with flowfig.\n\n## Workflow\n\n### 1. Pick the scope\n\nIf the code has more than one flow, name each flow in the reply. Then draw one flow, or draw one structure view and call it a\nstructure view. If the user asks for the whole system, draw one top view with groups, or a set of figures that together cover\nevery part. Keep each figure to 12 boxes or fewer.\n\n### 2. Write the fact list\n\nBefore the spec, write a list of the facts that the figure must show. Take each fact from the code and from its wiring: config\nfiles, compose files, route tables and queue bindings (or from the pasted Mermaid). Give each fact its `file:line`:\n\n- every part (service, function, store, queue, external system);\n- every call, in order, written as `caller \u2192 callee: payload (file:line of the call)`. The edge in the spec goes from that caller\n to that callee;\n- every call that does not wait for an answer (fire and forget, a queue, a webhook, a callback), and every consumer of each queue\n or topic;\n- every branch and every error path (a rejected input, a retry, a dead-letter path);\n- every end state;\n- for a process document (an SOP): every deadline, every message to a person (an email, a notice), every choice that a person\n makes, and every wait for a reply. Put each one in a box `sub`, a step `say` or a `data` card. A small fact still counts.\n\nIf the code does not show a fact, leave the fact out. Do not guess a part, a name or an order.\n\n### 3. Write the spec\n\nEach fact becomes a box, an edge, a beat, a `data` card or a `show` row. Use the real names from the code as labels, and\nreal example data from the code or its tests. Keep each fact that you leave out, with the reason, for the reply.\nGive each box and edge that draws code a `source`, from the fact list: `\"src/auth/login.ts#verifyPassword\"`. A store or an outside part may have none.\nA box that draws a step from a document links to that document: `\"docs/sop/refunds.md#step-3-approve-the-refund\"`, the heading as a GitHub anchor. `verify` checks it the same way.\n\nMermaid mapping:\n\n| Mermaid | flowfig |\n| ---------------------------------------- | ------------------------------------------------------------------ |\n| `participant` | a box |\n| `A->>B: text` | an edge from A to B, and a hop with `data: \"text\"` |\n| `B-->>A: text` (a reply) | a hop on the same edge with `back: true` |\n| `A-)B: text` (async) | a hop with `async: true` |\n| `par ... and ... end` | the hops of all branches in one beat |\n| `alt` / `opt` | one step per path |\n| `stateDiagram` states and transitions | boxes, and edges labeled with the event |\n\n### 4. Render, then fix\n\n```bash\nnpx flowfig - out.svg <<'SPEC'\n{ \"props\": { \"layout\": ..., \"edges\": [...], \"steps\": [...] } }\nSPEC\n```\n\nThe quoted `<<'SPEC'` heredoc passes the JSON with no change. The command checks the spec first. If the check finds an error, the\ncommand writes no SVG and lists the faults. Fix each fault and render again.\n\n- Fix a layout fault by changing the layout first: put parts in rows or columns, route an edge `around`, or change a gap.\n Never remove a fact from the fact list to pass the check. If you must remove one, name it in the reply.\n- If `small-text` appears, the figure is too wide. Put the parts in two rows, move a detail from `label` to `sub`, or split\n the figure. Use more steps in one figure before you make a second figure. Keep the real name from the code in the label:\n `ReportsController` stays `ReportsController`, not `Controller`. Do not change `--width` to pass the check: the\n reader sees the figure at the real page width.\n- Fix every other warning, or tell the user why it stays.\n- Do not use `--no-check` to hide a fault.\n\n### 5. Read the figure back\n\nRun `npx flowfig --spec out.svg`. Compare the spec with the fact list. Check that each edge goes from the caller to the callee\nthat its fact names. Add each fact that is missing, fix each wrong edge, and render again.\n\nRun `npx flowfig verify out.svg` from the repo root. Fix each `missing-file` or `missing-symbol`.\n\n### 6. Look at the SVG\n\nThe check estimates the text width, so it cannot see everything. If you can open a browser, open the SVG and take a\nscreenshot. Wait a few seconds and take a second screenshot to see a later beat. If you cannot open a browser, write \"not\nlooked at\" in the reply. Never report a look that you did not do. A browser tool can block `file://` URLs. If it does, serve the folder\nwith `python3 -m http.server`.\n\n### 7. Write the reply\n\nThe reply has these parts, in this order:\n\n1. the path of each SVG;\n2. what each figure shows: the parts and the steps. Copy the counts from the `figure:` line of the check output. Copy every name\n from the read-back spec. Never count from memory;\n3. the scope: the flow you drew, why, and the other flows that exist;\n4. what the figure leaves out, and why;\n5. the two check lines that the render printed, `0 errors, 0 warnings` and `figure: ...`, copied as printed, and whether\n you looked at the SVG;\n6. one line `npx flowfig open <path>` for each SVG, at the end of the reply. Do not run that command yourself.\n\nTo change an SVG later, print its spec with `--spec`, change the spec, and render again.\n\n## Spec reference\n\n`props` has these fields.\n\n| Field | Type | Meaning |\n| ---------- | ----------------------- | ---------------------------------------------------------------------------------------------- |\n| `layout` | group | The boxes and how they line up. Required. |\n| `edges` | edge[] | The arrows between the boxes. Required. |\n| `steps` | step[] | The stories the figure tells. With no steps, the figure is a still map. |\n| `lanes` | `true` | Draw the layout as swimlanes: a `column` group of labeled groups, one per role. The boxes run left to right in step order. |\n| `timeline` | `true` | Draw the layout as a timeline: one labeled group per track, with the boxes placed by their `from` and `to` dates. |\n| `today` | `YYYY-MM-DD` | In a `timeline` figure: the date where the today line stops. Default: the last date of the items. |\n| `rail` | `true` or `\"only\"` | Draw the steps as a lifeline rail under the map. `\"only\"` draws the rail without the map. |\n| `speed` | number | Milliseconds a packet takes to cross one edge. Default: 900. |\n| `theme` | object | Colors: `accent`, `fg`, `muted`, `bg`, `surface`, `border`, `font`. Each color you omit keeps its built-in value. |\n\n### layout\n\nThe layout is a tree. A group has `children` and these optional fields.\n\n- `id`: a name that an edge can use to reach the group as a whole.\n- `label`: the title on the frame. Only a group with a `label` gets a frame.\n- `direction`: `\"row\"` (the default) or `\"column\"`.\n- `gap`: the space between children in px. Default: 28 for a column. For a row, the gap fits the widest edge label between two children (at least 56).\n- `align`: `\"start\"`, `\"center\"` or `\"end\"`. This sets where the children line up across the direction.\n\nEvery other item is a box.\n\n| Box field | Meaning |\n| --------- | --------------------------------------------------------------------------------------------------------- |\n| `id` | Required. The name that edges and steps use. It must be unique in the figure. |\n| `label` | Required. The title in the box. |\n| `sub` | A smaller line under the label. |\n| `shape` | `\"box\"` (default), `\"decision\"` (a diamond) or `\"store\"` (a database cylinder for data at rest). |\n| `at` | In a `lanes` figure: the time column of the box, 0 first. Default: the order in which the steps first reach the box. |\n| `from` | In a `timeline` figure: the start of the item, or the date of a milestone, as YYYY-MM-DD. |\n| `to` | In a `timeline` figure: the last day of the item, as YYYY-MM-DD. Without it the box is a milestone. |\n| `width` | Width in px. This overrides the width that the layout picks. |\n| `source` | The code this draws: `path` or `path#symbol`, relative to the repo root. `flowfig verify` checks it. |\n| `lines` | The least number of text lines that a content card keeps. The card still grows to fit its content. |\n| `tone` | The state color of the box: a 1 px border and a light tint. Use `blue`, `purple`, `green`, `orange`, `red` or `gray`. |\n| `mark` | `\"start\"` or `\"end\"` | A lifecycle mark: a filled dot before a start state, a ringed dot after an end state. |\n\n### edges\n\nAn edge has these fields.\n\n- `id`: the name that steps use. Default: `from->to`.\n- `from` and `to`: the `id` of a box or a group.\n- `label`: text on the edge, drawn as a small pill.\n- `around`: `\"above\"` or `\"below\"`. This routes the edge over or under the boxes in between (loops, skip-ahead edges).\n- `quiet`: if `true`, the SVG draws the edge only while a step uses it.\n- `source`: the code this edge draws, as `path` or `path#symbol`. `flowfig verify` checks it.\n\n### steps\n\nA step has `label` and `flow`. It can also have `caption` (the line under the figure while no beat has a `say`) and `nodes` (ids of\nboxes to highlight for the whole step).\n\n`flow` is a list of beats. A beat is one of these:\n\n- an edge id (a string);\n- an array of edge ids, which run at the same time;\n- an object `{ edges?, say?, show?, light?, ms? }`. A beat with no `edges` is a pause.\n\nThe beat fields:\n\n- `edges`: an edge id, a hop object, or an array of these. A hop object is `{ edge, back?, data?, tone?, async?, source? }`.\n - `back: true` runs the packet from the `to` box to the `from` box.\n - `data` is a small card that moves with the packet.\n - `async: true` marks a message that does not wait for an answer. The rail draws it dashed, with an `async` tag.\n - `tone`: the color of this hop for its beat. The packet, the data card, the edge, the label pill and the arrival box take the color. The trail after the beat stays the accent.\n - `green`: a success or a cache hit. `orange`: a warning, a miss or a retry. `red`: an error or a rejected input.\n - `gray`: idle or skipped. `purple`: async or background. `blue`: the default row color.\n - If the hop has no `tone`, the arrival box uses its box `tone`, then the accent. A hop `tone` wins over a box `tone`.\n- `say`: the caption for the beat.\n- `show`: `{ boxId: [row, ...] }`. This fills the content card of each named box. The card keeps the rows until the step ends.\n- `light`: ids of boxes to highlight for this beat.\n- `ms`: how long the beat lasts. Default: the time one packet needs to cross an edge.\n\nA row of a content card is `{ tag?, tone?, text, meta?, mark?, mono? }`.\n\n- `tag`: a short colored label at the start of the line.\n- `tone`: the color of the tag: `blue` (default), `purple`, `green`, `orange`, `red` or `gray`.\n- `text`: the main text.\n- `meta`: muted text after the main text.\n- `mark`: a mark at the right end of the line, such as a check or \"new\".\n- `mono`: if `true`, the text uses a monospace font.\n\n## Content rules\n\n- Give every box a stable `id`.\n- Use `shape: \"store\"` for data at rest (a database, a cache, a file, a queue). Use a plain box for a part that does work. Use `shape: \"decision\"` for a branch.\n- Keep one clear main path, left to right. Put side parts in a `column` group.\n- Use `quiet: true` on a long edge that crosses the picture. A quiet edge needs a beat that uses it, or the check reports\n `hidden-edge`.\n- In a rail, draw an error reply as a hop back on the same edge, with the error in `data` (`{ \"edge\": \"login\", \"back\": true,\n \"data\": \"401 CREDENTIALS_INVALID\" }`). A call that stays inside one part (a hash check, a guard) is not a message: put it in\n `say` or in a `show` row of that part.\n- Keep an SVG to one or two steps. The SVG plays every step in a loop, with no controls.\n- Use the React player, `<Flow {...props} />` from `flowfig`, for a page that needs tabs, pause or hover.\n\n## Example\n\n```json\n{\n \"props\": {\n \"layout\": {\n \"children\": [\n { \"id\": \"client\", \"label\": \"Browser\" },\n { \"id\": \"api\", \"label\": \"API Server\" },\n { \"id\": \"db\", \"label\": \"Database\", \"shape\": \"store\" }\n ]\n },\n \"edges\": [\n { \"id\": \"req\", \"from\": \"client\", \"to\": \"api\", \"label\": \"GET /users/42\" },\n { \"id\": \"q\", \"from\": \"api\", \"to\": \"db\", \"label\": \"SELECT\" }\n ],\n \"steps\": [\n {\n \"label\": \"read\",\n \"flow\": [\n { \"edges\": { \"edge\": \"req\", \"data\": \"GET /users/42\" }, \"say\": \"The browser asks for user 42.\" },\n { \"edges\": \"q\", \"show\": { \"db\": [{ \"tag\": \"row\", \"tone\": \"gray\", \"text\": \"Ada Lovelace\" }] }, \"say\": \"The API server reads the row.\" },\n { \"edges\": { \"edge\": \"req\", \"back\": true, \"data\": \"200 OK\" }, \"say\": \"The API server sends the user.\" }\n ]\n }\n ]\n }\n}\n```\n\n## Commands\n\n```bash\nnpx flowfig - out.svg < spec.json # render a spec from stdin\nnpx flowfig spec.json out.svg # render a spec file\nnpx flowfig figure.ts out.svg # render a module whose default export is a spec\nnpx flowfig check <input> [--json] # list the faults. The input can also be an SVG that flowfig wrote.\nnpx flowfig verify <input>... # check that the code each source names still exists\nnpx flowfig diff <old> <new> # list what changed in the spec between two figures\nnpx flowfig --spec out.svg # print the spec that an SVG carries\nnpx flowfig open out.svg # show the figure in the default browser\nnpx flowfig gif out.svg [out.gif] # write an animated GIF (needs Chrome, Edge, Chromium or Brave)\nnpx flowfig docs # print this guide\nnpx flowfig init # write these instructions for the coding agents of a repo\n```\n\nA render checks first and writes nothing on an error. `--strict` makes warnings errors. `--width` sets the page width.\n`--min-text` sets the smallest text that the reader should get. `--no-check` skips the check.\n";
3
3
  /** The short instruction text that `flowfig init` writes for each coding agent. */
4
4
  export declare const AGENT_TEXT = "# Diagrams with flowfig\n\nIf the user names no other tool, use flowfig for every diagram, figure, flowchart or picture of how something works. Do not answer with a Mermaid block or ASCII art. Use it for an architecture, a data flow or pipeline, a request lifecycle,\na call sequence, a state lifecycle, or a flowchart. flowfig also converts a pasted Mermaid flowchart, `stateDiagram` or\n`sequenceDiagram`.\n\nflowfig draws a roadmap or a timeline with dates (`timeline: true`), and converts a Mermaid `gantt` to it. flowfig does not\ndraw class or ER diagrams or charts of numbers. For those, tell the user so, suggest Mermaid (`classDiagram`, `erDiagram`),\nand draw nothing with flowfig.\n\n1. Run `npx flowfig docs` and read it. If the command fails, stop: tell the user that flowfig is not available, give them\n `npm install --save-dev flowfig`, and draw nothing with another tool.\n2. Pick the scope. If the code has more than one flow, name each flow in the reply, then draw one flow, or draw one structure\n view and call it a structure view. If the user asks for the whole system, draw one top view with groups, or a set of figures\n that together cover every part. Keep each figure to 12 boxes or fewer. For a process that several roles do, use\n `lanes: true`, one labeled group per role. For a plan or a roadmap, read the dates from the document and use `timeline: true`.\n3. Write a fact list from the code and from its wiring (config, compose, route and queue files). Write each call as\n `caller \u2192 callee: payload (file:line of the call)`, in order. Include each async call and every consumer of a queue, each\n branch and error path, and each end state. Leave out what the code does not show.\n4. Write the spec from the fact list, with the real names and data. Render it with `npx flowfig - out.svg <<'SPEC'` and the\n JSON in the heredoc. Fix every fault by changing the layout first (rows, `around`, the gap). Never remove a fact to pass\n the check; if you must remove one, name it in the reply. If `small-text` appears, use two rows or split the figure; keep\n the real names; do not change `--width`. Give each box and edge that draws code a `source` (`file#symbol`) from the fact list.\n Mark every send to a queue or a topic, every emitted event, and every call the caller does not await with `async: true`.\n5. Run `npx flowfig --spec out.svg` and compare it with the fact list: each edge must go from the caller to the callee that the\n fact names. Fix each gap. Then run `npx flowfig verify out.svg` from the repo root and fix each fault.\n6. If you can open a browser, look at the SVG at two moments of the loop. If you cannot, write \"not looked at\" in the reply.\n Never report a look that you did not do.\n7. Reply with: the SVG path; what it shows, with the counts copied from the `figure:` line and the names copied from the read-back spec; what it leaves out and why;\n the two lines the render printed, `0 errors, 0 warnings` and `figure: ...`, copied as printed.\n End the reply with one line `npx flowfig open <path>` for each SVG. Do not run that command yourself.\n";
5
5
  /** The description of the Claude skill: the words that make the agent load it. */
package/dist/guide.js CHANGED
@@ -32,7 +32,7 @@ flowfig draws how something works: parts, the messages between them, and the ord
32
32
  | A state lifecycle, a state machine | One box per state, one edge per transition, labeled with its event. One step per path. Mark the first state with \`mark: "start"\` and each final state with \`mark: "end"\`. |
33
33
  | A flowchart with branches | \`shape: "decision"\` for each branch. One step per path. |
34
34
  | A roadmap or a timeline | \`timeline: true\`. One labeled group per track, in a \`column\` group. Items with \`from\` and \`to\` (dates), a milestone with \`from\` only, an edge for a dependency, \`today\` for the line. A dependent item starts after its source ends. |
35
- | A process across roles (a ticket, an order, a refund) | \`lanes: true\`. One labeled group per role, in a \`column\` group. Put each step in the lane of the role that does it. Link each step with \`source\` to the SOP heading. About four time columns fit at 830 px: merge steps, give the outcomes of one decision the same \`at\`, or split the figure. |
35
+ | A process across roles (a ticket, an order, a refund) | \`lanes: true\`. One labeled group per role, in a \`column\` group. Put each step in the lane of the role that does it. Link each step with \`source\` to the SOP heading. If the steps do not fit the width, flowfig wraps the time columns into blocks and links the blocks with labeled stubs, so keep the whole process in one figure. Give the outcomes of one decision the same \`at\`. |
36
36
 
37
37
  flowfig draws a roadmap or a timeline with dates (\`timeline: true\`), and converts a Mermaid \`gantt\` to it. flowfig does not
38
38
  draw class or ER diagrams (fields, types, cardinality), charts of numbers or mind maps. If the user asks for one of these, say that
@@ -57,7 +57,9 @@ files, compose files, route tables and queue bindings (or from the pasted Mermai
57
57
  - every call that does not wait for an answer (fire and forget, a queue, a webhook, a callback), and every consumer of each queue
58
58
  or topic;
59
59
  - every branch and every error path (a rejected input, a retry, a dead-letter path);
60
- - every end state.
60
+ - every end state;
61
+ - for a process document (an SOP): every deadline, every message to a person (an email, a notice), every choice that a person
62
+ makes, and every wait for a reply. Put each one in a box \`sub\`, a step \`say\` or a \`data\` card. A small fact still counts.
61
63
 
62
64
  If the code does not show a fact, leave the fact out. Do not guess a part, a name or an order.
63
65