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,134 @@
1
+ /**
2
+ * Operational APIs — the things a roster needs *after* it is built.
3
+ *
4
+ * Rosters are re-solved far more often than they are built, and the questions
5
+ * that arrive at 06:00 are not "give me a month" but "who can cover this, and
6
+ * why not her?". These four entry points answer them against the same
7
+ * constraint set the solver uses, so an answer here can never disagree with the
8
+ * roster the solver would produce.
9
+ *
10
+ * - `checkCompliance` — validate a roster the engine did not build. Human
11
+ * overrides are a legal requirement (GDPR Art 22 gives a right to human
12
+ * intervention), so a hand-edited roster must be re-checkable rather than
13
+ * trusted.
14
+ * - `explainCandidate` — every rule's verdict on one candidate, with numbers.
15
+ * - `repairSchedule` — minimal-perturbation re-plan around a disruption, with
16
+ * a ranked list of who can lawfully be called.
17
+ * - `diagnoseInfeasibility` — why the problem cannot be solved, before it is
18
+ * attempted.
19
+ */
20
+ import type { AssignmentPair, ConstraintViolation, LedgerEntry, RuleVerdict, ScheduleInput, ScheduledAssignment } from './types';
21
+ export interface ComplianceReport {
22
+ compliant: boolean;
23
+ violations: ConstraintViolation[];
24
+ /** Per-assignment verdicts for every rule that had something to say. */
25
+ verdicts: Array<{
26
+ pair: AssignmentPair;
27
+ verdicts: RuleVerdict[];
28
+ }>;
29
+ ledger: LedgerEntry[];
30
+ }
31
+ /**
32
+ * Validate an externally-produced or hand-edited roster.
33
+ *
34
+ * Runs the same constraints as the solver — there is deliberately no second
35
+ * validation path, because two paths drift and the one that drifts is always
36
+ * the one nobody reads.
37
+ */
38
+ export declare function checkCompliance(input: ScheduleInput, roster: ScheduledAssignment[]): ComplianceReport;
39
+ /**
40
+ * Why can — or can't — this person work this shift?
41
+ *
42
+ * A rule-by-rule scan against live state, not a solve. This is the question
43
+ * managers actually ask, and answering it with concrete numbers ("clock-out
44
+ * 22:00, shift starts 06:00, that is 8h against an 11h minimum") is what makes
45
+ * the roster arguable rather than oracular.
46
+ */
47
+ export declare function explainCandidate(input: ScheduleInput, employeeId: string, shiftInstanceId: string, roster?: ScheduledAssignment[]): RuleVerdict[];
48
+ export type Disruption = {
49
+ kind: 'absence';
50
+ employeeId: string;
51
+ from: string;
52
+ to?: string;
53
+ } | {
54
+ kind: 'noShow';
55
+ employeeId: string;
56
+ shiftInstanceId: string;
57
+ } | {
58
+ kind: 'cancelShift';
59
+ shiftInstanceId: string;
60
+ };
61
+ export interface RepairCandidate {
62
+ employeeId: string;
63
+ shiftInstanceId: string;
64
+ eligible: boolean;
65
+ verdicts: RuleVerdict[];
66
+ /** Failing rules only, for a compact "why not" list. */
67
+ blockers: RuleVerdict[];
68
+ marginalCostCents: number;
69
+ /** How far below their fair share of extra work this person is. Higher means more owed. */
70
+ fairnessDebt: number;
71
+ /** Lower is a better call. */
72
+ rank: number;
73
+ rationale: string;
74
+ }
75
+ export interface RepairResult {
76
+ diff: {
77
+ added: AssignmentPair[];
78
+ removed: AssignmentPair[];
79
+ };
80
+ candidates: RepairCandidate[];
81
+ violationsIntroduced: ConstraintViolation[];
82
+ perturbation: {
83
+ changedAssignments: number;
84
+ affectedEmployees: number;
85
+ };
86
+ }
87
+ /**
88
+ * Re-plan around a disruption, changing as little as possible.
89
+ *
90
+ * Everything not touched by the disruption is pinned, so the answer is a *diff*
91
+ * a manager can act on rather than a fresh roster nobody recognises. A full
92
+ * re-solve at 06:00 returns a different schedule for the whole team, which is
93
+ * not an answer anyone will accept.
94
+ *
95
+ * The candidate list is a ranked scan, not a solve — that is what keeps it
96
+ * interactive, and it is also the more useful output: the gap is filled by
97
+ * phoning someone, so the operator needs an ordered list with reasons, not a
98
+ * single name.
99
+ */
100
+ export declare function repairSchedule(input: ScheduleInput, disruption: Disruption, published: ScheduledAssignment[]): RepairResult;
101
+ /**
102
+ * Rank everyone who could take an open shift.
103
+ *
104
+ * The hard gate and the soft ordering are kept separate on purpose: an
105
+ * ineligible person is *never* promoted by being cheap, and the reason they are
106
+ * ineligible is still reported, because "Anna would be ideal but is 2h short on
107
+ * rest" is more useful than Anna's silent absence from the list.
108
+ *
109
+ * Ordering uses cost, fairness debt and stated preference — all facts about
110
+ * declared data and realised assignments. No reliability score, no acceptance
111
+ * history, no no-show prediction: those would make this profiling under AI Act
112
+ * Annex III point 4(b), which is high-risk with no narrow-task exemption.
113
+ */
114
+ export declare function rankCandidates(input: ScheduleInput, shiftInstanceId: string, roster: ScheduledAssignment[], disruption?: Disruption): RepairCandidate[];
115
+ export interface InfeasibilityReport {
116
+ feasible: boolean;
117
+ findings: Array<{
118
+ kind: 'noEligibleEmployee' | 'insufficientCapacity' | 'tagCapacity';
119
+ message: string;
120
+ shiftInstanceId?: string;
121
+ tag?: string;
122
+ shortfall?: number;
123
+ }>;
124
+ }
125
+ /**
126
+ * Why the problem cannot be solved, before spending a search budget on it.
127
+ *
128
+ * Cheap arithmetic catches most real infeasibility: total demand against total
129
+ * available capacity, per tag. "You are 24 registered-nurse-hours short on
130
+ * Tuesday to Thursday nights" starts a conversation; "no solution found" ends
131
+ * one.
132
+ */
133
+ export declare function diagnoseInfeasibility(input: ScheduleInput): InfeasibilityReport;
134
+ //# sourceMappingURL=operations.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"operations.d.ts","sourceRoot":"","sources":["../../src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mB,CAmD/E"}
@@ -0,0 +1,376 @@
1
+ "use strict";
2
+ /**
3
+ * Operational APIs — the things a roster needs *after* it is built.
4
+ *
5
+ * Rosters are re-solved far more often than they are built, and the questions
6
+ * that arrive at 06:00 are not "give me a month" but "who can cover this, and
7
+ * why not her?". These four entry points answer them against the same
8
+ * constraint set the solver uses, so an answer here can never disagree with the
9
+ * roster the solver would produce.
10
+ *
11
+ * - `checkCompliance` — validate a roster the engine did not build. Human
12
+ * overrides are a legal requirement (GDPR Art 22 gives a right to human
13
+ * intervention), so a hand-edited roster must be re-checkable rather than
14
+ * trusted.
15
+ * - `explainCandidate` — every rule's verdict on one candidate, with numbers.
16
+ * - `repairSchedule` — minimal-perturbation re-plan around a disruption, with
17
+ * a ranked list of who can lawfully be called.
18
+ * - `diagnoseInfeasibility` — why the problem cannot be solved, before it is
19
+ * attempted.
20
+ */
21
+ Object.defineProperty(exports, "__esModule", { value: true });
22
+ exports.diagnoseInfeasibility = exports.rankCandidates = exports.repairSchedule = exports.explainCandidate = exports.checkCompliance = void 0;
23
+ const model_1 = require("./model");
24
+ const propagation_1 = require("./engine/propagation");
25
+ const state_1 = require("./engine/state");
26
+ const construction_1 = require("./engine/construction");
27
+ const verdicts_1 = require("./engine/verdicts");
28
+ const scheduler_class_1 = require("./scheduler.class");
29
+ const availability_1 = require("./constraints/availability");
30
+ const cost_1 = require("./cost");
31
+ const time_1 = require("./time");
32
+ /**
33
+ * Validate an externally-produced or hand-edited roster.
34
+ *
35
+ * Runs the same constraints as the solver — there is deliberately no second
36
+ * validation path, because two paths drift and the one that drifts is always
37
+ * the one nobody reads.
38
+ */
39
+ function checkCompliance(input, roster) {
40
+ const ctx = (0, model_1.buildModel)(input);
41
+ const state = (0, state_1.createState)(ctx);
42
+ const violations = [];
43
+ for (const entry of roster) {
44
+ if (!ctx.instanceById.has(entry.shiftInstanceId)) {
45
+ violations.push({
46
+ constraintId: 'input',
47
+ severity: 'hard',
48
+ shiftInstanceId: entry.shiftInstanceId,
49
+ message: `roster references unknown shift instance "${entry.shiftInstanceId}"`,
50
+ });
51
+ continue;
52
+ }
53
+ if (!ctx.employeeById.has(entry.employeeId)) {
54
+ violations.push({
55
+ constraintId: 'input',
56
+ severity: 'hard',
57
+ employeeId: entry.employeeId,
58
+ message: `roster references unknown employee "${entry.employeeId}"`,
59
+ });
60
+ continue;
61
+ }
62
+ (0, state_1.assign)(state, entry.employeeId, entry.shiftInstanceId, entry.reasons ?? []);
63
+ }
64
+ // The same two passes the solver runs when it assembles its result.
65
+ const verdicts = [];
66
+ for (const [instanceId, employees] of state.assignments) {
67
+ for (const employeeId of employees) {
68
+ const pair = { employeeId, shiftInstanceId: instanceId };
69
+ verdicts.push({ pair, verdicts: (0, verdicts_1.verdictsFor)(state, pair) });
70
+ }
71
+ }
72
+ violations.push(...(0, verdicts_1.collectPairViolations)(state), ...(0, verdicts_1.collectAggregateViolations)(state));
73
+ return {
74
+ compliant: violations.every((v) => v.severity !== 'hard'),
75
+ violations,
76
+ verdicts,
77
+ ledger: [],
78
+ };
79
+ }
80
+ exports.checkCompliance = checkCompliance;
81
+ /* ------------------------------------------------------------------------- */
82
+ /* Explanation */
83
+ /* ------------------------------------------------------------------------- */
84
+ /**
85
+ * Why can — or can't — this person work this shift?
86
+ *
87
+ * A rule-by-rule scan against live state, not a solve. This is the question
88
+ * managers actually ask, and answering it with concrete numbers ("clock-out
89
+ * 22:00, shift starts 06:00, that is 8h against an 11h minimum") is what makes
90
+ * the roster arguable rather than oracular.
91
+ */
92
+ function explainCandidate(input, employeeId, shiftInstanceId, roster = []) {
93
+ const ctx = (0, model_1.buildModel)(input);
94
+ const state = (0, state_1.createState)(ctx);
95
+ for (const entry of roster) {
96
+ if (entry.employeeId === employeeId && entry.shiftInstanceId === shiftInstanceId)
97
+ continue;
98
+ if (ctx.instanceById.has(entry.shiftInstanceId) && ctx.employeeById.has(entry.employeeId)) {
99
+ (0, state_1.assign)(state, entry.employeeId, entry.shiftInstanceId, []);
100
+ }
101
+ }
102
+ return (0, verdicts_1.verdictsFor)(state, { employeeId, shiftInstanceId });
103
+ }
104
+ exports.explainCandidate = explainCandidate;
105
+ /**
106
+ * Re-plan around a disruption, changing as little as possible.
107
+ *
108
+ * Everything not touched by the disruption is pinned, so the answer is a *diff*
109
+ * a manager can act on rather than a fresh roster nobody recognises. A full
110
+ * re-solve at 06:00 returns a different schedule for the whole team, which is
111
+ * not an answer anyone will accept.
112
+ *
113
+ * The candidate list is a ranked scan, not a solve — that is what keeps it
114
+ * interactive, and it is also the more useful output: the gap is filled by
115
+ * phoning someone, so the operator needs an ordered list with reasons, not a
116
+ * single name.
117
+ */
118
+ function repairSchedule(input, disruption, published) {
119
+ const openings = openingsFor(disruption, published);
120
+ const surviving = published.filter((entry) => !isDropped(entry, disruption));
121
+ // Re-solve with the untouched roster pinned. Only the openings are free.
122
+ const repaired = (0, scheduler_class_1.solveSchedule)({
123
+ ...applyDisruption(input, disruption),
124
+ pinned: surviving.map((e) => ({ employeeId: e.employeeId, shiftInstanceId: e.shiftInstanceId })),
125
+ published: { roster: published, publishedAt: input.published?.publishedAt },
126
+ });
127
+ const before = new Set(published.map((e) => `${e.employeeId}|${e.shiftInstanceId}`));
128
+ const after = new Set(repaired.assignments.map((e) => `${e.employeeId}|${e.shiftInstanceId}`));
129
+ const added = [...after].filter((k) => !before.has(k)).map(toPair);
130
+ const removed = [...before].filter((k) => !after.has(k)).map(toPair);
131
+ const affected = new Set([...added, ...removed].map((p) => p.employeeId));
132
+ const candidates = openings.flatMap((instanceId) => rankCandidates(input, instanceId, surviving, disruption));
133
+ return {
134
+ diff: { added, removed },
135
+ candidates,
136
+ violationsIntroduced: repaired.violations.filter((v) => v.severity === 'hard'),
137
+ perturbation: { changedAssignments: added.length + removed.length, affectedEmployees: affected.size },
138
+ };
139
+ }
140
+ exports.repairSchedule = repairSchedule;
141
+ /**
142
+ * Rank everyone who could take an open shift.
143
+ *
144
+ * The hard gate and the soft ordering are kept separate on purpose: an
145
+ * ineligible person is *never* promoted by being cheap, and the reason they are
146
+ * ineligible is still reported, because "Anna would be ideal but is 2h short on
147
+ * rest" is more useful than Anna's silent absence from the list.
148
+ *
149
+ * Ordering uses cost, fairness debt and stated preference — all facts about
150
+ * declared data and realised assignments. No reliability score, no acceptance
151
+ * history, no no-show prediction: those would make this profiling under AI Act
152
+ * Annex III point 4(b), which is high-risk with no narrow-task exemption.
153
+ */
154
+ function rankCandidates(input, shiftInstanceId, roster, disruption) {
155
+ const ctx = (0, model_1.buildModel)(input);
156
+ const inst = ctx.instanceById.get(shiftInstanceId);
157
+ if (!inst)
158
+ return [];
159
+ const state = (0, state_1.createState)(ctx);
160
+ for (const entry of roster) {
161
+ if (ctx.instanceById.has(entry.shiftInstanceId) && ctx.employeeById.has(entry.employeeId)) {
162
+ (0, state_1.assign)(state, entry.employeeId, entry.shiftInstanceId, []);
163
+ }
164
+ }
165
+ const excluded = disruption && 'employeeId' in disruption ? disruption.employeeId : undefined;
166
+ const extraLoad = extraShiftCounts(state);
167
+ const meanExtra = average([...extraLoad.values()]);
168
+ const candidates = [];
169
+ for (const employee of ctx.employees) {
170
+ if (employee.id === excluded)
171
+ continue;
172
+ if (state.isAssigned(employee.id, shiftInstanceId))
173
+ continue;
174
+ const pair = { employeeId: employee.id, shiftInstanceId };
175
+ const verdicts = (0, verdicts_1.verdictsFor)(state, pair);
176
+ const blockers = verdicts.filter((v) => !v.pass && v.severity === 'hard');
177
+ const eligible = blockers.length === 0 && (0, construction_1.hardCompliant)(ctx, state, employee.id, shiftInstanceId);
178
+ // Marginal against what this person already holds: the same shift is
179
+ // dearer in the hands of someone past their overtime threshold.
180
+ const costCents = (0, cost_1.marginalCostCents)(inst, employee, state.minutesByEmployee.get(employee.id) ?? 0, ctx.rules.engagement);
181
+ const fairnessDebt = meanExtra - (extraLoad.get(employee.id) ?? 0);
182
+ const preference = (0, availability_1.preferenceScore)(ctx.clock, employee.availability, inst);
183
+ candidates.push({
184
+ employeeId: employee.id,
185
+ shiftInstanceId,
186
+ eligible,
187
+ verdicts,
188
+ blockers,
189
+ marginalCostCents: costCents,
190
+ fairnessDebt,
191
+ // Ineligible candidates sort to the bottom but stay visible.
192
+ rank: eligible ? costCents / 100 - fairnessDebt * 10 + preference * 5 : Number.MAX_SAFE_INTEGER,
193
+ rationale: rationaleFor(eligible, blockers, costCents, fairnessDebt, preference),
194
+ });
195
+ }
196
+ return candidates.sort((a, b) => a.rank - b.rank || (a.employeeId < b.employeeId ? -1 : 1));
197
+ }
198
+ exports.rankCandidates = rankCandidates;
199
+ function rationaleFor(eligible, blockers, costCents, fairnessDebt, preference) {
200
+ if (!eligible)
201
+ return blockers.map((b) => b.message).join('; ') || 'not eligible';
202
+ const parts = [`€${(costCents / 100).toFixed(2)} marginal cost`];
203
+ if (fairnessDebt > 0)
204
+ parts.push(`${fairnessDebt.toFixed(1)} fewer extra shifts than average`);
205
+ if (preference < 0)
206
+ parts.push('prefers this window');
207
+ if (preference > 0)
208
+ parts.push('would rather avoid this window');
209
+ return parts.join(' · ');
210
+ }
211
+ /** Shifts each person already holds, as the basis for fairness debt. */
212
+ function extraShiftCounts(state) {
213
+ const counts = new Map();
214
+ for (const employee of state.ctx.employees) {
215
+ counts.set(employee.id, state.byEmployee.get(employee.id)?.size ?? 0);
216
+ }
217
+ return counts;
218
+ }
219
+ function average(values) {
220
+ return values.length === 0 ? 0 : values.reduce((a, b) => a + b, 0) / values.length;
221
+ }
222
+ function openingsFor(disruption, published) {
223
+ switch (disruption.kind) {
224
+ case 'noShow':
225
+ return [disruption.shiftInstanceId];
226
+ case 'absence':
227
+ return published.filter((e) => e.employeeId === disruption.employeeId).map((e) => e.shiftInstanceId);
228
+ case 'cancelShift':
229
+ return [];
230
+ }
231
+ }
232
+ function isDropped(entry, disruption) {
233
+ switch (disruption.kind) {
234
+ case 'noShow':
235
+ return entry.employeeId === disruption.employeeId && entry.shiftInstanceId === disruption.shiftInstanceId;
236
+ case 'absence':
237
+ return entry.employeeId === disruption.employeeId;
238
+ case 'cancelShift':
239
+ return entry.shiftInstanceId === disruption.shiftInstanceId;
240
+ }
241
+ }
242
+ /**
243
+ * Fold the disruption into the problem itself, so every rule sees it.
244
+ *
245
+ * This has to change the *input*, not just the roster. Simply dropping the
246
+ * assignment and re-solving lets the solver hand the shift straight back to the
247
+ * person who called in sick — the removal is not a fact about the world, only
248
+ * about the plan.
249
+ */
250
+ function applyDisruption(input, disruption) {
251
+ switch (disruption.kind) {
252
+ case 'absence':
253
+ return {
254
+ ...input,
255
+ absences: [
256
+ ...(input.absences ?? []),
257
+ {
258
+ employeeId: disruption.employeeId,
259
+ from: disruption.from,
260
+ to: disruption.to ?? input.period.endDate,
261
+ kind: 'sick',
262
+ },
263
+ ],
264
+ };
265
+ case 'noShow': {
266
+ // Scoped time off: this person, this occurrence. They remain
267
+ // available for everything else, which is what a no-show means.
268
+ const date = disruption.shiftInstanceId.split('@')[1];
269
+ return {
270
+ ...input,
271
+ employees: input.employees.map((e) => e.id === disruption.employeeId
272
+ ? { ...e, timeOff: [...e.timeOff, { date, shiftInstanceId: disruption.shiftInstanceId }] }
273
+ : e),
274
+ };
275
+ }
276
+ case 'cancelShift':
277
+ return withoutInstance(input, disruption.shiftInstanceId);
278
+ }
279
+ }
280
+ /**
281
+ * Remove one occurrence from the problem.
282
+ *
283
+ * Templates are materialized to explicit dates first, because a template driven
284
+ * by `daysOfWeek` has no single date to strike out. Cancelling has to remove the
285
+ * *demand*, not merely the assignment, or the solver dutifully refills a shift
286
+ * that is no longer running.
287
+ */
288
+ function withoutInstance(input, instanceId) {
289
+ const ctx = (0, model_1.buildModel)(input);
290
+ const target = ctx.instanceById.get(instanceId);
291
+ if (!target)
292
+ return input;
293
+ const shifts = input.shifts.flatMap((template) => {
294
+ if (template.id !== target.templateId)
295
+ return [template];
296
+ const dates = ctx.instances.filter((i) => i.templateId === template.id).map((i) => i.date);
297
+ const remaining = dates.filter((d) => d !== target.date);
298
+ if (remaining.length === 0)
299
+ return [];
300
+ return [{ ...template, dates: remaining, daysOfWeek: undefined }];
301
+ });
302
+ return { ...input, shifts };
303
+ }
304
+ function toPair(key) {
305
+ const [employeeId, shiftInstanceId] = key.split('|');
306
+ return { employeeId, shiftInstanceId };
307
+ }
308
+ /**
309
+ * Why the problem cannot be solved, before spending a search budget on it.
310
+ *
311
+ * Cheap arithmetic catches most real infeasibility: total demand against total
312
+ * available capacity, per tag. "You are 24 registered-nurse-hours short on
313
+ * Tuesday to Thursday nights" starts a conversation; "no solution found" ends
314
+ * one.
315
+ */
316
+ function diagnoseInfeasibility(input) {
317
+ const ctx = (0, model_1.buildModel)(input);
318
+ const propagation = (0, propagation_1.propagate)(ctx);
319
+ const findings = [];
320
+ for (const inst of ctx.instances) {
321
+ const eligible = propagation.eligibleByInstance.get(inst.id) ?? [];
322
+ if (inst.minEmployees > 0 && eligible.length === 0) {
323
+ findings.push({
324
+ kind: 'noEligibleEmployee',
325
+ shiftInstanceId: inst.id,
326
+ message: `no employee is eligible for "${inst.id}"`,
327
+ });
328
+ }
329
+ else if (eligible.length < inst.minEmployees) {
330
+ findings.push({
331
+ kind: 'insufficientCapacity',
332
+ shiftInstanceId: inst.id,
333
+ shortfall: inst.minEmployees - eligible.length,
334
+ message: `"${inst.id}" needs ${inst.minEmployees} employees but only ${eligible.length} are eligible`,
335
+ });
336
+ }
337
+ }
338
+ // Demand against capacity in aggregate, which catches the shortfalls no
339
+ // single shift reveals: every shift individually fillable, not all at once.
340
+ const demandMinutes = ctx.instances.reduce((sum, i) => sum + i.minEmployees * i.workingMinutes, 0);
341
+ const capacityMinutes = ctx.employees.reduce((sum, e) => {
342
+ const cap = e.maxHoursForPeriod !== undefined ? e.maxHoursForPeriod * 60 : ctx.periodDays * time_1.MINUTES_PER_DAY;
343
+ return sum + cap;
344
+ }, 0);
345
+ if (demandMinutes > capacityMinutes) {
346
+ findings.push({
347
+ kind: 'insufficientCapacity',
348
+ shortfall: demandMinutes - capacityMinutes,
349
+ message: `the roster needs ${(demandMinutes / 60).toFixed(1)}h of work but the team's hour budgets total ${(capacityMinutes / 60).toFixed(1)}h`,
350
+ });
351
+ }
352
+ for (const [tag, needed] of tagDemand(ctx).entries()) {
353
+ const supply = ctx.employees.filter((e) => ctx.employeeTags.get(e.id)?.has(tag)).length;
354
+ if (supply === 0 && needed > 0) {
355
+ findings.push({
356
+ kind: 'tagCapacity',
357
+ tag,
358
+ shortfall: needed,
359
+ message: `${needed} assignment(s) require the tag "${tag}" but nobody in the team holds it`,
360
+ });
361
+ }
362
+ }
363
+ return { feasible: findings.length === 0, findings };
364
+ }
365
+ exports.diagnoseInfeasibility = diagnoseInfeasibility;
366
+ function tagDemand(ctx) {
367
+ const demand = new Map();
368
+ for (const inst of ctx.instances) {
369
+ for (const [tag, count] of Object.entries(inst.tagRequirements)) {
370
+ demand.set(tag, (demand.get(tag) ?? 0) + count);
371
+ }
372
+ for (const tag of inst.requiredTags)
373
+ demand.set(tag, (demand.get(tag) ?? 0) + inst.minEmployees);
374
+ }
375
+ return demand;
376
+ }
@@ -0,0 +1,33 @@
1
+ /**
2
+ * Provenance — identifying what produced a roster.
3
+ *
4
+ * Reproducibility is an audit requirement here, not a convenience. The defence
5
+ * of a roster is "it was lawful under the rules as they stood", which needs the
6
+ * rules and the objective weights to be identifiable after the fact. In Germany
7
+ * the weights are themselves co-determination subject matter (BetrVG §87(1)),
8
+ * so "we retuned the solver" is a works-council question, not an internal one.
9
+ *
10
+ * The hash is a stable digest of the configuration, not a cryptographic
11
+ * commitment: it exists to detect that the rules changed between two runs, and
12
+ * to key an audit record. It is deliberately dependency-free.
13
+ */
14
+ import type { ConstraintOptions, ObjectiveWeights, WorkingTimeRules } from './types';
15
+ /**
16
+ * A stable digest of the rule set, constraint options and objective weights.
17
+ *
18
+ * Object keys are sorted before hashing so two configurations that differ only
19
+ * in property order produce the same digest — otherwise a round-trip through
20
+ * JSON would look like a rule change.
21
+ */
22
+ export declare function hashRules(rules: WorkingTimeRules | undefined, options: ConstraintOptions | undefined, objectives?: ObjectiveWeights): string;
23
+ /** JSON with object keys sorted recursively. */
24
+ export declare function stableStringify(value: unknown): string;
25
+ /**
26
+ * 64-bit FNV-1a, rendered as hex.
27
+ *
28
+ * Implemented over two 32-bit halves because JavaScript's bitwise operators
29
+ * truncate to 32 bits, and a 32-bit digest collides too readily to key an audit
30
+ * record on.
31
+ */
32
+ export declare function fnv1a64(input: string): string;
33
+ //# sourceMappingURL=provenance.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"provenance.d.ts","sourceRoot":"","sources":["../../src/scheduling/provenance.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAEH,OAAO,KAAK,EAAE,iBAAiB,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,MAAM,SAAS,CAAC;AAErF;;;;;;GAMG;AACH,wBAAgB,SAAS,CACrB,KAAK,EAAE,gBAAgB,GAAG,SAAS,EACnC,OAAO,EAAE,iBAAiB,GAAG,SAAS,EACtC,UAAU,CAAC,EAAE,gBAAgB,GAC9B,MAAM,CAYR;AAED,gDAAgD;AAChD,wBAAgB,eAAe,CAAC,KAAK,EAAE,OAAO,GAAG,MAAM,CAOtD;AAED;;;;;;GAMG;AACH,wBAAgB,OAAO,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,CAY7C"}
@@ -0,0 +1,70 @@
1
+ "use strict";
2
+ /**
3
+ * Provenance — identifying what produced a roster.
4
+ *
5
+ * Reproducibility is an audit requirement here, not a convenience. The defence
6
+ * of a roster is "it was lawful under the rules as they stood", which needs the
7
+ * rules and the objective weights to be identifiable after the fact. In Germany
8
+ * the weights are themselves co-determination subject matter (BetrVG §87(1)),
9
+ * so "we retuned the solver" is a works-council question, not an internal one.
10
+ *
11
+ * The hash is a stable digest of the configuration, not a cryptographic
12
+ * commitment: it exists to detect that the rules changed between two runs, and
13
+ * to key an audit record. It is deliberately dependency-free.
14
+ */
15
+ Object.defineProperty(exports, "__esModule", { value: true });
16
+ exports.fnv1a64 = exports.stableStringify = exports.hashRules = void 0;
17
+ /**
18
+ * A stable digest of the rule set, constraint options and objective weights.
19
+ *
20
+ * Object keys are sorted before hashing so two configurations that differ only
21
+ * in property order produce the same digest — otherwise a round-trip through
22
+ * JSON would look like a rule change.
23
+ */
24
+ function hashRules(rules, options, objectives) {
25
+ const payload = stableStringify({
26
+ rules: rules ?? null,
27
+ // Only the parts of `constraints` that change outcomes: custom rules are
28
+ // functions and cannot be hashed, so their ids stand in for them.
29
+ minRestMinutes: options?.minRestMinutes ?? null,
30
+ oneShiftPerDay: options?.oneShiftPerDay ?? null,
31
+ overrides: options?.overrides ?? null,
32
+ custom: (options?.custom ?? []).map((c) => ({ id: c.id, hardness: c.hardness, weight: c.weight ?? null })),
33
+ objectives: objectives ?? null,
34
+ });
35
+ return fnv1a64(payload);
36
+ }
37
+ exports.hashRules = hashRules;
38
+ /** JSON with object keys sorted recursively. */
39
+ function stableStringify(value) {
40
+ if (value === null || typeof value !== 'object')
41
+ return JSON.stringify(value) ?? 'null';
42
+ if (Array.isArray(value))
43
+ return `[${value.map(stableStringify).join(',')}]`;
44
+ const entries = Object.entries(value)
45
+ .filter(([, v]) => v !== undefined)
46
+ .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
47
+ return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${stableStringify(v)}`).join(',')}}`;
48
+ }
49
+ exports.stableStringify = stableStringify;
50
+ /**
51
+ * 64-bit FNV-1a, rendered as hex.
52
+ *
53
+ * Implemented over two 32-bit halves because JavaScript's bitwise operators
54
+ * truncate to 32 bits, and a 32-bit digest collides too readily to key an audit
55
+ * record on.
56
+ */
57
+ function fnv1a64(input) {
58
+ let high = 3421674724;
59
+ let low = 2216829733;
60
+ for (let i = 0; i < input.length; i++) {
61
+ low ^= input.charCodeAt(i) & 0xff;
62
+ // Multiply by the 64-bit FNV prime (0x100000001b3) via 32-bit halves.
63
+ const lowMul = low * 0x1b3;
64
+ const highMul = high * 0x1b3 + Math.floor(lowMul / 4294967296) + low * 0x100;
65
+ low = lowMul >>> 0;
66
+ high = highMul >>> 0;
67
+ }
68
+ return high.toString(16).padStart(8, '0') + low.toString(16).padStart(8, '0');
69
+ }
70
+ exports.fnv1a64 = fnv1a64;
@@ -0,0 +1,23 @@
1
+ /**
2
+ * Helpers for expressing working-time rules.
3
+ *
4
+ * These are arithmetic conveniences, not policy: they hold no jurisdiction's
5
+ * numbers, they just remove the two conversions people reliably get wrong when
6
+ * writing a `WorkingTimeRules` object by hand.
7
+ */
8
+ import type { RollingAverage } from './types';
9
+ /**
10
+ * "At most `hoursPerWeek` on average over `days`" as a rolling-window limit.
11
+ *
12
+ * The conversion is the trap. A rolling average is expressed as a *total* over
13
+ * the window, so 48h/week over four months is not `{maxMinutes: 2880,
14
+ * windowDays: 120}` — that would cap the whole four months at 48 hours. It is
15
+ * 48h × (120 ÷ 7) ≈ 823h. Getting this wrong produces a rule that looks right
16
+ * and is off by a factor of seventeen.
17
+ */
18
+ export declare function weeklyAverageOver(hoursPerWeek: number, days: number, label?: string): RollingAverage;
19
+ /** Hours as minutes, for readability in rule objects. */
20
+ export declare function hours(count: number): number;
21
+ /** Days as minutes. */
22
+ export declare function days(count: number): number;
23
+ //# sourceMappingURL=rules.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"rules.d.ts","sourceRoot":"","sources":["../../src/scheduling/rules.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AAE9C;;;;;;;;GAQG;AACH,wBAAgB,iBAAiB,CAAC,YAAY,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,KAAK,CAAC,EAAE,MAAM,GAAG,cAAc,CAMpG;AAED,yDAAyD;AACzD,wBAAgB,KAAK,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,CAE3C;AAED,uBAAuB;AACvB,wBAAgB,IAAI,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,CAE1C"}