assignment-user-matcher 1.9.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 (150) hide show
  1. package/README.md +106 -1
  2. package/dist/index.d.ts +1 -0
  3. package/dist/index.d.ts.map +1 -1
  4. package/dist/index.js +19 -1
  5. package/dist/matcher.class.d.ts.map +1 -1
  6. package/dist/matcher.class.js +11 -0
  7. package/dist/scheduling/constraints/availability.d.ts +44 -0
  8. package/dist/scheduling/constraints/availability.d.ts.map +1 -0
  9. package/dist/scheduling/constraints/availability.js +142 -0
  10. package/dist/scheduling/constraints/consecutive.d.ts +25 -0
  11. package/dist/scheduling/constraints/consecutive.d.ts.map +1 -0
  12. package/dist/scheduling/constraints/consecutive.js +215 -0
  13. package/dist/scheduling/constraints/constraint.d.ts +35 -0
  14. package/dist/scheduling/constraints/constraint.d.ts.map +1 -0
  15. package/dist/scheduling/constraints/constraint.js +97 -0
  16. package/dist/scheduling/constraints/contract.d.ts +21 -0
  17. package/dist/scheduling/constraints/contract.d.ts.map +1 -0
  18. package/dist/scheduling/constraints/contract.js +106 -0
  19. package/dist/scheduling/constraints/cost.d.ts +18 -0
  20. package/dist/scheduling/constraints/cost.d.ts.map +1 -0
  21. package/dist/scheduling/constraints/cost.js +65 -0
  22. package/dist/scheduling/constraints/daily-rest.d.ts +22 -0
  23. package/dist/scheduling/constraints/daily-rest.d.ts.map +1 -0
  24. package/dist/scheduling/constraints/daily-rest.js +118 -0
  25. package/dist/scheduling/constraints/duty-quota.d.ts +20 -0
  26. package/dist/scheduling/constraints/duty-quota.d.ts.map +1 -0
  27. package/dist/scheduling/constraints/duty-quota.js +95 -0
  28. package/dist/scheduling/constraints/engagement-floor.d.ts +28 -0
  29. package/dist/scheduling/constraints/engagement-floor.d.ts.map +1 -0
  30. package/dist/scheduling/constraints/engagement-floor.js +79 -0
  31. package/dist/scheduling/constraints/fairness.d.ts +34 -0
  32. package/dist/scheduling/constraints/fairness.d.ts.map +1 -0
  33. package/dist/scheduling/constraints/fairness.js +149 -0
  34. package/dist/scheduling/constraints/group-composition.d.ts +19 -0
  35. package/dist/scheduling/constraints/group-composition.d.ts.map +1 -0
  36. package/dist/scheduling/constraints/group-composition.js +92 -0
  37. package/dist/scheduling/constraints/hour-budget.d.ts +13 -0
  38. package/dist/scheduling/constraints/hour-budget.d.ts.map +1 -0
  39. package/dist/scheduling/constraints/hour-budget.js +59 -0
  40. package/dist/scheduling/constraints/in-shift-breaks.d.ts +24 -0
  41. package/dist/scheduling/constraints/in-shift-breaks.d.ts.map +1 -0
  42. package/dist/scheduling/constraints/in-shift-breaks.js +97 -0
  43. package/dist/scheduling/constraints/intervals.d.ts +5 -0
  44. package/dist/scheduling/constraints/intervals.d.ts.map +1 -0
  45. package/dist/scheduling/constraints/intervals.js +17 -0
  46. package/dist/scheduling/constraints/max-shift-duration.d.ts +7 -0
  47. package/dist/scheduling/constraints/max-shift-duration.d.ts.map +1 -0
  48. package/dist/scheduling/constraints/max-shift-duration.js +38 -0
  49. package/dist/scheduling/constraints/min-rest.d.ts +22 -0
  50. package/dist/scheduling/constraints/min-rest.d.ts.map +1 -0
  51. package/dist/scheduling/constraints/min-rest.js +60 -0
  52. package/dist/scheduling/constraints/min-staffing.d.ts +14 -0
  53. package/dist/scheduling/constraints/min-staffing.d.ts.map +1 -0
  54. package/dist/scheduling/constraints/min-staffing.js +59 -0
  55. package/dist/scheduling/constraints/night-work.d.ts +24 -0
  56. package/dist/scheduling/constraints/night-work.d.ts.map +1 -0
  57. package/dist/scheduling/constraints/night-work.js +163 -0
  58. package/dist/scheduling/constraints/no-overlap.d.ts +7 -0
  59. package/dist/scheduling/constraints/no-overlap.d.ts.map +1 -0
  60. package/dist/scheduling/constraints/no-overlap.js +36 -0
  61. package/dist/scheduling/constraints/notice.d.ts +44 -0
  62. package/dist/scheduling/constraints/notice.d.ts.map +1 -0
  63. package/dist/scheduling/constraints/notice.js +140 -0
  64. package/dist/scheduling/constraints/one-shift-per-day.d.ts +7 -0
  65. package/dist/scheduling/constraints/one-shift-per-day.d.ts.map +1 -0
  66. package/dist/scheduling/constraints/one-shift-per-day.js +35 -0
  67. package/dist/scheduling/constraints/overtime.d.ts +47 -0
  68. package/dist/scheduling/constraints/overtime.d.ts.map +1 -0
  69. package/dist/scheduling/constraints/overtime.js +149 -0
  70. package/dist/scheduling/constraints/protections.d.ts +21 -0
  71. package/dist/scheduling/constraints/protections.d.ts.map +1 -0
  72. package/dist/scheduling/constraints/protections.js +93 -0
  73. package/dist/scheduling/constraints/qualification.d.ts +18 -0
  74. package/dist/scheduling/constraints/qualification.d.ts.map +1 -0
  75. package/dist/scheduling/constraints/qualification.js +78 -0
  76. package/dist/scheduling/constraints/rest-days.d.ts +30 -0
  77. package/dist/scheduling/constraints/rest-days.d.ts.map +1 -0
  78. package/dist/scheduling/constraints/rest-days.js +133 -0
  79. package/dist/scheduling/constraints/rolling-hours.d.ts +24 -0
  80. package/dist/scheduling/constraints/rolling-hours.d.ts.map +1 -0
  81. package/dist/scheduling/constraints/rolling-hours.js +147 -0
  82. package/dist/scheduling/constraints/start-interval.d.ts +20 -0
  83. package/dist/scheduling/constraints/start-interval.d.ts.map +1 -0
  84. package/dist/scheduling/constraints/start-interval.js +53 -0
  85. package/dist/scheduling/constraints/support.d.ts +48 -0
  86. package/dist/scheduling/constraints/support.d.ts.map +1 -0
  87. package/dist/scheduling/constraints/support.js +97 -0
  88. package/dist/scheduling/constraints/time-off.d.ts +7 -0
  89. package/dist/scheduling/constraints/time-off.d.ts.map +1 -0
  90. package/dist/scheduling/constraints/time-off.js +42 -0
  91. package/dist/scheduling/constraints/weekly-rest.d.ts +22 -0
  92. package/dist/scheduling/constraints/weekly-rest.d.ts.map +1 -0
  93. package/dist/scheduling/constraints/weekly-rest.js +92 -0
  94. package/dist/scheduling/cost.d.ts +56 -0
  95. package/dist/scheduling/cost.d.ts.map +1 -0
  96. package/dist/scheduling/cost.js +120 -0
  97. package/dist/scheduling/engine/construction.d.ts +22 -0
  98. package/dist/scheduling/engine/construction.d.ts.map +1 -0
  99. package/dist/scheduling/engine/construction.js +97 -0
  100. package/dist/scheduling/engine/explain.d.ts +12 -0
  101. package/dist/scheduling/engine/explain.d.ts.map +1 -0
  102. package/dist/scheduling/engine/explain.js +24 -0
  103. package/dist/scheduling/engine/objective.d.ts +73 -0
  104. package/dist/scheduling/engine/objective.d.ts.map +1 -0
  105. package/dist/scheduling/engine/objective.js +164 -0
  106. package/dist/scheduling/engine/prng.d.ts +5 -0
  107. package/dist/scheduling/engine/prng.d.ts.map +1 -0
  108. package/dist/scheduling/engine/prng.js +24 -0
  109. package/dist/scheduling/engine/propagation.d.ts +19 -0
  110. package/dist/scheduling/engine/propagation.d.ts.map +1 -0
  111. package/dist/scheduling/engine/propagation.js +40 -0
  112. package/dist/scheduling/engine/search.d.ts +50 -0
  113. package/dist/scheduling/engine/search.d.ts.map +1 -0
  114. package/dist/scheduling/engine/search.js +127 -0
  115. package/dist/scheduling/engine/state.d.ts +28 -0
  116. package/dist/scheduling/engine/state.d.ts.map +1 -0
  117. package/dist/scheduling/engine/state.js +96 -0
  118. package/dist/scheduling/engine/timeline.d.ts +179 -0
  119. package/dist/scheduling/engine/timeline.d.ts.map +1 -0
  120. package/dist/scheduling/engine/timeline.js +416 -0
  121. package/dist/scheduling/engine/verdicts.d.ts +18 -0
  122. package/dist/scheduling/engine/verdicts.d.ts.map +1 -0
  123. package/dist/scheduling/engine/verdicts.js +74 -0
  124. package/dist/scheduling/index.d.ts +10 -0
  125. package/dist/scheduling/index.d.ts.map +1 -0
  126. package/dist/scheduling/index.js +29 -0
  127. package/dist/scheduling/model.d.ts +53 -0
  128. package/dist/scheduling/model.d.ts.map +1 -0
  129. package/dist/scheduling/model.js +379 -0
  130. package/dist/scheduling/operations.d.ts +134 -0
  131. package/dist/scheduling/operations.d.ts.map +1 -0
  132. package/dist/scheduling/operations.js +376 -0
  133. package/dist/scheduling/provenance.d.ts +33 -0
  134. package/dist/scheduling/provenance.d.ts.map +1 -0
  135. package/dist/scheduling/provenance.js +70 -0
  136. package/dist/scheduling/rules.d.ts +23 -0
  137. package/dist/scheduling/rules.d.ts.map +1 -0
  138. package/dist/scheduling/rules.js +37 -0
  139. package/dist/scheduling/scheduler.class.d.ts +24 -0
  140. package/dist/scheduling/scheduler.class.d.ts.map +1 -0
  141. package/dist/scheduling/scheduler.class.js +150 -0
  142. package/dist/scheduling/time.d.ts +132 -0
  143. package/dist/scheduling/time.d.ts.map +1 -0
  144. package/dist/scheduling/time.js +256 -0
  145. package/dist/scheduling/types.d.ts +932 -0
  146. package/dist/scheduling/types.d.ts.map +1 -0
  147. package/dist/scheduling/types.js +19 -0
  148. package/dist/types/matcher.d.ts +15 -0
  149. package/dist/types/matcher.d.ts.map +1 -1
  150. package/package.json +4 -2
