@diagrammo/dgmo 0.47.0 → 0.48.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 (319) hide show
  1. package/dist/auto.js +1 -1
  2. package/dist/auto.mjs +1 -1
  3. package/dist/element.js +1 -1
  4. package/dist/element.mjs +1 -1
  5. package/package.json +19 -70
  6. package/dist/advanced.cjs +0 -71648
  7. package/dist/advanced.d.cts +0 -5719
  8. package/dist/auto.cjs +0 -70648
  9. package/dist/auto.d.cts +0 -54
  10. package/dist/block.cjs +0 -70208
  11. package/dist/block.d.cts +0 -115
  12. package/dist/editor.cjs +0 -526
  13. package/dist/editor.d.cts +0 -26
  14. package/dist/element.cjs +0 -70530
  15. package/dist/element.d.cts +0 -62
  16. package/dist/highlight.cjs +0 -852
  17. package/dist/highlight.d.cts +0 -49
  18. package/dist/index.cjs +0 -70491
  19. package/dist/index.d.cts +0 -160
  20. package/dist/pert.cjs +0 -325
  21. package/dist/pert.d.cts +0 -559
  22. package/dist/themes-1-CuKpeH.d.cts +0 -908
  23. package/src/advanced.ts +0 -873
  24. package/src/arc/parser.ts +0 -15
  25. package/src/arc/renderer.ts +0 -633
  26. package/src/auto/index.ts +0 -621
  27. package/src/auto/shared.ts +0 -370
  28. package/src/auto/styles.ts +0 -73
  29. package/src/block/layout.ts +0 -198
  30. package/src/block/parser.ts +0 -427
  31. package/src/block/renderer.ts +0 -484
  32. package/src/block/types.ts +0 -67
  33. package/src/boxes-and-lines/collapse.ts +0 -96
  34. package/src/boxes-and-lines/focus.ts +0 -257
  35. package/src/boxes-and-lines/label-placement.ts +0 -339
  36. package/src/boxes-and-lines/layout-grouped.ts +0 -912
  37. package/src/boxes-and-lines/layout-layered.ts +0 -722
  38. package/src/boxes-and-lines/layout-search.ts +0 -1678
  39. package/src/boxes-and-lines/layout.ts +0 -398
  40. package/src/boxes-and-lines/parser.ts +0 -1181
  41. package/src/boxes-and-lines/renderer.ts +0 -1465
  42. package/src/boxes-and-lines/types.ts +0 -66
  43. package/src/c4/layout.ts +0 -2441
  44. package/src/c4/parser.ts +0 -1158
  45. package/src/c4/renderer.ts +0 -2008
  46. package/src/c4/types.ts +0 -89
  47. package/src/chart-type-registry.ts +0 -529
  48. package/src/chart-types.ts +0 -225
  49. package/src/chart.ts +0 -685
  50. package/src/charts-d3/bar.ts +0 -338
  51. package/src/charts-d3/chord.ts +0 -140
  52. package/src/charts-d3/function.ts +0 -147
  53. package/src/charts-d3/funnel.ts +0 -104
  54. package/src/charts-d3/heatmap.ts +0 -145
  55. package/src/charts-d3/index.ts +0 -337
  56. package/src/charts-d3/interactions.ts +0 -477
  57. package/src/charts-d3/line.ts +0 -344
  58. package/src/charts-d3/mount.ts +0 -151
  59. package/src/charts-d3/pie.ts +0 -117
  60. package/src/charts-d3/polar.ts +0 -89
  61. package/src/charts-d3/radar.ts +0 -0
  62. package/src/charts-d3/sankey.ts +0 -0
  63. package/src/charts-d3/scatter.ts +0 -185
  64. package/src/charts-d3/shared.ts +0 -208
  65. package/src/class/layout.ts +0 -326
  66. package/src/class/parser.ts +0 -635
  67. package/src/class/renderer.ts +0 -793
  68. package/src/class/types.ts +0 -58
  69. package/src/cli-banner.ts +0 -106
  70. package/src/cli.ts +0 -1080
  71. package/src/colors-diagnostics.ts +0 -35
  72. package/src/colors.ts +0 -379
  73. package/src/completion-types.ts +0 -27
  74. package/src/completion.ts +0 -2668
  75. package/src/cycle/layout.ts +0 -1026
  76. package/src/cycle/parser.ts +0 -387
  77. package/src/cycle/renderer.ts +0 -653
  78. package/src/cycle/types.ts +0 -101
  79. package/src/d3.ts +0 -1434
  80. package/src/data-chart-parser.ts +0 -1007
  81. package/src/dgmo-router.ts +0 -296
  82. package/src/diagnostics-registry.ts +0 -108
  83. package/src/diagnostics.ts +0 -0
  84. package/src/dimensions.ts +0 -20
  85. package/src/directives-registry.ts +0 -396
  86. package/src/editor/dgmo.grammar +0 -76
  87. package/src/editor/dgmo.grammar.d.ts +0 -2
  88. package/src/editor/dgmo.grammar.js +0 -18
  89. package/src/editor/dgmo.grammar.terms.d.ts +0 -5
  90. package/src/editor/dgmo.grammar.terms.js +0 -35
  91. package/src/editor/highlight-api.ts +0 -596
  92. package/src/editor/highlight.ts +0 -36
  93. package/src/editor/index.ts +0 -27
  94. package/src/editor/keywords.ts +0 -128
  95. package/src/editor/tokens.ts +0 -30
  96. package/src/element/index.ts +0 -432
  97. package/src/embed/css.ts +0 -312
  98. package/src/embed/escape.ts +0 -15
  99. package/src/embed/index.ts +0 -280
  100. package/src/er/classify.ts +0 -228
  101. package/src/er/layout.ts +0 -530
  102. package/src/er/parser.ts +0 -750
  103. package/src/er/renderer.ts +0 -725
  104. package/src/er/types.ts +0 -52
  105. package/src/error-card.ts +0 -269
  106. package/src/event-line/diagnostics.ts +0 -117
  107. package/src/event-line/parser.ts +0 -643
  108. package/src/event-line/renderer.ts +0 -1742
  109. package/src/event-line/types.ts +0 -74
  110. package/src/fonts.ts +0 -3
  111. package/src/gantt/calculator.ts +0 -979
  112. package/src/gantt/parser.ts +0 -1641
  113. package/src/gantt/renderer.ts +0 -3787
  114. package/src/gantt/resolver.ts +0 -172
  115. package/src/gantt/types.ts +0 -206
  116. package/src/graph/diagnostics.ts +0 -64
  117. package/src/graph/edge-spline.ts +0 -29
  118. package/src/graph/flowchart-parser.ts +0 -759
  119. package/src/graph/flowchart-renderer.ts +0 -817
  120. package/src/graph/layout.ts +0 -472
  121. package/src/graph/notes.ts +0 -21
  122. package/src/graph/state-collapse.ts +0 -78
  123. package/src/graph/state-parser.ts +0 -574
  124. package/src/graph/state-renderer.ts +0 -653
  125. package/src/graph/types.ts +0 -65
  126. package/src/index.ts +0 -261
  127. package/src/infra/compute.ts +0 -1385
  128. package/src/infra/layout.ts +0 -888
  129. package/src/infra/parser.ts +0 -1234
  130. package/src/infra/renderer.ts +0 -2534
  131. package/src/infra/roles.ts +0 -75
  132. package/src/infra/types.ts +0 -216
  133. package/src/infra/validation.ts +0 -201
  134. package/src/journey-map/layout.ts +0 -490
  135. package/src/journey-map/parser.ts +0 -557
  136. package/src/journey-map/renderer.ts +0 -1580
  137. package/src/journey-map/types.ts +0 -47
  138. package/src/kanban/mutations.ts +0 -175
  139. package/src/kanban/parser.ts +0 -509
  140. package/src/kanban/renderer.ts +0 -1449
  141. package/src/kanban/types.ts +0 -39
  142. package/src/label-layout.ts +0 -368
  143. package/src/map/colorize.ts +0 -54
  144. package/src/map/completion.ts +0 -316
  145. package/src/map/context-labels.ts +0 -609
  146. package/src/map/data/PROVENANCE.json +0 -1
  147. package/src/map/data/README.md +0 -40
  148. package/src/map/data/airport-collisions.json +0 -1
  149. package/src/map/data/airports.json +0 -1
  150. package/src/map/data/gazetteer.json +0 -1
  151. package/src/map/data/lakes.json +0 -1
  152. package/src/map/data/mountain-ranges.json +0 -1
  153. package/src/map/data/na-lakes.json +0 -1
  154. package/src/map/data/na-land.json +0 -1
  155. package/src/map/data/region-names.json +0 -1
  156. package/src/map/data/rivers.json +0 -1
  157. package/src/map/data/types.ts +0 -121
  158. package/src/map/data/us-states.json +0 -1
  159. package/src/map/data/water-bodies.json +0 -1
  160. package/src/map/data/world-coarse.json +0 -1
  161. package/src/map/data/world-detail.json +0 -1
  162. package/src/map/diagnostics.ts +0 -134
  163. package/src/map/dimensions.ts +0 -150
  164. package/src/map/geo-query.ts +0 -295
  165. package/src/map/geo.ts +0 -438
  166. package/src/map/invert.ts +0 -111
  167. package/src/map/layout.ts +0 -5069
  168. package/src/map/legend-band.ts +0 -127
  169. package/src/map/load-data.ts +0 -186
  170. package/src/map/parser.ts +0 -783
  171. package/src/map/renderer.ts +0 -1445
  172. package/src/map/resolved-types.ts +0 -160
  173. package/src/map/resolver.ts +0 -1146
  174. package/src/map/types.ts +0 -194
  175. package/src/mindmap/collapse.ts +0 -67
  176. package/src/mindmap/layout.ts +0 -649
  177. package/src/mindmap/parser.ts +0 -430
  178. package/src/mindmap/renderer.ts +0 -637
  179. package/src/mindmap/text-wrap.ts +0 -218
  180. package/src/mindmap/types.ts +0 -56
  181. package/src/org/collapse.ts +0 -151
  182. package/src/org/layout.ts +0 -1262
  183. package/src/org/parser.ts +0 -519
  184. package/src/org/renderer.ts +0 -866
  185. package/src/org/resolver.ts +0 -636
  186. package/src/palettes/atlas.ts +0 -77
  187. package/src/palettes/blueprint.ts +0 -73
  188. package/src/palettes/catppuccin.ts +0 -84
  189. package/src/palettes/color-utils.ts +0 -443
  190. package/src/palettes/index.ts +0 -67
  191. package/src/palettes/nord.ts +0 -67
  192. package/src/palettes/registry.ts +0 -114
  193. package/src/palettes/slate.ts +0 -73
  194. package/src/palettes/tidewater.ts +0 -73
  195. package/src/palettes/tokyo-night.ts +0 -86
  196. package/src/palettes/types.ts +0 -88
  197. package/src/pert/analyzer.ts +0 -1183
  198. package/src/pert/diagnostics.ts +0 -110
  199. package/src/pert/index.ts +0 -43
  200. package/src/pert/internal.ts +0 -252
  201. package/src/pert/layout.ts +0 -971
  202. package/src/pert/monte-carlo.ts +0 -446
  203. package/src/pert/parser.ts +0 -1606
  204. package/src/pert/renderer.ts +0 -4009
  205. package/src/pert/share-normalize.ts +0 -62
  206. package/src/pert/types.ts +0 -604
  207. package/src/pyramid/parser.ts +0 -185
  208. package/src/pyramid/renderer.ts +0 -768
  209. package/src/pyramid/types.ts +0 -28
  210. package/src/quadrant/parser.ts +0 -18
  211. package/src/quadrant/renderer.ts +0 -638
  212. package/src/raci/diagnostics.ts +0 -213
  213. package/src/raci/index.ts +0 -23
  214. package/src/raci/mutations.ts +0 -321
  215. package/src/raci/parser.ts +0 -699
  216. package/src/raci/renderer.ts +0 -1627
  217. package/src/raci/types.ts +0 -82
  218. package/src/raci/variants.ts +0 -320
  219. package/src/render.ts +0 -268
  220. package/src/ring/parser.ts +0 -212
  221. package/src/ring/renderer.ts +0 -490
  222. package/src/ring/types.ts +0 -27
  223. package/src/sequence/collapse.ts +0 -174
  224. package/src/sequence/parser.ts +0 -1596
  225. package/src/sequence/participant-inference.ts +0 -152
  226. package/src/sequence/renderer.ts +0 -3168
  227. package/src/sequence/tag-resolution.ts +0 -164
  228. package/src/sharing.ts +0 -211
  229. package/src/sitemap/collapse.ts +0 -100
  230. package/src/sitemap/layout.ts +0 -925
  231. package/src/sitemap/parser.ts +0 -755
  232. package/src/sitemap/renderer.ts +0 -828
  233. package/src/sitemap/types.ts +0 -42
  234. package/src/slope/parser.ts +0 -18
  235. package/src/slope/renderer.ts +0 -378
  236. package/src/swimlane/diagnostics.ts +0 -94
  237. package/src/swimlane/layout.ts +0 -597
  238. package/src/swimlane/parser.ts +0 -613
  239. package/src/swimlane/renderer.ts +0 -681
  240. package/src/swimlane/types.ts +0 -151
  241. package/src/tech-radar/interactive.ts +0 -1129
  242. package/src/tech-radar/layout.ts +0 -197
  243. package/src/tech-radar/parser.ts +0 -436
  244. package/src/tech-radar/renderer.ts +0 -1239
  245. package/src/tech-radar/shared.ts +0 -151
  246. package/src/tech-radar/types.ts +0 -86
  247. package/src/themes.ts +0 -22
  248. package/src/timeline/parser.ts +0 -472
  249. package/src/timeline/renderer.ts +0 -3024
  250. package/src/timeline/types.ts +0 -33
  251. package/src/timeline/viz-parser.ts +0 -21
  252. package/src/treemap/diagnostics.ts +0 -62
  253. package/src/treemap/layout-radial.ts +0 -233
  254. package/src/treemap/layout.ts +0 -189
  255. package/src/treemap/parser.ts +0 -463
  256. package/src/treemap/renderer-radial.ts +0 -438
  257. package/src/treemap/renderer.ts +0 -572
  258. package/src/treemap/treemap-shared.ts +0 -309
  259. package/src/treemap/types.ts +0 -60
  260. package/src/utils/arrow-markers.ts +0 -51
  261. package/src/utils/arrows-diagnostics.ts +0 -62
  262. package/src/utils/arrows.ts +0 -227
  263. package/src/utils/brand.ts +0 -61
  264. package/src/utils/card.ts +0 -183
  265. package/src/utils/collapse-engine/tree-edges.ts +0 -115
  266. package/src/utils/collapse-engine/tree.ts +0 -117
  267. package/src/utils/d3-helpers.ts +0 -219
  268. package/src/utils/d3-types.ts +0 -9
  269. package/src/utils/description-helpers.ts +0 -38
  270. package/src/utils/duration.ts +0 -312
  271. package/src/utils/export-container.ts +0 -41
  272. package/src/utils/expr-eval.ts +0 -27
  273. package/src/utils/fit-canvas.ts +0 -64
  274. package/src/utils/hover-styles.ts +0 -673
  275. package/src/utils/inline-markdown.ts +0 -96
  276. package/src/utils/legend-constants.ts +0 -48
  277. package/src/utils/legend-d3.ts +0 -618
  278. package/src/utils/legend-integration.ts +0 -107
  279. package/src/utils/legend-layout.ts +0 -776
  280. package/src/utils/legend-svg.ts +0 -214
  281. package/src/utils/legend-types.ts +0 -272
  282. package/src/utils/name-normalize.ts +0 -163
  283. package/src/utils/note-box/constants.ts +0 -25
  284. package/src/utils/note-box/index.ts +0 -11
  285. package/src/utils/note-box/metrics.ts +0 -90
  286. package/src/utils/note-box/svg.ts +0 -331
  287. package/src/utils/notes/bounds.ts +0 -30
  288. package/src/utils/notes/build.ts +0 -131
  289. package/src/utils/notes/index.ts +0 -18
  290. package/src/utils/notes/model.ts +0 -19
  291. package/src/utils/notes/parse.ts +0 -131
  292. package/src/utils/notes/place.ts +0 -177
  293. package/src/utils/notes/resolve.ts +0 -88
  294. package/src/utils/number-format.ts +0 -36
  295. package/src/utils/parsing.ts +0 -953
  296. package/src/utils/reserved-key-registry.ts +0 -239
  297. package/src/utils/safe-href.ts +0 -38
  298. package/src/utils/scaling.ts +0 -97
  299. package/src/utils/svg-embed.ts +0 -251
  300. package/src/utils/tag-groups.ts +0 -607
  301. package/src/utils/text-measure.ts +0 -122
  302. package/src/utils/time-ticks.ts +0 -253
  303. package/src/utils/title-constants.ts +0 -24
  304. package/src/utils/visual-conventions.ts +0 -61
  305. package/src/utils/wrapped-desc.ts +0 -87
  306. package/src/venn/parser.ts +0 -18
  307. package/src/venn/renderer.ts +0 -1047
  308. package/src/version-control/diagnostics.ts +0 -67
  309. package/src/version-control/parser.ts +0 -544
  310. package/src/version-control/renderer.ts +0 -724
  311. package/src/version-control/types.ts +0 -100
  312. package/src/visualizations/parse.ts +0 -1560
  313. package/src/visualizations/types.ts +0 -262
  314. package/src/wireframe/layout.ts +0 -479
  315. package/src/wireframe/parser.ts +0 -1114
  316. package/src/wireframe/renderer.ts +0 -1318
  317. package/src/wireframe/types.ts +0 -110
  318. package/src/wordcloud/parser.ts +0 -18
  319. package/src/wordcloud/renderer.ts +0 -357
