-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcpm-engine.js
More file actions
8699 lines (8337 loc) · 426 KB
/
cpm-engine.js
File metadata and controls
8699 lines (8337 loc) · 426 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 / WBS metadata.
// // Two XERs with identical hashes have IDENTICAL CANONICALIZED TOPOLOGY under
// // the hashed-field set (activity codes, durations, predecessor links + types
// // + lags). NOT a forensic-equivalence statement — different calendars,
// // resources, WBS, names, or constraints can still produce different schedules.
// // Useful as a bid-collusion / retroactive-manipulation signal, not as a
// // schedule-equivalence proof.
//
// 8. Daubert / FRE 702 disclosure wrapper (forward-compatible with proposed FRE 707):
//
// 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.34';
// v2.9.20 A20-M5 — module-level DOS guards. The XER parser already enforces
// these for raw-file ingest (see SECTION G). They're hoisted here so callers
// that build activities/relationships arrays in-memory and pass them to
// `computeCPM` / `computeCPMSalvaging` / `computeTopologyHash` directly are
// also bounded. A schedule with >100k activities or >500k relationships is
// almost certainly degenerate or adversarial; surface a CAP_EXCEEDED error
// instead of letting the host process OOM during topological sort.
const MAX_ENGINE_ACTIVITIES = 100_000;
const MAX_ENGINE_RELATIONSHIPS = 500_000;
function _enforceEngineCaps(activities, relationships, context) {
if (Array.isArray(activities) && activities.length > MAX_ENGINE_ACTIVITIES) {
const err = new Error('CAP_EXCEEDED: ' + (context || 'engine') +
' activity count ' + activities.length + ' > ' + MAX_ENGINE_ACTIVITIES);
err.code = 'CAP_EXCEEDED';
err.limit = 'MAX_ENGINE_ACTIVITIES';
err.count = activities.length;
throw err;
}
if (Array.isArray(relationships) && relationships.length > MAX_ENGINE_RELATIONSHIPS) {
const err = new Error('CAP_EXCEEDED: ' + (context || 'engine') +
' relationship count ' + relationships.length + ' > ' + MAX_ENGINE_RELATIONSHIPS);
err.code = 'CAP_EXCEEDED';
err.limit = 'MAX_ENGINE_RELATIONSHIPS';
err.count = relationships.length;
throw err;
}
}
// P6 constraint mapping (v2.9.3). Primavera stores cstr_type as the long XER
// token (CS_MSO, CS_MEO, …) and cstr_date2 as 'YYYY-MM-DD HH:mm'. We normalize
// to canonical short codes used in the engine's forward/backward passes.
//
// References:
// - Oracle Primavera P6 Database Reference, TASK.cstr_type column (XER spec).
// - AACE 29R-03 §4 Technical Considerations (constraint handling per
// forensic schedule analysis RP).
const CONSTRAINT_TYPE_MAP = {
// Primavera XER tokens → canonical names used by the engine.
// v2.9.5 — Tokens corrected against Oracle P6 Database Reference
// (TASK.cstr_type). The "A/B" suffix is After/Before (Start/Finish No
// Earlier/Later Than). v2.9.3 misclassified CS_MEOA / CS_MSOA as
// mandatory; per the P6 spec they are deadline-style soft constraints.
'CS_MSO': 'MS_Start', // Mandatory Start On
'CS_MEO': 'MS_Finish', // Mandatory Finish On (Mandatory End Originally)
'CS_MSOA': 'SNET', // Start On or After (Start No Earlier Than)
'CS_MSOB': 'SNLT', // Start On or Before (Start No Later Than)
'CS_MEOA': 'FNET', // Finish On or After (Finish No Earlier Than)
'CS_MEOB': 'FNLT', // Finish On or Before (Finish No Later Than)
'CS_MANDSTART':'MS_Start',
'CS_MANDFIN': 'MS_Finish',
// v2.9.12 T1.7 — older P6 R8.x XER variant tokens. Some P6 exports
// (notably mid-period R8 builds) write `CS_MANSTART` / `CS_MANFINISH`
// without the `D` of "MANDATORY". Previously unrecognized → constraint
// silently dropped. Now alias to the canonical mandatory-start / -finish
// names so the same forensic semantics apply.
'CS_MANSTART': 'MS_Start',
'CS_MANFINISH':'MS_Finish',
'CS_ALAP': 'ALAP',
'CS_SO': 'SO', // Start On (treated as MS_Start)
// Short tokens (already canonical or P6 GUI labels)
'SNET': 'SNET',
'SNLT': 'SNLT',
'FNET': 'FNET',
'FNLT': 'FNLT',
'MS_Start': 'MS_Start',
'MS_Finish': 'MS_Finish',
'ALAP': 'ALAP',
'MFO': 'MFO',
'SO': 'SO',
// Common P6 short tokens for start/finish constraints
'CS_MSO_S': 'SNET',
'CS_MSO_F': 'SNLT',
'CS_MEO_S': 'FNET',
'CS_MEO_F': 'FNLT',
'StartOn': 'MS_Start',
'FinishOn': 'MS_Finish',
'StartNoEarlierThan': 'SNET',
'StartNoLaterThan': 'SNLT',
'FinishNoEarlierThan': 'FNET',
'FinishNoLaterThan': 'FNLT',
};
const CANONICAL_CONSTRAINT_TYPES = new Set([
'SNET','SNLT','FNET','FNLT','MS_Start','MS_Finish','ALAP','MFO','SO',
]);
// v2.9.12 T1.6 — Optional `alerts` array. Previously the function silently
// returned null on (a) unrecognized constraint token or (b) recognized token
// with empty date — both forensically interesting (someone wrote a constraint
// the engine cannot honor). Now: emit a labelled WARN so the caller can see
// what was dropped. Backward-compatible: when alerts is omitted, the function
// returns null silently as before (used by Section D parseXER which builds
// its own alerts via a different path; see also the constraint-unrecognized
// emission in parseXER for the XER-row path).
function _normalizeConstraint(c, alerts, _ctx) {
if (!c || typeof c !== 'object') return null;
const rawType = c.type || c.cstr_type || '';
if (!rawType) return null;
const canonical = CONSTRAINT_TYPE_MAP[rawType] || (CANONICAL_CONSTRAINT_TYPES.has(rawType) ? rawType : null);
if (!canonical) {
if (alerts) {
alerts.push({
severity: 'WARN',
context: 'constraint-unrecognized',
message: 'Constraint type ' + JSON.stringify(rawType) +
' on ' + (_ctx || 'activity') +
' is not a recognized P6 token; constraint dropped. ' +
'Engine honors: ' +
Array.from(CANONICAL_CONSTRAINT_TYPES).join(', ') +
' (long-form: CS_MSO, CS_MEO, CS_MSOA/B, CS_MEOA/B, CS_MANDSTART, CS_MANDFIN, ' +
'CS_MANSTART, CS_MANFINISH, CS_ALAP, CS_SO).',
});
}
return null;
}
const rawDate = c.date || c.cstr_date2 || c.cstr_date || '';
// ALAP has no date.
if (canonical === 'ALAP') return { type: 'ALAP', date: '' };
const dateStr = String(rawDate).slice(0, 10);
if (!dateStr) {
if (alerts) {
alerts.push({
severity: 'WARN',
context: 'constraint-incomplete',
message: 'Constraint ' + canonical + ' on ' + (_ctx || 'activity') +
' has no date; constraint dropped. P6 requires a cstr_date for ' +
'all non-ALAP constraint types.',
});
}
return null;
}
// v2.9.20 A16-M2 — validate the constraint date parses. Previously a
// malformed date string ('2026-13-99') silently coerced to 0 inside
// _applyForward*Constraint, effectively dropping the constraint with no
// signal. Now drop loudly with a constraint-invalid-date WARN.
if (dateToNum(dateStr) === 0) {
if (alerts) {
alerts.push({
severity: 'WARN',
context: 'constraint-invalid-date',
message: 'Constraint ' + canonical + ' on ' + (_ctx || 'activity') +
' has invalid date ' + JSON.stringify(rawDate) +
'; constraint dropped to prevent silent epoch-coercion. ' +
'Provide a YYYY-MM-DD date.',
});
}
return null;
}
return { type: canonical, date: dateStr };
}
// v2.9.7 — Secondary-constraint normalization. Per Oracle P6 Database
// Reference, TASK supports cstr_type2 / cstr_date as a SECONDARY constraint
// applied independently of the primary (cstr_type / cstr_date2). When both are
// present, P6 applies them sequentially in forward/backward passes — primary
// first, then secondary tightens further (secondary "wins" on conflict because
// it's the second clamp). Common pairing: SNET (cstr_type) + FNLT (cstr_type2).
// v2.9.12 T1.6 — Optional `alerts` parameter, mirroring `_normalizeConstraint`.
// When provided, unrecognized tokens or non-ALAP constraints with empty dates
// emit a forensic WARN; the function still returns null so downstream skip
// behavior is preserved.
function _normalizeConstraint2(c, alerts, _ctx) {
if (!c || typeof c !== 'object') return null;
// Accept either a separate object with type/date or fields off the parent.
const rawType = c.type || c.cstr_type2 || '';
if (!rawType) return null;
const canonical = CONSTRAINT_TYPE_MAP[rawType] || (CANONICAL_CONSTRAINT_TYPES.has(rawType) ? rawType : null);
if (!canonical) {
if (alerts) {
alerts.push({
severity: 'WARN',
context: 'constraint-unrecognized',
message: 'Secondary constraint type ' + JSON.stringify(rawType) +
' on ' + (_ctx || 'activity') +
' is not a recognized P6 token; secondary constraint dropped.',
});
}
return null;
}
const rawDate = c.date || c.cstr_date || '';
if (canonical === 'ALAP') return { type: 'ALAP', date: '' };
const dateStr = String(rawDate).slice(0, 10);
if (!dateStr) {
if (alerts) {
alerts.push({
severity: 'WARN',
context: 'constraint-incomplete',
message: 'Secondary constraint ' + canonical + ' on ' + (_ctx || 'activity') +
' has no date; secondary constraint dropped.',
});
}
return null;
}
// v2.9.20 A16-M2 — validate the date parses; mirror _normalizeConstraint.
if (dateToNum(dateStr) === 0) {
if (alerts) {
alerts.push({
severity: 'WARN',
context: 'constraint-invalid-date',
message: 'Secondary constraint ' + canonical + ' on ' + (_ctx || 'activity') +
' has invalid date ' + JSON.stringify(rawDate) +
'; secondary constraint dropped.',
});
}
return null;
}
return { type: canonical, date: dateStr };
}
// ============================================================================
// 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.9.14 F3 — Banker's-rounding parity helpers. JS `Math.round(0.5) === 1`
// (half-toward-+Infinity) while Python `int(round(0.5)) === 0` (banker's,
// half-to-even). With real-world P6 lags of 4 / 12 / 20 hours producing
// 0.5 / 1.5 / 2.5-day fractions, this divergence silently breaks JS↔Python
// parity. We harmonize on HALF-UP convention (`Math.floor(x + 0.5)`) in BOTH
// runtimes via the shared helpers below. Math-path callsites (date offsets,
// addWorkDays / subtractWorkDays integer rounding, tf precision) route here.
// Display-only sites (.toFixed(), SVG text formatting, dashboard percentages)
// keep their existing Math.round — those are presentation, not math.
function _roundHalfUp(x) {
if (!Number.isFinite(x)) return x;
// Math.floor(x + 0.5) handles both signs deterministically:
// half-up: 0.5→1, 1.5→2, 2.5→3, -0.5→0, -1.5→-1
return Math.floor(x + 0.5);
}
// v2.9.23 — codepoint-deterministic string comparator (audit MED R13).
// JS Array.sort coerces to UTF-16 code-unit order; Python sorted() uses
// Unicode codepoint order. For ASCII codes these orderings agree, but
// any activity code containing a non-BMP character (rare in P6 but
// legal — e.g. a Chinese-language code) sorts differently between
// engines, breaking the topology-hash + critical_codes parity claim.
// This comparator iterates by codePointAt so JS matches Python's
// scalar-value ordering bit-identically.
function _codepointCmp(a, b) {
const sa = String(a);
const sb = String(b);
const la = sa.length, lb = sb.length;
let i = 0, j = 0;
while (i < la && j < lb) {
const ca = sa.codePointAt(i);
const cb = sb.codePointAt(j);
if (ca !== cb) return ca - cb;
i += ca > 0xFFFF ? 2 : 1;
j += cb > 0xFFFF ? 2 : 1;
}
return la - lb;
}
// v2.9.22 — strict numeric parser. `parseFloat('5abc')` silently returns 5;
// for forensic CPM inputs this is a silent partial-parse poison vector
// (a corrupt duration_days='5abc' becomes 5 with no diagnostic). This helper
// rejects trailing garbage and returns NaN — letting the caller emit the
// proper INVALID_DURATION / lag-non-finite alert path. Accepts numbers
// directly, trimmed numeric strings, and `null`/`undefined`/'' as NaN.
function _strictParseFloat(x) {
if (x === null || x === undefined || x === '') return NaN;
if (typeof x === 'number') return x;
if (typeof x !== 'string') return NaN;
const s = x.trim();
if (s === '') return NaN;
// Accepts: integers, decimals, scientific notation, leading +/-.
// Rejects: '5abc', '5.0xyz', '1e', '1.2.3', ' 5 abc '.
if (!/^[+-]?(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?$/.test(s)) return NaN;
return Number(s);
}
function _roundHalfUpTo(x, decimals) {
if (decimals === undefined || decimals === null) decimals = 0;
if (!Number.isFinite(x)) return x;
const m = Math.pow(10, decimals);
return Math.floor(x * m + 0.5) / m;
}
// ── 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;
// v2.9.24 — audit LOW R21. Avoid the per-call `new Set(workDays)`
// allocation. On a 50k-activity × ~4-work-day-calls schedule that's
// 200k throw-away Set allocations. Direct integer membership check
// is O(5) and allocation-free.
let m = 0;
for (let i = 0; i < workDays.length; i++) {
const d = workDays[i];
if (d < 0 || d > 6) return false;
m |= (1 << d);
}
// Bits 1..5 = Mon..Fri = 0b00111110 = 62.
return m === 62;
}
// ─────────────────────────────────────────────────────────────────────────────
function _msToOffset(ms) {
return _roundHalfUp((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; }
// v2.9.20 A6-L2 — track tz-suffix warnings module-level so we emit once
// per distinct input rather than spamming for every relationship.
const _DATE_TZ_WARNED = new Set();
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;
// v2.9.20 A6-L2 — warn (once per distinct string) when the input carries
// a timezone suffix (T..Z or ±HH:MM). slice(0, 10) silently strips the
// suffix, but a string like '2024-03-10T23:59-08:00' is actually Mar 11
// UTC and silently mapping it to 2024-03-10 can off-by-one for non-UTC
// pipelines. P6 XER stores naive dates so the strip is fine for that
// path, but the public API also accepts JSON strings; opportunistic
// warning lets the analyst know to normalize.
if (typeof console !== 'undefined' && console.warn) {
if (/T\d{2}:\d{2}.*(Z|[+-]\d{2}:?\d{2})/.test(str) && !_DATE_TZ_WARNED.has(str)) {
_DATE_TZ_WARNED.add(str);
// Cap the set so a long-running session doesn't grow unbounded.
if (_DATE_TZ_WARNED.size > 100) _DATE_TZ_WARNED.clear();
console.warn('cpp-cpm-engine: dateToNum(' + JSON.stringify(str) +
') contains a timezone offset; slice(0, 10) ignores it. ' +
'If the schedule date crosses midnight in a non-UTC zone the ' +
'truncated date may be off by one. Normalize to YYYY-MM-DD ' +
'(naive) before passing to the engine.');
}
}
const head = str.slice(0, 10);
const parts = head.split('-');
if (parts.length !== 3) return 0;
// v2.9.17 A10-HIGH — reject trailing garbage in date components.
// parseInt('2026.5', 10) silently returns 2026; parseInt('99x', 10)
// returns 99. Forensic dates must be pure digits. Strict regex check
// prevents accept-with-truncation on locale-formatted CSV round-trips
// or hand-edited XML strings.
if (!/^\d{4}$/.test(parts[0]) || !/^\d{1,2}$/.test(parts[1]) || !/^\d{1,2}$/.test(parts[2])) {
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;
// v2.9.8 Bug B6 — Date.UTC(y, ...) silently rewrites 2-digit years to 19xx.
// Date.UTC(99, 0, 1) → 1999, not year 99. Forensic dates must be 4-digit;
// anything <1000 is rejected (XER dates have always been 4-digit Gregorian).
if (y < 1000) return 0;
// Use _safeDateUTC (defined in Section H) to avoid the Date.UTC(y, m, d)
// silent-rewrite path entirely for any year < 100 that might slip through.
const dt = _safeDateUTC(y, m - 1, d);
// v2.9.12 T2.14 — rollover guard. Date.UTC(2026, 1, 30) silently rolls
// to March 2 because February has 28 days. Forensic dates with invalid
// day-of-month components (Feb 30, Apr 31, etc.) must be rejected, not
// silently rewritten to a different month. Round-trip the constructed
// date and reject if it doesn't match the input components.
if (dt.getUTCFullYear() !== y || dt.getUTCMonth() !== m - 1 || dt.getUTCDate() !== d) {
return 0;
}
return _msToOffset(dt.getTime());
}
function numToDate(n) {
if (!Number.isFinite(n) || n <= 0) return '';
const dt = _offsetToDateUTC(_roundHalfUp(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));
}
// v2.9.12 F2.1 — Snap a calendar offset to the nearest working day.
// Used by the zero-advance / zero-retreat short-circuit in addWorkDays /
// subtractWorkDays so FS-0 / SS-0 / FF-0 / SF-0 forwarders never inherit
// a Sat / Sun / holiday anchor verbatim. Cap the walk at 366 days as a
// safety bound — an all-holiday calendar would otherwise hang.
function _roundForwardToWorkday(num, workDays, holidaysSet) {
if (!Number.isFinite(num) || num <= 0) return num;
let cur = _roundHalfUp(num);
let guard = 0;
while (!_isWorkDayOffset(cur, workDays, holidaysSet)) {
cur += 1;
if (++guard > 366) return _roundHalfUp(num);
}
return cur;
}
function _roundBackwardToWorkday(num, workDays, holidaysSet) {
if (!Number.isFinite(num) || num <= 0) return num;
let cur = _roundHalfUp(num);
let guard = 0;
while (!_isWorkDayOffset(cur, workDays, holidaysSet)) {
cur -= 1;
if (++guard > 366) return _roundHalfUp(num);
}
return cur;
}
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, alerts) {
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);
// v2.9.12 T2.16 — silent fallback to MonFri was forensically opaque.
// If the caller supplied an empty or invalid work_days array
// (`[]`, `[7, 8]`, etc.), we still fall back so the engine remains
// usable, but we emit a WARN so the analyst sees the substitution.
// An empty/invalid work_days on a calendar referenced by activities
// would otherwise produce phantom MonFri dates the schedule was
// never authored against.
if (alerts && Array.isArray(wdRaw) && wdRaw.length > 0 && wd.length === 0) {
alerts.push({
severity: 'WARN',
context: 'invalid-calendar-falling-back',
message: 'Calendar ' + JSON.stringify(k) + ' has work_days=' +
JSON.stringify(wdRaw) + ' with no valid P6 weekday indices ' +
'(0=Sun..6=Sat); falling back to MonFri [1,2,3,4,5]. ' +
'Verify the cal_map entry against the P6 source schedule.',
});
} else if (alerts && Array.isArray(wdRaw) && wdRaw.length === 0) {
alerts.push({
severity: 'WARN',
context: 'invalid-calendar-falling-back',
message: 'Calendar ' + JSON.stringify(k) + ' has empty work_days; ' +
'falling back to MonFri [1,2,3,4,5]. Verify the cal_map ' +
'entry against the P6 source schedule.',
});
}
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;
// v2.9.20 A15-L1 — `Number(nDays) || 0` keeps ±Infinity (truthy) and
// would push the work-day walker into an infinite loop. Coerce
// non-finite inputs to 0 so the function returns a sensible anchor
// rather than hanging. NaN, Infinity, -Infinity all collapse to 0.
let _rawN = Number(nDays);
if (!Number.isFinite(_rawN)) _rawN = 0;
let n = _roundHalfUp(_rawN);
if (n < 0) return subtractWorkDays(startNum, -n, calendarInfo);
// v2.9.12 F2.1 — zero-advance snap. When n === 0 with a real calendar,
// a startNum that lies on a non-workday must be snapped FORWARD to the
// next working day. Without this, FS-0 / SS-0 / FF-0 / SF-0 forwarders
// inherit a Sat / Sun / holiday anchor verbatim and stamp the
// successor's ES/EF on a non-working day. Bare zero with no calendar
// stays identity (preserves Section D ordinal-arithmetic callers).
if (n === 0) {
if (!calendarInfo || startNum <= 0) return startNum;
const { workDays: wd0, holidaysSet: hs0 } = _resolveCalendar(calendarInfo);
if (!wd0 || wd0.length === 0) return startNum;
return _roundForwardToWorkday(startNum, wd0, hs0);
}
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 = _roundHalfUp(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 = _roundHalfUp(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;
// v2.9.20 A15-L1 — symmetric to addWorkDays Infinity guard.
let _rawN = Number(nDays);
if (!Number.isFinite(_rawN)) _rawN = 0;
let n = _roundHalfUp(_rawN);
if (n < 0) return addWorkDays(endNum, -n, calendarInfo);
// v2.9.12 F2.1 — symmetric zero-retreat snap (see addWorkDays). When
// n === 0 with a real calendar, a non-workday anchor snaps BACKWARD to
// the prior working day. Used by FF-0 / SF-0 anchor → succ.ES retreat.
if (n === 0) {
if (!calendarInfo || endNum <= 0) return endNum;
const { workDays: wd0, holidaysSet: hs0 } = _resolveCalendar(calendarInfo);
if (!wd0 || wd0.length === 0) return endNum;
return _roundBackwardToWorkday(endNum, wd0, hs0);
}
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 = _roundHalfUp(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 = _roundHalfUp(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;
// v2.9.12 T2.12 — return signed result so callers (notably
// tf_working_days and ff_working_days) can preserve negative-float
// forensic signal on over-constrained networks. Previously the
// `<= fromNum` clamp swallowed every negative interval to 0.
if (toNum === fromNum) return 0;
if (toNum < fromNum) return -_countWorkDaysBetween(toNum, fromNum, calendarInfo);
if (!calendarInfo) return _roundHalfUp(toNum - fromNum);
const { workDays, holidaysSet } = _resolveCalendar(calendarInfo);
if (workDays.length === 0) return 0;
let n = 0, cur = _roundHalfUp(fromNum);
const end = _roundHalfUp(toNum);
while (cur < end) {
cur += 1;
if (_isWorkDayOffset(cur, workDays, holidaysSet)) n += 1;
}
return n;
}
// "Loud fallback" — match Python _advance_workdays / _retreat_workdays alerts.
// v2.9.11 R8A-2 — Sub-day fractional lag detector. The engine operates in
// day granularity; addWorkDays / subtractWorkDays internally Math.round() the
// nDays argument. P6 stores lags in hours and parseXER divides by 8 → e.g. a
// 4-hour lag becomes 0.5 days which Math.round() collapses (V8 rounds 0.5
// to 1, other engines half-even to 0 — both lose the half-day). 50 successive
// 4-hour lags would silently inflate project finish by up to 50 calendar days
// vs P6. Loud alert at the callsite so claims-prep flags the schedule as
// requiring sub-day precision review before relying on the dates.
function _emitFractionalLagAlertIfNeeded(nDays, alerts, ctx) {
if (!alerts) return;
const raw = Number(nDays);
if (!Number.isFinite(raw)) return;
if (raw === Math.round(raw)) return;
// v2.9.23 — dedup spam (audit MED R12). On a schedule with 500 4-hour
// lags, this helper fired 500 identical ALERTs through _advance/
// _retreatWithAlerts. Forensic readers got buried in noise. Dedup
// per (value, ctx) pair so the analyst sees ONE alert per unique
// fractional-lag value per callsite rather than N copies.
const _seenKey = '_sub_day_lag_seen';
if (!alerts[_seenKey]) alerts[_seenKey] = Object.create(null);
const dedupKey = String(raw) + '\x1f' + String(ctx);
if (alerts[_seenKey][dedupKey]) return;
alerts[_seenKey][dedupKey] = true;
alerts.push({
severity: 'ALERT',
context: ctx,
// v2.9.12 T2.17 — disclose the V8 Math.round direction bias. JS
// Math.round rounds half toward +Infinity (Math.round(0.5) === 1,
// Math.round(-0.5) === 0), so sub-day positive lags INFLATE by up
// to a full day, while sub-day leads (negative lags) between -0.5
// and 0 TRUNCATE to zero. This asymmetric loss is forensically
// material on schedules with many short lags; the engine cannot
// honor sub-day precision under day-granular arithmetic.
message: 'SUB_DAY_LAG_ROUNDED: lag/duration value ' + raw +
' is fractional; engine rounds to ' + Math.round(raw) +
' day(s). V8 Math.round rounds half toward +Infinity; sub-day ' +
'lags inflate, sub-day leads truncate to zero — sub-day ' +
'precision is forensically unavailable in this engine. P6 ' +
'typically stores lags in hours; re-run with full-day lags or ' +
'accept the documented drift.',
});
}
function _advanceWithAlerts(startNum, nDays, calendarInfo, alerts, ctx) {
_emitFractionalLagAlertIfNeeded(nDays, alerts, ctx);
// v2.9.20 A15-L1 — ordinal-arithmetic fallback also needs the Infinity
// guard. Without it, an Infinity lag in a non-calendar codepath would
// emit Infinity-valued ES/EF that JSON.stringify serializes as `null`.
const _nRaw = Number(nDays);
const _nSafe = Number.isFinite(_nRaw) ? _nRaw : 0;
if (startNum <= 0) return startNum + _roundHalfUp(_nSafe);
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 + _roundHalfUp(_nSafe);
}
return addWorkDays(startNum, nDays, calendarInfo);
}
function _retreatWithAlerts(endNum, nDays, calendarInfo, alerts, ctx) {
_emitFractionalLagAlertIfNeeded(nDays, alerts, ctx);
// v2.9.20 A15-L1 — symmetric to _advanceWithAlerts Infinity guard.
const _nRaw = Number(nDays);
const _nSafe = Number.isFinite(_nRaw) ? _nRaw : 0;
if (endNum <= 0) return endNum - _roundHalfUp(_nSafe);
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 - _roundHalfUp(_nSafe);
}
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];
}