assignment-user-matcher 1.16.1 → 1.22.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 (153) hide show
  1. package/README.md +290 -8
  2. package/dist/escalation/policy.d.ts +11 -0
  3. package/dist/escalation/policy.d.ts.map +1 -1
  4. package/dist/escalation/policy.js +22 -1
  5. package/dist/forecasting/backtest.d.ts +52 -0
  6. package/dist/forecasting/backtest.d.ts.map +1 -0
  7. package/dist/forecasting/backtest.js +195 -0
  8. package/dist/forecasting/calendar.d.ts +44 -0
  9. package/dist/forecasting/calendar.d.ts.map +1 -0
  10. package/dist/forecasting/calendar.js +85 -0
  11. package/dist/forecasting/cover.d.ts +69 -0
  12. package/dist/forecasting/cover.d.ts.map +1 -0
  13. package/dist/forecasting/cover.js +103 -0
  14. package/dist/forecasting/days.d.ts +17 -0
  15. package/dist/forecasting/days.d.ts.map +1 -0
  16. package/dist/forecasting/days.js +35 -0
  17. package/dist/forecasting/distributions.d.ts +31 -0
  18. package/dist/forecasting/distributions.d.ts.map +1 -0
  19. package/dist/forecasting/distributions.js +154 -0
  20. package/dist/forecasting/effects.d.ts +88 -0
  21. package/dist/forecasting/effects.d.ts.map +1 -0
  22. package/dist/forecasting/effects.js +303 -0
  23. package/dist/forecasting/erlang.d.ts +31 -0
  24. package/dist/forecasting/erlang.d.ts.map +1 -0
  25. package/dist/forecasting/erlang.js +86 -0
  26. package/dist/forecasting/forecast.d.ts +7 -0
  27. package/dist/forecasting/forecast.d.ts.map +1 -0
  28. package/dist/forecasting/forecast.js +221 -0
  29. package/dist/forecasting/index.d.ts +18 -0
  30. package/dist/forecasting/index.d.ts.map +1 -0
  31. package/dist/forecasting/index.js +54 -0
  32. package/dist/forecasting/model.d.ts +145 -0
  33. package/dist/forecasting/model.d.ts.map +1 -0
  34. package/dist/forecasting/model.js +583 -0
  35. package/dist/forecasting/nowcast.d.ts +26 -0
  36. package/dist/forecasting/nowcast.d.ts.map +1 -0
  37. package/dist/forecasting/nowcast.js +92 -0
  38. package/dist/forecasting/simulation.d.ts +91 -0
  39. package/dist/forecasting/simulation.d.ts.map +1 -0
  40. package/dist/forecasting/simulation.js +478 -0
  41. package/dist/forecasting/spikes.d.ts +6 -0
  42. package/dist/forecasting/spikes.d.ts.map +1 -0
  43. package/dist/forecasting/spikes.js +73 -0
  44. package/dist/forecasting/staffing.d.ts +64 -0
  45. package/dist/forecasting/staffing.d.ts.map +1 -0
  46. package/dist/forecasting/staffing.js +765 -0
  47. package/dist/forecasting/stats.d.ts +11 -0
  48. package/dist/forecasting/stats.d.ts.map +1 -0
  49. package/dist/forecasting/stats.js +45 -0
  50. package/dist/forecasting/types.d.ts +299 -0
  51. package/dist/forecasting/types.d.ts.map +1 -0
  52. package/dist/forecasting/types.js +8 -0
  53. package/dist/index.d.ts +3 -2
  54. package/dist/index.d.ts.map +1 -1
  55. package/dist/index.js +8 -1
  56. package/dist/learning/auto-weights.d.ts +1 -5
  57. package/dist/learning/auto-weights.d.ts.map +1 -1
  58. package/dist/learning/auto-weights.js +0 -3
  59. package/dist/lua/book-slot.lua +84 -0
  60. package/dist/lua/claim-queued.lua +47 -0
  61. package/dist/managers/DecisionTraceManager.d.ts +15 -0
  62. package/dist/managers/DecisionTraceManager.d.ts.map +1 -1
  63. package/dist/managers/DecisionTraceManager.js +117 -11
  64. package/dist/managers/LearningManager.d.ts +12 -0
  65. package/dist/managers/LearningManager.d.ts.map +1 -1
  66. package/dist/managers/LearningManager.js +21 -7
  67. package/dist/managers/ReliabilityManager.d.ts +1 -2
  68. package/dist/managers/ReliabilityManager.d.ts.map +1 -1
  69. package/dist/managers/ReliabilityManager.js +1 -1
  70. package/dist/managers/TelemetryManager.d.ts.map +1 -1
  71. package/dist/managers/TelemetryManager.js +9 -3
  72. package/dist/managers/WorkflowManager.d.ts.map +1 -1
  73. package/dist/managers/WorkflowManager.js +3 -4
  74. package/dist/matcher.class.d.ts +319 -4
  75. package/dist/matcher.class.d.ts.map +1 -1
  76. package/dist/matcher.class.js +1428 -102
  77. package/dist/queries/lane-stats.d.ts +51 -0
  78. package/dist/queries/lane-stats.d.ts.map +1 -0
  79. package/dist/queries/lane-stats.js +78 -0
  80. package/dist/schedule/recurrence.d.ts +11 -0
  81. package/dist/schedule/recurrence.d.ts.map +1 -1
  82. package/dist/schedule/recurrence.js +19 -2
  83. package/dist/schedule/slot.d.ts +60 -0
  84. package/dist/schedule/slot.d.ts.map +1 -0
  85. package/dist/schedule/slot.js +86 -0
  86. package/dist/scheduling/constraints/availability.d.ts +2 -14
  87. package/dist/scheduling/constraints/availability.d.ts.map +1 -1
  88. package/dist/scheduling/constraints/availability.js +14 -15
  89. package/dist/scheduling/constraints/employee-scope.d.ts.map +1 -1
  90. package/dist/scheduling/constraints/employee-scope.js +10 -2
  91. package/dist/scheduling/constraints/support.d.ts +4 -8
  92. package/dist/scheduling/constraints/support.d.ts.map +1 -1
  93. package/dist/scheduling/constraints/support.js +23 -2
  94. package/dist/scheduling/constraints/weekly-rest.d.ts +28 -0
  95. package/dist/scheduling/constraints/weekly-rest.d.ts.map +1 -1
  96. package/dist/scheduling/constraints/weekly-rest.js +108 -21
  97. package/dist/scheduling/engine/construction.d.ts.map +1 -1
  98. package/dist/scheduling/engine/construction.js +33 -4
  99. package/dist/scheduling/engine/objective.d.ts +0 -1
  100. package/dist/scheduling/engine/objective.d.ts.map +1 -1
  101. package/dist/scheduling/engine/objective.js +45 -3
  102. package/dist/scheduling/engine/search.d.ts +4 -0
  103. package/dist/scheduling/engine/search.d.ts.map +1 -1
  104. package/dist/scheduling/engine/search.js +2 -1
  105. package/dist/scheduling/engine/state.d.ts +14 -0
  106. package/dist/scheduling/engine/state.d.ts.map +1 -1
  107. package/dist/scheduling/engine/state.js +7 -0
  108. package/dist/scheduling/engine/timeline.d.ts +9 -1
  109. package/dist/scheduling/engine/timeline.d.ts.map +1 -1
  110. package/dist/scheduling/engine/timeline.js +52 -27
  111. package/dist/scheduling/engine/verdicts.d.ts +40 -1
  112. package/dist/scheduling/engine/verdicts.d.ts.map +1 -1
  113. package/dist/scheduling/engine/verdicts.js +177 -17
  114. package/dist/scheduling/index.d.ts +3 -2
  115. package/dist/scheduling/index.d.ts.map +1 -1
  116. package/dist/scheduling/index.js +7 -1
  117. package/dist/scheduling/model.d.ts +2 -3
  118. package/dist/scheduling/model.d.ts.map +1 -1
  119. package/dist/scheduling/model.js +30 -12
  120. package/dist/scheduling/operations.d.ts +174 -2
  121. package/dist/scheduling/operations.d.ts.map +1 -1
  122. package/dist/scheduling/operations.js +513 -15
  123. package/dist/scheduling/preference-report.d.ts +15 -0
  124. package/dist/scheduling/preference-report.d.ts.map +1 -0
  125. package/dist/scheduling/preference-report.js +111 -0
  126. package/dist/scheduling/preferences.d.ts +30 -0
  127. package/dist/scheduling/preferences.d.ts.map +1 -0
  128. package/dist/scheduling/preferences.js +85 -0
  129. package/dist/scheduling/resilience.d.ts +46 -0
  130. package/dist/scheduling/resilience.d.ts.map +1 -0
  131. package/dist/scheduling/resilience.js +45 -0
  132. package/dist/scheduling/scheduler.class.d.ts +12 -1
  133. package/dist/scheduling/scheduler.class.d.ts.map +1 -1
  134. package/dist/scheduling/scheduler.class.js +28 -4
  135. package/dist/scheduling/time.d.ts +28 -6
  136. package/dist/scheduling/time.d.ts.map +1 -1
  137. package/dist/scheduling/time.js +59 -17
  138. package/dist/scheduling/types.d.ts +107 -1
  139. package/dist/scheduling/types.d.ts.map +1 -1
  140. package/dist/scoring/fair-arbitration.d.ts.map +1 -1
  141. package/dist/scoring/fair-arbitration.js +2 -1
  142. package/dist/tracing/decision-trace.d.ts +5 -0
  143. package/dist/tracing/decision-trace.d.ts.map +1 -1
  144. package/dist/tracing/decision-trace.js +3 -0
  145. package/dist/types/matcher.d.ts +369 -2
  146. package/dist/types/matcher.d.ts.map +1 -1
  147. package/dist/updates/assignment-update.d.ts +93 -0
  148. package/dist/updates/assignment-update.d.ts.map +1 -0
  149. package/dist/updates/assignment-update.js +91 -0
  150. package/dist/utils/keys.d.ts +10 -0
  151. package/dist/utils/keys.d.ts.map +1 -1
  152. package/dist/utils/keys.js +43 -0
  153. package/package.json +15 -2
