assignment-user-matcher 1.15.1 → 1.16.1

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 (85) hide show
  1. package/README.md +372 -8
  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/consecutive.d.ts +10 -0
  24. package/dist/scheduling/constraints/consecutive.d.ts.map +1 -1
  25. package/dist/scheduling/constraints/consecutive.js +64 -1
  26. package/dist/scheduling/constraints/contract.d.ts.map +1 -1
  27. package/dist/scheduling/constraints/contract.js +12 -3
  28. package/dist/scheduling/constraints/cost.d.ts.map +1 -1
  29. package/dist/scheduling/constraints/cost.js +3 -2
  30. package/dist/scheduling/constraints/employee-scope.d.ts +5 -0
  31. package/dist/scheduling/constraints/employee-scope.d.ts.map +1 -0
  32. package/dist/scheduling/constraints/employee-scope.js +157 -0
  33. package/dist/scheduling/constraints/group-composition.js +2 -2
  34. package/dist/scheduling/constraints/min-staffing.d.ts.map +1 -1
  35. package/dist/scheduling/constraints/min-staffing.js +51 -8
  36. package/dist/scheduling/constraints/notice.d.ts.map +1 -1
  37. package/dist/scheduling/constraints/notice.js +8 -5
  38. package/dist/scheduling/constraints/rest-days.d.ts.map +1 -1
  39. package/dist/scheduling/constraints/rest-days.js +6 -6
  40. package/dist/scheduling/constraints/rolling-hours.d.ts.map +1 -1
  41. package/dist/scheduling/constraints/rolling-hours.js +29 -4
  42. package/dist/scheduling/cost.d.ts.map +1 -1
  43. package/dist/scheduling/cost.js +2 -1
  44. package/dist/scheduling/engine/construction.d.ts.map +1 -1
  45. package/dist/scheduling/engine/construction.js +23 -3
  46. package/dist/scheduling/engine/objective.d.ts +4 -4
  47. package/dist/scheduling/engine/objective.d.ts.map +1 -1
  48. package/dist/scheduling/engine/objective.js +32 -7
  49. package/dist/scheduling/engine/propagation.js +2 -1
  50. package/dist/scheduling/engine/search.d.ts +1 -0
  51. package/dist/scheduling/engine/search.d.ts.map +1 -1
  52. package/dist/scheduling/engine/search.js +1 -1
  53. package/dist/scheduling/engine/state.d.ts.map +1 -1
  54. package/dist/scheduling/engine/state.js +4 -0
  55. package/dist/scheduling/engine/timeline.d.ts +14 -0
  56. package/dist/scheduling/engine/timeline.d.ts.map +1 -1
  57. package/dist/scheduling/engine/timeline.js +33 -0
  58. package/dist/scheduling/index.d.ts +1 -1
  59. package/dist/scheduling/index.d.ts.map +1 -1
  60. package/dist/scheduling/model.d.ts +7 -2
  61. package/dist/scheduling/model.d.ts.map +1 -1
  62. package/dist/scheduling/model.js +254 -42
  63. package/dist/scheduling/operations.d.ts +4 -0
  64. package/dist/scheduling/operations.d.ts.map +1 -1
  65. package/dist/scheduling/operations.js +81 -22
  66. package/dist/scheduling/provenance.d.ts +1 -1
  67. package/dist/scheduling/provenance.d.ts.map +1 -1
  68. package/dist/scheduling/provenance.js +16 -2
  69. package/dist/scheduling/scheduler.class.d.ts +1 -1
  70. package/dist/scheduling/scheduler.class.d.ts.map +1 -1
  71. package/dist/scheduling/scheduler.class.js +5 -3
  72. package/dist/scheduling/sites.d.ts +1 -1
  73. package/dist/scheduling/sites.d.ts.map +1 -1
  74. package/dist/scheduling/sites.js +34 -1
  75. package/dist/scheduling/time.d.ts +2 -0
  76. package/dist/scheduling/time.d.ts.map +1 -1
  77. package/dist/scheduling/time.js +26 -1
  78. package/dist/scheduling/types.d.ts +152 -9
  79. package/dist/scheduling/types.d.ts.map +1 -1
  80. package/dist/types/matcher.d.ts +309 -4
  81. package/dist/types/matcher.d.ts.map +1 -1
  82. package/dist/utils/keys.d.ts +12 -2
  83. package/dist/utils/keys.d.ts.map +1 -1
  84. package/dist/utils/keys.js +35 -2
  85. package/package.json +12 -2
