@quolu/lattice 0.52.3 → 0.53.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 (188) hide show
  1. package/LICENSE +147 -147
  2. package/README.ja.md +355 -355
  3. package/README.md +258 -258
  4. package/bin/lattice-bridge.mjs +25 -0
  5. package/bin/lattice-hub.mjs +67 -0
  6. package/bin/lattice-mcp.mjs +0 -0
  7. package/bin/lattice-scripted-adapter.mjs +0 -0
  8. package/bin/lattice-scripted-worker.mjs +0 -0
  9. package/bin/lattice-work-order-adapter.mjs +0 -0
  10. package/bin/lattice.mjs +0 -0
  11. package/docs/bridge-setup.md +132 -132
  12. package/docs/schemas/lattice.executor_packet.v1.schema.json +57 -57
  13. package/docs/schemas/lattice.executor_receipt.v1.schema.json +66 -66
  14. package/docs/schemas/lattice.phase_todo_revision.v3.schema.json +360 -360
  15. package/docs/schemas/lattice.plan_create_input.v1.schema.json +56 -56
  16. package/docs/schemas/lattice.plan_create_input.v2.schema.json +72 -72
  17. package/docs/schemas/lattice.plan_create_input.v3.schema.json +81 -81
  18. package/docs/schemas/lattice.plan_create_input.v4.schema.json +85 -85
  19. package/docs/schemas/lattice.run_request.v1.schema.json +238 -238
  20. package/docs/schemas/lattice.runtime_adapter_capabilities.v2.schema.json +55 -55
  21. package/docs/schemas/lattice.runtime_adapter_registration_input.v1.schema.json +78 -78
  22. package/docs/schemas/lattice.runtime_adapter_registration_input.v2.schema.json +86 -86
  23. package/docs/schemas/lattice.todo_extraction.v2.schema.json +298 -298
  24. package/docs/schemas/lattice.todo_extraction.v3.schema.json +146 -146
  25. package/docs/schemas/lattice.todo_revision.v2.schema.json +260 -260
  26. package/docs/schemas/lattice.todo_revision_set.v3.schema.json +363 -363
  27. package/package.json +103 -103
  28. package/sensor/LICENSE +21 -21
  29. package/sensor/NOTICE +19 -19
  30. package/sensor/dist/bin/lattice-sensor.js +9 -9
  31. package/sensor/dist/db/index.js +24 -24
  32. package/sensor/dist/db/migrations.js +41 -41
  33. package/sensor/dist/db/queries.js +164 -164
  34. package/sensor/dist/db/schema.sql +205 -205
  35. package/sensor/dist/directory.js +5 -5
  36. package/sensor/dist/extraction/wasm/tree-sitter-c_sharp.wasm +0 -0
  37. package/sensor/dist/extraction/wasm/tree-sitter-cfml.wasm +0 -0
  38. package/sensor/dist/extraction/wasm/tree-sitter-cfquery.wasm +0 -0
  39. package/sensor/dist/extraction/wasm/tree-sitter-cfscript.wasm +0 -0
  40. package/sensor/dist/extraction/wasm/tree-sitter-cobol.wasm +0 -0
  41. package/sensor/dist/extraction/wasm/tree-sitter-erlang.wasm +0 -0
  42. package/sensor/dist/extraction/wasm/tree-sitter-go.wasm +0 -0
  43. package/sensor/dist/extraction/wasm/tree-sitter-java.wasm +0 -0
  44. package/sensor/dist/extraction/wasm/tree-sitter-javascript.wasm +0 -0
  45. package/sensor/dist/extraction/wasm/tree-sitter-nix.wasm +0 -0
  46. package/sensor/dist/extraction/wasm/tree-sitter-pascal.wasm +0 -0
  47. package/sensor/dist/extraction/wasm/tree-sitter-python.wasm +0 -0
  48. package/sensor/dist/extraction/wasm/tree-sitter-tsx.wasm +0 -0
  49. package/sensor/dist/extraction/wasm/tree-sitter-typescript.wasm +0 -0
  50. package/sensor/dist/extraction/wasm/tree-sitter-vbnet.wasm +0 -0
  51. package/sensor/dist/mcp/liveness-watchdog.js +53 -53
  52. package/sensor/dist/mcp/server-instructions.js +95 -95
  53. package/sensor/package.json +56 -56
  54. package/src/artifact-contracts-v2.mjs +325 -325
  55. package/src/artifact-contracts.mjs +895 -895
  56. package/src/boundary-compiler.mjs +712 -712
  57. package/src/boundary-observation-compiler-v2.mjs +344 -344
  58. package/src/bounded-seam.mjs +230 -230
  59. package/src/bridge-address.mjs +107 -107
  60. package/src/bridge-cli.mjs +303 -297
  61. package/src/bridge-config.mjs +382 -346
  62. package/src/bridge-daemon.mjs +378 -378
  63. package/src/bridge-hub-heartbeat.mjs +170 -0
  64. package/src/bridge-hub-protocol.mjs +198 -0
  65. package/src/bridge-hub-server.mjs +544 -0
  66. package/src/bridge-launch-agent.mjs +323 -323
  67. package/src/bridge-registrar.mjs +102 -102
  68. package/src/bridge-server.mjs +376 -376
  69. package/src/cli-help.mjs +308 -308
  70. package/src/cli-stdio.mjs +40 -40
  71. package/src/control-compiler.mjs +532 -532
  72. package/src/dag-chain.mjs +261 -261
  73. package/src/factory-diagnostics.mjs +188 -188
  74. package/src/git-process.mjs +72 -0
  75. package/src/hash-chain.mjs +76 -76
  76. package/src/hooks-cli.mjs +1057 -1057
  77. package/src/isolation-runner.mjs +409 -409
  78. package/src/node-version-guard.mjs +44 -44
  79. package/src/project-cli.mjs +3 -3
  80. package/src/project-identity.mjs +130 -130
  81. package/src/rc1-black-box-oracle.mjs +906 -906
  82. package/src/rc1-comparison.mjs +154 -154
  83. package/src/rc1-evidence-bundle.mjs +456 -456
  84. package/src/rc1-v4-campaign.mjs +708 -708
  85. package/src/rc1-v4-transform.mjs +467 -467
  86. package/src/rc1-v5-artifact-set.mjs +855 -855
  87. package/src/rc1-v5-behavior-evidence.mjs +594 -594
  88. package/src/rc1-v5-campaign.mjs +797 -797
  89. package/src/rc1-v5-transform.mjs +421 -421
  90. package/src/rc1-v6-artifact-set.mjs +807 -807
  91. package/src/rc1-v6-behavior-evidence.mjs +273 -273
  92. package/src/rc1-v6-campaign.mjs +623 -623
  93. package/src/rc1-v6-causal-binding.mjs +473 -473
  94. package/src/rc1-v6-measurement.mjs +313 -313
  95. package/src/rc2-artifact-set.mjs +1584 -1584
  96. package/src/rc2-campaign.mjs +1506 -1506
  97. package/src/rc2-delivery-policy-front-end.mjs +1079 -1079
  98. package/src/rc2-delivery-policy-oracle.mjs +134 -134
  99. package/src/rc2-delivery-policy-transform.mjs +1127 -1127
  100. package/src/rc2-rc1-transfer-front-end.mjs +511 -511
  101. package/src/rc3-actual-dogfood.mjs +652 -652
  102. package/src/rc3-dogfood-scaffold.mjs +315 -315
  103. package/src/rc3-scripted-campaign.mjs +1383 -1383
  104. package/src/rc4-stage1-dogfood.mjs +673 -673
  105. package/src/runtime-adapter-registry.mjs +524 -524
  106. package/src/runtime-cli.mjs +4588 -4588
  107. package/src/runtime-contracts.mjs +824 -824
  108. package/src/runtime-control-store.mjs +604 -604
  109. package/src/runtime-controller-protocol.mjs +587 -587
  110. package/src/runtime-decision-verifier.mjs +701 -701
  111. package/src/runtime-diff-observer.mjs +361 -361
  112. package/src/runtime-direct-os-observer.mjs +301 -301
  113. package/src/runtime-driver-state.mjs +166 -166
  114. package/src/runtime-engine.mjs +779 -779
  115. package/src/runtime-errors.mjs +356 -356
  116. package/src/runtime-event-store.mjs +189 -189
  117. package/src/runtime-front-end.mjs +925 -925
  118. package/src/runtime-gate-store.mjs +481 -481
  119. package/src/runtime-hold-recompile.mjs +916 -916
  120. package/src/runtime-io-sentinel.mjs +391 -391
  121. package/src/runtime-lifecycle-lock.mjs +294 -294
  122. package/src/runtime-managed-supervisor.mjs +1490 -1490
  123. package/src/runtime-multi-epoch-store.mjs +838 -838
  124. package/src/runtime-projection.mjs +269 -269
  125. package/src/runtime-pull-intake.mjs +1192 -1192
  126. package/src/runtime-scripted-adapter-controller.mjs +1160 -1160
  127. package/src/runtime-scripted-executor.mjs +163 -163
  128. package/src/runtime-scripted-worktree.mjs +104 -104
  129. package/src/runtime-seam-resolve.mjs +428 -428
  130. package/src/runtime-seam-treatment.mjs +173 -173
  131. package/src/runtime-socket-owner.mjs +125 -125
  132. package/src/runtime-work-order-contracts.mjs +91 -91
  133. package/src/runtime-work-order-controller.mjs +1171 -1171
  134. package/src/runtime-worktree-executor.mjs +199 -199
  135. package/src/schedulability-compiler-v2.mjs +303 -303
  136. package/src/schedulability-verifier-v2.mjs +317 -317
  137. package/src/seam-apply.mjs +549 -549
  138. package/src/seam-commit-shared.mjs +22 -22
  139. package/src/seam-commit-transform.mjs +81 -81
  140. package/src/seam-commit.mjs +18 -18
  141. package/src/seam-cost.mjs +322 -322
  142. package/src/seam-derivation.mjs +188 -188
  143. package/src/seam-gate.mjs +146 -146
  144. package/src/seam-proposal-contracts.mjs +446 -446
  145. package/src/seam-proposal-queries.mjs +521 -521
  146. package/src/seam-proposal.mjs +2011 -2011
  147. package/src/seam-ref.mjs +33 -33
  148. package/src/seam-rewrite.mjs +286 -286
  149. package/src/seam-transform.mjs +554 -554
  150. package/src/seam-verification.mjs +260 -260
  151. package/src/sensor-adapter.mjs +432 -432
  152. package/src/sensor-cli.mjs +139 -139
  153. package/src/sensor-diff.mjs +661 -661
  154. package/src/sensor-node-runtime.mjs +53 -53
  155. package/src/sensor-runtime.mjs +52 -52
  156. package/src/timestamp-contract.mjs +8 -8
  157. package/src/todo-audit-pending.mjs +91 -91
  158. package/src/todo-chain.mjs +178 -178
  159. package/src/todo-cli.mjs +8 -8
  160. package/src/todo-contracts.mjs +728 -728
  161. package/src/todo-dashboard-registry.mjs +573 -573
  162. package/src/todo-dispatch-shape.mjs +190 -190
  163. package/src/todo-gantt-html-independence.mjs +239 -239
  164. package/src/todo-gantt-html-shared.mjs +226 -226
  165. package/src/todo-gantt-html-style.mjs +131 -131
  166. package/src/todo-gantt-html.mjs +248 -248
  167. package/src/todo-gantt-layout.mjs +974 -974
  168. package/src/todo-gantt-live.mjs +361 -361
  169. package/src/todo-gantt-nested.mjs +263 -263
  170. package/src/todo-gantt-presentation.mjs +217 -217
  171. package/src/todo-gantt-scope.mjs +123 -123
  172. package/src/todo-gantt-svg.mjs +353 -353
  173. package/src/todo-independence-contracts.mjs +595 -595
  174. package/src/todo-independence-guidance.mjs +322 -322
  175. package/src/todo-independence.mjs +640 -640
  176. package/src/todo-markdown-renderer.mjs +260 -260
  177. package/src/todo-migration.mjs +448 -448
  178. package/src/todo-narrative-anchor.mjs +130 -130
  179. package/src/todo-note-store.mjs +629 -629
  180. package/src/todo-parallel-candidates.mjs +114 -114
  181. package/src/todo-revision.mjs +995 -995
  182. package/src/todo-split.mjs +472 -472
  183. package/src/todo-status.mjs +690 -690
  184. package/src/todo-store-git-transaction.mjs +418 -418
  185. package/src/todo-store.mjs +42 -21
  186. package/src/treatment-compiler.mjs +728 -728
  187. package/src/treatment-runner.mjs +656 -656
  188. package/src/witness-scaffold.mjs +180 -180