@@ -0,0 +1,111 @@
1
+ "use strict";
2
+ /**
3
+ * Which stated preferences a finished roster honoured, and why the others
4
+ * were not.
5
+ *
6
+ * Assembled once per result, never in the search loop. Eligibility is the
7
+ * same judgement `rankCandidates` makes: no hard verdict against the pair,
8
+ * and `hardCompliant`. So "nobody else could work it" here and an empty
9
+ * candidate list there are one answer. The one difference is the question
10
+ * asked: here it is whether a person could have taken a place somebody
11
+ * holds, so the holder is taken off the shift for the check and put back.
12
+ */
13
+ Object.defineProperty(exports, "__esModule", { value: true });
14
+ exports.preferenceReport = void 0;
15
+ const state_1 = require("./engine/state");
16
+ const verdicts_1 = require("./engine/verdicts");
17
+ const preferences_1 = require("./preferences");
18
+ function eligible(state, employeeId, instanceId) {
19
+ return !(0, verdicts_1.hardBlocked)(state, { employeeId, shiftInstanceId: instanceId });
20
+ }
21
+ /**
22
+ * Runs `check` with `holderId` taken off the instance, then puts them back
23
+ * exactly as they were (reasons included).
24
+ *
25
+ * The question a missed wish raises is "could somebody have *taken this
26
+ * place*?", not "could somebody have been added beside it?". On a shift
27
+ * already at `maxEmployees` the second question is always no — the
28
+ * headcount cap is a hard rule — so asking it would call every trade-off
29
+ * on a full shift a matter of cover.
30
+ */
31
+ function withVacated(state, holderId, instanceId, check) {
32
+ const reasons = state.reasons.get((0, state_1.pairKey)(holderId, instanceId)) ?? [];
33
+ (0, state_1.unassign)(state, holderId, instanceId);
34
+ try {
35
+ return check();
36
+ }
37
+ finally {
38
+ (0, state_1.assign)(state, holderId, instanceId, reasons);
39
+ }
40
+ }
41
+ /** Whether two employee records belong to the same person (`ctx.personIdOf` falls back to the id itself). */
42
+ function samePerson(state, a, b) {
43
+ return state.ctx.personIdOf.get(a) === state.ctx.personIdOf.get(b);
44
+ }
45
+ /**
46
+ * Whether anyone else could have worked `inst` in `employeeId`'s place.
47
+ *
48
+ * "Someone else" means someone else's *person*, not just another employee
49
+ * record: two contracts for the same person are not mutual cover, or a
50
+ * person with two records would always read as available to relieve
51
+ * themselves.
52
+ */
53
+ function someoneElseEligible(state, employeeId, inst) {
54
+ return withVacated(state, employeeId, inst.id, () => state.ctx.employees.some((other) => !samePerson(state, other.id, employeeId) &&
55
+ !state.isAssigned(other.id, inst.id) &&
56
+ eligible(state, other.id, inst.id)));
57
+ }
58
+ /** Whether `employeeId` could have worked `inst` — beside its holders, or in place of one of them. */
59
+ function couldHaveWorked(state, employeeId, inst) {
60
+ if (eligible(state, employeeId, inst.id))
61
+ return true;
62
+ const holders = [...(state.assignments.get(inst.id) ?? [])].filter((holder) => !samePerson(state, holder, employeeId));
63
+ return holders.some((holder) => withVacated(state, holder, inst.id, () => eligible(state, employeeId, inst.id)));
64
+ }
65
+ function preferenceReport(state) {
66
+ const { ctx } = state;
67
+ const out = [];
68
+ for (const employee of ctx.employees) {
69
+ const rules = ctx.preferenceRules.get(employee.id);
70
+ if (!rules?.length)
71
+ continue;
72
+ const outcomes = rules.map((rule) => {
73
+ // Safe: ctx.preferenceRules is built by resolvePreferenceRules (preferences.ts),
74
+ // which only ever keeps 'preferred' / 'avoid' rules — hard 'unavailable' rules
75
+ // never reach this map.
76
+ const kind = rule.kind;
77
+ const matching = ctx.instances.filter((inst) => (0, preferences_1.ruleMatchesInstance)(ctx.clock, rule, inst));
78
+ const assigned = matching.filter((inst) => state.isAssigned(employee.id, inst.id));
79
+ const dated = rule.fromDate !== undefined && rule.toDate !== undefined;
80
+ const base = {
81
+ ...(rule.id !== undefined ? { ruleId: rule.id } : {}),
82
+ kind,
83
+ priority: rule.priority ?? 'normal',
84
+ matchedInstances: matching.length,
85
+ };
86
+ if (matching.length === 0) {
87
+ return { ...base, honoured: 0, outcome: 'not-applicable', missed: [] };
88
+ }
89
+ if (kind === 'avoid') {
90
+ const missed = assigned.map((inst) => ({
91
+ instanceId: inst.id,
92
+ reason: someoneElseEligible(state, employee.id, inst) ? 'tradeoff' : 'cover',
93
+ }));
94
+ const outcome = assigned.length === 0 ? 'met' : dated || assigned.length === matching.length ? 'missed' : 'partly';
95
+ return { ...base, honoured: matching.length - assigned.length, outcome, missed };
96
+ }
97
+ if (assigned.length > 0)
98
+ return { ...base, honoured: assigned.length, outcome: 'met', missed: [] };
99
+ const missed = dated
100
+ ? matching.map((inst) => ({
101
+ instanceId: inst.id,
102
+ reason: couldHaveWorked(state, employee.id, inst) ? 'tradeoff' : 'blocked',
103
+ }))
104
+ : [];
105
+ return { ...base, honoured: 0, outcome: 'missed', missed };
106
+ });
107
+ out.push({ employeeId: employee.id, rules: outcomes });
108
+ }
109
+ return out;
110
+ }
111
+ exports.preferenceReport = preferenceReport;
@@ -0,0 +1,30 @@
1
+ /**
2
+ * Availability-rule matching and preference weights.
3
+ *
4
+ * A leaf module: `model.ts` resolves effective weights through it at build
5
+ * time, and every scorer and the preference report match rules through it, so
6
+ * the question "does this rule touch this shift" has exactly one answer.
7
+ */
8
+ import type { AvailabilityRule, Employee, PreferenceObjective, ShiftInstance } from './types';
9
+ import type { PeriodClock } from './time';
10
+ export type ClockLike = Pick<PeriodClock, 'minutesInClockRange'>;
11
+ /** Whether an availability rule's day, date and shift-type conditions apply to an occurrence. */
12
+ export declare function availabilityApplies(rule: AvailabilityRule, inst: ShiftInstance): boolean;
13
+ /** Minutes of `range` inside the rule's clock window; the whole range when the rule has none. */
14
+ export declare function ruleOverlapMinutes(clock: ClockLike, range: {
15
+ start: number;
16
+ end: number;
17
+ }, rule: AvailabilityRule): number;
18
+ /** Whether the rule touches the occurrence at all. */
19
+ export declare function ruleMatchesInstance(clock: ClockLike, rule: AvailabilityRule, inst: ShiftInstance): boolean;
20
+ /** Throws on a malformed preference objective. */
21
+ export declare function validatePreferenceObjectives(objective: PreferenceObjective | undefined): void;
22
+ /**
23
+ * Resolve every employee's soft preference rules to their effective weights,
24
+ * once, at model build. Priority multiplies first. The budget then scales
25
+ * the in-budget rules that touch at least one occurrence, so a wish about a
26
+ * day nothing runs on neither costs budget nor dilutes the rest (such a rule
27
+ * resolves to 0).
28
+ */
29
+ export declare function resolvePreferenceRules(employees: Employee[], instances: ShiftInstance[], clock: ClockLike, objective: PreferenceObjective | undefined): Map<string, AvailabilityRule[]>;
30
+ //# sourceMappingURL=preferences.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"preferences.d.ts","sourceRoot":"","sources":["../../src/scheduling/preferences.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,KAAK,EAAE,gBAAgB,EAAE,QAAQ,EAAE,mBAAmB,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AAE9F,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,QAAQ,CAAC;AAE1C,MAAM,MAAM,SAAS,GAAG,IAAI,CAAC,WAAW,EAAE,qBAAqB,CAAC,CAAC;AAEjE,iGAAiG;AACjG,wBAAgB,mBAAmB,CAAC,IAAI,EAAE,gBAAgB,EAAE,IAAI,EAAE,aAAa,GAAG,OAAO,CAQxF;AAED,iGAAiG;AACjG,wBAAgB,kBAAkB,CAC9B,KAAK,EAAE,SAAS,EAChB,KAAK,EAAE;IAAE,KAAK,EAAE,MAAM,CAAC;IAAC,GAAG,EAAE,MAAM,CAAA;CAAE,EACrC,IAAI,EAAE,gBAAgB,GACvB,MAAM,CAGR;AAED,sDAAsD;AACtD,wBAAgB,mBAAmB,CAAC,KAAK,EAAE,SAAS,EAAE,IAAI,EAAE,gBAAgB,EAAE,IAAI,EAAE,aAAa,GAAG,OAAO,CAG1G;AAED,kDAAkD;AAClD,wBAAgB,4BAA4B,CAAC,SAAS,EAAE,mBAAmB,GAAG,SAAS,GAAG,IAAI,CAS7F;AAED;;;;;;GAMG;AACH,wBAAgB,sBAAsB,CAClC,SAAS,EAAE,QAAQ,EAAE,EACrB,SAAS,EAAE,aAAa,EAAE,EAC1B,KAAK,EAAE,SAAS,EAChB,SAAS,EAAE,mBAAmB,GAAG,SAAS,GAC3C,GAAG,CAAC,MAAM,EAAE,gBAAgB,EAAE,CAAC,CAwBjC"}
@@ -0,0 +1,85 @@
1
+ "use strict";
2
+ /**
3
+ * Availability-rule matching and preference weights.
4
+ *
5
+ * A leaf module: `model.ts` resolves effective weights through it at build
6
+ * time, and every scorer and the preference report match rules through it, so
7
+ * the question "does this rule touch this shift" has exactly one answer.
8
+ */
9
+ Object.defineProperty(exports, "__esModule", { value: true });
10
+ exports.resolvePreferenceRules = exports.validatePreferenceObjectives = exports.ruleMatchesInstance = exports.ruleOverlapMinutes = exports.availabilityApplies = void 0;
11
+ const types_1 = require("./types");
12
+ /** Whether an availability rule's day, date and shift-type conditions apply to an occurrence. */
13
+ function availabilityApplies(rule, inst) {
14
+ if (rule.daysOfWeek && !rule.daysOfWeek.includes(inst.weekday))
15
+ return false;
16
+ if (rule.fromDate && inst.date < rule.fromDate)
17
+ return false;
18
+ if (rule.toDate && inst.date > rule.toDate)
19
+ return false;
20
+ if (rule.shiftTypeTags && (inst.shiftTypeTag === undefined || !rule.shiftTypeTags.includes(inst.shiftTypeTag))) {
21
+ return false;
22
+ }
23
+ return true;
24
+ }
25
+ exports.availabilityApplies = availabilityApplies;
26
+ /** Minutes of `range` inside the rule's clock window; the whole range when the rule has none. */
27
+ function ruleOverlapMinutes(clock, range, rule) {
28
+ if (rule.from === undefined || rule.to === undefined)
29
+ return range.end - range.start;
30
+ return clock.minutesInClockRange(range, { from: rule.from, to: rule.to });
31
+ }
32
+ exports.ruleOverlapMinutes = ruleOverlapMinutes;
33
+ /** Whether the rule touches the occurrence at all. */
34
+ function ruleMatchesInstance(clock, rule, inst) {
35
+ if (!availabilityApplies(rule, inst))
36
+ return false;
37
+ return ruleOverlapMinutes(clock, { start: inst.startMinute, end: inst.endMinute }, rule) > 0;
38
+ }
39
+ exports.ruleMatchesInstance = ruleMatchesInstance;
40
+ /** Throws on a malformed preference objective. */
41
+ function validatePreferenceObjectives(objective) {
42
+ if (!objective)
43
+ return;
44
+ const { budget, importantWeight } = objective;
45
+ if (budget !== undefined && (!Number.isFinite(budget) || budget <= 0)) {
46
+ throw new types_1.ScheduleValidationError('objectives.preferences.budget must be a positive number');
47
+ }
48
+ if (importantWeight !== undefined && (!Number.isFinite(importantWeight) || importantWeight <= 0)) {
49
+ throw new types_1.ScheduleValidationError('objectives.preferences.importantWeight must be a positive number');
50
+ }
51
+ }
52
+ exports.validatePreferenceObjectives = validatePreferenceObjectives;
53
+ /**
54
+ * Resolve every employee's soft preference rules to their effective weights,
55
+ * once, at model build. Priority multiplies first. The budget then scales
56
+ * the in-budget rules that touch at least one occurrence, so a wish about a
57
+ * day nothing runs on neither costs budget nor dilutes the rest (such a rule
58
+ * resolves to 0).
59
+ */
60
+ function resolvePreferenceRules(employees, instances, clock, objective) {
61
+ const importantWeight = objective?.importantWeight ?? 1;
62
+ const out = new Map();
63
+ for (const employee of employees) {
64
+ const soft = (employee.availability ?? []).filter((r) => r.kind === 'preferred' || r.kind === 'avoid');
65
+ if (soft.length === 0)
66
+ continue;
67
+ const resolved = soft.map((rule) => ({
68
+ ...rule,
69
+ weight: (rule.weight ?? 1) * (rule.priority === 'important' ? importantWeight : 1),
70
+ }));
71
+ if (objective?.budget !== undefined) {
72
+ const live = resolved.map((rule) => !rule.outsideBudget && instances.some((inst) => ruleMatchesInstance(clock, rule, inst)));
73
+ const sum = resolved.reduce((acc, rule, i) => acc + (live[i] ? Math.abs(rule.weight) : 0), 0);
74
+ const scale = sum > 0 ? objective.budget / sum : 0;
75
+ resolved.forEach((rule, i) => {
76
+ if (rule.outsideBudget)
77
+ return;
78
+ rule.weight = live[i] ? rule.weight * scale : 0;
79
+ });
80
+ }
81
+ out.set(employee.id, resolved);
82
+ }
83
+ return out;
84
+ }
85
+ exports.resolvePreferenceRules = resolvePreferenceRules;
@@ -0,0 +1,46 @@
1
+ import type { RepairCandidate } from './operations';
2
+ /**
3
+ * Shift resilience for the capacity radar: is a published shift short, and if
4
+ * someone drops out, is there anybody who could legally step in? Backups are
5
+ * counted by the same eligibility path as `rankCandidates`, so the radar and a
6
+ * cover offer can never disagree about who could take a shift.
7
+ *
8
+ * Profiling-free: inputs are declared facts (roster, time off, qualifications,
9
+ * rules) and an aggregate expected-dropout number the caller supplies.
10
+ */
11
+ export type ResilienceTier = 'ok' | 'watch' | 'at-risk' | 'critical';
12
+ export interface SkillResilience {
13
+ tag: string;
14
+ required: number;
15
+ held: number;
16
+ shortBy: number;
17
+ backups: number;
18
+ }
19
+ export interface ShiftResilience {
20
+ shiftInstanceId: string;
21
+ date: string;
22
+ startMinute: number;
23
+ endMinute: number;
24
+ siteId?: string;
25
+ need: number;
26
+ assigned: number;
27
+ absent: string[];
28
+ shortBy: number;
29
+ expectedDropouts: number;
30
+ backups: number;
31
+ skills: SkillResilience[];
32
+ topBackups: RepairCandidate[];
33
+ tier: ResilienceTier;
34
+ reasons: string[];
35
+ }
36
+ export declare function resilienceTier(input: {
37
+ shortBy: number;
38
+ backups: number;
39
+ expectedDropouts: number;
40
+ skills: SkillResilience[];
41
+ assigned?: number;
42
+ }): {
43
+ tier: ResilienceTier;
44
+ reasons: string[];
45
+ };
46
+ //# sourceMappingURL=resilience.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"resilience.d.ts","sourceRoot":"","sources":["../../src/scheduling/resilience.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,cAAc,CAAC;AAEpD;;;;;;;;GAQG;AACH,MAAM,MAAM,cAAc,GAAG,IAAI,GAAG,OAAO,GAAG,SAAS,GAAG,UAAU,CAAC;AAErE,MAAM,WAAW,eAAe;IAC5B,GAAG,EAAE,MAAM,CAAC;IACZ,QAAQ,EAAE,MAAM,CAAC;IACjB,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,MAAM,CAAC;IAChB,OAAO,EAAE,MAAM,CAAC;CACnB;AAED,MAAM,WAAW,eAAe;IAC5B,eAAe,EAAE,MAAM,CAAC;IACxB,IAAI,EAAE,MAAM,CAAC;IACb,WAAW,EAAE,MAAM,CAAC;IACpB,SAAS,EAAE,MAAM,CAAC;IAClB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,IAAI,EAAE,MAAM,CAAC;IACb,QAAQ,EAAE,MAAM,CAAC;IACjB,MAAM,EAAE,MAAM,EAAE,CAAC;IACjB,OAAO,EAAE,MAAM,CAAC;IAChB,gBAAgB,EAAE,MAAM,CAAC;IACzB,OAAO,EAAE,MAAM,CAAC;IAChB,MAAM,EAAE,eAAe,EAAE,CAAC;IAC1B,UAAU,EAAE,eAAe,EAAE,CAAC;IAC9B,IAAI,EAAE,cAAc,CAAC;IACrB,OAAO,EAAE,MAAM,EAAE,CAAC;CACrB;AAID,wBAAgB,cAAc,CAAC,KAAK,EAAE;IAClC,OAAO,EAAE,MAAM,CAAC;IAChB,OAAO,EAAE,MAAM,CAAC;IAChB,gBAAgB,EAAE,MAAM,CAAC;IACzB,MAAM,EAAE,eAAe,EAAE,CAAC;IAC1B,QAAQ,CAAC,EAAE,MAAM,CAAC;CACrB,GAAG;IAAE,IAAI,EAAE,cAAc,CAAC;IAAC,OAAO,EAAE,MAAM,EAAE,CAAA;CAAE,CAkC9C"}
@@ -0,0 +1,45 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.resilienceTier = void 0;
4
+ const RANK = { ok: 0, watch: 1, 'at-risk': 2, critical: 3 };
5
+ function resilienceTier(input) {
6
+ let tier = 'ok';
7
+ const reasons = [];
8
+ const raise = (next, reason) => {
9
+ if (RANK[next] > RANK[tier])
10
+ tier = next;
11
+ if (!reasons.includes(reason))
12
+ reasons.push(reason);
13
+ };
14
+ // Shared judge: short (shortBy > 0) escalates to critical when there aren't
15
+ // even enough backups to cover the shortfall, else at-risk; not short, it
16
+ // escalates to at-risk when backups don't cover the expected dropouts, or
17
+ // watch when they cover today's expectation but not one more than that.
18
+ const judge = (shortBy, backups, dropouts, shortReason, thinReason) => {
19
+ if (shortBy > 0) {
20
+ if (backups < shortBy) {
21
+ raise('critical', shortReason);
22
+ raise('critical', 'no-backups');
23
+ }
24
+ else
25
+ raise('at-risk', shortReason);
26
+ }
27
+ else if (backups < dropouts)
28
+ raise('at-risk', thinReason);
29
+ else if (backups < dropouts + 1)
30
+ raise('watch', thinReason);
31
+ };
32
+ judge(input.shortBy, input.backups, input.expectedDropouts, 'short', 'thin-backups');
33
+ // Per-skill: judged exactly like the shift, against that skill's own share
34
+ // of the expected dropouts — the fraction of assigned holders this skill
35
+ // accounts for. Without `assigned` (or an empty shift), fall back to the
36
+ // shift-wide rate unscaled.
37
+ for (const s of input.skills) {
38
+ const skillDropouts = input.assigned && input.assigned > 0
39
+ ? (input.expectedDropouts * s.held) / input.assigned
40
+ : input.expectedDropouts;
41
+ judge(s.shortBy, s.backups, skillDropouts, `short-skill:${s.tag}`, `thin-skill:${s.tag}`);
42
+ }
43
+ return { tier, reasons };
44
+ }
45
+ exports.resilienceTier = resilienceTier;
@@ -16,7 +16,18 @@ export declare const ENGINE_VERSION = "3";
16
16
  export declare class ShiftScheduler {
17
17
  /** Solve a scheduling problem synchronously. Throws `ScheduleValidationError` on malformed input. */
18
18
  solve(input: ScheduleInput): ScheduleResult;
19
- /** Shape a search state into the public result, running the aggregate rules once. */
19
+ /**
20
+ * Shape a search state into the public result, running the aggregate rules once.
21
+ *
22
+ * `final` defaults to `false` — the cheap path, skipping the preference
23
+ * report — so a new call site must opt in explicitly. The `onProgress`
24
+ * callbacks the LNS loop fires on every new best rely on that default: the
25
+ * preference report must never run in the search loop (it costs solve
26
+ * time on every improvement, and it vacates and restores the shared
27
+ * `best` state that the eventual final assembly reads), so progress
28
+ * payloads never get a `preferences` field.
29
+ * The final result after `solve()` finishes passes `true` explicitly.
30
+ */
20
31
  private assemble;
21
32
  }
