assignment-user-matcher 1.15.1 → 1.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. package/README.md +362 -8
  2. package/dist/index.d.ts +4 -2
  3. package/dist/index.d.ts.map +1 -1
  4. package/dist/index.js +6 -1
  5. package/dist/learning/atomic-ingestion.d.ts +11 -0
  6. package/dist/learning/atomic-ingestion.d.ts.map +1 -0
  7. package/dist/learning/atomic-ingestion.js +187 -0
  8. package/dist/learning/auto-weights.d.ts +13 -2
  9. package/dist/learning/auto-weights.d.ts.map +1 -1
  10. package/dist/learning/auto-weights.js +203 -35
  11. package/dist/learning/features.d.ts +5 -3
  12. package/dist/learning/features.d.ts.map +1 -1
  13. package/dist/learning/features.js +105 -4
  14. package/dist/learning/policy.d.ts +57 -0
  15. package/dist/learning/policy.d.ts.map +1 -0
  16. package/dist/learning/policy.js +71 -0
  17. package/dist/managers/LearningManager.d.ts +312 -35
  18. package/dist/managers/LearningManager.d.ts.map +1 -1
  19. package/dist/managers/LearningManager.js +1006 -168
  20. package/dist/matcher.class.d.ts +98 -11
  21. package/dist/matcher.class.d.ts.map +1 -1
  22. package/dist/matcher.class.js +247 -40
  23. package/dist/scheduling/constraints/cost.d.ts.map +1 -1
  24. package/dist/scheduling/constraints/cost.js +3 -2
  25. package/dist/scheduling/constraints/employee-scope.d.ts +5 -0
  26. package/dist/scheduling/constraints/employee-scope.d.ts.map +1 -0
  27. package/dist/scheduling/constraints/employee-scope.js +157 -0
  28. package/dist/scheduling/constraints/notice.d.ts.map +1 -1
  29. package/dist/scheduling/constraints/notice.js +8 -5
  30. package/dist/scheduling/constraints/rest-days.d.ts.map +1 -1
  31. package/dist/scheduling/constraints/rest-days.js +6 -6
  32. package/dist/scheduling/cost.d.ts.map +1 -1
  33. package/dist/scheduling/cost.js +2 -1
  34. package/dist/scheduling/engine/objective.d.ts +4 -4
  35. package/dist/scheduling/engine/objective.d.ts.map +1 -1
  36. package/dist/scheduling/engine/objective.js +12 -4
  37. package/dist/scheduling/engine/propagation.js +2 -1
  38. package/dist/scheduling/engine/search.d.ts +1 -0
  39. package/dist/scheduling/engine/search.d.ts.map +1 -1
  40. package/dist/scheduling/engine/search.js +1 -1
  41. package/dist/scheduling/engine/state.d.ts.map +1 -1
  42. package/dist/scheduling/engine/state.js +4 -0
  43. package/dist/scheduling/model.d.ts +1 -1
  44. package/dist/scheduling/model.d.ts.map +1 -1
  45. package/dist/scheduling/model.js +45 -31
  46. package/dist/scheduling/operations.d.ts +4 -0
  47. package/dist/scheduling/operations.d.ts.map +1 -1
  48. package/dist/scheduling/operations.js +36 -16
  49. package/dist/scheduling/provenance.d.ts +1 -1
  50. package/dist/scheduling/provenance.d.ts.map +1 -1
  51. package/dist/scheduling/provenance.js +16 -2
  52. package/dist/scheduling/scheduler.class.d.ts +1 -1
  53. package/dist/scheduling/scheduler.class.d.ts.map +1 -1
  54. package/dist/scheduling/scheduler.class.js +5 -3
  55. package/dist/scheduling/time.d.ts +2 -0
  56. package/dist/scheduling/time.d.ts.map +1 -1
  57. package/dist/scheduling/time.js +26 -1
  58. package/dist/scheduling/types.d.ts +12 -3
  59. package/dist/scheduling/types.d.ts.map +1 -1
  60. package/dist/types/matcher.d.ts +309 -4
  61. package/dist/types/matcher.d.ts.map +1 -1
  62. package/dist/utils/keys.d.ts +12 -2
  63. package/dist/utils/keys.d.ts.map +1 -1
  64. package/dist/utils/keys.js +35 -2
  65. package/package.json +2 -1
