dsh-archify-projects 0.0.0-stage → 0.1.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 (148) hide show
  1. package/README.md +204 -2
  2. package/cordis.patch.yml +99 -0
  3. package/dist/client.js +2261 -0
  4. package/dist/client.js.map +1 -0
  5. package/docs/CONTAINER.md +197 -0
  6. package/docs/DESIGN.md +905 -0
  7. package/docs/HANDOVER.md +391 -0
  8. package/docs/PUBLISH.md +107 -0
  9. package/icon.svg +12 -0
  10. package/lib/host/archify-skill.js +116 -0
  11. package/lib/host/archify-skill.js.map +1 -0
  12. package/lib/host/config.js +95 -0
  13. package/lib/host/config.js.map +1 -0
  14. package/lib/host/context.js +28 -0
  15. package/lib/host/context.js.map +1 -0
  16. package/lib/host/git.js +185 -0
  17. package/lib/host/git.js.map +1 -0
  18. package/lib/host/http.js +184 -0
  19. package/lib/host/http.js.map +1 -0
  20. package/lib/host/index.js +90 -0
  21. package/lib/host/index.js.map +1 -0
  22. package/lib/host/policy.js +124 -0
  23. package/lib/host/policy.js.map +1 -0
  24. package/lib/host/routes.js +667 -0
  25. package/lib/host/routes.js.map +1 -0
  26. package/lib/host/runner.js +913 -0
  27. package/lib/host/runner.js.map +1 -0
  28. package/lib/host/store.js +370 -0
  29. package/lib/host/store.js.map +1 -0
  30. package/lib/host/workspace.js +65 -0
  31. package/lib/host/workspace.js.map +1 -0
  32. package/lib/shared/format.js +138 -0
  33. package/lib/shared/format.js.map +1 -0
  34. package/lib/shared/prompt.js +257 -0
  35. package/lib/shared/prompt.js.map +1 -0
  36. package/lib/shared/protocol.js +31 -0
  37. package/lib/shared/protocol.js.map +1 -0
  38. package/lib/shared/types.js +173 -0
  39. package/lib/shared/types.js.map +1 -0
  40. package/locale/en.json +6 -0
  41. package/locale/zh.json +6 -0
  42. package/package.json +98 -4
  43. package/skills/archify/LICENSE +22 -0
  44. package/skills/archify/SKILL.md +109 -0
  45. package/skills/archify/THIRD_PARTY_NOTICES.md +69 -0
  46. package/skills/archify/assets/JetBrainsMono-OFL.txt +93 -0
  47. package/skills/archify/assets/template.html +13709 -0
  48. package/skills/archify/bin/archify.mjs +6936 -0
  49. package/skills/archify/bin/delivery-update.mjs +91 -0
  50. package/skills/archify/bin/finalize.mjs +895 -0
  51. package/skills/archify/bin/open-artifact.mjs +146 -0
  52. package/skills/archify/bin/preview.mjs +969 -0
  53. package/skills/archify/bin/recover-output.mjs +41 -0
  54. package/skills/archify/bin/visual-check.mjs +2667 -0
  55. package/skills/archify/brand-marks/README.md +31 -0
  56. package/skills/archify/brand-marks/catalog.json +131 -0
  57. package/skills/archify/delta/architecture-delta.mjs +1313 -0
  58. package/skills/archify/examples/agent-run.lifecycle.json +55 -0
  59. package/skills/archify/examples/agent-tool-call.workflow.json +74 -0
  60. package/skills/archify/examples/async-job-roundtrip.sequence.json +56 -0
  61. package/skills/archify/examples/brand-aware-delivery.architecture.json +34 -0
  62. package/skills/archify/examples/cache-miss-request.sequence.json +77 -0
  63. package/skills/archify/examples/checkout-platform.base.architecture.json +32 -0
  64. package/skills/archify/examples/checkout-platform.head.architecture.json +32 -0
  65. package/skills/archify/examples/dataflow-product-analytics.html +13820 -0
  66. package/skills/archify/examples/deployment-release.lifecycle.json +48 -0
  67. package/skills/archify/examples/event-stream.dataflow.json +52 -0
  68. package/skills/archify/examples/holiday-planning.workflow.json +143 -0
  69. package/skills/archify/examples/incident-response.workflow.json +59 -0
  70. package/skills/archify/examples/lifecycle-agent-run.html +13765 -0
  71. package/skills/archify/examples/locales/de.json +425 -0
  72. package/skills/archify/examples/locales/es.json +440 -0
  73. package/skills/archify/examples/locales/fr.json +425 -0
  74. package/skills/archify/examples/locales/fr.partial.json +22 -0
  75. package/skills/archify/examples/locales/it.json +425 -0
  76. package/skills/archify/examples/locales/ja.json +425 -0
  77. package/skills/archify/examples/locales/ko.json +440 -0
  78. package/skills/archify/examples/locales/pt.json +425 -0
  79. package/skills/archify/examples/locales/ru.json +425 -0
  80. package/skills/archify/examples/product-analytics.dataflow.json +71 -0
  81. package/skills/archify/examples/production-deployment.architecture.json +51 -0
  82. package/skills/archify/examples/release-delivery.workflow.json +57 -0
  83. package/skills/archify/examples/sequence-cache-miss-request.html +13835 -0
  84. package/skills/archify/examples/web-app-rendered.html +13808 -0
  85. package/skills/archify/examples/web-app.architecture.json +41 -0
  86. package/skills/archify/examples/workflow-agent-tool-call-rendered.html +13826 -0
  87. package/skills/archify/migrations/workflow-v2.mjs +280 -0
  88. package/skills/archify/package.json +17 -0
  89. package/skills/archify/recipes/scenarios.mjs +430 -0
  90. package/skills/archify/references/architecture-layout-repair.md +18 -0
  91. package/skills/archify/references/authoring-contract.md +419 -0
  92. package/skills/archify/references/authoring-defaults.md +41 -0
  93. package/skills/archify/references/brand-marks.md +82 -0
  94. package/skills/archify/references/delivery-contract.md +588 -0
  95. package/skills/archify/references/repository-authoring.md +105 -0
  96. package/skills/archify/references/update-awareness.md +12 -0
  97. package/skills/archify/references/viewer-runtime.md +35 -0
  98. package/skills/archify/renderers/architecture/grid.mjs +62 -0
  99. package/skills/archify/renderers/architecture/labels.mjs +215 -0
  100. package/skills/archify/renderers/architecture/render-architecture.mjs +1001 -0
  101. package/skills/archify/renderers/architecture/routing.mjs +1157 -0
  102. package/skills/archify/renderers/dataflow/README.md +105 -0
  103. package/skills/archify/renderers/dataflow/render-dataflow.mjs +544 -0
  104. package/skills/archify/renderers/lifecycle/README.md +171 -0
  105. package/skills/archify/renderers/lifecycle/grid-routing.mjs +429 -0
  106. package/skills/archify/renderers/lifecycle/render-lifecycle.mjs +938 -0
  107. package/skills/archify/renderers/sequence/README.md +129 -0
  108. package/skills/archify/renderers/sequence/render-sequence.mjs +526 -0
  109. package/skills/archify/renderers/shared/atomic-output.mjs +1982 -0
  110. package/skills/archify/renderers/shared/brand-marks.mjs +670 -0
  111. package/skills/archify/renderers/shared/cli.mjs +451 -0
  112. package/skills/archify/renderers/shared/desktop-readability.mjs +132 -0
  113. package/skills/archify/renderers/shared/diagnostics.mjs +173 -0
  114. package/skills/archify/renderers/shared/engineering-profiles.mjs +157 -0
  115. package/skills/archify/renderers/shared/generated-brand-marks.mjs +2003 -0
  116. package/skills/archify/renderers/shared/generated-validators.mjs +134 -0
  117. package/skills/archify/renderers/shared/geometry.mjs +1941 -0
  118. package/skills/archify/renderers/shared/i18n.mjs +603 -0
  119. package/skills/archify/renderers/shared/layout-report.mjs +42 -0
  120. package/skills/archify/renderers/shared/legend.mjs +217 -0
  121. package/skills/archify/renderers/shared/output-path.mjs +440 -0
  122. package/skills/archify/renderers/shared/path-semantics.mjs +1017 -0
  123. package/skills/archify/renderers/shared/portable-path.mjs +408 -0
  124. package/skills/archify/renderers/shared/repository-evidence.mjs +352 -0
  125. package/skills/archify/renderers/shared/repository-location.mjs +59 -0
  126. package/skills/archify/renderers/shared/route-quality.mjs +614 -0
  127. package/skills/archify/renderers/shared/sidecar-path.mjs +38 -0
  128. package/skills/archify/renderers/shared/spatial-grid.mjs +66 -0
  129. package/skills/archify/renderers/shared/text-fit.mjs +105 -0
  130. package/skills/archify/renderers/shared/utils.mjs +254 -0
  131. package/skills/archify/renderers/shared/validator.mjs +86 -0
  132. package/skills/archify/renderers/workflow/README.md +301 -0
  133. package/skills/archify/renderers/workflow/render-workflow.mjs +37 -0
  134. package/skills/archify/renderers/workflow/workflow-compiler.mjs +4913 -0
  135. package/skills/archify/renderers/workflow/workflow-migration-geometry.mjs +144 -0
  136. package/skills/archify/schemas/README.md +256 -0
  137. package/skills/archify/schemas/architecture.schema.json +152 -0
  138. package/skills/archify/schemas/common.schema.json +181 -0
  139. package/skills/archify/schemas/dataflow.schema.json +254 -0
  140. package/skills/archify/schemas/lifecycle.schema.json +280 -0
  141. package/skills/archify/schemas/sequence.schema.json +234 -0
  142. package/skills/archify/schemas/workflow.schema.json +439 -0
  143. package/skills/archify/scripts/check-render-output.mjs +1388 -0
  144. package/skills/archify/scripts/check-update.mjs +1710 -0
  145. package/skills/archify/scripts/delivery-update-child.mjs +23 -0
  146. package/skills/archify/scripts/render-examples.mjs +26 -0
  147. package/skills/archify/scripts/update-contract.mjs +182 -0
  148. package/skills/archify/skill-release.json +10 -0
