assignment-user-matcher 1.8.0 → 1.10.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 (165) hide show
  1. package/README.md +240 -12
  2. package/dist/index.d.ts +3 -1
  3. package/dist/index.d.ts.map +1 -1
  4. package/dist/index.js +23 -1
  5. package/dist/matcher.class.d.ts +44 -2
  6. package/dist/matcher.class.d.ts.map +1 -1
  7. package/dist/matcher.class.js +393 -4
  8. package/dist/queries/pagination.d.ts +5 -1
  9. package/dist/queries/pagination.d.ts.map +1 -1
  10. package/dist/queries/pagination.js +14 -3
  11. package/dist/schedule/policy.d.ts +35 -0
  12. package/dist/schedule/policy.d.ts.map +1 -0
  13. package/dist/schedule/policy.js +62 -0
  14. package/dist/scheduling/constraints/availability.d.ts +44 -0
  15. package/dist/scheduling/constraints/availability.d.ts.map +1 -0
  16. package/dist/scheduling/constraints/availability.js +142 -0
  17. package/dist/scheduling/constraints/consecutive.d.ts +25 -0
  18. package/dist/scheduling/constraints/consecutive.d.ts.map +1 -0
  19. package/dist/scheduling/constraints/consecutive.js +215 -0
  20. package/dist/scheduling/constraints/constraint.d.ts +35 -0
  21. package/dist/scheduling/constraints/constraint.d.ts.map +1 -0
  22. package/dist/scheduling/constraints/constraint.js +97 -0
  23. package/dist/scheduling/constraints/contract.d.ts +21 -0
  24. package/dist/scheduling/constraints/contract.d.ts.map +1 -0
  25. package/dist/scheduling/constraints/contract.js +106 -0
  26. package/dist/scheduling/constraints/cost.d.ts +18 -0
  27. package/dist/scheduling/constraints/cost.d.ts.map +1 -0
  28. package/dist/scheduling/constraints/cost.js +65 -0
  29. package/dist/scheduling/constraints/daily-rest.d.ts +22 -0
  30. package/dist/scheduling/constraints/daily-rest.d.ts.map +1 -0
  31. package/dist/scheduling/constraints/daily-rest.js +118 -0
  32. package/dist/scheduling/constraints/duty-quota.d.ts +20 -0
  33. package/dist/scheduling/constraints/duty-quota.d.ts.map +1 -0
  34. package/dist/scheduling/constraints/duty-quota.js +95 -0
  35. package/dist/scheduling/constraints/engagement-floor.d.ts +28 -0
  36. package/dist/scheduling/constraints/engagement-floor.d.ts.map +1 -0
  37. package/dist/scheduling/constraints/engagement-floor.js +79 -0
  38. package/dist/scheduling/constraints/fairness.d.ts +34 -0
  39. package/dist/scheduling/constraints/fairness.d.ts.map +1 -0
  40. package/dist/scheduling/constraints/fairness.js +149 -0
  41. package/dist/scheduling/constraints/group-composition.d.ts +19 -0
  42. package/dist/scheduling/constraints/group-composition.d.ts.map +1 -0
  43. package/dist/scheduling/constraints/group-composition.js +92 -0
  44. package/dist/scheduling/constraints/hour-budget.d.ts +13 -0
  45. package/dist/scheduling/constraints/hour-budget.d.ts.map +1 -0
  46. package/dist/scheduling/constraints/hour-budget.js +59 -0
  47. package/dist/scheduling/constraints/in-shift-breaks.d.ts +24 -0
  48. package/dist/scheduling/constraints/in-shift-breaks.d.ts.map +1 -0
  49. package/dist/scheduling/constraints/in-shift-breaks.js +97 -0
  50. package/dist/scheduling/constraints/intervals.d.ts +5 -0
  51. package/dist/scheduling/constraints/intervals.d.ts.map +1 -0
  52. package/dist/scheduling/constraints/intervals.js +17 -0
  53. package/dist/scheduling/constraints/max-shift-duration.d.ts +7 -0
  54. package/dist/scheduling/constraints/max-shift-duration.d.ts.map +1 -0
  55. package/dist/scheduling/constraints/max-shift-duration.js +38 -0
  56. package/dist/scheduling/constraints/min-rest.d.ts +22 -0
  57. package/dist/scheduling/constraints/min-rest.d.ts.map +1 -0
  58. package/dist/scheduling/constraints/min-rest.js +60 -0
  59. package/dist/scheduling/constraints/min-staffing.d.ts +14 -0
  60. package/dist/scheduling/constraints/min-staffing.d.ts.map +1 -0
  61. package/dist/scheduling/constraints/min-staffing.js +59 -0
  62. package/dist/scheduling/constraints/night-work.d.ts +24 -0
  63. package/dist/scheduling/constraints/night-work.d.ts.map +1 -0
  64. package/dist/scheduling/constraints/night-work.js +163 -0
  65. package/dist/scheduling/constraints/no-overlap.d.ts +7 -0
  66. package/dist/scheduling/constraints/no-overlap.d.ts.map +1 -0
  67. package/dist/scheduling/constraints/no-overlap.js +36 -0
  68. package/dist/scheduling/constraints/notice.d.ts +44 -0
  69. package/dist/scheduling/constraints/notice.d.ts.map +1 -0
  70. package/dist/scheduling/constraints/notice.js +140 -0
  71. package/dist/scheduling/constraints/one-shift-per-day.d.ts +7 -0
  72. package/dist/scheduling/constraints/one-shift-per-day.d.ts.map +1 -0
  73. package/dist/scheduling/constraints/one-shift-per-day.js +35 -0
  74. package/dist/scheduling/constraints/overtime.d.ts +47 -0
  75. package/dist/scheduling/constraints/overtime.d.ts.map +1 -0
  76. package/dist/scheduling/constraints/overtime.js +149 -0
  77. package/dist/scheduling/constraints/protections.d.ts +21 -0
  78. package/dist/scheduling/constraints/protections.d.ts.map +1 -0
  79. package/dist/scheduling/constraints/protections.js +93 -0
  80. package/dist/scheduling/constraints/qualification.d.ts +18 -0
  81. package/dist/scheduling/constraints/qualification.d.ts.map +1 -0
  82. package/dist/scheduling/constraints/qualification.js +78 -0
  83. package/dist/scheduling/constraints/rest-days.d.ts +30 -0
  84. package/dist/scheduling/constraints/rest-days.d.ts.map +1 -0
  85. package/dist/scheduling/constraints/rest-days.js +133 -0
  86. package/dist/scheduling/constraints/rolling-hours.d.ts +24 -0
  87. package/dist/scheduling/constraints/rolling-hours.d.ts.map +1 -0
  88. package/dist/scheduling/constraints/rolling-hours.js +147 -0
  89. package/dist/scheduling/constraints/start-interval.d.ts +20 -0
  90. package/dist/scheduling/constraints/start-interval.d.ts.map +1 -0
  91. package/dist/scheduling/constraints/start-interval.js +53 -0
  92. package/dist/scheduling/constraints/support.d.ts +48 -0
  93. package/dist/scheduling/constraints/support.d.ts.map +1 -0
  94. package/dist/scheduling/constraints/support.js +97 -0
  95. package/dist/scheduling/constraints/time-off.d.ts +7 -0
  96. package/dist/scheduling/constraints/time-off.d.ts.map +1 -0
  97. package/dist/scheduling/constraints/time-off.js +42 -0
  98. package/dist/scheduling/constraints/weekly-rest.d.ts +22 -0
  99. package/dist/scheduling/constraints/weekly-rest.d.ts.map +1 -0
  100. package/dist/scheduling/constraints/weekly-rest.js +92 -0
  101. package/dist/scheduling/cost.d.ts +56 -0
  102. package/dist/scheduling/cost.d.ts.map +1 -0
  103. package/dist/scheduling/cost.js +120 -0
  104. package/dist/scheduling/engine/construction.d.ts +22 -0
  105. package/dist/scheduling/engine/construction.d.ts.map +1 -0
  106. package/dist/scheduling/engine/construction.js +97 -0
  107. package/dist/scheduling/engine/explain.d.ts +12 -0
  108. package/dist/scheduling/engine/explain.d.ts.map +1 -0
  109. package/dist/scheduling/engine/explain.js +24 -0
  110. package/dist/scheduling/engine/objective.d.ts +73 -0
  111. package/dist/scheduling/engine/objective.d.ts.map +1 -0
  112. package/dist/scheduling/engine/objective.js +164 -0
  113. package/dist/scheduling/engine/prng.d.ts +5 -0
  114. package/dist/scheduling/engine/prng.d.ts.map +1 -0
  115. package/dist/scheduling/engine/prng.js +24 -0
  116. package/dist/scheduling/engine/propagation.d.ts +19 -0
  117. package/dist/scheduling/engine/propagation.d.ts.map +1 -0
  118. package/dist/scheduling/engine/propagation.js +40 -0
  119. package/dist/scheduling/engine/search.d.ts +50 -0
  120. package/dist/scheduling/engine/search.d.ts.map +1 -0
  121. package/dist/scheduling/engine/search.js +127 -0
  122. package/dist/scheduling/engine/state.d.ts +28 -0
  123. package/dist/scheduling/engine/state.d.ts.map +1 -0
  124. package/dist/scheduling/engine/state.js +96 -0
  125. package/dist/scheduling/engine/timeline.d.ts +179 -0
  126. package/dist/scheduling/engine/timeline.d.ts.map +1 -0
  127. package/dist/scheduling/engine/timeline.js +416 -0
  128. package/dist/scheduling/engine/verdicts.d.ts +18 -0
  129. package/dist/scheduling/engine/verdicts.d.ts.map +1 -0
  130. package/dist/scheduling/engine/verdicts.js +74 -0
  131. package/dist/scheduling/index.d.ts +10 -0
  132. package/dist/scheduling/index.d.ts.map +1 -0
  133. package/dist/scheduling/index.js +29 -0
  134. package/dist/scheduling/model.d.ts +53 -0
  135. package/dist/scheduling/model.d.ts.map +1 -0
  136. package/dist/scheduling/model.js +379 -0
  137. package/dist/scheduling/operations.d.ts +134 -0
  138. package/dist/scheduling/operations.d.ts.map +1 -0
  139. package/dist/scheduling/operations.js +376 -0
  140. package/dist/scheduling/provenance.d.ts +33 -0
  141. package/dist/scheduling/provenance.d.ts.map +1 -0
  142. package/dist/scheduling/provenance.js +70 -0
  143. package/dist/scheduling/rules.d.ts +23 -0
  144. package/dist/scheduling/rules.d.ts.map +1 -0
  145. package/dist/scheduling/rules.js +37 -0
  146. package/dist/scheduling/scheduler.class.d.ts +24 -0
  147. package/dist/scheduling/scheduler.class.d.ts.map +1 -0
  148. package/dist/scheduling/scheduler.class.js +150 -0
  149. package/dist/scheduling/time.d.ts +132 -0
  150. package/dist/scheduling/time.d.ts.map +1 -0
  151. package/dist/scheduling/time.js +256 -0
  152. package/dist/scheduling/types.d.ts +932 -0
  153. package/dist/scheduling/types.d.ts.map +1 -0
  154. package/dist/scheduling/types.js +19 -0
  155. package/dist/scoring/match-score.d.ts.map +1 -1
  156. package/dist/scoring/match-score.js +1 -3
  157. package/dist/types/matcher.d.ts +195 -1
  158. package/dist/types/matcher.d.ts.map +1 -1
  159. package/dist/utils/keys.d.ts +3 -0
  160. package/dist/utils/keys.d.ts.map +1 -1
  161. package/dist/utils/keys.js +15 -0
  162. package/dist/validation/assignment-lint.d.ts +24 -0
  163. package/dist/validation/assignment-lint.d.ts.map +1 -0
  164. package/dist/validation/assignment-lint.js +132 -0
  165. package/package.json +4 -2
