assignment-user-matcher 1.2.2 → 1.2.5

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 (38) hide show
  1. package/README.md +243 -91
  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/auto-weights.d.ts +31 -0
  6. package/dist/learning/auto-weights.d.ts.map +1 -0
  7. package/dist/learning/auto-weights.js +65 -0
  8. package/dist/lua/workflow-transition.lua +29 -0
  9. package/dist/managers/LearningManager.d.ts +39 -4
  10. package/dist/managers/LearningManager.d.ts.map +1 -1
  11. package/dist/managers/LearningManager.js +78 -3
  12. package/dist/managers/ReliabilityManager.d.ts +60 -2
  13. package/dist/managers/ReliabilityManager.d.ts.map +1 -1
  14. package/dist/managers/ReliabilityManager.js +190 -9
  15. package/dist/managers/TelemetryManager.d.ts.map +1 -1
  16. package/dist/managers/WorkflowManager.d.ts +78 -1
  17. package/dist/managers/WorkflowManager.d.ts.map +1 -1
  18. package/dist/managers/WorkflowManager.js +449 -77
  19. package/dist/matcher.class.d.ts +195 -8
  20. package/dist/matcher.class.d.ts.map +1 -1
  21. package/dist/matcher.class.js +619 -36
  22. package/dist/queries/pagination.d.ts.map +1 -1
  23. package/dist/queries/pagination.js +9 -6
  24. package/dist/scoring/fair-arbitration.d.ts +68 -0
  25. package/dist/scoring/fair-arbitration.d.ts.map +1 -0
  26. package/dist/scoring/fair-arbitration.js +151 -0
  27. package/dist/scoring/match-score.d.ts.map +1 -1
  28. package/dist/scoring/match-score.js +1 -1
  29. package/dist/types/matcher.d.ts +258 -0
  30. package/dist/types/matcher.d.ts.map +1 -1
  31. package/dist/utils/geo.d.ts +26 -0
  32. package/dist/utils/geo.d.ts.map +1 -0
  33. package/dist/utils/geo.js +62 -0
  34. package/dist/utils/keys.d.ts +13 -0
  35. package/dist/utils/keys.d.ts.map +1 -1
  36. package/dist/utils/keys.js +14 -0
  37. package/dist/workflow-validation.d.ts.map +1 -1
  38. package/package.json +58 -57
package/README.md CHANGED
@@ -51,28 +51,33 @@ Traditional matching systems can become bottlenecks, leading to delays, suboptim
51
51
  2. **Matching via Tag Intersection:**
52
52
  The core matching logic finds users whose tags have a common intersection with an assignment's tags.
53
53
 
54
- When using `routingWeights` with the built-in matcher:
55
- - Only **positive** weights (`> 0`) make assignments eligible.
56
- - Weight `0` is a **hard veto** (exact tag or suffix wildcard like `lang:*`).
57
- - Wildcards are **suffix-only** (`prefix*`). Patterns like `skill:*:node` are not treated as wildcards.
58
- - If a user has `routingWeights` but no positive entries, assignments stay queued.
54
+ When using `routingWeights` with the built-in matcher:
59
55
 
60
- Hard veto configuration example:
56
+ - Only **positive** weights (`> 0`) make assignments eligible.
57
+ - Weight `0` is a **hard veto** (exact tag or suffix wildcard like `lang:*`).
58
+ - Wildcards are **suffix-only** (`prefix*`). Patterns like `skill:*:node` are not treated as wildcards.
59
+ - If a user has `routingWeights` but no positive entries, assignments stay queued.
61
60
 
62
- ```ts
63
- await assignmentMatcher.addUser({
61
+ Hard veto configuration example:
62
+
63
+ ```ts
64
+ await assignmentMatcher.addUser({
64
65
  id: 'agent_1',
65
66
  tags: [],
66
67
  routingWeights: {
67
- 'support:*': 100, // eligible
68
- 'lang:*': 0, // hard veto for all language-tagged assignments
69
- default: 0, // hard veto for default matching fallback
68
+ 'support:*': 100, // eligible
69
+ 'lang:*': 0, // hard veto for all language-tagged assignments
70
+ default: 0, // hard veto for default matching fallback
70
71
  },
71
- });
72
- ```
72
+ });
73
+ ```
73
74
 
74
- Note: `usingDefaultMatchScore` is an internal implementation detail and is **not** a public option.
75
- Configure hard veto behavior only through `routingWeights` values.
75
+ Note: `usingDefaultMatchScore` is an internal implementation detail and is **not** a public option.
76
+ Configure hard veto behavior only through `routingWeights` values.
77
+
78
+ Assignments can also veto specific users from their side: setting `vetoedUsers: ['user_1']` on an
79
+ assignment guarantees those users are never matched to it, no matter how well their tags, weights,
80
+ or other criteria fit (this also overrides workflow targeting).
76
81
 
77
82
  3. **Prioritization Engine:**
78
83
  Assignments are typically processed in the order they are received or by a custom prioritization function you can provide. This ensures that older or more critical assignments get attention first. The library aims to match the highest priority assignments to available, suitable users.