@@ -22,11 +22,82 @@ function cosineSimilarity(a, b) {
22
22
  return dot / (Math.sqrt(normA) * Math.sqrt(normB));
23
23
  }
24
24
  exports.cosineSimilarity = cosineSimilarity;
25
+ /**
26
+ * Mean of a per-tag estimate over the assignment's tags, falling back to the
27
+ * worker's overall estimate, then to `undefined` (unknown, not zero).
28
+ */
29
+ function tagMean(perTag, tags, overall) {
30
+ if (perTag) {
31
+ let sum = 0;
32
+ let n = 0;
33
+ for (const tag of tags) {
34
+ const value = perTag[tag];
35
+ if (typeof value === 'number' && Number.isFinite(value)) {
36
+ sum += value;
37
+ n++;
38
+ }
39
+ }
40
+ if (n > 0)
41
+ return sum / n;
42
+ }
43
+ return overall;
44
+ }
45
+ /**
46
+ * Worker-side and interaction features, emitted only when the caller
47
+ * supplied batch-loaded performance aggregates.
48
+ *
49
+ * These are what make two workers with identical declared tags
50
+ * distinguishable: without them the feature vector for a given assignment is
51
+ * the same for every eligible worker, and the model has nothing to learn
52
+ * about *who* should get the work.
53
+ *
54
+ * Estimates are pre-shrunk toward the team prior by the caller, so a worker
55
+ * with no history reads as average rather than as a failure — an
56
+ * unjustifiably pessimistic estimate is how a new worker starves.
57
+ */
58
+ function addPerformanceFeatures(features, assignmentTags, performance, context, urgency, difficulty, complexity) {
59
+ const accept = tagMean(performance.acceptanceRate, assignmentTags, performance.overallAcceptanceRate);
60
+ if (accept !== undefined)
61
+ features['perf:accept'] = accept;
62
+ const success = tagMean(performance.successRate, assignmentTags, performance.overallSuccessRate);
63
+ if (success !== undefined)
64
+ features['perf:success'] = success;
65
+ // Sample support is its own feature: the model can learn how much to
66
+ // trust the rate above rather than treating a one-sample estimate and a
67
+ // thousand-sample estimate as the same number.
68
+ const attempts = tagMean(performance.attempts, assignmentTags, undefined);
69
+ if (attempts !== undefined)
70
+ features['perf:support'] = Math.min(1, attempts / 20);
71
+ // Speed relative to the team's own mean handling time — self-scaling, so
72
+ // no absolute duration constant has to be invented.
73
+ const handling = tagMean(performance.handlingTimeMs, assignmentTags, undefined);
74
+ const reference = context.priors?.handlingTimeMs;
75
+ let speed;
76
+ if (handling !== undefined && reference !== undefined && reference > 0) {
77
+ speed = Math.max(0, Math.min(1, 1 - handling / (2 * reference)));
78
+ features['perf:speed'] = speed;
79
+ features['perf:speedKnown'] = 1;
80
+ }
81
+ if (typeof performance.backlog === 'number' &&
82
+ typeof performance.backlogLimit === 'number' &&
83
+ performance.backlogLimit > 0) {
84
+ features['load:backlog'] = Math.min(1, performance.backlog / performance.backlogLimit);
85
+ }
86
+ // Interactions the linear model cannot represent on its own.
87
+ if (urgency !== undefined && speed !== undefined)
88
+ features['x:urgency*speed'] = urgency * speed;
89
+ if (difficulty !== undefined && success !== undefined)
90
+ features['x:difficulty*success'] = difficulty * success;
91
+ if (features['load:backlog'] !== undefined)
92
+ features['x:load*complexity'] = features['load:backlog'] * complexity;
93
+ }
25
94
  /**
26
95
  * Default feature extractor: tag matches, normalized skill weights,
27
- * tag-overlap ratio, optional embedding similarity, and SLA urgency.
96
+ * tag-overlap ratio, optional embedding similarity, SLA urgency, and —
97
+ * when performance aggregates are supplied — worker-side outcome rates,
98
+ * workload and their interactions.
28
99
  */