@@ -0,0 +1,416 @@
1
+ "use strict";
2
+ /**
3
+ * Person timeline — the data structure the EU rule families are built on.
4
+ *
5
+ * Almost every working-time rule of consequence is a question about a *window*
6
+ * of one person's timeline rather than about a single assignment:
7
+ *
8
+ * - "≤48h averaged over any 4 months" → worked minutes in a window
9
+ * - "11h rest in every rolling 24h" → longest gap in a window
10
+ * - "35h continuous rest per 7 days" → longest gap in a window
11
+ * - "≤36 shifts ending after 02:00 / 16wks" → filtered count in a window
12
+ * - "max 5 consecutive nights" → run length over entries
13
+ * - "max 6 consecutive working days" → run length over day indices
14
+ *
15
+ * So they all reduce to a handful of primitives here, and a constraint that
16
+ * needs one of them costs O(log n + hits) rather than a scan of the roster.
17
+ *
18
+ * Two design notes that matter:
19
+ *
20
+ * 1. **Keyed by person, not by contract.** CJEU C-585/19 holds that where a
21
+ * worker has several contracts with the same employer, daily rest applies to
22
+ * them taken as a whole. Aggregating per employee record would understate
23
+ * hours and overstate rest for exactly the people most at risk.
24
+ * 2. **History is first-class.** Rest and weekly-rest windows straddle the
25
+ * period boundary, so a roster built without the previous period's tail is
26
+ * non-compliant on its first days by construction. Historical entries are
27
+ * seeded at negative period minutes and are immutable.
28
+ */
29
+ Object.defineProperty(exports, "__esModule", { value: true });
30
+ exports.TimelineIndex = exports.PersonTimeline = void 0;
31
+ const time_1 = require("../time");
32
+ /**
33
+ * One person's ordered, non-overlapping-by-construction spans, with prefix sums
34
+ * for O(log n) window queries.
35
+ *
36
+ * Entries are kept sorted by start. The prefix array is rebuilt lazily, so a
37
+ * burst of assign/unassign calls during a search move costs one rebuild at the
38
+ * next query rather than one per mutation.
39
+ */
40
+ class PersonTimeline {
41
+ constructor(history = []) {
42
+ this.entries = [];
43
+ /** `prefix[i]` = total working minutes of entries `[0, i)`. */
44
+ this.prefix = [0];
45
+ /** `prefixMaxEnd[i]` = latest end among entries `[0, i)`; nondecreasing. */
46
+ this.prefixMaxEnd = [-Infinity];
47
+ this.dirty = false;
48
+ for (const entry of history)
49
+ this.entries.push({ ...entry, historical: true });
50
+ this.entries.sort(byStart);
51
+ this.rebuild();
52
+ }
53
+ /** Every entry, history first, ordered by start. */
54
+ all() {
55
+ this.ensureClean();
56
+ return this.entries;
57
+ }
58
+ /** Total working minutes currently on the timeline, history included. */
59
+ totalWorkingMinutes() {
60
+ this.ensureClean();
61
+ return this.prefix[this.prefix.length - 1];
62
+ }
63
+ add(entry) {
64
+ // Insert in place; timelines are short (tens of entries per period), so a
65
+ // splice beats re-sorting the whole array.
66
+ const at = lowerBound(this.entries, entry.start);
67
+ this.entries.splice(at, 0, entry);
68
+ this.dirty = true;
69
+ }
70
+ remove(id) {
71
+ const index = this.entries.findIndex((e) => e.id === id && !e.historical);
72
+ if (index === -1)
73
+ return false;
74
+ this.entries.splice(index, 1);
75
+ this.dirty = true;
76
+ return true;
77
+ }
78
+ has(id) {
79
+ return this.entries.some((e) => e.id === id);
80
+ }
81
+ /**
82
+ * Working minutes falling inside `window`, counting partial overlaps
83
+ * proportionally. This is the primitive behind every rolling average.
84
+ *
85
+ * Costs a binary search plus one step per overlapping entry. A person's
86
+ * timeline holds tens of entries per period, so scanning the hits beats
87
+ * maintaining a minute-resolution index — a Fenwick tree over period
88
+ * minutes would be ~45k slots per person, 22M across a 500-person solve,
89
+ * to save a walk over a few dozen items.
90
+ */
91
+ workingMinutesIn(window) {
92
+ this.ensureClean();
93
+ if (window.end <= window.start || this.entries.length === 0)
94
+ return 0;
95
+ const first = this.firstOverlapping(window.start);
96
+ let total = 0;
97
+ for (let i = first; i < this.entries.length; i++) {
98
+ const entry = this.entries[i];
99
+ if (entry.start >= window.end)
100
+ break;
101
+ total += proratedWorkingMinutes(entry, window);
102
+ }
103
+ return total;
104
+ }
105
+ /**
106
+ * Worst case of "working minutes in any window of `windowMinutes`" that
107
+ * overlaps `bounds` — the quantity a rolling average such as "≤48h in any
108
+ * 4-month window" actually limits.
109
+ *
110
+ * Checking windows on a fixed calendar grid is the classic way to get this
111
+ * wrong: a person can sit under 48h in every Mon–Sun week while working 60h
112
+ * across a Thursday-to-Wednesday stretch. The maximum is always attained by
113
+ * a window whose left edge sits on an entry boundary, so those are the only
114
+ * candidates worth evaluating.
115
+ */
116
+ maxWorkingMinutesInAnyWindow(windowMinutes, bounds) {
117
+ this.ensureClean();
118
+ if (windowMinutes <= 0)
119
+ return 0;
120
+ let worst = 0;
121
+ for (const start of this.candidateWindowStarts(windowMinutes, bounds)) {
122
+ const total = this.workingMinutesIn({ start, end: start + windowMinutes });
123
+ if (total > worst)
124
+ worst = total;
125
+ }
126
+ return worst;
127
+ }
128
+ /**
129
+ * Worst case of "longest continuous rest in any window of `windowMinutes`"
130
+ * overlapping `bounds` — what a weekly-rest rule requires a floor on.
131
+ *
132
+ * Returns `Infinity` when no candidate window applies, so an empty timeline
133
+ * never reads as a breach.
134
+ */
135
+ minLongestRestInAnyWindow(windowMinutes, bounds) {
136
+ this.ensureClean();
137
+ if (windowMinutes <= 0)
138
+ return Infinity;
139
+ let worst = Infinity;
140
+ for (const start of this.candidateWindowStarts(windowMinutes, bounds)) {
141
+ const rest = this.longestRestIn({ start, end: start + windowMinutes });
142
+ if (rest < worst)
143
+ worst = rest;
144
+ }
145
+ return worst;
146
+ }
147
+ /**
148
+ * Window left edges worth testing: every entry boundary that could put a
149
+ * window over `bounds`, plus the bounds themselves. Sliding a window until
150
+ * its edge meets a boundary never reduces the extreme being sought, so this
151
+ * finite set contains the answer.
152
+ */
153
+ candidateWindowStarts(windowMinutes, bounds) {
154
+ const starts = new Set([bounds.start, bounds.end - windowMinutes]);
155
+ for (const entry of this.entries) {
156
+ if (entry.end < bounds.start - windowMinutes || entry.start > bounds.end + windowMinutes)
157
+ continue;
158
+ starts.add(entry.start);
159
+ starts.add(entry.end - windowMinutes);
160
+ }
161
+ return [...starts];
162
+ }
163
+ /** Entries intersecting `window`, in order. */
164
+ entriesIn(window) {
165
+ this.ensureClean();
166
+ const out = [];
167
+ for (let i = this.firstOverlapping(window.start); i < this.entries.length; i++) {
168
+ const entry = this.entries[i];
169
+ if (entry.start >= window.end)
170
+ break;
171
+ if (entry.end > window.start)
172
+ out.push(entry);
173
+ }
174
+ return out;
175
+ }
176
+ /**
177
+ * Run `fn` with `entry` temporarily on the timeline, then restore it.
178
+ *
179
+ * Constraints are asked "what would assigning this pair cost", and the pair
180
+ * is not on the timeline yet — so window rules have to measure a
181
+ * hypothetical. Adding and removing around the call beats copying the
182
+ * timeline, which would allocate on every candidate evaluation in the
183
+ * search's hot loop.
184
+ *
185
+ * Idempotent: when the entry is already present (re-explaining a committed
186
+ * roster) `fn` simply runs against the timeline as it stands.
187
+ */
188
+ withEntry(entry, fn) {
189
+ if (this.has(entry.id))
190
+ return fn(this);
191
+ this.add(entry);
192
+ try {
193
+ return fn(this);
194
+ }
195
+ finally {
196
+ this.remove(entry.id);
197
+ }
198
+ }
199
+ /**
200
+ * Every free stretch inside `window`, in minutes, including the stretches at
201
+ * the window edges. Weekly-rest averaging needs the individual gaps, not
202
+ * just the longest one.
203
+ */
204
+ restGapsIn(window) {
205
+ if (window.end <= window.start)
206
+ return [];
207
+ const busy = this.entriesIn(window);
208
+ if (busy.length === 0)
209
+ return [window.end - window.start];
210
+ const gaps = [];
211
+ let cursor = window.start;
212
+ for (const entry of busy) {
213
+ if (entry.start > cursor)
214
+ gaps.push(entry.start - cursor);
215
+ cursor = Math.max(cursor, entry.end);
216
+ }
217
+ if (window.end > cursor)
218
+ gaps.push(window.end - cursor);
219
+ return gaps;
220
+ }
221
+ /**
222
+ * Longest uninterrupted free stretch inside `window`, in minutes.
223
+ *
224
+ * Gaps at the window edges count: a person with no assignments in a 7-day
225
+ * window has 7 days of rest, and a weekly-rest rule must see that.
226
+ */
227
+ longestRestIn(window) {
228
+ if (window.end <= window.start)
229
+ return 0;
230
+ const busy = this.entriesIn(window);
231
+ if (busy.length === 0)
232
+ return window.end - window.start;
233
+ let longest = 0;
234
+ let cursor = window.start;
235
+ for (const entry of busy) {
236
+ if (entry.start > cursor)
237
+ longest = Math.max(longest, entry.start - cursor);
238
+ cursor = Math.max(cursor, entry.end);
239
+ }
240
+ if (window.end > cursor)
241
+ longest = Math.max(longest, window.end - cursor);
242
+ return longest;
243
+ }
244
+ /**
245
+ * Smallest gap between `range` and any existing entry, ignoring `excludeId`.
246
+ * Returns `Infinity` when the timeline is otherwise empty, and 0 when
247
+ * something overlaps — overlap is a different rule's business.
248
+ */
249
+ minGapAround(range, excludeId) {
250
+ this.ensureClean();
251
+ let smallest = Infinity;
252
+ for (const entry of this.entries) {
253
+ if (entry.id === excludeId)
254
+ continue;
255
+ if (entry.end <= range.start)
256
+ smallest = Math.min(smallest, range.start - entry.end);
257
+ else if (entry.start >= range.end)
258
+ smallest = Math.min(smallest, entry.start - range.end);
259
+ else
260
+ return 0;
261
+ }
262
+ return smallest;
263
+ }
264
+ /** Number of entries in `window` satisfying `predicate`. */
265
+ countIn(window, predicate) {
266
+ const hits = this.entriesIn(window);
267
+ return predicate ? hits.filter(predicate).length : hits.length;
268
+ }
269
+ /**
270
+ * Longest run of consecutive entries satisfying `predicate`, where
271
+ * "consecutive" means adjacent in time order with no non-matching entry
272
+ * between them. Backs `max consecutive night shifts`.
273
+ */
274
+ longestRun(predicate) {
275
+ this.ensureClean();
276
+ let longest = 0;
277
+ let current = 0;
278
+ for (const entry of this.entries) {
279
+ if (predicate(entry)) {
280
+ current++;
281
+ if (current > longest)
282
+ longest = current;
283
+ }
284
+ else {
285
+ current = 0;
286
+ }
287
+ }
288
+ return longest;
289
+ }
290
+ /**
291
+ * Longest run of consecutive day indices on which the person has any entry.
292
+ * Backs `max consecutive working days`. `dayIndexOf` maps a period minute to
293
+ * a day so the caller's clock owns DST, not this structure.
294
+ */
295
+ longestConsecutiveDays(dayIndexOf) {
296
+ this.ensureClean();
297
+ const days = new Set();
298
+ for (const entry of this.entries)
299
+ days.add(dayIndexOf(entry.start));
300
+ const sorted = [...days].sort((a, b) => a - b);
301
+ let longest = 0;
302
+ let current = 0;
303
+ let previous;
304
+ for (const day of sorted) {
305
+ current = previous !== undefined && day === previous + 1 ? current + 1 : 1;
306
+ if (current > longest)
307
+ longest = current;
308
+ previous = day;
309
+ }
310
+ return longest;
311
+ }
312
+ /**
313
+ * First index that may overlap a window starting at `windowStart`.
314
+ *
315
+ * Entries are sorted by start but may be *nested* — a long stand-by span can
316
+ * fully contain a later-starting shift — so walking back from the lower
317
+ * bound while only the immediately preceding entry reaches past the window
318
+ * start misses the outer span. The running maximum of entry ends is
319
+ * nondecreasing, so the first index whose prefix max-end exceeds the window
320
+ * start is exactly where iteration must begin, found by binary search.
321
+ */
322
+ firstOverlapping(windowStart) {
323
+ let low = 0;
324
+ let high = this.entries.length;
325
+ while (low < high) {
326
+ const mid = (low + high) >> 1;
327
+ if (this.prefixMaxEnd[mid + 1] > windowStart)
328
+ high = mid;
329
+ else
330
+ low = mid + 1;
331
+ }
332
+ return low;
333
+ }
334
+ ensureClean() {
335
+ if (this.dirty)
336
+ this.rebuild();
337
+ }
338
+ rebuild() {
339
+ this.prefix = new Array(this.entries.length + 1);
340
+ this.prefix[0] = 0;
341
+ this.prefixMaxEnd = new Array(this.entries.length + 1);
342
+ this.prefixMaxEnd[0] = -Infinity;
343
+ for (let i = 0; i < this.entries.length; i++) {
344
+ this.prefix[i + 1] = this.prefix[i] + this.entries[i].workingMinutes;
345
+ this.prefixMaxEnd[i + 1] = Math.max(this.prefixMaxEnd[i], this.entries[i].end);
346
+ }
347
+ this.dirty = false;
348
+ }
349
+ }
350
+ exports.PersonTimeline = PersonTimeline;
351
+ /**
352
+ * All timelines for a solve, keyed by person id.
353
+ *
354
+ * The engine owns mutation; constraints only read. Keeping the index here
355
+ * rather than on `SearchState` means a constraint never has to reconstruct a
356
+ * person's history to answer a window question.
357
+ */
358
+ class TimelineIndex {
359
+ constructor(history = new Map()) {
360
+ this.byPerson = new Map();
361
+ for (const [personId, entries] of history) {
362
+ this.byPerson.set(personId, new PersonTimeline(entries));
363
+ }
364
+ }
365
+ /** The person's timeline, created empty on first use. */
366
+ for(personId) {
367
+ let timeline = this.byPerson.get(personId);
368
+ if (!timeline) {
369
+ timeline = new PersonTimeline();
370
+ this.byPerson.set(personId, timeline);
371
+ }
372
+ return timeline;
373
+ }
374
+ add(personId, entry) {
375
+ this.for(personId).add(entry);
376
+ }
377
+ remove(personId, entryId) {
378
+ return this.for(personId).remove(entryId);
379
+ }
380
+ personIds() {
381
+ return [...this.byPerson.keys()];
382
+ }
383
+ }
384
+ exports.TimelineIndex = TimelineIndex;
385
+ function byStart(a, b) {
386
+ return a.start - b.start || a.end - b.end;
387
+ }
388
+ /** First index whose entry starts at or after `start`. */
389
+ function lowerBound(entries, start) {
390
+ let low = 0;
391
+ let high = entries.length;
392
+ while (low < high) {
393
+ const mid = (low + high) >> 1;
394
+ if (entries[mid].start < start)
395
+ low = mid + 1;
396
+ else
397
+ high = mid;
398
+ }
399
+ return low;
400
+ }
401
+ /**
402
+ * Working minutes of `entry` attributable to `window`.
403
+ *
404
+ * Standby duties can have `workingMinutes` below their span (a duty that counts
405
+ * at a fraction, or only for actual call-outs), so a partial overlap is scaled
406
+ * by the same fraction rather than clipped to elapsed time.
407
+ */
408
+ function proratedWorkingMinutes(entry, window) {
409
+ const span = entry.end - entry.start;
410
+ if (span <= 0)
411
+ return 0;
412
+ const inside = (0, time_1.overlapMinutes)(entry, window);
413
+ if (inside === span)
414
+ return entry.workingMinutes;
415
+ return (entry.workingMinutes * inside) / span;
416
+ }
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Verdict collection — the single place a roster is judged.
3
+ *
4
+ * Both the solver's result assembly and `checkCompliance` run through here.
5
+ * That is deliberate: an earlier version had the solver report only aggregate
6
+ * violations while the compliance check evaluated every pair, so a solve could
7
+ * announce "no hard violations" on a roster the compliance check then rejected.
8
+ * Two judgement paths always drift, and the one that drifts is the one nobody
9
+ * is reading at the time.
10
+ */
11
+ import type { AssignmentPair, ConstraintViolation, RuleVerdict, SearchState } from '../types';
12
+ /** Every rule's verdict on one pair, in registry order. */
13
+ export declare function verdictsFor(state: SearchState, pair: AssignmentPair): RuleVerdict[];
14
+ /** Breaches attributable to individual assignments in the committed roster. */
15
+ export declare function collectPairViolations(state: SearchState): ConstraintViolation[];
16
+ /** Breaches only a whole-roster view can see: coverage, quotas, team fairness. */
17
+ export declare function collectAggregateViolations(state: SearchState): ConstraintViolation[];
18
+ //# sourceMappingURL=verdicts.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"verdicts.d.ts","sourceRoot":"","sources":["../../../src/scheduling/engine/verdicts.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAEH,OAAO,KAAK,EAAE,cAAc,EAAE,mBAAmB,EAAE,WAAW,EAAE,WAAW,EAAE,MAAM,UAAU,CAAC;AAE9F,2DAA2D;AAC3D,wBAAgB,WAAW,CAAC,KAAK,EAAE,WAAW,EAAE,IAAI,EAAE,cAAc,GAAG,WAAW,EAAE,CAoBnF;AAED,+EAA+E;AAC/E,wBAAgB,qBAAqB,CAAC,KAAK,EAAE,WAAW,GAAG,mBAAmB,EAAE,CAqB/E;AAED,kFAAkF;AAClF,wBAAgB,0BAA0B,CAAC,KAAK,EAAE,WAAW,GAAG,mBAAmB,EAAE,CASpF"}
@@ -0,0 +1,74 @@
1
+ "use strict";
2
+ /**
3
+ * Verdict collection — the single place a roster is judged.
4
+ *
5
+ * Both the solver's result assembly and `checkCompliance` run through here.
6
+ * That is deliberate: an earlier version had the solver report only aggregate
7
+ * violations while the compliance check evaluated every pair, so a solve could
8
+ * announce "no hard violations" on a roster the compliance check then rejected.
9
+ * Two judgement paths always drift, and the one that drifts is the one nobody
10
+ * is reading at the time.
11
+ */
12
+ Object.defineProperty(exports, "__esModule", { value: true });
13
+ exports.collectAggregateViolations = exports.collectPairViolations = exports.verdictsFor = void 0;
14
+ /** Every rule's verdict on one pair, in registry order. */
15
+ function verdictsFor(state, pair) {
16
+ const out = [];
17
+ for (const constraint of state.ctx.constraints) {
18
+ if (constraint.verdict) {
19
+ out.push(constraint.verdict(state, pair));
20
+ continue;
21
+ }
22
+ // Rules predating the structured SPI still contribute, through their
23
+ // delta/explain pair, so no rule is silently skipped.
24
+ const breach = constraint.delta(state, pair);
25
+ const message = constraint.explain(state, pair);
26
+ out.push({
27
+ ruleId: constraint.id,
28
+ pass: breach === 0,
29
+ severity: constraint.hardness,
30
+ message: message ?? `satisfies ${constraint.id}`,
31
+ citation: constraint.citation,
32
+ });
33
+ }
34
+ return out;
35
+ }
36
+ exports.verdictsFor = verdictsFor;
37
+ /** Breaches attributable to individual assignments in the committed roster. */
38
+ function collectPairViolations(state) {
39
+ const out = [];
40
+ for (const [shiftInstanceId, employees] of state.assignments) {
41
+ for (const employeeId of employees) {
42
+ for (const v of verdictsFor(state, { employeeId, shiftInstanceId })) {
43
+ if (v.pass)
44
+ continue;
45
+ out.push({
46
+ constraintId: v.ruleId,
47
+ severity: v.severity,
48
+ employeeId,
49
+ shiftInstanceId,
50
+ message: v.message,
51
+ citation: v.citation,
52
+ actual: v.actual,
53
+ required: v.required,
54
+ unit: v.unit,
55
+ });
56
+ }
57
+ }
58
+ }
59
+ return out;
60
+ }
61
+ exports.collectPairViolations = collectPairViolations;
62
+ /** Breaches only a whole-roster view can see: coverage, quotas, team fairness. */
63
+ function collectAggregateViolations(state) {
64
+ const out = [];
65
+ for (const constraint of state.ctx.constraints) {
66
+ if (!constraint.evaluate)
67
+ continue;
68
+ for (const violation of constraint.evaluate(state)) {
69
+ out.push({ citation: constraint.citation, ...violation });
70
+ }
71
+ }
72
+ return out;
73
+ }
74
+ exports.collectAggregateViolations = collectAggregateViolations;
@@ -0,0 +1,10 @@
1
+ /** Public surface of the scheduling module. */
2
+ export { ShiftScheduler, solveSchedule, ENGINE_VERSION } from './scheduler.class';
3
+ export { ScheduleValidationError } from './types';
4
+ /** Directive 2003/88/EC Art 3 floor (11h), the default when `minRestMinutes` is omitted. */
5
+ export { DEFAULT_MIN_REST_MINUTES } from './constraints/min-rest';
6
+ export { checkCompliance, explainCandidate, repairSchedule, rankCandidates, diagnoseInfeasibility, type ComplianceReport, type Disruption, type RepairCandidate, type RepairResult, type InfeasibilityReport, } from './operations';
7
+ export { PeriodClock, type MinuteRange, type ClockRange } from './time';
8
+ export { hours, days, weeklyAverageOver } from './rules';
9
+ export type { AssignmentPair, AvailabilityRule, BreakRule, ClockRangeConfig, ConsecutiveRule, ConstraintOptions, ConstraintViolation, DailyRestRule, DutyClassification, DutyQuota, Employee, EmployeeContract, EmployeeCost, EmployeeProtection, EngagementRule, FairnessRule, HistoricalAssignment, LedgerEntry, ModelContext, NightVolumeQuota, NightWorkRule, NoticeRule, ObjectiveWeights, OvertimeRule, Qualification, RestDayRule, RollingAverage, RuleVerdict, ScheduleInput, ScheduleProvenance, ScheduleResult, ScheduledAssignment, SchedulingConstraint, SearchState, Severity, ShiftInstance, ShiftTemplate, TimeOffEntry, WeeklyRestRule, WorkingTimeLimits, WorkingTimeRules, } from './types';
10
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/scheduling/index.ts"],"names":[],"mappings":"AAAA,+CAA+C;AAC/C,OAAO,EAAE,cAAc,EAAE,aAAa,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;AAClF,OAAO,EAAE,uBAAuB,EAAE,MAAM,SAAS,CAAC;AAClD,4FAA4F;AAC5F,OAAO,EAAE,wBAAwB,EAAE,MAAM,wBAAwB,CAAC;AAGlE,OAAO,EACH,eAAe,EACf,gBAAgB,EAChB,cAAc,EACd,cAAc,EACd,qBAAqB,EACrB,KAAK,gBAAgB,EACrB,KAAK,UAAU,EACf,KAAK,eAAe,EACpB,KAAK,YAAY,EACjB,KAAK,mBAAmB,GAC3B,MAAM,cAAc,CAAC;AAGtB,OAAO,EAAE,WAAW,EAAE,KAAK,WAAW,EAAE,KAAK,UAAU,EAAE,MAAM,QAAQ,CAAC;AAIxE,OAAO,EAAE,KAAK,EAAE,IAAI,EAAE,iBAAiB,EAAE,MAAM,SAAS,CAAC;AAEzD,YAAY,EACR,cAAc,EACd,gBAAgB,EAChB,SAAS,EACT,gBAAgB,EAChB,eAAe,EACf,iBAAiB,EACjB,mBAAmB,EACnB,aAAa,EACb,kBAAkB,EAClB,SAAS,EACT,QAAQ,EACR,gBAAgB,EAChB,YAAY,EACZ,kBAAkB,EAClB,cAAc,EACd,YAAY,EACZ,oBAAoB,EACpB,WAAW,EACX,YAAY,EACZ,gBAAgB,EAChB,aAAa,EACb,UAAU,EACV,gBAAgB,EAChB,YAAY,EACZ,aAAa,EACb,WAAW,EACX,cAAc,EACd,WAAW,EACX,aAAa,EACb,kBAAkB,EAClB,cAAc,EACd,mBAAmB,EACnB,oBAAoB,EACpB,WAAW,EACX,QAAQ,EACR,aAAa,EACb,aAAa,EACb,YAAY,EACZ,cAAc,EACd,iBAAiB,EACjB,gBAAgB,GACnB,MAAM,SAAS,CAAC"}
@@ -0,0 +1,29 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.weeklyAverageOver = exports.days = exports.hours = exports.PeriodClock = exports.diagnoseInfeasibility = exports.rankCandidates = exports.repairSchedule = exports.explainCandidate = exports.checkCompliance = exports.DEFAULT_MIN_REST_MINUTES = exports.ScheduleValidationError = exports.ENGINE_VERSION = exports.solveSchedule = exports.ShiftScheduler = void 0;
4
+ /** Public surface of the scheduling module. */
5
+ var scheduler_class_1 = require("./scheduler.class");
6
+ Object.defineProperty(exports, "ShiftScheduler", { enumerable: true, get: function () { return scheduler_class_1.ShiftScheduler; } });
7
+ Object.defineProperty(exports, "solveSchedule", { enumerable: true, get: function () { return scheduler_class_1.solveSchedule; } });
8
+ Object.defineProperty(exports, "ENGINE_VERSION", { enumerable: true, get: function () { return scheduler_class_1.ENGINE_VERSION; } });
9
+ var types_1 = require("./types");
10
+ Object.defineProperty(exports, "ScheduleValidationError", { enumerable: true, get: function () { return types_1.ScheduleValidationError; } });
11
+ /** Directive 2003/88/EC Art 3 floor (11h), the default when `minRestMinutes` is omitted. */
12
+ var min_rest_1 = require("./constraints/min-rest");
13
+ Object.defineProperty(exports, "DEFAULT_MIN_REST_MINUTES", { enumerable: true, get: function () { return min_rest_1.DEFAULT_MIN_REST_MINUTES; } });
14
+ // Operational APIs: validate, explain, repair, diagnose.
15
+ var operations_1 = require("./operations");
16
+ Object.defineProperty(exports, "checkCompliance", { enumerable: true, get: function () { return operations_1.checkCompliance; } });
17
+ Object.defineProperty(exports, "explainCandidate", { enumerable: true, get: function () { return operations_1.explainCandidate; } });
18
+ Object.defineProperty(exports, "repairSchedule", { enumerable: true, get: function () { return operations_1.repairSchedule; } });
19
+ Object.defineProperty(exports, "rankCandidates", { enumerable: true, get: function () { return operations_1.rankCandidates; } });
20
+ Object.defineProperty(exports, "diagnoseInfeasibility", { enumerable: true, get: function () { return operations_1.diagnoseInfeasibility; } });
21
+ // Time model, exported so hosts can resolve the same wall-clock the engine does.
22
+ var time_1 = require("./time");
23
+ Object.defineProperty(exports, "PeriodClock", { enumerable: true, get: function () { return time_1.PeriodClock; } });
24
+ // Rule-authoring arithmetic (no jurisdiction values, just the conversions
25
+ // people get wrong — notably weekly-average → rolling-window-total).
26
+ var rules_1 = require("./rules");
27
+ Object.defineProperty(exports, "hours", { enumerable: true, get: function () { return rules_1.hours; } });
28
+ Object.defineProperty(exports, "days", { enumerable: true, get: function () { return rules_1.days; } });
29
+ Object.defineProperty(exports, "weeklyAverageOver", { enumerable: true, get: function () { return rules_1.weeklyAverageOver; } });
@@ -0,0 +1,53 @@
1
+ /**
2
+ * Model normalization — pure logic.
3
+ *
4
+ * Turns the caller-facing `ScheduleInput` into the fully-indexed `ModelContext`
5
+ * the engine and constraints operate on: shift templates are expanded into
6
+ * dated shift instances (unique `(templateId, date)` ids, so same-named shifts
7
+ * on different days never collide), wall-clock times are resolved through a
8
+ * DST-correct `PeriodClock`, employee time-off becomes blocked minute
9
+ * intervals, per-person rule overrides are merged, and pre-period history is
10
+ * seeded onto person timelines. Everything is side-effect free; the scheduler
11
+ * facade owns sequencing.
12
+ *
13
+ * Two normalizations here carry legal weight and are easy to miss:
14
+ *
15
+ * - **Working minutes ≠ elapsed minutes.** Unpaid breaks come off, and a duty
16
+ * classification can scale the rest. Hour budgets and rolling averages must
17
+ * use working minutes; rest gaps must use the elapsed span.
18
+ * - **Person, not contract.** Rest and window rules aggregate on `personId`
19
+ * (CJEU C-585/19), which defaults to the employee id but must be shared by
20
+ * records belonging to one human.
21
+ *
22
+ * Differences from legacy: the Python solver parsed `"YYYY-MM-DDTHH:MM:SS"`
23
+ * strings, wrapped overnight durations in `abs()`, deduped shift *names* across
24
+ * days, and read only the first key of each time-off entry. All of those are
25
+ * modeled properly here.
26
+ */
27
+ import type { AvailabilityRule, ConstraintOptions, ModelContext, ObjectiveWeights, ScheduleInput, SchedulingConstraint, ShiftInstance, ShiftTemplate, WorkingTimeRules } from './types';
28
+ import { PeriodClock, MINUTES_PER_DAY } from './time';
29
+ export { daysBetween, addDays } from './time';
30
+ /** Expand one template into its dated instances inside the period. */
31
+ export declare function expandTemplate(template: ShiftTemplate, clock: PeriodClock, periodDays: number, context: {
32
+ nightRule?: WorkingTimeRules['nightWork'];
33
+ publicHolidays: Set<string>;
34
+ }): ShiftInstance[];
35
+ /**
36
+ * Merge the global rule set with one person's overrides.
37
+ *
38
+ * A shallow per-family merge, not a deep one: a person's `dailyRest` replaces
39
+ * the global `dailyRest` outright. Half-overriding a rule family is how you get
40
+ * a minor who inherits an adult's night window, so the boundary is the family.
41
+ */
42
+ export declare function mergeRules(base: WorkingTimeRules | undefined, override: WorkingTimeRules | undefined): WorkingTimeRules;
43
+ /** Resolve built-in constraints with caller hardness/weight overrides, then append customs. */
44
+ export declare function resolveConstraints(options: ConstraintOptions | undefined, rules?: WorkingTimeRules, objectives?: ObjectiveWeights): SchedulingConstraint[];
45
+ /**
46
+ * Normalize and validate the scheduling problem. Throws
47
+ * `ScheduleValidationError` on malformed input — never a silent wrong schedule.
48
+ */
49
+ export declare function buildModel(input: ScheduleInput): ModelContext;
50
+ /** Whether an availability rule applies to a shift instance. */
51
+ export declare function availabilityApplies(rule: AvailabilityRule, inst: ShiftInstance): boolean;
52
+ export { MINUTES_PER_DAY };
53
+ //# sourceMappingURL=model.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"model.d.ts","sourceRoot":"","sources":["../../src/scheduling/model.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AAEH,OAAO,KAAK,EACR,gBAAgB,EAChB,iBAAiB,EAGjB,YAAY,EACZ,gBAAgB,EAChB,aAAa,EACb,oBAAoB,EACpB,aAAa,EACb,aAAa,EACb,gBAAgB,EACnB,MAAM,SAAS,CAAC;AAMjB,OAAO,EAAE,WAAW,EAAE,eAAe,EAAmE,MAAM,QAAQ,CAAC;AAEvH,OAAO,EAAE,WAAW,EAAE,OAAO,EAAE,MAAM,QAAQ,CAAC;AAE9C,sEAAsE;AACtE,wBAAgB,cAAc,CAC1B,QAAQ,EAAE,aAAa,EACvB,KAAK,EAAE,WAAW,EAClB,UAAU,EAAE,MAAM,EAClB,OAAO,EAAE;IAAE,SAAS,CAAC,EAAE,gBAAgB,CAAC,WAAW,CAAC,CAAC;IAAC,cAAc,EAAE,GAAG,CAAC,MAAM,CAAC,CAAA;CAAE,GACpF,aAAa,EAAE,CAwFjB;AA4FD;;;;;;GAMG;AACH,wBAAgB,UAAU,CAAC,IAAI,EAAE,gBAAgB,GAAG,SAAS,EAAE,QAAQ,EAAE,gBAAgB,GAAG,SAAS,GAAG,gBAAgB,CAIvH;AAED,+FAA+F;AAC/F,wBAAgB,kBAAkB,CAC9B,OAAO,EAAE,iBAAiB,GAAG,SAAS,EACtC,KAAK,CAAC,EAAE,gBAAgB,EACxB,UAAU,CAAC,EAAE,gBAAgB,GAC9B,oBAAoB,EAAE,CAexB;AAgCD;;;GAGG;AACH,wBAAgB,UAAU,CAAC,KAAK,EAAE,aAAa,GAAG,YAAY,CAiG7D;AAED,gEAAgE;AAChE,wBAAgB,mBAAmB,CAAC,IAAI,EAAE,gBAAgB,EAAE,IAAI,EAAE,aAAa,GAAG,OAAO,CAKxF;AAED,OAAO,EAAE,eAAe,EAAE,CAAC"}