@transitrix/diagrams 1.0.0 → 1.0.1

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 (267) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +47 -47
  3. package/dist/__tests__/edge-path.test.js +8 -0
  4. package/dist/activity-card/__tests__/example.test.js +20 -1
  5. package/dist/activity-card/__tests__/layout.test.js +102 -11
  6. package/dist/activity-card/__tests__/resolver.test.js +139 -6
  7. package/dist/activity-card/index.d.ts +1 -1
  8. package/dist/activity-card/layout.d.ts +1 -1
  9. package/dist/activity-card/layout.js +220 -103
  10. package/dist/activity-card/resolver.js +107 -26
  11. package/dist/activity-card/types.d.ts +150 -27
  12. package/dist/activity-card/validate.js +3 -0
  13. package/dist/actor/__tests__/validate.test.js +63 -31
  14. package/dist/actor/index.d.ts +1 -1
  15. package/dist/actor/index.js +1 -1
  16. package/dist/actor/types.d.ts +7 -3
  17. package/dist/actor/types.js +17 -3
  18. package/dist/actor/validate.js +55 -26
  19. package/dist/assertion/types.d.ts +3 -1
  20. package/dist/assertion/types.js +1 -1
  21. package/dist/change/__tests__/validate.test.js +40 -34
  22. package/dist/change/index.d.ts +1 -0
  23. package/dist/change/types.d.ts +1 -1
  24. package/dist/change/types.js +2 -2
  25. package/dist/change/validate.d.ts +6 -1
  26. package/dist/change/validate.js +68 -41
  27. package/dist/compliance/__tests__/classify.test.js +34 -0
  28. package/dist/compliance/__tests__/coverage-metric.test.js +146 -46
  29. package/dist/compliance/__tests__/html.test.js +2 -2
  30. package/dist/compliance/__tests__/impact.test.js +311 -6
  31. package/dist/compliance/classify.d.ts +6 -0
  32. package/dist/compliance/classify.js +9 -1
  33. package/dist/compliance/coverage-metric.d.ts +31 -11
  34. package/dist/compliance/coverage-metric.js +149 -39
  35. package/dist/compliance/html.js +77 -74
  36. package/dist/compliance/impact.d.ts +77 -16
  37. package/dist/compliance/impact.js +193 -25
  38. package/dist/compliance/index.d.ts +2 -2
  39. package/dist/compliance/index.js +1 -1
  40. package/dist/compliance/markdown.js +1 -0
  41. package/dist/compliance/types.d.ts +25 -6
  42. package/dist/edge-path.d.ts +8 -4
  43. package/dist/edge-path.js +11 -6
  44. package/dist/factor/__tests__/validate.test.js +74 -45
  45. package/dist/factor/index.d.ts +3 -2
  46. package/dist/factor/index.js +1 -1
  47. package/dist/factor/types.d.ts +4 -7
  48. package/dist/factor/types.js +10 -5
  49. package/dist/factor/validate.d.ts +6 -1
  50. package/dist/factor/validate.js +68 -50
  51. package/dist/fgca/__tests__/resolver.test.js +185 -0
  52. package/dist/fgca/index.d.ts +2 -0
  53. package/dist/fgca/index.js +1 -0
  54. package/dist/fgca/resolver.d.ts +49 -0
  55. package/dist/fgca/resolver.js +124 -0
  56. package/dist/goals/index.d.ts +1 -1
  57. package/dist/index.d.ts +5 -0
  58. package/dist/index.js +5 -0
  59. package/dist/process-blueprint/__tests__/layout.test.js +37 -0
  60. package/dist/process-blueprint/layout.js +5 -1
  61. package/dist/process-blueprint/types.d.ts +22 -1
  62. package/dist/stakeholder/__tests__/validate.test.js +49 -47
  63. package/dist/stakeholder/index.d.ts +1 -0
  64. package/dist/stakeholder/types.d.ts +3 -4
  65. package/dist/stakeholder/types.js +2 -3
  66. package/dist/stakeholder/validate.d.ts +6 -1
  67. package/dist/stakeholder/validate.js +71 -50
  68. package/dist/target-state/__tests__/validate.test.js +43 -27
  69. package/dist/target-state/index.d.ts +2 -0
  70. package/dist/target-state/index.js +1 -0
  71. package/dist/target-state/types.d.ts +6 -1
  72. package/dist/target-state/types.js +8 -7
  73. package/dist/target-state/validate.d.ts +6 -1
  74. package/dist/target-state/validate.js +69 -45
  75. package/dist/theme/themes.js +69 -69
  76. package/dist/webview/__tests__/entry.test.js +11 -11
  77. package/dist/webview/render-activities.d.ts +3 -1
  78. package/dist/webview/render-activities.js +2 -2
  79. package/dist/webview/render-activity-card.js +104 -77
  80. package/dist/webview/render-fgca.d.ts +4 -0
  81. package/dist/webview/render-fgca.js +2 -5
  82. package/dist/webview/render-goals.d.ts +1 -0
  83. package/dist/webview/render-goals.js +15 -15
  84. package/dist/webview/render-process-blueprint.js +10 -10
  85. package/package.json +40 -40
  86. package/src/__tests__/edge-path.test.ts +58 -46
  87. package/src/__tests__/scope.test.ts +27 -27
  88. package/src/__tests__/yaml-normalize.test.ts +158 -158
  89. package/src/activities/__tests__/cpm.test.ts +164 -164
  90. package/src/activities/__tests__/gantt.test.ts +245 -245
  91. package/src/activities/__tests__/layout.test.ts +112 -112
  92. package/src/activities/__tests__/validate.test.ts +409 -409
  93. package/src/activities/cpm.ts +95 -95
  94. package/src/activities/gantt.ts +276 -276
  95. package/src/activities/index.ts +28 -28
  96. package/src/activities/layout.ts +112 -112
  97. package/src/activities/types.ts +148 -148
  98. package/src/activities/validate.ts +357 -357
  99. package/src/activity-card/__tests__/example.test.ts +85 -66
  100. package/src/activity-card/__tests__/layout.test.ts +169 -63
  101. package/src/activity-card/__tests__/resolver.test.ts +307 -161
  102. package/src/activity-card/__tests__/validate.test.ts +131 -131
  103. package/src/activity-card/index.ts +38 -32
  104. package/src/activity-card/layout.ts +324 -194
  105. package/src/activity-card/resolver.ts +415 -337
  106. package/src/activity-card/types.ts +376 -237
  107. package/src/activity-card/validate.ts +162 -158
  108. package/src/actor/__tests__/validate.test.ts +70 -31
  109. package/src/actor/index.ts +1 -1
  110. package/src/actor/types.ts +21 -7
  111. package/src/actor/validate.ts +59 -27
  112. package/src/applications/__tests__/validate.test.ts +256 -256
  113. package/src/applications/index.ts +11 -11
  114. package/src/applications/types.ts +43 -43
  115. package/src/applications/validate.ts +131 -131
  116. package/src/assertion/__tests__/example.test.ts +37 -37
  117. package/src/assertion/__tests__/validate.test.ts +142 -142
  118. package/src/assertion/index.ts +12 -12
  119. package/src/assertion/types.ts +60 -58
  120. package/src/assertion/validate.ts +145 -145
  121. package/src/blocks/__tests__/layout.test.ts +169 -169
  122. package/src/blocks/__tests__/validate.test.ts +260 -260
  123. package/src/blocks/index.ts +17 -17
  124. package/src/blocks/layout.ts +186 -186
  125. package/src/blocks/types.ts +62 -62
  126. package/src/blocks/validate.ts +206 -206
  127. package/src/capability-map/__tests__/validate.test.ts +238 -238
  128. package/src/capability-map/index.ts +8 -8
  129. package/src/capability-map/types.ts +29 -29
  130. package/src/capability-map/validate.ts +127 -127
  131. package/src/change/__tests__/validate.test.ts +43 -34
  132. package/src/change/index.ts +1 -0
  133. package/src/change/types.ts +5 -3
  134. package/src/change/validate.ts +75 -43
  135. package/src/compliance/__tests__/classify.test.ts +64 -27
  136. package/src/compliance/__tests__/confidence.test.ts +98 -98
  137. package/src/compliance/__tests__/coverage-metric.test.ts +300 -188
  138. package/src/compliance/__tests__/demo-scenario.test.ts +273 -273
  139. package/src/compliance/__tests__/example.test.ts +57 -57
  140. package/src/compliance/__tests__/gap-report.test.ts +128 -128
  141. package/src/compliance/__tests__/html.test.ts +141 -141
  142. package/src/compliance/__tests__/impact.test.ts +840 -481
  143. package/src/compliance/__tests__/markdown.test.ts +94 -94
  144. package/src/compliance/__tests__/views.test.ts +64 -64
  145. package/src/compliance/classify.ts +100 -84
  146. package/src/compliance/confidence.ts +69 -69
  147. package/src/compliance/coverage-metric.ts +404 -263
  148. package/src/compliance/gap-report.ts +94 -94
  149. package/src/compliance/html.ts +298 -295
  150. package/src/compliance/impact.ts +861 -677
  151. package/src/compliance/index.ts +57 -56
  152. package/src/compliance/markdown.ts +136 -135
  153. package/src/compliance/reverse-index.ts +33 -33
  154. package/src/compliance/types.ts +136 -120
  155. package/src/compliance/views.ts +46 -46
  156. package/src/compliance-matrix/__tests__/build.test.ts +200 -200
  157. package/src/compliance-matrix/__tests__/example.test.ts +57 -57
  158. package/src/compliance-matrix/index.ts +11 -11
  159. package/src/compliance-matrix/types.ts +102 -102
  160. package/src/edge-path.ts +50 -44
  161. package/src/factor/__tests__/validate.test.ts +80 -45
  162. package/src/factor/index.ts +3 -7
  163. package/src/factor/types.ts +14 -18
  164. package/src/factor/validate.ts +77 -51
  165. package/src/fgca/__tests__/chain-table.test.ts +172 -172
  166. package/src/fgca/__tests__/layout.test.ts +179 -179
  167. package/src/fgca/__tests__/parse-canonical.test.ts +248 -248
  168. package/src/fgca/__tests__/preview-layout.test.ts +124 -124
  169. package/src/fgca/__tests__/resolver.test.ts +209 -0
  170. package/src/fgca/__tests__/validate.test.ts +142 -142
  171. package/src/fgca/chain-table.ts +225 -225
  172. package/src/fgca/index.ts +47 -45
  173. package/src/fgca/layout.ts +204 -204
  174. package/src/fgca/nodeTypes.ts +11 -11
  175. package/src/fgca/nodes/FGCAActivityNode.tsx +65 -65
  176. package/src/fgca/nodes/FGCAChangeNode.tsx +64 -64
  177. package/src/fgca/nodes/FGCAFactorNode.tsx +64 -64
  178. package/src/fgca/nodes/FGCAGoalNode.tsx +72 -72
  179. package/src/fgca/parse-canonical.ts +400 -400
  180. package/src/fgca/preview-layout.ts +217 -217
  181. package/src/fgca/resolver.ts +157 -0
  182. package/src/fgca/types.ts +50 -50
  183. package/src/fgca/validate.ts +126 -126
  184. package/src/geometry.ts +9 -9
  185. package/src/goals/__tests__/layout.test.ts +175 -175
  186. package/src/goals/__tests__/mutations.test.ts +111 -111
  187. package/src/goals/__tests__/parse-canonical.test.ts +145 -145
  188. package/src/goals/__tests__/validate.test.ts +202 -202
  189. package/src/goals/index.ts +20 -21
  190. package/src/goals/layout.ts +172 -172
  191. package/src/goals/mutations.ts +123 -123
  192. package/src/goals/parse-canonical.ts +286 -286
  193. package/src/goals/types.ts +85 -85
  194. package/src/goals/validate.ts +136 -136
  195. package/src/index.ts +28 -23
  196. package/src/process-blueprint/__tests__/compliance-lane.test.ts +320 -320
  197. package/src/process-blueprint/__tests__/layout.test.ts +240 -195
  198. package/src/process-blueprint/__tests__/validate.test.ts +310 -310
  199. package/src/process-blueprint/index.ts +31 -31
  200. package/src/process-blueprint/layout.ts +535 -531
  201. package/src/process-blueprint/types.ts +263 -242
  202. package/src/process-blueprint/validate.ts +181 -181
  203. package/src/process-map/__tests__/validate.test.ts +223 -223
  204. package/src/process-map/index.ts +10 -10
  205. package/src/process-map/types.ts +36 -36
  206. package/src/process-map/validate.ts +135 -135
  207. package/src/products/__tests__/validate.test.ts +239 -239
  208. package/src/products/index.ts +9 -9
  209. package/src/products/types.ts +31 -31
  210. package/src/products/validate.ts +112 -112
  211. package/src/repo-validate/__tests__/validate-repo.test.ts +149 -149
  212. package/src/repo-validate/index.ts +2 -2
  213. package/src/repo-validate/types.ts +50 -50
  214. package/src/repo-validate/validate-repo.ts +196 -196
  215. package/src/requirement/__tests__/example.test.ts +24 -24
  216. package/src/requirement/__tests__/validate.test.ts +96 -96
  217. package/src/requirement/index.ts +4 -4
  218. package/src/requirement/types.ts +35 -35
  219. package/src/requirement/validate.ts +92 -92
  220. package/src/scenarios/__tests__/validate.test.ts +209 -209
  221. package/src/scenarios/index.ts +15 -15
  222. package/src/scenarios/types.ts +37 -37
  223. package/src/scenarios/validate.ts +122 -122
  224. package/src/schema-version.ts +16 -16
  225. package/src/scope.ts +46 -46
  226. package/src/stakeholder/__tests__/validate.test.ts +51 -47
  227. package/src/stakeholder/index.ts +1 -0
  228. package/src/stakeholder/types.ts +7 -7
  229. package/src/stakeholder/validate.ts +79 -52
  230. package/src/target-state/__tests__/validate.test.ts +48 -27
  231. package/src/target-state/index.ts +2 -0
  232. package/src/target-state/types.ts +11 -7
  233. package/src/target-state/validate.ts +76 -46
  234. package/src/theme/index.ts +4 -4
  235. package/src/theme/themes.ts +237 -237
  236. package/src/theme/tokens.ts +133 -133
  237. package/src/typed-id.ts +56 -56
  238. package/src/validation-types.ts +36 -36
  239. package/src/webview/__tests__/entry-notations.test.ts +77 -77
  240. package/src/webview/__tests__/entry.test.ts +64 -64
  241. package/src/webview/__tests__/render-goals.test.ts +72 -72
  242. package/src/webview/entry.ts +292 -292
  243. package/src/webview/render-activities.ts +5 -3
  244. package/src/webview/render-activity-card.ts +266 -234
  245. package/src/webview/render-fgca.ts +6 -5
  246. package/src/webview/render-goals.ts +111 -110
  247. package/src/webview/render-process-blueprint.ts +207 -207
  248. package/src/webview/styles.css +322 -323
  249. package/src/yaml-normalize.ts +56 -56
  250. package/dist/element-envelope.d.ts +0 -15
  251. package/dist/element-envelope.js +0 -55
  252. package/dist/issues/__tests__/layout.test.js +0 -62
  253. package/dist/issues/__tests__/validate.test.d.ts +0 -1
  254. package/dist/issues/__tests__/validate.test.js +0 -82
  255. package/dist/issues/index.d.ts +0 -4
  256. package/dist/issues/index.js +0 -2
  257. package/dist/issues/layout.d.ts +0 -10
  258. package/dist/issues/layout.js +0 -82
  259. package/dist/issues/types.d.ts +0 -61
  260. package/dist/issues/types.js +0 -6
  261. package/dist/issues/validate.d.ts +0 -3
  262. package/dist/issues/validate.js +0 -143
  263. package/dist/webview/transitrix-render.css +0 -323
  264. package/dist/webview/transitrix-render.js +0 -6452
  265. package/dist/webview/transitrix-render.js.map +0 -7
  266. package/src/element-envelope.ts +0 -76
  267. /package/dist/{issues/__tests__/layout.test.d.ts → fgca/__tests__/resolver.test.d.ts} +0 -0
