assignment-user-matcher 1.15.0 → 1.16.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +378 -9
- package/dist/index.d.ts +5 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +6 -1
- package/dist/learning/atomic-ingestion.d.ts +11 -0
- package/dist/learning/atomic-ingestion.d.ts.map +1 -0
- package/dist/learning/atomic-ingestion.js +187 -0
- package/dist/learning/auto-weights.d.ts +13 -2
- package/dist/learning/auto-weights.d.ts.map +1 -1
- package/dist/learning/auto-weights.js +203 -35
- package/dist/learning/features.d.ts +5 -3
- package/dist/learning/features.d.ts.map +1 -1
- package/dist/learning/features.js +105 -4
- package/dist/learning/policy.d.ts +57 -0
- package/dist/learning/policy.d.ts.map +1 -0
- package/dist/learning/policy.js +71 -0
- package/dist/managers/LearningManager.d.ts +312 -35
- package/dist/managers/LearningManager.d.ts.map +1 -1
- package/dist/managers/LearningManager.js +1006 -168
- package/dist/matcher.class.d.ts +98 -11
- package/dist/matcher.class.d.ts.map +1 -1
- package/dist/matcher.class.js +247 -40
- package/dist/scheduling/constraints/cost.d.ts.map +1 -1
- package/dist/scheduling/constraints/cost.js +3 -2
- package/dist/scheduling/constraints/employee-scope.d.ts +5 -0
- package/dist/scheduling/constraints/employee-scope.d.ts.map +1 -0
- package/dist/scheduling/constraints/employee-scope.js +157 -0
- package/dist/scheduling/constraints/notice.d.ts.map +1 -1
- package/dist/scheduling/constraints/notice.js +8 -5
- package/dist/scheduling/constraints/rest-days.d.ts.map +1 -1
- package/dist/scheduling/constraints/rest-days.js +6 -6
- package/dist/scheduling/cost.d.ts.map +1 -1
- package/dist/scheduling/cost.js +2 -1
- package/dist/scheduling/engine/construction.d.ts +11 -3
- package/dist/scheduling/engine/construction.d.ts.map +1 -1
- package/dist/scheduling/engine/construction.js +31 -6
- package/dist/scheduling/engine/objective.d.ts +4 -4
- package/dist/scheduling/engine/objective.d.ts.map +1 -1
- package/dist/scheduling/engine/objective.js +12 -4
- package/dist/scheduling/engine/propagation.js +2 -1
- package/dist/scheduling/engine/search.d.ts +1 -0
- package/dist/scheduling/engine/search.d.ts.map +1 -1
- package/dist/scheduling/engine/search.js +1 -1
- package/dist/scheduling/engine/state.d.ts.map +1 -1
- package/dist/scheduling/engine/state.js +4 -0
- package/dist/scheduling/index.d.ts +1 -1
- package/dist/scheduling/index.d.ts.map +1 -1
- package/dist/scheduling/model.d.ts +1 -1
- package/dist/scheduling/model.d.ts.map +1 -1
- package/dist/scheduling/model.js +184 -42
- package/dist/scheduling/operations.d.ts +4 -0
- package/dist/scheduling/operations.d.ts.map +1 -1
- package/dist/scheduling/operations.js +36 -16
- package/dist/scheduling/provenance.d.ts +1 -1
- package/dist/scheduling/provenance.d.ts.map +1 -1
- package/dist/scheduling/provenance.js +16 -2
- package/dist/scheduling/scheduler.class.d.ts +1 -1
- package/dist/scheduling/scheduler.class.d.ts.map +1 -1
- package/dist/scheduling/scheduler.class.js +5 -3
- package/dist/scheduling/time.d.ts +2 -0
- package/dist/scheduling/time.d.ts.map +1 -1
- package/dist/scheduling/time.js +26 -1
- package/dist/scheduling/types.d.ts +78 -3
- package/dist/scheduling/types.d.ts.map +1 -1
- package/dist/types/matcher.d.ts +309 -4
- package/dist/types/matcher.d.ts.map +1 -1
- package/dist/utils/keys.d.ts +12 -2
- package/dist/utils/keys.d.ts.map +1 -1
- package/dist/utils/keys.js +35 -2
- package/package.json +2 -1
package/dist/matcher.class.js
CHANGED
|
@@ -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
|
|
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
|
|
2236
|
-
|
|
2237
|
-
//
|
|
2238
|
-
|
|
2239
|
-
|
|
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 +
|
|
2244
|
-
eligible.push({
|
|
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
|
-
|
|
2259
|
-
|
|
2260
|
-
|
|
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({
|
|
2263
|
-
|
|
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
|
-
*
|
|
2458
|
-
*
|
|
2459
|
-
*
|
|
2460
|
-
*
|
|
2461
|
-
*
|
|
2462
|
-
*
|
|
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
|
-
|
|
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
|
-
|
|
2926
|
-
|
|
2927
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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({
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cost.d.ts","sourceRoot":"","sources":["../../../src/scheduling/constraints/cost.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;
|
|
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.
|
|
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.
|
|
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"}
|
|
@@ -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;
|