-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcpm-engine.js
More file actions
4445 lines (4162 loc) · 195 KB
/
cpm-engine.js
File metadata and controls
4445 lines (4162 loc) · 195 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// ============================================================================
// CPM Engine — JavaScript Reconstruction
// ----------------------------------------------------------------------------
// Reconstructed 2026-05-09 from two surviving sources after the original
// cpm-engine__11_.js (Tarjan-SCC + claims/salvage + 3 driving-path strategies,
// 226 tests) was lost on Critical Path Partners infra. This file is faithful
// to what we still have on disk; it is NOT a guess at the lost forensic API.
//
// Sources:
// 1. _cpp_common/scripts/cpm.py (443 lines) — production calendar-aware
// engine used by every CPP forensic skill (forensic-delay-analysis,
// time-impact-analysis, claim-workbench, etc.). 997+ tests green.
// 2. cpm-engine-v15.md (12,301 bytes, 339 lines) — Dec 15 2025 extract from
// monte-carlo-v15.html. Lightweight 5-day-calendar engine designed for
// hot-loop Monte Carlo (10k iterations × per-iter CPM).
//
// What this file PROVIDES:
// Section A — date helpers (epoch-offset ordinals, calendar arithmetic)
// Section B — topologicalSort (Kahn's) + tarjanSCC (cycle isolation)
// Section C — computeCPM — calendar-aware Python-equivalent API
// Section D — parseXER + runCPM — v15.md Monte-Carlo-embedded API
// Section E — module/window exports
//
// What this file DOES NOT include (lost from cpm-engine__11_.js):
// - "claims/salvage modes" — original spec lost; do not invent.
// - "3 driving-path strategies" — original spec lost; do not invent.
// Re-add when the spec is recovered. Inventing forensic semantics from
// memory would dress fabrication as reconstruction.
//
// Forward-pass formula table (matches v15.md §Validation Audit):
// FS ES = pred.EF + lag
// SS ES = pred.ES + lag
// FF ES = pred.EF + lag - duration
// SF ES = pred.ES + lag - duration ← v14 fix; was pred.EF
//
// Backward-pass formula table (matches v15.md §Validation Audit):
// FS LF = succ.LS - lag
// SS LS = succ.LS - lag
// FF LF = succ.LF - lag
// SF LS = succ.LF - lag
//
// Calendar-aware variant (Section C) replaces "+ lag" / "- duration" with
// add_work_days / subtract_work_days walks on the activity's calendar; lag
// is scheduled on the SUCCESSOR's calendar per P6 convention.
// ============================================================================
// ============================================================================
// QUICK USAGE GUIDE
// ============================================================================
//
// 1. Basic CPM (calendar-aware, throws on cycles):
//
// const E = require('./cpm-engine.js');
// const result = E.computeCPM(
// [{ code: 'A', duration_days: 5, early_start: '2026-01-05', clndr_id: 'MF' },
// { code: 'B', duration_days: 3, clndr_id: 'MF' }],
// [{ from_code: 'A', to_code: 'B', type: 'FS', lag_days: 0 }],
// { dataDate: '2026-01-05',
// calMap: { MF: { work_days: [1,2,3,4,5], holidays: [] } } }
// );
// // result.nodes[code] = { es, ef, ls, lf, tf, tf_working_days, ff,
// // ff_working_days, driving_predecessor, ... }
// // result.criticalCodesArray, result.topo_order, result.alerts,
// // result.manifest = { engine_version, method_id, computed_at, ... }
//
// 2. Salvage mode (degraded inputs are logged, not thrown):
//
// const r = E.computeCPMSalvaging(activities, relationships, opts);
// // r.salvage_log = [{severity, category, message, details}, ...]
//
// 3. Multiple critical-path strategies (LPM/TFM/MFP) + divergence:
//
// const r = E.computeCPMWithStrategies(activities, relationships,
// { strategies: ['LPM', 'TFM', 'MFP'], tfThreshold: 0,
// mfpField: 'crt_path_num', salvage: false });
// // r.strategy_summary, r.divergence (only_LPM, only_TFM, only_MFP, all_agree)
//
// 4. Time Impact Analysis (fragnet insertion):
//
// const r = E.computeTIA(activities, relationships, fragnets,
// { dataDate, calMap, projectCalendar, mode: 'isolated', salvage: false });
// // r.baseline (full CPM), r.per_fragnet[].impact_days,
// // r.cumulative_days, r.by_liability, r.manifest.methodology
//
// 5. Schedule health auto-grade (SmartPM-comparable A–F):
//
// const health = E.computeScheduleHealth(result, { /* opts */ });
// // health.score (0..100), health.letter ('A'..'F'),
// // health.checks = [{id, name, value, penalty, threshold, passed}, ...]
//
// 6. Kinematic delay dynamics (slip velocity / accel / jerk + breach forecast):
//
// const k = E.computeKinematicDelay(slipSeries, { thresholdDays: 15 });
// // slipSeries = [{window, slip_days}, ...] chronological
// // k.velocity_series, k.acceleration_series, k.jerk_series,
// // k.predicted_threshold_breach = {breached, windows_to_breach, method}
// // Industry first: nobody else has published d²/dt² + d³/dt³ for CPM.
//
// 7. Topology fingerprint hash (copy-detection across XERs):
//
// const h = E.computeTopologyHash(activities, relationships);
// // h.topology_hash = SHA-256 hex over canonical (code, duration, sorted preds).
// // Excludes P6 UIDs / timestamps / names / resources / calendars.
// // Two XERs with identical hashes ARE the same schedule regardless of
// // UID rotation — bid-collusion + retroactive-manipulation signal.
//
// 8. Daubert / FRE 707 disclosure wrapper:
//
// const d = E.buildDaubertDisclosure(result, opts);
// // d.prong_1_tested / prong_2_peer_review / prong_3_error_rate /
// // prong_4_general_acceptance — each with evidence text.
// // d.provenance.input_topology_hash auto-populated when activities/rels
// // supplied via opts. Compliant before FRE 707 final rule lands.
//
// 9. Float-burndown timeline (per-activity TF erosion across snapshots):
//
// const fb = E.computeFloatBurndown(snapshots, { renderHTML: true });
// // snapshots = [computeCPM result, ...] in chronological order.
// // fb.series[code] = [{window, tf, was_critical}, ...]
// // fb.first_zero_crossing[code] = window where TF crossed ≤ 0
// // fb.recovery_events[code] = where TF went back up
// // fb.html = inline SVG chart (no external deps) when renderHTML true.
//
// 10. Multi-jurisdiction statutory holiday calendars:
//
// const cal = E.getJurisdictionCalendar('CA-ON', { from_year: 2026, to_year: 2030 });
// // cal = { work_days: [1,2,3,4,5], holidays: ['2026-01-01', ...] }
// const result = E.computeCPM(activities, rels, {
// dataDate: '2026-01-05',
// calMap: { '1': cal },
// });
// // 66 jurisdictions: CA-FED + 13 provinces/territories, US-FED + 50 states + DC
// // E.getHolidays('CA-ON', 2026, 2030) → sorted deduplicated YYYY-MM-DD strings
// // E.LISTED_JURISDICTIONS → array of all 66 jurisdiction codes
//
// SECTION C ('computeCPM') is calendar-aware and uses epoch-offset day numbers.
// SECTION D ('parseXER' + 'runCPM') is the lightweight Monte-Carlo engine and
// uses RAW DAY ORDINALS from 0 (NOT epoch-offset). DO NOT mix outputs from
// the two engines — they live in different number spaces.
// ============================================================================
'use strict';
// Node.js crypto module for topology hash (E2). Null in browser; browser fallback uses FNV-1a.
const _crypto = (typeof require !== 'undefined') ? (() => { try { return require('crypto'); } catch(e) { return null; } })() : null;
const ENGINE_VERSION = '2.9.2';
// ============================================================================
// SECTION A — Date helpers + calendar arithmetic
// ============================================================================
const EPOCH_YEAR = 2020;
const EPOCH_MONTH = 1; // 1-based
const EPOCH_DAY = 1;
const VALID_REL_TYPES = ['FS', 'SS', 'FF', 'SF'];
// Internally we track integer day offsets from EPOCH (2020-01-01). All public
// num↔date conversions go through this anchor. We avoid Date.UTC(1,...)
// because JS's 2-digit-year quirk silently rewrites year 1 → 1901.
const _EPOCH_MS = Date.UTC(EPOCH_YEAR, EPOCH_MONTH - 1, EPOCH_DAY);
const _MS_PER_DAY = 86400000;
// ── v2.1-C1: MonFri arithmetic fast path ─────────────────────────────────────
//
// For clean MonFri calendars (work_days=[1,2,3,4,5], no holidays), addWorkDays
// and subtractWorkDays are computable in O(1) using the helper below instead of
// the O(n) day-by-day walk. Speedup: ~13× for 5d walks, ~250× for 30d walks,
// ~900× for 120d walks. Larger schedules with long-duration LOE activities
// benefit most (~600k cal-walk iterations per CPM run eliminated on a 10k-act
// MonFri schedule).
//
// Core formula (addWorkDays path):
// fw = (startWeekday + 1) % 7 ← first calendar day we will scan
// advance = _walkFromFirstFw(fw, n) ← O(1) calendar days to consume n wd
// result = startNum + advance
//
// The formula for _walkFromFirstFw(fw, n) decomposes by which weekday fw falls
// on and how many workdays remain before the first Mon-based "full cycle":
//
// fw = Mon(1): walkFromMon(n) directly [Mon..Fri = 5 wd, 5 cal; then +2 skip/+5 for each extra 5 wd]
// fw = Tue(2): partial 4 wd (Tue-Fri, 4 cal), then +2 skip, then walkFromMon(n-4)
// fw = Wed(3): partial 3 wd, then +2 skip, then walkFromMon(n-3)
// fw = Thu(4): partial 2 wd, then +2 skip, then walkFromMon(n-2)
// fw = Fri(5): partial 1 wd, then +2 skip, then walkFromMon(n-1)
// fw = Sat(6): 0 wd, skip 2 (Sat+Sun), then walkFromMon(n)
// fw = Sun(0): 0 wd, skip 1 (Sun), then walkFromMon(n)
//
// walkFromMon(n): n workdays from Mon (inclusive) = n + 2*floor((n-1)/5) cal
// (n=1→1, n=5→5, n=6→8, n=10→12). Verified by regression below.
//
// subtractWorkDays uses the same formula via the verified symmetry:
// walkToEnd(lw, n) = walkFromFirst(backwardMirror[lw], n)
// where backwardMirror = [Sun,Mon,Tue,Wed,Thu,Fri,Sat] → [Sun,Sat,Fri,Thu,Wed,Tue,Mon]
// i.e. bwMirror = [0,6,5,4,3,2,1]
//
// Both paths produce output IDENTICAL to the day-by-day walk for all 1,500
// (start/end, n) pairs in the regression test (30×50 grid each direction).
// Any non-MonFri-clean calendar (custom workdays, holidays) falls back to the
// general walk.
// walkFromMon(n): calendar days to consume n workdays starting from Mon (inclusive).
// Verified formula: n + 2*floor((n-1)/5) for n>=1. n=0 → 0.
function _walkFromMon(n) {
if (n <= 0) return 0;
if (n % 5 === 0) return (n / 5 - 1) * 7 + 5; // avoids -1 edge in (n-1)/5
return Math.floor(n / 5) * 7 + (n % 5);
}
// Calendar days to consume n workdays starting from fw (first day scanned
// forward). fw = (startWeekday + 1) % 7.
function _walkFromFirstFw(fw, n) {
if (n <= 0) return 0;
// fw = Mon: direct
if (fw === 1) return _walkFromMon(n);
// fw = Sat: skip 2 (Sat+Sun), then Mon-based
if (fw === 6) return 2 + _walkFromMon(n);
// fw = Sun: skip 1 (Sun), then Mon-based
if (fw === 0) return 1 + _walkFromMon(n);
// fw = Tue(2)..Fri(5): partial week then +2 skip then Mon-based
// partialWd = 6 - fw (Tue→4, Wed→3, Thu→2, Fri→1)
const partialWd = 6 - fw;
if (n <= partialWd) return n;
return partialWd + 2 + _walkFromMon(n - partialWd);
}
// backwardMirror[lw]: maps end weekday to the equivalent forward-fw for subtractWorkDays.
// Verified: walkToEnd(lw, n) === walkFromFirst(bwMirror[lw], n) for all lw, n.
// [Sun→Sun, Mon→Sat, Tue→Fri, Wed→Thu, Thu→Wed, Fri→Tue, Sat→Mon]
const _BW_MIRROR = [0, 6, 5, 4, 3, 2, 1];
// Returns true when calendarInfo is the clean Mon-Fri case (work_days=[1..5],
// no holidays) where the arithmetic fast path is safe. Any deviation (custom
// workdays, any holiday) falls back to the day-by-day walk.
function _isCleanMonFri(workDays, holidaysSet) {
if (holidaysSet && holidaysSet.size > 0) return false;
if (!workDays || workDays.length !== 5) return false;
const s = new Set(workDays);
return s.has(1) && s.has(2) && s.has(3) && s.has(4) && s.has(5);
}
// ─────────────────────────────────────────────────────────────────────────────
function _msToOffset(ms) {
return Math.round((ms - _EPOCH_MS) / _MS_PER_DAY);
}
function _offsetToDateUTC(offset) {
return new Date(_EPOCH_MS + offset * _MS_PER_DAY);
}
function _pad2(n) { return n < 10 ? '0' + n : '' + n; }
function dateToNum(s) {
// 'YYYY-MM-DD' (or 'YYYY-MM-DD HH:MM') → integer day offset from EPOCH.
if (s === null || s === undefined) return 0;
const str = String(s).trim();
if (!str) return 0;
const head = str.slice(0, 10);
const parts = head.split('-');
if (parts.length !== 3) return 0;
const y = parseInt(parts[0], 10);
const m = parseInt(parts[1], 10);
const d = parseInt(parts[2], 10);
if (!(y > 0) || !(m >= 1 && m <= 12) || !(d >= 1 && d <= 31)) return 0;
return _msToOffset(Date.UTC(y, m - 1, d));
}
function numToDate(n) {
if (!Number.isFinite(n) || n <= 0) return '';
const dt = _offsetToDateUTC(Math.round(n));
return dt.getUTCFullYear() + '-' + _pad2(dt.getUTCMonth() + 1) + '-' + _pad2(dt.getUTCDate());
}
// P6 weekday convention: 0=Sun, 1=Mon, ..., 6=Sat.
// JS Date.getUTCDay(): 0=Sun, 1=Mon, ..., 6=Sat — already P6-aligned.
function _p6WeekdayFromOffset(offset) {
return _offsetToDateUTC(offset).getUTCDay();
}
function _dateStringFromOffset(offset) {
const dt = _offsetToDateUTC(offset);
return dt.getUTCFullYear() + '-' + _pad2(dt.getUTCMonth() + 1) + '-' + _pad2(dt.getUTCDate());
}
function _isWorkDayOffset(offset, workDays, holidaysSet) {
const p6 = _p6WeekdayFromOffset(offset);
if (workDays.indexOf(p6) === -1) return false;
if (!holidaysSet || holidaysSet.size === 0) return true;
return !holidaysSet.has(_dateStringFromOffset(offset));
}
function _resolveCalendar(calendarInfo) {
// v2.1-C2 fast-return: when computeCPM pre-resolves the calMap at the top
// of its run, every calFor(node) call passes an already-resolved struct.
// Skipping new Set(holidays) here eliminates ~125k Set constructions on a
// 25k-activity schedule with a 365-holiday calendar (~1,572ms saved per
// Audit 2026-05-09 OPT-3 measurement).
if (calendarInfo && calendarInfo._resolved) {
return { workDays: calendarInfo.workDays, holidaysSet: calendarInfo.holidaysSet };
}
if (!calendarInfo) {
return { workDays: [1, 2, 3, 4, 5], holidaysSet: null };
}
const wdRaw = calendarInfo.work_days || calendarInfo.workDays;
const hl = calendarInfo.holidays || [];
// Filter to valid P6 weekday indices (0=Sun, ..., 6=Sat). Drops empty
// arrays and impossible values like [7] that would cause the
// addWorkDays/subtractWorkDays loop to never decrement remaining and
// hang. Falls back to MonFri default when no valid days remain.
const wd = (Array.isArray(wdRaw) ? wdRaw : [])
.filter((d) => Number.isInteger(d) && d >= 0 && d <= 6);
return {
workDays: wd.length ? wd : [1, 2, 3, 4, 5],
holidaysSet: new Set(hl),
};
}
// v2.1-C2: Build a parallel calMap where every entry is pre-resolved with
// {_resolved:true, workDays, holidaysSet} so downstream addWorkDays /
// subtractWorkDays calls skip the per-call new Set(holidays) construction.
// The caller's original calMap is NOT mutated; original work_days / holidays
// are preserved on the resolved struct for any downstream introspection.
function _preResolveCalendars(calMap) {
if (!calMap) return calMap;
const out = Object.create(null);
for (const k of Object.keys(calMap)) {
const orig = calMap[k];
if (!orig) { out[k] = orig; continue; }
if (orig._resolved) { out[k] = orig; continue; } // already resolved (re-entry safety)
const wdRaw = orig.work_days || orig.workDays;
const hl = orig.holidays || [];
const wd = (Array.isArray(wdRaw) ? wdRaw : [])
.filter((d) => Number.isInteger(d) && d >= 0 && d <= 6);
out[k] = {
_resolved: true,
workDays: wd.length ? wd : [1, 2, 3, 4, 5],
holidaysSet: new Set(hl),
// Preserve originals so callers that inspect work_days / holidays still work.
work_days: orig.work_days,
holidays: orig.holidays,
};
}
return out;
}
function addWorkDays(startNum, nDays, calendarInfo) {
// startNum: epoch-offset days. Returns new offset after N working days.
if (nDays === null || nDays === undefined) nDays = 0;
let n = Math.round(Number(nDays) || 0);
if (n < 0) return subtractWorkDays(startNum, -n, calendarInfo);
if (n === 0) return startNum;
if (startNum <= 0) return startNum + n; // no anchor — ordinal fallback
const { workDays, holidaysSet } = _resolveCalendar(calendarInfo);
if (workDays.length === 0) return startNum; // pathological, prevent infinite loop
// v2.1-C1 fast path: clean MonFri, no holidays → O(1) modular arithmetic.
// Hot path on real schedules; ~250× speedup for a 30d activity vs the walk.
if (_isCleanMonFri(workDays, holidaysSet)) {
const startInt = Math.round(startNum);
const fw = (_p6WeekdayFromOffset(startInt) + 1) % 7;
return startInt + _walkFromFirstFw(fw, n);
}
// General fallback: day-by-day walk (custom workdays or holidays present).
let cur = Math.round(startNum);
let remaining = n;
while (remaining > 0) {
cur += 1;
if (_isWorkDayOffset(cur, workDays, holidaysSet)) remaining -= 1;
}
return cur;
}
function subtractWorkDays(endNum, nDays, calendarInfo) {
if (nDays === null || nDays === undefined) nDays = 0;
let n = Math.round(Number(nDays) || 0);
if (n < 0) return addWorkDays(endNum, -n, calendarInfo);
if (n === 0) return endNum;
if (endNum <= 0) return endNum - n;
const { workDays, holidaysSet } = _resolveCalendar(calendarInfo);
if (workDays.length === 0) return endNum;
// v2.1-C1 fast path: clean MonFri, no holidays → O(1) modular arithmetic.
// Symmetry: walkToEnd(lw, n) === walkFromFirstFw(_BW_MIRROR[lw], n).
if (_isCleanMonFri(workDays, holidaysSet)) {
const endInt = Math.round(endNum);
const lw = _p6WeekdayFromOffset(endInt);
return endInt - _walkFromFirstFw(_BW_MIRROR[lw], n);
}
// General fallback: day-by-day walk (custom workdays or holidays present).
let cur = Math.round(endNum);
let remaining = n;
while (remaining > 0) {
cur -= 1;
if (_isWorkDayOffset(cur, workDays, holidaysSet)) remaining -= 1;
}
return cur;
}
// Count working days in (fromNum, toNum] on a given calendar. Used for
// TF (working days) reporting alongside the calendar-day TF that the
// epoch-offset arithmetic produces. P6 reports TF in working days on the
// activity's own calendar; without this companion field, an expert quoting
// "tf=13" on a MonFri-calendar activity will be impeached when P6 shows 10.
function _countWorkDaysBetween(fromNum, toNum, calendarInfo) {
if (!Number.isFinite(fromNum) || !Number.isFinite(toNum)) return 0;
if (toNum <= fromNum) return 0;
if (!calendarInfo) return Math.round(toNum - fromNum);
const { workDays, holidaysSet } = _resolveCalendar(calendarInfo);
if (workDays.length === 0) return 0;
let n = 0, cur = Math.round(fromNum);
const end = Math.round(toNum);
while (cur < end) {
cur += 1;
if (_isWorkDayOffset(cur, workDays, holidaysSet)) n += 1;
}
return n;
}
// "Loud fallback" — match Python _advance_workdays / _retreat_workdays alerts.
function _advanceWithAlerts(startNum, nDays, calendarInfo, alerts, ctx) {
if (startNum <= 0) return startNum + Math.round(Number(nDays) || 0);
if (!calendarInfo) {
alerts.push({
severity: 'ALERT',
context: ctx,
message: 'Calendar-aware arithmetic unavailable (no cal_map/clndr_id) — falling back to 7-day ordinal arithmetic.',
});
return startNum + Math.round(Number(nDays) || 0);
}
return addWorkDays(startNum, nDays, calendarInfo);
}
function _retreatWithAlerts(endNum, nDays, calendarInfo, alerts, ctx) {
if (endNum <= 0) return endNum - Math.round(Number(nDays) || 0);
if (!calendarInfo) {
alerts.push({
severity: 'ALERT',
context: ctx,
message: 'Calendar-aware backward arithmetic unavailable (no cal_map/clndr_id) — falling back to 7-day ordinal arithmetic.',
});
return endNum - Math.round(Number(nDays) || 0);
}
return subtractWorkDays(endNum, nDays, calendarInfo);
}
// ============================================================================
// SECTION B — Topological sort (Kahn's) + Tarjan SCC for cycle isolation
// ============================================================================
function topologicalSort(nodeCodes, succMap, predMap) {
// Returns { order: [...], hasCycle: bool, excluded: [...] }
const inDegree = Object.create(null);
for (const c of nodeCodes) inDegree[c] = 0;
for (const tc in predMap) {
if (!Object.prototype.hasOwnProperty.call(predMap, tc)) continue;
if (!(tc in inDegree)) continue;
let cnt = 0;
for (const p of predMap[tc]) {
if (p.from_code in inDegree) cnt += 1;
}
inDegree[tc] = cnt;
}
// Pointer-walk queue: O(1) dequeue (queue.shift would be O(n) per pop).
const queue = [];
let head = 0;
for (const c of nodeCodes) if (inDegree[c] === 0) queue.push(c);
const order = [];
while (head < queue.length) {
const code = queue[head++];
order.push(code);
const succs = succMap[code] || [];
for (const s of succs) {
const sc = s.to_code;
if (!(sc in inDegree)) continue;
inDegree[sc] -= 1;
if (inDegree[sc] === 0) queue.push(sc);
}
}
// Set.has membership: O(1) per check (vs order.indexOf at O(n) was the
// O(n²) bomb that took 25k-activity networks to ~3.7s in audit perf-3).
const orderSet = new Set(order);
const excluded = [];
for (const c of nodeCodes) {
if (!orderSet.has(c)) excluded.push(c);
}
return { order, hasCycle: order.length !== nodeCodes.length, excluded };
}
function tarjanSCC(nodeCodes, succMap) {
// Tarjan's strongly-connected-components algorithm — iterative variant.
// The recursive form blew JS stack at ~4,334 linear-chain nodes (audit
// 2026-05-09); explicit work-list lifts the limit to whatever heap allows.
let index = 0;
const stack = [];
const onStack = Object.create(null);
const idx = Object.create(null);
const low = Object.create(null);
const sccs = [];
for (const root of nodeCodes) {
if (root in idx) continue;
// Each work-list frame: { v, succs, i } — node v plus position i in v's
// successor list. We push a child frame when we descend; on pop we
// propagate low[v] back to the parent and (if low[v]===idx[v]) extract
// the SCC.
const succsRoot = succMap[root] || [];
const workList = [{ v: root, succs: succsRoot, i: 0 }];
idx[root] = low[root] = index++;
stack.push(root);
onStack[root] = true;
while (workList.length) {
const frame = workList[workList.length - 1];
const { v, succs } = frame;
let descended = false;
while (frame.i < succs.length) {
const w = succs[frame.i++].to_code;
if (!(w in idx)) {
idx[w] = low[w] = index++;
stack.push(w);
onStack[w] = true;
const wSuccs = succMap[w] || [];
workList.push({ v: w, succs: wSuccs, i: 0 });
descended = true;
break;
} else if (onStack[w]) {
if (idx[w] < low[v]) low[v] = idx[w];
}
}
if (descended) continue;
// All successors of v processed. Check if v is an SCC root.
if (low[v] === idx[v]) {
const comp = [];
let w;
do {
w = stack.pop();
onStack[w] = false;
comp.push(w);
} while (w !== v);
sccs.push(comp);
}
workList.pop();
// Propagate low[v] back to the parent frame.
if (workList.length) {
const parent = workList[workList.length - 1].v;
if (low[v] < low[parent]) low[parent] = low[v];
}
}
}
// Identify cycles: SCCs of size > 1, or size-1 SCCs with self-edge.
const cycles = [];
for (const comp of sccs) {
if (comp.length > 1) {
cycles.push(comp);
} else if (comp.length === 1) {
const v = comp[0];
const succs = succMap[v] || [];
if (succs.some((s) => s.to_code === v)) cycles.push(comp);
}
}
return { sccs, cycles };
}
// ============================================================================
// SECTION C — computeCPM — calendar-aware Python-equivalent API
// ============================================================================
//
// computeCPM(activities, relationships, opts) -> result
//
// activities: [{ code, duration_days, name?, actual_start?, actual_finish?,
// early_start?, early_finish?, is_complete?, is_fragnet?,
// clndr_id? }]
// relationships: [{ from_code, to_code, type: 'FS'|'SS'|'FF'|'SF', lag_days }]
// opts: { dataDate?: 'YYYY-MM-DD', calMap?: { clndrId: calendarInfo } }
// calendarInfo: { work_days: [P6 weekdays], holidays: ['YYYY-MM-DD', ...] }
//
// result: { nodes, projectFinish, projectFinishNum, criticalCodes (Set),
// topoOrder, alerts }
// ============================================================================
function computeCPM(activities, relationships, opts) {
opts = opts || {};
const dataDate = opts.dataDate || opts.data_date || '';
// v2.1-C2: Pre-resolve all calendars once at the top of each CPM run.
// _resolveCalendar fast-returns when it sees the _resolved sentinel, so
// every addWorkDays/subtractWorkDays call in the forward/backward passes
// avoids rebuilding new Set(holidays). Caller's calMap is not mutated.
const rawCalMap = opts.calMap || opts.cal_map || {};
const calMap = _preResolveCalendars(rawCalMap);
const ddNum = dataDate ? dateToNum(dataDate) : 0;
const alerts = [];
// Build node map.
// We track insertion order in a separate array because JavaScript's
// Object.keys / for...in hoists integer-like string keys (e.g., "2170")
// to the front in numeric ascending order — Python dicts don't do this.
// Without this, an activity code like "2170" would silently change its
// position in topo_order vs Python and break Section 3's alphabetical
// edge-drop tiebreak when cycles include numeric-only codes.
const nodes = Object.create(null);
const nodeCodesOrdered = [];
for (const a of activities) {
if (!a) continue;
const code = a.code || '';
if (!code) continue;
if (!(code in nodes)) nodeCodesOrdered.push(code);
const durRaw = parseFloat(a.duration_days);
if (!Number.isFinite(durRaw)) {
const err = new Error('Activity ' + code + ' has non-finite duration_days=' +
a.duration_days +
'; use computeCPMSalvaging for degraded-input tolerance');
err.code = 'INVALID_DURATION';
err.activity_code = code;
err.duration_days = a.duration_days;
throw err;
}
const dur = durRaw;
if (dur < 0) {
const err = new Error('Activity ' + code + ' has negative duration_days=' + dur +
'; use computeCPMSalvaging for degraded-input tolerance');
err.code = 'NEGATIVE_DURATION';
err.activity_code = code;
err.duration_days = dur;
throw err;
}
const actualStart = a.actual_start || '';
const actualFinish = a.actual_finish || '';
const isComplete = !!a.is_complete || !!actualFinish;
let es = a.early_start ? dateToNum(a.early_start) : 0;
let ef = a.early_finish ? dateToNum(a.early_finish) : 0;
if (isComplete && actualFinish) {
es = dateToNum(actualStart || actualFinish);
ef = dateToNum(actualFinish);
}
nodes[code] = {
code,
name: a.name || '',
duration_days: dur,
es, ef,
ls: 0, lf: 0,
tf: 0,
is_complete: isComplete,
is_fragnet: !!a.is_fragnet,
actual_start: actualStart,
actual_finish: actualFinish,
clndr_id: a.clndr_id || '',
};
}
// Adjacency.
const predMap = Object.create(null);
const succMap = Object.create(null);
for (const r of relationships) {
const fc = r.from_code;
const tc = r.to_code;
let rtype = (r.type || 'FS').toUpperCase();
if (VALID_REL_TYPES.indexOf(rtype) === -1) rtype = 'FS';
const lag = parseFloat(r.lag_days) || 0;
if (!(fc in nodes) || !(tc in nodes)) {
// Audit T1 fix: emit a non-blocking ALERT so DAUBERT.md's
// "No silent wrong-answer paths" claim holds for strict mode.
// Salvage mode logs DANGLING_REL separately; strict mode previously
// dropped the edge silently.
alerts.push({
severity: 'ALERT',
context: 'dangling-rel',
message: 'Dropped relationship ' + fc + '->' + tc + ' ' + rtype +
': endpoint(s) not in node set',
});
continue;
}
const rec = { from_code: fc, to_code: tc, type: rtype, lag_days: lag };
if (!predMap[tc]) predMap[tc] = [];
if (!succMap[fc]) succMap[fc] = [];
predMap[tc].push(rec);
succMap[fc].push(rec);
}
// Use the insertion-order array, NOT Object.keys(nodes) — see comment above.
const sortRes = topologicalSort(nodeCodesOrdered, succMap, predMap);
if (sortRes.hasCycle) {
const sccRes = tarjanSCC(nodeCodesOrdered, succMap);
const cycleSummary = sccRes.cycles.map((c) => c.join(' -> ')).join(' | ');
const err = new Error(
'CPM network contains a cycle — cannot compute a forward pass. Cycles: ' + cycleSummary
);
err.code = 'CYCLE';
err.cycles = sccRes.cycles;
err.excluded = sortRes.excluded;
throw err;
}
function calFor(node) {
return node.clndr_id ? (calMap[node.clndr_id] || null) : null;
}
// Forward pass.
for (const code of sortRes.order) {
const node = nodes[code];
if (node.is_complete) continue;
const preds = predMap[code] || [];
const nodeCal = calFor(node);
let maxES = Math.max(node.es, ddNum);
let drivingPred = null; // tracks which pred (if any) gave maxES
for (const p of preds) {
const pnode = nodes[p.from_code];
if (!pnode) continue;
let drive = 0;
const lag = p.lag_days;
if (p.type === 'FS') {
drive = _advanceWithAlerts(pnode.ef, lag, nodeCal, alerts,
'FS lag ' + pnode.code + '->' + code);
} else if (p.type === 'SS') {
drive = _advanceWithAlerts(pnode.es, lag, nodeCal, alerts,
'SS lag ' + pnode.code + '->' + code);
} else if (p.type === 'FF') {
const ffAnchor = _advanceWithAlerts(pnode.ef, lag, nodeCal, alerts,
'FF lag ' + pnode.code + '->' + code);
drive = _retreatWithAlerts(ffAnchor, node.duration_days, nodeCal, alerts,
'FF duration ' + code);
} else if (p.type === 'SF') {
const sfAnchor = _advanceWithAlerts(pnode.es, lag, nodeCal, alerts,
'SF lag ' + pnode.code + '->' + code);
drive = _retreatWithAlerts(sfAnchor, node.duration_days, nodeCal, alerts,
'SF duration ' + code);
} else {
drive = _advanceWithAlerts(pnode.ef, lag, nodeCal, alerts,
'FS-default lag ' + pnode.code + '->' + code);
}
if (drive > maxES) {
maxES = drive;
drivingPred = {
code: pnode.code,
type: p.type,
lag_days: lag,
};
}
}
node.es = maxES;
node.ef = _advanceWithAlerts(node.es, node.duration_days, nodeCal, alerts,
'forward ' + code + '.EF');
node.driving_predecessor = drivingPred;
}
let maxEF = 0;
for (const c in nodes) {
if (nodes[c].ef > maxEF) maxEF = nodes[c].ef;
}
// Backward pass — initialize.
for (const c in nodes) {
const n = nodes[c];
const nCal = calFor(n);
n.lf = maxEF;
n.ls = _retreatWithAlerts(maxEF, n.duration_days, nCal, alerts,
'init-LS ' + n.code);
}
for (let i = sortRes.order.length - 1; i >= 0; i--) {
const code = sortRes.order[i];
const node = nodes[code];
if (node.is_complete) {
node.lf = node.ef;
node.ls = node.es;
node.tf = 0;
continue;
}
const nodeCal = calFor(node);
const succs = succMap[code] || [];
let minLF = node.lf;
if (succs.length) {
minLF = null;
for (const s of succs) {
const snode = nodes[s.to_code];
if (!snode) continue;
const sCal = calFor(snode);
let drive;
const lag = s.lag_days;
if (s.type === 'FS') {
drive = _retreatWithAlerts(snode.ls, lag, sCal, alerts,
'backward FS lag ' + code + '->' + snode.code);
} else if (s.type === 'SS') {
const anchor = _retreatWithAlerts(snode.ls, lag, sCal, alerts,
'backward SS lag ' + code + '->' + snode.code);
drive = _advanceWithAlerts(anchor, node.duration_days, nodeCal, alerts,
'backward SS dur ' + code);
} else if (s.type === 'FF') {
drive = _retreatWithAlerts(snode.lf, lag, sCal, alerts,
'backward FF lag ' + code + '->' + snode.code);
} else if (s.type === 'SF') {
const anchor = _retreatWithAlerts(snode.lf, lag, sCal, alerts,
'backward SF lag ' + code + '->' + snode.code);
drive = _advanceWithAlerts(anchor, node.duration_days, nodeCal, alerts,
'backward SF dur ' + code);
} else {
drive = _retreatWithAlerts(snode.ls, lag, sCal, alerts,
'backward default ' + code + '->' + snode.code);
}
if (minLF === null || drive < minLF) minLF = drive;
}
if (minLF === null) minLF = maxEF;
}
node.lf = minLF;
node.ls = _retreatWithAlerts(node.lf, node.duration_days, nodeCal, alerts,
'backward ' + code + '.LS');
node.tf = Math.round((node.lf - node.ef) * 1000) / 1000;
}
// Populate date strings + TF in working days (companion to TF in calendar
// days). P6 reports TF in working days on each activity's own calendar.
for (const c in nodes) {
const n = nodes[c];
n.es_date = numToDate(n.es);
n.ef_date = numToDate(n.ef);
n.ls_date = numToDate(n.ls);
n.lf_date = numToDate(n.lf);
const nCal = (n.clndr_id && calMap) ? calMap[n.clndr_id] : null;
n.tf_working_days = n.is_complete
? 0
: _countWorkDaysBetween(n.ef, n.lf, nCal);
}
// Free Float: slack that doesn't delay any successor's earliest start.
// For terminals, FF = TF (no successor constraint). Computed in calendar
// days same as TF; ff_working_days follows.
for (const c in nodes) {
const n = nodes[c];
if (n.is_complete) {
n.ff = 0;
n.ff_working_days = 0;
continue;
}
const successors = succMap[c] || [];
if (successors.length === 0) {
n.ff = n.tf;
const nCal = (n.clndr_id && calMap) ? calMap[n.clndr_id] : null;
n.ff_working_days = _countWorkDaysBetween(n.ef, n.lf, nCal);
continue;
}
let minSlack = Infinity;
for (const s of successors) {
const sn = nodes[s.to_code];
if (!sn) continue;
let slack;
if (s.type === 'FS') slack = sn.es - n.ef - (s.lag_days || 0);
else if (s.type === 'SS') slack = sn.es - n.es - (s.lag_days || 0);
else if (s.type === 'FF') slack = sn.ef - n.ef - (s.lag_days || 0);
else if (s.type === 'SF') slack = sn.ef - n.es - (s.lag_days || 0);
else slack = sn.es - n.ef - (s.lag_days || 0);
if (slack < minSlack) minSlack = slack;
}
const ff = (minSlack === Infinity) ? n.tf : Math.max(0, Math.round(minSlack * 1000) / 1000);
n.ff = ff;
const nCal = (n.clndr_id && calMap) ? calMap[n.clndr_id] : null;
n.ff_working_days = _countWorkDaysBetween(n.ef, n.ef + ff, nCal);
}
const criticalCodes = new Set();
for (const c in nodes) {
const n = nodes[c];
if (n.tf <= 0 && !n.is_complete) criticalCodes.add(c);
}
// Out-of-sequence progress detection (non-blocking — emits ALERT only).
// Salvage mode does the same scan with OUT_OF_SEQUENCE log entries; strict
// mode users (mid-project TIA, ad-hoc analysis) still need awareness so
// they don't unknowingly base findings on a schedule with retained-logic
// anomalies.
// Audit T2 fix: replace O(n²) `activities.find(...)` per predecessor with
// a single Map lookup built once. On a 25k-completed-activity schedule,
// this drops the OoS scan from ~1.8s to <100ms.
const _actByCode = new Map();
for (const _aa of activities) {
if (_aa && _aa.code) _actByCode.set(_aa.code, _aa);
}
for (const a of activities) {
if (!a || !a.code || !a.is_complete) continue;
const preds = predMap[a.code] || [];
for (const p of preds) {
const pred = nodes[p.from_code];
if (!pred) continue;
// Predecessor unstarted = no actual_start AND not is_complete
const predAct = _actByCode.get(p.from_code);
if (!predAct) continue;
if (!predAct.actual_start && !predAct.is_complete) {
alerts.push({
severity: 'ALERT',
context: 'out-of-sequence',
message: 'Activity ' + a.code +
' is complete but predecessor ' + p.from_code +
' has no actual_start (retained-logic anomaly)',
});
break; // one alert per OoS activity
}
}
}
// criticalCodesArray is a JSON-safe parallel field. JSON.stringify of a
// Set silently produces "{}" — would corrupt any REST/MCP/dashboard
// consumer that round-trips the result through JSON. The Set is kept for
// in-process callers that use .has() lookups; the array is the wire form.
// topo_order (snake_case) mirrors the Python compute_cpm field name so
// downstream skills can read either convention.
const manifest = {
engine_version: ENGINE_VERSION,
method_id: 'computeCPM',
activity_count: Object.keys(nodes).length,
relationship_count: Object.keys(succMap).reduce((acc, k) => acc + succMap[k].length, 0),
data_date: dataDate || '',
calendar_count: Object.keys(calMap).length,
computed_at: new Date().toISOString(),
};
return {
nodes,
projectFinishNum: maxEF,
projectFinish: numToDate(maxEF),
criticalCodes,
criticalCodesArray: Array.from(criticalCodes),
topoOrder: sortRes.order,
topo_order: sortRes.order,
alerts,
manifest,
};
}
// ============================================================================
// SECTION D — parseXER + runCPM — v15.md Monte-Carlo-embedded API
// ----------------------------------------------------------------------------
// Lightweight 5-day-Mon-Fri engine with hour-based duration math (÷ 8). This
// is the per-iteration engine the Monte Carlo wrapper calls 10k× per
// simulation; intentionally NOT calendar-aware (the per-activity calendar
// resolution lives in Section C). Mirrors v15.md formula tables verbatim,
// including the v14 SF forward-pass fix (predTask.ES, not predTask.EF).
// ============================================================================
const _MC = {
tasks: {}, // { taskId: {...} }
predecessors: [], // [{ predTaskId, taskId, type, lag }]
};
function parseXER(content) {
_MC.tasks = {};
_MC.predecessors = [];
let currentTable = '';
let headers = [];
const lines = String(content).split('\n');
for (const line of lines) {
const trimmed = line.trim();
if (trimmed.startsWith('%T')) {
currentTable = trimmed.substring(2).trim();
headers = [];
} else if (trimmed.startsWith('%F')) {
headers = trimmed.substring(2).trim().split('\t');
} else if (trimmed.startsWith('%R')) {
const values = trimmed.substring(2).trim().split('\t');
const row = {};
for (let i = 0; i < headers.length && i < values.length; i++) {
row[headers[i]] = values[i];
}
if (currentTable === 'TASK') {
const taskId = row.task_id;
const remaining = (parseFloat(row.remain_drtn_hr_cnt) || 0) / 8;
if (remaining > 0 && row.task_type !== 'TT_LOE' && row.task_type !== 'TT_WBS') {
// Audit Alpha #1+#4: capture progress markers + per-activity
// calendar so Section C consumers (e.g. /try's
// _buildSectionCInput) can propagate them. XER timestamps
// are 'YYYY-MM-DD HH:mm'; truncate to 'YYYY-MM-DD' for
// Section C consumption. Section D Monte Carlo
// (runCPM) intentionally ignores these — it samples
// per-iteration and re-derives criticality.
const actStart = (row.act_start_date || '').slice(0, 10);
const actFinish = (row.act_end_date || '').slice(0, 10);
_MC.tasks[taskId] = {
id: taskId,
code: row.task_code || taskId,
name: row.task_name || 'Unnamed',
remaining,
originalRemaining: remaining,
actual_start: actStart,
actual_finish: actFinish,
is_complete: !!actFinish,
task_type: row.task_type || '',
clndr_id: row.clndr_id || '',
ES: 0, EF: 0,
LS: Infinity, LF: Infinity,
TF: 0,
preds: [],
succs: [],
criticalCount: 0,
durationSamples: [],
};
}
}
if (currentTable === 'TASKPRED') {