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
@@ -0,0 +1,157 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.scopeEmployeeConstraints = void 0;
4
+ const constraint_1 = require("./constraint");
5
+ const provenance_1 = require("../provenance");
6
+ /** Rule families are instantiated once per effective configuration, then dispatched by employee. */
7
+ function scopeEmployeeConstraints(options, rulesByEmployee) {
8
+ const base = (0, constraint_1.createDefaultConstraints)(options);
9
+ if ([...rulesByEmployee.values()].every((rules) => (0, provenance_1.stableStringify)(rules) === (0, provenance_1.stableStringify)(options.rules ?? {}))) {
10
+ return base;
11
+ }
12
+ const families = new Set([
13
+ 'min-rest',
14
+ 'daily-rest',
15
+ 'weekly-rest',
16
+ 'rolling-hours',
17
+ 'overtime',
18
+ 'duty-quota',
19
+ 'night-work',
20
+ 'consecutive-days',
21
+ 'consecutive-nights',
22
+ 'shift-succession',
23
+ 'start-interval',
24
+ 'in-shift-breaks',
25
+ 'rest-days',
26
+ 'engagement-floor',
27
+ 'notice',
28
+ 'fairness',
29
+ ]);
30
+ const groups = new Map();
31
+ for (const [id, rules] of rulesByEmployee) {
32
+ const key = (0, provenance_1.stableStringify)(rules);
33
+ let group = groups.get(key);
34
+ if (!group) {
35
+ group = {
36
+ rules,
37
+ ids: new Set(),
38
+ constraints: new Map((0, constraint_1.createDefaultConstraints)({ ...options, rules }).map((c) => [c.id, c])),
39
+ };
40
+ groups.set(key, group);
41
+ }
42
+ group.ids.add(id);
43
+ }
44
+ const registry = new Map(base.map((c) => [c.id, c]));
45
+ for (const group of groups.values()) {
46
+ for (const [id, c] of group.constraints)
47
+ if (families.has(id))
48
+ registry.set(id, c);
49
+ }
50
+ const contexts = new WeakMap();
51
+ for (const [id, prototype] of registry) {
52
+ if (!families.has(id))
53
+ continue;
54
+ const byEmployee = new Map();
55
+ const delegates = [];
56
+ // Unrelated personal overrides must not split a team-wide fairness group.
57
+ const scopedGroups = id === 'fairness' ? new Map() : groups;
58
+ if (id === 'fairness') {
59
+ for (const group of groups.values()) {
60
+ const key = (0, provenance_1.stableStringify)(group.rules.fairness);
61
+ const existing = scopedGroups.get(key);
62
+ if (existing)
63
+ for (const employeeId of group.ids)
64
+ existing.ids.add(employeeId);
65
+ else
66
+ scopedGroups.set(key, { ...group, ids: new Set(group.ids) });
67
+ }
68
+ }
69
+ for (const group of scopedGroups.values()) {
70
+ const constraint = group.constraints.get(id);
71
+ if (!constraint)
72
+ continue;
73
+ const cache = contexts.get(group) ?? new WeakMap();
74
+ contexts.set(group, cache);
75
+ const context = (ctx) => {
76
+ let scoped = cache.get(ctx);
77
+ if (scoped)
78
+ return scoped;
79
+ const night = group.rules.nightWork;
80
+ const instances = (0, provenance_1.stableStringify)(night) === (0, provenance_1.stableStringify)(ctx.rules.nightWork)
81
+ ? ctx.instances
82
+ : ctx.instances.map((inst) => {
83
+ const nightMinutes = night
84
+ ? ctx.clock.minutesInClockRange({ start: inst.startMinute, end: inst.endMinute }, night.window)
85
+ : 0;
86
+ return {
87
+ ...inst,
88
+ nightMinutes,
89
+ isNightShift: nightMinutes >= (night?.qualifiesAfterMinutes ?? 180),
90
+ };
91
+ });
92
+ scoped = {
93
+ ...ctx,
94
+ rules: group.rules,
95
+ employees: ctx.employees.filter((e) => group.ids.has(e.id)),
96
+ instances,
97
+ instanceById: new Map(instances.map((inst) => [inst.id, inst])),
98
+ };
99
+ cache.set(ctx, scoped);
100
+ return scoped;
101
+ };
102
+ const view = (state, aggregate = false) => ({
103
+ ...state,
104
+ ctx: context(state.ctx),
105
+ ...(aggregate
106
+ ? {
107
+ assignments: new Map([...state.assignments].map(([key, ids]) => [
108
+ key,
109
+ new Set([...ids].filter((employeeId) => group.ids.has(employeeId))),
110
+ ])),
111
+ }
112
+ : {}),
113
+ });
114
+ delegates.push({ constraint, view });
115
+ for (const employeeId of group.ids)
116
+ byEmployee.set(employeeId, { constraint, context });
117
+ }
118
+ const delegate = (state, pair) => {
119
+ const found = byEmployee.get(pair.employeeId);
120
+ return found && { c: found.constraint, state: { ...state, ctx: found.context(state.ctx) } };
121
+ };
122
+ registry.set(id, {
123
+ ...prototype,
124
+ delta(state, pair) {
125
+ const d = delegate(state, pair);
126
+ return d ? d.c.delta(d.state, pair) : 0;
127
+ },
128
+ explain(state, pair) {
129
+ const d = delegate(state, pair);
130
+ return d ? d.c.explain(d.state, pair) : null;
131
+ },
132
+ verdict(state, pair) {
133
+ const d = delegate(state, pair);
134
+ if (!d)
135
+ return {
136
+ ruleId: id,
137
+ pass: true,
138
+ severity: this.hardness,
139
+ message: `no ${id} rule applies to this employee`,
140
+ };
141
+ return d.c.verdict
142
+ ? d.c.verdict(d.state, pair)
143
+ : {
144
+ ruleId: id,
145
+ pass: d.c.delta(d.state, pair) === 0,
146
+ severity: this.hardness,
147
+ message: d.c.explain(d.state, pair) ?? `satisfies ${id}`,
148
+ };
149
+ },
150
+ evaluate: delegates.some((d) => d.constraint.evaluate)
151
+ ? (state) => delegates.flatMap((d) => d.constraint.evaluate?.(d.view(state, true)) ?? [])
152
+ : undefined,
153
+ });
154
+ }
155
+ return [...registry.values()];
156
+ }
157
+ exports.scopeEmployeeConstraints = scopeEmployeeConstraints;
@@ -33,7 +33,7 @@ function groupComposition() {
33
33
  return (0, support_1.fail)('group-composition', 'hard', `"${inst.id}" already has its maximum of ${inst.maxEmployees} assignees`, { actual: wouldBe, required: inst.maxEmployees, unit: 'count' });
34
34
  }