@@ -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);
@@ -240,7 +262,30 @@ function rankCandidates(input, shiftInstanceId, roster, disruption) {
240
262
  rationale: rationaleFor(eligible, blockers, costCents, fairnessDebt, preference, travelMinutes, distanceKm, originSiteId, isHomeSite, contractDeltaMinutes),
241
263
  });
242
264
  }
243
- return candidates.sort((a, b) => a.rank - b.rank || (a.employeeId < b.employeeId ? -1 : 1));
265
+ /*
266
+ * Rank, then seniority, then id.
267
+ *
268
+ * `Employee.seniority` was declared from the start and read nowhere, so the
269
+ * field asserted a capability the engine did not have. Collective
270
+ * agreements very commonly order offers by it, and the honest place for
271
+ * that is a **tiebreak**: it decides between candidates who are otherwise
272
+ * indistinguishable, and never outranks cost, travel or contract debt. An
273
+ * agreement that says "offer by seniority" means exactly that — not that a
274
+ * senior person should be called out across the city ahead of somebody on
275
+ * site.
276
+ *
277
+ * It stays inside the profiling-free boundary. Seniority is a declared
278
+ * contractual fact of the same class as a qualification or a contracted
279
+ * week — not reliability, not acceptance history, not anything learned —
280
+ * which is what `provenance.profilingFree` asserts and what keeps this
281
+ * module outside AI Act Annex III point 4(b).
282
+ *
283
+ * The id remains the final tiebreak so the order is total and reproducible
284
+ * for the many teams that record no seniority at all.
285
+ */
286
+ return candidates.sort((a, b) => a.rank - b.rank ||
287
+ (ctx.employeeById.get(b.employeeId)?.seniority ?? 0) - (ctx.employeeById.get(a.employeeId)?.seniority ?? 0) ||
288
+ (a.employeeId < b.employeeId ? -1 : 1));
244
289
  }
245
290
  exports.rankCandidates = rankCandidates;
