chompyy 0.0.0-stage → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (178) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +252 -2
  3. package/THIRD_PARTY_NOTICES.md +59 -0
  4. package/dist/appstate.js +116 -0
  5. package/dist/away.js +314 -0
  6. package/dist/blueprint.js +91 -0
  7. package/dist/board.js +186 -0
  8. package/dist/claudesettings.js +23 -0
  9. package/dist/cli.js +861 -0
  10. package/dist/coldstart.js +207 -0
  11. package/dist/config.js +89 -0
  12. package/dist/costs.js +162 -0
  13. package/dist/duration.js +36 -0
  14. package/dist/gate.js +69 -0
  15. package/dist/history.js +308 -0
  16. package/dist/home.js +34 -0
  17. package/dist/livequota.js +92 -0
  18. package/dist/macapp.js +57 -0
  19. package/dist/pacing.js +189 -0
  20. package/dist/picture.js +117 -0
  21. package/dist/projects.js +114 -0
  22. package/dist/quota.js +153 -0
  23. package/dist/report.js +136 -0
  24. package/dist/review.js +173 -0
  25. package/dist/runner.js +357 -0
  26. package/dist/taste.js +507 -0
  27. package/dist/triggers.js +182 -0
  28. package/dist/vendor/codeburn/claude.js +255 -0
  29. package/dist/vendor/codeburn/security.js +260 -0
  30. package/dist/vendor/codeburn/types.js +1 -0
  31. package/dist/verify.js +131 -0
  32. package/dist/workspace.js +80 -0
  33. package/package.json +48 -4
  34. package/skills/away/SKILL.md +26 -0
  35. package/skills/eat-tokens/SKILL.md +18 -0
  36. package/skills/later/SKILL.md +20 -0
  37. package/skills/taste/SKILL.md +19 -0
  38. package/vendor/diagram-design/LICENSE +21 -0
  39. package/vendor/diagram-design/SKILL.md +399 -0
  40. package/vendor/diagram-design/UPSTREAM.md +18 -0
  41. package/vendor/diagram-design/assets/example-arc-diagram.html +111 -0
  42. package/vendor/diagram-design/assets/example-architecture-containment.html +205 -0
  43. package/vendor/diagram-design/assets/example-architecture-delta.html +193 -0
  44. package/vendor/diagram-design/assets/example-architecture.html +183 -0
  45. package/vendor/diagram-design/assets/example-axonometric-plan-campus.html +108 -0
  46. package/vendor/diagram-design/assets/example-axonometric-plan-coffee-shop.html +121 -0
  47. package/vendor/diagram-design/assets/example-axonometric-plan-warehouse.html +127 -0
  48. package/vendor/diagram-design/assets/example-axonometric-plan.html +114 -0
  49. package/vendor/diagram-design/assets/example-bar.html +129 -0
  50. package/vendor/diagram-design/assets/example-beeswarm.html +384 -0
  51. package/vendor/diagram-design/assets/example-box-plot.html +127 -0
  52. package/vendor/diagram-design/assets/example-bubble.html +147 -0
  53. package/vendor/diagram-design/assets/example-bump.html +142 -0
  54. package/vendor/diagram-design/assets/example-data-flow.html +143 -0
  55. package/vendor/diagram-design/assets/example-datalake.html +269 -0
  56. package/vendor/diagram-design/assets/example-db-schema.html +302 -0
  57. package/vendor/diagram-design/assets/example-dependency.html +224 -0
  58. package/vendor/diagram-design/assets/example-deployment.html +190 -0
  59. package/vendor/diagram-design/assets/example-dp-integration.html +81 -0
  60. package/vendor/diagram-design/assets/example-dp-security-matrix.html +88 -0
  61. package/vendor/diagram-design/assets/example-er.html +202 -0
  62. package/vendor/diagram-design/assets/example-event-modeling.html +64 -0
  63. package/vendor/diagram-design/assets/example-exploded-ai-stack.html +85 -0
  64. package/vendor/diagram-design/assets/example-exploded-keyboard.html +84 -0
  65. package/vendor/diagram-design/assets/example-exploded-phone.html +83 -0
  66. package/vendor/diagram-design/assets/example-exploded-unboxing.html +84 -0
  67. package/vendor/diagram-design/assets/example-exploded.html +83 -0
  68. package/vendor/diagram-design/assets/example-fishbone.html +152 -0
  69. package/vendor/diagram-design/assets/example-flowchart.html +163 -0
  70. package/vendor/diagram-design/assets/example-gantt.html +137 -0
  71. package/vendor/diagram-design/assets/example-heatmap.html +224 -0
  72. package/vendor/diagram-design/assets/example-high-level-vertical.html +325 -0
  73. package/vendor/diagram-design/assets/example-high-level.html +301 -0
  74. package/vendor/diagram-design/assets/example-import-drawio.html +185 -0
  75. package/vendor/diagram-design/assets/example-import-excalidraw.html +70 -0
  76. package/vendor/diagram-design/assets/example-import-mermaid.html +70 -0
  77. package/vendor/diagram-design/assets/example-import-plantuml.html +107 -0
  78. package/vendor/diagram-design/assets/example-it-state.html +128 -0
  79. package/vendor/diagram-design/assets/example-journey.html +148 -0
  80. package/vendor/diagram-design/assets/example-kanban.html +174 -0
  81. package/vendor/diagram-design/assets/example-layers.html +123 -0
  82. package/vendor/diagram-design/assets/example-line.html +111 -0
  83. package/vendor/diagram-design/assets/example-loop.html +100 -0
  84. package/vendor/diagram-design/assets/example-marimekko.html +148 -0
  85. package/vendor/diagram-design/assets/example-medallion.html +159 -0
  86. package/vendor/diagram-design/assets/example-nested.html +136 -0
  87. package/vendor/diagram-design/assets/example-org-chart.html +45 -0
  88. package/vendor/diagram-design/assets/example-polar.html +116 -0
  89. package/vendor/diagram-design/assets/example-process.html +64 -0
  90. package/vendor/diagram-design/assets/example-pyramid.html +119 -0
  91. package/vendor/diagram-design/assets/example-quadrant-consultant.html +166 -0
  92. package/vendor/diagram-design/assets/example-quadrant.html +135 -0
  93. package/vendor/diagram-design/assets/example-radar.html +139 -0
  94. package/vendor/diagram-design/assets/example-requirement-traceability.html +122 -0
  95. package/vendor/diagram-design/assets/example-ridgeline.html +104 -0
  96. package/vendor/diagram-design/assets/example-sankey.html +150 -0
  97. package/vendor/diagram-design/assets/example-sbgn.html +213 -0
  98. package/vendor/diagram-design/assets/example-scatter.html +141 -0
  99. package/vendor/diagram-design/assets/example-sequence-oauth.html +227 -0
  100. package/vendor/diagram-design/assets/example-sequence.html +222 -0
  101. package/vendor/diagram-design/assets/example-service-blueprint.html +185 -0
  102. package/vendor/diagram-design/assets/example-slopegraph.html +119 -0
  103. package/vendor/diagram-design/assets/example-state-lifecycle.html +92 -0
  104. package/vendor/diagram-design/assets/example-state.html +147 -0
  105. package/vendor/diagram-design/assets/example-steps.html +78 -0
  106. package/vendor/diagram-design/assets/example-story-map.html +184 -0
  107. package/vendor/diagram-design/assets/example-streamgraph.html +99 -0
  108. package/vendor/diagram-design/assets/example-swimlane.html +172 -0
  109. package/vendor/diagram-design/assets/example-timeline.html +135 -0
  110. package/vendor/diagram-design/assets/example-tree-block-decomposition.html +151 -0
  111. package/vendor/diagram-design/assets/example-tree.html +173 -0
  112. package/vendor/diagram-design/assets/example-treemap.html +107 -0
  113. package/vendor/diagram-design/assets/example-uml-class.html +188 -0
  114. package/vendor/diagram-design/assets/example-unit-grid.html +141 -0
  115. package/vendor/diagram-design/assets/example-venn.html +110 -0
  116. package/vendor/diagram-design/assets/example-wardley.html +153 -0
  117. package/vendor/diagram-design/assets/example-waterfall.html +129 -0
  118. package/vendor/diagram-design/assets/template-dark.html +99 -0
  119. package/vendor/diagram-design/assets/template.html +100 -0
  120. package/vendor/diagram-design/references/layout-budget.md +103 -0
  121. package/vendor/diagram-design/references/output-spec.md +277 -0
  122. package/vendor/diagram-design/references/primitive-annotation.md +36 -0
  123. package/vendor/diagram-design/references/primitive-sketchy.md +43 -0
  124. package/vendor/diagram-design/references/primitives-core.md +146 -0
  125. package/vendor/diagram-design/references/semantic-patterns.md +154 -0
  126. package/vendor/diagram-design/references/style-guide.md +234 -0
  127. package/vendor/diagram-design/references/type-architecture-delta.md +143 -0
  128. package/vendor/diagram-design/references/type-architecture.md +117 -0
  129. package/vendor/diagram-design/references/type-axonometric-plan.md +83 -0
  130. package/vendor/diagram-design/references/type-bar.md +108 -0
  131. package/vendor/diagram-design/references/type-data-flow.md +371 -0
  132. package/vendor/diagram-design/references/type-db-schema.md +48 -0
  133. package/vendor/diagram-design/references/type-dependency.md +113 -0
  134. package/vendor/diagram-design/references/type-deployment.md +45 -0
  135. package/vendor/diagram-design/references/type-dp-integration.md +407 -0
  136. package/vendor/diagram-design/references/type-dp-security-matrix.md +379 -0
  137. package/vendor/diagram-design/references/type-er.md +25 -0
  138. package/vendor/diagram-design/references/type-event-modeling.md +36 -0
  139. package/vendor/diagram-design/references/type-exploded.md +115 -0
  140. package/vendor/diagram-design/references/type-fishbone.md +75 -0
  141. package/vendor/diagram-design/references/type-flowchart.md +23 -0
  142. package/vendor/diagram-design/references/type-gantt.md +45 -0
  143. package/vendor/diagram-design/references/type-heatmap.md +80 -0
  144. package/vendor/diagram-design/references/type-high-level.md +470 -0
  145. package/vendor/diagram-design/references/type-it-state.md +468 -0
  146. package/vendor/diagram-design/references/type-journey.md +55 -0
  147. package/vendor/diagram-design/references/type-kanban.md +49 -0
  148. package/vendor/diagram-design/references/type-layers.md +26 -0
  149. package/vendor/diagram-design/references/type-line.md +337 -0
  150. package/vendor/diagram-design/references/type-loop.md +223 -0
  151. package/vendor/diagram-design/references/type-medallion.md +356 -0
  152. package/vendor/diagram-design/references/type-nested.md +22 -0
  153. package/vendor/diagram-design/references/type-org-chart.md +44 -0
  154. package/vendor/diagram-design/references/type-polar.md +136 -0
  155. package/vendor/diagram-design/references/type-process.md +490 -0
  156. package/vendor/diagram-design/references/type-pyramid.md +33 -0
  157. package/vendor/diagram-design/references/type-quadrant.md +81 -0
  158. package/vendor/diagram-design/references/type-radar.md +82 -0
  159. package/vendor/diagram-design/references/type-requirement-traceability.md +45 -0
  160. package/vendor/diagram-design/references/type-sankey.md +75 -0
  161. package/vendor/diagram-design/references/type-sbgn.md +80 -0
  162. package/vendor/diagram-design/references/type-scatter.md +276 -0
  163. package/vendor/diagram-design/references/type-sequence.md +130 -0
  164. package/vendor/diagram-design/references/type-service-blueprint.md +103 -0
  165. package/vendor/diagram-design/references/type-state.md +30 -0
  166. package/vendor/diagram-design/references/type-steps.md +180 -0
  167. package/vendor/diagram-design/references/type-story-map.md +46 -0
  168. package/vendor/diagram-design/references/type-swimlane.md +22 -0
  169. package/vendor/diagram-design/references/type-timeline.md +20 -0
  170. package/vendor/diagram-design/references/type-tree.md +24 -0
  171. package/vendor/diagram-design/references/type-treemap.md +137 -0
  172. package/vendor/diagram-design/references/type-uml-class.md +65 -0
  173. package/vendor/diagram-design/references/type-unit-grid.md +63 -0
  174. package/vendor/diagram-design/references/type-venn.md +26 -0
  175. package/vendor/diagram-design/references/type-wardley.md +39 -0
  176. package/vendor/diagram-design/references/type-waterfall.md +75 -0
  177. package/vendor/diagram-design/scripts/self_check.py +1177 -0
  178. package/vendor/diagram-design/scripts/verify_geometry.py +696 -0