@@ -1,353 +1,353 @@
1
- import stringWidth from 'fast-string-width';
2
-
3
- const STATUS_CLASSES = Object.freeze({
4
- pending: 'status-pending',
5
- 'in-progress': 'status-in-progress',
6
- blocked: 'status-blocked',
7
- done: 'status-done',
8
- });
9
-
10
- export const TODO_GANTT_STATUS_PRESENTATION = Object.freeze({
11
- pending: Object.freeze({ mark: '☐', label: '未着手' }),
12
- 'in-progress': Object.freeze({ mark: '▶', label: '作業中' }),
13
- blocked: Object.freeze({ mark: '⛔', label: 'ブロック中' }),
14
- done: Object.freeze({ mark: '✅', label: '完了' }),
15
- });
16
-
17
- /**
18
- * 独立性バッジの記号と和名(ADR 0129 Decision 1)。
19
- *
20
- * 枠線はstatusとready frontierが使い切っているため、カード内の記号と色で示す。
21
- * 記録が語らないtaskにはバッジを出さない——「独立と分かっている」と「まだ何も言えない」を
22
- * 同じ見た目にしない。
23
- */
24
- export const TODO_GANTT_INDEPENDENCE_PRESENTATION = Object.freeze({
25
- verified: Object.freeze({ mark: '∥', label: '独立検証済', class: 'independence-verified' }),
26
- conflict: Object.freeze({ mark: '⛓', label: '要直列', class: 'independence-conflict' }),
27
- unknown: Object.freeze({ mark: '?', label: '未検査', class: 'independence-unknown' }),
28
- });
29
-
30
- export function escapeSvgText(value) {
31
- return String(value).replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;');
32
- }
33
-
34
- export function escapeSvgAttribute(value) {
35
- return escapeSvgText(value).replaceAll('"', '&quot;').replaceAll("'", '&#39;')
36
- .replace(/[\u0000-\u001f\u007f]/gu, '');
37
- }
38
-
39
- function nodeKey(ref) {
40
- return JSON.stringify([ref.project_id, ref.plan_key, ref.task_id]);
41
- }
42
-
43
- function laneKey(planKey, lane) {
44
- return JSON.stringify([planKey, lane]);
45
- }
46
-
47
- const BRIDGE_RADIUS = 5;
48
-
49
- function edgePath(edge) {
50
- const commands = [`M ${edge.route[0][0]} ${edge.route[0][1]}`];
51
- for (let segmentIndex = 0; segmentIndex < edge.route.length - 1; segmentIndex += 1) {
52
- const start = edge.route[segmentIndex];
53
- const end = edge.route[segmentIndex + 1];
54
- const bridges = (edge.bridges ?? []).filter((bridge) => bridge.segment_index === segmentIndex);
55
- if (start[1] !== end[1] || bridges.length === 0) {
56
- commands.push(`L ${end[0]} ${end[1]}`);
57
- continue;
58
- }
59
- const direction = end[0] > start[0] ? 1 : -1;
60
- for (const bridge of bridges) {
61
- commands.push(`L ${bridge.x - direction * BRIDGE_RADIUS} ${bridge.y}`);
62
- commands.push(`A ${BRIDGE_RADIUS} ${BRIDGE_RADIUS} 0 0 ${direction > 0 ? 1 : 0} ${bridge.x + direction * BRIDGE_RADIUS} ${bridge.y}`);
63
- }
64
- commands.push(`L ${end[0]} ${end[1]}`);
65
- }
66
- return commands.join(' ');
67
- }
68
-
69
- function arrowHead(route) {
70
- const [x, y] = route.at(-1);
71
- const [previousX, previousY] = route.at(-2);
72
- const deltaX = x - previousX;
73
- const deltaY = y - previousY;
74
- const length = Math.hypot(deltaX, deltaY) || 1;
75
- const unitX = deltaX / length;
76
- const unitY = deltaY / length;
77
- const baseX = x - unitX * 6;
78
- const baseY = y - unitY * 6;
79
- const perpendicularX = -unitY * 3;
80
- const perpendicularY = unitX * 3;
81
- const compact = (value) => Number(value.toFixed(3));
82
- return `<polygon class="edge-arrow" points="${x},${y} ${compact(baseX + perpendicularX)},${compact(baseY + perpendicularY)} ${compact(baseX - perpendicularX)},${compact(baseY - perpendicularY)}"></polygon>`;
83
- }
84
-
85
- function renderJunction(edge) {
86
- if (edge.junction === null || edge.junction === undefined) return '';
87
- const [x, y] = edge.junction;
88
- return `<g class="join-marker" aria-label="join ${escapeSvgAttribute(edge.join_ids.join(', '))}"><circle cx="${x}" cy="${y}" r="4"></circle><title>${escapeSvgText(edge.join_ids.join(', '))}</title></g>`;
89
- }
90
-
91
- function renderConnector(connector) {
92
- return `<g class="join-connector" data-connector-id="${escapeSvgAttribute(connector.id)}"><path class="edge-route" d="${escapeSvgAttribute(edgePath(connector))}"></path></g>`;
93
- }
94
-
95
- function renderEdge(edge, laneKeysByNode) {
96
- if (!edge.visible || edge.route === null) return '';
97
- const classes = ['dependency-edge'];
98
- if (edge.visibility.longest_dependency_chain) classes.push('longest-chain-edge');
99
- if (edge.visibility.selected_incident) classes.push('selected-incident-edge');
100
- const fromLaneKey = laneKeysByNode.get(nodeKey(edge.from));
101
- const toLaneKey = laneKeysByNode.get(nodeKey(edge.to));
102
- return `<g class="${classes.join(' ')}" data-edge-id="${escapeSvgAttribute(edge.id)}" data-from-node-key="${escapeSvgAttribute(nodeKey(edge.from))}" data-to-node-key="${escapeSvgAttribute(nodeKey(edge.to))}" data-from-lane-key="${escapeSvgAttribute(fromLaneKey)}" data-to-lane-key="${escapeSvgAttribute(toLaneKey)}"><path class="edge-route" d="${escapeSvgAttribute(edgePath(edge))}"></path>${arrowHead(edge.route)}</g>`;
103
- }
104
-
105
- function truncateLabel(value, maximum = 17) {
106
- const source = String(value);
107
- if (stringWidth(source) <= maximum) return source;
108
- let result = '';
109
- for (const character of source) {
110
- if (stringWidth(`${result}${character}…`) > maximum) break;
111
- result += character;
112
- }
113
- return `${result}…`;
114
- }
115
-
116
- function wrapLabel(value, maximum = 30, maximumLines = 2) {
117
- const characters = [...String(value)];
118
- const lines = [];
119
- let cursor = 0;
120
- for (let lineIndex = 0; lineIndex < maximumLines && cursor < characters.length; lineIndex += 1) {
121
- const remaining = characters.slice(cursor).join('');
122
- if (stringWidth(remaining) <= maximum) {
123
- lines.push(remaining);
124
- cursor = characters.length;
125
- break;
126
- }
127
- if (lineIndex === maximumLines - 1) {
128
- lines.push(truncateLabel(remaining, maximum));
129
- cursor = characters.length;
130
- break;
131
- }
132
- let line = '';
133
- while (cursor < characters.length && stringWidth(`${line}${characters[cursor]}`) <= maximum) {
134
- line += characters[cursor];
135
- cursor += 1;
136
- }
137
- if (line === '') {
138
- line = characters[cursor];
139
- cursor += 1;
140
- }
141
- lines.push(line);
142
- }
143
- return lines.length === 0 ? [''] : lines;
144
- }
145
-
146
- function presentationMaps(presentation) {
147
- return {
148
- lanes: new Map((presentation?.lanes ?? []).map((entry) => [laneKey(entry.plan_key, entry.lane), entry])),
149
- taskNumbers: new Map((presentation?.task_numbers ?? []).map((entry) => [nodeKey(entry), entry])),
150
- };
151
- }
152
-
153
- function renderNode(node, maps) {
154
- if (!node.visible || node.geometry === null) return '';
155
- const { x, y, width, height } = node.geometry;
156
- const classes = ['todo-node', STATUS_CLASSES[node.status] ?? 'status-unknown'];
157
- if (node.visibility.longest_dependency_chain) classes.push('longest-chain-node');
158
- if (node.visibility.active) classes.push('active-node');
159
- if (node.visibility.next_ready) classes.push('next-ready-node');
160
- if (node.visibility.selected) classes.push('selected-node');
161
- const independence = TODO_GANTT_INDEPENDENCE_PRESENTATION[node.visibility.independence] ?? null;
162
- if (independence !== null) classes.push(independence.class);
163
- const key = nodeKey(node.ref);
164
- const nodeLaneKey = laneKey(node.ref.plan_key, node.lane);
165
- const status = TODO_GANTT_STATUS_PRESENTATION[node.status] ?? { mark: '?', label: '状態不明' };
166
- const lane = maps.lanes.get(nodeLaneKey);
167
- const laneLabel = lane === undefined ? node.lane : `${node.lane}、${lane.name}`;
168
- const taskNumber = maps.taskNumbers.get(key);
169
- const visibleReference = `工程 ${node.ref.task_id}`;
170
- const spokenReference = `工程${node.ref.task_id}`;
171
- const readyLabel = node.visibility.next_ready ? '。ready frontierの同時dispatch候補' : '';
172
- const independenceLabel = independence === null ? '' : `。並列可否は${independence.label}`;
173
- const identity = `正規ID ${node.ref.plan_key}/${node.ref.task_id}`;
174
- const ariaLabel = `${spokenReference}。${status.label}。${laneLabel}。${node.title}。${identity}${readyLabel}${independenceLabel}`;
175
- // カードの右上へ寄せる。node_width/node_heightは変えないので配線規約に影響しない。
176
- const independenceBadge = independence === null ? ''
177
- : `<text class="independence-badge" x="${x + width - 10}" y="${y + 20}" text-anchor="end">${escapeSvgText(`${independence.mark} ${independence.label}`)}</text>`;
178
- const statusBar = node.status === 'in-progress'
179
- ? `<line class="status-bar" x1="${x + 5}" y1="${y + 6}" x2="${x + 5}" y2="${y + height - 6}"></line>` : '';
180
- const titleLines = wrapLabel(node.title);
181
- const titleMarkup = titleLines.map((line, index) => `<tspan x="${x + 10}" dy="${index === 0 ? 0 : 17}" class="node-title-line">${escapeSvgText(line)}</tspan>`).join('');
182
- const taskNumberAttributes = taskNumber === undefined ? ''
183
- : ` data-task-number="${escapeSvgAttribute(taskNumber.display_number)}" data-task-number-normalized="${escapeSvgAttribute(taskNumber.normalized_number)}" data-task-number-globally-unique="${taskNumber.globally_unique ? 'true' : 'false'}"`;
184
- return `<g class="${classes.join(' ')}" data-node-key="${escapeSvgAttribute(key)}" data-lane-key="${escapeSvgAttribute(nodeLaneKey)}" data-project-id="${escapeSvgAttribute(node.ref.project_id)}" data-plan-key="${escapeSvgAttribute(node.ref.plan_key)}" data-task-id="${escapeSvgAttribute(node.ref.task_id)}"${taskNumberAttributes} tabindex="0" role="button" aria-selected="${node.visibility.selected ? 'true' : 'false'}" aria-label="${escapeSvgAttribute(ariaLabel)}"><rect class="node-surface" x="${x}" y="${y}" width="${width}" height="${height}" rx="4"></rect>${statusBar}<text class="status-mark" x="${x + 10}" y="${y + 21}">${escapeSvgText(status.mark)}</text><text class="node-meta" x="${x + 34}" y="${y + 20}">${escapeSvgText(`${status.label} · ${visibleReference}`)}</text>${independenceBadge}<text class="node-title" x="${x + 10}" y="${y + 42}">${titleMarkup}</text><title>${escapeSvgText(`${spokenReference}: ${node.title} — ${status.label} — ${laneLabel} — ${identity}`)}</title></g>`;
185
- }
186
-
187
- function summaryLabel(value, maximum = 34) {
188
- return truncateLabel(value, maximum);
189
- }
190
-
191
- function summaryChipWidth(label, minimum = 116) {
192
- return Math.max(minimum, Math.min(280, 24 + stringWidth(label) * 7));
193
- }
194
-
195
- function renderTodoSummary(layout, maps) {
196
- const markup = [];
197
- let groupX = 16;
198
- // The band is a header for the diagram, so it covers what the diagram draws.
199
- // Keeping a chip for every lane of every finished plan stretched the canvas to
200
- // several times the width of the graph itself, all of it empty columns.
201
- // The chips still count every ToDo in the lane, folded ones included.
202
- const drawnPlans = new Set(layout.nodes.map((node) => node.ref.plan_key));
203
- const drawnLanes = new Set(layout.nodes.map((node) => laneKey(node.ref.plan_key, node.lane)));
204
- for (const plan of layout.groups.plans.filter(({ plan_key }) => drawnPlans.has(plan_key))) {
205
- const lanes = layout.groups.lanes.filter((lane) => lane.plan_key === plan.plan_key
206
- && drawnLanes.has(laneKey(lane.plan_key, lane.lane)));
207
- const laneChips = lanes.map((lane) => {
208
- const metadata = maps.lanes.get(laneKey(lane.plan_key, lane.lane));
209
- const fullLabel = metadata === undefined
210
- ? `${lane.lane} ${lane.task_count}`
211
- : `${lane.lane} · ${metadata.name} ${lane.task_count}`;
212
- const label = summaryLabel(fullLabel);
213
- const ariaLabel = metadata === undefined
214
- ? `${lane.lane} — ${lane.task_count} ToDo`
215
- : `${lane.lane} — ${metadata.name}、${lane.task_count} ToDo。${metadata.description}`;
216
- return { lane, metadata, fullLabel, ariaLabel, label, width: summaryChipWidth(label) };
217
- });
218
- const childrenWidth = laneChips.reduce((total, chip) => total + chip.width, 0)
219
- + Math.max(0, laneChips.length - 1) * 8;
220
- const planLabel = summaryLabel(`${plan.plan_key} · ${plan.task_count} ToDo`);
221
- const contentWidth = Math.max(summaryChipWidth(planLabel, 152), childrenWidth);
222
- const groupWidth = contentWidth + 16;
223
- markup.push(`<g class="summary-plan-group" aria-label="${escapeSvgAttribute(`${plan.plan_key} — ${plan.task_count} ToDo、${laneChips.length} lanes`)}"><rect class="summary-container" x="${groupX}" y="8" width="${groupWidth}" height="72" rx="8"></rect><g class="summary-plan" aria-label="${escapeSvgAttribute(`${plan.plan_key} — ${plan.task_count} ToDo`)}"><rect class="summary-chip plan-chip" x="${groupX + 8}" y="16" width="${summaryChipWidth(planLabel, 152)}" height="24" rx="9999"></rect><text x="${groupX + 20}" y="33">${escapeSvgText(planLabel)}</text><title>${escapeSvgText(`${plan.plan_key}: ${plan.task_count} ToDo`)}</title></g>`);
224
- let laneX = groupX + 8;
225
- for (const chip of laneChips) {
226
- const key = laneKey(chip.lane.plan_key, chip.lane.lane);
227
- markup.push(`<g class="summary-lane" data-lane-key="${escapeSvgAttribute(key)}" role="button" tabindex="0" aria-pressed="false" aria-label="${escapeSvgAttribute(chip.ariaLabel)}"><rect class="summary-chip lane-chip" x="${laneX}" y="48" width="${chip.width}" height="24" rx="9999"></rect><text x="${laneX + 12}" y="65">${escapeSvgText(chip.label)}</text><title>${escapeSvgText(chip.ariaLabel)}</title></g>`);
228
- laneX += chip.width + 8;
229
- }
230
- markup.push('</g>');
231
- groupX += groupWidth + 16;
232
- }
233
- return { markup: `<g class="todo-summary" aria-label="カテゴリ別ToDo集計表">${markup.join('')}</g>`, height: 96, width: groupX };
234
- }
235
-
236
- function renderFlatTodoGanttSvg(layout, options = {}) {
237
- if (layout === null || typeof layout !== 'object' || layout.schema !== 'lattice.todo_gantt_layout.v2'
238
- || !Array.isArray(layout.nodes) || !Array.isArray(layout.edges)) {
239
- throw new TypeError('layout must be lattice.todo_gantt_layout.v2');
240
- }
241
- const maps = presentationMaps(options.presentation);
242
- const summary = renderTodoSummary(layout, maps);
243
- const contentOffset = summary.height;
244
- const width = Math.max(240, layout.bounds.width + 40, summary.width + 12);
245
- const height = Math.max(240, layout.bounds.height + contentOffset + 32);
246
- const laneKeysByNode = new Map(layout.nodes.map((node) => [
247
- nodeKey(node.ref), laneKey(node.ref.plan_key, node.lane),
248
- ]));
249
- const nodes = layout.nodes.map((node) => {
250
- if (node.geometry === null) return '';
251
- return renderNode({ ...node, geometry: { ...node.geometry, y: node.geometry.y + contentOffset } }, maps);
252
- }).join('');
253
- // Edge coordinates need the same vertical offset as nodes.
254
- const shiftedEdgeModels = layout.edges.map((edge) => edge.route === null ? edge : ({
255
- ...edge,
256
- route: edge.route.map(([x, y]) => [x, y + contentOffset]),
257
- bridges: (edge.bridges ?? []).map((bridge) => ({ ...bridge, y: bridge.y + contentOffset })),
258
- junction: edge.junction === null || edge.junction === undefined
259
- ? null : [edge.junction[0], edge.junction[1] + contentOffset],
260
- }));
261
- const shiftedConnectors = (layout.connectors ?? []).map((connector) => ({
262
- ...connector,
263
- route: connector.route.map(([x, y]) => [x, y + contentOffset]),
264
- bridges: (connector.bridges ?? []).map((bridge) => ({ ...bridge, y: bridge.y + contentOffset })),
265
- contacts: (connector.contacts ?? []).map(([x, y]) => [x, y + contentOffset]),
266
- }));
267
- const shiftedEdges = shiftedEdgeModels.map((edge) => renderEdge(edge, laneKeysByNode)).join('');
268
- const connectors = shiftedConnectors.map(renderConnector).join('');
269
- const junctions = shiftedEdgeModels.map(renderJunction).join('');
270
- const mainJunctions = new Set(shiftedEdgeModels.filter(({ junction }) => junction !== null)
271
- .map(({ junction }) => junction.join(',')));
272
- const contactMarkers = shiftedConnectors.flatMap(({ contacts }) => contacts)
273
- .filter((contact) => !mainJunctions.has(contact.join(',')))
274
- .map(([x, y]) => `<circle class="join-contact-marker" cx="${x}" cy="${y}" r="3"></circle>`).join('');
275
- return `<svg class="todo-gantt" data-gantt-svg data-svg-width="${width}" data-svg-height="${height}" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${width} ${height}" width="${width}" height="${height}" role="group" aria-label="Todo依存工程図"><desc>縦方向は登録済み依存関係による工程段階。構造上の最長依存鎖は各工程を同じ重みとして数え、実時間・工数・資源律速を表さない。</desc>${summary.markup}<g class="edge-layer">${shiftedEdges}<g class="connector-layer">${connectors}</g><g class="junction-layer">${junctions}${contactMarkers}</g></g><g class="node-layer">${nodes}</g></svg>`;
276
- }
277
-
278
- function svgDimensions(markup) {
279
- const match = markup.match(/data-svg-width="([0-9.]+)" data-svg-height="([0-9.]+)"/u);
280
- if (match === null) throw new TypeError('nested todo gantt SVG must expose its dimensions');
281
- return { width: Number(match[1]), height: Number(match[2]) };
282
- }
283
-
284
- function resizeSvg(markup, width, height) {
285
- return markup
286
- .replace(/data-svg-width="[0-9.]+" data-svg-height="[0-9.]+"/u,
287
- `data-svg-width="${width}" data-svg-height="${height}"`)
288
- .replace(/viewBox="0 0 [0-9.]+ [0-9.]+" width="[0-9.]+" height="[0-9.]+"/u,
289
- `viewBox="0 0 ${width} ${height}" width="${width}" height="${height}"`);
290
- }
291
-
292
- function childLayoutOf(child) {
293
- if (child.level.children.length === 0) return child.level.layout;
294
- return {
295
- ...child.level.layout,
296
- hierarchy: {
297
- schema: 'lattice.todo_gantt_hierarchy.v1',
298
- children: child.level.children,
299
- },
300
- };
301
- }
302
-
303
- function renderNestedTodoGanttSvg(layout, options) {
304
- let markup = renderFlatTodoGanttSvg(layout, options);
305
- const base = svgDimensions(markup);
306
- let width = base.width;
307
- let height = base.height;
308
- const panels = [];
309
- const toggles = [];
310
- const links = [];
311
- const nodeByKey = new Map(layout.nodes.map((node) => [nodeKey(node.ref), node]));
312
- let nextPanelY = 96;
313
-
314
- for (const child of layout.hierarchy.children) {
315
- const key = nodeKey(child.parent_ref);
316
- const parent = nodeByKey.get(key);
317
- if (parent?.geometry === null || parent === undefined) continue;
318
- const childMarkup = renderTodoGanttSvg(childLayoutOf(child), options);
319
- const childSize = svgDimensions(childMarkup);
320
- // 開いた内部工程図を基底DAGの上へ重ねない。右側へ専用領域を確保し、親カードから
321
- // 直交線で結ぶ。これなら後続taskも、同じ箱の兄弟taskも隠れない。
322
- const panelX = base.width + 16;
323
- const panelY = Math.max(parent.geometry.y + 96, nextPanelY);
324
- const panelWidth = childSize.width + 24;
325
- const panelHeight = childSize.height + 44;
326
- nextPanelY = panelY + panelHeight + 16;
327
- width = Math.max(width, panelX + panelWidth + 16);
328
- height = Math.max(height, panelY + panelHeight + 16);
329
- const embedded = childMarkup.replace('<svg class="todo-gantt"',
330
- `<svg x="${panelX + 12}" y="${panelY + 32}" class="todo-gantt nested-task-diagram"`);
331
- const label = `工程 ${child.parent_ref.plan_key}/${child.parent_ref.task_id} の内部工程`;
332
- panels.push(`<g class="nested-task-panel" data-nested-panel-for="${escapeSvgAttribute(key)}" hidden aria-label="${escapeSvgAttribute(label)}"><rect class="nested-task-surface" x="${panelX}" y="${panelY}" width="${panelWidth}" height="${panelHeight}" rx="8"></rect><text class="nested-task-label" x="${panelX + 12}" y="${panelY + 22}">${escapeSvgText(label)}</text>${embedded}</g>`);
333
- const parentX = parent.geometry.x + parent.geometry.width;
334
- const parentY = parent.geometry.y + 96 + parent.geometry.height / 2;
335
- const elbowX = panelX - 8;
336
- links.push(`<path class="nested-task-link" data-nested-link-for="${escapeSvgAttribute(key)}" hidden d="M ${parentX} ${parentY} H ${elbowX} V ${panelY + 18} H ${panelX}"></path>`);
337
- const toggleX = parent.geometry.x + parent.geometry.width - 24;
338
- const toggleY = parent.geometry.y + 96 + parent.geometry.height - 18;
339
- toggles.push(`<g class="nested-task-toggle" data-nested-toggle-for="${escapeSvgAttribute(key)}" tabindex="0" role="button" aria-expanded="false" aria-label="${escapeSvgAttribute(`${label}を開く`)}"><rect x="${toggleX - 8}" y="${toggleY - 13}" width="28" height="22" rx="4"></rect><text x="${toggleX + 6}" y="${toggleY + 3}" text-anchor="middle">+</text></g>`);
340
- }
341
-
342
- markup = resizeSvg(markup, width, height);
343
- return markup.replace('</svg>', `<g class="nested-link-layer">${links.join('')}</g><g class="nested-panel-layer">${panels.join('')}</g><g class="nested-toggle-layer">${toggles.join('')}</g></svg>`);
344
- }
345
-
346
- export function renderTodoGanttSvg(layout, options = {}) {
347
- if (layout?.hierarchy === undefined) return renderFlatTodoGanttSvg(layout, options);
348
- if (layout.hierarchy?.schema !== 'lattice.todo_gantt_hierarchy.v1'
349
- || !Array.isArray(layout.hierarchy.children)) {
350
- throw new TypeError('layout hierarchy must be lattice.todo_gantt_hierarchy.v1');
351
- }
352
- return renderNestedTodoGanttSvg(layout, options);
353
- }
1
+ import stringWidth from 'fast-string-width';
2
+
3
+ const STATUS_CLASSES = Object.freeze({
4
+ pending: 'status-pending',
5
+ 'in-progress': 'status-in-progress',
6
+ blocked: 'status-blocked',
7
+ done: 'status-done',
8
+ });
9
+
10
+ export const TODO_GANTT_STATUS_PRESENTATION = Object.freeze({
11
+ pending: Object.freeze({ mark: '☐', label: '未着手' }),
12
+ 'in-progress': Object.freeze({ mark: '▶', label: '作業中' }),
13
+ blocked: Object.freeze({ mark: '⛔', label: 'ブロック中' }),
14
+ done: Object.freeze({ mark: '✅', label: '完了' }),
15
+ });
16
+
17
+ /**
18
+ * 独立性バッジの記号と和名(ADR 0129 Decision 1)。
19
+ *
20
+ * 枠線はstatusとready frontierが使い切っているため、カード内の記号と色で示す。
21
+ * 記録が語らないtaskにはバッジを出さない——「独立と分かっている」と「まだ何も言えない」を
22
+ * 同じ見た目にしない。
23
+ */
24
+ export const TODO_GANTT_INDEPENDENCE_PRESENTATION = Object.freeze({
25
+ verified: Object.freeze({ mark: '∥', label: '独立検証済', class: 'independence-verified' }),
26
+ conflict: Object.freeze({ mark: '⛓', label: '要直列', class: 'independence-conflict' }),
27
+ unknown: Object.freeze({ mark: '?', label: '未検査', class: 'independence-unknown' }),
28
+ });
29
+
30
+ export function escapeSvgText(value) {
31
+ return String(value).replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;');
32
+ }
33
+
34
+ export function escapeSvgAttribute(value) {
35
+ return escapeSvgText(value).replaceAll('"', '&quot;').replaceAll("'", '&#39;')
36
+ .replace(/[\u0000-\u001f\u007f]/gu, '');
37
+ }
38
+
39
+ function nodeKey(ref) {
40
+ return JSON.stringify([ref.project_id, ref.plan_key, ref.task_id]);
41
+ }
42
+
43
+ function laneKey(planKey, lane) {
44
+ return JSON.stringify([planKey, lane]);
45
+ }
46
+
47
+ const BRIDGE_RADIUS = 5;
48
+
49
+ function edgePath(edge) {
50
+ const commands = [`M ${edge.route[0][0]} ${edge.route[0][1]}`];
51
+ for (let segmentIndex = 0; segmentIndex < edge.route.length - 1; segmentIndex += 1) {
52
+ const start = edge.route[segmentIndex];
53
+ const end = edge.route[segmentIndex + 1];
54
+ const bridges = (edge.bridges ?? []).filter((bridge) => bridge.segment_index === segmentIndex);
55
+ if (start[1] !== end[1] || bridges.length === 0) {
56
+ commands.push(`L ${end[0]} ${end[1]}`);
57
+ continue;
58
+ }
59
+ const direction = end[0] > start[0] ? 1 : -1;
60
+ for (const bridge of bridges) {
61
+ commands.push(`L ${bridge.x - direction * BRIDGE_RADIUS} ${bridge.y}`);
62
+ commands.push(`A ${BRIDGE_RADIUS} ${BRIDGE_RADIUS} 0 0 ${direction > 0 ? 1 : 0} ${bridge.x + direction * BRIDGE_RADIUS} ${bridge.y}`);
63
+ }
64
+ commands.push(`L ${end[0]} ${end[1]}`);
65
+ }
66
+ return commands.join(' ');
67
+ }
68
+
69
+ function arrowHead(route) {
70
+ const [x, y] = route.at(-1);
71
+ const [previousX, previousY] = route.at(-2);
72
+ const deltaX = x - previousX;
73
+ const deltaY = y - previousY;
74
+ const length = Math.hypot(deltaX, deltaY) || 1;
75
+ const unitX = deltaX / length;
76
+ const unitY = deltaY / length;
77
+ const baseX = x - unitX * 6;
78
+ const baseY = y - unitY * 6;
79
+ const perpendicularX = -unitY * 3;
80
+ const perpendicularY = unitX * 3;
81
+ const compact = (value) => Number(value.toFixed(3));
82
+ return `<polygon class="edge-arrow" points="${x},${y} ${compact(baseX + perpendicularX)},${compact(baseY + perpendicularY)} ${compact(baseX - perpendicularX)},${compact(baseY - perpendicularY)}"></polygon>`;
83
+ }
84
+
85
+ function renderJunction(edge) {
86
+ if (edge.junction === null || edge.junction === undefined) return '';
87
+ const [x, y] = edge.junction;
88
+ return `<g class="join-marker" aria-label="join ${escapeSvgAttribute(edge.join_ids.join(', '))}"><circle cx="${x}" cy="${y}" r="4"></circle><title>${escapeSvgText(edge.join_ids.join(', '))}</title></g>`;
89
+ }
90
+
91
+ function renderConnector(connector) {
92
+ return `<g class="join-connector" data-connector-id="${escapeSvgAttribute(connector.id)}"><path class="edge-route" d="${escapeSvgAttribute(edgePath(connector))}"></path></g>`;
93
+ }
94
+
95
+ function renderEdge(edge, laneKeysByNode) {
96
+ if (!edge.visible || edge.route === null) return '';
97
+ const classes = ['dependency-edge'];
98
+ if (edge.visibility.longest_dependency_chain) classes.push('longest-chain-edge');
99
+ if (edge.visibility.selected_incident) classes.push('selected-incident-edge');
100
+ const fromLaneKey = laneKeysByNode.get(nodeKey(edge.from));
101
+ const toLaneKey = laneKeysByNode.get(nodeKey(edge.to));
102
+ return `<g class="${classes.join(' ')}" data-edge-id="${escapeSvgAttribute(edge.id)}" data-from-node-key="${escapeSvgAttribute(nodeKey(edge.from))}" data-to-node-key="${escapeSvgAttribute(nodeKey(edge.to))}" data-from-lane-key="${escapeSvgAttribute(fromLaneKey)}" data-to-lane-key="${escapeSvgAttribute(toLaneKey)}"><path class="edge-route" d="${escapeSvgAttribute(edgePath(edge))}"></path>${arrowHead(edge.route)}</g>`;
103
+ }
104
+
105
+ function truncateLabel(value, maximum = 17) {
106
+ const source = String(value);
107
+ if (stringWidth(source) <= maximum) return source;
108
+ let result = '';
109
+ for (const character of source) {
110
+ if (stringWidth(`${result}${character}…`) > maximum) break;
111
+ result += character;
112
+ }
113
+ return `${result}…`;
114
+ }
115
+
116
+ function wrapLabel(value, maximum = 30, maximumLines = 2) {
117
+ const characters = [...String(value)];
118
+ const lines = [];
119
+ let cursor = 0;
120
+ for (let lineIndex = 0; lineIndex < maximumLines && cursor < characters.length; lineIndex += 1) {
121
+ const remaining = characters.slice(cursor).join('');
122
+ if (stringWidth(remaining) <= maximum) {
123
+ lines.push(remaining);
124
+ cursor = characters.length;
125
+ break;
126
+ }
127
+ if (lineIndex === maximumLines - 1) {
128
+ lines.push(truncateLabel(remaining, maximum));
129
+ cursor = characters.length;
130
+ break;
131
+ }
132
+ let line = '';
133
+ while (cursor < characters.length && stringWidth(`${line}${characters[cursor]}`) <= maximum) {
134
+ line += characters[cursor];
135
+ cursor += 1;
136
+ }
137
+ if (line === '') {
138
+ line = characters[cursor];
139
+ cursor += 1;
140
+ }
141
+ lines.push(line);
142
+ }
143
+ return lines.length === 0 ? [''] : lines;
144
+ }
145
+
146
+ function presentationMaps(presentation) {
147
+ return {
148
+ lanes: new Map((presentation?.lanes ?? []).map((entry) => [laneKey(entry.plan_key, entry.lane), entry])),
149
+ taskNumbers: new Map((presentation?.task_numbers ?? []).map((entry) => [nodeKey(entry), entry])),
150
+ };
151
+ }
152
+
153
+ function renderNode(node, maps) {
154
+ if (!node.visible || node.geometry === null) return '';
155
+ const { x, y, width, height } = node.geometry;
156
+ const classes = ['todo-node', STATUS_CLASSES[node.status] ?? 'status-unknown'];
157
+ if (node.visibility.longest_dependency_chain) classes.push('longest-chain-node');
158
+ if (node.visibility.active) classes.push('active-node');
159
+ if (node.visibility.next_ready) classes.push('next-ready-node');
160
+ if (node.visibility.selected) classes.push('selected-node');
161
+ const independence = TODO_GANTT_INDEPENDENCE_PRESENTATION[node.visibility.independence] ?? null;
162
+ if (independence !== null) classes.push(independence.class);
163
+ const key = nodeKey(node.ref);
164
+ const nodeLaneKey = laneKey(node.ref.plan_key, node.lane);
165
+ const status = TODO_GANTT_STATUS_PRESENTATION[node.status] ?? { mark: '?', label: '状態不明' };
166
+ const lane = maps.lanes.get(nodeLaneKey);
167
+ const laneLabel = lane === undefined ? node.lane : `${node.lane}、${lane.name}`;
168
+ const taskNumber = maps.taskNumbers.get(key);
169
+ const visibleReference = `工程 ${node.ref.task_id}`;
170
+ const spokenReference = `工程${node.ref.task_id}`;
171
+ const readyLabel = node.visibility.next_ready ? '。ready frontierの同時dispatch候補' : '';
172
+ const independenceLabel = independence === null ? '' : `。並列可否は${independence.label}`;
173
+ const identity = `正規ID ${node.ref.plan_key}/${node.ref.task_id}`;
174
+ const ariaLabel = `${spokenReference}。${status.label}。${laneLabel}。${node.title}。${identity}${readyLabel}${independenceLabel}`;
175
+ // カードの右上へ寄せる。node_width/node_heightは変えないので配線規約に影響しない。
176
+ const independenceBadge = independence === null ? ''
177
+ : `<text class="independence-badge" x="${x + width - 10}" y="${y + 20}" text-anchor="end">${escapeSvgText(`${independence.mark} ${independence.label}`)}</text>`;
178
+ const statusBar = node.status === 'in-progress'
179
+ ? `<line class="status-bar" x1="${x + 5}" y1="${y + 6}" x2="${x + 5}" y2="${y + height - 6}"></line>` : '';
180
+ const titleLines = wrapLabel(node.title);
181
+ const titleMarkup = titleLines.map((line, index) => `<tspan x="${x + 10}" dy="${index === 0 ? 0 : 17}" class="node-title-line">${escapeSvgText(line)}</tspan>`).join('');
182
+ const taskNumberAttributes = taskNumber === undefined ? ''
183
+ : ` data-task-number="${escapeSvgAttribute(taskNumber.display_number)}" data-task-number-normalized="${escapeSvgAttribute(taskNumber.normalized_number)}" data-task-number-globally-unique="${taskNumber.globally_unique ? 'true' : 'false'}"`;
184
+ return `<g class="${classes.join(' ')}" data-node-key="${escapeSvgAttribute(key)}" data-lane-key="${escapeSvgAttribute(nodeLaneKey)}" data-project-id="${escapeSvgAttribute(node.ref.project_id)}" data-plan-key="${escapeSvgAttribute(node.ref.plan_key)}" data-task-id="${escapeSvgAttribute(node.ref.task_id)}"${taskNumberAttributes} tabindex="0" role="button" aria-selected="${node.visibility.selected ? 'true' : 'false'}" aria-label="${escapeSvgAttribute(ariaLabel)}"><rect class="node-surface" x="${x}" y="${y}" width="${width}" height="${height}" rx="4"></rect>${statusBar}<text class="status-mark" x="${x + 10}" y="${y + 21}">${escapeSvgText(status.mark)}</text><text class="node-meta" x="${x + 34}" y="${y + 20}">${escapeSvgText(`${status.label} · ${visibleReference}`)}</text>${independenceBadge}<text class="node-title" x="${x + 10}" y="${y + 42}">${titleMarkup}</text><title>${escapeSvgText(`${spokenReference}: ${node.title} — ${status.label} — ${laneLabel} — ${identity}`)}</title></g>`;
185
+ }
186
+
187
+ function summaryLabel(value, maximum = 34) {
188
+ return truncateLabel(value, maximum);
189
+ }
190
+
191
+ function summaryChipWidth(label, minimum = 116) {
192
+ return Math.max(minimum, Math.min(280, 24 + stringWidth(label) * 7));
193
+ }
194
+
195
+ function renderTodoSummary(layout, maps) {
196
+ const markup = [];
197
+ let groupX = 16;
198
+ // The band is a header for the diagram, so it covers what the diagram draws.
199
+ // Keeping a chip for every lane of every finished plan stretched the canvas to
200
+ // several times the width of the graph itself, all of it empty columns.
201
+ // The chips still count every ToDo in the lane, folded ones included.
202
+ const drawnPlans = new Set(layout.nodes.map((node) => node.ref.plan_key));
203
+ const drawnLanes = new Set(layout.nodes.map((node) => laneKey(node.ref.plan_key, node.lane)));
204
+ for (const plan of layout.groups.plans.filter(({ plan_key }) => drawnPlans.has(plan_key))) {
205
+ const lanes = layout.groups.lanes.filter((lane) => lane.plan_key === plan.plan_key
206
+ && drawnLanes.has(laneKey(lane.plan_key, lane.lane)));
207
+ const laneChips = lanes.map((lane) => {
208
+ const metadata = maps.lanes.get(laneKey(lane.plan_key, lane.lane));
209
+ const fullLabel = metadata === undefined
210
+ ? `${lane.lane} ${lane.task_count}`
211
+ : `${lane.lane} · ${metadata.name} ${lane.task_count}`;
212
+ const label = summaryLabel(fullLabel);
213
+ const ariaLabel = metadata === undefined
214
+ ? `${lane.lane} — ${lane.task_count} ToDo`
215
+ : `${lane.lane} — ${metadata.name}、${lane.task_count} ToDo。${metadata.description}`;
216
+ return { lane, metadata, fullLabel, ariaLabel, label, width: summaryChipWidth(label) };
217
+ });
218
+ const childrenWidth = laneChips.reduce((total, chip) => total + chip.width, 0)
219
+ + Math.max(0, laneChips.length - 1) * 8;
220
+ const planLabel = summaryLabel(`${plan.plan_key} · ${plan.task_count} ToDo`);
221
+ const contentWidth = Math.max(summaryChipWidth(planLabel, 152), childrenWidth);
222
+ const groupWidth = contentWidth + 16;
223
+ markup.push(`<g class="summary-plan-group" aria-label="${escapeSvgAttribute(`${plan.plan_key} — ${plan.task_count} ToDo、${laneChips.length} lanes`)}"><rect class="summary-container" x="${groupX}" y="8" width="${groupWidth}" height="72" rx="8"></rect><g class="summary-plan" aria-label="${escapeSvgAttribute(`${plan.plan_key} — ${plan.task_count} ToDo`)}"><rect class="summary-chip plan-chip" x="${groupX + 8}" y="16" width="${summaryChipWidth(planLabel, 152)}" height="24" rx="9999"></rect><text x="${groupX + 20}" y="33">${escapeSvgText(planLabel)}</text><title>${escapeSvgText(`${plan.plan_key}: ${plan.task_count} ToDo`)}</title></g>`);
224
+ let laneX = groupX + 8;
225
+ for (const chip of laneChips) {
226
+ const key = laneKey(chip.lane.plan_key, chip.lane.lane);
227
+ markup.push(`<g class="summary-lane" data-lane-key="${escapeSvgAttribute(key)}" role="button" tabindex="0" aria-pressed="false" aria-label="${escapeSvgAttribute(chip.ariaLabel)}"><rect class="summary-chip lane-chip" x="${laneX}" y="48" width="${chip.width}" height="24" rx="9999"></rect><text x="${laneX + 12}" y="65">${escapeSvgText(chip.label)}</text><title>${escapeSvgText(chip.ariaLabel)}</title></g>`);
228
+ laneX += chip.width + 8;
229
+ }
230
+ markup.push('</g>');
231
+ groupX += groupWidth + 16;
232
+ }
233
+ return { markup: `<g class="todo-summary" aria-label="カテゴリ別ToDo集計表">${markup.join('')}</g>`, height: 96, width: groupX };
234
+ }
235
+
236
+ function renderFlatTodoGanttSvg(layout, options = {}) {
237
+ if (layout === null || typeof layout !== 'object' || layout.schema !== 'lattice.todo_gantt_layout.v2'
238
+ || !Array.isArray(layout.nodes) || !Array.isArray(layout.edges)) {
239
+ throw new TypeError('layout must be lattice.todo_gantt_layout.v2');
240
+ }
241
+ const maps = presentationMaps(options.presentation);
242
+ const summary = renderTodoSummary(layout, maps);
243
+ const contentOffset = summary.height;
244
+ const width = Math.max(240, layout.bounds.width + 40, summary.width + 12);
245
+ const height = Math.max(240, layout.bounds.height + contentOffset + 32);
246
+ const laneKeysByNode = new Map(layout.nodes.map((node) => [
247
+ nodeKey(node.ref), laneKey(node.ref.plan_key, node.lane),
248
+ ]));
249
+ const nodes = layout.nodes.map((node) => {
250
+ if (node.geometry === null) return '';
251
+ return renderNode({ ...node, geometry: { ...node.geometry, y: node.geometry.y + contentOffset } }, maps);
252
+ }).join('');
253
+ // Edge coordinates need the same vertical offset as nodes.
254
+ const shiftedEdgeModels = layout.edges.map((edge) => edge.route === null ? edge : ({
255
+ ...edge,
256
+ route: edge.route.map(([x, y]) => [x, y + contentOffset]),
257
+ bridges: (edge.bridges ?? []).map((bridge) => ({ ...bridge, y: bridge.y + contentOffset })),
258
+ junction: edge.junction === null || edge.junction === undefined
259
+ ? null : [edge.junction[0], edge.junction[1] + contentOffset],
260
+ }));
261
+ const shiftedConnectors = (layout.connectors ?? []).map((connector) => ({
262
+ ...connector,
263
+ route: connector.route.map(([x, y]) => [x, y + contentOffset]),
264
+ bridges: (connector.bridges ?? []).map((bridge) => ({ ...bridge, y: bridge.y + contentOffset })),
265
+ contacts: (connector.contacts ?? []).map(([x, y]) => [x, y + contentOffset]),
266
+ }));
267
+ const shiftedEdges = shiftedEdgeModels.map((edge) => renderEdge(edge, laneKeysByNode)).join('');
268
+ const connectors = shiftedConnectors.map(renderConnector).join('');
269
+ const junctions = shiftedEdgeModels.map(renderJunction).join('');
270
+ const mainJunctions = new Set(shiftedEdgeModels.filter(({ junction }) => junction !== null)
271
+ .map(({ junction }) => junction.join(',')));
272
+ const contactMarkers = shiftedConnectors.flatMap(({ contacts }) => contacts)
273
+ .filter((contact) => !mainJunctions.has(contact.join(',')))
274
+ .map(([x, y]) => `<circle class="join-contact-marker" cx="${x}" cy="${y}" r="3"></circle>`).join('');
275
+ return `<svg class="todo-gantt" data-gantt-svg data-svg-width="${width}" data-svg-height="${height}" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${width} ${height}" width="${width}" height="${height}" role="group" aria-label="Todo依存工程図"><desc>縦方向は登録済み依存関係による工程段階。構造上の最長依存鎖は各工程を同じ重みとして数え、実時間・工数・資源律速を表さない。</desc>${summary.markup}<g class="edge-layer">${shiftedEdges}<g class="connector-layer">${connectors}</g><g class="junction-layer">${junctions}${contactMarkers}</g></g><g class="node-layer">${nodes}</g></svg>`;
276
+ }
277
+
278
+ function svgDimensions(markup) {
279
+ const match = markup.match(/data-svg-width="([0-9.]+)" data-svg-height="([0-9.]+)"/u);
280
+ if (match === null) throw new TypeError('nested todo gantt SVG must expose its dimensions');
281
+ return { width: Number(match[1]), height: Number(match[2]) };
282
+ }
283
+
284
+ function resizeSvg(markup, width, height) {
285
+ return markup
286
+ .replace(/data-svg-width="[0-9.]+" data-svg-height="[0-9.]+"/u,
287
+ `data-svg-width="${width}" data-svg-height="${height}"`)
288
+ .replace(/viewBox="0 0 [0-9.]+ [0-9.]+" width="[0-9.]+" height="[0-9.]+"/u,
289
+ `viewBox="0 0 ${width} ${height}" width="${width}" height="${height}"`);
290
+ }
291
+
292
+ function childLayoutOf(child) {
293
+ if (child.level.children.length === 0) return child.level.layout;
294
+ return {
295
+ ...child.level.layout,
296
+ hierarchy: {
297
+ schema: 'lattice.todo_gantt_hierarchy.v1',
298
+ children: child.level.children,
299
+ },
300
+ };
301
+ }
302
+
303
+ function renderNestedTodoGanttSvg(layout, options) {
304
+ let markup = renderFlatTodoGanttSvg(layout, options);
305
+ const base = svgDimensions(markup);
306
+ let width = base.width;
307
+ let height = base.height;
308
+ const panels = [];
309
+ const toggles = [];
310
+ const links = [];
311
+ const nodeByKey = new Map(layout.nodes.map((node) => [nodeKey(node.ref), node]));
312
+ let nextPanelY = 96;
313
+
314
+ for (const child of layout.hierarchy.children) {
315
+ const key = nodeKey(child.parent_ref);
316
+ const parent = nodeByKey.get(key);
317
+ if (parent?.geometry === null || parent === undefined) continue;
318
+ const childMarkup = renderTodoGanttSvg(childLayoutOf(child), options);
319
+ const childSize = svgDimensions(childMarkup);
320
+ // 開いた内部工程図を基底DAGの上へ重ねない。右側へ専用領域を確保し、親カードから
321
+ // 直交線で結ぶ。これなら後続taskも、同じ箱の兄弟taskも隠れない。
322
+ const panelX = base.width + 16;
323
+ const panelY = Math.max(parent.geometry.y + 96, nextPanelY);
324
+ const panelWidth = childSize.width + 24;
325
+ const panelHeight = childSize.height + 44;
326
+ nextPanelY = panelY + panelHeight + 16;
327
+ width = Math.max(width, panelX + panelWidth + 16);
328
+ height = Math.max(height, panelY + panelHeight + 16);
329
+ const embedded = childMarkup.replace('<svg class="todo-gantt"',
330
+ `<svg x="${panelX + 12}" y="${panelY + 32}" class="todo-gantt nested-task-diagram"`);
331
+ const label = `工程 ${child.parent_ref.plan_key}/${child.parent_ref.task_id} の内部工程`;
332
+ panels.push(`<g class="nested-task-panel" data-nested-panel-for="${escapeSvgAttribute(key)}" hidden aria-label="${escapeSvgAttribute(label)}"><rect class="nested-task-surface" x="${panelX}" y="${panelY}" width="${panelWidth}" height="${panelHeight}" rx="8"></rect><text class="nested-task-label" x="${panelX + 12}" y="${panelY + 22}">${escapeSvgText(label)}</text>${embedded}</g>`);
333
+ const parentX = parent.geometry.x + parent.geometry.width;
334
+ const parentY = parent.geometry.y + 96 + parent.geometry.height / 2;
335
+ const elbowX = panelX - 8;
336
+ links.push(`<path class="nested-task-link" data-nested-link-for="${escapeSvgAttribute(key)}" hidden d="M ${parentX} ${parentY} H ${elbowX} V ${panelY + 18} H ${panelX}"></path>`);
337
+ const toggleX = parent.geometry.x + parent.geometry.width - 24;
338
+ const toggleY = parent.geometry.y + 96 + parent.geometry.height - 18;
339
+ toggles.push(`<g class="nested-task-toggle" data-nested-toggle-for="${escapeSvgAttribute(key)}" tabindex="0" role="button" aria-expanded="false" aria-label="${escapeSvgAttribute(`${label}を開く`)}"><rect x="${toggleX - 8}" y="${toggleY - 13}" width="28" height="22" rx="4"></rect><text x="${toggleX + 6}" y="${toggleY + 3}" text-anchor="middle">+</text></g>`);
340
+ }
341
+
342
+ markup = resizeSvg(markup, width, height);
343
+ return markup.replace('</svg>', `<g class="nested-link-layer">${links.join('')}</g><g class="nested-panel-layer">${panels.join('')}</g><g class="nested-toggle-layer">${toggles.join('')}</g></svg>`);
344
+ }
345
+
346
+ export function renderTodoGanttSvg(layout, options = {}) {
347
+ if (layout?.hierarchy === undefined) return renderFlatTodoGanttSvg(layout, options);
348
+ if (layout.hierarchy?.schema !== 'lattice.todo_gantt_hierarchy.v1'
349
+ || !Array.isArray(layout.hierarchy.children)) {
350
+ throw new TypeError('layout hierarchy must be lattice.todo_gantt_hierarchy.v1');
351
+ }
352
+ return renderNestedTodoGanttSvg(layout, options);
353
+ }