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,50 @@
1
+ /**
2
+ * Large-neighborhood search with late acceptance — pure logic.
3
+ *
4
+ * Until the wall-clock budget runs out: destroy a neighborhood (biased toward
5
+ * understaffed and tag-short instances), repair greedily, and accept against a
6
+ * *late* comparison rather than against the best-so-far.
7
+ *
8
+ * Why late acceptance rather than the strict hill climb this replaced: comparing
9
+ * every candidate against the incumbent best rejects any move that is even
10
+ * marginally worse, so the search stalls on the first local optimum it reaches
11
+ * and then spends its whole budget rediscovering it. Late Acceptance Hill
12
+ * Climbing compares against the score from `historyLength` iterations ago, which
13
+ * lets the search drift through slightly worse states and out of a basin, while
14
+ * still refusing sustained deterioration. It has one tunable, which is its main
15
+ * advantage over simulated annealing here — a temperature schedule would need
16
+ * calibrating per problem size, and this does not.
17
+ *
18
+ * The other change is that iterations no longer clone the whole state. The old
19
+ * loop rebuilt the working state from the best state on every pass, which is
20
+ * O(assignments) per iteration before any evaluation happens; at 500 employees
21
+ * × 31 days that dominated the budget. Now the working state is mutated in
22
+ * place and only rolled back when a move is rejected.
23
+ */
24
+ import type { ModelContext } from '../types';
25
+ import type { PropagationResult } from './propagation';
26
+ import { type LexScore } from './objective';
27
+ import { type InternalState } from './state';
28
+ export interface SearchOptions {
29
+ objective: 'standard' | 'balanced';
30
+ minHoursWeight: number;
31
+ timeBudgetMs: number;
32
+ rand: () => number;
33
+ now?: () => number;
34
+ /** Late-acceptance history length. Larger accepts more drift. */
35
+ historyLength?: number;
36
+ /** Called whenever a new best is found, for anytime reporting. */
37
+ onImprovement?: (state: InternalState, score: LexScore) => void;
38
+ }
39
+ export interface SearchOutcome {
40
+ best: InternalState;
41
+ evaluatedVariants: number;
42
+ }
43
+ /**
44
+ * Run the LNS loop on `state` in place, returning the best state found.
45
+ *
46
+ * `state` is consumed: it becomes the working state. The returned best is a
47
+ * separate snapshot, so callers may keep using it after the search ends.
48
+ */
49
+ export declare function improveWithLns(ctx: ModelContext, state: InternalState, propagation: PropagationResult, options: SearchOptions, createEmptyState: () => InternalState): SearchOutcome;
50
+ //# sourceMappingURL=search.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"search.d.ts","sourceRoot":"","sources":["../../../src/scheduling/engine/search.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;AAEH,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,UAAU,CAAC;AAC7C,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,eAAe,CAAC;AAEvD,OAAO,EAAgE,KAAK,QAAQ,EAAE,MAAM,aAAa,CAAC;AAC1G,OAAO,EAAmC,KAAK,aAAa,EAAE,MAAM,SAAS,CAAC;AAG9E,MAAM,WAAW,aAAa;IAC1B,SAAS,EAAE,UAAU,GAAG,UAAU,CAAC;IACnC,cAAc,EAAE,MAAM,CAAC;IACvB,YAAY,EAAE,MAAM,CAAC;IACrB,IAAI,EAAE,MAAM,MAAM,CAAC;IACnB,GAAG,CAAC,EAAE,MAAM,MAAM,CAAC;IACnB,iEAAiE;IACjE,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,kEAAkE;IAClE,aAAa,CAAC,EAAE,CAAC,KAAK,EAAE,aAAa,EAAE,KAAK,EAAE,QAAQ,KAAK,IAAI,CAAC;CACnE;AAED,MAAM,WAAW,aAAa;IAC1B,IAAI,EAAE,aAAa,CAAC;IACpB,iBAAiB,EAAE,MAAM,CAAC;CAC7B;AAiCD;;;;;GAKG;AACH,wBAAgB,cAAc,CAC1B,GAAG,EAAE,YAAY,EACjB,KAAK,EAAE,aAAa,EACpB,WAAW,EAAE,iBAAiB,EAC9B,OAAO,EAAE,aAAa,EACtB,gBAAgB,EAAE,MAAM,aAAa,GACtC,aAAa,CA4Ef"}
@@ -0,0 +1,127 @@
1
+ "use strict";
2
+ /**
3
+ * Large-neighborhood search with late acceptance — pure logic.
4
+ *
5
+ * Until the wall-clock budget runs out: destroy a neighborhood (biased toward
6
+ * understaffed and tag-short instances), repair greedily, and accept against a
7
+ * *late* comparison rather than against the best-so-far.
8
+ *
9
+ * Why late acceptance rather than the strict hill climb this replaced: comparing
10
+ * every candidate against the incumbent best rejects any move that is even
11
+ * marginally worse, so the search stalls on the first local optimum it reaches
12
+ * and then spends its whole budget rediscovering it. Late Acceptance Hill
13
+ * Climbing compares against the score from `historyLength` iterations ago, which
14
+ * lets the search drift through slightly worse states and out of a basin, while
15
+ * still refusing sustained deterioration. It has one tunable, which is its main
16
+ * advantage over simulated annealing here — a temperature schedule would need
17
+ * calibrating per problem size, and this does not.
18
+ *
19
+ * The other change is that iterations no longer clone the whole state. The old
20
+ * loop rebuilt the working state from the best state on every pass, which is
21
+ * O(assignments) per iteration before any evaluation happens; at 500 employees
22
+ * × 31 days that dominated the budget. Now the working state is mutated in
23
+ * place and only rolled back when a move is rejected.
24
+ */
25
+ Object.defineProperty(exports, "__esModule", { value: true });
26
+ exports.improveWithLns = void 0;
27
+ const construction_1 = require("./construction");
28
+ const objective_1 = require("./objective");
29
+ const state_1 = require("./state");
30
+ const prng_1 = require("./prng");
31
+ const DEFAULT_HISTORY_LENGTH = 50;
32
+ const DESTROY_FRACTION = 0.15;
33
+ const MIN_DESTROY = 3;
34
+ /** Copy a state's assignments into a fresh state (indices and reasons preserved). */
35
+ function cloneInto(from, into) {
36
+ for (const { employeeId, instanceId } of (0, state_1.assignedPairs)(from)) {
37
+ const reasons = from.reasons.get(`${employeeId}|${instanceId}`) ?? [];
38
+ (0, state_1.assign)(into, employeeId, instanceId, [...reasons]);
39
+ }
40
+ }
41
+ /** Pick a destroy neighborhood: understaffed/tag-short instances first, then random. */
42
+ function pickNeighborhood(ctx, state, rand, size) {
43
+ const hot = new Set();
44
+ for (const inst of ctx.instances) {
45
+ if ((0, objective_1.slotShortage)(ctx, state, inst.id) > 0 || (0, objective_1.tagShortage)(ctx, state, inst.id) > 0)
46
+ hot.add(inst.id);
47
+ }
48
+ const pairs = (0, state_1.assignedPairs)(state).filter(({ employeeId, instanceId }) => !ctx.pinned.has(`${employeeId}|${instanceId}`));
49
+ (0, prng_1.shuffle)(pairs, rand);
50
+ pairs.sort((a, b) => Number(hot.has(b.instanceId)) - Number(hot.has(a.instanceId)));
51
+ return pairs.slice(0, Math.min(size, pairs.length));
52
+ }
53
+ /**
54
+ * Run the LNS loop on `state` in place, returning the best state found.
55
+ *
56
+ * `state` is consumed: it becomes the working state. The returned best is a
57
+ * separate snapshot, so callers may keep using it after the search ends.
58
+ */
59
+ function improveWithLns(ctx, state, propagation, options, createEmptyState) {
60
+ const now = options.now ?? Date.now;
61
+ const deadline = now() + Math.max(0, options.timeBudgetMs);
62
+ const rand = options.rand;
63
+ const evaluate = (s) => (0, objective_1.scoreLex)(ctx, s, options.objective, options.minHoursWeight);
64
+ const working = state;
65
+ let workingScore = evaluate(working);
66
+ let best = createEmptyState();
67
+ cloneInto(working, best);
68
+ let bestScore = workingScore;
69
+ let evaluatedVariants = 1;
70
+ // Late-acceptance history, seeded with the starting score.
71
+ const historyLength = Math.max(1, options.historyLength ?? DEFAULT_HISTORY_LENGTH);
72
+ const history = new Array(historyLength).fill(workingScore);
73
+ let iteration = 0;
74
+ while (now() < deadline) {
75
+ const total = (0, state_1.assignedPairs)(working).length;
76
+ if (total === 0)
77
+ break;
78
+ const size = Math.max(MIN_DESTROY, Math.floor(total * DESTROY_FRACTION));
79
+ const neighborhood = pickNeighborhood(ctx, working, rand, size);
80
+ if (neighborhood.length === 0)
81
+ break;
82
+ // Remember what was removed so a rejected move can be undone exactly,
83
+ // including the reason strings, which the result reports.
84
+ const removed = neighborhood.map(({ employeeId, instanceId }) => ({
85
+ employeeId,
86
+ instanceId,
87
+ reasons: working.reasons.get(`${employeeId}|${instanceId}`) ?? [],
88
+ }));
89
+ const touchedInstances = new Set();
90
+ for (const { employeeId, instanceId } of removed) {
91
+ (0, state_1.unassign)(working, employeeId, instanceId);
92
+ touchedInstances.add(instanceId);
93
+ }
94
+ const addedBefore = new Set((0, state_1.assignedPairs)(working).map((p) => `${p.employeeId}|${p.instanceId}`));
95
+ (0, construction_1.greedyFill)(ctx, working, propagation, options.objective, rand, [...touchedInstances]);
96
+ // A destroy can free capacity that lets other understaffed slots fill.
97
+ (0, construction_1.greedyFill)(ctx, working, propagation, options.objective, rand);
98
+ const candidateScore = evaluate(working);
99
+ evaluatedVariants++;
100
+ const compareAgainst = history[iteration % historyLength];
101
+ const accepted = (0, objective_1.compareScores)(candidateScore, compareAgainst) <= 0 || (0, objective_1.compareScores)(candidateScore, workingScore) <= 0;
102
+ if (accepted) {
103
+ workingScore = candidateScore;
104
+ if ((0, objective_1.isBetter)(candidateScore, bestScore)) {
105
+ bestScore = candidateScore;
106
+ const next = createEmptyState();
107
+ cloneInto(working, next);
108
+ best = next;
109
+ options.onImprovement?.(best, bestScore);
110
+ }
111
+ }
112
+ else {
113
+ // Roll back: drop whatever the repair added, restore what we removed.
114
+ for (const { employeeId, instanceId } of (0, state_1.assignedPairs)(working)) {
115
+ if (!addedBefore.has(`${employeeId}|${instanceId}`))
116
+ (0, state_1.unassign)(working, employeeId, instanceId);
117
+ }
118
+ for (const { employeeId, instanceId, reasons } of removed) {
119
+ (0, state_1.assign)(working, employeeId, instanceId, [...reasons]);
120
+ }
121
+ }
122
+ history[iteration % historyLength] = workingScore;
123
+ iteration++;
124
+ }
125
+ return { best, evaluatedVariants };
126
+ }
127
+ exports.improveWithLns = improveWithLns;
@@ -0,0 +1,28 @@
1
+ /**
2
+ * Search state — the mutable assignment matrix the engine owns and constraints
3
+ * read. Kept deliberately small: three indices plus derived minutes and the
4
+ * per-person timelines, all updated together on every assign/unassign so
5
+ * constraint `delta` calls stay local rather than rebuilding a person's
6
+ * schedule from scratch.
7
+ */
8
+ import type { ModelContext, SearchState } from '../types';
9
+ export interface InternalState extends SearchState {
10
+ /** Per-pair selection reasons recorded by construction/repair, surfaced in the result. */
11
+ reasons: Map<string, string[]>;
12
+ }
13
+ export declare function createState(ctx: ModelContext): InternalState;
14
+ export declare function pairKey(employeeId: string, instanceId: string): string;
15
+ export declare function assign(state: InternalState, employeeId: string, instanceId: string, reasons: string[]): void;
16
+ export declare function unassign(state: InternalState, employeeId: string, instanceId: string): void;
17
+ /**
18
+ * Timeline entries are keyed by employee *and* instance, not by instance alone:
19
+ * two contracts of the same person share a timeline, so an instance id on its
20
+ * own would not identify which record's entry to remove.
21
+ */
22
+ export declare function timelineEntryId(employeeId: string, instanceId: string): string;
23
+ /** Snapshot as a flat list of assigned pairs (stable order: instance, then employee). */
24
+ export declare function assignedPairs(state: InternalState): Array<{
25
+ employeeId: string;
26
+ instanceId: string;
27
+ }>;
28
+ //# sourceMappingURL=state.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"state.d.ts","sourceRoot":"","sources":["../../../src/scheduling/engine/state.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,KAAK,EAAE,YAAY,EAAE,WAAW,EAAE,MAAM,UAAU,CAAC;AAG1D,MAAM,WAAW,aAAc,SAAQ,WAAW;IAC9C,0FAA0F;IAC1F,OAAO,EAAE,GAAG,CAAC,MAAM,EAAE,MAAM,EAAE,CAAC,CAAC;CAClC;AAED,wBAAgB,WAAW,CAAC,GAAG,EAAE,YAAY,GAAG,aAAa,CAsB5D;AAED,wBAAgB,OAAO,CAAC,UAAU,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,GAAG,MAAM,CAEtE;AAED,wBAAgB,MAAM,CAAC,KAAK,EAAE,aAAa,EAAE,UAAU,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,GAAG,IAAI,CAqB5G;AAED,wBAAgB,QAAQ,CAAC,KAAK,EAAE,aAAa,EAAE,UAAU,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,GAAG,IAAI,CAW3F;AAED;;;;GAIG;AACH,wBAAgB,eAAe,CAAC,UAAU,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,GAAG,MAAM,CAE9E;AAED,yFAAyF;AACzF,wBAAgB,aAAa,CAAC,KAAK,EAAE,aAAa,GAAG,KAAK,CAAC;IAAE,UAAU,EAAE,MAAM,CAAC;IAAC,UAAU,EAAE,MAAM,CAAA;CAAE,CAAC,CAQrG"}
@@ -0,0 +1,96 @@
1
+ "use strict";
2
+ /**
3
+ * Search state — the mutable assignment matrix the engine owns and constraints
4
+ * read. Kept deliberately small: three indices plus derived minutes and the
5
+ * per-person timelines, all updated together on every assign/unassign so
6
+ * constraint `delta` calls stay local rather than rebuilding a person's
7
+ * schedule from scratch.
8
+ */
9
+ Object.defineProperty(exports, "__esModule", { value: true });
10
+ exports.assignedPairs = exports.timelineEntryId = exports.unassign = exports.assign = exports.pairKey = exports.createState = void 0;
11
+ const timeline_1 = require("./timeline");
12
+ function createState(ctx) {
13
+ const assignments = new Map();
14
+ const byEmployee = new Map();
15
+ const minutesByEmployee = new Map();
16
+ for (const inst of ctx.instances)
17
+ assignments.set(inst.id, new Set());
18
+ for (const emp of ctx.employees) {
19
+ byEmployee.set(emp.id, new Set());
20
+ minutesByEmployee.set(emp.id, 0);
21
+ }
22
+ return {
23
+ ctx,
24
+ assignments,
25
+ byEmployee,
26
+ minutesByEmployee,
27
+ // Seeded from history so rest and rolling windows see across the period
28
+ // boundary from the very first evaluation.
29
+ timelines: new timeline_1.TimelineIndex(ctx.history),
30
+ reasons: new Map(),
31
+ isAssigned(employeeId, instanceId) {
32
+ return assignments.get(instanceId)?.has(employeeId) ?? false;
33
+ },
34
+ };
35
+ }
36
+ exports.createState = createState;
37
+ function pairKey(employeeId, instanceId) {
38
+ return `${employeeId}|${instanceId}`;
39
+ }
40
+ exports.pairKey = pairKey;
41
+ function assign(state, employeeId, instanceId, reasons) {
42
+ const inst = state.ctx.instanceById.get(instanceId);
43
+ // Unknown ids are a no-op, not a partial write: booking minutes for an
44
+ // employee the model never saw would corrupt the fairness and cost sums.
45
+ if (!inst || !state.ctx.employeeById.has(employeeId))
46
+ return;
47
+ state.assignments.get(instanceId)?.add(employeeId);
48
+ state.byEmployee.get(employeeId)?.add(instanceId);
49
+ // `minutesByEmployee` tracks *working* time, which unpaid breaks and duty
50
+ // classification can put below the elapsed span.
51
+ state.minutesByEmployee.set(employeeId, (state.minutesByEmployee.get(employeeId) ?? 0) + inst.workingMinutes);
52
+ const personId = state.ctx.personIdOf.get(employeeId) ?? employeeId;
53
+ state.timelines.add(personId, {
54
+ id: timelineEntryId(employeeId, instanceId),
55
+ start: inst.startMinute,
56
+ end: inst.endMinute,
57
+ workingMinutes: inst.workingMinutes,
58
+ tag: inst.shiftTypeTag,
59
+ });
60
+ state.reasons.set(pairKey(employeeId, instanceId), reasons);
61
+ }
62
+ exports.assign = assign;
63
+ function unassign(state, employeeId, instanceId) {
64
+ const inst = state.ctx.instanceById.get(instanceId);
65
+ if (!inst || !state.ctx.employeeById.has(employeeId))
66
+ return;
67
+ state.assignments.get(instanceId)?.delete(employeeId);
68
+ state.byEmployee.get(employeeId)?.delete(instanceId);
69
+ state.minutesByEmployee.set(employeeId, (state.minutesByEmployee.get(employeeId) ?? 0) - inst.workingMinutes);
70
+ const personId = state.ctx.personIdOf.get(employeeId) ?? employeeId;
71
+ state.timelines.remove(personId, timelineEntryId(employeeId, instanceId));
72
+ state.reasons.delete(pairKey(employeeId, instanceId));
73
+ }
74
+ exports.unassign = unassign;
75
+ /**
76
+ * Timeline entries are keyed by employee *and* instance, not by instance alone:
77
+ * two contracts of the same person share a timeline, so an instance id on its
78
+ * own would not identify which record's entry to remove.
79
+ */
80
+ function timelineEntryId(employeeId, instanceId) {
81
+ return `${employeeId}@@${instanceId}`;
82
+ }
83
+ exports.timelineEntryId = timelineEntryId;
84
+ /** Snapshot as a flat list of assigned pairs (stable order: instance, then employee). */
85
+ function assignedPairs(state) {
86
+ const out = [];
87
+ for (const inst of state.ctx.instances) {
88
+ const set = state.assignments.get(inst.id);
89
+ if (!set)
90
+ continue;
91
+ for (const employeeId of [...set].sort())
92
+ out.push({ employeeId, instanceId: inst.id });
93
+ }
94
+ return out;
95
+ }
96
+ exports.assignedPairs = assignedPairs;
@@ -0,0 +1,179 @@
1
+ /**
2
+ * Person timeline — the data structure the EU rule families are built on.
3
+ *
4
+ * Almost every working-time rule of consequence is a question about a *window*
5
+ * of one person's timeline rather than about a single assignment:
6
+ *
7
+ * - "≤48h averaged over any 4 months" → worked minutes in a window
8
+ * - "11h rest in every rolling 24h" → longest gap in a window
9
+ * - "35h continuous rest per 7 days" → longest gap in a window
10
+ * - "≤36 shifts ending after 02:00 / 16wks" → filtered count in a window
11
+ * - "max 5 consecutive nights" → run length over entries
12
+ * - "max 6 consecutive working days" → run length over day indices
13
+ *
14
+ * So they all reduce to a handful of primitives here, and a constraint that
15
+ * needs one of them costs O(log n + hits) rather than a scan of the roster.
16
+ *
17
+ * Two design notes that matter:
18
+ *
19
+ * 1. **Keyed by person, not by contract.** CJEU C-585/19 holds that where a
20
+ * worker has several contracts with the same employer, daily rest applies to
21
+ * them taken as a whole. Aggregating per employee record would understate
22
+ * hours and overstate rest for exactly the people most at risk.
23
+ * 2. **History is first-class.** Rest and weekly-rest windows straddle the
24
+ * period boundary, so a roster built without the previous period's tail is
25
+ * non-compliant on its first days by construction. Historical entries are
26
+ * seeded at negative period minutes and are immutable.
27
+ */
28
+ import type { MinuteRange } from '../time';
29
+ /** One occupied span on a person's timeline. */
30
+ export interface TimelineEntry extends MinuteRange {
31
+ /** Shift instance id, or a synthetic id for historical//absence spans. */
32
+ id: string;
33
+ /** Minutes that count as working time — may differ from the span for standby duties. */
34
+ workingMinutes: number;
35
+ /** Free-form classification tag used by sequence rules (e.g. a shift type). */
36
+ tag?: string;
37
+ /** Historical entries are immutable and never returned by the mutable views. */
38
+ historical?: boolean;
39
+ }
40
+ /**
41
+ * One person's ordered, non-overlapping-by-construction spans, with prefix sums
42
+ * for O(log n) window queries.
43
+ *
44
+ * Entries are kept sorted by start. The prefix array is rebuilt lazily, so a
45
+ * burst of assign/unassign calls during a search move costs one rebuild at the
46
+ * next query rather than one per mutation.
47
+ */
48
+ export declare class PersonTimeline {
49
+ private entries;
50
+ /** `prefix[i]` = total working minutes of entries `[0, i)`. */
51
+ private prefix;
52
+ /** `prefixMaxEnd[i]` = latest end among entries `[0, i)`; nondecreasing. */
53
+ private prefixMaxEnd;
54
+ private dirty;
55
+ constructor(history?: TimelineEntry[]);
56
+ /** Every entry, history first, ordered by start. */
57
+ all(): readonly TimelineEntry[];
58
+ /** Total working minutes currently on the timeline, history included. */
59
+ totalWorkingMinutes(): number;
60
+ add(entry: TimelineEntry): void;
61
+ remove(id: string): boolean;
62
+ has(id: string): boolean;
63
+ /**
64
+ * Working minutes falling inside `window`, counting partial overlaps
65
+ * proportionally. This is the primitive behind every rolling average.
66
+ *
67
+ * Costs a binary search plus one step per overlapping entry. A person's
68
+ * timeline holds tens of entries per period, so scanning the hits beats
69
+ * maintaining a minute-resolution index — a Fenwick tree over period
70
+ * minutes would be ~45k slots per person, 22M across a 500-person solve,
71
+ * to save a walk over a few dozen items.
72
+ */
73
+ workingMinutesIn(window: MinuteRange): number;
74
+ /**
75
+ * Worst case of "working minutes in any window of `windowMinutes`" that
76
+ * overlaps `bounds` — the quantity a rolling average such as "≤48h in any
77
+ * 4-month window" actually limits.
78
+ *
79
+ * Checking windows on a fixed calendar grid is the classic way to get this
80
+ * wrong: a person can sit under 48h in every Mon–Sun week while working 60h
81
+ * across a Thursday-to-Wednesday stretch. The maximum is always attained by
82
+ * a window whose left edge sits on an entry boundary, so those are the only
83
+ * candidates worth evaluating.
84
+ */
85
+ maxWorkingMinutesInAnyWindow(windowMinutes: number, bounds: MinuteRange): number;
86
+ /**
87
+ * Worst case of "longest continuous rest in any window of `windowMinutes`"
88
+ * overlapping `bounds` — what a weekly-rest rule requires a floor on.
89
+ *
90
+ * Returns `Infinity` when no candidate window applies, so an empty timeline
91
+ * never reads as a breach.
92
+ */
93
+ minLongestRestInAnyWindow(windowMinutes: number, bounds: MinuteRange): number;
94
+ /**
95
+ * Window left edges worth testing: every entry boundary that could put a
96
+ * window over `bounds`, plus the bounds themselves. Sliding a window until
97
+ * its edge meets a boundary never reduces the extreme being sought, so this
98
+ * finite set contains the answer.
99
+ */
100
+ private candidateWindowStarts;
101
+ /** Entries intersecting `window`, in order. */
102
+ entriesIn(window: MinuteRange): TimelineEntry[];
103
+ /**
104
+ * Run `fn` with `entry` temporarily on the timeline, then restore it.
105
+ *
106
+ * Constraints are asked "what would assigning this pair cost", and the pair
107
+ * is not on the timeline yet — so window rules have to measure a
108
+ * hypothetical. Adding and removing around the call beats copying the
109
+ * timeline, which would allocate on every candidate evaluation in the
110
+ * search's hot loop.
111
+ *
112
+ * Idempotent: when the entry is already present (re-explaining a committed
113
+ * roster) `fn` simply runs against the timeline as it stands.
114
+ */
115
+ withEntry<T>(entry: TimelineEntry, fn: (timeline: PersonTimeline) => T): T;
116
+ /**
117
+ * Every free stretch inside `window`, in minutes, including the stretches at
118
+ * the window edges. Weekly-rest averaging needs the individual gaps, not
119
+ * just the longest one.
120
+ */
121
+ restGapsIn(window: MinuteRange): number[];
122
+ /**
123
+ * Longest uninterrupted free stretch inside `window`, in minutes.
124
+ *
125
+ * Gaps at the window edges count: a person with no assignments in a 7-day
126
+ * window has 7 days of rest, and a weekly-rest rule must see that.
127
+ */
128
+ longestRestIn(window: MinuteRange): number;
129
+ /**
130
+ * Smallest gap between `range` and any existing entry, ignoring `excludeId`.
131
+ * Returns `Infinity` when the timeline is otherwise empty, and 0 when
132
+ * something overlaps — overlap is a different rule's business.
133
+ */
134
+ minGapAround(range: MinuteRange, excludeId?: string): number;
135
+ /** Number of entries in `window` satisfying `predicate`. */
136
+ countIn(window: MinuteRange, predicate?: (entry: TimelineEntry) => boolean): number;
137
+ /**
138
+ * Longest run of consecutive entries satisfying `predicate`, where
139
+ * "consecutive" means adjacent in time order with no non-matching entry
140
+ * between them. Backs `max consecutive night shifts`.
141
+ */
142
+ longestRun(predicate: (entry: TimelineEntry) => boolean): number;
143
+ /**
144
+ * Longest run of consecutive day indices on which the person has any entry.
145
+ * Backs `max consecutive working days`. `dayIndexOf` maps a period minute to
146
+ * a day so the caller's clock owns DST, not this structure.
147
+ */
148
+ longestConsecutiveDays(dayIndexOf: (minute: number) => number): number;
149
+ /**
150
+ * First index that may overlap a window starting at `windowStart`.
151
+ *
152
+ * Entries are sorted by start but may be *nested* — a long stand-by span can
153
+ * fully contain a later-starting shift — so walking back from the lower
154
+ * bound while only the immediately preceding entry reaches past the window
155
+ * start misses the outer span. The running maximum of entry ends is
156
+ * nondecreasing, so the first index whose prefix max-end exceeds the window
157
+ * start is exactly where iteration must begin, found by binary search.
158
+ */
159
+ private firstOverlapping;
160
+ private ensureClean;
161
+ private rebuild;
162
+ }
163
+ /**
164
+ * All timelines for a solve, keyed by person id.
165
+ *
166
+ * The engine owns mutation; constraints only read. Keeping the index here
167
+ * rather than on `SearchState` means a constraint never has to reconstruct a
168
+ * person's history to answer a window question.
169
+ */
170
+ export declare class TimelineIndex {
171
+ private readonly byPerson;
172
+ constructor(history?: Map<string, TimelineEntry[]>);
173
+ /** The person's timeline, created empty on first use. */
174
+ for(personId: string): PersonTimeline;
175
+ add(personId: string, entry: TimelineEntry): void;
176
+ remove(personId: string, entryId: string): boolean;
177
+ personIds(): string[];
178
+ }
179
+ //# sourceMappingURL=timeline.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"timeline.d.ts","sourceRoot":"","sources":["../../../src/scheduling/engine/timeline.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AAEH,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,SAAS,CAAC;AAG3C,gDAAgD;AAChD,MAAM,WAAW,aAAc,SAAQ,WAAW;IAC9C,0EAA0E;IAC1E,EAAE,EAAE,MAAM,CAAC;IACX,wFAAwF;IACxF,cAAc,EAAE,MAAM,CAAC;IACvB,+EAA+E;IAC/E,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,gFAAgF;IAChF,UAAU,CAAC,EAAE,OAAO,CAAC;CACxB;AAED;;;;;;;GAOG;AACH,qBAAa,cAAc;IACvB,OAAO,CAAC,OAAO,CAAuB;IACtC,+DAA+D;IAC/D,OAAO,CAAC,MAAM,CAAiB;IAC/B,4EAA4E;IAC5E,OAAO,CAAC,YAAY,CAAyB;IAC7C,OAAO,CAAC,KAAK,CAAS;gBAEV,OAAO,GAAE,aAAa,EAAO;IAMzC,oDAAoD;IACpD,GAAG,IAAI,SAAS,aAAa,EAAE;IAK/B,yEAAyE;IACzE,mBAAmB,IAAI,MAAM;IAK7B,GAAG,CAAC,KAAK,EAAE,aAAa,GAAG,IAAI;IAQ/B,MAAM,CAAC,EAAE,EAAE,MAAM,GAAG,OAAO;IAQ3B,GAAG,CAAC,EAAE,EAAE,MAAM,GAAG,OAAO;IAIxB;;;;;;;;;OASG;IACH,gBAAgB,CAAC,MAAM,EAAE,WAAW,GAAG,MAAM;IAc7C;;;;;;;;;;OAUG;IACH,4BAA4B,CAAC,aAAa,EAAE,MAAM,EAAE,MAAM,EAAE,WAAW,GAAG,MAAM;IAWhF;;;;;;OAMG;IACH,yBAAyB,CAAC,aAAa,EAAE,MAAM,EAAE,MAAM,EAAE,WAAW,GAAG,MAAM;IAW7E;;;;;OAKG;IACH,OAAO,CAAC,qBAAqB;IAU7B,+CAA+C;IAC/C,SAAS,CAAC,MAAM,EAAE,WAAW,GAAG,aAAa,EAAE;IAW/C;;;;;;;;;;;OAWG;IACH,SAAS,CAAC,CAAC,EAAE,KAAK,EAAE,aAAa,EAAE,EAAE,EAAE,CAAC,QAAQ,EAAE,cAAc,KAAK,CAAC,GAAG,CAAC;IAU1E;;;;OAIG;IACH,UAAU,CAAC,MAAM,EAAE,WAAW,GAAG,MAAM,EAAE;IAezC;;;;;OAKG;IACH,aAAa,CAAC,MAAM,EAAE,WAAW,GAAG,MAAM;IAe1C;;;;OAIG;IACH,YAAY,CAAC,KAAK,EAAE,WAAW,EAAE,SAAS,CAAC,EAAE,MAAM,GAAG,MAAM;IAY5D,4DAA4D;IAC5D,OAAO,CAAC,MAAM,EAAE,WAAW,EAAE,SAAS,CAAC,EAAE,CAAC,KAAK,EAAE,aAAa,KAAK,OAAO,GAAG,MAAM;IAKnF;;;;OAIG;IACH,UAAU,CAAC,SAAS,EAAE,CAAC,KAAK,EAAE,aAAa,KAAK,OAAO,GAAG,MAAM;IAehE;;;;OAIG;IACH,sBAAsB,CAAC,UAAU,EAAE,CAAC,MAAM,EAAE,MAAM,KAAK,MAAM,GAAG,MAAM;IAiBtE;;;;;;;;;OASG;IACH,OAAO,CAAC,gBAAgB;IAWxB,OAAO,CAAC,WAAW;IAInB,OAAO,CAAC,OAAO;CAWlB;AAED;;;;;;GAMG;AACH,qBAAa,aAAa;IACtB,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAqC;gBAElD,OAAO,GAAE,GAAG,CAAC,MAAM,EAAE,aAAa,EAAE,CAAa;IAM7D,yDAAyD;IACzD,GAAG,CAAC,QAAQ,EAAE,MAAM,GAAG,cAAc;IASrC,GAAG,CAAC,QAAQ,EAAE,MAAM,EAAE,KAAK,EAAE,aAAa,GAAG,IAAI;IAIjD,MAAM,CAAC,QAAQ,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,OAAO;IAIlD,SAAS,IAAI,MAAM,EAAE;CAGxB"}