assignment-user-matcher 1.9.0 → 1.11.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 (166) hide show
  1. package/README.md +164 -10
  2. package/dist/index.d.ts +2 -1
  3. package/dist/index.d.ts.map +1 -1
  4. package/dist/index.js +19 -1
  5. package/dist/learning/auto-weights.d.ts +7 -4
  6. package/dist/learning/auto-weights.d.ts.map +1 -1
  7. package/dist/learning/auto-weights.js +7 -6
  8. package/dist/lua/workflow-transition.lua +8 -2
  9. package/dist/managers/LearningManager.d.ts.map +1 -1
  10. package/dist/managers/LearningManager.js +47 -0
  11. package/dist/managers/WorkflowManager.d.ts +7 -1
  12. package/dist/managers/WorkflowManager.d.ts.map +1 -1
  13. package/dist/managers/WorkflowManager.js +85 -12
  14. package/dist/matcher.class.d.ts +35 -3
  15. package/dist/matcher.class.d.ts.map +1 -1
  16. package/dist/matcher.class.js +319 -76
  17. package/dist/queries/users.d.ts +34 -0
  18. package/dist/queries/users.d.ts.map +1 -0
  19. package/dist/queries/users.js +227 -0
  20. package/dist/scheduling/constraints/availability.d.ts +43 -0
  21. package/dist/scheduling/constraints/availability.d.ts.map +1 -0
  22. package/dist/scheduling/constraints/availability.js +165 -0
  23. package/dist/scheduling/constraints/consecutive.d.ts +25 -0
  24. package/dist/scheduling/constraints/consecutive.d.ts.map +1 -0
  25. package/dist/scheduling/constraints/consecutive.js +215 -0
  26. package/dist/scheduling/constraints/constraint.d.ts +35 -0
  27. package/dist/scheduling/constraints/constraint.d.ts.map +1 -0
  28. package/dist/scheduling/constraints/constraint.js +97 -0
  29. package/dist/scheduling/constraints/contract.d.ts +21 -0
  30. package/dist/scheduling/constraints/contract.d.ts.map +1 -0
  31. package/dist/scheduling/constraints/contract.js +120 -0
  32. package/dist/scheduling/constraints/cost.d.ts +18 -0
  33. package/dist/scheduling/constraints/cost.d.ts.map +1 -0
  34. package/dist/scheduling/constraints/cost.js +65 -0
  35. package/dist/scheduling/constraints/daily-rest.d.ts +22 -0
  36. package/dist/scheduling/constraints/daily-rest.d.ts.map +1 -0
  37. package/dist/scheduling/constraints/daily-rest.js +123 -0
  38. package/dist/scheduling/constraints/duty-quota.d.ts +20 -0
  39. package/dist/scheduling/constraints/duty-quota.d.ts.map +1 -0
  40. package/dist/scheduling/constraints/duty-quota.js +95 -0
  41. package/dist/scheduling/constraints/engagement-floor.d.ts +28 -0
  42. package/dist/scheduling/constraints/engagement-floor.d.ts.map +1 -0
  43. package/dist/scheduling/constraints/engagement-floor.js +79 -0
  44. package/dist/scheduling/constraints/fairness.d.ts +34 -0
  45. package/dist/scheduling/constraints/fairness.d.ts.map +1 -0
  46. package/dist/scheduling/constraints/fairness.js +149 -0
  47. package/dist/scheduling/constraints/group-composition.d.ts +19 -0
  48. package/dist/scheduling/constraints/group-composition.d.ts.map +1 -0
  49. package/dist/scheduling/constraints/group-composition.js +92 -0
  50. package/dist/scheduling/constraints/hour-budget.d.ts +13 -0
  51. package/dist/scheduling/constraints/hour-budget.d.ts.map +1 -0
  52. package/dist/scheduling/constraints/hour-budget.js +65 -0
  53. package/dist/scheduling/constraints/in-shift-breaks.d.ts +24 -0
  54. package/dist/scheduling/constraints/in-shift-breaks.d.ts.map +1 -0
  55. package/dist/scheduling/constraints/in-shift-breaks.js +99 -0
  56. package/dist/scheduling/constraints/intervals.d.ts +5 -0
  57. package/dist/scheduling/constraints/intervals.d.ts.map +1 -0
  58. package/dist/scheduling/constraints/intervals.js +17 -0
  59. package/dist/scheduling/constraints/max-shift-duration.d.ts +7 -0
  60. package/dist/scheduling/constraints/max-shift-duration.d.ts.map +1 -0
  61. package/dist/scheduling/constraints/max-shift-duration.js +38 -0
  62. package/dist/scheduling/constraints/min-rest.d.ts +22 -0
  63. package/dist/scheduling/constraints/min-rest.d.ts.map +1 -0
  64. package/dist/scheduling/constraints/min-rest.js +49 -0
  65. package/dist/scheduling/constraints/min-staffing.d.ts +14 -0
  66. package/dist/scheduling/constraints/min-staffing.d.ts.map +1 -0
  67. package/dist/scheduling/constraints/min-staffing.js +59 -0
  68. package/dist/scheduling/constraints/night-work.d.ts +24 -0
  69. package/dist/scheduling/constraints/night-work.d.ts.map +1 -0
  70. package/dist/scheduling/constraints/night-work.js +179 -0
  71. package/dist/scheduling/constraints/no-overlap.d.ts +11 -0
  72. package/dist/scheduling/constraints/no-overlap.d.ts.map +1 -0
  73. package/dist/scheduling/constraints/no-overlap.js +35 -0
  74. package/dist/scheduling/constraints/notice.d.ts +44 -0
  75. package/dist/scheduling/constraints/notice.d.ts.map +1 -0
  76. package/dist/scheduling/constraints/notice.js +140 -0
  77. package/dist/scheduling/constraints/one-shift-per-day.d.ts +7 -0
  78. package/dist/scheduling/constraints/one-shift-per-day.d.ts.map +1 -0
  79. package/dist/scheduling/constraints/one-shift-per-day.js +35 -0
  80. package/dist/scheduling/constraints/overtime.d.ts +47 -0
  81. package/dist/scheduling/constraints/overtime.d.ts.map +1 -0
  82. package/dist/scheduling/constraints/overtime.js +149 -0
  83. package/dist/scheduling/constraints/protections.d.ts +21 -0
  84. package/dist/scheduling/constraints/protections.d.ts.map +1 -0
  85. package/dist/scheduling/constraints/protections.js +93 -0
  86. package/dist/scheduling/constraints/qualification.d.ts +18 -0
  87. package/dist/scheduling/constraints/qualification.d.ts.map +1 -0
  88. package/dist/scheduling/constraints/qualification.js +78 -0
  89. package/dist/scheduling/constraints/rest-days.d.ts +30 -0
  90. package/dist/scheduling/constraints/rest-days.d.ts.map +1 -0
  91. package/dist/scheduling/constraints/rest-days.js +133 -0
  92. package/dist/scheduling/constraints/rolling-hours.d.ts +24 -0
  93. package/dist/scheduling/constraints/rolling-hours.d.ts.map +1 -0
  94. package/dist/scheduling/constraints/rolling-hours.js +147 -0
  95. package/dist/scheduling/constraints/start-interval.d.ts +20 -0
  96. package/dist/scheduling/constraints/start-interval.d.ts.map +1 -0
  97. package/dist/scheduling/constraints/start-interval.js +53 -0
  98. package/dist/scheduling/constraints/support.d.ts +48 -0
  99. package/dist/scheduling/constraints/support.d.ts.map +1 -0
  100. package/dist/scheduling/constraints/support.js +97 -0
  101. package/dist/scheduling/constraints/time-off.d.ts +7 -0
  102. package/dist/scheduling/constraints/time-off.d.ts.map +1 -0
  103. package/dist/scheduling/constraints/time-off.js +42 -0
  104. package/dist/scheduling/constraints/weekly-rest.d.ts +22 -0
  105. package/dist/scheduling/constraints/weekly-rest.d.ts.map +1 -0
  106. package/dist/scheduling/constraints/weekly-rest.js +103 -0
  107. package/dist/scheduling/cost.d.ts +56 -0
  108. package/dist/scheduling/cost.d.ts.map +1 -0
  109. package/dist/scheduling/cost.js +120 -0
  110. package/dist/scheduling/engine/construction.d.ts +22 -0
  111. package/dist/scheduling/engine/construction.d.ts.map +1 -0
  112. package/dist/scheduling/engine/construction.js +104 -0
  113. package/dist/scheduling/engine/explain.d.ts +12 -0
  114. package/dist/scheduling/engine/explain.d.ts.map +1 -0
  115. package/dist/scheduling/engine/explain.js +24 -0
  116. package/dist/scheduling/engine/objective.d.ts +73 -0
  117. package/dist/scheduling/engine/objective.d.ts.map +1 -0
  118. package/dist/scheduling/engine/objective.js +164 -0
  119. package/dist/scheduling/engine/prng.d.ts +5 -0
  120. package/dist/scheduling/engine/prng.d.ts.map +1 -0
  121. package/dist/scheduling/engine/prng.js +24 -0
  122. package/dist/scheduling/engine/propagation.d.ts +19 -0
  123. package/dist/scheduling/engine/propagation.d.ts.map +1 -0
  124. package/dist/scheduling/engine/propagation.js +40 -0
  125. package/dist/scheduling/engine/search.d.ts +50 -0
  126. package/dist/scheduling/engine/search.d.ts.map +1 -0
  127. package/dist/scheduling/engine/search.js +127 -0
  128. package/dist/scheduling/engine/state.d.ts +28 -0
  129. package/dist/scheduling/engine/state.d.ts.map +1 -0
  130. package/dist/scheduling/engine/state.js +96 -0
  131. package/dist/scheduling/engine/timeline.d.ts +179 -0
  132. package/dist/scheduling/engine/timeline.d.ts.map +1 -0
  133. package/dist/scheduling/engine/timeline.js +416 -0
  134. package/dist/scheduling/engine/verdicts.d.ts +18 -0
  135. package/dist/scheduling/engine/verdicts.d.ts.map +1 -0
  136. package/dist/scheduling/engine/verdicts.js +74 -0
  137. package/dist/scheduling/index.d.ts +10 -0
  138. package/dist/scheduling/index.d.ts.map +1 -0
  139. package/dist/scheduling/index.js +29 -0
  140. package/dist/scheduling/model.d.ts +53 -0
  141. package/dist/scheduling/model.d.ts.map +1 -0
  142. package/dist/scheduling/model.js +380 -0
  143. package/dist/scheduling/operations.d.ts +134 -0
  144. package/dist/scheduling/operations.d.ts.map +1 -0
  145. package/dist/scheduling/operations.js +376 -0
  146. package/dist/scheduling/provenance.d.ts +33 -0
  147. package/dist/scheduling/provenance.d.ts.map +1 -0
  148. package/dist/scheduling/provenance.js +70 -0
  149. package/dist/scheduling/rules.d.ts +23 -0
  150. package/dist/scheduling/rules.d.ts.map +1 -0
  151. package/dist/scheduling/rules.js +37 -0
  152. package/dist/scheduling/scheduler.class.d.ts +24 -0
  153. package/dist/scheduling/scheduler.class.d.ts.map +1 -0
  154. package/dist/scheduling/scheduler.class.js +150 -0
  155. package/dist/scheduling/time.d.ts +138 -0
  156. package/dist/scheduling/time.d.ts.map +1 -0
  157. package/dist/scheduling/time.js +267 -0
  158. package/dist/scheduling/types.d.ts +938 -0
  159. package/dist/scheduling/types.d.ts.map +1 -0
  160. package/dist/scheduling/types.js +19 -0
  161. package/dist/types/matcher.d.ts +86 -2
  162. package/dist/types/matcher.d.ts.map +1 -1
  163. package/dist/utils/keys.d.ts +1 -0
  164. package/dist/utils/keys.d.ts.map +1 -1
  165. package/dist/utils/keys.js +6 -0
  166. package/package.json +4 -2
