assignment-user-matcher 1.15.0 → 1.16.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 (70) hide show
  1. package/README.md +378 -9
  2. package/dist/index.d.ts +5 -3
  3. package/dist/index.d.ts.map +1 -1
  4. package/dist/index.js +6 -1
  5. package/dist/learning/atomic-ingestion.d.ts +11 -0
  6. package/dist/learning/atomic-ingestion.d.ts.map +1 -0
  7. package/dist/learning/atomic-ingestion.js +187 -0
  8. package/dist/learning/auto-weights.d.ts +13 -2
  9. package/dist/learning/auto-weights.d.ts.map +1 -1
  10. package/dist/learning/auto-weights.js +203 -35
  11. package/dist/learning/features.d.ts +5 -3
  12. package/dist/learning/features.d.ts.map +1 -1
  13. package/dist/learning/features.js +105 -4
  14. package/dist/learning/policy.d.ts +57 -0
  15. package/dist/learning/policy.d.ts.map +1 -0
  16. package/dist/learning/policy.js +71 -0
  17. package/dist/managers/LearningManager.d.ts +312 -35
  18. package/dist/managers/LearningManager.d.ts.map +1 -1
  19. package/dist/managers/LearningManager.js +1006 -168
  20. package/dist/matcher.class.d.ts +98 -11
  21. package/dist/matcher.class.d.ts.map +1 -1
  22. package/dist/matcher.class.js +247 -40
  23. package/dist/scheduling/constraints/cost.d.ts.map +1 -1
  24. package/dist/scheduling/constraints/cost.js +3 -2
  25. package/dist/scheduling/constraints/employee-scope.d.ts +5 -0
  26. package/dist/scheduling/constraints/employee-scope.d.ts.map +1 -0
  27. package/dist/scheduling/constraints/employee-scope.js +157 -0
  28. package/dist/scheduling/constraints/notice.d.ts.map +1 -1
  29. package/dist/scheduling/constraints/notice.js +8 -5
  30. package/dist/scheduling/constraints/rest-days.d.ts.map +1 -1
  31. package/dist/scheduling/constraints/rest-days.js +6 -6
  32. package/dist/scheduling/cost.d.ts.map +1 -1
  33. package/dist/scheduling/cost.js +2 -1
  34. package/dist/scheduling/engine/construction.d.ts +11 -3
  35. package/dist/scheduling/engine/construction.d.ts.map +1 -1
  36. package/dist/scheduling/engine/construction.js +31 -6
  37. package/dist/scheduling/engine/objective.d.ts +4 -4
  38. package/dist/scheduling/engine/objective.d.ts.map +1 -1
  39. package/dist/scheduling/engine/objective.js +12 -4
  40. package/dist/scheduling/engine/propagation.js +2 -1
  41. package/dist/scheduling/engine/search.d.ts +1 -0
  42. package/dist/scheduling/engine/search.d.ts.map +1 -1
  43. package/dist/scheduling/engine/search.js +1 -1
  44. package/dist/scheduling/engine/state.d.ts.map +1 -1
  45. package/dist/scheduling/engine/state.js +4 -0
  46. package/dist/scheduling/index.d.ts +1 -1
  47. package/dist/scheduling/index.d.ts.map +1 -1
  48. package/dist/scheduling/model.d.ts +1 -1
  49. package/dist/scheduling/model.d.ts.map +1 -1
  50. package/dist/scheduling/model.js +184 -42
  51. package/dist/scheduling/operations.d.ts +4 -0
  52. package/dist/scheduling/operations.d.ts.map +1 -1
  53. package/dist/scheduling/operations.js +36 -16
  54. package/dist/scheduling/provenance.d.ts +1 -1
  55. package/dist/scheduling/provenance.d.ts.map +1 -1
  56. package/dist/scheduling/provenance.js +16 -2
  57. package/dist/scheduling/scheduler.class.d.ts +1 -1
  58. package/dist/scheduling/scheduler.class.d.ts.map +1 -1
  59. package/dist/scheduling/scheduler.class.js +5 -3
  60. package/dist/scheduling/time.d.ts +2 -0
  61. package/dist/scheduling/time.d.ts.map +1 -1
  62. package/dist/scheduling/time.js +26 -1
  63. package/dist/scheduling/types.d.ts +78 -3
  64. package/dist/scheduling/types.d.ts.map +1 -1
  65. package/dist/types/matcher.d.ts +309 -4
  66. package/dist/types/matcher.d.ts.map +1 -1
  67. package/dist/utils/keys.d.ts +12 -2
  68. package/dist/utils/keys.d.ts.map +1 -1
  69. package/dist/utils/keys.js +35 -2
  70. package/package.json +2 -1
@@ -29,6 +29,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
29
29
  exports.MINUTES_PER_DAY = exports.availabilityApplies = exports.buildModel = exports.resolveConstraints = exports.mergeRules = exports.expandTemplate = exports.expandShiftInstances = exports.addDays = exports.daysBetween = void 0;
30
30
  const types_1 = require("./types");
31
31
  const constraint_1 = require("./constraints/constraint");
32
+ const employee_scope_1 = require("./constraints/employee-scope");
32
33
  const min_rest_1 = require("./constraints/min-rest");
33
34
  const overtime_1 = require("./constraints/overtime");
34
35
  const contract_hours_1 = require("./contract-hours");
@@ -86,28 +87,51 @@ function expandTemplate(template, clock, periodDays, context) {
86
87
  (!Number.isInteger(template.maxEmployees) || template.maxEmployees < (template.minEmployees ?? 1))) {
87
88
  throw new types_1.ScheduleValidationError(`Shift template "${template.id}" has maxEmployees below minEmployees`);
88
89
  }