@@ -0,0 +1,105 @@
1
+ # Data Flow Renderer
2
+
3
+ Render `diagram_type: "dataflow"` JSON files into the standard Archify HTML
4
+ template.
5
+
6
+ ```bash
7
+ node archify/renderers/dataflow/render-dataflow.mjs input.dataflow.json output.html
8
+ ```
9
+
10
+ The renderer validates input against `archify/schemas/dataflow.schema.json`
11
+ with the bundled standalone validator. No dependency installation is required.
12
+
13
+ If `output.html` is omitted, the renderer uses the required `meta.output` value
14
+ from the JSON file.
15
+
16
+ ## Input
17
+
18
+ Data-flow JSON files must set:
19
+
20
+ ```json
21
+ {
22
+ "schema_version": 1,
23
+ "diagram_type": "dataflow",
24
+ "meta": {
25
+ "title": "Product Analytics Data Flow",
26
+ "output": "product-analytics-dataflow.html",
27
+ "viewBox": [940, 720]
28
+ },
29
+ "stages": [],
30
+ "nodes": [],
31
+ "flows": [],
32
+ "cards": []
33
+ }
34
+ ```
35
+
36
+ A complete worked example lives at
37
+ `archify/examples/product-analytics.dataflow.json`.
38
+
39
+ The schema lives at:
40
+
41
+ ```text
42
+ archify/schemas/dataflow.schema.json
43
+ ```
44
+
45
+ ## Legend
46
+
47
+ The default visual legend derives kinds from `flows[].variant` (omitting
48
+ `variant` means `default`) and adds `database` only when a database node exists.
49
+ Supported `meta.legend.entries` keys, in stable order, are `emphasis`,
50
+ `security`, `dashed`, `database`, and `default`. Flow variants remain
51
+ visual-only because Archify has no compiled edge-kind facts in this slice. A
52
+ present `database` entry is different: it comes from exact
53
+ `nodes[].type: "database"` facts, so it publishes the normal Semantic Legend
54
+ count, accessible name, and keyboard interaction. Forcing `database` visible
55
+ without a database node keeps it visual-only.
56
+
57
+ ## Layout budget
58
+
59
+ | Constant | Value |
60
+ |----------|-------|
61
+ | viewBox | default `[940, 720]`; schema minimum `[360, 360]` |
62
+ | Stages (2–5) | centers at x = 100 + stage×215; stage band 168 wide, header at y 46 |
63
+ | Row tops (`row` 0–4) | y = 128, 242, 356, 470, 584 (plus `yOffset`) |
64
+ | Default node | 112×58 |
65
+ | Node area | x within `[24, width − 24]`; y within `[104, height − 74]` |
66
+ | Node spacing | ≥10px between any two nodes (checked across stages and rows) |
67
+ | Flow length | ≥34px between endpoints |
68
+ | Legend row | y = height − 36 |
69
+
70
+ Route presets for flows: `straight`, `vertical-channel`, `bottom-channel`,
71
+ `top-channel`, explicit `via` points, or the default `auto` (midpoint elbow).
72
+
73
+ ## Design Rules
74
+
75
+ - Use stages for data lifecycle boundaries: source, ingest, process, store,
76
+ consume.
77
+ - Place nodes by stage index and row index; do not hand-place raw SVG for the
78
+ common case.
79
+ - Use flow labels to name the data asset, not the transport primitive:
80
+ `clickstream`, `identity map`, `normalized facts`, `feature vectors`.
81
+ - Use `classification` for short sensitivity or governance context:
82
+ `PII touch`, `non-PII`, `approved only`, `batch`, `read-only`.
83
+ - Use `security` for PII, policy, consent, access-control, or restricted joins.
84
+ - Use `emphasis` for the primary data path and `dashed` for async or batch
85
+ derivations.
86
+ - Keep labels short enough to fit in narrow previews.
87
+
88
+ Schema violations exit non-zero with path-prefixed messages annotated with the
89
+ element's id or label. The renderer additionally fails when it can detect
90
+ layout problems, including missing stages, duplicate node IDs, nodes outside
91
+ the readable diagram area, node overlap, labels colliding with nodes or other
92
+ labels, labels wider than their node, unknown flow endpoints, missing flow
93
+ labels, unreadably short flows, flows crossing unrelated nodes (2px Clean Flow
94
+ clearance), or stages that exceed the viewBox. Stage frames remain intentional
95
+ pass-through containers. Text width
96
+ is estimated CJK-aware: fullwidth glyphs count as two units.
97
+
98
+ Set `meta.quality_profile` to `showcase` for polished delivery. Unrelated proper
99
+ X crossings then fail with `composition/proper-crossing`; default `standard`
100
+ keeps them as artifact-receipt warnings. Collinear stage corridors are outside
101
+ the proper-X rule, but a separate gate warns in `standard` and fails in
102
+ `showcase` when unrelated flows overlap for at least 8px. Shared semantic
103
+ endpoints, point touches, and shorter overlaps remain valid. Showcase also
104
+ rejects any route segment below 8px and any interior turn segment below 16px;
105
+ ordinary 8–15px endpoint stubs remain valid.
@@ -0,0 +1,544 @@
1
+ import path from 'node:path';
2
+ import { fileURLToPath } from 'node:url';
3
+ import { esc, renderDefinitions, renderSemanticSigil, textUnits } from '../shared/utils.mjs';
4
+ import { animateAttr, focusEdgeAttrs, focusNodeAttrs, focusNodeTitle, loadDiagramWithBrandMarks, writeDiagram, svgAccessibleText, svgRootAttrs } from '../shared/cli.mjs';
5
+ import { throwDiagnosticProblems } from '../shared/diagnostics.mjs';
6
+ import { resolveLegend, renderLegend as renderResolvedLegend } from '../shared/legend.mjs';
7
+ import { availableNodeTextWidth, fittedNodeFontSize, minimumNodeTextWidth, nodeLabelLayout } from '../shared/text-fit.mjs';
8
+ import { brandLabelFitWidth, brandMarkFor, brandMetadataFor, brandTopRailProblem, renderBrandMark } from '../shared/brand-marks.mjs';
9
+ import { translateMessage as i18nText } from '../shared/i18n.mjs';
10
+ import {
11
+ asArray,
12
+ isFinitePoint,
13
+ rectsOverlap,
14
+ cleanEndpointSideProblems,
15
+ cleanFlowProblems,
16
+ cleanCrossingProblems,
17
+ cleanAmbiguousCorridorProblems,
18
+ cleanBorderRunProblems,
19
+ cleanRouteRhythmProblems,
20
+ cleanLabelRouteClearanceProblems,
21
+ cleanLabelCanvasContainmentProblems,
22
+ suggestLabelObstacleFix,
23
+ suggestLabelPairFix,
24
+ anchor,
25
+ automaticPortSpread,
26
+ legacyDefaultFromSide as defaultFromSide,
27
+ legacyDefaultToSide as defaultToSide,
28
+ chosenSide,
29
+ polylinePath,
30
+ routePointsValue,
31
+ authoredStraightRouteAttrs,
32
+ labelPoint,
33
+ componentFill,
34
+ componentText,
35
+ arrowClassMap,
36
+ edgeLabelAccent
37
+ } from '../shared/geometry.mjs';
38
+
39
+ const nodeTextFit = {
40
+ sublabelPreferred: 7,
41
+ sublabelMinimum: 6,
42
+ tagPreferred: 7,
43
+ tagMinimum: 6,
44
+ };
45
+
46
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
47
+ const { diagram: dataflow, template, outPath, sourceEvidence } = await loadDiagramWithBrandMarks({
48
+ rendererDir: __dirname,
49
+ diagramType: 'dataflow',
50
+ defaultExample: 'product-analytics.dataflow.json'
51
+ });
52
+
53
+ const viewBox = dataflow.meta?.viewBox || [940, 720];
54
+ const layout = {
55
+ stageY: 46,
56
+ stageH: 36,
57
+ stageBottomPad: 74,
58
+ leftX: 100,
59
+ colGap: 215,
60
+ stageW: 168,
61
+ nodeW: 112,
62
+ nodeH: 58,
63
+ rowYs: [128, 242, 356, 470, 584],
64
+ labelH: 16
65
+ };
66
+
67
+ function flowLabelSize(flow) {
68
+ const longestLine = Math.max(textUnits(flow.label), textUnits(flow.classification || ''));
69
+ return {
70
+ width: Math.round(Math.max(34, longestLine * 4.9 + 12) * 10) / 10,
71
+ height: flow.classification ? 27 : layout.labelH,
72
+ };
73
+ }
74
+
75
+ function stageX(index) {
76
+ return layout.leftX + index * layout.colGap;
77
+ }
78
+
79
+ function stageFrame(stage, index) {
80
+ return {
81
+ id: index,
82
+ label: stage.label,
83
+ kind: 'stage',
84
+ x: stageX(index) - layout.stageW / 2,
85
+ y: layout.stageY,
86
+ width: layout.stageW,
87
+ height: viewBox[1] - layout.stageY - layout.stageBottomPad,
88
+ radius: 10,
89
+ };
90
+ }
91
+
92
+ const compositionFrames = asArray(dataflow.stages).map(stageFrame);
93
+
94
+ function measureNode(node) {
95
+ const width = node.width || layout.nodeW;
96
+ const height = node.height || layout.nodeH;
97
+ const cx = stageX(node.stage);
98
+ const y = layout.rowYs[node.row] + (node.yOffset || 0);
99
+ return {
100
+ ...node,
101
+ width,
102
+ height,
103
+ cx,
104
+ cy: y + height / 2,
105
+ x: cx - width / 2,
106
+ y
107
+ };
108
+ }
109
+
110
+ const nodes = new Map(asArray(dataflow.nodes).map((node) => [node.id, measureNode(node)]));
111
+ const nodeSteps = new Map();
112
+ for (const [index, flow] of asArray(dataflow.flows).entries()) {
113
+ if (!nodeSteps.has(flow.from)) nodeSteps.set(flow.from, index);
114
+ if (!nodeSteps.has(flow.to)) nodeSteps.set(flow.to, index + 1);
115
+ }
116
+ for (const [index, node] of asArray(dataflow.nodes).entries()) {
117
+ if (!nodeSteps.has(node.id)) nodeSteps.set(node.id, index);
118
+ }
119
+
120
+ function validateDataflow() {
121
+ const problems = [];
122
+ if (nodes.size !== asArray(dataflow.nodes).length) problems.push('Node ids must be unique.');
123
+
124
+ const stageCount = asArray(dataflow.stages).length;
125
+ for (const node of nodes.values()) {
126
+ if (typeof node.stage !== 'number' || node.stage < 0 || node.stage >= stageCount) {
127
+ problems.push(`Node "${node.id}" uses invalid stage ${node.stage} — valid stages are 0..${stageCount - 1}.`);
128
+ }
129
+ if (typeof node.row !== 'number' || node.row < 0 || node.row >= layout.rowYs.length) {
130
+ problems.push(`Node "${node.id}" uses invalid row ${node.row} — valid rows are 0..${layout.rowYs.length - 1}.`);
131
+ }
132
+ if (!isFinitePoint(node.x, node.y, node.cx, node.cy)) {
133
+ problems.push(`Node "${node.id}" produced non-finite coordinates — check stage, row, width, height, and yOffset are numbers.`);
134
+ continue;
135
+ }
136
+ if (node.x < 24 || node.x + node.width > viewBox[0] - 24) {
137
+ problems.push(`Node "${node.id}" exceeds the horizontal bounds of the viewBox — reduce node.width or increase meta.viewBox[0].`);
138
+ }
139
+ if (node.y < layout.stageY + layout.stageH + 22 || node.y + node.height > viewBox[1] - layout.stageBottomPad) {
140
+ problems.push(`Node "${node.id}" exceeds the readable diagram area — keep y between ${layout.stageY + layout.stageH + 22} and ${viewBox[1] - layout.stageBottomPad} (adjust row/yOffset or increase meta.viewBox[1]).`);
141
+ }
142
+ const estLabelW = textUnits(node.label) * 6.2;
143
+ if (estLabelW > node.width + 6) {
144
+ problems.push(`Label "${node.label}" (~${Math.round(estLabelW)}px) is wider than node "${node.id}" (${node.width}px) — shorten the label or increase node.width.`);
145
+ }
146
+ const brandRailProblem = brandTopRailProblem(node, node.width, 8);
147
+ if (brandRailProblem) problems.push(brandRailProblem);
148
+ // sublabel and tag render as single unwrapped <text> elements; shrink-to-fit
149
+ // handles the ordinary case, this rejects what it cannot rescue.
150
+ const availableTextW = availableNodeTextWidth(node.width);
151
+ for (const [field, value, minimum] of [
152
+ ['Sublabel', node.sublabel, nodeTextFit.sublabelMinimum],
153
+ ['Tag', node.tag, nodeTextFit.tagMinimum],
154
+ ]) {
155
+ if (!value) continue;
156
+ const minimumW = minimumNodeTextWidth(value, minimum);
157
+ if (minimumW > availableTextW) {
158
+ problems.push(`${field} "${value}" needs ~${Math.ceil(minimumW)}px at the ${minimum}px legible minimum, but node "${node.id}" provides ${availableTextW}px — shorten the ${field.toLowerCase()} or increase node.width.`);
159
+ }
160
+ }
161
+ }
162
+
163
+ const nodeList = asArray(dataflow.nodes);
164
+ for (let i = 0; i < nodeList.length; i += 1) {
165
+ for (let j = i + 1; j < nodeList.length; j += 1) {
166
+ const a = nodes.get(nodeList[i].id);
167
+ const b = nodes.get(nodeList[j].id);
168
+ if (rectsOverlap(a, b, 10)) {
169
+ problems.push(`Nodes "${a.id}" and "${b.id}" are less than 10px apart — move one to another stage/row or adjust yOffset.`);
170
+ }
171
+ }
172
+ }
173
+
174
+ for (const flow of asArray(dataflow.flows)) {
175
+ if (!nodes.has(flow.from)) problems.push(`Flow "${flow.label || flow.from}" references unknown source "${flow.from}".`);
176
+ if (!nodes.has(flow.to)) problems.push(`Flow "${flow.label || flow.to}" references unknown target "${flow.to}".`);
177
+ if (!flow.label) problems.push(`Flow "${flow.from}" -> "${flow.to}" must include a short data label.`);
178
+ if (nodes.has(flow.from) && nodes.has(flow.to)) {
179
+ const routed = pathFor(flow);
180
+ const [start, end] = [routed.points[0], routed.points[routed.points.length - 1]];
181
+ const distance = Math.hypot(end[0] - start[0], end[1] - start[1]);
182
+ if (distance < 34) problems.push(`Flow "${flow.label}" is too short (${Math.round(distance)}px; minimum 34px) — route it through a channel or spread its nodes.`);
183
+ if (Array.isArray(flow.via)) {
184
+ for (let segmentIndex = 0; segmentIndex < routed.points.length - 1; segmentIndex += 1) {
185
+ const segmentStart = routed.points[segmentIndex];
186
+ const segmentEnd = routed.points[segmentIndex + 1];
187
+ const isDiagonal = Math.abs(segmentStart[0] - segmentEnd[0]) > 0.01
188
+ && Math.abs(segmentStart[1] - segmentEnd[1]) > 0.01;
189
+ if (!isDiagonal) continue;
190
+ const viaIndex = Math.min(segmentIndex, flow.via.length - 1);
191
+ problems.push(`Flow "${flow.label}" has a diagonal segment from (${segmentStart.join(', ')}) to (${segmentEnd.join(', ')}) — align via[${viaIndex}] with its adjacent point by sharing the same x or y coordinate.`);
192
+ }
193
+ }
194
+ }
195
+ }
196
+
197
+ problems.push(...cleanEndpointSideProblems({
198
+ relations: dataflow.flows,
199
+ endpointIds: new Set(nodes.keys()),
200
+ pathFor,
201
+ diagramType: 'dataflow',
202
+ relationCollection: 'flows',
203
+ fromSideFor: (flow) => flowSides(flow).fromSide,
204
+ toSideFor: (flow) => flowSides(flow).toSide,
205
+ routeHint: 'keep automatic routing, or choose fromSide/toSide and via points whose first and final segments cross node borders perpendicularly',
206
+ }));
207
+ problems.push(...cleanFlowProblems({
208
+ relations: dataflow.flows,
209
+ obstacles: nodes.values(),
210
+ pathFor,
211
+ diagramType: 'dataflow',
212
+ relationCollection: 'flows',
213
+ obstacleKind: 'node',
214
+ routeHint: 'adjust fromSide/toSide, set route/via or channelX/channelY, or move the node to another stage/row'
215
+ }));
216
+ problems.push(...cleanCrossingProblems({
217
+ relations: dataflow.flows,
218
+ endpointIds: new Set(nodes.keys()),
219
+ pathFor,
220
+ diagramType: 'dataflow',
221
+ relationCollection: 'flows',
222
+ profile: dataflow.meta?.quality_profile,
223
+ routeHint: 'adjust route/via or channelX/channelY so the flows use separate stage corridors'
224
+ }));
225
+ problems.push(...cleanAmbiguousCorridorProblems({
226
+ relations: dataflow.flows,
227
+ endpointIds: new Set(nodes.keys()),
228
+ pathFor,
229
+ diagramType: 'dataflow',
230
+ relationCollection: 'flows',
231
+ profile: dataflow.meta?.quality_profile,
232
+ routeHint: 'adjust route/via or channelX/channelY so unrelated flows do not visually merge'
233
+ }));
234
+ problems.push(...cleanBorderRunProblems({
235
+ relations: dataflow.flows,
236
+ endpointIds: new Set(nodes.keys()),
237
+ frames: compositionFrames,
238
+ pathFor,
239
+ diagramType: 'dataflow',
240
+ relationCollection: 'flows',
241
+ profile: dataflow.meta?.quality_profile,
242
+ routeHint: 'adjust route/via or channelX/channelY so the flow crosses the stage perpendicularly instead of following its border'
243
+ }));
244
+ problems.push(...cleanRouteRhythmProblems({
245
+ relations: dataflow.flows,
246
+ endpointIds: new Set(nodes.keys()),
247
+ pathFor,
248
+ diagramType: 'dataflow',
249
+ relationCollection: 'flows',
250
+ profile: dataflow.meta?.quality_profile,
251
+ routeHint: 'adjust route/via or channelX/channelY so each turn uses a clear inter-stage corridor'
252
+ }));
253
+
254
+ const labelRects = [];
255
+ for (const [flowIndex, flow] of asArray(dataflow.flows).entries()) {
256
+ if (!flow.label || !nodes.has(flow.from) || !nodes.has(flow.to)) continue;
257
+ const [lx, ly] = labelPoint(flow, pathFor(flow).points);
258
+ const { width, height } = flowLabelSize(flow);
259
+ labelRects.push({ relation: flow, relationIndex: flowIndex, label: flow.label, x: lx - width / 2, y: ly - 11, width, height, lx, ly });
260
+ }
261
+ for (const rect of labelRects) {
262
+ for (const node of nodes.values()) {
263
+ if (rectsOverlap(rect, node, -2)) {
264
+ problems.push(`Label "${rect.label}" overlaps node "${node.id}" — adjust labelDx/labelDy/labelSegment or set labelAt.\n${suggestLabelObstacleFix(rect, rect.lx, rect.ly, node, 'node', viewBox, nodes.values())}`);
265
+ }
266
+ }
267
+ }
268
+ for (let i = 0; i < labelRects.length; i += 1) {
269
+ for (let j = i + 1; j < labelRects.length; j += 1) {
270
+ if (rectsOverlap(labelRects[i], labelRects[j], -2)) {
271
+ problems.push(`Labels "${labelRects[i].label}" and "${labelRects[j].label}" overlap — adjust labelDx/labelDy.\n${suggestLabelPairFix(labelRects[i], labelRects[j])}`);
272
+ }
273
+ }
274
+ }
275
+ problems.push(...cleanLabelRouteClearanceProblems({
276
+ relations: dataflow.flows,
277
+ labels: labelRects,
278
+ endpointIds: new Set(nodes.keys()),
279
+ pathFor,
280
+ diagramType: 'dataflow',
281
+ relationCollection: 'flows',
282
+ profile: dataflow.meta?.quality_profile,
283
+ routeHint: 'adjust labelAt, labelDx, labelDy, or labelSegment; otherwise adjust the other flow route/via/channelX/channelY'
284
+ }));
285
+ problems.push(...cleanLabelCanvasContainmentProblems({
286
+ labels: labelRects,
287
+ viewBox,
288
+ diagramType: 'dataflow',
289
+ relationCollection: 'flows',
290
+ profile: dataflow.meta?.quality_profile,
291
+ }));
292
+
293
+ const lastStageX = stageX(asArray(dataflow.stages).length - 1);
294
+ if (lastStageX + layout.stageW / 2 > viewBox[0] - 24) {
295
+ problems.push(`Stages exceed viewBox width — set meta.viewBox[0] to at least ${Math.ceil(lastStageX + layout.stageW / 2 + 24)}.`);
296
+ }
297
+
298
+ if (problems.length) {
299
+ throwDiagnosticProblems('Data-flow layout validation failed', problems, {
300
+ subject: { diagramType: 'dataflow' },
301
+ });
302
+ }
303
+ }
304
+
305
+ function routeVia(flow, from, to, start, end) {
306
+ if (flow.via) return flow.via;
307
+ switch (flow.route || 'auto') {
308
+ case 'straight':
309
+ return [];
310
+ case 'vertical-channel': {
311
+ const x = flow.channelX ?? start[0] + (end[0] > start[0] ? 44 : -44);
312
+ return [[x, start[1]], [x, end[1]]];
313
+ }
314
+ case 'bottom-channel': {
315
+ const y = flow.channelY ?? Math.max(from.y + from.height, to.y + to.height) + 26;
316
+ return [[start[0], y], [end[0], y]];
317
+ }
318
+ case 'top-channel': {
319
+ const y = flow.channelY ?? Math.min(from.y, to.y) - 24;
320
+ return [[start[0], y], [end[0], y]];
321
+ }
322
+ case 'auto':
323
+ default: {
324
+ if (Math.abs(start[1] - end[1]) < 4) return [];
325
+ const midX = start[0] + (end[0] - start[0]) / 2;
326
+ return [[midX, start[1]], [midX, end[1]]];
327
+ }
328
+ }
329
+ }
330
+
331
+ const pathCache = new Map();
332
+
333
+ function flowSides(flow) {
334
+ const from = nodes.get(flow.from);
335
+ const to = nodes.get(flow.to);
336
+ return {
337
+ fromSide: chosenSide(flow.fromSide, defaultFromSide(from, to)),
338
+ toSide: chosenSide(flow.toSide, defaultToSide(from, to)),
339
+ };
340
+ }
341
+
342
+ const automaticPorts = automaticPortSpread(dataflow.flows, nodes, {
343
+ sideFor: (flow, endpoint) => flowSides(flow)[endpoint === 'source' ? 'fromSide' : 'toSide'],
344
+ });
345
+
346
+ function pathFor(flow) {
347
+ if (pathCache.has(flow)) return pathCache.get(flow);
348
+ const from = nodes.get(flow.from);
349
+ const to = nodes.get(flow.to);
350
+ const ports = automaticPorts.get(flow);
351
+ const { fromSide, toSide } = flowSides(flow);
352
+ const start = ports?.from || anchor(from, fromSide);
353
+ const end = ports?.to || anchor(to, toSide);
354
+ // Drop consecutive duplicate points so a purely vertical (or horizontal)
355
+ // auto-route never emits a zero-length final segment — SVG derives
356
+ // marker-end orientation from the last segment, and a degenerate segment
357
+ // leaves the arrowhead angle undefined (see #169).
358
+ const rawPoints = [start, ...routeVia(flow, from, to, start, end), end];
359
+ const points = [];
360
+ for (const p of rawPoints) {
361
+ const prev = points.at(-1);
362
+ if (!prev || Math.abs(p[0] - prev[0]) > 0.0001 || Math.abs(p[1] - prev[1]) > 0.0001) {
363
+ points.push(p);
364
+ }
365
+ }
366
+ // Guard against an all-degenerate route (e.g. start === end): keep both
367
+ // endpoints so the path is still well-formed even if the marker is hidden.
368
+ if (points.length < 2) points.push(end);
369
+ const routed = { d: polylinePath(points), points };
370
+ pathCache.set(flow, routed);
371
+ return routed;
372
+ }
373
+
374
+ // Header measurement follows 276970789's #257, including the ordinal.
375
+ // Long titles wrap at the same legible floor instead of becoming invalid input.
376
+ function stageHeaderText(stage, index) {
377
+ return `${String(index + 1).padStart(2, '0')} / ${stage.label}`;
378
+ }
379
+
380
+ function renderStageHeader(stage, index, cx) {
381
+ const text = stageHeaderText(stage, index);
382
+ const font = fittedNodeFontSize(text, layout.stageW, 9, 7);
383
+ const available = availableNodeTextWidth(layout.stageW);
384
+ const open = `<text x="${cx}" y="${layout.stageY + 22}" class="t-dim" font-size="${font}" font-weight="600" text-anchor="middle">`;
385
+ if (minimumNodeTextWidth(text, font) <= available) return `${open}${esc(text)}</text>`;
386
+ const lines = [];
387
+ let line = '';
388
+ // Prefer word boundaries; split oversized words and CJK by grapheme, without
389
+ // dropping whitespace or splitting a combining character/emoji sequence.
390
+ const segmenter = new Intl.Segmenter(undefined, { granularity: 'grapheme' });
391
+ for (const word of text.match(/\s+|\S+/gu) || []) {
392
+ if (line && minimumNodeTextWidth(line + word, font) > available) {
393
+ lines.push(line); line = '';
394
+ }
395
+ for (const { segment } of segmenter.segment(word)) {
396
+ if (line && minimumNodeTextWidth(line + segment, font) > available) {
397
+ lines.push(line); line = '';
398
+ }
399
+ line += segment;
400
+ }
401
+ }
402
+ if (line) lines.push(line);
403
+ // Explicit node geometry is authoritative. Do not turn an old horizontal
404
+ // overflow into a new collision with nodes when the header area is packed.
405
+ const firstNodeY = Math.min(...[...nodes.values()].filter(node => node.stage === index).map(node => node.y),
406
+ viewBox[1] - layout.stageBottomPad);
407
+ const lastLineBottom = layout.stageY + 22 + (lines.length - 1) * (font + 4) + font * 0.3;
408
+ if (lastLineBottom > firstNodeY - 4) return `${open}${esc(text)}</text>`;
409
+ const content = lines.length === 1 ? esc(text) : lines.map((line, i) =>
410
+ `<tspan x="${cx}" dy="${i ? font + 4 : 0}">${esc(line)}</tspan>`).join('');
411
+ return `${open}${content}</text>`;
412
+ }
413
+
414
+ function renderStage(stage, index) {
415
+ const frame = compositionFrames[index];
416
+ const cx = stageX(index);
417
+ return ` <rect data-graph-role="structural-frame" data-composition-frame-kind="stage" data-composition-frame-id="${index}" x="${frame.x}" y="${frame.y}" width="${frame.width}" height="${frame.height}" rx="${frame.radius}" class="c-lane" stroke-width="1"/>
418
+ ${renderStageHeader(stage, index, cx)}`;
419
+ }
420
+
421
+ function renderNode(node) {
422
+ const fill = componentFill[node.type] || 'c-external';
423
+ const accent = componentText[node.type] || 't-muted';
424
+ const hasSub = node.sublabel != null && node.sublabel !== '';
425
+ const labelFontSize = fittedNodeFontSize(node.label, brandLabelFitWidth(node, node.width), 10, 8);
426
+ const sublabelFontSize = fittedNodeFontSize(node.sublabel, node.width, nodeTextFit.sublabelPreferred, nodeTextFit.sublabelMinimum);
427
+ const tagFontSize = fittedNodeFontSize(node.tag, node.width, nodeTextFit.tagPreferred, nodeTextFit.tagMinimum);
428
+ const textRows = [{ text: node.label, font: labelFontSize, y: 21 }];
429
+ if (hasSub) textRows.push({ text: node.sublabel, font: sublabelFontSize, y: 37 });
430
+ if (node.tag) textRows.push({ text: node.tag, font: tagFontSize, y: node.height - 11 });
431
+ const labelLayout = nodeLabelLayout({ width: node.width, height: node.height, rows: textRows,
432
+ brand: Boolean(brandMarkFor(node)), source: Boolean(sourceEvidence?.nodes?.[node.id]?.length) });
433
+ const sub = hasSub
434
+ ? `\n <text data-detail="context" x="${node.cx}" y="${node.y + labelLayout.ys[1]}" class="t-muted" font-size="${sublabelFontSize}" text-anchor="middle">${esc(node.sublabel)}</text>`
435
+ : '';
436
+ const tag = node.tag
437
+ ? `\n <text data-detail="fine" x="${node.cx}" y="${node.y + labelLayout.ys[hasSub ? 2 : 1]}" class="${accent}" font-size="${tagFontSize}" text-anchor="middle">${esc(node.tag)}</text>`
438
+ : '';
439
+ const stage = asArray(dataflow.stages)[node.stage];
440
+ const context = stage
441
+ ? `${String(node.stage + 1).padStart(2, '0')} / ${stage.label}`
442
+ : i18nText(dataflow.meta.locale, 'node.context.dataflow');
443
+ const brand = renderBrandMark(node, { x: node.x + node.width - 22, y: node.y + 6 });
444
+ const passport = { kind: node.type, sublabel: node.sublabel, tag: node.tag, context, ...brandMetadataFor(node) };
445
+ return ` <g ${focusNodeAttrs(node.id, node.label, passport, dataflow.meta.locale)}>
446
+ ${focusNodeTitle(node.label, passport)}
447
+ <rect x="${node.x}" y="${node.y}" width="${node.width}" height="${node.height}" rx="6" class="c-mask"/>
448
+ <rect x="${node.x}" y="${node.y}" width="${node.width}" height="${node.height}" rx="6" class="${fill}"${animateAttr(dataflow.meta, 'node', nodeSteps.get(node.id))} stroke-width="1.5"/>
449
+ ${renderSemanticSigil(node.type, { icon: node.icon, x: node.x + 6, y: node.y + labelLayout.sigilY, size: labelLayout.sigilSize })}${brand ? `\n ${brand}` : ''}
450
+ <text data-node-label=""${hasSub ? ' data-detail-anchor=""' : ''} x="${node.x + labelLayout.x}" y="${node.y + labelLayout.ys[0]}" class="t-primary" font-size="${labelFontSize}" font-weight="600" text-anchor="middle">${esc(node.label)}</text>${sub}${tag}
451
+ </g>`;
452
+ }
453
+
454
+ function renderFlowPath(flow, index) {
455
+ const [cls, marker] = arrowClassMap[flow.variant || 'default'] || arrowClassMap.default;
456
+ const routed = pathFor(flow);
457
+ const strokeWidth = flow.width || (flow.variant === 'emphasis' ? 1.8 : 1.4);
458
+ return ` <path ${focusEdgeAttrs(flow.from, flow.to, flow.label, index, flow.id)} data-composition-points="${routePointsValue(routed.points)}"${authoredStraightRouteAttrs(flow, routed.points)} d="${routed.d}" class="${cls}"${animateAttr(dataflow.meta, 'edge', index)} stroke-width="${strokeWidth}" marker-end="url(#${marker})"/>`;
459
+ }
460
+
461
+ function renderFlowLabel(flow, index) {
462
+ const routed = pathFor(flow);
463
+ const [lx, ly] = labelPoint(flow, routed.points);
464
+ const { width: labelW, height: labelH } = flowLabelSize(flow);
465
+ const classification = flow.classification
466
+ ? `\n <text data-detail="fine" x="${lx}" y="${ly + 11}" class="t-dim" font-size="7" text-anchor="middle">${esc(flow.classification)}</text>`
467
+ : '';
468
+ return ` <g data-detail="context" ${focusEdgeAttrs(flow.from, flow.to, flow.label, index, flow.id)}>
469
+ <rect x="${lx - labelW / 2}" y="${ly - 11}" width="${labelW}" height="${labelH}" rx="4" class="c-mask"/>
470
+ <text x="${lx}" y="${ly}" class="${edgeLabelAccent(flow.variant)}" font-size="8" text-anchor="middle">${esc(flow.label)}</text>${classification}
471
+ </g>`;
472
+ }
473
+
474
+ const LEGEND_CATALOG = [
475
+ { kind: 'emphasis', className: 'a-emphasis', marker: 'arrowhead-emphasis', strokeWidth: 1.8, swatchWidth: 34, swatchGap: 9, interactive: false },
476
+ { kind: 'security', className: 'a-security', marker: 'arrowhead-security', swatchWidth: 34, swatchGap: 9, interactive: false },
477
+ { kind: 'dashed', className: 'a-dashed', marker: 'arrowhead-dashed', swatchWidth: 34, swatchGap: 9, interactive: false },
478
+ { kind: 'database' },
479
+ { kind: 'default', className: 'a-default', marker: 'arrowhead', swatchWidth: 34, swatchGap: 9, interactive: false },
480
+ ].map((entry) => ({
481
+ ...entry,
482
+ label: i18nText(dataflow.meta.locale, `legend.dataflow.${entry.kind}`),
483
+ }));
484
+
485
+ function renderLegend() {
486
+ const presentKinds = new Set(asArray(dataflow.flows).map((flow) => flow.variant || 'default'));
487
+ if ([...nodes.values()].some((node) => node.type === 'database')) presentKinds.add('database');
488
+ const entries = resolveLegend(dataflow.meta?.legend, LEGEND_CATALOG, presentKinds);
489
+ return renderResolvedLegend({
490
+ entries,
491
+ locale: dataflow.meta.locale,
492
+ layout: {
493
+ x: 40,
494
+ baselineY: viewBox[1] - 36,
495
+ width: viewBox[0] - 80,
496
+ minTitleY: viewBox[1] - 66,
497
+ unfit: dataflow.meta?.legend === undefined ? 'hide' : 'error',
498
+ diagramType: 'dataflow',
499
+ },
500
+ renderSwatch: (entry) => entry.kind === 'database'
501
+ ? `<rect x="${entry.x}" y="${entry.baseline - 8}" width="14" height="9" rx="2" class="c-database" stroke-width="1"/>`
502
+ : `<path d="M ${entry.x} ${entry.baseline - 3} L ${entry.x + 34} ${entry.baseline - 3}" class="${entry.className}" stroke-width="${entry.strokeWidth || 1.4}" marker-end="url(#${entry.marker})"/>`,
503
+ });
504
+ }
505
+
506
+ function renderSvg() {
507
+ // Same default-canvas contract as lifecycle: 940x720 is below the 1.55 wide
508
+ // ratio, so without intrinsic-height the desktop Reader can neither narrow
509
+ // nor scroll it and every default dataflow fails the browser gate.
510
+ const readerFit = dataflow.meta?.viewBox ? '' : ' data-reader-fit="intrinsic-height"';
511
+ return ` <svg viewBox="0 0 ${viewBox[0]} ${viewBox[1]}"${readerFit} ${svgRootAttrs(dataflow.meta)}>
512
+ ${svgAccessibleText(dataflow.meta, 'dataflow')}
513
+ ${renderDefinitions()}
514
+
515
+ <!-- Background Grid -->
516
+ <rect width="100%" height="100%" fill="url(#grid)" />
517
+
518
+ <!-- Data Stages -->
519
+ ${dataflow.stages.map(renderStage).join('\n\n')}
520
+
521
+ <!-- Flow paths -->
522
+ ${asArray(dataflow.flows).map(renderFlowPath).join('\n')}
523
+
524
+ <!-- Nodes -->
525
+ ${[...nodes.values()].map(renderNode).join('\n\n')}
526
+
527
+ <!-- Flow labels -->
528
+ ${asArray(dataflow.flows).map(renderFlowLabel).join('\n')}
529
+
530
+ <!-- Legend -->
531
+ ${renderLegend()}
532
+ </svg>`;
533
+ }
534
+
535
+ validateDataflow();
536
+ writeDiagram({
537
+ outPath,
538
+ template,
539
+ diagramType: 'dataflow',
540
+ meta: dataflow.meta,
541
+ svg: renderSvg(),
542
+ cards: dataflow.cards,
543
+ sourceEvidence,
544
+ });