@@ -0,0 +1,150 @@
1
+ "use strict";
2
+ /**
3
+ * ShiftScheduler — the facade.
4
+ *
5
+ * Orchestration only: normalize input → propagate → construct → improve →
6
+ * interpret. Pure logic lives in `model.ts`, `constraints/`, and `engine/`;
7
+ * this class owns sequencing and result shaping. No Redis, no I/O — consumers
8
+ * wrap `solveSchedule` in their own queue.
9
+ *
10
+ * Status semantics: `'partial'` when slots are unfilled or a hard rule is
11
+ * breached, `'feasible'` when every slot is staffed but softer obligations are
12
+ * unmet, `'optimal'` when nothing is outstanding — "no known improvement", never
13
+ * a proof of optimality.
14
+ */
15
+ Object.defineProperty(exports, "__esModule", { value: true });
16
+ exports.solveSchedule = exports.ShiftScheduler = exports.ENGINE_VERSION = void 0;
17
+ const model_1 = require("./model");
18
+ const propagation_1 = require("./engine/propagation");
19
+ const state_1 = require("./engine/state");
20
+ const construction_1 = require("./engine/construction");
21
+ const search_1 = require("./engine/search");
22
+ const objective_1 = require("./engine/objective");
23
+ const explain_1 = require("./engine/explain");
24
+ const min_staffing_1 = require("./constraints/min-staffing");
25
+ const hour_budget_1 = require("./constraints/hour-budget");
26
+ const rest_days_1 = require("./constraints/rest-days");
27
+ const notice_1 = require("./constraints/notice");
28
+ const protections_1 = require("./constraints/protections");
29
+ const overtime_1 = require("./constraints/overtime");
30
+ const cost_1 = require("./cost");
31
+ const prng_1 = require("./engine/prng");
32
+ const verdicts_1 = require("./engine/verdicts");
33
+ const provenance_1 = require("./provenance");
34
+ const DEFAULT_TIME_BUDGET_MS = 10000;
35
+ const DEFAULT_SEED = 42;
36
+ exports.ENGINE_VERSION = '2';
37
+ class ShiftScheduler {
38
+ /** Solve a scheduling problem synchronously. Throws `ScheduleValidationError` on malformed input. */
39
+ solve(input) {
40
+ const startedAt = Date.now();
41
+ const objective = input.objective ?? 'standard';
42
+ const timeBudgetMs = input.timeBudgetMs ?? DEFAULT_TIME_BUDGET_MS;
43
+ const seed = input.seed ?? DEFAULT_SEED;
44
+ const rand = (0, prng_1.createPrng)(seed);
45
+ const ctx = (0, model_1.buildModel)(input);
46
+ const propagation = (0, propagation_1.propagate)(ctx);
47
+ const state = (0, state_1.createState)(ctx);
48
+ // Pinned pairs are placed first and never removed, so a re-solve keeps
49
+ // the parts of a published roster the caller committed to.
50
+ for (const key of ctx.pinned) {
51
+ const [employeeId, instanceId] = key.split('|');
52
+ if (!ctx.employeeById.has(employeeId) || !ctx.instanceById.has(instanceId))
53
+ continue;
54
+ (0, state_1.assign)(state, employeeId, instanceId, ['pinned by the caller']);
55
+ }
56
+ (0, construction_1.greedyFill)(ctx, state, propagation, objective, rand);
57
+ const minHoursWeight = ctx.constraints.find((c) => c.id === 'hour-budget')?.weight ?? objective_1.MIN_HOURS_WEIGHT;
58
+ let finalState = state;
59
+ let evaluatedVariants = 1;
60
+ if (timeBudgetMs > 0) {
61
+ const outcome = (0, search_1.improveWithLns)(ctx, state, propagation, {
62
+ objective,
63
+ minHoursWeight,
64
+ timeBudgetMs,
65
+ rand,
66
+ onImprovement: input.onProgress
67
+ ? (best) => input.onProgress(this.assemble(best, propagation, startedAt, seed, input, 0))
68
+ : undefined,
69
+ }, () => (0, state_1.createState)(ctx));
70
+ finalState = outcome.best;
71
+ evaluatedVariants += outcome.evaluatedVariants;
72
+ }
73
+ return this.assemble(finalState, propagation, startedAt, seed, input, evaluatedVariants);
74
+ }
75
+ /** Shape a search state into the public result, running the aggregate rules once. */
76
+ assemble(state, propagation, startedAt, seed, input, evaluatedVariants) {
77
+ const ctx = state.ctx;
78
+ const minHoursWeight = ctx.constraints.find((c) => c.id === 'hour-budget')?.weight ?? objective_1.MIN_HOURS_WEIGHT;
79
+ const assignments = (0, state_1.assignedPairs)(state).map(({ employeeId, instanceId }) => {
80
+ const inst = ctx.instanceById.get(instanceId);
81
+ return {
82
+ shiftInstanceId: instanceId,
83
+ employeeId,
84
+ date: inst.date,
85
+ reasons: (0, explain_1.reasonsFor)(state, employeeId, instanceId),
86
+ };
87
+ });
88
+ const staffing = (0, min_staffing_1.staffingViolations)(ctx, state, 'medium');
89
+ const softHours = (0, hour_budget_1.minHourViolations)(ctx, state, minHoursWeight);
90
+ // Pair-level and aggregate rules both run once here, not per move: they
91
+ // are O(roster) and the search calls the objective in its innermost
92
+ // loop. Sharing these two passes with `checkCompliance` is what stops
93
+ // the solver and the validator from reaching different conclusions
94
+ // about the same roster.
95
+ const pairLevel = (0, verdicts_1.collectPairViolations)(state);
96
+ const aggregate = (0, verdicts_1.collectAggregateViolations)(state);
97
+ const violations = [...propagation.violations, ...staffing, ...softHours, ...pairLevel, ...aggregate];
98
+ const unfilled = (0, objective_1.unfilledSlots)(ctx, state);
99
+ const hardBreaches = violations.filter((v) => v.severity === 'hard');
100
+ // Coverage is judged on staffing shortfalls rather than on `unfilled`
101
+ // alone: a shift can have its headcount and still be missing a required
102
+ // tag, which is a roster that does not meet the stated requirement.
103
+ const coverageShort = unfilled > 0 || staffing.length > 0;
104
+ const outstanding = violations.some((v) => v.severity === 'medium') || softHours.length > 0;
105
+ const status = coverageShort || hardBreaches.length > 0 ? 'partial' : outstanding ? 'feasible' : 'optimal';
106
+ const ledger = [
107
+ ...(0, rest_days_1.compensatoryRestLedger)(state, ctx.rules.restDays),
108
+ ...(0, notice_1.cancellationLedger)(state, ctx.rules.notice),
109
+ ...(0, protections_1.protectionLedger)(state),
110
+ ...(0, overtime_1.overtimeLedger)(state),
111
+ ];
112
+ const cost = (0, cost_1.rosterCost)(state);
113
+ return {
114
+ status,
115
+ assignments,
116
+ violations,
117
+ stats: {
118
+ evaluatedVariants,
119
+ durationMs: Date.now() - startedAt,
120
+ unfilledSlots: unfilled,
121
+ },
122
+ provenance: {
123
+ engineVersion: exports.ENGINE_VERSION,
124
+ seed,
125
+ rulesHash: (0, provenance_1.hashRules)(input.rules, input.constraints, input.objectives),
126
+ dutyClassificationNotes: dutyNotes(ctx),
127
+ // Nothing in this module consumes a behavioural or predictive
128
+ // per-worker signal, so the claim is structural rather than a
129
+ // promise about configuration.
130
+ profilingFree: true,
131
+ },
132
+ ...(ledger.length ? { ledger } : {}),
133
+ ...(cost ? { cost } : {}),
134
+ };
135
+ }
136
+ }
137
+ exports.ShiftScheduler = ShiftScheduler;
138
+ function dutyNotes(ctx) {
139
+ const notes = {};
140
+ for (const inst of ctx.instances) {
141
+ if (inst.duty?.classificationNote)
142
+ notes[inst.templateId] = inst.duty.classificationNote;
143
+ }
144
+ return Object.keys(notes).length ? notes : undefined;
145
+ }
146
+ /** One-shot convenience wrapper around `new ShiftScheduler().solve(input)`. */
147
+ function solveSchedule(input) {
148
+ return new ShiftScheduler().solve(input);
149
+ }
150
+ exports.solveSchedule = solveSchedule;
@@ -0,0 +1,138 @@
1
+ /**
2
+ * Time model — pure logic, zero dependencies.
3
+ *
4
+ * The engine works in "period minutes": integer minutes elapsed since local
5
+ * midnight on `period.startDate` in the roster's time zone. That keeps the hot
6
+ * path integer-only while staying correct across DST transitions.
7
+ *
8
+ * Why this matters legally: on the EU changeover nights (last Sunday of March
9
+ * and October) a 22:00–06:00 shift is 7h or 9h, not 8h. Naive UTC-epoch
10
+ * arithmetic — what `model.ts` does today — reports 8h, which then feeds hour
11
+ * budgets, rolling-window averages and rest gaps. Every one of those is a
12
+ * number an inspector can check, so the error is material, not cosmetic.
13
+ *
14
+ * Zone offsets come from `Intl.DateTimeFormat`, which ships with Node and the
15
+ * browser; the library stays dependency-free.
16
+ */
17
+ export declare const MINUTES_PER_DAY = 1440;
18
+ /** A half-open range of period minutes, `[start, end)`. */
19
+ export interface MinuteRange {
20
+ start: number;
21
+ end: number;
22
+ }
23
+ /** A wall-clock time-of-day range; `to <= from` means it wraps past midnight (e.g. 22:00–06:00). */
24
+ export interface ClockRange {
25
+ from: string;
26
+ to: string;
27
+ }
28
+ /**
29
+ * Resolves wall-clock times in one IANA zone to period minutes and back.
30
+ *
31
+ * Construct once per solve and share it: each instance memoizes the per-day UTC
32
+ * offset, so repeated conversions cost a map lookup rather than an `Intl` call.
33
+ */
34
+ export declare class PeriodClock {
35
+ readonly startDate: string;
36
+ readonly timeZone: string;
37
+ readonly days: number;
38
+ private readonly formatter;
39
+ /** UTC epoch ms of local midnight, keyed by day index from the period start. */
40
+ private readonly midnightByDay;
41
+ /** UTC epoch ms of local midnight on the period start — the origin of period minutes. */
42
+ private originMs;
43
+ constructor(startDate: string, days: number, timeZone?: string);
44
+ /** Day index of an ISO date relative to the period start; negative before it. */
45
+ dayIndexOf(date: string): number;
46
+ /** ISO date `offset` days after the period start. */
47
+ dateAt(offset: number): string;
48
+ /**
49
+ * Period minutes for a wall-clock `(date, HH:MM)` in this zone.
50
+ *
51
+ * Each wall-clock time is resolved to its own UTC instant before being
52
+ * measured, so a transition earlier the same day is already priced in:
53
+ * 06:00 on a spring-forward morning is 5 real hours after that day's local
54
+ * midnight, not 6.
55
+ */
56
+ toPeriodMinutes(date: string, timeOfDay: string, field?: string): number;
57
+ /**
58
+ * True elapsed minutes from local midnight on the period start to local
59
+ * midnight on `dayIndex` — 1440 per day except across a DST transition.
60
+ */
61
+ dayStartMinutes(dayIndex: number): number;
62
+ /** Period minutes for `minutesIntoDay` wall-clock minutes past local midnight on `dayIndex`. */
63
+ private periodMinuteAt;
64
+ /** The ISO date a period minute falls on. */
65
+ dateOfMinute(minute: number): string;
66
+ /** ISO weekday of a period minute: 1 (Mon) .. 7 (Sun). */
67
+ weekdayOfMinute(minute: number): number;
68
+ /**
69
+ * Absolute UTC epoch milliseconds for a period minute.
70
+ *
71
+ * The bridge out of the engine's integer-minute world. Anything that leaves
72
+ * the solver — a matcher assignment, an API payload, a calendar entry —
73
+ * needs a real instant, and deriving one by adding minutes to the period
74
+ * start would reintroduce exactly the DST error the clock exists to avoid.
75
+ */
76
+ toEpochMs(periodMinute: number): number;
77
+ /** Period minutes for an absolute UTC epoch instant. */
78
+ fromEpochMs(epochMs: number): number;
79
+ /** ISO 8601 instant for a period minute, in UTC. */
80
+ toISOString(periodMinute: number): string;
81
+ /**
82
+ * Minutes of `range` that fall inside a recurring wall-clock window, summed
83
+ * across every day the range touches. Windows that wrap midnight (a night
84
+ * band such as 22:00–06:00) are handled.
85
+ *
86
+ * This is the primitive behind night-work accounting and premium bands —
87
+ * both need "how much of this shift was inside that clock window", not
88
+ * "did it start at night".
89
+ */
90
+ minutesInClockRange(range: MinuteRange, clock: ClockRange): number;
91
+ /**
92
+ * The clipped period-minute intervals where `range` intersects the daily
93
+ * clock band. This is `minutesInClockRange` without the final sum — for
94
+ * callers that need to union several bands rather than total one.
95
+ */
96
+ clockRangeIntervals(range: MinuteRange, clock: ClockRange): MinuteRange[];
97
+ /**
98
+ * Day index containing a period minute. May fall outside `[0, days)` —
99
+ * history from the previous period lives at negative indices.
100
+ *
101
+ * `dayStartMinutes` is monotonic and never drifts from the nominal
102
+ * 1440-per-day grid by more than a DST offset, so the floor estimate is
103
+ * correct or off by one; the two guards settle it.
104
+ */
105
+ dayIndexOfMinute(minute: number): number;
106
+ /** UTC epoch ms of local midnight on the given day index, memoized. */
107
+ private utcMidnightMs;
108
+ /**
109
+ * UTC epoch ms for a local wall-clock time in this zone.
110
+ *
111
+ * The zone offset depends on the instant we are solving for, so this is a
112
+ * fixed-point: guess with the offset at the nominal instant, then re-check
113
+ * with the offset at the guess. One refinement settles every real-world
114
+ * transition; where a wall-clock time does not exist (the skipped hour on a
115
+ * spring-forward night) the two probes disagree and the second wins,
116
+ * yielding the instant the clock jumps to.
117
+ */
118
+ private utcInstantMs;
119
+ /** Offset in minutes east of UTC at a given instant. */
120
+ private offsetAtMs;
121
+ }
122
+ /** Overlap of two half-open minute ranges, in minutes (0 when disjoint). */
123
+ export declare function overlapMinutes(a: MinuteRange, b: MinuteRange): number;
124
+ /** Whether two half-open minute ranges intersect. */
125
+ export declare function overlaps(a: MinuteRange, b: MinuteRange): boolean;
126
+ /** Gap between two non-overlapping ranges in minutes; 0 when they overlap. */
127
+ export declare function gapBetween(a: MinuteRange, b: MinuteRange): number;
128
+ /** Days between two ISO dates (`to - from`); negative when `to` precedes `from`. */
129
+ export declare function daysBetween(from: string, to: string): number;
130
+ /** ISO date `days` after `date`. */
131
+ export declare function addDays(date: string, days: number): string;
132
+ /** ISO weekday 1 (Mon) .. 7 (Sun). */
133
+ export declare function isoWeekday(date: string): number;
134
+ /** Minutes since local midnight for an `HH:MM` / `HH:MM:SS` string. */
135
+ export declare function parseTimeOfDay(value: string, field: string): number;
136
+ /** Throws `ScheduleValidationError` unless `value` is a real `YYYY-MM-DD` date. */
137
+ export declare function assertIsoDate(value: string, field: string): void;
138
+ //# sourceMappingURL=time.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"time.d.ts","sourceRoot":"","sources":["../../src/scheduling/time.ts"],"names":[],"mappings":"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"}
@@ -0,0 +1,267 @@
1
+ "use strict";
2
+ /**
3
+ * Time model — pure logic, zero dependencies.
4
+ *
5
+ * The engine works in "period minutes": integer minutes elapsed since local
6
+ * midnight on `period.startDate` in the roster's time zone. That keeps the hot
7
+ * path integer-only while staying correct across DST transitions.
8
+ *
9
+ * Why this matters legally: on the EU changeover nights (last Sunday of March
10
+ * and October) a 22:00–06:00 shift is 7h or 9h, not 8h. Naive UTC-epoch
11
+ * arithmetic — what `model.ts` does today — reports 8h, which then feeds hour
12
+ * budgets, rolling-window averages and rest gaps. Every one of those is a
13
+ * number an inspector can check, so the error is material, not cosmetic.
14
+ *
15
+ * Zone offsets come from `Intl.DateTimeFormat`, which ships with Node and the
16
+ * browser; the library stays dependency-free.
17
+ */
18
+ Object.defineProperty(exports, "__esModule", { value: true });
19
+ exports.assertIsoDate = exports.parseTimeOfDay = exports.isoWeekday = exports.addDays = exports.daysBetween = exports.gapBetween = exports.overlaps = exports.overlapMinutes = exports.PeriodClock = exports.MINUTES_PER_DAY = void 0;
20
+ const types_1 = require("./types");
21
+ exports.MINUTES_PER_DAY = 1440;
22
+ const ISO_DATE = /^\d{4}-\d{2}-\d{2}$/;
23
+ const TIME_OF_DAY = /^(\d{1,2}):(\d{2})(?::(\d{2}))?$/;
24
+ /**
25
+ * Resolves wall-clock times in one IANA zone to period minutes and back.
26
+ *
27
+ * Construct once per solve and share it: each instance memoizes the per-day UTC
28
+ * offset, so repeated conversions cost a map lookup rather than an `Intl` call.
29
+ */
30
+ class PeriodClock {
31
+ constructor(startDate, days, timeZone = 'UTC') {
32
+ /** UTC epoch ms of local midnight, keyed by day index from the period start. */
33
+ this.midnightByDay = new Map();
34
+ assertIsoDate(startDate, 'period.startDate');
35
+ if (!Number.isInteger(days) || days <= 0) {
36
+ throw new types_1.ScheduleValidationError(`period must span at least one day, got ${days}`);
37
+ }
38
+ this.startDate = startDate;
39
+ this.days = days;
40
+ this.timeZone = timeZone;
41
+ try {
42
+ this.formatter = new Intl.DateTimeFormat('en-US', {
43
+ timeZone,
44
+ hourCycle: 'h23',
45
+ year: 'numeric',
46
+ month: '2-digit',
47
+ day: '2-digit',
48
+ hour: '2-digit',
49
+ minute: '2-digit',
50
+ });
51
+ }
52
+ catch {
53
+ throw new types_1.ScheduleValidationError(`Unknown time zone: "${timeZone}"`);
54
+ }
55
+ this.originMs = this.utcInstantMs(startDate, 0);
56
+ }
57
+ /** Day index of an ISO date relative to the period start; negative before it. */
58
+ dayIndexOf(date) {
59
+ assertIsoDate(date, 'date');
60
+ return daysBetween(this.startDate, date);
61
+ }
62
+ /** ISO date `offset` days after the period start. */
63
+ dateAt(offset) {
64
+ return addDays(this.startDate, offset);
65
+ }
66
+ /**
67
+ * Period minutes for a wall-clock `(date, HH:MM)` in this zone.
68
+ *
69
+ * Each wall-clock time is resolved to its own UTC instant before being
70
+ * measured, so a transition earlier the same day is already priced in:
71
+ * 06:00 on a spring-forward morning is 5 real hours after that day's local
72
+ * midnight, not 6.
73
+ */
74
+ toPeriodMinutes(date, timeOfDay, field = 'time') {
75
+ return this.periodMinuteAt(this.dayIndexOf(date), parseTimeOfDay(timeOfDay, field));
76
+ }
77
+ /**
78
+ * True elapsed minutes from local midnight on the period start to local
79
+ * midnight on `dayIndex` — 1440 per day except across a DST transition.
80
+ */
81
+ dayStartMinutes(dayIndex) {
82
+ return this.periodMinuteAt(dayIndex, 0);
83
+ }
84
+ /** Period minutes for `minutesIntoDay` wall-clock minutes past local midnight on `dayIndex`. */
85
+ periodMinuteAt(dayIndex, minutesIntoDay) {
86
+ if (minutesIntoDay === 0) {
87
+ return Math.round((this.utcMidnightMs(dayIndex) - this.originMs) / 60000);
88
+ }
89
+ return Math.round((this.utcInstantMs(this.dateAt(dayIndex), minutesIntoDay) - this.originMs) / 60000);
90
+ }
91
+ /** The ISO date a period minute falls on. */
92
+ dateOfMinute(minute) {
93
+ return this.dateAt(this.dayIndexOfMinute(minute));
94
+ }
95
+ /** ISO weekday of a period minute: 1 (Mon) .. 7 (Sun). */
96
+ weekdayOfMinute(minute) {
97
+ return isoWeekday(this.dateOfMinute(minute));
98
+ }
99
+ /**
100
+ * Absolute UTC epoch milliseconds for a period minute.
101
+ *
102
+ * The bridge out of the engine's integer-minute world. Anything that leaves
103
+ * the solver — a matcher assignment, an API payload, a calendar entry —
104
+ * needs a real instant, and deriving one by adding minutes to the period
105
+ * start would reintroduce exactly the DST error the clock exists to avoid.
106
+ */
107
+ toEpochMs(periodMinute) {
108
+ return this.originMs + periodMinute * 60000;
109
+ }
110
+ /** Period minutes for an absolute UTC epoch instant. */
111
+ fromEpochMs(epochMs) {
112
+ return Math.round((epochMs - this.originMs) / 60000);
113
+ }
114
+ /** ISO 8601 instant for a period minute, in UTC. */
115
+ toISOString(periodMinute) {
116
+ return new Date(this.toEpochMs(periodMinute)).toISOString();
117
+ }
118
+ /**
119
+ * Minutes of `range` that fall inside a recurring wall-clock window, summed
120
+ * across every day the range touches. Windows that wrap midnight (a night
121
+ * band such as 22:00–06:00) are handled.
122
+ *
123
+ * This is the primitive behind night-work accounting and premium bands —
124
+ * both need "how much of this shift was inside that clock window", not
125
+ * "did it start at night".
126
+ */
127
+ minutesInClockRange(range, clock) {
128
+ return this.clockRangeIntervals(range, clock).reduce((sum, i) => sum + (i.end - i.start), 0);
129
+ }
130
+ /**
131
+ * The clipped period-minute intervals where `range` intersects the daily
132
+ * clock band. This is `minutesInClockRange` without the final sum — for
133
+ * callers that need to union several bands rather than total one.
134
+ */
135
+ clockRangeIntervals(range, clock) {
136
+ const from = parseTimeOfDay(clock.from, 'clockRange.from');
137
+ const to = parseTimeOfDay(clock.to, 'clockRange.to');
138
+ if (range.end <= range.start)
139
+ return [];
140
+ const out = [];
141
+ const push = (interval) => {
142
+ const start = Math.max(range.start, interval.start);
143
+ const end = Math.min(range.end, interval.end);
144
+ if (end > start)
145
+ out.push({ start, end });
146
+ };
147
+ const firstDay = this.dayIndexOfMinute(range.start);
148
+ const lastDay = this.dayIndexOfMinute(range.end - 1);
149
+ // A wrapping window spills into the following day, so start one day early.
150
+ for (let day = firstDay - 1; day <= lastDay + 1; day++) {
151
+ if (from < to) {
152
+ push({ start: this.periodMinuteAt(day, from), end: this.periodMinuteAt(day, to) });
153
+ }
154
+ else {
155
+ // Wraps midnight: [from, 24:00) on this day plus [00:00, to) on the next.
156
+ const nextMidnight = this.dayStartMinutes(day + 1);
157
+ push({ start: this.periodMinuteAt(day, from), end: nextMidnight });
158
+ push({ start: nextMidnight, end: this.periodMinuteAt(day + 1, to) });
159
+ }
160
+ }
161
+ return out;
162
+ }
163
+ /**
164
+ * Day index containing a period minute. May fall outside `[0, days)` —
165
+ * history from the previous period lives at negative indices.
166
+ *
167
+ * `dayStartMinutes` is monotonic and never drifts from the nominal
168
+ * 1440-per-day grid by more than a DST offset, so the floor estimate is
169
+ * correct or off by one; the two guards settle it.
170
+ */
171
+ dayIndexOfMinute(minute) {
172
+ let day = Math.floor(minute / exports.MINUTES_PER_DAY);
173
+ while (this.dayStartMinutes(day) > minute)
174
+ day--;
175
+ while (this.dayStartMinutes(day + 1) <= minute)
176
+ day++;
177
+ return day;
178
+ }
179
+ /** UTC epoch ms of local midnight on the given day index, memoized. */
180
+ utcMidnightMs(dayIndex) {
181
+ const cached = this.midnightByDay.get(dayIndex);
182
+ if (cached !== undefined)
183
+ return cached;
184
+ const ms = this.utcInstantMs(this.dateAt(dayIndex), 0);
185
+ this.midnightByDay.set(dayIndex, ms);
186
+ return ms;
187
+ }
188
+ /**
189
+ * UTC epoch ms for a local wall-clock time in this zone.
190
+ *
191
+ * The zone offset depends on the instant we are solving for, so this is a
192
+ * fixed-point: guess with the offset at the nominal instant, then re-check
193
+ * with the offset at the guess. One refinement settles every real-world
194
+ * transition; where a wall-clock time does not exist (the skipped hour on a
195
+ * spring-forward night) the two probes disagree and the second wins,
196
+ * yielding the instant the clock jumps to.
197
+ */
198
+ utcInstantMs(date, minutesIntoDay) {
199
+ const nominal = Date.parse(`${date}T00:00:00Z`) + minutesIntoDay * 60000;
200
+ const guess = nominal - this.offsetAtMs(nominal) * 60000;
201
+ return nominal - this.offsetAtMs(guess) * 60000;
202
+ }
203
+ /** Offset in minutes east of UTC at a given instant. */
204
+ offsetAtMs(instantMs) {
205
+ const parts = this.formatter.formatToParts(new Date(instantMs));
206
+ const get = (type) => Number(parts.find((p) => p.type === type)?.value ?? '0');
207
+ const localAsUtc = Date.UTC(get('year'), get('month') - 1, get('day'), get('hour'), get('minute'));
208
+ return Math.round((localAsUtc - instantMs) / 60000);
209
+ }
210
+ }
211
+ exports.PeriodClock = PeriodClock;
212
+ /** Overlap of two half-open minute ranges, in minutes (0 when disjoint). */
213
+ function overlapMinutes(a, b) {
214
+ return Math.max(0, Math.min(a.end, b.end) - Math.max(a.start, b.start));
215
+ }
216
+ exports.overlapMinutes = overlapMinutes;
217
+ /** Whether two half-open minute ranges intersect. */
218
+ function overlaps(a, b) {
219
+ return a.start < b.end && b.start < a.end;
220
+ }
221
+ exports.overlaps = overlaps;
222
+ /** Gap between two non-overlapping ranges in minutes; 0 when they overlap. */
223
+ function gapBetween(a, b) {
224
+ if (a.end <= b.start)
225
+ return b.start - a.end;
226
+ if (b.end <= a.start)
227
+ return a.start - b.end;
228
+ return 0;
229
+ }
230
+ exports.gapBetween = gapBetween;
231
+ /** Days between two ISO dates (`to - from`); negative when `to` precedes `from`. */
232
+ function daysBetween(from, to) {
233
+ return Math.round((Date.parse(`${to}T00:00:00Z`) - Date.parse(`${from}T00:00:00Z`)) / 86400000);
234
+ }
235
+ exports.daysBetween = daysBetween;
236
+ /** ISO date `days` after `date`. */
237
+ function addDays(date, days) {
238
+ return new Date(Date.parse(`${date}T00:00:00Z`) + days * 86400000).toISOString().slice(0, 10);
239
+ }
240
+ exports.addDays = addDays;
241
+ /** ISO weekday 1 (Mon) .. 7 (Sun). */
242
+ function isoWeekday(date) {
243
+ const d = new Date(`${date}T00:00:00Z`).getUTCDay();
244
+ return d === 0 ? 7 : d;
245
+ }
246
+ exports.isoWeekday = isoWeekday;
247
+ /** Minutes since local midnight for an `HH:MM` / `HH:MM:SS` string. */
248
+ function parseTimeOfDay(value, field) {
249
+ const m = TIME_OF_DAY.exec(value);
250
+ if (!m)
251
+ throw new types_1.ScheduleValidationError(`Invalid time-of-day for ${field}: "${value}" (expected HH:MM)`);
252
+ const h = Number(m[1]);
253
+ const min = Number(m[2]);
254
+ const s = m[3] === undefined ? 0 : Number(m[3]);
255
+ if (h > 24 || min > 59 || s > 59 || (h === 24 && (min > 0 || s > 0))) {
256
+ throw new types_1.ScheduleValidationError(`Invalid time-of-day for ${field}: "${value}"`);
257
+ }
258
+ return h * 60 + min + Math.round(s / 60);
259
+ }
260
+ exports.parseTimeOfDay = parseTimeOfDay;
261
+ /** Throws `ScheduleValidationError` unless `value` is a real `YYYY-MM-DD` date. */
262
+ function assertIsoDate(value, field) {
263
+ if (!ISO_DATE.test(value) || Number.isNaN(Date.parse(`${value}T00:00:00Z`))) {
264
+ throw new types_1.ScheduleValidationError(`Invalid ISO date for ${field}: "${value}" (expected YYYY-MM-DD)`);
265
+ }
266
+ }
267
+ exports.assertIsoDate = assertIsoDate;