assignment-user-matcher 1.6.0 → 1.8.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 (43) hide show
  1. package/README.md +177 -11
  2. package/dist/escalation/policy.d.ts +65 -0
  3. package/dist/escalation/policy.d.ts.map +1 -0
  4. package/dist/escalation/policy.js +120 -0
  5. package/dist/index.d.ts +2 -2
  6. package/dist/index.d.ts.map +1 -1
  7. package/dist/learning/auto-weights.d.ts +18 -8
  8. package/dist/learning/auto-weights.d.ts.map +1 -1
  9. package/dist/learning/auto-weights.js +120 -18
  10. package/dist/learning/features.d.ts +2 -2
  11. package/dist/learning/features.d.ts.map +1 -1
  12. package/dist/learning/features.js +10 -2
  13. package/dist/managers/LearningManager.d.ts +7 -0
  14. package/dist/managers/LearningManager.d.ts.map +1 -1
  15. package/dist/managers/LearningManager.js +85 -11
  16. package/dist/managers/WorkflowManager.d.ts +10 -0
  17. package/dist/managers/WorkflowManager.d.ts.map +1 -1
  18. package/dist/managers/WorkflowManager.js +57 -2
  19. package/dist/matcher.class.d.ts +141 -4
  20. package/dist/matcher.class.d.ts.map +1 -1
  21. package/dist/matcher.class.js +801 -27
  22. package/dist/queries/pagination.d.ts +5 -0
  23. package/dist/queries/pagination.d.ts.map +1 -1
  24. package/dist/queries/pagination.js +13 -1
  25. package/dist/scoring/match-score.d.ts +6 -0
  26. package/dist/scoring/match-score.d.ts.map +1 -1
  27. package/dist/scoring/match-score.js +17 -2
  28. package/dist/sla/policy.d.ts +49 -0
  29. package/dist/sla/policy.d.ts.map +1 -0
  30. package/dist/sla/policy.js +96 -0
  31. package/dist/tracing/decision-trace.d.ts.map +1 -1
  32. package/dist/tracing/decision-trace.js +4 -2
  33. package/dist/types/matcher.d.ts +395 -2
  34. package/dist/types/matcher.d.ts.map +1 -1
  35. package/dist/utils/keys.d.ts +8 -0
  36. package/dist/utils/keys.d.ts.map +1 -1
  37. package/dist/utils/keys.js +16 -0
  38. package/dist/workflow-builder.d.ts +22 -0
  39. package/dist/workflow-builder.d.ts.map +1 -1
  40. package/dist/workflow-builder.js +29 -0
  41. package/dist/workflow-validation.d.ts.map +1 -1
  42. package/dist/workflow-validation.js +32 -0
  43. package/package.json +2 -1
@@ -6,12 +6,118 @@ exports.DEFAULT_AUTO_WEIGHTS_OPTIONS = {
6
6
  vetoThreshold: -0.5,
7
7
  maxWeight: 100,
8
8
  explorationBonus: 0.5,
9
+ priorWeight: 50,
10
+ policy: 'ucb1',
11
+ confidenceZ: 1.96,
12
+ minTotalSamples: 0,
13
+ minSamplesForVeto: 5,
14
+ terminalOnlyTagStats: false,
9
15
  };