90
+ const overrides = validateDemandOverrides(template);
89
91
  const startTod = (0, time_1.parseTimeOfDay)(template.startTime, `shift "${template.id}".startTime`);
90
92
  const endTodRaw = (0, time_1.parseTimeOfDay)(template.endTime, `shift "${template.id}".endTime`);
91
93
  // Overnight shifts roll the end into the next day explicitly; a same-time
92
94
  // start/end is treated as a full 24h shift, never zero length.
93
95
  const overnight = endTodRaw <= startTod;
94
- const dates = [];
96
+ // The template's own pattern, then the dates an override opens on top of it.
97
+ // A weekday-only shift that has to open for one weekend is a temporary fact
98
+ // like any other here, and the alternative — widening the template's
99
+ // `daysOfWeek` — would open every weekend from then on.
100
+ const onPattern = new Set();
95
101
  if (template.dates) {
96
102
  for (const d of template.dates) {
97
103
  (0, time_1.assertIsoDate)(d, `shift "${template.id}".dates`);
98
104
  const offset = clock.dayIndexOf(d);
99
105
  if (offset >= 0 && offset < periodDays)
100
- dates.push(d);
106
+ onPattern.add(d);
101
107
  }
102
108
  }
103
109
  else {
104
110
  for (let i = 0; i < periodDays; i++) {
105
111
  const d = clock.dateAt(i);
106
112
  if (!template.daysOfWeek || template.daysOfWeek.includes((0, time_1.isoWeekday)(d)))
107
- dates.push(d);
113
+ onPattern.add(d);
108
114
  }
109
115
  }