35
35
  for (const [tag, max] of Object.entries(inst.tagMaximums)) {
36
- if (!state.ctx.employeeTags.get(pair.employeeId)?.has(tag))
36
+ if (!state.ctx.holdsTagOn(pair.employeeId, tag, inst.date))
37
37
  continue;
38
38
  const current = countTag(state, inst, tag, pair.employeeId);
39
39
  if (current + 1 > max) {
@@ -85,7 +85,7 @@ function countTag(state, inst, tag, exclude) {
85
85
  for (const employeeId of state.assignments.get(inst.id) ?? []) {
86
86
  if (employeeId === exclude)
87
87
  continue;
88
- if (state.ctx.employeeTags.get(employeeId)?.has(tag))
88
+ if (state.ctx.holdsTagOn(employeeId, tag, inst.date))
89
89
  count++;
90
90
  }
91
91
  return count;
@@ -1 +1 @@
1
- {"version":3,"file":"min-staffing.d.ts","sourceRoot":"","sources":["../../../src/scheduling/constraints/min-staffing.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,OAAO,KAAK,EAAE,mBAAmB,EAAE,YAAY,EAAE,oBAAoB,EAAE,WAAW,EAAE,QAAQ,EAAE,MAAM,UAAU,CAAC;AAE/G,wBAAgB,WAAW,IAAI,oBAAoB,CAOlD;AAED,+FAA+F;AAC/F,wBAAgB,kBAAkB,CAAC,GAAG,EAAE,YAAY,EAAE,KAAK,EAAE,WAAW,EAAE,QAAQ,EAAE,QAAQ,GAAG,mBAAmB,EAAE,CAkCnH"}
1
+ {"version":3,"file":"min-staffing.d.ts","sourceRoot":"","sources":["../../../src/scheduling/constraints/min-staffing.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,OAAO,KAAK,EAAE,mBAAmB,EAAE,YAAY,EAAE,oBAAoB,EAAE,WAAW,EAAE,QAAQ,EAAE,MAAM,UAAU,CAAC;AA2B/G,wBAAgB,WAAW,IAAI,oBAAoB,CAOlD;AAED,+FAA+F;AAC/F,wBAAgB,kBAAkB,CAAC,GAAG,EAAE,YAAY,EAAE,KAAK,EAAE,WAAW,EAAE,QAAQ,EAAE,QAAQ,GAAG,mBAAmB,EAAE,CA4DnH"}
@@ -10,6 +10,25 @@
10
10
  */
11
11
  Object.defineProperty(exports, "__esModule", { value: true });
12
12
  exports.staffingViolations = exports.minStaffing = void 0;
13
+ /**
14
+ * How many of the assigned team hold a tag on the shift's date, at or above an
15
+ * optional grade floor.
16
+ *
17
+ * One helper for both the count and the ratio, so a graded minimum and a
18
+ * proportion can never disagree about who counts — and both read the date, so a
19
+ * lapsed certificate satisfies neither.
20
+ */
21
+ function countTag(ctx, assigned, tag, date, minLevel) {
22
+ if (!assigned)
23
+ return 0;
24
+ let have = 0;
25
+ for (const employeeId of assigned) {
26
+ if (minLevel === undefined ? ctx.holdsTagOn(employeeId, tag, date) : ctx.holdsTagAt(employeeId, tag, date, minLevel)) {
27
+ have++;
28
+ }
29
+ }
30
+ return have;
31
+ }
13
32
  function minStaffing() {
14
33
  return {
15
34
  id: 'min-staffing',
@@ -36,20 +55,44 @@ function staffingViolations(ctx, state, severity) {
36
55
  unit: 'count',
37
56
  });
38
57
  }
39
- for (const [tag, needed] of Object.entries(inst.tagRequirements)) {
40
- let have = 0;
41
- if (assigned) {
42
- for (const employeeId of assigned) {
43
- if (ctx.employeeTags.get(employeeId)?.has(tag))
44
- have++;
45
- }
58
+ for (const [tag, requirement] of Object.entries(inst.tagRequirements)) {
59
+ const have = countTag(ctx, assigned, tag, inst.date, requirement.level);
60
+ if (have < requirement.min) {
61
+ const graded = requirement.level === undefined ? '' : ` at level ${requirement.level}`;
62
+ out.push({
63
+ constraintId: 'min-staffing',
64
+ severity,
65
+ shiftInstanceId: inst.id,
66
+ message: `shift "${inst.id}" needs ${requirement.min} employees with tag "${tag}"${graded}, has ${have}`,
67
+ actual: have,
68
+ required: requirement.min,
69
+ unit: 'count',
70
+ });
46
71
  }
72
+ }
73
+ /*
74
+ * Proportions, which a headcount cannot express.
75
+ *
76
+ * A floor rounded up: 60% of four people is 2.4, and nobody staffs 2.4.
77
+ * An empty shift is silent — a proportion of nobody is undefined, and
78
+ * reporting it as a breach would bury the real finding, which is the
79
+ * unstaffed shift already reported above.
80
+ */
81
+ for (const [tag, ratio] of Object.entries(inst.tagRatios)) {
82
+ if (count === 0)
83
+ continue;
84
+ const needed = Math.ceil(ratio * count);
85
+ const have = countTag(ctx, assigned, tag, inst.date);
47
86
  if (have < needed) {
48
87
  out.push({
49
88
  constraintId: 'min-staffing',
50
89
  severity,
51
90
  shiftInstanceId: inst.id,
52
- message: `shift "${inst.id}" needs ${needed} employees with tag "${tag}", has ${have}`,
91
+ message: `shift "${inst.id}" needs ${Math.round(ratio * 100)}% of its team tagged "${tag}" ` +
92
+ `(${needed} of ${count}), has ${have} of ${count}`,
93
+ actual: have,
94
+ required: needed,
95
+ unit: 'count',
53
96
  });
54
97
  }
55
98
  }
@@ -1 +1 @@
1
- {"version":3,"file":"notice.d.ts","sourceRoot":"","sources":["../../../src/scheduling/constraints/notice.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;GAmBG;AAEH,OAAO,KAAK,EAER,UAAU,EAEV,oBAAoB,EACpB,WAAW,EAEd,MAAM,UAAU,CAAC;AAGlB,eAAO,MAAM,eAAe,oCAAoC,CAAC;AAEjE,wBAAgB,UAAU,CAAC,IAAI,EAAE,UAAU,GAAG,oBAAoB,CAoEjE;AAwBD;;;;;;;;;;;;GAYG;AACH,wBAAgB,kBAAkB,CAAC,KAAK,EAAE,WAAW,EAAE,IAAI,EAAE,UAAU,GAAG,SAAS;;;;;;IAwBlF"}
1
+ {"version":3,"file":"notice.d.ts","sourceRoot":"","sources":["../../../src/scheduling/constraints/notice.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;GAmBG;AAEH,OAAO,KAAK,EAER,UAAU,EAEV,oBAAoB,EACpB,WAAW,EAEd,MAAM,UAAU,CAAC;AAGlB,eAAO,MAAM,eAAe,oCAAoC,CAAC;AAEjE,wBAAgB,UAAU,CAAC,IAAI,EAAE,UAAU,GAAG,oBAAoB,CAoEjE;AAwBD;;;;;;;;;;;;GAYG;AACH,wBAAgB,kBAAkB,CAAC,KAAK,EAAE,WAAW,EAAE,IAAI,EAAE,UAAU,GAAG,SAAS;;;;;;IA2BlF"}
@@ -113,24 +113,27 @@ function noticeShortfall(state, inst, rule) {
113
113
  * that matters.
114
114
  */
115
115
  function cancellationLedger(state, rule) {
116
- if (!rule?.cancellationCompensationMinutes)
117
- return [];
118
116
  const out = [];
119
117
  for (const key of state.ctx.publishedPairs) {
120
118
  const [employeeId, instanceId] = key.split('|');
119
+ const applied = Object.prototype.hasOwnProperty.call(state.ctx.employeeById.get(employeeId)?.rules ?? {}, 'notice')
120
+ ? (0, support_1.rulesFor)(state.ctx, employeeId).notice
121
+ : ((0, support_1.rulesFor)(state.ctx, employeeId).notice ?? rule);
122
+ if (!applied?.cancellationCompensationMinutes)
123
+ continue;
121
124
  if (state.assignments.get(instanceId)?.has(employeeId))
122
125
  continue;
123
126
  const inst = state.ctx.instanceById.get(instanceId);
124
- if (rule.cancellationDeadlineMinutes !== undefined &&
127
+ if (applied.cancellationDeadlineMinutes !== undefined &&
125
128
  state.ctx.asOfMinute !== undefined &&
126
129
  inst !== undefined &&
127
- inst.startMinute - state.ctx.asOfMinute >= rule.cancellationDeadlineMinutes) {
130
+ inst.startMinute - state.ctx.asOfMinute >= applied.cancellationDeadlineMinutes) {
128
131
  continue; // cancelled with the deadline still ahead — no liability
129
132
  }
130
133
  out.push({
131
134
  kind: 'lateCancellationPay',
132
135
  employeeId,
133
- minutes: Math.max(rule.cancellationCompensationMinutes, inst?.workingMinutes ?? 0),
136
+ minutes: Math.max(applied.cancellationCompensationMinutes, inst?.workingMinutes ?? 0),
134
137
  reason: `published assignment "${instanceId}" was cancelled`,
135
138
  citation: exports.NOTICE_CITATION,
136
139
  });
@@ -1 +1 @@
1
- {"version":3,"file":"rest-days.d.ts","sourceRoot":"","sources":["../../../src/scheduling/constraints/rest-days.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AAEH,OAAO,KAAK,EAER,WAAW,EACX,WAAW,EAEX,oBAAoB,EACpB,WAAW,EACd,MAAM,UAAU,CAAC;AAIlB,eAAO,MAAM,eAAe,qCAAqC,CAAC;AAElE,wBAAgB,QAAQ,CAAC,IAAI,EAAE,WAAW,GAAG,oBAAoB,CAgEhE;AAwBD;;;;;;GAMG;AACH,wBAAgB,sBAAsB,CAAC,KAAK,EAAE,WAAW,EAAE,IAAI,EAAE,WAAW,GAAG,SAAS,GAAG,WAAW,EAAE,CAuBvG"}
1
+ {"version":3,"file":"rest-days.d.ts","sourceRoot":"","sources":["../../../src/scheduling/constraints/rest-days.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AAEH,OAAO,KAAK,EAER,WAAW,EACX,WAAW,EAEX,oBAAoB,EACpB,WAAW,EACd,MAAM,UAAU,CAAC;AAIlB,eAAO,MAAM,eAAe,qCAAqC,CAAC;AAElE,wBAAgB,QAAQ,CAAC,IAAI,EAAE,WAAW,GAAG,oBAAoB,CAgEhE;AAwBD;;;;;;GAMG;AACH,wBAAgB,sBAAsB,CAAC,KAAK,EAAE,WAAW,EAAE,IAAI,EAAE,WAAW,GAAG,SAAS,GAAG,WAAW,EAAE,CAwBvG"}
@@ -107,18 +107,18 @@ function sundaysInPeriod(state) {
107
107
  * honest output is a dated debt the operator can act on.
108
108
  */
109
109
  function compensatoryRestLedger(state, rule) {
110
- const within = rule?.compensatoryRestWithinDays;
111
- if (!within)
112
- return [];
113
110
  const out = [];
114
111
  for (const [instanceId, employees] of state.assignments) {
115
112
  const inst = state.ctx.instanceById.get(instanceId);
116
113
  if (!inst || employees.size === 0)
117
114
  continue;
118
- const deadlineDays = inst.isPublicHoliday ? within.holiday : inst.isSunday ? within.sunday : undefined;
119
- if (deadlineDays === undefined)
120
- continue;
121
115
  for (const employeeId of employees) {
116
+ const within = (Object.prototype.hasOwnProperty.call(state.ctx.employeeById.get(employeeId)?.rules ?? {}, 'restDays')
117
+ ? (0, support_1.rulesFor)(state.ctx, employeeId).restDays
118
+ : ((0, support_1.rulesFor)(state.ctx, employeeId).restDays ?? rule))?.compensatoryRestWithinDays;
119
+ const deadlineDays = inst.isPublicHoliday ? within?.holiday : inst.isSunday ? within?.sunday : undefined;
120
+ if (deadlineDays === undefined)
121
+ continue;
122
122
  out.push({
123
123
  kind: 'substituteRestDay',
124
124
  employeeId,
@@ -1 +1 @@
1
- {"version":3,"file":"rolling-hours.d.ts","sourceRoot":"","sources":["../../../src/scheduling/constraints/rolling-hours.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;GAmBG;AAEH,OAAO,KAAK,EAAe,oBAAoB,EAAe,iBAAiB,EAAE,MAAM,UAAU,CAAC;AAIlG,eAAO,MAAM,qBAAqB,6CAA6C,CAAC;AAEhF,wBAAgB,YAAY,CAAC,MAAM,EAAE,iBAAiB,GAAG,oBAAoB,CAuE5E"}
1
+ {"version":3,"file":"rolling-hours.d.ts","sourceRoot":"","sources":["../../../src/scheduling/constraints/rolling-hours.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;GAmBG;AAEH,OAAO,KAAK,EAAe,oBAAoB,EAAe,iBAAiB,EAAE,MAAM,UAAU,CAAC;AAIlG,eAAO,MAAM,qBAAqB,6CAA6C,CAAC;AAEhF,wBAAgB,YAAY,CAAC,MAAM,EAAE,iBAAiB,GAAG,oBAAoB,CAoF5E"}
@@ -57,9 +57,13 @@ function rollingHours(limits) {
57
57
  return over('week', weekTotal, limits.maxPerWeekAbsoluteMinutes, pair.employeeId, inst.id);
58
58
  }
59
59
  }
60
+ // Which average the opening balance belongs to. Computed once
61
+ // per verdict rather than per average, and ties are harmless:
62
+ // two averages over the same window are the same window.
63
+ const longestWindowDays = Math.max(0, ...(limits.rollingAverages ?? []).map((a) => a.windowDays));
60
64
  for (const average of limits.rollingAverages ?? []) {
61
65
  const span = average.windowDays * support_1.MINUTES_PER_DAY;
62
- const breach = worstAverageBreach(state, t, pair.employeeId, average.maxMinutes, span, range, limits);
66
+ const breach = worstAverageBreach(state, t, pair.employeeId, average.maxMinutes, span, range, limits, average.windowDays === longestWindowDays);
63
67
  if (breach !== null) {
64
68
  const label = average.label ?? `${(0, support_1.h)(average.maxMinutes)}/${average.windowDays}d`;
65
69
  return (0, support_1.fail)('rolling-hours', 'hard', `employee "${pair.employeeId}" would work ${(0, support_1.h)(breach.worked)} in some ${average.windowDays}-day window, over the ${label} limit of ${(0, support_1.h)(breach.allowance)}`, {
@@ -114,14 +118,35 @@ function dayAverageHolds(timeline, limits, range) {
114
118
  * start, with breakpoints at entry and absence boundaries, so the extreme lies
115
119
  * on a window whose edge touches one of those boundaries (or the probe bounds).
116
120
  */
117
- function worstAverageBreach(state, timeline, employeeId, maxMinutes, span, range, limits) {
121
+ function worstAverageBreach(state, timeline, employeeId, maxMinutes, span, range, limits, appliesTo) {
118
122
  const bounds = windowFor(range, span);
119
123
  const kinds = limits.neutraliseAbsenceKinds;
120
124
  const neutral = kinds?.length
121
125
  ? (state.ctx.absences.get(employeeId) ?? []).filter((a) => a.kind !== undefined && kinds.includes(a.kind))
122
126
  : [];
127
+ /*
128
+ * Hours already inside the window when the period opened.
129
+ *
130
+ * A twelve-month reference period otherwise needs twelve months of
131
+ * shift-level history replayed on every solve, because the only way to put
132
+ * minutes into a window was one assignment at a time. The balance is added
133
+ * to the *worked* side rather than taken off the cap so the reported
134
+ * numbers stay legible: "would work 114h against a 100h budget" is what a
135
+ * person needs to read, not "would work 16h against 2h".
136
+ *
137
+ * It belongs to the **longest** window and to no other. Hours worked last
138
+ * autumn are inside a 365-day window and are plainly not inside the last
139
+ * seven days, so adding the figure to every average made 1,500 hours into
140
+ * an annual budget breach a 48-hour *week* — and the one configuration the
141
+ * field exists for, an annual reference period beside the ordinary weekly
142
+ * average, produced an empty roster with no error at all.
143
+ *
144
+ * The longest window is the reference period the balance was measured over,
145
+ * which is the only window it can honestly be added to.
146
+ */
147
+ const carried = appliesTo ? (state.ctx.employeeById.get(employeeId)?.contract?.openingBalanceMinutes ?? 0) : 0;
123
148
  if (neutral.length === 0) {
124
- const worked = timeline.maxWorkingMinutesInAnyWindow(span, bounds);
149
+ const worked = timeline.maxWorkingMinutesInAnyWindow(span, bounds) + carried;
125
150
  return worked > maxMinutes ? { worked, allowance: maxMinutes } : null;
126
151
  }
127
152
  const starts = new Set([bounds.start, bounds.end - span]);
@@ -136,7 +161,7 @@ function worstAverageBreach(state, timeline, employeeId, maxMinutes, span, range
136
161
  let worst = null;
137
162
  for (const start of starts) {
138
163
  const window = { start, end: start + span };
139
- const worked = timeline.workingMinutesIn(window);
164
+ const worked = timeline.workingMinutesIn(window) + carried;
140
165
  const neutralMinutes = neutral.reduce((sum, a) => sum + Math.max(0, Math.min(a.end, window.end) - Math.max(a.start, window.start)), 0);
141
166
  const allowance = maxMinutes * (1 - Math.min(1, neutralMinutes / span));
142
167
  const excess = worked - allowance;
@@ -1 +1 @@
1
- {"version":3,"file":"cost.d.ts","sourceRoot":"","sources":["../../src/scheduling/cost.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;AAEH,OAAO,KAAK,EAAE,QAAQ,EAAE,YAAY,EAAE,cAAc,EAAE,WAAW,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AAGlG;;;;;;;;GAQG;AACH,wBAAgB,cAAc,CAAC,IAAI,EAAE,aAAa,EAAE,IAAI,EAAE,YAAY,GAAG,SAAS,EAAE,UAAU,CAAC,EAAE,cAAc,GAAG,MAAM,CAsBvH;AAaD;;;;GAIG;AACH,wBAAgB,sBAAsB,CAAC,aAAa,EAAE,MAAM,EAAE,IAAI,EAAE,YAAY,GAAG,SAAS,GAAG,MAAM,CAIpG;AAED;;;;;GAKG;AACH,wBAAgB,iBAAiB,CAC7B,IAAI,EAAE,aAAa,EACnB,QAAQ,EAAE,QAAQ,EAClB,aAAa,EAAE,MAAM,EACrB,UAAU,CAAC,EAAE,cAAc,GAC5B,MAAM,CAQR;AAED;;;GAGG;AACH,wBAAgB,UAAU,CAAC,KAAK,EAAE,WAAW,GAAG;IAAE,UAAU,EAAE,MAAM,CAAC;IAAC,UAAU,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;CAAE,GAAG,SAAS,CAiBrH"}
1
+ {"version":3,"file":"cost.d.ts","sourceRoot":"","sources":["../../src/scheduling/cost.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;AAGH,OAAO,KAAK,EAAE,QAAQ,EAAE,YAAY,EAAE,cAAc,EAAE,WAAW,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AAGlG;;;;;;;;GAQG;AACH,wBAAgB,cAAc,CAAC,IAAI,EAAE,aAAa,EAAE,IAAI,EAAE,YAAY,GAAG,SAAS,EAAE,UAAU,CAAC,EAAE,cAAc,GAAG,MAAM,CAsBvH;AAaD;;;;GAIG;AACH,wBAAgB,sBAAsB,CAAC,aAAa,EAAE,MAAM,EAAE,IAAI,EAAE,YAAY,GAAG,SAAS,GAAG,MAAM,CAIpG;AAED;;;;;GAKG;AACH,wBAAgB,iBAAiB,CAC7B,IAAI,EAAE,aAAa,EACnB,QAAQ,EAAE,QAAQ,EAClB,aAAa,EAAE,MAAM,EACrB,UAAU,CAAC,EAAE,cAAc,GAC5B,MAAM,CAQR;AAED;;;GAGG;AACH,wBAAgB,UAAU,CAAC,KAAK,EAAE,WAAW,GAAG;IAAE,UAAU,EAAE,MAAM,CAAC;IAAC,UAAU,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;CAAE,GAAG,SAAS,CAiBrH"}
@@ -24,6 +24,7 @@
24
24
  */
25
25
  Object.defineProperty(exports, "__esModule", { value: true });
26
26
  exports.rosterCost = exports.marginalCostCents = exports.overtimeSurchargeCents = exports.shiftCostCents = void 0;
27
+ const support_1 = require("./constraints/support");
27
28
  const engagement_floor_1 = require("./constraints/engagement-floor");
28
29
  /**
29
30
  * Price of one shift for one cost model, excluding any overtime surcharge.
@@ -108,7 +109,7 @@ function rosterCost(state) {
108
109
  for (const instanceId of state.byEmployee.get(employee.id) ?? []) {
109
110
  const inst = ctx.instanceById.get(instanceId);
110
111
  if (inst)
111
- cents += shiftCostCents(inst, employee.cost, ctx.rules.engagement);
112
+ cents += shiftCostCents(inst, employee.cost, (0, support_1.rulesFor)(ctx, employee.id).engagement);
112
113
  }
113
114
  cents += overtimeSurchargeCents(state.minutesByEmployee.get(employee.id) ?? 0, employee.cost);
114
115
  if (cents > 0)
@@ -1 +1 @@
1
- {"version":3,"file":"construction.d.ts","sourceRoot":"","sources":["../../../src/scheduling/engine/construction.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;GAgBG;AAEH,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,UAAU,CAAC;AAC7C,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,eAAe,CAAC;AACvD,OAAO,EAAU,KAAK,aAAa,EAAE,MAAM,SAAS,CAAC;AAGrD,wEAAwE;AACxE,wBAAgB,aAAa,CAAC,GAAG,EAAE,YAAY,EAAE,KAAK,EAAE,aAAa,EAAE,UAAU,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,GAAG,OAAO,CAKtH;AAkED,gGAAgG;AAChG,wBAAgB,iBAAiB,CAAC,GAAG,EAAE,YAAY,EAAE,WAAW,EAAE,iBAAiB,GAAG,MAAM,EAAE,CAS7F;AAwDD;;;;;;;;;;;;;;;;;;GAkBG;AACH,wBAAgB,cAAc,CAC1B,GAAG,EAAE,YAAY,EACjB,KAAK,EAAE,aAAa,EACpB,WAAW,EAAE,iBAAiB,EAC9B,IAAI,EAAE,MAAM,MAAM,GACnB,IAAI,CA0CN;AAKD;;;;GAIG;AACH,wBAAgB,UAAU,CACtB,GAAG,EAAE,YAAY,EACjB,KAAK,EAAE,aAAa,EACpB,WAAW,EAAE,iBAAiB,EAC9B,SAAS,EAAE,UAAU,GAAG,UAAU,EAClC,IAAI,EAAE,MAAM,MAAM,EAClB,WAAW,CAAC,EAAE,MAAM,EAAE,GACvB,IAAI,CA6BN"}
1
+ {"version":3,"file":"construction.d.ts","sourceRoot":"","sources":["../../../src/scheduling/engine/construction.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;GAgBG;AAEH,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,UAAU,CAAC;AAC7C,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,eAAe,CAAC;AACvD,OAAO,EAAU,KAAK,aAAa,EAAE,MAAM,SAAS,CAAC;AAGrD,wEAAwE;AACxE,wBAAgB,aAAa,CAAC,GAAG,EAAE,YAAY,EAAE,KAAK,EAAE,aAAa,EAAE,UAAU,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,GAAG,OAAO,CAKtH;AAmFD,gGAAgG;AAChG,wBAAgB,iBAAiB,CAAC,GAAG,EAAE,YAAY,EAAE,WAAW,EAAE,iBAAiB,GAAG,MAAM,EAAE,CAS7F;AAwDD;;;;;;;;;;;;;;;;;;GAkBG;AACH,wBAAgB,cAAc,CAC1B,GAAG,EAAE,YAAY,EACjB,KAAK,EAAE,aAAa,EACpB,WAAW,EAAE,iBAAiB,EAC9B,IAAI,EAAE,MAAM,MAAM,GACnB,IAAI,CA0CN;AAKD;;;;GAIG;AACH,wBAAgB,UAAU,CACtB,GAAG,EAAE,YAAY,EACjB,KAAK,EAAE,aAAa,EACpB,WAAW,EAAE,iBAAiB,EAC9B,SAAS,EAAE,UAAU,GAAG,UAAU,EAClC,IAAI,EAAE,MAAM,MAAM,EAClB,WAAW,CAAC,EAAE,MAAM,EAAE,GACvB,IAAI,CA6BN"}
@@ -36,17 +36,37 @@ function rankCandidate(ctx, state, instanceId, employeeId, objective, rand) {
36
36
  const inst = ctx.instanceById.get(instanceId);
37
37
  if (inst) {
38
38
  const assigned = state.assignments.get(instanceId);
39
- for (const [tag, needed] of Object.entries(inst.tagRequirements)) {
39
+ for (const [tag, requirement] of Object.entries(inst.tagRequirements)) {
40
+ const counts = (id) => requirement.level === undefined
41
+ ? ctx.holdsTagOn(id, tag, inst.date)
42
+ : ctx.holdsTagAt(id, tag, inst.date, requirement.level);
40
43
  let have = 0;
41
44
  if (assigned)
42
45
  for (const e of assigned)
43
- if (ctx.employeeTags.get(e)?.has(tag))
46
+ if (counts(e))
44
47
  have++;
45
- if (have < needed && ctx.employeeTags.get(employeeId)?.has(tag)) {
48
+ if (have < requirement.min && counts(employeeId)) {
46
49
  rank -= 1000;
47
50
  reasons.push(`fills tag requirement "${tag}"`);
48
51
  }
49
52
  }
53
+ // Somebody who moves a proportion toward its floor. Judged against the
54
+ // team as it stands, so the preference strengthens as the shift fills
55
+ // rather than being decided when it was empty.
56
+ const onShift = assigned?.size ?? 0;
57
+ for (const [tag, ratio] of Object.entries(inst.tagRatios)) {
58
+ if (!ctx.holdsTagOn(employeeId, tag, inst.date))
59
+ continue;
60
+ let have = 0;
61
+ if (assigned)
62
+ for (const e of assigned)
63
+ if (ctx.holdsTagOn(e, tag, inst.date))
64
+ have++;
65
+ if (have < Math.ceil(ratio * (onShift + 1))) {
66
+ rank -= 800;
67
+ reasons.push(`helps the "${tag}" ratio`);
68
+ }
69
+ }
50
70
  }
51
71
  const planned = state.minutesByEmployee.get(employeeId) ?? 0;
52
72
  const contracted = ctx.contractedPeriodMinutes.get(employeeId);
@@ -19,10 +19,10 @@
19
19
  * gradient to climb out of an infeasible region; a 0/1 flag leaves it on a
20
20
  * plateau with nothing to follow.
21
21
  *
22
- * Aggregate constraints (`evaluate`) are deliberately not run per move — they
23
- * are O(roster) and the search calls the objective in its innermost loop. The
24
- * cheap aggregates that steer the search (coverage, fairness) have dedicated
25
- * terms here; the full `evaluate` pass runs once when the result is assembled.
22
+ * Built-in aggregates use dedicated scoring terms below. Custom `evaluate`
23
+ * hooks also contribute to the score, so extension rules can steer search.
24
+ * Their authors should keep these hooks cheap: they run for each candidate
25
+ * roster. All aggregate hooks run again during final validation.
26
26
  */
27
27
  import type { FairnessRule, ModelContext, SearchState } from '../types';
28
28
  export declare const UNFILLED_WEIGHT = 10000;
@@ -1 +1 @@
1
- {"version":3,"file":"objective.d.ts","sourceRoot":"","sources":["../../../src/scheduling/engine/objective.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AAEH,OAAO,KAAK,EAAE,YAAY,EAAE,YAAY,EAAE,WAAW,EAAE,MAAM,UAAU,CAAC;AAKxE,eAAO,MAAM,eAAe,QAAS,CAAC;AACtC,eAAO,MAAM,oBAAoB,OAAQ,CAAC;AAC1C,eAAO,MAAM,gBAAgB,MAAM,CAAC;AACpC,6EAA6E;AAC7E,eAAO,MAAM,mBAAmB,IAAI,CAAC;AAErC,2DAA2D;AAC3D,MAAM,WAAW,QAAQ;IACrB,IAAI,EAAE,MAAM,CAAC;IACb,MAAM,EAAE,MAAM,CAAC;IACf,IAAI,EAAE,MAAM,CAAC;CAChB;AAED,+EAA+E;AAC/E,wBAAgB,aAAa,CAAC,CAAC,EAAE,QAAQ,EAAE,CAAC,EAAE,QAAQ,GAAG,MAAM,CAI9D;AAED,wBAAgB,QAAQ,CAAC,CAAC,EAAE,QAAQ,EAAE,CAAC,EAAE,QAAQ,GAAG,OAAO,CAE1D;AAED,gEAAgE;AAChE,wBAAgB,YAAY,CAAC,GAAG,EAAE,YAAY,EAAE,KAAK,EAAE,WAAW,EAAE,UAAU,EAAE,MAAM,GAAG,MAAM,CAI9F;AAED,6EAA6E;AAC7E,wBAAgB,WAAW,CAAC,GAAG,EAAE,YAAY,EAAE,KAAK,EAAE,WAAW,EAAE,UAAU,EAAE,MAAM,GAAG,MAAM,CAa7F;AAED,kEAAkE;AAClE,wBAAgB,aAAa,CAAC,GAAG,EAAE,YAAY,EAAE,KAAK,EAAE,WAAW,GAAG,MAAM,CAI3E;AAED,2EAA2E;AAC3E,wBAAgB,aAAa,CAAC,GAAG,EAAE,YAAY,EAAE,KAAK,EAAE,WAAW,GAAG,MAAM,CAK3E;AAED,4DAA4D;AAC5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AAE,MAAM,GACvB,MAAM,CAGR"}
@@ -20,10 +20,10 @@
20
20
  * gradient to climb out of an infeasible region; a 0/1 flag leaves it on a
21
21
  * plateau with nothing to follow.
22
22
  *
23
- * Aggregate constraints (`evaluate`) are deliberately not run per move — they
24
- * are O(roster) and the search calls the objective in its innermost loop. The
25
- * cheap aggregates that steer the search (coverage, fairness) have dedicated
26
- * terms here; the full `evaluate` pass runs once when the result is assembled.
23
+ * Built-in aggregates use dedicated scoring terms below. Custom `evaluate`
24
+ * hooks also contribute to the score, so extension rules can steer search.
25
+ * Their authors should keep these hooks cheap: they run for each candidate
26
+ * roster. All aggregate hooks run again during final validation.
27
27
  */
28
28
  Object.defineProperty(exports, "__esModule", { value: true });
29
29
  exports.score = exports.scoreLex = exports.softBreaches = exports.breachTotals = exports.minHoursShortfalls = exports.hoursVariance = exports.unfilledSlots = exports.tagShortage = exports.slotShortage = exports.isBetter = exports.compareScores = exports.DEFAULT_SOFT_WEIGHT = exports.MIN_HOURS_WEIGHT = exports.TAG_SHORTFALL_WEIGHT = exports.UNFILLED_WEIGHT = void 0;
@@ -63,14 +63,31 @@ function tagShortage(ctx, state, instanceId) {
63
63
  return 0;
64
64
  const assigned = state.assignments.get(instanceId);
65
65
  let short = 0;
66
- for (const [tag, needed] of Object.entries(inst.tagRequirements)) {
66
+ for (const [tag, requirement] of Object.entries(inst.tagRequirements)) {
67
67
  let have = 0;
68
68
  if (assigned) {
69
+ for (const employeeId of assigned) {
70
+ const holds = requirement.level === undefined
71
+ ? ctx.holdsTagOn(employeeId, tag, inst.date)
72
+ : ctx.holdsTagAt(employeeId, tag, inst.date, requirement.level);
73
+ if (holds)
74
+ have++;
75
+ }
76
+ }
77
+ short += Math.max(0, requirement.min - have);
78
+ }
79
+ // A ratio's shortfall is measured against the team that is actually on, so
80
+ // it moves as the shift fills — which is what lets the search close it by
81
+ // adding the right person rather than by adding anybody.
82
+ const size = assigned?.size ?? 0;
83
+ if (size > 0) {
84
+ for (const [tag, ratio] of Object.entries(inst.tagRatios)) {
85
+ let have = 0;
69
86
  for (const employeeId of assigned)
70
- if (ctx.employeeTags.get(employeeId)?.has(tag))
87
+ if (ctx.holdsTagOn(employeeId, tag, inst.date))
71
88
  have++;
89
+ short += Math.max(0, Math.ceil(ratio * size) - have);
72
90
  }
73
- short += Math.max(0, needed - have);
74
91
  }
75
92
  return short;
76
93
  }
@@ -136,6 +153,14 @@ exports.softBreaches = softBreaches;
136
153
  /** The full three-level score. Lower is better at every level. */
137
154
  function scoreLex(ctx, state, objective, minHoursWeight, fairnessRules) {
138
155
  const totals = breachTotals(ctx, state);
156
+ for (const constraint of ctx.aggregateConstraints ?? []) {
157
+ for (const violation of constraint.evaluate?.(state) ?? []) {
158
+ const magnitude = violation.actual !== undefined && violation.required !== undefined
159
+ ? Math.max(1, Math.abs(violation.actual - violation.required))
160
+ : 1;
161
+ totals[violation.severity] += magnitude * (constraint.weight ?? exports.DEFAULT_SOFT_WEIGHT);
162
+ }
163
+ }
139
164
  for (const inst of ctx.instances) {
140
165
  totals.medium += slotShortage(ctx, state, inst.id) * exports.UNFILLED_WEIGHT;
141
166
  totals.medium += tagShortage(ctx, state, inst.id) * exports.TAG_SHORTFALL_WEIGHT;
@@ -15,7 +15,8 @@ function propagate(ctx) {
15
15
  eligibility.set(emp.id, new Set(ctx.instances.map((i) => i.id)));
16
16
  }
17
17
  for (const constraint of ctx.constraints) {
18
- constraint.prune?.(ctx, eligibility);
18
+ if (constraint.hardness === 'hard')
19
+ constraint.prune?.(ctx, eligibility);
19
20
  }
20
21
  const eligibleByInstance = new Map();
21
22
  for (const inst of ctx.instances)
@@ -29,6 +29,7 @@ export interface SearchOptions {
29
29
  objective: 'standard' | 'balanced';
30
30
  minHoursWeight: number;
31
31
  timeBudgetMs: number;
32
+ maxIterations?: number;
32
33
  rand: () => number;
33
34
  now?: () => number;
34
35
  /** Late-acceptance history length. Larger accepts more drift. */
@@ -1 +1 @@
1
- {"version":3,"file":"search.d.ts","sourceRoot":"","sources":["../../../src/scheduling/engine/search.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;AAEH,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,UAAU,CAAC;AAC7C,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,eAAe,CAAC;AAEvD,OAAO,EAAgE,KAAK,QAAQ,EAAE,MAAM,aAAa,CAAC;AAC1G,OAAO,EAAmC,KAAK,aAAa,EAAE,MAAM,SAAS,CAAC;AAG9E,MAAM,WAAW,aAAa;IAC1B,SAAS,EAAE,UAAU,GAAG,UAAU,CAAC;IACnC,cAAc,EAAE,MAAM,CAAC;IACvB,YAAY,EAAE,MAAM,CAAC;IACrB,IAAI,EAAE,MAAM,MAAM,CAAC;IACnB,GAAG,CAAC,EAAE,MAAM,MAAM,CAAC;IACnB,iEAAiE;IACjE,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,kEAAkE;IAClE,aAAa,CAAC,EAAE,CAAC,KAAK,EAAE,aAAa,EAAE,KAAK,EAAE,QAAQ,KAAK,IAAI,CAAC;CACnE;AAED,MAAM,WAAW,aAAa;IAC1B,IAAI,EAAE,aAAa,CAAC;IACpB,iBAAiB,EAAE,MAAM,CAAC;CAC7B;AAiCD;;;;;GAKG;AACH,wBAAgB,cAAc,CAC1B,GAAG,EAAE,YAAY,EACjB,KAAK,EAAE,aAAa,EACpB,WAAW,EAAE,iBAAiB,EAC9B,OAAO,EAAE,aAAa,EACtB,gBAAgB,EAAE,MAAM,aAAa,GACtC,aAAa,CA4Ef"}
1
+ {"version":3,"file":"search.d.ts","sourceRoot":"","sources":["../../../src/scheduling/engine/search.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;AAEH,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,UAAU,CAAC;AAC7C,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,eAAe,CAAC;AAEvD,OAAO,EAAgE,KAAK,QAAQ,EAAE,MAAM,aAAa,CAAC;AAC1G,OAAO,EAAmC,KAAK,aAAa,EAAE,MAAM,SAAS,CAAC;AAG9E,MAAM,WAAW,aAAa;IAC1B,SAAS,EAAE,UAAU,GAAG,UAAU,CAAC;IACnC,cAAc,EAAE,MAAM,CAAC;IACvB,YAAY,EAAE,MAAM,CAAC;IACrB,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,IAAI,EAAE,MAAM,MAAM,CAAC;IACnB,GAAG,CAAC,EAAE,MAAM,MAAM,CAAC;IACnB,iEAAiE;IACjE,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,kEAAkE;IAClE,aAAa,CAAC,EAAE,CAAC,KAAK,EAAE,aAAa,EAAE,KAAK,EAAE,QAAQ,KAAK,IAAI,CAAC;CACnE;AAED,MAAM,WAAW,aAAa;IAC1B,IAAI,EAAE,aAAa,CAAC;IACpB,iBAAiB,EAAE,MAAM,CAAC;CAC7B;AAiCD;;;;;GAKG;AACH,wBAAgB,cAAc,CAC1B,GAAG,EAAE,YAAY,EACjB,KAAK,EAAE,aAAa,EACpB,WAAW,EAAE,iBAAiB,EAC9B,OAAO,EAAE,aAAa,EACtB,gBAAgB,EAAE,MAAM,aAAa,GACtC,aAAa,CA4Ef"}
@@ -71,7 +71,7 @@ function improveWithLns(ctx, state, propagation, options, createEmptyState) {
71
71
  const historyLength = Math.max(1, options.historyLength ?? DEFAULT_HISTORY_LENGTH);
72
72
  const history = new Array(historyLength).fill(workingScore);
73
73
  let iteration = 0;
74
- while (now() < deadline) {
74
+ while (now() < deadline && iteration < (options.maxIterations ?? Infinity)) {
75
75
  const total = (0, state_1.assignedPairs)(working).length;
76
76
  if (total === 0)
77
77
  break;
@@ -1 +1 @@
1
- {"version":3,"file":"state.d.ts","sourceRoot":"","sources":["../../../src/scheduling/engine/state.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,KAAK,EAAE,YAAY,EAAE,WAAW,EAAE,MAAM,UAAU,CAAC;AAG1D,MAAM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AAM,CAAC,KAAK,EAAE,aAAa,EAAE,UAAU,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,GAAG,IAAI,CAuB5G;AAED,wBAAgB,QAAQ,CAAC,KAAK,EAAE,aAAa,EAAE,UAAU,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,GAAG,IAAI,CAY3F;AAED;;;;GAIG;AACH,wBAAgB,eAAe,CAAC,UAAU,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,GAAG,MAAM,CAE9E;AAED,yFAAyF;AACzF,wBAAgB,aAAa,CAAC,KAAK,EAAE,aAAa,GAAG,KAAK,CAAC;IAAE,UAAU,EAAE,MAAM,CAAC;IAAC,UAAU,EAAE,MAAM,CAAA;CAAE,CAAC,CAQrG"}
@@ -44,6 +44,8 @@ function assign(state, employeeId, instanceId, reasons) {
44
44
  // employee the model never saw would corrupt the fairness and cost sums.
45
45
  if (!inst || !state.ctx.employeeById.has(employeeId))
46
46
  return;
47
+ if (state.isAssigned(employeeId, instanceId))
48
+ return;
47
49
  state.assignments.get(instanceId)?.add(employeeId);
48
50
  state.byEmployee.get(employeeId)?.add(instanceId);
49
51
  // `minutesByEmployee` tracks *working* time, which unpaid breaks and duty
@@ -65,6 +67,8 @@ function unassign(state, employeeId, instanceId) {
65
67
  const inst = state.ctx.instanceById.get(instanceId);
66
68
  if (!inst || !state.ctx.employeeById.has(employeeId))
67
69
  return;
70
+ if (!state.isAssigned(employeeId, instanceId))
71
+ return;
68
72
  state.assignments.get(instanceId)?.delete(employeeId);
69
73
  state.byEmployee.get(employeeId)?.delete(instanceId);
70
74
  state.minutesByEmployee.set(employeeId, (state.minutesByEmployee.get(employeeId) ?? 0) - inst.workingMinutes);