16
+ function resolveOptions(options) {
17
+ const maxWeight = options?.maxWeight ?? exports.DEFAULT_AUTO_WEIGHTS_OPTIONS.maxWeight;
18
+ return {
19
+ minSamples: options?.minSamples ?? exports.DEFAULT_AUTO_WEIGHTS_OPTIONS.minSamples,
20
+ vetoThreshold: options?.vetoThreshold ?? exports.DEFAULT_AUTO_WEIGHTS_OPTIONS.vetoThreshold,
21
+ maxWeight,
22
+ explorationBonus: options?.explorationBonus ?? exports.DEFAULT_AUTO_WEIGHTS_OPTIONS.explorationBonus,
23
+ policy: options?.policy ?? exports.DEFAULT_AUTO_WEIGHTS_OPTIONS.policy,
24
+ confidenceZ: options?.confidenceZ ?? exports.DEFAULT_AUTO_WEIGHTS_OPTIONS.confidenceZ,
25
+ minTotalSamples: options?.minTotalSamples ?? exports.DEFAULT_AUTO_WEIGHTS_OPTIONS.minTotalSamples,
26
+ minSamplesForVeto: options?.minSamplesForVeto ?? options?.minSamples ?? exports.DEFAULT_AUTO_WEIGHTS_OPTIONS.minSamples,
27
+ terminalOnlyTagStats: options?.terminalOnlyTagStats ?? exports.DEFAULT_AUTO_WEIGHTS_OPTIONS.terminalOnlyTagStats,
28
+ priorWeight: options?.priorWeight ?? Math.round(maxWeight / 2),
29
+ maxDeltaPerSync: options?.maxDeltaPerSync,
30
+ decayHalfLifeMs: options?.decayHalfLifeMs,
31
+ rng: options?.rng ?? Math.random,
32
+ };
33
+ }
34
+ function isManualTag(tag, existingWeights) {
35
+ return !!existingWeights && tag in existingWeights;
36
+ }
37
+ function canVeto(policy, stat, vetoScore, lcb, opts, existingWeights) {
38
+ const manual = isManualTag(stat.tag, existingWeights);
39
+ const effectiveMinSamples = manual ? opts.minSamplesForVeto : opts.minSamples;
40
+ if (stat.count < effectiveMinSamples)
41
+ return false;
42
+ if (policy === 'confidence') {
43
+ return lcb <= opts.vetoThreshold;
44
+ }
45
+ return vetoScore <= opts.vetoThreshold;
46
+ }
47
+ function tagScore(policy, stat, totalCount, opts) {
48
+ const mean = stat.meanReward;
49
+ const se = stat.standardError ?? 0;
50
+ if (policy === 'confidence') {
51
+ const z = opts.confidenceZ;
52
+ return { ucb: mean + z * se, lcb: mean - z * se, sample: mean };
53
+ }
54
+ if (policy === 'thompson') {
55
+ // Gaussian Thompson sample: mean + Z(rng) * se, where Z is the normal
56
+ // inverse CDF approximated by the Acklam/Bailey approximation.
57
+ const sample = se > 0 ? mean + acklamInverseNormal(opts.rng()) * se : mean;
58
+ return { ucb: sample, lcb: sample, sample };
59
+ }
60
+ // 'ucb1'
61
+ const ucb = mean + opts.explorationBonus * Math.sqrt(Math.log(totalCount + 1) / stat.count);
62
+ return { ucb, lcb: mean, sample: ucb };
63
+ }
64
+ function normalizedWeight(score, maxWeight) {
65
+ const normalized = (Math.min(Math.max(score, -1), 1) + 1) / 2;
66
+ return Math.max(1, Math.round(normalized * maxWeight));
67
+ }
68
+ /**
69
+ * Acklam/Bailey approximation of the standard-normal quantile function.
70
+ * Maps p in (0, 1) to a z-score. Used for Thompson sampling without pulling
71
+ * in a statistics dependency.
72
+ */
73
+ function acklamInverseNormal(p) {
74
+ if (p <= 0)
75
+ return -6;
76
+ if (p >= 1)
77
+ return 6;
78
+ const a1 = -39.6968302866538;
79
+ const a2 = 220.946098424521;
80
+ const a3 = -275.928510446969;
81
+ const a4 = 138.357751867269;
82
+ const a5 = -30.6647980661472;
83
+ const a6 = 2.50662827745924;
84
+ const b1 = -54.4760987982241;
85
+ const b2 = 161.585836858041;
86
+ const b3 = -155.698979859887;
87
+ const b4 = 66.8013118877197;
88
+ const b5 = -13.2806815528857;
89
+ const c1 = -0.00778489400243029;
90
+ const c2 = -0.322396458441136;
91
+ const c3 = -2.40075827716184;
92
+ const c4 = -2.54973253934373;
93
+ const c5 = 4.37466414146497;
94
+ const c6 = 2.93816398269878;
95
+ const d1 = 0.00778469570904146;
96
+ const d2 = 0.32246712907004;
97
+ const d3 = 2.445134137143;
98
+ const d4 = 3.75440866190742;
99
+ const pLow = 0.02425;
100
+ const pHigh = 1 - pLow;
101
+ let q;
102
+ let r;
103
+ if (p < pLow) {
104
+ q = Math.sqrt(-2 * Math.log(p));
105
+ return (((((c1 * q + c2) * q + c3) * q + c4) * q + c5) * q + c6) / ((((d1 * q + d2) * q + d3) * q + d4) * q + 1);
106
+ }
107
+ if (p <= pHigh) {
108
+ q = p - 0.5;
109
+ r = q * q;
110
+ return (((((((a1 * r + a2) * r + a3) * r + a4) * r + a5) * r + a6) * q) /
111
+ (((((b1 * r + b2) * r + b3) * r + b4) * r + b5) * r + 1));
112
+ }
113
+ q = Math.sqrt(-2 * Math.log(1 - p));
114
+ return -(((((c1 * q + c2) * q + c3) * q + c4) * q + c5) * q + c6) / ((((d1 * q + d2) * q + d3) * q + d4) * q + 1);
115
+ }
10
116
  /**
11
117
  * Synthesize a routingWeights map from per-tag reward statistics.
12
118
  *
13
119
  * @param stats per-user tag reward statistics (from learned outcomes)
14
- * @param options UCB policy tuning (merged with defaults)
120
+ * @param options synthesis policy and tuning (merged with defaults)
15
121
  * @param knownTags optional tags to include even without observations;
16
122
  * unobserved known tags receive the optimistic prior weight
17
123
  * @param existingWeights optional current routingWeights of the user;
@@ -19,37 +125,33 @@ exports.DEFAULT_AUTO_WEIGHTS_OPTIONS = {
19
125
  * tags instead of the flat `priorWeight` when provided
20
126
  */