@@ -0,0 +1,696 @@
1
+ #!/usr/bin/env python3
2
+ """Verify no diagram label mask is clipped by a node painted after it.
3
+
4
+ SKILL.md §6 keeps an arrow label 6-10px clear of its connector, and §5 fixes the
5
+ paint order as background -> zones -> arrows -> labels -> nodes. Nothing keeps a
6
+ label mask off a *node*, so a label whose mask lands partly inside a node
7
+ rectangle that is painted later gets covered by the node fill: the text renders
8
+ as a fragment sitting on the node border.
9
+
10
+ Paint order is what makes this a defect rather than a stylistic choice:
11
+
12
+ * A mask overlapping a zone container is fine - zones are painted before labels,
13
+ so the label stays on top. Zone eyebrows rely on this.
14
+ * A mask overlapping a node declared *later* in the document is clipped by that
15
+ node. That is the failure this check reports.
16
+
17
+ Shape heuristics follow the shipped templates:
18
+
19
+ * A node is a `<rect>` at least 60x40 - large enough for a title and sublabel.
20
+ * A label mask is a `<rect>` 20-200 wide and 8-14 tall - the masking plate that
21
+ SKILL.md §6 prescribes (markup in references/primitives-core.md) for arrow
22
+ labels and zone eyebrows. The width cap covers the long mono plates shipped
23
+ in example-sequence-oauth.html (128px) and the wider plates CJK labels need
24
+ at the same glyph count.
25
+ * A mask fully contained in a node is a badge chip (`EXT`, `EDGE`, `ORIG`) and
26
+ is legal.
27
+
28
+ It also checks connector routing (references/primitives-core.md rule 1). A
29
+ connector is a `<path>` or `<line>` that carries an arrow marker; a node, for
30
+ this check, is a stroked `<rect>` at least 60x40, so unstroked quadrant fills
31
+ and chart bars stay out of it. Five shapes are reported:
32
+
33
+ * A straight segment that is neither horizontal nor vertical. Loop write-back
34
+ spokes (`class="spoke"`) are the documented radial exception and skipped.
35
+ * A horizontal or vertical segment lying on a node's border. It hides behind
36
+ the node fill, so the arrow appears to start at the corner.
37
+ * A connector endpoint within 8px of a node corner, where the rounded corner
38
+ makes the port ambiguous.
39
+ * Two connectors leaving (or two arriving at) the same edge of a node closer
40
+ than primitives-core.md rule 4 allows: 12px, or 8px on an edge shorter than
41
+ 48px. A head-to-tail chain joint is allowed.
42
+ * Two connectors drawn within 1px of each other along a continuous stretch
43
+ longer than 4px, straight or curved: the stacked trunk primitives-core.md
44
+ rule 3 forbids. Curves and arcs are flattened into short chords so their
45
+ shape is compared too. Forks and merges from one point count from that
46
+ point; only a head-to-tail joint is exempt near the joint.
47
+
48
+ An arrowed path whose data the checker cannot parse is reported too, so a
49
+ connector never passes because nothing read it.
50
+
51
+ Usage, from the installed skill directory:
52
+ python3 scripts/verify_geometry.py path/to/diagram.html
53
+ python3 scripts/verify_geometry.py --all
54
+
55
+ From a repository checkout, `python3 scripts/verify-geometry.py` runs this file.
56
+ """
57
+
58
+ from __future__ import annotations
59
+
60
+ import argparse
61
+ import math
62
+ import re
63
+ import sys
64
+ from pathlib import Path
65
+
66
+ ASSET_DIR = Path(__file__).resolve().parent.parent / "assets"
67
+
68
+ NODE_MIN_W = 60.0
69
+ NODE_MIN_H = 40.0
70
+ MASK_MIN_W = 20.0
71
+ MASK_MAX_W = 200.0
72
+ MASK_MIN_H = 8.0
73
+ MASK_MAX_H = 14.0
74
+ EPSILON = 0.5
75
+
76
+
77
+ class Rect:
78
+ __slots__ = ("x", "y", "w", "h", "line", "offset")
79
+
80
+ def __init__(self, x, y, w, h, line, offset) -> None:
81
+ self.x, self.y, self.w, self.h = x, y, w, h
82
+ self.line, self.offset = line, offset
83
+
84
+ @property
85
+ def right(self) -> float:
86
+ return self.x + self.w
87
+
88
+ @property
89
+ def bottom(self) -> float:
90
+ return self.y + self.h
91
+
92
+ def __repr__(self) -> str:
93
+ return f"({self.x:g},{self.y:g} {self.w:g}x{self.h:g})"
94
+
95
+
96
+ def parse_rects(source: str) -> list[Rect]:
97
+ """Mask and node bounds in the same translated canvas as connectors."""
98
+ rects: list[Rect] = []
99
+ for tag, attrs, start, frame in shapes(source):
100
+ if tag != "rect" or frame is None:
101
+ continue
102
+ x, y, w, h = (number(attrs, key) for key in ("x", "y", "width", "height"))
103
+ if None in (x, y, w, h):
104
+ continue
105
+ rects.append(Rect(x + frame[0], y + frame[1], w, h,
106
+ source.count("\n", 0, start) + 1, start))
107
+ return rects
108
+
109
+
110
+ def overlap(a: Rect, b: Rect) -> tuple[float, float]:
111
+ return (
112
+ min(a.right, b.right) - max(a.x, b.x),
113
+ min(a.bottom, b.bottom) - max(a.y, b.y),
114
+ )
115
+
116
+
117
+ def contained(inner: Rect, outer: Rect) -> bool:
118
+ return (
119
+ inner.x >= outer.x - EPSILON
120
+ and inner.y >= outer.y - EPSILON
121
+ and inner.right <= outer.right + EPSILON
122
+ and inner.bottom <= outer.bottom + EPSILON
123
+ )
124
+
125
+
126
+ TAG_RE = re.compile(
127
+ r"<!--[\s\S]*?-->|<(?P<close>/?)(?P<tag>g|svg|defs|symbol|marker|pattern|clipPath|mask|rect|path|line)\b(?P<attrs>(?:\"[^\"]*\"|'[^']*'|[^'\">])*?)(?P<empty>/?)>",
128
+ re.IGNORECASE,
129
+ )
130
+ ATTR_RE = re.compile(r'''([^\s"'>/=]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|[^\s>]*))?''')
131
+ TRANSLATE_RE = re.compile(
132
+ r"^\s*translate\(\s*([-+]?[\d.]+)(?:[\s,]+([-+]?[\d.]+))?\s*\)\s*$"
133
+ )
134
+ PATH_COMMAND_RE = re.compile(r"[\s,]*([MmLlHhVvQqCcSsTtAaZz])")
135
+ PATH_NUMBER_RE = re.compile(r"[\s,]*([-+]?(?:\d+\.?\d*|\.\d+)(?:[eE][-+]?\d+)?)")
136
+ # Arc flags are one character and may run into the next number: `A 8 8 0 0120 20`.
137
+ PATH_FLAG_RE = re.compile(r"[\s,]*([01])")
138
+ PATH_END_RE = re.compile(r"[\s,]*$")
139
+ # Parameters each path command consumes per repetition.
140
+ PATH_ARITY = {"M": 2, "L": 2, "H": 1, "V": 1, "Q": 4, "T": 2, "C": 6, "S": 4, "A": 7, "Z": 0}
141
+
142
+ AXIS_TOLERANCE = 0.5 # a segment this close to axis-aligned is orthogonal
143
+ BORDER_TOLERANCE = 1.0 # a segment this close to a node edge lies on it
144
+ BORDER_MIN_RUN = 4.0 # shorter shared runs are a port touching the edge, not a ride
145
+ PORT_TOLERANCE = 4.0 # an endpoint this close to a node outline attaches to it
146
+ CORNER_CLEARANCE = 8.0 # ports keep this far from a corner (primitives-core rule 1)
147
+ SHARED_PORT_MIN = 12.0 # two ports on one edge keep at least this far apart (rule 4)
148
+ SMALL_PORT_MIN = 8.0 # rule 4's floor for very small boxes...
149
+ SMALL_EDGE = 48.0 # ...meaning an edge shorter than this
150
+
151
+
152
+ def attribute(attrs: str, name: str) -> str | None:
153
+ for match in ATTR_RE.finditer(attrs):
154
+ if match.group(1) == name:
155
+ return match.group(2) if match.group(2) is not None else match.group(3)
156
+ return None
157
+
158
+
159
+ def number(attrs: str, name: str) -> float | None:
160
+ value = attribute(attrs, name)
161
+ try:
162
+ return float(value) if value is not None else None
163
+ except ValueError:
164
+ return None
165
+
166
+
167
+ Segment = tuple[str, float, float, float, float] # (kind, x1, y1, x2, y2)
168
+
169
+
170
+ CHORD_LENGTH = 2.0 # curves are flattened into chords about this long
171
+
172
+
173
+ def chord_count(points: list[tuple[float, float]]) -> int:
174
+ """Chords to split a curve into, from the length of its control polygon."""
175
+
176
+ length = sum(math.dist(a, b) for a, b in zip(points, points[1:]))
177
+ return max(4, min(256, math.ceil(length / CHORD_LENGTH)))
178
+
179
+
180
+ def bezier(points: list[tuple[float, float]]) -> list[tuple[float, float]]:
181
+ """Points along a quadratic or cubic Bezier, excluding its start."""
182
+
183
+ steps = chord_count(points)
184
+ out = []
185
+ for i in range(1, steps + 1):
186
+ t = i / steps
187
+ level = points
188
+ while len(level) > 1: # de Casteljau
189
+ level = [
190
+ (a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t)
191
+ for a, b in zip(level, level[1:])
192
+ ]
193
+ out.append(level[0])
194
+ return out
195
+
196
+
197
+ def arc(
198
+ start: tuple[float, float], rx: float, ry: float, rotation: float,
199
+ large: float, sweep: float, end: tuple[float, float],
200
+ ) -> list[tuple[float, float]]:
201
+ """Points along an SVG elliptical arc (SVG 2 appendix B.2.4), excluding its start."""
202
+
203
+ (x1, y1), (x2, y2) = start, end
204
+ rx, ry = abs(rx), abs(ry)
205
+ if rx == 0 or ry == 0 or start == end:
206
+ return [end]
207
+ phi = math.radians(rotation)
208
+ cos_p, sin_p = math.cos(phi), math.sin(phi)
209
+ hx, hy = (x1 - x2) / 2, (y1 - y2) / 2
210
+ x1p, y1p = cos_p * hx + sin_p * hy, -sin_p * hx + cos_p * hy
211
+ scale = (x1p / rx) ** 2 + (y1p / ry) ** 2
212
+ if scale > 1:
213
+ rx, ry = rx * math.sqrt(scale), ry * math.sqrt(scale)
214
+ denominator = (rx * y1p) ** 2 + (ry * x1p) ** 2
215
+ numerator = (rx * ry) ** 2 - denominator
216
+ root = math.sqrt(max(0.0, numerator / denominator)) if denominator else 0.0
217
+ if large == sweep:
218
+ root = -root
219
+ cxp, cyp = root * rx * y1p / ry, -root * ry * x1p / rx
220
+ cx = cos_p * cxp - sin_p * cyp + (x1 + x2) / 2
221
+ cy = sin_p * cxp + cos_p * cyp + (y1 + y2) / 2
222
+ ux, uy = (x1p - cxp) / rx, (y1p - cyp) / ry
223
+ vx, vy = (-x1p - cxp) / rx, (-y1p - cyp) / ry
224
+ theta = math.atan2(uy, ux)
225
+ delta = math.atan2(ux * vy - uy * vx, ux * vx + uy * vy)
226
+ if not sweep and delta > 0:
227
+ delta -= 2 * math.pi
228
+ elif sweep and delta < 0:
229
+ delta += 2 * math.pi
230
+ steps = max(4, min(256, math.ceil(abs(delta) * max(rx, ry) / CHORD_LENGTH)))
231
+ out = []
232
+ for i in range(1, steps + 1):
233
+ angle = theta + delta * i / steps
234
+ ex, ey = rx * math.cos(angle), ry * math.sin(angle)
235
+ out.append((cos_p * ex - sin_p * ey + cx, sin_p * ex + cos_p * ey + cy))
236
+ out[-1] = end
237
+ return out
238
+
239
+
240
+ def path_segments(d: str) -> list[Segment] | None:
241
+ """Flatten a path into straight segments and curve chords, or None if unparseable.
242
+
243
+ Straight commands become one `line` segment each. Curves and arcs become a
244
+ run of short `curve` chords, so overlap checks can follow their shape.
245
+ """
246
+
247
+ segments: list[Segment] = []
248
+ x = y = start_x = start_y = 0.0
249
+ previous_control: tuple[str, float, float] | None = None # for S and T reflection
250
+ command = ""
251
+ pos = 0
252
+ while not PATH_END_RE.match(d, pos):
253
+ match = PATH_COMMAND_RE.match(d, pos)
254
+ if match:
255
+ command, pos = match.group(1), match.end()
256
+ if command in "Zz":
257
+ if (x, y) != (start_x, start_y):
258
+ segments.append(("line", x, y, start_x, start_y))
259
+ x, y = start_x, start_y
260
+ continue
261
+ elif not command or command in "Zz":
262
+ return None # numbers before the first command or after a closepath
263
+ upper = command.upper()
264
+ args: list[float] = []
265
+ for slot in range(PATH_ARITY[upper]):
266
+ pattern = PATH_FLAG_RE if upper == "A" and slot in (3, 4) else PATH_NUMBER_RE
267
+ match = pattern.match(d, pos)
268
+ if not match:
269
+ return None # truncated arguments or an unexpected character
270
+ args.append(float(match.group(1)))
271
+ pos = match.end()
272
+ relative = command.islower()
273
+ ox, oy = (x, y) if relative else (0.0, 0.0)
274
+ if upper == "H":
275
+ nx, ny = args[0] + ox, y
276
+ elif upper == "V":
277
+ nx, ny = x, args[0] + oy
278
+ else:
279
+ nx, ny = args[-2] + ox, args[-1] + oy
280
+ if upper == "M":
281
+ x, y = start_x, start_y = nx, ny
282
+ command = "l" if relative else "L" # implicit lineto after moveto
283
+ previous_control = None
284
+ continue
285
+ if upper in "LHV":
286
+ segments.append(("line", x, y, nx, ny))
287
+ previous_control = None
288
+ else:
289
+ pairs = [(args[i] + ox, args[i + 1] + oy) for i in range(0, len(args) - 1, 2)]
290
+ if upper in "ST":
291
+ family = "C" if upper == "S" else "Q"
292
+ if previous_control and previous_control[0] == family:
293
+ reflected = (2 * x - previous_control[1], 2 * y - previous_control[2])
294
+ else:
295
+ reflected = (x, y)
296
+ pairs = [reflected] + pairs
297
+ if upper == "A":
298
+ points = arc((x, y), args[0], args[1], args[2], args[3], args[4], (nx, ny))
299
+ previous_control = None
300
+ else:
301
+ points = bezier([(x, y)] + pairs)
302
+ family = "C" if upper in "CS" else "Q"
303
+ previous_control = (family, pairs[-2][0], pairs[-2][1])
304
+ px, py = x, y
305
+ for qx, qy in points:
306
+ segments.append(("curve", px, py, qx, qy))
307
+ px, py = qx, qy
308
+ x, y = nx, ny
309
+ return segments
310
+
311
+
312
+ Offset = tuple[float, float]
313
+ DEFINITION_TAGS = {"defs", "symbol", "marker", "pattern", "clippath", "mask"}
314
+
315
+
316
+ def translation(attrs: str) -> Offset | None:
317
+ """Offset a `transform` applies, (0, 0) when absent, None when not a translate."""
318
+
319
+ transform = attribute(attrs, "transform")
320
+ if transform is None:
321
+ return 0.0, 0.0
322
+ match = TRANSLATE_RE.match(transform)
323
+ if not match:
324
+ return None
325
+ return float(match.group(1)), float(match.group(2) or 0.0)
326
+
327
+
328
+ def shapes(source: str):
329
+ """Yield (tag, attrs, match start, offset) for each rect, path, and line.
330
+
331
+ Offsets accumulate `translate()` on enclosing groups, so panels drawn with
332
+ the same local coordinates (architecture delta snapshots) are compared in
333
+ canvas space. Under any other transform, or inside a nested `<svg>` icon,
334
+ the offset is None and the element is left out of connector checks. Shapes
335
+ inside definition-only containers do not paint at their source coordinates
336
+ and are also left out; this does not resolve referenced <use> instances.
337
+ """
338
+
339
+ stack: list[Offset | None] = []
340
+ containers: list[str] = []
341
+ for match in TAG_RE.finditer(source):
342
+ if match.group("tag") is None: # Inert comments cannot change paint custody.
343
+ continue
344
+ tag, attrs = match.group("tag").lower(), match.group("attrs")
345
+ if tag in {"g", "svg"} or tag in DEFINITION_TAGS:
346
+ if match.group("close"):
347
+ if stack:
348
+ stack.pop()
349
+ containers.pop()
350
+ elif not match.group("empty"):
351
+ nested_svg = tag == "svg" and bool(stack)
352
+ stack.append(None if nested_svg else translation(attrs))
353
+ containers.append(tag)
354
+ continue
355
+ if any(container in DEFINITION_TAGS for container in containers):
356
+ continue
357
+ frame: Offset | None = (0.0, 0.0)
358
+ for step in stack + [translation(attrs)]:
359
+ if step is None or frame is None:
360
+ frame = None
361
+ break
362
+ frame = (frame[0] + step[0], frame[1] + step[1])
363
+ yield tag, attrs, match.start(), frame
364
+
365
+
366
+ def shifted(segments: list[Segment], frame: Offset) -> list[Segment]:
367
+ dx, dy = frame
368
+ return [(kind, x1 + dx, y1 + dy, x2 + dx, y2 + dy) for kind, x1, y1, x2, y2 in segments]
369
+
370
+
371
+ def connectors(source: str) -> list[tuple[int, str, list[Segment] | None]]:
372
+ """Return (line number, short label, segments) for every arrowed connector.
373
+
374
+ Segments are None for a path the parser cannot read, so the caller can
375
+ fail closed instead of passing a connector nothing checked.
376
+ """
377
+
378
+ found: list[tuple[int, str, list[Segment] | None]] = []
379
+ for tag, attrs, start, frame in shapes(source):
380
+ if tag == "rect" or frame is None:
381
+ continue
382
+ if attribute(attrs, "marker-end") is None and attribute(attrs, "marker-start") is None:
383
+ continue
384
+ if "spoke" in (attribute(attrs, "class") or "").split():
385
+ continue
386
+ line = source.count("\n", 0, start) + 1
387
+ if tag == "line":
388
+ coords = [number(attrs, key) for key in ("x1", "y1", "x2", "y2")]
389
+ if None in coords:
390
+ continue
391
+ x1, y1, x2, y2 = coords # type: ignore[misc]
392
+ segments: list[Segment] | None = [("line", x1, y1, x2, y2)]
393
+ label = f"<line {x1:g},{y1:g} -> {x2:g},{y2:g}>"
394
+ else:
395
+ d = attribute(attrs, "d") or ""
396
+ segments = path_segments(d)
397
+ label = f'<path d="{d if len(d) <= 48 else d[:45] + "..."}">'
398
+ if segments is None:
399
+ found.append((line, label, None))
400
+ elif segments:
401
+ found.append((line, label, shifted(segments, frame)))
402
+ return found
403
+
404
+
405
+ def stroked_nodes(source: str) -> list[Rect]:
406
+ nodes: list[Rect] = []
407
+ for tag, attrs, start, frame in shapes(source):
408
+ if tag != "rect" or frame is None:
409
+ continue
410
+ x, y, w, h = (number(attrs, key) for key in ("x", "y", "width", "height"))
411
+ if None in (x, y, w, h) or w < NODE_MIN_W or h < NODE_MIN_H: # type: ignore[operator]
412
+ continue
413
+ stroke = (attribute(attrs, "stroke") or "none").strip().lower()
414
+ if stroke in {"none", "transparent"} or number(attrs, "stroke-width") == 0:
415
+ continue
416
+ line = source.count("\n", 0, start) + 1
417
+ nodes.append(Rect(x + frame[0], y + frame[1], w, h, line, start))
418
+ return nodes
419
+
420
+
421
+ def rides_border(segment: Segment, node: Rect) -> str | None:
422
+ _, x1, y1, x2, y2 = segment
423
+ if abs(y1 - y2) <= AXIS_TOLERANCE:
424
+ low, high = sorted((x1, x2))
425
+ shared = min(high, node.right) - max(low, node.x)
426
+ for edge, name in ((node.y, "top"), (node.bottom, "bottom")):
427
+ if abs(y1 - edge) <= BORDER_TOLERANCE and shared > BORDER_MIN_RUN:
428
+ return name
429
+ if abs(x1 - x2) <= AXIS_TOLERANCE:
430
+ low, high = sorted((y1, y2))
431
+ shared = min(high, node.bottom) - max(low, node.y)
432
+ for edge, name in ((node.x, "left"), (node.right, "right")):
433
+ if abs(x1 - edge) <= BORDER_TOLERANCE and shared > BORDER_MIN_RUN:
434
+ return name
435
+ return None
436
+
437
+
438
+ def attached(px: float, py: float, node: Rect) -> bool:
439
+ """True when an endpoint sits on (or just off) the node's outline."""
440
+
441
+ outside_x = max(node.x - px, 0.0, px - node.right)
442
+ outside_y = max(node.y - py, 0.0, py - node.bottom)
443
+ inside = min(px - node.x, node.right - px, py - node.y, node.bottom - py)
444
+ return max(outside_x, outside_y) <= PORT_TOLERANCE and inside <= PORT_TOLERANCE
445
+
446
+
447
+ def port_edge(px: float, py: float, node: Rect) -> tuple[str, float, float]:
448
+ """Return (side, edge length, position along the edge) for an attached port."""
449
+
450
+ distances = {
451
+ "top": abs(py - node.y),
452
+ "bottom": abs(py - node.bottom),
453
+ "left": abs(px - node.x),
454
+ "right": abs(px - node.right),
455
+ }
456
+ side = min(distances, key=distances.__getitem__)
457
+ if side in {"top", "bottom"}:
458
+ return side, node.w, px
459
+ return side, node.h, py
460
+
461
+
462
+ def near_corner(px: float, py: float, node: Rect) -> tuple[float, float] | None:
463
+ if not attached(px, py, node):
464
+ return None
465
+ for cx in (node.x, node.right):
466
+ for cy in (node.y, node.bottom):
467
+ if max(abs(px - cx), abs(py - cy)) < CORNER_CLEARANCE:
468
+ return cx, cy
469
+ return None
470
+
471
+
472
+ def check_connectors(path: Path, source: str) -> list[str]:
473
+ nodes = stroked_nodes(source)
474
+ findings: list[str] = []
475
+ ports: list[tuple[int, float, float, int, str, str, int]] = []
476
+ parsed: list[tuple[int, str, list[Segment]]] = []
477
+ for ident, (line, label, segments) in enumerate(connectors(source)):
478
+ where = f"{path.name}:{line}: connector {label}"
479
+ if segments is None:
480
+ findings.append(
481
+ f"{where} has path data the checker cannot parse"
482
+ f" - write it with absolute M/L/H/V/Q/C/A commands"
483
+ )
484
+ continue
485
+ parsed.append((line, label, segments))
486
+ for kind, x1, y1, x2, y2 in segments:
487
+ if kind == "line" and abs(x1 - x2) > AXIS_TOLERANCE and abs(y1 - y2) > AXIS_TOLERANCE:
488
+ findings.append(
489
+ f"{where} has a diagonal segment {x1:g},{y1:g} -> {x2:g},{y2:g}"
490
+ f" - route it as a rounded right-angle elbow"
491
+ )
492
+ break
493
+ for segment in segments:
494
+ if segment[0] != "line":
495
+ continue
496
+ hit = next(((node, side) for node in nodes if (side := rides_border(segment, node))), None)
497
+ if hit:
498
+ node, side = hit
499
+ findings.append(
500
+ f"{where} runs along the {side} border of node {node} (line {node.line})"
501
+ f" - leave the node perpendicular to the edge the port sits on"
502
+ )
503
+ break
504
+ ends = ((segments[0][1], segments[0][2]), (segments[-1][3], segments[-1][4]))
505
+ for px, py in ends:
506
+ corner = next(((node, c) for node in nodes if (c := near_corner(px, py, node))), None)
507
+ if corner:
508
+ node, (cx, cy) = corner
509
+ findings.append(
510
+ f"{where} attaches at {px:g},{py:g}, within {CORNER_CLEARANCE:g}px of the"
511
+ f" {cx:g},{cy:g} corner of node {node} (line {node.line})"
512
+ f" - move the port onto the straight part of the edge"
513
+ )
514
+ break
515
+ for (px, py), role in zip(ends, ("start", "end")):
516
+ for index, node in enumerate(nodes):
517
+ if attached(px, py, node):
518
+ ports.append((index, px, py, line, label, role, ident))
519
+ findings.extend(shared_ports(path, nodes, ports))
520
+ findings.extend(stacked_connectors(path, parsed))
521
+ return findings
522
+
523
+
524
+ STACK_TOLERANCE = 1.0 # strokes this close are drawn on top of each other
525
+ SAMPLE_STEP = 1.0 # distance between samples when measuring a shared run
526
+
527
+
528
+ def bounds(segments: list[Segment], pad: float) -> tuple[float, float, float, float]:
529
+ xs = [v for _, x1, _, x2, _ in segments for v in (x1, x2)]
530
+ ys = [v for _, _, y1, _, y2 in segments for v in (y1, y2)]
531
+ return min(xs) - pad, min(ys) - pad, max(xs) + pad, max(ys) + pad
532
+
533
+
534
+ def distance_to_segment(px: float, py: float, segment: Segment) -> float:
535
+ _, x1, y1, x2, y2 = segment
536
+ dx, dy = x2 - x1, y2 - y1
537
+ length_sq = dx * dx + dy * dy
538
+ t = 0.0 if not length_sq else max(0.0, min(1.0, ((px - x1) * dx + (py - y1) * dy) / length_sq))
539
+ return math.hypot(px - (x1 + t * dx), py - (y1 + t * dy))
540
+
541
+
542
+ def shared_run(a: list[Segment], b: list[Segment]) -> float:
543
+ """Longest continuous stretch of connector `a` drawn within 1px of connector `b`.
544
+
545
+ Straight runs and curve chords count alike, so a shared curved trunk is
546
+ caught as well as a straight one. The run must be continuous: two separate
547
+ right-angle crossings each touch for a pixel or two and never add up to a
548
+ shared trunk. Only a head-to-tail joint, where one arrow ends and the
549
+ other starts, is exempt near the joint; a fork or merge from one shared
550
+ point is measured from that point.
551
+ """
552
+
553
+ left, top, right, bottom = bounds(b, STACK_TOLERANCE)
554
+ a_left, a_top, a_right, a_bottom = bounds(a, 0.0)
555
+ if a_right < left or a_left > right or a_bottom < top or a_top > bottom:
556
+ return 0.0
557
+ a_start, a_end = (a[0][1], a[0][2]), (a[-1][3], a[-1][4])
558
+ b_start, b_end = (b[0][1], b[0][2]), (b[-1][3], b[-1][4])
559
+ joints = [
560
+ joint
561
+ for joint, other in ((a_end, b_start), (a_start, b_end))
562
+ if math.dist(joint, other) <= STACK_TOLERANCE
563
+ ]
564
+ boxes = [bounds([segment], STACK_TOLERANCE) for segment in b]
565
+
566
+ def near(px: float, py: float) -> bool:
567
+ if not (left <= px <= right and top <= py <= bottom):
568
+ return False
569
+ if any(math.dist((px, py), joint) < CORNER_CLEARANCE for joint in joints):
570
+ return False
571
+ return any(
572
+ bx0 <= px <= bx1 and by0 <= py <= by1
573
+ and distance_to_segment(px, py, segment) <= STACK_TOLERANCE
574
+ for segment, (bx0, by0, bx1, by1) in zip(b, boxes)
575
+ )
576
+
577
+ longest = run = 0
578
+ for _, x1, y1, x2, y2 in a:
579
+ steps = max(1, math.ceil(math.hypot(x2 - x1, y2 - y1) / SAMPLE_STEP))
580
+ for i in range(steps):
581
+ if near(x1 + (x2 - x1) * i / steps, y1 + (y2 - y1) * i / steps):
582
+ run += 1
583
+ longest = max(longest, run)
584
+ else:
585
+ run = 0
586
+ return longest * SAMPLE_STEP
587
+
588
+
589
+ def stacked_connectors(
590
+ path: Path, parsed: list[tuple[int, str, list[Segment]]]
591
+ ) -> list[str]:
592
+ """Report two connectors drawn on top of each other (primitives-core rule 3)."""
593
+
594
+ findings: list[str] = []
595
+ for i, (line_a, label_a, segments_a) in enumerate(parsed):
596
+ for line_b, label_b, segments_b in parsed[i + 1 :]:
597
+ shared = max(shared_run(segments_a, segments_b), shared_run(segments_b, segments_a))
598
+ if shared > BORDER_MIN_RUN:
599
+ findings.append(
600
+ f"{path.name}:{line_b}: connector {label_b} runs on top of {label_a}"
601
+ f" (line {line_a}) for about {shared:g}px - offset one route by at least"
602
+ f" {SHARED_PORT_MIN:g}px so each arrow stays traceable"
603
+ )
604
+ return findings
605
+
606
+
607
+ def shared_ports(
608
+ path: Path, nodes: list[Rect], ports: list[tuple[int, float, float, int, str, str, int]]
609
+ ) -> list[str]:
610
+ """Report two connectors leaving, or two arriving, at one point on a node.
611
+
612
+ A head-to-tail joint, where one arrow lands and the next leaves, is a chain
613
+ the reader traces in order (Medallion's documented promotion joints), so it
614
+ is not reported. Two starts are a fork and two ends are a merge.
615
+ """
616
+
617
+ findings: list[str] = []
618
+ for i, (node_a, ax, ay, line_a, label_a, role_a, id_a) in enumerate(ports):
619
+ for node_b, bx, by, line_b, label_b, role_b, id_b in ports[i + 1 :]:
620
+ if node_a != node_b or id_a == id_b or role_a != role_b:
621
+ continue
622
+ node = nodes[node_a]
623
+ side_a, length, along_a = port_edge(ax, ay, node)
624
+ side_b, _, along_b = port_edge(bx, by, node)
625
+ if side_a != side_b:
626
+ continue
627
+ minimum = SMALL_PORT_MIN if length < SMALL_EDGE else SHARED_PORT_MIN
628
+ gap = abs(along_a - along_b)
629
+ if gap < minimum:
630
+ findings.append(
631
+ f"{path.name}:{line_b}: connector {label_b} attaches {gap:g}px from"
632
+ f" {label_a} (line {line_a}) on the {side_a} edge of node {node}"
633
+ f" (line {node.line}) - fan the ports at least {minimum:g}px apart"
634
+ )
635
+ return findings
636
+
637
+
638
+ def check(path: Path) -> list[str]:
639
+ source = path.read_text(encoding="utf-8")
640
+ rects = parse_rects(source)
641
+ nodes = [r for r in rects if r.w >= NODE_MIN_W and r.h >= NODE_MIN_H]
642
+ masks = [
643
+ r
644
+ for r in rects
645
+ if MASK_MIN_W <= r.w <= MASK_MAX_W and MASK_MIN_H <= r.h <= MASK_MAX_H
646
+ ]
647
+
648
+ findings: list[str] = []
649
+ for mask in masks:
650
+ for node in nodes:
651
+ if node.offset <= mask.offset:
652
+ continue # painted before the label; the label stays on top
653
+ dx, dy = overlap(mask, node)
654
+ if dx <= 1.0 or dy <= 1.0 or contained(mask, node):
655
+ continue
656
+ findings.append(
657
+ f"{path.name}:{mask.line}: label mask {mask} is clipped by node "
658
+ f"{node} declared later at line {node.line} (overlap {dx:g}x{dy:g}px)"
659
+ f" - move the label onto a free segment of its connector"
660
+ )
661
+ break
662
+ findings.extend(check_connectors(path, source))
663
+ return findings
664
+
665
+
666
+ def targets(args: argparse.Namespace) -> list[Path]:
667
+ if args.all:
668
+ return sorted(ASSET_DIR.glob("*.html"))
669
+ return [Path(p) for p in args.files]
670
+
671
+
672
+ def main() -> int:
673
+ parser = argparse.ArgumentParser(description=__doc__)
674
+ parser.add_argument("files", nargs="*", help="HTML diagrams to check")
675
+ parser.add_argument("--all", action="store_true", help="check every shipped asset")
676
+ args = parser.parse_args()
677
+
678
+ paths = targets(args)
679
+ if not paths:
680
+ parser.error("pass one or more files, or --all")
681
+
682
+ findings: list[str] = []
683
+ for path in paths:
684
+ if not path.exists():
685
+ findings.append(f"{path}: file not found")
686
+ continue
687
+ findings.extend(check(path))
688
+
689
+ for finding in findings:
690
+ print(finding)
691
+ print(f"Summary: {len(paths)} file(s) checked, {len(findings)} finding(s).")
692
+ return 1 if findings else 0
693
+
694
+
695
+ if __name__ == "__main__":
696
+ sys.exit(main())