@@ -1,172 +1,172 @@
1
- import type { Goal, GoalTree, LayoutOptions, GoalTreeLayout, LaidOutNode, LaidOutEdge } from './types.js';
2
- import type { Scope } from '../scope.js';
3
-
4
- const DEFAULT_NODE_WIDTH = 250;
5
- const DEFAULT_NODE_HEIGHT = 80;
6
- const DEFAULT_RANK_SEP = 80;
7
- const DEFAULT_NODE_SEP = 40;
8
-
9
- /**
10
- * Trims a flat goal list to a scope (vkgeorgia/strategy#77).
11
- * - 'level' → goals with `level <= maxLevel`.
12
- * - 'root' → the root goal (matched by string id) plus all its descendants
13
- * via `parent_id`; an empty list when the root is absent.
14
- * Pure and exported so a future access-control layer can reuse it.
15
- */
16
- export function selectScopedGoals(goals: Goal[], scope: Scope): Goal[] {
17
- if (scope.mode === 'all') return goals;
18
- if (scope.mode === 'level') return goals.filter(g => g.level <= scope.maxLevel);
19
-
20
- // root mode: collect the subtree rooted at rootGoalId (descendants via parent_id).
21
- const children = new Map<number, number[]>();
22
- for (const g of goals) {
23
- if (!children.has(g.parent_id)) children.set(g.parent_id, []);
24
- children.get(g.parent_id)!.push(g.id);
25
- }
26
- const root = goals.find(g => String(g.id) === scope.rootGoalId);
27
- if (!root) return [];
28
- const keep = new Set<number>();
29
- const stack = [root.id];
30
- while (stack.length > 0) {
31
- const id = stack.pop()!;
32
- if (keep.has(id)) continue; // guard against malformed cycles
33
- keep.add(id);
34
- for (const c of children.get(id) ?? []) stack.push(c);
35
- }
36
- return goals.filter(g => keep.has(g.id));
37
- }
38
-
39
- export function layoutGoalTree(tree: GoalTree, options: LayoutOptions = {}): GoalTreeLayout {
40
- const {
41
- nodeWidth = DEFAULT_NODE_WIDTH,
42
- nodeHeight = DEFAULT_NODE_HEIGHT,
43
- rankSep = DEFAULT_RANK_SEP,
44
- nodeSep = DEFAULT_NODE_SEP,
45
- hideCollapsed = [],
46
- viewDepth = null,
47
- scope = { mode: 'all' },
48
- } = options;
49
-
50
- const hiddenSet = new Set(hideCollapsed);
51
- const goals = selectScopedGoals(tree.goals, scope);
52
-
53
- // Build parent→children map
54
- const children = new Map<number, number[]>();
55
- const goalById = new Map<number, Goal>();
56
- for (const g of goals) {
57
- goalById.set(g.id, g);
58
- if (!children.has(g.parent_id)) children.set(g.parent_id, []);
59
- children.get(g.parent_id)!.push(g.id);
60
- }
61
-
62
- // Compress the levels actually used into contiguous column ranks. The
63
- // canonical N+1 rule (GOALS-013) keeps `level` contiguous from 0, so for
64
- // conforming input this is the identity map. It only rescues legacy /
65
- // non-canonical documents whose `goal_types` skip levels (e.g. 0, 2, 4):
66
- // without it those gaps open phantom empty columns and double the
67
- // horizontal spacing between rendered tiers.
68
- const usedLevels = Array.from(new Set(goals.map(g => g.level))).sort((a, b) => a - b);
69
- const levelToCol = new Map<number, number>();
70
- usedLevels.forEach((lvl, i) => levelToCol.set(lvl, i));
71
-
72
- // Find effective roots: level 0 or parent_id === 0 or broken ref
73
- const allIds = new Set(goals.map(g => g.id));
74
- const roots = goals.filter(g => g.parent_id === 0 || !allIds.has(g.parent_id));
75
-
76
- // Determine hidden subtrees (collapsed or beyond viewDepth)
77
- const hiddenSubtrees = new Set<number>();
78
- function markHidden(id: number): void {
79
- for (const child of children.get(id) ?? []) {
80
- hiddenSubtrees.add(child);
81
- markHidden(child);
82
- }
83
- }
84
- for (const id of hiddenSet) markHidden(id);
85
- if (viewDepth !== null) {
86
- for (const g of goals) {
87
- if (g.level > viewDepth) hiddenSubtrees.add(g.id);
88
- }
89
- }
90
-
91
- const nodes: LaidOutNode[] = [];
92
- const edges: LaidOutEdge[] = [];
93
-
94
- // Recursive layout: assign y by counting vertical slots per column
95
- const columnNextY = new Map<number, number>();
96
-
97
- function getNextY(col: number): number {
98
- return columnNextY.get(col) ?? 0;
99
- }
100
- function advanceY(col: number, delta: number): void {
101
- columnNextY.set(col, (columnNextY.get(col) ?? 0) + delta);
102
- }
103
-
104
- const placed = new Set<number>();
105
-
106
- function placeSubtree(id: number): { top: number; bottom: number } {
107
- const goal = goalById.get(id);
108
- if (!goal || hiddenSubtrees.has(id)) return { top: 0, bottom: 0 };
109
- // Guard against cycles (parent-of-itself, mutual parenting). Without
110
- // validateGoalTree() upstream, layoutGoalTree must not stack-overflow on
111
- // malformed input — drop any subtree we've already placed.
112
- if (placed.has(id)) return { top: 0, bottom: 0 };
113
- placed.add(id);
114
-
115
- const col = levelToCol.get(goal.level) ?? 0;
116
- const childIds = (children.get(id) ?? []).filter(c => !hiddenSubtrees.has(c) && !placed.has(c));
117
- const isCollapsedRoot = hiddenSet.has(id) && childIds.length > 0;
118
- const hasHiddenChildren = childIds.length < (children.get(id) ?? []).length;
119
-
120
- if (childIds.length === 0) {
121
- // Leaf: place at current column Y
122
- const y = getNextY(col);
123
- advanceY(col, nodeHeight + nodeSep);
124
- nodes.push({ id, x: col * (nodeWidth + rankSep), y, width: nodeWidth, height: nodeHeight, data: goal, isCollapsedRoot, hasHiddenChildren });
125
- return { top: y, bottom: y + nodeHeight };
126
- }
127
-
128
- // Place children first to get their span
129
- const spans: Array<{ top: number; bottom: number }> = [];
130
- for (const cid of childIds) {
131
- spans.push(placeSubtree(cid));
132
- }
133
-
134
- const spanTop = Math.min(...spans.map(s => s.top));
135
- const spanBottom = Math.max(...spans.map(s => s.bottom));
136
- const parentY = spanTop + (spanBottom - spanTop) / 2 - nodeHeight / 2;
137
-
138
- // Make sure parent column is at least this far
139
- const curColY = getNextY(col);
140
- const finalY = Math.max(parentY, curColY);
141
- advanceY(col, finalY - curColY + nodeHeight + nodeSep);
142
-
143
- nodes.push({ id, x: col * (nodeWidth + rankSep), y: finalY, width: nodeWidth, height: nodeHeight, data: goal, isCollapsedRoot, hasHiddenChildren });
144
-
145
- for (const cid of childIds) {
146
- edges.push({ source: id, target: cid });
147
- }
148
-
149
- return { top: Math.min(finalY, spanTop), bottom: Math.max(finalY + nodeHeight, spanBottom) };
150
- }
151
-
152
- for (const root of roots) {
153
- if (!hiddenSubtrees.has(root.id) && !placed.has(root.id)) {
154
- placeSubtree(root.id);
155
- // Add inter-root gap
156
- for (const [col, y] of columnNextY) {
157
- columnNextY.set(col, y + nodeSep);
158
- }
159
- }
160
- }
161
-
162
- if (nodes.length === 0) {
163
- return { nodes: [], edges: [], bounds: { x: 0, y: 0, width: 0, height: 0 } };
164
- }
165
-
166
- const minX = Math.min(...nodes.map(n => n.x));
167
- const minY = Math.min(...nodes.map(n => n.y));
168
- const maxX = Math.max(...nodes.map(n => n.x + n.width));
169
- const maxY = Math.max(...nodes.map(n => n.y + n.height));
170
-
171
- return { nodes, edges, bounds: { x: minX, y: minY, width: maxX - minX, height: maxY - minY } };
172
- }
1
+ import type { Goal, GoalTree, LayoutOptions, GoalTreeLayout, LaidOutNode, LaidOutEdge } from './types.js';
2
+ import type { Scope } from '../scope.js';
3
+
4
+ const DEFAULT_NODE_WIDTH = 250;
5
+ const DEFAULT_NODE_HEIGHT = 80;
6
+ const DEFAULT_RANK_SEP = 80;
7
+ const DEFAULT_NODE_SEP = 40;
8
+
9
+ /**
10
+ * Trims a flat goal list to a scope (vkgeorgia/strategy#77).
11
+ * - 'level' → goals with `level <= maxLevel`.
12
+ * - 'root' → the root goal (matched by string id) plus all its descendants
13
+ * via `parent_id`; an empty list when the root is absent.
14
+ * Pure and exported so a future access-control layer can reuse it.
15
+ */
16
+ export function selectScopedGoals(goals: Goal[], scope: Scope): Goal[] {
17
+ if (scope.mode === 'all') return goals;
18
+ if (scope.mode === 'level') return goals.filter(g => g.level <= scope.maxLevel);
19
+
20
+ // root mode: collect the subtree rooted at rootGoalId (descendants via parent_id).
21
+ const children = new Map<number, number[]>();
22
+ for (const g of goals) {
23
+ if (!children.has(g.parent_id)) children.set(g.parent_id, []);
24
+ children.get(g.parent_id)!.push(g.id);
25
+ }
26
+ const root = goals.find(g => String(g.id) === scope.rootGoalId);
27
+ if (!root) return [];
28
+ const keep = new Set<number>();
29
+ const stack = [root.id];
30
+ while (stack.length > 0) {
31
+ const id = stack.pop()!;
32
+ if (keep.has(id)) continue; // guard against malformed cycles
33
+ keep.add(id);
34
+ for (const c of children.get(id) ?? []) stack.push(c);
35
+ }
36
+ return goals.filter(g => keep.has(g.id));
37
+ }
38
+
39
+ export function layoutGoalTree(tree: GoalTree, options: LayoutOptions = {}): GoalTreeLayout {
40
+ const {
41
+ nodeWidth = DEFAULT_NODE_WIDTH,
42
+ nodeHeight = DEFAULT_NODE_HEIGHT,
43
+ rankSep = DEFAULT_RANK_SEP,
44
+ nodeSep = DEFAULT_NODE_SEP,
45
+ hideCollapsed = [],
46
+ viewDepth = null,
47
+ scope = { mode: 'all' },
48
+ } = options;
49
+
50
+ const hiddenSet = new Set(hideCollapsed);
51
+ const goals = selectScopedGoals(tree.goals, scope);
52
+
53
+ // Build parent→children map
54
+ const children = new Map<number, number[]>();
55
+ const goalById = new Map<number, Goal>();
56
+ for (const g of goals) {
57
+ goalById.set(g.id, g);
58
+ if (!children.has(g.parent_id)) children.set(g.parent_id, []);
59
+ children.get(g.parent_id)!.push(g.id);
60
+ }
61
+
62
+ // Compress the levels actually used into contiguous column ranks. The
63
+ // canonical N+1 rule (GOALS-013) keeps `level` contiguous from 0, so for
64
+ // conforming input this is the identity map. It only rescues legacy /
65
+ // non-canonical documents whose `goal_types` skip levels (e.g. 0, 2, 4):
66
+ // without it those gaps open phantom empty columns and double the
67
+ // horizontal spacing between rendered tiers.
68
+ const usedLevels = Array.from(new Set(goals.map(g => g.level))).sort((a, b) => a - b);
69
+ const levelToCol = new Map<number, number>();
70
+ usedLevels.forEach((lvl, i) => levelToCol.set(lvl, i));
71
+
72
+ // Find effective roots: level 0 or parent_id === 0 or broken ref
73
+ const allIds = new Set(goals.map(g => g.id));
74
+ const roots = goals.filter(g => g.parent_id === 0 || !allIds.has(g.parent_id));
75
+
76
+ // Determine hidden subtrees (collapsed or beyond viewDepth)
77
+ const hiddenSubtrees = new Set<number>();
78
+ function markHidden(id: number): void {
79
+ for (const child of children.get(id) ?? []) {
80
+ hiddenSubtrees.add(child);
81
+ markHidden(child);
82
+ }
83
+ }
84
+ for (const id of hiddenSet) markHidden(id);
85
+ if (viewDepth !== null) {
86
+ for (const g of goals) {
87
+ if (g.level > viewDepth) hiddenSubtrees.add(g.id);
88
+ }
89
+ }
90
+
91
+ const nodes: LaidOutNode[] = [];
92
+ const edges: LaidOutEdge[] = [];
93
+
94
+ // Recursive layout: assign y by counting vertical slots per column
95
+ const columnNextY = new Map<number, number>();
96
+
97
+ function getNextY(col: number): number {
98
+ return columnNextY.get(col) ?? 0;
99
+ }
100
+ function advanceY(col: number, delta: number): void {
101
+ columnNextY.set(col, (columnNextY.get(col) ?? 0) + delta);
102
+ }
103
+
104
+ const placed = new Set<number>();
105
+
106
+ function placeSubtree(id: number): { top: number; bottom: number } {
107
+ const goal = goalById.get(id);
108
+ if (!goal || hiddenSubtrees.has(id)) return { top: 0, bottom: 0 };
109
+ // Guard against cycles (parent-of-itself, mutual parenting). Without
110
+ // validateGoalTree() upstream, layoutGoalTree must not stack-overflow on
111
+ // malformed input — drop any subtree we've already placed.
112
+ if (placed.has(id)) return { top: 0, bottom: 0 };
113
+ placed.add(id);
114
+
115
+ const col = levelToCol.get(goal.level) ?? 0;
116
+ const childIds = (children.get(id) ?? []).filter(c => !hiddenSubtrees.has(c) && !placed.has(c));
117
+ const isCollapsedRoot = hiddenSet.has(id) && childIds.length > 0;
118
+ const hasHiddenChildren = childIds.length < (children.get(id) ?? []).length;
119
+
120
+ if (childIds.length === 0) {
121
+ // Leaf: place at current column Y
122
+ const y = getNextY(col);
123
+ advanceY(col, nodeHeight + nodeSep);
124
+ nodes.push({ id, x: col * (nodeWidth + rankSep), y, width: nodeWidth, height: nodeHeight, data: goal, isCollapsedRoot, hasHiddenChildren });
125
+ return { top: y, bottom: y + nodeHeight };
126
+ }
127
+
128
+ // Place children first to get their span
129
+ const spans: Array<{ top: number; bottom: number }> = [];
130
+ for (const cid of childIds) {
131
+ spans.push(placeSubtree(cid));
132
+ }
133
+
134
+ const spanTop = Math.min(...spans.map(s => s.top));
135
+ const spanBottom = Math.max(...spans.map(s => s.bottom));
136
+ const parentY = spanTop + (spanBottom - spanTop) / 2 - nodeHeight / 2;
137
+
138
+ // Make sure parent column is at least this far
139
+ const curColY = getNextY(col);
140
+ const finalY = Math.max(parentY, curColY);
141
+ advanceY(col, finalY - curColY + nodeHeight + nodeSep);
142
+
143
+ nodes.push({ id, x: col * (nodeWidth + rankSep), y: finalY, width: nodeWidth, height: nodeHeight, data: goal, isCollapsedRoot, hasHiddenChildren });
144
+
145
+ for (const cid of childIds) {
146
+ edges.push({ source: id, target: cid });
147
+ }
148
+
149
+ return { top: Math.min(finalY, spanTop), bottom: Math.max(finalY + nodeHeight, spanBottom) };
150
+ }
151
+
152
+ for (const root of roots) {
153
+ if (!hiddenSubtrees.has(root.id) && !placed.has(root.id)) {
154
+ placeSubtree(root.id);
155
+ // Add inter-root gap
156
+ for (const [col, y] of columnNextY) {
157
+ columnNextY.set(col, y + nodeSep);
158
+ }
159
+ }
160
+ }
161
+
162
+ if (nodes.length === 0) {
163
+ return { nodes: [], edges: [], bounds: { x: 0, y: 0, width: 0, height: 0 } };
164
+ }
165
+
166
+ const minX = Math.min(...nodes.map(n => n.x));
167
+ const minY = Math.min(...nodes.map(n => n.y));
168
+ const maxX = Math.max(...nodes.map(n => n.x + n.width));
169
+ const maxY = Math.max(...nodes.map(n => n.y + n.height));
170
+
171
+ return { nodes, edges, bounds: { x: minX, y: minY, width: maxX - minX, height: maxY - minY } };
172
+ }
@@ -1,123 +1,123 @@
1
- import type { GoalTree, Goal, MutationResult, ValidationError } from './types.js';
2
- import { validateGoalTree } from './validate.js';
3
-
4
- function cloneTree(tree: GoalTree): GoalTree {
5
- return {
6
- goal_types: tree.goal_types.map(gt => ({ ...gt })),
7
- goals: tree.goals.map(g => ({ ...g, factors: g.factors ? g.factors.map(f => ({ ...f })) : undefined })),
8
- };
9
- }
10
-
11
- function nextId(tree: GoalTree): number {
12
- return Math.max(0, ...tree.goals.map(g => g.id)) + 1;
13
- }
14
-
15
- function getLevel(tree: GoalTree, goalId: number): number {
16
- const goal = tree.goals.find(g => g.id === goalId);
17
- return goal?.level ?? 0;
18
- }
19
-
20
- function getTypeForLevel(tree: GoalTree, level: number): string {
21
- const gt = tree.goal_types.find(t => t.level === level);
22
- return gt?.name ?? '';
23
- }
24
-
25
- function updateDescendantLevels(goals: Goal[], id: number, levelDelta: number): void {
26
- for (const g of goals) {
27
- if (g.parent_id === id) {
28
- g.level += levelDelta;
29
- g.type = '';
30
- updateDescendantLevels(goals, g.id, levelDelta);
31
- }
32
- }
33
- }
34
-
35
- function hasPathTo(goals: Goal[], fromId: number, targetId: number): boolean {
36
- const visited = new Set<number>();
37
- const stack = [fromId];
38
- while (stack.length > 0) {
39
- const cur = stack.pop()!;
40
- if (cur === targetId) return true;
41
- if (visited.has(cur)) continue;
42
- visited.add(cur);
43
- for (const g of goals) {
44
- if (g.parent_id === cur) stack.push(g.id);
45
- }
46
- }
47
- return false;
48
- }
49
-
50
- function refusalError(message: string): MutationResult<GoalTree> {
51
- const err: ValidationError = { code: 'MUTATION_REFUSED', message };
52
- return { ok: false, error: err };
53
- }
54
-
55
- export function reparent(tree: GoalTree, sourceId: number, targetId: number): MutationResult<GoalTree> {
56
- const clone = cloneTree(tree);
57
- const source = clone.goals.find(g => g.id === sourceId);
58
- const target = clone.goals.find(g => g.id === targetId);
59
-
60
- if (!source) return refusalError(`Goal ${sourceId} not found`);
61
- if (!target) return refusalError(`Target goal ${targetId} not found`);
62
- if (sourceId === targetId) return refusalError('Cannot reparent to self');
63
- if (hasPathTo(clone.goals, sourceId, targetId)) return refusalError('Cannot reparent: would create cycle');
64
-
65
- const maxLevel = Math.max(...clone.goal_types.map(gt => gt.level), 0);
66
- const newLevel = target.level + 1;
67
- if (newLevel > maxLevel) return refusalError(`Reparent would exceed max level ${maxLevel}`);
68
-
69
- const levelDelta = newLevel - source.level;
70
- source.parent_id = targetId;
71
- source.level = newLevel;
72
- source.type = getTypeForLevel(clone, newLevel);
73
- if (levelDelta !== 0) updateDescendantLevels(clone.goals, sourceId, levelDelta);
74
-
75
- const v = validateGoalTree(clone);
76
- if (!v.valid) return refusalError(v.errors[0]?.message ?? 'Validation failed after reparent');
77
- return { ok: true, result: clone };
78
- }
79
-
80
- export function addChild(tree: GoalTree, parentId: number, newGoal: Omit<Goal, 'id'>): MutationResult<GoalTree> {
81
- const clone = cloneTree(tree);
82
- const parent = parentId === 0 ? null : clone.goals.find(g => g.id === parentId);
83
-
84
- if (parentId !== 0 && !parent) return refusalError(`Parent goal ${parentId} not found`);
85
-
86
- const maxLevel = Math.max(...clone.goal_types.map(gt => gt.level), 0);
87
- const expectedLevel = parent ? parent.level + 1 : 0;
88
- if (expectedLevel > maxLevel) return refusalError(`New child would exceed max level ${maxLevel}`);
89
-
90
- const id = nextId(clone);
91
- clone.goals.push({ ...newGoal, id, parent_id: parentId, level: expectedLevel, type: getTypeForLevel(clone, expectedLevel) || newGoal.type });
92
-
93
- return { ok: true, result: clone };
94
- }
95
-
96
- export function deleteWithDescendants(tree: GoalTree, id: number): MutationResult<GoalTree> {
97
- const clone = cloneTree(tree);
98
- if (!clone.goals.find(g => g.id === id)) return refusalError(`Goal ${id} not found`);
99
-
100
- const toDelete = new Set<number>();
101
- const stack = [id];
102
- while (stack.length > 0) {
103
- const cur = stack.pop()!;
104
- toDelete.add(cur);
105
- for (const g of clone.goals) {
106
- if (g.parent_id === cur) stack.push(g.id);
107
- }
108
- }
109
- clone.goals = clone.goals.filter(g => !toDelete.has(g.id));
110
- return { ok: true, result: clone };
111
- }
112
-
113
- export function moveToBacklog(tree: GoalTree, id: number): MutationResult<GoalTree> {
114
- const clone = cloneTree(tree);
115
- const goal = clone.goals.find(g => g.id === id);
116
- if (!goal) return refusalError(`Goal ${id} not found`);
117
- goal.parent_id = 0;
118
- return { ok: true, result: clone };
119
- }
120
-
121
- export function restoreFromBacklog(tree: GoalTree, id: number, newParentId: number): MutationResult<GoalTree> {
122
- return reparent(tree, id, newParentId);
123
- }
1
+ import type { GoalTree, Goal, MutationResult, ValidationError } from './types.js';
2
+ import { validateGoalTree } from './validate.js';
3
+
4
+ function cloneTree(tree: GoalTree): GoalTree {
5
+ return {
6
+ goal_types: tree.goal_types.map(gt => ({ ...gt })),
7
+ goals: tree.goals.map(g => ({ ...g, factors: g.factors ? g.factors.map(f => ({ ...f })) : undefined })),
8
+ };
9
+ }
10
+
11
+ function nextId(tree: GoalTree): number {
12
+ return Math.max(0, ...tree.goals.map(g => g.id)) + 1;
13
+ }
14
+
15
+ function getLevel(tree: GoalTree, goalId: number): number {
16
+ const goal = tree.goals.find(g => g.id === goalId);
17
+ return goal?.level ?? 0;
18
+ }
19
+
20
+ function getTypeForLevel(tree: GoalTree, level: number): string {
21
+ const gt = tree.goal_types.find(t => t.level === level);
22
+ return gt?.name ?? '';
23
+ }
24
+
25
+ function updateDescendantLevels(goals: Goal[], id: number, levelDelta: number): void {
26
+ for (const g of goals) {
27
+ if (g.parent_id === id) {
28
+ g.level += levelDelta;
29
+ g.type = '';
30
+ updateDescendantLevels(goals, g.id, levelDelta);
31
+ }
32
+ }
33
+ }
34
+
35
+ function hasPathTo(goals: Goal[], fromId: number, targetId: number): boolean {
36
+ const visited = new Set<number>();
37
+ const stack = [fromId];
38
+ while (stack.length > 0) {
39
+ const cur = stack.pop()!;
40
+ if (cur === targetId) return true;
41
+ if (visited.has(cur)) continue;
42
+ visited.add(cur);
43
+ for (const g of goals) {
44
+ if (g.parent_id === cur) stack.push(g.id);
45
+ }
46
+ }
47
+ return false;
48
+ }
49
+
50
+ function refusalError(message: string): MutationResult<GoalTree> {
51
+ const err: ValidationError = { code: 'MUTATION_REFUSED', message };
52
+ return { ok: false, error: err };
53
+ }
54
+
55
+ export function reparent(tree: GoalTree, sourceId: number, targetId: number): MutationResult<GoalTree> {
56
+ const clone = cloneTree(tree);
57
+ const source = clone.goals.find(g => g.id === sourceId);
58
+ const target = clone.goals.find(g => g.id === targetId);
59
+
60
+ if (!source) return refusalError(`Goal ${sourceId} not found`);
61
+ if (!target) return refusalError(`Target goal ${targetId} not found`);
62
+ if (sourceId === targetId) return refusalError('Cannot reparent to self');
63
+ if (hasPathTo(clone.goals, sourceId, targetId)) return refusalError('Cannot reparent: would create cycle');
64
+
65
+ const maxLevel = Math.max(...clone.goal_types.map(gt => gt.level), 0);
66
+ const newLevel = target.level + 1;
67
+ if (newLevel > maxLevel) return refusalError(`Reparent would exceed max level ${maxLevel}`);
68
+
69
+ const levelDelta = newLevel - source.level;
70
+ source.parent_id = targetId;
71
+ source.level = newLevel;
72
+ source.type = getTypeForLevel(clone, newLevel);
73
+ if (levelDelta !== 0) updateDescendantLevels(clone.goals, sourceId, levelDelta);
74
+
75
+ const v = validateGoalTree(clone);
76
+ if (!v.valid) return refusalError(v.errors[0]?.message ?? 'Validation failed after reparent');
77
+ return { ok: true, result: clone };
78
+ }
79
+
80
+ export function addChild(tree: GoalTree, parentId: number, newGoal: Omit<Goal, 'id'>): MutationResult<GoalTree> {
81
+ const clone = cloneTree(tree);
82
+ const parent = parentId === 0 ? null : clone.goals.find(g => g.id === parentId);
83
+
84
+ if (parentId !== 0 && !parent) return refusalError(`Parent goal ${parentId} not found`);
85
+
86
+ const maxLevel = Math.max(...clone.goal_types.map(gt => gt.level), 0);
87
+ const expectedLevel = parent ? parent.level + 1 : 0;
88
+ if (expectedLevel > maxLevel) return refusalError(`New child would exceed max level ${maxLevel}`);
89
+
90
+ const id = nextId(clone);
91
+ clone.goals.push({ ...newGoal, id, parent_id: parentId, level: expectedLevel, type: getTypeForLevel(clone, expectedLevel) || newGoal.type });
92
+
93
+ return { ok: true, result: clone };
94
+ }
95
+
96
+ export function deleteWithDescendants(tree: GoalTree, id: number): MutationResult<GoalTree> {
97
+ const clone = cloneTree(tree);
98
+ if (!clone.goals.find(g => g.id === id)) return refusalError(`Goal ${id} not found`);
99
+
100
+ const toDelete = new Set<number>();
101
+ const stack = [id];
102
+ while (stack.length > 0) {
103
+ const cur = stack.pop()!;
104
+ toDelete.add(cur);
105
+ for (const g of clone.goals) {
106
+ if (g.parent_id === cur) stack.push(g.id);
107
+ }
108
+ }
109
+ clone.goals = clone.goals.filter(g => !toDelete.has(g.id));
110
+ return { ok: true, result: clone };
111
+ }
112
+
113
+ export function moveToBacklog(tree: GoalTree, id: number): MutationResult<GoalTree> {
114
+ const clone = cloneTree(tree);
115
+ const goal = clone.goals.find(g => g.id === id);
116
+ if (!goal) return refusalError(`Goal ${id} not found`);
117
+ goal.parent_id = 0;
118
+ return { ok: true, result: clone };
119
+ }
120
+
121
+ export function restoreFromBacklog(tree: GoalTree, id: number, newParentId: number): MutationResult<GoalTree> {
122
+ return reparent(tree, id, newParentId);
123
+ }