246
291
  function rationaleFor(eligible, blockers, costCents, fairnessDebt, preference, travelMinutes, distanceKm, originSiteId, isHomeSite, contractDeltaMinutes) {
@@ -300,22 +345,20 @@ function extraShiftCounts(state) {
300
345
  function average(values) {
301
346
  return values.length === 0 ? 0 : values.reduce((a, b) => a + b, 0) / values.length;
302
347
  }
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) {
348
+ function isDropped(entry, disruption, ctx) {
314
349
  switch (disruption.kind) {
315
350
  case 'noShow':
316
351
  return entry.employeeId === disruption.employeeId && entry.shiftInstanceId === disruption.shiftInstanceId;
317
- case 'absence':
318
- return entry.employeeId === disruption.employeeId;
352
+ case 'absence': {
353
+ if (entry.employeeId !== disruption.employeeId)
354
+ return false;
355
+ const inst = ctx.instanceById.get(entry.shiftInstanceId);
356
+ if (!inst)
357
+ return false;
358
+ const start = ctx.clock.parseDateTime(disruption.from, 'disruption.from');
359
+ const end = ctx.clock.parseDateTime(disruption.to ?? ctx.clock.dateAt(ctx.periodDays - 1), 'disruption.to', true);
360
+ return inst.startMinute < end && start < inst.endMinute;
361
+ }
319
362
  case 'cancelShift':
320
363
  return entry.shiftInstanceId === disruption.shiftInstanceId;
321
364
  }
@@ -430,8 +473,12 @@ function diagnoseInfeasibility(input) {
430
473
  message: `the roster needs ${(demandMinutes / 60).toFixed(1)}h of work but the team's hour budgets total ${(capacityMinutes / 60).toFixed(1)}h`,
431
474
  });
432
475
  }
433
- for (const [tag, needed] of tagDemand(ctx).entries()) {
434
- const supply = ctx.employees.filter((e) => ctx.employeeTags.get(e.id)?.has(tag)).length;
476
+ for (const [tag, { needed, dates }] of tagDemand(ctx).entries()) {
477
+ // Holding the tag on *some* day the tag is wanted is what makes a person
478
+ // supply for it. Counting plain tags alone would call a lapsed
479
+ // certificate supply; counting only the first date would call a nurse
480
+ // who joins mid-period nobody.
481
+ const supply = ctx.employees.filter((e) => dates.some((date) => ctx.holdsTagOn(e.id, tag, date))).length;
435
482
  if (supply === 0 && needed > 0) {
436
483
  findings.push({
437
484
  kind: 'tagCapacity',
@@ -444,14 +491,26 @@ function diagnoseInfeasibility(input) {
444
491
  return { feasible: findings.length === 0, findings };
445
492
  }
446
493
  exports.diagnoseInfeasibility = diagnoseInfeasibility;
494
+ /** Per tag: how many assignments want it, and on which dates they want it. */
447
495
  function tagDemand(ctx) {
448
496
  const demand = new Map();
497
+ const add = (tag, count, date) => {
498
+ const entry = demand.get(tag) ?? { needed: 0, dates: [] };
499
+ entry.needed += count;
500
+ if (!entry.dates.includes(date))
501
+ entry.dates.push(date);
502
+ demand.set(tag, entry);
503
+ };
449
504
  for (const inst of ctx.instances) {
450
- for (const [tag, count] of Object.entries(inst.tagRequirements)) {
451
- demand.set(tag, (demand.get(tag) ?? 0) + count);
505
+ for (const [tag, requirement] of Object.entries(inst.tagRequirements))
506
+ add(tag, requirement.min, inst.date);
507
+ // A proportion of the minimum team, rounded up — the fewest people this
508
+ // occurrence could possibly need holding the tag.
509
+ for (const [tag, ratio] of Object.entries(inst.tagRatios)) {
510
+ add(tag, Math.ceil(ratio * inst.minEmployees), inst.date);
452
511
  }
453
512
  for (const tag of inst.requiredTags)
454
- demand.set(tag, (demand.get(tag) ?? 0) + inst.minEmployees);
513
+ add(tag, inst.minEmployees, inst.date);
455
514
  }
456
515
  return demand;
457
516
  }
@@ -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
@@ -16,7 +16,7 @@ import type { Site, SiteIndex } from './types';
16
16
  * referenced by templates or employees but not declared here are tolerated;
17
17
  * they simply have no coordinates or matrix entries.
18
18
  */
19
- export declare function buildSiteIndex(sites: Site[] | undefined, travelSpeedKmh?: number): SiteIndex;
19
+ export declare function buildSiteIndex(sites: Site[] | undefined, travelSpeedKmh?: number, periodTimeZone?: string): SiteIndex;
20
20
  /**
21
21
  * Travel time between two sites, in minutes.
22
22
  *
@@ -1 +1 @@
1
- {"version":3,"file":"sites.d.ts","sourceRoot":"","sources":["../../src/scheduling/sites.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,OAAO,KAAK,EAAE,IAAI,EAAE,SAAS,EAAE,MAAM,SAAS,CAAC;AAI/C;;;;;;;GAOG;AACH,wBAAgB,cAAc,CAAC,KAAK,EAAE,IAAI,EAAE,GAAG,SAAS,EAAE,cAAc,CAAC,EAAE,MAAM,GAAG,SAAS,CA2C5F;AAsBD;;;;;GAKG;AACH,wBAAgB,oBAAoB,CAAC,KAAK,EAAE,SAAS,EAAE,IAAI,CAAC,EAAE,MAAM,EAAE,EAAE,CAAC,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAIrG;AAED;;;;;;GAMG;AACH,wBAAgB,iBAAiB,CAAC,KAAK,EAAE,SAAS,EAAE,IAAI,CAAC,EAAE,MAAM,EAAE,EAAE,CAAC,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAalG"}
1
+ {"version":3,"file":"sites.d.ts","sourceRoot":"","sources":["../../src/scheduling/sites.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,OAAO,KAAK,EAAE,IAAI,EAAE,SAAS,EAAE,MAAM,SAAS,CAAC;AAmC/C;;;;;;;GAOG;AACH,wBAAgB,cAAc,CAAC,KAAK,EAAE,IAAI,EAAE,GAAG,SAAS,EAAE,cAAc,CAAC,EAAE,MAAM,EAAE,cAAc,CAAC,EAAE,MAAM,GAAG,SAAS,CAiDrH;AAsBD;;;;;GAKG;AACH,wBAAgB,oBAAoB,CAAC,KAAK,EAAE,SAAS,EAAE,IAAI,CAAC,EAAE,MAAM,EAAE,EAAE,CAAC,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAIrG;AAED;;;;;;GAMG;AACH,wBAAgB,iBAAiB,CAAC,KAAK,EAAE,SAAS,EAAE,IAAI,CAAC,EAAE,MAAM,EAAE,EAAE,CAAC,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAalG"}
@@ -11,7 +11,35 @@
11
11
  Object.defineProperty(exports, "__esModule", { value: true });
12
12
  exports.distanceKmBetween = exports.travelMinutesBetween = exports.buildSiteIndex = void 0;
13
13
  const types_1 = require("./types");
14
+ const time_1 = require("./time");
14
15
  const geo_1 = require("../utils/geo");
16
+ /**
17
+ * A site's zone must match the roster's, because there is only one clock.
18
+ *
19
+ * Instances are placed in absolute period minutes, so rest gaps and overlaps
20
+ * survive a zone difference — but the night band, break windows, weekday and
21
+ * holiday attribution are all resolved once, at expansion, against the period's
22
+ * `PeriodClock`. A Stockholm site inside a Tallinn roster would have its 22:00
23
+ * night boundary computed an hour out, and nothing downstream could tell.
24
+ *
25
+ * Refusing is the honest answer: an hour of silent drift in a compliance
26
+ * verdict is worse than an error that says to split the roster.
27
+ */
28
+ function assertSiteZone(siteId, siteZone, periodTimeZone) {
29
+ try {
30
+ new Intl.DateTimeFormat('en-US', { timeZone: siteZone });
31
+ }
32
+ catch {
33
+ throw new types_1.ScheduleValidationError(`Site "${siteId}" has an unknown time zone: "${siteZone}"`);
34
+ }
35
+ const rosterZone = periodTimeZone ?? 'UTC';
36
+ if (siteZone !== rosterZone) {
37
+ throw new types_1.ScheduleValidationError(`Site "${siteId}" is in "${siteZone}" but the roster's period is in "${rosterZone}". ` +
38
+ `One roster resolves wall-clock times against one zone, so a roster spanning zones would ` +
39
+ `place this site's night band, breaks and day boundaries an hour out without reporting it. ` +
40
+ `Solve one roster per zone.`);
41
+ }
42
+ }
15
43
  /**
16
44
  * Build a validated site index from caller input.
17
45
  *
@@ -20,7 +48,7 @@ const geo_1 = require("../utils/geo");
20
48
  * referenced by templates or employees but not declared here are tolerated;
21
49
  * they simply have no coordinates or matrix entries.
22
50
  */
23
- function buildSiteIndex(sites, travelSpeedKmh) {
51
+ function buildSiteIndex(sites, travelSpeedKmh, periodTimeZone) {
24
52
  if (travelSpeedKmh !== undefined && (!Number.isFinite(travelSpeedKmh) || travelSpeedKmh <= 0)) {
25
53
  throw new types_1.ScheduleValidationError(`travelSpeedKmh must be a positive finite number: ${travelSpeedKmh}`);
26
54
  }
@@ -30,6 +58,11 @@ function buildSiteIndex(sites, travelSpeedKmh) {
30
58
  throw new types_1.ScheduleValidationError('Site is missing `id`');
31
59
  if (byId.has(site.id))
32
60
  throw new types_1.ScheduleValidationError(`Duplicate site id "${site.id}"`);
61
+ for (const date of site.publicHolidays ?? []) {
62
+ (0, time_1.assertIsoDate)(date, `Site "${site.id}".publicHolidays`);
63
+ }
64
+ if (site.timeZone !== undefined)
65
+ assertSiteZone(site.id, site.timeZone, periodTimeZone);
33
66
  if (site.lat !== undefined || site.lng !== undefined) {
34
67
  if (!(0, geo_1.hasValidCoordinates)(site.lat, site.lng)) {
35
68
  throw new types_1.ScheduleValidationError(`Site "${site.id}" has invalid coordinates: lat=${site.lat}, lng=${site.lng}`);
@@ -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,O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AAK,EAAE,WAAW,EAAE,KAAK,EAAE,UAAU,GAAG,WAAW,EAAE;IA2BzE;;;;;;;OAOG;IACH,gBAAgB,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM;IAOxC,uEAAuE;IACvE,OAAO,CAAC,aAAa;IAQrB;;;;;;;;;OASG;IACH,OAAO,CAAC,YAAY;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
  }