22
33
  /** One-shot convenience wrapper around `new ShiftScheduler().solve(input)`. */
@@ -1 +1 @@
1
- {"version":3,"file":"scheduler.class.d.ts","sourceRoot":"","sources":["../../src/scheduling/scheduler.class.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAEH,OAAO,KAAK,EAAoC,aAAa,EAAE,cAAc,EAAuB,MAAM,SAAS,CAAC;AAsBpH,eAAO,MAAM,cAAc,MAAM,CAAC;AAElC,qBAAa,cAAc;IACvB,qGAAqG;IACrG,KAAK,CAAC,KAAK,EAAE,aAAa,GAAG,cAAc;IAgD3C,qFAAqF;IACrF,OAAO,CAAC,QAAQ;CAsFnB;AAUD,+EAA+E;AAC/E,wBAAgB,aAAa,CAAC,KAAK,EAAE,aAAa,GAAG,cAAc,CAElE"}
1
+ {"version":3,"file":"scheduler.class.d.ts","sourceRoot":"","sources":["../../src/scheduling/scheduler.class.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAEH,OAAO,KAAK,EAGR,aAAa,EACb,cAAc,EAGjB,MAAM,SAAS,CAAC;AAuBjB,eAAO,MAAM,cAAc,MAAM,CAAC;AAElC,qBAAa,cAAc;IACvB,qGAAqG;IACrG,KAAK,CAAC,KAAK,EAAE,aAAa,GAAG,cAAc;IA2D3C;;;;;;;;;;;OAWG;IACH,OAAO,CAAC,QAAQ;CAyFnB;AAUD,+EAA+E;AAC/E,wBAAgB,aAAa,CAAC,KAAK,EAAE,aAAa,GAAG,cAAc,CAElE"}
@@ -29,6 +29,7 @@ const protections_1 = require("./constraints/protections");
29
29
  const overtime_1 = require("./constraints/overtime");
30
30
  const cost_1 = require("./cost");
31
31
  const contract_hours_1 = require("./contract-hours");
32
+ const preference_report_1 = require("./preference-report");
32
33
  const prng_1 = require("./engine/prng");
33
34
  const verdicts_1 = require("./engine/verdicts");
34
35
  const provenance_1 = require("./provenance");
@@ -55,6 +56,14 @@ class ShiftScheduler {
55
56
  (0, state_1.assign)(state, employeeId, instanceId, ['pinned by the caller']);
56
57
  }
57
58
  (0, construction_1.greedyFill)(ctx, state, propagation, objective, rand);
59
+ const report = (phase, from, evaluatedVariants) => input.onSearch?.({
60
+ phase,
61
+ assigned: [...from.assignments.values()].reduce((sum, set) => sum + set.size, 0),
62
+ unfilledSlots: (0, objective_1.unfilledSlots)(ctx, from),
63
+ evaluatedVariants,
64
+ elapsedMs: Date.now() - startedAt,
65
+ });
66
+ report('draft', state, 1);
58
67
  const minHoursWeight = ctx.constraints.find((c) => c.id === 'hour-budget')?.weight ?? objective_1.MIN_HOURS_WEIGHT;
59
68
  let finalState = state;
60
69
  let evaluatedVariants = 1;
@@ -66,16 +75,29 @@ class ShiftScheduler {
66
75
  maxIterations: input.maxIterations,
67
76
  rand,
68
77
  onImprovement: input.onProgress
69
- ? (best) => input.onProgress(this.assemble(best, propagation, startedAt, seed, input, 0))
78
+ ? (best) => input.onProgress(this.assemble(best, propagation, startedAt, seed, input, 0, false))
70
79
  : undefined,
80
+ onRound: input.onSearch ? (best, variants) => report('improving', best, 1 + variants) : undefined,
81
+ shouldStop: input.shouldStop,
71
82
  }, () => (0, state_1.createState)(ctx));
72
83
  finalState = outcome.best;
73
84
  evaluatedVariants += outcome.evaluatedVariants;
74
85
  }
