@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,974 +1,974 @@
1
- import { TODO_GANTT_SCOPES, projectTodoGanttScope } from './todo-gantt-scope.mjs';
2
- import { buildTodoGanttHierarchy } from './todo-gantt-nested.mjs';
3
- import { projectTodoCrossPlanDependencies } from './todo-store.mjs';
4
-
5
- const TASK_LIMIT = 2_000;
6
- const EDGE_LIMIT = 8_000;
7
- const SWEEP_ROUNDS = 4;
8
-
9
- /** Columns for a stage made only of ToDos with no registered dependency. */
10
- const LOOSE_COLUMNS_MINIMUM = 8;
11
-
12
- const GEOMETRY = Object.freeze({
13
- left: 16,
14
- top: 16,
15
- wave_gap: 104,
16
- lane_gap: 296,
17
- node_width: 272,
18
- node_height: 68,
19
- stage_row_gap: 12,
20
- route_inset: 8,
21
- route_spacing: 12,
22
- });
23
-
24
- function segmentKind(left, right) {
25
- if (left[1] === right[1] && left[0] !== right[0]) return 'horizontal';
26
- if (left[0] === right[0] && left[1] !== right[1]) return 'vertical';
27
- return 'point';
28
- }
29
-
30
- function strictlyBetween(value, left, right) {
31
- return value > Math.min(left, right) && value < Math.max(left, right);
32
- }
33
-
34
- function addCrossingBridges(projectedEdges, logicalContacts = new Set()) {
35
- const horizontalByY = new Map();
36
- const verticals = [];
37
- for (const edge of projectedEdges) {
38
- for (let segment = 0; segment < edge.route.length - 1; segment += 1) {
39
- const start = edge.route[segment];
40
- const end = edge.route[segment + 1];
41
- const kind = segmentKind(start, end);
42
- if (kind === 'horizontal') {
43
- if (!horizontalByY.has(start[1])) horizontalByY.set(start[1], []);
44
- horizontalByY.get(start[1]).push({ edge, segment, start, end });
45
- } else if (kind === 'vertical') verticals.push({ edge, start, end });
46
- }
47
- }
48
- const yValues = [...horizontalByY.keys()].sort((left, right) => left - right);
49
- const firstGreater = (value) => {
50
- let low = 0; let high = yValues.length;
51
- while (low < high) {
52
- const middle = Math.floor((low + high) / 2);
53
- if (yValues[middle] <= value) low = middle + 1; else high = middle;
54
- }
55
- return low;
56
- };
57
- const firstAtLeast = (value) => {
58
- let low = 0; let high = yValues.length;
59
- while (low < high) {
60
- const middle = Math.floor((low + high) / 2);
61
- if (yValues[middle] < value) low = middle + 1; else high = middle;
62
- }
63
- return low;
64
- };
65
- for (const vertical of verticals) {
66
- const minimumY = Math.min(vertical.start[1], vertical.end[1]);
67
- const maximumY = Math.max(vertical.start[1], vertical.end[1]);
68
- for (let yIndex = firstGreater(minimumY); yIndex < firstAtLeast(maximumY); yIndex += 1) {
69
- const y = yValues[yIndex];
70
- for (const horizontal of horizontalByY.get(y)) {
71
- if (horizontal.edge === vertical.edge
72
- || !strictlyBetween(vertical.start[0], horizontal.start[0], horizontal.end[0])) continue;
73
- if (logicalContacts.has(`${vertical.start[0]},${y}`)) continue;
74
- horizontal.edge.bridges.push({
75
- segment_index: horizontal.segment, x: vertical.start[0], y,
76
- });
77
- }
78
- }
79
- }
80
- for (const edge of projectedEdges) {
81
- edge.bridges.sort((left, right) => left.segment_index - right.segment_index
82
- || (edge.route[left.segment_index][0] <= edge.route[left.segment_index + 1][0]
83
- ? left.x - right.x : right.x - left.x));
84
- }
85
- }
86
-
87
- export class TodoGanttLayoutError extends Error {
88
- constructor(code, message, detail = null) {
89
- super(message);
90
- this.name = 'TodoGanttLayoutError';
91
- this.code = code;
92
- this.detail = detail;
93
- }
94
- }
95
-
96
- function fail(code, message, detail) {
97
- throw new TodoGanttLayoutError(code, message, detail);
98
- }
99
-
100
- function plain(value) {
101
- return value !== null && typeof value === 'object' && !Array.isArray(value)
102
- && Object.getPrototypeOf(value) === Object.prototype;
103
- }
104
-
105
- function compareText(left, right) {
106
- return left < right ? -1 : left > right ? 1 : 0;
107
- }
108
-
109
- function refOf(value, context) {
110
- if (!plain(value) || typeof value.project_id !== 'string'
111
- || typeof value.plan_key !== 'string' || typeof value.task_id !== 'string') {
112
- fail('TODO_LAYOUT_INVALID_INPUT', `${context} must be a task ref`);
113
- }
114
- return { project_id: value.project_id, plan_key: value.plan_key, task_id: value.task_id };
115
- }
116
-
117
- function refKey(ref) {
118
- return JSON.stringify([ref.project_id, ref.plan_key, ref.task_id]);
119
- }
120
-
121
- function compareRefs(left, right) {
122
- return compareText(left.project_id, right.project_id)
123
- || compareText(left.plan_key, right.plan_key)
124
- || compareText(left.task_id, right.task_id);
125
- }
126
-
127
- function groupKey(planKey, lane) {
128
- return JSON.stringify([planKey, lane]);
129
- }
130
-
131
- function normalizeInput(readModel, chainProjection) {
132
- if (!plain(readModel) || readModel.schema !== 'lattice.todo_store_read.v1'
133
- || !Array.isArray(readModel.members)) {
134
- fail('TODO_LAYOUT_INVALID_INPUT', 'read model must be lattice.todo_store_read.v1');
135
- }
136
- if (!plain(chainProjection) || chainProjection.schema !== 'lattice.todo_chain.v1'
137
- || !Array.isArray(chainProjection.longest_chain_node_refs)
138
- || !Array.isArray(chainProjection.longest_chain_edges)) {
139
- fail('TODO_LAYOUT_INVALID_INPUT', 'chain projection must be lattice.todo_chain.v1');
140
- }
141
-
142
- const nodesByKey = new Map();
143
- const members = [...readModel.members].sort((left, right) => {
144
- const leftPlan = left?.plan;
145
- const rightPlan = right?.plan;
146
- return compareText(leftPlan?.project_id ?? '', rightPlan?.project_id ?? '')
147
- || compareText(leftPlan?.plan_key ?? '', rightPlan?.plan_key ?? '');
148
- });
149
- for (let memberIndex = 0; memberIndex < members.length; memberIndex += 1) {
150
- const member = members[memberIndex];
151
- if (!plain(member) || !plain(member.plan) || !Array.isArray(member.plan.tasks)
152
- || !Array.isArray(member.tasks) || !Array.isArray(member.plan.hard_dependencies)
153
- || !Array.isArray(member.plan.joins)) {
154
- fail('TODO_LAYOUT_INVALID_INPUT', `members[${memberIndex}] has an invalid read-model shape`);
155
- }
156
- const { plan } = member;
157
- const statusByTask = new Map(member.tasks.map((task) => [task.task_id, task]));
158
- // snapshot artifactの形式(v1にはphasesキーが無い)には縛られない導出ビューを読む
159
- // (readTodoStoreが常にmember.phasesとして埋める。ADR 0147)。
160
- const statusByPhase = new Map((member.phases ?? [])
161
- .map((phase) => [phase.phase_id, phase.status]));
162
- for (const task of plan.tasks) {
163
- if (!plain(task) || typeof task.task_id !== 'string' || typeof task.lane !== 'string') {
164
- fail('TODO_LAYOUT_INVALID_INPUT', 'plan task has an invalid shape');
165
- }
166
- const state = statusByTask.get(task.task_id);
167
- if (!plain(state) || !['pending', 'in-progress', 'blocked', 'done'].includes(state.status)) {
168
- fail('TODO_LAYOUT_INVALID_INPUT', `missing task state for ${task.task_id}`);
169
- }
170
- const ref = { project_id: plan.project_id, plan_key: plan.plan_key, task_id: task.task_id };
171
- const key = refKey(ref);
172
- if (nodesByKey.has(key)) fail('TODO_LAYOUT_INVALID_INPUT', `duplicate task: ${key}`);
173
- nodesByKey.set(key, {
174
- key,
175
- ref,
176
- title: typeof task.title === 'string' ? task.title : task.task_id,
177
- lane: task.lane,
178
- status: state.status,
179
- plan_schema: plan.schema ?? null,
180
- phase_id: task.phase_id ?? null,
181
- // ADR 0147: phase無しplan(task.phase_idが無い世代)も、終端に暗黙のterminal-audit
182
- // Phaseを1つ持つ(todo-store.mjsのphasesOf/TERMINAL_AUDIT_PHASE_ID)。ここで素通しせず
183
- // nullのままにすると、gantt scope側(todo-gantt-scope.mjs)が「監査未了のplanを畳まない」
184
- // 判定に使える材料を一切受け取れない。'terminal-audit'はTERMINAL_AUDIT_PHASE_IDと同じ
185
- // 予約IDで、phase_readyの判定(v4だけを見る既存分岐)には影響しない。
186
- phase_status: task.phase_id === undefined
187
- ? statusByPhase.get('terminal-audit') ?? null
188
- : statusByPhase.get(task.phase_id) ?? null,
189
- phase_ready: plan.schema !== 'lattice.todo_plan.v4'
190
- || statusByPhase.get(task.phase_id) === 'active',
191
- });
192
- }
193
- }
194
- if (nodesByKey.size > TASK_LIMIT) {
195
- fail('TODO_SCALE_EXCEEDED', 'todo gantt task limit exceeded', {
196
- task_count: nodesByKey.size, task_limit: TASK_LIMIT, edge_count: null, edge_limit: EDGE_LIMIT,
197
- });
198
- }
199
-
200
- const edgeMap = new Map();
201
- const addEdge = (fromValue, toValue, kind, joinIdentity = null) => {
202
- const fromRef = refOf(fromValue, 'edge.from');
203
- const toRef = refOf(toValue, 'edge.to');
204
- const from = refKey(fromRef);
205
- const to = refKey(toRef);
206
- if (!nodesByKey.has(from) || !nodesByKey.has(to) || from === to) {
207
- fail('TODO_LAYOUT_INVALID_INPUT', 'edge must connect two distinct read-model tasks');
208
- }
209
- const key = JSON.stringify([from, to]);
210
- let edge = edgeMap.get(key);
211
- if (edge === undefined) {
212
- edge = { key, from, to, kinds: new Set(), joinIdentities: new Map() };
213
- edgeMap.set(key, edge);
214
- }
215
- edge.kinds.add(kind);
216
- if (joinIdentity !== null) {
217
- const identityKey = JSON.stringify([
218
- joinIdentity.project_id, joinIdentity.plan_key, joinIdentity.join_id,
219
- ]);
220
- edge.joinIdentities.set(identityKey, joinIdentity);
221
- }
222
- };
223
- for (const member of members) {
224
- for (const edge of member.plan.hard_dependencies) addEdge(edge.from, edge.to, 'hard');
225
- for (const join of member.plan.joins) {
226
- if (!plain(join) || !Array.isArray(join.after) || typeof join.id !== 'string') {
227
- fail('TODO_LAYOUT_INVALID_INPUT', 'join has an invalid shape');
228
- }
229
- const identity = { project_id: member.plan.project_id, plan_key: member.plan.plan_key,
230
- join_id: join.id };
231
- for (const after of join.after) addEdge(after, join.before, 'join', identity);
232
- }
233
- }
234
- for (const dependency of projectTodoCrossPlanDependencies(members)) {
235
- addEdge(dependency.from, dependency.to, 'cross_plan');
236
- }
237
- if (edgeMap.size > EDGE_LIMIT) {
238
- fail('TODO_SCALE_EXCEEDED', 'todo gantt edge limit exceeded', {
239
- task_count: nodesByKey.size, task_limit: TASK_LIMIT,
240
- edge_count: edgeMap.size, edge_limit: EDGE_LIMIT,
241
- });
242
- }
243
-
244
- const nodes = [...nodesByKey.values()].sort((left, right) => compareRefs(left.ref, right.ref));
245
- const edges = [...edgeMap.values()].sort((left, right) => compareText(left.key, right.key));
246
- return { nodes, nodesByKey, edges };
247
- }
248
-
249
- function readyTaskKeys(readModel, nodes, nodesByKey, incoming) {
250
- const phaseStatuses = new Map();
251
- const phaseAcceptIncoming = new Map(nodes.map(({ key }) => [key, new Set()]));
252
- for (const member of readModel.members) {
253
- // snapshot artifactの形式には縛られない導出ビュー(member.phases)を読む(ADR 0147)。
254
- for (const phase of member.phases ?? []) {
255
- phaseStatuses.set(JSON.stringify([
256
- member.plan.project_id, member.plan.plan_key, phase.phase_id,
257
- ]), phase.status);
258
- }
259
- if (['lattice.todo_plan.v5', 'lattice.todo_plan.v7'].includes(member.plan.schema)) {
260
- for (const edge of member.plan.phase_accept_dependencies ?? []) {
261
- const target = refKey(refOf(edge.to, 'phase_accept_dependencies.to'));
262
- if (!nodesByKey.has(target)) {
263
- fail('TODO_LAYOUT_INVALID_INPUT', 'phase accept dependency targets an absent task');
264
- }
265
- phaseAcceptIncoming.get(target).add(JSON.stringify([
266
- edge.from.project_id, edge.from.plan_key, edge.from.phase_id,
267
- ]));
268
- }
269
- }
270
- }
271
- return new Set(nodes.filter((node) => node.status === 'pending' && node.phase_ready
272
- && incoming.get(node.key).every((predecessorKey) => {
273
- const predecessor = nodesByKey.get(predecessorKey);
274
- return predecessor.status === 'done'
275
- && (predecessor.plan_schema !== 'lattice.todo_plan.v4'
276
- || predecessor.phase_id === null
277
- || (predecessor.ref.plan_key === node.ref.plan_key
278
- && predecessor.phase_id === node.phase_id)
279
- || predecessor.phase_status === 'accepted');
280
- }) && [...phaseAcceptIncoming.get(node.key)]
281
- .every((phaseKey) => phaseStatuses.get(phaseKey) === 'accepted'))
282
- .map(({ key }) => key));
283
- }
284
-
285
- function assignWaves(nodes, nodesByKey, edges) {
286
- const incoming = new Map(nodes.map(({ key }) => [key, []]));
287
- const outgoing = new Map(nodes.map(({ key }) => [key, []]));
288
- const indegree = new Map(nodes.map(({ key }) => [key, 0]));
289
- for (const edge of edges) {
290
- incoming.get(edge.to).push(edge.from);
291
- outgoing.get(edge.from).push(edge.to);
292
- indegree.set(edge.to, indegree.get(edge.to) + 1);
293
- }
294
- for (const values of incoming.values()) values.sort(compareText);
295
- for (const values of outgoing.values()) values.sort(compareText);
296
- let ready = nodes.filter(({ key }) => indegree.get(key) === 0).map(({ key }) => key);
297
- ready.sort((left, right) => compareRefs(nodesByKey.get(left).ref, nodesByKey.get(right).ref));
298
- const wave = new Map(nodes.map(({ key }) => [key, 0]));
299
- let visited = 0;
300
- while (ready.length > 0) {
301
- const current = ready.shift();
302
- visited += 1;
303
- for (const next of outgoing.get(current)) {
304
- wave.set(next, Math.max(wave.get(next), wave.get(current) + 1));
305
- indegree.set(next, indegree.get(next) - 1);
306
- if (indegree.get(next) === 0) {
307
- ready.push(next);
308
- ready.sort((left, right) => compareRefs(nodesByKey.get(left).ref, nodesByKey.get(right).ref));
309
- }
310
- }
311
- }
312
- if (visited !== nodes.length) fail('TODO_LAYOUT_CYCLE', 'todo layout input contains a cycle');
313
- return { incoming, outgoing, wave };
314
- }
315
-
316
- function median(values) {
317
- if (values.length === 0) return null;
318
- values.sort((left, right) => left - right);
319
- const middle = Math.floor(values.length / 2);
320
- return values.length % 2 === 1 ? values[middle] : (values[middle - 1] + values[middle]) / 2;
321
- }
322
-
323
- function orderLayers(nodes, wave, incoming, outgoing) {
324
- const maximumWave = nodes.reduce((maximum, node) => Math.max(maximum, wave.get(node.key)), 0);
325
- const layers = Array.from({ length: maximumWave + 1 }, () => []);
326
- for (const node of nodes) layers[wave.get(node.key)].push(node.key);
327
- const nodeByKey = new Map(nodes.map((node) => [node.key, node]));
328
- const baseCompare = (leftKey, rightKey) => {
329
- const left = nodeByKey.get(leftKey);
330
- const right = nodeByKey.get(rightKey);
331
- return compareText(left.lane, right.lane)
332
- || compareText(left.ref.plan_key, right.ref.plan_key)
333
- || compareRefs(left.ref, right.ref);
334
- };
335
- for (const layer of layers) layer.sort(baseCompare);
336
-
337
- const reorder = (layerIndex, neighborMap) => {
338
- const layer = layers[layerIndex];
339
- const previousPosition = new Map(layer.map((key, index) => [key, index]));
340
- const allPositions = new Map();
341
- for (const otherLayer of layers) {
342
- for (let index = 0; index < otherLayer.length; index += 1) allPositions.set(otherLayer[index], index);
343
- }
344
- const score = new Map(layer.map((key) => [key, median(
345
- neighborMap.get(key).filter((neighbor) => allPositions.has(neighbor)).map((neighbor) => allPositions.get(neighbor)),
346
- )]));
347
- layer.sort((leftKey, rightKey) => {
348
- const left = nodeByKey.get(leftKey);
349
- const right = nodeByKey.get(rightKey);
350
- const groupOrder = compareText(left.lane, right.lane)
351
- || compareText(left.ref.plan_key, right.ref.plan_key);
352
- if (groupOrder !== 0) return groupOrder;
353
- const leftScore = score.get(leftKey);
354
- const rightScore = score.get(rightKey);
355
- if (leftScore !== null && rightScore !== null && leftScore !== rightScore) return leftScore - rightScore;
356
- if (leftScore === null && rightScore !== null) return 1;
357
- if (leftScore !== null && rightScore === null) return -1;
358
- return previousPosition.get(leftKey) - previousPosition.get(rightKey) || baseCompare(leftKey, rightKey);
359
- });
360
- };
361
-
362
- for (let round = 0; round < SWEEP_ROUNDS; round += 1) {
363
- for (let layer = 1; layer < layers.length; layer += 1) reorder(layer, incoming);
364
- for (let layer = layers.length - 2; layer >= 0; layer -= 1) reorder(layer, outgoing);
365
- }
366
- return layers;
367
- }
368
-
369
- function crossingCount(edges, wave, transversePosition) {
370
- const groups = new Map();
371
- for (const edge of edges) {
372
- const pair = `${wave.get(edge.from)}\0${wave.get(edge.to)}`;
373
- if (!groups.has(pair)) groups.set(pair, []);
374
- groups.get(pair).push([transversePosition.get(edge.from), transversePosition.get(edge.to)]);
375
- }
376
- let total = 0;
377
- for (const group of groups.values()) {
378
- group.sort((left, right) => left[0] - right[0] || left[1] - right[1]);
379
- const targets = [...new Set(group.map((entry) => entry[1]))].sort((left, right) => left - right);
380
- const rank = new Map(targets.map((value, index) => [value, index + 1]));
381
- const tree = new Uint32Array(targets.length + 1);
382
- let seen = 0;
383
- for (const [, target] of group) {
384
- let prefix = 0;
385
- for (let index = rank.get(target); index > 0; index -= index & -index) prefix += tree[index];
386
- total += seen - prefix;
387
- for (let index = rank.get(target); index < tree.length; index += index & -index) tree[index] += 1;
388
- seen += 1;
389
- }
390
- }
391
- return total;
392
- }
393
-
394
- /**
395
- * plan別の独立性投影を、task refで引ける索引と図の外が語る要約へ畳む(ADR 0129 Decision 4)。
396
- *
397
- * 読み出しはasync I/Oとgit実行を伴うためCLI層が行い、ここへは値として渡る。
398
- * layoutは同期pureのままに保つ。
399
- */
400
- function normalizeIndependence(value, nodesByKey) {
401
- if (value === null || value === undefined) return { stateByKey: new Map(), summary: null };
402
- if (!Array.isArray(value)) {
403
- fail('TODO_LAYOUT_INVALID_INPUT', 'independence must be an array of plan projections');
404
- }
405
- const stateByKey = new Map();
406
- const plans = [];
407
- for (const projection of value) {
408
- if (!plain(projection) || typeof projection.plan_key !== 'string'
409
- || typeof projection.coverage !== 'string' || !plain(projection.frontier)) {
410
- fail('TODO_LAYOUT_INVALID_INPUT', 'independence entry must carry plan_key, coverage and frontier');
411
- }
412
- const { plan_key: planKey, frontier } = projection;
413
- const mark = (taskId, state) => {
414
- const key = refKey({
415
- project_id: projection.project_id, plan_key: planKey, task_id: taskId,
416
- });
417
- // 図に無いtaskへ状態を付けない。layoutのready判定と投影のready判定が食い違えば、
418
- // 静かに無視するのでなくここで露見させる。
419
- if (!nodesByKey.has(key)) {
420
- fail('TODO_LAYOUT_INDEPENDENCE_DRIFT', 'independence references a task absent from layout', {
421
- plan_key: planKey, task_id: taskId,
422
- });
423
- }
424
- stateByKey.set(key, state);
425
- };
426
- for (const group of frontier.parallel_groups ?? []) {
427
- for (const taskId of group.task_ids) mark(taskId, 'verified');
428
- }
429
- for (const pair of frontier.serialize_pairs ?? []) {
430
- for (const taskId of pair.task_ids) mark(taskId, 'conflict');
431
- }
432
- for (const entry of frontier.conflicts_with_active ?? []) mark(entry.ready_task_id, 'conflict');
433
- for (const entry of frontier.unknown ?? []) mark(entry.task_id, 'unknown');
434
- plans.push({
435
- plan_key: planKey,
436
- coverage: projection.coverage,
437
- verified_group_count: (frontier.parallel_groups ?? []).length,
438
- verified_task_count: (frontier.parallel_groups ?? [])
439
- .reduce((total, group) => total + group.task_ids.length, 0),
440
- serialize_pairs: (frontier.serialize_pairs ?? []).map((pair) => ({
441
- task_ids: [...pair.task_ids], type: pair.type, detail: pair.detail,
442
- kind: pair.kind ?? null, severability: pair.severability ?? 'serial',
443
- })),
444
- conflicts_with_active: (frontier.conflicts_with_active ?? []).map((entry) => ({
445
- ready_task_id: entry.ready_task_id, active_task_id: entry.active_task_id,
446
- type: entry.type, detail: entry.detail,
447
- kind: entry.kind ?? null, severability: entry.severability ?? 'serial',
448
- })),
449
- unknown_task_ids: (frontier.unknown ?? []).map(({ task_id: taskId }) => taskId).sort(compareText),
450
- });
451
- }
452
- plans.sort((left, right) => compareText(left.plan_key, right.plan_key));
453
- return { stateByKey, summary: { plans } };
454
- }
455
-
456
- /**
457
- * seam proposalの公開投影を、描画に必要なhuman-facing fieldだけへ畳む。
458
- * resource_idは記録のidentityであって表示名ではないため、layoutへ持ち込まない。
459
- */
460
- function normalizeSeamProposals(value) {
461
- if (value === null || value === undefined) return { summary: null };
462
- if (!Array.isArray(value)) {
463
- fail('TODO_LAYOUT_INVALID_INPUT', 'seamProposals must be an array of plan projections');
464
- }
465
- const plans = value.map((projection) => {
466
- if (!plain(projection) || typeof projection.project_id !== 'string'
467
- || typeof projection.plan_key !== 'string'
468
- || !['missing', 'superseded', 'stale', 'verified'].includes(projection.coverage)
469
- || !plain(projection.guidance)
470
- || typeof projection.guidance.code !== 'string'
471
- || typeof projection.guidance.message !== 'string'
472
- || typeof projection.guidance.next_action !== 'string'
473
- || !Array.isArray(projection.components)) {
474
- fail('TODO_LAYOUT_INVALID_INPUT', 'seam proposal entry has an invalid projection shape');
475
- }
476
- return {
477
- project_id: projection.project_id,
478
- plan_key: projection.plan_key,
479
- coverage: projection.coverage,
480
- guidance: { ...projection.guidance },
481
- component_count: projection.component_count,
482
- conflict_resource_count: projection.conflict_resource_count,
483
- components: projection.components.map((component) => {
484
- if (!plain(component) || typeof component.component_id !== 'string'
485
- || typeof component.verdict !== 'string'
486
- || !Array.isArray(component.task_ids)
487
- || !Array.isArray(component.conflicts)
488
- || !Array.isArray(component.proposed_surfaces)
489
- || !Array.isArray(component.affected_tests)
490
- || !Array.isArray(component.limits)
491
- || !Array.isArray(component.reasons)
492
- || !Array.isArray(component.unknowns)) {
493
- fail('TODO_LAYOUT_INVALID_INPUT', 'seam proposal component has an invalid shape');
494
- }
495
- return {
496
- component_id: component.component_id,
497
- verdict: component.verdict,
498
- task_ids: [...component.task_ids],
499
- conflicts: component.conflicts.map((conflict) => {
500
- if (!plain(conflict) || typeof conflict.kind !== 'string'
501
- || typeof conflict.target !== 'string' || !Array.isArray(conflict.task_pairs)) {
502
- fail('TODO_LAYOUT_INVALID_INPUT', 'seam proposal conflict has an invalid shape');
503
- }
504
- return {
505
- kind: conflict.kind,
506
- target: conflict.target,
507
- task_pairs: conflict.task_pairs.map((pair) => [...pair]),
508
- };
509
- }),
510
- proposed_surfaces: component.proposed_surfaces.map((surface) => ({ ...surface,
511
- owner_task_ids: [...surface.owner_task_ids] })),
512
- affected_tests: [...component.affected_tests],
513
- limits: [...component.limits],
514
- reasons: component.reasons.map((reason) => ({ ...reason })),
515
- unknowns: component.unknowns.map((unknown) => ({ ...unknown })),
516
- };
517
- }),
518
- };
519
- });
520
- plans.sort((left, right) => {
521
- const leftHasDecisions = left.components.length > 0;
522
- const rightHasDecisions = right.components.length > 0;
523
- return leftHasDecisions === rightHasDecisions
524
- ? compareText(left.plan_key, right.plan_key) : leftHasDecisions ? -1 : 1;
525
- });
526
- return { summary: { plans } };
527
- }
528
-
529
- function layoutTodoGanttFlat(readModel, chainProjection, options = {}) {
530
- const scope = options.scope ?? 'live';
531
- if (!TODO_GANTT_SCOPES.includes(scope)) {
532
- fail('TODO_LAYOUT_INVALID_INPUT', `scope must be one of ${TODO_GANTT_SCOPES.join(', ')}`);
533
- }
534
-
535
- // Every structural number below is measured on the FULL graph: the dependency
536
- // waves, the longest dependency chain and the ready frontier describe the real
537
- // plan. Folding first and measuring second would make all three lie.
538
- const full = normalizeInput(readModel, chainProjection);
539
- const fullWaves = assignWaves(full.nodes, full.nodesByKey, full.edges);
540
-
541
- const longestNodeKeys = new Set(chainProjection.longest_chain_node_refs.map((ref, index) => {
542
- const key = refKey(refOf(ref, `longest_chain_node_refs[${index}]`));
543
- if (!full.nodesByKey.has(key)) fail('TODO_LAYOUT_INVALID_INPUT', 'chain projection references an absent task');
544
- return key;
545
- }));
546
- const longestEdgeKeys = new Set(chainProjection.longest_chain_edges.map((edge, index) => {
547
- if (!plain(edge)) fail('TODO_LAYOUT_INVALID_INPUT', `longest_chain_edges[${index}] is invalid`);
548
- const from = refKey(refOf(edge.from, `longest_chain_edges[${index}].from`));
549
- const to = refKey(refOf(edge.to, `longest_chain_edges[${index}].to`));
550
- const key = JSON.stringify([from, to]);
551
- if (!full.edges.some((candidate) => candidate.key === key)) {
552
- fail('TODO_LAYOUT_INVALID_INPUT', 'chain projection edge is absent from the read model');
553
- }
554
- return key;
555
- }));
556
- const readyKeys = readyTaskKeys(readModel, full.nodes, full.nodesByKey, fullWaves.incoming);
557
- const independence = normalizeIndependence(options.independence ?? null, full.nodesByKey);
558
- const seamProposals = normalizeSeamProposals(options.seamProposals ?? null);
559
-
560
- // Only the geometry stage below sees the narrowed graph.
561
- const projected = scope === 'all'
562
- ? { nodes: full.nodes, edges: full.edges, foldedKeys: new Set() }
563
- : projectTodoGanttScope({ nodes: full.nodes, edges: full.edges, wave: fullWaves.wave });
564
- const nodes = projected.nodes;
565
- const edges = projected.edges;
566
- const nodesByKey = new Map(nodes.map((node) => [node.key, node]));
567
- const { incoming, outgoing, wave } = assignWaves(nodes, nodesByKey, edges);
568
- const layers = orderLayers(nodes, wave, incoming, outgoing);
569
- // A ToDo with no registered dependency has nothing to line up with. Laying
570
- // every one of them out in a single row makes the canvas as wide as the plan
571
- // is old — real stores have hundreds — so they wrap into a block of rows.
572
- //
573
- // That block goes ABOVE the wired ToDos of its stage. Below them it used to be
574
- // pierced: a wired card's port descends from its own bottom edge to the routing
575
- // band under the whole stage, straight through whatever independent card had
576
- // wrapped into the same column, and the hidden half of that line read as a
577
- // dependency the plan does not have. Independent ToDos carry no edge, so they
578
- // have no incoming one either and always land in stage 0, which nothing ever
579
- // arrives into — putting them on top leaves no line to cross them.
580
- const wired = new Set();
581
- for (const edge of edges) { wired.add(edge.from); wired.add(edge.to); }
582
- const transversePosition = new Map();
583
- const stageRow = new Map();
584
- const stageRowCount = [];
585
- for (const layer of layers) {
586
- const connected = layer.filter((key) => wired.has(key));
587
- const loose = layer.filter((key) => !wired.has(key));
588
- const columns = Math.max(LOOSE_COLUMNS_MINIMUM, connected.length);
589
- const looseRows = loose.length === 0 ? 0 : Math.ceil(loose.length / columns);
590
- loose.forEach((key, index) => {
591
- transversePosition.set(key, index % columns);
592
- stageRow.set(key, Math.floor(index / columns));
593
- });
594
- connected.forEach((key, index) => {
595
- transversePosition.set(key, index);
596
- stageRow.set(key, looseRows);
597
- });
598
- stageRowCount.push(Math.max(0, ...layer.map((key) => stageRow.get(key))) + 1);
599
- }
600
- const maximumLayerWidth = Math.max(1,
601
- ...[...transversePosition.values()].map((position) => position + 1));
602
- const visibleKeys = new Set(nodes.map(({ key }) => key));
603
- const displayBranches = edges.flatMap((edge, semanticIndex) => {
604
- const identities = [...edge.joinIdentities.entries()]
605
- .sort(([left], [right]) => compareText(left, right)).map(([, identity]) => identity);
606
- const variants = identities.length === 0 ? [null] : identities;
607
- return variants.map((joinIdentity, branchIndex) => ({
608
- key: JSON.stringify([edge.key, joinIdentity]), edge, semanticIndex, branchIndex, joinIdentity,
609
- }));
610
- });
611
-
612
- const gapGroups = new Map();
613
- const portGroups = new Map();
614
- const portGroupKey = (gap, row) => `${gap}\0${row}`;
615
- const portEntryKey = (edgeKey, direction) => `${edgeKey}\0${direction}`;
616
- const addPort = (gap, row, entry) => {
617
- const key = portGroupKey(gap, row);
618
- if (!portGroups.has(key)) portGroups.set(key, []);
619
- portGroups.get(key).push(entry);
620
- };
621
- // 隣の段の真下へ繋ぐ辺は、出発と到着が同じ取り付け位置の集合を奪い合う。別々の
622
- // 枠を取ると2本の縦線が12pxずれて短い横棒で継がれ、まっすぐ引ける線が段差付きに
623
- // 見える。両端の縦線は帯の中で1点で接するだけなので、1枠を共有させて直線にする。
624
- const sharedPort = new Set();
625
- displayBranches.forEach((branch) => {
626
- const { edge } = branch;
627
- for (const gap of new Set([wave.get(edge.from), wave.get(edge.to) - 1])) {
628
- if (!gapGroups.has(gap)) gapGroups.set(gap, []);
629
- gapGroups.get(gap).push(branch.key);
630
- }
631
- const departureGap = wave.get(edge.from);
632
- const fromColumn = transversePosition.get(edge.from);
633
- const toColumn = transversePosition.get(edge.to);
634
- if (departureGap === wave.get(edge.to) - 1 && fromColumn === toColumn) {
635
- sharedPort.add(branch.key);
636
- addPort(departureGap, fromColumn, portEntryKey(branch.key, 'through'));
637
- return;
638
- }
639
- addPort(departureGap, fromColumn, portEntryKey(branch.key, 'departure'));
640
- addPort(wave.get(edge.to) - 1, toColumn, portEntryKey(branch.key, 'arrival'));
641
- });
642
- for (const keys of gapGroups.values()) keys.sort(compareText);
643
- for (const entries of portGroups.values()) entries.sort(compareText);
644
- const maximumPortTraffic = Math.max(0, ...[...portGroups.values()].map(({ length }) => length));
645
- const connectorGroupKeysByGap = new Map();
646
- for (const branch of displayBranches) {
647
- if (branch.joinIdentity === null) continue;
648
- const targetGap = wave.get(branch.edge.to) - 1;
649
- if (!connectorGroupKeysByGap.has(targetGap)) connectorGroupKeysByGap.set(targetGap, new Set());
650
- connectorGroupKeysByGap.get(targetGap).add(JSON.stringify([branch.edge.to, branch.joinIdentity]));
651
- }
652
- const allGapIndexes = new Set([...gapGroups.keys(), ...connectorGroupKeysByGap.keys()]);
653
- const maximumGapOccupancy = Math.max(0, ...[...allGapIndexes].map((gap) =>
654
- (gapGroups.get(gap)?.length ?? 0) + (connectorGroupKeysByGap.get(gap)?.size ?? 0)));
655
- // An edge that skips a stage has to travel vertically past the stages in
656
- // between. It used to do that in a corridor beyond the right edge of the
657
- // whole diagram, so a local hop between two neighbouring cards was drawn as a
658
- // trip to the far right and back. It now descends through the vertical
659
- // channel between two columns of cards, chosen from the boundaries that lie
660
- // between its endpoints. Every card sits on the same column grid, so those
661
- // gaps are free of cards at every stage: routing inside one is both shorter
662
- // to follow and structurally unable to cross a card.
663
- const channelLoad = new Map();
664
- const channelAssignment = new Map();
665
- const channelTraffic = (boundary) => channelLoad.get(boundary) ?? 0;
666
- for (const branch of [...displayBranches].sort((left, right) => compareText(left.key, right.key))) {
667
- const { edge } = branch;
668
- if (wave.get(edge.from) === wave.get(edge.to) - 1) continue;
669
- const fromColumn = transversePosition.get(edge.from);
670
- const toColumn = transversePosition.get(edge.to);
671
- const [first, last] = fromColumn === toColumn
672
- ? [toColumn, toColumn + 1]
673
- : [Math.min(fromColumn, toColumn) + 1, Math.max(fromColumn, toColumn)];
674
- let chosen = first;
675
- for (let boundary = first + 1; boundary <= last; boundary += 1) {
676
- const closer = Math.abs(boundary - toColumn) < Math.abs(chosen - toColumn);
677
- if (channelTraffic(boundary) < channelTraffic(chosen)
678
- || (channelTraffic(boundary) === channelTraffic(chosen) && closer)) chosen = boundary;
679
- }
680
- channelAssignment.set(branch.key, { boundary: chosen, lane: channelTraffic(chosen) });
681
- channelLoad.set(chosen, channelTraffic(chosen) + 1);
682
- }
683
-
684
- const nodeWidth = Math.max(GEOMETRY.node_width,
685
- GEOMETRY.route_inset * 2 + (maximumPortTraffic + 1) * GEOMETRY.route_spacing);
686
- // Only the boundaries that actually carry channels pay for them. Boundary 0
687
- // is the margin left of the first column and only exists when something
688
- // routes there, so an untravelled diagram keeps its original left edge.
689
- const channelWidth = (boundary) => Math.max(24,
690
- (channelTraffic(boundary) + 1) * GEOMETRY.route_spacing);
691
- const columnLeft = [GEOMETRY.left + (channelTraffic(0) === 0 ? 0 : channelWidth(0))];
692
- for (let column = 1; column < maximumLayerWidth; column += 1) {
693
- columnLeft.push(columnLeft[column - 1] + nodeWidth + channelWidth(column));
694
- }
695
- const channelPosition = (edgeKey) => {
696
- const { boundary, lane } = channelAssignment.get(edgeKey);
697
- const left = boundary === 0 ? GEOMETRY.left : columnLeft[boundary - 1] + nodeWidth;
698
- return left + GEOMETRY.route_spacing * (lane + 1);
699
- };
700
- // Each routing band is sized for the edges that actually cross it. One
701
- // crowded band used to set the spacing for every stage in the diagram, so a
702
- // long plan paid the width of its busiest junction on all of its stages.
703
- const gapBand = (gap) => Math.max(36, ((gapGroups.get(gap)?.length ?? 0)
704
- + (connectorGroupKeysByGap.get(gap)?.size ?? 0) + 1) * GEOMETRY.route_spacing);
705
- const stageHeight = (index) => stageRowCount[index] * GEOMETRY.node_height
706
- + (stageRowCount[index] - 1) * GEOMETRY.stage_row_gap;
707
- const stageTop = [GEOMETRY.top];
708
- for (let index = 0; index + 1 < layers.length; index += 1) {
709
- stageTop.push(stageTop[index] + stageHeight(index) + gapBand(index));
710
- }
711
-
712
- const coordinates = new Map();
713
- const projectedNodes = nodes.map((node) => {
714
- const visible = visibleKeys.has(node.key);
715
- const geometry = visible ? {
716
- x: columnLeft[transversePosition.get(node.key)],
717
- y: stageTop[wave.get(node.key)]
718
- + stageRow.get(node.key) * (GEOMETRY.node_height + GEOMETRY.stage_row_gap),
719
- width: nodeWidth,
720
- height: GEOMETRY.node_height,
721
- } : null;
722
- if (geometry !== null) coordinates.set(node.key, geometry);
723
- return {
724
- ref: { ...node.ref }, title: node.title, lane: node.lane, status: node.status,
725
- wave: wave.get(node.key), row: transversePosition.get(node.key), visible,
726
- visibility: {
727
- longest_dependency_chain: longestNodeKeys.has(node.key),
728
- active: node.status === 'in-progress', next_ready: readyKeys.has(node.key),
729
- selected: false,
730
- // 記録が語らないtaskはnull。「独立と分かっている」と「まだ何も言えない」を
731
- // 図の上でも同じ顔にしない(ADR 0129 Decision 1)。
732
- independence: independence.stateByKey.get(node.key) ?? null,
733
- },
734
- geometry,
735
- };
736
- });
737
-
738
- const gapPosition = (edgeKey, waveIndex) => {
739
- const keys = gapGroups.get(waveIndex);
740
- const index = keys.indexOf(edgeKey);
741
- return stageTop[waveIndex] + stageHeight(waveIndex)
742
- + GEOMETRY.route_spacing * (index + 1);
743
- };
744
- const branchCounts = new Map();
745
- for (const branch of displayBranches) {
746
- branchCounts.set(branch.semanticIndex, (branchCounts.get(branch.semanticIndex) ?? 0) + 1);
747
- }
748
- const portPosition = (edgeKey, direction, gap, row, nodeX) => {
749
- const entries = portGroups.get(portGroupKey(gap, row));
750
- const entry = portEntryKey(edgeKey, sharedPort.has(edgeKey) ? 'through' : direction);
751
- return nodeX + GEOMETRY.route_inset
752
- + GEOMETRY.route_spacing * (entries.indexOf(entry) + 1);
753
- };
754
-
755
- const projectedEdges = displayBranches.map((branch) => {
756
- const { edge } = branch;
757
- const onLongestChain = longestEdgeKeys.has(edge.key);
758
- const from = coordinates.get(edge.from);
759
- const to = coordinates.get(edge.to);
760
- const departureGap = wave.get(edge.from);
761
- const arrivalGap = wave.get(edge.to) - 1;
762
- const startX = portPosition(branch.key, 'departure', departureGap,
763
- transversePosition.get(edge.from), from.x);
764
- const startY = from.y + from.height;
765
- const endX = portPosition(branch.key, 'arrival', arrivalGap,
766
- transversePosition.get(edge.to), to.x);
767
- const endY = to.y;
768
- const departureY = gapPosition(branch.key, departureGap);
769
- const arrivalY = gapPosition(branch.key, arrivalGap);
770
- const corners = [[startX, startY], [startX, departureY]];
771
- if (departureGap === arrivalGap) corners.push([endX, arrivalY]);
772
- else {
773
- const channelX = channelPosition(branch.key);
774
- corners.push([channelX, departureY], [channelX, arrivalY], [endX, arrivalY]);
775
- }
776
- corners.push([endX, endY]);
777
- // 1枠を共有する直線では折れ点が重なる。長さゼロの区間を残すと交差判定にも
778
- // 描画にも意味のない点が混ざるので畳む。
779
- const route = corners.filter(([x, y], index) =>
780
- index === 0 || x !== corners[index - 1][0] || y !== corners[index - 1][1]);
781
- return {
782
- id: branchCounts.get(branch.semanticIndex) === 1
783
- ? `edge-${branch.semanticIndex}` : `edge-${branch.semanticIndex}-join-${branch.branchIndex}`,
784
- semantic_edge_id: `edge-${branch.semanticIndex}`,
785
- from: { ...nodesByKey.get(edge.from).ref }, to: { ...nodesByKey.get(edge.to).ref },
786
- kinds: [...edge.kinds].sort(compareText),
787
- join_ids: branch.joinIdentity === null ? [] : [branch.joinIdentity.join_id],
788
- join_owners: branch.joinIdentity === null ? [] : [{ ...branch.joinIdentity }],
789
- visible: true, visibility: { longest_dependency_chain: onLongestChain, selected_incident: false },
790
- route, bridges: [], junction: null,
791
- };
792
- });
793
- const joinGroups = new Map();
794
- for (const edge of projectedEdges) {
795
- if (edge.join_ids.length === 0) continue;
796
- const key = JSON.stringify([edge.to, edge.join_owners[0]]);
797
- if (!joinGroups.has(key)) joinGroups.set(key, []);
798
- joinGroups.get(key).push(edge);
799
- }
800
- const junctionConnectors = [];
801
- const logicalContacts = new Set();
802
- const connectorGapRanks = new Map();
803
- for (const [, group] of [...joinGroups.entries()].sort(([left], [right]) => compareText(left, right))) {
804
- group.sort((left, right) => compareText(left.id, right.id));
805
- const target = coordinates.get(refKey(group[0].to));
806
- const targetGap = wave.get(refKey(group[0].to)) - 1;
807
- const groupRank = connectorGapRanks.get(targetGap) ?? 0;
808
- connectorGapRanks.set(targetGap, groupRank + 1);
809
- const primaryTargetPortX = group[0].route.at(-1)[0];
810
- const junction = [primaryTargetPortX,
811
- stageTop[targetGap] + stageHeight(targetGap)
812
- + GEOMETRY.route_spacing * ((gapGroups.get(targetGap)?.length ?? 0) + groupRank + 1)];
813
- const contacts = [];
814
- for (const [index, edge] of group.entries()) {
815
- edge.route.pop();
816
- const contact = [edge.route.at(-1)[0], junction[1]];
817
- if (edge.route.at(-1)[1] !== contact[1]) edge.route.push(contact);
818
- contacts.push(contact);
819
- logicalContacts.add(`${contact[0]},${contact[1]}`);
820
- if (index === 0) {
821
- edge.route.push([junction[0], target.y]);
822
- edge.junction = junction;
823
- }
824
- }
825
- const contactXs = contacts.map(([x]) => x);
826
- if (Math.min(...contactXs) !== Math.max(...contactXs)) {
827
- junctionConnectors.push({
828
- id: `join-connector-${junctionConnectors.length}`,
829
- join_ids: [...group[0].join_ids], join_owners: group[0].join_owners.map((owner) => ({ ...owner })),
830
- route: [[Math.min(...contactXs), junction[1]], [Math.max(...contactXs), junction[1]]],
831
- bridges: [], contacts,
832
- });
833
- }
834
- }
835
- addCrossingBridges([...projectedEdges, ...junctionConnectors], logicalContacts);
836
- let routeMaximumX = nodes.length === 0 ? 0
837
- : columnLeft[maximumLayerWidth - 1] + nodeWidth;
838
- for (const edge of projectedEdges) {
839
- for (const [x] of edge.route) routeMaximumX = Math.max(routeMaximumX, x);
840
- }
841
- for (const connector of junctionConnectors) {
842
- for (const [x] of connector.route) routeMaximumX = Math.max(routeMaximumX, x);
843
- }
844
-
845
- // Counts stay honest: the summary chips report every ToDo in the plan, not
846
- // only the ones the narrowed diagram happens to draw.
847
- const planMap = new Map();
848
- const laneMap = new Map();
849
- for (const node of full.nodes) {
850
- if (!planMap.has(node.ref.plan_key)) planMap.set(node.ref.plan_key, 0);
851
- planMap.set(node.ref.plan_key, planMap.get(node.ref.plan_key) + 1);
852
- const key = groupKey(node.ref.plan_key, node.lane);
853
- if (!laneMap.has(key)) laneMap.set(key, { plan_key: node.ref.plan_key, lane: node.lane, task_count: 0 });
854
- laneMap.get(key).task_count += 1;
855
- }
856
- return {
857
- schema: 'lattice.todo_gantt_layout.v2',
858
- assumptions: { logical_time: 'dependency_wave', duration_estimation: false, lane_is_presentation_only: true },
859
- sweep: { method: 'stable_median', rounds: SWEEP_ROUNDS, tie_break: 'previous_position_then_task_ref' },
860
- bounds: {
861
- width: nodes.length === 0 ? 0 : routeMaximumX + GEOMETRY.left,
862
- height: nodes.length === 0 ? 0
863
- : GEOMETRY.top + stageTop.at(-1) + stageHeight(layers.length - 1),
864
- wave_count: layers.length,
865
- },
866
- nodes: projectedNodes,
867
- // 図の外が語るための投影。カードはバッジで状態だけを示し、相手と理由は右ペインが持つ。
868
- independence: independence.summary,
869
- // seam提案は図形を増やさず、右ペインで係争資源・ToDo組・判定・不足証拠をまとめて示す。
870
- seam_proposals: seamProposals.summary,
871
- edges: projectedEdges,
872
- // Every dependency in the plan, before folding contracted any of them away.
873
- // The diagram draws `edges`; anything that describes a ToDo in words — the
874
- // premises and successors in the right pane — reads this instead, so a
875
- // folded ToDo keeps telling the truth about what it depended on.
876
- full_edges: full.edges.map((edge) => ({
877
- from: { ...full.nodesByKey.get(edge.from).ref },
878
- to: { ...full.nodesByKey.get(edge.to).ref },
879
- kinds: [...edge.kinds].sort(compareText),
880
- join_ids: [...edge.joinIdentities.values()].map(({ join_id }) => join_id).sort(compareText),
881
- })),
882
- connectors: junctionConnectors,
883
- groups: {
884
- plans: [...planMap.entries()].map(([plan_key, task_count]) => ({ plan_key, task_count })),
885
- lanes: [...laneMap.values()],
886
- },
887
- scope: {
888
- requested: scope,
889
- folded_task_count: projected.foldedKeys.size,
890
- },
891
- // The ToDos the diagram no longer draws. They stay in the task index and in
892
- // every count, so the reader can still reach them by name.
893
- folded: [...projected.foldedKeys]
894
- .map((taskKey) => JSON.parse(taskKey))
895
- .map(([project_id, plan_key, task_id]) => ({ project_id, plan_key, task_id }))
896
- .sort(compareRefs),
897
- metrics: {
898
- crossing_count: crossingCount(edges, wave, transversePosition),
899
- visible_node_count: visibleKeys.size,
900
- visible_edge_count: projectedEdges.filter(({ visible }) => visible).length,
901
- task_count: full.nodes.length,
902
- edge_count: full.edges.length,
903
- },
904
- };
905
- }
906
-
907
- function applyHierarchySemantics(level, semanticByKey) {
908
- const layout = {
909
- ...level.layout,
910
- nodes: level.layout.nodes.map((node) => {
911
- const semantic = semanticByKey.get(refKey(node.ref));
912
- return semantic === undefined ? node : { ...node, visibility: { ...semantic.visibility } };
913
- }),
914
- };
915
- return {
916
- layout,
917
- children: level.children.map((child) => ({
918
- ...child,
919
- level: applyHierarchySemantics(child.level, semanticByKey),
920
- })),
921
- };
922
- }
923
-
924
- function descendantNodes(level) {
925
- return level.children.flatMap((child) => [
926
- ...child.level.layout.nodes,
927
- ...descendantNodes(child.level),
928
- ]);
929
- }
930
-
931
- export function layoutTodoGantt(readModel, chainProjection, options = {}) {
932
- const fullLayout = layoutTodoGanttFlat(readModel, chainProjection, options);
933
- let nested;
934
- try {
935
- const visibleTaskKeys = (options.scope ?? 'live') === 'all' ? null
936
- : new Set(fullLayout.nodes.map((node) => refKey(node.ref)));
937
- nested = buildTodoGanttHierarchy(
938
- readModel, options, layoutTodoGanttFlat, visibleTaskKeys,
939
- );
940
- } catch (error) {
941
- if (error?.code !== 'TODO_LAYOUT_INVALID_HIERARCHY') throw error;
942
- fail(error.code, error.message, error.detail);
943
- }
944
- if (nested === null) return fullLayout;
945
-
946
- // 階層ごとの縮約graphは座標だけを決める。ready/最長鎖/独立性まで縮約graphで
947
- // 再計算すると、未完の子を持つdone親が後続をreadyへ進めるなど、実graphと違う判断を描く。
948
- const semanticLayout = options.scope === 'all'
949
- ? fullLayout : layoutTodoGanttFlat(readModel, chainProjection, { ...options, scope: 'all' });
950
- const semanticByKey = new Map(semanticLayout.nodes.map((node) => [refKey(node.ref), node]));
951
- const semanticRoot = applyHierarchySemantics(nested.root, semanticByKey);
952
- const rootLayout = semanticRoot.layout;
953
- return {
954
- ...rootLayout,
955
- full_edges: fullLayout.full_edges,
956
- groups: fullLayout.groups,
957
- scope: fullLayout.scope,
958
- folded: fullLayout.folded,
959
- hierarchy_nodes: descendantNodes(semanticRoot),
960
- metrics: {
961
- ...rootLayout.metrics,
962
- visible_node_count: nested.metrics.visibleNodeCount,
963
- visible_edge_count: nested.metrics.visibleEdgeCount,
964
- task_count: fullLayout.metrics.task_count,
965
- edge_count: fullLayout.metrics.edge_count,
966
- },
967
- hierarchy: {
968
- schema: 'lattice.todo_gantt_hierarchy.v1',
969
- children: semanticRoot.children,
970
- maximum_depth: nested.metrics.maximumDepth,
971
- task_count: nested.metrics.taskCount,
972
- },
973
- };
974
- }
1
+ import { TODO_GANTT_SCOPES, projectTodoGanttScope } from './todo-gantt-scope.mjs';
2
+ import { buildTodoGanttHierarchy } from './todo-gantt-nested.mjs';
3
+ import { projectTodoCrossPlanDependencies } from './todo-store.mjs';
4
+
5
+ const TASK_LIMIT = 2_000;
6
+ const EDGE_LIMIT = 8_000;
7
+ const SWEEP_ROUNDS = 4;
8
+
9
+ /** Columns for a stage made only of ToDos with no registered dependency. */
10
+ const LOOSE_COLUMNS_MINIMUM = 8;
11
+
12
+ const GEOMETRY = Object.freeze({
13
+ left: 16,
14
+ top: 16,
15
+ wave_gap: 104,
16
+ lane_gap: 296,
17
+ node_width: 272,
18
+ node_height: 68,
19
+ stage_row_gap: 12,
20
+ route_inset: 8,
21
+ route_spacing: 12,
22
+ });
23
+
24
+ function segmentKind(left, right) {
25
+ if (left[1] === right[1] && left[0] !== right[0]) return 'horizontal';
26
+ if (left[0] === right[0] && left[1] !== right[1]) return 'vertical';
27
+ return 'point';
28
+ }
29
+
30
+ function strictlyBetween(value, left, right) {
31
+ return value > Math.min(left, right) && value < Math.max(left, right);
32
+ }
33
+
34
+ function addCrossingBridges(projectedEdges, logicalContacts = new Set()) {
35
+ const horizontalByY = new Map();
36
+ const verticals = [];
37
+ for (const edge of projectedEdges) {
38
+ for (let segment = 0; segment < edge.route.length - 1; segment += 1) {
39
+ const start = edge.route[segment];
40
+ const end = edge.route[segment + 1];
41
+ const kind = segmentKind(start, end);
42
+ if (kind === 'horizontal') {
43
+ if (!horizontalByY.has(start[1])) horizontalByY.set(start[1], []);
44
+ horizontalByY.get(start[1]).push({ edge, segment, start, end });
45
+ } else if (kind === 'vertical') verticals.push({ edge, start, end });
46
+ }
47
+ }
48
+ const yValues = [...horizontalByY.keys()].sort((left, right) => left - right);
49
+ const firstGreater = (value) => {
50
+ let low = 0; let high = yValues.length;
51
+ while (low < high) {
52
+ const middle = Math.floor((low + high) / 2);
53
+ if (yValues[middle] <= value) low = middle + 1; else high = middle;
54
+ }
55
+ return low;
56
+ };
57
+ const firstAtLeast = (value) => {
58
+ let low = 0; let high = yValues.length;
59
+ while (low < high) {
60
+ const middle = Math.floor((low + high) / 2);
61
+ if (yValues[middle] < value) low = middle + 1; else high = middle;
62
+ }
63
+ return low;
64
+ };
65
+ for (const vertical of verticals) {
66
+ const minimumY = Math.min(vertical.start[1], vertical.end[1]);
67
+ const maximumY = Math.max(vertical.start[1], vertical.end[1]);
68
+ for (let yIndex = firstGreater(minimumY); yIndex < firstAtLeast(maximumY); yIndex += 1) {
69
+ const y = yValues[yIndex];
70
+ for (const horizontal of horizontalByY.get(y)) {
71
+ if (horizontal.edge === vertical.edge
72
+ || !strictlyBetween(vertical.start[0], horizontal.start[0], horizontal.end[0])) continue;
73
+ if (logicalContacts.has(`${vertical.start[0]},${y}`)) continue;
74
+ horizontal.edge.bridges.push({
75
+ segment_index: horizontal.segment, x: vertical.start[0], y,
76
+ });
77
+ }
78
+ }
79
+ }
80
+ for (const edge of projectedEdges) {
81
+ edge.bridges.sort((left, right) => left.segment_index - right.segment_index
82
+ || (edge.route[left.segment_index][0] <= edge.route[left.segment_index + 1][0]
83
+ ? left.x - right.x : right.x - left.x));
84
+ }
85
+ }
86
+
87
+ export class TodoGanttLayoutError extends Error {
88
+ constructor(code, message, detail = null) {
89
+ super(message);
90
+ this.name = 'TodoGanttLayoutError';
91
+ this.code = code;
92
+ this.detail = detail;
93
+ }
94
+ }
95
+
96
+ function fail(code, message, detail) {
97
+ throw new TodoGanttLayoutError(code, message, detail);
98
+ }
99
+
100
+ function plain(value) {
101
+ return value !== null && typeof value === 'object' && !Array.isArray(value)
102
+ && Object.getPrototypeOf(value) === Object.prototype;
103
+ }
104
+
105
+ function compareText(left, right) {
106
+ return left < right ? -1 : left > right ? 1 : 0;
107
+ }
108
+
109
+ function refOf(value, context) {
110
+ if (!plain(value) || typeof value.project_id !== 'string'
111
+ || typeof value.plan_key !== 'string' || typeof value.task_id !== 'string') {
112
+ fail('TODO_LAYOUT_INVALID_INPUT', `${context} must be a task ref`);
113
+ }
114
+ return { project_id: value.project_id, plan_key: value.plan_key, task_id: value.task_id };
115
+ }
116
+
117
+ function refKey(ref) {
118
+ return JSON.stringify([ref.project_id, ref.plan_key, ref.task_id]);
119
+ }
120
+
121
+ function compareRefs(left, right) {
122
+ return compareText(left.project_id, right.project_id)
123
+ || compareText(left.plan_key, right.plan_key)
124
+ || compareText(left.task_id, right.task_id);
125
+ }
126
+
127
+ function groupKey(planKey, lane) {
128
+ return JSON.stringify([planKey, lane]);
129
+ }
130
+
131
+ function normalizeInput(readModel, chainProjection) {
132
+ if (!plain(readModel) || readModel.schema !== 'lattice.todo_store_read.v1'
133
+ || !Array.isArray(readModel.members)) {
134
+ fail('TODO_LAYOUT_INVALID_INPUT', 'read model must be lattice.todo_store_read.v1');
135
+ }
136
+ if (!plain(chainProjection) || chainProjection.schema !== 'lattice.todo_chain.v1'
137
+ || !Array.isArray(chainProjection.longest_chain_node_refs)
138
+ || !Array.isArray(chainProjection.longest_chain_edges)) {
139
+ fail('TODO_LAYOUT_INVALID_INPUT', 'chain projection must be lattice.todo_chain.v1');
140
+ }
141
+
142
+ const nodesByKey = new Map();
143
+ const members = [...readModel.members].sort((left, right) => {
144
+ const leftPlan = left?.plan;
145
+ const rightPlan = right?.plan;
146
+ return compareText(leftPlan?.project_id ?? '', rightPlan?.project_id ?? '')
147
+ || compareText(leftPlan?.plan_key ?? '', rightPlan?.plan_key ?? '');
148
+ });
149
+ for (let memberIndex = 0; memberIndex < members.length; memberIndex += 1) {
150
+ const member = members[memberIndex];
151
+ if (!plain(member) || !plain(member.plan) || !Array.isArray(member.plan.tasks)
152
+ || !Array.isArray(member.tasks) || !Array.isArray(member.plan.hard_dependencies)
153
+ || !Array.isArray(member.plan.joins)) {
154
+ fail('TODO_LAYOUT_INVALID_INPUT', `members[${memberIndex}] has an invalid read-model shape`);
155
+ }
156
+ const { plan } = member;
157
+ const statusByTask = new Map(member.tasks.map((task) => [task.task_id, task]));
158
+ // snapshot artifactの形式(v1にはphasesキーが無い)には縛られない導出ビューを読む
159
+ // (readTodoStoreが常にmember.phasesとして埋める。ADR 0147)。
160
+ const statusByPhase = new Map((member.phases ?? [])
161
+ .map((phase) => [phase.phase_id, phase.status]));
162
+ for (const task of plan.tasks) {
163
+ if (!plain(task) || typeof task.task_id !== 'string' || typeof task.lane !== 'string') {
164
+ fail('TODO_LAYOUT_INVALID_INPUT', 'plan task has an invalid shape');
165
+ }
166
+ const state = statusByTask.get(task.task_id);
167
+ if (!plain(state) || !['pending', 'in-progress', 'blocked', 'done'].includes(state.status)) {
168
+ fail('TODO_LAYOUT_INVALID_INPUT', `missing task state for ${task.task_id}`);
169
+ }
170
+ const ref = { project_id: plan.project_id, plan_key: plan.plan_key, task_id: task.task_id };
171
+ const key = refKey(ref);
172
+ if (nodesByKey.has(key)) fail('TODO_LAYOUT_INVALID_INPUT', `duplicate task: ${key}`);
173
+ nodesByKey.set(key, {
174
+ key,
175
+ ref,
176
+ title: typeof task.title === 'string' ? task.title : task.task_id,
177
+ lane: task.lane,
178
+ status: state.status,
179
+ plan_schema: plan.schema ?? null,
180
+ phase_id: task.phase_id ?? null,
181
+ // ADR 0147: phase無しplan(task.phase_idが無い世代)も、終端に暗黙のterminal-audit
182
+ // Phaseを1つ持つ(todo-store.mjsのphasesOf/TERMINAL_AUDIT_PHASE_ID)。ここで素通しせず
183
+ // nullのままにすると、gantt scope側(todo-gantt-scope.mjs)が「監査未了のplanを畳まない」
184
+ // 判定に使える材料を一切受け取れない。'terminal-audit'はTERMINAL_AUDIT_PHASE_IDと同じ
185
+ // 予約IDで、phase_readyの判定(v4だけを見る既存分岐)には影響しない。
186
+ phase_status: task.phase_id === undefined
187
+ ? statusByPhase.get('terminal-audit') ?? null
188
+ : statusByPhase.get(task.phase_id) ?? null,
189
+ phase_ready: plan.schema !== 'lattice.todo_plan.v4'
190
+ || statusByPhase.get(task.phase_id) === 'active',
191
+ });
192
+ }
193
+ }
194
+ if (nodesByKey.size > TASK_LIMIT) {
195
+ fail('TODO_SCALE_EXCEEDED', 'todo gantt task limit exceeded', {
196
+ task_count: nodesByKey.size, task_limit: TASK_LIMIT, edge_count: null, edge_limit: EDGE_LIMIT,
197
+ });
198
+ }
199
+
200
+ const edgeMap = new Map();
201
+ const addEdge = (fromValue, toValue, kind, joinIdentity = null) => {
202
+ const fromRef = refOf(fromValue, 'edge.from');
203
+ const toRef = refOf(toValue, 'edge.to');
204
+ const from = refKey(fromRef);
205
+ const to = refKey(toRef);
206
+ if (!nodesByKey.has(from) || !nodesByKey.has(to) || from === to) {
207
+ fail('TODO_LAYOUT_INVALID_INPUT', 'edge must connect two distinct read-model tasks');
208
+ }
209
+ const key = JSON.stringify([from, to]);
210
+ let edge = edgeMap.get(key);
211
+ if (edge === undefined) {
212
+ edge = { key, from, to, kinds: new Set(), joinIdentities: new Map() };
213
+ edgeMap.set(key, edge);
214
+ }
215
+ edge.kinds.add(kind);
216
+ if (joinIdentity !== null) {
217
+ const identityKey = JSON.stringify([
218
+ joinIdentity.project_id, joinIdentity.plan_key, joinIdentity.join_id,
219
+ ]);
220
+ edge.joinIdentities.set(identityKey, joinIdentity);
221
+ }
222
+ };
223
+ for (const member of members) {
224
+ for (const edge of member.plan.hard_dependencies) addEdge(edge.from, edge.to, 'hard');
225
+ for (const join of member.plan.joins) {
226
+ if (!plain(join) || !Array.isArray(join.after) || typeof join.id !== 'string') {
227
+ fail('TODO_LAYOUT_INVALID_INPUT', 'join has an invalid shape');
228
+ }
229
+ const identity = { project_id: member.plan.project_id, plan_key: member.plan.plan_key,
230
+ join_id: join.id };
231
+ for (const after of join.after) addEdge(after, join.before, 'join', identity);
232
+ }
233
+ }
234
+ for (const dependency of projectTodoCrossPlanDependencies(members)) {
235
+ addEdge(dependency.from, dependency.to, 'cross_plan');
236
+ }
237
+ if (edgeMap.size > EDGE_LIMIT) {
238
+ fail('TODO_SCALE_EXCEEDED', 'todo gantt edge limit exceeded', {
239
+ task_count: nodesByKey.size, task_limit: TASK_LIMIT,
240
+ edge_count: edgeMap.size, edge_limit: EDGE_LIMIT,
241
+ });
242
+ }
243
+
244
+ const nodes = [...nodesByKey.values()].sort((left, right) => compareRefs(left.ref, right.ref));
245
+ const edges = [...edgeMap.values()].sort((left, right) => compareText(left.key, right.key));
246
+ return { nodes, nodesByKey, edges };
247
+ }
248
+
249
+ function readyTaskKeys(readModel, nodes, nodesByKey, incoming) {
250
+ const phaseStatuses = new Map();
251
+ const phaseAcceptIncoming = new Map(nodes.map(({ key }) => [key, new Set()]));
252
+ for (const member of readModel.members) {
253
+ // snapshot artifactの形式には縛られない導出ビュー(member.phases)を読む(ADR 0147)。
254
+ for (const phase of member.phases ?? []) {
255
+ phaseStatuses.set(JSON.stringify([
256
+ member.plan.project_id, member.plan.plan_key, phase.phase_id,
257
+ ]), phase.status);
258
+ }
259
+ if (['lattice.todo_plan.v5', 'lattice.todo_plan.v7'].includes(member.plan.schema)) {
260
+ for (const edge of member.plan.phase_accept_dependencies ?? []) {
261
+ const target = refKey(refOf(edge.to, 'phase_accept_dependencies.to'));
262
+ if (!nodesByKey.has(target)) {
263
+ fail('TODO_LAYOUT_INVALID_INPUT', 'phase accept dependency targets an absent task');
264
+ }
265
+ phaseAcceptIncoming.get(target).add(JSON.stringify([
266
+ edge.from.project_id, edge.from.plan_key, edge.from.phase_id,
267
+ ]));
268
+ }
269
+ }
270
+ }
271
+ return new Set(nodes.filter((node) => node.status === 'pending' && node.phase_ready
272
+ && incoming.get(node.key).every((predecessorKey) => {
273
+ const predecessor = nodesByKey.get(predecessorKey);
274
+ return predecessor.status === 'done'
275
+ && (predecessor.plan_schema !== 'lattice.todo_plan.v4'
276
+ || predecessor.phase_id === null
277
+ || (predecessor.ref.plan_key === node.ref.plan_key
278
+ && predecessor.phase_id === node.phase_id)
279
+ || predecessor.phase_status === 'accepted');
280
+ }) && [...phaseAcceptIncoming.get(node.key)]
281
+ .every((phaseKey) => phaseStatuses.get(phaseKey) === 'accepted'))
282
+ .map(({ key }) => key));
283
+ }
284
+
285
+ function assignWaves(nodes, nodesByKey, edges) {
286
+ const incoming = new Map(nodes.map(({ key }) => [key, []]));
287
+ const outgoing = new Map(nodes.map(({ key }) => [key, []]));
288
+ const indegree = new Map(nodes.map(({ key }) => [key, 0]));
289
+ for (const edge of edges) {
290
+ incoming.get(edge.to).push(edge.from);
291
+ outgoing.get(edge.from).push(edge.to);
292
+ indegree.set(edge.to, indegree.get(edge.to) + 1);
293
+ }
294
+ for (const values of incoming.values()) values.sort(compareText);
295
+ for (const values of outgoing.values()) values.sort(compareText);
296
+ let ready = nodes.filter(({ key }) => indegree.get(key) === 0).map(({ key }) => key);
297
+ ready.sort((left, right) => compareRefs(nodesByKey.get(left).ref, nodesByKey.get(right).ref));
298
+ const wave = new Map(nodes.map(({ key }) => [key, 0]));
299
+ let visited = 0;
300
+ while (ready.length > 0) {
301
+ const current = ready.shift();
302
+ visited += 1;
303
+ for (const next of outgoing.get(current)) {
304
+ wave.set(next, Math.max(wave.get(next), wave.get(current) + 1));
305
+ indegree.set(next, indegree.get(next) - 1);
306
+ if (indegree.get(next) === 0) {
307
+ ready.push(next);
308
+ ready.sort((left, right) => compareRefs(nodesByKey.get(left).ref, nodesByKey.get(right).ref));
309
+ }
310
+ }
311
+ }
312
+ if (visited !== nodes.length) fail('TODO_LAYOUT_CYCLE', 'todo layout input contains a cycle');
313
+ return { incoming, outgoing, wave };
314
+ }
315
+
316
+ function median(values) {
317
+ if (values.length === 0) return null;
318
+ values.sort((left, right) => left - right);
319
+ const middle = Math.floor(values.length / 2);
320
+ return values.length % 2 === 1 ? values[middle] : (values[middle - 1] + values[middle]) / 2;
321
+ }
322
+
323
+ function orderLayers(nodes, wave, incoming, outgoing) {
324
+ const maximumWave = nodes.reduce((maximum, node) => Math.max(maximum, wave.get(node.key)), 0);
325
+ const layers = Array.from({ length: maximumWave + 1 }, () => []);
326
+ for (const node of nodes) layers[wave.get(node.key)].push(node.key);
327
+ const nodeByKey = new Map(nodes.map((node) => [node.key, node]));
328
+ const baseCompare = (leftKey, rightKey) => {
329
+ const left = nodeByKey.get(leftKey);
330
+ const right = nodeByKey.get(rightKey);
331
+ return compareText(left.lane, right.lane)
332
+ || compareText(left.ref.plan_key, right.ref.plan_key)
333
+ || compareRefs(left.ref, right.ref);
334
+ };
335
+ for (const layer of layers) layer.sort(baseCompare);
336
+
337
+ const reorder = (layerIndex, neighborMap) => {
338
+ const layer = layers[layerIndex];
339
+ const previousPosition = new Map(layer.map((key, index) => [key, index]));
340
+ const allPositions = new Map();
341
+ for (const otherLayer of layers) {
342
+ for (let index = 0; index < otherLayer.length; index += 1) allPositions.set(otherLayer[index], index);
343
+ }
344
+ const score = new Map(layer.map((key) => [key, median(
345
+ neighborMap.get(key).filter((neighbor) => allPositions.has(neighbor)).map((neighbor) => allPositions.get(neighbor)),
346
+ )]));
347
+ layer.sort((leftKey, rightKey) => {
348
+ const left = nodeByKey.get(leftKey);
349
+ const right = nodeByKey.get(rightKey);
350
+ const groupOrder = compareText(left.lane, right.lane)
351
+ || compareText(left.ref.plan_key, right.ref.plan_key);
352
+ if (groupOrder !== 0) return groupOrder;
353
+ const leftScore = score.get(leftKey);
354
+ const rightScore = score.get(rightKey);
355
+ if (leftScore !== null && rightScore !== null && leftScore !== rightScore) return leftScore - rightScore;
356
+ if (leftScore === null && rightScore !== null) return 1;
357
+ if (leftScore !== null && rightScore === null) return -1;
358
+ return previousPosition.get(leftKey) - previousPosition.get(rightKey) || baseCompare(leftKey, rightKey);
359
+ });
360
+ };
361
+
362
+ for (let round = 0; round < SWEEP_ROUNDS; round += 1) {
363
+ for (let layer = 1; layer < layers.length; layer += 1) reorder(layer, incoming);
364
+ for (let layer = layers.length - 2; layer >= 0; layer -= 1) reorder(layer, outgoing);
365
+ }
366
+ return layers;
367
+ }
368
+
369
+ function crossingCount(edges, wave, transversePosition) {
370
+ const groups = new Map();
371
+ for (const edge of edges) {
372
+ const pair = `${wave.get(edge.from)}\0${wave.get(edge.to)}`;
373
+ if (!groups.has(pair)) groups.set(pair, []);
374
+ groups.get(pair).push([transversePosition.get(edge.from), transversePosition.get(edge.to)]);
375
+ }
376
+ let total = 0;
377
+ for (const group of groups.values()) {
378
+ group.sort((left, right) => left[0] - right[0] || left[1] - right[1]);
379
+ const targets = [...new Set(group.map((entry) => entry[1]))].sort((left, right) => left - right);
380
+ const rank = new Map(targets.map((value, index) => [value, index + 1]));
381
+ const tree = new Uint32Array(targets.length + 1);
382
+ let seen = 0;
383
+ for (const [, target] of group) {
384
+ let prefix = 0;
385
+ for (let index = rank.get(target); index > 0; index -= index & -index) prefix += tree[index];
386
+ total += seen - prefix;
387
+ for (let index = rank.get(target); index < tree.length; index += index & -index) tree[index] += 1;
388
+ seen += 1;
389
+ }
390
+ }
391
+ return total;
392
+ }
393
+
394
+ /**
395
+ * plan別の独立性投影を、task refで引ける索引と図の外が語る要約へ畳む(ADR 0129 Decision 4)。
396
+ *
397
+ * 読み出しはasync I/Oとgit実行を伴うためCLI層が行い、ここへは値として渡る。
398
+ * layoutは同期pureのままに保つ。
399
+ */
400
+ function normalizeIndependence(value, nodesByKey) {
401
+ if (value === null || value === undefined) return { stateByKey: new Map(), summary: null };
402
+ if (!Array.isArray(value)) {
403
+ fail('TODO_LAYOUT_INVALID_INPUT', 'independence must be an array of plan projections');
404
+ }
405
+ const stateByKey = new Map();
406
+ const plans = [];
407
+ for (const projection of value) {
408
+ if (!plain(projection) || typeof projection.plan_key !== 'string'
409
+ || typeof projection.coverage !== 'string' || !plain(projection.frontier)) {
410
+ fail('TODO_LAYOUT_INVALID_INPUT', 'independence entry must carry plan_key, coverage and frontier');
411
+ }
412
+ const { plan_key: planKey, frontier } = projection;
413
+ const mark = (taskId, state) => {
414
+ const key = refKey({
415
+ project_id: projection.project_id, plan_key: planKey, task_id: taskId,
416
+ });
417
+ // 図に無いtaskへ状態を付けない。layoutのready判定と投影のready判定が食い違えば、
418
+ // 静かに無視するのでなくここで露見させる。
419
+ if (!nodesByKey.has(key)) {
420
+ fail('TODO_LAYOUT_INDEPENDENCE_DRIFT', 'independence references a task absent from layout', {
421
+ plan_key: planKey, task_id: taskId,
422
+ });
423
+ }
424
+ stateByKey.set(key, state);
425
+ };
426
+ for (const group of frontier.parallel_groups ?? []) {
427
+ for (const taskId of group.task_ids) mark(taskId, 'verified');
428
+ }
429
+ for (const pair of frontier.serialize_pairs ?? []) {
430
+ for (const taskId of pair.task_ids) mark(taskId, 'conflict');
431
+ }
432
+ for (const entry of frontier.conflicts_with_active ?? []) mark(entry.ready_task_id, 'conflict');
433
+ for (const entry of frontier.unknown ?? []) mark(entry.task_id, 'unknown');
434
+ plans.push({
435
+ plan_key: planKey,
436
+ coverage: projection.coverage,
437
+ verified_group_count: (frontier.parallel_groups ?? []).length,
438
+ verified_task_count: (frontier.parallel_groups ?? [])
439
+ .reduce((total, group) => total + group.task_ids.length, 0),
440
+ serialize_pairs: (frontier.serialize_pairs ?? []).map((pair) => ({
441
+ task_ids: [...pair.task_ids], type: pair.type, detail: pair.detail,
442
+ kind: pair.kind ?? null, severability: pair.severability ?? 'serial',
443
+ })),
444
+ conflicts_with_active: (frontier.conflicts_with_active ?? []).map((entry) => ({
445
+ ready_task_id: entry.ready_task_id, active_task_id: entry.active_task_id,
446
+ type: entry.type, detail: entry.detail,
447
+ kind: entry.kind ?? null, severability: entry.severability ?? 'serial',
448
+ })),
449
+ unknown_task_ids: (frontier.unknown ?? []).map(({ task_id: taskId }) => taskId).sort(compareText),
450
+ });
451
+ }
452
+ plans.sort((left, right) => compareText(left.plan_key, right.plan_key));
453
+ return { stateByKey, summary: { plans } };
454
+ }
455
+
456
+ /**
457
+ * seam proposalの公開投影を、描画に必要なhuman-facing fieldだけへ畳む。
458
+ * resource_idは記録のidentityであって表示名ではないため、layoutへ持ち込まない。
459
+ */
460
+ function normalizeSeamProposals(value) {
461
+ if (value === null || value === undefined) return { summary: null };
462
+ if (!Array.isArray(value)) {
463
+ fail('TODO_LAYOUT_INVALID_INPUT', 'seamProposals must be an array of plan projections');
464
+ }
465
+ const plans = value.map((projection) => {
466
+ if (!plain(projection) || typeof projection.project_id !== 'string'
467
+ || typeof projection.plan_key !== 'string'
468
+ || !['missing', 'superseded', 'stale', 'verified'].includes(projection.coverage)
469
+ || !plain(projection.guidance)
470
+ || typeof projection.guidance.code !== 'string'
471
+ || typeof projection.guidance.message !== 'string'
472
+ || typeof projection.guidance.next_action !== 'string'
473
+ || !Array.isArray(projection.components)) {
474
+ fail('TODO_LAYOUT_INVALID_INPUT', 'seam proposal entry has an invalid projection shape');
475
+ }
476
+ return {
477
+ project_id: projection.project_id,
478
+ plan_key: projection.plan_key,
479
+ coverage: projection.coverage,
480
+ guidance: { ...projection.guidance },
481
+ component_count: projection.component_count,
482
+ conflict_resource_count: projection.conflict_resource_count,
483
+ components: projection.components.map((component) => {
484
+ if (!plain(component) || typeof component.component_id !== 'string'
485
+ || typeof component.verdict !== 'string'
486
+ || !Array.isArray(component.task_ids)
487
+ || !Array.isArray(component.conflicts)
488
+ || !Array.isArray(component.proposed_surfaces)
489
+ || !Array.isArray(component.affected_tests)
490
+ || !Array.isArray(component.limits)
491
+ || !Array.isArray(component.reasons)
492
+ || !Array.isArray(component.unknowns)) {
493
+ fail('TODO_LAYOUT_INVALID_INPUT', 'seam proposal component has an invalid shape');
494
+ }
495
+ return {
496
+ component_id: component.component_id,
497
+ verdict: component.verdict,
498
+ task_ids: [...component.task_ids],
499
+ conflicts: component.conflicts.map((conflict) => {
500
+ if (!plain(conflict) || typeof conflict.kind !== 'string'
501
+ || typeof conflict.target !== 'string' || !Array.isArray(conflict.task_pairs)) {
502
+ fail('TODO_LAYOUT_INVALID_INPUT', 'seam proposal conflict has an invalid shape');
503
+ }
504
+ return {
505
+ kind: conflict.kind,
506
+ target: conflict.target,
507
+ task_pairs: conflict.task_pairs.map((pair) => [...pair]),
508
+ };
509
+ }),
510
+ proposed_surfaces: component.proposed_surfaces.map((surface) => ({ ...surface,
511
+ owner_task_ids: [...surface.owner_task_ids] })),
512
+ affected_tests: [...component.affected_tests],
513
+ limits: [...component.limits],
514
+ reasons: component.reasons.map((reason) => ({ ...reason })),
515
+ unknowns: component.unknowns.map((unknown) => ({ ...unknown })),
516
+ };
517
+ }),
518
+ };
519
+ });
520
+ plans.sort((left, right) => {
521
+ const leftHasDecisions = left.components.length > 0;
522
+ const rightHasDecisions = right.components.length > 0;
523
+ return leftHasDecisions === rightHasDecisions
524
+ ? compareText(left.plan_key, right.plan_key) : leftHasDecisions ? -1 : 1;
525
+ });
526
+ return { summary: { plans } };
527
+ }
528
+
529
+ function layoutTodoGanttFlat(readModel, chainProjection, options = {}) {
530
+ const scope = options.scope ?? 'live';
531
+ if (!TODO_GANTT_SCOPES.includes(scope)) {
532
+ fail('TODO_LAYOUT_INVALID_INPUT', `scope must be one of ${TODO_GANTT_SCOPES.join(', ')}`);
533
+ }
534
+
535
+ // Every structural number below is measured on the FULL graph: the dependency
536
+ // waves, the longest dependency chain and the ready frontier describe the real
537
+ // plan. Folding first and measuring second would make all three lie.
538
+ const full = normalizeInput(readModel, chainProjection);
539
+ const fullWaves = assignWaves(full.nodes, full.nodesByKey, full.edges);
540
+
541
+ const longestNodeKeys = new Set(chainProjection.longest_chain_node_refs.map((ref, index) => {
542
+ const key = refKey(refOf(ref, `longest_chain_node_refs[${index}]`));
543
+ if (!full.nodesByKey.has(key)) fail('TODO_LAYOUT_INVALID_INPUT', 'chain projection references an absent task');
544
+ return key;
545
+ }));
546
+ const longestEdgeKeys = new Set(chainProjection.longest_chain_edges.map((edge, index) => {
547
+ if (!plain(edge)) fail('TODO_LAYOUT_INVALID_INPUT', `longest_chain_edges[${index}] is invalid`);
548
+ const from = refKey(refOf(edge.from, `longest_chain_edges[${index}].from`));
549
+ const to = refKey(refOf(edge.to, `longest_chain_edges[${index}].to`));
550
+ const key = JSON.stringify([from, to]);
551
+ if (!full.edges.some((candidate) => candidate.key === key)) {
552
+ fail('TODO_LAYOUT_INVALID_INPUT', 'chain projection edge is absent from the read model');
553
+ }
554
+ return key;
555
+ }));
556
+ const readyKeys = readyTaskKeys(readModel, full.nodes, full.nodesByKey, fullWaves.incoming);
557
+ const independence = normalizeIndependence(options.independence ?? null, full.nodesByKey);
558
+ const seamProposals = normalizeSeamProposals(options.seamProposals ?? null);
559
+
560
+ // Only the geometry stage below sees the narrowed graph.
561
+ const projected = scope === 'all'
562
+ ? { nodes: full.nodes, edges: full.edges, foldedKeys: new Set() }
563
+ : projectTodoGanttScope({ nodes: full.nodes, edges: full.edges, wave: fullWaves.wave });
564
+ const nodes = projected.nodes;
565
+ const edges = projected.edges;
566
+ const nodesByKey = new Map(nodes.map((node) => [node.key, node]));
567
+ const { incoming, outgoing, wave } = assignWaves(nodes, nodesByKey, edges);
568
+ const layers = orderLayers(nodes, wave, incoming, outgoing);
569
+ // A ToDo with no registered dependency has nothing to line up with. Laying
570
+ // every one of them out in a single row makes the canvas as wide as the plan
571
+ // is old — real stores have hundreds — so they wrap into a block of rows.
572
+ //
573
+ // That block goes ABOVE the wired ToDos of its stage. Below them it used to be
574
+ // pierced: a wired card's port descends from its own bottom edge to the routing
575
+ // band under the whole stage, straight through whatever independent card had
576
+ // wrapped into the same column, and the hidden half of that line read as a
577
+ // dependency the plan does not have. Independent ToDos carry no edge, so they
578
+ // have no incoming one either and always land in stage 0, which nothing ever
579
+ // arrives into — putting them on top leaves no line to cross them.
580
+ const wired = new Set();
581
+ for (const edge of edges) { wired.add(edge.from); wired.add(edge.to); }
582
+ const transversePosition = new Map();
583
+ const stageRow = new Map();
584
+ const stageRowCount = [];
585
+ for (const layer of layers) {
586
+ const connected = layer.filter((key) => wired.has(key));
587
+ const loose = layer.filter((key) => !wired.has(key));
588
+ const columns = Math.max(LOOSE_COLUMNS_MINIMUM, connected.length);
589
+ const looseRows = loose.length === 0 ? 0 : Math.ceil(loose.length / columns);
590
+ loose.forEach((key, index) => {
591
+ transversePosition.set(key, index % columns);
592
+ stageRow.set(key, Math.floor(index / columns));
593
+ });
594
+ connected.forEach((key, index) => {
595
+ transversePosition.set(key, index);
596
+ stageRow.set(key, looseRows);
597
+ });
598
+ stageRowCount.push(Math.max(0, ...layer.map((key) => stageRow.get(key))) + 1);
599
+ }
600
+ const maximumLayerWidth = Math.max(1,
601
+ ...[...transversePosition.values()].map((position) => position + 1));
602
+ const visibleKeys = new Set(nodes.map(({ key }) => key));
603
+ const displayBranches = edges.flatMap((edge, semanticIndex) => {
604
+ const identities = [...edge.joinIdentities.entries()]
605
+ .sort(([left], [right]) => compareText(left, right)).map(([, identity]) => identity);
606
+ const variants = identities.length === 0 ? [null] : identities;
607
+ return variants.map((joinIdentity, branchIndex) => ({
608
+ key: JSON.stringify([edge.key, joinIdentity]), edge, semanticIndex, branchIndex, joinIdentity,
609
+ }));
610
+ });
611
+
612
+ const gapGroups = new Map();
613
+ const portGroups = new Map();
614
+ const portGroupKey = (gap, row) => `${gap}\0${row}`;
615
+ const portEntryKey = (edgeKey, direction) => `${edgeKey}\0${direction}`;
616
+ const addPort = (gap, row, entry) => {
617
+ const key = portGroupKey(gap, row);
618
+ if (!portGroups.has(key)) portGroups.set(key, []);
619
+ portGroups.get(key).push(entry);
620
+ };
621
+ // 隣の段の真下へ繋ぐ辺は、出発と到着が同じ取り付け位置の集合を奪い合う。別々の
622
+ // 枠を取ると2本の縦線が12pxずれて短い横棒で継がれ、まっすぐ引ける線が段差付きに
623
+ // 見える。両端の縦線は帯の中で1点で接するだけなので、1枠を共有させて直線にする。
624
+ const sharedPort = new Set();
625
+ displayBranches.forEach((branch) => {
626
+ const { edge } = branch;
627
+ for (const gap of new Set([wave.get(edge.from), wave.get(edge.to) - 1])) {
628
+ if (!gapGroups.has(gap)) gapGroups.set(gap, []);
629
+ gapGroups.get(gap).push(branch.key);
630
+ }
631
+ const departureGap = wave.get(edge.from);
632
+ const fromColumn = transversePosition.get(edge.from);
633
+ const toColumn = transversePosition.get(edge.to);
634
+ if (departureGap === wave.get(edge.to) - 1 && fromColumn === toColumn) {
635
+ sharedPort.add(branch.key);
636
+ addPort(departureGap, fromColumn, portEntryKey(branch.key, 'through'));
637
+ return;
638
+ }
639
+ addPort(departureGap, fromColumn, portEntryKey(branch.key, 'departure'));
640
+ addPort(wave.get(edge.to) - 1, toColumn, portEntryKey(branch.key, 'arrival'));
641
+ });
642
+ for (const keys of gapGroups.values()) keys.sort(compareText);
643
+ for (const entries of portGroups.values()) entries.sort(compareText);
644
+ const maximumPortTraffic = Math.max(0, ...[...portGroups.values()].map(({ length }) => length));
645
+ const connectorGroupKeysByGap = new Map();
646
+ for (const branch of displayBranches) {
647
+ if (branch.joinIdentity === null) continue;
648
+ const targetGap = wave.get(branch.edge.to) - 1;
649
+ if (!connectorGroupKeysByGap.has(targetGap)) connectorGroupKeysByGap.set(targetGap, new Set());
650
+ connectorGroupKeysByGap.get(targetGap).add(JSON.stringify([branch.edge.to, branch.joinIdentity]));
651
+ }
652
+ const allGapIndexes = new Set([...gapGroups.keys(), ...connectorGroupKeysByGap.keys()]);
653
+ const maximumGapOccupancy = Math.max(0, ...[...allGapIndexes].map((gap) =>
654
+ (gapGroups.get(gap)?.length ?? 0) + (connectorGroupKeysByGap.get(gap)?.size ?? 0)));
655
+ // An edge that skips a stage has to travel vertically past the stages in
656
+ // between. It used to do that in a corridor beyond the right edge of the
657
+ // whole diagram, so a local hop between two neighbouring cards was drawn as a
658
+ // trip to the far right and back. It now descends through the vertical
659
+ // channel between two columns of cards, chosen from the boundaries that lie
660
+ // between its endpoints. Every card sits on the same column grid, so those
661
+ // gaps are free of cards at every stage: routing inside one is both shorter
662
+ // to follow and structurally unable to cross a card.
663
+ const channelLoad = new Map();
664
+ const channelAssignment = new Map();
665
+ const channelTraffic = (boundary) => channelLoad.get(boundary) ?? 0;
666
+ for (const branch of [...displayBranches].sort((left, right) => compareText(left.key, right.key))) {
667
+ const { edge } = branch;
668
+ if (wave.get(edge.from) === wave.get(edge.to) - 1) continue;
669
+ const fromColumn = transversePosition.get(edge.from);
670
+ const toColumn = transversePosition.get(edge.to);
671
+ const [first, last] = fromColumn === toColumn
672
+ ? [toColumn, toColumn + 1]
673
+ : [Math.min(fromColumn, toColumn) + 1, Math.max(fromColumn, toColumn)];
674
+ let chosen = first;
675
+ for (let boundary = first + 1; boundary <= last; boundary += 1) {
676
+ const closer = Math.abs(boundary - toColumn) < Math.abs(chosen - toColumn);
677
+ if (channelTraffic(boundary) < channelTraffic(chosen)
678
+ || (channelTraffic(boundary) === channelTraffic(chosen) && closer)) chosen = boundary;
679
+ }
680
+ channelAssignment.set(branch.key, { boundary: chosen, lane: channelTraffic(chosen) });
681
+ channelLoad.set(chosen, channelTraffic(chosen) + 1);
682
+ }
683
+
684
+ const nodeWidth = Math.max(GEOMETRY.node_width,
685
+ GEOMETRY.route_inset * 2 + (maximumPortTraffic + 1) * GEOMETRY.route_spacing);
686
+ // Only the boundaries that actually carry channels pay for them. Boundary 0
687
+ // is the margin left of the first column and only exists when something
688
+ // routes there, so an untravelled diagram keeps its original left edge.
689
+ const channelWidth = (boundary) => Math.max(24,
690
+ (channelTraffic(boundary) + 1) * GEOMETRY.route_spacing);
691
+ const columnLeft = [GEOMETRY.left + (channelTraffic(0) === 0 ? 0 : channelWidth(0))];
692
+ for (let column = 1; column < maximumLayerWidth; column += 1) {
693
+ columnLeft.push(columnLeft[column - 1] + nodeWidth + channelWidth(column));
694
+ }
695
+ const channelPosition = (edgeKey) => {
696
+ const { boundary, lane } = channelAssignment.get(edgeKey);
697
+ const left = boundary === 0 ? GEOMETRY.left : columnLeft[boundary - 1] + nodeWidth;
698
+ return left + GEOMETRY.route_spacing * (lane + 1);
699
+ };
700
+ // Each routing band is sized for the edges that actually cross it. One
701
+ // crowded band used to set the spacing for every stage in the diagram, so a
702
+ // long plan paid the width of its busiest junction on all of its stages.
703
+ const gapBand = (gap) => Math.max(36, ((gapGroups.get(gap)?.length ?? 0)
704
+ + (connectorGroupKeysByGap.get(gap)?.size ?? 0) + 1) * GEOMETRY.route_spacing);
705
+ const stageHeight = (index) => stageRowCount[index] * GEOMETRY.node_height
706
+ + (stageRowCount[index] - 1) * GEOMETRY.stage_row_gap;
707
+ const stageTop = [GEOMETRY.top];
708
+ for (let index = 0; index + 1 < layers.length; index += 1) {
709
+ stageTop.push(stageTop[index] + stageHeight(index) + gapBand(index));
710
+ }
711
+
712
+ const coordinates = new Map();
713
+ const projectedNodes = nodes.map((node) => {
714
+ const visible = visibleKeys.has(node.key);
715
+ const geometry = visible ? {
716
+ x: columnLeft[transversePosition.get(node.key)],
717
+ y: stageTop[wave.get(node.key)]
718
+ + stageRow.get(node.key) * (GEOMETRY.node_height + GEOMETRY.stage_row_gap),
719
+ width: nodeWidth,
720
+ height: GEOMETRY.node_height,
721
+ } : null;
722
+ if (geometry !== null) coordinates.set(node.key, geometry);
723
+ return {
724
+ ref: { ...node.ref }, title: node.title, lane: node.lane, status: node.status,
725
+ wave: wave.get(node.key), row: transversePosition.get(node.key), visible,
726
+ visibility: {
727
+ longest_dependency_chain: longestNodeKeys.has(node.key),
728
+ active: node.status === 'in-progress', next_ready: readyKeys.has(node.key),
729
+ selected: false,
730
+ // 記録が語らないtaskはnull。「独立と分かっている」と「まだ何も言えない」を
731
+ // 図の上でも同じ顔にしない(ADR 0129 Decision 1)。
732
+ independence: independence.stateByKey.get(node.key) ?? null,
733
+ },
734
+ geometry,
735
+ };
736
+ });
737
+
738
+ const gapPosition = (edgeKey, waveIndex) => {
739
+ const keys = gapGroups.get(waveIndex);
740
+ const index = keys.indexOf(edgeKey);
741
+ return stageTop[waveIndex] + stageHeight(waveIndex)
742
+ + GEOMETRY.route_spacing * (index + 1);
743
+ };
744
+ const branchCounts = new Map();
745
+ for (const branch of displayBranches) {
746
+ branchCounts.set(branch.semanticIndex, (branchCounts.get(branch.semanticIndex) ?? 0) + 1);
747
+ }
748
+ const portPosition = (edgeKey, direction, gap, row, nodeX) => {
749
+ const entries = portGroups.get(portGroupKey(gap, row));
750
+ const entry = portEntryKey(edgeKey, sharedPort.has(edgeKey) ? 'through' : direction);
751
+ return nodeX + GEOMETRY.route_inset
752
+ + GEOMETRY.route_spacing * (entries.indexOf(entry) + 1);
753
+ };
754
+
755
+ const projectedEdges = displayBranches.map((branch) => {
756
+ const { edge } = branch;
757
+ const onLongestChain = longestEdgeKeys.has(edge.key);
758
+ const from = coordinates.get(edge.from);
759
+ const to = coordinates.get(edge.to);
760
+ const departureGap = wave.get(edge.from);
761
+ const arrivalGap = wave.get(edge.to) - 1;
762
+ const startX = portPosition(branch.key, 'departure', departureGap,
763
+ transversePosition.get(edge.from), from.x);
764
+ const startY = from.y + from.height;
765
+ const endX = portPosition(branch.key, 'arrival', arrivalGap,
766
+ transversePosition.get(edge.to), to.x);
767
+ const endY = to.y;
768
+ const departureY = gapPosition(branch.key, departureGap);
769
+ const arrivalY = gapPosition(branch.key, arrivalGap);
770
+ const corners = [[startX, startY], [startX, departureY]];
771
+ if (departureGap === arrivalGap) corners.push([endX, arrivalY]);
772
+ else {
773
+ const channelX = channelPosition(branch.key);
774
+ corners.push([channelX, departureY], [channelX, arrivalY], [endX, arrivalY]);
775
+ }
776
+ corners.push([endX, endY]);
777
+ // 1枠を共有する直線では折れ点が重なる。長さゼロの区間を残すと交差判定にも
778
+ // 描画にも意味のない点が混ざるので畳む。
779
+ const route = corners.filter(([x, y], index) =>
780
+ index === 0 || x !== corners[index - 1][0] || y !== corners[index - 1][1]);
781
+ return {
782
+ id: branchCounts.get(branch.semanticIndex) === 1
783
+ ? `edge-${branch.semanticIndex}` : `edge-${branch.semanticIndex}-join-${branch.branchIndex}`,
784
+ semantic_edge_id: `edge-${branch.semanticIndex}`,
785
+ from: { ...nodesByKey.get(edge.from).ref }, to: { ...nodesByKey.get(edge.to).ref },
786
+ kinds: [...edge.kinds].sort(compareText),
787
+ join_ids: branch.joinIdentity === null ? [] : [branch.joinIdentity.join_id],
788
+ join_owners: branch.joinIdentity === null ? [] : [{ ...branch.joinIdentity }],
789
+ visible: true, visibility: { longest_dependency_chain: onLongestChain, selected_incident: false },
790
+ route, bridges: [], junction: null,
791
+ };
792
+ });
793
+ const joinGroups = new Map();
794
+ for (const edge of projectedEdges) {
795
+ if (edge.join_ids.length === 0) continue;
796
+ const key = JSON.stringify([edge.to, edge.join_owners[0]]);
797
+ if (!joinGroups.has(key)) joinGroups.set(key, []);
798
+ joinGroups.get(key).push(edge);
799
+ }
800
+ const junctionConnectors = [];
801
+ const logicalContacts = new Set();
802
+ const connectorGapRanks = new Map();
803
+ for (const [, group] of [...joinGroups.entries()].sort(([left], [right]) => compareText(left, right))) {
804
+ group.sort((left, right) => compareText(left.id, right.id));
805
+ const target = coordinates.get(refKey(group[0].to));
806
+ const targetGap = wave.get(refKey(group[0].to)) - 1;
807
+ const groupRank = connectorGapRanks.get(targetGap) ?? 0;
808
+ connectorGapRanks.set(targetGap, groupRank + 1);
809
+ const primaryTargetPortX = group[0].route.at(-1)[0];
810
+ const junction = [primaryTargetPortX,
811
+ stageTop[targetGap] + stageHeight(targetGap)
812
+ + GEOMETRY.route_spacing * ((gapGroups.get(targetGap)?.length ?? 0) + groupRank + 1)];
813
+ const contacts = [];
814
+ for (const [index, edge] of group.entries()) {
815
+ edge.route.pop();
816
+ const contact = [edge.route.at(-1)[0], junction[1]];
817
+ if (edge.route.at(-1)[1] !== contact[1]) edge.route.push(contact);
818
+ contacts.push(contact);
819
+ logicalContacts.add(`${contact[0]},${contact[1]}`);
820
+ if (index === 0) {
821
+ edge.route.push([junction[0], target.y]);
822
+ edge.junction = junction;
823
+ }
824
+ }
825
+ const contactXs = contacts.map(([x]) => x);
826
+ if (Math.min(...contactXs) !== Math.max(...contactXs)) {
827
+ junctionConnectors.push({
828
+ id: `join-connector-${junctionConnectors.length}`,
829
+ join_ids: [...group[0].join_ids], join_owners: group[0].join_owners.map((owner) => ({ ...owner })),
830
+ route: [[Math.min(...contactXs), junction[1]], [Math.max(...contactXs), junction[1]]],
831
+ bridges: [], contacts,
832
+ });
833
+ }
834
+ }
835
+ addCrossingBridges([...projectedEdges, ...junctionConnectors], logicalContacts);
836
+ let routeMaximumX = nodes.length === 0 ? 0
837
+ : columnLeft[maximumLayerWidth - 1] + nodeWidth;
838
+ for (const edge of projectedEdges) {
839
+ for (const [x] of edge.route) routeMaximumX = Math.max(routeMaximumX, x);
840
+ }
841
+ for (const connector of junctionConnectors) {
842
+ for (const [x] of connector.route) routeMaximumX = Math.max(routeMaximumX, x);
843
+ }
844
+
845
+ // Counts stay honest: the summary chips report every ToDo in the plan, not
846
+ // only the ones the narrowed diagram happens to draw.
847
+ const planMap = new Map();
848
+ const laneMap = new Map();
849
+ for (const node of full.nodes) {
850
+ if (!planMap.has(node.ref.plan_key)) planMap.set(node.ref.plan_key, 0);
851
+ planMap.set(node.ref.plan_key, planMap.get(node.ref.plan_key) + 1);
852
+ const key = groupKey(node.ref.plan_key, node.lane);
853
+ if (!laneMap.has(key)) laneMap.set(key, { plan_key: node.ref.plan_key, lane: node.lane, task_count: 0 });
854
+ laneMap.get(key).task_count += 1;
855
+ }
856
+ return {
857
+ schema: 'lattice.todo_gantt_layout.v2',
858
+ assumptions: { logical_time: 'dependency_wave', duration_estimation: false, lane_is_presentation_only: true },
859
+ sweep: { method: 'stable_median', rounds: SWEEP_ROUNDS, tie_break: 'previous_position_then_task_ref' },
860
+ bounds: {
861
+ width: nodes.length === 0 ? 0 : routeMaximumX + GEOMETRY.left,
862
+ height: nodes.length === 0 ? 0
863
+ : GEOMETRY.top + stageTop.at(-1) + stageHeight(layers.length - 1),
864
+ wave_count: layers.length,
865
+ },
866
+ nodes: projectedNodes,
867
+ // 図の外が語るための投影。カードはバッジで状態だけを示し、相手と理由は右ペインが持つ。
868
+ independence: independence.summary,
869
+ // seam提案は図形を増やさず、右ペインで係争資源・ToDo組・判定・不足証拠をまとめて示す。
870
+ seam_proposals: seamProposals.summary,
871
+ edges: projectedEdges,
872
+ // Every dependency in the plan, before folding contracted any of them away.
873
+ // The diagram draws `edges`; anything that describes a ToDo in words — the
874
+ // premises and successors in the right pane — reads this instead, so a
875
+ // folded ToDo keeps telling the truth about what it depended on.
876
+ full_edges: full.edges.map((edge) => ({
877
+ from: { ...full.nodesByKey.get(edge.from).ref },
878
+ to: { ...full.nodesByKey.get(edge.to).ref },
879
+ kinds: [...edge.kinds].sort(compareText),
880
+ join_ids: [...edge.joinIdentities.values()].map(({ join_id }) => join_id).sort(compareText),
881
+ })),
882
+ connectors: junctionConnectors,
883
+ groups: {
884
+ plans: [...planMap.entries()].map(([plan_key, task_count]) => ({ plan_key, task_count })),
885
+ lanes: [...laneMap.values()],
886
+ },
887
+ scope: {
888
+ requested: scope,
889
+ folded_task_count: projected.foldedKeys.size,
890
+ },
891
+ // The ToDos the diagram no longer draws. They stay in the task index and in
892
+ // every count, so the reader can still reach them by name.
893
+ folded: [...projected.foldedKeys]
894
+ .map((taskKey) => JSON.parse(taskKey))
895
+ .map(([project_id, plan_key, task_id]) => ({ project_id, plan_key, task_id }))
896
+ .sort(compareRefs),
897
+ metrics: {
898
+ crossing_count: crossingCount(edges, wave, transversePosition),
899
+ visible_node_count: visibleKeys.size,
900
+ visible_edge_count: projectedEdges.filter(({ visible }) => visible).length,
901
+ task_count: full.nodes.length,
902
+ edge_count: full.edges.length,
903
+ },
904
+ };
905
+ }
906
+
907
+ function applyHierarchySemantics(level, semanticByKey) {
908
+ const layout = {
909
+ ...level.layout,
910
+ nodes: level.layout.nodes.map((node) => {
911
+ const semantic = semanticByKey.get(refKey(node.ref));
912
+ return semantic === undefined ? node : { ...node, visibility: { ...semantic.visibility } };
913
+ }),
914
+ };
915
+ return {
916
+ layout,
917
+ children: level.children.map((child) => ({
918
+ ...child,
919
+ level: applyHierarchySemantics(child.level, semanticByKey),
920
+ })),
921
+ };
922
+ }
923
+
924
+ function descendantNodes(level) {
925
+ return level.children.flatMap((child) => [
926
+ ...child.level.layout.nodes,
927
+ ...descendantNodes(child.level),
928
+ ]);
929
+ }
930
+
931
+ export function layoutTodoGantt(readModel, chainProjection, options = {}) {
932
+ const fullLayout = layoutTodoGanttFlat(readModel, chainProjection, options);
933
+ let nested;
934
+ try {
935
+ const visibleTaskKeys = (options.scope ?? 'live') === 'all' ? null
936
+ : new Set(fullLayout.nodes.map((node) => refKey(node.ref)));
937
+ nested = buildTodoGanttHierarchy(
938
+ readModel, options, layoutTodoGanttFlat, visibleTaskKeys,
939
+ );
940
+ } catch (error) {
941
+ if (error?.code !== 'TODO_LAYOUT_INVALID_HIERARCHY') throw error;
942
+ fail(error.code, error.message, error.detail);
943
+ }
944
+ if (nested === null) return fullLayout;
945
+
946
+ // 階層ごとの縮約graphは座標だけを決める。ready/最長鎖/独立性まで縮約graphで
947
+ // 再計算すると、未完の子を持つdone親が後続をreadyへ進めるなど、実graphと違う判断を描く。
948
+ const semanticLayout = options.scope === 'all'
949
+ ? fullLayout : layoutTodoGanttFlat(readModel, chainProjection, { ...options, scope: 'all' });
950
+ const semanticByKey = new Map(semanticLayout.nodes.map((node) => [refKey(node.ref), node]));
951
+ const semanticRoot = applyHierarchySemantics(nested.root, semanticByKey);
952
+ const rootLayout = semanticRoot.layout;
953
+ return {
954
+ ...rootLayout,
955
+ full_edges: fullLayout.full_edges,
956
+ groups: fullLayout.groups,
957
+ scope: fullLayout.scope,
958
+ folded: fullLayout.folded,
959
+ hierarchy_nodes: descendantNodes(semanticRoot),
960
+ metrics: {
961
+ ...rootLayout.metrics,
962
+ visible_node_count: nested.metrics.visibleNodeCount,
963
+ visible_edge_count: nested.metrics.visibleEdgeCount,
964
+ task_count: fullLayout.metrics.task_count,
965
+ edge_count: fullLayout.metrics.edge_count,
966
+ },
967
+ hierarchy: {
968
+ schema: 'lattice.todo_gantt_hierarchy.v1',
969
+ children: semanticRoot.children,
970
+ maximum_depth: nested.metrics.maximumDepth,
971
+ task_count: nested.metrics.taskCount,
972
+ },
973
+ };
974
+ }