@@ -174,8 +179,8 @@ Workflows are easiest to use with the builder helpers and the `executeWorkflow()
174
179
  import AssignmentMatcher, { workflow } from 'assignment-user-matcher';
175
180
 
176
181
  const matcher = new AssignmentMatcher(redisClient, {
177
- enableWorkflows: true,
178
- redisPrefix: 'exampleApp:',
182
+ enableWorkflows: true,
183
+ redisPrefix: 'exampleApp:',
179
184
  });
180
185
 
181
186
  // Optional if your Redis client is already connected.
@@ -183,23 +188,23 @@ const matcher = new AssignmentMatcher(redisClient, {
183
188
  await matcher.waitUntilReady();
184
189
 
185
190
  const onboardingWorkflow = workflow('onboarding', 'Onboarding')
186
- .step('profile')
191
+ .step('profile')
187
192
  .name('Complete profile')
188
193
  .assignment({ tags: ['profile'], title: 'Complete your profile' })
189
194
  .targetUser('initiator')
190
195
  .defaultNext('review')
191
196
  .done()
192
- .step('review')
197
+ .step('review')
193
198
  .name('Manager review')
194
199
  .assignment({ tags: ['review'], title: 'Review onboarding' })
195
200
  .targetUser({ tag: 'managers' })
196
201
  .defaultNext(null)
197
202
  .done()
198
- .build();
203
+ .build();
199
204
 
200
205
  // Registers the definition if needed, then starts the workflow instance.
201
206
  const instance = await matcher.executeWorkflow(onboardingWorkflow, 'agent_007', {
202
- source: 'signup',
207
+ source: 'signup',
203
208
  });
204
209
 
205
210
  console.log(instance.id, instance.currentStepId);
@@ -213,6 +218,43 @@ Plain object workflow definitions are also accepted. The library now fills in se
213
218
  - `initialStepId` defaults to the first step ID
214
219
  - invalid definitions fail early during registration with clear validation errors
215
220
 
221
+ ### 4. Scaling & Reliability for Workflows
222
+
223
+ The workflow engine is designed to run with many orchestrator replicas over large instance counts. The key building blocks:
224
+
225
+ - **Indexed step timeouts** — step expirations are tracked in a sorted set and claimed atomically, so `processExpiredWorkflowSteps()` is O(due steps) instead of scanning every instance, and an expiry fires on exactly one replica.
226
+ - **In-place conflict retries** — optimistic-lock (`VERSION_MISMATCH`) conflicts are retried immediately with a fresh read instead of waiting for the orphan-reclaim window.
227
+ - **Delayed retry queue** — failed events are scheduled for retry with exponential backoff (`workflowRetryBackoffMs`, default 1000ms initial delay) and drained automatically by the orchestrator; retries are claimed atomically across replicas.
228
+ - **Flow rate control** — tune orchestrator throughput per replica: `workflowEventBatchSize` (XREADGROUP COUNT, default 10), `workflowPollBlockMs` (blocking poll wait, default 5000ms), and `workflowMaxEventsPerSecond` to cap event processing (applies to both stream consumption and retry draining; unlimited when unset).
229
+ - **Per-event idempotency markers** — processed-event markers carry their own TTL (`workflowIdempotencyTtlMs`), and replayed step executions generate deterministic assignment IDs so crash-replays never create duplicate assignments.
230
+ - **Shared circuit breaker** — set `circuitBreakerShared: true` to converge breaker state across replicas through a shared Redis failure counter (recommended for multi-replica deployments).
231
+ - **Instance retention** — set `workflowInstanceRetentionMs` to expire terminal (completed/failed/cancelled) instances and clean their registry/index entries. Unset (the default) keeps them forever, matching previous behavior; a value in the range of days to weeks is recommended for high-volume deployments.
232
+
233
+ Operational helpers:
234
+
235
+ ```typescript
236
+ const matcher = new AssignmentMatcher(redisClient, {
237
+ enableWorkflows: true,
238
+ circuitBreakerShared: true,
239
+ workflowInstanceRetentionMs: 30 * 24 * 60 * 60 * 1000, // 30 days
240
+ });
241
+
242
+ // Machine steps can run through named handlers with timeout enforcement
243
+ // (step.timeoutMs / defaultTimeoutMs); falls back to executeMachineTask.
244
+ matcher.registerMachineHandler('score-lead', async ({ instance, step }) => {
245
+ return { score: 42 };
246
+ });
247
+
248
+ // One-time migration for deployments created before the indexes existed
249
+ await matcher.backfillWorkflowIndexes();
250
+
251
+ // Periodic maintenance for deployments without retention configured
252
+ await matcher.pruneWorkflowInstances(30 * 24 * 60 * 60 * 1000);
253
+
254
+ // Monitoring: active instances, retry queue depth, DLQ size, stream stats
255
+ const metrics = await matcher.getWorkflowMetrics();
256
+ ```
257
+
216
258
  ## API Reference
217
259
 
218
260
  The main class provided is `AssignmentMatcher`.
@@ -241,10 +283,11 @@ Adds a new assignment to be matched.
241
283
  - `tags: string[]`: Array of tags required for the assignment.
242
284
  - `createdAt: number`: Timestamp (e.g., `new Date().getTime()`) indicating when the assignment was created. Used for default prioritization (older assignments get higher priority). Can be influenced by `prioritizationFunction`.
243
285
  - `priority?: number | string`: Optional explicit priority. If `prioritizationFunction` is used, this might be an input to it.
286
+ - `vetoedUsers?: string[]`: Optional list of user IDs that must never receive this assignment, regardless of any other matching criteria (tags, `routingWeights`, priority, or workflow targeting). Vetoed assignments are excluded from a user's candidate pool before scoring, so the veto adds no per-match overhead. To change an assignment's vetoes, remove and re-add the assignment.
244
287
 
245
288
  ### `matchUsersAssignments(): Promise<void>`
246
289
 
247
- Triggers the matching process. This method iterates through pending assignments and tries to match them with suitable, available users based on tags and user backlog capacity.
290
+ Triggers the matching process. This method iterates through pending assignments and tries to match them with suitable, available users based on tags and user backlog capacity. With no `userId`, every eligible user is evaluated in parallel by default and contested assignments go to whoever's claim resolves first - see the `fairness` option in [Options](#options) to make the best-scoring candidate win deterministically (`'best-match'`), or to additionally balance load across users (`'balanced'`, `'spread-work'`).
248
291
 
249
292
  ### `getCurrentAssignmentsForUser(userId: string): Promise<Assignment[]>`
250
293
 
@@ -322,6 +365,54 @@ type Options = {
322
365
  // the check periodically. Disabled when undefined (default).
323
366
  idleUserTimeoutMs?: number; // Default: undefined (disabled)
324
367
 
368
+ // Who wins when several users are eligible for the same assignment
369
+ // during bulk matching (matchUsersAssignments() with no userId)?
370
+ // 'first-come' - whoever's claim reaches Redis first (fastest; the
371
+ // winner is arbitrary). This is the default.
372
+ // 'best-match' - the highest-scoring eligible user, deterministically.
373
+ // 'balanced' - best match wins, but near-ties (within ~5% of the
374
+ // typical candidate score) go to whoever has less work.
375
+ // 'spread-work' - work is spread as evenly as skills allow: every
376
+ // assignment already on someone's plate discounts their
377
+ // next bid by half the typical candidate score, so
378
+ // finishing work fast never just means drowning in more.
379
+ // The numbers behind 'balanced' / 'spread-work' are derived automatically
380
+ // from each matching pass's candidate scores - nothing to calibrate. Both
381
+ // also include an hourly guardrail by default: nobody receives at more
382
+ // than double the team's average grant rate (see fairnessMaxPerWindow).
383
+ // Switchable at runtime via `setFairness(mode)` / `getFairness()`, or
384
+ // retune every fairness knob below at once with
385
+ // `setFairnessConfig(partial)` / `getFairnessConfig()` - changes apply on
386
+ // the next `matchUsersAssignments()` call, no reconstruction needed.
387
+ fairness?: 'first-come' | 'best-match' | 'balanced' | 'spread-work'; // Default: 'first-come'
388
+
389
+ // Hard ceiling on how many assignments one user can be *granted* within a
390
+ // rolling time window, in any fairness mode other than 'first-come'. The
391
+ // backlog cap alone can't protect diligent users: fast workers keep
392
+ // freeing backlog slots and keep winning, so speed is rewarded with ever
393
+ // more work. This counts grants regardless of how quickly they were
394
+ // cleared; at the cap, contested work spills to the next-best eligible
395
+ // user (or stays queued) until the window rolls. Workflow-targeted
396
+ // assignments are direct handoffs and bypass the cap.
397
+ // Left undefined, the 'balanced' / 'spread-work' presets default it to a
398
+ // team-relative guardrail - max(maxUserBacklogSize, 2x the team's average
399
+ // grants in the window), recomputed each pass, so it adapts to any
400
+ // deployment's volume. Set a number to pin the ceiling, or Infinity to
401
+ // disable the window cap entirely.
402
+ fairnessMaxPerWindow?: number; // Default: auto for 'balanced'/'spread-work', else disabled
403
+ fairnessWindowMs?: number; // Default: 3600000 (one hour)
404
+
405
+ // Expert alternative to `fairness` - the raw switches behind it:
406
+ // enableFairTiebreaker is exactly `fairness: 'best-match'` when true;
407
+ // fairnessLoadPenalty is an absolute score discount per assignment
408
+ // already on a user's backlog, and fairnessTieBand treats scores in the
409
+ // same band-sized bucket as tied (less-loaded user wins). Explicit values
410
+ // here override what a `fairness` preset would derive. Runtime toggles:
411
+ // `setFairTiebreaker(enabled)` / `isFairTiebreakerEnabled()`.
412
+ enableFairTiebreaker?: boolean; // Default: false
413
+ fairnessLoadPenalty?: number; // Default: 0 (off)
414
+ fairnessTieBand?: number; // Default: 0 (off)
415
+
325
416
  // A custom function to determine the priority of an assignment.
326
417
  // The function receives assignment objects (or undefined if fewer than 3 are available for comparison)
327
418
  // and should return a numerical priority score. Higher scores mean higher priority.
@@ -436,7 +527,7 @@ The learning layer supports three external feed paths:
436
527
 
437
528
  **1. Named feedback signals (post-processing per assignment).** When an
438
529
  assignment reaches a terminal state, its feature context is archived as an
439
- *episode* (kept for `learningFeedbackTtlMs`). External pipelines can attribute
530
+ _episode_ (kept for `learningFeedbackTtlMs`). External pipelines can attribute
440
531
  late signals to it at any point within that window:
441
532
 
442
533
  ```typescript