75
- return this.assemble(finalState, propagation, startedAt, seed, input, evaluatedVariants);
86
+ return this.assemble(finalState, propagation, startedAt, seed, input, evaluatedVariants, true);
76
87
  }
77
- /** Shape a search state into the public result, running the aggregate rules once. */
78
- assemble(state, propagation, startedAt, seed, input, evaluatedVariants) {
88
+ /**
89
+ * Shape a search state into the public result, running the aggregate rules once.
90
+ *
91
+ * `final` defaults to `false` — the cheap path, skipping the preference
92
+ * report — so a new call site must opt in explicitly. The `onProgress`
93
+ * callbacks the LNS loop fires on every new best rely on that default: the
94
+ * preference report must never run in the search loop (it costs solve
95
+ * time on every improvement, and it vacates and restores the shared
96
+ * `best` state that the eventual final assembly reads), so progress
97
+ * payloads never get a `preferences` field.
98
+ * The final result after `solve()` finishes passes `true` explicitly.
99
+ */
100
+ assemble(state, propagation, startedAt, seed, input, evaluatedVariants, final = false) {
79
101
  const ctx = state.ctx;
80
102
  const minHoursWeight = ctx.constraints.find((c) => c.id === 'hour-budget')?.weight ?? objective_1.MIN_HOURS_WEIGHT;
81
103
  const assignments = (0, state_1.assignedPairs)(state).map(({ employeeId, instanceId }) => {
@@ -113,6 +135,7 @@ class ShiftScheduler {
113
135
  ];
114
136
  const cost = (0, cost_1.rosterCost)(state);
115
137
  const contractHours = (0, contract_hours_1.contractHoursSummary)(state);
138
+ const preferences = final ? (0, preference_report_1.preferenceReport)(state) : [];
116
139
  return {
117
140
  status,
118
141
  assignments,
@@ -136,6 +159,7 @@ class ShiftScheduler {
136
159
  ...(ledger.length ? { ledger } : {}),
137
160
  ...(cost ? { cost } : {}),
138
161
  ...(contractHours.length ? { contractHours } : {}),
162
+ ...(preferences.length ? { preferences } : {}),
139
163
  };
140
164
  }
141
165
  }
@@ -28,16 +28,24 @@ export interface ClockRange {
28
28
  /**
29
29
  * Resolves wall-clock times in one IANA zone to period minutes and back.
30
30
  *
31
- * Construct once per solve and share it: each instance memoizes the per-day UTC
32
- * offset, so repeated conversions cost a map lookup rather than an `Intl` call.
31
+ * Construct once per solve and share it: each instance memoizes every wall-clock
32
+ * instant it resolves, so repeated conversions cost a map lookup rather than an `Intl` call.
33
33
  */
34
34
  export declare class PeriodClock {
35
35
  readonly startDate: string;
36
36
  readonly timeZone: string;
37
37
  readonly days: number;
38
38
  private readonly formatter;
39
- /** UTC epoch ms of local midnight, keyed by day index from the period start. */
40
- private readonly midnightByDay;
39
+ /** UTC epoch ms of a wall-clock minute, keyed by `dayIndex * 1441 + minutesIntoDay`. */
40
+ private readonly instantByDayMinute;
41
+ /**
42
+ * ISO date and weekday per day index. Sequence rules ask "which day, which
43
+ * weekday" of every entry on a timeline for every candidate they judge, and
44
+ * each uncached answer is a `Date` parse and format.
45
+ */
46
+ private readonly dateByDayIndex;
47
+ private readonly weekdayByDayIndex;
48
+ private readonly dayIndexByDate;
41
49
  /** UTC epoch ms of local midnight on the period start — the origin of period minutes. */
42
50
  private originMs;
43
51
  constructor(startDate: string, days: number, timeZone?: string);
@@ -76,6 +84,16 @@ export declare class PeriodClock {
76
84
  * start would reintroduce exactly the DST error the clock exists to avoid.
77
85
  */
78
86
  toEpochMs(periodMinute: number): number;
87
+ /**
88
+ * What a clock on the wall shows at an absolute instant: the local date and
89
+ * the minute of that day. On a fall-back night two instants an hour apart
90
+ * both read 03:00; on a spring-forward night 03:00 never shows. Costs one
91
+ * `Intl` call — callers on a hot path use it only on transition days.
92
+ */
93
+ localTimeOf(epochMs: number): {
94
+ date: string;
95
+ minuteOfDay: number;
96
+ };
79
97
  /** Period minutes for an absolute UTC epoch instant. */
80
98
  fromEpochMs(epochMs: number): number;
81
99
  /** ISO 8601 instant for a period minute, in UTC. */
@@ -105,8 +123,12 @@ export declare class PeriodClock {
105
123
  * correct or off by one; the two guards settle it.
106
124
  */
107
125
  dayIndexOfMinute(minute: number): number;
108
- /** UTC epoch ms of local midnight on the given day index, memoized. */
109
- private utcMidnightMs;
126
+ /**
127
+ * UTC epoch ms of `minutesIntoDay` (0..1440) past local midnight on the
128
+ * given day index, memoized: clock-band arithmetic asks for the same few
129
+ * wall-clock minutes on every day, and each miss costs two `Intl` calls.
130
+ */
131
+ private localInstantMs;
110
132
  /**
111
133
  * UTC epoch ms for a local wall-clock time in this zone.
112
134
  *
@@ -1 +1 @@
1
- {"version":3,"file":"time.d.ts","sourceRoot":"","sources":["../../src/scheduling/time.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AAIH,eAAO,MAAM,eAAe,OAAO,CAAC;AAIpC,2DAA2D;AAC3D,MAAM,WAAW,WAAW;IACxB,KAAK,EAAE,MAAM,CAAC;IACd,GAAG,EAAE,MAAM,CAAC;CACf;AAED,oGAAoG;AACpG,MAAM,WAAW,UAAU;IACvB,IAAI,EAAE,MAAM,CAAC;IACb,EAAE,EAAE,MAAM,CAAC;CACd;AAED;;;;;GAKG;AACH,qBAAa,WAAW;IACpB,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,QAAQ,CAAC,QAAQ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C;AACtC,wBAAgB,UAAU,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAG/C;AAED,uEAAuE;AACvE,wBAAgB,cAAc,CAAC,KAAK,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,MAAM,CAUnE;AAED,mFAAmF;AACnF,wBAAgB,aAAa,CAAC,KAAK,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,IAAI,CAQhE"}
@@ -24,13 +24,21 @@ const TIME_OF_DAY = /^(\d{1,2}):(\d{2})(?::(\d{2}))?$/;
24
24
  /**
25
25
  * Resolves wall-clock times in one IANA zone to period minutes and back.
26
26
  *
27
- * Construct once per solve and share it: each instance memoizes the per-day UTC
28
- * offset, so repeated conversions cost a map lookup rather than an `Intl` call.
27
+ * Construct once per solve and share it: each instance memoizes every wall-clock
28
+ * instant it resolves, so repeated conversions cost a map lookup rather than an `Intl` call.
29
29
  */
30
30
  class PeriodClock {
31
31
  constructor(startDate, days, timeZone = 'UTC') {
32
- /** UTC epoch ms of local midnight, keyed by day index from the period start. */
33
- this.midnightByDay = new Map();
32
+ /** UTC epoch ms of a wall-clock minute, keyed by `dayIndex * 1441 + minutesIntoDay`. */
33
+ this.instantByDayMinute = new Map();
34
+ /**
35
+ * ISO date and weekday per day index. Sequence rules ask "which day, which
36
+ * weekday" of every entry on a timeline for every candidate they judge, and
37
+ * each uncached answer is a `Date` parse and format.
38
+ */
39
+ this.dateByDayIndex = new Map();
40
+ this.weekdayByDayIndex = new Map();
41
+ this.dayIndexByDate = new Map();
34
42
  assertIsoDate(startDate, 'period.startDate');
35
43
  if (!Number.isInteger(days) || days <= 0) {
36
44
  throw new types_1.ScheduleValidationError(`period must span at least one day, got ${days}`);
@@ -56,12 +64,24 @@ class PeriodClock {
56
64
  }
57
65
  /** Day index of an ISO date relative to the period start; negative before it. */
58
66
  dayIndexOf(date) {
59
- assertIsoDate(date, 'date');
60
- return daysBetween(this.startDate, date);
67
+ let index = this.dayIndexByDate.get(date);
68
+ if (index === undefined) {
69
+ // Only a date that passed validation is remembered, so a bad one
70
+ // throws on every call rather than once.
71
+ assertIsoDate(date, 'date');
72
+ index = daysBetween(this.startDate, date);
73
+ this.dayIndexByDate.set(date, index);
74
+ }
75
+ return index;
61
76
  }
62
77
  /** ISO date `offset` days after the period start. */
63
78
  dateAt(offset) {
64
- return addDays(this.startDate, offset);
79
+ let date = this.dateByDayIndex.get(offset);
80
+ if (date === undefined) {
81
+ date = addDays(this.startDate, offset);
82
+ this.dateByDayIndex.set(offset, date);
83
+ }
84
+ return date;
65
85
  }
66
86
  /**
67
87
  * Period minutes for a wall-clock `(date, HH:MM)` in this zone.
@@ -106,10 +126,7 @@ class PeriodClock {
106
126
  }
107
127
  /** Period minutes for `minutesIntoDay` wall-clock minutes past local midnight on `dayIndex`. */
108
128
  periodMinuteAt(dayIndex, minutesIntoDay) {
109
- if (minutesIntoDay === 0) {
110
- return Math.round((this.utcMidnightMs(dayIndex) - this.originMs) / 60000);
111
- }
112
- return Math.round((this.utcInstantMs(this.dateAt(dayIndex), minutesIntoDay) - this.originMs) / 60000);
129
+ return Math.round((this.localInstantMs(dayIndex, minutesIntoDay) - this.originMs) / 60000);
113
130
  }
114
131
  /** The ISO date a period minute falls on. */
115
132
  dateOfMinute(minute) {
@@ -117,7 +134,13 @@ class PeriodClock {
117
134
  }
118
135
  /** ISO weekday of a period minute: 1 (Mon) .. 7 (Sun). */
119
136
  weekdayOfMinute(minute) {
120
- return isoWeekday(this.dateOfMinute(minute));
137
+ const dayIndex = this.dayIndexOfMinute(minute);
138
+ let weekday = this.weekdayByDayIndex.get(dayIndex);
139
+ if (weekday === undefined) {
140
+ weekday = isoWeekday(this.dateAt(dayIndex));
141
+ this.weekdayByDayIndex.set(dayIndex, weekday);
142
+ }
143
+ return weekday;
121
144
  }
122
145
  /**
123
146
  * Absolute UTC epoch milliseconds for a period minute.
@@ -130,6 +153,20 @@ class PeriodClock {
130
153
  toEpochMs(periodMinute) {
131
154
  return this.originMs + periodMinute * 60000;
132
155
  }
156
+ /**
157
+ * What a clock on the wall shows at an absolute instant: the local date and
158
+ * the minute of that day. On a fall-back night two instants an hour apart
159
+ * both read 03:00; on a spring-forward night 03:00 never shows. Costs one
160
+ * `Intl` call — callers on a hot path use it only on transition days.
161
+ */
162
+ localTimeOf(epochMs) {
163
+ const local = epochMs + this.offsetAtMs(epochMs) * 60000;
164
+ const day = Math.floor(local / 86400000);
165
+ return {
166
+ date: new Date(day * 86400000).toISOString().slice(0, 10),
167
+ minuteOfDay: Math.floor((local - day * 86400000) / 60000),
168
+ };
169
+ }
133
170
  /** Period minutes for an absolute UTC epoch instant. */
134
171
  fromEpochMs(epochMs) {
135
172
  return Math.round((epochMs - this.originMs) / 60000);
@@ -199,13 +236,18 @@ class PeriodClock {
199
236
  day++;
200
237
  return day;
201
238
  }
202
- /** UTC epoch ms of local midnight on the given day index, memoized. */
203
- utcMidnightMs(dayIndex) {
204
- const cached = this.midnightByDay.get(dayIndex);
239
+ /**
240
+ * UTC epoch ms of `minutesIntoDay` (0..1440) past local midnight on the
241
+ * given day index, memoized: clock-band arithmetic asks for the same few
242
+ * wall-clock minutes on every day, and each miss costs two `Intl` calls.
243
+ */
244
+ localInstantMs(dayIndex, minutesIntoDay) {
245
+ const key = dayIndex * 1441 + minutesIntoDay;
246
+ const cached = this.instantByDayMinute.get(key);
205
247
  if (cached !== undefined)
206
248
  return cached;
207
- const ms = this.utcInstantMs(this.dateAt(dayIndex), 0);
208
- this.midnightByDay.set(dayIndex, ms);
249
+ const ms = this.utcInstantMs(this.dateAt(dayIndex), minutesIntoDay);
250
+ this.instantByDayMinute.set(key, ms);
209
251
  return ms;
210
252
  }
211
253
  /**