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
@@ -17,6 +17,7 @@ const recurrence_1 = require("./schedule/recurrence");
17
17
  const assignment_lint_1 = require("./validation/assignment-lint");
18
18
  const decision_trace_1 = require("./tracing/decision-trace");
19
19
  const features_1 = require("./learning/features");
20
+ const policy_4 = require("./learning/policy");
20
21
  const DecisionTraceManager_1 = require("./managers/DecisionTraceManager");
21
22
  const LearningManager_1 = require("./managers/LearningManager");
22
23
  const ReliabilityManager_1 = require("./managers/ReliabilityManager");
@@ -128,7 +129,10 @@ class AssignmentMatcher {
128
129
  // reference; custom extractors keep their exact signature.
129
130
  this.learningFeatureExtractor =
130
131
  options?.learningFeatureExtractor ??
131
- ((user, assignment) => (0, features_1.extractMatchFeatures)(user, assignment, this.learningSlaTightnessReferenceMs));
132
+ ((user, assignment, context) => (0, features_1.extractMatchFeatures)(user, assignment, this.learningSlaTightnessReferenceMs, context));
133
+ this.enableLearningPerformanceFeatures = options?.enableLearningPerformanceFeatures ?? false;
134
+ this.learningMaxBoost = options?.learningMaxBoost;
135
+ this.learningRng = options?.learningRng ?? Math.random;
132
136
  this.learning = new LearningManager_1.LearningManager(this.redisClient, this.keys, {
133
137
  learningRate: options?.learningRate,
134
138
  explorationRate: options?.learningExplorationRate,
@@ -140,6 +144,19 @@ class AssignmentMatcher {
140
144
  feedbackTtlMs: options?.learningFeedbackTtlMs,
141
145
  trackTagStats: this.enableAutoRoutingWeights,
142
146
  autoWeights: options?.autoRoutingWeights,
147
+ updateMode: options?.learningUpdateMode,
148
+ l2: options?.learningL2,
149
+ maxUpdateNorm: options?.learningMaxUpdateNorm,
150
+ maxWeightMagnitude: options?.learningMaxWeightMagnitude,
151
+ rewardAccounting: options?.learningRewardAccounting,
152
+ explorationPolicy: options?.learningExplorationPolicy,
153
+ rng: this.learningRng,
154
+ targets: options?.learningTargets,
155
+ maxFeedbackAgeMs: options?.learningMaxFeedbackAgeMs,
156
+ maxSignalMagnitude: options?.learningMaxSignalMagnitude,
157
+ maxRewardMagnitude: options?.learningMaxRewardMagnitude,
158
+ trackPerformance: this.enableLearningPerformanceFeatures,
159
+ performancePriorStrength: options?.learningPerformancePriorStrength,
143
160
  });
144
161
  // Decision traces (opt-in explainability/audit records per routing decision)
145
162
  this.enableDecisionTraces = options?.enableDecisionTraces ?? false;
@@ -454,9 +471,28 @@ class AssignmentMatcher {
454
471
  * Enables custom reward shaping beyond the built-in lifecycle outcomes.
455
472
  * Returns false when no decision context exists for the assignment.
456
473
  */
457
- async recordLearningReward(assignmentId, reward) {
474
+ async recordLearningReward(assignmentId, reward, options) {
458
475
  await this.readyPromise;
459
- return this.learning.recordReward(assignmentId, reward);
476
+ return this.learning.recordReward(assignmentId, reward, options);
477
+ }
478
+ /**
479
+ * The learning context of the attempt currently in flight for an
480
+ * assignment: features, prediction, selection propensity and policy.
481
+ * Null when there is none.
482
+ */
483
+ async getLearningDecision(assignmentId) {
484
+ await this.readyPromise;
485
+ return this.learning.getDecision(assignmentId);
486
+ }
487
+ /** The learning context of one specific attempt, by decision id. */
488
+ async getLearningDecisionById(decisionId) {
489
+ await this.readyPromise;
490
+ return this.learning.getDecisionById(decisionId);
491
+ }
492
+ /** The archived episode of the most recent closed attempt for an assignment. */
493
+ async getLearningEpisode(assignmentId) {
494
+ await this.readyPromise;
495
+ return this.learning.getEpisode(assignmentId);
460
496
  }
461
497
  /**
462
498
  * Feed external post-processing signals into the model for an assignment
@@ -465,9 +501,9 @@ class AssignmentMatcher {
465
501
  * Signal values are weighted via the `learningSignalWeights` option (default 1).
466
502
  * Returns false when no learning context exists for the assignment.
467
503
  */
468
- async recordLearningFeedback(assignmentId, signals) {
504
+ async recordLearningFeedback(assignmentId, signals, options) {
469
505
  await this.readyPromise;
470
- return this.learning.recordFeedback(assignmentId, signals);
506
+ return this.learning.recordFeedback(assignmentId, signals, options);
471
507
  }
472
508
  /**
473
509
  * Train the model directly with raw (features, reward) samples from an
@@ -1107,6 +1143,23 @@ class AssignmentMatcher {
1107
1143
  const existingWeights = userJson ? JSON.parse(userJson).routingWeights : undefined;
1108
1144
  return this.learning.getLearnedRoutingWeights(userId, knownTags, existingWeights);
1109
1145
  }
1146
+ /**
1147
+ * The same synthesis with its reasoning attached, per tag: posterior
1148
+ * estimate and uncertainty, credible bounds, independent attempts,
1149
+ * effective sample size after decay, last observation, decay settings and
1150
+ * — for a lapsed veto — when it will be reassessed.
1151
+ *
1152
+ * A hard veto removes a worker's eligibility for a tag outright, so
1153
+ * "the model decided" is not an adequate account of it; this is the API
1154
+ * that makes such a change reviewable.
1155
+ */
1156
+ async explainLearnedRoutingWeights(userId, opts) {
1157
+ await this.readyPromise;
1158
+ const knownTags = opts?.includeUnexploredTags ? await this.getKnownTagsForAutoWeights() : undefined;
1159
+ const userJson = await this.redisClient.hGet(this.usersKey, userId);
1160
+ const existingWeights = userJson ? JSON.parse(userJson).routingWeights : undefined;
1161
+ return this.learning.explainLearnedRoutingWeights(userId, knownTags, existingWeights);
1162
+ }
1110
1163
  /**
1111
1164
  * Apply learned routing weights to one user (or every tracked user when
1112
1165
  * no id is given), automating tags/weights generation from RL outcomes.
@@ -2043,6 +2096,59 @@ class AssignmentMatcher {
2043
2096
  const own = user.maxBacklogSize;
2044
2097
  return typeof own === 'number' && Number.isFinite(own) && own >= 0 ? own : this.maxUserBacklogSize;
2045
2098
  }
2099
+ /**
2100
+ * Record how long an accepted assignment took this worker, for the
2101
+ * handling-time performance feature. Best effort: an assignment whose
2102
+ * accept timestamp was never stored contributes nothing rather than a
2103
+ * fabricated duration.
2104
+ */
2105
+ async recordLearningHandlingTime(userId, assignment, completedAt) {
2106
+ if (!this.enableLearningPerformanceFeatures)
2107
+ return;
2108
+ const acceptedAt = Number(assignment?.[policy_2.SLA_ACCEPTED_AT_FIELD] ?? assignment?._acceptedAt);
2109
+ if (!Number.isFinite(acceptedAt) || acceptedAt <= 0 || completedAt < acceptedAt)
2110
+ return;
2111
+ await this.learning.recordHandlingTime(userId, assignment?.tags, completedAt - acceptedAt);
2112
+ }
2113
+ /**
2114
+ * Bound the learning layer's contribution to a candidate's effective
2115
+ * priority.
2116
+ *
2117
+ * Predicted reward and business priority are in unrelated units, so an
2118
+ * unbounded boost can silently outrank an operator's priority or an SLA
2119
+ * band. `learningMaxBoost` is the explicit ceiling; without it the
2120
+ * pre-1.16 unbounded behaviour is kept.
2121
+ */
2122
+ clampLearningBoost(boost) {
2123
+ if (!Number.isFinite(boost))
2124
+ return 0;
2125
+ const limit = this.learningMaxBoost;
2126
+ if (limit === undefined)
2127
+ return boost;
2128
+ return Math.max(-limit, Math.min(limit, boost));
2129
+ }
2130
+ /**
2131
+ * Ambient context for the feature extractor: batch-loaded performance
2132
+ * aggregates for this worker plus the team priors they are shrunk
2133
+ * toward, and one `now` shared by every candidate in the pass so
2134
+ * deadline arithmetic is consistent across the whole scoring loop.
2135
+ *
2136
+ * Returns just `{ now }` when performance features are off, which is the
2137
+ * default — existing extractors and learned weights are unaffected.
2138
+ */
2139
+ async buildLearningFeatureContext(user) {
2140
+ const now = Date.now();
2141
+ if (!this.enableLearningPerformanceFeatures)
2142
+ return { now };
2143
+ const [priors, backlog] = await Promise.all([
2144
+ this.learning.loadTeamPriors(),
2145
+ this.redisClient.sCard(this.keys.userAssignments(user.id)),
2146
+ ]);
2147
+ const performance = await this.learning.loadPerformance(user.id, priors);
2148
+ performance.backlog = Number(backlog) || 0;
2149
+ performance.backlogLimit = this.backlogLimitFor(user);
2150
+ return { now, priors, performance };
2151
+ }
2046
2152
  async computeCandidatesForUser(user, capToBacklog = true, collector, grantBudget) {
2047
2153
  const userAssignments = [];
2048
2154
  const routingWeights = user.routingWeights;
@@ -2182,7 +2288,11 @@ class AssignmentMatcher {
2182
2288
  if (this.enableLearning) {
2183
2289
  // Learning path: evaluate all eligible candidates, then re-rank by
2184
2290
  // base priority + predicted reward (hard filters still apply first).
2185
- const modelWeights = await this.learning.getModel();
2291
+ const snapshot = await this.learning.loadModels();
2292
+ // Worker performance aggregates are read ONCE per user per pass,
2293
+ // never per candidate: the whole point of the batch load is that
2294
+ // richer features cost no extra Redis round trips inside the loop.
2295
+ const featureContext = await this.buildLearningFeatureContext(user);
2186
2296
  const eligible = [];
2187
2297
  for (const d of details) {
2188
2298
  if (!(0, cidr_1.checkCidrMatch)(user.ip, d.allowedCidrs)) {
@@ -2231,17 +2341,31 @@ class AssignmentMatcher {
2231
2341
  id: d.id,
2232
2342
  tags: d.tags ? d.tags.split(',').filter(Boolean) : [],
2233
2343
  };
2234
- const features = this.learningFeatureExtractor(user, context);
2235
- const predicted = this.learning.predict(features, modelWeights);
2236
- // Shadow mode observes without influencing ranking.
2237
- // Epsilon-greedy exploration adds random jitter to gather data on under-served candidates.
2238
- const exploration = !this.learning.shadowMode && this.learning.shouldExplore()
2239
- ? Math.random() * this.learning.boostFactor
2344
+ const features = this.learningFeatureExtractor(user, context, featureContext);
2345
+ const prediction = this.learning.predictWith(snapshot, features);
2346
+ const predicted = prediction.utility;
2347
+ // Shadow mode observes without influencing ranking. Under the
2348
+ // legacy 'jitter' policy exploration is random score noise;
2349
+ // under 'epsilon-greedy' the score stays clean and the
2350
+ // selection step does the exploring, so the probability it
2351
+ // chose with is recoverable.
2352
+ const exploration = this.learning.explorationPolicy === 'jitter' &&
2353
+ !this.learning.shadowMode &&
2354
+ this.learning.shouldExplore()
2355
+ ? this.learningRng() * this.learning.boostFactor
2240
2356
  : 0;
2357
+ const boost = this.clampLearningBoost(this.learning.boostFactor * predicted);
2241
2358
  const effectivePriority = this.learning.shadowMode
2242
2359
  ? geoAdjustedPriority
2243
- : geoAdjustedPriority + this.learning.boostFactor * predicted + exploration;
2244
- eligible.push({ detail: d, combinedPriority, features, predicted, effectivePriority });
2360
+ : geoAdjustedPriority + boost + exploration;
2361
+ eligible.push({
2362
+ detail: d,
2363
+ combinedPriority,
2364
+ features,
2365
+ predicted,
2366
+ components: prediction.components,
2367
+ effectivePriority,
2368
+ });
2245
2369
  collector?.record(d.id, d.tags, {
2246
2370
  userId: user.id,
2247
2371
  eligible: true,
@@ -2255,12 +2379,42 @@ class AssignmentMatcher {
2255
2379
  });
2256
2380
  }
2257
2381
  eligible.sort((a, b) => b.effectivePriority - a.effectivePriority);
2258
- for (const c of eligible) {
2259
- if (capToBacklog && userAssignments.length >= effectiveCap)
2260
- break;
2382
+ // Selection is a named policy, not an ad-hoc take-the-top-N: the
2383
+ // probability each candidate was actually chosen with travels
2384
+ // with the decision, and that propensity is what makes the logs
2385
+ // usable for off-policy evaluation.
2386
+ const budget = capToBacklog ? Math.max(0, effectiveCap - userAssignments.length) : eligible.length;
2387
+ const choices = this.learning.explorationPolicy === 'epsilon-greedy' && !this.learning.shadowMode
2388
+ ? (0, policy_4.epsilonGreedySelect)(eligible, (c) => c.effectivePriority, budget, {
2389
+ epsilon: this.learning.explorationRate,
2390
+ rng: this.learningRng,
2391
+ })
2392
+ : eligible
2393
+ .slice(0, budget)
2394
+ .map((item) => ({ item, propensity: undefined, candidateCount: eligible.length }));
2395
+ // NOTE: no decision is recorded here. A candidate scored in this
2396
+ // pass may still lose the assignment — to another worker under
2397
+ // fair arbitration, or to another process at the claim gate — and
2398
+ // a decision written for a worker who never received the work is
2399
+ // training data attributed to the wrong person. Decisions are
2400
+ // committed in claimSelected(), for winners only.
2401
+ for (const choice of choices) {
2402
+ const c = choice.item;
2261
2403
  userAssignments.push({ id: c.detail.id, priority: c.effectivePriority });
2262
- selected.push({ id: c.detail.id, tags: c.detail.tags });
2263
- await this.learning.recordDecision(user.id, c.detail.id, c.features, c.predicted, c.detail.tags ? c.detail.tags.split(',').filter(Boolean) : undefined);
2404
+ selected.push({
2405
+ id: c.detail.id,
2406
+ tags: c.detail.tags,
2407
+ learning: {
2408
+ features: c.features,
2409
+ predictedReward: c.predicted,
2410
+ components: c.components,
2411
+ tags: c.detail.tags ? c.detail.tags.split(',').filter(Boolean) : undefined,
2412
+ propensity: choice.propensity,
2413
+ policy: this.learning.explorationPolicy,
2414
+ candidateCount: choice.candidateCount,
2415
+ generation: snapshot.generation,
2416
+ },
2417
+ });
2264
2418
  }
2265
2419
  }
2266
2420
  else {
@@ -2407,6 +2561,33 @@ class AssignmentMatcher {
2407
2561
  rm.hSet(this.assignmentOwnerKey, s.id, user.id);
2408
2562
  }
2409
2563
  }
2564
+ // Commit the learning context for the attempts this worker
2565
+ // actually won — and only those. The HDEL above is the atomic gate
2566
+ // that decides ownership, so this is the first point at which "who
2567
+ // got this assignment" is a settled fact. The writes go into the
2568
+ // SAME transaction as the queued -> pending move: a separate write
2569
+ // afterwards would leave a crash gap in which the worker owns the
2570
+ // assignment but no learning context exists for it, and its
2571
+ // outcome would then arrive orphaned.
2572
+ if (this.enableLearning) {
2573
+ const decisions = selected
2574
+ .filter((s) => claimedIds.has(s.id) && s.learning)
2575
+ .map((s) => ({
2576
+ decisionId: this.learning.newDecisionId(s.id),
2577
+ userId: user.id,
2578
+ assignmentId: s.id,
2579
+ features: s.learning.features,
2580
+ predictedReward: s.learning.predictedReward,
2581
+ components: s.learning.components,
2582
+ tags: s.learning.tags,
2583
+ propensity: s.learning.propensity,
2584
+ policy: s.learning.policy,
2585
+ candidateCount: s.learning.candidateCount,
2586
+ }));
2587
+ if (decisions.length > 0) {
2588
+ this.learning.queueDecisionWrites(rm, decisions, selected.find((s) => s.learning)?.learning?.generation ?? 0);
2589
+ }
2590
+ }
2410
2591
  await rm.exec();
2411
2592
  for (let i = 0; i < selected.length; i++) {
2412
2593
  const s = selected[i];
@@ -2454,12 +2635,14 @@ class AssignmentMatcher {
2454
2635
  * contested assignment, rather than whichever user's independent claim
2455
2636
  * happened to reach Redis first.
2456
2637
  *
2457
- * Known limitation: when combined with enableLearning, computeCandidatesForUser
2458
- * still records a bandit decision for every scored candidate at evaluation
2459
- * time, including ones that lose the global tiebreak here - the learning
2460
- * layer's per-user candidate ordering isn't itself part of the fairness
2461
- * comparison in this mode. Fine for the common case (fairness without
2462
- * learning), but a consumer combining both should be aware.
2638
+ * Combined with enableLearning, the learned score IS the score that
2639
+ * arbitration compares: `computeCandidatesForUser` returns the
2640
+ * learning-adjusted effective priority, and it is that number that flows
2641
+ * into `globalPairs`. Learning contexts ride along unpersisted and are
2642
+ * committed inside claimSelected() for winners only, so a candidate that
2643
+ * loses the global tiebreak leaves no decision behind — the earlier
2644
+ * behaviour, which recorded one for every scored candidate, attributed
2645
+ * outcomes to workers who never received the work.
2463
2646
  */
2464
2647
  async matchAllUsersFair() {
2465
2648
  let users = [];
@@ -2567,6 +2750,7 @@ class AssignmentMatcher {
2567
2750
  id: s.id,
2568
2751
  tags: s.tags,
2569
2752
  priority: priorityById.get(s.id) ?? 0,
2753
+ learning: s.learning,
2570
2754
  });
2571
2755
  }
2572
2756
  }
@@ -2613,7 +2797,7 @@ class AssignmentMatcher {
2613
2797
  const tentative = new Map();
2614
2798
  for (const w of winners) {
2615
2799
  const bucket = tentative.get(w.userId) ?? { user: w.user, pairs: [] };
2616
- bucket.pairs.push({ id: w.id, tags: w.tags });
2800
+ bucket.pairs.push({ id: w.id, tags: w.tags, learning: w.learning });
2617
2801
  tentative.set(w.userId, bucket);
2618
2802
  }
2619
2803
  if (tentative.size === 0)
@@ -2916,15 +3100,21 @@ class AssignmentMatcher {
2916
3100
  if (json) {
2917
3101
  const slaPolicy = (0, policy_2.slaFromJson)(json);
2918
3102
  let acceptedJson = json;
2919
- if (slaPolicy) {
3103
+ // The accept stamp is also what the learning layer's handling-time
3104
+ // feature measures from, so it is written for SLA-bearing work and
3105
+ // — only when that opt-in feature is on — for everything else too.
3106
+ // With both off, an assignment's stored JSON stays byte-identical.
3107
+ if (slaPolicy || this.enableLearningPerformanceFeatures) {
2920
3108
  try {
2921
3109
  const parsed = JSON.parse(json);
2922
3110
  parsed[policy_2.SLA_ACCEPTED_AT_FIELD] = now;
2923
3111
  parsed[policy_2.SLA_ACCEPTED_BY_FIELD] = userId;
2924
3112
  acceptedJson = JSON.stringify(parsed);
2925
- const deadline = (0, policy_2.completionDeadlineScore)(now, slaPolicy);
2926
- if (deadline !== null) {
2927
- multi.zAdd(this.acceptedAssignmentsExpiryKey, { score: deadline, value: assignmentId });
3113
+ if (slaPolicy) {
3114
+ const deadline = (0, policy_2.completionDeadlineScore)(now, slaPolicy);
3115
+ if (deadline !== null) {
3116
+ multi.zAdd(this.acceptedAssignmentsExpiryKey, { score: deadline, value: assignmentId });
3117
+ }
2928
3118
  }
2929
3119
  }
2930
3120
  catch {
@@ -2944,7 +3134,7 @@ class AssignmentMatcher {
2944
3134
  await this.recordSlaAccept(json, now);
2945
3135
  }
2946
3136
  if (this.enableLearning) {
2947
- await this.learning.applyOutcome(assignmentId, 'accept');
3137
+ await this.learning.applyOutcome(assignmentId, 'accept', { expectedUserId: userId });
2948
3138
  }
2949
3139
  this.emitAssignmentLifecycle({
2950
3140
  kind: 'accepted',
@@ -2970,7 +3160,7 @@ class AssignmentMatcher {
2970
3160
  multi.sAdd(this.keys.userRejected(userId), assignmentId);
2971
3161
  await multi.exec();
2972
3162
  if (this.enableLearning) {
2973
- await this.learning.applyOutcome(assignmentId, 'reject');
3163
+ await this.learning.applyOutcome(assignmentId, 'reject', { expectedUserId: userId });
2974
3164
  }
2975
3165
  this.emitAssignmentLifecycle({
2976
3166
  kind: 'rejected',
@@ -3085,7 +3275,8 @@ class AssignmentMatcher {
3085
3275
  await this.recordSlaComplete(json, now);
3086
3276
  }
3087
3277
  if (this.enableLearning) {
3088
- await this.learning.applyOutcome(assignmentId, 'complete');
3278
+ await this.learning.applyOutcome(assignmentId, 'complete', { expectedUserId: userId });
3279
+ await this.recordLearningHandlingTime(userId, assignment, now);
3089
3280
  }
3090
3281
  // Publish workflow event if workflows are enabled
3091
3282
  if (this.enableWorkflows) {
@@ -3113,7 +3304,7 @@ class AssignmentMatcher {
3113
3304
  * @param assignmentId - The assignment being failed
3114
3305
  * @param reason - Optional reason for failure
3115
3306
  */
3116
- async failAssignment(userId, assignmentId, reason) {
3307
+ async failAssignment(userId, assignmentId, reason, options) {
3117
3308
  await this.readyPromise;
3118
3309
  const json = await this.redisClient.hGet(this.acceptedAssignmentsKey, assignmentId);
3119
3310
  if (!json) {
@@ -3138,7 +3329,10 @@ class AssignmentMatcher {
3138
3329
  multi.zAdd(this.completedAssignmentsAtKey, { score: now, value: assignmentId });
3139
3330
  await multi.exec();
3140
3331
  if (this.enableLearning) {
3141
- await this.learning.applyOutcome(assignmentId, 'fail');
3332
+ await this.learning.applyOutcome(assignmentId, 'fail', {
3333
+ expectedUserId: userId,
3334
+ systemFault: options?.systemFault,
3335
+ });
3142
3336
  }
3143
3337
  // Publish workflow event if workflows are enabled
3144
3338
  if (this.enableWorkflows) {
@@ -3415,7 +3609,7 @@ class AssignmentMatcher {
3415
3609
  await this.bumpSlaStats(assignment.tags, { acceptanceBreaches: 1 });
3416
3610
  }
3417
3611
  if (this.enableLearning) {
3418
- await this.learning.applyOutcome(id, 'expire');
3612
+ await this.learning.applyOutcome(id, 'expire', { expectedUserId: owner ?? undefined });
3419
3613
  }
3420
3614
  // Publish workflow expired event if workflows are enabled
3421
3615
  if (this.enableWorkflows && owner) {
@@ -3528,7 +3722,9 @@ class AssignmentMatcher {
3528
3722
  });
3529
3723
  await this.bumpSlaStats(assignment.tags, { completionBreaches: 1 });
3530
3724
  if (this.enableLearning) {
3531
- await this.learning.applyOutcome(id, action === 'fail' ? 'fail' : 'expire');
3725
+ await this.learning.applyOutcome(id, action === 'fail' ? 'fail' : 'expire', {
3726
+ expectedUserId: workerId ?? undefined,
3727
+ });
3532
3728
  }
3533
3729
  if (action === 'notify') {
3534
3730
  // Worker keeps the assignment; the event + learning outcome
@@ -3658,7 +3854,12 @@ class AssignmentMatcher {
3658
3854
  });
3659
3855
  await this.bumpSlaStats(assignment.tags, { ttlExpiries: 1 });
3660
3856
  if (this.enableLearning) {
3661
- await this.learning.applyOutcome(id, 'expire');
3857
+ // A freshness TTL running out is the system aging work out,
3858
+ // not the worker declining or failing it.
3859
+ await this.learning.applyOutcome(id, 'expire', {
3860
+ expectedUserId: ownerId ?? undefined,
3861
+ systemFault: true,
3862
+ });
3662
3863
  }
3663
3864
  }
3664
3865
  return { expired };
@@ -3743,7 +3944,11 @@ class AssignmentMatcher {
3743
3944
  });
3744
3945
  await this.bumpSlaStats(assignment.tags, { scheduleMisses: 1 });
3745
3946
  if (this.enableLearning) {
3746
- await this.learning.applyOutcome(id, 'expire');
3947
+ // The offer window closed; nobody declined anything.
3948
+ await this.learning.applyOutcome(id, 'expire', {
3949
+ expectedUserId: ownerId ?? undefined,
3950
+ systemFault: true,
3951
+ });
3747
3952
  }
3748
3953
  }
3749
3954
  const dueIds = await this.redisClient.zRangeByScore(this.scheduledActivateAtKey, '-inf', now);
@@ -4291,7 +4496,9 @@ class AssignmentMatcher {
4291
4496
  releasedAt: now,
4292
4497
  });
4293
4498
  if (this.enableLearning) {
4294
- await this.learning.applyOutcome(id, 'expire');
4499
+ // Redistribution is an operator/idle-sweep action, so it is
4500
+ // never counted as the worker failing the work.
4501
+ await this.learning.applyOutcome(id, 'expire', { expectedUserId: userId, systemFault: true });
4295
4502
  }
4296
4503
  if (this.enableWorkflows) {
4297
4504
  await this.workflow.publishWorkflowEvent({
@@ -19,6 +19,16 @@ import type { ConsecutiveRule, SchedulingConstraint } from '../types';
19
19
  export declare const CONSECUTIVE_CITATION = "National working-time law / collective agreement";
20
20
  /** Every sequence constraint the rule configures. */
21
21
  export declare function consecutiveConstraints(rule: ConsecutiveRule): SchedulingConstraint[];
22
+ /**
23
+ * Weekends in a row.
24
+ *
25
+ * "Every second weekend off" — the term most often negotiated and the one a
26
+ * count cannot hold. Weekends are keyed by the Saturday that opens them, so a
27
+ * Saturday and the Sunday after it are one weekend; keying by week number would
28
+ * split a weekend across a year boundary and keying by day would make every
29
+ * ordinary weekend a run of two.
30
+ */
31
+ export declare function consecutiveWeekends(maxWeekends: number): SchedulingConstraint;
22
32
  export declare function consecutiveDays(maxDays: number): SchedulingConstraint;
23
33
  export declare function consecutiveNights(rule: ConsecutiveRule): SchedulingConstraint;
24
34
  export declare function shiftSuccession(forbidden: NonNullable<ConsecutiveRule['forbiddenSuccessions']>): SchedulingConstraint;
@@ -1 +1 @@
1
- {"version":3,"file":"consecutive.d.ts","sourceRoot":"","sources":["../../../src/scheduling/constraints/consecutive.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;GAgBG;AAEH,OAAO,KAAK,EAAE,eAAe,EAAe,oBAAoB,EAA8B,MAAM,UAAU,CAAC;AAI/G,eAAO,MAAM,oBAAoB,qDAAqD,CAAC;AAEvF,qDAAqD;AACrD,wBAAgB,sBAAsB,CAAC,IAAI,EAAE,eAAe,GAAG,oBAAoB,EAAE,CAQpF;AAED,wBAAgB,eAAe,CAAC,OAAO,EAAE,MAAM,GAAG,oBAAoB,CAiCrE;AAED,wBAAgB,iBAAiB,CAAC,IAAI,EAAE,eAAe,GAAG,oBAAoB,CAqE7E;AAED,wBAAgB,eAAe,CAAC,SAAS,EAAE,WAAW,CAAC,eAAe,CAAC,sBAAsB,CAAC,CAAC,GAAG,oBAAoB,CA6DrH"}
1
+ {"version":3,"file":"consecutive.d.ts","sourceRoot":"","sources":["../../../src/scheduling/constraints/consecutive.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;GAgBG;AAEH,OAAO,KAAK,EAAE,eAAe,EAAe,oBAAoB,EAA8B,MAAM,UAAU,CAAC;AAI/G,eAAO,MAAM,oBAAoB,qDAAqD,CAAC;AAEvF,qDAAqD;AACrD,wBAAgB,sBAAsB,CAAC,IAAI,EAAE,eAAe,GAAG,oBAAoB,EAAE,CASpF;AAED;;;;;;;;GAQG;AACH,wBAAgB,mBAAmB,CAAC,WAAW,EAAE,MAAM,GAAG,oBAAoB,CAiC7E;AAwBD,wBAAgB,eAAe,CAAC,OAAO,EAAE,MAAM,GAAG,oBAAoB,CAiCrE;AAED,wBAAgB,iBAAiB,CAAC,IAAI,EAAE,eAAe,GAAG,oBAAoB,CAqE7E;AAED,wBAAgB,eAAe,CAAC,SAAS,EAAE,WAAW,CAAC,eAAe,CAAC,sBAAsB,CAAC,CAAC,GAAG,oBAAoB,CA6DrH"}
@@ -17,7 +17,7 @@
17
17
  * minimum.
18
18
  */
19
19
  Object.defineProperty(exports, "__esModule", { value: true });
20
- exports.shiftSuccession = exports.consecutiveNights = exports.consecutiveDays = exports.consecutiveConstraints = exports.CONSECUTIVE_CITATION = void 0;
20
+ exports.shiftSuccession = exports.consecutiveNights = exports.consecutiveDays = exports.consecutiveWeekends = exports.consecutiveConstraints = exports.CONSECUTIVE_CITATION = void 0;
21
21
  const support_1 = require("./support");
22
22
  exports.CONSECUTIVE_CITATION = 'National working-time law / collective agreement';
23
23
  /** Every sequence constraint the rule configures. */
@@ -28,11 +28,74 @@ function consecutiveConstraints(rule) {
28
28
  if (rule.maxNightShifts !== undefined || rule.restAfterNightBlockMinutes !== undefined) {
29
29
  out.push(consecutiveNights(rule));
30
30
  }
31
+ if (rule.maxConsecutiveWeekends !== undefined)
32
+ out.push(consecutiveWeekends(rule.maxConsecutiveWeekends));
31
33
  if (rule.forbiddenSuccessions?.length)
32
34
  out.push(shiftSuccession(rule.forbiddenSuccessions));
33
35
  return out;
34
36
  }
35
37
  exports.consecutiveConstraints = consecutiveConstraints;
38
+ /**
39
+ * Weekends in a row.
40
+ *
41
+ * "Every second weekend off" — the term most often negotiated and the one a
42
+ * count cannot hold. Weekends are keyed by the Saturday that opens them, so a
43
+ * Saturday and the Sunday after it are one weekend; keying by week number would
44
+ * split a weekend across a year boundary and keying by day would make every
45
+ * ordinary weekend a run of two.
46
+ */
47
+ function consecutiveWeekends(maxWeekends) {
48
+ return (0, support_1.fromVerdict)({
49
+ id: 'consecutive-weekends',
50
+ hardness: 'hard',
51
+ weight: 1,
52
+ citation: exports.CONSECUTIVE_CITATION,
53
+ verdict(state, pair) {
54
+ const inst = (0, support_1.instanceOf)(state, pair);
55
+ if (!inst)
56
+ return (0, support_1.pass)('consecutive-weekends', 'unknown shift');
57
+ const timeline = (0, support_1.timelineFor)(state, pair.employeeId);
58
+ const probe = { ...(0, support_1.rangeOf)(inst), id: (0, support_1.entryIdOf)(pair), workingMinutes: inst.workingMinutes };
59
+ const clock = state.ctx.clock;
60
+ return timeline.withEntry(probe, (t) => {
61
+ const run = t.longestConsecutiveWeekends((minute) => weekendKey(clock, minute));
62
+ if (run > maxWeekends) {
63
+ return (0, support_1.fail)('consecutive-weekends', 'hard', `employee "${pair.employeeId}" would work ${run} weekends in a row, over the ${maxWeekends} allowed`, { actual: run, required: maxWeekends, unit: 'count', citation: exports.CONSECUTIVE_CITATION });
64
+ }
65
+ return (0, support_1.pass)('consecutive-weekends', `${run} weekends in a row, within the ${maxWeekends} allowed`, {
66
+ actual: run,
67
+ required: maxWeekends,
68
+ unit: 'count',
69
+ citation: exports.CONSECUTIVE_CITATION,
70
+ });
71
+ });
72
+ },
73
+ });
74
+ }
75
+ exports.consecutiveWeekends = consecutiveWeekends;
76
+ /**
77
+ * Which weekend a minute belongs to, as a consecutive ordinal, or `null` for a
78
+ * weekday.
79
+ *
80
+ * Resolved to the Saturday that opens the weekend first — a Sunday belongs to
81
+ * the weekend whose Saturday was the day before, so an ordinary weekend is one
82
+ * weekend rather than two — and then divided into weeks, so that successive
83
+ * weekends differ by exactly one and the run check is a plain `+ 1`.
84
+ *
85
+ * The division is safe at any period alignment and before the period starts:
86
+ * Saturdays are always seven days apart, so integer division by seven yields
87
+ * consecutive ordinals wherever the period begins, and `Math.floor` carries
88
+ * that through the negative indices history occupies.
89
+ */
90
+ function weekendKey(clock, minute) {
91
+ const weekday = clock.weekdayOfMinute(minute);
92
+ const dayIndex = clock.dayIndexOfMinute(minute);
93
+ if (weekday === 6)
94
+ return Math.floor(dayIndex / 7);
95
+ if (weekday === 7)
96
+ return Math.floor((dayIndex - 1) / 7);
97
+ return null;
98
+ }
36
99
  function consecutiveDays(maxDays) {
37
100
  return (0, support_1.fromVerdict)({
38
101
  id: 'consecutive-days',
@@ -1 +1 @@
1
- {"version":3,"file":"contract.d.ts","sourceRoot":"","sources":["../../../src/scheduling/constraints/contract.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AAEH,OAAO,KAAK,EAAoC,oBAAoB,EAAE,MAAM,UAAU,CAAC;AAGvF,eAAO,MAAM,uBAAuB,yEAAyE,CAAC;AAE9G,wBAAgB,cAAc,IAAI,oBAAoB,CAmKrD"}
1
+ {"version":3,"file":"contract.d.ts","sourceRoot":"","sources":["../../../src/scheduling/constraints/contract.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AAEH,OAAO,KAAK,EAAoC,oBAAoB,EAAE,MAAM,UAAU,CAAC;AAGvF,eAAO,MAAM,uBAAuB,yEAAyE,CAAC;AAE9G,wBAAgB,cAAc,IAAI,oBAAoB,CA8KrD"}
@@ -28,12 +28,18 @@ function contractLimits() {
28
28
  weight: 1,
29
29
  prune(ctx, eligibility) {
30
30
  for (const [employeeId, instances] of eligibility) {
31
- const endDate = ctx.employeeById.get(employeeId)?.contract?.endDate;
32
- if (!endDate)
31
+ const contract = ctx.employeeById.get(employeeId)?.contract;
32
+ if (!contract?.startDate && !contract?.endDate)
33
33
  continue;
34
34
  for (const instanceId of [...instances]) {
35
35
  const inst = ctx.instanceById.get(instanceId);
36
- if (inst && inst.date > endDate)
36
+ if (!inst)
37
+ continue;
38
+ // Both ends, one rule: a shift before somebody joins is as
39
+ // unworkable as one after they leave.
40
+ if (contract.endDate && inst.date > contract.endDate)
41
+ instances.delete(instanceId);
42
+ else if (contract.startDate && inst.date < contract.startDate)
37
43
  instances.delete(instanceId);
38
44
  }
39
45
  }
@@ -46,6 +52,9 @@ function contractLimits() {
46
52
  if (contract.endDate && inst.date > contract.endDate) {
47
53
  return (0, support_1.fail)('contract', 'hard', `employee "${pair.employeeId}"'s contract ends ${contract.endDate}, before "${inst.id}"`);
48
54
  }
55
+ if (contract.startDate && inst.date < contract.startDate) {
56
+ return (0, support_1.fail)('contract', 'hard', `employee "${pair.employeeId}"'s contract starts ${contract.startDate}, after "${inst.id}"`);
57
+ }
49
58
  const timeline = (0, support_1.timelineFor)(state, pair.employeeId);
50
59
  const probe = {
51
60
  start: inst.startMinute,
@@ -1 +1 @@
1
- {"version":3,"file":"cost.d.ts","sourceRoot":"","sources":["../../../src/scheduling/constraints/cost.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,KAAK,EAAkB,oBAAoB,EAAe,MAAM,UAAU,CAAC;AAGlF,wBAAgB,aAAa,CAAC,aAAa,EAAE,MAAM,GAAG,oBAAoB,CAuBzE"}
1
+ {"version":3,"file":"cost.d.ts","sourceRoot":"","sources":["../../../src/scheduling/constraints/cost.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAGH,OAAO,KAAK,EAAkB,oBAAoB,EAAe,MAAM,UAAU,CAAC;AAGlF,wBAAgB,aAAa,CAAC,aAAa,EAAE,MAAM,GAAG,oBAAoB,CAuBzE"}
@@ -16,6 +16,7 @@
16
16
  */
17
17
  Object.defineProperty(exports, "__esModule", { value: true });
18
18
  exports.costObjective = void 0;
19
+ const support_1 = require("./support");
19
20
  const cost_1 = require("../cost");
20
21
  function costObjective(weightPerEuro) {
21
22
  return {
@@ -56,9 +57,9 @@ function pairCostCents(state, pair) {
56
57
  return 0;
57
58
  const worked = state.minutesByEmployee.get(pair.employeeId) ?? 0;
58
59
  if (!state.isAssigned(pair.employeeId, pair.shiftInstanceId)) {
59
- return (0, cost_1.marginalCostCents)(inst, employee, worked, state.ctx.rules.engagement);
60
+ return (0, cost_1.marginalCostCents)(inst, employee, worked, (0, support_1.rulesFor)(state.ctx, employee.id).engagement);
60
61
  }
61
- const base = (0, cost_1.shiftCostCents)(inst, employee.cost, state.ctx.rules.engagement);
62
+ const base = (0, cost_1.shiftCostCents)(inst, employee.cost, (0, support_1.rulesFor)(state.ctx, employee.id).engagement);
62
63
  const surcharge = (0, cost_1.overtimeSurchargeCents)(worked, employee.cost);
63
64
  const share = worked > 0 ? (surcharge * inst.workingMinutes) / worked : 0;
64
65
  return base + share;
@@ -0,0 +1,5 @@
1
+ import type { SchedulingConstraint, WorkingTimeRules } from '../types';
2
+ import { type DefaultConstraintOptions } from './constraint';
3
+ /** Rule families are instantiated once per effective configuration, then dispatched by employee. */
4
+ export declare function scopeEmployeeConstraints(options: DefaultConstraintOptions, rulesByEmployee: Map<string, WorkingTimeRules>): SchedulingConstraint[];
5
+ //# sourceMappingURL=employee-scope.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"employee-scope.d.ts","sourceRoot":"","sources":["../../../src/scheduling/constraints/employee-scope.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAgC,oBAAoB,EAAe,gBAAgB,EAAE,MAAM,UAAU,CAAC;AAClH,OAAO,EAA4B,KAAK,wBAAwB,EAAE,MAAM,cAAc,CAAC;AASvF,oGAAoG;AACpG,wBAAgB,wBAAwB,CACpC,OAAO,EAAE,wBAAwB,EACjC,eAAe,EAAE,GAAG,CAAC,MAAM,EAAE,gBAAgB,CAAC,GAC/C,oBAAoB,EAAE,CAwJxB"}