@@ -444,8 +535,8 @@ const matcher = new AssignmentMatcher(redisClient, {
444
535
  enableLearning: true,
445
536
  // Reward = sum(signalValue * signalWeight); unlisted signals default to 1
446
537
  learningSignalWeights: {
447
- accuracy: 2, // accuracy audits matter most
448
- csat: 1, // customer satisfaction
538
+ accuracy: 2, // accuracy audits matter most
539
+ csat: 1, // customer satisfaction
449
540
  handleTimePenalty: -0.5, // longer handling reduces reward
450
541
  },
451
542
  });
@@ -487,6 +578,56 @@ tune `learningBoostFactor` / `learningExplorationRate` for your workload. For
487
578
  domain-specific setups (custom embeddings, business features), supply a
488
579
  `learningFeatureExtractor`.
489
580
 
581
+ ### Automatic Routing Weights (RL-Generated Tags/Weights)
582
+
583
+ Beyond re-ranking, the learning layer can fully automate `routingWeights`
584
+ authoring. With `enableAutoRoutingWeights: true` (requires `enableLearning`),
585
+ every reward observation also updates per-user, per-tag statistics in Redis
586
+ (atomic `HINCRBY`/`HINCRBYFLOAT` — O(tags) per outcome, no scans, no
587
+ read-modify-write), and weights are synthesized on demand with a UCB1 bandit
588
+ policy:
589
+
590
+ - tags with a high mean reward get proportionally high weights (UCB
591
+ exploration bonus favors less-sampled tags),
592
+ - tags with a mean reward at/below `vetoThreshold` (after `minSamples`
593
+ observations) get weight `0` — the matcher's hard-veto semantics,
594
+ - under-sampled or unobserved known tags get an optimistic `priorWeight` so
595
+ the system keeps exploring them.
596
+
597
+ ```typescript
598
+ const matcher = new AssignmentMatcher(redisClient, {
599
+ enableLearning: true,
600
+ enableAutoRoutingWeights: true,
601
+ autoRoutingWeights: {
602
+ minSamples: 5, // observations before a tag's stats are trusted
603
+ vetoThreshold: -0.5, // mean reward at/below this → weight 0 (hard veto)
604
+ maxWeight: 100, // top of the synthesized weight scale
605
+ explorationBonus: 0.5, // UCB coefficient; higher → more exploration
606
+ priorWeight: 50, // optimistic weight for unexplored tags
607
+ },
608
+ });
609
+
610
+ // Inspect what the system has learned for a user
611
+ const stats = await matcher.getLearnedTagStats('user-1');
612
+ const preview = await matcher.getLearnedRoutingWeights('user-1');
613
+
614
+ // Apply learned weights to one user, or to all tracked users (e.g. on a
615
+ // periodic job). Manual routingWeights entries for tags the learner has no
616
+ // data on are preserved; pass { overrideManual: true } to replace them.
617
+ await matcher.syncLearnedRoutingWeights('user-1');
618
+ await matcher.syncLearnedRoutingWeights(); // all tracked users
619
+
620
+ // Include exploration priors for known tags the user has never seen:
621
+ await matcher.syncLearnedRoutingWeights('user-1', { includeUnexploredTags: true });
622
+ ```
623
+
624
+ Synthesis happens outside the matching hot path — matching itself reads the
625
+ user's stored `routingWeights` exactly as before, so the per-match cost is
626
+ unchanged. The last-applied learned map is stored on the user as
627
+ `learnedRoutingWeights` for observability, and `resetLearningModel()` clears
628
+ all per-user tag statistics. The pure synthesis function is exported as
629
+ `synthesizeRoutingWeights` for offline pipelines.
630
+
490
631
  ### RL Scalability & Redis Constraints