@@ -1,1606 +0,0 @@
1
- // ============================================================
2
- // PERT Parser — two-pass
3
- // ============================================================
4
- //
5
- // Pass 1: scan source line-by-line, collect declarations, references,
6
- // groups. Indent-tracked state machine, no resolution.
7
- // Pass 2: resolve aliases → canonical ids; classify groups (hammock vs
8
- // cluster); detect conflicts; emit diagnostics.
9
- //
10
- // See `_bmad-output/implementation-artifacts/tech-spec-pert.md`
11
- // for the design rationale; AC1.* for the contract this parser meets.
12
-
13
- import { emit, makeDgmoError, suggest } from '../diagnostics';
14
- import type { DgmoError } from '../diagnostics';
15
- import { PERT_DX } from './diagnostics';
16
- import { parseDuration } from '../utils/duration';
17
- import {
18
- extractColor,
19
- measureIndent,
20
- splitNameAndMeta,
21
- warnUnknownMetaKeys,
22
- } from '../utils/parsing';
23
- import { PERT_REGISTRY, withTagAliases } from '../utils/reserved-key-registry';
24
- import { normalizeName } from '../utils/name-normalize';
25
- import {
26
- injectDefaultTagMetadata,
27
- matchTagBlockHeading,
28
- stripDefaultModifier,
29
- validateTagGroupNames,
30
- validateTagValues,
31
- finalizeAutoTagColors,
32
- AUTO_TAG_COLOR_SENTINEL,
33
- type TagGroup,
34
- tagAttrKey,
35
- } from '../utils/tag-groups';
36
- import type { Writable } from '../utils/brand';
37
- import type { Duration, DurationUnit } from '../gantt/types';
38
- import type { PaletteColors } from '../palettes';
39
- import type {
40
- EdgeType,
41
- ParsedPert,
42
- PertActivity,
43
- PertEdge,
44
- PertGroup,
45
- PertOptions,
46
- PertDirection,
47
- NodeDetail,
48
- } from './types';
49
- import { formatLocalISODate, parseLocalISODate } from './internal';
50
- import type {
51
- DurationEstimate,
52
- DeclarationSite,
53
- ReferenceSite,
54
- } from './internal';
55
- import type { DiagramSymbols } from '../completion-types';
56
-
57
- // ============================================================
58
- // Regexes / constants
59
- // ============================================================
60
-
61
- /** Bare directive lines accepted at the diagram level. */
62
- const DIRECTIVE_KEYS = new Set([
63
- 'time-unit',
64
- 'default-confidence',
65
- 'direction',
66
- 'node-detail',
67
- 'no-analysis',
68
- 'trials',
69
- 'seed',
70
- 'scrubber-trials',
71
- 'start-date',
72
- 'end-date',
73
- 'no-title',
74
- 'solid-fill',
75
- 'sprint-length',
76
- 'sprint-number',
77
- 'sprint-start',
78
- 'active-tag',
79
- ]);
80
-
81
- /**
82
- * Pipe-metadata keys that PERT consumes for non-tag purposes. Anything
83
- * else after alias resolution is treated as tag metadata.
84
- */
85
- const RESERVED_PIPE_KEYS: ReadonlySet<string> = new Set([
86
- 'confidence',
87
- 'collapsed',
88
- ]);
89
-
90
- /**
91
- * Common typo stems for directive keywords. When a line starts with one
92
- * of these AND its value would be valid for the canonical directive, we
93
- * emit a clear error instead of silently registering a TBD activity —
94
- * the latter previously poisoned backward-anchored rollups, leaving the
95
- * user to debug a chart full of `?` cells with no diagnostic to follow.
96
- */
97
- const NEAR_DIRECTIVE_HINTS: ReadonlyArray<{
98
- stem: string;
99
- canonical: string;
100
- matches: RegExp;
101
- }> = [
102
- {
103
- stem: 'confidence',
104
- canonical: 'default-confidence',
105
- matches: /^(low|medium|high)$/i,
106
- },
107
- {
108
- stem: 'start',
109
- canonical: 'start-date',
110
- matches: /^(\d{4}-\d{2}-\d{2}|now)$/i,
111
- },
112
- {
113
- stem: 'end',
114
- canonical: 'end-date',
115
- matches: /^\d{4}-\d{2}-\d{2}$/,
116
- },
117
- {
118
- stem: 'time',
119
- canonical: 'time-unit',
120
- matches: /^(d|w|m|q|y|h|min|bd|s)$/i,
121
- },
122
- ];
123
-
124
- /** Group header: `[name]` with optional `| collapsed: true` etc. */
125
- // Captures: [1]=name [2]=trailing content (metadata, parsed via splitNameAndMeta below)
126
- const GROUP_HEADER_RE = /^\[([^\]]+)\]\s*(.*)$/;
127
-
128
- /** Indented reference, no edge label: `-> dest`. */
129
- const ARROW_RE = /^->\s*(.+?)\s*$/;
130
-
131
- /**
132
- * Indented metadata line: `key: value` (§1.4.2). Captures [1]=key
133
- * [2]=value. The key must still pass the reserved-registry / tag-alias
134
- * gate before it dispatches as metadata — this only screens the shape.
135
- */
136
- const INDENTED_META_RE = /^([A-Za-z][\w-]*)\s*:\s*(.+)$/;
137
-
138
- /**
139
- * Indented reference with edge label: `-LABEL-> dest` where LABEL encodes
140
- * dependency type and/or lag (e.g. `SS`, `2d`, `SS+2d`, `FF-1d`).
141
- * The leading `-` and trailing `->` frame the label.
142
- */
143
- const LABELED_ARROW_RE = /^-(.+?)->\s*(.+?)\s*$/;
144
-
145
- /**
146
- * Parse an edge label into `{ type, lag }`. Returns `null` when the
147
- * label is malformed; emits no diagnostics — caller decides phrasing.
148
- *
149
- * Grammar: `[TYPE][SIGN NUMBER UNIT?]` — at least one of TYPE / lag must
150
- * be present. TYPE is FS/SS/FF/SF (case-insensitive). NUMBER may be
151
- * decimal. UNIT defaults to the diagram-level `time-unit`.
152
- */
153
- export function parseEdgeLabel(
154
- label: string,
155
- defaultUnit: Duration['unit']
156
- ): { type: EdgeType; lag: Duration | null } | null {
157
- const trimmed = label.trim();
158
- if (trimmed === '') return null;
159
- // [TYPE][SIGN NUMBER UNIT?] — TYPE optional, lag optional, but at least
160
- // one must be present (re-checked below).
161
- const m = trimmed.match(/^(fs|ss|ff|sf)?([+-]?\d+(?:\.\d+)?)?\s*([a-z]+)?$/i);
162
- if (!m) return null;
163
- const typeRaw = m[1];
164
- const numRaw = m[2];
165
- const unitRaw = m[3];
166
- // Reject empty match where neither piece was provided.
167
- if (!typeRaw && !numRaw) return null;
168
- // Unit alone (no number) is not a valid lag.
169
- if (unitRaw && !numRaw) return null;
170
- const type: EdgeType = typeRaw ? (typeRaw.toUpperCase() as EdgeType) : 'FS';
171
- let lag: Duration | null = null;
172
- if (numRaw) {
173
- const amount = parseFloat(numRaw);
174
- if (amount !== 0) {
175
- const unit = unitRaw
176
- ? (unitRaw.toLowerCase() as Duration['unit'])
177
- : defaultUnit;
178
- // Whitelist valid units to surface typos instead of silently
179
- // accepting `A -SS+2x-> B`.
180
- if (!isValidDurationUnit(unit)) return null;
181
- lag = { amount, unit };
182
- }
183
- }
184
- return { type, lag };
185
- }
186
-
187
- const VALID_DURATION_UNITS: ReadonlySet<string> = new Set([
188
- 'min',
189
- 'h',
190
- 'd',
191
- 'bd',
192
- 'w',
193
- 'm',
194
- 'q',
195
- 'y',
196
- 's',
197
- ]);
198
-
199
- function isValidDurationUnit(u: string): u is Duration['unit'] {
200
- return VALID_DURATION_UNITS.has(u);
201
- }
202
-
203
- /** Trailing `as <ident>` (alias) suffix; `<ident>` ≤ 12 chars. */
204
- const ALIAS_SUFFIX_RE = /\s+as\s+([A-Za-z][A-Za-z0-9_]{0,11})\s*$/;
205
-
206
- /**
207
- * Numeric-with-optional-unit token. The unit set matches `parseDuration()`
208
- * (h/min/d/bd/w/m/q/y/s). A bare number falls back to `timeUnit`.
209
- */
210
- const ESTIMATE_TOKEN_RE = /^(\d+(?:\.\d+)?)(min|bd|d|w|m|q|y|h|s)?$/;
211
-
212
- /** Default options when nothing is declared. */
213
- /**
214
- * Sentinel values mean "user didn't author this directive — derive a
215
- * sensible default from the parsed graph at the end of parsePert".
216
- * `trials`: scaled to activity count (see `deriveTrials`).
217
- * `seed`: FNV-1a hash of the title or sorted activity names.
218
- */
219
- const DEFAULT_OPTIONS: PertOptions = {
220
- timeUnit: 'd',
221
- direction: 'LR',
222
- nodeDetail: 'compact',
223
- confidence: 'medium',
224
- trials: -1,
225
- seed: -1,
226
- scrubberTrials: 300,
227
- anchor: null,
228
- sprintLength: null,
229
- sprintNumber: null,
230
- sprintStart: null,
231
- sprintMode: null,
232
- today: '',
233
- };
234
-
235
- /**
236
- * Auto-derive `trials` from activity count: small plans run fast, big
237
- * plans get more samples. Clamped to [5000, 20000].
238
- */
239
- function deriveTrials(activityCount: number): number {
240
- const t = Math.round(1000 * Math.sqrt(Math.max(activityCount, 1)));
241
- return Math.max(5000, Math.min(20000, t));
242
- }
243
-
244
- /**
245
- * Auto-derive `seed` from a stable string (title or activity names).
246
- * FNV-1a 32-bit. Returns a positive 31-bit integer so it round-trips
247
- * cleanly through JSON / share-link encoding.
248
- */
249
- function deriveSeed(s: string): number {
250
- let h = 0x811c9dc5;
251
- for (let i = 0; i < s.length; i++) {
252
- h ^= s.charCodeAt(i);
253
- h = Math.imul(h, 0x01000193);
254
- }
255
- return h >>> 1;
256
- }
257
-
258
- // ============================================================
259
- // Utility helpers
260
- // ============================================================
261
-
262
- /** Trim a `#` line-leading comment off the END of a line. */
263
- function stripTrailingComment(line: string): string {
264
- // Only strip when `#` is preceded by whitespace; preserves names that
265
- // happen to contain `#` literally (none in PERT today, but cheap).
266
- const m = line.match(/^(.*?)\s+#.*$/);
267
- // In-bounds by regex match: group 1 is guaranteed present.
268
- return (m ? m[1]! : line).trimEnd();
269
- }
270
-
271
- /**
272
- * Peel a trailing `as <ident>` suffix off `text`, returning the bare
273
- * left-hand side and (optionally) the alias. Backward scan per Parser
274
- * Rule 8 — names containing the literal `as` parse cleanly when no
275
- * alias is actually appended.
276
- */
277
- function peelAlias(text: string): { head: string; alias?: string } {
278
- const trimmed = text.trim();
279
- const m = trimmed.match(ALIAS_SUFFIX_RE);
280
- if (!m) return { head: trimmed };
281
- const alias = m[1];
282
- return {
283
- head: trimmed.slice(0, m.index!).trim(),
284
- ...(alias !== undefined && { alias }),
285
- };
286
- }
287
-
288
- /**
289
- * Split a line into name and duration-token portions, plus an optional
290
- * trailing alias and pipe-metadata block. The split point is the first
291
- * token that parses as a numeric estimate token.
292
- *
293
- * Returns `{ name, durationTokens, alias?, pipeMetadata? }`.
294
- */
295
- function tokenizeActivityLine(
296
- line: string,
297
- diagnostics?: import('../diagnostics').DgmoError[],
298
- lineNumber?: number,
299
- metaAliasMap?: Map<string, string>
300
- ): {
301
- name: string;
302
- durationTokens: string[];
303
- alias?: string;
304
- pipeMetadata?: string;
305
- } {
306
- let body = line;
307
- let pipeMetadata: string | undefined;
308
-
309
- // §1.4 unified metadata grammar — same-line cut on the body.
310
- // PERT activity lines: `Name 5 10 15 confidence: low` → split out
311
- // metadata, leaving `Name 5 10 15` for duration tokenization below.
312
- if (metaAliasMap !== undefined) {
313
- const registry = withTagAliases(
314
- PERT_REGISTRY,
315
- new Set(metaAliasMap.keys())
316
- );
317
- const split = splitNameAndMeta(
318
- body,
319
- registry,
320
- metaAliasMap,
321
- undefined,
322
- diagnostics,
323
- lineNumber
324
- );
325
- if (diagnostics && lineNumber != null) {
326
- warnUnknownMetaKeys(
327
- split.meta,
328
- registry,
329
- (msg) => diagnostics.push(makeDgmoError(lineNumber, msg, 'warning')),
330
- split.name
331
- );
332
- }
333
- if (Object.keys(split.meta).length > 0) {
334
- // Restore body with color and alias re-appended so the downstream
335
- // PERT tokenizer (peelAlias, duration token scan) sees the same
336
- // shape as a pre-0.18.0 `name 5 10 15 as id` body.
337
- let restored = split.name;
338
- if (split.color) restored = `${restored} ${split.color}`;
339
- if (split.alias) restored = `${restored} as ${split.alias}`;
340
- body = restored;
341
- // Merge metadata into the pipeMetadata string so downstream
342
- // parsePipeMetadata picks it up unchanged.
343
- const merged = Object.entries(split.meta)
344
- .map(([k, v]) => `${k}: ${v}`)
345
- .join(', ');
346
- pipeMetadata = pipeMetadata ? `${pipeMetadata}, ${merged}` : merged;
347
- }
348
- }
349
-
350
- // Peel alias suffix (must come after numeric tail; the alias regex
351
- // requires whitespace + `as` + ident so it cleanly avoids names that
352
- // contain `as` as a literal token).
353
- const peeled = peelAlias(body);
354
-
355
- // Now scan tokens left-to-right (whitespace OR commas separate),
356
- // splitting on the first numeric-looking token.
357
- const rawTokens = peeled.head
358
- .split(/[,\s]+/)
359
- .map((t) => t.trim())
360
- .filter(Boolean);
361
-
362
- let firstNumIdx = -1;
363
- for (let i = 0; i < rawTokens.length; i++) {
364
- // In-bounds by loop guard.
365
- if (ESTIMATE_TOKEN_RE.test(rawTokens[i]!)) {
366
- firstNumIdx = i;
367
- break;
368
- }
369
- }
370
-
371
- let name: string;
372
- let durationTokens: string[];
373
- if (firstNumIdx === -1) {
374
- name = peeled.head;
375
- durationTokens = [];
376
- } else {
377
- name = rawTokens.slice(0, firstNumIdx).join(' ').trim();
378
- durationTokens = rawTokens.slice(firstNumIdx);
379
- }
380
-
381
- return {
382
- name,
383
- durationTokens,
384
- ...(peeled.alias !== undefined && { alias: peeled.alias }),
385
- ...(pipeMetadata !== undefined && { pipeMetadata }),
386
- };
387
- }
388
-
389
- /**
390
- * Parse a single estimate token into a `Duration`. Accepts bare numerics
391
- * (inheriting `defaultUnit`) and unit-suffixed forms (`0.5d`). Returns
392
- * null on a malformed token (caller will diagnose).
393
- */
394
- function parseEstimateToken(
395
- token: string,
396
- defaultUnit: DurationUnit
397
- ): Duration | null {
398
- const m = token.match(ESTIMATE_TOKEN_RE);
399
- if (!m) return null;
400
- // In-bounds by regex match: group 1 is guaranteed present.
401
- const amount = parseFloat(m[1]!);
402
- if (!Number.isFinite(amount)) return null;
403
- const unit = (m[2] as DurationUnit | undefined) ?? defaultUnit;
404
- if (unit === 's') {
405
- // Sprint units don't make sense for PERT (no calendar). Fall back
406
- // to the diagram time-unit for now and let the analyzer warn.
407
- return { amount, unit: defaultUnit };
408
- }
409
- // Use parseDuration to round-trip the value (also normalizes form).
410
- const round = parseDuration(`${amount}${unit}`);
411
- return round ?? { amount, unit };
412
- }
413
-
414
- /**
415
- * Build a `DurationEstimate` from a list of tokens.
416
- * - 0 tokens → null (TBD)
417
- * - 1 token → caller must apply confidence factors elsewhere; here we
418
- * return `{ o: m, m, p: m }` so the analyzer's `applyMOnlyHeuristic()`
419
- * can rebuild it once it knows the per-activity confidence.
420
- * - 3 tokens → O, M, P literal.
421
- * - 2/N tokens → null + diagnostic at call site.
422
- */
423
- function buildEstimate(
424
- tokens: string[],
425
- defaultUnit: DurationUnit,
426
- diagnose: (msg: string) => void
427
- ): DurationEstimate | null {
428
- if (tokens.length === 0) return null;
429
- if (tokens.length === 2) {
430
- // In-bounds by length check above: tokens[0] and tokens[1] are guaranteed present.
431
- diagnose(
432
- `Expected 1 (M) or 3 (O M P) durations; got 2 (${tokens.join(' ')}). ` +
433
- `Did you mean '${tokens[0]!} ${(parseFloat(tokens[0]!) + parseFloat(tokens[1]!)) / 2} ${tokens[1]!}'?`
434
- );
435
- return null;
436
- }
437
- if (tokens.length !== 1 && tokens.length !== 3) {
438
- diagnose(
439
- `Expected 1 (M) or 3 (O M P) durations; got ${tokens.length} (${tokens.join(' ')}).`
440
- );
441
- return null;
442
- }
443
-
444
- const parsed: Duration[] = [];
445
- for (const t of tokens) {
446
- const dur = parseEstimateToken(t, defaultUnit);
447
- if (!dur) {
448
- diagnose(`Invalid duration token '${t}'.`);
449
- return null;
450
- }
451
- if (dur.amount < 0) {
452
- diagnose(`Duration must be ≥ 0; got '${t}'.`);
453
- return null;
454
- }
455
- parsed.push(dur);
456
- }
457
-
458
- if (parsed.length === 1) {
459
- // M-only — analyzer expands using confidence factors. Stash M in
460
- // all three slots; the `mOnly` flag (not value-equality) is the
461
- // sentinel, so a literal "1 1 1" triple is correctly preserved.
462
- // In-bounds by length === 1 check.
463
- return { o: parsed[0]!, m: parsed[0]!, p: parsed[0]!, mOnly: true };
464
- }
465
-
466
- // 3-tuple — validate O ≤ M ≤ P (after unit-normalization on amounts).
467
- // In-bounds: validated to be length 3 above.
468
- const [o, m, p] = parsed as [Duration, Duration, Duration];
469
- // For mixed units we compare with same-unit normalization; for v1 we
470
- // compare amounts directly when units match (the common case).
471
- const sameUnit = o.unit === m.unit && m.unit === p.unit;
472
- if (sameUnit && !(o.amount <= m.amount && m.amount <= p.amount)) {
473
- diagnose(
474
- `Invalid estimate (${tokens.join(' ')}): expected O ≤ M ≤ P. ` +
475
- `Did you mean (${[o.amount, m.amount, p.amount].sort((a, b) => a - b).join(' ')})?`
476
- );
477
- return null;
478
- }
479
- return { o, m, p, mOnly: false };
480
- }
481
-
482
- /**
483
- * Pipe metadata: `key: value, key2: value2`.
484
- * Reserved keys (`confidence`, `collapsed`) flow into their dedicated
485
- * activity/group fields; everything else is treated as tag metadata
486
- * once aliases (`p` → `priority`) are resolved against the diagram's
487
- * declared tag groups.
488
- */
489
- function parsePipeMetadata(
490
- raw: string,
491
- aliasMap: Map<string, string> = new Map()
492
- ): Record<string, string> {
493
- const out: Record<string, string> = {};
494
- for (const part of raw.split(',')) {
495
- const trimmed = part.trim();
496
- if (!trimmed) continue;
497
- const idx = trimmed.indexOf(':');
498
- if (idx <= 0) continue;
499
- const rawKey = trimmed.slice(0, idx).trim().toLowerCase();
500
- const key = aliasMap.get(rawKey) ?? rawKey;
501
- const value = trimmed.slice(idx + 1).trim();
502
- out[key] = value;
503
- }
504
- return out;
505
- }
506
-
507
- // ============================================================
508
- // parsePert
509
- // ============================================================
510
-
511
- export interface ParsePertOptions {
512
- /**
513
- * "Today" reference for `start-date now` and `options.today`. Defaults
514
- * to `new Date()` at call time; tests inject a fixed date for
515
- * deterministic snapshots and past-row assertions.
516
- */
517
- now?: Date;
518
- /**
519
- * Active palette — used when resolving color names on `tag` entries
520
- * (e.g. `High red` → palette.colors.red). Optional; when omitted the
521
- * universal default color map is used.
522
- */
523
- palette?: PaletteColors;
524
- }
525
-
526
- export function parsePert(
527
- content: string,
528
- parseOpts: ParsePertOptions = {}
529
- ): ParsedPert {
530
- const lines = content.split('\n');
531
- const diagnostics: DgmoError[] = [];
532
- const error = (line: number, msg: string, code?: string): void => {
533
- diagnostics.push(makeDgmoError(line, msg, 'error', code));
534
- };
535
- const warn = (line: number, msg: string, code?: string): void => {
536
- diagnostics.push(makeDgmoError(line, msg, 'warning', code));
537
- };
538
-
539
- // Parse-time "today" — single capture, used both for `start-date now`
540
- // resolution AND surfaced to the analyzer via `options.today`. Baking
541
- // at parse time matches the spec: shared share-links land on the
542
- // recipient's render path with a frozen `today`, and `(as of …)`
543
- // suffixes reflect the author's clock.
544
- const today = formatLocalISODate(parseOpts.now ?? new Date());
545
-
546
- const options: PertOptions = { ...DEFAULT_OPTIONS, today };
547
- let title: string | null = null;
548
-
549
- // Track the line of the FIRST anchor directive so a later collision
550
- // can name it (per F9 review feedback). Cleared along with
551
- // `options.anchor` when both-anchors is detected.
552
- let firstAnchorLine: number | null = null;
553
- let firstAnchorKey: 'start-date' | 'end-date' | null = null;
554
-
555
- // ── Pass 1 ──────────────────────────────────────────────
556
- // Collect declarations, references, group blocks. No resolution yet.
557
-
558
- /** Map of canonical normalized name → declaration site (the first one wins). */
559
- const declarationsByName = new Map<string, DeclarationSite>();
560
- /** Same map keyed by alias literal → declaration. */
561
- const declarationsByAlias = new Map<string, DeclarationSite>();
562
- /** All declaration sites in source order (used for conflict detection). */
563
- const allDeclarations: DeclarationSite[] = [];
564
- /** Cross-site duplicate buckets keyed by normalized name. */
565
- const sitesByName = new Map<string, DeclarationSite[]>();
566
-
567
- /** Edge references from indented `-> dest` lines. */
568
- const references: ReferenceSite[] = [];
569
-
570
- /** Groups discovered in source order; activityIds populated in Pass 2. */
571
- const groups: Writable<PertGroup>[] = [];
572
-
573
- /**
574
- * Tag groups declared at the top of the diagram. A `tag …` heading
575
- * opens a block; entries (indented `Value color` lines) accumulate
576
- * until the first non-tag content line closes it.
577
- */
578
- const tagGroups: TagGroup[] = [];
579
- let currentTagGroup: Writable<TagGroup> | null = null;
580
- /**
581
- * Tag-block phase ends as soon as the parser sees any directive,
582
- * group header, activity, or arrow line. After `contentStarted`
583
- * flips, further `tag …` headings are rejected with an error.
584
- */
585
- let contentStarted = false;
586
- /**
587
- * Map of pipe-metadata alias → canonical tag-group key (lowercased
588
- * tag-group name). `tag Priority as p` adds `p → priority`, so
589
- * `| p: High` resolves to `priority: High` at activity-parse time.
590
- */
591
- const metaAliasMap = new Map<string, string>();
592
-
593
- /** Stack of (groupId, indent) — the group at the bottom is the open one. */
594
- type GroupFrame = { groupId: string; indent: number };
595
- const groupStack: GroupFrame[] = [];
596
- const currentGroupId = (): string | undefined =>
597
- groupStack.length > 0
598
- ? // In-bounds by length check.
599
- groupStack[groupStack.length - 1]!.groupId
600
- : undefined;
601
-
602
- /** Tracks the most recent activity declaration line (for `-> dest` source). */
603
- let currentSourceName: string | null = null;
604
- /** Indent of currentSourceName — used to pop on dedent. */
605
- let currentSourceIndent = -1;
606
- /**
607
- * The declaration site backing `currentSourceName` — the target for
608
- * indented `key: value` metadata lines (§1.4.2) that appear beneath an
609
- * activity, intermixed with its `-> dest` arrows.
610
- */
611
- let currentSourceSite: DeclarationSite | null = null;
612
-
613
- let pastFirstLine = false;
614
-
615
- for (let i = 0; i < lines.length; i++) {
616
- // In-bounds by loop guard.
617
- const rawLine = lines[i]!;
618
- const lineNumber = i + 1;
619
- const trimmed = stripTrailingComment(rawLine).trim();
620
- if (!trimmed) continue;
621
- if (trimmed.startsWith('#') || trimmed.startsWith('//')) continue;
622
-
623
- const indent = measureIndent(rawLine);
624
-
625
- // Pop any group frames whose indent ≥ this line's indent (block closes).
626
- while (groupStack.length > 0) {
627
- // In-bounds by length check.
628
- const top = groupStack[groupStack.length - 1]!;
629
- if (indent <= top.indent) groupStack.pop();
630
- else break;
631
- }
632
- // Ditto for current source: indented arrow lines (`-> dest` or
633
- // `-LABEL-> dest`) must be deeper than the source.
634
- if (
635
- currentSourceIndent >= 0 &&
636
- indent <= currentSourceIndent &&
637
- !trimmed.startsWith('-')
638
- ) {
639
- currentSourceName = null;
640
- currentSourceIndent = -1;
641
- currentSourceSite = null;
642
- }
643
-
644
- // ── First line: `pert [title]` (chart-type declaration).
645
- if (!pastFirstLine) {
646
- pastFirstLine = true;
647
- const tokens = trimmed.split(/\s+/);
648
- // In-bounds: split always returns at least one element.
649
- const head = tokens[0]!.toLowerCase();
650
- if (head === 'pert') {
651
- if (tokens.length > 1) title = tokens.slice(1).join(' ');
652
- continue;
653
- }
654
- // No explicit `pert` line — fall through; the diagram may be
655
- // inferred via `looksLikePert`. We don't error here; the dispatch
656
- // layer is responsible for routing.
657
- }
658
-
659
- // ── Tag-block phase. `tag Priority as p\n High red\n Low green`
660
- // lives BEFORE diagram content; once any group / activity / arrow
661
- // is seen, `contentStarted` flips and further `tag …` headings
662
- // emit an error.
663
- if (!contentStarted) {
664
- const tagBlockMatch = matchTagBlockHeading(trimmed);
665
- if (tagBlockMatch) {
666
- currentTagGroup = {
667
- name: tagBlockMatch.name,
668
- ...(tagBlockMatch.alias !== undefined && {
669
- alias: tagBlockMatch.alias,
670
- }),
671
- entries: [],
672
- lineNumber,
673
- };
674
- if (tagBlockMatch.alias) {
675
- metaAliasMap.set(
676
- tagBlockMatch.alias.toLowerCase(),
677
- tagAttrKey(tagBlockMatch.name)
678
- );
679
- }
680
- metaAliasMap.set(
681
- normalizeName(tagBlockMatch.name),
682
- tagAttrKey(tagBlockMatch.name)
683
- );
684
- tagGroups.push(currentTagGroup);
685
- // Inline values (e.g. `tag Priority as p Low green, High red`).
686
- if (tagBlockMatch.inlineValues) {
687
- for (const raw of tagBlockMatch.inlineValues) {
688
- const { text, isDefault } = stripDefaultModifier(raw);
689
- const { label, color } = extractColor(
690
- text,
691
- parseOpts.palette,
692
- diagnostics,
693
- lineNumber
694
- );
695
- // Bare value (no explicit color) → keep it; finalized below.
696
- if (isDefault || currentTagGroup.entries.length === 0) {
697
- currentTagGroup.defaultValue = label;
698
- }
699
- currentTagGroup.entries.push({
700
- value: label,
701
- color: color ?? AUTO_TAG_COLOR_SENTINEL,
702
- lineNumber,
703
- });
704
- }
705
- }
706
- continue;
707
- }
708
- // Indented `Value color` entry under an open tag block.
709
- if (currentTagGroup && indent > 0) {
710
- const { text, isDefault } = stripDefaultModifier(trimmed);
711
- const { label, color } = extractColor(
712
- text,
713
- parseOpts.palette,
714
- diagnostics,
715
- lineNumber
716
- );
717
- // Bare value (no explicit color) → keep it; finalized below.
718
- if (isDefault || currentTagGroup.entries.length === 0) {
719
- currentTagGroup.defaultValue = label;
720
- }
721
- currentTagGroup.entries.push({
722
- value: label,
723
- color: color ?? AUTO_TAG_COLOR_SENTINEL,
724
- lineNumber,
725
- });
726
- continue;
727
- }
728
- // Any other line at indent 0 closes the tag block (and content phase begins).
729
- currentTagGroup = null;
730
- } else if (matchTagBlockHeading(trimmed)) {
731
- // `tag …` after content has started — must live at the top of the file.
732
- error(
733
- lineNumber,
734
- `'tag' declarations must appear before activities and groups.`
735
- );
736
- continue;
737
- }
738
-
739
- // ── Group header: `[group-name] collapsed: true` or `[group-name] c: Bosun`.
740
- const groupMatch = trimmed.match(GROUP_HEADER_RE);
741
- if (groupMatch) {
742
- contentStarted = true;
743
- currentTagGroup = null;
744
- const name = groupMatch[1]!.trim();
745
- const tail = (groupMatch[2] ?? '').trim();
746
- // Parse the tail as §1.4 metadata. tail is `k: v, k: v` shape.
747
- const meta = tail ? parsePipeMetadata(tail, metaAliasMap) : {};
748
- const id = `[${normalizeName(name)}]`;
749
- const tags: Record<string, string> = {};
750
- for (const [k, v] of Object.entries(meta)) {
751
- if (!RESERVED_PIPE_KEYS.has(k)) tags[k] = v;
752
- }
753
- groups.push({
754
- id,
755
- name,
756
- activityIds: [],
757
- collapsed: meta['collapsed'] === 'true',
758
- lineNumber,
759
- ...(Object.keys(tags).length > 0 && { tags }),
760
- });
761
- groupStack.push({ groupId: id, indent });
762
- currentSourceName = null;
763
- currentSourceIndent = -1;
764
- currentSourceSite = null;
765
- continue;
766
- }
767
-
768
- // ── Indented arrow line: `-> dest` or `-LABEL-> dest` where LABEL
769
- // is `[TYPE][±LAG]` (e.g. `SS`, `2d`, `SS+2d`, `FF-1d`). Type
770
- // defaults to FS, lag to zero.
771
- if (trimmed.startsWith('-')) {
772
- contentStarted = true;
773
- currentTagGroup = null;
774
- let arrowTargetText: string;
775
- let edgeType: EdgeType = 'FS';
776
- let edgeLag: Duration | null = null;
777
-
778
- const bareMatch = trimmed.match(ARROW_RE);
779
- if (bareMatch) {
780
- // In-bounds by regex match: group 1 is guaranteed present.
781
- arrowTargetText = bareMatch[1]!;
782
- } else {
783
- const labeledMatch = trimmed.match(LABELED_ARROW_RE);
784
- if (!labeledMatch) {
785
- error(lineNumber, `Malformed arrow line: '${trimmed}'.`);
786
- continue;
787
- }
788
- // In-bounds by regex match: groups 1 and 2 are guaranteed present.
789
- const parsedLabel = parseEdgeLabel(labeledMatch[1]!, options.timeUnit);
790
- if (!parsedLabel) {
791
- error(
792
- lineNumber,
793
- `Invalid edge label '${labeledMatch[1]!}' in '${trimmed}'. ` +
794
- `Expected a dependency type (FS/SS/FF/SF) and/or lag (e.g. '+2d', '-1d').`
795
- );
796
- continue;
797
- }
798
- arrowTargetText = labeledMatch[2]!;
799
- edgeType = parsedLabel.type;
800
- edgeLag = parsedLabel.lag;
801
- }
802
-
803
- if (!currentSourceName) {
804
- error(
805
- lineNumber,
806
- `'-> ${arrowTargetText}' has no source — declare an activity above on a non-indented line.`
807
- );
808
- continue;
809
- }
810
- const tok = tokenizeActivityLine(
811
- arrowTargetText,
812
- diagnostics,
813
- lineNumber,
814
- metaAliasMap
815
- );
816
- const targetName = tok.name;
817
- if (!targetName) {
818
- error(lineNumber, `'-> …' is missing a target name.`);
819
- continue;
820
- }
821
-
822
- // Arrow lines are pure references. Durations, alias declarations,
823
- // and pipe metadata must live on a non-indented source-line so
824
- // readers know exactly where to look for an activity's attributes.
825
- if (
826
- tok.durationTokens.length > 0 ||
827
- tok.alias !== undefined ||
828
- tok.pipeMetadata !== undefined
829
- ) {
830
- const extras: string[] = [];
831
- if (tok.durationTokens.length > 0) {
832
- extras.push(`'${tok.durationTokens.join(' ')}'`);
833
- }
834
- if (tok.alias !== undefined) extras.push(`'as ${tok.alias}'`);
835
- if (tok.pipeMetadata !== undefined) {
836
- extras.push(`'${tok.pipeMetadata}'`);
837
- }
838
- const durHint =
839
- tok.durationTokens.length > 0
840
- ? ` ${tok.durationTokens.join(' ')}`
841
- : '';
842
- error(
843
- lineNumber,
844
- `Inline forward-declaration not allowed on '-> ${arrowTargetText}' ` +
845
- `(${extras.join(', ')}). ` +
846
- `Move attributes to a source-line: '${targetName}${durHint}' ` +
847
- `then '-> ${targetName}'.`
848
- );
849
- continue;
850
- }
851
-
852
- references.push({
853
- sourceName: currentSourceName,
854
- sourceLineNumber: -1, // resolved in Pass 2 from declarations
855
- targetName,
856
- targetLineNumber: lineNumber,
857
- type: edgeType,
858
- lag: edgeLag,
859
- });
860
- continue;
861
- }
862
-
863
- // ── Indented metadata line (§1.4.2): `key: value` attached to the
864
- // activity declared above, intermixable with its `-> dest` arrows.
865
- // Only keys in the reserved registry (`confidence`, `collapsed`) or a
866
- // declared tag alias dispatch here; everything else falls through to
867
- // the activity-declaration grammar below. Reaching this point with a
868
- // live source guarantees the line is indented deeper than it (the
869
- // dedent guard above already cleared shallower lines).
870
- if (currentSourceSite) {
871
- const metaMatch = trimmed.match(INDENTED_META_RE);
872
- if (metaMatch) {
873
- const rawKey = metaMatch[1]!;
874
- const key = rawKey.toLowerCase();
875
- const resolvedKey = metaAliasMap.get(key) ?? key;
876
- if (RESERVED_PIPE_KEYS.has(resolvedKey) || metaAliasMap.has(key)) {
877
- contentStarted = true;
878
- currentTagGroup = null;
879
- const entry = `${rawKey}: ${metaMatch[2]!.trim()}`;
880
- currentSourceSite.pipeMetadata = currentSourceSite.pipeMetadata
881
- ? `${currentSourceSite.pipeMetadata}, ${entry}`
882
- : entry;
883
- continue;
884
- }
885
- }
886
- }
887
-
888
- // ── Diagram-level directives (bare keyword + optional value).
889
- {
890
- const firstSpace = trimmed.indexOf(' ');
891
- const head =
892
- firstSpace === -1
893
- ? trimmed.toLowerCase()
894
- : trimmed.slice(0, firstSpace).toLowerCase();
895
- if (DIRECTIVE_KEYS.has(head)) {
896
- const value =
897
- firstSpace === -1 ? '' : trimmed.slice(firstSpace + 1).trim();
898
- if (head === 'start-date' || head === 'end-date') {
899
- // Closure-aware path: collision diagnostic names the first
900
- // anchor's line so the user knows which directive to remove.
901
- const hadAnchor = options.anchor !== null;
902
- applyAnchorDirective(
903
- head as 'start-date' | 'end-date',
904
- value,
905
- lineNumber,
906
- options,
907
- diagnostics,
908
- firstAnchorLine,
909
- firstAnchorKey
910
- );
911
- if (!hadAnchor && options.anchor !== null) {
912
- firstAnchorLine = lineNumber;
913
- firstAnchorKey = head as 'start-date' | 'end-date';
914
- } else if (hadAnchor && options.anchor === null) {
915
- // Both-anchors collision cleared the prior anchor — clear the
916
- // tracker too so a third directive (if any) sees a clean slate.
917
- firstAnchorLine = null;
918
- firstAnchorKey = null;
919
- }
920
- continue;
921
- }
922
- applyDirective(head, value, lineNumber, options, error, warn);
923
- continue;
924
- }
925
- }
926
-
927
- // ── Near-directive typos: `confidence medium` (meaning
928
- // `default-confidence medium`), `start 2026-06-01`, `end YYYY-MM-DD`,
929
- // `time w`. Without this check the line was silently parsed as a
930
- // TBD activity, which propagates `?` through every corner cell in
931
- // backward-anchor mode with no actionable error to fix.
932
- {
933
- const firstSpace = trimmed.indexOf(' ');
934
- if (firstSpace > 0) {
935
- const head = trimmed.slice(0, firstSpace).toLowerCase();
936
- const value = trimmed.slice(firstSpace + 1).trim();
937
- const hint = NEAR_DIRECTIVE_HINTS.find((h) => h.stem === head);
938
- if (hint?.matches.test(value)) {
939
- diagnostics.push(
940
- emit(PERT_DX.NEAR_DIRECTIVE, lineNumber, {
941
- head,
942
- canonical: hint.canonical,
943
- })
944
- );
945
- continue;
946
- }
947
- }
948
- }
949
-
950
- // ── Reject the `milestone` keyword outright — zero-duration
951
- // activities (`<name> 0`) cover the use case.
952
- if (/^milestone(\s|$)/i.test(trimmed)) {
953
- error(lineNumber, `Unknown keyword 'milestone'.`);
954
- continue;
955
- }
956
-
957
- // ── Activity declaration: `<name> <durs?> [as <id>] [| meta]`.
958
- {
959
- const tok = tokenizeActivityLine(
960
- trimmed,
961
- diagnostics,
962
- lineNumber,
963
- metaAliasMap
964
- );
965
- if (!tok.name) {
966
- error(lineNumber, `Empty activity name: '${trimmed}'.`);
967
- continue;
968
- }
969
- contentStarted = true;
970
- currentTagGroup = null;
971
-
972
- // Bare source-line referencing an existing alias: don't register a
973
- // duplicate activity — just point currentSource at the canonical
974
- // name so subsequent `-> dest` lines attach correctly.
975
- const isBareSource =
976
- tok.durationTokens.length === 0 &&
977
- tok.alias === undefined &&
978
- tok.pipeMetadata === undefined;
979
- if (isBareSource && declarationsByAlias.has(tok.name)) {
980
- const existing = declarationsByAlias.get(tok.name)!;
981
- currentSourceName = existing.name;
982
- currentSourceIndent = indent;
983
- currentSourceSite = existing;
984
- continue;
985
- }
986
-
987
- const groupHint = currentGroupId();
988
- const site: DeclarationSite = {
989
- name: tok.name,
990
- ...(tok.alias !== undefined && { alias: tok.alias }),
991
- durationTokens: tok.durationTokens,
992
- ...(tok.pipeMetadata !== undefined && {
993
- pipeMetadata: tok.pipeMetadata,
994
- }),
995
- lineNumber,
996
- ...(groupHint !== undefined && { groupHint }),
997
- };
998
- registerSite(site);
999
- currentSourceName = tok.name;
1000
- currentSourceIndent = indent;
1001
- currentSourceSite = site;
1002
- continue;
1003
- }
1004
- }
1005
-
1006
- function registerSite(site: DeclarationSite): void {
1007
- allDeclarations.push(site);
1008
- const key = normalizeName(site.name);
1009
- const bucket = sitesByName.get(key);
1010
- if (bucket) bucket.push(site);
1011
- else sitesByName.set(key, [site]);
1012
- if (!declarationsByName.has(key)) {
1013
- declarationsByName.set(key, site);
1014
- }
1015
- if (site.alias && !declarationsByAlias.has(site.alias)) {
1016
- declarationsByAlias.set(site.alias, site);
1017
- }
1018
- }
1019
-
1020
- // ── Anchor + time-unit cross-checks ─────────────────────
1021
- // Order-independent: directives can appear in any order; both must
1022
- // be parsed before this fires. Render-blocking false; the chart
1023
- // still renders with whatever rounding the date display imposes.
1024
- if (options.anchor !== null) {
1025
- if (options.timeUnit === 'bd') {
1026
- diagnostics.push(emit(PERT_DX.BD_WITH_ANCHOR, 0));
1027
- } else if (options.timeUnit === 'min' || options.timeUnit === 'h') {
1028
- diagnostics.push(emit(PERT_DX.SUBDAY_WITH_ANCHOR, 0));
1029
- }
1030
- }
1031
-
1032
- // ── Pass 2 ──────────────────────────────────────────────
1033
- // Resolve, validate, classify, build edges + activities.
1034
-
1035
- // 2a) Conflict detection across declaration sites of the same name.
1036
- for (const [key, sites] of sitesByName) {
1037
- if (sites.length < 2) continue;
1038
- // Collect explicit-duration sites; tokens-equal across all → silent OK.
1039
- const explicit = sites.filter((s) => s.durationTokens.length > 0);
1040
- if (explicit.length < 2) continue;
1041
- const fingerprints = new Set(
1042
- explicit.map((s) => s.durationTokens.join(' '))
1043
- );
1044
- if (fingerprints.size > 1) {
1045
- const lineList = explicit
1046
- .map((s) => `line ${s.lineNumber} (${s.durationTokens.join(' ')})`)
1047
- .join(' and ');
1048
- // Anchor the diagnostic on the first site so navigation lands somewhere stable.
1049
- // In-bounds: explicit.length >= 2 above.
1050
- error(
1051
- explicit[0]!.lineNumber,
1052
- `Conflicting estimates for "${declarationsByName.get(key)!.name}" on ${lineList}. Keep one declaration site.`
1053
- );
1054
- }
1055
- }
1056
-
1057
- // 2b) Build alias → canonical id table.
1058
- // Canonical id = normalizeName(decl.name). Aliases are alternate lookup
1059
- // keys for resolution; an aliased activity and a bare-name source line
1060
- // pointing at the same activity must collapse to one canonical id.
1061
- const idMap: Record<string, string> = {};
1062
- for (const [, decl] of declarationsByName) {
1063
- const id = canonicalIdFromDeclaration(decl);
1064
- idMap[normalizeName(decl.name)] = id;
1065
- idMap[decl.name.toLowerCase()] = id;
1066
- }
1067
- for (const [aliasLiteral, decl] of declarationsByAlias) {
1068
- idMap[aliasLiteral] = canonicalIdFromDeclaration(decl);
1069
- }
1070
-
1071
- function canonicalIdFromDeclaration(decl: DeclarationSite): string {
1072
- return normalizeName(decl.name);
1073
- }
1074
-
1075
- function resolveTargetId(token: string, lineNumber: number): string | null {
1076
- const trimmed = token.trim();
1077
- // Try alias first (case-sensitive — aliases are short tokens).
1078
- if (declarationsByAlias.has(trimmed)) {
1079
- return canonicalIdFromDeclaration(declarationsByAlias.get(trimmed)!);
1080
- }
1081
- const norm = normalizeName(trimmed);
1082
- if (declarationsByName.has(norm)) {
1083
- return canonicalIdFromDeclaration(declarationsByName.get(norm)!);
1084
- }
1085
- const candidates = [
1086
- ...declarationsByAlias.keys(),
1087
- ...[...declarationsByName.values()].map((d) => d.name),
1088
- ];
1089
- const hint = suggest(trimmed, candidates);
1090
- error(
1091
- lineNumber,
1092
- `Unknown activity '${trimmed}'.${hint ? ` ${hint}` : ''}`
1093
- );
1094
- return null;
1095
- }
1096
-
1097
- // 2c) Materialize activities from declarations (one per canonical name).
1098
- // The "best" declaration site for an activity is the one that supplies
1099
- // duration tokens (or the alias) — a bare-name source line never wins
1100
- // over an explicit declaration.
1101
- const bestDeclByName = new Map<string, DeclarationSite>();
1102
- for (const decl of allDeclarations) {
1103
- const key = normalizeName(decl.name);
1104
- const existing = bestDeclByName.get(key);
1105
- if (!existing) {
1106
- bestDeclByName.set(key, decl);
1107
- continue;
1108
- }
1109
- const existingHasInfo =
1110
- existing.durationTokens.length > 0 || existing.alias !== undefined;
1111
- const incomingHasInfo =
1112
- decl.durationTokens.length > 0 || decl.alias !== undefined;
1113
- if (!existingHasInfo && incomingHasInfo) {
1114
- bestDeclByName.set(key, decl);
1115
- }
1116
- }
1117
-
1118
- const activitiesById = new Map<string, Writable<PertActivity>>();
1119
- for (const [id, decl] of bestDeclByName) {
1120
- const estimate = buildEstimate(
1121
- decl.durationTokens,
1122
- options.timeUnit,
1123
- (msg) => error(decl.lineNumber, msg)
1124
- );
1125
- const meta = decl.pipeMetadata
1126
- ? parsePipeMetadata(decl.pipeMetadata, metaAliasMap)
1127
- : {};
1128
- // Split reserved keys (`confidence`) from tag metadata.
1129
- const tags: Record<string, string> = {};
1130
- for (const [k, v] of Object.entries(meta)) {
1131
- if (!RESERVED_PIPE_KEYS.has(k)) tags[k] = v;
1132
- }
1133
- // Zero-duration activities (O = M = P = 0) are flagged as milestones
1134
- // so the renderer can mark them with the diamond glyph.
1135
- const isMilestone =
1136
- estimate !== null &&
1137
- estimate.o.amount === 0 &&
1138
- estimate.m.amount === 0 &&
1139
- estimate.p.amount === 0;
1140
- activitiesById.set(id, {
1141
- id,
1142
- name: decl.name,
1143
- ...(decl.alias !== undefined && { alias: decl.alias }),
1144
- duration: estimate,
1145
- ...(meta['confidence'] && { confidence: meta['confidence'] }),
1146
- ...(decl.groupHint !== undefined && { groupId: decl.groupHint }),
1147
- lineNumber: decl.lineNumber,
1148
- isMilestone,
1149
- ...(Object.keys(tags).length > 0 && { tags }),
1150
- });
1151
- }
1152
-
1153
- // 2d) Build edges from references; resolve sources + targets.
1154
- const edges: PertEdge[] = [];
1155
- for (const ref of references) {
1156
- const sourceId = resolveTargetId(ref.sourceName, ref.targetLineNumber);
1157
- const targetId = resolveTargetId(ref.targetName, ref.targetLineNumber);
1158
- if (!sourceId || !targetId) continue;
1159
- edges.push({
1160
- source: sourceId,
1161
- target: targetId,
1162
- lineNumber: ref.targetLineNumber,
1163
- type: ref.type,
1164
- lag: ref.lag,
1165
- });
1166
- }
1167
-
1168
- // 2e) Populate group memberships + classify hammock vs cluster.
1169
- for (const group of groups) {
1170
- group.activityIds = [...activitiesById.values()]
1171
- .filter((a) => a.groupId === group.id)
1172
- .map((a) => a.id);
1173
- group.classification = classifyGroup(group, edges);
1174
- }
1175
-
1176
- // 2f) Final ordering — preserve source order from `allDeclarations`.
1177
- const seen = new Set<string>();
1178
- const activities: Writable<PertActivity>[] = [];
1179
- for (const decl of allDeclarations) {
1180
- const id = canonicalIdFromDeclaration(decl);
1181
- if (seen.has(id)) continue;
1182
- seen.add(id);
1183
- const a = activitiesById.get(id);
1184
- if (a) activities.push(a);
1185
- }
1186
-
1187
- // Resolve auto-derived defaults for `trials` and `seed`. The directive
1188
- // sets the value verbatim; -1 sentinel means "user didn't author it".
1189
- if (options.trials === -1) {
1190
- options.trials = deriveTrials(activities.length);
1191
- }
1192
- if (options.seed === -1) {
1193
- const seedSource =
1194
- title ||
1195
- activities
1196
- .map((a) => a.name)
1197
- .sort()
1198
- .join('\n') ||
1199
- 'pert';
1200
- options.seed = deriveSeed(seedSource);
1201
- }
1202
-
1203
- // Sprint-mode detection (mirrors Gantt). `time-unit s` → auto;
1204
- // any explicit `sprint-*` directive → explicit (wins over auto).
1205
- // Apply sensible defaults when sprint mode is active.
1206
- const hasSprintOption =
1207
- options.sprintLength !== null ||
1208
- options.sprintNumber !== null ||
1209
- options.sprintStart !== null;
1210
- const hasSprintUnit =
1211
- options.timeUnit === 's' ||
1212
- activities.some(
1213
- (a) =>
1214
- a.duration !== null &&
1215
- (a.duration.o.unit === 's' ||
1216
- a.duration.m.unit === 's' ||
1217
- a.duration.p.unit === 's')
1218
- );
1219
- if (hasSprintOption) {
1220
- options.sprintMode = 'explicit';
1221
- } else if (hasSprintUnit) {
1222
- options.sprintMode = 'auto';
1223
- }
1224
- if (options.sprintMode) {
1225
- if (!options.sprintLength) {
1226
- options.sprintLength = { amount: 2, unit: 'w' };
1227
- }
1228
- if (options.sprintNumber === null) {
1229
- options.sprintNumber = 1;
1230
- }
1231
- }
1232
-
1233
- // Assign palette colors to bare (colorless) tag values.
1234
- finalizeAutoTagColors(tagGroups as Writable<TagGroup>[], parseOpts.palette);
1235
-
1236
- // ── Tag-group post-validation + default injection ───────
1237
- if (tagGroups.length > 0) {
1238
- validateTagGroupNames(
1239
- tagGroups.map((g) => ({
1240
- name: g.name,
1241
- alias: g.alias ?? null,
1242
- lineNumber: g.lineNumber,
1243
- })),
1244
- warn,
1245
- error
1246
- );
1247
- const ensureTags = (
1248
- entity: Writable<PertActivity> | Writable<PertGroup>
1249
- ): { metadata: Record<string, string>; lineNumber: number } => {
1250
- if (!entity.tags) entity.tags = {};
1251
- return {
1252
- metadata: entity.tags as Record<string, string>,
1253
- lineNumber: entity.lineNumber,
1254
- };
1255
- };
1256
- const activityShells = activities.map(ensureTags);
1257
- const groupShells = groups.map(ensureTags);
1258
- validateTagValues(
1259
- [...activityShells, ...groupShells],
1260
- tagGroups,
1261
- warn,
1262
- suggest
1263
- );
1264
- // Default-tag injection: only activities (containers stay structural).
1265
- injectDefaultTagMetadata(activityShells, tagGroups);
1266
- // Strip empty tags maps for cleaner downstream consumption.
1267
- for (const a of activities) {
1268
- if (a.tags && Object.keys(a.tags).length === 0) delete a.tags;
1269
- }
1270
- for (const g of groups) {
1271
- if (g.tags && Object.keys(g.tags).length === 0) delete g.tags;
1272
- }
1273
- }
1274
-
1275
- const firstFatal = diagnostics.find((d) => d.severity === 'error');
1276
- return {
1277
- title,
1278
- options,
1279
- activities,
1280
- edges,
1281
- groups,
1282
- tagGroups,
1283
- idMap,
1284
- diagnostics,
1285
- error: firstFatal ? firstFatal.message : null,
1286
- };
1287
- }
1288
-
1289
- // ============================================================
1290
- // Helpers continued
1291
- // ============================================================
1292
-
1293
- function applyDirective(
1294
- key: string,
1295
- value: string,
1296
- lineNumber: number,
1297
- options: PertOptions,
1298
- error: (line: number, msg: string, code?: string) => void,
1299
- warn: (line: number, msg: string, code?: string) => void
1300
- ): void {
1301
- switch (key) {
1302
- case 'time-unit': {
1303
- const valid: DurationUnit[] = [
1304
- 'min',
1305
- 'h',
1306
- 'd',
1307
- 'bd',
1308
- 'w',
1309
- 'm',
1310
- 'q',
1311
- 'y',
1312
- 's',
1313
- ];
1314
- if (!(valid as string[]).includes(value)) {
1315
- error(
1316
- lineNumber,
1317
- `Unknown time-unit '${value}'. Expected one of ${valid.join(', ')}.`
1318
- );
1319
- return;
1320
- }
1321
- options.timeUnit = value as DurationUnit;
1322
- return;
1323
- }
1324
- case 'default-confidence': {
1325
- // Verbatim — `resolveConfidence` validates at analyzer time.
1326
- options.confidence = value || 'medium';
1327
- return;
1328
- }
1329
- case 'no-title': {
1330
- // Bare boolean directive — suppresses the diagram banner title.
1331
- options.noTitle = true;
1332
- return;
1333
- }
1334
- case 'solid-fill': {
1335
- // Bare boolean directive — render card fills at full saturation.
1336
- options.solidFill = true;
1337
- return;
1338
- }
1339
- case 'active-tag': {
1340
- // Selects which declared tag group drives node fill.
1341
- // `none` (case-insensitive) suppresses coloring entirely;
1342
- // an unrecognized name resolves to no color at render time.
1343
- // Unset → first declared group auto-activates.
1344
- options.activeTag = value;
1345
- return;
1346
- }
1347
- case 'sprint-length': {
1348
- const dur = parseDuration(value);
1349
- if (!dur) {
1350
- warn(
1351
- lineNumber,
1352
- `Invalid sprint-length value: "${value}". Expected a duration like "2w" or "10d".`
1353
- );
1354
- } else if (dur.unit !== 'd' && dur.unit !== 'w') {
1355
- warn(
1356
- lineNumber,
1357
- `sprint-length only accepts "d" or "w" units, got "${dur.unit}".`
1358
- );
1359
- } else if (dur.amount <= 0) {
1360
- warn(lineNumber, `sprint-length must be greater than 0.`);
1361
- } else if (!Number.isInteger(dur.amount * (dur.unit === 'w' ? 7 : 1))) {
1362
- warn(
1363
- lineNumber,
1364
- `sprint-length must resolve to a whole number of days.`
1365
- );
1366
- } else {
1367
- options.sprintLength = dur;
1368
- }
1369
- return;
1370
- }
1371
- case 'sprint-number': {
1372
- const n = Number(value);
1373
- if (!Number.isFinite(n) || !Number.isInteger(n) || n <= 0) {
1374
- warn(
1375
- lineNumber,
1376
- `sprint-number must be a positive integer, got "${value}".`
1377
- );
1378
- } else {
1379
- options.sprintNumber = n;
1380
- }
1381
- return;
1382
- }
1383
- case 'sprint-start': {
1384
- if (!/^\d{4}-\d{2}-\d{2}$/.test(value)) {
1385
- warn(
1386
- lineNumber,
1387
- `sprint-start requires a full date (YYYY-MM-DD), got "${value}".`
1388
- );
1389
- } else if (Number.isNaN(new Date(value + 'T00:00:00').getTime())) {
1390
- warn(lineNumber, `sprint-start is not a valid date: "${value}".`);
1391
- } else {
1392
- options.sprintStart = value;
1393
- }
1394
- return;
1395
- }
1396
- case 'direction': {
1397
- const upper = value.toUpperCase();
1398
- if (upper !== 'LR' && upper !== 'TB') {
1399
- error(lineNumber, `Unknown direction '${value}'. Expected LR or TB.`);
1400
- return;
1401
- }
1402
- options.direction = upper as PertDirection;
1403
- return;
1404
- }
1405
- case 'node-detail': {
1406
- if (value !== 'compact' && value !== 'full') {
1407
- error(
1408
- lineNumber,
1409
- `Unknown node-detail '${value}'. Expected compact or full.`
1410
- );
1411
- return;
1412
- }
1413
- options.nodeDetail = value as NodeDetail;
1414
- return;
1415
- }
1416
- case 'no-analysis': {
1417
- // Bare boolean directive — suppresses the analysis layer (tornado
1418
- // + S-curve), which otherwise renders by default whenever Monte
1419
- // Carlo ran. Mirrors `no-title`. An explicit `viewState.an` (app
1420
- // toggle / share link) overrides it at render time.
1421
- options.noAnalysis = true;
1422
- return;
1423
- }
1424
- case 'trials': {
1425
- const n = parseInt(value, 10);
1426
- if (!Number.isFinite(n) || n < 1) {
1427
- error(
1428
- lineNumber,
1429
- `'trials' expects a positive integer; got '${value}'.`
1430
- );
1431
- return;
1432
- }
1433
- options.trials = n;
1434
- return;
1435
- }
1436
- case 'seed': {
1437
- const n = parseInt(value, 10);
1438
- if (!Number.isFinite(n)) {
1439
- error(lineNumber, `'seed' expects an integer; got '${value}'.`);
1440
- return;
1441
- }
1442
- options.seed = n;
1443
- return;
1444
- }
1445
- case 'scrubber-trials': {
1446
- const n = parseInt(value, 10);
1447
- if (!Number.isFinite(n) || n < 1) {
1448
- error(
1449
- lineNumber,
1450
- `'scrubber-trials' expects a positive integer; got '${value}'.`
1451
- );
1452
- return;
1453
- }
1454
- if (n < 100) {
1455
- warn(
1456
- lineNumber,
1457
- `'scrubber-trials ${n}' is below the floor of 100; analyzer will still degrade if needed.`
1458
- );
1459
- }
1460
- options.scrubberTrials = n;
1461
- return;
1462
- }
1463
- case 'start-date':
1464
- case 'end-date': {
1465
- // Anchor directives need closure state (first-anchor line/key) to
1466
- // produce a useful collision diagnostic. They are intercepted in
1467
- // the parse loop before this dispatch fires; reaching this case
1468
- // would be a bug.
1469
- error(
1470
- lineNumber,
1471
- `internal error: anchor directive '${key}' reached generic dispatch`
1472
- );
1473
- return;
1474
- }
1475
- }
1476
- }
1477
-
1478
- /**
1479
- * Validate and apply a `start-date` / `end-date` directive. Mutual
1480
- * exclusion enforced via clear-on-collision: when a second anchor of
1481
- * either kind arrives we emit `E_PERT_BOTH_ANCHORS` and reset
1482
- * `options.anchor` to `null` so downstream code never sees partial state.
1483
- */
1484
- function applyAnchorDirective(
1485
- key: 'start-date' | 'end-date',
1486
- value: string,
1487
- lineNumber: number,
1488
- options: PertOptions,
1489
- diagnostics: DgmoError[],
1490
- firstAnchorLine: number | null,
1491
- firstAnchorKey: 'start-date' | 'end-date' | null
1492
- ): void {
1493
- // Both-anchors collision (per F4 — clear-on-collision policy):
1494
- // if the user already authored an anchor of either kind, emit error
1495
- // AND drop the prior anchor so the parsed result has no ambiguous
1496
- // partial state. The user must fix the source.
1497
- if (options.anchor !== null) {
1498
- diagnostics.push(
1499
- emit(PERT_DX.BOTH_ANCHORS, lineNumber, {
1500
- firstAnchorKey,
1501
- firstAnchorLine,
1502
- })
1503
- );
1504
- options.anchor = null;
1505
- return;
1506
- }
1507
-
1508
- const trimmed = value.trim();
1509
- if (trimmed.length === 0) {
1510
- diagnostics.push(
1511
- emit(PERT_DX.INVALID_DATE, lineNumber, { empty: true, key, value })
1512
- );
1513
- return;
1514
- }
1515
-
1516
- // `now` token — only valid for start-date.
1517
- if (trimmed.toLowerCase() === 'now') {
1518
- if (key === 'end-date') {
1519
- diagnostics.push(emit(PERT_DX.END_DATE_NOW, lineNumber));
1520
- return;
1521
- }
1522
- // Resolve `now` from the parse-time today snapshot stored on
1523
- // `options.today` (single source — see parsePert entry).
1524
- options.anchor = { kind: 'forward', date: options.today };
1525
- return;
1526
- }
1527
-
1528
- const parsed = parseLocalISODate(trimmed);
1529
- if (!parsed) {
1530
- diagnostics.push(emit(PERT_DX.INVALID_DATE, lineNumber, { trimmed, key }));
1531
- return;
1532
- }
1533
-
1534
- options.anchor =
1535
- key === 'start-date'
1536
- ? { kind: 'forward', date: trimmed }
1537
- : { kind: 'backward', date: trimmed };
1538
- }
1539
-
1540
- function classifyGroup(
1541
- group: PertGroup,
1542
- edges: PertEdge[]
1543
- ): 'hammock' | 'cluster' {
1544
- const members = new Set(group.activityIds);
1545
- if (members.size === 0) return 'cluster';
1546
-
1547
- const entries = new Set<string>();
1548
- const exits = new Set<string>();
1549
-
1550
- for (const id of members) {
1551
- const incoming = edges.filter((e) => e.target === id);
1552
- const outgoing = edges.filter((e) => e.source === id);
1553
- const hasInsideIn = incoming.some((e) => members.has(e.source));
1554
- const hasOutsideIn = incoming.some((e) => !members.has(e.source));
1555
- const hasInsideOut = outgoing.some((e) => members.has(e.target));
1556
- const hasOutsideOut = outgoing.some((e) => !members.has(e.target));
1557
- if (hasOutsideIn || (!hasInsideIn && incoming.length === 0))
1558
- entries.add(id);
1559
- if (hasOutsideOut || (!hasInsideOut && outgoing.length === 0))
1560
- exits.add(id);
1561
- }
1562
-
1563
- return entries.size === 1 && exits.size === 1 ? 'hammock' : 'cluster';
1564
- }
1565
-
1566
- // ============================================================
1567
- // extractPertSymbols — for editor autocomplete
1568
- // ============================================================
1569
-
1570
- export function extractPertSymbols(docText: string): DiagramSymbols {
1571
- const parsed = parsePert(docText);
1572
- const entities: string[] = [];
1573
- for (const a of parsed.activities) {
1574
- if (!entities.includes(a.name)) entities.push(a.name);
1575
- if (a.alias && !entities.includes(a.alias)) entities.push(a.alias);
1576
- }
1577
- for (const g of parsed.groups) {
1578
- if (!entities.includes(g.name)) entities.push(g.name);
1579
- }
1580
- return {
1581
- kind: 'pert',
1582
- entities,
1583
- };
1584
- }
1585
-
1586
- // ============================================================
1587
- // looksLikePert — content-inference heuristic
1588
- // ============================================================
1589
-
1590
- /**
1591
- * Returns true when content lacks an explicit chart type but reads as a
1592
- * PERT diagram. Per spec § Implementation Decisions: drop the
1593
- * "three-number durations" heuristic (too generic) — require any of:
1594
- * (a) literal `pert` chart-type line (already handled by parseFirstLine)
1595
- * (b) an `analysis monte-carlo` directive
1596
- *
1597
- * This function is for case (b) inference — case (a) is handled upstream.
1598
- */
1599
- export function looksLikePert(content: string): boolean {
1600
- for (const raw of content.split('\n')) {
1601
- const line = raw.trim();
1602
- if (!line || line.startsWith('//') || line.startsWith('#')) continue;
1603
- if (/^analysis\s+monte-carlo\b/i.test(line)) return true;
1604
- }
1605
- return false;
1606
- }