110
- return dates.map((date) => {
116
+ const candidates = new Set(onPattern);
117
+ for (const override of overrides) {
118
+ if (override.runs !== true)
119
+ continue;
120
+ for (let i = 0; i < periodDays; i++) {
121
+ const d = clock.dateAt(i);
122
+ if (d < override.from || d > override.to)
123
+ continue;
124
+ if (override.daysOfWeek?.length && !override.daysOfWeek.includes((0, time_1.isoWeekday)(d)))
125
+ continue;
126
+ candidates.add(d);
127
+ }
128
+ }
129
+ const dates = [...candidates].sort();
130
+ const instances = [];
131
+ for (const date of dates) {
132
+ const demand = resolveDemand(template, overrides, date, onPattern.has(date));
133
+ if (!demand)
134
+ continue;
111
135
  const startMinute = clock.toPeriodMinutes(date, template.startTime, `shift "${template.id}".startTime`);
112
136
  const endDate = overnight ? (0, time_1.addDays)(date, 1) : date;
113
137
  const endMinute = clock.toPeriodMinutes(endDate, template.endTime, `shift "${template.id}".endTime`);
@@ -118,11 +142,11 @@ function expandTemplate(template, clock, periodDays, context) {
118
142
  throw new types_1.ScheduleValidationError(`Shift template "${template.id}" resolves to a non-positive duration on ${date}`);
119
143
  }
120
144
  const unpaidBreak = template.unpaidBreakMinutes ?? 0;
121
- if (unpaidBreak < 0 || unpaidBreak >= durationMinutes) {
145
+ if (!Number.isFinite(unpaidBreak) || unpaidBreak < 0 || unpaidBreak >= durationMinutes) {
122
146
  throw new types_1.ScheduleValidationError(`Shift template "${template.id}" has invalid unpaidBreakMinutes`);
123
147
  }
124
148
  const paidBreak = template.paidBreakMinutes ?? 0;
125
- if (paidBreak < 0 || unpaidBreak + paidBreak >= durationMinutes) {
149
+ if (!Number.isFinite(paidBreak) || paidBreak < 0 || unpaidBreak + paidBreak >= durationMinutes) {
126
150
  throw new types_1.ScheduleValidationError(`Shift template "${template.id}" has invalid paidBreakMinutes`);
127
151
  }
128
152
  // A paid break counts as working time, so only the unpaid one is deducted.
@@ -130,7 +154,7 @@ function expandTemplate(template, clock, periodDays, context) {
130
154
  const range = { start: startMinute, end: endMinute };
131
155
  const nightMinutes = context.nightRule ? clock.minutesInClockRange(range, context.nightRule.window) : 0;
132
156
  const nightThreshold = context.nightRule?.qualifiesAfterMinutes ?? 180;
133
- return {
157
+ const instance = {
134
158
  id: `${template.id}@${date}`,
135
159
  templateId: template.id,
136
160
  name: template.name,
@@ -141,11 +165,11 @@ function expandTemplate(template, clock, periodDays, context) {
141
165
  workingMinutes,
142
166
  paidBreakMinutes: paidBreak,
143
167
  unpaidBreakMinutes: unpaidBreak,
144
- minEmployees: template.minEmployees ?? 1,
145
- maxEmployees: template.maxEmployees,
146
- tagRequirements: template.tagRequirements ?? {},
147
- tagMaximums: template.tagMaximums ?? {},
148
- requiredTags: template.requiredTags ?? [],
168
+ minEmployees: demand.minEmployees,
169
+ maxEmployees: demand.maxEmployees,
170
+ tagRequirements: demand.tagRequirements,
171
+ tagMaximums: demand.tagMaximums,
172
+ requiredTags: demand.requiredTags,
149
173
  shiftTypeTag: template.shiftTypeTag,
150
174
  siteId: template.siteId,
151
175
  duty: template.duty,
@@ -155,9 +179,114 @@ function expandTemplate(template, clock, periodDays, context) {
155
179
  isSunday: (0, time_1.isoWeekday)(date) === 7,
156
180
  isPublicHoliday: context.publicHolidays.has(date),
157
181
  };
158
- });
182
+ if (demand.label !== undefined)
183
+ instance.demandLabel = demand.label;
184
+ instances.push(instance);
185
+ }
186
+ return instances;
159
187
  }
160
188
  exports.expandTemplate = expandTemplate;
189
+ function validateDemandOverrides(template) {
190
+ const overrides = template.demandOverrides ?? [];
191
+ if (!Array.isArray(overrides)) {
192
+ throw new types_1.ScheduleValidationError(`Shift template "${template.id}" has non-array demandOverrides`);
193
+ }
194
+ overrides.forEach((override, index) => {
195
+ const field = `shift "${template.id}".demandOverrides[${index}]`;
196
+ (0, time_1.assertIsoDate)(override.from, `${field}.from`);
197
+ (0, time_1.assertIsoDate)(override.to, `${field}.to`);
198
+ if (override.to < override.from)
199
+ throw new types_1.ScheduleValidationError(`${field}: to precedes from`);
200
+ if (override.daysOfWeek !== undefined) {
201
+ const ok = Array.isArray(override.daysOfWeek) &&
202
+ override.daysOfWeek.every((d) => Number.isInteger(d) && d >= 1 && d <= 7);
203
+ if (!ok)
204
+ throw new types_1.ScheduleValidationError(`${field}: daysOfWeek must be ISO weekdays 1..7`);
205
+ }
206
+ for (const key of ['minEmployees', 'extraEmployees']) {
207
+ const value = override[key];
208
+ if (value !== undefined && (!Number.isInteger(value) || value < 0)) {
209
+ throw new types_1.ScheduleValidationError(`${field}: invalid ${key}`);
210
+ }
211
+ }
212
+ if (override.maxEmployees !== undefined &&
213
+ override.maxEmployees !== null &&
214
+ (!Number.isInteger(override.maxEmployees) || override.maxEmployees < 0)) {
215
+ throw new types_1.ScheduleValidationError(`${field}: invalid maxEmployees`);
216
+ }
217
+ });
218
+ return overrides;
219
+ }
220
+ /**
221
+ * Fold the overrides matching `date` onto the template's standing demand.
222
+ *
223
+ * Applied in order, later wins per field, `extraEmployees` accumulates. A
224
+ * minimum raised above the template's standing maximum lifts that maximum with
225
+ * it: "the most it can take" was said of the ordinary day, and "three at the
226
+ * peak" plainly means three. Only a maximum the override itself states is held
227
+ * against the resolved minimum — that combination is a shape nobody can staff.
228
+ */
229
+ function resolveDemand(template, overrides, date, onPattern) {
230
+ let min = template.minEmployees ?? 1;
231
+ let max = template.maxEmployees;
232
+ let extra = 0;
233
+ let maxStated = false;
234
+ let runs = true;
235
+ const demand = {
236
+ minEmployees: min,
237
+ maxEmployees: max,
238
+ tagRequirements: template.tagRequirements ?? {},
239
+ tagMaximums: template.tagMaximums ?? {},
240
+ requiredTags: template.requiredTags ?? [],
241
+ };
242
+ const weekday = (0, time_1.isoWeekday)(date);
243
+ // A date the template's own pattern does not cover is only here because an
244
+ // override opened it, so it starts closed: a later override setting
245
+ // `runs: false` over the same stretch has to be able to shut it again.
246
+ if (!onPattern)
247
+ runs = false;
248
+ let matched = false;
249
+ for (const override of overrides) {
250
+ if (date < override.from || date > override.to)
251
+ continue;
252
+ if (override.daysOfWeek && !override.daysOfWeek.includes(weekday))
253
+ continue;
254
+ matched = true;
255
+ if (override.minEmployees !== undefined)
256
+ min = override.minEmployees;
257
+ if (override.maxEmployees !== undefined) {
258
+ max = override.maxEmployees ?? undefined;
259
+ maxStated = true;
260
+ }
261
+ if (override.extraEmployees !== undefined)
262
+ extra += override.extraEmployees;
263
+ if (override.tagRequirements !== undefined)
264
+ demand.tagRequirements = override.tagRequirements;
265
+ if (override.tagMaximums !== undefined)
266
+ demand.tagMaximums = override.tagMaximums;
267
+ if (override.requiredTags !== undefined)
268
+ demand.requiredTags = override.requiredTags;
269
+ if (override.runs !== undefined)
270
+ runs = override.runs;
271
+ if (override.label !== undefined)
272
+ demand.label = override.label;
273
+ }
274
+ if (!matched)
275
+ return demand;
276
+ if (!runs)
277
+ return null;
278
+ demand.minEmployees = min + extra;
279
+ demand.maxEmployees = max === undefined ? undefined : max + extra;
280
+ if (demand.maxEmployees !== undefined && demand.maxEmployees < demand.minEmployees) {
281
+ if (!maxStated) {
282
+ demand.maxEmployees = demand.minEmployees;
283
+ return demand;
284
+ }
285
+ throw new types_1.ScheduleValidationError(`Shift template "${template.id}" resolves to maxEmployees below minEmployees on ${date}` +
286
+ (demand.label ? ` (${demand.label})` : ''));
287
+ }
288
+ return demand;
289
+ }
161
290
  /**
162
291
  * Working minutes for a duty of `paidSpan` elapsed minutes.
163
292
  *
@@ -191,9 +320,12 @@ function blockedIntervalsFor(employee, clock, periodDays, instanceById) {
191
320
  continue;
192
321
  }
193
322
  const offset = clock.dayIndexOf(entry.date);
194
- if (offset < 0 || offset >= periodDays)
195
- continue; // outside the period: irrelevant, not an error
196
- out.push({ start: clock.dayStartMinutes(offset), end: clock.dayStartMinutes(offset + 1) });
323
+ const blocked = { start: clock.dayStartMinutes(offset), end: clock.dayStartMinutes(offset + 1) };
324
+ if (offset < 0 || offset >= periodDays) {
325
+ if (![...instanceById.values()].some((inst) => inst.startMinute < blocked.end && blocked.start < inst.endMinute))
326
+ continue;
327
+ }
328
+ out.push(blocked);
197
329
  }
198
330
  // External commitments are blackouts the roster may never override
199
331
  // (Directive (EU) 2019/1152 Art 9 bars treating parallel employment as
@@ -205,15 +337,11 @@ function blockedIntervalsFor(employee, clock, periodDays, instanceById) {
205
337
  }
206
338
  /** Resolve an ISO date or date-time span to period minutes. */
207
339
  function spanToMinutes(from, to, clock, field) {
208
- const parse = (value, endOfDayWhenBare) => {
209
- const [datePart, timePart] = value.split('T');
210
- (0, time_1.assertIsoDate)(datePart, field);
211
- if (timePart)
212
- return clock.toPeriodMinutes(datePart, timePart.slice(0, 5), field);
213
- const dayIndex = clock.dayIndexOf(datePart);
214
- return endOfDayWhenBare ? clock.dayStartMinutes(dayIndex + 1) : clock.dayStartMinutes(dayIndex);
215
- };
216
- return { start: parse(from, false), end: parse(to, true) };
340
+ const start = clock.parseDateTime(from, `${field}.from`);
341
+ const end = clock.parseDateTime(to, `${field}.to`, true);
342
+ if (end <= start)
343
+ throw new types_1.ScheduleValidationError(`${field}: to must follow from`);
344
+ return { start, end };
217
345
  }
218
346
  function validateEmployee(employee) {
219
347
  if (!employee.id)
@@ -276,20 +404,30 @@ function mergeRules(base, override) {
276
404
  }
277
405
  exports.mergeRules = mergeRules;
278
406
  /** Resolve built-in constraints with caller hardness/weight overrides, then append customs. */
279
- function resolveConstraints(options, rules, objectives) {
280
- const constraints = (0, constraint_1.createDefaultConstraints)({
407
+ function resolveConstraints(options, rules, objectives, employeeRules) {
408
+ const defaults = {
281
409
  minRestMinutes: options?.minRestMinutes ?? rules?.dailyRest?.minMinutes ?? min_rest_1.DEFAULT_MIN_REST_MINUTES,
282
410
  oneShiftPerDay: options?.oneShiftPerDay ?? false,
283
411
  rules,
284
412
  objectives,
285
- });
413
+ };
414
+ const constraints = employeeRules
415
+ ? (0, employee_scope_1.scopeEmployeeConstraints)(defaults, employeeRules)
416
+ : (0, constraint_1.createDefaultConstraints)(defaults);
286
417
  const overrides = options?.overrides ?? {};
287
418
  for (const c of constraints) {
288
419
  const o = overrides[c.id];
289
420
  if (!o)
290
421
  continue;
291
- if (o.hardness !== undefined)
422
+ if (o.hardness !== undefined) {
292
423
  c.hardness = o.hardness;
424
+ const verdict = c.verdict?.bind(c);
425
+ if (verdict)
426
+ c.verdict = (state, pair) => ({ ...verdict(state, pair), severity: o.hardness });
427
+ const evaluate = c.evaluate?.bind(c);
428
+ if (evaluate)
429
+ c.evaluate = (state) => evaluate(state).map((v) => ({ ...v, severity: o.hardness }));
430
+ }
293
431
  if (o.weight !== undefined)
294
432
  c.weight = o.weight;
295
433
  }
@@ -328,6 +466,15 @@ function buildHistory(history, clock, personIdOf) {
328
466
  function buildModel(input) {
329
467
  (0, time_1.assertIsoDate)(input.period.startDate, 'period.startDate');
330
468
  (0, time_1.assertIsoDate)(input.period.endDate, 'period.endDate');
469
+ for (const [name, value] of [
470
+ ['timeBudgetMs', input.timeBudgetMs],
471
+ ['maxIterations', input.maxIterations],
472
+ ]) {
473
+ if (value !== undefined &&
474
+ (!Number.isFinite(value) || value < 0 || (name === 'maxIterations' && !Number.isInteger(value)))) {
475
+ throw new types_1.ScheduleValidationError(`${name} must be a finite non-negative ${name === 'maxIterations' ? 'integer' : 'number'}`);
476
+ }
477
+ }
331
478
  const periodDays = (0, time_1.daysBetween)(input.period.startDate, input.period.endDate) + 1;
332
479
  if (periodDays <= 0)
333
480
  throw new types_1.ScheduleValidationError('period.endDate must not precede period.startDate');
@@ -397,6 +544,8 @@ function buildModel(input) {
397
544
  }
398
545
  const absences = new Map();
399
546
  for (const absence of input.absences ?? []) {
547
+ if (!employeeById.has(absence.employeeId))
548
+ throw new types_1.ScheduleValidationError(`Unknown absence employee "${absence.employeeId}"`);
400
549
  const span = spanToMinutes(absence.from, absence.to, clock, 'absences');
401
550
  absences.set(absence.employeeId, [...(absences.get(absence.employeeId) ?? []), { ...span, kind: absence.kind }]);
402
551
  // An absence blocks assignment as firmly as time off does.
@@ -409,18 +558,10 @@ function buildModel(input) {
409
558
  publishedPairs.add(`${assignment.employeeId}|${assignment.shiftInstanceId}`);
410
559
  }
411
560
  const pinned = new Set((input.pinned ?? []).map((p) => `${p.employeeId}|${p.shiftInstanceId}`));
412
- let publishedAtMinute;
413
- if (input.published?.publishedAt) {
414
- const [datePart, timePart] = input.published.publishedAt.split('T');
415
- (0, time_1.assertIsoDate)(datePart, 'published.publishedAt');
416
- publishedAtMinute = clock.toPeriodMinutes(datePart, (timePart ?? '00:00').slice(0, 5), 'published.publishedAt');
417
- }
418
- let asOfMinute;
419
- if (input.asOf) {
420
- const [datePart, timePart] = input.asOf.split('T');
421
- (0, time_1.assertIsoDate)(datePart, 'asOf');
422
- asOfMinute = clock.toPeriodMinutes(datePart, (timePart ?? '00:00').slice(0, 5), 'asOf');
423
- }
561
+ const publishedAtMinute = input.published?.publishedAt === undefined
562
+ ? undefined
563
+ : clock.parseDateTime(input.published.publishedAt, 'published.publishedAt');
564
+ const asOfMinute = input.asOf === undefined ? undefined : clock.parseDateTime(input.asOf, 'asOf');
424
565
  return {
425
566
  periodStartDate: input.period.startDate,
426
567
  periodDays,
@@ -432,7 +573,8 @@ function buildModel(input) {
432
573
  siteIndex,
433
574
  employeeBlockedIntervals,
434
575
  minRestMinutes: input.constraints?.minRestMinutes ?? rules.dailyRest?.minMinutes ?? min_rest_1.DEFAULT_MIN_REST_MINUTES,
435
- constraints: resolveConstraints(input.constraints, rules, input.objectives),
576
+ aggregateConstraints: input.constraints?.custom?.filter((c) => c.evaluate) ?? [],
577
+ constraints: resolveConstraints(input.constraints, rules, input.objectives, rulesByEmployee),
436
578
  clock,
437
579
  rules,
438
580
  rulesByEmployee,
@@ -20,6 +20,10 @@
20
20
  import type { AssignmentPair, ConstraintViolation, LedgerEntry, RuleVerdict, ScheduleInput, ScheduledAssignment, ContractHoursSummary } from './types';
21
21
  export interface ComplianceReport {
22
22
  compliant: boolean;
23
+ /** Whether all headcount and skill coverage requirements are met. */
24
+ coverageComplete: boolean;
25
+ /** A fully covered roster with no hard breaches. */
26
+ publishable: boolean;
23
27
  violations: ConstraintViolation[];
24
28
  /** Per-assignment verdicts for every rule that had something to say. */
25
29
  verdicts: Array<{
@@ -1 +1 @@
1
- {"version":3,"file":"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AC9B,oBAAoB,EAAE,mBAAmB,EAAE,CAAC;IAC5C,YAAY,EAAE;QAAE,kBAAkB,EAAE,MAAM,CAAC;QAAC,iBAAiB,EAAE,MAAM,CAAA;KAAE,CAAC;CAC3E;AAED;;;;;;;;;;;;GAYG;AACH,wBAAgB,cAAc,CAC1B,KAAK,EAAE,aAAa,EACpB,UAAU,EAAE,UAAU,EACtB,SAAS,EAAE,mBAAmB,EAAE,GACjC,YAAY,CA+Bd;AAED;;;;;;;;;;;;GAYG;AACH,wBAAgB,cAAc,CAC1B,KAAK,EAAE,aAAa,EACpB,eAAe,EAAE,MAAM,EACvB,MAAM,EAAE,mBAAmB,EAAE,EAC7B,UAAU,CAAC,EAAE,UAAU,GACxB,eAAe,EAAE,CA6FnB;AAwKD,MAAM,WAAW,mBAAmB;IAChC,QAAQ,EAAE,OAAO,CAAC;IAClB,QAAQ,EAAE,KAAK,CAAC;QACZ,IAAI,EAAE,oBAAoB,GAAG,sBAAsB,GAAG,aAAa,CAAC;QACpE,OAAO,EAAE,MAAM,CAAC;QAChB,eAAe,CAAC,EAAE,MAAM,CAAC;QACzB,GAAG,CAAC,EAAE,MAAM,CAAC;QACb,SAAS,CAAC,EAAE,MAAM,CAAC;KACtB,CAAC,CAAC;CACN;AAED;;;;;;;GAOG;AACH,wBAAgB,qBAAqB,CAAC,KAAK,EAAE,aAAa,GAAG,mBAAmB,CAmD/E"}
@@ -20,6 +20,10 @@
20
20
  */
21
21
  Object.defineProperty(exports, "__esModule", { value: true });
22
22
  exports.diagnoseInfeasibility = exports.rankCandidates = exports.repairSchedule = exports.explainCandidate = exports.checkCompliance = void 0;
23
+ const support_1 = require("./constraints/support");
24
+ const min_staffing_1 = require("./constraints/min-staffing");
25
+ const hour_budget_1 = require("./constraints/hour-budget");
26
+ const objective_1 = require("./engine/objective");
23
27
  const model_1 = require("./model");
24
28
  const propagation_1 = require("./engine/propagation");
25
29
  const state_1 = require("./engine/state");
@@ -69,6 +73,16 @@ function checkCompliance(input, roster) {
69
73
  });
70
74
  continue;
71
75
  }
76
+ if (state.isAssigned(entry.employeeId, entry.shiftInstanceId)) {
77
+ violations.push({
78
+ constraintId: 'input',
79
+ severity: 'hard',
80
+ employeeId: entry.employeeId,
81
+ shiftInstanceId: entry.shiftInstanceId,
82
+ message: 'roster contains a duplicate assignment',
83
+ });
84
+ continue;
85
+ }
72
86
  (0, state_1.assign)(state, entry.employeeId, entry.shiftInstanceId, entry.reasons ?? []);
73
87
  }
74
88
  // The same two passes the solver runs when it assembles its result.
@@ -80,6 +94,8 @@ function checkCompliance(input, roster) {
80
94
  }
81
95
  }
82
96
  violations.push(...(0, verdicts_1.collectPairViolations)(state), ...(0, verdicts_1.collectAggregateViolations)(state));
97
+ const staffing = (0, min_staffing_1.staffingViolations)(ctx, state, 'medium');
98
+ violations.push(...staffing, ...(0, hour_budget_1.minHourViolations)(ctx, state, ctx.constraints.find((c) => c.id === 'hour-budget')?.weight ?? objective_1.MIN_HOURS_WEIGHT));
83
99
  // The same ledger pass the solver runs at result assembly — one judgement
84
100
  // path, so `checkCompliance` can never disagree with `solveSchedule`
85
101
  // about what a roster owes.
@@ -91,6 +107,8 @@ function checkCompliance(input, roster) {
91
107
  ];
92
108
  return {
93
109
  compliant: violations.every((v) => v.severity !== 'hard'),
110
+ coverageComplete: staffing.length === 0,
111
+ publishable: staffing.length === 0 && violations.every((v) => v.severity !== 'hard'),
94
112
  violations,
95
113
  verdicts,
96
114
  ledger,
@@ -136,8 +154,12 @@ exports.explainCandidate = explainCandidate;
136
154
  * single name.
137
155
  */
138
156
  function repairSchedule(input, disruption, published) {
139
- const openings = openingsFor(disruption, published);
140
- const surviving = published.filter((entry) => !isDropped(entry, disruption));
157
+ const ctx = (0, model_1.buildModel)(input);
158
+ const dropped = (entry) => isDropped(entry, disruption, ctx);
159
+ const openings = disruption.kind === 'cancelShift'
160
+ ? []
161
+ : [...new Set(published.filter(dropped).map((entry) => entry.shiftInstanceId))];
162
+ const surviving = published.filter((entry) => !dropped(entry));
141
163
  // Re-solve with the untouched roster pinned. Only the openings are free.
142
164
  const repaired = (0, scheduler_class_1.solveSchedule)({
143
165
  ...applyDisruption(input, disruption),
@@ -197,7 +219,7 @@ function rankCandidates(input, shiftInstanceId, roster, disruption) {
197
219
  const eligible = blockers.length === 0 && (0, construction_1.hardCompliant)(ctx, state, employee.id, shiftInstanceId);
198
220
  // Marginal against what this person already holds: the same shift is
199
221
  // dearer in the hands of someone past their overtime threshold.
200
- const costCents = (0, cost_1.marginalCostCents)(inst, employee, state.minutesByEmployee.get(employee.id) ?? 0, ctx.rules.engagement);
222
+ const costCents = (0, cost_1.marginalCostCents)(inst, employee, state.minutesByEmployee.get(employee.id) ?? 0, (0, support_1.rulesFor)(ctx, employee.id).engagement);
201
223
  const fairnessDebt = meanExtra - (extraLoad.get(employee.id) ?? 0);
202
224
  const preference = (0, availability_1.preferenceScore)(ctx.clock, employee.availability, inst);
203
225
  const originSiteId = originSiteFor(state, employee.id, inst);
@@ -300,22 +322,20 @@ function extraShiftCounts(state) {
300
322
  function average(values) {
301
323
  return values.length === 0 ? 0 : values.reduce((a, b) => a + b, 0) / values.length;
302
324
  }
303
- function openingsFor(disruption, published) {
304
- switch (disruption.kind) {
305
- case 'noShow':
306
- return [disruption.shiftInstanceId];
307
- case 'absence':
308
- return published.filter((e) => e.employeeId === disruption.employeeId).map((e) => e.shiftInstanceId);
309
- case 'cancelShift':
310
- return [];
311
- }
312
- }
313
- function isDropped(entry, disruption) {
325
+ function isDropped(entry, disruption, ctx) {
314
326
  switch (disruption.kind) {
315
327
  case 'noShow':
316
328
  return entry.employeeId === disruption.employeeId && entry.shiftInstanceId === disruption.shiftInstanceId;
317
- case 'absence':
318
- return entry.employeeId === disruption.employeeId;
329
+ case 'absence': {
330
+ if (entry.employeeId !== disruption.employeeId)
331
+ return false;
332
+ const inst = ctx.instanceById.get(entry.shiftInstanceId);
333
+ if (!inst)
334
+ return false;
335
+ const start = ctx.clock.parseDateTime(disruption.from, 'disruption.from');
336
+ const end = ctx.clock.parseDateTime(disruption.to ?? ctx.clock.dateAt(ctx.periodDays - 1), 'disruption.to', true);
337
+ return inst.startMinute < end && start < inst.endMinute;
338
+ }
319
339
  case 'cancelShift':
320
340
  return entry.shiftInstanceId === disruption.shiftInstanceId;
321
341
  }
@@ -19,7 +19,7 @@ import type { ConstraintOptions, ObjectiveWeights, Site, WorkingTimeRules } from
19
19
  * in property order produce the same digest — otherwise a round-trip through
20
20
  * JSON would look like a rule change.
21
21
  */
22
- export declare function hashRules(rules: WorkingTimeRules | undefined, options: ConstraintOptions | undefined, objectives?: ObjectiveWeights, sites?: Site[], travelSpeedKmh?: number): string;
22
+ export declare function hashRules(rules: WorkingTimeRules | undefined, options: ConstraintOptions | undefined, objectives?: ObjectiveWeights, sites?: Site[], travelSpeedKmh?: number, employeeRules?: Map<string, WorkingTimeRules>): string;
23
23
  /** JSON with object keys sorted recursively. */
24
24
  export declare function stableStringify(value: unknown): string;
25
25
  /**
@@ -1 +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,IAAI,EAAE,gBAAgB,EAAE,MAAM,SAAS,CAAC;AAE3F;;;;;;GAMG;AACH,wBAAgB,SAAS,CACrB,KAAK,EAAE,gBAAgB,GAAG,SAAS,EACnC,OAAO,EAAE,iBAAiB,GAAG,SAAS,EACtC,UAAU,CAAC,EAAE,gBAAgB,EAC7B,KAAK,CAAC,EAAE,IAAI,EAAE,EACd,cAAc,CAAC,EAAE,MAAM,GACxB,MAAM,CAgBR;AAaD,gDAAgD;AAChD,wBAAgB,eAAe,CAAC,KAAK,EAAE,OAAO,GAAG,MAAM,CAOtD;AAED;;;;;;GAMG;AACH,wBAAgB,OAAO,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,CAY7C"}
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,IAAI,EAAE,gBAAgB,EAAE,MAAM,SAAS,CAAC;AAE3F;;;;;;GAMG;AACH,wBAAgB,SAAS,CACrB,KAAK,EAAE,gBAAgB,GAAG,SAAS,EACnC,OAAO,EAAE,iBAAiB,GAAG,SAAS,EACtC,UAAU,CAAC,EAAE,gBAAgB,EAC7B,KAAK,CAAC,EAAE,IAAI,EAAE,EACd,cAAc,CAAC,EAAE,MAAM,EACvB,aAAa,CAAC,EAAE,GAAG,CAAC,MAAM,EAAE,gBAAgB,CAAC,GAC9C,MAAM,CA8BR;AAaD,gDAAgD;AAChD,wBAAgB,eAAe,CAAC,KAAK,EAAE,OAAO,GAAG,MAAM,CAOtD;AAED;;;;;;GAMG;AACH,wBAAgB,OAAO,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,CAY7C"}
@@ -21,15 +21,29 @@ exports.fnv1a64 = exports.stableStringify = exports.hashRules = void 0;
21
21
  * in property order produce the same digest — otherwise a round-trip through
22
22
  * JSON would look like a rule change.
23
23
  */
24
- function hashRules(rules, options, objectives, sites, travelSpeedKmh) {
24
+ function hashRules(rules, options, objectives, sites, travelSpeedKmh, employeeRules) {
25
+ // Only the employees whose effective rules actually differ from the global
26
+ // set. `rulesByEmployee` carries an entry for *every* employee, so hashing
27
+ // it whole would make the digest move when a person is added or renamed —
28
+ // and `rulesHash` is a configuration fingerprint, not a roster one.
29
+ const globalDigest = stableStringify(rules ?? {});
30
+ const personalRules = [...(employeeRules ?? [])]
31
+ .filter(([, effective]) => stableStringify(effective) !== globalDigest)
32
+ .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
25
33
  const payload = stableStringify({
26
34
  rules: rules ?? null,
35
+ ...(personalRules.length > 0 ? { employeeRules: personalRules } : {}),
27
36
  // Only the parts of `constraints` that change outcomes: custom rules are
28
37
  // functions and cannot be hashed, so their ids stand in for them.
29
38
  minRestMinutes: options?.minRestMinutes ?? null,
30
39
  oneShiftPerDay: options?.oneShiftPerDay ?? null,
31
40
  overrides: options?.overrides ?? null,
32
- custom: (options?.custom ?? []).map((c) => ({ id: c.id, hardness: c.hardness, weight: c.weight ?? null })),
41
+ custom: (options?.custom ?? []).map((c) => ({
42
+ id: c.id,
43
+ hardness: c.hardness,
44
+ weight: c.weight ?? null,
45
+ ...(c.version === undefined ? {} : { version: c.version }),
46
+ })),
33
47
  objectives: objectives ?? null,
34
48
  // Omit these keys entirely when absent so existing inputs without site data
35
49
  // keep the same rulesHash they had before this feature existed.
@@ -12,7 +12,7 @@
12
12
  * a proof of optimality.
13
13
  */
14
14
  import type { ScheduleInput, ScheduleResult } from './types';
15
- export declare const ENGINE_VERSION = "2";
15
+ 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;
@@ -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;IA+C3C,qFAAqF;IACrF,OAAO,CAAC,QAAQ;CA8EnB;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,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"}
@@ -34,13 +34,13 @@ const verdicts_1 = require("./engine/verdicts");
34
34
  const provenance_1 = require("./provenance");
35
35
  const DEFAULT_TIME_BUDGET_MS = 10000;
36
36
  const DEFAULT_SEED = 42;
37
- exports.ENGINE_VERSION = '2';
37
+ exports.ENGINE_VERSION = '3';
38
38
  class ShiftScheduler {
39
39
  /** Solve a scheduling problem synchronously. Throws `ScheduleValidationError` on malformed input. */
40
40
  solve(input) {
41
41
  const startedAt = Date.now();
42
42
  const objective = input.objective ?? 'standard';
43
- const timeBudgetMs = input.timeBudgetMs ?? DEFAULT_TIME_BUDGET_MS;
43
+ const timeBudgetMs = input.timeBudgetMs ?? (input.maxIterations === undefined ? DEFAULT_TIME_BUDGET_MS : Infinity);
44
44
  const seed = input.seed ?? DEFAULT_SEED;
45
45
  const rand = (0, prng_1.createPrng)(seed);
46
46
  const ctx = (0, model_1.buildModel)(input);
@@ -63,6 +63,7 @@ class ShiftScheduler {
63
63
  objective,
64
64
  minHoursWeight,
65
65
  timeBudgetMs,
66
+ maxIterations: input.maxIterations,
66
67
  rand,
67
68
  onImprovement: input.onProgress
68
69
  ? (best) => input.onProgress(this.assemble(best, propagation, startedAt, seed, input, 0))
@@ -123,8 +124,9 @@ class ShiftScheduler {
123
124
  },
124
125
  provenance: {
125
126
  engineVersion: exports.ENGINE_VERSION,
127
+ ...(input.maxIterations === undefined ? {} : { maxIterations: input.maxIterations }),
126
128
  seed,
127
- rulesHash: (0, provenance_1.hashRules)(input.rules, input.constraints, input.objectives, input.sites, input.travelSpeedKmh),
129
+ rulesHash: (0, provenance_1.hashRules)(input.rules, input.constraints, input.objectives, input.sites, input.travelSpeedKmh, ctx.rulesByEmployee),
128
130
  dutyClassificationNotes: dutyNotes(ctx),
129
131
  // Nothing in this module consumes a behavioural or predictive
130
132
  // per-worker signal, so the claim is structural rather than a
@@ -54,6 +54,8 @@ export declare class PeriodClock {
54
54
  * midnight, not 6.
55
55
  */
56
56
  toPeriodMinutes(date: string, timeOfDay: string, field?: string): number;
57
+ /** Resolve a local date-time or an ISO instant with an explicit UTC offset. */
58
+ parseDateTime(value: string, field?: string, endOfBareDate?: boolean): number;
57
59
  /**
58
60
  * True elapsed minutes from local midnight on the period start to local
59
61
  * midnight on `dayIndex` — 1440 per day except across a DST transition.
@@ -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,EAAE,MAAM,CAAC;IAC1B,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IAEtB,OAAO,CAAC,QAAQ,CAAC,SAAS,CAAsB;IAChD,gFAAgF;IAChF,OAAO,CAAC,QAAQ,CAAC,aAAa,CAA6B;IAC3D,yFAAyF;IACzF,OAAO,CAAC,QAAQ,CAAU;gBAEd,SAAS,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,QAAQ,SAAQ;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;IAMpB,wDAAwD;IACxD,OAAO,CAAC,UAAU;CAMrB;AAED,4EAA4E;AAC5E,wBAAgB,cAAc,CAAC,CAAC,EAAE,WAAW,EAAE,CAAC,EAAE,WAAW,GAAG,MAAM,CAErE;AAED,qDAAqD;AACrD,wBAAgB,QAAQ,CAAC,CAAC,EAAE,WAAW,EAAE,CAAC,EAAE,WAAW,GAAG,OAAO,CAEhE;AAED,8EAA8E;AAC9E,wBAAgB,UAAU,CAAC,CAAC,EAAE,WAAW,EAAE,CAAC,EAAE,WAAW,GAAG,MAAM,CAIjE;AAED,oFAAoF;AACpF,wBAAgB,WAAW,CAAC,IAAI,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,GAAG,MAAM,CAE5D;AAED,oCAAoC;AACpC,wBAAgB,OAAO,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,MAAM,CAE1D;AAED,sCAAsC;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"}
@@ -74,6 +74,29 @@ class PeriodClock {
74
74
  toPeriodMinutes(date, timeOfDay, field = 'time') {
75
75
  return this.periodMinuteAt(this.dayIndexOf(date), parseTimeOfDay(timeOfDay, field));
76
76
  }
77
+ /** Resolve a local date-time or an ISO instant with an explicit UTC offset. */
78
+ parseDateTime(value, field = 'dateTime', endOfBareDate = false) {
79
+ const match = /^(\d{4}-\d{2}-\d{2})(?:T(\d{2}:\d{2}(?::\d{2}(?:\.\d{1,3})?)?)(Z|[+-]\d{2}:\d{2})?)?$/.exec(value);
80
+ if (!match)
81
+ throw new types_1.ScheduleValidationError(`Invalid ISO date-time for ${field}: "${value}"`);
82
+ const [, date, time, offset] = match;
83
+ assertIsoDate(date, field);
84
+ if (!time)
85
+ return this.dayStartMinutes(this.dayIndexOf(date) + (endOfBareDate ? 1 : 0));
86
+ parseTimeOfDay(time.split('.')[0], field);
87
+ if (offset) {
88
+ if (offset !== 'Z') {
89
+ const [hours, minutes] = offset.slice(1).split(':').map(Number);
90
+ if (hours > 23 || minutes > 59)
91
+ throw new types_1.ScheduleValidationError(`Invalid UTC offset for ${field}`);
92
+ }
93
+ const epoch = Date.parse(`${date}T${time}${offset}`);
94
+ if (!Number.isFinite(epoch))
95
+ throw new types_1.ScheduleValidationError(`Invalid ISO instant for ${field}`);
96
+ return this.fromEpochMs(epoch);
97
+ }
98
+ return this.toPeriodMinutes(date, time.split('.')[0], field);
99
+ }
77
100
  /**
78
101
  * True elapsed minutes from local midnight on the period start to local
79
102
  * midnight on `dayIndex` — 1440 per day except across a DST transition.
@@ -260,7 +283,9 @@ function parseTimeOfDay(value, field) {
260
283
  exports.parseTimeOfDay = parseTimeOfDay;
261
284
  /** Throws `ScheduleValidationError` unless `value` is a real `YYYY-MM-DD` date. */
262
285
  function assertIsoDate(value, field) {
263
- if (!ISO_DATE.test(value) || Number.isNaN(Date.parse(`${value}T00:00:00Z`))) {
286
+ if (!ISO_DATE.test(value) ||
287
+ Number.isNaN(Date.parse(`${value}T00:00:00Z`)) ||
288
+ new Date(`${value}T00:00:00Z`).toISOString().slice(0, 10) !== value) {
264
289
  throw new types_1.ScheduleValidationError(`Invalid ISO date for ${field}: "${value}" (expected YYYY-MM-DD)`);
265
290
  }
266
291
  }