491
632
 
492
633
  The RL layer adds controlled overhead: decision recording, outcome archival,
@@ -497,12 +638,14 @@ cardinality — not on learning math itself.
497
638
  #### Redis Workload Breakdown
498
639
 
499
640
  Each matched assignment now costs:
641
+
500
642
  1. **Decision record** (live): ~300 bytes for features + metadata; expires in 7 days (configurable).
501
643
  2. **Episode archive** (terminal): ~400 bytes; kept until feedback arrives, expires in 7 days.
502
644
  3. **Model updates**: One hash increment per feature per outcome (typically 5–15 features).
503
645
  4. **Stats tracking**: Shared atomic increments.
504
646
 
505
647
  Matching a single assignment typically involves:
648
+
506
649
  - 1–2 Redis reads (model + candidate details).
507
650
  - 3–5 Redis writes per matched assignment (decision, model updates, stats).
508
651
  - Pipelined to reduce round trips.
@@ -510,25 +653,28 @@ Matching a single assignment typically involves:
510
653
  #### Memory Estimation
511
654
 
512
655
  Assume:
656
+
513
657
  - **Small deployment**: 10 users, 1,000 live assignments, ~8 features per assignment.
514
- - Model: ~8 KB (8 features × 1 KB per weight + overhead).
515
- - Decisions: ~300 KB (1,000 × 300 bytes).
516
- - Overhead: ~500 KB for indices and stats.
517
- - **Total: ~1 MB**. No scaling issues with standard Redis (safe at anything).
658
+
659
+ - Model: ~8 KB (8 features × 1 KB per weight + overhead).
660
+ - Decisions: ~300 KB (1,000 × 300 bytes).
661
+ - Overhead: ~500 KB for indices and stats.
662
+ - **Total: ~1 MB**. No scaling issues with standard Redis (safe at anything).
518
663
 
519
664
  - **Medium deployment**: 100 users, 100,000 live assignments, ~15 features.
520
- - Model: ~15 KB.
521
- - Decisions: ~30 MB (100,000 × 300 bytes).
522
- - Episodes archived: ~10 MB (depends on feedback delay; typically 10% of live at any moment).
523
- - Overhead: ~5 MB.
524
- - **Total: ~50 MB**. Easily within Redis limits; watch growth over weeks.
665
+
666
+ - Model: ~15 KB.
667
+ - Decisions: ~30 MB (100,000 × 300 bytes).
668
+ - Episodes archived: ~10 MB (depends on feedback delay; typically 10% of live at any moment).
669
+ - Overhead: ~5 MB.
670
+ - **Total: ~50 MB**. Easily within Redis limits; watch growth over weeks.
525
671
 
526
672
  - **High-throughput deployment**: 1,000 users, 1,000,000 live assignments, ~20 features, exploration enabled.
527
- - Model: ~20 KB.
528
- - Decisions: ~300 MB (1,000,000 × 300 bytes).
529
- - Episodes: ~100 MB.
530
- - Overhead: ~50 MB.
531
- - **Total: ~450 MB**. Manageable with a 2–4 GB Redis instance; requires TTL discipline.
673
+ - Model: ~20 KB.
674
+ - Decisions: ~300 MB (1,000,000 × 300 bytes).
675
+ - Episodes: ~100 MB.
676
+ - Overhead: ~50 MB.
677
+ - **Total: ~450 MB**. Manageable with a 2–4 GB Redis instance; requires TTL discipline.
532
678
 