29
- function extractMatchFeatures(user, assignment, slaTightnessReferenceMs = 3600000) {
100
+ function extractMatchFeatures(user, assignment, slaTightnessReferenceMs = 3600000, context) {
30
101
  const features = { bias: 1 };
31
102
  const userTags = new Set(user.tags || []);
32
103
  const assignmentTags = assignment.tags || [];
@@ -52,11 +123,41 @@ function extractMatchFeatures(user, assignment, slaTightnessReferenceMs = 360000
52
123
  }
53
124
  // SLA urgency: assignment-side only (user-invariant), so custom
54
125
  // extractors and existing learned weights are unaffected.
55
- const completeWithinMs = Number(assignment.sla?.completeWithinMs);
126
+ const raw = assignment;
127
+ const completeWithinMs = Number(raw.sla?.completeWithinMs);
128
+ const reference = Number.isFinite(slaTightnessReferenceMs) && slaTightnessReferenceMs > 0 ? slaTightnessReferenceMs : 3600000;
129
+ let urgency;
56
130
  if (Number.isFinite(completeWithinMs) && completeWithinMs > 0) {
57
131
  features['sla:hasDeadline'] = 1;
58
- const reference = Number.isFinite(slaTightnessReferenceMs) && slaTightnessReferenceMs > 0 ? slaTightnessReferenceMs : 3600000;
59
132
  features['sla:tightness'] = 1 - Math.min(1, completeWithinMs / reference);
133
+ urgency = features['sla:tightness'];
134
+ }
135
+ // Time actually left, not the duration originally configured: an
136
+ // assignment with a 1h deadline that has been queued for 55 minutes is
137
+ // urgent, and the configured duration alone cannot say so. Only computed
138
+ // when the caller anchors the pass with an explicit `now`.
139
+ const now = context?.now;
140
+ const enqueuedAt = Number(raw._enqueuedAt);
141
+ if (now !== undefined && Number.isFinite(completeWithinMs) && completeWithinMs > 0 && Number.isFinite(enqueuedAt)) {
142
+ const remaining = enqueuedAt + completeWithinMs - now;
143
+ const fraction = Math.max(0, Math.min(1, remaining / completeWithinMs));
144
+ features['sla:remainingFraction'] = fraction;
145
+ urgency = 1 - fraction;
146
+ features['sla:urgency'] = urgency;
147
+ }
148
+ if (context?.performance) {
149
+ const difficultyRaw = Number(raw.difficulty);
150
+ const difficulty = Number.isFinite(difficultyRaw) ? Math.max(0, Math.min(1, difficultyRaw)) : undefined;
151
+ if (difficulty !== undefined)
152
+ features.difficulty = difficulty;
153
+ // Tag count is a crude but always-available complexity proxy; an
154
+ // explicit `complexity` on the assignment overrides it.
155
+ const complexityRaw = Number(raw.complexity);
156
+ const complexity = Number.isFinite(complexityRaw)
157
+ ? Math.max(0, Math.min(1, complexityRaw))
158
+ : Math.min(1, assignmentTags.length / 5);
159
+ features.complexity = complexity;
160
+ addPerformanceFeatures(features, assignmentTags, context.performance, context, urgency, difficulty, complexity);
60
161
  }
61
162
  return features;
62
163
  }
@@ -0,0 +1,57 @@
1
+ /**
2
+ * Explicit selection policies for the learning layer.
3
+ *
4
+ * The point of a *named* policy is the propensity: off-policy evaluation
5
+ * (IPS, doubly-robust) needs the probability with which the logged action was
6
+ * actually taken. Adding independent random jitter to a score — the pre-1.16
7
+ * behaviour — perturbs the ranking without any recoverable probability, so
8
+ * the logs it produces cannot be evaluated offline at all.
9
+ *
10
+ * Selection of `k` items is modelled as `k` sequential conditional choices,
11
+ * each over the admissible set that remains. That is the only construction
12
+ * whose per-step probabilities multiply out to the joint probability of the
13
+ * chosen set, which is what a constrained top-k choice actually is.
14
+ *
15
+ * Pure module: no Redis, no clock, no global RNG.
16
+ */
17
+ /** One selected item together with the probability the policy chose it. */
18
+ export interface PolicyChoice<T> {
19
+ item: T;
20
+ /** Probability of this item being chosen at the step it was chosen */
21
+ propensity: number;
22
+ /** Size of the admissible set at that step */
23
+ candidateCount: number;
24
+ /** True when the step took the exploratory branch */
25
+ explored: boolean;
26
+ }
27
+ export interface EpsilonGreedyOptions {
28
+ /** Probability of the exploratory branch, in [0, 1] */
29
+ epsilon: number;
30
+ /** Random source returning values in [0, 1) */
31
+ rng: () => number;
32
+ /**
33
+ * Scores within this distance of the leader count as tied for greedy
34
+ * purposes, so a tie is shared rather than resolved by list order.
35
+ */
36
+ tieEpsilon?: number;
37
+ }
38
+ /**
39
+ * Epsilon-greedy selection of up to `k` items.
40
+ *
41
+ * At each step, with probability `1 - epsilon` the choice is uniform over the
42
+ * leaders (the best remaining score, plus anything within `tieEpsilon` of
43
+ * it), and otherwise uniform over the whole admissible set. So for a unique
44
+ * leader among `K` admissible items the leader's probability is
45
+ * `1 - epsilon + epsilon/K` and every other item's is `epsilon/K` — the
46
+ * identity the propensity logs are checked against.
47
+ *
48
+ * `epsilon: 0` degenerates to greedy, with a propensity of `1/G` over the
49
+ * tied leaders.
50
+ */
51
+ export declare function epsilonGreedySelect<T>(candidates: T[], scoreOf: (item: T) => number, k: number, options: EpsilonGreedyOptions): Array<PolicyChoice<T>>;
52
+ /**
53
+ * Greedy selection with tie sharing — epsilon-greedy at `epsilon = 0`, kept
54
+ * separate so callers can express "no exploration" without a magic number.
55
+ */
56
+ export declare function greedySelect<T>(candidates: T[], scoreOf: (item: T) => number, k: number, rng: () => number, tieEpsilon?: number): Array<PolicyChoice<T>>;
57
+ //# sourceMappingURL=policy.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"policy.d.ts","sourceRoot":"","sources":["../../src/learning/policy.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AAEH,2EAA2E;AAC3E,MAAM,WAAW,YAAY,CAAC,CAAC;IAC3B,IAAI,EAAE,CAAC,CAAC;IACR,sEAAsE;IACtE,UAAU,EAAE,MAAM,CAAC;IACnB,8CAA8C;IAC9C,cAAc,EAAE,MAAM,CAAC;IACvB,qDAAqD;IACrD,QAAQ,EAAE,OAAO,CAAC;CACrB;AAED,MAAM,WAAW,oBAAoB;IACjC,uDAAuD;IACvD,OAAO,EAAE,MAAM,CAAC;IAChB,+CAA+C;IAC/C,GAAG,EAAE,MAAM,MAAM,CAAC;IAClB;;;OAGG;IACH,UAAU,CAAC,EAAE,MAAM,CAAC;CACvB;AAED;;;;;;;;;;;;GAYG;AACH,wBAAgB,mBAAmB,CAAC,CAAC,EACjC,UAAU,EAAE,CAAC,EAAE,EACf,OAAO,EAAE,CAAC,IAAI,EAAE,CAAC,KAAK,MAAM,EAC5B,CAAC,EAAE,MAAM,EACT,OAAO,EAAE,oBAAoB,GAC9B,KAAK,CAAC,YAAY,CAAC,CAAC,CAAC,CAAC,CAiCxB;AAED;;;GAGG;AACH,wBAAgB,YAAY,CAAC,CAAC,EAC1B,UAAU,EAAE,CAAC,EAAE,EACf,OAAO,EAAE,CAAC,IAAI,EAAE,CAAC,KAAK,MAAM,EAC5B,CAAC,EAAE,MAAM,EACT,GAAG,EAAE,MAAM,MAAM,EACjB,UAAU,SAAI,GACf,KAAK,CAAC,YAAY,CAAC,CAAC,CAAC,CAAC,CAExB"}
@@ -0,0 +1,71 @@
1
+ "use strict";
2
+ /**
3
+ * Explicit selection policies for the learning layer.
4
+ *
5
+ * The point of a *named* policy is the propensity: off-policy evaluation
6
+ * (IPS, doubly-robust) needs the probability with which the logged action was
7
+ * actually taken. Adding independent random jitter to a score — the pre-1.16
8
+ * behaviour — perturbs the ranking without any recoverable probability, so
9
+ * the logs it produces cannot be evaluated offline at all.
10
+ *
11
+ * Selection of `k` items is modelled as `k` sequential conditional choices,
12
+ * each over the admissible set that remains. That is the only construction
13
+ * whose per-step probabilities multiply out to the joint probability of the
14
+ * chosen set, which is what a constrained top-k choice actually is.
15
+ *
16
+ * Pure module: no Redis, no clock, no global RNG.
17
+ */
18
+ Object.defineProperty(exports, "__esModule", { value: true });
19
+ exports.greedySelect = exports.epsilonGreedySelect = void 0;
20
+ /**
21
+ * Epsilon-greedy selection of up to `k` items.
22
+ *
23
+ * At each step, with probability `1 - epsilon` the choice is uniform over the
24
+ * leaders (the best remaining score, plus anything within `tieEpsilon` of
25
+ * it), and otherwise uniform over the whole admissible set. So for a unique
26
+ * leader among `K` admissible items the leader's probability is
27
+ * `1 - epsilon + epsilon/K` and every other item's is `epsilon/K` — the
28
+ * identity the propensity logs are checked against.
29
+ *
30
+ * `epsilon: 0` degenerates to greedy, with a propensity of `1/G` over the
31
+ * tied leaders.
32
+ */
33
+ function epsilonGreedySelect(candidates, scoreOf, k, options) {
34
+ const epsilon = Math.max(0, Math.min(1, options.epsilon));
35
+ const tieEpsilon = options.tieEpsilon ?? 0;
36
+ const rng = options.rng;
37
+ const remaining = [...candidates];
38
+ const chosen = [];
39
+ while (chosen.length < k && remaining.length > 0) {
40
+ const K = remaining.length;
41
+ let best = -Infinity;
42
+ for (const item of remaining) {
43
+ const score = scoreOf(item);
44
+ if (score > best)
45
+ best = score;
46
+ }
47
+ const leaders = [];
48
+ for (let i = 0; i < K; i++) {
49
+ if (best - scoreOf(remaining[i]) <= tieEpsilon)
50
+ leaders.push(i);
51
+ }
52
+ const G = leaders.length;
53
+ const explored = epsilon > 0 && rng() < epsilon;
54
+ const index = explored ? Math.min(K - 1, Math.floor(rng() * K)) : leaders[Math.min(G - 1, Math.floor(rng() * G))];
55
+ const isLeader = leaders.includes(index);
56
+ // p(a) = (1 - eps) * [a is a leader] / G + eps / K
57
+ const propensity = (isLeader ? (1 - epsilon) / G : 0) + epsilon / K || 1 / K;
58
+ chosen.push({ item: remaining[index], propensity, candidateCount: K, explored });
59
+ remaining.splice(index, 1);
60
+ }
61
+ return chosen;
62
+ }
63
+ exports.epsilonGreedySelect = epsilonGreedySelect;
64
+ /**
65
+ * Greedy selection with tie sharing — epsilon-greedy at `epsilon = 0`, kept
66
+ * separate so callers can express "no exploration" without a magic number.
67
+ */
68
+ function greedySelect(candidates, scoreOf, k, rng, tieEpsilon = 0) {
69
+ return epsilonGreedySelect(candidates, scoreOf, k, { epsilon: 0, rng, tieEpsilon });
70
+ }
71
+ exports.greedySelect = greedySelect;