@@ -0,0 +1,164 @@
1
+ "use strict";
2
+ /**
3
+ * Objective scoring — pure logic.
4
+ *
5
+ * The score has three lexicographic levels rather than one number:
6
+ *
7
+ * - **hard** — legal or physical impossibility (rest, overlap, expired
8
+ * qualification, contract breach);
9
+ * - **medium** — coverage: unfilled slots and unmet tag requirements;
10
+ * - **soft** — cost, fairness, preferences, hour-balance.
11
+ *
12
+ * They are compared in order, never summed. A weighted sum would let a large
13
+ * enough soft gain buy a hard breach — arrange the weights unluckily and the
14
+ * solver "discovers" that under-resting one person improves fairness for
15
+ * everyone else. Lexicographic ordering makes that trade unrepresentable
16
+ * instead of merely unlikely.
17
+ *
18
+ * Within a level, breaches contribute their *magnitude*, so a rest gap ten
19
+ * minutes short scores better than one six hours short. Local search needs that
20
+ * gradient to climb out of an infeasible region; a 0/1 flag leaves it on a
21
+ * plateau with nothing to follow.
22
+ *
23
+ * Aggregate constraints (`evaluate`) are deliberately not run per move — they
24
+ * are O(roster) and the search calls the objective in its innermost loop. The
25
+ * cheap aggregates that steer the search (coverage, fairness) have dedicated
26
+ * terms here; the full `evaluate` pass runs once when the result is assembled.
27
+ */
28
+ Object.defineProperty(exports, "__esModule", { value: true });
29
+ exports.score = exports.scoreLex = exports.softBreaches = exports.breachTotals = exports.minHoursShortfalls = exports.hoursVariance = exports.unfilledSlots = exports.tagShortage = exports.slotShortage = exports.isBetter = exports.compareScores = exports.DEFAULT_SOFT_WEIGHT = exports.MIN_HOURS_WEIGHT = exports.TAG_SHORTFALL_WEIGHT = exports.UNFILLED_WEIGHT = void 0;
30
+ const fairness_1 = require("../constraints/fairness");
31
+ const availability_1 = require("../constraints/availability");
32
+ exports.UNFILLED_WEIGHT = 10000;
33
+ exports.TAG_SHORTFALL_WEIGHT = 5000;
34
+ exports.MIN_HOURS_WEIGHT = 100;
35
+ /** Default weight applied to a soft constraint that does not declare one. */
36
+ exports.DEFAULT_SOFT_WEIGHT = 1;
37
+ /** Negative when `a` is better than `b`, positive when worse, 0 when equal. */
38
+ function compareScores(a, b) {
39
+ if (a.hard !== b.hard)
40
+ return a.hard - b.hard;
41
+ if (a.medium !== b.medium)
42
+ return a.medium - b.medium;
43
+ return a.soft - b.soft;
44
+ }
45
+ exports.compareScores = compareScores;
46
+ function isBetter(a, b) {
47
+ return compareScores(a, b) < 0;
48
+ }
49
+ exports.isBetter = isBetter;
50
+ /** Missing assignees for an instance (0 when fully staffed). */
51
+ function slotShortage(ctx, state, instanceId) {
52
+ const inst = ctx.instanceById.get(instanceId);
53
+ if (!inst)
54
+ return 0;
55
+ return Math.max(0, inst.minEmployees - (state.assignments.get(instanceId)?.size ?? 0));
56
+ }
57
+ exports.slotShortage = slotShortage;
58
+ /** Missing tagged assignees, summed over the instance's tag requirements. */
59
+ function tagShortage(ctx, state, instanceId) {
60
+ const inst = ctx.instanceById.get(instanceId);
61
+ if (!inst)
62
+ return 0;
63
+ const assigned = state.assignments.get(instanceId);
64
+ let short = 0;
65
+ for (const [tag, needed] of Object.entries(inst.tagRequirements)) {
66
+ let have = 0;
67
+ if (assigned) {
68
+ for (const employeeId of assigned)
69
+ if (ctx.employeeTags.get(employeeId)?.has(tag))
70
+ have++;
71
+ }
72
+ short += Math.max(0, needed - have);
73
+ }
74
+ return short;
75
+ }
76
+ exports.tagShortage = tagShortage;
77
+ /** Total unfilled capacity across the period, in person-slots. */
78
+ function unfilledSlots(ctx, state) {
79
+ let total = 0;
80
+ for (const inst of ctx.instances)
81
+ total += slotShortage(ctx, state, inst.id);
82
+ return total;
83
+ }
84
+ exports.unfilledSlots = unfilledSlots;
85
+ /** Variance of worked minutes across employees (0 for an empty roster). */
86
+ function hoursVariance(ctx, state) {
87
+ if (ctx.employees.length === 0)
88
+ return 0;
89
+ const values = ctx.employees.map((e) => state.minutesByEmployee.get(e.id) ?? 0);
90
+ const mean = values.reduce((a, b) => a + b, 0) / values.length;
91
+ return values.reduce((acc, v) => acc + (v - mean) * (v - mean), 0) / values.length;
92
+ }
93
+ exports.hoursVariance = hoursVariance;
94
+ /** Number of employees below their soft min-hours bound. */
95
+ function minHoursShortfalls(ctx, state) {
96
+ let n = 0;
97
+ for (const e of ctx.employees) {
98
+ if (e.minHoursForPeriod !== undefined && (state.minutesByEmployee.get(e.id) ?? 0) < e.minHoursForPeriod * 60)
99
+ n++;
100
+ }
101
+ return n;
102
+ }
103
+ exports.minHoursShortfalls = minHoursShortfalls;
104
+ /**
105
+ * Weighted breach total per level, over the currently assigned pairs.
106
+ *
107
+ * This is what gives `SchedulingConstraint.weight` teeth — a caller who softens
108
+ * a built-in via `overrides`, or registers a custom rule, now moves the score
109
+ * instead of being silently ignored.
110
+ */
111
+ function breachTotals(ctx, state) {
112
+ const totals = { hard: 0, medium: 0, soft: 0 };
113
+ // `min-staffing` and `fairness` have dedicated terms below; evaluating their
114
+ // per-pair delta here would either double-count or contribute a constant 0.
115
+ const scored = ctx.constraints.filter((c) => c.id !== 'min-staffing' && c.id !== 'fairness');
116
+ if (scored.length === 0)
117
+ return totals;
118
+ for (const [instanceId, employees] of state.assignments) {
119
+ for (const employeeId of employees) {
120
+ for (const c of scored) {
121
+ const d = c.delta(state, { employeeId, shiftInstanceId: instanceId });
122
+ if (d > 0)
123
+ totals[c.hardness] += d * (c.weight ?? exports.DEFAULT_SOFT_WEIGHT);
124
+ }
125
+ }
126
+ }
127
+ return totals;
128
+ }
129
+ exports.breachTotals = breachTotals;
130
+ /** Backwards-compatible soft-breach total, for callers that want a single figure. */
131
+ function softBreaches(ctx, state) {
132
+ return breachTotals(ctx, state).soft;
133
+ }
134
+ exports.softBreaches = softBreaches;
135
+ /** The full three-level score. Lower is better at every level. */
136
+ function scoreLex(ctx, state, objective, minHoursWeight, fairnessRules) {
137
+ const totals = breachTotals(ctx, state);
138
+ for (const inst of ctx.instances) {
139
+ totals.medium += slotShortage(ctx, state, inst.id) * exports.UNFILLED_WEIGHT;
140
+ totals.medium += tagShortage(ctx, state, inst.id) * exports.TAG_SHORTFALL_WEIGHT;
141
+ }
142
+ totals.soft += minHoursShortfalls(ctx, state) * (minHoursWeight || exports.MIN_HOURS_WEIGHT);
143
+ totals.soft += (0, fairness_1.fairnessPenalty)(state, fairnessRules ?? ctx.rules?.fairness);
144
+ // Preferred/avoid availability windows are scored, not advisory: avoided
145
+ // assignments cost, preferred ones credit, weighted per rule.
146
+ totals.soft += (0, availability_1.preferencePenalty)(state);
147
+ if (objective === 'balanced')
148
+ totals.soft += hoursVariance(ctx, state) / 60; // hours-scale variance term
149
+ return totals;
150
+ }
151
+ exports.scoreLex = scoreLex;
152
+ /**
153
+ * Flattened score, lower is better.
154
+ *
155
+ * Retained for callers that need one number. The level separation is preserved
156
+ * by scaling, but comparisons should prefer `compareScores` — a flattened score
157
+ * can only approximate a lexicographic order, and at extreme magnitudes the
158
+ * approximation leaks.
159
+ */
160
+ function score(ctx, state, objective, minHoursWeight) {
161
+ const lex = scoreLex(ctx, state, objective, minHoursWeight);
162
+ return lex.hard * 1e12 + lex.medium * 1e6 + lex.soft;
163
+ }
164
+ exports.score = score;
@@ -0,0 +1,5 @@
1
+ /** mulberry32 — small seeded PRNG so runs are reproducible without a dependency. */
2
+ export declare function createPrng(seed: number): () => number;
3
+ /** In-place Fisher–Yates shuffle driven by `rand`. */
4
+ export declare function shuffle<T>(arr: T[], rand: () => number): T[];
5
+ //# sourceMappingURL=prng.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"prng.d.ts","sourceRoot":"","sources":["../../../src/scheduling/engine/prng.ts"],"names":[],"mappings":"AAAA,oFAAoF;AACpF,wBAAgB,UAAU,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,MAAM,CASrD;AAED,sDAAsD;AACtD,wBAAgB,OAAO,CAAC,CAAC,EAAE,GAAG,EAAE,CAAC,EAAE,EAAE,IAAI,EAAE,MAAM,MAAM,GAAG,CAAC,EAAE,CAM5D"}
@@ -0,0 +1,24 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.shuffle = exports.createPrng = void 0;
4
+ /** mulberry32 — small seeded PRNG so runs are reproducible without a dependency. */
5
+ function createPrng(seed) {
6
+ let a = seed >>> 0;
7
+ return () => {
8
+ a = (a + 0x6d2b79f5) >>> 0;
9
+ let t = a;
10
+ t = Math.imul(t ^ (t >>> 15), t | 1);
11
+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
12
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
13
+ };
14
+ }
15
+ exports.createPrng = createPrng;
16
+ /** In-place Fisher–Yates shuffle driven by `rand`. */
17
+ function shuffle(arr, rand) {
18
+ for (let i = arr.length - 1; i > 0; i--) {
19
+ const j = Math.floor(rand() * (i + 1));
20
+ [arr[i], arr[j]] = [arr[j], arr[i]];
21
+ }
22
+ return arr;
23
+ }
24
+ exports.shuffle = shuffle;
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Propagation — domain pruning before search.
3
+ *
4
+ * Builds the eligibility matrix (employee × shift instance) and applies every
5
+ * constraint's `prune()` hook (time-off, impossible per-shift duration, …).
6
+ * A slot left with zero eligible employees is an early infeasibility signal
7
+ * and is reported as a violation before any search runs.
8
+ */
9
+ import type { ConstraintViolation, ModelContext } from '../types';
10
+ export interface PropagationResult {
11
+ /** employeeId -> set of shift-instance ids they may legally take. */
12
+ eligibility: Map<string, Set<string>>;
13
+ /** instanceId -> eligible employee ids (the transposed view). */
14
+ eligibleByInstance: Map<string, string[]>;
15
+ /** Slots with zero eligible employees, reported before search. */
16
+ violations: ConstraintViolation[];
17
+ }
18
+ export declare function propagate(ctx: ModelContext): PropagationResult;
19
+ //# sourceMappingURL=propagation.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"propagation.d.ts","sourceRoot":"","sources":["../../../src/scheduling/engine/propagation.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,OAAO,KAAK,EAAE,mBAAmB,EAAE,YAAY,EAAE,MAAM,UAAU,CAAC;AAElE,MAAM,WAAW,iBAAiB;IAC9B,qEAAqE;IACrE,WAAW,EAAE,GAAG,CAAC,MAAM,EAAE,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC;IACtC,iEAAiE;IACjE,kBAAkB,EAAE,GAAG,CAAC,MAAM,EAAE,MAAM,EAAE,CAAC,CAAC;IAC1C,kEAAkE;IAClE,UAAU,EAAE,mBAAmB,EAAE,CAAC;CACrC;AAED,wBAAgB,SAAS,CAAC,GAAG,EAAE,YAAY,GAAG,iBAAiB,CA6B9D"}
@@ -0,0 +1,40 @@
1
+ "use strict";
2
+ /**
3
+ * Propagation — domain pruning before search.
4
+ *
5
+ * Builds the eligibility matrix (employee × shift instance) and applies every
6
+ * constraint's `prune()` hook (time-off, impossible per-shift duration, …).
7
+ * A slot left with zero eligible employees is an early infeasibility signal
8
+ * and is reported as a violation before any search runs.
9
+ */
10
+ Object.defineProperty(exports, "__esModule", { value: true });
11
+ exports.propagate = void 0;
12
+ function propagate(ctx) {
13
+ const eligibility = new Map();
14
+ for (const emp of ctx.employees) {
15
+ eligibility.set(emp.id, new Set(ctx.instances.map((i) => i.id)));
16
+ }
17
+ for (const constraint of ctx.constraints) {
18
+ constraint.prune?.(ctx, eligibility);
19
+ }
20
+ const eligibleByInstance = new Map();
21
+ for (const inst of ctx.instances)
22
+ eligibleByInstance.set(inst.id, []);
23
+ for (const [employeeId, instances] of eligibility) {
24
+ for (const instanceId of instances)
25
+ eligibleByInstance.get(instanceId)?.push(employeeId);
26
+ }
27
+ const violations = [];
28
+ for (const inst of ctx.instances) {
29
+ if ((eligibleByInstance.get(inst.id) ?? []).length === 0 && inst.minEmployees > 0) {
30
+ violations.push({
31
+ constraintId: 'min-staffing',
32
+ severity: 'hard',
33
+ shiftInstanceId: inst.id,
34
+ message: `shift "${inst.id}" has zero eligible employees`,
35
+ });
36
+ }
37
+ }
38
+ return { eligibility, eligibleByInstance, violations };
39
+ }
40
+ exports.propagate = propagate;
@@ -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;