533
679
  #### Configuration Guidelines
534
680
 
@@ -537,11 +683,11 @@ Assume:
537
683
  ```typescript
538
684
  const matcher = new AssignmentMatcher(redisClient, {
539
685
  enableLearning: true,
540
- learningShadowMode: true, // Observe first; no ranking impact
686
+ learningShadowMode: true, // Observe first; no ranking impact
541
687
  learningRate: 0.1,
542
- learningExplorationRate: 0, // No exploration overhead
543
- learningDecisionTtlMs: 604800000, // 7 days
544
- learningFeedbackTtlMs: 604800000, // 7 days
688
+ learningExplorationRate: 0, // No exploration overhead
689
+ learningDecisionTtlMs: 604800000, // 7 days
690
+ learningFeedbackTtlMs: 604800000, // 7 days
545
691
  });
546
692
  // Safe: no performance issues. Monitor model size weekly.
547
693
  ```
@@ -552,10 +698,10 @@ const matcher = new AssignmentMatcher(redisClient, {
552
698
  const matcher = new AssignmentMatcher(redisClient, {
553
699
  enableLearning: true,
554
700
  learningShadowMode: false,
555
- learningRate: 0.05, // Slower learning for stability
556
- learningExplorationRate: 0.02, // 2% of matches explore randomly
557
- learningBoostFactor: 50, // Moderate impact on ranking
558
- learningDecisionTtlMs: 259200000, // 3 days (balance TTL vs memory)
701
+ learningRate: 0.05, // Slower learning for stability
702
+ learningExplorationRate: 0.02, // 2% of matches explore randomly
703
+ learningBoostFactor: 50, // Moderate impact on ranking
704
+ learningDecisionTtlMs: 259200000, // 3 days (balance TTL vs memory)
559
705
  learningFeedbackTtlMs: 259200000,
560
706
  learningSignalWeights: { accuracy: 1, csat: 0.5, errorRate: -1 },
561
707
  });
@@ -569,12 +715,12 @@ const matcher = new AssignmentMatcher(redisClient, {
569
715
  const matcher = new AssignmentMatcher(redisClient, {
570
716
  enableLearning: true,
571
717
  learningShadowMode: false,
572
- learningRate: 0.02, // Conservative learning rate
573
- learningExplorationRate: 0.01, // Minimal exploration (1%)
574
- learningBoostFactor: 30, // Restrained boost to avoid instability
575
- learningDecisionTtlMs: 86400000, // 1 day (shorter TTL for faster cleanup)
576
- learningFeedbackTtlMs: 172800000, // 2 days (stagger feedback arrival)
577
- learningSignalWeights: { accuracy: 1, csat: 0.3 }, // Fewer signals = less noise
718
+ learningRate: 0.02, // Conservative learning rate
719
+ learningExplorationRate: 0.01, // Minimal exploration (1%)
720
+ learningBoostFactor: 30, // Restrained boost to avoid instability
721
+ learningDecisionTtlMs: 86400000, // 1 day (shorter TTL for faster cleanup)
722
+ learningFeedbackTtlMs: 172800000, // 2 days (stagger feedback arrival)
723
+ learningSignalWeights: { accuracy: 1, csat: 0.3 }, // Fewer signals = less noise
578
724
  // Consider sampling outcomes if traffic is extreme:
579
725
  // Only learn from 10% of low-priority assignments.
580
726
  });
@@ -645,19 +791,20 @@ Use this quick guide based on your primary goal.
645
791
 
646
792
  ```typescript
647
793
  const matcher = new AssignmentMatcher(redisClient, {
648
- enableLearning: true,
649
- learningShadowMode: false,
650
- learningExplorationRate: 0.005,
651
- learningBoostFactor: 20,
652
- learningRate: 0.02,
653
- learningDecisionTtlMs: 86400000,
654
- learningFeedbackTtlMs: 86400000,
655
- relevantBatchSize: 50,
656
- maxUserBacklogSize: 1,
794
+ enableLearning: true,
795
+ learningShadowMode: false,
796
+ learningExplorationRate: 0.005,
797
+ learningBoostFactor: 20,
798
+ learningRate: 0.02,
799
+ learningDecisionTtlMs: 86400000,
800
+ learningFeedbackTtlMs: 86400000,
801
+ relevantBatchSize: 50,
802
+ maxUserBacklogSize: 1,
657
803
  });
658
804
  ```
659
805
 
660
806
  When to use:
807
+
661
808
  1. You have tight p95/p99 latency SLOs.
662
809
  2. Even a 2-5% throughput drop is expensive.
663
810
 
@@ -665,19 +812,20 @@ When to use:
665
812
 
666
813
  ```typescript
667
814
  const matcher = new AssignmentMatcher(redisClient, {
668
- enableLearning: true,
669
- learningShadowMode: false,
670
- learningExplorationRate: 0.01,
671
- learningBoostFactor: 35,
672
- learningRate: 0.05,
673
- learningDecisionTtlMs: 259200000,
674
- learningFeedbackTtlMs: 259200000,
675
- relevantBatchSize: 100,
676
- maxUserBacklogSize: 1,
815
+ enableLearning: true,
816
+ learningShadowMode: false,
817
+ learningExplorationRate: 0.01,
818
+ learningBoostFactor: 35,
819
+ learningRate: 0.05,
820
+ learningDecisionTtlMs: 259200000,
821
+ learningFeedbackTtlMs: 259200000,
822
+ relevantBatchSize: 100,
823
+ maxUserBacklogSize: 1,
677
824
  });
678
825
  ```
679
826
 
680
827
  When to use:
828
+
681
829
  1. You want measurable quality lift with moderate performance cost.
682
830
  2. You can tolerate small throughput swings while tuning.
683
831
 
@@ -685,19 +833,20 @@ When to use:
685
833
 
686
834
  ```typescript
687
835
  const matcher = new AssignmentMatcher(redisClient, {
688
- enableLearning: true,
689
- learningShadowMode: false,
690
- learningExplorationRate: 0.02,
691
- learningBoostFactor: 60,
692
- learningRate: 0.08,
693
- learningDecisionTtlMs: 604800000,
694
- learningFeedbackTtlMs: 604800000,
695
- relevantBatchSize: 200,
696
- maxUserBacklogSize: 1,
836
+ enableLearning: true,
837
+ learningShadowMode: false,
838
+ learningExplorationRate: 0.02,
839
+ learningBoostFactor: 60,
840
+ learningRate: 0.08,
841
+ learningDecisionTtlMs: 604800000,
842
+ learningFeedbackTtlMs: 604800000,
843
+ relevantBatchSize: 200,
844
+ maxUserBacklogSize: 1,
697
845
  });
698
846
  ```
699
847
 
700
848
  When to use:
849
+
701
850
  1. Completion/quality metrics matter more than raw throughput.
702
851
  2. You have enough headroom in Redis and CPU.
703
852
 
@@ -725,20 +874,22 @@ learningExplorationRate: 0.005,
725
874
  ```
726
875
 
727
876
  4. Compare deltas:
728
- - `Throughput delta` should stay above your SLO floor (e.g. not below `-2%`).
729
- - `Completion rate delta` should be positive.
730
- - `Quality score delta` should be positive.
877
+
878
+ - `Throughput delta` should stay above your SLO floor (e.g. not below `-2%`).
879
+ - `Completion rate delta` should be positive.
880
+ - `Quality score delta` should be positive.
731
881
 
732
882
  5. If throughput regresses too much:
733
- - Reduce `learningBoostFactor`.
734
- - Reduce `learningExplorationRate`.
735
- - Reduce `relevantBatchSize`.
736
- - Shorten `learningDecisionTtlMs` / `learningFeedbackTtlMs`.
883
+
884
+ - Reduce `learningBoostFactor`.
885
+ - Reduce `learningExplorationRate`.
886
+ - Reduce `relevantBatchSize`.
887
+ - Shorten `learningDecisionTtlMs` / `learningFeedbackTtlMs`.
737
888
 
738
889
  6. If quality lift is too small:
739
- - Increase `learningBoostFactor` gradually (`+10` per step).
740
- - Increase `learningExplorationRate` slightly (`+0.005`), capped at `0.05`.
741
- - Improve signal quality in `learningSignalWeights`.
890
+ - Increase `learningBoostFactor` gradually (`+10` per step).
891
+ - Increase `learningExplorationRate` slightly (`+0.005`), capped at `0.05`.
892
+ - Improve signal quality in `learningSignalWeights`.
742
893
 
743
894
  ### Reading Benchmark Deltas Quickly
744
895
 
@@ -751,6 +902,7 @@ Quality score delta: +0.0274
751
902
  ```
752
903
 
753
904
  Interpretation:
905
+
754
906
  1. You traded some speed (`-5.11%`) for better outcomes.
755
907
  2. Completion improved by **4.80 percentage points** (`pp`, not percent).
756
908
  3. Quality improved overall (`+0.0274`).
@@ -933,4 +1085,4 @@ Consumers can `import AssignmentMatcher from 'assignment-user-matcher'` or `cons
933
1085
 
934
1086
  ## License
935
1087
 
936
- This library is licensed under the MIT License. (Assuming MIT - please update if incorrect)
1088
+ This library is proprietary, commercially-licensed software — see [`LICENCE`](./LICENCE) for the full terms. No use, copying, modification, or distribution is permitted without the Owner's prior written permission (the LICENCE file's non-commercial fair-use footnote covers limited evaluation/academic use with written confirmation from the Owner). Contact viljar@forgemaster.ai for licensing.
package/dist/index.d.ts CHANGED
@@ -1,10 +1,12 @@
1
1
  import AssignmentMatcher from './matcher.class';
2
- export type { Assignment, options, Stats, User } from './matcher.class';
3
- export type { WorkflowDefinition, WorkflowDefinitionInput, WorkflowDefinitionSummary, WorkflowInstance, WorkflowStep, WorkflowTargetUser, WorkflowMachineTask, WorkflowTaskType, WorkflowEvent, WorkflowEventType, AssignmentResult, ParallelBranchState, DeadLetterEntry, AuditEntry, CircuitBreakerState, WorkflowInstanceWithSnapshot, LearningOutcome, LearningRewards, LearningFeatures, LearningAssignmentContext, LearningFeatureExtractor, LearningDecisionRecord, LearningEpisodeRecord, LearningSignals, LearningSample, LearningStats, PendingAssignmentInfo, } from './matcher.class';
2
+ export type { Assignment, MatcherOptions, options, Stats, User, GeoMatchResult, GeoMatchingFunction, ReliabilityMetrics, AssignmentStatus, FairnessMode, FairnessConfig, } from './matcher.class';
3
+ export type { WorkflowDefinition, WorkflowDefinitionInput, WorkflowDefinitionSummary, WorkflowInstance, WorkflowInstanceStatus, WorkflowStep, WorkflowRouting, WorkflowTargetUser, WorkflowMachineTask, WorkflowTaskType, WorkflowEvent, WorkflowEventType, AssignmentResult, ParallelBranchState, DeadLetterEntry, AuditEntry, CircuitBreakerState, WorkflowInstanceWithSnapshot, LearningOutcome, LearningRewards, LearningFeatures, LearningAssignmentContext, LearningFeatureExtractor, LearningDecisionRecord, LearningEpisodeRecord, LearningSignals, LearningSample, LearningStats, LearningTagStat, AutoRoutingWeightsOptions, PendingAssignmentInfo, WorkflowEngineMetrics, MachineTaskHandler, WorkflowHost, PaginationOptions, PaginationResult, AssignmentCounts, } from './matcher.class';
4
4
  export { extractMatchFeatures, cosineSimilarity } from './learning/features';
5
- export { WorkflowBuilder, WorkflowStepBuilder, workflow, linearWorkflow, approvalWorkflow, } from './workflow-builder';
5
+ export { synthesizeRoutingWeights, DEFAULT_AUTO_WEIGHTS_OPTIONS } from './learning/auto-weights';
6
+ export { WorkflowBuilder, WorkflowStepBuilder, workflow, linearWorkflow, approvalWorkflow } from './workflow-builder';
6
7
  export { normalizeWorkflowDefinition, validateWorkflowDefinition } from './workflow-validation';
7
8
  export * from './utils/cidr';
9
+ export * from './utils/geo';
8
10
  export { createKeyBuilders, type KeyBuilders, type RedisKeyConfig } from './utils/keys';
9
11
  export { AssignmentMatcher };
10
12
  export default AssignmentMatcher;
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,iBAAiB,MAAM,iBAAiB,CAAC;AAEhD,YAAY,EAAE,UAAU,EAAE,OAAO,EAAE,KAAK,EAAE,IAAI,EAAE,MAAM,iBAAiB,CAAC;AAGxE,YAAY,EACR,kBAAkB,EAClB,uBAAuB,EACvB,yBAAyB,EACzB,gBAAgB,EAChB,YAAY,EACZ,kBAAkB,EAClB,mBAAmB,EACnB,gBAAgB,EAChB,aAAa,EACb,iBAAiB,EACjB,gBAAgB,EAChB,mBAAmB,EACnB,eAAe,EACf,UAAU,EACV,mBAAmB,EACnB,4BAA4B,EAC5B,eAAe,EACf,eAAe,EACf,gBAAgB,EAChB,yBAAyB,EACzB,wBAAwB,EACxB,sBAAsB,EACtB,qBAAqB,EACrB,eAAe,EACf,cAAc,EACd,aAAa,EACb,qBAAqB,GACxB,MAAM,iBAAiB,CAAC;AAGzB,OAAO,EAAE,oBAAoB,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAG7E,OAAO,EACH,eAAe,EACf,mBAAmB,EACnB,QAAQ,EACR,cAAc,EACd,gBAAgB,GACnB,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EAAE,2BAA2B,EAAE,0BAA0B,EAAE,MAAM,uBAAuB,CAAC;AAGhG,cAAc,cAAc,CAAC;AAC7B,OAAO,EAAE,iBAAiB,EAAE,KAAK,WAAW,EAAE,KAAK,cAAc,EAAE,MAAM,cAAc,CAAC;AAExF,OAAO,EAAE,iBAAiB,EAAE,CAAC;AAC7B,eAAe,iBAAiB,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,iBAAiB,MAAM,iBAAiB,CAAC;AAEhD,YAAY,EACR,UAAU,EACV,cAAc,EACd,OAAO,EACP,KAAK,EACL,IAAI,EACJ,cAAc,EACd,mBAAmB,EACnB,kBAAkB,EAClB,gBAAgB,EAChB,YAAY,EACZ,cAAc,GACjB,MAAM,iBAAiB,CAAC;AAGzB,YAAY,EACR,kBAAkB,EAClB,uBAAuB,EACvB,yBAAyB,EACzB,gBAAgB,EAChB,sBAAsB,EACtB,YAAY,EACZ,eAAe,EACf,kBAAkB,EAClB,mBAAmB,EACnB,gBAAgB,EAChB,aAAa,EACb,iBAAiB,EACjB,gBAAgB,EAChB,mBAAmB,EACnB,eAAe,EACf,UAAU,EACV,mBAAmB,EACnB,4BAA4B,EAC5B,eAAe,EACf,eAAe,EACf,gBAAgB,EAChB,yBAAyB,EACzB,wBAAwB,EACxB,sBAAsB,EACtB,qBAAqB,EACrB,eAAe,EACf,cAAc,EACd,aAAa,EACb,eAAe,EACf,yBAAyB,EACzB,qBAAqB,EACrB,qBAAqB,EACrB,kBAAkB,EAClB,YAAY,EACZ,iBAAiB,EACjB,gBAAgB,EAChB,gBAAgB,GACnB,MAAM,iBAAiB,CAAC;AAGzB,OAAO,EAAE,oBAAoB,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAE7E,OAAO,EAAE,wBAAwB,EAAE,4BAA4B,EAAE,MAAM,yBAAyB,CAAC;AAGjG,OAAO,EAAE,eAAe,EAAE,mBAAmB,EAAE,QAAQ,EAAE,cAAc,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AACtH,OAAO,EAAE,2BAA2B,EAAE,0BAA0B,EAAE,MAAM,uBAAuB,CAAC;AAGhG,cAAc,cAAc,CAAC;AAC7B,cAAc,aAAa,CAAC;AAC5B,OAAO,EAAE,iBAAiB,EAAE,KAAK,WAAW,EAAE,KAAK,cAAc,EAAE,MAAM,cAAc,CAAC;AAExF,OAAO,EAAE,iBAAiB,EAAE,CAAC;AAC7B,eAAe,iBAAiB,CAAC"}
package/dist/index.js CHANGED
@@ -17,13 +17,17 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
17
17
  return (mod && mod.__esModule) ? mod : { "default": mod };
18
18
  };
19
19
  Object.defineProperty(exports, "__esModule", { value: true });
20
- exports.AssignmentMatcher = exports.createKeyBuilders = exports.validateWorkflowDefinition = exports.normalizeWorkflowDefinition = exports.approvalWorkflow = exports.linearWorkflow = exports.workflow = exports.WorkflowStepBuilder = exports.WorkflowBuilder = exports.cosineSimilarity = exports.extractMatchFeatures = void 0;
20
+ exports.AssignmentMatcher = exports.createKeyBuilders = exports.validateWorkflowDefinition = exports.normalizeWorkflowDefinition = exports.approvalWorkflow = exports.linearWorkflow = exports.workflow = exports.WorkflowStepBuilder = exports.WorkflowBuilder = exports.DEFAULT_AUTO_WEIGHTS_OPTIONS = exports.synthesizeRoutingWeights = exports.cosineSimilarity = exports.extractMatchFeatures = void 0;
21
21
  const matcher_class_1 = __importDefault(require("./matcher.class"));
22
22
  exports.AssignmentMatcher = matcher_class_1.default;
23
23
  // Learning feature helpers (for custom feature extractors)
24
24
  var features_1 = require("./learning/features");
25
25
  Object.defineProperty(exports, "extractMatchFeatures", { enumerable: true, get: function () { return features_1.extractMatchFeatures; } });
26
26
  Object.defineProperty(exports, "cosineSimilarity", { enumerable: true, get: function () { return features_1.cosineSimilarity; } });
27
+ // Automatic routing-weight synthesis (UCB1 policy over learned tag stats)
28
+ var auto_weights_1 = require("./learning/auto-weights");
29
+ Object.defineProperty(exports, "synthesizeRoutingWeights", { enumerable: true, get: function () { return auto_weights_1.synthesizeRoutingWeights; } });
30
+ Object.defineProperty(exports, "DEFAULT_AUTO_WEIGHTS_OPTIONS", { enumerable: true, get: function () { return auto_weights_1.DEFAULT_AUTO_WEIGHTS_OPTIONS; } });
27
31
  // Workflow builder DSL
28
32
  var workflow_builder_1 = require("./workflow-builder");
29
33
  Object.defineProperty(exports, "WorkflowBuilder", { enumerable: true, get: function () { return workflow_builder_1.WorkflowBuilder; } });
@@ -36,6 +40,7 @@ Object.defineProperty(exports, "normalizeWorkflowDefinition", { enumerable: true
36
40
  Object.defineProperty(exports, "validateWorkflowDefinition", { enumerable: true, get: function () { return workflow_validation_1.validateWorkflowDefinition; } });
37
41
  // Utility exports for advanced usage
38
42
  __exportStar(require("./utils/cidr"), exports);
43
+ __exportStar(require("./utils/geo"), exports);
39
44
  var keys_1 = require("./utils/keys");
40
45
  Object.defineProperty(exports, "createKeyBuilders", { enumerable: true, get: function () { return keys_1.createKeyBuilders; } });
41
46
  exports.default = matcher_class_1.default;
@@ -0,0 +1,31 @@
1
+ /**
2
+ * Automatic routing-weight synthesis from per-user tag reward statistics.
3
+ *
4
+ * Implements a UCB1-style bandit policy over tags: each tag's score is its
5
+ * mean observed reward plus an exploration bonus that shrinks as the tag is
6
+ * sampled more. Scores map onto the conventional 0-100 routing-weight scale:
7
+ *
8
+ * - tags with enough samples and a mean reward at/below `vetoThreshold` get
9
+ * weight 0 (the matcher's hard-veto semantics),
10
+ * - under-sampled or unobserved known tags get an optimistic `priorWeight`
11
+ * so the matcher keeps exploring them,
12
+ * - all other tags get a weight proportional to their UCB score, clamped to
13
+ * [1, maxWeight] so eligible tags never collapse to an accidental veto.
14
+ *
15
+ * Pure module: no Redis access, O(number of tags) per call.
16
+ */
17
+ import type { AutoRoutingWeightsOptions, LearningTagStat } from '../types/matcher';
18
+ export declare const DEFAULT_AUTO_WEIGHTS_OPTIONS: Required<Omit<AutoRoutingWeightsOptions, 'priorWeight'>>;
19
+ /**
20
+ * Synthesize a routingWeights map from per-tag reward statistics.
21
+ *
22
+ * @param stats per-user tag reward statistics (from learned outcomes)
23
+ * @param options UCB policy tuning (merged with defaults)
24
+ * @param knownTags optional tags to include even without observations;
25
+ * unobserved known tags receive the optimistic prior weight
26
+ * @param existingWeights optional current routingWeights of the user;
27
+ * used as the per-tag prior for under-sampled or unobserved
28
+ * tags instead of the flat `priorWeight` when provided
29
+ */
30
+ export declare function synthesizeRoutingWeights(stats: LearningTagStat[], options?: AutoRoutingWeightsOptions, knownTags?: string[], existingWeights?: Record<string, number>): Record<string, number>;
31
+ //# sourceMappingURL=auto-weights.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"auto-weights.d.ts","sourceRoot":"","sources":["../../src/learning/auto-weights.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AACH,OAAO,KAAK,EAAE,yBAAyB,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAC;AAEnF,eAAO,MAAM,4BAA4B,EAAE,QAAQ,CAAC,IAAI,CAAC,yBAAyB,EAAE,aAAa,CAAC,CAKjG,CAAC;AAEF;;;;;;;;;;GAUG;AACH,wBAAgB,wBAAwB,CACpC,KAAK,EAAE,eAAe,EAAE,EACxB,OAAO,CAAC,EAAE,yBAAyB,EACnC,SAAS,CAAC,EAAE,MAAM,EAAE,EACpB,eAAe,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GACzC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CA8CxB"}