21
127
  function synthesizeRoutingWeights(stats, options, knownTags, existingWeights) {
22
- const minSamples = options?.minSamples ?? exports.DEFAULT_AUTO_WEIGHTS_OPTIONS.minSamples;
23
- const vetoThreshold = options?.vetoThreshold ?? exports.DEFAULT_AUTO_WEIGHTS_OPTIONS.vetoThreshold;
24
- const maxWeight = options?.maxWeight ?? exports.DEFAULT_AUTO_WEIGHTS_OPTIONS.maxWeight;
25
- const explorationBonus = options?.explorationBonus ?? exports.DEFAULT_AUTO_WEIGHTS_OPTIONS.explorationBonus;
26
- const priorWeight = options?.priorWeight ?? Math.round(maxWeight / 2);
27
- const weights = {};
128
+ const opts = resolveOptions(options);
28
129
  const totalCount = stats.reduce((sum, s) => sum + s.count, 0);
130
+ if (opts.minTotalSamples > 0 && totalCount < opts.minTotalSamples) {
131
+ return {};
132
+ }
133
+ const weights = {};
29
134
  for (const stat of stats) {
30
- if (stat.count < minSamples) {
135
+ if (stat.count < opts.minSamples) {
31
136
  // Not enough evidence yet: use the existing weight as a warm
32
137
  // prior if available, otherwise fall back to the flat prior.
33
- weights[stat.tag] = existingWeights?.[stat.tag] ?? priorWeight;
138
+ weights[stat.tag] = existingWeights?.[stat.tag] ?? opts.priorWeight;
34
139
  continue;
35
140
  }
36
- // UCB1 score: mean reward + exploration bonus for under-sampled tags.
37
- const ucb = stat.meanReward + explorationBonus * Math.sqrt(Math.log(totalCount + 1) / stat.count);
38
- if (stat.meanReward <= vetoThreshold) {
39
- // Consistently bad on the evidence: hard veto (matcher treats
40
- // weight 0 as exclusion). The veto uses the raw mean so the
41
- // exploration bonus cannot keep a provably bad tag alive.
141
+ const { ucb, lcb, sample } = tagScore(opts.policy, stat, totalCount, opts);
142
+ const weightScore = opts.policy === 'thompson' ? sample : ucb;
143
+ const vetoScore = opts.policy === 'confidence' ? lcb : opts.policy === 'thompson' ? sample : stat.meanReward;
144
+ if (canVeto(opts.policy, stat, vetoScore, lcb, opts, existingWeights)) {
42
145
  weights[stat.tag] = 0;
43
146
  continue;
44
147
  }
45
148
  // Map score (clamped to [-1, 1]) onto [1, maxWeight].
46
- const normalized = (Math.min(Math.max(ucb, -1), 1) + 1) / 2;
47
- weights[stat.tag] = Math.max(1, Math.round(normalized * maxWeight));
149
+ weights[stat.tag] = normalizedWeight(weightScore, opts.maxWeight);
48
150
  }
49
151
  if (knownTags) {
50
152
  for (const tag of knownTags) {
51
153
  if (!(tag in weights))
52
- weights[tag] = existingWeights?.[tag] ?? priorWeight;
154
+ weights[tag] = existingWeights?.[tag] ?? opts.priorWeight;
53
155
  }
54
156
  }
55
157
  // Tags the user already had weights for are treated as implicitly known:
@@ -13,7 +13,7 @@ import type { User, LearningFeatures, LearningAssignmentContext } from '../types
13
13
  export declare function cosineSimilarity(a: number[], b: number[]): number;
14
14
  /**
15
15
  * Default feature extractor: tag matches, normalized skill weights,
16
- * tag-overlap ratio, and optional embedding similarity.
16
+ * tag-overlap ratio, optional embedding similarity, and SLA urgency.
17
17
  */
18
- export declare function extractMatchFeatures(user: User, assignment: LearningAssignmentContext): LearningFeatures;
18
+ export declare function extractMatchFeatures(user: User, assignment: LearningAssignmentContext, slaTightnessReferenceMs?: number): LearningFeatures;
19
19
  //# sourceMappingURL=features.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"features.d.ts","sourceRoot":"","sources":["../../src/learning/features.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,OAAO,KAAK,EAAE,IAAI,EAAE,gBAAgB,EAAE,yBAAyB,EAAE,MAAM,kBAAkB,CAAC;AAG1F;;;GAGG;AACH,wBAAgB,gBAAgB,CAAC,CAAC,EAAE,MAAM,EAAE,EAAE,CAAC,EAAE,MAAM,EAAE,GAAG,MAAM,CAYjE;AAED;;;GAGG;AACH,wBAAgB,oBAAoB,CAAC,IAAI,EAAE,IAAI,EAAE,UAAU,EAAE,yBAAyB,GAAG,gBAAgB,CA6BxG"}
1
+ {"version":3,"file":"features.d.ts","sourceRoot":"","sources":["../../src/learning/features.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,OAAO,KAAK,EAAE,IAAI,EAAE,gBAAgB,EAAE,yBAAyB,EAAE,MAAM,kBAAkB,CAAC;AAG1F;;;GAGG;AACH,wBAAgB,gBAAgB,CAAC,CAAC,EAAE,MAAM,EAAE,EAAE,CAAC,EAAE,MAAM,EAAE,GAAG,MAAM,CAYjE;AAED;;;GAGG;AACH,wBAAgB,oBAAoB,CAChC,IAAI,EAAE,IAAI,EACV,UAAU,EAAE,yBAAyB,EACrC,uBAAuB,GAAE,MAAgB,GAC1C,gBAAgB,CAuClB"}
@@ -24,9 +24,9 @@ function cosineSimilarity(a, b) {
24
24
  exports.cosineSimilarity = cosineSimilarity;
25
25
  /**
26
26
  * Default feature extractor: tag matches, normalized skill weights,
27
- * tag-overlap ratio, and optional embedding similarity.
27
+ * tag-overlap ratio, optional embedding similarity, and SLA urgency.
28
28
  */
29
- function extractMatchFeatures(user, assignment) {
29
+ function extractMatchFeatures(user, assignment, slaTightnessReferenceMs = 3600000) {
30
30
  const features = { bias: 1 };
31
31
  const userTags = new Set(user.tags || []);
32
32
  const assignmentTags = assignment.tags || [];
@@ -50,6 +50,14 @@ function extractMatchFeatures(user, assignment) {
50
50
  if (Array.isArray(user.embedding) && Array.isArray(assignment.embedding)) {
51
51
  features['emb:sim'] = cosineSimilarity(user.embedding, assignment.embedding);
52
52
  }
53
+ // SLA urgency: assignment-side only (user-invariant), so custom
54
+ // extractors and existing learned weights are unaffected.
55
+ const completeWithinMs = Number(assignment.sla?.completeWithinMs);
56
+ if (Number.isFinite(completeWithinMs) && completeWithinMs > 0) {
57
+ features['sla:hasDeadline'] = 1;
58
+ const reference = Number.isFinite(slaTightnessReferenceMs) && slaTightnessReferenceMs > 0 ? slaTightnessReferenceMs : 3600000;
59
+ features['sla:tightness'] = 1 - Math.min(1, completeWithinMs / reference);
60
+ }
53
61
  return features;
54
62
  }
55
63
  exports.extractMatchFeatures = extractMatchFeatures;
@@ -99,6 +99,11 @@ export declare class LearningManager {
99
99
  * Train the model directly with raw (features, reward) samples.
100
100
  * Enables offline/batch imports from external pipelines (data warehouses,
101
101
  * historical logs, post-processing jobs) without a live decision context.
102
+ *
103
+ * The model is loaded once and SGD is replayed locally, then the
104
+ * accumulated deltas are written in a single batched round trip —
105
+ * equivalent to per-sample updateModel calls when no concurrent writer
106
+ * interleaves, and orders of magnitude cheaper for bulk imports.
102
107
  */
103
108
  trainSamples(samples: LearningSample[]): Promise<number>;
104
109
  /**
@@ -107,6 +112,8 @@ export declare class LearningManager {
107
112
  * so high-throughput outcome streams scale without contention.
108
113
  */
109
114
  private updateTagStats;
115
+ /** True when the configured policy/decay needs reward variance/timestamps. */
116
+ private needsVarianceTracking;
110
117
  /** Per-user, per-tag reward statistics aggregated from observed outcomes */
111
118
  getUserTagStats(userId: string): Promise<LearningTagStat[]>;
112
119
  /** Users that have accumulated tag reward statistics */
@@ -1 +1 @@
1
- {"version":3,"file":"LearningManager.d.ts","sourceRoot":"","sources":["../../src/managers/LearningManager.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AACH,OAAO,KAAK,EACR,eAAe,EACf,gBAAgB,EAChB,eAAe,EACf,eAAe,EACf,sBAAsB,EACtB,qBAAqB,EACrB,eAAe,EACf,cAAc,EACd,aAAa,EACb,eAAe,EACf,yBAAyB,EAC5B,MAAM,kBAAkB,CAAC;AAC1B,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAGjD,eAAO,MAAM,wBAAwB,EAAE,eAMtC,CAAC;AAKF,MAAM,WAAW,sBAAsB;IACnC,uCAAuC;IACvC,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,sDAAsD;IACtD,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,6EAA6E;IAC7E,UAAU,CAAC,EAAE,OAAO,CAAC;IACrB,0EAA0E;IAC1E,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,4CAA4C;IAC5C,OAAO,CAAC,EAAE,OAAO,CAAC,eAAe,CAAC,CAAC;IACnC,+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,CAAC,YAAY,EAAE,MAAM,EAAE,OAAO,EAAE,eAAe,GAAG,OAAO,CAAC,OAAO,CAAC;IAIpF;;;OAGG;IACG,YAAY,CAAC,YAAY,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC;YAI5D,WAAW;IAiCzB,sEAAsE;YACxD,WAAW;IAezB,oEAAoE;IAC9D,UAAU,CAAC,YAAY,EAAE,MAAM,GAAG,OAAO,CAAC,qBAAqB,GAAG,IAAI,CAAC;IAU7E;;;;;OAKG;IACG,cAAc,CAAC,YAAY,EAAE,MAAM,EAAE,OAAO,EAAE,eAAe,GAAG,OAAO,CAAC,OAAO,CAAC;IAetF;;;;;;;;;OASG;IACG,YAAY,CAAC,OAAO,EAAE,cAAc,EAAE,GAAG,OAAO,CAAC,MAAM,CAAC;IAiC9D;;;;OAIG;YACW,cAAc;IAyB5B,8EAA8E;IAC9E,OAAO,CAAC,qBAAqB;IAK7B,4EAA4E;IACtE,eAAe,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,eAAe,EAAE,CAAC;IA8CjE,wDAAwD;IAClD,gBAAgB,IAAI,OAAO,CAAC,MAAM,EAAE,CAAC;IAI3C;;;;;;;;OAQG;IACG,wBAAwB,CAC1B,MAAM,EAAE,MAAM,EACd,SAAS,CAAC,EAAE,MAAM,EAAE,EACpB,eAAe,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GACzC,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAMlC,oCAAoC;IAC9B,QAAQ,IAAI,OAAO,CAAC,aAAa,CAAC;IAaxC,mEAAmE;IAC7D,UAAU,IAAI,OAAO,CAAC,IAAI,CAAC;CAcpC"}
@@ -110,7 +110,7 @@ class LearningManager {
110
110
  if (!decision)
111
111
  return false;
112
112
  await this.updateModel(decision.features, reward);
113
- await this.updateTagStats(decision.userId, decision.tags, reward);
113
+ await this.updateTagStats(decision.userId, decision.tags, reward, terminal);
114
114
  if (terminal) {
115
115
  // Archive as episode so external post-processing feedback can
116
116
  // still reach the model after the assignment is closed.
@@ -174,50 +174,122 @@ class LearningManager {
174
174
  reward += value * weight;
175
175
  }
176
176
  await this.updateModel(context.features, reward);
177
- await this.updateTagStats(context.userId, context.tags, reward);
177
+ await this.updateTagStats(context.userId, context.tags, reward, true);
178
178
  return true;
179
179
  }
180
180
  /**
181
181
  * Train the model directly with raw (features, reward) samples.
182
182
  * Enables offline/batch imports from external pipelines (data warehouses,
183
183
  * historical logs, post-processing jobs) without a live decision context.
184
+ *
185
+ * The model is loaded once and SGD is replayed locally, then the
186
+ * accumulated deltas are written in a single batched round trip —
187
+ * equivalent to per-sample updateModel calls when no concurrent writer
188
+ * interleaves, and orders of magnitude cheaper for bulk imports.
184
189
  */
185
190
  async trainSamples(samples) {
186
- let applied = 0;
191
+ if (samples.length === 0)
192
+ return 0;
193
+ const weights = await this.getModel();
194
+ const local = {};
195
+ for (const [feature, raw] of Object.entries(weights)) {
196
+ local[feature] = Number(raw) || 0;
197
+ }
198
+ const deltas = new Map();
199
+ let totalReward = 0;
187
200
  for (const sample of samples) {
188
- await this.updateModel(sample.features, sample.reward);
189
- applied++;
201
+ const prediction = this.predict(sample.features, local);
202
+ const error = sample.reward - prediction;
203
+ for (const [feature, value] of Object.entries(sample.features)) {
204
+ if (value === 0)
205
+ continue;
206
+ const delta = this.learningRate * error * value;
207
+ deltas.set(feature, (deltas.get(feature) ?? 0) + delta);
208
+ local[feature] = (local[feature] ?? 0) + delta;
209
+ }
210
+ totalReward += sample.reward;
211
+ }
212
+ const multi = this.redisClient.multi();
213
+ for (const [feature, delta] of deltas) {
214
+ multi.hIncrByFloat(this.keys.learningModel(), feature, delta);
190
215
  }
191
- return applied;
216
+ multi.hIncrBy(this.keys.learningStats(), 'rewards', samples.length);
217
+ multi.hIncrByFloat(this.keys.learningStats(), 'totalReward', totalReward);
218
+ await multi.exec();
219
+ return samples.length;
192
220
  }
193
221
  /**
194
222
  * Update per-user, per-tag reward aggregates (count + reward sum).
195
223
  * Uses atomic hash increments only - O(tags) with no read-modify-write -
196
224
  * so high-throughput outcome streams scale without contention.
197
225
  */
198
- async updateTagStats(userId, tags, reward) {
226
+ async updateTagStats(userId, tags, reward, terminal) {
199
227
  if (!this.trackTagStats || !tags || tags.length === 0)
200
228
  return;
229
+ if (this.autoWeights.terminalOnlyTagStats && !terminal)
230
+ return;
231
+ const needVariance = this.needsVarianceTracking();
232
+ const now = Date.now();
201
233
  const multi = this.redisClient.multi();
202
234
  for (const tag of tags) {
203
235
  if (!tag)
204
236
  continue;
205
237
  multi.hIncrBy(this.keys.learningUserTagCounts(userId), tag, 1);
206
238
  multi.hIncrByFloat(this.keys.learningUserTagRewards(userId), tag, reward);
239
+ if (needVariance) {
240
+ multi.hIncrByFloat(this.keys.learningUserTagRewardSq(userId), tag, reward * reward);
241
+ multi.hSet(this.keys.learningUserTagTs(userId), tag, now.toString());
242
+ }
207
243
  }
208
244
  multi.sAdd(this.keys.learningUsers(), userId);
209
245
  await multi.exec();
210
246
  }
247
+ /** True when the configured policy/decay needs reward variance/timestamps. */
248
+ needsVarianceTracking() {
249
+ const policy = this.autoWeights.policy;
250
+ return policy === 'confidence' || policy === 'thompson' || (this.autoWeights.decayHalfLifeMs ?? 0) > 0;
251
+ }
211
252
  /** Per-user, per-tag reward statistics aggregated from observed outcomes */
212
253
  async getUserTagStats(userId) {
213
- const [counts, rewards] = await Promise.all([
254
+ const needVariance = this.needsVarianceTracking();
255
+ const [counts, rewards, sq, ts] = await Promise.all([
214
256
  this.redisClient.hGetAll(this.keys.learningUserTagCounts(userId)),
215
257
  this.redisClient.hGetAll(this.keys.learningUserTagRewards(userId)),
258
+ needVariance ? this.redisClient.hGetAll(this.keys.learningUserTagRewardSq(userId)) : Promise.resolve({}),
259
+ needVariance ? this.redisClient.hGetAll(this.keys.learningUserTagTs(userId)) : Promise.resolve({}),
216
260
  ]);
261
+ const halfLife = this.autoWeights.decayHalfLifeMs;
262
+ const now = Date.now();
217
263
  return Object.entries(counts).map(([tag, rawCount]) => {
218
- const count = Number(rawCount) || 0;
219
- const rewardSum = Number(rewards[tag]) || 0;
220
- return { tag, count, rewardSum, meanReward: count > 0 ? rewardSum / count : 0 };
264
+ let count = Number(rawCount) || 0;
265
+ let rewardSum = Number(rewards[tag]) || 0;
266
+ let rewardSqSum = needVariance ? Number(sq[tag]) || 0 : undefined;
267
+ let lastUpdatedAt = needVariance ? Number(ts[tag]) || undefined : undefined;
268
+ if (halfLife && halfLife > 0 && lastUpdatedAt) {
269
+ const elapsed = now - lastUpdatedAt;
270
+ const factor = Math.pow(2, -elapsed / halfLife);
271
+ count *= factor;
272
+ rewardSum *= factor;
273
+ if (rewardSqSum !== undefined)
274
+ rewardSqSum *= factor;
275
+ }
276
+ const meanReward = count > 0 ? rewardSum / count : 0;
277
+ let variance;
278
+ let standardError;
279
+ if (needVariance && rewardSqSum !== undefined && count > 0) {
280
+ variance = Math.max(0, rewardSqSum / count - meanReward * meanReward);
281
+ standardError = Math.sqrt(variance / count);
282
+ }
283
+ return {
284
+ tag,
285
+ count,
286
+ rewardSum,
287
+ meanReward,
288
+ rewardSqSum,
289
+ lastUpdatedAt,
290
+ variance,
291
+ standardError,
292
+ };
221
293
  });
222
294
  }
223
295
  /** Users that have accumulated tag reward statistics */
@@ -261,6 +333,8 @@ class LearningManager {
261
333
  for (const userId of trackedUsers) {
262
334
  multi.del(this.keys.learningUserTagCounts(userId));
263
335
  multi.del(this.keys.learningUserTagRewards(userId));
336
+ multi.del(this.keys.learningUserTagRewardSq(userId));
337
+ multi.del(this.keys.learningUserTagTs(userId));
264
338
  }
265
339
  multi.del(this.keys.learningUsers());
266
340
  await multi.exec();
@@ -54,6 +54,8 @@ export declare class WorkflowManager {
54
54
  pollBlockMs?: number;
55
55
  /** Per-replica cap on processed events per second; unlimited when unset */
56
56
  maxEventsPerSecond?: number;
57
+ /** Throttle window length in ms (default: 1000). Internal tuning knob. */
58
+ throttleWindowMs?: number;
57
59
  /** Fired after every durably-applied transition; best-effort, errors swallowed */
58
60
  onWorkflowEvent?: (transition: WorkflowTransition) => void;
59
61
  });
@@ -147,6 +149,14 @@ export declare class WorkflowManager {
147
149
  private handleStepCompletion;
148
150
  private handleStepFailure;
149
151
  private handleStepExpiry;
152
+ /**
153
+ * Advance a timed-out step to its `onTimeoutStepId` instead of failing the
154
+ * run — the escalation ladder (page primary, then secondary, then the
155
+ * manager). Returns false when the step declares no escalation target, or
156
+ * when the run has climbed past `maxEscalationDepth`, in which case the
157
+ * caller falls through to the ordinary failure path.
158
+ */
159
+ private tryEscalateExpiredStep;
150
160
  private evaluateCondition;
151
161
  reclaimOrphanedMessages(): Promise<number>;
152
162
  private saveInstance;
@@ -1 +1 @@
1
- {"version":3,"file":"WorkflowManager.d.ts","sourceRoot":"","sources":["../../src/managers/WorkflowManager.ts"],"names":[],"mappings":"AACA,OAAO,EACH,eAAe,EACf,kBAAkB,EAClB,uBAAuB,EACvB,yBAAyB,EACzB,gBAAgB,EAChB,YAAY,EACZ,aAAa,EAEb,UAAU,EACV,4BAA4B,EAE5B,qBAAqB,EACrB,qBAAqB,EACrB,oBAAoB,EACpB,kBAAkB,EACrB,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAC5C,OAAO,EAAE,kBAAkB,EAAE,MAAM,sBAAsB,CAAC;AAC1D,OAAO,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AAItD,eAAO,MAAQ,OAAO,mCAAuB,CAAC;AAE9C,MAAM,WAAW,YAAY;IACzB,aAAa,CAAC,UAAU,EAAE,UAAU,GAAG,OAAO,CAAC,UAAU,CAAC,CAAC;IAC3D,qBAAqB,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,GAAG,CAAC,CAAC;IACpD,kBAAkB,CAAC,CAAC,IAAI,EAAE;QACtB,QAAQ,EAAE,gBAAgB,CAAC;QAC3B,I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MAAM,GAAG,IAAI,EACxB,cAAc,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,EACnC,YAAY,CAAC,EAAE,gBAAgB,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,GAC9C,OAAO,CAAC;QAAE,EAAE,EAAE,OAAO,CAAC;QAAC,QAAQ,CAAC,EAAE,gBAAgB,CAAC;QAAC,KAAK,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC;CAgB3E"}
@@ -1070,8 +1070,62 @@ class WorkflowManager {
1070
1070
  }
1071
1071
  async handleStepExpiry(instance, definition, event) {
1072
1072
  this.emitTransition('step.expired', instance, { stepId: event.stepId, assignmentId: event.assignmentId });
1073
+ if (await this.tryEscalateExpiredStep(instance, definition, event))
1074
+ return;
1073
1075
  await this.handleStepFailure(instance, definition, event);
1074
1076
  }
1077
+ /**
1078
+ * Advance a timed-out step to its `onTimeoutStepId` instead of failing the
1079
+ * run — the escalation ladder (page primary, then secondary, then the
1080
+ * manager). Returns false when the step declares no escalation target, or
1081
+ * when the run has climbed past `maxEscalationDepth`, in which case the
1082
+ * caller falls through to the ordinary failure path.
1083
+ */
1084
+ async tryEscalateExpiredStep(instance, definition, event) {
1085
+ const stepId = event.stepId;
1086
+ if (!stepId)
1087
+ return false;
1088
+ const step = definition.steps.find((s) => s.id === stepId);
1089
+ const target = step?.onTimeoutStepId;
1090
+ if (!step || !target)
1091
+ return false;
1092
+ // A parallel branch has no single "next step" to escalate to; validation
1093
+ // rejects the combination, but a hand-written definition could slip past
1094
+ // an older registration, so bail out rather than corrupt the branch state.
1095
+ if (instance.parallelBranches?.some((b) => b.stepId === stepId))
1096
+ return false;
1097
+ const depth = Number(instance.context._escalationDepth ?? 0) + 1;
1098
+ const maxDepth = definition.maxEscalationDepth ?? 10;
1099
+ if (depth > maxDepth)
1100
+ return false;
1101
+ // Pull the superseded assignment so a late responder on the previous
1102
+ // tier cannot act on work the ladder has already moved on from.
1103
+ const assignmentId = event.assignmentId || instance.currentAssignmentId;
1104
+ if (assignmentId && this.host.removeAssignment) {
1105
+ await this.host.removeAssignment(assignmentId).catch(() => {
1106
+ /* already gone (accepted, cancelled, swept) — nothing to supersede */
1107
+ });
1108
+ await this.redisClient.del(this.keys.workflowAssignmentLink(assignmentId));
1109
+ }
1110
+ instance.history.push({
1111
+ stepId,
1112
+ assignmentId: assignmentId ?? '',
1113
+ userId: '',
1114
+ completedAt: Date.now(),
1115
+ result: { escalated: true, to: target },
1116
+ });
1117
+ instance.context._escalatedFrom = stepId;
1118
+ instance.context._escalationDepth = depth;
1119
+ this.emitTransition('step.escalated', instance, {
1120
+ stepId,
1121
+ assignmentId,
1122
+ payload: { from: stepId, to: target, depth },
1123
+ });
1124
+ // Deliberately does not touch instance.retryCount: an escalation is a
1125
+ // different person getting the work, not another attempt at the same one.
1126
+ await this.executeWorkflowStep(instance, target, definition);
1127
+ return true;
1128
+ }
1075
1129
  evaluateCondition(condition, result, context) {
1076
1130
  try {
1077
1131
  const match = condition.match(/^(result|context)\.(\w+)\s*(===|!==|==|!=|>=|<=|>|<)\s*(.+)$/);
@@ -1226,13 +1280,14 @@ class WorkflowManager {
1226
1280
  const limit = this.options.maxEventsPerSecond;
1227
1281
  if (!limit || limit <= 0)
1228
1282
  return;
1283
+ const windowMs = this.options.throttleWindowMs ?? 1000;
1229
1284
  const now = Date.now();
1230
- if (now - this.throttleWindowStart >= 1000) {
1285
+ if (now - this.throttleWindowStart >= windowMs) {
1231
1286
  this.throttleWindowStart = now;
1232
1287
  this.throttleTokensUsed = 0;
1233
1288
  }
1234
1289
  if (this.throttleTokensUsed >= limit) {
1235
- const waitMs = Math.max(this.throttleWindowStart + 1000 - now, 1);
1290
+ const waitMs = Math.max(this.throttleWindowStart + windowMs - now, 1);
1236
1291
  await new Promise((r) => setTimeout(r, waitMs));
1237
1292
  this.throttleWindowStart = Date.now();
1238
1293
  this.throttleTokensUsed = 0;